[
  {
    "path": ".gitattributes",
    "content": "# Auto detect text files and perform LF normalization\n* text=auto\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# Non-local U-Nets for Biomedical Image Segmentation\n\nThis repository provides the experimental code for our paper \"Non-local U-Nets for Biomedical Image Segmentation\" accepted by AAAI-20.\n\nThis repository includes an (re-)implementation, using updated Tensorflow APIs, of [3D Unet](https://github.com/zhengyang-wang/Unet_3D) for isointense infant brain image segmentation. Besides, we implement our proposed global aggregation blocks, which modify self-attention layers for 3D Unet. The user can optionally insert the blocks to the standard 3D Unet.\n\nFor users who wants to use the standard 3D Unet, you need to modify network.py by removing line 62-67 and 72-79. Do not use \"_att_decoding_block_layer\" in \"_build_network\". Should you have any question, open an issue and I will respond.\n\nCreated by [Zhengyang Wang](http://people.tamu.edu/~zhengyang.wang/) and [Shuiwang Ji](http://people.tamu.edu/~sji/index.html) at Texas A&M University.\n\n## Update\n**11/10/2019**:\n\nOur paper \"Non-local U-Nets for Biomedical Image Segmentation\" has been accepted by AAAI-20!\n\n**10/01/2018**:\n1. The code now works when we have subjects of different spatial sizes.\n\n2. During training, validation and prediction, you only need to change the configures in configure.py. In the old version, you have to change configures correspondingly in several files like main.py, utils/input_fn.py, etc.\n\n## Publication\n\nThe paper is available at [https://www.aaai.org/Papers/AAAI/2020GB/AAAI-WangZ.5933.pdf](https://www.aaai.org/Papers/AAAI/2020GB/AAAI-WangZ.5933.pdf).\n\nIf using this code , please cite our paper.\n```\n@inproceedings{wang2020non,\n  title={Non-local U-Nets for Biomedical Image Segmentation},\n  author={Wang, Zhengyang and Zou, Na and Shen, Dinggang and Ji, Shuiwang},\n  booktitle={Proceedings of the AAAI Conference on Artificial Intelligence},\n  year={2020}\n}\n```\n\n## Dataset\n\nThe dataset is from UNC and used as the training dataset in [iSeg-2017](http://iseg2017.web.unc.edu/). Basically, it is composed of multi-modality isointense infant brain MR images (3D) of 10 subjects. Each subject has two 3D images (modalities), T1WI and T2WI, with a manually created 3D segmentation label.\n\nIt is an important step in brain development study to perform automatic segmentation of infant brain magnetic resonance (MR) images into white matter (WM), grey matter (GM) and cerebrospinal fluid (CSF) regions. This task is especially challenging in the isointense stage (approximately 6-8 months of age) when WM and GM exhibit similar levels of intensities in MR images.\n\n## Results\n\nHere provides a glance at the effect of our proposed model. The baseline is [3-D Fully Convolutional Networks for Multimodal Isointense Infant Brain Image Segmentation](https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8287819).\n\n**Visualization of the segmentation results on the 10th subject by our proposed model and the baseline model**:\n![model](./results/sample_results.png)\n\n**Comparison of training processes between our proposed model and the baseline model**:\n![model](./results/training_curve.png)\n\n## System requirement\n\n#### Programming language\n\nPython 3.5+\n\n#### Python Packages\n\ntensorflow-gpu 1.7 - 1.10, numpy, scipy\n\n## Configure the network\n\nAll network hyperparameters are configured in main.py.\n\n#### Training\n\nraw_data_dir:the directory where the raw data is stored\n\ndata_dir: the directory where the input data is stored\n\nnum_training_subs: the number of subjects used for training\n\ntrain_epochs: the number of epochs to use for training\n\nepochs_per_eval: the number of training epochs to run between evaluations\n\nbatch_size: the number of examples processed in each training batch\n\nlearning_rate: learning rate\n\nweight_decay: weight decay rate\n\nnum_parallel_calls: The number of records that are processed in parallel during input processing. This can be optimized per data set but for generally homogeneous data sets, should be approximately the number of available CPU cores.\n\nmodel_dir: the directory where the model will be stored\n\n#### Validation\n\npatch_size: spatial size of patches\n\noverlap_step: overlap step size when performing testing\n\nvalidation_id: 1-10, which subject is used for validation\n\ncheckpoint_num: which checkpoint is used for validation\n\nsave_dir: the directory where the prediction is stored\n\nraw_data_dir: the directory where the raw data is stored\n\n#### Network architecture\n\nnetwork_depth: the network depth\n\nnum_classes: the number of classes\n\nnum_filters: number of filters for initial_conv\n\n## Training and Evaluation\n\n#### Preprocess data\n\nBefore training, we preprocess data into tfrecords format, which is optimized for Tensorflow. A good example of how to preprocess data and use tfrecords files as inputs can be found in generate_tfrecord.py and input_fn.py.\n\n#### Start training\n\nAfter configure configure.py, we can start to train by running\n```\npython main.py\n```\n\n#### Training process visualization\n\nWe employ tensorboard to visualize the training process.\n```\ntensorboard --logdir=model_dir/\n```\n\n#### Testing and prediction\n\nIf you want to do testing, first make predictions by running\n```\npython main.py --option='predict'\n```\n\nThen, if you have access to labels, setup evaluation.py and run\n```\npython evaluation.py\n```\n\nYou may also visualize the results. setup visualize.py and run\n```\npython visualize.py\n```\n"
  },
  {
    "path": "configure.py",
    "content": "import tensorflow as tf\n\n\n\"\"\"This script defines hyperparameters.\n\"\"\"\n\ndef configure():\n\tflags = tf.app.flags\n\n\t# training\n\tflags.DEFINE_string('raw_data_dir', '/data/zhengyang/InfantBrain/RawData',\n\t\t\t'the directory where the raw data is stored')\n\tflags.DEFINE_string('data_dir', '/data/zhengyang/InfantBrain/tfrecords_full',\n\t\t\t'the directory where the input data is stored')\n\tflags.DEFINE_integer('num_training_subs', 9,\n\t\t\t'the number of subjects used for training')\n\tflags.DEFINE_integer('train_epochs', 100000,\n\t\t\t'the number of epochs to use for training')\n\tflags.DEFINE_integer('epochs_per_eval', 5000,\n\t\t\t'the number of training epochs to run between evaluations')\n\tflags.DEFINE_integer('batch_size', 5,\n\t\t\t'the number of examples processed in each training batch')\n\tflags.DEFINE_float('learning_rate', 1e-3, 'learning rate')\n\tflags.DEFINE_float('weight_decay', 2e-6, 'weight decay rate')\n\tflags.DEFINE_integer('num_parallel_calls', 5,\n\t\t\t'The number of records that are processed in parallel \\\n\t\t\tduring input processing. This can be optimized per data set but \\\n\t\t\tfor generally homogeneous data sets, should be approximately the \\\n\t\t\tnumber of available CPU cores.')\n\tflags.DEFINE_string('model_dir', './model-10',\n\t\t\t'the directory where the model will be stored')\n\n\t# validation / prediction\n\tflags.DEFINE_integer('patch_size', 32, 'spatial size of patches')\n\tflags.DEFINE_integer('overlap_step', 8,\n\t\t\t'overlap step size when performing validation/prediction')\n\tflags.DEFINE_integer('validation_id', 10,\n\t\t\t'1-10 or -1, which subject is used for validation')\n\tflags.DEFINE_integer('prediction_id', 11,\n\t\t\t'1-23, which subject is used for prediction')\n\tflags.DEFINE_integer('checkpoint_num', 153000,\n\t\t\t'which checkpoint is used for validation/prediction')\n\tflags.DEFINE_string('save_dir', './results',\n\t\t\t'the directory where the prediction is stored')\n\n\t# network\n\tflags.DEFINE_integer('network_depth', 3, 'the network depth')\n\tflags.DEFINE_integer('num_classes', 4, 'the number of classes')\n\tflags.DEFINE_integer('num_filters', 32,\n\t\t\t 'number of filters for initial_conv')\n\t\n\tflags.FLAGS.__dict__['__parsed'] = False\n\treturn flags.FLAGS\n\n\nconf = configure()"
  },
  {
    "path": "evaluation.py",
    "content": "import os\nimport numpy as np\nfrom utils import dice_ratio, ModHausdorffDist\nfrom generate_tfrecord import load_subject\n\n\n\"\"\"Perform evaluation in terms of dice ratio and 3D MHD.\n\"\"\"\n\n\n################################################################################\n# Arguments\n################################################################################\nRAW_DATA_DIR = '/data/zhengyang/InfantBrain/RawData'\nLABEL_DIR = '/data/zhengyang/InfantBrain/tfrecords_full'\nPRED_DIR = './results'\nPRED_ID = 10 # 1-10\nPATCH_SIZE = 32\nCHECKPOINT_NUM = 153000\nOVERLAP_STEPSIZE = 8\n\n\n################################################################################\n# Functions\n################################################################################\ndef one_hot(label):\n\t'''Convert label (d,h,w) to one-hot label (d,h,w,num_class).\n\t'''\n\n\tnum_class = np.max(label) + 1\n\treturn np.eye(num_class)[label]\n\n\ndef MHD_3D(pred, label):\n\t'''Compute 3D MHD for a single class.\n\t\n\tArgs:\n\t\tpred: An array of size [Depth, Height, Width], with only 0 or 1 values\n\t\tlabel: An array of size [Depth, Height, Width], with only 0 or 1 values\n\n\tReturns:\n\t\t3D MHD for a single class\n\t'''\n\n\tD, H, W = label.shape\n\n\tpred_d = np.array([pred[:, i, j] for i in range(H) for j in range(W)])\n\tpred_h = np.array([pred[i, :, j] for i in range(D) for j in range(W)])\n\tpred_w = np.array([pred[i, j, :] for i in range(D) for j in range(H)])\n\n\tlabel_d = np.array([label[:, i, j] for i in range(H) for j in range(W)])\n\tlabel_h = np.array([label[i, :, j] for i in range(D) for j in range(W)])\n\tlabel_w = np.array([label[i, j, :] for i in range(D) for j in range(H)])\n\n\tMHD_d = ModHausdorffDist(pred_d, label_d)[0]\n\tMHD_h = ModHausdorffDist(pred_h, label_h)[0]\n\tMHD_w = ModHausdorffDist(pred_w, label_w)[0]\n\n\tret = np.mean([MHD_d, MHD_h, MHD_w])\n\n\tprint('--->MHD d:', MHD_d)\n\tprint('--->MHD h:', MHD_h)\n\tprint('--->MHD w:', MHD_w)\n\t# print('--->avg:', ret)\n\n\treturn ret\n\n\ndef Evaluate(label_dir, pred_dir, pred_id, patch_size, checkpoint_num,\n\t\toverlap_step):\n\tprint('Perform evaluation for subject-%d:' % pred_id)\n\n\tprint('Loading label...')\n\tlabel_file = os.path.join(label_dir, 'subject-%d-label.npy' % pred_id)\n\tassert os.path.isfile(label_file), \\\n\t\t('Run generate_tfrecord.py to generate the label file.')\n\tlabel = np.load(label_file)\n\tprint('Check label: ', label.shape, np.max(label))\n\n\tprint('Loading predition...')\n\tpred_file = os.path.join(pred_dir, \n\t\t\t\t'preds-%d-sub-%d-overlap-%d-patch-%d.npy' % \\\n\t\t\t\t(checkpoint_num, pred_id, overlap_step, patch_size))\n\tassert os.path.isfile(pred_file), \\\n\t\t('Run main.py --option=predict to generate the prediction results.')\n\tpred = np.load(pred_file)\n\tprint('Check pred: ', pred.shape, np.max(pred))\n\n\tprint('Extract pred and label for each class...')\n\tlabel_one_hot = one_hot(label)\n\tpred_one_hot = one_hot(pred)\n\tprint('Check shape: ', label_one_hot.shape, pred_one_hot.shape)\n\n\t# Separate each class. 0 corresponds to the background class (ignore).\n\tcsf_pred = pred_one_hot[:,:,:,1]\n\tcsf_label = label_one_hot[:,:,:,1]\n\n\tgm_pred = pred_one_hot[:,:,:,2]\n\tgm_label = label_one_hot[:,:,:,2]\n\n\twm_pred = pred_one_hot[:,:,:,3]\n\twm_label = label_one_hot[:,:,:,3]\n\n\t# evaluate dice ratio\n\tprint('Evaluate dice ratio...')\n\tcsf_dr = dice_ratio(csf_pred, csf_label)\n\tprint('--->CSF Dice Ratio:', csf_dr)\n\tgm_dr = dice_ratio(gm_pred, gm_label)\n\tprint('--->GM Dice Ratio:', gm_dr)\n\twm_dr = dice_ratio(wm_pred, wm_label)\n\tprint('--->WM Dice Ratio:', wm_dr)\n\tprint('--->avg:', np.mean([csf_dr, gm_dr, wm_dr]))\n\n\t# # evaluate MHD\n\t# print('Evaluate 3D MHD (---SLOW---)...')\n\t# csf_mhd = MHD_3D(csf_pred, csf_label)\n\t# print('--->CSF MHD:', csf_mhd)\n\t# gm_mhd = MHD_3D(gm_pred, gm_label)\n\t# print('--->GM MHD:', gm_mhd)\n\t# wm_mhd = MHD_3D(wm_pred, wm_label)\n\t# print('--->WM MHD:', wm_mhd)\n\t# print('--->avg:', np.mean([csf_mhd, gm_mhd, wm_mhd]))\n\n\tprint('Done.')\n\nif __name__ == '__main__':\n\tEvaluate(\n\t\tlabel_dir=LABEL_DIR,\n\t\tpred_dir=PRED_DIR,\n\t\tpred_id=PRED_ID,\n\t\tpatch_size=PATCH_SIZE,\n\t\tcheckpoint_num=CHECKPOINT_NUM,\n\t\toverlap_step=OVERLAP_STEPSIZE)"
  },
  {
    "path": "generate_tfrecord.py",
    "content": "import os\nimport sys\nimport tensorflow as tf\nimport nibabel as nib\nimport numpy as np\nfrom configure import conf\n\n\n\"\"\"Generate TFRecord Files.\n\"\"\"\n\n################################################################################\n# Basic Functions\n################################################################################\ndef _float_feature(value):\n\treturn tf.train.Feature(float_list=tf.train.FloatList(value=value))\n\n\ndef _bytes_feature(value):\n\treturn tf.train.Feature(bytes_list=tf.train.BytesList(value=value))\n\n\ndef _int64_feature(value):\n\treturn tf.train.Feature(int64_list=tf.train.Int64List(value=value))\n\n\ndef cut_edge(data):\n\t'''Cuts zero edge for a 3D image.\n\n\tArgs:\n\t\tdata: A 3D image, [Depth, Height, Width, 1].\n\n\tReturns:\n\t\toriginal_shape: [Depth, Height, Width]\n\t\tcut_size: A list of six integers [Depth_s, Depth_e, Height_s, Height_e, Width_s, Width_e]\n\t'''\n\n\tD, H, W, _ = data.shape\n\tD_s, D_e = 0, D-1\n\tH_s, H_e = 0, H-1\n\tW_s, W_e = 0, W-1\n\n\twhile D_s < D:\n\t\tif data[D_s].sum() != 0:\n\t\t\tbreak\n\t\tD_s += 1\n\twhile D_e > D_s:\n\t\tif data[D_e].sum() != 0:\n\t\t\tbreak\n\t\tD_e -= 1\n\twhile H_s < H:\n\t\tif data[:,H_s].sum() != 0:\n\t\t\tbreak\n\t\tH_s += 1\n\twhile H_e > H_s:\n\t\tif data[:,H_e].sum() != 0:\n\t\t\tbreak\n\t\tH_e -= 1\n\twhile W_s < W:\n\t\tif data[:,:,W_s].sum() != 0:\n\t\t\tbreak\n\t\tW_s += 1\n\twhile W_e > W_s:\n\t\tif data[:,:,W_e].sum() != 0:\n\t\t\tbreak\n\t\tW_e -= 1\n\t\n\toriginal_shape = [D, H, W]\n\tcut_size = [int(D_s), int(D_e+1), int(H_s), int(H_e+1), int(W_s), int(W_e+1)]\n\treturn (original_shape, cut_size)\n\ndef convert_labels(labels):\n\t'''Converts 0:background / 10:CSF / 150:GM / 250:WM to 0/1/2/3. SLOW!\n\t'''\n\n\tD, H, W, C = labels.shape\n\n\tfor d in range(D):\n\t\tfor h in range(H):\n\t\t\tfor w in range(W):\n\t\t\t\tif labels[d,h,w,0] == 10:\n\t\t\t\t\tlabels[d,h,w,0] = 1\n\t\t\t\telif labels[d,h,w,0] == 150:\n\t\t\t\t\tlabels[d,h,w,0] = 2\n\t\t\t\telif labels[d,h,w,0] == 250:\n\t\t\t\t\tlabels[d,h,w,0] = 3\n\n\ndef load_subject(raw_data_dir, subject_id):\n\t'''Load subject data.\n\n\tArgs:\n\t\tsubject_id: [1-23]\n\n\tReturns:\n\t\t[T1, T2, label]\n\t'''\n\n\tsubject_name = 'subject-%d-' % subject_id\n\n\tf1 = os.path.join(raw_data_dir, subject_name+'T1.hdr')\n\tf2 = os.path.join(raw_data_dir, subject_name+'T2.hdr')\n\n\timg_T1 = nib.load(f1)\n\timg_T2 = nib.load(f2)\n\n\tinputs_T1 = img_T1.get_data()\n\tinputs_T2 = img_T2.get_data()\n\t\n\tif subject_id < 11:\n\t\tfl = os.path.join(raw_data_dir, subject_name+'label.hdr')\n\t\timg_label = nib.load(fl)\n\t\tinputs_label = img_label.get_data()\n\telse:\n\t\tinputs_label = None\n\n\treturn [inputs_T1, inputs_T2, inputs_label]\n\t\t\n\ndef prepare_validation(cutted_image, patch_size, overlap_stepsize):\n\t\"\"\"Determine patches for validation.\"\"\"\n\n\tpatch_ids = []\n\n\tD, H, W, _ = cutted_image.shape\n\n\tdrange = list(range(0, D-patch_size+1, overlap_stepsize))\n\thrange = list(range(0, H-patch_size+1, overlap_stepsize))\n\twrange = list(range(0, W-patch_size+1, overlap_stepsize))\n\n\tif (D-patch_size) % overlap_stepsize != 0:\n\t\tdrange.append(D-patch_size)\n\tif (H-patch_size) % overlap_stepsize != 0:\n\t\thrange.append(H-patch_size)\n\tif (W-patch_size) % overlap_stepsize != 0:\n\t\twrange.append(W-patch_size)\n\n\tfor d in drange:\n\t\tfor h in hrange:\n\t\t\tfor w in wrange:\n\t\t\t\tpatch_ids.append((d, h, w))\n\n\treturn patch_ids\n\n################################################################################\n# TFRecord Generation Functions\n################################################################################\n\ndef write_training_examples(T1, T2, label, original_shape, cut_size, output_file):\n\t\"\"\"Create a training tfrecord file.\n\t\n\tArgs:\n\t\tT1: T1 image. [Depth, Height, Width, 1].\n\t\tT2: T2 image. [Depth, Height, Width, 1].\n\t\tlabel: Label. [Depth, Height, Width, 1].\n\t\toriginal_shape: A list of three integers [D, H, W].\n\t\tcut_size: A list of six integers [Depth_s, Depth_e, Height_s, Height_e, Width_s, Width_e].\n\t\toutput_file: The file name for the tfrecord file.\n\t\"\"\"\n\n\twriter = tf.python_io.TFRecordWriter(output_file)\n\n\texample = tf.train.Example(features=tf.train.Features(\n\t\tfeature={\n\t\t\t'T1': _bytes_feature([T1[:,:,:,0].tostring()]), #int16\n\t\t\t'T2': _bytes_feature([T2[:,:,:,0].tostring()]), #int16\n\t\t\t'label': _bytes_feature([label[:,:,:,0].tostring()]), #uint8\n\t\t\t'original_shape': _int64_feature(original_shape),\n\t\t\t'cut_size': _int64_feature(cut_size)\n\t\t}\n\t))\n\n\twriter.write(example.SerializeToString())\n\n\twriter.close()\n\n\ndef write_validation_examples(T1, T2, label, patch_size, cut_size, overlap_stepsize, output_file):\n\t\"\"\"Create a validation tfrecord file.\n\t\n\tArgs:\n\t\tT1: T1 image. [Depth, Height, Width, 1].\n\t\tT2: T2 image. [Depth, Height, Width, 1].\n\t\tlabel: Label. [Depth, Height, Width, 1].\n\t\tpatch_size: An integer.\n\t\tcut_size: A list of six integers [Depth_s, Depth_e, Height_s, Height_e, Width_s, Width_e].\n\t\toverlap_stepsize: An integer.\n\t\toutput_file: The file name for the tfrecord file.\n\t\"\"\"\n\n\tT1 = T1[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :]\n\tT2 = T2[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :]\n\tlabel = label[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :]\n\n\tpatch_ids = prepare_validation(T1, patch_size, overlap_stepsize)\n\tprint ('Number of patches:', len(patch_ids))\n\n\twriter = tf.python_io.TFRecordWriter(output_file)\n\n\tfor i in range(len(patch_ids)):\n\n\t\t(d, h, w) = patch_ids[i]\n\n\t\t_T1 = T1[d:d+patch_size, h:h+patch_size, w:w+patch_size, :]\n\t\t_T2 = T2[d:d+patch_size, h:h+patch_size, w:w+patch_size, :]\n\t\t_label = label[d:d+patch_size, h:h+patch_size, w:w+patch_size, :]\n\n\t\texample = tf.train.Example(features=tf.train.Features(\n\t\t\tfeature={\n\t\t\t\t'T1': _bytes_feature([_T1[:,:,:,0].tostring()]), #int16\n\t\t\t\t'T2': _bytes_feature([_T2[:,:,:,0].tostring()]), #int16\n\t\t\t\t'label': _bytes_feature([_label[:,:,:,0].tostring()]), #uint8\n\t\t\t}\n\t\t))\n\n\t\twriter.write(example.SerializeToString())\n\n\twriter.close()\n\n\ndef write_prediction_examples(T1, T2, patch_size, cut_size, overlap_stepsize, output_file):\n\t\"\"\"Create a testing tfrecord file.\n\t\n\tArgs:\n\t\tT1: T1 image. [Depth, Height, Width, 1].\n\t\tT2: T2 image. [Depth, Height, Width, 1].\n\t\tpatch_size: An integer.\n\t\tcut_size: A list of six integers [Depth_s, Depth_e, Height_s, Height_e, Width_s, Width_e].\n\t\toverlap_stepsize: An integer.\n\t\toutput_file: The file name for the tfrecord file.\n\t\"\"\"\n\n\tT1 = T1[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :]\n\tT2 = T2[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :]\n\n\tpatch_ids = prepare_validation(T1, patch_size, overlap_stepsize)\n\tprint ('Number of patches:', len(patch_ids))\n\n\twriter = tf.python_io.TFRecordWriter(output_file)\n\n\tfor i in range(len(patch_ids)):\n\n\t\t(d, h, w) = patch_ids[i]\n\n\t\t_T1 = T1[d:d+patch_size, h:h+patch_size, w:w+patch_size, :]\n\t\t_T2 = T2[d:d+patch_size, h:h+patch_size, w:w+patch_size, :]\n\n\t\texample = tf.train.Example(features=tf.train.Features(\n\t\t\tfeature={\n\t\t\t\t'T1': _bytes_feature([_T1[:,:,:,0].tostring()]), #int16\n\t\t\t\t'T2': _bytes_feature([_T2[:,:,:,0].tostring()]), #int16\n\t\t\t}\n\t\t))\n\n\t\twriter.write(example.SerializeToString())\n\n\twriter.close()\n\n\ndef generate_files(raw_data_dir, output_path, valid_id, pred_id, patch_size, overlap_stepsize):\n\t\"\"\"Create tfrecord files.\"\"\"\n\tif valid_id not in range(1, 11) and valid_id != -1:\n\t\tprint('The valid_id should be in [1,10] or -1.')\n\t\tsys.exit(-1)\n\n\tif not os.path.exists(output_path):\n\t\tos.makedirs(output_path)\n\n\tfor i in range(1, 24):\n\t\tprint('---Process subject %d:---' % i)\n\n\t\tsubject_name = 'subject-%d' % i\n\t\ttrain_filename = os.path.join(output_path, subject_name+'.tfrecords')\n\n\t\tpred_subject_name = 'subject-%d-pred-%d-patch-%d' % (pred_id, overlap_stepsize, patch_size)\n\t\tpred_filename = os.path.join(output_path, pred_subject_name+'.tfrecords')\n\n\t\tvalid_subject_name = 'subject-%d-valid-%d-patch-%d' % (valid_id, overlap_stepsize, patch_size)\n\t\tvalid_filename = os.path.join(output_path, valid_subject_name+'.tfrecords')\n\n\t\t# save converted label for fast evaluation\n\t\tconverted_label_filename = 'subject-%d-label.npy' % valid_id\n\t\tconverted_label_filename = os.path.join(output_path, converted_label_filename)\n\t\t\n\t\tif (i < 11 and not os.path.isfile(train_filename)) or \\\n\t\t\t(i == pred_id and not os.path.isfile(pred_filename)) or \\\n\t\t\t(i == valid_id and (not os.path.isfile(valid_filename) or \\\n\t\t\t\tnot os.path.isfile(converted_label_filename))):\n\t\t\tprint('Loading data...')\n\t\t\t[_T1, _T2, _label] = load_subject(raw_data_dir, i)\n\n\t\t\tif _label is not None:\n\t\t\t\tprint('Converting label...')\n\t\t\t\tconvert_labels(_label)\n\t\t\t\tprint('Check label: ', np.max(_label))\n\n\t\t\t(original_shape, cut_size) = cut_edge(_T1)\n\t\t\tprint('Check original_shape: ', original_shape)\n\t\t\tprint('Check cut_size: ', cut_size)\n\n\t\tif not os.path.isfile(train_filename) and i < 11:\n\t\t\tprint('Create the training file:')\n\t\t\twrite_training_examples(_T1, _T2, _label, original_shape, cut_size, train_filename)\n\n\t\tif i == valid_id:\n\t\t\tif not os.path.isfile(valid_filename):\n\t\t\t\tprint('Create the validation file:')\n\t\t\t\twrite_validation_examples(_T1, _T2, _label, patch_size, cut_size, overlap_stepsize, valid_filename)\n\n\t\t\tif not os.path.isfile(converted_label_filename):\n\t\t\t\tprint('Create the converted label file:')\n\t\t\t\tnp.save(converted_label_filename, _label[:,:,:,0])\n\n\t\tif i == pred_id:\n\t\t\tif not os.path.isfile(pred_filename):\n\t\t\t\tprint('Create the prediction file:')\n\t\t\t\twrite_prediction_examples(_T1, _T2, patch_size, cut_size, overlap_stepsize, pred_filename)\n\n\t\tprint('---Done.---')\n\n\nif __name__ == '__main__':\n\tgenerate_files(\n\t\tconf.raw_data_dir,\n\t\tconf.data_dir,\n\t\tconf.validation_id,\n\t\tconf.prediction_id,\n\t\tconf.patch_size,\n\t\tconf.overlap_step)\n"
  },
  {
    "path": "input_fn.py",
    "content": "import tensorflow as tf\nimport os\nfrom configure import conf\n\n\"\"\"This script defines the input interface.\n\"\"\"\n\n\n################################################################################\n# Functions\n################################################################################\ndef get_filenames(data_dir, mode, valid_id, pred_id, overlap_step, patch_size):\n\t\"\"\"Returns a list of filenames.\"\"\"\n\n\tif mode == 'train':\n\t\ttrain_files = [\n\t\t\tos.path.join(data_dir, 'subject-%d.tfrecords' % i)\n\t\t\tfor i in range(1, 11)\n\t\t\tif i != valid_id\n\t\t]\n\t\tfor f in train_files:\n\t\t\tassert os.path.isfile(f), \\\n\t\t\t\t('Run generate_tfrecord.py to generate training files.')\n\t\treturn train_files\n\telif mode == 'valid':\n\t\tvalid_file = os.path.join(data_dir, \n\t\t\t'subject-%d-valid-%d-patch-%d.tfrecords' % (valid_id, overlap_step, patch_size))\n\t\tassert os.path.isfile(valid_file), \\\n\t\t\t('Run generate_tfrecord.py to generate the validation file.')\n\t\treturn [valid_file]\n\telif mode == 'pred':\n\t\tpred_file = os.path.join(data_dir,\n\t\t\t'subject-%d-pred-%d-patch-%d.tfrecords' % (pred_id, overlap_step, patch_size))\n\t\tassert os.path.isfile(pred_file), \\\n\t\t\t('Run generate_tfrecord.py to generate the prediction file.')\n\t\treturn [pred_file]\n\n\ndef decode_train(serialized_example):\n\t\"\"\"Parses training data from the given `serialized_example`.\"\"\"\n\n\tfeatures = tf.parse_single_example(\n\t\t\t\t\tserialized_example,\n\t\t\t\t\tfeatures={\n\t\t\t\t\t\t'T1':tf.FixedLenFeature([],tf.string),\n\t\t\t\t\t\t'T2':tf.FixedLenFeature([], tf.string),\n\t\t\t\t\t\t'label':tf.FixedLenFeature([],tf.string),\n\t\t\t\t\t\t'original_shape':tf.FixedLenFeature(3, tf.int64),\n\t\t\t\t\t\t'cut_size':tf.FixedLenFeature(6, tf.int64)\n\t\t\t\t\t})\n\n\timg_shape = features['original_shape']\n\tcut_size = features['cut_size']\n\n\t# Convert from a scalar string tensor\n\timage_T1 = tf.decode_raw(features['T1'], tf.int16)\n\timage_T1 = tf.reshape(image_T1, img_shape)\n\timage_T2 = tf.decode_raw(features['T2'], tf.int16)\n\timage_T2 = tf.reshape(image_T2, img_shape)\n\tlabel = tf.decode_raw(features['label'], tf.uint8)\n\tlabel = tf.reshape(label, img_shape)\n\n\t# Convert dtype.\n\timage_T1 = tf.cast(image_T1, tf.float32)\n\timage_T2 = tf.cast(image_T2, tf.float32)\n\tlabel = tf.cast(label, tf.float32)\n\n\treturn image_T1, image_T2, label, cut_size\n\n\ndef decode_valid(serialized_example):\n\t\"\"\"Parses validation data from the given `serialized_example`.\"\"\"\n\n\tfeatures = tf.parse_single_example(\n\t\t\t\t\tserialized_example,\n\t\t\t\t\tfeatures={\n\t\t\t\t\t\t'T1':tf.FixedLenFeature([],tf.string),\n\t\t\t\t\t\t'T2':tf.FixedLenFeature([], tf.string),\n\t\t\t\t\t\t'label':tf.FixedLenFeature([],tf.string)\n\t\t\t\t\t})\n\n\tpatch_shape = [conf.patch_size, conf.patch_size, conf.patch_size]\n\n\t# Convert from a scalar string tensor\n\timage_T1 = tf.decode_raw(features['T1'], tf.int16)\n\timage_T1 = tf.reshape(image_T1, patch_shape)\n\timage_T2 = tf.decode_raw(features['T2'], tf.int16)\n\timage_T2 = tf.reshape(image_T2, patch_shape)\n\tlabel = tf.decode_raw(features['label'], tf.uint8)\n\tlabel = tf.reshape(label, patch_shape)\n\n\t# Convert dtype.\n\timage_T1 = tf.cast(image_T1, tf.float32)\n\timage_T2 = tf.cast(image_T2, tf.float32)\n\n\treturn image_T1, image_T2, label\n\n\ndef decode_pred(serialized_example):\n\t\"\"\"Parses prediction data from the given `serialized_example`.\"\"\"\n\n\tfeatures = tf.parse_single_example(\n\t\t\t\t\tserialized_example,\n\t\t\t\t\tfeatures={\n\t\t\t\t\t\t'T1':tf.FixedLenFeature([],tf.string),\n\t\t\t\t\t\t'T2':tf.FixedLenFeature([], tf.string)\n\t\t\t\t\t})\n\n\tpatch_shape = [conf.patch_size, conf.patch_size, conf.patch_size]\n\n\t# Convert from a scalar string tensor\n\timage_T1 = tf.decode_raw(features['T1'], tf.int16)\n\timage_T1 = tf.reshape(image_T1, patch_shape)\n\timage_T2 = tf.decode_raw(features['T2'], tf.int16)\n\timage_T2 = tf.reshape(image_T2, patch_shape)\n\n\t# Convert dtype.\n\timage_T1 = tf.cast(image_T1, tf.float32)\n\timage_T2 = tf.cast(image_T2, tf.float32)\n\tlabel = tf.zeros(image_T1.shape) # pseudo label\n\n\treturn image_T1, image_T2, label\n\n\ndef crop_image(image_T1, image_T2, label, cut_size):\n\t\"\"\"Crop training data.\"\"\"\n\n\tdata = tf.stack([image_T1, image_T2, label], axis=-1)\n\n\t# Randomly crop a [patch_size, patch_size, patch_size] section of the image.\n\timage = tf.random_crop(\n\t\t\t\tdata[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :],\n\t\t\t\t[conf.patch_size, conf.patch_size, conf.patch_size, 3])\n\n\t[image_T1, image_T2, label] = tf.unstack(image, 3, axis=-1)\n\n\treturn image_T1, image_T2, label\n\n\ndef normalize_image(image_T1, image_T2, label):\n\t\"\"\"Normalize data.\"\"\"\n\n\t# Subtract off the mean and divide by the variance of the pixels.\n\timage_T1 = tf.image.per_image_standardization(image_T1)\n\timage_T2 = tf.image.per_image_standardization(image_T2)\n\n\tfeatures = tf.stack([image_T1, image_T2], axis=-1)\n\n\tlabel = tf.cast(label, tf.int32)\n\t\n\treturn features, label\n\n\ndef input_function(data_dir, mode, patch_size, batch_size, buffer_size, valid_id,\n\t\t\t\t\t\tpred_id, overlap_step, num_epochs=1, num_parallel_calls=1):\n\t\"\"\"Input function.\n\n\tArgs:\n\t\tdata_dir: The directory containing the input data.\n\t\tmode: A string in ['train', 'valid', 'pred'].\n\t\tpatch_size: An integer.\n\t\tbatch_size: The number of samples per batch.\n\t\tbuffer_size: The buffer size to use when shuffling records. A larger\n\t\t\tvalue results in better randomness, but smaller values reduce startup\n\t\t\ttime and use less memory.\n\t\tvalid_id: The ID of the validation subject.\n\t\tpred_id: The ID of the prediction subject.\n\t\toverlap_step: An integer.\n\t\tnum_epochs: The number of epochs to repeat the dataset.\n\t\tnum_parallel_calls: The number of records that are processed in parallel.\n\t\t\tThis can be optimized per data set but for generally homogeneous data\n\t\t\tsets, should be approximately the number of available CPU cores.\n\n\tReturns:\n\t\tDataset of (features, labels) pairs ready for iteration.\n\t\"\"\"\n\n\twith tf.name_scope('input'):\n\t\t# Generate a Dataset with raw records.\n\t\tfilenames = get_filenames(data_dir, mode, valid_id, pred_id, overlap_step, patch_size)\n\t\tdataset = tf.data.TFRecordDataset(filenames)\n\n\t\t# We prefetch a batch at a time, This can help smooth out the time taken to\n\t\t# load input files as we go through shuffling and processing.\n\t\tdataset = dataset.prefetch(buffer_size=batch_size)\n\n\t\tif mode == 'train':\n\t\t\t# Shuffle the records. Note that we shuffle before repeating to ensure\n\t\t\t# that the shuffling respects epoch boundaries.\n\t\t\tdataset = dataset.shuffle(buffer_size=buffer_size)\n\n\t\t# If we are training over multiple epochs before evaluating, repeat the\n\t\t# dataset for the appropriate number of epochs.\n\t\tdataset = dataset.repeat(num_epochs)\n\n\t\tif mode == 'train':\n\t\t\tdataset = dataset.map(decode_train, num_parallel_calls=num_parallel_calls)\n\t\t\tdataset = dataset.map(crop_image, num_parallel_calls=num_parallel_calls)\n\t\telif mode == 'valid':\n\t\t\tdataset = dataset.map(decode_valid, num_parallel_calls=num_parallel_calls)\n\t\telif mode == 'pred':\n\t\t\tdataset = dataset.map(decode_pred, num_parallel_calls=num_parallel_calls)\n\n\t\tdataset = dataset.map(normalize_image, num_parallel_calls=num_parallel_calls)\n\n\t\tdataset = dataset.batch(batch_size)\n\n\t\t# Operations between the final prefetch and the get_next call to the iterator\n\t\t# will happen synchronously during run time. We prefetch here again to\n\t\t# background all of the above processing work and keep it out of the\n\t\t# critical training path.\n\t\tdataset = dataset.prefetch(1)\n\n\t\titerator = dataset.make_one_shot_iterator()\n\t\tfeatures, label = iterator.get_next()\n\n\t\treturn features, label\n"
  },
  {
    "path": "main.py",
    "content": "import argparse\nimport os\nimport tensorflow as tf\nfrom model import Model\nfrom configure import conf\n\n\n\"\"\"This script defines hyperparameters.\n\"\"\"\n\n\ndef main(_):\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('--option', dest='option', type=str, default='train',\n\t\t\t\t\t\thelp='actions: train or predict')\n\targs = parser.parse_args()\n\n\tif args.option not in ['train', 'predict']:\n\t\tprint('invalid option: ', args.option)\n\t\tprint(\"Please input a option: train or predict\")\n\telse:\n\t\tmodel = Model(conf)\n\t\tgetattr(model, args.option)()\n\n\nif __name__ == '__main__':\n\t# Choose which gpu or cpu to use\n\tos.environ['CUDA_VISIBLE_DEVICES'] = '5'\n\ttf.logging.set_verbosity(tf.logging.INFO)\n\ttf.app.run()\n"
  },
  {
    "path": "model.py",
    "content": "import tensorflow as tf\nimport os\nimport sys\nimport numpy as np\n\nfrom network import Network\nfrom input_fn import input_function\nfrom generate_tfrecord import cut_edge, prepare_validation, load_subject\n\n\n\"\"\"This script trains or evaluates the model.\n\"\"\"\n\n\nclass Model(object):\n\n\tdef __init__(self, conf):\n\t\tself.conf = conf\n\n\n\tdef _model_fn(self, features, labels, mode):\n\t\t\"\"\"Initializes the Model representing the model layers\n\t\tand uses that model to build the necessary EstimatorSpecs for\n\t\tthe `mode` in question. For training, this means building losses,\n\t\tthe optimizer, and the train op that get passed into the EstimatorSpec.\n\t\tFor evaluation and prediction, the EstimatorSpec is returned without\n\t\ta train op, but with the necessary parameters for the given mode.\n\n\t\tArgs:\n\t\t\tfeatures: tensor representing input images\n\t\t\tlabels: tensor representing class labels for all input images\n\t\t\tmode: current estimator mode; should be one of\n\t\t\t\t`tf.estimator.ModeKeys.TRAIN`, `EVALUATE`, `PREDICT`\n\n\t\tReturns:\n\t\t\tModelFnOps\n\t\t\"\"\"\n\t\tnet = Network(self.conf)\n\t\tlogits = net(features, mode == tf.estimator.ModeKeys.TRAIN)\n\n\t\tpredictions = {\n\t\t\t'classes': tf.argmax(logits, axis=-1),\n\t\t\t'probabilities': tf.nn.softmax(logits, name='softmax_tensor')\n\t\t}\n\n\t\tif mode == tf.estimator.ModeKeys.PREDICT:\n\t\t\treturn tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)\n\n\t\t# Calculate loss, which includes softmax cross entropy and L2 regularization.\n\t\tcross_entropy = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(\n\t\t\t\t\t\t\t\t\t\t\tlabels=labels, logits=logits))\n\n\t\t# Create a tensor named cross_entropy for logging purposes.\n\t\ttf.identity(cross_entropy, name='cross_entropy')\n\t\ttf.summary.scalar('cross_entropy', cross_entropy)\n\n\t\t# Add weight decay to the loss.\n\t\tloss = cross_entropy + self.conf.weight_decay * tf.add_n(\n\t\t\t\t[tf.nn.l2_loss(v) for v in tf.trainable_variables() if 'kernel' in v.name])\n\n\t\tif mode == tf.estimator.ModeKeys.TRAIN:\n\t\t\tglobal_step = tf.train.get_or_create_global_step()\n\t\t\t\n\t\t\t# Learning rate.\n\t\t\t# initial_learning_rate = self.conf.learning_rate\n\t\t\t# Multiply the learning rate by 0.1 at 100, 150, and 200 epochs.\n\t\t\t# boundaries = [int(batches_per_epoch * epoch) for epoch in [150, 200]]\n\t\t\t# vals = [initial_learning_rate * decay for decay in [1, 0.25, 0.25*0.25]]\n\t\t\t# learning_rate = tf.train.piecewise_constant(global_step, boundaries, vals)\n\n\t\t\t# Create a tensor named learning_rate for logging purposes\n\t\t\t# tf.identity(learning_rate, name='learning_rate')\n\t\t\t# tf.summary.scalar('learning_rate', learning_rate)\n\n\t\t\t# optimizer = tf.train.MomentumOptimizer(\n\t\t\t# \t\t\t\tlearning_rate=learning_rate,\n\t\t\t# \t\t\t\tmomentum=self.conf.momentum)\n\n\t\t\toptimizer = tf.train.AdamOptimizer(learning_rate=self.conf.learning_rate)\n\n\t\t\t# Batch norm requires update ops to be added as a dependency to train_op\n\t\t\tupdate_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n\t\t\twith tf.control_dependencies(update_ops):\n\t\t\t\ttrain_op = optimizer.minimize(loss, global_step)\n\t\telse:\n\t\t\ttrain_op = None\n\n\t\taccuracy = tf.metrics.accuracy(labels, predictions['classes'])\n\t\tmetrics = {'accuracy': accuracy}\n\n\t\t# Create a tensor named train_accuracy for logging purposes\n\t\ttf.identity(accuracy[1], name='train_accuracy')\n\t\ttf.summary.scalar('train_accuracy', accuracy[1])\n\n\t\treturn tf.estimator.EstimatorSpec(\n\t\t\t\tmode=mode,\n\t\t\t\tpredictions=predictions,\n\t\t\t\tloss=loss,\n\t\t\t\ttrain_op=train_op,\n\t\t\t\teval_metric_ops=metrics)\n\n\n\tdef train(self):\n\t\t# Using the Winograd non-fused algorithms provides a small performance boost.\n\t\tos.environ['TF_ENABLE_WINOGRAD_NONFUSED'] = '1'\n\n\t\tsave_checkpoints_steps = self.conf.epochs_per_eval * \\\n\t\t\t\t\t\tself.conf.num_training_subs // self.conf.batch_size\n\t\trun_config = tf.estimator.RunConfig().replace(\n\t\t\t\t\t\tsave_checkpoints_steps=save_checkpoints_steps,\n\t\t\t\t\t\tkeep_checkpoint_max=0)\n\n\t\tclassifier = tf.estimator.Estimator(\n\t\t\t\t\t\tmodel_fn=self._model_fn,\n\t\t\t\t\t\tmodel_dir=self.conf.model_dir,\n\t\t\t\t\t\tconfig=run_config)\n\n\t\tfor _ in range(self.conf.train_epochs // self.conf.epochs_per_eval):\n\t\t\ttensors_to_log = {\n\t\t\t\t# 'learning_rate': 'learning_rate',\n\t\t\t\t'cross_entropy': 'cross_entropy',\n\t\t\t\t'train_accuracy': 'train_accuracy'\n\t\t\t}\n\n\t\t\tlogging_hook = tf.train.LoggingTensorHook(\n\t\t\t\t\t\t\t\ttensors=tensors_to_log, every_n_iter=100)\n\n\t\t\tprint('Starting a training cycle.')\n\n\t\t\tdef input_fn_train():\n\t\t\t\treturn input_function(\n\t\t\t\t\t\t\tdata_dir=self.conf.data_dir,\n\t\t\t\t\t\t\tmode='train',\n\t\t\t\t\t\t\tpatch_size=self.conf.patch_size,\n\t\t\t\t\t\t\tbatch_size=self.conf.batch_size,\n\t\t\t\t\t\t\tbuffer_size=self.conf.num_training_subs,\n\t\t\t\t\t\t\tvalid_id=self.conf.validation_id,\n\t\t\t\t\t\t\tpred_id=-1, # not used\n\t\t\t\t\t\t\toverlap_step=-1, # not used\n\t\t\t\t\t\t\tnum_epochs=self.conf.epochs_per_eval,\n\t\t\t\t\t\t\tnum_parallel_calls=self.conf.num_parallel_calls)\n\n\t\t\tclassifier.train(input_fn=input_fn_train, hooks=[logging_hook])\n\n\t\t\tif self.conf.validation_id != -1:\n\t\t\t\tprint('Starting to evaluate.')\n\n\t\t\t\tdef input_fn_eval():\n\t\t\t\t\treturn input_function(\n\t\t\t\t\t\t\t\tdata_dir=self.conf.data_dir,\n\t\t\t\t\t\t\t\tmode='valid',\n\t\t\t\t\t\t\t\tpatch_size=self.conf.patch_size,\n\t\t\t\t\t\t\t\tbatch_size=self.conf.batch_size,\n\t\t\t\t\t\t\t\tbuffer_size=-1, # not used\n\t\t\t\t\t\t\t\tvalid_id=self.conf.validation_id,\n\t\t\t\t\t\t\t\tpred_id=-1, # not used\n\t\t\t\t\t\t\t\toverlap_step=self.conf.overlap_step,\n\t\t\t\t\t\t\t\tnum_epochs=1,\n\t\t\t\t\t\t\t\tnum_parallel_calls=self.conf.num_parallel_calls)\n\n\t\t\t\tclassifier.evaluate(input_fn=input_fn_eval)\n\n\n\tdef predict(self):\n\t\t# Using the Winograd non-fused algorithms provides a small performance boost.\n\t\tos.environ['TF_ENABLE_WINOGRAD_NONFUSED'] = '1'\n\n\t\tprint('Perform prediction for subject-%d:' % self.conf.prediction_id)\n\n\t\tprint('Loading data...')\n\t\t[T1, _, _] = load_subject(self.conf.raw_data_dir, self.conf.prediction_id)\n\n\t\t(_, cut_size) = cut_edge(T1)\n\t\tprint('Check cut_size: ',cut_size)\n\n\t\tcutted_T1 = T1[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :]\n\t\tpatch_ids = prepare_validation(cutted_T1, self.conf.patch_size, self.conf.overlap_step)\n\t\tnum_patches = len(patch_ids)\n\t\tprint ('Number of patches:', num_patches)\n\n\t\tprint('Initialize...')\n\t\tclassifier = tf.estimator.Estimator(\n\t\t\t\t\t\tmodel_fn=self._model_fn,\n\t\t\t\t\t\tmodel_dir=self.conf.model_dir)\n\n\t\tdef input_fn_predict():\n\t\t\treturn input_function(\n\t\t\t\t\t\tdata_dir=self.conf.data_dir,\n\t\t\t\t\t\tmode='pred',\n\t\t\t\t\t\tpatch_size=self.conf.patch_size,\n\t\t\t\t\t\tbatch_size=self.conf.batch_size,\n\t\t\t\t\t\tbuffer_size=-1, # not used\n\t\t\t\t\t\tvalid_id=-1, # not used\n\t\t\t\t\t\tpred_id=self.conf.prediction_id,\n\t\t\t\t\t\toverlap_step=self.conf.overlap_step,\n\t\t\t\t\t\tnum_epochs=1,\n\t\t\t\t\t\tnum_parallel_calls=self.conf.num_parallel_calls)\n\n\t\tcheckpoint_file = os.path.join(self.conf.model_dir, \n\t\t\t\t\t\t\t'model.ckpt-'+str(self.conf.checkpoint_num))\n\n\t\tpreds = classifier.predict(\n\t\t\t\t\tinput_fn=input_fn_predict,\n\t\t\t\t\tcheckpoint_path=checkpoint_file)\n\n\t\tprint('Starting to predict.')\n\n\t\tpredictions = {}\n\t\tfor i, pred in enumerate(preds):\n\t\t\tlocation = patch_ids[i]\n\t\t\tprint('Step {:d}/{:d} processing results for ({:d},{:d},{:d})'.format(\n\t\t\t\t\t\ti+1, num_patches, location[0], location[1], location[2]),\n\t\t\t\t\t\tend='\\r',\n\t\t\t\t\t\tflush=True)\n\t\t\tlogits = pred['probabilities']\n\t\t\tfor j in range(self.conf.patch_size):\n\t\t\t\tfor k in range(self.conf.patch_size):\n\t\t\t\t\tfor l in range(self.conf.patch_size):\n\t\t\t\t\t\tkey = (location[0]+j, location[1]+k, location[2]+l)\n\t\t\t\t\t\tif key not in predictions.keys():\n\t\t\t\t\t\t\tpredictions[key] = []\n\t\t\t\t\t\tpredictions[key].append(logits[j, k, l, :])\n\n\t\tprint('Averaging results...')\n\n\t\tresults = np.zeros((T1.shape[0], T1.shape[1], T1.shape[2], self.conf.num_classes),\n\t\t\t\t\t\t\tdtype=np.float32)\n\t\tprint(results.shape)\n\t\tfor key in predictions.keys():\n\t\t\tresults[cut_size[0]+key[0],\tcut_size[2]+key[1], cut_size[4]+key[2]] = \\\n\t\t\t\t\t\tnp.mean(predictions[key], axis=0)\n\t\tresults = np.argmax(results, axis=-1)\n\n\t\tprint('Saving results...')\n\n\t\tif not os.path.exists(self.conf.save_dir):\n\t\t\tos.makedirs(self.conf.save_dir)\n\t\tsave_filename = 'preds-' + str(self.conf.checkpoint_num) + \\\n\t\t\t\t\t\t'-sub-' + str(self.conf.prediction_id) + \\\n\t\t\t\t\t\t'-overlap-' + str(self.conf.overlap_step) + \\\n\t\t\t\t\t\t'-patch-' + str(self.conf.patch_size) + '.npy'\n\t\tsave_file = os.path.join(self.conf.save_dir, save_filename)\n\t\tnp.save(save_file, results)\n\n\t\tprint('Done.')\n\n\t\tos._exit(0)\n"
  },
  {
    "path": "network.py",
    "content": "import tensorflow as tf\n\nfrom utils import Deconv3D, Conv3D, BN_ReLU, Dilated_Conv3D, multihead_attention_3d\n\n\n\"\"\"This script defines the network.\n\"\"\"\n\n\nclass Network(object):\n\n\tdef __init__(self, conf):\n\t\t# configure\n\t\tself.num_classes = conf.num_classes\n\t\tself.num_filters = conf.num_filters\n\t\tself.block_sizes = [1] * conf.network_depth\n\t\tself.block_strides = [1] + [2] * (conf.network_depth - 1)\n\n\n\tdef __call__(self, inputs, training):\n\t\t\"\"\"Add operations to classify a batch of input images.\n\n\t\tArgs:\n\t\t\tinputs: A Tensor representing a batch of input images.\n\t\t\ttraining: A boolean. Set to True to add operations required only when\n\t\t\t\ttraining the classifier.\n\n\t\tReturns:\n\t\t\tA logits Tensor with shape [<batch_size>, self.num_classes].\n\t\t\"\"\"\n\n\t\treturn self._build_network(inputs, training)\n\n\n\t################################################################################\n\t# Composite blocks building the network\n\t################################################################################\n\tdef _build_network(self, inputs, training):\n\t\t\"\"\"Build the network.\n\t\t\"\"\"\n\n\t\tinputs = Conv3D(\n\t\t\t\t\tinputs=inputs,\n\t\t\t\t\tfilters=self.num_filters,\n\t\t\t\t\tkernel_size=3,\n\t\t\t\t\tstrides=1)\n\t\tinputs = tf.identity(inputs, 'initial_conv')\n\n\t\tskip_inputs = []\n\t\tfor i, num_blocks in enumerate(self.block_sizes):\n\t\t\t# print(i, num_blocks)\n\t\t\tnum_filters = self.num_filters * (2**i)\n\t\t\tinputs = self._encoding_block_layer(\n\t\t\t\t\t\tinputs=inputs, filters=num_filters,\n\t\t\t\t\t\tblock_fn=self._residual_block, blocks=num_blocks,\n\t\t\t\t\t\tstrides=self.block_strides[i], training=training,\n\t\t\t\t\t\tname='encode_block_layer{}'.format(i+1))\n\t\t\tskip_inputs.append(inputs)\n\t\t\t# print(inputs.shape)\n\t\t# print(len(skip_inputs))\n\t\t\n\t\tinputs = BN_ReLU(inputs, training)\n\t\tnum_filters = self.num_filters * (2**(len(self.block_sizes)-1))\n\t\t# print(num_filters)\n\t\tinputs = multihead_attention_3d(\n\t\t\t\t\tinputs, num_filters, num_filters, num_filters, 2, training, layer_type='SAME')\n\t\tinputs += skip_inputs[-1]\n\n\t\tfor i, num_blocks in reversed(list(enumerate(self.block_sizes[1:]))):\n\t\t\t# print(i, num_blocks)\n\t\t\tnum_filters = self.num_filters * (2**i)\n\t\t\tif i == len(self.block_sizes) - 2:\n\t\t\t\tinputs = self._att_decoding_block_layer(\n\t\t\t\t\t\tinputs=inputs, skip_inputs=skip_inputs[i],\n\t\t\t\t\t\tfilters=num_filters, block_fn=self._residual_block,\n\t\t\t\t\t\tblocks=1, strides=self.block_strides[i+1],\n\t\t\t\t\t\ttraining=training,\n\t\t\t\t\t\tname='decode_block_layer{}'.format(len(self.block_sizes)-i-1))\n\t\t\telse:\n\t\t\t\tinputs = self._decoding_block_layer(\n\t\t\t\t\t\tinputs=inputs, skip_inputs=skip_inputs[i],\n\t\t\t\t\t\tfilters=num_filters, block_fn=self._residual_block,\n\t\t\t\t\t\tblocks=1, strides=self.block_strides[i+1],\n\t\t\t\t\t\ttraining=training,\n\t\t\t\t\t\tname='decode_block_layer{}'.format(len(self.block_sizes)-i-1))\n\t\t\t# print(inputs.shape)\n\n\t\tinputs = self._output_block_layer(inputs=inputs, training=training)\n\t\t# print(inputs.shape)\n\n\t\treturn inputs\n\n\n\t################################################################################\n\t# Composite blocks building the network\n\t################################################################################\n\tdef _output_block_layer(self, inputs, training):\n\n\t\tinputs = BN_ReLU(inputs, training)\n\n\t\tinputs = tf.layers.dropout(inputs, rate=0.5, training=training)\n\t\t\n\t\tinputs = Conv3D(\n\t\t\t\t\tinputs=inputs,\n\t\t\t\t\tfilters=self.num_classes,\n\t\t\t\t\tkernel_size=1,\n\t\t\t\t\tstrides=1,\n\t\t\t\t\tuse_bias=True)\n\n\t\treturn tf.identity(inputs, 'output')\n\n\n\tdef _encoding_block_layer(self, inputs, filters, block_fn,\n\t\t\t\t\t\t\t\tblocks, strides, training, name):\n\t\t\"\"\"Creates one layer of encoding blocks for the model.\n\n\t\tArgs:\n\t\t\tinputs: A tensor of size [batch, depth_in, height_in, width_in, channels].\n\t\t\tfilters: The number of filters for the first convolution of the layer.\n\t\t\tblock_fn: The block to use within the model.\n\t\t\tblocks: The number of blocks contained in the layer.\n\t\t\tstrides: The stride to use for the first convolution of the layer. If\n\t\t\t\tgreater than 1, this layer will ultimately downsample the input.\n\t\t\ttraining: Either True or False, whether we are currently training the\n\t\t\t\tmodel. Needed for batch norm.\n\t\t\tname: A string name for the tensor output of the block layer.\n\n\t\tReturns:\n\t\t\tThe output tensor of the block layer.\n\t\t\"\"\"\n\n\t\tdef projection_shortcut(inputs):\n\t\t\treturn Conv3D(\n\t\t\t\t\tinputs=inputs,\n\t\t\t\t\tfilters=filters,\n\t\t\t\t\tkernel_size=1,\n\t\t\t\t\tstrides=strides)\n\n\t\t# Only the first block per block_layer uses projection_shortcut and strides\n\t\tinputs = block_fn(inputs, filters, training, projection_shortcut, strides)\n\n\t\tfor _ in range(1, blocks):\n\t\t\tinputs = block_fn(inputs, filters, training, None, 1)\n\n\t\treturn tf.identity(inputs, name)\n\n\n\tdef _att_decoding_block_layer(self, inputs, skip_inputs, filters,\n\t\t\t\t\t\t\t\tblock_fn, blocks, strides, training, name):\n\t\t\"\"\"Creates one layer of decoding blocks for the model.\n\n\t\tArgs:\n\t\t\tinputs: A tensor of size [batch, depth_in, height_in, width_in, channels].\n\t\t\tskip_inputs: A tensor of size [batch, depth_in, height_in, width_in, filters].\n\t\t\tfilters: The number of filters for the first convolution of the layer.\n\t\t\tblock_fn: The block to use within the model.\n\t\t\tblocks: The number of blocks contained in the layer.\n\t\t\tstrides: The stride to use for the first convolution of the layer. If\n\t\t\t\tgreater than 1, this layer will ultimately downsample the input.\n\t\t\ttraining: Either True or False, whether we are currently training the\n\t\t\t\tmodel. Needed for batch norm.\n\t\t\tname: A string name for the tensor output of the block layer.\n\n\t\tReturns:\n\t\t\tThe output tensor of the block layer.\n\t\t\"\"\"\n\n\t\tdef projection_shortcut(inputs):\n\t\t\treturn Deconv3D(\n\t\t\t\t\tinputs=inputs,\n\t\t\t\t\tfilters=filters,\n\t\t\t\t\tkernel_size=3,\n\t\t\t\t\tstrides=strides)\n\n\t\tinputs = self._attention_block(\n\t\t\t\t\tinputs, filters, training, projection_shortcut, strides)\n\n\t\tinputs = inputs + skip_inputs\n\n\t\tfor _ in range(0, blocks):\n\t\t\tinputs = block_fn(inputs, filters, training, None, 1)\n\n\t\treturn tf.identity(inputs, name)\n\n\n\tdef _decoding_block_layer(self, inputs, skip_inputs, filters,\n\t\t\t\t\t\t\t\tblock_fn, blocks, strides, training, name):\n\t\t\"\"\"Creates one layer of decoding blocks for the model.\n\n\t\tArgs:\n\t\t\tinputs: A tensor of size [batch, depth_in, height_in, width_in, channels].\n\t\t\tskip_inputs: A tensor of size [batch, depth_in, height_in, width_in, filters].\n\t\t\tfilters: The number of filters for the first convolution of the layer.\n\t\t\tblock_fn: The block to use within the model.\n\t\t\tblocks: The number of blocks contained in the layer.\n\t\t\tstrides: The stride to use for the first convolution of the layer. If\n\t\t\t\tgreater than 1, this layer will ultimately downsample the input.\n\t\t\ttraining: Either True or False, whether we are currently training the\n\t\t\t\tmodel. Needed for batch norm.\n\t\t\tname: A string name for the tensor output of the block layer.\n\n\t\tReturns:\n\t\t\tThe output tensor of the block layer.\n\t\t\"\"\"\n\n\t\tinputs = Deconv3D(\n\t\t\t\t\tinputs=inputs,\n\t\t\t\t\tfilters=filters,\n\t\t\t\t\tkernel_size=3,\n\t\t\t\t\tstrides=strides)\n\n\t\tinputs = inputs + skip_inputs\n\n\t\tfor _ in range(0, blocks):\n\t\t\tinputs = block_fn(inputs, filters, training, None, 1)\n\n\t\treturn tf.identity(inputs, name)\n\n\n\t################################################################################\n\t# Basic blocks building the network\n\t################################################################################\n\tdef _residual_block(self, inputs, filters, training,\n\t\t\t\t\t\t\tprojection_shortcut, strides):\n\t\t\"\"\"Standard building block for residual networks with BN before convolutions.\n\n\t\tArgs:\n\t\t\tinputs: A tensor of size [batch, depth_in, height_in, width_in, channels].\n\t\t\tfilters: The number of filters for the convolutions.\n\t\t\ttraining: A Boolean for whether the model is in training or inference\n\t\t\t\tmode. Needed for batch normalization.\n\t\t\tprojection_shortcut: The function to use for projection shortcuts\n\t\t\t\t(typically a 1x1 convolution when downsampling the input).\n\t\t\tstrides: The block's stride. If greater than 1, this block will ultimately\n\t\t\t\tdownsample the input.\n\n\t\tReturns:\n\t\t\tThe output tensor of the block.\n\t\t\"\"\"\n\n\t\tshortcut = inputs\n\t\tinputs = BN_ReLU(inputs, training)\n\n\t\t# The projection shortcut should come after the first batch norm and ReLU\n\t\t# since it performs a 1x1 convolution.\n\t\tif projection_shortcut is not None:\n\t\t\tshortcut = projection_shortcut(inputs)\n\n\t\tinputs = Conv3D(\n\t\t\t\t\tinputs=inputs,\n\t\t\t\t\tfilters=filters,\n\t\t\t\t\tkernel_size=3,\n\t\t\t\t\tstrides=strides)\n\n\t\tinputs = BN_ReLU(inputs, training)\n\n\t\tinputs = Conv3D(\n\t\t\t\t\tinputs=inputs,\n\t\t\t\t\tfilters=filters,\n\t\t\t\t\tkernel_size=3,\n\t\t\t\t\tstrides=1)\n\n\t\treturn inputs + shortcut\n\n\n\tdef _attention_block(self, inputs, filters, training,\n\t\t\t\t\t\t\tprojection_shortcut, strides):\n\t\t\"\"\"Attentional building block for residual networks with BN before convolutions.\n\n\t\tArgs:\n\t\t\tinputs: A tensor of size [batch, depth_in, height_in, width_in, channels].\n\t\t\tfilters: The number of filters for the convolutions.\n\t\t\ttraining: A Boolean for whether the model is in training or inference\n\t\t\t\tmode. Needed for batch normalization.\n\t\t\tprojection_shortcut: The function to use for projection shortcuts\n\t\t\t\t(typically a 1x1 convolution when downsampling the input).\n\t\t\tstrides: The block's stride. If greater than 1, this block will ultimately\n\t\t\t\tdownsample the input.\n\n\t\tReturns:\n\t\t\tThe output tensor of the block.\n\t\t\"\"\"\n\n\t\tshortcut = inputs\n\t\tinputs = BN_ReLU(inputs, training)\n\n\t\t# The projection shortcut should come after the first batch norm and ReLU\n\t\t# since it performs a 1x1 convolution.\n\t\tif projection_shortcut is not None:\n\t\t\tshortcut = projection_shortcut(inputs)\n\n\t\tif strides != 1:\n\t\t\tlayer_type = 'UP'\n\t\telse:\n\t\t\tlayer_type = 'SAME'\n\n\t\tinputs = multihead_attention_3d(\n\t\t\t\t\tinputs, filters, filters, filters, 1, training, layer_type)\n\n\t\treturn inputs + shortcut\n"
  },
  {
    "path": "utils/DiceRatio.py",
    "content": "import numpy as np\n\ndef dice_ratio(pred, label):\n    '''Note: pred & label should only contain 0 or 1.\n    '''\n    \n    return np.sum(pred[label==1])*2.0 / (np.sum(pred) + np.sum(label))"
  },
  {
    "path": "utils/HausdorffDistance.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 16 23:56:41 2014\n\n@author: Edward\n\"\"\"\nimport numpy as np\nfrom numpy.core.umath_tests import inner1d\n# A = np.array([[1,2],[3,4],[5,6],[7,8]])\n# B = np.array([[2,3],[4,5],[6,7],[8,9],[10,11]])\n\n\n# Hausdorff Distance\ndef HausdorffDist(A,B):\n    # Hausdorf Distance: Compute the Hausdorff distance between two point\n    # clouds.\n    # Let A and B be subsets of metric space (Z,dZ),\n    # The Hausdorff distance between A and B, denoted by dH(A,B),\n    # is defined by:\n    # dH(A,B) = max(h(A,B),h(B,A)),\n    # where h(A,B) = max(min(d(a,b))\n    # and d(a,b) is a L2 norm\n    # dist_H = hausdorff(A,B)\n    # A: First point sets (MxN, with M observations in N dimension)\n    # B: Second point sets (MxN, with M observations in N dimension)\n    # ** A and B may have different number of rows, but must have the same\n    # number of columns.\n    #\n    # Edward DongBo Cui; Stanford University; 06/17/2014\n\n    # Find pairwise distance\n    D_mat = np.sqrt(inner1d(A,A)[np.newaxis].T + inner1d(B,B)-2*(np.dot(A,B.T)))\n    # Find DH\n    dH = np.max(np.array([np.max(np.min(D_mat,axis=0)),np.max(np.min(D_mat,axis=1))]))\n    return(dH)\n\ndef ModHausdorffDist(A,B):\n    #This function computes the Modified Hausdorff Distance (MHD) which is\n    #proven to function better than the directed HD as per Dubuisson et al.\n    #in the following work:\n    #\n    #M. P. Dubuisson and A. K. Jain. A Modified Hausdorff distance for object\n    #matching. In ICPR94, pages A:566-568, Jerusalem, Israel, 1994.\n    #http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=576361\n    #\n    #The function computed the forward and reverse distances and outputs the\n    #maximum/minimum of both.\n    #Optionally, the function can return forward and reverse distance.\n    #\n    #Format for calling function:\n    #\n    #[MHD,FHD,RHD] = ModHausdorffDist(A,B);\n    #\n    #where\n    #MHD = Modified Hausdorff Distance.\n    #FHD = Forward Hausdorff Distance: minimum distance from all points of B\n    #      to a point in A, averaged for all A\n    #RHD = Reverse Hausdorff Distance: minimum distance from all points of A\n    #      to a point in B, averaged for all B\n    #A -> Point set 1, [row as observations, and col as dimensions]\n    #B -> Point set 2, [row as observations, and col as dimensions]\n    #\n    #No. of samples of each point set may be different but the dimension of\n    #the points must be the same.\n    #\n    #Edward DongBo Cui Stanford University; 06/17/2014\n\n    # Find pairwise distance\n    D_mat = np.sqrt(inner1d(A,A)[np.newaxis].T + inner1d(B,B)-2*(np.dot(A,B.T)))\n    # Calculating the forward HD: mean(min(each col))\n    FHD = np.mean(np.min(D_mat,axis=1))\n    # Calculating the reverse HD: mean(min(each row))\n    RHD = np.mean(np.min(D_mat,axis=0))\n    # Calculating mhd\n    MHD = np.max(np.array([FHD, RHD]))\n    return(MHD, FHD, RHD)"
  },
  {
    "path": "utils/__init__.py",
    "content": "from .basic_ops import Pool3d, Deconv3D, Conv3D, Dilated_Conv3D, BN_ReLU\nfrom .DiceRatio import dice_ratio\nfrom .HausdorffDistance import ModHausdorffDist\nfrom .attention import multihead_attention_3d"
  },
  {
    "path": "utils/attention.py",
    "content": "import tensorflow as tf\nfrom .basic_ops import *\n\n\n\"\"\"This script defines 3D different multi-head attention layers.\n\"\"\"\n\n\ndef multihead_attention_3d(inputs, total_key_filters, total_value_filters,\n\t\t\t\t\t\t\toutput_filters, num_heads, training, layer_type='SAME',\n\t\t\t\t\t\t\tname=None):\n\t\"\"\"3d Multihead scaled-dot-product attention with input/output transformations.\n\t\n\tArgs:\n\t\tinputs: a Tensor with shape [batch, d, h, w, channels]\n\t\ttotal_key_filters: an integer. Note that queries have the same number \n\t\t\tof channels as keys\n\t\ttotal_value_filters: an integer\n\t\toutput_depth: an integer\n\t\tnum_heads: an integer dividing total_key_filters and total_value_filters\n\t\tlayer_type: a string, type of this layer -- SAME, DOWN, UP\n\t\tname: an optional string\n\n\tReturns:\n\t\tA Tensor of shape [batch, _d, _h, _w, output_filters]\n\t\n\tRaises:\n\t\tValueError: if the total_key_filters or total_value_filters are not divisible\n\t\t\tby the number of attention heads.\n\t\"\"\"\n\n\tif total_key_filters % num_heads != 0:\n\t\traise ValueError(\"Key depth (%d) must be divisible by the number of \"\n\t\t\t\t\t\t\"attention heads (%d).\" % (total_key_filters, num_heads))\n\tif total_value_filters % num_heads != 0:\n\t\traise ValueError(\"Value depth (%d) must be divisible by the number of \"\n\t\t\t\t\t\t\"attention heads (%d).\" % (total_value_filters, num_heads))\n\tif layer_type not in ['SAME', 'DOWN', 'UP']:\n\t\traise ValueError(\"Layer type (%s) must be one of SAME, \"\n\t\t\t\t\t\t\"DOWN, UP.\" % (layer_type))\n\n\twith tf.variable_scope(\n\t\t\tname,\n\t\t\tdefault_name=\"multihead_attention_3d\",\n\t\t\tvalues=[inputs]):\n\n\t\t# produce q, k, v\n\t\tq, k, v = compute_qkv_3d(inputs, total_key_filters,\n\t\t\t\t\t\ttotal_value_filters, layer_type)\n\n\t\t# after splitting, shape is [batch, heads, d, h, w, channels / heads]\n\t\tq = split_heads_3d(q, num_heads)\n\t\tk = split_heads_3d(k, num_heads)\n\t\tv = split_heads_3d(v, num_heads)\n\n\t\t# normalize\n\t\tkey_filters_per_head = total_key_filters // num_heads\n\t\tq *= key_filters_per_head**-0.5\n\n\t\t# attention\n\t\tx = global_attention_3d(q, k, v, training)\n\t\t\n\t\tx = combine_heads_3d(x)\n\t\tx = Conv3D(x, output_filters, 1, 1, use_bias=True)\n\n\t\treturn x\n\n\ndef compute_qkv_3d(inputs, total_key_filters, total_value_filters, layer_type):\n\t\"\"\"Computes query, key and value.\n\n\tArgs:\n\t\tinputs: a Tensor with shape [batch, d, h, w, channels]\n\t\ttotal_key_filters: an integer\n\t\ttotal_value_filters: and integer\n\t\tlayer_type: String, type of this layer -- SAME, DOWN, UP\n\t\n\tReturns:\n\t\tq: [batch, _d, _h, _w, total_key_filters] tensor\n\t\tk: [batch, h, w, total_key_filters] tensor\n\t\tv: [batch, h, w, total_value_filters] tensor\n\t\"\"\"\n\n\t# linear transformation for q\n\tif layer_type == 'SAME':\n\t\tq = Conv3D(inputs, total_key_filters, 1, 1, use_bias=True)\n\telif layer_type == 'DOWN':\n\t\tq = Conv3D(inputs, total_key_filters, 3, 2, use_bias=True)\n\telif layer_type == 'UP':\n\t\tq = Deconv3D(inputs, total_key_filters, 3, 2, use_bias=True)\n\n\t# linear transformation for k\n\tk = Conv3D(inputs, total_key_filters, 1, 1, use_bias=True)\n\n\t# linear transformation for k\n\tv = Conv3D(inputs, total_value_filters, 1, 1, use_bias=True)\n\n\treturn q, k, v\n\n\ndef split_heads_3d(x, num_heads):\n\t\"\"\"Split channels (last dimension) into multiple heads (becomes dimension 1).\n\t\n\tArgs:\n\t\tx: a Tensor with shape [batch, d, h, w, channels]\n\t\tnum_heads: an integer\n\t\n\tReturns:\n\t\ta Tensor with shape [batch, num_heads, d, h, w, channels / num_heads]\n\t\"\"\"\n\n\treturn tf.transpose(split_last_dimension(x, num_heads), [0, 4, 1, 2, 3, 5])\n\n\ndef split_last_dimension(x, n):\n\t\"\"\"Reshape x so that the last dimension becomes two dimensions.\n\tThe first of these two dimensions is n.\n\n\tArgs:\n\t\tx: a Tensor with shape [..., m]\n\t\tn: an integer.\n\n\tReturns:\n\t\ta Tensor with shape [..., n, m/n]\n\t\"\"\"\n\n\told_shape = x.get_shape().dims\n\tlast = old_shape[-1]\n\tnew_shape = old_shape[:-1] + [n] + [last // n if last else None]\n\t\n\tret = tf.reshape(x, tf.concat([tf.shape(x)[:-1], [n, -1]], 0))\n\tret.set_shape(new_shape)\n\t\n\treturn ret\n\n\ndef global_attention_3d(q, k, v, training, name=None):\n\t\"\"\"global self-attention.\n\tArgs:\n\t\tq: a Tensor with shape [batch, heads, _d, _h, _w, channels_k]\n\t\tk: a Tensor with shape [batch, heads, d, h, w, channels_k]\n\t\tv: a Tensor with shape [batch, heads, d, h, w, channels_v]\n\t\tname: an optional string\n\tReturns:\n\t\ta Tensor of shape [batch, heads, _d, _h, _w, channels_v]\n\t\"\"\"\n\twith tf.variable_scope(\n\t\t\tname,\n\t\t\tdefault_name=\"global_attention_3d\",\n\t\t\tvalues=[q, k, v]):\n\n\t\tnew_shape = tf.concat([tf.shape(q)[0:-1], [v.shape[-1].value]], 0)\n\n\t\t# flatten q,k,v\n\t\tq_new = flatten_3d(q)\n\t\tk_new = flatten_3d(k)\n\t\tv_new = flatten_3d(v)\n\n\t\t# attention\n\t\toutput = dot_product_attention(q_new, k_new, v_new, bias=None,\n\t\t\t\t\ttraining=training, dropout_rate=0.5, name=\"global_3d\")\n\n\t\t# putting the representations back in the right place\n\t\toutput = scatter_3d(output, new_shape)\n\n\t\treturn output\n\n\ndef reshape_range(tensor, i, j, shape):\n\t\"\"\"Reshapes a tensor between dimensions i and j.\"\"\"\n\n\ttarget_shape = tf.concat(\n\t\t\t[tf.shape(tensor)[:i], shape, tf.shape(tensor)[j:]],\n\t\t\taxis=0)\n\n\treturn tf.reshape(tensor, target_shape)\n\n\ndef flatten_3d(x):\n\t\"\"\"flatten x.\"\"\"\n\n\tx_shape = tf.shape(x)\n\t# [batch, heads, length, channels], length = d*h*w\n\tx = reshape_range(x, 2, 5, [tf.reduce_prod(x_shape[2:5])])\n\n\treturn x\n\n\ndef scatter_3d(x, shape):\n\t\"\"\"scatter x.\"\"\"\n\n\tx = tf.reshape(x, shape)\n\n\treturn x\n\n\ndef dot_product_attention(q, k, v, bias, training, dropout_rate=0.0, name=None):\n\t\"\"\"Dot-product attention.\n\n\tArgs:\n\t\tq: a Tensor with shape [batch, heads, length_q, channels_k]\n\t\tk: a Tensor with shape [batch, heads, length_kv, channels_k]\n\t\tv: a Tensor with shape [batch, heads, length_kv, channels_v]\n\t\tbias: bias Tensor\n\t\tdropout_rate: a floating point number\n\t\tname: an optional string\n\n\tReturns:\n\t\tA Tensor with shape [batch, heads, length_q, channels_v]\n\t\"\"\"\n\n\twith tf.variable_scope(\n\t\t\tname,\n\t\t\tdefault_name=\"dot_product_attention\",\n\t\t\tvalues=[q, k, v]):\n\n\t\t# [batch, num_heads, length_q, length_kv]\n\t\tlogits = tf.matmul(q, k, transpose_b=True)\n\n\t\tif bias is not None:\n\t\t\tlogits += bias\n\n\t\tweights = tf.nn.softmax(logits, name=\"attention_weights\")\n\n\t\t# dropping out the attention links for each of the heads\n\t\tweights = tf.layers.dropout(weights, dropout_rate, training)\n\n\t\treturn tf.matmul(weights, v)\n\n\ndef combine_heads_3d(x):\n\t\"\"\"Inverse of split_heads_3d.\n\n\tArgs:\n\t\tx: a Tensor with shape [batch, num_heads, d, h, w, channels / num_heads]\n\n\tReturns:\n\t\ta Tensor with shape [batch, d, h, w, channels]\n\t\"\"\"\n\n\treturn combine_last_two_dimensions(tf.transpose(x, [0, 2, 3, 4, 1, 5]))\n\n\ndef combine_last_two_dimensions(x):\n\t\"\"\"Reshape x so that the last two dimension become one.\n\n\tArgs:\n\t\tx: a Tensor with shape [..., a, b]\n\n\tReturns:\n\t\ta Tensor with shape [..., a*b]\n\t\"\"\"\n\n\told_shape = x.get_shape().dims\n\ta, b = old_shape[-2:]\n\tnew_shape = old_shape[:-2] + [a * b if a and b else None]\n\n\tret = tf.reshape(x, tf.concat([tf.shape(x)[:-2], [-1]], 0))\n\tret.set_shape(new_shape)\n\n\treturn ret\n"
  },
  {
    "path": "utils/basic_ops.py",
    "content": "import tensorflow as tf\n\n\n\"\"\"This script defines basic operations.\n\"\"\"\n\n\n\n################################################################################\n# Basic operations building the network\n################################################################################\ndef Pool3d(inputs, kernel_size, strides):\n\t\"\"\"Performs 3D max pooling.\"\"\"\n\n\treturn tf.layers.max_pooling3d(\n\t\t\tinputs=inputs,\n\t\t\tpool_size=kernel_size,\n\t\t\tstrides=strides,\n\t\t\tpadding='same')\n\n\ndef Deconv3D(inputs, filters, kernel_size, strides, use_bias=False):\n\t\"\"\"Performs 3D deconvolution without bias and activation function.\"\"\"\n\n\treturn tf.layers.conv3d_transpose(\n\t\t\tinputs=inputs,\n\t\t\tfilters=filters,\n\t\t\tkernel_size=kernel_size,\n\t\t\tstrides=strides,\n\t\t\tpadding='same',\n\t\t\tuse_bias=use_bias,\n\t\t\tkernel_initializer=tf.truncated_normal_initializer())\n\n\ndef Conv3D(inputs, filters, kernel_size, strides, use_bias=False):\n\t\"\"\"Performs 3D convolution without bias and activation function.\"\"\"\n\n\treturn tf.layers.conv3d(\n\t\t\tinputs=inputs,\n\t\t\tfilters=filters,\n\t\t\tkernel_size=kernel_size,\n\t\t\tstrides=strides,\n\t\t\tpadding='same',\n\t\t\tuse_bias=use_bias,\n\t\t\tkernel_initializer=tf.truncated_normal_initializer())\n\n\ndef Dilated_Conv3D(inputs, filters, kernel_size, dilation_rate, use_bias=False):\n\t\"\"\"Performs 3D dilated convolution without bias and activation function.\"\"\"\n\n\treturn tf.layers.conv3d(\n\t\t\tinputs=inputs,\n\t\t\tfilters=filters,\n\t\t\tkernel_size=kernel_size,\n\t\t\tstrides=1,\n\t\t\tdilation_rate=dilation_rate,\n\t\t\tpadding='same',\n\t\t\tuse_bias=use_bias,\n\t\t\tkernel_initializer=tf.truncated_normal_initializer())\n\n\ndef BN_ReLU(inputs, training):\n\t\"\"\"Performs a batch normalization followed by a ReLU6.\"\"\"\n\n\t# We set fused=True for a significant performance boost. See\n\t# https://www.tensorflow.org/performance/performance_guide#common_fused_ops\n\tinputs = tf.layers.batch_normalization(\n\t\t\t\tinputs=inputs,\n\t\t\t\taxis=-1,\n\t\t\t\tmomentum=0.997,\n\t\t\t\tepsilon=1e-5,\n\t\t\t\tcenter=True,\n\t\t\t\tscale=True,\n\t\t\t\ttraining=training, \n\t\t\t\tfused=True)\n\n\treturn tf.nn.relu6(inputs)\n"
  },
  {
    "path": "visualize.py",
    "content": "import os\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n\n\"\"\"Visualize results by slices.\n\"\"\"\n\n\n################################################################################\n# Arguments\n################################################################################\nRAW_DATA_DIR = '/data/zhengyang/InfantBrain/RawData'\nLABEL_DIR = '/data/zhengyang/InfantBrain/tfrecords_full'\nPRED_DIR = './results'\nPRED_ID = 10 # 1-10\nPATCH_SIZE = 32\nCHECKPOINT_NUM = 153000\nOVERLAP_STEPSIZE = 8\nSLICE_DEPTH = 150\n\n\n################################################################################\n# Functions\n################################################################################\ndef Visualize(label_dir, pred_dir, pred_id, patch_size, checkpoint_num,\n\t\toverlap_step, slice_depth):\n\tprint('Perform visualization for subject-%d:' % pred_id)\n\n\tprint('Loading label...')\n\tlabel_file = os.path.join(label_dir, 'subject-%d-label.npy' % pred_id)\n\tassert os.path.isfile(label_file), \\\n\t\t('Run generate_tfrecord.py to generate the label file.')\n\tlabel = np.load(label_file)\n\tprint('Check label: ', label.shape, np.max(label))\n\n\tprint('Loading predition...')\n\tpred_file = os.path.join(pred_dir, \n\t\t\t\t'preds-%d-sub-%d-overlap-%d-patch-%d.npy' % \\\n\t\t\t\t(checkpoint_num, pred_id, overlap_step, patch_size))\n\tassert os.path.isfile(pred_file), \\\n\t\t('Run main.py --option=predict to generate the prediction results.')\n\tpred = np.load(pred_file)\n\tprint('Check pred: ', pred.shape, np.max(pred))\n\n\tpred_show = pred[:, :, slice_depth]\n\tlabel_show = label[:, :, slice_depth]\n\n\tfig = plt.figure()\n\tfig.suptitle('Compare the %d-th slice.' % slice_depth, fontsize=14)\n\n\ta = fig.add_subplot(1,2,1)\n\timgplot = plt.imshow(label_show)\n\ta.set_title('Groud Truth')\n\n\ta = fig.add_subplot(1,2,2)\n\timgplot = plt.imshow(pred_show)\n\ta.set_title('Prediction')\n\n\tplt.savefig('visualization-%d-sub-%d-overlap-%d' % \\\n\t\t\t(checkpoint_num, pred_id, overlap_step))\n\nif __name__ == '__main__':\n\tVisualize(\n\t\tlabel_dir=LABEL_DIR,\n\t\tpred_dir=PRED_DIR,\n\t\tpred_id=PRED_ID,\n\t\tpatch_size=PATCH_SIZE,\n\t\tcheckpoint_num=CHECKPOINT_NUM,\n\t\toverlap_step=OVERLAP_STEPSIZE,\n\t\tslice_depth=SLICE_DEPTH)"
  }
]