diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 0000000..2ea586b --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,69 @@ +version: 2.1 + +orbs: + # https://circleci.com/orbs/registry/orb/circleci/docker-publish + docker-publish: circleci/docker-publish@0.1.3 + +jobs: + + build: + environment: + - TZ: "/usr/share/zoneinfo/Canada/Toronto" + - CONTAINER_NAME: "mgoubran/hippmapper" + docker: + - image: docker:18.06.3-ce-git + working_directory: /tmp/src/HippMapp3r + steps: + - checkout + - setup_remote_docker + - run: + name: Build Docker images + no_output_timeout: 60m + command: | + # Build docker image + hippmapper_VERSION=$(cat /tmp/src/HippMapp3r/hippmapper/__init__.py | tr -dc '0-9' | sed 's/./&./g') + echo "hippmapper version is ${hippmapper_VERSION}" + e=1 && for i in {1..5}; do + docker build \ + --rm=false \ + -t ${CONTAINER_NAME} \ + -f /tmp/src/HippMapp3r/Dockerfile \ + --build-arg BUILD_DATE=`date -u +"%Y-%m-%dT%H:%M:%SZ"` \ + --build-arg VCS_REF=`git rev-parse --short HEAD` \ + --build-arg VERSION="${CIRCLE_TAG:-$THISVERSION}" . \ + && e=0 && break || sleep 15 + done && [ "$e" -eq "0" ] + - run: + name: Run Tests + no_output_timeout: 2h + command: | + + echo "Runing tests:" + docker run --entrypoint bash -it mgoubran/hippmapper -c "hippmapper seg_hipp -t1 /HippMapp3r/data/test_case/mprage.nii.gz" + + - store_test_results: + path: /home/circleci/out/tests + + +workflows: + build_and_test: + jobs: + - build: + filters: + tags: + only: /.*/ + + # This workflow will deploy images on merge to master only + docker_with_lifecycle: + jobs: + - docker-publish/publish: + image: mgoubran/hippmapper + tag: latest + filters: + branches: + only: master + after_build: + - run: + name: Publish Docker Tag with hippmapper Version + command: | + docker tag mgoubran/hippmapper:latest mgoubran/hippmapper:0.1.0 \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5c7ec89 --- /dev/null +++ b/.gitignore @@ -0,0 +1,110 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +# models directory +models/ + +# .idea directory +.idea/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..72fd3f0 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,66 @@ +# Use a Linux Distro as a parent image +FROM ubuntu:16.04 + +# Set up +RUN apt-get update && apt-get install -y git wget build-essential g++ gcc cmake curl clang && \ + apt-get install -y libfreetype6-dev apt-utils pkg-config vim gfortran && \ + apt-get install -y binutils make linux-source unzip && \ + apt install -y libsm6 libxext6 libfontconfig1 libxrender1 libgl1-mesa-glx + +# Install c3d +RUN wget https://downloads.sourceforge.net/project/c3d/c3d/Nightly/c3d-nightly-Linux-x86_64.tar.gz && \ + tar -xzvf c3d-nightly-Linux-x86_64.tar.gz && mv c3d-1.1.0-Linux-x86_64 /opt/c3d && \ + rm c3d-nightly-Linux-x86_64.tar.gz +ENV PATH /opt/c3d/bin:${PATH} + +# FSL +# Installing Neurodebian packages FSL +RUN wget -O- http://neuro.debian.net/lists/xenial.us-tn.full | tee /etc/apt/sources.list.d/neurodebian.sources.list +RUN apt-key adv --recv-keys --keyserver hkp://pool.sks-keyservers.net:80 0xA5D32F012649A5A9 + +# Install FSL +RUN apt-get update && apt-get install -y fsl + +ENV FSLDIR="/usr/share/fsl/5.0" \ + FSLOUTPUTTYPE="NIFTI_GZ" \ + FSLMULTIFILEQUIT="TRUE" \ + POSSUMDIR="/usr/share/fsl/5.0" \ + LD_LIBRARY_PATH="/usr/lib/fsl/5.0:$LD_LIBRARY_PATH" \ + FSLTCLSH="/usr/bin/tclsh" \ + FSLWISH="/usr/bin/wish" \ + POSSUMDIR="/usr/share/fsl/5.0" + +ENV PATH="/usr/lib/fsl/5.0":${PATH} + +# Install ANTs +ENV ANTSPATH /opt/ANTs +RUN mkdir -p /opt/ANTs && \ + curl -sSL "https://dl.dropbox.com/s/2f4sui1z6lcgyek/ANTs-Linux-centos5_x86_64-v2.2.0-0740f91.tar.gz" \ + | tar -xzC $ANTSPATH --strip-components 1 +ENV PATH=${ANTSPATH}:${PATH} + +# Install miniconda +RUN curl -LO https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh && \ + bash Miniconda3-latest-Linux-x86_64.sh -p /opt/miniconda -b && \ + rm Miniconda3-latest-Linux-x86_64.sh +ENV PATH=/opt/miniconda/bin:${PATH} + +# Install all needed packages based on pip installation +RUN git clone https://github.com/mgoubran/HippMapp3r.git && \ + cd HippMapp3r && \ + pip install git+https://www.github.com/keras-team/keras-contrib.git && \ + pip install -e .[hippmapper] + +# Download models, store in directory +RUN mkdir /HippMapp3r/models && \ + wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1ftE79HF-sWXGa_X2bOUc-ldyWQEB5-Dz' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1ftE79HF-sWXGa_X2bOUc-ldyWQEB5-Dz" -O /HippMapp3r/models/hipp_model.json && \ + rm -rf /tmp/cookies.txt && \ + wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=19zEi7552X93_5JbEokfry2Y28gFeVGt2' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=19zEi7552X93_5JbEokfry2Y28gFeVGt2" -O /HippMapp3r/models/hipp_model_weights.h5 && \ + rm -rf /tmp/cookies.txt && \ + wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1NmyniIkAk_wY2OW4YqEp9vF7IlVsRfrA' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1NmyniIkAk_wY2OW4YqEp9vF7IlVsRfrA" -O /HippMapp3r/models/hipp_zoom_model.json && \ + rm -rf /tmp/cookies.txt && \ + wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=10uPh9byC-7Qj7Duwgh9gyQcSXH-CwWz1' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=10uPh9byC-7Qj7Duwgh9gyQcSXH-CwWz1" -O /HippMapp3r/models/hipp_zoom_model_weights.h5 && \ + rm -rf /tmp/cookies.txt + +# Run hippmapper when the container launches +ENTRYPOINT /bin/bash diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..3be6f0d --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +# HippMapp3r + +*HippMapp3r* (pronounced hippmapper) is a CNN-based segmentation technique of the whole hippocampus +using MRI images from BrainLab. +It can deal with brains with extensive atrophy and segments the hippocampi in seconds. +It uses a T1-weighted image as the only input and segments both with-skull and skull-stripped images. + +

+ hippocampus pop-up window +

