[
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 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 Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\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,\nour General Public Licenses are 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.\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  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\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 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 work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be 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 Affero 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 Affero 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 Affero 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 Affero General Public License as published\n    by 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 Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\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 AGPL, see\n<https://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "README.md",
    "content": "# Max Snippet Model (Work in Progress) \n\n## Introduction\nThe complete set of T cell receptors in an individual carries evidence of both past and current immune responses. These traces can act as biomarkers for diseases mediated by the immune system, such as infectious diseases, autoimmune disorders, and cancer. Recent technological advancements enable us to sequence T cell receptors from patients. Nonetheless, only a small number of sequenced T cell receptors from a patient are expected to contain traces relevant to a specific disease. In this repository, we introduce the latest source code for our method to identify these traces.\n\nTo pinpoint the location of these traces within T cell receptor sequences, we previously analyzed 3D X-ray crystallographic structures of T-cell receptors bound to antigens (disease particles). We observed a continuous strip, typically consisting of four amino acid residues from the complementary determining region 3 (CDR3), in direct contact with each antigen. Moreover, the first and last three amino acid residues from each CDR3 do not interact with the antigen. Based on this observation, we discard the first and last three amino acid residues and extract every possible 4-residue long strip from every CDR3 of a T cell receptor sequence. We refer to each 4-residue long strip as a snippet. To represent each amino acid residue in the snippet, we use Atchley numbers, with each amino acid residue having five Atchley numbers that describe its biochemical properties. Since a snippet contains four residues and five Atchley numbers per residue, we can represent each snippet using 20 Atchley numbers. The frequency of a snippet is crucial for identifying traces of past and ongoing immune responses, as T cells involved in an immune response can proliferate, potentially generating multiple copies of a relevant snippet. To quantify the number of copies of each snippet, we calculate the log of its relative abundance, obtained by dividing the number of times that same snippet is observed by the total number of all snippets. This measurement is included alongside the 20 Atchley numbers, resulting in a total of 21 numbers.\n\nSubsequently, the 21 numbers associated with each snippet are evaluated using a linear kernel. The linear kernel treats each of the 21 numbers as features of the snippet, multiplies each number by a weight, adds a bias term, and calculates the sum, resulting in a single number for that snippet. The weight and bias values are determined by a fitting procedure described later. Every snippet from an individual is assessed by the linear kernel using the same weight and bias. The highest score among the snippets is then selected from an individual using a max operator, the reasoning for which will be explained later. By choosing the highest score, the numerous snippets from an individual are represented by a single number. Finally, the highest score is processed through a sigmoid function that converts the score into a probability between 0 and 1.\n\nThe weights and bias values are chosen to ensure that the model assigns a probability close to 1 for an individual with an immune trace. As probability is determined by the highest scoring snippet, at least one snippet must have a high score to assign a probability close to 1 for an individual with an immune trace. The weights and bias values are also chosen to ensure that the model assigns a probability close to 0 for an individual without an immune trace. As probability is determined by the highest scoring snippet, no snippet can have a high score to assign a probability close to 0 for an individual without an immune trace.\n\nWe employ a gradient optimization method, based on gradient or steepest descent, to fit the weights and bias values. We often observe gradient optimization getting trapped in local optima. To address this issue, we fit thousands of model replicas and select the one with the best fit to the training data, aiming to identify the global optimum among numerous local optima. To efficiently utilize GPU cards, we have coded the optimization procedure to fit multiple replicas in parallel. After determining the best optimum, the corresponding weights and bias values are used to score snippets from a holdout individual. We note that the model's performance on holdouts will be suboptimal unless we strive to find the global optimum, as measured on the training set.\n\nIn this repository, we present several examples illustrating our method for identifying immune traces that can serve as biomarkers. Each example is self-contained, complete with the associated datasets required to re-run the model. Some results are successful, while others are not (perhps there are bugs in the code). Our examples demonstrate the ability to:\n* [distinguish malignant from non-malignant ovarian tissue](ovarian-cancer),\n* [diagnose breast cancer from peripheral blood](breast-cancer),\n* [predict clearance of preneoplastic cervical lesions](cervical-cancer),\n* [and provide an example where our code performed poorly.](colorectal-cancer)\n\n## Publications\n* [Cervical Cancer Screening](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC8050337/)\n* [Ovarian Cancer](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7058380/)\n* [Breast and Colorectal Cancer](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6445742/)\n* [Multiple Sclerosis](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5588725/)\n\n## Requirements\n* [Python3](https://www.python.org/)\n* [PyTorch](https://pytorch.org//)\n* [NumPy](http://www.numpy.org/)\n* CUDA GPU\n* Linux Environment (Recommended)\n\n## Download\n* Download: [zip](https://github.com/jostmey/msm/zipball/master)\n* Git: `git clone https://github.com/jostmey/msm`\n\n## To Do\n* Bugs in code preventing replication of all published results (some results replicated, some not)\n* Change-log of modifications of each model from the original publication (point out where we get identical performance)\n* Code to extract top scoring 4mers\n* Rename folders to indicate tissue/blood and published/not\n"
  },
  {
    "path": "aminoacid-representation/README.md",
    "content": "## Amino Acid Representation\n\nInstead of representing each amino acid residue with its symbol (as in one-hot encoding), we utilize a numerical vector that describes its biochemical properties. These properties convey essential information, such as the interchangeable nature of residues R and K based on their positively charged sidechains. Although numerous biochemical properties exist, many carry redundant information. For instance, the mass of an amino acid residue strongly correlates with its size, rendering it unnecessary to include both values. Atchley and colleagues reduced over 50 amino acid biochemical properties to just five by identifying covarying properties (link). These five values are known as Atchley numbers, which loosely correspond to hydrophobicity, secondary structure, molecular volume, codon diversity, and electrostatic charge.\n\nThe CSV files in this folder contain the original Atchley factors. We normalize these factors to achieve unit variance and zero mean. To recompute the normalization, run the following command:\n\n`python3 atchley_factors_normalized.py`\n\n"
  },
  {
    "path": "aminoacid-representation/atchley_factors.csv",
    "content": "A, -0.591, -1.302, -0.733, 1.570, -0.146\nC, -1.343, 0.465, -0.862, -1.020, -0.255\nD, 1.050, 0.302, -3.656, -0.259, -3.242\nE, 1.357, -1.453, 1.477, 0.113, -0.837\nF, -1.006, -0.590, 1.891, -0.397, 0.412\nG, -0.384, 1.652, 1.330, 1.045, 2.064\nH, 0.336, -0.417, -1.673, -1.474, -0.078\nI, -1.239, -0.547, 2.131, 0.393, 0.816\nK, 1.831, -0.561, 0.533, -0.277, 1.648\nL, -1.019, -0.987, -1.505, 1.266, -0.912\nM, -0.663, -1.524, 2.219, -1.005, 1.212\nN, 0.945, 0.828, 1.299, -0.169, 0.933\nP, 0.189, 2.081, -1.628, 0.421, -1.392\nQ, 0.931, -0.179, -3.005, -0.503, -1.853\nR, 1.538, -0.055, 1.502, 0.440, 2.897\nS, -0.228, 1.399, -4.760, 0.670, -2.647\nT, -0.032, 0.326, 2.213, 0.908, 1.313\nV, -1.337, -0.279, -0.544, 1.242, -1.262\nW, -0.595, 0.009, 0.672, -2.128, -0.184\nY, 0.260, 0.830, 3.097, -0.838, 1.512\n"
  },
  {
    "path": "aminoacid-representation/atchley_factors_normalized.csv",
    "content": "A,-0.60384715,-1.3302325,-0.34452927,1.6302937,-0.093537085\nC,-1.3721942,0.4752217,-0.40517095,-1.0590004,-0.16339348\nD,1.0728248,0.3086744,-1.7186037,-0.2688256,-2.0777154\nE,1.3864983,-1.4845185,0.6943706,0.117435955,-0.5363883\nF,-1.0278684,-0.60273767,0.8889881,-0.41211617,0.26407644\nG,-0.39234737,1.6880536,0.6252673,1.0851665,1.3228176\nH,0.34330395,-0.42597276,-0.78641427,-1.5304055,-0.049956944\nI,-1.2659333,-0.5588019,1.0018097,0.40817046,0.52299374\nK,1.8708022,-0.5731065,0.25060523,-0.28751567,1.0562096\nL,-1.041151,-1.0083773,-0.7074391,1.3146391,-0.5844546\nM,-0.6774123,-1.5570637,1.0431777,-1.0434253,0.776784\nN,0.9655424,0.84612143,0.6106945,-0.17537521,0.5979773\nP,0.19310847,2.1263897,-0.7652602,0.4372439,-0.8920792\nQ,0.95123804,-0.18279332,-1.4125749,-0.5221799,-1.187527\nR,1.571433,-0.05609477,0.7061229,0.4569723,1.8566744\nS,-0.23295625,1.4295478,-2.2375836,0.69579,-1.6963892\nT,-0.032695606,0.3331967,1.0403571,0.94291425,0.8415133\nV,-1.3660636,-0.28496957,-0.2556822,1.289719,-0.80876416\nW,-0.6079341,0.009298024,0.3159478,-2.2094784,-0.11789069\nY,0.26565185,0.8481649,1.455917,-0.87002295,0.96904933\n"
  },
  {
    "path": "aminoacid-representation/atchley_factors_normalized.py",
    "content": "#!/usr/bin/env python3\n##########################################################################################\n# Author: Jared L. Ostmeyer\n# Date Started: 2019-08-02\n# Purpose: Normalize atchley factor embedding of amino acid residues\n##########################################################################################\n\n##########################################################################################\n# Libraries\n##########################################################################################\n\nimport numpy as np\n\n##########################################################################################\n# Settings\n##########################################################################################\n\npath_embedding = 'atchley_factors.csv'\npath_embedding_norm = 'atchley_factors_normalized.csv'\n\n##########################################################################################\n# Load data\n##########################################################################################\n\nns = []\nfs = []\nwith open(path_embedding, 'r') as stream:\n  for line in stream:\n    rows = line.split(',')\n    ns.append(rows[0])\n    fs.append(np.array(rows[1:], dtype=np.float32))\n\n##########################################################################################\n# Format data\n##########################################################################################\n\nfs = np.array(fs)\nfs = (fs-np.mean(fs, axis=0))/np.std(fs, axis=0)\n\n##########################################################################################\n# Save results\n##########################################################################################\n\nwith open(path_embedding_norm, 'w') as stream:\n  for n, f in zip(ns, fs):\n    print(n, ','.join([ str(v) for v in f ]), sep=',', file=stream)\n\n"
  },
  {
    "path": "breast-cancer/README.md",
    "content": "# Instructions\nThis example demonstrates the application of our method to predict whether an individual is \"healthy\" or affected by \"cancer\" based on their peripheral blood sample. Each sample is collected from a distinct individual.\n\n## Dataset\nThe `dataset` folder contains T cell receptor sequences from 32 blood samples, with half of the samples originating from healthy individuals and the other half from breast cancer patients. To extract the data, utilize the commands provided below.\n```\ncd dataset\nunzip '*.zip'\ncd ../\n```\n\n## Modeling\nThis model employs snippets derived from T cell receptor sequences in peripheral blood to predict whether an individual is healthy or has breast cancer. The model is trained on data from numerous individuals and its performance is assessed through patient-holdout cross-validation. During the cross-validation process, data from a single individual is withheld during the fitting procedure and subsequently used to evaluate the model's performance on data not included in the fitting. Each individual takes a turn as the holdout, necessitating the model to be refit each time a different individual is held out. To execute the cross-validation, use the following commands, which assume you are running the model on a CUDA-enabled GPU with a minimum of 11GB memory.\n```\nmkdir -p bin\npython3 train_val.py --seed 1 --holdouts BR01B --num_fits 16384 --output bin/1\npython3 train_val.py --seed 1 --holdouts BR05B --num_fits 16384 --output bin/2\npython3 train_val.py --seed 1 --holdouts BR07B --num_fits 16384 --output bin/3\npython3 train_val.py --seed 1 --holdouts BR13B --num_fits 16384 --output bin/4\npython3 train_val.py --seed 1 --holdouts BR14B --num_fits 16384 --output bin/5\npython3 train_val.py --seed 1 --holdouts BR15B --num_fits 16384 --output bin/6\npython3 train_val.py --seed 1 --holdouts BR16B --num_fits 16384 --output bin/7\npython3 train_val.py --seed 1 --holdouts BR17B --num_fits 16384 --output bin/8\npython3 train_val.py --seed 1 --holdouts BR18B --num_fits 16384 --output bin/9\npython3 train_val.py --seed 1 --holdouts BR19B --num_fits 16384 --output bin/10\npython3 train_val.py --seed 1 --holdouts BR20B --num_fits 16384 --output bin/11\npython3 train_val.py --seed 1 --holdouts BR21B --num_fits 16384 --output bin/12\npython3 train_val.py --seed 1 --holdouts BR22B --num_fits 16384 --output bin/13\npython3 train_val.py --seed 1 --holdouts BR24B --num_fits 16384 --output bin/14\npython3 train_val.py --seed 1 --holdouts BR25B --num_fits 16384 --output bin/15\npython3 train_val.py --seed 1 --holdouts BR26B --num_fits 16384 --output bin/16\npython3 train_val.py --seed 1 --holdouts HIP00602 --num_fits 16384 --output bin/17\npython3 train_val.py --seed 1 --holdouts HIP01091 --num_fits 16384 --output bin/18\npython3 train_val.py --seed 1 --holdouts HIP02271 --num_fits 16384 --output bin/19\npython3 train_val.py --seed 1 --holdouts HIP02962 --num_fits 16384 --output bin/20\npython3 train_val.py --seed 1 --holdouts HIP03194 --num_fits 16384 --output bin/21\npython3 train_val.py --seed 1 --holdouts HIP04475 --num_fits 16384 --output bin/22\npython3 train_val.py --seed 1 --holdouts HIP05590 --num_fits 16384 --output bin/23\npython3 train_val.py --seed 1 --holdouts HIP09020 --num_fits 16384 --output bin/24\npython3 train_val.py --seed 1 --holdouts HIP09365 --num_fits 16384 --output bin/25\npython3 train_val.py --seed 1 --holdouts HIP11774 --num_fits 16384 --output bin/26\npython3 train_val.py --seed 1 --holdouts HIP13449 --num_fits 16384 --output bin/27\npython3 train_val.py --seed 1 --holdouts HIP13789 --num_fits 16384 --output bin/28\npython3 train_val.py --seed 1 --holdouts HIP14009 --num_fits 16384 --output bin/29\npython3 train_val.py --seed 1 --holdouts HIP14045 --num_fits 16384 --output bin/30\npython3 train_val.py --seed 1 --holdouts HIP14055 --num_fits 16384 --output bin/31\npython3 train_val.py --seed 1 --holdouts HIP14221 --num_fits 16384 --output bin/32\n```\nThe first flag --seed sets the seed value for generating the initial guess of the weight values. The second flag --holdouts specifies the sample to be held out. The third flag --num_fits determines the number of attempts to find the global best fit for the training data, and has been reduced to accommodate larger samples within GPU memory constraints. The fourth flag --output designates the prefix for filenames saved during the fitting procedure. An optional flag, --device, can be utilized to select either gpu or cpu for processing.\n\n## How does this differ from the other examples in this repository?\nThis dataset comprises individuals from two distinct studies. The first study focuses on healthy individuals, while the second study involves participants with breast cancer. The healthy individuals were chosen to ensure age and sex matching with the breast cancer patients.\n\n## Evaluation\nUpon executing each of the aforementioned commands and completing the patient-holdout cross-validation, you can consolidate the results using the command provided below.\n```\npython3 report.py > report.csv\n```\nThe results are stored in a CSV file that can be opened by your favorite spreadsheet viewer. There are nine columns that represent:\n1.\tThe training step.\n2.\tThe accuracy on the training data averaged over the cross-validation.\n3.\tThe true negative rate (specificity) on the training data averaged over the cross-validation.\n4.\tThe true positive rate (sensitivity) on the training data averaged over the cross-validation.\n5.\tThe cross-entropy on the training data averaged over the cross-validation.\n6.\tThe accuracy on the holdout data averaged over the cross-validation.\n7.\tThe true negative rate (specificity) on the holdout data averaged over the cross-validation.\n8.\tThe true positive rate (sensitivity) on the holdout data averaged over the cross-validation.\n9.\tThe cross-entropy on the holdout data averaged over the cross-validation.\n\n## Publications\n* [Source of Healthy Control Samples](https://www.nature.com/articles/ng.3822)\n* [Source of Breast Cancer Samples](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5715779/)\n* [Original Breast Cancer Model](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6445742/)\n"
  },
  {
    "path": "breast-cancer/dataplumbing.py",
    "content": "#########################################################################################\n# Author: Jared L. Ostmeyer\n# Date Started: 2021-11-16\n# Environment: Python3\n# Purpose: Utilities for loading immune receptor sequences\n##########################################################################################\n\n##########################################################################################\n# Libraries\n##########################################################################################\n\nimport csv\nfrom itertools import combinations\n\n##########################################################################################\n# Utilities\n##########################################################################################\n\ndef load_cdr3s(path_tsv, min_length=4, max_length=32, version='v2'):\n  receptors = {}\n  with open(path_tsv, 'r') as stream:\n    reader = csv.DictReader(stream, delimiter='\\t')\n    for row in reader:\n      if version == 'v2':\n        cdr3 = row['aminoAcid']\n#        quantity = float(row['frequencyCount (%)'])\n        quantity = float(row['count (templates/reads)'])\n        status = row['sequenceStatus']\n      elif version == 'v3':\n        cdr3 = row['amino_acid']\n#        quantity = float(row['frequency'])\n        quantity = float(row['templates'])\n        status = row['frame_type']\n      else:\n        print('ERROR: Unsupported version')\n        exit()\n      if 'In' in status and min_length <= len(cdr3) and len(cdr3) <= max_length and quantity > 0.0 and 'X' not in cdr3:\n        if cdr3 not in receptors:\n          receptors[cdr3] = quantity\n        else:\n          receptors[cdr3] += quantity\n  return receptors\n\ndef trim_cdr3s(receptors, trim_front=0, trim_rear=0):\n  cdr3s = {}\n  for cdr3, quantity in receptors.items():\n    cdr3_trim = cdr3[trim_front:]\n    if trim_rear > 0:\n      cdr3_trim = cdr3_trim[:-trim_rear]\n    if len(cdr3_trim) > 0:\n      if cdr3_trim not in cdr3s:\n        cdr3s[cdr3_trim] = quantity\n      else:\n        cdr3s[cdr3_trim] += quantity\n  return cdr3s\n\ndef cdr3s_to_kmers(cdr3s, kmer_size):\n  kmers = {}\n  for cdr3, quantity in cdr3s.items():\n    if len(cdr3) >= kmer_size:\n      for i in range(len(cdr3)-kmer_size+1):\n        kmer = cdr3[i:i+kmer_size]\n        if kmer not in kmers:\n          kmers[kmer] = quantity\n        else:\n          kmers[kmer] += quantity\n  return kmers\n\ndef cdr3s_to_motifs(cdr3s, window_size, motif_size):\n  templates = []\n  for template in list(combinations(range(window_size), motif_size)):\n    if template[0] == 0:\n      templates.append(template)\n  motifs = {}\n  for cdr3, quantity in cdr3s.items():\n    if len(cdr3) >= motif_size:\n      for i in range(len(cdr3)-motif_size+1):\n        window = cdr3[i:i+window_size]\n        for template in templates:\n          if template[-1] < len(window):\n            motif = ''\n            for i in template:\n              motif += window[i]\n            if motif not in motifs:\n              motifs[motif] = quantity\n            else:\n              motifs[motif] += quantity\n  return motifs\n\ndef flatten_sample(sequences):\n  return { sequence: 1.0 for sequence in sequences.keys() }\n\ndef normalize_sample(sequences):\n  total = 0.0\n  for quantity in sorted(sequences.values()):\n    total += quantity\n  sequences_ = {}\n  for sequence, quantity in sequences.items():\n    sequences_[sequence] = quantity/total\n  return sequences_\n\ndef merge_samples(samples):\n  sequences = {}\n  for sample in samples:\n    for sequence, quantity in sample.items():\n      if sequence not in sequences:\n        sequences[sequence] = quantity/float(len(samples))\n      else:\n        sequences[sequence] += quantity/float(len(samples))\n  return sequences\n\ndef debug_insert_sequence(receptors, sequence, count):\n  if sequence not in receptors:\n    receptors[sequence] = count\n  else:\n    receptors[sequence] += count\n  return receptors\n"
  },
  {
    "path": "breast-cancer/dataset.py",
    "content": "#########################################################################################\n# Author: Jared L. Ostmeyer\n# Date Started: 2021-11-16\n# Environment: Python3\n# Purpose: Utilities for converting immune receptor sequences into numeric features\n##########################################################################################\n\n##########################################################################################\n# Libraries\n##########################################################################################\n\nimport csv\nimport numpy as np\n\n##########################################################################################\n# Utilities\n##########################################################################################\n\ndef load_aminoacid_embedding_dict(path_embedding):\n\n  # Amino acid factors\n  #\n  names = []\n  factors = []\n  with open(path_embedding, 'r') as stream:\n    for line in stream:\n      rows = line.split(',')\n      names.append(rows[0])\n      factors.append(np.array(rows[1:], dtype=np.float32))\n  names = np.array(names)\n  factors = np.array(factors)\n\n  # Convert into a dictionary\n  #\n  aminoacids_dict = { name: factors[i,:] for i, name in enumerate(names) }\n\n  return aminoacids_dict\n\ndef assemble_samples(cases, controls, aminoacids_dict):\n\n  # Determine tensor dimensions \n  #\n  max_steps = -1\n  for sequences in cases.values():\n    for sequence in sequences.keys():\n      if len(sequence) > max_steps:\n        max_steps = len(sequence)\n  for sequences in controls.values():\n    for sequence in sequences.keys():\n      if len(sequence) > max_steps:\n        max_steps = len(sequence)\n  num_factors = len(list(aminoacids_dict.values())[0])\n\n  # Assemble dataset\n  #\n  samples = []\n\n  for subject in sorted(cases.keys()):\n\n    sequences = cases[subject]\n\n    # Initialize tensors\n    #\n    xs = np.zeros([ len(sequences), max_steps*num_factors+1 ], dtype=np.float32)\n\n    # Fill tensors\n    #\n    for i, ( sequence, quantity ) in enumerate(sorted(sequences.items())):\n      for j, aa in enumerate(sequence):\n        xs[i,num_factors*j:num_factors*(j+1)] = aminoacids_dict[aa]\n      xs[i,-1] = np.log(quantity)\n\n    u = np.mean(xs[:,-1])\n    v = np.var(xs[:,-1])\n    xs[:,-1] = (xs[:,-1]-u)/np.sqrt(v)\n\n    samples.append(\n      {\n        'subject': subject,\n        'features': xs,\n        'label': 1.0\n      }\n    )\n\n  for subject in sorted(controls.keys()):\n\n    sequences = controls[subject]\n\n    # Initialize tensors\n    #\n    xs = np.zeros([ len(sequences), max_steps*num_factors+1 ], dtype=np.float32)\n\n    # Fill tensors\n    #\n    for i, ( sequence, quantity ) in enumerate(sorted(sequences.items())):\n      for j, aa in enumerate(sequence):\n        xs[i,num_factors*j:num_factors*(j+1)] = aminoacids_dict[aa]\n      xs[i,-1] = np.log(quantity)\n\n    u = np.mean(xs[:,-1])\n    v = np.var(xs[:,-1])\n    xs[:,-1] = (xs[:,-1]-u)/np.sqrt(v)\n\n    samples.append(\n      {\n        'subject': subject,\n        'features': xs,\n        'label': 0.0\n      }\n    )\n\n  return samples\n\ndef split_samples(samples, holdouts):\n  samples_train = []\n  samples_val = []\n  for sample in samples:\n    if sample['subject'] not in holdouts:\n      samples_train.append(sample)\n    else:\n      samples_val.append(sample)\n  return samples_train, samples_val\n\ndef weight_samples(samples):\n  num_case = 0\n  num_control = 0\n  for sample in samples:\n    if sample['label'] > 0.5:\n      num_case += 1\n    else:\n      num_control += 1\n  for sample in samples:\n    if sample['label'] > 0.5:\n      sample['weight'] = 0.5/num_case if num_control > 0 else 1.0/num_case\n    else:\n      sample['weight'] = 0.5/num_control if num_case > 0 else 1.0/num_control\n  return samples\n\ndef normalize_samples(samples_train, samples_holdout):\n\n  # Calculate normalization statistics from the training samples\n  #\n  us = 0.0\n  us2 = 0.0\n  for sample in samples_train:\n    xs_sample = sample['features']\n    us_sample = np.mean(xs_sample, axis=0)\n    us2_sample = np.mean(xs_sample**2, axis=0)\n    us += sample['weight']*us_sample\n    us2 += sample['weight']*us2_sample\n  vs = us2-us**2\n\n  # Normalize the training samples\n  #\n  for sample in samples_train:\n    xs_sample = sample['features']\n    xs_sample = (xs_sample-us)/np.sqrt(vs)\n    sample['features'] = xs_sample\n\n  # Normalize the holdout samples\n  #\n  for sample in samples_holdout:\n    xs_sample = sample['features']\n    xs_sample = (xs_sample-us)/np.sqrt(vs)\n    sample['features'] = xs_sample\n\n  return samples_train, samples_holdout\n    \ndef debug_permute_labels(samples):\n  labels = []\n  for sample in samples:\n    labels.append(sample['label'])\n  np.random.shuffle(labels)\n  for sample, label in zip(samples, labels):\n    sample['label'] = label\n  return samples\n"
  },
  {
    "path": "breast-cancer/gold.report.csv",
    "content": "Step,Accuracy_Train,TRP_Train,FPR_Train,Cost_train,Accuracy_Val,TRP_Val,FPR_Val,Cost_Val\n0,50.000001303851604,100.0,0.0,1.1087665660203974,50.0,100.0,0.0,1.1087657122359977\n32,50.000001303851604,100.0,0.0,0.9746543546169101,50.0,100.0,0.0,0.9882532360182199\n64,50.000001303851604,100.0,0.0,0.956154798123996,50.0,100.0,0.0,0.9837422744544466\n96,53.951824340038,100.0,7.903645833333334,0.9401936699025335,50.0,100.0,0.0,0.9790061340358706\n128,68.17057471489534,100.0,36.341145833333336,0.9239505371786172,53.125,93.75,12.5,0.9752436512905321\n160,77.7473978814669,100.0,55.49479166666667,0.9074316060254094,62.5,93.75,31.25,0.9687489525085784\n192,83.89323137234896,99.19270833333333,68.59375,0.8905648795940816,68.75,93.75,43.75,0.9538709485176311\n224,88.50911689223722,99.59635416666666,77.421875,0.8737513345043975,78.125,93.75,62.5,0.929324595937833\n256,91.52995030162856,99.58333333333334,83.4765625,0.8569250998503849,84.375,93.75,75.0,0.9147365863269314\n288,93.21614824002609,99.375,87.05729166666666,0.8402085232017285,87.5,93.75,81.25,0.9047697525179907\n320,94.42708577262238,99.375,89.47916666666666,0.8238007498990938,90.625,93.75,87.5,0.8920257760985286\n352,95.26692957151681,99.8046875,90.72916666666667,0.8076075657417026,90.625,93.75,87.5,0.8842510580236446\n384,95.26692957151681,99.8046875,90.72916666666667,0.7916881633274516,90.625,93.75,87.5,0.8783291066010929\n416,94.96093997731805,99.19270833333333,90.72916666666667,0.7761440248828644,90.625,93.75,87.5,0.8693954466613332\n448,94.66797122731805,98.41145833333333,90.92447916666666,0.7610957371224165,90.625,93.75,87.5,0.8622378710171007\n480,94.66797122731805,98.41145833333333,90.92447916666667,0.746253870558137,90.625,93.75,87.5,0.8530867435889941\n512,94.45963788311929,97.79947916666666,91.11979166666666,0.7318797536910446,90.625,93.75,87.5,0.8517006999611726\n544,94.76562747731805,98.0078125,91.5234375,0.717854169227414,90.625,93.75,87.5,0.8445357926794053\n576,94.75911705521867,97.60416666666666,91.9140625,0.704166846760235,87.5,93.75,81.25,0.849290836799375\n608,94.75260663311929,97.1875,92.31770833333334,0.6908289997243852,84.375,87.5,81.25,0.856516151860143\n640,94.75260663311929,97.1875,92.31770833333333,0.6778869727830005,84.375,87.5,81.25,0.8489620948378077\n672,94.96093997731805,97.1875,92.734375,0.6652883385398278,84.375,87.5,81.25,0.8425030595239287\n704,95.06510664941743,96.97916666666666,93.15104166666666,0.6530945915645023,84.375,87.5,81.25,0.8379974671428634\n736,95.16927332151681,96.97916666666666,93.35937499999999,0.6412082921590925,84.375,87.5,81.25,0.8328068964770631\n768,95.26692957151681,96.97916666666666,93.5546875,0.6297269575665889,81.25,81.25,81.25,0.8271064566042978\n800,95.36458582151681,96.97916666666666,93.75,0.6185128326843261,84.375,87.5,81.25,0.8227516269445052\n832,95.36458582151681,96.97916666666666,93.75,0.6076064886449966,81.25,81.25,81.25,0.8249912571832305\n864,95.26692957151681,96.97916666666666,93.5546875,0.5970243687302654,81.25,81.25,81.25,0.8212471615775674\n896,95.36458582151681,96.97916666666666,93.75,0.5867097868701365,81.25,81.25,81.25,0.8187135871003274\n928,95.36458582151681,96.97916666666666,93.75,0.5767185010983471,81.25,81.25,81.25,0.8104618389456697\n960,95.76823166571558,97.36979166666666,94.16666666666666,0.5669785672589269,78.125,81.25,75.0,0.8185991292988433\n992,95.76823166571558,97.36979166666666,94.16666666666666,0.5574113566407709,78.125,81.25,75.0,0.8137786351914669\n1024,95.76823166571558,97.36979166666666,94.16666666666666,0.5481521124754212,78.125,81.25,75.0,0.8101358135130107\n1056,95.76823166571558,97.36979166666666,94.16666666666666,0.5391171956300372,78.125,81.25,75.0,0.8074424743395503\n1088,95.96354416571558,97.56510416666666,94.36197916666666,0.5303491122878181,78.125,81.25,75.0,0.8038067717727604\n1120,95.96354416571558,97.56510416666666,94.36197916666666,0.5217630404127704,78.125,81.25,75.0,0.7998339898714826\n1152,95.96354416571558,97.56510416666666,94.36197916666666,0.5134105944800843,78.125,81.25,75.0,0.7973929960949235\n1184,96.16536708781496,97.7734375,94.55729166666666,0.5053450472342641,78.125,81.25,75.0,0.7930752943700994\n1216,96.26953375991434,97.98177083333333,94.55729166666666,0.4973053309558505,78.125,81.25,75.0,0.7928495641664652\n1248,96.07422125991434,97.59114583333333,94.55729166666666,0.4894706371246692,78.125,81.25,75.0,0.795023525207023\n1280,96.07422125991434,97.59114583333333,94.55729166666666,0.48176503905133095,78.125,81.25,75.0,0.7902311028206138\n1312,96.07422125991434,97.59114583333333,94.55729166666666,0.47438760345431,78.125,81.25,75.0,0.786830205460078\n1344,96.17838793201372,97.59114583333333,94.765625,0.4671956851524221,78.125,81.25,75.0,0.7854635542025163\n1376,96.27604418201372,97.78645833333333,94.765625,0.4601819473358414,78.125,81.25,75.0,0.7846301144935698\n1408,96.58203377621248,97.99479166666666,95.16927083333333,0.45329373841953524,78.125,75.0,81.25,0.780967960778678\n1440,96.67969002621248,98.38541666666666,94.97395833333333,0.44653359854701147,78.125,75.0,81.25,0.7836665167930863\n1472,96.67969002621248,98.19010416666666,95.16927083333333,0.43976705156884816,78.125,75.0,81.25,0.7891126846033775\n1504,96.6731796041131,98.17708333333333,95.16927083333333,0.43328257073043785,78.125,75.0,81.25,0.7871588678975525\n1536,96.97916919831187,98.58072916666666,95.37760416666666,0.42690001483190154,78.125,75.0,81.25,0.7839307608619616\n1568,96.97916919831187,98.58072916666666,95.37760416666666,0.42057523763823845,78.125,75.0,81.25,0.7828612026020991\n1600,96.98567962041125,98.59375,95.37760416666666,0.4144518048654613,78.125,75.0,81.25,0.7814457654550357\n1632,96.98567962041125,98.59375,95.37760416666666,0.4085118590453364,78.125,75.0,81.25,0.7816419080320025\n1664,96.98567962041125,98.59375,95.37760416666666,0.40268018485447066,78.125,75.0,81.25,0.7798756305344625\n1696,97.18750254251063,98.7890625,95.5859375,0.39698017025105103,78.125,75.0,81.25,0.78677006597077\n1728,97.19401296461001,98.59375,95.79427083333333,0.39135352034582704,78.125,75.0,81.25,0.7874269235493413\n1760,97.39583588670939,98.80208333333333,95.98958333333333,0.385871643207593,78.125,75.0,81.25,0.7792872464736458\n1792,97.49349213670939,98.99739583333333,95.98958333333333,0.38047289018006025,78.125,75.0,81.25,0.7884103824638327\n1824,97.49349213670939,98.99739583333333,95.98958333333333,0.37517013150231093,78.125,75.0,81.25,0.7828765052434095\n1856,97.69531505880877,98.99739583333333,96.39322916666666,0.3698902704628685,78.125,75.0,81.25,0.7811844484462991\n1888,97.69531505880877,98.99739583333333,96.39322916666666,0.36477528109697493,78.125,75.0,81.25,0.7790873517023973\n1920,97.69531505880877,98.99739583333333,96.39322916666666,0.35977617906798676,78.125,75.0,81.25,0.7793601207881784\n1952,97.79297130880877,98.99739583333333,96.58854166666666,0.3548837654341777,75.0,68.75,81.25,0.7825976981065828\n1984,97.79297130880877,98.99739583333333,96.58854166666666,0.3500895295224291,75.0,68.75,81.25,0.780542845291275\n2016,97.79297130880877,98.99739583333333,96.58854166666666,0.3453763728733972,75.0,68.75,81.25,0.7810088340211877\n"
  },
  {
    "path": "breast-cancer/report.py",
    "content": "#!/usr/bin/env python3\r\n##########################################################################################\r\n# Author: Jared L. Ostmeyer\r\n# Date Started: 2018-02-05\r\n# Purpose: Print results of the holdout cross-validation\r\n##########################################################################################\r\n\r\n##########################################################################################\r\n# Libraries\r\n##########################################################################################\r\n\r\nimport glob\r\nimport csv\r\nfrom scipy.special import xlogy\r\nimport numpy as np\r\n\r\n##########################################################################################\r\n# Load data\r\n##########################################################################################\r\n\r\ncosts_train = {}\r\naccuracies_train = {}\r\ntprs_train = {}\r\nfprs_train = {}\r\nfor path in glob.glob('bin/*_ps_train.csv'):\r\n  with open(path, 'r') as stream:\r\n    reader = csv.DictReader(stream)\r\n    costs = []\r\n    accuracies = []\r\n    tprs = []\r\n    fprs = []\r\n    for row in reader:\r\n      label = float(row['Label'])\r\n      weight = float(row['Weight'])\r\n      prediction = float(row['Prediction'])\r\n      costs.append(\r\n        weight*(-xlogy(label, prediction)-xlogy(1.0-label, 1.0-prediction))/np.log(2.0)\r\n      )\r\n      accuracies.append(\r\n        100.0*weight*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n      )\r\n      if label == 1.0:\r\n        tprs.append(\r\n          100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n        )\r\n      elif label == 0.0:\r\n        fprs.append(\r\n          100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n        )\r\n      else:\r\n        print('ERROR: Unrecognized value in the label.')\r\n        exit()\r\n  filename = path.split('/')[-1].split('.')[0]\r\n  _, step, _, _ = filename.split('_')\r\n  i = int(step)\r\n  if i not in costs_train:\r\n    costs_train[i] = []\r\n  costs_train[i].append(\r\n    np.sum(costs)\r\n  )\r\n  if i not in accuracies_train:\r\n    accuracies_train[i] = []\r\n  accuracies_train[i].append(\r\n    np.sum(accuracies)\r\n  )\r\n  if len(tprs) > 0:\r\n    if i not in tprs_train:\r\n      tprs_train[i] = []\r\n    tprs_train[i].append(\r\n      np.mean(tprs)\r\n    )\r\n  if len(fprs) > 0:\r\n    if i not in fprs_train:\r\n      fprs_train[i] = []\r\n    fprs_train[i].append(\r\n      np.mean(fprs)\r\n    )\r\n\r\ncosts_val = {}\r\naccuracies_val = {}\r\ntprs_val = {}\r\nfprs_val = {}\r\nfor path in glob.glob('bin/*_ps_val.csv'):\r\n  with open(path, 'r') as stream:\r\n    reader = csv.DictReader(stream)\r\n    costs = []\r\n    accuracies = []\r\n    tprs = []\r\n    fprs = []\r\n    for row in reader:\r\n      label = float(row['Label'])\r\n      weight = float(row['Weight'])\r\n      prediction = float(row['Prediction'])\r\n      costs.append(\r\n        weight*(-xlogy(label, prediction)-xlogy(1.0-label, 1.0-prediction))/np.log(2.0)\r\n      )\r\n      accuracies.append(\r\n        100.0*weight*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n      )\r\n      if label == 1.0:\r\n        tprs.append(\r\n          100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n        )\r\n      elif label == 0.0:\r\n        fprs.append(\r\n          100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n        )\r\n      else:\r\n        print('ERROR: Unrecognized value in the label.')\r\n        exit()\r\n  filename = path.split('/')[-1].split('.')[0]\r\n  _, step, _, _ = filename.split('_')\r\n  i = int(step)\r\n  if i not in costs_val:\r\n    costs_val[i] = []\r\n  costs_val[i].append(\r\n    np.sum(costs)\r\n  )\r\n  if i not in accuracies_val:\r\n    accuracies_val[i] = []\r\n  accuracies_val[i].append(\r\n    np.sum(accuracies)\r\n  )\r\n  if len(tprs) > 0:\r\n    if i not in tprs_val:\r\n      tprs_val[i] = []\r\n    tprs_val[i].append(\r\n      np.mean(tprs)\r\n    )\r\n  if len(fprs) > 0:\r\n    if i not in fprs_val:\r\n      fprs_val[i] = []\r\n    fprs_val[i].append(\r\n      np.mean(fprs)\r\n    )\r\n\r\n##########################################################################################\r\n# Results\r\n##########################################################################################\r\n\r\nprint(\r\n  'Step',\r\n  'Accuracy_Train', 'TRP_Train', 'FPR_Train', 'Cost_train',\r\n  'Accuracy_Val', 'TRP_Val', 'FPR_Val', 'Cost_Val',\r\n  sep=','\r\n)\r\nfor i in sorted(accuracies_train.keys()):\r\n  print(\r\n    i,\r\n    np.mean(accuracies_train[i]), np.mean(tprs_train[i]), np.mean(fprs_train[i]), np.mean(costs_train[i]),\r\n    np.mean(accuracies_val[i]), np.mean(tprs_val[i]), np.mean(fprs_val[i]), np.mean(costs_val[i]),\r\n    sep=','\r\n  )\r\n"
  },
  {
    "path": "breast-cancer/train_val.py",
    "content": "#!/usr/bin/env python3\n##########################################################################################\n# Author: Jared L. Ostmeyer\n# Date Started: 2021-11-16\n# Purpose: Train and validate a classifier for immune repertoires\n##########################################################################################\n\n##########################################################################################\n# Libraries\n##########################################################################################\n\nimport argparse\nimport csv\nimport glob\nimport dataplumbing as dp\nimport dataset as ds\nimport numpy as np\nimport torch\n\n##########################################################################################\n# Arguments\n##########################################################################################\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--holdouts', help='Holdout samples', type=str, nargs='+', required=True)\nparser.add_argument('--restart', help='Basename for restart files', type=str, default=None)\nparser.add_argument('--output', help='Basename for output files', type=str, required=True)\nparser.add_argument('--seed', help='Seed value for randomly initializing fits', type=int, default=1)\nparser.add_argument('--device', help='Examples are cuda:0 or cpu', type=str, default='cuda:0')\nparser.add_argument('--num_fits', help='Number of fits to the training data', type=int, default=2**17)\nargs = parser.parse_args()\n\n##########################################################################################\n# Assemble sequences\n##########################################################################################\n\n# Settings\n#\ntrim_front = 3\ntrim_rear = 3\n\nkmer_size = 4\n\n# To hold sequences from each subject\n#\ncases = {}\ncontrols = {}\n\n# Load immune repertoires\n#\nfor path in glob.glob('dataset/*.tsv'):\n  cdr3s = dp.load_cdr3s(path, min_length=kmer_size+trim_front+trim_rear, max_length=32)\n  cdr3s = dp.trim_cdr3s(cdr3s, trim_front=trim_front, trim_rear=trim_rear)\n  kmers = dp.cdr3s_to_kmers(cdr3s, kmer_size)\n  kmers = dp.normalize_sample(kmers)\n  subject = path.split('/')[-1].split('.')[0]\n  if 'BR' in subject:\n    cases[subject] = kmers\n  elif 'HIP' in subject:\n    controls[subject] = kmers\n\n##########################################################################################\n# Assemble datasets\n##########################################################################################\n\n# Load embeddings\n#\naminoacids_dict = ds.load_aminoacid_embedding_dict('../aminoacid-representation/atchley_factors_normalized.csv')\n\n# Convert to numeric representations\n#\nsamples = ds.assemble_samples(cases, controls, aminoacids_dict)\n\n# Split into a training and validation cohort\n#\nsamples_train, samples_val = ds.split_samples(samples, args.holdouts)\n\n# Weight samples\n#\nsamples_train = ds.weight_samples(samples_train)\nsamples_val = ds.weight_samples(samples_val)\n\n# Normalize features\n#\nsamples_train, samples_val = ds.normalize_samples(samples_train, samples_val)\n\n##########################################################################################\n# Assemble tensors\n##########################################################################################\n\n# Settings\n#\ndevice = torch.device(args.device)\n\n# Convert numpy arrays to pytorch tensors\n#\nfor sample in samples_train:\n  sample['features'] = torch.from_numpy(sample['features']).to(device)\n  sample['label'] = torch.tensor(sample['label']).to(device)\n  sample['weight'] = torch.tensor(sample['weight']).to(device)\n\n# Convert numpy arrays to pytorch tensors\n#\nfor sample in samples_val:\n  sample['features'] = torch.from_numpy(sample['features']).to(device)\n  sample['label'] = torch.tensor(sample['label']).to(device)\n  sample['weight'] = torch.tensor(sample['weight']).to(device)\n\n##########################################################################################\n# Model\n##########################################################################################\n\n# Settings\n#\nnum_features = samples_train[0]['features'].shape[1]\nnum_fits = args.num_fits\n\ntorch.manual_seed(args.seed)\n\n# Function for initializing the weights of the model\n#\ndef init_weights():\n  return torch.cat(\n    [\n      0.5**0.5*torch.rand([ num_features-1, num_fits ])/(num_features-1.0)**0.5,  # Weights for the Atchley factors\n      0.5**0.5*torch.rand([ 1, num_fits ])/(1.0)**0.5,  # Weight for the abundance term\n    ],\n    0\n  )\n\n# Class defining the model\n#\nclass MaxSnippetModel(torch.nn.Module):\n  def __init__(self):\n    super(MaxSnippetModel, self).__init__()\n    self.linear = torch.nn.Linear(num_features, num_fits)\n    with torch.no_grad():\n      self.linear.weights = init_weights()  # Initialize the weights\n  def forward(self, x):\n    ls = self.linear(x)\n    ms, _ = torch.max(ls, axis=0)\n    return ms\n\n# Instantiation of the model\n#\nmsm = MaxSnippetModel()\n\n# Turn on GPU acceleration\n#\nmsm.to(device)\n\n##########################################################################################\n# Metrics and optimization\n##########################################################################################\n\n# Settings\n#\nlearning_rate = 0.01\n\n# Optimizer\n#\noptimizer = torch.optim.Adam(msm.parameters(), lr=learning_rate)  # Adam is based on gradient descent but better\n\n# Metrics\n#\nloss = torch.nn.BCEWithLogitsLoss(reduction='none')  # The loss function is calculated seperately for each fit by setting reduction to none\n\ndef accuracy(ls_block, ys_block):  # The binary accuracy is calculated seperate for each fit\n  a = torch.nn.Sigmoid()\n  ps_block = a(ls_block)\n  cs_block = (torch.round(ps_block) == torch.round(ys_block)).to(ys_block.dtype)\n  return cs_block\n\n##########################################################################################\n# Fit and evaluate model\n##########################################################################################\n\n# Settings\n#\nnum_epochs = 2048\n\n# Restore saved models\n#\nif args.restart is not None:\n  msm = torch.load(args.output+'_model.p')\n\n# Each iteration represents one batch\n#\nfor epoch in range(0, num_epochs):\n\n  # Reset the gradients\n  #\n  optimizer.zero_grad()\n\n  es_train = 0.0  # Cross-entropy error\n  as_train = 0.0  # Accuracy\n\n  for sample in samples_train:\n\n    xs_block = sample['features']\n    ys_block = torch.tile(sample['label'], [ num_fits ])\n    w_block = sample['weight']\n\n    ls_block = msm(xs_block)\n    sample['predictions'] = torch.sigmoid(ls_block)\n\n    es_block = w_block*loss(ls_block, ys_block)  # The loss function is calculated seperately for each fit\n    as_block = w_block*accuracy(ls_block, ys_block)  # The binary accuracy is calculated seperate for each fit\n\n    es_train += es_block.detach()\n    as_train += as_block.detach()\n\n    e_block = torch.sum(es_block)\n    e_block.backward()\n\n  i_bestfit = torch.argmin(es_train)  # Very important index selects the best fit to the training data\n\n  es_val = 0.0\n  as_val = 0.0\n\n  with torch.no_grad():\n\n    for sample in samples_val:\n\n      xs_block = sample['features']\n      ys_block = torch.tile(sample['label'], [ num_fits ])\n      w_block = sample['weight']\n\n      ls_block = msm(xs_block)\n      sample['predictions'] = torch.sigmoid(ls_block)\n\n      es_block = w_block*loss(ls_block, ys_block)  # The loss function is calculated seperately for each fit\n      as_block = w_block*accuracy(ls_block, ys_block)  # The binary accuracy is calculated seperate for each fit\n\n      es_val += es_block.detach()\n      as_val += as_block.detach()\n\n  # Print report\n  #\n  print(\n    'Epoch:', epoch,\n    'Accuracy (train):', round(100.0*float(as_train[i_bestfit]), 2), '%',\n    'Accuracy (val):', round(100.0*float(as_val[i_bestfit]), 2), '%',\n    flush=True\n  )\n\n  # Save parameters and results from the best fit to the training data\n  #\n  if epoch%32 == 0:\n    ws = msm.linear.weights.detach().numpy()\n    bs = msm.linear.bias.cpu().detach().numpy()\n    np.savetxt(args.output+'_'+str(epoch)+'_ws.csv', ws[:,i_bestfit])\n    np.savetxt(args.output+'_'+str(epoch)+'_b.csv', bs[[i_bestfit.cpu()]])\n    with open(args.output+'_'+str(epoch)+'_ms_train.csv', 'w') as stream:\n      print('Cross Entropy (bits)', 'Accuracy (%)', sep=',', file=stream)\n      print(float(es_train[i_bestfit])/np.log(2.0), 100.0*float(as_train[i_bestfit]), sep=',', file=stream)\n    with open(args.output+'_'+str(epoch)+'_ms_val.csv', 'w') as stream:\n      print('Cross Entropy (bits)', 'Accuracy (%)', sep=',', file=stream)\n      print(float(es_val[i_bestfit])/np.log(2.0), 100.0*float(as_val[i_bestfit]), sep=',', file=stream)\n    with open(args.output+'_'+str(epoch)+'_ps_train.csv', 'w') as stream:\n      print('Subject', 'Label', 'Weight', 'Prediction', sep=',', file=stream)\n      for sample in samples_train:\n        print(sample['subject'], float(sample['label']), float(sample['weight']), float(sample['predictions'][i_bestfit]), sep=',', file=stream)\n    with open(args.output+'_'+str(epoch)+'_ps_val.csv', 'w') as stream:\n      print('Subject', 'Label', 'Weight', 'Prediction', sep=',', file=stream)\n      for sample in samples_val:\n        print(sample['subject'], float(sample['label']), float(sample['weight']), float(sample['predictions'][i_bestfit]), sep=',', file=stream)\n\n  optimizer.step()\n\ntorch.save(msm, args.output+'_model.p')\n"
  },
  {
    "path": "cervical-cancer/README.md",
    "content": "# Instructions\nThis example demonstrates the application of our method for predicting the regression of preneoplastic cervical lesions caused by HPV. Spontaneous regression of these lesions is favorable, as it suggests the individual's immune system can naturally eliminate these precancerous growths. The samples are categorized as either \"regress\" or \"progress/same,\" with each sample originating from a distinct individual.\n\n## Dataset\nThe dataset folder contains T cell receptor sequences from 24 cervical samples, with six samples labeled as \"progress/same\" and eighteen as \"regress\". To extract the data, use the commands provided below.\n```\ncd dataset\nunzip '*.zip'\ncd ../\n```\n\n## Modeling\nThis model employs snippets derived from T cell receptor sequences in ovarian tissue to predict whether the tissue is \"progress/same\" or \"regress\". The model is trained on data from numerous individuals, and its performance is assessed through patient-holdout cross-validation. During the cross-validation process, data from a single individual is withheld during the fitting procedure, and subsequently used to evaluate the model's performance on data not included in the fitting. Each individual takes a turn as the holdout, necessitating the model to be refit each time a different individual is held out. To execute the cross-validation, use the following commands, which assume you are running the model on a CUDA-enabled GPU with a minimum of 11GB memo.\n```\nmkdir -p bin\npython3 train_val.py --seed 1 --holdouts 112015051_3_38 --output bin/1\npython3 train_val.py --seed 1 --holdouts 3-4_DNA --output bin/2\npython3 train_val.py --seed 1 --holdouts 5-15_DNA --output bin/3\npython3 train_val.py --seed 1 --holdouts 112015051_4_38 --output bin/4\npython3 train_val.py --seed 1 --holdouts 2_31 --output bin/5\npython3 train_val.py --seed 1 --holdouts 112015051_3_39 --output bin/6\npython3 train_val.py --seed 1 --holdouts 4-1_DNA --output bin/7\npython3 train_val.py --seed 1 --holdouts 3-11_DNA --output bin/8\npython3 train_val.py --seed 1 --holdouts 5-6_DNA --output bin/9\npython3 train_val.py --seed 1 --holdouts 112015051_5_33 --output bin/10\npython3 train_val.py --seed 1 --holdouts 3-6_DNA --output bin/11\npython3 train_val.py --seed 1 --holdouts 112015051_5_31 --output bin/12\npython3 train_val.py --seed 1 --holdouts 112015051_5_39 --output bin/13\npython3 train_val.py --seed 1 --holdouts 4-2_DNA --output bin/14\npython3 train_val.py --seed 1 --holdouts 112015051_3_40 --output bin/15\npython3 train_val.py --seed 1 --holdouts 4-13_DNA --output bin/16\npython3 train_val.py --seed 1 --holdouts 5-19_DNA --output bin/17\npython3 train_val.py --seed 1 --holdouts 4-22_DNA --output bin/18\npython3 train_val.py --seed 1 --holdouts 112015051_4_33 --output bin/19\npython3 train_val.py --seed 1 --holdouts 2-30_DNA --output bin/20\npython3 train_val.py --seed 1 --holdouts 5-27A_DNA --output bin/21\npython3 train_val.py --seed 1 --holdouts 112015051_3_32 --output bin/22\npython3 train_val.py --seed 1 --holdouts 112015051_5_35 --output bin/23\npython3 train_val.py --seed 1 --holdouts 4-11_DNA --output bin/24\n```\nThe first flag --seed sets the seed value for generating the initial guess of the weight values. The second flag --holdouts specifies the sample to be held out. The third flag --output designates the prefix for filenames saved during the fitting procedure. Optional flags include --num_fits, which determines the number of attempts to find the global best fit for the training data, and --device, which allows the selection of either gpu or cpu for processing.\n\n## How does this differ from the other examples in this repository?\nPatients who experience regression are expected to have T cells capable of recognizing their precancerous lesions, while patients who show progression or remain the same are likely lacking T cells that can detect these lesions. Consequently, each \"regress\" is treated as a case, and each \"progress/same\" is considered a control. \n\n## Evaluation\nUpon executing each of the aforementioned commands and completing the patient-holdout cross-validation, you can consolidate the results using the command provided below.\n```\npython3 report.py > report.csv\n```\nThe results are stored in a CSV file that can be opened by your favorite spreadsheet viewer. There are nine columns that represent:\n1.\tThe training step.\n2.\tThe accuracy on the training data averaged over the cross-validation.\n3.\tThe true negative rate (specificity) on the training data averaged over the cross-validation.\n4.\tThe true positive rate (sensitivity) on the training data averaged over the cross-validation.\n5.\tThe cross-entropy on the training data averaged over the cross-validation.\n6.\tThe accuracy on the holdout data averaged over the cross-validation.\n7.\tThe true negative rate (specificity) on the holdout data averaged over the cross-validation.\n8.\tThe true positive rate (sensitivity) on the holdout data averaged over the cross-validation.\n9.\tThe cross-entropy on the holdout data averaged over the cross-validation.\n\n## Publication\n* [Cervical Cancer Screening](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC8050337/)\n"
  },
  {
    "path": "cervical-cancer/dataplumbing.py",
    "content": "#########################################################################################\n# Author: Jared L. Ostmeyer\n# Date Started: 2021-11-16\n# Environment: Python3\n# Purpose: Utilities for loading immune receptor sequences\n##########################################################################################\n\n##########################################################################################\n# Libraries\n##########################################################################################\n\nimport csv\nfrom itertools import combinations\n\n##########################################################################################\n# Utilities\n##########################################################################################\n\ndef load_cdr3s(path_tsv, min_length=4, max_length=32, version='v2'):\n  receptors = {}\n  with open(path_tsv, 'r') as stream:\n    reader = csv.DictReader(stream, delimiter='\\t')\n    for row in reader:\n      if version == 'v2':\n        cdr3 = row['aminoAcid']\n#        quantity = float(row['frequencyCount (%)'])\n        quantity = float(row['count (templates/reads)'])\n        status = row['sequenceStatus']\n      elif version == 'v3':\n        cdr3 = row['amino_acid']\n#        quantity = float(row['frequency'])\n        quantity = float(row['templates'])\n        status = row['frame_type']\n      else:\n        print('ERROR: Unsupported version')\n        exit()\n      if 'In' in status and min_length <= len(cdr3) and len(cdr3) <= max_length and quantity > 0.0 and 'X' not in cdr3:\n        if cdr3 not in receptors:\n          receptors[cdr3] = quantity\n        else:\n          receptors[cdr3] += quantity\n  return receptors\n\ndef trim_cdr3s(receptors, trim_front=0, trim_rear=0):\n  cdr3s = {}\n  for cdr3, quantity in receptors.items():\n    cdr3_trim = cdr3[trim_front:]\n    if trim_rear > 0:\n      cdr3_trim = cdr3_trim[:-trim_rear]\n    if len(cdr3_trim) > 0:\n      if cdr3_trim not in cdr3s:\n        cdr3s[cdr3_trim] = quantity\n      else:\n        cdr3s[cdr3_trim] += quantity\n  return cdr3s\n\ndef cdr3s_to_kmers(cdr3s, kmer_size):\n  kmers = {}\n  for cdr3, quantity in cdr3s.items():\n    if len(cdr3) >= kmer_size:\n      for i in range(len(cdr3)-kmer_size+1):\n        kmer = cdr3[i:i+kmer_size]\n        if kmer not in kmers:\n          kmers[kmer] = quantity\n        else:\n          kmers[kmer] += quantity\n  return kmers\n\ndef cdr3s_to_motifs(cdr3s, window_size, motif_size):\n  templates = []\n  for template in list(combinations(range(window_size), motif_size)):\n    if template[0] == 0:\n      templates.append(template)\n  motifs = {}\n  for cdr3, quantity in cdr3s.items():\n    if len(cdr3) >= motif_size:\n      for i in range(len(cdr3)-motif_size+1):\n        window = cdr3[i:i+window_size]\n        for template in templates:\n          if template[-1] < len(window):\n            motif = ''\n            for i in template:\n              motif += window[i]\n            if motif not in motifs:\n              motifs[motif] = quantity\n            else:\n              motifs[motif] += quantity\n  return motifs\n\ndef flatten_sample(sequences):\n  return { sequence: 1.0 for sequence in sequences.keys() }\n\ndef normalize_sample(sequences):\n  total = 0.0\n  for quantity in sorted(sequences.values()):\n    total += quantity\n  sequences_ = {}\n  for sequence, quantity in sequences.items():\n    sequences_[sequence] = quantity/total\n  return sequences_\n\ndef merge_samples(samples):\n  sequences = {}\n  for sample in samples:\n    for sequence, quantity in sample.items():\n      if sequence not in sequences:\n        sequences[sequence] = quantity/float(len(samples))\n      else:\n        sequences[sequence] += quantity/float(len(samples))\n  return sequences\n\ndef debug_insert_sequence(receptors, sequence, count):\n  if sequence not in receptors:\n    receptors[sequence] = count\n  else:\n    receptors[sequence] += count\n  return receptors\n"
  },
  {
    "path": "cervical-cancer/dataset.py",
    "content": "#########################################################################################\n# Author: Jared L. Ostmeyer\n# Date Started: 2021-11-16\n# Environment: Python3\n# Purpose: Utilities for converting immune receptor sequences into numeric features\n##########################################################################################\n\n##########################################################################################\n# Libraries\n##########################################################################################\n\nimport csv\nimport numpy as np\n\n##########################################################################################\n# Utilities\n##########################################################################################\n\ndef load_aminoacid_embedding_dict(path_embedding):\n\n  # Amino acid factors\n  #\n  names = []\n  factors = []\n  with open(path_embedding, 'r') as stream:\n    for line in stream:\n      rows = line.split(',')\n      names.append(rows[0])\n      factors.append(np.array(rows[1:], dtype=np.float32))\n  names = np.array(names)\n  factors = np.array(factors)\n\n  # Convert into a dictionary\n  #\n  aminoacids_dict = { name: factors[i,:] for i, name in enumerate(names) }\n\n  return aminoacids_dict\n\ndef assemble_samples(cases, controls, aminoacids_dict):\n\n  # Determine tensor dimensions \n  #\n  max_steps = -1\n  for sequences in cases.values():\n    for sequence in sequences.keys():\n      if len(sequence) > max_steps:\n        max_steps = len(sequence)\n  for sequences in controls.values():\n    for sequence in sequences.keys():\n      if len(sequence) > max_steps:\n        max_steps = len(sequence)\n  num_factors = len(list(aminoacids_dict.values())[0])\n\n  # Assemble dataset\n  #\n  samples = []\n\n  for subject in sorted(cases.keys()):\n\n    sequences = cases[subject]\n\n    # Initialize tensors\n    #\n    xs = np.zeros([ len(sequences), max_steps*num_factors+1 ], dtype=np.float32)\n\n    # Fill tensors\n    #\n    for i, ( sequence, quantity ) in enumerate(sorted(sequences.items())):\n      for j, aa in enumerate(sequence):\n        xs[i,num_factors*j:num_factors*(j+1)] = aminoacids_dict[aa]\n      xs[i,-1] = np.log(quantity)\n\n    u = np.mean(xs[:,-1])\n    v = np.var(xs[:,-1])\n    xs[:,-1] = (xs[:,-1]-u)/np.sqrt(v)\n\n    samples.append(\n      {\n        'subject': subject,\n        'features': xs,\n        'label': 1.0\n      }\n    )\n\n  for subject in sorted(controls.keys()):\n\n    sequences = controls[subject]\n\n    # Initialize tensors\n    #\n    xs = np.zeros([ len(sequences), max_steps*num_factors+1 ], dtype=np.float32)\n\n    # Fill tensors\n    #\n    for i, ( sequence, quantity ) in enumerate(sorted(sequences.items())):\n      for j, aa in enumerate(sequence):\n        xs[i,num_factors*j:num_factors*(j+1)] = aminoacids_dict[aa]\n      xs[i,-1] = np.log(quantity)\n\n    u = np.mean(xs[:,-1])\n    v = np.var(xs[:,-1])\n    xs[:,-1] = (xs[:,-1]-u)/np.sqrt(v)\n\n    samples.append(\n      {\n        'subject': subject,\n        'features': xs,\n        'label': 0.0\n      }\n    )\n\n  return samples\n\ndef split_samples(samples, holdouts):\n  samples_train = []\n  samples_val = []\n  for sample in samples:\n    if sample['subject'] not in holdouts:\n      samples_train.append(sample)\n    else:\n      samples_val.append(sample)\n  return samples_train, samples_val\n\ndef weight_samples(samples):\n  num_case = 0\n  num_control = 0\n  for sample in samples:\n    if sample['label'] > 0.5:\n      num_case += 1\n    else:\n      num_control += 1\n  for sample in samples:\n    if sample['label'] > 0.5:\n      sample['weight'] = 0.5/num_case if num_control > 0 else 1.0/num_case\n    else:\n      sample['weight'] = 0.5/num_control if num_case > 0 else 1.0/num_control\n  return samples\n\ndef normalize_samples(samples_train, samples_holdout):\n\n  # Calculate normalization statistics from the training samples\n  #\n  us = 0.0\n  us2 = 0.0\n  for sample in samples_train:\n    xs_sample = sample['features']\n    us_sample = np.mean(xs_sample, axis=0)\n    us2_sample = np.mean(xs_sample**2, axis=0)\n    us += sample['weight']*us_sample\n    us2 += sample['weight']*us2_sample\n  vs = us2-us**2\n\n  # Normalize the training samples\n  #\n  for sample in samples_train:\n    xs_sample = sample['features']\n    xs_sample = (xs_sample-us)/np.sqrt(vs)\n    sample['features'] = xs_sample\n\n  # Normalize the holdout samples\n  #\n  for sample in samples_holdout:\n    xs_sample = sample['features']\n    xs_sample = (xs_sample-us)/np.sqrt(vs)\n    sample['features'] = xs_sample\n\n  return samples_train, samples_holdout\n    \ndef debug_permute_labels(samples):\n  labels = []\n  for sample in samples:\n    labels.append(sample['label'])\n  np.random.shuffle(labels)\n  for sample, label in zip(samples, labels):\n    sample['label'] = label\n  return samples\n"
  },
  {
    "path": "cervical-cancer/gold.report.csv",
    "content": "Step,Accuracy_Train,TRP_Train,FPR_Train,Cost_train,Accuracy_Val,TRP_Val,FPR_Val,Cost_Val\n0,50.000000232830644,100.0,0.0,1.0634694351974636,75.0,100.0,0.0,0.8554268361069818\n32,50.000000232830644,100.0,0.0,0.9334031339165191,75.0,100.0,0.0,0.8702897988200883\n64,55.76388927487036,100.0,11.527777777777779,0.8949095965869437,75.0,100.0,0.0,0.8787156345192338\n96,66.6666673341145,100.0,33.333333333333336,0.8603624134151185,75.0,100.0,0.0,0.8866239609609213\n128,82.29166773768763,100.0,64.58333333333333,0.8282770790695366,75.0,100.0,0.0,0.8563799333294329\n160,84.86111224628985,100.0,69.72222222222223,0.7982708314577837,75.0,100.0,0.0,0.8558552828063647\n192,87.1160142744581,99.50980392156862,74.72222222222221,0.7700393627297001,83.33333333333333,100.0,33.333333333333336,0.8463269539004522\n224,90.03540432701509,98.5430283224401,81.52777777777777,0.7438618456093575,70.83333333333333,83.33333333333333,33.333333333333336,0.8369867586437527\n256,90.23965271189809,97.56263616557733,82.91666666666667,0.7188706127697538,70.83333333333333,83.33333333333333,33.333333333333336,0.8774391341771434\n288,92.32570941870411,96.59586056644882,88.05555555555554,0.6954612895595235,70.83333333333333,83.33333333333333,33.333333333333336,0.8761016785176139\n320,96.26770299704124,96.84095860566451,95.69444444444444,0.6732027237251303,66.66666666666667,77.77777777777777,33.333333333333336,0.8961094110772311\n352,96.14515397697687,96.59586056644879,95.69444444444444,0.6521811053121295,66.66666666666667,77.77777777777777,33.333333333333336,0.8987154658081696\n384,97.07788820378482,97.07244008714598,97.08333333333333,0.6321874014473823,62.5,72.22222222222223,33.333333333333336,0.902417650017313\n416,98.61655926021437,98.06644880174292,99.16666666666667,0.6130386018997859,66.66666666666667,77.77777777777777,33.333333333333336,0.8968461326272417\n448,98.62336753867567,98.08006535947713,99.16666666666667,0.5946679742890651,66.66666666666667,77.77777777777777,33.333333333333336,0.8951872277239626\n480,98.80855272834499,97.61710239651417,100.0,0.5773249839932246,66.66666666666667,72.22222222222223,50.0,0.8867685804877564\n512,98.80855272834499,97.61710239651416,100.0,0.5607548173989209,66.66666666666667,72.22222222222223,50.0,0.892859816297781\n544,98.57707124513884,97.15413943355121,100.0,0.545210859300138,66.66666666666667,72.22222222222223,50.0,0.8747522133486937\n576,98.93791002687067,97.87581699346406,100.0,0.5302248540468361,70.83333333333333,77.77777777777777,50.0,0.8591929362288866\n608,99.04684249001245,98.09368191721133,100.0,0.5157593958414521,62.5,72.22222222222223,33.333333333333336,0.9273084820596301\n640,98.93110174840938,97.86220043572985,100.0,0.501964532491237,62.5,72.22222222222223,33.333333333333336,0.9351755813220107\n672,98.92429346994807,97.84858387799564,100.0,0.48878516330200794,58.333333333333336,66.66666666666667,33.333333333333336,0.9477638420703115\n704,99.16258323161553,98.32516339869282,100.0,0.47616100426724356,58.333333333333336,66.66666666666667,33.333333333333336,0.9645430628786023\n736,99.04684249001245,98.09368191721133,100.0,0.4640593983495253,58.333333333333336,66.66666666666667,33.333333333333336,0.9434826356367502\n768,99.2851322516799,98.57026143790851,100.0,0.4525845447317966,62.5,72.22222222222223,33.333333333333336,0.964542368104469\n800,99.16258323161553,98.32516339869282,100.0,0.4414310126941354,58.333333333333336,66.66666666666667,33.333333333333336,0.9833559404330657\n832,99.16258323161553,98.32516339869282,100.0,0.4307829687697815,58.333333333333336,66.66666666666667,33.333333333333336,1.0065603144518112\n864,99.2783239732186,98.5566448801743,100.0,0.4205502539730311,58.333333333333336,66.66666666666667,33.333333333333336,1.00343599750756\n896,99.2783239732186,98.55664488017429,100.0,0.41069690719385904,58.333333333333336,66.66666666666667,33.333333333333336,1.0209493622585424\n928,99.2783239732186,98.5566448801743,100.0,0.4010567565771413,58.333333333333336,66.66666666666667,33.333333333333336,1.0325164928686876\n960,99.2783239732186,98.5566448801743,100.0,0.391909282709473,54.166666666666664,66.66666666666667,16.666666666666668,1.0514157673023952\n992,99.2783239732186,98.5566448801743,100.0,0.38300871020181787,54.166666666666664,66.66666666666667,16.666666666666668,1.0606235633185321\n1024,99.52342201334734,99.04684095860567,100.0,0.3745122770633142,58.333333333333336,72.22222222222223,16.666666666666668,1.0571691501962264\n1056,99.52342201334734,99.04684095860567,100.0,0.3660535339704964,62.5,72.22222222222223,33.333333333333336,1.05738866515358\n1088,99.51661373488605,99.03322440087146,100.0,0.3581120690495103,62.5,72.22222222222223,33.333333333333336,1.0182468240718021\n1120,99.63916275495042,99.27832244008714,100.0,0.3502775518824605,62.5,72.22222222222223,33.333333333333336,1.0468283152583353\n1152,99.63916275495042,99.27832244008715,100.0,0.3427729184239747,62.5,72.22222222222223,33.333333333333336,1.0056428391349492\n1184,99.7617117750148,99.52342047930283,100.0,0.33543198021426296,62.5,72.22222222222223,33.333333333333336,1.0778154195170642\n1216,99.7617117750148,99.52342047930283,100.0,0.3282812682931278,62.5,72.22222222222223,33.333333333333336,1.050291907953176\n1248,99.7617117750148,99.52342047930283,100.0,0.32149969837560427,58.333333333333336,66.66666666666667,33.333333333333336,1.0846131209760779\n1280,99.7617117750148,99.52342047930283,100.0,0.3147783563942984,58.333333333333336,66.66666666666667,33.333333333333336,1.0945050866914154\n1312,99.87745251661788,99.75490196078431,100.0,0.3084497572798046,58.333333333333336,66.66666666666667,33.333333333333336,1.1136941745214457\n1344,99.7617117750148,99.52342047930283,100.0,0.30213019734677077,58.333333333333336,66.66666666666667,33.333333333333336,1.1135871047690111\n1376,99.87745251661788,99.75490196078431,100.0,0.2959683573204777,58.333333333333336,66.66666666666667,33.333333333333336,1.1528383197506067\n1408,99.87745251661788,99.75490196078431,100.0,0.2899510179658565,58.333333333333336,66.66666666666667,33.333333333333336,1.1590160818101067\n1440,99.87745251661788,99.75490196078431,100.0,0.2843179585993099,58.333333333333336,66.66666666666667,33.333333333333336,1.1693464632209356\n1472,99.87745251661788,99.75490196078431,100.0,0.27863738389993253,58.333333333333336,66.66666666666667,33.333333333333336,1.1814312089756471\n1504,99.87745251661788,99.75490196078431,100.0,0.27322572759999525,58.333333333333336,66.66666666666667,33.333333333333336,1.1887506610304475\n1536,99.7549034965535,99.50980392156862,100.0,0.26796076192267465,54.166666666666664,61.111111111111114,33.333333333333336,1.2936243087352561\n1568,99.87745251661788,99.75490196078431,100.0,0.26266453605726786,58.333333333333336,66.66666666666667,33.333333333333336,1.2851303422267801\n1600,99.87745251661788,99.75490196078431,100.0,0.2576251850393286,62.5,72.22222222222223,33.333333333333336,1.2750365884846881\n1632,99.87745251661788,99.75490196078431,100.0,0.2527183558150053,62.5,72.22222222222223,33.333333333333336,1.2843436473199483\n1664,99.87745251661788,99.75490196078431,100.0,0.24800572360031034,62.5,72.22222222222223,33.333333333333336,1.2931612462555375\n1696,99.87745251661788,99.75490196078431,100.0,0.24328414524718378,62.5,72.22222222222223,33.333333333333336,1.304073469485531\n1728,100.00000153668225,100.0,100.0,0.23869307529349573,62.5,72.22222222222223,33.333333333333336,1.31155561028911\n1760,100.00000153668225,100.0,100.0,0.23428441173316691,62.5,72.22222222222223,33.333333333333336,1.3246346275131644\n1792,100.00000153668225,100.0,100.0,0.23005443097415115,62.5,72.22222222222223,33.333333333333336,1.3306561863060427\n1824,100.00000153668225,100.0,100.0,0.2258117014117641,62.5,72.22222222222223,33.333333333333336,1.3419289701434165\n1856,100.00000153668225,100.0,100.0,0.22164463687868038,62.5,72.22222222222223,33.333333333333336,1.3511359678562596\n1888,100.00000153668225,100.0,100.0,0.21759565281646961,62.5,72.22222222222223,33.333333333333336,1.3568514382680557\n1920,100.00000153668225,100.0,100.0,0.21359155371278246,62.5,72.22222222222223,33.333333333333336,1.3679553524939767\n1952,100.00000153668225,100.0,100.0,0.20983161099332226,62.5,72.22222222222223,33.333333333333336,1.3744357966892808\n1984,100.00000153668225,100.0,100.0,0.2060198270746907,62.5,72.22222222222223,33.333333333333336,1.4083040914817715\n2016,100.00000153668225,100.0,100.0,0.2025229832087374,62.5,72.22222222222223,33.333333333333336,1.4195121176262238\n"
  },
  {
    "path": "cervical-cancer/report.py",
    "content": "#!/usr/bin/env python3\r\n##########################################################################################\r\n# Author: Jared L. Ostmeyer\r\n# Date Started: 2018-02-05\r\n# Purpose: Print results of the holdout cross-validation\r\n##########################################################################################\r\n\r\n##########################################################################################\r\n# Libraries\r\n##########################################################################################\r\n\r\nimport glob\r\nimport csv\r\nfrom scipy.special import xlogy\r\nimport numpy as np\r\n\r\n##########################################################################################\r\n# Load data\r\n##########################################################################################\r\n\r\ncosts_train = {}\r\naccuracies_train = {}\r\ntprs_train = {}\r\nfprs_train = {}\r\nfor path in glob.glob('bin/*_ps_train.csv'):\r\n  with open(path, 'r') as stream:\r\n    reader = csv.DictReader(stream)\r\n    costs = []\r\n    accuracies = []\r\n    tprs = []\r\n    fprs = []\r\n    for row in reader:\r\n      label = float(row['Label'])\r\n      weight = float(row['Weight'])\r\n      prediction = float(row['Prediction'])\r\n      costs.append(\r\n        weight*(-xlogy(label, prediction)-xlogy(1.0-label, 1.0-prediction))/np.log(2.0)\r\n      )\r\n      accuracies.append(\r\n        100.0*weight*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n      )\r\n      if label == 1.0:\r\n        tprs.append(\r\n          100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n        )\r\n      elif label == 0.0:\r\n        fprs.append(\r\n          100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n        )\r\n      else:\r\n        print('ERROR: Unrecognized value in the label.')\r\n        exit()\r\n  filename = path.split('/')[-1].split('.')[0]\r\n  _, step, _, _ = filename.split('_')\r\n  i = int(step)\r\n  if i not in costs_train:\r\n    costs_train[i] = []\r\n  costs_train[i].append(\r\n    np.sum(costs)\r\n  )\r\n  if i not in accuracies_train:\r\n    accuracies_train[i] = []\r\n  accuracies_train[i].append(\r\n    np.sum(accuracies)\r\n  )\r\n  if len(tprs) > 0:\r\n    if i not in tprs_train:\r\n      tprs_train[i] = []\r\n    tprs_train[i].append(\r\n      np.mean(tprs)\r\n    )\r\n  if len(fprs) > 0:\r\n    if i not in fprs_train:\r\n      fprs_train[i] = []\r\n    fprs_train[i].append(\r\n      np.mean(fprs)\r\n    )\r\n\r\ncosts_val = {}\r\naccuracies_val = {}\r\ntprs_val = {}\r\nfprs_val = {}\r\nfor path in glob.glob('bin/*_ps_val.csv'):\r\n  with open(path, 'r') as stream:\r\n    reader = csv.DictReader(stream)\r\n    costs = []\r\n    accuracies = []\r\n    tprs = []\r\n    fprs = []\r\n    for row in reader:\r\n      label = float(row['Label'])\r\n      weight = float(row['Weight'])\r\n      prediction = float(row['Prediction'])\r\n      costs.append(\r\n        weight*(-xlogy(label, prediction)-xlogy(1.0-label, 1.0-prediction))/np.log(2.0)\r\n      )\r\n      accuracies.append(\r\n        100.0*weight*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n      )\r\n      if label == 1.0:\r\n        tprs.append(\r\n          100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n        )\r\n      elif label == 0.0:\r\n        fprs.append(\r\n          100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n        )\r\n      else:\r\n        print('ERROR: Unrecognized value in the label.')\r\n        exit()\r\n  filename = path.split('/')[-1].split('.')[0]\r\n  _, step, _, _ = filename.split('_')\r\n  i = int(step)\r\n  if i not in costs_val:\r\n    costs_val[i] = []\r\n  costs_val[i].append(\r\n    np.sum(costs)\r\n  )\r\n  if i not in accuracies_val:\r\n    accuracies_val[i] = []\r\n  accuracies_val[i].append(\r\n    np.sum(accuracies)\r\n  )\r\n  if len(tprs) > 0:\r\n    if i not in tprs_val:\r\n      tprs_val[i] = []\r\n    tprs_val[i].append(\r\n      np.mean(tprs)\r\n    )\r\n  if len(fprs) > 0:\r\n    if i not in fprs_val:\r\n      fprs_val[i] = []\r\n    fprs_val[i].append(\r\n      np.mean(fprs)\r\n    )\r\n\r\n##########################################################################################\r\n# Results\r\n##########################################################################################\r\n\r\nprint(\r\n  'Step',\r\n  'Accuracy_Train', 'TRP_Train', 'FPR_Train', 'Cost_train',\r\n  'Accuracy_Val', 'TRP_Val', 'FPR_Val', 'Cost_Val',\r\n  sep=','\r\n)\r\nfor i in sorted(accuracies_train.keys()):\r\n  print(\r\n    i,\r\n    np.mean(accuracies_train[i]), np.mean(tprs_train[i]), np.mean(fprs_train[i]), np.mean(costs_train[i]),\r\n    np.mean(accuracies_val[i]), np.mean(tprs_val[i]), np.mean(fprs_val[i]), np.mean(costs_val[i]),\r\n    sep=','\r\n  )\r\n"
  },
  {
    "path": "cervical-cancer/train_val.py",
    "content": "#!/usr/bin/env python3\n##########################################################################################\n# Author: Jared L. Ostmeyer\n# Date Started: 2021-11-16\n# Purpose: Train and validate a classifier for immune repertoires\n##########################################################################################\n\n##########################################################################################\n# Libraries\n##########################################################################################\n\nimport argparse\nimport csv\nimport glob\nimport dataplumbing as dp\nimport dataset as ds\nimport numpy as np\nimport torch\n\n##########################################################################################\n# Arguments\n##########################################################################################\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--holdouts', help='Holdout samples', type=str, nargs='+', required=True)\nparser.add_argument('--restart', help='Basename for restart files', type=str, default=None)\nparser.add_argument('--output', help='Basename for output files', type=str, required=True)\nparser.add_argument('--seed', help='Seed value for randomly initializing fits', type=int, default=1)\nparser.add_argument('--device', help='Examples are cuda:0 or cpu', type=str, default='cuda:0')\nparser.add_argument('--num_fits', help='Number of fits to the training data', type=int, default=2**17)\nargs = parser.parse_args()\n\n##########################################################################################\n# Assemble sequences\n##########################################################################################\n\n# Settings\n#\ntrim_front = 3\ntrim_rear = 3\n\nkmer_size = 4\n\n# To hold sequences from each subject\n#\ncases = {}\ncontrols = {}\n\n# Labels\n#\nsamples = {\n  '2-30_DNA': 'regress',\n  '2_31': 'regress',\n  '3-11_DNA': 'progress',\n  '112015051_3_32': 'regress',\n  '112015051_3_38': 'regress',\n  '112015051_3_39': 'regress',\n  '3-4_DNA': 'progress',\n  '112015051_3_40': 'progress',\n  '3-6_DNA': 'regress',\n  '4-1_DNA': 'regress',\n  '4-11_DNA': 'regress',\n  '4-13_DNA': 'regress',\n  '4-2_DNA': 'regress',\n  '4-22_DNA': 'regress',\n  '112015051_4_33': 'regress',\n  '112015051_4_38': 'progress',\n  '5-15_DNA': 'regress',\n  '5-19_DNA': 'same',\n  '5-27A_DNA': 'regress',\n  '112015051_5_31': 'regress',\n  '112015051_5_33': 'regress',\n  '112015051_5_35': 'regress',\n  '112015051_5_39': 'same',\n  '5-6_DNA': 'regress'\n}\n\n# Load immune repertoires\n#\nfor sample, label in samples.items():\n  path = 'dataset/'+sample+'.tsv'\n  cdr3s = dp.load_cdr3s(path, min_length=kmer_size+trim_front+trim_rear, max_length=32)\n  cdr3s = dp.trim_cdr3s(cdr3s, trim_front=trim_front, trim_rear=trim_rear)\n  kmers = dp.cdr3s_to_kmers(cdr3s, kmer_size)\n  kmers = dp.normalize_sample(kmers)\n  if 'regress' in label:\n    cases[sample] = kmers\n  else:\n    controls[sample] = kmers\n\n##########################################################################################\n# Assemble datasets\n##########################################################################################\n\n# Load embeddings\n#\naminoacids_dict = ds.load_aminoacid_embedding_dict('../aminoacid-representation/atchley_factors_normalized.csv')\n\n# Convert to numeric representations\n#\nsamples = ds.assemble_samples(cases, controls, aminoacids_dict)\n\n# Split into a training and validation cohort\n#\nsamples_train, samples_val = ds.split_samples(samples, args.holdouts)\n\n# Weight samples\n#\nsamples_train = ds.weight_samples(samples_train)\nsamples_val = ds.weight_samples(samples_val)\n\n# Normalize features\n#\nsamples_train, samples_val = ds.normalize_samples(samples_train, samples_val)\n\n##########################################################################################\n# Assemble tensors\n##########################################################################################\n\n# Settings\n#\ndevice = torch.device(args.device)\n\n# Convert numpy arrays to pytorch tensors\n#\nfor sample in samples_train:\n  sample['features'] = torch.from_numpy(sample['features']).to(device)\n  sample['label'] = torch.tensor(sample['label']).to(device)\n  sample['weight'] = torch.tensor(sample['weight']).to(device)\n\n# Convert numpy arrays to pytorch tensors\n#\nfor sample in samples_val:\n  sample['features'] = torch.from_numpy(sample['features']).to(device)\n  sample['label'] = torch.tensor(sample['label']).to(device)\n  sample['weight'] = torch.tensor(sample['weight']).to(device)\n\n##########################################################################################\n# Model\n##########################################################################################\n\n# Settings\n#\nnum_features = samples_train[0]['features'].shape[1]\nnum_fits = args.num_fits\n\ntorch.manual_seed(args.seed)\n\n# Function for initializing the weights of the model\n#\ndef init_weights():\n  return torch.cat(\n    [\n      0.5**0.5*torch.rand([ num_features-1, num_fits ])/(num_features-1.0)**0.5,  # Weights for the Atchley factors\n      0.5**0.5*torch.rand([ 1, num_fits ])/(1.0)**0.5,  # Weight for the abundance term\n    ],\n    0\n  )\n\n# Class defining the model\n#\nclass MaxSnippetModel(torch.nn.Module):\n  def __init__(self):\n    super(MaxSnippetModel, self).__init__()\n    self.linear = torch.nn.Linear(num_features, num_fits)\n    with torch.no_grad():\n      self.linear.weights = init_weights()  # Initialize the weights\n  def forward(self, x):\n    ls = self.linear(x)\n    ms, _ = torch.max(ls, axis=0)\n    return ms\n\n# Instantiation of the model\n#\nmsm = MaxSnippetModel()\n\n# Turn on GPU acceleration\n#\nmsm.to(device)\n\n##########################################################################################\n# Metrics and optimization\n##########################################################################################\n\n# Settings\n#\nlearning_rate = 0.01\n\n# Optimizer\n#\noptimizer = torch.optim.Adam(msm.parameters(), lr=learning_rate)  # Adam is based on gradient descent but better\n\n# Metrics\n#\nloss = torch.nn.BCEWithLogitsLoss(reduction='none')  # The loss function is calculated seperately for each fit by setting reduction to none\n\ndef accuracy(ls_block, ys_block):  # The binary accuracy is calculated seperate for each fit\n  a = torch.nn.Sigmoid()\n  ps_block = a(ls_block)\n  cs_block = (torch.round(ps_block) == torch.round(ys_block)).to(ys_block.dtype)\n  return cs_block\n\n##########################################################################################\n# Fit and evaluate model\n##########################################################################################\n\n# Settings\n#\nnum_epochs = 2048\n\n# Restore saved models\n#\nif args.restart is not None:\n  msm = torch.load(args.output+'_model.p')\n\n# Each iteration represents one batch\n#\nfor epoch in range(0, num_epochs):\n\n  # Reset the gradients\n  #\n  optimizer.zero_grad()\n\n  es_train = 0.0  # Cross-entropy error\n  as_train = 0.0  # Accuracy\n\n  for sample in samples_train:\n\n    xs_block = sample['features']\n    ys_block = torch.tile(sample['label'], [ num_fits ])\n    w_block = sample['weight']\n\n    ls_block = msm(xs_block)\n    sample['predictions'] = torch.sigmoid(ls_block)\n\n    es_block = w_block*loss(ls_block, ys_block)  # The loss function is calculated seperately for each fit\n    as_block = w_block*accuracy(ls_block, ys_block)  # The binary accuracy is calculated seperate for each fit\n\n    es_train += es_block.detach()\n    as_train += as_block.detach()\n\n    e_block = torch.sum(es_block)\n    e_block.backward()\n\n  i_bestfit = torch.argmin(es_train)  # Very important index selects the best fit to the training data\n\n  es_val = 0.0\n  as_val = 0.0\n\n  with torch.no_grad():\n\n    for sample in samples_val:\n\n      xs_block = sample['features']\n      ys_block = torch.tile(sample['label'], [ num_fits ])\n      w_block = sample['weight']\n\n      ls_block = msm(xs_block)\n      sample['predictions'] = torch.sigmoid(ls_block)\n\n      es_block = w_block*loss(ls_block, ys_block)  # The loss function is calculated seperately for each fit\n      as_block = w_block*accuracy(ls_block, ys_block)  # The binary accuracy is calculated seperate for each fit\n\n      es_val += es_block.detach()\n      as_val += as_block.detach()\n\n  # Print report\n  #\n  print(\n    'Epoch:', epoch,\n    'Accuracy (train):', round(100.0*float(as_train[i_bestfit]), 2), '%',\n    'Accuracy (val):', round(100.0*float(as_val[i_bestfit]), 2), '%',\n    flush=True\n  )\n\n  # Save parameters and results from the best fit to the training data\n  #\n  if epoch%32 == 0:\n    ws = msm.linear.weights.detach().numpy()\n    bs = msm.linear.bias.cpu().detach().numpy()\n    np.savetxt(args.output+'_'+str(epoch)+'_ws.csv', ws[:,i_bestfit])\n    np.savetxt(args.output+'_'+str(epoch)+'_b.csv', bs[[i_bestfit.cpu()]])\n    with open(args.output+'_'+str(epoch)+'_ms_train.csv', 'w') as stream:\n      print('Cross Entropy (bits)', 'Accuracy (%)', sep=',', file=stream)\n      print(float(es_train[i_bestfit])/np.log(2.0), 100.0*float(as_train[i_bestfit]), sep=',', file=stream)\n    with open(args.output+'_'+str(epoch)+'_ms_val.csv', 'w') as stream:\n      print('Cross Entropy (bits)', 'Accuracy (%)', sep=',', file=stream)\n      print(float(es_val[i_bestfit])/np.log(2.0), 100.0*float(as_val[i_bestfit]), sep=',', file=stream)\n    with open(args.output+'_'+str(epoch)+'_ps_train.csv', 'w') as stream:\n      print('Subject', 'Label', 'Weight', 'Prediction', sep=',', file=stream)\n      for sample in samples_train:\n        print(sample['subject'], float(sample['label']), float(sample['weight']), float(sample['predictions'][i_bestfit]), sep=',', file=stream)\n    with open(args.output+'_'+str(epoch)+'_ps_val.csv', 'w') as stream:\n      print('Subject', 'Label', 'Weight', 'Prediction', sep=',', file=stream)\n      for sample in samples_val:\n        print(sample['subject'], float(sample['label']), float(sample['weight']), float(sample['predictions'][i_bestfit]), sep=',', file=stream)\n\n  optimizer.step()\n\ntorch.save(msm, args.output+'_model.p')\n"
  },
  {
    "path": "colorectal-cancer/README.md",
    "content": "# Instructions\nThis example demonstrates the application of our method to predict whether colorectal tissue is classified as \"adjacent healthy\" or \"tumor.\" For each individual in the dataset, both an \"adjacent healthy\" and a \"tumor\" sample have been collected.\n\n## Dataset\nIn the dataset folder, you will find T cell receptor sequences from 28 tissue samples. Half of these samples are from adjacent healthy tissue, while the other half are from tumor tissue. To extract the data, utilize the commands provided below.\n```\ncd dataset\nunzip '*.zip'\ncd ../\n```\n\n## Modeling\nThis model leverages snippets from the T cell receptor sequences in ovarian tissue to predict whether the tissue is classified as adjacent healthy or tumor tissue. The model is trained on data from multiple individuals, and its performance is assessed using patient-holdout cross-validation. During this process, data from one individual is withheld during the fitting procedure, and subsequently used to evaluate the model's performance on data not included in the fitting. As each individual takes a turn being held out, the model must be refit for each new holdout. To execute the cross-validation, use the following commands, which assume you are running the model on a CUDA-enabled GPU with a minimum of 11GB memory.\n```\nmkdir -p bin\npython3 train_val.py --seed 1 --holdouts Patient1 --output bin/1\npython3 train_val.py --seed 1 --holdouts Patient2 --output bin/2\npython3 train_val.py --seed 1 --holdouts Patient3 --output bin/3\npython3 train_val.py --seed 1 --holdouts Patient4 --output bin/4\npython3 train_val.py --seed 1 --holdouts Patient5 --output bin/5\npython3 train_val.py --seed 1 --holdouts Patient6 --output bin/6\npython3 train_val.py --seed 1 --holdouts Patient7 --output bin/7\npython3 train_val.py --seed 1 --holdouts Patient8 --output bin/8\npython3 train_val.py --seed 1 --holdouts Patient9 --output bin/9\npython3 train_val.py --seed 1 --holdouts Patient10 --output bin/10\npython3 train_val.py --seed 1 --holdouts Patient11 --output bin/11\npython3 train_val.py --seed 1 --holdouts Patient12 --output bin/12\npython3 train_val.py --seed 1 --holdouts Patient13 --output bin/13\npython3 train_val.py --seed 1 --holdouts Patient14 --output bin/14\n```\nThe first flag, --seed, sets the seed value for generating the initial guess of the weight values. The second flag, --holdouts, specifies which sample to hold out. The third flag, --output, defines the prefix for filenames saved during the fitting process. Additional flags include --num_fits, which determines the number of attempts to find the global best fit for the training data, and --device, which allows for the selection of either gpu or cpu.\n\n## Evaluation\nUpon executing each of the aforementioned commands and completing the patient-holdout cross-validation, you can consolidate the results using the command provided below.\n```\npython3 report.py > report.csv\n```\nThe results are stored in a CSV file that can be opened by your favorite spreadsheet viewer. There are nine columns that represent:\n1.\tThe training step.\n2.\tThe accuracy on the training data averaged over the cross-validation.\n3.\tThe true negative rate (specificity) on the training data averaged over the cross-validation.\n4.\tThe true positive rate (sensitivity) on the training data averaged over the cross-validation.\n5.\tThe cross-entropy on the training data averaged over the cross-validation.\n6.\tThe accuracy on the holdout data averaged over the cross-validation.\n7.\tThe true negative rate (specificity) on the holdout data averaged over the cross-validation.\n8.\tThe true positive rate (sensitivity) on the holdout data averaged over the cross-validation.\n9.\tThe cross-entropy on the holdout data averaged over the cross-validation.\n\n## Publication\n* [Source of Samples](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5714653/)\n* [Original Breast Cancer Model](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6445742/)\n"
  },
  {
    "path": "colorectal-cancer/dataplumbing.py",
    "content": "#########################################################################################\n# Author: Jared L. Ostmeyer\n# Date Started: 2021-11-16\n# Environment: Python3\n# Purpose: Utilities for loading immune receptor sequences\n##########################################################################################\n\n##########################################################################################\n# Libraries\n##########################################################################################\n\nimport csv\nfrom itertools import combinations\n\n##########################################################################################\n# Utilities\n##########################################################################################\n\ndef load_cdr3s(path_tsv, min_length=4, max_length=32, version='v2'):\n  receptors = {}\n  with open(path_tsv, 'r') as stream:\n    reader = csv.DictReader(stream, delimiter='\\t')\n    for row in reader:\n      if version == 'v2':\n        cdr3 = row['aminoAcid']\n#        quantity = float(row['frequencyCount (%)'])\n        quantity = float(row['count (templates/reads)'])\n        status = row['sequenceStatus']\n      elif version == 'v3':\n        cdr3 = row['amino_acid']\n#        quantity = float(row['frequency'])\n        quantity = float(row['templates'])\n        status = row['frame_type']\n      else:\n        print('ERROR: Unsupported version')\n        exit()\n      if 'In' in status and min_length <= len(cdr3) and len(cdr3) <= max_length and quantity > 0.0 and 'X' not in cdr3:\n        if cdr3 not in receptors:\n          receptors[cdr3] = quantity\n        else:\n          receptors[cdr3] += quantity\n  return receptors\n\ndef trim_cdr3s(receptors, trim_front=0, trim_rear=0):\n  cdr3s = {}\n  for cdr3, quantity in receptors.items():\n    cdr3_trim = cdr3[trim_front:]\n    if trim_rear > 0:\n      cdr3_trim = cdr3_trim[:-trim_rear]\n    if len(cdr3_trim) > 0:\n      if cdr3_trim not in cdr3s:\n        cdr3s[cdr3_trim] = quantity\n      else:\n        cdr3s[cdr3_trim] += quantity\n  return cdr3s\n\ndef cdr3s_to_kmers(cdr3s, kmer_size):\n  kmers = {}\n  for cdr3, quantity in cdr3s.items():\n    if len(cdr3) >= kmer_size:\n      for i in range(len(cdr3)-kmer_size+1):\n        kmer = cdr3[i:i+kmer_size]\n        if kmer not in kmers:\n          kmers[kmer] = quantity\n        else:\n          kmers[kmer] += quantity\n  return kmers\n\ndef cdr3s_to_motifs(cdr3s, window_size, motif_size):\n  templates = []\n  for template in list(combinations(range(window_size), motif_size)):\n    if template[0] == 0:\n      templates.append(template)\n  motifs = {}\n  for cdr3, quantity in cdr3s.items():\n    if len(cdr3) >= motif_size:\n      for i in range(len(cdr3)-motif_size+1):\n        window = cdr3[i:i+window_size]\n        for template in templates:\n          if template[-1] < len(window):\n            motif = ''\n            for i in template:\n              motif += window[i]\n            if motif not in motifs:\n              motifs[motif] = quantity\n            else:\n              motifs[motif] += quantity\n  return motifs\n\ndef flatten_sample(sequences):\n  return { sequence: 1.0 for sequence in sequences.keys() }\n\ndef normalize_sample(sequences):\n  total = 0.0\n  for quantity in sorted(sequences.values()):\n    total += quantity\n  sequences_ = {}\n  for sequence, quantity in sequences.items():\n    sequences_[sequence] = quantity/total\n  return sequences_\n\ndef merge_samples(samples):\n  sequences = {}\n  for sample in samples:\n    for sequence, quantity in sample.items():\n      if sequence not in sequences:\n        sequences[sequence] = quantity/float(len(samples))\n      else:\n        sequences[sequence] += quantity/float(len(samples))\n  return sequences\n\ndef debug_insert_sequence(receptors, sequence, count):\n  if sequence not in receptors:\n    receptors[sequence] = count\n  else:\n    receptors[sequence] += count\n  return receptors\n"
  },
  {
    "path": "colorectal-cancer/dataset.py",
    "content": "#########################################################################################\n# Author: Jared L. Ostmeyer\n# Date Started: 2021-11-16\n# Environment: Python3\n# Purpose: Utilities for converting immune receptor sequences into numeric features\n##########################################################################################\n\n##########################################################################################\n# Libraries\n##########################################################################################\n\nimport csv\nimport numpy as np\n\n##########################################################################################\n# Utilities\n##########################################################################################\n\ndef load_aminoacid_embedding_dict(path_embedding):\n\n  # Amino acid factors\n  #\n  names = []\n  factors = []\n  with open(path_embedding, 'r') as stream:\n    for line in stream:\n      rows = line.split(',')\n      names.append(rows[0])\n      factors.append(np.array(rows[1:], dtype=np.float32))\n  names = np.array(names)\n  factors = np.array(factors)\n\n  # Convert into a dictionary\n  #\n  aminoacids_dict = { name: factors[i,:] for i, name in enumerate(names) }\n\n  return aminoacids_dict\n\ndef assemble_samples(cases, controls, aminoacids_dict):\n\n  # Determine tensor dimensions \n  #\n  max_steps = -1\n  for sequences in cases.values():\n    for sequence in sequences.keys():\n      if len(sequence) > max_steps:\n        max_steps = len(sequence)\n  for sequences in controls.values():\n    for sequence in sequences.keys():\n      if len(sequence) > max_steps:\n        max_steps = len(sequence)\n  num_factors = len(list(aminoacids_dict.values())[0])\n\n  # Assemble dataset\n  #\n  samples = []\n\n  for subject in sorted(cases.keys()):\n\n    sequences = cases[subject]\n\n    # Initialize tensors\n    #\n    xs = np.zeros([ len(sequences), max_steps*num_factors+1 ], dtype=np.float32)\n\n    # Fill tensors\n    #\n    for i, ( sequence, quantity ) in enumerate(sorted(sequences.items())):\n      for j, aa in enumerate(sequence):\n        xs[i,num_factors*j:num_factors*(j+1)] = aminoacids_dict[aa]\n      xs[i,-1] = np.log(quantity)\n\n    u = np.mean(xs[:,-1])\n    v = np.var(xs[:,-1])\n    xs[:,-1] = (xs[:,-1]-u)/np.sqrt(v)\n\n    samples.append(\n      {\n        'subject': subject,\n        'features': xs,\n        'label': 1.0\n      }\n    )\n\n  for subject in sorted(controls.keys()):\n\n    sequences = controls[subject]\n\n    # Initialize tensors\n    #\n    xs = np.zeros([ len(sequences), max_steps*num_factors+1 ], dtype=np.float32)\n\n    # Fill tensors\n    #\n    for i, ( sequence, quantity ) in enumerate(sorted(sequences.items())):\n      for j, aa in enumerate(sequence):\n        xs[i,num_factors*j:num_factors*(j+1)] = aminoacids_dict[aa]\n      xs[i,-1] = np.log(quantity)\n\n    u = np.mean(xs[:,-1])\n    v = np.var(xs[:,-1])\n    xs[:,-1] = (xs[:,-1]-u)/np.sqrt(v)\n\n    samples.append(\n      {\n        'subject': subject,\n        'features': xs,\n        'label': 0.0\n      }\n    )\n\n  return samples\n\ndef split_samples(samples, holdouts):\n  samples_train = []\n  samples_val = []\n  for sample in samples:\n    if sample['subject'] not in holdouts:\n      samples_train.append(sample)\n    else:\n      samples_val.append(sample)\n  return samples_train, samples_val\n\ndef weight_samples(samples):\n  num_case = 0\n  num_control = 0\n  for sample in samples:\n    if sample['label'] > 0.5:\n      num_case += 1\n    else:\n      num_control += 1\n  for sample in samples:\n    if sample['label'] > 0.5:\n      sample['weight'] = 0.5/num_case if num_control > 0 else 1.0/num_case\n    else:\n      sample['weight'] = 0.5/num_control if num_case > 0 else 1.0/num_control\n  return samples\n\ndef normalize_samples(samples_train, samples_holdout):\n\n  # Calculate normalization statistics from the training samples\n  #\n  us = 0.0\n  us2 = 0.0\n  for sample in samples_train:\n    xs_sample = sample['features']\n    us_sample = np.mean(xs_sample, axis=0)\n    us2_sample = np.mean(xs_sample**2, axis=0)\n    us += sample['weight']*us_sample\n    us2 += sample['weight']*us2_sample\n  vs = us2-us**2\n\n  # Normalize the training samples\n  #\n  for sample in samples_train:\n    xs_sample = sample['features']\n    xs_sample = (xs_sample-us)/np.sqrt(vs)\n    sample['features'] = xs_sample\n\n  # Normalize the holdout samples\n  #\n  for sample in samples_holdout:\n    xs_sample = sample['features']\n    xs_sample = (xs_sample-us)/np.sqrt(vs)\n    sample['features'] = xs_sample\n\n  return samples_train, samples_holdout\n    \ndef debug_permute_labels(samples):\n  labels = []\n  for sample in samples:\n    labels.append(sample['label'])\n  np.random.shuffle(labels)\n  for sample, label in zip(samples, labels):\n    sample['label'] = label\n  return samples\n"
  },
  {
    "path": "colorectal-cancer/gold.report.csv",
    "content": "Step,Accuracy_Train,TRP_Train,FPR_Train,Cost_train,Accuracy_Val,TRP_Val,FPR_Val,Cost_Val\n0,50.00000186264515,100.0,0.0,1.0881439744578585,50.0,100.0,0.0,1.1065032239346837\n32,50.00000186264515,100.0,0.0,0.9666056012260252,50.0,100.0,0.0,1.0014956872219747\n64,50.00000186264515,99.45054945054946,0.5494505494505495,0.945405424172516,42.857142857142854,85.71428571428571,0.0,1.0212423565856366\n96,56.31868341671569,98.90109890109889,13.736263736263734,0.9282460340882187,42.857142857142854,85.71428571428571,0.0,1.0196147039954704\n128,67.58242010005883,98.9010989010989,36.26373626373626,0.9097048915555551,46.42857142857143,85.71428571428571,7.142857142857143,1.0079379699797113\n160,80.4945084931595,99.45054945054946,61.53846153846153,0.8907438170930095,50.0,85.71428571428571,14.285714285714286,1.0090333807174678\n192,85.71428890739169,99.45054945054946,71.97802197802199,0.8718586532274488,50.0,78.57142857142857,21.428571428571427,1.0108581268144543\n224,87.36264061714921,98.9010989010989,75.82417582417584,0.8532775698077774,53.57142857142857,78.57142857142857,28.571428571428573,1.0067119946551661\n256,88.18681647202799,97.80219780219781,78.57142857142857,0.834966302554523,53.57142857142857,78.57142857142857,28.571428571428573,1.007452599447569\n288,88.73626704194716,97.25274725274726,80.21978021978022,0.8174033100918975,57.142857142857146,71.42857142857143,42.857142857142854,0.9779638692820152\n320,89.56044289682593,97.25274725274726,81.86813186813187,0.7998896203131363,60.714285714285715,71.42857142857143,50.0,0.9796172508233029\n352,90.38461875170469,97.80219780219781,82.96703296703296,0.7828980053555642,57.142857142857146,71.42857142857143,42.857142857142854,0.9978110252191862\n384,91.48351989154305,97.80219780219781,85.16483516483515,0.7663747789680074,57.142857142857146,71.42857142857143,42.857142857142854,0.9997084227495041\n416,92.30769574642181,97.25274725274726,87.36263736263736,0.7506304530237441,53.57142857142857,64.28571428571429,42.857142857142854,0.9985832522178227\n448,92.5824210313814,97.25274725274724,87.9120879120879,0.7352956188089965,53.57142857142857,64.28571428571429,42.857142857142854,0.9968082632009411\n480,93.13187160130057,97.25274725274726,89.010989010989,0.7204149906047868,53.57142857142857,64.28571428571429,42.857142857142854,0.9965770713724125\n512,93.40659688626017,97.25274725274724,89.56043956043956,0.7060286237591064,57.142857142857146,64.28571428571429,50.0,0.9957834990015566\n544,93.40659688626017,97.25274725274724,89.56043956043956,0.6919458740309858,57.142857142857146,64.28571428571429,50.0,0.9984296529378182\n576,93.68132217121976,97.25274725274726,90.1098901098901,0.6785377600422074,57.142857142857146,64.28571428571429,50.0,1.0009971071441892\n608,93.68132217121976,96.70329670329672,90.65934065934066,0.6655857760481575,64.28571428571429,57.142857142857146,71.42857142857143,0.966618726160825\n640,93.95604745617935,97.25274725274726,90.65934065934064,0.6530428635256289,57.142857142857146,57.142857142857146,57.142857142857146,0.9989855242657754\n672,94.23077274113894,97.25274725274724,91.20879120879121,0.6410200189686145,60.714285714285715,57.142857142857146,64.28571428571429,1.002178738400748\n704,93.95604745617935,97.25274725274726,90.65934065934064,0.6294766597079416,60.714285714285715,57.142857142857146,64.28571428571429,1.004734253893208\n736,94.23077274113894,97.25274725274724,91.20879120879121,0.6181324745095693,64.28571428571429,57.142857142857146,71.42857142857143,0.9821739215487931\n768,95.0549485960177,97.80219780219781,92.3076923076923,0.6070587051300939,64.28571428571429,57.142857142857146,71.42857142857143,0.9700133339767305\n800,95.0549485960177,97.80219780219781,92.3076923076923,0.5962523185995457,64.28571428571429,57.142857142857146,71.42857142857143,0.9703092249442438\n832,94.78022331105811,97.25274725274726,92.3076923076923,0.5858770288182199,64.28571428571429,50.0,78.57142857142857,0.9919944967660701\n864,95.3296738809773,97.25274725274726,93.4065934065934,0.5755775219818444,67.85714285714286,57.142857142857146,78.57142857142857,0.9780689145963589\n896,95.3296738809773,97.25274725274726,93.4065934065934,0.5656879074719912,67.85714285714286,57.142857142857146,78.57142857142857,0.9764508297013126\n928,95.3296738809773,97.25274725274724,93.40659340659342,0.5559427401892524,60.714285714285715,50.0,71.42857142857143,1.0121962773878648\n960,95.3296738809773,97.25274725274724,93.4065934065934,0.5466123558863033,60.714285714285715,50.0,71.42857142857143,1.0164603980954958\n992,95.60439916593688,97.25274725274726,93.95604395604396,0.5374986408841845,60.714285714285715,50.0,71.42857142857143,1.0150157685089352\n1024,95.60439916593688,97.25274725274726,93.95604395604396,0.5287220296055044,60.714285714285715,50.0,71.42857142857143,1.0190886667509313\n1056,95.87912445089647,97.25274725274724,94.50549450549453,0.5201257157404621,60.714285714285715,50.0,71.42857142857143,1.020774235656863\n1088,95.87912445089647,97.25274725274724,94.50549450549453,0.5117593226460525,60.714285714285715,50.0,71.42857142857143,1.0243199707118837\n1120,96.15384973585606,97.25274725274724,95.05494505494507,0.5036681645608095,60.714285714285715,50.0,71.42857142857143,1.028799671718467\n1152,96.70330030577523,97.25274725274728,96.15384615384616,0.4957527739839653,60.714285714285715,50.0,71.42857142857143,1.0310785068217228\n1184,96.70330030577523,97.25274725274724,96.15384615384616,0.4880586901656048,60.714285714285715,50.0,71.42857142857143,1.0347101259192926\n1216,96.70330030577523,97.25274725274724,96.15384615384616,0.4805858955148957,60.714285714285715,50.0,71.42857142857143,1.0951665519770672\n1248,96.70330030577523,97.25274725274724,96.15384615384616,0.4732428644031068,60.714285714285715,50.0,71.42857142857143,1.1012568918721952\n1280,96.70330030577523,97.25274725274726,96.15384615384616,0.46607263096878004,60.714285714285715,50.0,71.42857142857143,1.1063644282439575\n1312,96.97802559073482,97.25274725274724,96.70329670329672,0.4591182290886128,60.714285714285715,50.0,71.42857142857143,1.1112164674602203\n1344,96.70330030577523,97.25274725274724,96.15384615384617,0.45228862931132746,60.714285714285715,50.0,71.42857142857143,1.1157842074243587\n1376,96.70330030577523,96.70329670329672,96.7032967032967,0.44560730293788614,57.142857142857146,50.0,64.28571428571429,1.1339305413141858\n1408,96.97802559073482,96.70329670329672,97.25274725274724,0.4389851200646443,57.142857142857146,50.0,64.28571428571429,1.1379203740435273\n1440,96.97802559073482,96.7032967032967,97.25274725274724,0.43262298529223714,57.142857142857146,50.0,64.28571428571429,1.1432987096084548\n1472,96.97802559073482,96.7032967032967,97.25274725274726,0.42645455632203433,57.142857142857146,50.0,64.28571428571429,1.149274070056317\n1504,96.97802559073482,96.7032967032967,97.25274725274726,0.4203795525202317,57.142857142857146,50.0,64.28571428571429,1.1531467526418369\n1536,97.527476160654,97.25274725274726,97.8021978021978,0.4143302027935524,64.28571428571429,57.142857142857146,71.42857142857143,1.0965169041653244\n1568,97.527476160654,97.25274725274724,97.80219780219782,0.4085315596017578,64.28571428571429,57.142857142857146,71.42857142857143,1.099552076753183\n1600,97.527476160654,97.25274725274726,97.8021978021978,0.4027627966429136,64.28571428571429,57.142857142857146,71.42857142857143,1.1035399510554709\n1632,97.527476160654,97.25274725274726,97.80219780219781,0.39715910964840717,64.28571428571429,57.142857142857146,71.42857142857143,1.1076057338793257\n1664,97.527476160654,97.25274725274726,97.80219780219781,0.3916676718371987,60.714285714285715,57.142857142857146,64.28571428571429,1.1153264517957375\n1696,97.80220144561359,97.25274725274724,98.35164835164836,0.3863043223430614,57.142857142857146,50.0,64.28571428571429,1.1683701116177723\n1728,97.80220144561359,97.25274725274726,98.35164835164836,0.3807211139391626,60.714285714285715,50.0,71.42857142857143,1.1649994934059165\n1760,97.80220144561359,97.25274725274726,98.35164835164836,0.3755378570378185,57.142857142857146,50.0,64.28571428571429,1.170103099601716\n1792,97.80220144561359,97.25274725274724,98.35164835164836,0.3704457807837788,60.714285714285715,50.0,71.42857142857143,1.1749594710463769\n1824,97.80220144561359,97.25274725274728,98.35164835164835,0.3654243267467638,60.714285714285715,50.0,71.42857142857143,1.182162186613202\n1856,97.80220144561359,97.25274725274726,98.35164835164836,0.36060164181660326,60.714285714285715,50.0,71.42857142857143,1.1861205191681812\n1888,97.80220144561359,97.25274725274724,98.35164835164835,0.35578458048460293,57.142857142857146,50.0,64.28571428571429,1.1918098529497847\n1920,98.07692673057318,97.25274725274724,98.9010989010989,0.3511148095241527,60.714285714285715,50.0,71.42857142857143,1.1982332768482074\n1952,98.07692673057318,97.25274725274724,98.9010989010989,0.34656422278027804,57.142857142857146,50.0,64.28571428571429,1.2036779535085558\n1984,98.07692673057318,97.25274725274726,98.9010989010989,0.3420026787128994,57.142857142857146,50.0,64.28571428571429,1.210345241952746\n2016,98.07692673057318,97.25274725274726,98.9010989010989,0.3376371374489987,60.714285714285715,50.0,71.42857142857143,1.2159515102316953\n"
  },
  {
    "path": "colorectal-cancer/report.py",
    "content": "#!/usr/bin/env python3\r\n##########################################################################################\r\n# Author: Jared L. Ostmeyer\r\n# Date Started: 2018-02-05\r\n# Purpose: Print results of the holdout cross-validation\r\n##########################################################################################\r\n\r\n##########################################################################################\r\n# Libraries\r\n##########################################################################################\r\n\r\nimport glob\r\nimport csv\r\nfrom scipy.special import xlogy\r\nimport numpy as np\r\n\r\n##########################################################################################\r\n# Load data\r\n##########################################################################################\r\n\r\ncosts_train = {}\r\naccuracies_train = {}\r\ntprs_train = {}\r\nfprs_train = {}\r\nfor path in glob.glob('bin/*_ps_train.csv'):\r\n  with open(path, 'r') as stream:\r\n    reader = csv.DictReader(stream)\r\n    costs = []\r\n    accuracies = []\r\n    tprs = []\r\n    fprs = []\r\n    for row in reader:\r\n      label = float(row['Label'])\r\n      weight = float(row['Weight'])\r\n      prediction = float(row['Prediction'])\r\n      costs.append(\r\n        weight*(-xlogy(label, prediction)-xlogy(1.0-label, 1.0-prediction))/np.log(2.0)\r\n      )\r\n      accuracies.append(\r\n        100.0*weight*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n      )\r\n      if label == 1.0:\r\n        tprs.append(\r\n          100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n        )\r\n      elif label == 0.0:\r\n        fprs.append(\r\n          100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n        )\r\n      else:\r\n        print('ERROR: Unrecognized value in the label.')\r\n        exit()\r\n  filename = path.split('/')[-1].split('.')[0]\r\n  _, step, _, _ = filename.split('_')\r\n  i = int(step)\r\n  if i not in costs_train:\r\n    costs_train[i] = []\r\n  costs_train[i].append(\r\n    np.sum(costs)\r\n  )\r\n  if i not in accuracies_train:\r\n    accuracies_train[i] = []\r\n  accuracies_train[i].append(\r\n    np.sum(accuracies)\r\n  )\r\n  if len(tprs) > 0:\r\n    if i not in tprs_train:\r\n      tprs_train[i] = []\r\n    tprs_train[i].append(\r\n      np.mean(tprs)\r\n    )\r\n  if len(fprs) > 0:\r\n    if i not in fprs_train:\r\n      fprs_train[i] = []\r\n    fprs_train[i].append(\r\n      np.mean(fprs)\r\n    )\r\n\r\ncosts_val = {}\r\naccuracies_val = {}\r\ntprs_val = {}\r\nfprs_val = {}\r\nfor path in glob.glob('bin/*_ps_val.csv'):\r\n  with open(path, 'r') as stream:\r\n    reader = csv.DictReader(stream)\r\n    costs = []\r\n    accuracies = []\r\n    tprs = []\r\n    fprs = []\r\n    for row in reader:\r\n      label = float(row['Label'])\r\n      weight = float(row['Weight'])\r\n      prediction = float(row['Prediction'])\r\n      costs.append(\r\n        weight*(-xlogy(label, prediction)-xlogy(1.0-label, 1.0-prediction))/np.log(2.0)\r\n      )\r\n      accuracies.append(\r\n        100.0*weight*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n      )\r\n      if label == 1.0:\r\n        tprs.append(\r\n          100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n        )\r\n      elif label == 0.0:\r\n        fprs.append(\r\n          100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n        )\r\n      else:\r\n        print('ERROR: Unrecognized value in the label.')\r\n        exit()\r\n  filename = path.split('/')[-1].split('.')[0]\r\n  _, step, _, _ = filename.split('_')\r\n  i = int(step)\r\n  if i not in costs_val:\r\n    costs_val[i] = []\r\n  costs_val[i].append(\r\n    np.sum(costs)\r\n  )\r\n  if i not in accuracies_val:\r\n    accuracies_val[i] = []\r\n  accuracies_val[i].append(\r\n    np.sum(accuracies)\r\n  )\r\n  if len(tprs) > 0:\r\n    if i not in tprs_val:\r\n      tprs_val[i] = []\r\n    tprs_val[i].append(\r\n      np.mean(tprs)\r\n    )\r\n  if len(fprs) > 0:\r\n    if i not in fprs_val:\r\n      fprs_val[i] = []\r\n    fprs_val[i].append(\r\n      np.mean(fprs)\r\n    )\r\n\r\n##########################################################################################\r\n# Results\r\n##########################################################################################\r\n\r\nprint(\r\n  'Step',\r\n  'Accuracy_Train', 'TRP_Train', 'FPR_Train', 'Cost_train',\r\n  'Accuracy_Val', 'TRP_Val', 'FPR_Val', 'Cost_Val',\r\n  sep=','\r\n)\r\nfor i in sorted(accuracies_train.keys()):\r\n  print(\r\n    i,\r\n    np.mean(accuracies_train[i]), np.mean(tprs_train[i]), np.mean(fprs_train[i]), np.mean(costs_train[i]),\r\n    np.mean(accuracies_val[i]), np.mean(tprs_val[i]), np.mean(fprs_val[i]), np.mean(costs_val[i]),\r\n    sep=','\r\n  )\r\n"
  },
  {
    "path": "colorectal-cancer/train_val.py",
    "content": "#!/usr/bin/env python3\n##########################################################################################\n# Author: Jared L. Ostmeyer\n# Date Started: 2021-11-16\n# Purpose: Train and validate a classifier for immune repertoires\n##########################################################################################\n\n##########################################################################################\n# Libraries\n##########################################################################################\n\nimport argparse\nimport csv\nimport glob\nimport dataplumbing as dp\nimport dataset as ds\nimport numpy as np\nimport torch\n\n##########################################################################################\n# Arguments\n##########################################################################################\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--holdouts', help='Holdout samples', type=str, nargs='+', required=True)\nparser.add_argument('--restart', help='Basename for restart files', type=str, default=None)\nparser.add_argument('--output', help='Basename for output files', type=str, required=True)\nparser.add_argument('--seed', help='Seed value for randomly initializing fits', type=int, default=1)\nparser.add_argument('--device', help='Examples are cuda:0 or cpu', type=str, default='cuda:0')\nparser.add_argument('--num_fits', help='Number of fits to the training data', type=int, default=2**17)\nargs = parser.parse_args()\n\n##########################################################################################\n# Assemble sequences\n##########################################################################################\n\n# Settings\n#\ntrim_front = 3\ntrim_rear = 3\n\nkmer_size = 4\n\n# To hold sequences from each subject\n#\ncases = {}\ncontrols = {}\n\n# Load immune repertoires\n#\nfor path in glob.glob('dataset/*.tsv'):\n  sample = path.split('/')[-1].split('.')[0]\n  subject, label = sample.split('_')\n  cdr3s = dp.load_cdr3s(path, min_length=kmer_size+trim_front+trim_rear, max_length=32)\n  cdr3s = dp.trim_cdr3s(cdr3s, trim_front=trim_front, trim_rear=trim_rear)\n  kmers = dp.cdr3s_to_kmers(cdr3s, kmer_size)\n  kmers = dp.normalize_sample(kmers)\n  if 'Tumor' in label:\n    cases[subject] = kmers\n  elif 'Mucosa' in label:\n    controls[subject] = kmers\n\n##########################################################################################\n# Assemble datasets\n##########################################################################################\n\n# Load embeddings\n#\naminoacids_dict = ds.load_aminoacid_embedding_dict('../aminoacid-representation/atchley_factors_normalized.csv')\n\n# Convert to numeric representations\n#\nsamples = ds.assemble_samples(cases, controls, aminoacids_dict)\n\n# Split into a training and validation cohort\n#\nsamples_train, samples_val = ds.split_samples(samples, args.holdouts)\n\n# Weight samples\n#\nsamples_train = ds.weight_samples(samples_train)\nsamples_val = ds.weight_samples(samples_val)\n\n# Normalize features\n#\nsamples_train, samples_val = ds.normalize_samples(samples_train, samples_val)\n\n##########################################################################################\n# Assemble tensors\n##########################################################################################\n\n# Settings\n#\ndevice = torch.device(args.device)\n\n# Convert numpy arrays to pytorch tensors\n#\nfor sample in samples_train:\n  sample['features'] = torch.from_numpy(sample['features']).to(device)\n  sample['label'] = torch.tensor(sample['label']).to(device)\n  sample['weight'] = torch.tensor(sample['weight']).to(device)\n\n# Convert numpy arrays to pytorch tensors\n#\nfor sample in samples_val:\n  sample['features'] = torch.from_numpy(sample['features']).to(device)\n  sample['label'] = torch.tensor(sample['label']).to(device)\n  sample['weight'] = torch.tensor(sample['weight']).to(device)\n\n##########################################################################################\n# Model\n##########################################################################################\n\n# Settings\n#\nnum_features = samples_train[0]['features'].shape[1]\nnum_fits = args.num_fits\n\ntorch.manual_seed(args.seed)\n\n# Function for initializing the weights of the model\n#\ndef init_weights():\n  return torch.cat(\n    [\n      0.5**0.5*torch.rand([ num_features-1, num_fits ])/(num_features-1.0)**0.5,  # Weights for the Atchley factors\n      0.5**0.5*torch.rand([ 1, num_fits ])/(1.0)**0.5,  # Weight for the abundance term\n    ],\n    0\n  )\n\n# Class defining the model\n#\nclass MaxSnippetModel(torch.nn.Module):\n  def __init__(self):\n    super(MaxSnippetModel, self).__init__()\n    self.linear = torch.nn.Linear(num_features, num_fits)\n    with torch.no_grad():\n      self.linear.weights = init_weights()  # Initialize the weights\n  def forward(self, x):\n    ls = self.linear(x)\n    ms, _ = torch.max(ls, axis=0)\n    return ms\n\n# Instantiation of the model\n#\nmsm = MaxSnippetModel()\n\n# Turn on GPU acceleration\n#\nmsm.to(device)\n\n##########################################################################################\n# Metrics and optimization\n##########################################################################################\n\n# Settings\n#\nlearning_rate = 0.01\n\n# Optimizer\n#\noptimizer = torch.optim.Adam(msm.parameters(), lr=learning_rate)  # Adam is based on gradient descent but better\n\n# Metrics\n#\nloss = torch.nn.BCEWithLogitsLoss(reduction='none')  # The loss function is calculated seperately for each fit by setting reduction to none\n\ndef accuracy(ls_block, ys_block):  # The binary accuracy is calculated seperate for each fit\n  a = torch.nn.Sigmoid()\n  ps_block = a(ls_block)\n  cs_block = (torch.round(ps_block) == torch.round(ys_block)).to(ys_block.dtype)\n  return cs_block\n\n##########################################################################################\n# Fit and evaluate model\n##########################################################################################\n\n# Settings\n#\nnum_epochs = 2048\n\n# Restore saved models\n#\nif args.restart is not None:\n  msm = torch.load(args.output+'_model.p')\n\n# Each iteration represents one batch\n#\nfor epoch in range(0, num_epochs):\n\n  # Reset the gradients\n  #\n  optimizer.zero_grad()\n\n  es_train = 0.0  # Cross-entropy error\n  as_train = 0.0  # Accuracy\n\n  for sample in samples_train:\n\n    xs_block = sample['features']\n    ys_block = torch.tile(sample['label'], [ num_fits ])\n    w_block = sample['weight']\n\n    ls_block = msm(xs_block)\n    sample['predictions'] = torch.sigmoid(ls_block)\n\n    es_block = w_block*loss(ls_block, ys_block)  # The loss function is calculated seperately for each fit\n    as_block = w_block*accuracy(ls_block, ys_block)  # The binary accuracy is calculated seperate for each fit\n\n    es_train += es_block.detach()\n    as_train += as_block.detach()\n\n    e_block = torch.sum(es_block)\n    e_block.backward()\n\n  i_bestfit = torch.argmin(es_train)  # Very important index selects the best fit to the training data\n\n  es_val = 0.0\n  as_val = 0.0\n\n  with torch.no_grad():\n\n    for sample in samples_val:\n\n      xs_block = sample['features']\n      ys_block = torch.tile(sample['label'], [ num_fits ])\n      w_block = sample['weight']\n\n      ls_block = msm(xs_block)\n      sample['predictions'] = torch.sigmoid(ls_block)\n\n      es_block = w_block*loss(ls_block, ys_block)  # The loss function is calculated seperately for each fit\n      as_block = w_block*accuracy(ls_block, ys_block)  # The binary accuracy is calculated seperate for each fit\n\n      es_val += es_block.detach()\n      as_val += as_block.detach()\n\n  # Print report\n  #\n  print(\n    'Epoch:', epoch,\n    'Accuracy (train):', round(100.0*float(as_train[i_bestfit]), 2), '%',\n    'Accuracy (val):', round(100.0*float(as_val[i_bestfit]), 2), '%',\n    flush=True\n  )\n\n  # Save parameters and results from the best fit to the training data\n  #\n  if epoch%32 == 0:\n    ws = msm.linear.weights.detach().numpy()\n    bs = msm.linear.bias.cpu().detach().numpy()\n    np.savetxt(args.output+'_'+str(epoch)+'_ws.csv', ws[:,i_bestfit])\n    np.savetxt(args.output+'_'+str(epoch)+'_b.csv', bs[[i_bestfit.cpu()]])\n    with open(args.output+'_'+str(epoch)+'_ms_train.csv', 'w') as stream:\n      print('Cross Entropy (bits)', 'Accuracy (%)', sep=',', file=stream)\n      print(float(es_train[i_bestfit])/np.log(2.0), 100.0*float(as_train[i_bestfit]), sep=',', file=stream)\n    with open(args.output+'_'+str(epoch)+'_ms_val.csv', 'w') as stream:\n      print('Cross Entropy (bits)', 'Accuracy (%)', sep=',', file=stream)\n      print(float(es_val[i_bestfit])/np.log(2.0), 100.0*float(as_val[i_bestfit]), sep=',', file=stream)\n    with open(args.output+'_'+str(epoch)+'_ps_train.csv', 'w') as stream:\n      print('Subject', 'Label', 'Weight', 'Prediction', sep=',', file=stream)\n      for sample in samples_train:\n        print(sample['subject'], float(sample['label']), float(sample['weight']), float(sample['predictions'][i_bestfit]), sep=',', file=stream)\n    with open(args.output+'_'+str(epoch)+'_ps_val.csv', 'w') as stream:\n      print('Subject', 'Label', 'Weight', 'Prediction', sep=',', file=stream)\n      for sample in samples_val:\n        print(sample['subject'], float(sample['label']), float(sample['weight']), float(sample['predictions'][i_bestfit]), sep=',', file=stream)\n\n  optimizer.step()\n\ntorch.save(msm, args.output+'_model.p')\n"
  },
  {
    "path": "ovarian-cancer/README.md",
    "content": "# Instructions\nThis example demonstrates the application of our method to distinguish between normal and malignant ovarian tissue. Each tissue sample in the dataset is obtained from a different individual.\n\n## Dataset\nT cell receptor sequences from 20 ovarian tissue samples are located in the dataset folder. The samples are evenly split, with half from normal tissue and half from malignant tissue. To extract the data, use the following commands.\n```\ncd dataset\nunzip '*.zip'\ncd ../\n```\n\n## Modeling\nThis model employs snippets from T cell receptor sequences in ovarian tissue samples to classify the tissue as either normal or malignant. It is trained on data from numerous individuals, and its performance is assessed using a patient-holdout cross-validation approach. During this process, data from one individual is withheld while fitting the model. Subsequently, the model's performance is evaluated on the withheld individual, who was not used during the fitting. This procedure is repeated for each individual in the dataset, requiring the model to be retrained each time. To execute the cross-validation, use the following commands, assuming the model is run on a CUDA-enabled GPU with a minimum of 11GB memory.\n```\nmkdir -p bin\npython3 train_val.py --seed 1 --holdouts O-10M --output bin/1\npython3 train_val.py --seed 1 --holdouts O-10N --output bin/2\npython3 train_val.py --seed 1 --holdouts O-1M --output bin/3\npython3 train_val.py --seed 1 --holdouts O-1N --output bin/4\npython3 train_val.py --seed 1 --holdouts O-2M --output bin/5\npython3 train_val.py --seed 1 --holdouts O-2N --output bin/6\npython3 train_val.py --seed 1 --holdouts O-3M --output bin/7\npython3 train_val.py --seed 1 --holdouts O-3N --output bin/8\npython3 train_val.py --seed 1 --holdouts O-4M --output bin/9\npython3 train_val.py --seed 1 --holdouts O-4N --output bin/10\npython3 train_val.py --seed 1 --holdouts O-5M --output bin/11\npython3 train_val.py --seed 1 --holdouts O-5N --output bin/12\npython3 train_val.py --seed 1 --holdouts O-6M --output bin/13\npython3 train_val.py --seed 1 --holdouts O-6N --output bin/14\npython3 train_val.py --seed 1 --holdouts O-7M --output bin/15\npython3 train_val.py --seed 1 --holdouts O-7N --output bin/16\npython3 train_val.py --seed 1 --holdouts O-8M --output bin/17\npython3 train_val.py --seed 1 --holdouts O-8N --output bin/18\npython3 train_val.py --seed 1 --holdouts O-9M --output bin/19\npython3 train_val.py --seed 1 --holdouts O-9N --output bin/20\n```\nThe first flag --seed sets the seed value for generating the initial weight guesses. The second flag --holdouts specifies the sample to withhold during validation. The third flag --output defines the prefix for the filenames saved throughout the fitting process. Additional flags include --num_fits, which determines the number of attempts to find the global best fit for the training data, and --device, which allows you to select either gpu or cpu for processing.\n\n## How does this differ from the other examples in this repository?\nThis model incorporates a gap feature within the snippet, which has been found to enhance performance for this dataset. Gaps, derived from sequence alignment algorithms, allow for spaces between individual amino acid residues. The gap implementation can be found in dataplumbing.py on line 71 and is utilized on line 58 in train_val.py. The motif_size value defines the number of amino acid residues in the snippet, while the difference between window_size and motif_size determines the number of gaps present.\n\n## Evaluation\nThe results are stored in a CSV file that can be opened by your favorite spreadsheet viewer. There are nine columns that represent:\n```\npython3 report.py > report.csv\n```\nThe results are stored in a CSV file that can be opened by your favorite spreadsheet viewer. There are nine columns that represent:\n1.\tThe training step.\n2.\tThe accuracy on the training data averaged over the cross-validation.\n3.\tThe true negative rate (specificity) on the training data averaged over the cross-validation.\n4.\tThe true positive rate (sensitivity) on the training data averaged over the cross-validation.\n5.\tThe cross-entropy on the training data averaged over the cross-validation.\n6.\tThe accuracy on the holdout data averaged over the cross-validation.\n7.\tThe true negative rate (specificity) on the holdout data averaged over the cross-validation.\n8.\tThe true positive rate (sensitivity) on the holdout data averaged over the cross-validation.\n9.\tThe cross-entropy on the holdout data averaged over the cross-validation.\n\n## Publication\n* [Ovarian Cancer](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7058380/)\n"
  },
  {
    "path": "ovarian-cancer/dataplumbing.py",
    "content": "#########################################################################################\n# Author: Jared L. Ostmeyer\n# Date Started: 2021-11-16\n# Environment: Python3\n# Purpose: Utilities for loading immune receptor sequences\n##########################################################################################\n\n##########################################################################################\n# Libraries\n##########################################################################################\n\nimport csv\nfrom itertools import combinations\n\n##########################################################################################\n# Utilities\n##########################################################################################\n\ndef load_cdr3s(path_tsv, min_length=4, max_length=32, version='v2'):\n  receptors = {}\n  with open(path_tsv, 'r') as stream:\n    reader = csv.DictReader(stream, delimiter='\\t')\n    for row in reader:\n      if version == 'v2':\n        cdr3 = row['aminoAcid']\n#        quantity = float(row['frequencyCount (%)'])\n        quantity = float(row['count (templates/reads)'])\n        status = row['sequenceStatus']\n      elif version == 'v3':\n        cdr3 = row['amino_acid']\n#        quantity = float(row['frequency'])\n        quantity = float(row['templates'])\n        status = row['frame_type']\n      else:\n        print('ERROR: Unsupported version')\n        exit()\n      if 'In' in status and min_length <= len(cdr3) and len(cdr3) <= max_length and quantity > 0.0 and 'X' not in cdr3:\n        if cdr3 not in receptors:\n          receptors[cdr3] = quantity\n        else:\n          receptors[cdr3] += quantity\n  return receptors\n\ndef trim_cdr3s(receptors, trim_front=0, trim_rear=0):\n  cdr3s = {}\n  for cdr3, quantity in receptors.items():\n    cdr3_trim = cdr3[trim_front:]\n    if trim_rear > 0:\n      cdr3_trim = cdr3_trim[:-trim_rear]\n    if len(cdr3_trim) > 0:\n      if cdr3_trim not in cdr3s:\n        cdr3s[cdr3_trim] = quantity\n      else:\n        cdr3s[cdr3_trim] += quantity\n  return cdr3s\n\ndef cdr3s_to_kmers(cdr3s, kmer_size):\n  kmers = {}\n  for cdr3, quantity in cdr3s.items():\n    if len(cdr3) >= kmer_size:\n      for i in range(len(cdr3)-kmer_size+1):\n        kmer = cdr3[i:i+kmer_size]\n        if kmer not in kmers:\n          kmers[kmer] = quantity\n        else:\n          kmers[kmer] += quantity\n  return kmers\n\ndef cdr3s_to_motifs(cdr3s, window_size, motif_size):\n  templates = []\n  for template in list(combinations(range(window_size), motif_size)):\n    if template[0] == 0:\n      templates.append(template)\n  motifs = {}\n  for cdr3, quantity in cdr3s.items():\n    if len(cdr3) >= motif_size:\n      for i in range(len(cdr3)-motif_size+1):\n        window = cdr3[i:i+window_size]\n        for template in templates:\n          if template[-1] < len(window):\n            motif = ''\n            for i in template:\n              motif += window[i]\n            if motif not in motifs:\n              motifs[motif] = quantity\n            else:\n              motifs[motif] += quantity\n  return motifs\n\ndef flatten_sample(sequences):\n  return { sequence: 1.0 for sequence in sequences.keys() }\n\ndef normalize_sample(sequences):\n  total = 0.0\n  for quantity in sorted(sequences.values()):\n    total += quantity\n  sequences_ = {}\n  for sequence, quantity in sequences.items():\n    sequences_[sequence] = quantity/total\n  return sequences_\n\ndef merge_samples(samples):\n  sequences = {}\n  for sample in samples:\n    for sequence, quantity in sample.items():\n      if sequence not in sequences:\n        sequences[sequence] = quantity/float(len(samples))\n      else:\n        sequences[sequence] += quantity/float(len(samples))\n  return sequences\n\ndef debug_insert_sequence(receptors, sequence, count):\n  if sequence not in receptors:\n    receptors[sequence] = count\n  else:\n    receptors[sequence] += count\n  return receptors\n"
  },
  {
    "path": "ovarian-cancer/dataset.py",
    "content": "#########################################################################################\n# Author: Jared L. Ostmeyer\n# Date Started: 2021-11-16\n# Environment: Python3\n# Purpose: Utilities for converting immune receptor sequences into numeric features\n##########################################################################################\n\n##########################################################################################\n# Libraries\n##########################################################################################\n\nimport csv\nimport numpy as np\n\n##########################################################################################\n# Utilities\n##########################################################################################\n\ndef load_aminoacid_embedding_dict(path_embedding):\n\n  # Amino acid factors\n  #\n  names = []\n  factors = []\n  with open(path_embedding, 'r') as stream:\n    for line in stream:\n      rows = line.split(',')\n      names.append(rows[0])\n      factors.append(np.array(rows[1:], dtype=np.float32))\n  names = np.array(names)\n  factors = np.array(factors)\n\n  # Convert into a dictionary\n  #\n  aminoacids_dict = { name: factors[i,:] for i, name in enumerate(names) }\n\n  return aminoacids_dict\n\ndef assemble_samples(cases, controls, aminoacids_dict):\n\n  # Determine tensor dimensions \n  #\n  max_steps = -1\n  for sequences in cases.values():\n    for sequence in sequences.keys():\n      if len(sequence) > max_steps:\n        max_steps = len(sequence)\n  for sequences in controls.values():\n    for sequence in sequences.keys():\n      if len(sequence) > max_steps:\n        max_steps = len(sequence)\n  num_factors = len(list(aminoacids_dict.values())[0])\n\n  # Assemble dataset\n  #\n  samples = []\n\n  for subject in sorted(cases.keys()):\n\n    sequences = cases[subject]\n\n    # Initialize tensors\n    #\n    xs = np.zeros([ len(sequences), max_steps*num_factors+1 ], dtype=np.float32)\n\n    # Fill tensors\n    #\n    for i, ( sequence, quantity ) in enumerate(sorted(sequences.items())):\n      for j, aa in enumerate(sequence):\n        xs[i,num_factors*j:num_factors*(j+1)] = aminoacids_dict[aa]\n      xs[i,-1] = np.log(quantity)\n\n    u = np.mean(xs[:,-1])\n    v = np.var(xs[:,-1])\n    xs[:,-1] = (xs[:,-1]-u)/np.sqrt(v)\n\n    samples.append(\n      {\n        'subject': subject,\n        'features': xs,\n        'label': 1.0\n      }\n    )\n\n  for subject in sorted(controls.keys()):\n\n    sequences = controls[subject]\n\n    # Initialize tensors\n    #\n    xs = np.zeros([ len(sequences), max_steps*num_factors+1 ], dtype=np.float32)\n\n    # Fill tensors\n    #\n    for i, ( sequence, quantity ) in enumerate(sorted(sequences.items())):\n      for j, aa in enumerate(sequence):\n        xs[i,num_factors*j:num_factors*(j+1)] = aminoacids_dict[aa]\n      xs[i,-1] = np.log(quantity)\n\n    u = np.mean(xs[:,-1])\n    v = np.var(xs[:,-1])\n    xs[:,-1] = (xs[:,-1]-u)/np.sqrt(v)\n\n    samples.append(\n      {\n        'subject': subject,\n        'features': xs,\n        'label': 0.0\n      }\n    )\n\n  return samples\n\ndef split_samples(samples, holdouts):\n  samples_train = []\n  samples_val = []\n  for sample in samples:\n    if sample['subject'] not in holdouts:\n      samples_train.append(sample)\n    else:\n      samples_val.append(sample)\n  return samples_train, samples_val\n\ndef weight_samples(samples):\n  num_case = 0\n  num_control = 0\n  for sample in samples:\n    if sample['label'] > 0.5:\n      num_case += 1\n    else:\n      num_control += 1\n  for sample in samples:\n    if sample['label'] > 0.5:\n      sample['weight'] = 0.5/num_case if num_control > 0 else 1.0/num_case\n    else:\n      sample['weight'] = 0.5/num_control if num_case > 0 else 1.0/num_control\n  return samples\n\ndef normalize_samples(samples_train, samples_holdout):\n\n  # Calculate normalization statistics from the training samples\n  #\n  us = 0.0\n  us2 = 0.0\n  for sample in samples_train:\n    xs_sample = sample['features']\n    us_sample = np.mean(xs_sample, axis=0)\n    us2_sample = np.mean(xs_sample**2, axis=0)\n    us += sample['weight']*us_sample\n    us2 += sample['weight']*us2_sample\n  vs = us2-us**2\n\n  # Normalize the training samples\n  #\n  for sample in samples_train:\n    xs_sample = sample['features']\n    xs_sample = (xs_sample-us)/np.sqrt(vs)\n    sample['features'] = xs_sample\n\n  # Normalize the holdout samples\n  #\n  for sample in samples_holdout:\n    xs_sample = sample['features']\n    xs_sample = (xs_sample-us)/np.sqrt(vs)\n    sample['features'] = xs_sample\n\n  return samples_train, samples_holdout\n    \ndef debug_permute_labels(samples):\n  labels = []\n  for sample in samples:\n    labels.append(sample['label'])\n  np.random.shuffle(labels)\n  for sample, label in zip(samples, labels):\n    sample['label'] = label\n  return samples\n"
  },
  {
    "path": "ovarian-cancer/gold.report.csv",
    "content": "Step,Accuracy_Train,TRP_Train,FPR_Train,Cost_train,Accuracy_Val,TRP_Val,FPR_Val,Cost_Val\n0,50.000000558793545,100.0,0.0,1.0365936592801854,50.0,100.0,0.0,1.053734415443118\n32,50.000000558793545,100.0,0.0,0.9457275844220987,50.0,100.0,0.0,0.9521947011631451\n64,51.86111168935895,100.0,3.7222222222222223,0.9173581467213623,50.0,100.0,0.0,0.9362032431566807\n96,61.333334017544985,100.0,22.666666666666668,0.8897864747897849,55.0,100.0,10.0,0.9138892262835843\n128,73.25000081211329,100.0,46.5,0.8622117969742218,60.0,100.0,20.0,0.8933784246978418\n160,86.38888984918594,100.0,72.77777777777779,0.8349512024155757,80.0,100.0,60.0,0.869854996615784\n192,93.9166677184403,100.0,87.83333333333333,0.8079039280915398,80.0,100.0,60.0,0.8469194746369686\n224,95.25000106543303,100.0,90.5,0.7816135581196335,80.0,90.0,70.0,0.8275820896617134\n256,95.25000106543303,100.0,90.49999999999999,0.7567312342808346,80.0,90.0,70.0,0.8071864255777736\n288,95.52777884528041,100.0,91.05555555555556,0.7328786795241862,85.0,90.0,80.0,0.7887767919786073\n320,95.52777884528041,100.0,91.05555555555557,0.7098933654731956,85.0,90.0,80.0,0.7689075815972282\n352,96.63888996466994,100.0,93.27777777777779,0.6879672937503374,85.0,90.0,80.0,0.7519116439578173\n384,97.38888997584581,100.0,94.77777777777779,0.6670572165352502,90.0,100.0,80.0,0.7267877282394819\n416,98.94444555044174,100.0,97.88888888888889,0.6470529204055335,90.0,100.0,80.0,0.707885453170132\n448,99.7222233377397,100.0,99.44444444444444,0.6278908228197596,95.0,100.0,90.0,0.6905346270594236\n480,100.00000111758709,100.0,100.0,0.6096233055829081,95.0,100.0,90.0,0.6781916343268548\n512,100.00000111758709,100.0,100.0,0.5920660224461953,95.0,100.0,90.0,0.6640477000409764\n544,100.00000111758709,100.0,100.0,0.5753083104294501,95.0,100.0,90.0,0.6503199255223708\n576,100.00000111758709,100.0,100.0,0.5589253495562464,95.0,100.0,90.0,0.6366496359304342\n608,100.00000111758709,100.0,100.0,0.5432534700153104,95.0,100.0,90.0,0.6244075318577076\n640,100.00000111758709,100.0,100.0,0.5282158401170938,95.0,100.0,90.0,0.6128997276029248\n672,100.00000111758709,100.0,100.0,0.5138654622392067,90.0,90.0,90.0,0.6017583106087383\n704,100.00000111758709,100.0,100.0,0.5000623705611038,90.0,90.0,90.0,0.590825447223445\n736,100.00000111758709,100.0,100.0,0.48684374270568787,95.0,90.0,100.0,0.5782254056093944\n768,100.00000111758709,100.0,100.0,0.4741169244519874,95.0,90.0,100.0,0.5684024076401123\n800,100.00000111758709,100.0,100.0,0.46195317693568294,95.0,90.0,100.0,0.5581231700201241\n832,100.00000111758709,100.0,100.0,0.45028973981363174,95.0,90.0,100.0,0.5484136721696521\n864,100.00000111758709,100.0,100.0,0.4389629335160132,95.0,90.0,100.0,0.5375965943507595\n896,100.00000111758709,100.0,100.0,0.4280574290433732,95.0,90.0,100.0,0.5297755064326588\n928,100.00000111758709,100.0,100.0,0.4176026136917771,95.0,90.0,100.0,0.5216564912294647\n960,100.00000111758709,100.0,100.0,0.4074523138478397,95.0,90.0,100.0,0.5134361414385197\n992,100.00000111758709,100.0,100.0,0.39777359406335816,95.0,90.0,100.0,0.5049372061110985\n1024,100.00000111758709,100.0,100.0,0.38836321196962514,95.0,90.0,100.0,0.4970579486596722\n1056,100.00000111758709,100.0,100.0,0.3792962122463345,95.0,90.0,100.0,0.49127351752597176\n1088,100.00000111758709,100.0,100.0,0.3705926858408387,95.0,90.0,100.0,0.48535818041470524\n1120,100.00000111758709,100.0,100.0,0.36218755251354484,95.0,90.0,100.0,0.47837351165870634\n1152,100.00000111758709,100.0,100.0,0.35407859271871234,95.0,90.0,100.0,0.4729071859863523\n1184,100.00000111758709,100.0,100.0,0.3462821212907713,95.0,90.0,100.0,0.4665835793381013\n1216,100.00000111758709,100.0,100.0,0.338692420943195,95.0,90.0,100.0,0.46210833328654816\n1248,100.00000111758709,100.0,100.0,0.3313764813681741,95.0,90.0,100.0,0.45604253442672815\n1280,100.00000111758709,100.0,100.0,0.3243162694793336,95.0,90.0,100.0,0.4515586959041891\n1312,100.00000111758709,100.0,100.0,0.3175235311984152,95.0,90.0,100.0,0.4468846051338997\n1344,100.00000111758709,100.0,100.0,0.3109138439736886,95.0,90.0,100.0,0.44157299072729145\n1376,100.00000111758709,100.0,100.0,0.30448979218288896,95.0,90.0,100.0,0.4365165014256018\n1408,100.00000111758709,100.0,100.0,0.2983435353743342,95.0,90.0,100.0,0.4308327025918729\n1440,100.00000111758709,100.0,100.0,0.29240556195744166,95.0,90.0,100.0,0.42403151793405386\n1472,100.00000111758709,100.0,100.0,0.2865611275197513,95.0,90.0,100.0,0.4205571672247593\n1504,100.00000111758709,100.0,100.0,0.28095418242576214,95.0,90.0,100.0,0.4161738706359409\n1536,100.00000111758709,100.0,100.0,0.2755610349446828,95.0,90.0,100.0,0.4120982358530646\n1568,100.00000111758709,100.0,100.0,0.270299678602454,95.0,90.0,100.0,0.4062375990454443\n1600,100.00000111758709,100.0,100.0,0.26517320919942977,95.0,90.0,100.0,0.4039691460886542\n1632,100.00000111758709,100.0,100.0,0.26018200741182473,95.0,90.0,100.0,0.39965023115332954\n1664,100.00000111758709,100.0,100.0,0.2553767035143239,95.0,90.0,100.0,0.39618380143984677\n1696,100.00000111758709,100.0,100.0,0.2506901729754958,95.0,90.0,100.0,0.39397577668149797\n1728,100.00000111758709,100.0,100.0,0.24612113579653422,95.0,90.0,100.0,0.3916619430153634\n1760,100.00000111758709,100.0,100.0,0.2416658876462623,95.0,90.0,100.0,0.3906025837666053\n1792,100.00000111758709,100.0,100.0,0.23734113966146766,95.0,90.0,100.0,0.3896043942462871\n1824,100.00000111758709,100.0,100.0,0.23310908908556463,95.0,90.0,100.0,0.38870543940374896\n1856,100.00000111758709,100.0,100.0,0.22903719926413862,95.0,90.0,100.0,0.38585061401509607\n1888,100.00000111758709,100.0,100.0,0.225015971355118,95.0,90.0,100.0,0.3828368833285537\n1920,100.00000111758709,100.0,100.0,0.22109123290831584,95.0,90.0,100.0,0.3816345447835901\n1952,100.00000111758709,100.0,100.0,0.21729761440695397,95.0,90.0,100.0,0.3789834054120344\n1984,100.00000111758709,100.0,100.0,0.21360048249148603,95.0,90.0,100.0,0.37814051140292076\n2016,100.00000111758709,100.0,100.0,0.20999734441149975,95.0,90.0,100.0,0.37531046687184993\n"
  },
  {
    "path": "ovarian-cancer/report.py",
    "content": "#!/usr/bin/env python3\r\n##########################################################################################\r\n# Author: Jared L. Ostmeyer\r\n# Date Started: 2018-02-05\r\n# Purpose: Print results of the holdout cross-validation\r\n##########################################################################################\r\n\r\n##########################################################################################\r\n# Libraries\r\n##########################################################################################\r\n\r\nimport glob\r\nimport csv\r\nfrom scipy.special import xlogy\r\nimport numpy as np\r\n\r\n##########################################################################################\r\n# Load data\r\n##########################################################################################\r\n\r\ncosts_train = {}\r\naccuracies_train = {}\r\ntprs_train = {}\r\nfprs_train = {}\r\nfor path in glob.glob('bin/*_ps_train.csv'):\r\n  with open(path, 'r') as stream:\r\n    reader = csv.DictReader(stream)\r\n    costs = []\r\n    accuracies = []\r\n    tprs = []\r\n    fprs = []\r\n    for row in reader:\r\n      label = float(row['Label'])\r\n      weight = float(row['Weight'])\r\n      prediction = float(row['Prediction'])\r\n      costs.append(\r\n        weight*(-xlogy(label, prediction)-xlogy(1.0-label, 1.0-prediction))/np.log(2.0)\r\n      )\r\n      accuracies.append(\r\n        100.0*weight*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n      )\r\n      if label == 1.0:\r\n        tprs.append(\r\n          100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n        )\r\n      elif label == 0.0:\r\n        fprs.append(\r\n          100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n        )\r\n      else:\r\n        print('ERROR: Unrecognized value in the label.')\r\n        exit()\r\n  filename = path.split('/')[-1].split('.')[0]\r\n  _, step, _, _ = filename.split('_')\r\n  i = int(step)\r\n  if i not in costs_train:\r\n    costs_train[i] = []\r\n  costs_train[i].append(\r\n    np.sum(costs)\r\n  )\r\n  if i not in accuracies_train:\r\n    accuracies_train[i] = []\r\n  accuracies_train[i].append(\r\n    np.sum(accuracies)\r\n  )\r\n  if len(tprs) > 0:\r\n    if i not in tprs_train:\r\n      tprs_train[i] = []\r\n    tprs_train[i].append(\r\n      np.mean(tprs)\r\n    )\r\n  if len(fprs) > 0:\r\n    if i not in fprs_train:\r\n      fprs_train[i] = []\r\n    fprs_train[i].append(\r\n      np.mean(fprs)\r\n    )\r\n\r\ncosts_val = {}\r\naccuracies_val = {}\r\ntprs_val = {}\r\nfprs_val = {}\r\nfor path in glob.glob('bin/*_ps_val.csv'):\r\n  with open(path, 'r') as stream:\r\n    reader = csv.DictReader(stream)\r\n    costs = []\r\n    accuracies = []\r\n    tprs = []\r\n    fprs = []\r\n    for row in reader:\r\n      label = float(row['Label'])\r\n      weight = float(row['Weight'])\r\n      prediction = float(row['Prediction'])\r\n      costs.append(\r\n        weight*(-xlogy(label, prediction)-xlogy(1.0-label, 1.0-prediction))/np.log(2.0)\r\n      )\r\n      accuracies.append(\r\n        100.0*weight*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n      )\r\n      if label == 1.0:\r\n        tprs.append(\r\n          100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n        )\r\n      elif label == 0.0:\r\n        fprs.append(\r\n          100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)\r\n        )\r\n      else:\r\n        print('ERROR: Unrecognized value in the label.')\r\n        exit()\r\n  filename = path.split('/')[-1].split('.')[0]\r\n  _, step, _, _ = filename.split('_')\r\n  i = int(step)\r\n  if i not in costs_val:\r\n    costs_val[i] = []\r\n  costs_val[i].append(\r\n    np.sum(costs)\r\n  )\r\n  if i not in accuracies_val:\r\n    accuracies_val[i] = []\r\n  accuracies_val[i].append(\r\n    np.sum(accuracies)\r\n  )\r\n  if len(tprs) > 0:\r\n    if i not in tprs_val:\r\n      tprs_val[i] = []\r\n    tprs_val[i].append(\r\n      np.mean(tprs)\r\n    )\r\n  if len(fprs) > 0:\r\n    if i not in fprs_val:\r\n      fprs_val[i] = []\r\n    fprs_val[i].append(\r\n      np.mean(fprs)\r\n    )\r\n\r\n##########################################################################################\r\n# Results\r\n##########################################################################################\r\n\r\nprint(\r\n  'Step',\r\n  'Accuracy_Train', 'TRP_Train', 'FPR_Train', 'Cost_train',\r\n  'Accuracy_Val', 'TRP_Val', 'FPR_Val', 'Cost_Val',\r\n  sep=','\r\n)\r\nfor i in sorted(accuracies_train.keys()):\r\n  print(\r\n    i,\r\n    np.mean(accuracies_train[i]), np.mean(tprs_train[i]), np.mean(fprs_train[i]), np.mean(costs_train[i]),\r\n    np.mean(accuracies_val[i]), np.mean(tprs_val[i]), np.mean(fprs_val[i]), np.mean(costs_val[i]),\r\n    sep=','\r\n  )\r\n"
  },
  {
    "path": "ovarian-cancer/train_val.py",
    "content": "#!/usr/bin/env python3\n##########################################################################################\n# Author: Jared L. Ostmeyer\n# Date Started: 2021-11-16\n# Purpose: Train and validate a classifier for immune repertoires\n##########################################################################################\n\n##########################################################################################\n# Libraries\n##########################################################################################\n\nimport argparse\nimport csv\nimport glob\nimport dataplumbing as dp\nimport dataset as ds\nimport numpy as np\nimport torch\n\n##########################################################################################\n# Arguments\n##########################################################################################\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--holdouts', help='Holdout samples', type=str, nargs='+', required=True)\nparser.add_argument('--restart', help='Basename for restart files', type=str, default=None)\nparser.add_argument('--output', help='Basename for output files', type=str, required=True)\nparser.add_argument('--seed', help='Seed value for randomly initializing fits', type=int, default=1)\nparser.add_argument('--device', help='Examples are cuda:0 or cpu', type=str, default='cuda:0')\nparser.add_argument('--num_fits', help='Number of fits to the training data', type=int, default=2**17)\nargs = parser.parse_args()\n\n##########################################################################################\n# Assemble sequences\n##########################################################################################\n\n# Settings\n#\ntrim_front = 3\ntrim_rear = 3\n\nwindow_size = 4\nmotif_size = 3\n\n# To hold sequences from each subject\n#\ncases = {}\ncontrols = {}\n\n# Load immune repertoires\n#\nfor path in glob.glob('dataset/*.tsv'):\n  sample = path.split('/')[-1].split('.')[0]\n  label = sample[-1]\n  if label == 'M' or label == 'N':\n    cdr3s = dp.load_cdr3s(path, min_length=motif_size+trim_front+trim_rear, max_length=32)\n    cdr3s = dp.trim_cdr3s(cdr3s, trim_front=trim_front, trim_rear=trim_rear)\n    motifs = dp.cdr3s_to_motifs(cdr3s, window_size, motif_size)\n    motifs = dp.normalize_sample(motifs)\n    if label == 'M':\n      cases[sample] = motifs\n    else:\n      controls[sample] = motifs\n\n##########################################################################################\n# Assemble datasets\n##########################################################################################\n\n# Load embeddings\n#\naminoacids_dict = ds.load_aminoacid_embedding_dict('../aminoacid-representation/atchley_factors_normalized.csv')\n\n# Convert to numeric representations\n#\nsamples = ds.assemble_samples(cases, controls, aminoacids_dict)\n\n# Split into a training and validation cohort\n#\nsamples_train, samples_val = ds.split_samples(samples, args.holdouts)\n\n# Weight samples\n#\nsamples_train = ds.weight_samples(samples_train)\nsamples_val = ds.weight_samples(samples_val)\n\n# Normalize features\n#\nsamples_train, samples_val = ds.normalize_samples(samples_train, samples_val)\n\n##########################################################################################\n# Assemble tensors\n##########################################################################################\n\n# Settings\n#\ndevice = torch.device(args.device)\n\n# Convert numpy arrays to pytorch tensors\n#\nfor sample in samples_train:\n  sample['features'] = torch.from_numpy(sample['features']).to(device)\n  sample['label'] = torch.tensor(sample['label']).to(device)\n  sample['weight'] = torch.tensor(sample['weight']).to(device)\n\n# Convert numpy arrays to pytorch tensors\n#\nfor sample in samples_val:\n  sample['features'] = torch.from_numpy(sample['features']).to(device)\n  sample['label'] = torch.tensor(sample['label']).to(device)\n  sample['weight'] = torch.tensor(sample['weight']).to(device)\n\n##########################################################################################\n# Model\n##########################################################################################\n\n# Settings\n#\nnum_features = samples_train[0]['features'].shape[1]\nnum_fits = args.num_fits\n\ntorch.manual_seed(args.seed)\n\n# Function for initializing the weights of the model\n#\ndef init_weights():\n  return torch.cat(\n    [\n      0.5**0.5*torch.rand([ num_features-1, num_fits ])/(num_features-1.0)**0.5,  # Weights for the Atchley factors\n      0.5**0.5*torch.rand([ 1, num_fits ])/(1.0)**0.5,  # Weight for the abundance term\n    ],\n    0\n  )\n\n# Class defining the model\n#\nclass MaxSnippetModel(torch.nn.Module):\n  def __init__(self):\n    super(MaxSnippetModel, self).__init__()\n    self.linear = torch.nn.Linear(num_features, num_fits)\n    with torch.no_grad():\n      self.linear.weights = init_weights()  # Initialize the weights\n  def forward(self, x):\n    ls = self.linear(x)\n    ms, _ = torch.max(ls, axis=0)\n    return ms\n\n# Instantiation of the model\n#\nmsm = MaxSnippetModel()\n\n# Turn on GPU acceleration\n#\nmsm.to(device)\n\n##########################################################################################\n# Metrics and optimization\n##########################################################################################\n\n# Settings\n#\nlearning_rate = 0.01\n\n# Optimizer\n#\noptimizer = torch.optim.Adam(msm.parameters(), lr=learning_rate)  # Adam is based on gradient descent but better\n\n# Metrics\n#\nloss = torch.nn.BCEWithLogitsLoss(reduction='none')  # The loss function is calculated seperately for each fit by setting reduction to none\n\ndef accuracy(ls_block, ys_block):  # The binary accuracy is calculated seperate for each fit\n  a = torch.nn.Sigmoid()\n  ps_block = a(ls_block)\n  cs_block = (torch.round(ps_block) == torch.round(ys_block)).to(ys_block.dtype)\n  return cs_block\n\n##########################################################################################\n# Fit and evaluate model\n##########################################################################################\n\n# Settings\n#\nnum_epochs = 2048\n\n# Restore saved models\n#\nif args.restart is not None:\n  msm = torch.load(args.output+'_model.p')\n\n# Each iteration represents one batch\n#\nfor epoch in range(0, num_epochs):\n\n  # Reset the gradients\n  #\n  optimizer.zero_grad()\n\n  es_train = 0.0  # Cross-entropy error\n  as_train = 0.0  # Accuracy\n\n  for sample in samples_train:\n\n    xs_block = sample['features']\n    ys_block = torch.tile(sample['label'], [ num_fits ])\n    w_block = sample['weight']\n\n    ls_block = msm(xs_block)\n    sample['predictions'] = torch.sigmoid(ls_block)\n\n    es_block = w_block*loss(ls_block, ys_block)  # The loss function is calculated seperately for each fit\n    as_block = w_block*accuracy(ls_block, ys_block)  # The binary accuracy is calculated seperate for each fit\n\n    es_train += es_block.detach()\n    as_train += as_block.detach()\n\n    e_block = torch.sum(es_block)\n    e_block.backward()\n\n  i_bestfit = torch.argmin(es_train)  # Very important index selects the best fit to the training data\n\n  es_val = 0.0\n  as_val = 0.0\n\n  with torch.no_grad():\n\n    for sample in samples_val:\n\n      xs_block = sample['features']\n      ys_block = torch.tile(sample['label'], [ num_fits ])\n      w_block = sample['weight']\n\n      ls_block = msm(xs_block)\n      sample['predictions'] = torch.sigmoid(ls_block)\n\n      es_block = w_block*loss(ls_block, ys_block)  # The loss function is calculated seperately for each fit\n      as_block = w_block*accuracy(ls_block, ys_block)  # The binary accuracy is calculated seperate for each fit\n\n      es_val += es_block.detach()\n      as_val += as_block.detach()\n\n  # Print report\n  #\n  print(\n    'Epoch:', epoch,\n    'Accuracy (train):', round(100.0*float(as_train[i_bestfit]), 2), '%',\n    'Accuracy (val):', round(100.0*float(as_val[i_bestfit]), 2), '%',\n    flush=True\n  )\n\n  # Save parameters and results from the best fit to the training data\n  #\n  if epoch%32 == 0:\n    ws = msm.linear.weights.detach().numpy()\n    bs = msm.linear.bias.cpu().detach().numpy()\n    np.savetxt(args.output+'_'+str(epoch)+'_ws.csv', ws[:,i_bestfit])\n    np.savetxt(args.output+'_'+str(epoch)+'_b.csv', bs[[i_bestfit.cpu()]])\n    with open(args.output+'_'+str(epoch)+'_ms_train.csv', 'w') as stream:\n      print('Cross Entropy (bits)', 'Accuracy (%)', sep=',', file=stream)\n      print(float(es_train[i_bestfit])/np.log(2.0), 100.0*float(as_train[i_bestfit]), sep=',', file=stream)\n    with open(args.output+'_'+str(epoch)+'_ms_val.csv', 'w') as stream:\n      print('Cross Entropy (bits)', 'Accuracy (%)', sep=',', file=stream)\n      print(float(es_val[i_bestfit])/np.log(2.0), 100.0*float(as_val[i_bestfit]), sep=',', file=stream)\n    with open(args.output+'_'+str(epoch)+'_ps_train.csv', 'w') as stream:\n      print('Subject', 'Label', 'Weight', 'Prediction', sep=',', file=stream)\n      for sample in samples_train:\n        print(sample['subject'], float(sample['label']), float(sample['weight']), float(sample['predictions'][i_bestfit]), sep=',', file=stream)\n    with open(args.output+'_'+str(epoch)+'_ps_val.csv', 'w') as stream:\n      print('Subject', 'Label', 'Weight', 'Prediction', sep=',', file=stream)\n      for sample in samples_val:\n        print(sample['subject'], float(sample['label']), float(sample['weight']), float(sample['predictions'][i_bestfit]), sep=',', file=stream)\n\n  optimizer.step()\n\ntorch.save(msm, args.output+'_model.p')\n"
  }
]