+ + +____________________________ + +For more details, see our [docs](https://hippmapp3r.readthedocs.io). diff --git a/data/test_case/mprage.nii.gz b/data/test_case/mprage.nii.gz new file mode 100644 index 0000000..4cd698f Binary files /dev/null and b/data/test_case/mprage.nii.gz differ diff --git a/data/test_case/mprage_hipp_pred.nii.gz b/data/test_case/mprage_hipp_pred.nii.gz new file mode 100644 index 0000000..6a10902 Binary files /dev/null and b/data/test_case/mprage_hipp_pred.nii.gz differ diff --git a/data/test_case/mprage_hipp_pred_bin.nii.gz b/data/test_case/mprage_hipp_pred_bin.nii.gz new file mode 100644 index 0000000..16da82d Binary files /dev/null and b/data/test_case/mprage_hipp_pred_bin.nii.gz differ diff --git a/data/test_case/qc/hipp_seg_qc.png b/data/test_case/qc/hipp_seg_qc.png new file mode 100644 index 0000000..40c6aea Binary files /dev/null and b/data/test_case/qc/hipp_seg_qc.png differ diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..93c4d51 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +SPHINXPROJ = HippMapp3r +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/docs/before_install.md b/docs/before_install.md new file mode 100644 index 0000000..a24df58 --- /dev/null +++ b/docs/before_install.md @@ -0,0 +1,22 @@ +# Before installing HippMapp3r + +## Acknowledging this work +If you wish to include results generated by HippMapp3r in a publication, please include a line such as the following: + +* Whole hippocampal segmentation was performing using the HippMapp3r algorithm ([hippmapp3r.readthedocs.io](hippmapp3r.readthedocs.io)) based on a convolutional neural network. + +## Reference + +* Paper in preparation + + +## Warranty + +The software described in this manual has no warranty, it is provided “as is”. It is your responsibility to validate the behavior of the routines and their accuracy using the source code provided, or to purchase support and warranties from commercial redistributors. Consult the [Mozilla Public License](https://www.mozilla.org/en-US/MPL/2.0/) for further details. + + +## License + +HippMapp3r is free software: you can redistribute it and/or modify it under the terms of the [Mozilla Public License](https://www.mozilla.org/en-US/MPL/2.0/) as published by the [Free Software Foundation](http://www.fsf.org/), either version 2 of the License, or (at your option) any later version. + +HippMapp3r is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the [Mozilla Public License](https://www.mozilla.org/en-US/MPL/2.0/) for more details. You should have received a copy of [Mozilla Public License](https://www.mozilla.org/en-US/MPL/2.0/) along with MRtrix. If not, see http://mozilla.org/MPL/2.0/. diff --git a/docs/beginner.md b/docs/beginner.md new file mode 100644 index 0000000..d7b7dcf --- /dev/null +++ b/docs/beginner.md @@ -0,0 +1,68 @@ +# Getting started + +You can use HippMapp3r through the graphical user interface (GUI) or command line: + +## For GUI + +To start the GUI, type + + hippmapper + +A GUI that looks like the image below should appear. You can hover any of buttons in the GUI to see a brief description of the command. + +![Graphical user interface for the Dasher application](images/hippmapper_gui.png) + +You can get the command usage info by click the "Help" box on any of the pop-up windows. + +![Help screen for graphical user interface for Dasher application](images/hippmapper_help.png) + +## For Command Line + +You can see all the hippmapper commands by typing either of the following lines: + + hippmapper -h + hippmapper --help + +Once you know the command you want to know from the list, you can see more information about the command. For example, to learn more about seg_hfb: + + hippmapper seg_hipp -h + hippmapper seg_hipp --help + +## Hippocampal volumes +To extract hippocampal volumes use the GUI (Stats/Hippocampal Volumes) or command line: + + hippmapper stats_hp -h + +## QC +QC files are automatically generated in a sub-folder within the subject folder. +They are .png images that show a series of slices in the brain to +help you quickly evaluate if your command worked successfully, +especially if you have run multiple subjects. +They can also be created through the GUI or command line: + + hippmapper seg_qc -h + +The QC image should look like this: + +![Quality control imagefor hippocampus segmentation](images/hipp_qc_corr.png) + + +## Logs +Log files are automatically generated in a sub-folder within the subject folder. +They are .txt files that contain information regarding the command +and can be useful if something did not work successfully. + +## File conversion + +Convert Analyze to Nifti (or vice versa) + + hippmapper filetype + + Required arguments: + -i , --in_img input image, ex:MM.img + -o , --out_img output image, ex:MM.nii + + Example: + hippmapper filetype --in_img subject_T1.img --out_img subject_T1.nii.gz + + diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..8d0fc82 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,160 @@ +# -*- coding: utf-8 -*- +# +# Configuration file for the Sphinx documentation builder. +# +# This file does only contain a selection of the most common options. For a +# full list see the documentation: +# http://www.sphinx-doc.org/en/master/config + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +# import os +# import sys +# sys.path.insert(0, os.path.abspath('.')) + + +# -- Project information ----------------------------------------------------- + +project = 'HippMapp3r' +copyright = '2018, BrainLab' +author = 'Maged Goubran, Edward Ntiri, Melissa Holmes, Hassan Akhavein, Sandra Black' + +# The short X.Y version +version = '' +# The full version, including alpha/beta/rc tags +release = '' + + +# -- General configuration --------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# Source parsers +source_parsers = { + '.md': 'recommonmark.parser.CommonMarkParser', +} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = ['.rst', '.md'] + +# The master toctree document. +master_doc = 'index' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path . +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'sphinx_rtd_theme' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Custom sidebar templates, must be a dictionary that maps document names +# to template names. +# +# The default sidebars (for documents that don't match any pattern) are +# defined by theme itself. Builtin themes are using these templates by +# default: ``['localtoc.html', 'relations.html', 'sourcelink.html', +# 'searchbox.html']``. +# +# html_sidebars = {} + + +# -- Options for HTMLHelp output --------------------------------------------- + +# Output file base name for HTML help builder. +htmlhelp_basename = 'HippMapp3rdoc' + + +# -- Options for LaTeX output ------------------------------------------------ + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'HippMapp3r.tex', 'HippMapp3r Documentation', + 'Maged Goubran, Edward Ntiri, Melissa Holmes, Hassan Akhavein, Sandra Black', 'manual'), +] + + +# -- Options for manual page output ------------------------------------------ + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'hippmapper', 'HippMapp3r Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ---------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'HippMapp3r', 'HippMapp3r Documentation', + author, 'HippMapp3r', 'One line description of project.', + 'Miscellaneous'), +] \ No newline at end of file diff --git a/docs/docker.md b/docs/docker.md new file mode 100644 index 0000000..22ed5fd --- /dev/null +++ b/docs/docker.md @@ -0,0 +1,3 @@ +# Docker (coming soon) + + diff --git a/docs/gallery.md b/docs/gallery.md new file mode 100644 index 0000000..807c813 --- /dev/null +++ b/docs/gallery.md @@ -0,0 +1,3 @@ +# Gallery + + diff --git a/docs/hipp_seg.md b/docs/hipp_seg.md new file mode 100644 index 0000000..a2c7723 --- /dev/null +++ b/docs/hipp_seg.md @@ -0,0 +1,40 @@ +# Segmentation tutorials + +## GUI + +Watch this video tutorial: + +[![IMAGE ALT TEXT](https://img.youtube.com/vi/QF-1oIQ4eRA/0.jpg)](https://youtu.be/QF-1oIQ4eRA "Hipp Seg") + +----- + +Or follow the steps below: + +After opening the HippMapper GUI, click "Hippocampus" under the "Segmentation" tab. Wait for a new pop-up window to appear. The window should look like the image below. + +![hippocampus pop up window](images/hipp_1.PNG) + +Click "Select t1w" and chose your T1 image. Click "Run". +Type your desired output name in the "out" box. +Your output file will automatically appear in your t1w folder. + + +## Command Line + + hippmapper seg_hipp + + Optional arguments: + -s , --subj input subject + -t1 , --t1w input T1-weighted + -b, --bias bias field correct image before segmentation + -o , --out output prediction + -f, --force overwrite existing segmentation + -ss , --session input session for longitudinal studies + + Examples: + hippmapper seg_hipp -s subjectname -b + hippmapper seg_hipp -t1 subject_T1_nu.nii.gz -o subject_hipp.nii.gz + +The output should look like this.: + +![hippocampus segmentation](images/3d_snap_resize.png) diff --git a/docs/images/3d_snap.png b/docs/images/3d_snap.png new file mode 100644 index 0000000..28b4bd2 Binary files /dev/null and b/docs/images/3d_snap.png differ diff --git a/docs/images/3d_snap_resize.png b/docs/images/3d_snap_resize.png new file mode 100644 index 0000000..7935f29 Binary files /dev/null and b/docs/images/3d_snap_resize.png differ diff --git a/docs/images/graph_abstract.png b/docs/images/graph_abstract.png new file mode 100644 index 0000000..460760c Binary files /dev/null and b/docs/images/graph_abstract.png differ diff --git a/docs/images/hipp_1.PNG b/docs/images/hipp_1.PNG new file mode 100644 index 0000000..be16c8f Binary files /dev/null and b/docs/images/hipp_1.PNG differ diff --git a/docs/images/hipp_qc_corr.png b/docs/images/hipp_qc_corr.png new file mode 100644 index 0000000..7053f85 Binary files /dev/null and b/docs/images/hipp_qc_corr.png differ diff --git a/docs/images/hippmapper_gui.png b/docs/images/hippmapper_gui.png new file mode 100644 index 0000000..260c89c Binary files /dev/null and b/docs/images/hippmapper_gui.png differ diff --git a/docs/images/hippmapper_help.png b/docs/images/hippmapper_help.png new file mode 100644 index 0000000..6ee5224 Binary files /dev/null and b/docs/images/hippmapper_help.png differ diff --git a/docs/images/hippmapper_hipp_popup.png b/docs/images/hippmapper_hipp_popup.png new file mode 100644 index 0000000..bd3a522 Binary files /dev/null and b/docs/images/hippmapper_hipp_popup.png differ diff --git a/docs/images/hippmapper_icon.png b/docs/images/hippmapper_icon.png new file mode 100644 index 0000000..a786dfd Binary files /dev/null and b/docs/images/hippmapper_icon.png differ diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..b8f818c --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,40 @@ +.. HippMapp3r documentation master file, created by + sphinx-quickstart on Fri Dec 14 15:34:18 2018. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to HippMapp3r's documentation! +================================== + +.. image:: images/hippmapper_icon.png + :width: 550px + :alt: Graph abstract + :align: center + +*HippMapp3r* (pronounced hippmapper) is a CNN-based segmentation technique of the whole hippocampus +using MRI images from BrainLab. +It can deal with brains with extensive atrophy and segments the hippocampi in seconds. +It uses a T1-weighted image as the only input and segments both with-skull and skull-stripped images. + +.. image:: images/graph_abstract.png + :width: 550px + :alt: Graph abstract + :align: center + +.. toctree:: + :maxdepth: 2 + :caption: Contents: + + before_install + install + beginner + hipp_seg + issues + docker + +Indices and tables +==================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/docs/install.md b/docs/install.md new file mode 100644 index 0000000..a8b1f9c --- /dev/null +++ b/docs/install.md @@ -0,0 +1,66 @@ +# Local Install + +## Python +For the main required Python packages (numpy, scipy, etc.) we recommend using +[Anaconda for Python 3.6](https://www.continuum.io/downloads) + +## Installing package and dependencies for HippMapp3r locally + +1. Clone repository + + git clone https://github.com/mgoubran/HippMapp3r.git HippMapp3r + + (or install zip file and uncompress) + + cd HippMapp3r + + If you want to create a virtual environment where HippMapp3r can be run, + + conda create -n hippmapper python=3.6 anaconda + source activate hippmapper + + To end the session, + + source deactivate + + To remove the environment + + conda env remove --name hippmapper + +2. Install dependencies + + pip install git+https://www.github.com/keras-team/keras-contrib.git + + If the computer you are using has a GPU: + + pip install -e .[hippmapper_gpu] + + If not: + + pip install -e .[hippmapper] + +3. Test the installation by running + + hippmapper --help + + To confirm that the command line function works, and + + hippmapper + + To launch the interactive GUI. + +## Download deep models + +Download the models from [this link](https://drive.google.com/open?id=10aVCDurd_mcB49mJfwm658IZg33u0pd2) and place them in the "models" directory + +## For tab completion + pip3 install argcomplete + activate-global-python-argcomplete + +## Updating HippMapp3r +To update HippMapp3r, navigate to the directory where HippMapp3r was cloned and run + + git pull + pip install -e .[{option}] -process-dependency-links + +where "option" is dependent on whether or not you have a GPU (see package installation steps above) diff --git a/docs/issues.md b/docs/issues.md new file mode 100644 index 0000000..6554e8a --- /dev/null +++ b/docs/issues.md @@ -0,0 +1,3 @@ +# Issues + + diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..3bd9c30 --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,36 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=. +set BUILDDIR=_build +set SPHINXPROJ=HippMapp3r + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% + +:end +popd diff --git a/hippmapper/__init__.py b/hippmapper/__init__.py new file mode 100755 index 0000000..89eafbd --- /dev/null +++ b/hippmapper/__init__.py @@ -0,0 +1,11 @@ +import hippmapper.convert +import hippmapper.preprocess +import hippmapper.segment +import hippmapper.stats +import hippmapper.qc +import hippmapper.utils + +VERSION = (0, 1, 0) +__version__ = '.'.join(map(str, VERSION)) + +__all__ = ['convert', 'preprocess', 'qc', 'segment', 'stats', 'utils'] diff --git a/hippmapper/cli.py b/hippmapper/cli.py new file mode 100755 index 0000000..238144c --- /dev/null +++ b/hippmapper/cli.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +# PYTHON_ARGCOMPLETE_OK +# coding: utf-8 + +import argcomplete +import argparse +import logging +import os +import sys +import warnings + +from hippmapper import __version__ +from hippmapper import gui +from hippmapper.segment import hippmapper +from hippmapper.convert import filetype +from hippmapper.preprocess import biascorr, trim_like +from hippmapper.qc import seg_qc +from hippmapper.stats import summary_hp_vols + +warnings.simplefilter("ignore") +# warnings.simplefilter("ignore", RuntimeWarning) +# warnings.simplefilter("ignore", FutureWarning) + +os.environ['TF_CPP_MIN_LOG_LEVEL'] = "3" + + +# -------------- +# functions + + +def run_filetype(args): + filetype.main(args) + + +def run_hippmapper(args): + hippmapper.main(args) + + +def run_hp_seg_summary(args): + summary_hp_vols.main(args) + + +def run_seg_qc(args): + seg_qc.main(args) + + +def run_utils_biascorr(args): + biascorr.main(args) + + +def run_trim_like(args): + trim_like.main(args) + +# -------------- +# parser + + +def get_parser(): + parser = argparse.ArgumentParser() + subparsers = parser.add_subparsers() + # -------------- + + # seg hippocampus (hipp) + hipp_parser = hippmapper.parsefn() + parser_seg_hipp = subparsers.add_parser('seg_hipp', add_help=False, parents=[hipp_parser], + help="Segment hippocampus using a trained CNN", + usage=hipp_parser.usage) + parser_seg_hipp.set_defaults(func=run_hippmapper) + + # -------------- + + # seg qc + seg_qc_parser = seg_qc.parsefn() + parser_seg_qc = subparsers.add_parser('seg_qc', add_help=False, parents=[seg_qc_parser], + help="Create tiled mosaic of segmentation overlaid on structural image", + usage=seg_qc_parser.usage) + parser_seg_qc.set_defaults(func=run_seg_qc) + + # -------------- + + # utils biascorr + biascorr_parser = biascorr.parsefn() + parser_utils_biascorr = subparsers.add_parser('bias_corr', add_help=False, parents=[biascorr_parser], + help="Bias field correct images using N4", + usage=biascorr_parser.usage) + parser_utils_biascorr.set_defaults(func=run_utils_biascorr) + + # -------------- + + # filetype + filetype_parser = filetype.parsefn() + parser_filetype = subparsers.add_parser('filetype', add_help=False, parents=[filetype_parser], + help="Convert the Analyse format to Nifti", + usage=filetype_parser.usage) + parser_filetype.set_defaults(func=run_filetype) + + # -------------- + + # hipp vol seg + hp_vol_parser = summary_hp_vols.parsefn() + parser_stats_hp = subparsers.add_parser('stats_hp', add_help=False, parents=[hp_vol_parser], + help="Generates volumetric summary of hippocampus segmentations", + usage=hp_vol_parser.usage) + parser_stats_hp.set_defaults(func=run_hp_seg_summary) + + # -------------- + + # trim like + trim_parser = trim_like.parsefn() + + parser_trim_like = subparsers.add_parser('trim_like', help='Trim or expand image in same space like reference', + add_help=False, parents=[trim_parser], + usage='%(prog)s -i [ img ] -r [ ref ] -o [ out ] \n\n' + 'Trim or expand image in same space like reference') + parser_trim_like.set_defaults(func=run_trim_like) + + # -------------------- + + # version + parser.add_argument('-v', '--version', action='version', + version='%(prog)s {version}'.format(version=__version__)) + + return parser + + +# -------------- +# main fn + +def main(args=None): + """ main cli call""" + if args is None: + args = sys.argv[1:] + + parser = get_parser() + argcomplete.autocomplete(parser) + args = parser.parse_args(args) + + if hasattr(args, 'func'): + + # set filename, file path for the log file + log_filename = args.func.__name__.split('run_')[1] + if hasattr(args, 'subj'): + if args.subj: + log_filepath = os.path.join(args.subj, 'logs', '{}.log'.format(log_filename)) + + elif hasattr(args, 't1w'): + if args.t1w: + log_filepath = os.path.join(os.path.dirname(args.t1w), 'logs', '{}.log'.format(log_filename)) + + else: + log_filepath = os.path.join(os.getcwd(), '{}.log'.format(log_filename)) + + os.makedirs(os.path.dirname(log_filepath), exist_ok=True) + + # log keeps console output and redirects to file + root = logging.getLogger('interface') + formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s') + handler = logging.FileHandler(filename=log_filepath) + handler.setFormatter(formatter) + root.addHandler(handler) + + args.func(args) + + else: + gui.main() + + +if __name__ == '__main__': + main() diff --git a/hippmapper/convert/__init__.py b/hippmapper/convert/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/hippmapper/convert/filetype.py b/hippmapper/convert/filetype.py new file mode 100644 index 0000000..9e6e350 --- /dev/null +++ b/hippmapper/convert/filetype.py @@ -0,0 +1,54 @@ +import sys +import nibabel as nib +import argcomplete +import argparse +import os +# from nipype.interfaces.c3 import C3d + + +def parsefn(): + parser = argparse.ArgumentParser(usage='Converts image format/type') + + parser.add_argument('-i', '--in_img', type=str, required=True, metavar='', + help="input image, ex:MM.img") + parser.add_argument('-o', '--out_img', type=str, required=True, metavar='', + help="output image, ex:MM.nii") + return parser + +def parse_inputs(parser, args): + if isinstance(args, list): + args = parser.parse_args(args) + argcomplete.autocomplete(parser) + + return args.in_img, args.out_img + +def main(args): + parser = parsefn() + [in_img, out_img] = parse_inputs(parser, args) + DTYPES = { + 'uint8': 'uchar', + 'int16': 'short', + '>i2': 'short', + 'float32': 'float', + '>f4': 'float', + } + img = nib.analyze.AnalyzeImage.load(in_img) + dtype=DTYPES[str(img.get_data_dtype())] + + # c3 = C3d() + # c3.inputs.in_file = in_img + # c3.inputs.out_file = out_img + # c3d.inputs.pix_type = dtype + + print('\n converting image and orienting to RPI \n') + + cmd='c3d -verbose '+in_img+' -orient RPI -type '+dtype+' -o '+out_img + os.system(cmd) + +if __name__ == '__main__': + main(sys.argv[1:]) + +# TODO +# use nipype w c3d or mri_convert +# option to not reorient to RPI + diff --git a/hippmapper/deep/__init__.py b/hippmapper/deep/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/hippmapper/deep/metrics.py b/hippmapper/deep/metrics.py new file mode 100755 index 0000000..193f0d6 --- /dev/null +++ b/hippmapper/deep/metrics.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 + +# coding: utf-8 + +from functools import partial +from keras import backend as K + + +def dice_coefficient(y_true, y_pred, smooth=1.): + y_true_f = K.flatten(y_true) + y_pred_f = K.flatten(y_pred) + intersection = K.sum(y_true_f * y_pred_f) + return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth) + + +def dice_coefficient_loss(y_true, y_pred): + return -dice_coefficient(y_true, y_pred) + + +def weighted_dice_coefficient(y_true, y_pred, axis=(-3, -2, -1), smooth=0.00001): + """ + Weighted dice coefficient. Default axis assumes a "channels first" data structure + :param smooth: + :param y_true: + :param y_pred: + :param axis: + :return: + """ + return K.mean(2. * (K.sum(y_true * y_pred, + axis=axis) + smooth/2)/(K.sum(y_true, + axis=axis) + K.sum(y_pred, + axis=axis) + smooth)) + + +def weighted_dice_coefficient_loss(y_true, y_pred): + return -weighted_dice_coefficient(y_true, y_pred) + + +def label_wise_dice_coefficient(y_true, y_pred, label_index): + return dice_coefficient(y_true[:, label_index], y_pred[:, label_index]) + + +def get_label_dice_coefficient_function(label_index): + f = partial(label_wise_dice_coefficient, label_index=label_index) + f.__setattr__('__name__', 'label_{0}_dice_coef'.format(label_index)) + return f + + +dice_coef = dice_coefficient +dice_coef_loss = dice_coefficient_loss diff --git a/hippmapper/deep/predict.py b/hippmapper/deep/predict.py new file mode 100755 index 0000000..e0911b7 --- /dev/null +++ b/hippmapper/deep/predict.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 + +# coding: utf-8 + +import os +import nibabel as nib +import numpy as np + +from keras.models import load_model, model_from_json +from keras_contrib.layers import InstanceNormalization +from hippmapper.deep.metrics import (dice_coefficient, dice_coefficient_loss, dice_coef, dice_coef_loss, + weighted_dice_coefficient_loss, weighted_dice_coefficient) +import warnings + +warnings.simplefilter("ignore", RuntimeWarning) +warnings.simplefilter("ignore", FutureWarning) + +os.environ['TF_CPP_MIN_LOG_LEVEL'] = "3" + + +def load_old_model_json(model_json): + print("\n loading pre-trained model") + + custom_objects = {'dice_coefficient_loss': dice_coefficient_loss, 'dice_coefficient': dice_coefficient, + 'dice_coef': dice_coef, 'dice_coef_loss': dice_coef_loss, + 'weighted_dice_coefficient': weighted_dice_coefficient, + 'weighted_dice_coefficient_loss': weighted_dice_coefficient_loss} + try: + custom_objects["InstanceNormalization"] = InstanceNormalization + except ImportError: + pass + + try: + return model_from_json(model_json, custom_objects=custom_objects) + except ValueError as error: + if 'InstanceNormalization' in str(error): + raise ValueError(str(error) + + "\n\n Please install keras-contrib for InstanceNormalization:\n" + "'pip install git+https://www.github.com/keras-team/keras-contrib.git'") + else: + raise error + + +def get_prediction_labels(prediction, threshold=0.5, labels=None): + n_samples = prediction.shape[0] + label_arrays = [] + + for sample_number in range(n_samples): + label_data = np.argmax(prediction[sample_number], axis=0) + 1 + label_data[np.max(prediction[sample_number], axis=0) < threshold] = 0 + if labels: + for value in np.unique(label_data).tolist()[1:]: + label_data[label_data == value] = labels[value - 1] + label_arrays.append(np.array(label_data, dtype=np.uint8)) + + return label_arrays + + +def prediction_to_image(prediction, affine, label_map=False, threshold=0.5, labels=None): + if prediction.shape[1] == 1: + data = prediction[0, 0] + + elif prediction.shape[1] > 1: + if label_map: + label_map_data = get_prediction_labels(prediction, threshold=threshold, labels=labels) + data = label_map_data[0] + else: + return multi_class_prediction(prediction, affine) + else: + raise RuntimeError("Invalid prediction array shape: {0}".format(prediction.shape)) + + return nib.Nifti1Image(data, affine) + + +def multi_class_prediction(prediction, affine): + prediction_images = [] + + for i in range(prediction.shape[1]): + prediction_images.append(nib.Nifti1Image(prediction[0, i], affine)) + + return prediction_images + + +def run_test_case(test_data, model_json, model_weights, affine, + output_label_map=False, threshold=0.5, labels=None): + json_file = open(model_json, 'r') + loaded_model_json = json_file.read() + json_file.close() + model = load_old_model_json(loaded_model_json) + + model.load_weights(model_weights) + + prediction = model.predict(test_data) + + return prediction_to_image(prediction, affine, label_map=output_label_map, threshold=threshold, + labels=labels) diff --git a/hippmapper/deep/save_weights.py b/hippmapper/deep/save_weights.py new file mode 100755 index 0000000..a5a2586 --- /dev/null +++ b/hippmapper/deep/save_weights.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 + +# coding: utf-8 + +from keras.models import load_model +from keras_contrib.layers import InstanceNormalization +import hippmapper.deep.metrics +import sys +import os + +in_model = sys.argv[1] +model_name = sys.argv[2] + +custom_objects = {'dice_coefficient_loss': hippmapper.deep.metrics.dice_coefficient_loss, + 'dice_coefficient': hippmapper.deep.metrics.dice_coefficient, + 'dice_coef': hippmapper.deep.metrics.dice_coef, + 'dice_coef_loss': hippmapper.deep.metrics.dice_coef_loss, + 'weighted_dice_coefficient': hippmapper.deep.metrics.weighted_dice_coefficient, + 'weighted_dice_coefficient_loss': hippmapper.deep.metrics.weighted_dice_coefficient_loss, + "InstanceNormalization": InstanceNormalization} + +model = load_model(in_model, custom_objects=custom_objects) +model_json = model.to_json() + +with open("%s.json" % model_name, "w") as json_file: + json_file.write(model_json) + +print("Saving model weights") + +model.save_weights('%s_weights.h5' % model_name) + +print("Model weights and json saved") diff --git a/hippmapper/gui.py b/hippmapper/gui.py new file mode 100755 index 0000000..d12edb7 --- /dev/null +++ b/hippmapper/gui.py @@ -0,0 +1,189 @@ +#! /usr/bin/env python3 +# PYTHON_ARGCOMPLETE_OK +# coding: utf-8 + +import os +import subprocess +import sys +import hippmapper +from pathlib import Path +from PyQt5 import QtGui, QtCore, QtWidgets + +os.environ['TF_CPP_MIN_LOG_LEVEL'] = "3" + + +# from collections import defaultdict +class HorzTabBarWidget(QtWidgets.QTabBar): + def __init__(self, parent=None, *args, **kwargs): + self.tabSize = QtCore.QSize(kwargs.pop('width', 100), kwargs.pop('height', 25)) + QtWidgets.QTabBar.__init__(self, parent, *args, **kwargs) + + def paintEvent(self, event): + painter = QtWidgets.QStylePainter(self) + option = QtWidgets.QStyleOptionTab() + + for index in range(self.count()): + self.initStyleOption(option, index) + tabRect = self.tabRect(index) + tabRect.moveLeft(10) + painter.drawControl(QtWidgets.QStyle.CE_TabBarTabShape, option) + painter.drawText(tabRect, QtCore.Qt.AlignVCenter | + QtCore.Qt.TextDontClip, + self.tabText(index)) + painter.end() + + def tabSizeHint(self, index): + return self.tabSize + + +class HorzTabWidget(QtWidgets.QTabWidget): + def __init__(self, parent, *args): + QtGui.QTabWidget.__init__(self, parent, *args) + self.setTabBar(HorzTabBarWidget(self)) + + +def capture_help_fn(fn_name): + proc = subprocess.Popen("hippmapper %s -h" % fn_name, shell=True, stdout=subprocess.PIPE) + out = proc.communicate()[0] + out_str = out.decode("utf-8") + return out_str + + +modules = ['Conversion', 'Pre-Process', 'Segmentation', 'QC', 'Statistics',] + +nested_dict = { + + 'Conversion': { + 'functions': { + 0: { + 'name': 'File Type', + 'script': 'filetype', + 'opts': '-t filetype -v in_img -f out', + 'helpmsg': '' + }, + } + }, + + 'Pre-Process': { + 'functions': { + 0: { + 'name': 'Bias Correct', + 'script': 'bias_corr', + 'opts': '-t bias_corr -v in_img -f out', + 'helpmsg': 'Bias correct using N4' + }, + } + }, + + 'Segmentation': { + 'functions': { + 0: { + 'name': 'Hippocampus', + 'script': 'seg_hipp', + 'opts': '-t seg_hipp -v t1w -f out', + 'helpmsg': 'Segments hippocampus using a trained CNN' + }, + } + }, + + 'QC': { + 'functions': { + 0: { + 'name': 'Segmentation QC', + 'script': 'seg_qc', + 'opts': '-t seg_qc -v img seg -f out', + 'helpmsg': 'Creates tiled mosaic of segmentation overlaid on structural image' + } + } + }, + + 'Statistics': { + 'functions': { + 0: { + 'name': 'Hippocampal Volume Summary', + 'script': 'stats_hp', + 'opts': '-t stats_hp -v in_dir -f out_csv', + 'helpmsg': 'Generates volumetric summary of hippocampus segmentations' + }, + } + }, +} + + +def fun_button(nested_dictionary, module, btn_num, hyper_home): + fun_name = nested_dictionary[module]['functions'][btn_num]['name'] + btn = QtWidgets.QPushButton(fun_name) + btn.clicked.connect(lambda: run_func(nested_dictionary, module, btn_num, hyper_home)) + btn.setToolTip(nested_dict[module]['functions'][btn_num]['helpmsg']) + + return btn + + +def run_func(nested_dictionary, module, btnnum, hyper_home): + opts = nested_dictionary[module]['functions'][btnnum]['opts'] + script_name = nested_dictionary[module]['functions'][btnnum]['script'] + help_str = capture_help_fn(fn_name=script_name) + + subprocess.Popen('%s/utils/gui_options.py %s -hf "%s"' % (hyper_home, opts, help_str), shell=True, + stdin=None, stdout=None, stderr=None, close_fds=True) + + +def main(): + app = QtWidgets.QApplication(sys.argv) + + mainwidget = QtWidgets.QWidget() + mainwidget.resize(150, 550) + + font = QtGui.QFont('Mono', 10, QtGui.QFont.Light) + mainwidget.setFont(font) + mainwidget.move(QtWidgets.QApplication.desktop().screen().rect().center() - mainwidget.rect().center()) + + ver = hippmapper.__version__ + mainwidget.setWindowTitle("HippMapp3r %s" % ver) + + p = mainwidget.palette() + # p.setColor(mainwidget.backgroundRole(), QtCore.Qt.black) + mainwidget.setPalette(p) + + vbox = QtWidgets.QVBoxLayout(mainwidget) + + gui_file = os.path.realpath(__file__) + hyper_home = Path(gui_file).parents[0] + hyper_mother = Path(gui_file).parents[1] + + pic = QtWidgets.QLabel() + pixmap = QtGui.QPixmap("%s/docs/images/hippmapper_icon.png" % hyper_mother) + + pixmaps = pixmap.scaled(270, 150) # QtCore.Qt.KeepAspectRatio + pic.setPixmap(pixmaps) + pic.setAlignment(QtCore.Qt.AlignCenter) + + vbox.addWidget(pic) + + tabs = QtWidgets.QTabWidget() + tabs.setTabBar(HorzTabBarWidget(width=150, height=50)) + + for m, mod in enumerate(modules): + + widget = QtWidgets.QWidget() + widget.layout = QtWidgets.QVBoxLayout() + + for b in range(len(nested_dict[mod]['functions'])): + btn = fun_button(nested_dict, mod, b, hyper_home) + widget.layout.addWidget(btn) + + widget.setLayout(widget.layout) + tabs.addTab(widget, mod) + + tabs.setTabPosition(QtWidgets.QTabWidget.West) + + vbox.addWidget(tabs) + + mainwidget.setLayout(vbox) + mainwidget.show() + + sys.exit(app.exec_()) + + +if __name__ == '__main__': + main() diff --git a/hippmapper/preprocess/__init__.py b/hippmapper/preprocess/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/hippmapper/preprocess/biascorr.py b/hippmapper/preprocess/biascorr.py new file mode 100755 index 0000000..8567e27 --- /dev/null +++ b/hippmapper/preprocess/biascorr.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +# PYTHON_ARGCOMPLETE_OK +# coding: utf-8 + +import argparse +import argcomplete +import sys +import multiprocessing +import os +from datetime import datetime +from hippmapper.utils import endstatement + +from nipype.interfaces.ants import N4BiasFieldCorrection + +os.environ['TF_CPP_MIN_LOG_LEVEL'] = "3" + + +def parsefn(): + parser = argparse.ArgumentParser(usage="%(prog)s -i [ in_img ] \n\n" + "Bias field correct images using N4") + + required = parser.add_argument_group('required arguments') + required.add_argument('-i', '--in_img', type=str, required=True, metavar='', + help="input image") + + optional = parser.add_argument_group('optional arguments') + + optional.add_argument('-m', '--mask_img', type=str, metavar='', default=None, + help="mask image before correction (default: %(default)s)") + optional.add_argument('-s', '--shrink', type=int, metavar='', default=3, + help="shrink factor (default: %(default)s)") + + optional.add_argument('-n', '--noise', type=float, metavar='', default=0.005, + help="Noise parameter for histogram sharpening - deconvolution (default: %(default)s)") + optional.add_argument('-b', '--bspline', type=int, metavar='', default=300, + help="Bspline distance (default: %(default)s)") + optional.add_argument('-k', '--fwhm', type=float, metavar='', default=0.3, + help="FWHM for histogram sharpening - deconvolution (default: %(default)s)") + optional.add_argument('-it', '--iters', type=int, nargs='+', metavar='', default=[50, 50, 30, 20], + help="Number of iterations for convergence (default: %(default)s)") + optional.add_argument('-t', '--thresh', type=int, metavar='', default=1e-6, + help="Threshold for convergence (default: %(default)s)") + optional.add_argument('-o', '--out_img', type=str, metavar='', default=None, + help="output image (default: %(default)s)") + + # optional.add_argument("-h", "--help", action="help", help="Show this help message and exit") + + return parser + + +def parse_inputs(parser, args): + + if isinstance(args, list): + args = parser.parse_args(args) + argcomplete.autocomplete(parser) + + in_img = args.in_img.strip() + mask_img = args.mask_img + shrink = args.shrink + bspline = args.bspline + iters = args.iters + thresh = args.thresh + out_img = args.out_img.strip() if args.out_img is not None else None + + return in_img, mask_img, shrink, bspline, iters, thresh, out_img + + +def main(args): + parser = parsefn() + [in_img, mask_img, shrink, bspline, iters, thresh, out_img] = parse_inputs(parser, args) + + if out_img is not None and os.path.exists(out_img): + print("\n %s already exists" % out_img) + + else: + + start_time = datetime.now() + + n4 = N4BiasFieldCorrection() + n4.inputs.dimension = 3 + n4.inputs.input_image = in_img + n4.inputs.bspline_fitting_distance = bspline + n4.inputs.shrink_factor = shrink + n4.inputs.n_iterations = iters + n4.inputs.convergence_threshold = thresh + + cpu_load = 0.9 + cpus = multiprocessing.cpu_count() + ncpus = int(cpu_load * cpus) + + n4.inputs.num_threads = ncpus + + if mask_img is not None: + n4.inputs.args = "--mask-image %s" % mask_img.strip() + + if out_img is not None: + n4.inputs.output_image = out_img.strip() + + print("\n bias field correcting %s " % in_img) + n4.terminal_output = "none" + n4.run() + + endstatement.main('Bias field correction', '%s' % (datetime.now() - start_time)) + +if __name__ == '__main__': + main(sys.argv[1:]) + diff --git a/hippmapper/preprocess/trim_like.py b/hippmapper/preprocess/trim_like.py new file mode 100644 index 0000000..5fd1a94 --- /dev/null +++ b/hippmapper/preprocess/trim_like.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +# PYTHON_ARGCOMPLETE_OK +# coding: utf-8 + +import numpy as np +import nibabel as nib +import argcomplete +import argparse +import sys + + +def parsefn(): + parser = argparse.ArgumentParser() + + required = parser.add_argument_group('required arguments') + + required.add_argument('-r', '--ref', type=str, metavar='', help="input reference (trimmed or expanded)", + required=True) + required.add_argument('-i', '--img', type=str, metavar='', help="input image", required=True) + required.add_argument('-o', '--out', type=str, metavar='', help="output image", required=True) + + # optional = parser.add_argument_group('optional arguments') + + # optional.add_argument("-h", "--help", action="help", help="Show this help message and exit") + + return parser + +def parse_inputs(parser, args): + + if isinstance(args, list): + args = parser.parse_args(args) + argcomplete.autocomplete(parser) + + img = args.img.strip() + ref = args.ref.strip() + out = args.out.strip() + + return img, ref, out + + +def main(in_args): + parser = parsefn() + img, ref, out = parse_inputs(parser, in_args) + + in_img = nib.load(img) + in_img_data = in_img.get_data() + in_ref = nib.load(ref) + + in_img_aff = in_img.affine + in_ref_aff = in_ref.affine + + vxi = in_img.header.get_zooms()[0] + vyi = in_img.header.get_zooms()[1] + vzi = in_img.header.get_zooms()[2] + + vxr = in_img.header.get_zooms()[0] + vyr = in_img.header.get_zooms()[1] + vzr = in_img.header.get_zooms()[2] + + if min(in_ref.shape) < min(in_img.shape): + # trim + dimx = in_ref.shape[0] + dimy = in_ref.shape[1] + dimz = in_ref.shape[2] + + x = np.abs(in_img_aff[0, 3]) - np.abs(in_ref_aff[0, 3]) + y = np.abs(in_img_aff[1, 3]) - np.abs(in_ref_aff[1, 3]) + z = np.abs(in_img_aff[2, 3]) - np.abs(in_ref_aff[2, 3]) + + x = int(np.round(np.abs(x) / np.abs(vxi))) + y = int(np.round(np.abs(y) / np.abs(vyi))) + z = int(np.round(np.abs(z) / np.abs(vzi))) + + # x = int( ( np.abs(in_img_aff[0,3]) / np.abs(vx) ) - ( np.abs(in_ref_aff[0,3]) / np.abs(vx) ) ) + # y = int( ( np.abs(in_img_aff[1,3]) / np.abs(vy) ) - ( np.abs(in_ref_aff[1,3]) / np.abs(vy) ) ) + # z = int( ( np.abs(in_img_aff[2,3]) / np.abs(vz) ) - ( np.abs(in_ref_aff[2,3]) / np.abs(vz) ) ) + + img_trim = in_img_data[x:x + dimx, y:y + dimy, z:z + dimz] + nii = nib.Nifti1Image(img_trim, affine=in_ref.affine) + + elif min(in_ref.shape) > min(in_img.shape): + # expand with zero padding + dimx = in_img.shape[0] + dimy = in_img.shape[1] + dimz = in_img.shape[2] + + x = np.abs(in_ref_aff[0, 3]) - np.abs(in_img_aff[0, 3]) + y = np.abs(in_ref_aff[1, 3]) - np.abs(in_img_aff[1, 3]) + z = np.abs(in_ref_aff[2, 3]) - np.abs(in_img_aff[2, 3]) + + x = int(np.round(np.abs(x) / np.abs(vxi))) + y = int(np.round(np.abs(y) / np.abs(vyi))) + z = int(np.round(np.abs(z) / np.abs(vzi))) + + img_expand = np.zeros(in_ref.shape) + img_expand[x:x + dimx, y:y + dimy, z:z + dimz] = in_img.get_data() + nii = nib.Nifti1Image(img_expand, affine=in_ref.affine) + + nib.save(nii, out) + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/hippmapper/qc/__init__.py b/hippmapper/qc/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/hippmapper/qc/seg_qc.py b/hippmapper/qc/seg_qc.py new file mode 100755 index 0000000..c98af48 --- /dev/null +++ b/hippmapper/qc/seg_qc.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +# PYTHON_ARGCOMPLETE_OK +# coding: utf-8 + +import os +import argcomplete +import argparse +import sys +from nipype.interfaces.ants.visualization import ConvertScalarImageToRGB, CreateTiledMosaic +from nipype.interfaces.c3 import C3d +import warnings + +warnings.simplefilter("ignore", FutureWarning) + +os.environ['TF_CPP_MIN_LOG_LEVEL'] = "3" + + +def parsefn(): + parser = argparse.ArgumentParser(usage='%(prog)s -i [ img ] \n\n' + "Create tiled mosaic of segmentation overlaid on structural image") + + required = parser.add_argument_group('optional arguments') + + required.add_argument('-i', '--img', type=str, metavar='', help="input structural image", required=True) + + optional = parser.add_argument_group('optional arguments') + + optional.add_argument('-s', '--seg', type=str, metavar='', help="input segmentation") + optional.add_argument('-g', '--gap', type=int, metavar='', help="gap between slices/increment", + default=2) + optional.add_argument('-m', '--min', type=int, metavar='', help="min slice", default=30) + optional.add_argument('-a', '--alpha', type=float, metavar='', help="alpha", default=0.5) + optional.add_argument('-t', '--tile', type=str, metavar='', help="tile size", default='4x5') + optional.add_argument('-d', '--direct', type=int, metavar='', help="direction", default=2) + optional.add_argument('-f', '--flip', type=str, metavar='', help="flip xy", default='0x1') + optional.add_argument('-r', '--roi', type=int, metavar='', help="roi around segmentation (isotropic)", default=30) + optional.add_argument('-o', '--out', type=str, metavar='', help="output image") + + # optional.add_argument("-h", "--help", action="help", help="Show this help message and exit") + + return parser + + +def parse_inputs(parser, args): + if isinstance(args, list): + args = parser.parse_args(args) + argcomplete.autocomplete(parser) + + img = args.img + seg = args.seg + gap = args.gap + tile = args.tile + alpha = args.alpha + ax = args.direct + roi = args.roi + flip = args.flip + min_sl = args.min + + subj_dir = os.path.dirname(os.path.abspath(img)) + qc_dir = os.path.join(subj_dir, 'qc') + if (args.out is None) and (not os.path.exists(qc_dir)): + os.mkdir(qc_dir) + + if seg: + seg_name = os.path.basename(seg.split('.')[0]) + if 'pred' in seg_name: + seg_name = seg_name.split('_pred')[0].split('_')[-1] + out = args.out if args.out is not None else '%s/%s_seg_qc.png' % (qc_dir, seg_name) + else: + out = args.out if args.out is not None else '%s/seg_qc.png' % qc_dir + + return subj_dir, img, seg, gap, tile, alpha, ax, roi, flip, min_sl, out + + +def main(args): + parser = parsefn() + subj_dir, img, seg, gap, tile, alpha, ax, roi, flip, min_sl, out = parse_inputs(parser, args) + + # pred preprocess dir + pred_dir = '%s/pred_process' % os.path.abspath(subj_dir) + if not os.path.exists(pred_dir): + os.mkdir(pred_dir) + + # trim seg to focus + c3 = C3d() + + mosaic_slicer = CreateTiledMosaic() + + if seg: + c3.inputs.in_file = seg + c3.inputs.args = "-trim %sx%sx%svox" % (roi, roi, roi) + seg_trim_file = "%s/%s_trim_mosaic.nii.gz" % (pred_dir, os.path.basename(seg).split('.')[0]) + # seg_trim_file = "seg_trim.nii.gz" + c3.inputs.out_file = seg_trim_file + c3.run() + + # trim struct like seg + c3.inputs.in_file = seg_trim_file + c3.inputs.args = "%s -reslice-identity" % img + struct_trim_file = "%s/%s_trim_mosaic.nii.gz" % (pred_dir, os.path.basename(img).split('.')[0]) + # struct_trim_file = "struct_trim.nii.gz" + c3.inputs.out_file = struct_trim_file + c3.run() + + # create rgb image from seg + converter = ConvertScalarImageToRGB() + + converter.inputs.dimension = 3 + converter.inputs.input_image = seg_trim_file + converter.inputs.colormap = 'jet' + converter.inputs.minimum_input = 0 + converter.inputs.maximum_input = 10 + out_rgb = "%s/%s_trim_rgb.nii.gz" % (pred_dir, os.path.basename(seg).split('.')[0]) + converter.inputs.output_image = out_rgb + converter.run() + + mosaic_slicer.inputs.rgb_image = out_rgb + mosaic_slicer.inputs.mask_image = seg_trim_file + mosaic_slicer.inputs.alpha_value = alpha + + else: + struct_trim_file = img + + mosaic_slicer.inputs.rgb_image = struct_trim_file + + # stretch and clip intensities + c3.inputs.in_file = struct_trim_file + c3.inputs.args = "-stretch 2% 98% 0 255 -clip 0 255" + c3.inputs.out_file = struct_trim_file + c3.run() + + # slices to show + if gap == 1: + max_sl = 100 + elif gap == 2: + max_sl = 220 + elif gap == 5: + max_sl = 275 + else: + max_sl = 300 + + slices = '[%s,%s,%s]' % (gap, min_sl, max_sl) + + mosaic_slicer.inputs.input_image = struct_trim_file + + mosaic_slicer.inputs.output_image = out + mosaic_slicer.inputs.direction = ax + # mosaic_slicer.inputs.pad_or_crop = '[ -15x -50 , -15x -30 ,0]' + mosaic_slicer.inputs.tile_geometry = tile + mosaic_slicer.inputs.slices = slices + mosaic_slicer.inputs.flip_slice = flip + mosaic_slicer.terminal_output = "none" + mosaic_slicer.run() + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/hippmapper/segment/__init__.py b/hippmapper/segment/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/hippmapper/segment/hippmapper.py b/hippmapper/segment/hippmapper.py new file mode 100755 index 0000000..f8c1d08 --- /dev/null +++ b/hippmapper/segment/hippmapper.py @@ -0,0 +1,416 @@ +#!/usr/bin/env python3 +# PYTHON_ARGCOMPLETE_OK +# coding: utf-8 + +import os +import sys +import glob +from datetime import datetime +from pathlib import Path +import argcomplete +import argparse +import numpy as np +import nibabel as nib +import subprocess +from nilearn.image import reorder_img, resample_img, resample_to_img, math_img, largest_connected_component_img +from hippmapper.deep.predict import run_test_case +from hippmapper.utils import endstatement +from hippmapper.preprocess import biascorr, trim_like +from hippmapper.qc import seg_qc +from nipype.interfaces.fsl import maths +from nipype.interfaces.c3 import C3d +import warnings + +warnings.simplefilter("ignore") + +os.environ['TF_CPP_MIN_LOG_LEVEL'] = "3" + + +def parsefn(): + parser = argparse.ArgumentParser(usage="%(prog)s -s [ subj ] \n\n" + "Segments hippocampus using a trained CNN\n" + "works best with a bias-corrected with-skull or skull-tripped image in" + " standard orientation (RPI or LPI)\n\n" + "Examples: \n" + " hippmapper -t1 my_subj/mprage.nii.gz \n" + "OR (to bias-correct before and overwrite existing segmentation)\n" + " hippmapper -t1 my_subj/mprage.nii.gz -b -f \n" + "OR (to run for subj - looks for my_subj_T1_nu.nii.gz)\n" + " hippmapper -s my_subj \n") + + optional = parser.add_argument_group('optional arguments') + + optional.add_argument('-s', '--subj', type=str, metavar='', help="input subject") + optional.add_argument('-t1', '--t1w', type=str, metavar='', help="input T1-weighted") + optional.add_argument('-b', '--bias', help="bias field correct image before segmentation", + action='store_true') + optional.add_argument('-o', '--out', type=str, metavar='', help="output prediction") + optional.add_argument('-f', '--force', help="overwrite existing segmentation", action='store_true') + optional.add_argument('-ss', '--session', type=str, metavar='', help="input session for longitudinal studies") + optional.add_argument("-ign_ort", "--ign_ort", action='store_true', + help="ignore orientation if tag is wrong") + return parser + + +def parse_inputs(parser, args): + if isinstance(args, list): + args = parser.parse_args(args) + argcomplete.autocomplete(parser) + + # check if subj or t1w are given + if (args.subj is None) and (args.t1w is None): + sys.exit('subj (-s) or t1w (-t1) must be given') + + # get subj dir if cross-sectional or longitudinal + if args.subj: + if args.session: + subj_dir = os.path.abspath(glob.glob(os.path.join(args.subj, '*%s*' % args.session))[0]) + else: + subj_dir = os.path.abspath(args.subj) + else: + subj_dir = os.path.abspath(os.path.dirname(args.t1w)) + + subj = os.path.basename(subj_dir) if args.subj is not None else os.path.basename(args.t1w).split('.')[0] + print('\n input subject:', subj) + + bias = True if args.bias else False + + if args.t1w is not None: + t1 = args.t1w + else: + # look for bias-corrected or original T1 + try: + t1_nu = glob.glob(os.path.join(subj_dir, '%s_T1_nu.*' % subj))[0] + t1 = t1_nu + except IndexError: + assert glob.glob(os.path.join(subj_dir, '%s_T1.*' % subj)), \ + "no file called: %s_T1 in the subject dir" % subj + t1_org = glob.glob(os.path.join(subj_dir, '%s_T1.*' % subj))[0] + t1 = t1_org + bias = True + print('\n reading the original T1.. will bias-field correct it before segmentation') + + assert os.path.exists(t1), "%s does not exist ... please check path and rerun script" % t1 + + out = args.out if args.out is not None else None + + force = True if args.force else False + + ign_ort = True if args.ign_ort else False + + return subj_dir, subj, t1, out, bias, ign_ort, force + + +def orient_img(in_img_file, orient_tag, out_img_file): + c3 = C3d() + c3.inputs.in_file = in_img_file + c3.inputs.args = "-orient %s" % orient_tag + c3.inputs.out_file = out_img_file + c3.run() + + +def check_orient(in_img_file, r_orient, l_orient, out_img_file): + """ + Check image orientation and re-orient if not in standard orientation (RPI or LPI) + :param in_img_file: input_image + :param r_orient: right ras orientation + :param l_orient: left las orientation + :param out_img_file: output oriented image + """ + res = subprocess.run('c3d %s -info' % in_img_file, shell=True, stdout=subprocess.PIPE) + out = res.stdout.decode('utf-8') + ort_str = out.find('orient =') + 9 + img_ort = out[ort_str:ort_str + 3] + + if (img_ort != r_orient) and (img_ort != l_orient): + print("\n Warning: input image is not in RPI or LPI orientation.. " + "\n re-orienting image to standard orientation based on orient tags (please make sure they are correct)") + + if img_ort == 'Obl': + orient_tag = out[-5:-2] + else: + orient_tag = 'RPI' if 'R' in img_ort else 'LPI' + orient_img(in_img_file, orient_tag, out_img_file) + + +def resample(image, new_shape, interpolation="continuous"): + """ + Resample image to new shape + :param image: input image + :param new_shape: chosen shape + :param interpolation: interpolation method + :return: resampled image + """ + input_shape = np.asarray(image.shape, dtype=image.get_data_dtype()) + ras_image = reorder_img(image, resample=interpolation) + output_shape = np.asarray(new_shape) + new_spacing = input_shape / output_shape + new_affine = np.copy(ras_image.affine) + new_affine[:3, :3] = ras_image.affine[:3, :3] * np.diag(new_spacing) + + return resample_img(ras_image, target_affine=new_affine, target_shape=output_shape, interpolation=interpolation) + + +def threshold_img(t1, training_mod, thresh_val, thresh_file): + """ + Threshold image using fsl maths + :param t1: input image + :param training_mod: image name + :param thresh_val: threshold value (in percentile) + :param thresh_file: output thresholded image + """ + threshold = maths.Threshold() + threshold.inputs.in_file = t1 + threshold.inputs.thresh = thresh_val + threshold.inputs.use_robust_range = True + threshold.inputs.use_nonzero_voxels = True + threshold.inputs.out_file = thresh_file + + if not os.path.exists(thresh_file): + print("\n pre-processing %s" % training_mod) + threshold.run() + + +def standard_img(in_file, std_file): + """ + Orient image in standard orientation + :param in_file: input image + :param std_file: output oriented image + """ + c3 = C3d() + c3.inputs.in_file = in_file + file_shape = nib.load(in_file).shape + nx = int(file_shape[0] / 2.2) + ny = int(file_shape[1] / 2.2) + nz = int(file_shape[2] / 2.2) + c3.inputs.args = "-binarize -as m %s -push m -nlw %sx%sx%s -push m -times -replace nan 0" % (in_file, nx, ny, nz) + c3.inputs.out_file = std_file + + if not os.path.exists(std_file): + c3.run() + + +def get_largest_two_comps(in_img, out_comps): + """ + Get the two largest connected components + :param in_img: input image + :param out_comps: output image with two components + """ + first_comp = largest_connected_component_img(in_img) + residual = math_img('img1 - img2', img1=in_img, img2=first_comp) + second_comp = largest_connected_component_img(residual) + comb_comps = math_img('img1 + img2', img1=first_comp, img2=second_comp) + + nib.save(comb_comps, out_comps) + + +def trim_img_to_size(in_img, trimmed_img): + """ + Trim image to specific size (112x112x64mm) + :param in_img: input image + :param trimmed_img: trimmed image + """ + c3 = C3d() + c3.inputs.in_file = in_img + c3.inputs.args = "-trim-to-size 112x112x64mm" + c3.inputs.out_file = trimmed_img + + if not os.path.exists(trimmed_img): + print("\n extracting hippocampus region") + c3.run() + + +def split_seg_sides(in_bin_seg_file, out_seg_file): + """ + Split segmentation into Right/Left + :param in_bin_seg_file: input binary segmentation + :param out_seg_file: output segmentation with both sides + """ + in_bin_seg = nib.load(in_bin_seg_file) + mid = int(in_bin_seg.shape[0] / 2) + out_seg = in_bin_seg.get_data().copy() + seg_ort = nib.aff2axcodes(in_bin_seg.affine) + + r_orient_nii = ('R', 'A', 'S') + l_orient_nii = ('L', 'A', 'S') + + if seg_ort == l_orient_nii: + new = in_bin_seg.get_data()[mid:-1, :, :] + new[new == 1] = 2 + out_seg[mid:-1, :, :] = new + elif seg_ort == r_orient_nii: + new = in_bin_seg.get_data()[0:mid, :, :] + new[new == 1] = 2 + out_seg[0:mid, :, :] = new + + out_seg_nii = nib.Nifti1Image(out_seg, in_bin_seg.affine) + + nib.save(out_seg_nii, out_seg_file) + + +# -------------- +# Main function +# -------------- + + +def main(args): + """ + Segment hippocampus using a trained CNN + :param args: subj_dir, subj, t1, out, bias, force + :return: prediction (segmentation file) + """ + parser = parsefn() + subj_dir, subj, t1, out, bias, ign_ort, force = parse_inputs(parser, args) + pred_name = 'T1acq_hipp_pred' if args.subj is not None else 'hipp_pred' + + if out is None: + prediction = os.path.join(subj_dir, "%s_%s.nii.gz" % (subj, pred_name)) + else: + prediction = out + + if os.path.exists(prediction) and force is False: + print("\n %s already exists" % prediction) + + else: + start_time = datetime.now() + + hfb = os.path.realpath(__file__) + hyper_dir = Path(hfb).parents[2] + + model_json = os.path.join(hyper_dir, 'models', 'hipp_model.json') + model_weights = os.path.join(hyper_dir, 'models', 'hipp_model_weights.h5') + + assert os.path.exists( + model_weights), "%s model does not exits ... please download and rerun script" % model_weights + + # pred preprocess dir + pred_dir = os.path.join('%s' % os.path.abspath(subj_dir), 'pred_process') + if not os.path.exists(pred_dir): + os.mkdir(pred_dir) + + training_mod = "t1" + + if bias is True: + t1_bias = os.path.join(subj_dir, "%s_nu.nii.gz" % os.path.basename(t1).split('.')[0]) + biascorr.main(["-i", "%s" % t1, "-o", "%s" % t1_bias]) + in_ort = t1_bias + else: + in_ort = t1 + + # check orientation + r_orient = 'RPI' + l_orient = 'LPI' + t1_ort = os.path.join(subj_dir, "%s_std_orient.nii.gz" % os.path.basename(t1).split('.')[0]) + + if ign_ort is False: + check_orient(in_ort, r_orient, l_orient, t1_ort) + + # threshold at 10 percentile of non-zero voxels + thresh_file = os.path.join(pred_dir, "%s_thresholded.nii.gz" % os.path.basename(t1).split('.')[0]) + in_thresh = t1_ort if os.path.exists(t1_ort) else t1 + threshold_img(in_thresh, training_mod, 10, thresh_file) + + # standardize + std_file = os.path.join(pred_dir, "%s_thresholded_standardized.nii.gz" % os.path.basename(t1).split('.')[0]) + standard_img(thresh_file, std_file) + + # resample images + t1_img = nib.load(std_file) + res = resample(t1_img, [160, 160, 128]) + res_file = os.path.join(pred_dir, "%s_thresholded_resampled.nii.gz" % os.path.basename(t1).split('.')[0]) + res.to_filename(res_file) + + std = nib.load(res_file) + test_data = np.zeros((1, 1, 160, 160, 128), dtype=t1_img.get_data_dtype()) + test_data[0, 0, :, :, :] = std.get_data() + + print("\n predicting initial hippocampus segmentation") + + pred = run_test_case(test_data=test_data, model_json=model_json, model_weights=model_weights, + affine=res.affine, output_label_map=True, labels=1) + + # resample back + pred_res = resample_to_img(pred, t1_img) + pred_th = math_img('img > 0.5', img=pred_res) + + # largest conn comp + init_pred_name = os.path.join(pred_dir, "%s_hipp_init_pred.nii.gz" % subj) + get_largest_two_comps(pred_th, init_pred_name) + + # trim seg to size + trim_seg = os.path.join(pred_dir, "%s_hipp_init_pred_trimmed.nii.gz" % subj) + trim_img_to_size(init_pred_name, trim_seg) + + # trim t1 + t1_zoom = os.path.join(pred_dir, "%s_hipp_region.nii.gz" % subj) + trim_like.main(['-i %s' % thresh_file, '-r %s' % trim_seg, '-o %s' % t1_zoom]) + + # -------------- + # 2nd model + # -------------- + + pred_shape = [112, 112, 64] + + t1_zoom_img = nib.load(t1_zoom) + test_zoom_data = np.zeros((1, 1, pred_shape[0], pred_shape[1], pred_shape[2]), + dtype=t1_zoom_img.get_data_dtype()) + + # standardize + std_file_trim = os.path.join(pred_dir, "%s_trimmed_thresholded_standardized.nii.gz" + % os.path.basename(t1).split('.')[0]) + standard_img(t1_zoom, std_file_trim) + + # resample images + t1_img = nib.load(std_file_trim) + res_zoom = resample(t1_img, pred_shape) + res_file = os.path.join(pred_dir, "%s_trimmed_resampled.nii.gz" % os.path.basename(t1).split('.')[0]) + res_zoom.to_filename(res_file) + + test_zoom_data[0, 0, :, :, :] = res_zoom.get_data() + + model_zoom_json = os.path.join(hyper_dir, 'models', 'hipp_zoom_model.json') + model_zoom_weights = os.path.join(hyper_dir, 'models', 'hipp_zoom_model_weights.h5') + + assert os.path.exists( + model_zoom_weights), "%s model does not exits ... please download and rerun script" % model_zoom_weights + + print("\n predicting hippocampus segmentation") + + pred_zoom = run_test_case(test_data=test_zoom_data, model_json=model_zoom_json, + model_weights=model_zoom_weights, + affine=res_zoom.affine, output_label_map=True, labels=1) + + # resample back + pred_zoom_res = resample_to_img(pred_zoom, t1_zoom_img) + pred_zoom_name = os.path.join(pred_dir, "%s_trimmed_hipp_pred_prob.nii.gz" % subj) + nib.save(pred_zoom_res, pred_zoom_name) + pred_zoom_th = math_img('img > 0.5', img=pred_zoom_res) + + # largest 2 conn comp + comb_comps_zoom_bin_name = os.path.join(pred_dir, "%s_trimmed_hipp_bin_pred.nii.gz" % subj) + get_largest_two_comps(pred_zoom_th, comb_comps_zoom_bin_name) + + # split seg sides + comb_comps_zoom_name = os.path.join(pred_dir, "%s_trimmed_hipp_pred.nii.gz" % subj) + split_seg_sides(comb_comps_zoom_bin_name, comb_comps_zoom_name) + + # expand to original size + bin_prediction = os.path.join(subj_dir, "%s_%s_bin.nii.gz" % (subj, pred_name)) + + t1_ref = t1_ort if os.path.exists(t1_ort) else t1 + + trim_like.main(['-i %s' % comb_comps_zoom_bin_name, '-r %s' % t1_ref, '-o %s' % bin_prediction]) + trim_like.main(['-i %s' % comb_comps_zoom_name, '-r %s' % t1_ref, '-o %s' % prediction]) + + print("\n generating mosaic image for qc") + + seg_qc.main(['-i', '%s' % t1_ref, '-s', '%s' % prediction, '-d', '1', '-g', '3']) + + endstatement.main('Hippocampus prediction and mosaic generation', '%s' % (datetime.now() - start_time)) + + +if __name__ == "__main__": + main(sys.argv[1:]) + +# TODO +# add neck option -hfb t1 then trim diff --git a/hippmapper/stats/__init__.py b/hippmapper/stats/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/hippmapper/stats/outlier_detection.py b/hippmapper/stats/outlier_detection.py new file mode 100644 index 0000000..8125415 --- /dev/null +++ b/hippmapper/stats/outlier_detection.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Created on Fri Feb 8 14:20:38 2019 + +@author: mgoubran +""" +import os +import glob +import pandas as pd +import numpy as np +import datetime +import sys + + +proj_dir = sys.argv[1] + +# read geom dataframe +list_of_files = glob.glob('%s/label_geom*' % proj_dir) +df = pd.read_csv(max(list_of_files, key=os.path.getctime)) + +# paras +stds = [2, 2] +min_vol = 1000 + +# norm volumes +df['Vol_norm_R'] = df['Vol_R'] / df['HfB_Vol'] +df['Vol_norm_L'] = df['Vol_L'] / df['HfB_Vol'] + +# threshold by 1000 +r_fil = df[df.Vol_R > min_vol] +l_fil = df[df.Vol_L > min_vol] + +# add ones less than 1000 +r_less = df.Subject[df.Vol_R < min_vol].values +l_less = df.Subject[df.Vol_L < min_vol].values + +rp_less = df.Path[df.Vol_R < min_vol].values +lp_less = df.Path[df.Vol_L < min_vol].values + +# metrics = ['Vol', 'SA', 'ECC', 'Elong'] +metrics = ['Vol_norm', 'SA'] + +out_subjs_std = {} +for s, std in enumerate(stds): + + std_off_ass = std # std dev + std_off_vol = std + + r_outs = [] + rp_outs = [] + l_outs = [] + lp_outs = [] + d_outs = [] + dp_outs = [] + + for m, met in enumerate(metrics): + # get means + r_m = r_fil['%s_R' % met].mean() + l_m = r_fil['%s_L' % met].mean() + + # get stds + r_s = r_fil['%s_R' % met].std() + l_s = r_fil['%s_L' % met].std() + + # extract subjects with less than 2 std from mean + r_out = df.Subject[df['%s_R' % met] < (r_m - std_off_vol * r_s)].values + rp_out = df.Path[df['%s_R' % met] < (r_m - std_off_vol * r_s)].values + r_outs.append(r_out) + rp_outs.append(rp_out) + + l_out = df.Subject[df['%s_L' % met] < (l_m - std_off_vol * l_s)].values + lp_out = df.Path[df['%s_L' % met] < (l_m - std_off_vol * l_s)].values + l_outs.append(l_out) + lp_outs.append(lp_out) + + # outliers by left/right assymetry + fil = df[(df.Vol_R > min_vol) & (df.Vol_L > min_vol)] + diff = np.abs(fil['%s_R' % met].values - fil['%s_L' % met].values) + fil['diff'] = diff + d_m = diff.mean() + d_s = diff.std() + d_out = fil.Subject[fil['diff'] > (d_m + (d_s * std_off_ass))].values + dp_out = fil.Path[fil['diff'] > (d_m + (d_s * std_off_ass))].values + d_outs.append(d_out) + dp_outs.append(dp_out) + + r_outs = np.hstack(r_outs) + l_outs = np.hstack(l_outs) + d_outs = np.hstack(d_outs) + + rp_outs = np.hstack(rp_outs) + lp_outs = np.hstack(lp_outs) + dp_outs = np.hstack(dp_outs) + + # add all lists + all_out = np.hstack((r_outs, l_outs, d_outs, r_less, l_less)) + all_p_out = np.hstack((rp_outs, lp_outs, dp_outs, rp_less, lp_less)) + + # get unique + out_subjs_std[std] = np.unique(all_out) + + +# --- outlier prob +out_subjs_std_low = out_subjs_std[stds[0]] +out_subjs_std_high = out_subjs_std[stds[1]] + +med_prob_subjs = np.setdiff1d(out_subjs_std_low, out_subjs_std_high) +prob_subjs = np.hstack([med_prob_subjs, out_subjs_std_high]) + +med_probs = np.repeat('M', len(med_prob_subjs)) +high_probs = np.repeat('H', len(out_subjs_std_high)) +probs = np.hstack([med_probs, high_probs]) + +probs_dict = dict(zip(prob_subjs, probs)) + +df['Outlier_Prob'] = df.Subject.map(probs_dict) +df['Outlier_Prob'] = df.Outlier_Prob.fillna('L') + +date_str = datetime.date.today().strftime("%d%m%y") +df.to_csv('%s/hippocampal_volumes_with_outlier_prob_%s.csv' % (proj_dir, date_str), index=False) diff --git a/hippmapper/stats/summary_hp_vols.py b/hippmapper/stats/summary_hp_vols.py new file mode 100644 index 0000000..bd4e125 --- /dev/null +++ b/hippmapper/stats/summary_hp_vols.py @@ -0,0 +1,78 @@ +import numpy as np +import nibabel as nib +import os +import pandas as pd +import warnings +import argcomplete +import argparse +import sys +import glob + +warnings.filterwarnings("ignore") + + +def parsefn(): + parser = argparse.ArgumentParser(description='Generates volumetric summary of hippocampus segmentations', + usage="%(prog)s -i [ in_dir ] -o [ out_csv ]") + + required = parser.add_argument_group('required arguments') + + required.add_argument('-i', '--in_dir', type=str, required=True, metavar='', + help='input directory containing subjects') + required.add_argument('-o', '--out_csv', type=str, metavar='', + help='output stats ex: hp_vols_summary.csv', default='hipp_volumes.csv') + + return parser + + +def parse_inputs(parser, args): + if isinstance(args, list): + args = parser.parse_args(args) + argcomplete.autocomplete(parser) + + input_dir = args.in_dir + out_csv = args.out_csv + + return input_dir, out_csv + + +def main(args): + parser = parsefn() + input_dir, out_csv = parse_inputs(parser, args) + + hp_label = [1, 2] + hp_abb = ['Right_HP', 'Left_HP'] + mask_name = 'hipp_pred.nii.gz' + + subjs_dirs = [subj for subj in os.listdir(input_dir) if os.path.isdir(os.path.join(input_dir, subj))] + index = [] + my_index = [] + volume = np.zeros([len(subjs_dirs), len(hp_abb)]) + for i in range(0, len(subjs_dirs)): + my_index.append(i) + if glob.glob(os.path.join(input_dir, subjs_dirs[i], '*%s' % mask_name)): + # if os.path.isfile(os.path.join(input_dir, subjs_dirs[i], subjs_dirs[i] + mask_name)): + print('reading ', subjs_dirs[i]) + index.append(subjs_dirs[i]) + # mask = nib.load(os.path.join(input_dir, subjs_dirs[i], subjs_dirs[i] + mask_name)) + mask = nib.load(glob.glob(os.path.join(input_dir, subjs_dirs[i], '*%s' % mask_name))[0]) + mask_data = mask.get_data() + mask_hdr = mask.get_header() + voxel_size = mask_hdr.get_zooms() + voxel_volume = voxel_size[0] * voxel_size[1] * voxel_size[2] + for j in range(0, len(hp_label)): + volume[i, j] = np.shape(np.nonzero(mask_data == hp_label[j]))[1] * voxel_volume + else: + print(subjs_dirs[i], ' is missing') + + cols = ['%s_Volume' % hp_abb[0], '%s_Volume' % hp_abb[1]] + + df = pd.DataFrame(volume, index=subjs_dirs, columns=cols) + df.index.name = 'Subjects' + df = df[(df.T != 0).any()] + print('saving hippocampus volumetric csv') + df.round(3).to_csv(out_csv) + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/hippmapper/utils/__init__.py b/hippmapper/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/hippmapper/utils/endstatement.py b/hippmapper/utils/endstatement.py new file mode 100644 index 0000000..5d11143 --- /dev/null +++ b/hippmapper/utils/endstatement.py @@ -0,0 +1,39 @@ +#! /usr/bin/env python3 +# PYTHON_ARGCOMPLETE_OK +# coding: utf-8 + +import os +import pwd +import re +from datetime import datetime +import warnings +warnings.simplefilter("ignore", RuntimeWarning) +warnings.simplefilter("ignore", FutureWarning) + + +def main(task=None, timediff=None): + """ + Generates end statement based on function/task and time difference + """ + name = pwd.getpwuid(os.getuid())[4] + + if re.search('[a-zA-Z]', name): + user = name.split(" ")[0] + user = user.replace(',', '').strip() + else: + user = os.environ['USER'] + + if 6 < datetime.now().hour < 12: + timeday = 'morning' + elif 12 <= datetime.now().hour < 18: + timeday = 'afternoon' + elif 18 <= datetime.now().hour < 22: + timeday = 'evening' + else: + timeday = 'night' + + print("\n %s done in %s ... Have a good %s %s!\n" % (task, timediff, timeday, user)) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/hippmapper/utils/gui_options.py b/hippmapper/utils/gui_options.py new file mode 100755 index 0000000..a9ad898 --- /dev/null +++ b/hippmapper/utils/gui_options.py @@ -0,0 +1,209 @@ +#! /usr/bin/env python3 +# PYTHON_ARGCOMPLETE_OK +# coding: utf-8 + +import os +import argparse +import sys +import re +import subprocess +from PyQt5 import QtGui, QtCore, QtWidgets + +os.environ['TF_CPP_MIN_LOG_LEVEL'] = "3" + + +def helpmsg(): + return '''gui_options.py -t title -f [ fields separated by space] -v [volumes to open] -d [dirs to open] + -hf helpfun + +Takes list of strings as options for entries for a gui options, and a gui title + +example: gui_options.py -t "Reg options" -v clar labels -f orient label resolution + +Input options will be printed as output + +''' + + +def parseargs(): + parser = argparse.ArgumentParser(description='Sample argparse py', usage=helpmsg()) + parser.add_argument('-t', '--title', type=str, help="gui title", required=True) + parser.add_argument('-f', '--fields', type=str, nargs='+', help="fields for options") + parser.add_argument('-v', '--vols', type=str, nargs='+', help="volumes for reading") + parser.add_argument('-d', '--dirs', type=str, nargs='+', help="directories for reading") + parser.add_argument('-hf', '--helpfun', type=str, help="help fun") + + args = parser.parse_args() + + title = args.title + fields = args.fields + vols = args.vols + dirs = args.dirs + helpfun = args.helpfun + + return title, vols, dirs, fields, helpfun + + +def OptsMenu(title, vols=None, dirs=None, fields=None, helpfun=None): + # create GUI + main = QtWidgets.QMainWindow() + + widget = QtWidgets.QWidget() + widget.setWindowTitle('%s' % title) + + widget.move(QtWidgets.QApplication.desktop().screen().rect().center() - widget.rect().center()) + + layout = QtWidgets.QFormLayout() + + layout.setFieldGrowthPolicy(QtWidgets.QFormLayout.AllNonFixedFieldsGrow) + + linedits = {} + buttons = {} + labels = {} + + if dirs: + + for d, indir in enumerate(dirs): + # Create buttons for vols + labels["%s" % indir] = QtWidgets.QLabel('No Dir selected') + buttons["%s" % indir] = QtWidgets.QPushButton('Select %s' % indir) + + # Layout for widgets + layout.addRow(labels["%s" % indir], buttons["%s" % indir]) + + buttons["%s" % indir].clicked.connect(lambda ignore, xd=indir: get_dname(main, labels, xd)) + + if vols: + + for v, vol in enumerate(vols): + # Create buttons for vols + labels["%s" % vol] = QtWidgets.QLabel('No file selected') + buttons["%s" % vol] = QtWidgets.QPushButton('Select %s' % vol) + + # Layout for widgets + layout.addRow(labels["%s" % vol], buttons["%s" % vol]) + + buttons["%s" % vol].clicked.connect(lambda ignore, xv=vol: get_fname(main, labels, xv)) + + if fields: + + for f, field in enumerate(fields): + # Create inputs (line edts) + linedits["%s" % field] = QtWidgets.QLineEdit() + linedits["%s" % field].setAlignment(QtCore.Qt.AlignRight) + + # Layout for widgets + layout.addRow("%s" % field, linedits["%s" % field]) + + # Create push button + helpbutton = QtWidgets.QPushButton('Help') + submit = QtWidgets.QPushButton('Run') + + layout.addRow(helpbutton, submit) + + widget.setLayout(layout) + + helpbutton.clicked.connect(lambda: print_help(main, helpfun)) + + fn_name = title.replace(' ', '_').lower() + submit.clicked.connect(lambda: parse_inputs(fn_name, labels, linedits, vols, dirs, fields)) + + return widget, linedits, labels + + +def get_fname(main, labels, volume): + vfile = QtWidgets.QFileDialog.getOpenFileName(main, 'Select %s' % volume) + if vfile: + vfilestr = "%s : %s" % (volume, str(vfile[0]).lstrip()) + labels["%s" % volume].setText(vfilestr) + print('%s path: %s' % (volume, vfile[0])) + else: + labels["%s" % volume].setText('No file selected') + + return vfile[0] + + +def get_dname(main, labels, indir): + dfile = QtWidgets.QFileDialog.getExistingDirectory(main, "Select %s" % indir, ".") + if dfile: + dfilestr = "%s : %s" % (indir, str(dfile).lstrip()) + labels["%s" % indir].setText(dfilestr) + print('%s path: %s' % (indir, dfile)) + else: + labels["%s" % indir].setText('No Dir selected') + + return dfile + + +def parse_inputs(fn_name, labels, linedits, vols, dirs, fields): + cmd = "hippmapper %s" % fn_name + + if vols: + for v, vol in enumerate(vols): + try: + in_vol = str(labels["%s" % vol].text()).split(":")[1].lstrip() + vols_cmd = " --%s %s" % (vol, in_vol) + cmd = cmd + "%s" % vols_cmd + except IndexError: + continue + if dirs: + for d, indir in enumerate(dirs): + try: + dfile = str(labels["%s" % indir].text()).split(":")[1].lstrip() + dirs_cmd = " --%s %s" % (indir, dfile) + cmd = cmd + "%s" % dirs_cmd + except IndexError: + continue + if fields: + for f, field in enumerate(fields): + in_field = str(linedits["%s" % field].text()).lstrip() + if in_field != "": + fields_cmd = " --%s %s" % (field, in_field) + cmd = cmd + "%s" % fields_cmd + + print("\n running HippMapp3r with the following command: \n\n %s \n" % cmd) + + subprocess.Popen("%s" % cmd, shell=True, + stdin=None, stdout=None, stderr=None, close_fds=True) + + # QtCore.QCoreApplication.instance().quit + sys.exit() + + +def print_help(main, helpfun): + main.setWindowTitle('Help function') + scrollarea = QtWidgets.QScrollArea() + + helplbl = QtWidgets.QLabel() + helplbl.setText(helpfun) + font = QtGui.QFont('Mono', 9, QtGui.QFont.Light) + helplbl.setFont(font) + helplbl.setWordWrap(True) + + scrollarea.setWidget(helplbl) + #scrollarea.setWidgetResizable(False) + scrollarea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) + scrollarea.setAttribute(QtCore.Qt.WA_DeleteOnClose) + main.setCentralWidget(scrollarea) + + main.move(QtWidgets.QApplication.desktop().screen().rect().center() - main.rect().center()) + main.show() + + QtWidgets.QApplication.processEvents() + + +def main(): + [title, vols, dirs, fields, helpfun] = parseargs() + helpfunhtml = helpfun.replace('\n','
') + + # Create an PyQT5 application object. + app = QtWidgets.QApplication(sys.argv) + gui_name = title.replace('_', ' ').upper() + menu, linedits, labels = OptsMenu(title=gui_name, vols=vols, dirs=dirs, fields=fields, helpfun=helpfunhtml) + menu.show() + app.exec_() + app.processEvents() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..cde4f03 --- /dev/null +++ b/setup.py @@ -0,0 +1,51 @@ +from setuptools import setup, find_packages +from hippmapper import __version__ + +setup( + name='HippMapp3r', + version=__version__, + description='A CNN-based segmentation technique using MRI images from BrainLab', + author=['Maged Goubran', 'Hassan Akhavein', 'Edward Ntiri'], + author_email='maged.goubran@sri.utoronto.ca', + packages=find_packages(), + include_package_data=True, + zip_safe=False, + license='GNU GENERAL PUBLIC LICENSE v3', + url='https://github.com/mgoubran/HippMapp3r', # change later + download_url='https://github.com/mgoubran/HippMapp3r', + long_description=open('README.md').read(), + classifiers=[ + 'Development Status :: 2 - Pre-Alpha', + 'Environment :: Console', + 'Environment :: X11 Applications :: Qt', + 'Intended Audience :: Science/Research', + 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', + 'Operating System :: POSIX :: Linux', + 'Operating System :: MacOS', + 'Operating System :: Unix', + 'Programming Language :: Python', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Unix Shell', + 'Topic :: Scientific/Engineering', + 'Topic :: Scientific/Engineering :: Medical Science Apps.', + 'Topic :: Scientific/Engineering :: Bio-Informatics', + 'Topic :: Scientific/Engineering :: Image Recognition', + ], + dependency_links=[ + 'git+https://github.com/keras-team/keras-contrib.git' + ], + install_requires=[ + 'nibabel', 'nipype', 'argparse', 'argcomplete', 'joblib', 'keras', 'nilearn', 'scikit-learn', + 'keras-contrib', 'pandas', 'numpy', 'plotly', 'PyQt5' + ], + extras_require={ + "hippmapper": ["tensorflow>=1.4.0"], + "hippmapper_gpu": ["tensorflow-gpu>=1.4.0"], + }, + entry_points={'console_scripts': ['hippmapper=hippmapper.cli:main']}, + keywords=[ + 'neuroscience dementia lesion stroke white-matter-hyperintensity brain-atlas mri neuroimaging', + 'medical-imaging biomedical image-processing image-registration image-segmentation', + ], +) \ No newline at end of file