Repository: jostmey/msm
Branch: main
Commit: affbee47ff81
Files: 30
Total size: 182.3 KB
Directory structure:
gitextract_dwe47jrw/
├── LICENSE
├── README.md
├── aminoacid-representation/
│ ├── README.md
│ ├── atchley_factors.csv
│ ├── atchley_factors_normalized.csv
│ └── atchley_factors_normalized.py
├── breast-cancer/
│ ├── README.md
│ ├── dataplumbing.py
│ ├── dataset.py
│ ├── gold.report.csv
│ ├── report.py
│ └── train_val.py
├── cervical-cancer/
│ ├── README.md
│ ├── dataplumbing.py
│ ├── dataset.py
│ ├── gold.report.csv
│ ├── report.py
│ └── train_val.py
├── colorectal-cancer/
│ ├── README.md
│ ├── dataplumbing.py
│ ├── dataset.py
│ ├── gold.report.csv
│ ├── report.py
│ └── train_val.py
└── ovarian-cancer/
├── README.md
├── dataplumbing.py
├── dataset.py
├── gold.report.csv
├── report.py
└── train_val.py
================================================
FILE CONTENTS
================================================
================================================
FILE: LICENSE
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
.
================================================
FILE: README.md
================================================
# Max Snippet Model (Work in Progress)
## Introduction
The 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.
To 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.
Subsequently, 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.
The 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.
We 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.
In 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:
* [distinguish malignant from non-malignant ovarian tissue](ovarian-cancer),
* [diagnose breast cancer from peripheral blood](breast-cancer),
* [predict clearance of preneoplastic cervical lesions](cervical-cancer),
* [and provide an example where our code performed poorly.](colorectal-cancer)
## Publications
* [Cervical Cancer Screening](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC8050337/)
* [Ovarian Cancer](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7058380/)
* [Breast and Colorectal Cancer](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6445742/)
* [Multiple Sclerosis](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5588725/)
## Requirements
* [Python3](https://www.python.org/)
* [PyTorch](https://pytorch.org//)
* [NumPy](http://www.numpy.org/)
* CUDA GPU
* Linux Environment (Recommended)
## Download
* Download: [zip](https://github.com/jostmey/msm/zipball/master)
* Git: `git clone https://github.com/jostmey/msm`
## To Do
* Bugs in code preventing replication of all published results (some results replicated, some not)
* Change-log of modifications of each model from the original publication (point out where we get identical performance)
* Code to extract top scoring 4mers
* Rename folders to indicate tissue/blood and published/not
================================================
FILE: aminoacid-representation/README.md
================================================
## Amino Acid Representation
Instead 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.
The 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:
`python3 atchley_factors_normalized.py`
================================================
FILE: aminoacid-representation/atchley_factors.csv
================================================
A, -0.591, -1.302, -0.733, 1.570, -0.146
C, -1.343, 0.465, -0.862, -1.020, -0.255
D, 1.050, 0.302, -3.656, -0.259, -3.242
E, 1.357, -1.453, 1.477, 0.113, -0.837
F, -1.006, -0.590, 1.891, -0.397, 0.412
G, -0.384, 1.652, 1.330, 1.045, 2.064
H, 0.336, -0.417, -1.673, -1.474, -0.078
I, -1.239, -0.547, 2.131, 0.393, 0.816
K, 1.831, -0.561, 0.533, -0.277, 1.648
L, -1.019, -0.987, -1.505, 1.266, -0.912
M, -0.663, -1.524, 2.219, -1.005, 1.212
N, 0.945, 0.828, 1.299, -0.169, 0.933
P, 0.189, 2.081, -1.628, 0.421, -1.392
Q, 0.931, -0.179, -3.005, -0.503, -1.853
R, 1.538, -0.055, 1.502, 0.440, 2.897
S, -0.228, 1.399, -4.760, 0.670, -2.647
T, -0.032, 0.326, 2.213, 0.908, 1.313
V, -1.337, -0.279, -0.544, 1.242, -1.262
W, -0.595, 0.009, 0.672, -2.128, -0.184
Y, 0.260, 0.830, 3.097, -0.838, 1.512
================================================
FILE: aminoacid-representation/atchley_factors_normalized.csv
================================================
A,-0.60384715,-1.3302325,-0.34452927,1.6302937,-0.093537085
C,-1.3721942,0.4752217,-0.40517095,-1.0590004,-0.16339348
D,1.0728248,0.3086744,-1.7186037,-0.2688256,-2.0777154
E,1.3864983,-1.4845185,0.6943706,0.117435955,-0.5363883
F,-1.0278684,-0.60273767,0.8889881,-0.41211617,0.26407644
G,-0.39234737,1.6880536,0.6252673,1.0851665,1.3228176
H,0.34330395,-0.42597276,-0.78641427,-1.5304055,-0.049956944
I,-1.2659333,-0.5588019,1.0018097,0.40817046,0.52299374
K,1.8708022,-0.5731065,0.25060523,-0.28751567,1.0562096
L,-1.041151,-1.0083773,-0.7074391,1.3146391,-0.5844546
M,-0.6774123,-1.5570637,1.0431777,-1.0434253,0.776784
N,0.9655424,0.84612143,0.6106945,-0.17537521,0.5979773
P,0.19310847,2.1263897,-0.7652602,0.4372439,-0.8920792
Q,0.95123804,-0.18279332,-1.4125749,-0.5221799,-1.187527
R,1.571433,-0.05609477,0.7061229,0.4569723,1.8566744
S,-0.23295625,1.4295478,-2.2375836,0.69579,-1.6963892
T,-0.032695606,0.3331967,1.0403571,0.94291425,0.8415133
V,-1.3660636,-0.28496957,-0.2556822,1.289719,-0.80876416
W,-0.6079341,0.009298024,0.3159478,-2.2094784,-0.11789069
Y,0.26565185,0.8481649,1.455917,-0.87002295,0.96904933
================================================
FILE: aminoacid-representation/atchley_factors_normalized.py
================================================
#!/usr/bin/env python3
##########################################################################################
# Author: Jared L. Ostmeyer
# Date Started: 2019-08-02
# Purpose: Normalize atchley factor embedding of amino acid residues
##########################################################################################
##########################################################################################
# Libraries
##########################################################################################
import numpy as np
##########################################################################################
# Settings
##########################################################################################
path_embedding = 'atchley_factors.csv'
path_embedding_norm = 'atchley_factors_normalized.csv'
##########################################################################################
# Load data
##########################################################################################
ns = []
fs = []
with open(path_embedding, 'r') as stream:
for line in stream:
rows = line.split(',')
ns.append(rows[0])
fs.append(np.array(rows[1:], dtype=np.float32))
##########################################################################################
# Format data
##########################################################################################
fs = np.array(fs)
fs = (fs-np.mean(fs, axis=0))/np.std(fs, axis=0)
##########################################################################################
# Save results
##########################################################################################
with open(path_embedding_norm, 'w') as stream:
for n, f in zip(ns, fs):
print(n, ','.join([ str(v) for v in f ]), sep=',', file=stream)
================================================
FILE: breast-cancer/README.md
================================================
# Instructions
This 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.
## Dataset
The `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.
```
cd dataset
unzip '*.zip'
cd ../
```
## Modeling
This 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.
```
mkdir -p bin
python3 train_val.py --seed 1 --holdouts BR01B --num_fits 16384 --output bin/1
python3 train_val.py --seed 1 --holdouts BR05B --num_fits 16384 --output bin/2
python3 train_val.py --seed 1 --holdouts BR07B --num_fits 16384 --output bin/3
python3 train_val.py --seed 1 --holdouts BR13B --num_fits 16384 --output bin/4
python3 train_val.py --seed 1 --holdouts BR14B --num_fits 16384 --output bin/5
python3 train_val.py --seed 1 --holdouts BR15B --num_fits 16384 --output bin/6
python3 train_val.py --seed 1 --holdouts BR16B --num_fits 16384 --output bin/7
python3 train_val.py --seed 1 --holdouts BR17B --num_fits 16384 --output bin/8
python3 train_val.py --seed 1 --holdouts BR18B --num_fits 16384 --output bin/9
python3 train_val.py --seed 1 --holdouts BR19B --num_fits 16384 --output bin/10
python3 train_val.py --seed 1 --holdouts BR20B --num_fits 16384 --output bin/11
python3 train_val.py --seed 1 --holdouts BR21B --num_fits 16384 --output bin/12
python3 train_val.py --seed 1 --holdouts BR22B --num_fits 16384 --output bin/13
python3 train_val.py --seed 1 --holdouts BR24B --num_fits 16384 --output bin/14
python3 train_val.py --seed 1 --holdouts BR25B --num_fits 16384 --output bin/15
python3 train_val.py --seed 1 --holdouts BR26B --num_fits 16384 --output bin/16
python3 train_val.py --seed 1 --holdouts HIP00602 --num_fits 16384 --output bin/17
python3 train_val.py --seed 1 --holdouts HIP01091 --num_fits 16384 --output bin/18
python3 train_val.py --seed 1 --holdouts HIP02271 --num_fits 16384 --output bin/19
python3 train_val.py --seed 1 --holdouts HIP02962 --num_fits 16384 --output bin/20
python3 train_val.py --seed 1 --holdouts HIP03194 --num_fits 16384 --output bin/21
python3 train_val.py --seed 1 --holdouts HIP04475 --num_fits 16384 --output bin/22
python3 train_val.py --seed 1 --holdouts HIP05590 --num_fits 16384 --output bin/23
python3 train_val.py --seed 1 --holdouts HIP09020 --num_fits 16384 --output bin/24
python3 train_val.py --seed 1 --holdouts HIP09365 --num_fits 16384 --output bin/25
python3 train_val.py --seed 1 --holdouts HIP11774 --num_fits 16384 --output bin/26
python3 train_val.py --seed 1 --holdouts HIP13449 --num_fits 16384 --output bin/27
python3 train_val.py --seed 1 --holdouts HIP13789 --num_fits 16384 --output bin/28
python3 train_val.py --seed 1 --holdouts HIP14009 --num_fits 16384 --output bin/29
python3 train_val.py --seed 1 --holdouts HIP14045 --num_fits 16384 --output bin/30
python3 train_val.py --seed 1 --holdouts HIP14055 --num_fits 16384 --output bin/31
python3 train_val.py --seed 1 --holdouts HIP14221 --num_fits 16384 --output bin/32
```
The 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.
## How does this differ from the other examples in this repository?
This 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.
## Evaluation
Upon executing each of the aforementioned commands and completing the patient-holdout cross-validation, you can consolidate the results using the command provided below.
```
python3 report.py > report.csv
```
The results are stored in a CSV file that can be opened by your favorite spreadsheet viewer. There are nine columns that represent:
1. The training step.
2. The accuracy on the training data averaged over the cross-validation.
3. The true negative rate (specificity) on the training data averaged over the cross-validation.
4. The true positive rate (sensitivity) on the training data averaged over the cross-validation.
5. The cross-entropy on the training data averaged over the cross-validation.
6. The accuracy on the holdout data averaged over the cross-validation.
7. The true negative rate (specificity) on the holdout data averaged over the cross-validation.
8. The true positive rate (sensitivity) on the holdout data averaged over the cross-validation.
9. The cross-entropy on the holdout data averaged over the cross-validation.
## Publications
* [Source of Healthy Control Samples](https://www.nature.com/articles/ng.3822)
* [Source of Breast Cancer Samples](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5715779/)
* [Original Breast Cancer Model](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6445742/)
================================================
FILE: breast-cancer/dataplumbing.py
================================================
#########################################################################################
# Author: Jared L. Ostmeyer
# Date Started: 2021-11-16
# Environment: Python3
# Purpose: Utilities for loading immune receptor sequences
##########################################################################################
##########################################################################################
# Libraries
##########################################################################################
import csv
from itertools import combinations
##########################################################################################
# Utilities
##########################################################################################
def load_cdr3s(path_tsv, min_length=4, max_length=32, version='v2'):
receptors = {}
with open(path_tsv, 'r') as stream:
reader = csv.DictReader(stream, delimiter='\t')
for row in reader:
if version == 'v2':
cdr3 = row['aminoAcid']
# quantity = float(row['frequencyCount (%)'])
quantity = float(row['count (templates/reads)'])
status = row['sequenceStatus']
elif version == 'v3':
cdr3 = row['amino_acid']
# quantity = float(row['frequency'])
quantity = float(row['templates'])
status = row['frame_type']
else:
print('ERROR: Unsupported version')
exit()
if 'In' in status and min_length <= len(cdr3) and len(cdr3) <= max_length and quantity > 0.0 and 'X' not in cdr3:
if cdr3 not in receptors:
receptors[cdr3] = quantity
else:
receptors[cdr3] += quantity
return receptors
def trim_cdr3s(receptors, trim_front=0, trim_rear=0):
cdr3s = {}
for cdr3, quantity in receptors.items():
cdr3_trim = cdr3[trim_front:]
if trim_rear > 0:
cdr3_trim = cdr3_trim[:-trim_rear]
if len(cdr3_trim) > 0:
if cdr3_trim not in cdr3s:
cdr3s[cdr3_trim] = quantity
else:
cdr3s[cdr3_trim] += quantity
return cdr3s
def cdr3s_to_kmers(cdr3s, kmer_size):
kmers = {}
for cdr3, quantity in cdr3s.items():
if len(cdr3) >= kmer_size:
for i in range(len(cdr3)-kmer_size+1):
kmer = cdr3[i:i+kmer_size]
if kmer not in kmers:
kmers[kmer] = quantity
else:
kmers[kmer] += quantity
return kmers
def cdr3s_to_motifs(cdr3s, window_size, motif_size):
templates = []
for template in list(combinations(range(window_size), motif_size)):
if template[0] == 0:
templates.append(template)
motifs = {}
for cdr3, quantity in cdr3s.items():
if len(cdr3) >= motif_size:
for i in range(len(cdr3)-motif_size+1):
window = cdr3[i:i+window_size]
for template in templates:
if template[-1] < len(window):
motif = ''
for i in template:
motif += window[i]
if motif not in motifs:
motifs[motif] = quantity
else:
motifs[motif] += quantity
return motifs
def flatten_sample(sequences):
return { sequence: 1.0 for sequence in sequences.keys() }
def normalize_sample(sequences):
total = 0.0
for quantity in sorted(sequences.values()):
total += quantity
sequences_ = {}
for sequence, quantity in sequences.items():
sequences_[sequence] = quantity/total
return sequences_
def merge_samples(samples):
sequences = {}
for sample in samples:
for sequence, quantity in sample.items():
if sequence not in sequences:
sequences[sequence] = quantity/float(len(samples))
else:
sequences[sequence] += quantity/float(len(samples))
return sequences
def debug_insert_sequence(receptors, sequence, count):
if sequence not in receptors:
receptors[sequence] = count
else:
receptors[sequence] += count
return receptors
================================================
FILE: breast-cancer/dataset.py
================================================
#########################################################################################
# Author: Jared L. Ostmeyer
# Date Started: 2021-11-16
# Environment: Python3
# Purpose: Utilities for converting immune receptor sequences into numeric features
##########################################################################################
##########################################################################################
# Libraries
##########################################################################################
import csv
import numpy as np
##########################################################################################
# Utilities
##########################################################################################
def load_aminoacid_embedding_dict(path_embedding):
# Amino acid factors
#
names = []
factors = []
with open(path_embedding, 'r') as stream:
for line in stream:
rows = line.split(',')
names.append(rows[0])
factors.append(np.array(rows[1:], dtype=np.float32))
names = np.array(names)
factors = np.array(factors)
# Convert into a dictionary
#
aminoacids_dict = { name: factors[i,:] for i, name in enumerate(names) }
return aminoacids_dict
def assemble_samples(cases, controls, aminoacids_dict):
# Determine tensor dimensions
#
max_steps = -1
for sequences in cases.values():
for sequence in sequences.keys():
if len(sequence) > max_steps:
max_steps = len(sequence)
for sequences in controls.values():
for sequence in sequences.keys():
if len(sequence) > max_steps:
max_steps = len(sequence)
num_factors = len(list(aminoacids_dict.values())[0])
# Assemble dataset
#
samples = []
for subject in sorted(cases.keys()):
sequences = cases[subject]
# Initialize tensors
#
xs = np.zeros([ len(sequences), max_steps*num_factors+1 ], dtype=np.float32)
# Fill tensors
#
for i, ( sequence, quantity ) in enumerate(sorted(sequences.items())):
for j, aa in enumerate(sequence):
xs[i,num_factors*j:num_factors*(j+1)] = aminoacids_dict[aa]
xs[i,-1] = np.log(quantity)
u = np.mean(xs[:,-1])
v = np.var(xs[:,-1])
xs[:,-1] = (xs[:,-1]-u)/np.sqrt(v)
samples.append(
{
'subject': subject,
'features': xs,
'label': 1.0
}
)
for subject in sorted(controls.keys()):
sequences = controls[subject]
# Initialize tensors
#
xs = np.zeros([ len(sequences), max_steps*num_factors+1 ], dtype=np.float32)
# Fill tensors
#
for i, ( sequence, quantity ) in enumerate(sorted(sequences.items())):
for j, aa in enumerate(sequence):
xs[i,num_factors*j:num_factors*(j+1)] = aminoacids_dict[aa]
xs[i,-1] = np.log(quantity)
u = np.mean(xs[:,-1])
v = np.var(xs[:,-1])
xs[:,-1] = (xs[:,-1]-u)/np.sqrt(v)
samples.append(
{
'subject': subject,
'features': xs,
'label': 0.0
}
)
return samples
def split_samples(samples, holdouts):
samples_train = []
samples_val = []
for sample in samples:
if sample['subject'] not in holdouts:
samples_train.append(sample)
else:
samples_val.append(sample)
return samples_train, samples_val
def weight_samples(samples):
num_case = 0
num_control = 0
for sample in samples:
if sample['label'] > 0.5:
num_case += 1
else:
num_control += 1
for sample in samples:
if sample['label'] > 0.5:
sample['weight'] = 0.5/num_case if num_control > 0 else 1.0/num_case
else:
sample['weight'] = 0.5/num_control if num_case > 0 else 1.0/num_control
return samples
def normalize_samples(samples_train, samples_holdout):
# Calculate normalization statistics from the training samples
#
us = 0.0
us2 = 0.0
for sample in samples_train:
xs_sample = sample['features']
us_sample = np.mean(xs_sample, axis=0)
us2_sample = np.mean(xs_sample**2, axis=0)
us += sample['weight']*us_sample
us2 += sample['weight']*us2_sample
vs = us2-us**2
# Normalize the training samples
#
for sample in samples_train:
xs_sample = sample['features']
xs_sample = (xs_sample-us)/np.sqrt(vs)
sample['features'] = xs_sample
# Normalize the holdout samples
#
for sample in samples_holdout:
xs_sample = sample['features']
xs_sample = (xs_sample-us)/np.sqrt(vs)
sample['features'] = xs_sample
return samples_train, samples_holdout
def debug_permute_labels(samples):
labels = []
for sample in samples:
labels.append(sample['label'])
np.random.shuffle(labels)
for sample, label in zip(samples, labels):
sample['label'] = label
return samples
================================================
FILE: breast-cancer/gold.report.csv
================================================
Step,Accuracy_Train,TRP_Train,FPR_Train,Cost_train,Accuracy_Val,TRP_Val,FPR_Val,Cost_Val
0,50.000001303851604,100.0,0.0,1.1087665660203974,50.0,100.0,0.0,1.1087657122359977
32,50.000001303851604,100.0,0.0,0.9746543546169101,50.0,100.0,0.0,0.9882532360182199
64,50.000001303851604,100.0,0.0,0.956154798123996,50.0,100.0,0.0,0.9837422744544466
96,53.951824340038,100.0,7.903645833333334,0.9401936699025335,50.0,100.0,0.0,0.9790061340358706
128,68.17057471489534,100.0,36.341145833333336,0.9239505371786172,53.125,93.75,12.5,0.9752436512905321
160,77.7473978814669,100.0,55.49479166666667,0.9074316060254094,62.5,93.75,31.25,0.9687489525085784
192,83.89323137234896,99.19270833333333,68.59375,0.8905648795940816,68.75,93.75,43.75,0.9538709485176311
224,88.50911689223722,99.59635416666666,77.421875,0.8737513345043975,78.125,93.75,62.5,0.929324595937833
256,91.52995030162856,99.58333333333334,83.4765625,0.8569250998503849,84.375,93.75,75.0,0.9147365863269314
288,93.21614824002609,99.375,87.05729166666666,0.8402085232017285,87.5,93.75,81.25,0.9047697525179907
320,94.42708577262238,99.375,89.47916666666666,0.8238007498990938,90.625,93.75,87.5,0.8920257760985286
352,95.26692957151681,99.8046875,90.72916666666667,0.8076075657417026,90.625,93.75,87.5,0.8842510580236446
384,95.26692957151681,99.8046875,90.72916666666667,0.7916881633274516,90.625,93.75,87.5,0.8783291066010929
416,94.96093997731805,99.19270833333333,90.72916666666667,0.7761440248828644,90.625,93.75,87.5,0.8693954466613332
448,94.66797122731805,98.41145833333333,90.92447916666666,0.7610957371224165,90.625,93.75,87.5,0.8622378710171007
480,94.66797122731805,98.41145833333333,90.92447916666667,0.746253870558137,90.625,93.75,87.5,0.8530867435889941
512,94.45963788311929,97.79947916666666,91.11979166666666,0.7318797536910446,90.625,93.75,87.5,0.8517006999611726
544,94.76562747731805,98.0078125,91.5234375,0.717854169227414,90.625,93.75,87.5,0.8445357926794053
576,94.75911705521867,97.60416666666666,91.9140625,0.704166846760235,87.5,93.75,81.25,0.849290836799375
608,94.75260663311929,97.1875,92.31770833333334,0.6908289997243852,84.375,87.5,81.25,0.856516151860143
640,94.75260663311929,97.1875,92.31770833333333,0.6778869727830005,84.375,87.5,81.25,0.8489620948378077
672,94.96093997731805,97.1875,92.734375,0.6652883385398278,84.375,87.5,81.25,0.8425030595239287
704,95.06510664941743,96.97916666666666,93.15104166666666,0.6530945915645023,84.375,87.5,81.25,0.8379974671428634
736,95.16927332151681,96.97916666666666,93.35937499999999,0.6412082921590925,84.375,87.5,81.25,0.8328068964770631
768,95.26692957151681,96.97916666666666,93.5546875,0.6297269575665889,81.25,81.25,81.25,0.8271064566042978
800,95.36458582151681,96.97916666666666,93.75,0.6185128326843261,84.375,87.5,81.25,0.8227516269445052
832,95.36458582151681,96.97916666666666,93.75,0.6076064886449966,81.25,81.25,81.25,0.8249912571832305
864,95.26692957151681,96.97916666666666,93.5546875,0.5970243687302654,81.25,81.25,81.25,0.8212471615775674
896,95.36458582151681,96.97916666666666,93.75,0.5867097868701365,81.25,81.25,81.25,0.8187135871003274
928,95.36458582151681,96.97916666666666,93.75,0.5767185010983471,81.25,81.25,81.25,0.8104618389456697
960,95.76823166571558,97.36979166666666,94.16666666666666,0.5669785672589269,78.125,81.25,75.0,0.8185991292988433
992,95.76823166571558,97.36979166666666,94.16666666666666,0.5574113566407709,78.125,81.25,75.0,0.8137786351914669
1024,95.76823166571558,97.36979166666666,94.16666666666666,0.5481521124754212,78.125,81.25,75.0,0.8101358135130107
1056,95.76823166571558,97.36979166666666,94.16666666666666,0.5391171956300372,78.125,81.25,75.0,0.8074424743395503
1088,95.96354416571558,97.56510416666666,94.36197916666666,0.5303491122878181,78.125,81.25,75.0,0.8038067717727604
1120,95.96354416571558,97.56510416666666,94.36197916666666,0.5217630404127704,78.125,81.25,75.0,0.7998339898714826
1152,95.96354416571558,97.56510416666666,94.36197916666666,0.5134105944800843,78.125,81.25,75.0,0.7973929960949235
1184,96.16536708781496,97.7734375,94.55729166666666,0.5053450472342641,78.125,81.25,75.0,0.7930752943700994
1216,96.26953375991434,97.98177083333333,94.55729166666666,0.4973053309558505,78.125,81.25,75.0,0.7928495641664652
1248,96.07422125991434,97.59114583333333,94.55729166666666,0.4894706371246692,78.125,81.25,75.0,0.795023525207023
1280,96.07422125991434,97.59114583333333,94.55729166666666,0.48176503905133095,78.125,81.25,75.0,0.7902311028206138
1312,96.07422125991434,97.59114583333333,94.55729166666666,0.47438760345431,78.125,81.25,75.0,0.786830205460078
1344,96.17838793201372,97.59114583333333,94.765625,0.4671956851524221,78.125,81.25,75.0,0.7854635542025163
1376,96.27604418201372,97.78645833333333,94.765625,0.4601819473358414,78.125,81.25,75.0,0.7846301144935698
1408,96.58203377621248,97.99479166666666,95.16927083333333,0.45329373841953524,78.125,75.0,81.25,0.780967960778678
1440,96.67969002621248,98.38541666666666,94.97395833333333,0.44653359854701147,78.125,75.0,81.25,0.7836665167930863
1472,96.67969002621248,98.19010416666666,95.16927083333333,0.43976705156884816,78.125,75.0,81.25,0.7891126846033775
1504,96.6731796041131,98.17708333333333,95.16927083333333,0.43328257073043785,78.125,75.0,81.25,0.7871588678975525
1536,96.97916919831187,98.58072916666666,95.37760416666666,0.42690001483190154,78.125,75.0,81.25,0.7839307608619616
1568,96.97916919831187,98.58072916666666,95.37760416666666,0.42057523763823845,78.125,75.0,81.25,0.7828612026020991
1600,96.98567962041125,98.59375,95.37760416666666,0.4144518048654613,78.125,75.0,81.25,0.7814457654550357
1632,96.98567962041125,98.59375,95.37760416666666,0.4085118590453364,78.125,75.0,81.25,0.7816419080320025
1664,96.98567962041125,98.59375,95.37760416666666,0.40268018485447066,78.125,75.0,81.25,0.7798756305344625
1696,97.18750254251063,98.7890625,95.5859375,0.39698017025105103,78.125,75.0,81.25,0.78677006597077
1728,97.19401296461001,98.59375,95.79427083333333,0.39135352034582704,78.125,75.0,81.25,0.7874269235493413
1760,97.39583588670939,98.80208333333333,95.98958333333333,0.385871643207593,78.125,75.0,81.25,0.7792872464736458
1792,97.49349213670939,98.99739583333333,95.98958333333333,0.38047289018006025,78.125,75.0,81.25,0.7884103824638327
1824,97.49349213670939,98.99739583333333,95.98958333333333,0.37517013150231093,78.125,75.0,81.25,0.7828765052434095
1856,97.69531505880877,98.99739583333333,96.39322916666666,0.3698902704628685,78.125,75.0,81.25,0.7811844484462991
1888,97.69531505880877,98.99739583333333,96.39322916666666,0.36477528109697493,78.125,75.0,81.25,0.7790873517023973
1920,97.69531505880877,98.99739583333333,96.39322916666666,0.35977617906798676,78.125,75.0,81.25,0.7793601207881784
1952,97.79297130880877,98.99739583333333,96.58854166666666,0.3548837654341777,75.0,68.75,81.25,0.7825976981065828
1984,97.79297130880877,98.99739583333333,96.58854166666666,0.3500895295224291,75.0,68.75,81.25,0.780542845291275
2016,97.79297130880877,98.99739583333333,96.58854166666666,0.3453763728733972,75.0,68.75,81.25,0.7810088340211877
================================================
FILE: breast-cancer/report.py
================================================
#!/usr/bin/env python3
##########################################################################################
# Author: Jared L. Ostmeyer
# Date Started: 2018-02-05
# Purpose: Print results of the holdout cross-validation
##########################################################################################
##########################################################################################
# Libraries
##########################################################################################
import glob
import csv
from scipy.special import xlogy
import numpy as np
##########################################################################################
# Load data
##########################################################################################
costs_train = {}
accuracies_train = {}
tprs_train = {}
fprs_train = {}
for path in glob.glob('bin/*_ps_train.csv'):
with open(path, 'r') as stream:
reader = csv.DictReader(stream)
costs = []
accuracies = []
tprs = []
fprs = []
for row in reader:
label = float(row['Label'])
weight = float(row['Weight'])
prediction = float(row['Prediction'])
costs.append(
weight*(-xlogy(label, prediction)-xlogy(1.0-label, 1.0-prediction))/np.log(2.0)
)
accuracies.append(
100.0*weight*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
if label == 1.0:
tprs.append(
100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
elif label == 0.0:
fprs.append(
100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
else:
print('ERROR: Unrecognized value in the label.')
exit()
filename = path.split('/')[-1].split('.')[0]
_, step, _, _ = filename.split('_')
i = int(step)
if i not in costs_train:
costs_train[i] = []
costs_train[i].append(
np.sum(costs)
)
if i not in accuracies_train:
accuracies_train[i] = []
accuracies_train[i].append(
np.sum(accuracies)
)
if len(tprs) > 0:
if i not in tprs_train:
tprs_train[i] = []
tprs_train[i].append(
np.mean(tprs)
)
if len(fprs) > 0:
if i not in fprs_train:
fprs_train[i] = []
fprs_train[i].append(
np.mean(fprs)
)
costs_val = {}
accuracies_val = {}
tprs_val = {}
fprs_val = {}
for path in glob.glob('bin/*_ps_val.csv'):
with open(path, 'r') as stream:
reader = csv.DictReader(stream)
costs = []
accuracies = []
tprs = []
fprs = []
for row in reader:
label = float(row['Label'])
weight = float(row['Weight'])
prediction = float(row['Prediction'])
costs.append(
weight*(-xlogy(label, prediction)-xlogy(1.0-label, 1.0-prediction))/np.log(2.0)
)
accuracies.append(
100.0*weight*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
if label == 1.0:
tprs.append(
100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
elif label == 0.0:
fprs.append(
100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
else:
print('ERROR: Unrecognized value in the label.')
exit()
filename = path.split('/')[-1].split('.')[0]
_, step, _, _ = filename.split('_')
i = int(step)
if i not in costs_val:
costs_val[i] = []
costs_val[i].append(
np.sum(costs)
)
if i not in accuracies_val:
accuracies_val[i] = []
accuracies_val[i].append(
np.sum(accuracies)
)
if len(tprs) > 0:
if i not in tprs_val:
tprs_val[i] = []
tprs_val[i].append(
np.mean(tprs)
)
if len(fprs) > 0:
if i not in fprs_val:
fprs_val[i] = []
fprs_val[i].append(
np.mean(fprs)
)
##########################################################################################
# Results
##########################################################################################
print(
'Step',
'Accuracy_Train', 'TRP_Train', 'FPR_Train', 'Cost_train',
'Accuracy_Val', 'TRP_Val', 'FPR_Val', 'Cost_Val',
sep=','
)
for i in sorted(accuracies_train.keys()):
print(
i,
np.mean(accuracies_train[i]), np.mean(tprs_train[i]), np.mean(fprs_train[i]), np.mean(costs_train[i]),
np.mean(accuracies_val[i]), np.mean(tprs_val[i]), np.mean(fprs_val[i]), np.mean(costs_val[i]),
sep=','
)
================================================
FILE: breast-cancer/train_val.py
================================================
#!/usr/bin/env python3
##########################################################################################
# Author: Jared L. Ostmeyer
# Date Started: 2021-11-16
# Purpose: Train and validate a classifier for immune repertoires
##########################################################################################
##########################################################################################
# Libraries
##########################################################################################
import argparse
import csv
import glob
import dataplumbing as dp
import dataset as ds
import numpy as np
import torch
##########################################################################################
# Arguments
##########################################################################################
parser = argparse.ArgumentParser()
parser.add_argument('--holdouts', help='Holdout samples', type=str, nargs='+', required=True)
parser.add_argument('--restart', help='Basename for restart files', type=str, default=None)
parser.add_argument('--output', help='Basename for output files', type=str, required=True)
parser.add_argument('--seed', help='Seed value for randomly initializing fits', type=int, default=1)
parser.add_argument('--device', help='Examples are cuda:0 or cpu', type=str, default='cuda:0')
parser.add_argument('--num_fits', help='Number of fits to the training data', type=int, default=2**17)
args = parser.parse_args()
##########################################################################################
# Assemble sequences
##########################################################################################
# Settings
#
trim_front = 3
trim_rear = 3
kmer_size = 4
# To hold sequences from each subject
#
cases = {}
controls = {}
# Load immune repertoires
#
for path in glob.glob('dataset/*.tsv'):
cdr3s = dp.load_cdr3s(path, min_length=kmer_size+trim_front+trim_rear, max_length=32)
cdr3s = dp.trim_cdr3s(cdr3s, trim_front=trim_front, trim_rear=trim_rear)
kmers = dp.cdr3s_to_kmers(cdr3s, kmer_size)
kmers = dp.normalize_sample(kmers)
subject = path.split('/')[-1].split('.')[0]
if 'BR' in subject:
cases[subject] = kmers
elif 'HIP' in subject:
controls[subject] = kmers
##########################################################################################
# Assemble datasets
##########################################################################################
# Load embeddings
#
aminoacids_dict = ds.load_aminoacid_embedding_dict('../aminoacid-representation/atchley_factors_normalized.csv')
# Convert to numeric representations
#
samples = ds.assemble_samples(cases, controls, aminoacids_dict)
# Split into a training and validation cohort
#
samples_train, samples_val = ds.split_samples(samples, args.holdouts)
# Weight samples
#
samples_train = ds.weight_samples(samples_train)
samples_val = ds.weight_samples(samples_val)
# Normalize features
#
samples_train, samples_val = ds.normalize_samples(samples_train, samples_val)
##########################################################################################
# Assemble tensors
##########################################################################################
# Settings
#
device = torch.device(args.device)
# Convert numpy arrays to pytorch tensors
#
for sample in samples_train:
sample['features'] = torch.from_numpy(sample['features']).to(device)
sample['label'] = torch.tensor(sample['label']).to(device)
sample['weight'] = torch.tensor(sample['weight']).to(device)
# Convert numpy arrays to pytorch tensors
#
for sample in samples_val:
sample['features'] = torch.from_numpy(sample['features']).to(device)
sample['label'] = torch.tensor(sample['label']).to(device)
sample['weight'] = torch.tensor(sample['weight']).to(device)
##########################################################################################
# Model
##########################################################################################
# Settings
#
num_features = samples_train[0]['features'].shape[1]
num_fits = args.num_fits
torch.manual_seed(args.seed)
# Function for initializing the weights of the model
#
def init_weights():
return torch.cat(
[
0.5**0.5*torch.rand([ num_features-1, num_fits ])/(num_features-1.0)**0.5, # Weights for the Atchley factors
0.5**0.5*torch.rand([ 1, num_fits ])/(1.0)**0.5, # Weight for the abundance term
],
0
)
# Class defining the model
#
class MaxSnippetModel(torch.nn.Module):
def __init__(self):
super(MaxSnippetModel, self).__init__()
self.linear = torch.nn.Linear(num_features, num_fits)
with torch.no_grad():
self.linear.weights = init_weights() # Initialize the weights
def forward(self, x):
ls = self.linear(x)
ms, _ = torch.max(ls, axis=0)
return ms
# Instantiation of the model
#
msm = MaxSnippetModel()
# Turn on GPU acceleration
#
msm.to(device)
##########################################################################################
# Metrics and optimization
##########################################################################################
# Settings
#
learning_rate = 0.01
# Optimizer
#
optimizer = torch.optim.Adam(msm.parameters(), lr=learning_rate) # Adam is based on gradient descent but better
# Metrics
#
loss = torch.nn.BCEWithLogitsLoss(reduction='none') # The loss function is calculated seperately for each fit by setting reduction to none
def accuracy(ls_block, ys_block): # The binary accuracy is calculated seperate for each fit
a = torch.nn.Sigmoid()
ps_block = a(ls_block)
cs_block = (torch.round(ps_block) == torch.round(ys_block)).to(ys_block.dtype)
return cs_block
##########################################################################################
# Fit and evaluate model
##########################################################################################
# Settings
#
num_epochs = 2048
# Restore saved models
#
if args.restart is not None:
msm = torch.load(args.output+'_model.p')
# Each iteration represents one batch
#
for epoch in range(0, num_epochs):
# Reset the gradients
#
optimizer.zero_grad()
es_train = 0.0 # Cross-entropy error
as_train = 0.0 # Accuracy
for sample in samples_train:
xs_block = sample['features']
ys_block = torch.tile(sample['label'], [ num_fits ])
w_block = sample['weight']
ls_block = msm(xs_block)
sample['predictions'] = torch.sigmoid(ls_block)
es_block = w_block*loss(ls_block, ys_block) # The loss function is calculated seperately for each fit
as_block = w_block*accuracy(ls_block, ys_block) # The binary accuracy is calculated seperate for each fit
es_train += es_block.detach()
as_train += as_block.detach()
e_block = torch.sum(es_block)
e_block.backward()
i_bestfit = torch.argmin(es_train) # Very important index selects the best fit to the training data
es_val = 0.0
as_val = 0.0
with torch.no_grad():
for sample in samples_val:
xs_block = sample['features']
ys_block = torch.tile(sample['label'], [ num_fits ])
w_block = sample['weight']
ls_block = msm(xs_block)
sample['predictions'] = torch.sigmoid(ls_block)
es_block = w_block*loss(ls_block, ys_block) # The loss function is calculated seperately for each fit
as_block = w_block*accuracy(ls_block, ys_block) # The binary accuracy is calculated seperate for each fit
es_val += es_block.detach()
as_val += as_block.detach()
# Print report
#
print(
'Epoch:', epoch,
'Accuracy (train):', round(100.0*float(as_train[i_bestfit]), 2), '%',
'Accuracy (val):', round(100.0*float(as_val[i_bestfit]), 2), '%',
flush=True
)
# Save parameters and results from the best fit to the training data
#
if epoch%32 == 0:
ws = msm.linear.weights.detach().numpy()
bs = msm.linear.bias.cpu().detach().numpy()
np.savetxt(args.output+'_'+str(epoch)+'_ws.csv', ws[:,i_bestfit])
np.savetxt(args.output+'_'+str(epoch)+'_b.csv', bs[[i_bestfit.cpu()]])
with open(args.output+'_'+str(epoch)+'_ms_train.csv', 'w') as stream:
print('Cross Entropy (bits)', 'Accuracy (%)', sep=',', file=stream)
print(float(es_train[i_bestfit])/np.log(2.0), 100.0*float(as_train[i_bestfit]), sep=',', file=stream)
with open(args.output+'_'+str(epoch)+'_ms_val.csv', 'w') as stream:
print('Cross Entropy (bits)', 'Accuracy (%)', sep=',', file=stream)
print(float(es_val[i_bestfit])/np.log(2.0), 100.0*float(as_val[i_bestfit]), sep=',', file=stream)
with open(args.output+'_'+str(epoch)+'_ps_train.csv', 'w') as stream:
print('Subject', 'Label', 'Weight', 'Prediction', sep=',', file=stream)
for sample in samples_train:
print(sample['subject'], float(sample['label']), float(sample['weight']), float(sample['predictions'][i_bestfit]), sep=',', file=stream)
with open(args.output+'_'+str(epoch)+'_ps_val.csv', 'w') as stream:
print('Subject', 'Label', 'Weight', 'Prediction', sep=',', file=stream)
for sample in samples_val:
print(sample['subject'], float(sample['label']), float(sample['weight']), float(sample['predictions'][i_bestfit]), sep=',', file=stream)
optimizer.step()
torch.save(msm, args.output+'_model.p')
================================================
FILE: cervical-cancer/README.md
================================================
# Instructions
This 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.
## Dataset
The 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.
```
cd dataset
unzip '*.zip'
cd ../
```
## Modeling
This 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.
```
mkdir -p bin
python3 train_val.py --seed 1 --holdouts 112015051_3_38 --output bin/1
python3 train_val.py --seed 1 --holdouts 3-4_DNA --output bin/2
python3 train_val.py --seed 1 --holdouts 5-15_DNA --output bin/3
python3 train_val.py --seed 1 --holdouts 112015051_4_38 --output bin/4
python3 train_val.py --seed 1 --holdouts 2_31 --output bin/5
python3 train_val.py --seed 1 --holdouts 112015051_3_39 --output bin/6
python3 train_val.py --seed 1 --holdouts 4-1_DNA --output bin/7
python3 train_val.py --seed 1 --holdouts 3-11_DNA --output bin/8
python3 train_val.py --seed 1 --holdouts 5-6_DNA --output bin/9
python3 train_val.py --seed 1 --holdouts 112015051_5_33 --output bin/10
python3 train_val.py --seed 1 --holdouts 3-6_DNA --output bin/11
python3 train_val.py --seed 1 --holdouts 112015051_5_31 --output bin/12
python3 train_val.py --seed 1 --holdouts 112015051_5_39 --output bin/13
python3 train_val.py --seed 1 --holdouts 4-2_DNA --output bin/14
python3 train_val.py --seed 1 --holdouts 112015051_3_40 --output bin/15
python3 train_val.py --seed 1 --holdouts 4-13_DNA --output bin/16
python3 train_val.py --seed 1 --holdouts 5-19_DNA --output bin/17
python3 train_val.py --seed 1 --holdouts 4-22_DNA --output bin/18
python3 train_val.py --seed 1 --holdouts 112015051_4_33 --output bin/19
python3 train_val.py --seed 1 --holdouts 2-30_DNA --output bin/20
python3 train_val.py --seed 1 --holdouts 5-27A_DNA --output bin/21
python3 train_val.py --seed 1 --holdouts 112015051_3_32 --output bin/22
python3 train_val.py --seed 1 --holdouts 112015051_5_35 --output bin/23
python3 train_val.py --seed 1 --holdouts 4-11_DNA --output bin/24
```
The 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.
## How does this differ from the other examples in this repository?
Patients 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.
## Evaluation
Upon executing each of the aforementioned commands and completing the patient-holdout cross-validation, you can consolidate the results using the command provided below.
```
python3 report.py > report.csv
```
The results are stored in a CSV file that can be opened by your favorite spreadsheet viewer. There are nine columns that represent:
1. The training step.
2. The accuracy on the training data averaged over the cross-validation.
3. The true negative rate (specificity) on the training data averaged over the cross-validation.
4. The true positive rate (sensitivity) on the training data averaged over the cross-validation.
5. The cross-entropy on the training data averaged over the cross-validation.
6. The accuracy on the holdout data averaged over the cross-validation.
7. The true negative rate (specificity) on the holdout data averaged over the cross-validation.
8. The true positive rate (sensitivity) on the holdout data averaged over the cross-validation.
9. The cross-entropy on the holdout data averaged over the cross-validation.
## Publication
* [Cervical Cancer Screening](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC8050337/)
================================================
FILE: cervical-cancer/dataplumbing.py
================================================
#########################################################################################
# Author: Jared L. Ostmeyer
# Date Started: 2021-11-16
# Environment: Python3
# Purpose: Utilities for loading immune receptor sequences
##########################################################################################
##########################################################################################
# Libraries
##########################################################################################
import csv
from itertools import combinations
##########################################################################################
# Utilities
##########################################################################################
def load_cdr3s(path_tsv, min_length=4, max_length=32, version='v2'):
receptors = {}
with open(path_tsv, 'r') as stream:
reader = csv.DictReader(stream, delimiter='\t')
for row in reader:
if version == 'v2':
cdr3 = row['aminoAcid']
# quantity = float(row['frequencyCount (%)'])
quantity = float(row['count (templates/reads)'])
status = row['sequenceStatus']
elif version == 'v3':
cdr3 = row['amino_acid']
# quantity = float(row['frequency'])
quantity = float(row['templates'])
status = row['frame_type']
else:
print('ERROR: Unsupported version')
exit()
if 'In' in status and min_length <= len(cdr3) and len(cdr3) <= max_length and quantity > 0.0 and 'X' not in cdr3:
if cdr3 not in receptors:
receptors[cdr3] = quantity
else:
receptors[cdr3] += quantity
return receptors
def trim_cdr3s(receptors, trim_front=0, trim_rear=0):
cdr3s = {}
for cdr3, quantity in receptors.items():
cdr3_trim = cdr3[trim_front:]
if trim_rear > 0:
cdr3_trim = cdr3_trim[:-trim_rear]
if len(cdr3_trim) > 0:
if cdr3_trim not in cdr3s:
cdr3s[cdr3_trim] = quantity
else:
cdr3s[cdr3_trim] += quantity
return cdr3s
def cdr3s_to_kmers(cdr3s, kmer_size):
kmers = {}
for cdr3, quantity in cdr3s.items():
if len(cdr3) >= kmer_size:
for i in range(len(cdr3)-kmer_size+1):
kmer = cdr3[i:i+kmer_size]
if kmer not in kmers:
kmers[kmer] = quantity
else:
kmers[kmer] += quantity
return kmers
def cdr3s_to_motifs(cdr3s, window_size, motif_size):
templates = []
for template in list(combinations(range(window_size), motif_size)):
if template[0] == 0:
templates.append(template)
motifs = {}
for cdr3, quantity in cdr3s.items():
if len(cdr3) >= motif_size:
for i in range(len(cdr3)-motif_size+1):
window = cdr3[i:i+window_size]
for template in templates:
if template[-1] < len(window):
motif = ''
for i in template:
motif += window[i]
if motif not in motifs:
motifs[motif] = quantity
else:
motifs[motif] += quantity
return motifs
def flatten_sample(sequences):
return { sequence: 1.0 for sequence in sequences.keys() }
def normalize_sample(sequences):
total = 0.0
for quantity in sorted(sequences.values()):
total += quantity
sequences_ = {}
for sequence, quantity in sequences.items():
sequences_[sequence] = quantity/total
return sequences_
def merge_samples(samples):
sequences = {}
for sample in samples:
for sequence, quantity in sample.items():
if sequence not in sequences:
sequences[sequence] = quantity/float(len(samples))
else:
sequences[sequence] += quantity/float(len(samples))
return sequences
def debug_insert_sequence(receptors, sequence, count):
if sequence not in receptors:
receptors[sequence] = count
else:
receptors[sequence] += count
return receptors
================================================
FILE: cervical-cancer/dataset.py
================================================
#########################################################################################
# Author: Jared L. Ostmeyer
# Date Started: 2021-11-16
# Environment: Python3
# Purpose: Utilities for converting immune receptor sequences into numeric features
##########################################################################################
##########################################################################################
# Libraries
##########################################################################################
import csv
import numpy as np
##########################################################################################
# Utilities
##########################################################################################
def load_aminoacid_embedding_dict(path_embedding):
# Amino acid factors
#
names = []
factors = []
with open(path_embedding, 'r') as stream:
for line in stream:
rows = line.split(',')
names.append(rows[0])
factors.append(np.array(rows[1:], dtype=np.float32))
names = np.array(names)
factors = np.array(factors)
# Convert into a dictionary
#
aminoacids_dict = { name: factors[i,:] for i, name in enumerate(names) }
return aminoacids_dict
def assemble_samples(cases, controls, aminoacids_dict):
# Determine tensor dimensions
#
max_steps = -1
for sequences in cases.values():
for sequence in sequences.keys():
if len(sequence) > max_steps:
max_steps = len(sequence)
for sequences in controls.values():
for sequence in sequences.keys():
if len(sequence) > max_steps:
max_steps = len(sequence)
num_factors = len(list(aminoacids_dict.values())[0])
# Assemble dataset
#
samples = []
for subject in sorted(cases.keys()):
sequences = cases[subject]
# Initialize tensors
#
xs = np.zeros([ len(sequences), max_steps*num_factors+1 ], dtype=np.float32)
# Fill tensors
#
for i, ( sequence, quantity ) in enumerate(sorted(sequences.items())):
for j, aa in enumerate(sequence):
xs[i,num_factors*j:num_factors*(j+1)] = aminoacids_dict[aa]
xs[i,-1] = np.log(quantity)
u = np.mean(xs[:,-1])
v = np.var(xs[:,-1])
xs[:,-1] = (xs[:,-1]-u)/np.sqrt(v)
samples.append(
{
'subject': subject,
'features': xs,
'label': 1.0
}
)
for subject in sorted(controls.keys()):
sequences = controls[subject]
# Initialize tensors
#
xs = np.zeros([ len(sequences), max_steps*num_factors+1 ], dtype=np.float32)
# Fill tensors
#
for i, ( sequence, quantity ) in enumerate(sorted(sequences.items())):
for j, aa in enumerate(sequence):
xs[i,num_factors*j:num_factors*(j+1)] = aminoacids_dict[aa]
xs[i,-1] = np.log(quantity)
u = np.mean(xs[:,-1])
v = np.var(xs[:,-1])
xs[:,-1] = (xs[:,-1]-u)/np.sqrt(v)
samples.append(
{
'subject': subject,
'features': xs,
'label': 0.0
}
)
return samples
def split_samples(samples, holdouts):
samples_train = []
samples_val = []
for sample in samples:
if sample['subject'] not in holdouts:
samples_train.append(sample)
else:
samples_val.append(sample)
return samples_train, samples_val
def weight_samples(samples):
num_case = 0
num_control = 0
for sample in samples:
if sample['label'] > 0.5:
num_case += 1
else:
num_control += 1
for sample in samples:
if sample['label'] > 0.5:
sample['weight'] = 0.5/num_case if num_control > 0 else 1.0/num_case
else:
sample['weight'] = 0.5/num_control if num_case > 0 else 1.0/num_control
return samples
def normalize_samples(samples_train, samples_holdout):
# Calculate normalization statistics from the training samples
#
us = 0.0
us2 = 0.0
for sample in samples_train:
xs_sample = sample['features']
us_sample = np.mean(xs_sample, axis=0)
us2_sample = np.mean(xs_sample**2, axis=0)
us += sample['weight']*us_sample
us2 += sample['weight']*us2_sample
vs = us2-us**2
# Normalize the training samples
#
for sample in samples_train:
xs_sample = sample['features']
xs_sample = (xs_sample-us)/np.sqrt(vs)
sample['features'] = xs_sample
# Normalize the holdout samples
#
for sample in samples_holdout:
xs_sample = sample['features']
xs_sample = (xs_sample-us)/np.sqrt(vs)
sample['features'] = xs_sample
return samples_train, samples_holdout
def debug_permute_labels(samples):
labels = []
for sample in samples:
labels.append(sample['label'])
np.random.shuffle(labels)
for sample, label in zip(samples, labels):
sample['label'] = label
return samples
================================================
FILE: cervical-cancer/gold.report.csv
================================================
Step,Accuracy_Train,TRP_Train,FPR_Train,Cost_train,Accuracy_Val,TRP_Val,FPR_Val,Cost_Val
0,50.000000232830644,100.0,0.0,1.0634694351974636,75.0,100.0,0.0,0.8554268361069818
32,50.000000232830644,100.0,0.0,0.9334031339165191,75.0,100.0,0.0,0.8702897988200883
64,55.76388927487036,100.0,11.527777777777779,0.8949095965869437,75.0,100.0,0.0,0.8787156345192338
96,66.6666673341145,100.0,33.333333333333336,0.8603624134151185,75.0,100.0,0.0,0.8866239609609213
128,82.29166773768763,100.0,64.58333333333333,0.8282770790695366,75.0,100.0,0.0,0.8563799333294329
160,84.86111224628985,100.0,69.72222222222223,0.7982708314577837,75.0,100.0,0.0,0.8558552828063647
192,87.1160142744581,99.50980392156862,74.72222222222221,0.7700393627297001,83.33333333333333,100.0,33.333333333333336,0.8463269539004522
224,90.03540432701509,98.5430283224401,81.52777777777777,0.7438618456093575,70.83333333333333,83.33333333333333,33.333333333333336,0.8369867586437527
256,90.23965271189809,97.56263616557733,82.91666666666667,0.7188706127697538,70.83333333333333,83.33333333333333,33.333333333333336,0.8774391341771434
288,92.32570941870411,96.59586056644882,88.05555555555554,0.6954612895595235,70.83333333333333,83.33333333333333,33.333333333333336,0.8761016785176139
320,96.26770299704124,96.84095860566451,95.69444444444444,0.6732027237251303,66.66666666666667,77.77777777777777,33.333333333333336,0.8961094110772311
352,96.14515397697687,96.59586056644879,95.69444444444444,0.6521811053121295,66.66666666666667,77.77777777777777,33.333333333333336,0.8987154658081696
384,97.07788820378482,97.07244008714598,97.08333333333333,0.6321874014473823,62.5,72.22222222222223,33.333333333333336,0.902417650017313
416,98.61655926021437,98.06644880174292,99.16666666666667,0.6130386018997859,66.66666666666667,77.77777777777777,33.333333333333336,0.8968461326272417
448,98.62336753867567,98.08006535947713,99.16666666666667,0.5946679742890651,66.66666666666667,77.77777777777777,33.333333333333336,0.8951872277239626
480,98.80855272834499,97.61710239651417,100.0,0.5773249839932246,66.66666666666667,72.22222222222223,50.0,0.8867685804877564
512,98.80855272834499,97.61710239651416,100.0,0.5607548173989209,66.66666666666667,72.22222222222223,50.0,0.892859816297781
544,98.57707124513884,97.15413943355121,100.0,0.545210859300138,66.66666666666667,72.22222222222223,50.0,0.8747522133486937
576,98.93791002687067,97.87581699346406,100.0,0.5302248540468361,70.83333333333333,77.77777777777777,50.0,0.8591929362288866
608,99.04684249001245,98.09368191721133,100.0,0.5157593958414521,62.5,72.22222222222223,33.333333333333336,0.9273084820596301
640,98.93110174840938,97.86220043572985,100.0,0.501964532491237,62.5,72.22222222222223,33.333333333333336,0.9351755813220107
672,98.92429346994807,97.84858387799564,100.0,0.48878516330200794,58.333333333333336,66.66666666666667,33.333333333333336,0.9477638420703115
704,99.16258323161553,98.32516339869282,100.0,0.47616100426724356,58.333333333333336,66.66666666666667,33.333333333333336,0.9645430628786023
736,99.04684249001245,98.09368191721133,100.0,0.4640593983495253,58.333333333333336,66.66666666666667,33.333333333333336,0.9434826356367502
768,99.2851322516799,98.57026143790851,100.0,0.4525845447317966,62.5,72.22222222222223,33.333333333333336,0.964542368104469
800,99.16258323161553,98.32516339869282,100.0,0.4414310126941354,58.333333333333336,66.66666666666667,33.333333333333336,0.9833559404330657
832,99.16258323161553,98.32516339869282,100.0,0.4307829687697815,58.333333333333336,66.66666666666667,33.333333333333336,1.0065603144518112
864,99.2783239732186,98.5566448801743,100.0,0.4205502539730311,58.333333333333336,66.66666666666667,33.333333333333336,1.00343599750756
896,99.2783239732186,98.55664488017429,100.0,0.41069690719385904,58.333333333333336,66.66666666666667,33.333333333333336,1.0209493622585424
928,99.2783239732186,98.5566448801743,100.0,0.4010567565771413,58.333333333333336,66.66666666666667,33.333333333333336,1.0325164928686876
960,99.2783239732186,98.5566448801743,100.0,0.391909282709473,54.166666666666664,66.66666666666667,16.666666666666668,1.0514157673023952
992,99.2783239732186,98.5566448801743,100.0,0.38300871020181787,54.166666666666664,66.66666666666667,16.666666666666668,1.0606235633185321
1024,99.52342201334734,99.04684095860567,100.0,0.3745122770633142,58.333333333333336,72.22222222222223,16.666666666666668,1.0571691501962264
1056,99.52342201334734,99.04684095860567,100.0,0.3660535339704964,62.5,72.22222222222223,33.333333333333336,1.05738866515358
1088,99.51661373488605,99.03322440087146,100.0,0.3581120690495103,62.5,72.22222222222223,33.333333333333336,1.0182468240718021
1120,99.63916275495042,99.27832244008714,100.0,0.3502775518824605,62.5,72.22222222222223,33.333333333333336,1.0468283152583353
1152,99.63916275495042,99.27832244008715,100.0,0.3427729184239747,62.5,72.22222222222223,33.333333333333336,1.0056428391349492
1184,99.7617117750148,99.52342047930283,100.0,0.33543198021426296,62.5,72.22222222222223,33.333333333333336,1.0778154195170642
1216,99.7617117750148,99.52342047930283,100.0,0.3282812682931278,62.5,72.22222222222223,33.333333333333336,1.050291907953176
1248,99.7617117750148,99.52342047930283,100.0,0.32149969837560427,58.333333333333336,66.66666666666667,33.333333333333336,1.0846131209760779
1280,99.7617117750148,99.52342047930283,100.0,0.3147783563942984,58.333333333333336,66.66666666666667,33.333333333333336,1.0945050866914154
1312,99.87745251661788,99.75490196078431,100.0,0.3084497572798046,58.333333333333336,66.66666666666667,33.333333333333336,1.1136941745214457
1344,99.7617117750148,99.52342047930283,100.0,0.30213019734677077,58.333333333333336,66.66666666666667,33.333333333333336,1.1135871047690111
1376,99.87745251661788,99.75490196078431,100.0,0.2959683573204777,58.333333333333336,66.66666666666667,33.333333333333336,1.1528383197506067
1408,99.87745251661788,99.75490196078431,100.0,0.2899510179658565,58.333333333333336,66.66666666666667,33.333333333333336,1.1590160818101067
1440,99.87745251661788,99.75490196078431,100.0,0.2843179585993099,58.333333333333336,66.66666666666667,33.333333333333336,1.1693464632209356
1472,99.87745251661788,99.75490196078431,100.0,0.27863738389993253,58.333333333333336,66.66666666666667,33.333333333333336,1.1814312089756471
1504,99.87745251661788,99.75490196078431,100.0,0.27322572759999525,58.333333333333336,66.66666666666667,33.333333333333336,1.1887506610304475
1536,99.7549034965535,99.50980392156862,100.0,0.26796076192267465,54.166666666666664,61.111111111111114,33.333333333333336,1.2936243087352561
1568,99.87745251661788,99.75490196078431,100.0,0.26266453605726786,58.333333333333336,66.66666666666667,33.333333333333336,1.2851303422267801
1600,99.87745251661788,99.75490196078431,100.0,0.2576251850393286,62.5,72.22222222222223,33.333333333333336,1.2750365884846881
1632,99.87745251661788,99.75490196078431,100.0,0.2527183558150053,62.5,72.22222222222223,33.333333333333336,1.2843436473199483
1664,99.87745251661788,99.75490196078431,100.0,0.24800572360031034,62.5,72.22222222222223,33.333333333333336,1.2931612462555375
1696,99.87745251661788,99.75490196078431,100.0,0.24328414524718378,62.5,72.22222222222223,33.333333333333336,1.304073469485531
1728,100.00000153668225,100.0,100.0,0.23869307529349573,62.5,72.22222222222223,33.333333333333336,1.31155561028911
1760,100.00000153668225,100.0,100.0,0.23428441173316691,62.5,72.22222222222223,33.333333333333336,1.3246346275131644
1792,100.00000153668225,100.0,100.0,0.23005443097415115,62.5,72.22222222222223,33.333333333333336,1.3306561863060427
1824,100.00000153668225,100.0,100.0,0.2258117014117641,62.5,72.22222222222223,33.333333333333336,1.3419289701434165
1856,100.00000153668225,100.0,100.0,0.22164463687868038,62.5,72.22222222222223,33.333333333333336,1.3511359678562596
1888,100.00000153668225,100.0,100.0,0.21759565281646961,62.5,72.22222222222223,33.333333333333336,1.3568514382680557
1920,100.00000153668225,100.0,100.0,0.21359155371278246,62.5,72.22222222222223,33.333333333333336,1.3679553524939767
1952,100.00000153668225,100.0,100.0,0.20983161099332226,62.5,72.22222222222223,33.333333333333336,1.3744357966892808
1984,100.00000153668225,100.0,100.0,0.2060198270746907,62.5,72.22222222222223,33.333333333333336,1.4083040914817715
2016,100.00000153668225,100.0,100.0,0.2025229832087374,62.5,72.22222222222223,33.333333333333336,1.4195121176262238
================================================
FILE: cervical-cancer/report.py
================================================
#!/usr/bin/env python3
##########################################################################################
# Author: Jared L. Ostmeyer
# Date Started: 2018-02-05
# Purpose: Print results of the holdout cross-validation
##########################################################################################
##########################################################################################
# Libraries
##########################################################################################
import glob
import csv
from scipy.special import xlogy
import numpy as np
##########################################################################################
# Load data
##########################################################################################
costs_train = {}
accuracies_train = {}
tprs_train = {}
fprs_train = {}
for path in glob.glob('bin/*_ps_train.csv'):
with open(path, 'r') as stream:
reader = csv.DictReader(stream)
costs = []
accuracies = []
tprs = []
fprs = []
for row in reader:
label = float(row['Label'])
weight = float(row['Weight'])
prediction = float(row['Prediction'])
costs.append(
weight*(-xlogy(label, prediction)-xlogy(1.0-label, 1.0-prediction))/np.log(2.0)
)
accuracies.append(
100.0*weight*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
if label == 1.0:
tprs.append(
100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
elif label == 0.0:
fprs.append(
100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
else:
print('ERROR: Unrecognized value in the label.')
exit()
filename = path.split('/')[-1].split('.')[0]
_, step, _, _ = filename.split('_')
i = int(step)
if i not in costs_train:
costs_train[i] = []
costs_train[i].append(
np.sum(costs)
)
if i not in accuracies_train:
accuracies_train[i] = []
accuracies_train[i].append(
np.sum(accuracies)
)
if len(tprs) > 0:
if i not in tprs_train:
tprs_train[i] = []
tprs_train[i].append(
np.mean(tprs)
)
if len(fprs) > 0:
if i not in fprs_train:
fprs_train[i] = []
fprs_train[i].append(
np.mean(fprs)
)
costs_val = {}
accuracies_val = {}
tprs_val = {}
fprs_val = {}
for path in glob.glob('bin/*_ps_val.csv'):
with open(path, 'r') as stream:
reader = csv.DictReader(stream)
costs = []
accuracies = []
tprs = []
fprs = []
for row in reader:
label = float(row['Label'])
weight = float(row['Weight'])
prediction = float(row['Prediction'])
costs.append(
weight*(-xlogy(label, prediction)-xlogy(1.0-label, 1.0-prediction))/np.log(2.0)
)
accuracies.append(
100.0*weight*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
if label == 1.0:
tprs.append(
100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
elif label == 0.0:
fprs.append(
100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
else:
print('ERROR: Unrecognized value in the label.')
exit()
filename = path.split('/')[-1].split('.')[0]
_, step, _, _ = filename.split('_')
i = int(step)
if i not in costs_val:
costs_val[i] = []
costs_val[i].append(
np.sum(costs)
)
if i not in accuracies_val:
accuracies_val[i] = []
accuracies_val[i].append(
np.sum(accuracies)
)
if len(tprs) > 0:
if i not in tprs_val:
tprs_val[i] = []
tprs_val[i].append(
np.mean(tprs)
)
if len(fprs) > 0:
if i not in fprs_val:
fprs_val[i] = []
fprs_val[i].append(
np.mean(fprs)
)
##########################################################################################
# Results
##########################################################################################
print(
'Step',
'Accuracy_Train', 'TRP_Train', 'FPR_Train', 'Cost_train',
'Accuracy_Val', 'TRP_Val', 'FPR_Val', 'Cost_Val',
sep=','
)
for i in sorted(accuracies_train.keys()):
print(
i,
np.mean(accuracies_train[i]), np.mean(tprs_train[i]), np.mean(fprs_train[i]), np.mean(costs_train[i]),
np.mean(accuracies_val[i]), np.mean(tprs_val[i]), np.mean(fprs_val[i]), np.mean(costs_val[i]),
sep=','
)
================================================
FILE: cervical-cancer/train_val.py
================================================
#!/usr/bin/env python3
##########################################################################################
# Author: Jared L. Ostmeyer
# Date Started: 2021-11-16
# Purpose: Train and validate a classifier for immune repertoires
##########################################################################################
##########################################################################################
# Libraries
##########################################################################################
import argparse
import csv
import glob
import dataplumbing as dp
import dataset as ds
import numpy as np
import torch
##########################################################################################
# Arguments
##########################################################################################
parser = argparse.ArgumentParser()
parser.add_argument('--holdouts', help='Holdout samples', type=str, nargs='+', required=True)
parser.add_argument('--restart', help='Basename for restart files', type=str, default=None)
parser.add_argument('--output', help='Basename for output files', type=str, required=True)
parser.add_argument('--seed', help='Seed value for randomly initializing fits', type=int, default=1)
parser.add_argument('--device', help='Examples are cuda:0 or cpu', type=str, default='cuda:0')
parser.add_argument('--num_fits', help='Number of fits to the training data', type=int, default=2**17)
args = parser.parse_args()
##########################################################################################
# Assemble sequences
##########################################################################################
# Settings
#
trim_front = 3
trim_rear = 3
kmer_size = 4
# To hold sequences from each subject
#
cases = {}
controls = {}
# Labels
#
samples = {
'2-30_DNA': 'regress',
'2_31': 'regress',
'3-11_DNA': 'progress',
'112015051_3_32': 'regress',
'112015051_3_38': 'regress',
'112015051_3_39': 'regress',
'3-4_DNA': 'progress',
'112015051_3_40': 'progress',
'3-6_DNA': 'regress',
'4-1_DNA': 'regress',
'4-11_DNA': 'regress',
'4-13_DNA': 'regress',
'4-2_DNA': 'regress',
'4-22_DNA': 'regress',
'112015051_4_33': 'regress',
'112015051_4_38': 'progress',
'5-15_DNA': 'regress',
'5-19_DNA': 'same',
'5-27A_DNA': 'regress',
'112015051_5_31': 'regress',
'112015051_5_33': 'regress',
'112015051_5_35': 'regress',
'112015051_5_39': 'same',
'5-6_DNA': 'regress'
}
# Load immune repertoires
#
for sample, label in samples.items():
path = 'dataset/'+sample+'.tsv'
cdr3s = dp.load_cdr3s(path, min_length=kmer_size+trim_front+trim_rear, max_length=32)
cdr3s = dp.trim_cdr3s(cdr3s, trim_front=trim_front, trim_rear=trim_rear)
kmers = dp.cdr3s_to_kmers(cdr3s, kmer_size)
kmers = dp.normalize_sample(kmers)
if 'regress' in label:
cases[sample] = kmers
else:
controls[sample] = kmers
##########################################################################################
# Assemble datasets
##########################################################################################
# Load embeddings
#
aminoacids_dict = ds.load_aminoacid_embedding_dict('../aminoacid-representation/atchley_factors_normalized.csv')
# Convert to numeric representations
#
samples = ds.assemble_samples(cases, controls, aminoacids_dict)
# Split into a training and validation cohort
#
samples_train, samples_val = ds.split_samples(samples, args.holdouts)
# Weight samples
#
samples_train = ds.weight_samples(samples_train)
samples_val = ds.weight_samples(samples_val)
# Normalize features
#
samples_train, samples_val = ds.normalize_samples(samples_train, samples_val)
##########################################################################################
# Assemble tensors
##########################################################################################
# Settings
#
device = torch.device(args.device)
# Convert numpy arrays to pytorch tensors
#
for sample in samples_train:
sample['features'] = torch.from_numpy(sample['features']).to(device)
sample['label'] = torch.tensor(sample['label']).to(device)
sample['weight'] = torch.tensor(sample['weight']).to(device)
# Convert numpy arrays to pytorch tensors
#
for sample in samples_val:
sample['features'] = torch.from_numpy(sample['features']).to(device)
sample['label'] = torch.tensor(sample['label']).to(device)
sample['weight'] = torch.tensor(sample['weight']).to(device)
##########################################################################################
# Model
##########################################################################################
# Settings
#
num_features = samples_train[0]['features'].shape[1]
num_fits = args.num_fits
torch.manual_seed(args.seed)
# Function for initializing the weights of the model
#
def init_weights():
return torch.cat(
[
0.5**0.5*torch.rand([ num_features-1, num_fits ])/(num_features-1.0)**0.5, # Weights for the Atchley factors
0.5**0.5*torch.rand([ 1, num_fits ])/(1.0)**0.5, # Weight for the abundance term
],
0
)
# Class defining the model
#
class MaxSnippetModel(torch.nn.Module):
def __init__(self):
super(MaxSnippetModel, self).__init__()
self.linear = torch.nn.Linear(num_features, num_fits)
with torch.no_grad():
self.linear.weights = init_weights() # Initialize the weights
def forward(self, x):
ls = self.linear(x)
ms, _ = torch.max(ls, axis=0)
return ms
# Instantiation of the model
#
msm = MaxSnippetModel()
# Turn on GPU acceleration
#
msm.to(device)
##########################################################################################
# Metrics and optimization
##########################################################################################
# Settings
#
learning_rate = 0.01
# Optimizer
#
optimizer = torch.optim.Adam(msm.parameters(), lr=learning_rate) # Adam is based on gradient descent but better
# Metrics
#
loss = torch.nn.BCEWithLogitsLoss(reduction='none') # The loss function is calculated seperately for each fit by setting reduction to none
def accuracy(ls_block, ys_block): # The binary accuracy is calculated seperate for each fit
a = torch.nn.Sigmoid()
ps_block = a(ls_block)
cs_block = (torch.round(ps_block) == torch.round(ys_block)).to(ys_block.dtype)
return cs_block
##########################################################################################
# Fit and evaluate model
##########################################################################################
# Settings
#
num_epochs = 2048
# Restore saved models
#
if args.restart is not None:
msm = torch.load(args.output+'_model.p')
# Each iteration represents one batch
#
for epoch in range(0, num_epochs):
# Reset the gradients
#
optimizer.zero_grad()
es_train = 0.0 # Cross-entropy error
as_train = 0.0 # Accuracy
for sample in samples_train:
xs_block = sample['features']
ys_block = torch.tile(sample['label'], [ num_fits ])
w_block = sample['weight']
ls_block = msm(xs_block)
sample['predictions'] = torch.sigmoid(ls_block)
es_block = w_block*loss(ls_block, ys_block) # The loss function is calculated seperately for each fit
as_block = w_block*accuracy(ls_block, ys_block) # The binary accuracy is calculated seperate for each fit
es_train += es_block.detach()
as_train += as_block.detach()
e_block = torch.sum(es_block)
e_block.backward()
i_bestfit = torch.argmin(es_train) # Very important index selects the best fit to the training data
es_val = 0.0
as_val = 0.0
with torch.no_grad():
for sample in samples_val:
xs_block = sample['features']
ys_block = torch.tile(sample['label'], [ num_fits ])
w_block = sample['weight']
ls_block = msm(xs_block)
sample['predictions'] = torch.sigmoid(ls_block)
es_block = w_block*loss(ls_block, ys_block) # The loss function is calculated seperately for each fit
as_block = w_block*accuracy(ls_block, ys_block) # The binary accuracy is calculated seperate for each fit
es_val += es_block.detach()
as_val += as_block.detach()
# Print report
#
print(
'Epoch:', epoch,
'Accuracy (train):', round(100.0*float(as_train[i_bestfit]), 2), '%',
'Accuracy (val):', round(100.0*float(as_val[i_bestfit]), 2), '%',
flush=True
)
# Save parameters and results from the best fit to the training data
#
if epoch%32 == 0:
ws = msm.linear.weights.detach().numpy()
bs = msm.linear.bias.cpu().detach().numpy()
np.savetxt(args.output+'_'+str(epoch)+'_ws.csv', ws[:,i_bestfit])
np.savetxt(args.output+'_'+str(epoch)+'_b.csv', bs[[i_bestfit.cpu()]])
with open(args.output+'_'+str(epoch)+'_ms_train.csv', 'w') as stream:
print('Cross Entropy (bits)', 'Accuracy (%)', sep=',', file=stream)
print(float(es_train[i_bestfit])/np.log(2.0), 100.0*float(as_train[i_bestfit]), sep=',', file=stream)
with open(args.output+'_'+str(epoch)+'_ms_val.csv', 'w') as stream:
print('Cross Entropy (bits)', 'Accuracy (%)', sep=',', file=stream)
print(float(es_val[i_bestfit])/np.log(2.0), 100.0*float(as_val[i_bestfit]), sep=',', file=stream)
with open(args.output+'_'+str(epoch)+'_ps_train.csv', 'w') as stream:
print('Subject', 'Label', 'Weight', 'Prediction', sep=',', file=stream)
for sample in samples_train:
print(sample['subject'], float(sample['label']), float(sample['weight']), float(sample['predictions'][i_bestfit]), sep=',', file=stream)
with open(args.output+'_'+str(epoch)+'_ps_val.csv', 'w') as stream:
print('Subject', 'Label', 'Weight', 'Prediction', sep=',', file=stream)
for sample in samples_val:
print(sample['subject'], float(sample['label']), float(sample['weight']), float(sample['predictions'][i_bestfit]), sep=',', file=stream)
optimizer.step()
torch.save(msm, args.output+'_model.p')
================================================
FILE: colorectal-cancer/README.md
================================================
# Instructions
This 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.
## Dataset
In 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.
```
cd dataset
unzip '*.zip'
cd ../
```
## Modeling
This 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.
```
mkdir -p bin
python3 train_val.py --seed 1 --holdouts Patient1 --output bin/1
python3 train_val.py --seed 1 --holdouts Patient2 --output bin/2
python3 train_val.py --seed 1 --holdouts Patient3 --output bin/3
python3 train_val.py --seed 1 --holdouts Patient4 --output bin/4
python3 train_val.py --seed 1 --holdouts Patient5 --output bin/5
python3 train_val.py --seed 1 --holdouts Patient6 --output bin/6
python3 train_val.py --seed 1 --holdouts Patient7 --output bin/7
python3 train_val.py --seed 1 --holdouts Patient8 --output bin/8
python3 train_val.py --seed 1 --holdouts Patient9 --output bin/9
python3 train_val.py --seed 1 --holdouts Patient10 --output bin/10
python3 train_val.py --seed 1 --holdouts Patient11 --output bin/11
python3 train_val.py --seed 1 --holdouts Patient12 --output bin/12
python3 train_val.py --seed 1 --holdouts Patient13 --output bin/13
python3 train_val.py --seed 1 --holdouts Patient14 --output bin/14
```
The 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.
## Evaluation
Upon executing each of the aforementioned commands and completing the patient-holdout cross-validation, you can consolidate the results using the command provided below.
```
python3 report.py > report.csv
```
The results are stored in a CSV file that can be opened by your favorite spreadsheet viewer. There are nine columns that represent:
1. The training step.
2. The accuracy on the training data averaged over the cross-validation.
3. The true negative rate (specificity) on the training data averaged over the cross-validation.
4. The true positive rate (sensitivity) on the training data averaged over the cross-validation.
5. The cross-entropy on the training data averaged over the cross-validation.
6. The accuracy on the holdout data averaged over the cross-validation.
7. The true negative rate (specificity) on the holdout data averaged over the cross-validation.
8. The true positive rate (sensitivity) on the holdout data averaged over the cross-validation.
9. The cross-entropy on the holdout data averaged over the cross-validation.
## Publication
* [Source of Samples](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5714653/)
* [Original Breast Cancer Model](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6445742/)
================================================
FILE: colorectal-cancer/dataplumbing.py
================================================
#########################################################################################
# Author: Jared L. Ostmeyer
# Date Started: 2021-11-16
# Environment: Python3
# Purpose: Utilities for loading immune receptor sequences
##########################################################################################
##########################################################################################
# Libraries
##########################################################################################
import csv
from itertools import combinations
##########################################################################################
# Utilities
##########################################################################################
def load_cdr3s(path_tsv, min_length=4, max_length=32, version='v2'):
receptors = {}
with open(path_tsv, 'r') as stream:
reader = csv.DictReader(stream, delimiter='\t')
for row in reader:
if version == 'v2':
cdr3 = row['aminoAcid']
# quantity = float(row['frequencyCount (%)'])
quantity = float(row['count (templates/reads)'])
status = row['sequenceStatus']
elif version == 'v3':
cdr3 = row['amino_acid']
# quantity = float(row['frequency'])
quantity = float(row['templates'])
status = row['frame_type']
else:
print('ERROR: Unsupported version')
exit()
if 'In' in status and min_length <= len(cdr3) and len(cdr3) <= max_length and quantity > 0.0 and 'X' not in cdr3:
if cdr3 not in receptors:
receptors[cdr3] = quantity
else:
receptors[cdr3] += quantity
return receptors
def trim_cdr3s(receptors, trim_front=0, trim_rear=0):
cdr3s = {}
for cdr3, quantity in receptors.items():
cdr3_trim = cdr3[trim_front:]
if trim_rear > 0:
cdr3_trim = cdr3_trim[:-trim_rear]
if len(cdr3_trim) > 0:
if cdr3_trim not in cdr3s:
cdr3s[cdr3_trim] = quantity
else:
cdr3s[cdr3_trim] += quantity
return cdr3s
def cdr3s_to_kmers(cdr3s, kmer_size):
kmers = {}
for cdr3, quantity in cdr3s.items():
if len(cdr3) >= kmer_size:
for i in range(len(cdr3)-kmer_size+1):
kmer = cdr3[i:i+kmer_size]
if kmer not in kmers:
kmers[kmer] = quantity
else:
kmers[kmer] += quantity
return kmers
def cdr3s_to_motifs(cdr3s, window_size, motif_size):
templates = []
for template in list(combinations(range(window_size), motif_size)):
if template[0] == 0:
templates.append(template)
motifs = {}
for cdr3, quantity in cdr3s.items():
if len(cdr3) >= motif_size:
for i in range(len(cdr3)-motif_size+1):
window = cdr3[i:i+window_size]
for template in templates:
if template[-1] < len(window):
motif = ''
for i in template:
motif += window[i]
if motif not in motifs:
motifs[motif] = quantity
else:
motifs[motif] += quantity
return motifs
def flatten_sample(sequences):
return { sequence: 1.0 for sequence in sequences.keys() }
def normalize_sample(sequences):
total = 0.0
for quantity in sorted(sequences.values()):
total += quantity
sequences_ = {}
for sequence, quantity in sequences.items():
sequences_[sequence] = quantity/total
return sequences_
def merge_samples(samples):
sequences = {}
for sample in samples:
for sequence, quantity in sample.items():
if sequence not in sequences:
sequences[sequence] = quantity/float(len(samples))
else:
sequences[sequence] += quantity/float(len(samples))
return sequences
def debug_insert_sequence(receptors, sequence, count):
if sequence not in receptors:
receptors[sequence] = count
else:
receptors[sequence] += count
return receptors
================================================
FILE: colorectal-cancer/dataset.py
================================================
#########################################################################################
# Author: Jared L. Ostmeyer
# Date Started: 2021-11-16
# Environment: Python3
# Purpose: Utilities for converting immune receptor sequences into numeric features
##########################################################################################
##########################################################################################
# Libraries
##########################################################################################
import csv
import numpy as np
##########################################################################################
# Utilities
##########################################################################################
def load_aminoacid_embedding_dict(path_embedding):
# Amino acid factors
#
names = []
factors = []
with open(path_embedding, 'r') as stream:
for line in stream:
rows = line.split(',')
names.append(rows[0])
factors.append(np.array(rows[1:], dtype=np.float32))
names = np.array(names)
factors = np.array(factors)
# Convert into a dictionary
#
aminoacids_dict = { name: factors[i,:] for i, name in enumerate(names) }
return aminoacids_dict
def assemble_samples(cases, controls, aminoacids_dict):
# Determine tensor dimensions
#
max_steps = -1
for sequences in cases.values():
for sequence in sequences.keys():
if len(sequence) > max_steps:
max_steps = len(sequence)
for sequences in controls.values():
for sequence in sequences.keys():
if len(sequence) > max_steps:
max_steps = len(sequence)
num_factors = len(list(aminoacids_dict.values())[0])
# Assemble dataset
#
samples = []
for subject in sorted(cases.keys()):
sequences = cases[subject]
# Initialize tensors
#
xs = np.zeros([ len(sequences), max_steps*num_factors+1 ], dtype=np.float32)
# Fill tensors
#
for i, ( sequence, quantity ) in enumerate(sorted(sequences.items())):
for j, aa in enumerate(sequence):
xs[i,num_factors*j:num_factors*(j+1)] = aminoacids_dict[aa]
xs[i,-1] = np.log(quantity)
u = np.mean(xs[:,-1])
v = np.var(xs[:,-1])
xs[:,-1] = (xs[:,-1]-u)/np.sqrt(v)
samples.append(
{
'subject': subject,
'features': xs,
'label': 1.0
}
)
for subject in sorted(controls.keys()):
sequences = controls[subject]
# Initialize tensors
#
xs = np.zeros([ len(sequences), max_steps*num_factors+1 ], dtype=np.float32)
# Fill tensors
#
for i, ( sequence, quantity ) in enumerate(sorted(sequences.items())):
for j, aa in enumerate(sequence):
xs[i,num_factors*j:num_factors*(j+1)] = aminoacids_dict[aa]
xs[i,-1] = np.log(quantity)
u = np.mean(xs[:,-1])
v = np.var(xs[:,-1])
xs[:,-1] = (xs[:,-1]-u)/np.sqrt(v)
samples.append(
{
'subject': subject,
'features': xs,
'label': 0.0
}
)
return samples
def split_samples(samples, holdouts):
samples_train = []
samples_val = []
for sample in samples:
if sample['subject'] not in holdouts:
samples_train.append(sample)
else:
samples_val.append(sample)
return samples_train, samples_val
def weight_samples(samples):
num_case = 0
num_control = 0
for sample in samples:
if sample['label'] > 0.5:
num_case += 1
else:
num_control += 1
for sample in samples:
if sample['label'] > 0.5:
sample['weight'] = 0.5/num_case if num_control > 0 else 1.0/num_case
else:
sample['weight'] = 0.5/num_control if num_case > 0 else 1.0/num_control
return samples
def normalize_samples(samples_train, samples_holdout):
# Calculate normalization statistics from the training samples
#
us = 0.0
us2 = 0.0
for sample in samples_train:
xs_sample = sample['features']
us_sample = np.mean(xs_sample, axis=0)
us2_sample = np.mean(xs_sample**2, axis=0)
us += sample['weight']*us_sample
us2 += sample['weight']*us2_sample
vs = us2-us**2
# Normalize the training samples
#
for sample in samples_train:
xs_sample = sample['features']
xs_sample = (xs_sample-us)/np.sqrt(vs)
sample['features'] = xs_sample
# Normalize the holdout samples
#
for sample in samples_holdout:
xs_sample = sample['features']
xs_sample = (xs_sample-us)/np.sqrt(vs)
sample['features'] = xs_sample
return samples_train, samples_holdout
def debug_permute_labels(samples):
labels = []
for sample in samples:
labels.append(sample['label'])
np.random.shuffle(labels)
for sample, label in zip(samples, labels):
sample['label'] = label
return samples
================================================
FILE: colorectal-cancer/gold.report.csv
================================================
Step,Accuracy_Train,TRP_Train,FPR_Train,Cost_train,Accuracy_Val,TRP_Val,FPR_Val,Cost_Val
0,50.00000186264515,100.0,0.0,1.0881439744578585,50.0,100.0,0.0,1.1065032239346837
32,50.00000186264515,100.0,0.0,0.9666056012260252,50.0,100.0,0.0,1.0014956872219747
64,50.00000186264515,99.45054945054946,0.5494505494505495,0.945405424172516,42.857142857142854,85.71428571428571,0.0,1.0212423565856366
96,56.31868341671569,98.90109890109889,13.736263736263734,0.9282460340882187,42.857142857142854,85.71428571428571,0.0,1.0196147039954704
128,67.58242010005883,98.9010989010989,36.26373626373626,0.9097048915555551,46.42857142857143,85.71428571428571,7.142857142857143,1.0079379699797113
160,80.4945084931595,99.45054945054946,61.53846153846153,0.8907438170930095,50.0,85.71428571428571,14.285714285714286,1.0090333807174678
192,85.71428890739169,99.45054945054946,71.97802197802199,0.8718586532274488,50.0,78.57142857142857,21.428571428571427,1.0108581268144543
224,87.36264061714921,98.9010989010989,75.82417582417584,0.8532775698077774,53.57142857142857,78.57142857142857,28.571428571428573,1.0067119946551661
256,88.18681647202799,97.80219780219781,78.57142857142857,0.834966302554523,53.57142857142857,78.57142857142857,28.571428571428573,1.007452599447569
288,88.73626704194716,97.25274725274726,80.21978021978022,0.8174033100918975,57.142857142857146,71.42857142857143,42.857142857142854,0.9779638692820152
320,89.56044289682593,97.25274725274726,81.86813186813187,0.7998896203131363,60.714285714285715,71.42857142857143,50.0,0.9796172508233029
352,90.38461875170469,97.80219780219781,82.96703296703296,0.7828980053555642,57.142857142857146,71.42857142857143,42.857142857142854,0.9978110252191862
384,91.48351989154305,97.80219780219781,85.16483516483515,0.7663747789680074,57.142857142857146,71.42857142857143,42.857142857142854,0.9997084227495041
416,92.30769574642181,97.25274725274726,87.36263736263736,0.7506304530237441,53.57142857142857,64.28571428571429,42.857142857142854,0.9985832522178227
448,92.5824210313814,97.25274725274724,87.9120879120879,0.7352956188089965,53.57142857142857,64.28571428571429,42.857142857142854,0.9968082632009411
480,93.13187160130057,97.25274725274726,89.010989010989,0.7204149906047868,53.57142857142857,64.28571428571429,42.857142857142854,0.9965770713724125
512,93.40659688626017,97.25274725274724,89.56043956043956,0.7060286237591064,57.142857142857146,64.28571428571429,50.0,0.9957834990015566
544,93.40659688626017,97.25274725274724,89.56043956043956,0.6919458740309858,57.142857142857146,64.28571428571429,50.0,0.9984296529378182
576,93.68132217121976,97.25274725274726,90.1098901098901,0.6785377600422074,57.142857142857146,64.28571428571429,50.0,1.0009971071441892
608,93.68132217121976,96.70329670329672,90.65934065934066,0.6655857760481575,64.28571428571429,57.142857142857146,71.42857142857143,0.966618726160825
640,93.95604745617935,97.25274725274726,90.65934065934064,0.6530428635256289,57.142857142857146,57.142857142857146,57.142857142857146,0.9989855242657754
672,94.23077274113894,97.25274725274724,91.20879120879121,0.6410200189686145,60.714285714285715,57.142857142857146,64.28571428571429,1.002178738400748
704,93.95604745617935,97.25274725274726,90.65934065934064,0.6294766597079416,60.714285714285715,57.142857142857146,64.28571428571429,1.004734253893208
736,94.23077274113894,97.25274725274724,91.20879120879121,0.6181324745095693,64.28571428571429,57.142857142857146,71.42857142857143,0.9821739215487931
768,95.0549485960177,97.80219780219781,92.3076923076923,0.6070587051300939,64.28571428571429,57.142857142857146,71.42857142857143,0.9700133339767305
800,95.0549485960177,97.80219780219781,92.3076923076923,0.5962523185995457,64.28571428571429,57.142857142857146,71.42857142857143,0.9703092249442438
832,94.78022331105811,97.25274725274726,92.3076923076923,0.5858770288182199,64.28571428571429,50.0,78.57142857142857,0.9919944967660701
864,95.3296738809773,97.25274725274726,93.4065934065934,0.5755775219818444,67.85714285714286,57.142857142857146,78.57142857142857,0.9780689145963589
896,95.3296738809773,97.25274725274726,93.4065934065934,0.5656879074719912,67.85714285714286,57.142857142857146,78.57142857142857,0.9764508297013126
928,95.3296738809773,97.25274725274724,93.40659340659342,0.5559427401892524,60.714285714285715,50.0,71.42857142857143,1.0121962773878648
960,95.3296738809773,97.25274725274724,93.4065934065934,0.5466123558863033,60.714285714285715,50.0,71.42857142857143,1.0164603980954958
992,95.60439916593688,97.25274725274726,93.95604395604396,0.5374986408841845,60.714285714285715,50.0,71.42857142857143,1.0150157685089352
1024,95.60439916593688,97.25274725274726,93.95604395604396,0.5287220296055044,60.714285714285715,50.0,71.42857142857143,1.0190886667509313
1056,95.87912445089647,97.25274725274724,94.50549450549453,0.5201257157404621,60.714285714285715,50.0,71.42857142857143,1.020774235656863
1088,95.87912445089647,97.25274725274724,94.50549450549453,0.5117593226460525,60.714285714285715,50.0,71.42857142857143,1.0243199707118837
1120,96.15384973585606,97.25274725274724,95.05494505494507,0.5036681645608095,60.714285714285715,50.0,71.42857142857143,1.028799671718467
1152,96.70330030577523,97.25274725274728,96.15384615384616,0.4957527739839653,60.714285714285715,50.0,71.42857142857143,1.0310785068217228
1184,96.70330030577523,97.25274725274724,96.15384615384616,0.4880586901656048,60.714285714285715,50.0,71.42857142857143,1.0347101259192926
1216,96.70330030577523,97.25274725274724,96.15384615384616,0.4805858955148957,60.714285714285715,50.0,71.42857142857143,1.0951665519770672
1248,96.70330030577523,97.25274725274724,96.15384615384616,0.4732428644031068,60.714285714285715,50.0,71.42857142857143,1.1012568918721952
1280,96.70330030577523,97.25274725274726,96.15384615384616,0.46607263096878004,60.714285714285715,50.0,71.42857142857143,1.1063644282439575
1312,96.97802559073482,97.25274725274724,96.70329670329672,0.4591182290886128,60.714285714285715,50.0,71.42857142857143,1.1112164674602203
1344,96.70330030577523,97.25274725274724,96.15384615384617,0.45228862931132746,60.714285714285715,50.0,71.42857142857143,1.1157842074243587
1376,96.70330030577523,96.70329670329672,96.7032967032967,0.44560730293788614,57.142857142857146,50.0,64.28571428571429,1.1339305413141858
1408,96.97802559073482,96.70329670329672,97.25274725274724,0.4389851200646443,57.142857142857146,50.0,64.28571428571429,1.1379203740435273
1440,96.97802559073482,96.7032967032967,97.25274725274724,0.43262298529223714,57.142857142857146,50.0,64.28571428571429,1.1432987096084548
1472,96.97802559073482,96.7032967032967,97.25274725274726,0.42645455632203433,57.142857142857146,50.0,64.28571428571429,1.149274070056317
1504,96.97802559073482,96.7032967032967,97.25274725274726,0.4203795525202317,57.142857142857146,50.0,64.28571428571429,1.1531467526418369
1536,97.527476160654,97.25274725274726,97.8021978021978,0.4143302027935524,64.28571428571429,57.142857142857146,71.42857142857143,1.0965169041653244
1568,97.527476160654,97.25274725274724,97.80219780219782,0.4085315596017578,64.28571428571429,57.142857142857146,71.42857142857143,1.099552076753183
1600,97.527476160654,97.25274725274726,97.8021978021978,0.4027627966429136,64.28571428571429,57.142857142857146,71.42857142857143,1.1035399510554709
1632,97.527476160654,97.25274725274726,97.80219780219781,0.39715910964840717,64.28571428571429,57.142857142857146,71.42857142857143,1.1076057338793257
1664,97.527476160654,97.25274725274726,97.80219780219781,0.3916676718371987,60.714285714285715,57.142857142857146,64.28571428571429,1.1153264517957375
1696,97.80220144561359,97.25274725274724,98.35164835164836,0.3863043223430614,57.142857142857146,50.0,64.28571428571429,1.1683701116177723
1728,97.80220144561359,97.25274725274726,98.35164835164836,0.3807211139391626,60.714285714285715,50.0,71.42857142857143,1.1649994934059165
1760,97.80220144561359,97.25274725274726,98.35164835164836,0.3755378570378185,57.142857142857146,50.0,64.28571428571429,1.170103099601716
1792,97.80220144561359,97.25274725274724,98.35164835164836,0.3704457807837788,60.714285714285715,50.0,71.42857142857143,1.1749594710463769
1824,97.80220144561359,97.25274725274728,98.35164835164835,0.3654243267467638,60.714285714285715,50.0,71.42857142857143,1.182162186613202
1856,97.80220144561359,97.25274725274726,98.35164835164836,0.36060164181660326,60.714285714285715,50.0,71.42857142857143,1.1861205191681812
1888,97.80220144561359,97.25274725274724,98.35164835164835,0.35578458048460293,57.142857142857146,50.0,64.28571428571429,1.1918098529497847
1920,98.07692673057318,97.25274725274724,98.9010989010989,0.3511148095241527,60.714285714285715,50.0,71.42857142857143,1.1982332768482074
1952,98.07692673057318,97.25274725274724,98.9010989010989,0.34656422278027804,57.142857142857146,50.0,64.28571428571429,1.2036779535085558
1984,98.07692673057318,97.25274725274726,98.9010989010989,0.3420026787128994,57.142857142857146,50.0,64.28571428571429,1.210345241952746
2016,98.07692673057318,97.25274725274726,98.9010989010989,0.3376371374489987,60.714285714285715,50.0,71.42857142857143,1.2159515102316953
================================================
FILE: colorectal-cancer/report.py
================================================
#!/usr/bin/env python3
##########################################################################################
# Author: Jared L. Ostmeyer
# Date Started: 2018-02-05
# Purpose: Print results of the holdout cross-validation
##########################################################################################
##########################################################################################
# Libraries
##########################################################################################
import glob
import csv
from scipy.special import xlogy
import numpy as np
##########################################################################################
# Load data
##########################################################################################
costs_train = {}
accuracies_train = {}
tprs_train = {}
fprs_train = {}
for path in glob.glob('bin/*_ps_train.csv'):
with open(path, 'r') as stream:
reader = csv.DictReader(stream)
costs = []
accuracies = []
tprs = []
fprs = []
for row in reader:
label = float(row['Label'])
weight = float(row['Weight'])
prediction = float(row['Prediction'])
costs.append(
weight*(-xlogy(label, prediction)-xlogy(1.0-label, 1.0-prediction))/np.log(2.0)
)
accuracies.append(
100.0*weight*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
if label == 1.0:
tprs.append(
100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
elif label == 0.0:
fprs.append(
100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
else:
print('ERROR: Unrecognized value in the label.')
exit()
filename = path.split('/')[-1].split('.')[0]
_, step, _, _ = filename.split('_')
i = int(step)
if i not in costs_train:
costs_train[i] = []
costs_train[i].append(
np.sum(costs)
)
if i not in accuracies_train:
accuracies_train[i] = []
accuracies_train[i].append(
np.sum(accuracies)
)
if len(tprs) > 0:
if i not in tprs_train:
tprs_train[i] = []
tprs_train[i].append(
np.mean(tprs)
)
if len(fprs) > 0:
if i not in fprs_train:
fprs_train[i] = []
fprs_train[i].append(
np.mean(fprs)
)
costs_val = {}
accuracies_val = {}
tprs_val = {}
fprs_val = {}
for path in glob.glob('bin/*_ps_val.csv'):
with open(path, 'r') as stream:
reader = csv.DictReader(stream)
costs = []
accuracies = []
tprs = []
fprs = []
for row in reader:
label = float(row['Label'])
weight = float(row['Weight'])
prediction = float(row['Prediction'])
costs.append(
weight*(-xlogy(label, prediction)-xlogy(1.0-label, 1.0-prediction))/np.log(2.0)
)
accuracies.append(
100.0*weight*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
if label == 1.0:
tprs.append(
100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
elif label == 0.0:
fprs.append(
100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
else:
print('ERROR: Unrecognized value in the label.')
exit()
filename = path.split('/')[-1].split('.')[0]
_, step, _, _ = filename.split('_')
i = int(step)
if i not in costs_val:
costs_val[i] = []
costs_val[i].append(
np.sum(costs)
)
if i not in accuracies_val:
accuracies_val[i] = []
accuracies_val[i].append(
np.sum(accuracies)
)
if len(tprs) > 0:
if i not in tprs_val:
tprs_val[i] = []
tprs_val[i].append(
np.mean(tprs)
)
if len(fprs) > 0:
if i not in fprs_val:
fprs_val[i] = []
fprs_val[i].append(
np.mean(fprs)
)
##########################################################################################
# Results
##########################################################################################
print(
'Step',
'Accuracy_Train', 'TRP_Train', 'FPR_Train', 'Cost_train',
'Accuracy_Val', 'TRP_Val', 'FPR_Val', 'Cost_Val',
sep=','
)
for i in sorted(accuracies_train.keys()):
print(
i,
np.mean(accuracies_train[i]), np.mean(tprs_train[i]), np.mean(fprs_train[i]), np.mean(costs_train[i]),
np.mean(accuracies_val[i]), np.mean(tprs_val[i]), np.mean(fprs_val[i]), np.mean(costs_val[i]),
sep=','
)
================================================
FILE: colorectal-cancer/train_val.py
================================================
#!/usr/bin/env python3
##########################################################################################
# Author: Jared L. Ostmeyer
# Date Started: 2021-11-16
# Purpose: Train and validate a classifier for immune repertoires
##########################################################################################
##########################################################################################
# Libraries
##########################################################################################
import argparse
import csv
import glob
import dataplumbing as dp
import dataset as ds
import numpy as np
import torch
##########################################################################################
# Arguments
##########################################################################################
parser = argparse.ArgumentParser()
parser.add_argument('--holdouts', help='Holdout samples', type=str, nargs='+', required=True)
parser.add_argument('--restart', help='Basename for restart files', type=str, default=None)
parser.add_argument('--output', help='Basename for output files', type=str, required=True)
parser.add_argument('--seed', help='Seed value for randomly initializing fits', type=int, default=1)
parser.add_argument('--device', help='Examples are cuda:0 or cpu', type=str, default='cuda:0')
parser.add_argument('--num_fits', help='Number of fits to the training data', type=int, default=2**17)
args = parser.parse_args()
##########################################################################################
# Assemble sequences
##########################################################################################
# Settings
#
trim_front = 3
trim_rear = 3
kmer_size = 4
# To hold sequences from each subject
#
cases = {}
controls = {}
# Load immune repertoires
#
for path in glob.glob('dataset/*.tsv'):
sample = path.split('/')[-1].split('.')[0]
subject, label = sample.split('_')
cdr3s = dp.load_cdr3s(path, min_length=kmer_size+trim_front+trim_rear, max_length=32)
cdr3s = dp.trim_cdr3s(cdr3s, trim_front=trim_front, trim_rear=trim_rear)
kmers = dp.cdr3s_to_kmers(cdr3s, kmer_size)
kmers = dp.normalize_sample(kmers)
if 'Tumor' in label:
cases[subject] = kmers
elif 'Mucosa' in label:
controls[subject] = kmers
##########################################################################################
# Assemble datasets
##########################################################################################
# Load embeddings
#
aminoacids_dict = ds.load_aminoacid_embedding_dict('../aminoacid-representation/atchley_factors_normalized.csv')
# Convert to numeric representations
#
samples = ds.assemble_samples(cases, controls, aminoacids_dict)
# Split into a training and validation cohort
#
samples_train, samples_val = ds.split_samples(samples, args.holdouts)
# Weight samples
#
samples_train = ds.weight_samples(samples_train)
samples_val = ds.weight_samples(samples_val)
# Normalize features
#
samples_train, samples_val = ds.normalize_samples(samples_train, samples_val)
##########################################################################################
# Assemble tensors
##########################################################################################
# Settings
#
device = torch.device(args.device)
# Convert numpy arrays to pytorch tensors
#
for sample in samples_train:
sample['features'] = torch.from_numpy(sample['features']).to(device)
sample['label'] = torch.tensor(sample['label']).to(device)
sample['weight'] = torch.tensor(sample['weight']).to(device)
# Convert numpy arrays to pytorch tensors
#
for sample in samples_val:
sample['features'] = torch.from_numpy(sample['features']).to(device)
sample['label'] = torch.tensor(sample['label']).to(device)
sample['weight'] = torch.tensor(sample['weight']).to(device)
##########################################################################################
# Model
##########################################################################################
# Settings
#
num_features = samples_train[0]['features'].shape[1]
num_fits = args.num_fits
torch.manual_seed(args.seed)
# Function for initializing the weights of the model
#
def init_weights():
return torch.cat(
[
0.5**0.5*torch.rand([ num_features-1, num_fits ])/(num_features-1.0)**0.5, # Weights for the Atchley factors
0.5**0.5*torch.rand([ 1, num_fits ])/(1.0)**0.5, # Weight for the abundance term
],
0
)
# Class defining the model
#
class MaxSnippetModel(torch.nn.Module):
def __init__(self):
super(MaxSnippetModel, self).__init__()
self.linear = torch.nn.Linear(num_features, num_fits)
with torch.no_grad():
self.linear.weights = init_weights() # Initialize the weights
def forward(self, x):
ls = self.linear(x)
ms, _ = torch.max(ls, axis=0)
return ms
# Instantiation of the model
#
msm = MaxSnippetModel()
# Turn on GPU acceleration
#
msm.to(device)
##########################################################################################
# Metrics and optimization
##########################################################################################
# Settings
#
learning_rate = 0.01
# Optimizer
#
optimizer = torch.optim.Adam(msm.parameters(), lr=learning_rate) # Adam is based on gradient descent but better
# Metrics
#
loss = torch.nn.BCEWithLogitsLoss(reduction='none') # The loss function is calculated seperately for each fit by setting reduction to none
def accuracy(ls_block, ys_block): # The binary accuracy is calculated seperate for each fit
a = torch.nn.Sigmoid()
ps_block = a(ls_block)
cs_block = (torch.round(ps_block) == torch.round(ys_block)).to(ys_block.dtype)
return cs_block
##########################################################################################
# Fit and evaluate model
##########################################################################################
# Settings
#
num_epochs = 2048
# Restore saved models
#
if args.restart is not None:
msm = torch.load(args.output+'_model.p')
# Each iteration represents one batch
#
for epoch in range(0, num_epochs):
# Reset the gradients
#
optimizer.zero_grad()
es_train = 0.0 # Cross-entropy error
as_train = 0.0 # Accuracy
for sample in samples_train:
xs_block = sample['features']
ys_block = torch.tile(sample['label'], [ num_fits ])
w_block = sample['weight']
ls_block = msm(xs_block)
sample['predictions'] = torch.sigmoid(ls_block)
es_block = w_block*loss(ls_block, ys_block) # The loss function is calculated seperately for each fit
as_block = w_block*accuracy(ls_block, ys_block) # The binary accuracy is calculated seperate for each fit
es_train += es_block.detach()
as_train += as_block.detach()
e_block = torch.sum(es_block)
e_block.backward()
i_bestfit = torch.argmin(es_train) # Very important index selects the best fit to the training data
es_val = 0.0
as_val = 0.0
with torch.no_grad():
for sample in samples_val:
xs_block = sample['features']
ys_block = torch.tile(sample['label'], [ num_fits ])
w_block = sample['weight']
ls_block = msm(xs_block)
sample['predictions'] = torch.sigmoid(ls_block)
es_block = w_block*loss(ls_block, ys_block) # The loss function is calculated seperately for each fit
as_block = w_block*accuracy(ls_block, ys_block) # The binary accuracy is calculated seperate for each fit
es_val += es_block.detach()
as_val += as_block.detach()
# Print report
#
print(
'Epoch:', epoch,
'Accuracy (train):', round(100.0*float(as_train[i_bestfit]), 2), '%',
'Accuracy (val):', round(100.0*float(as_val[i_bestfit]), 2), '%',
flush=True
)
# Save parameters and results from the best fit to the training data
#
if epoch%32 == 0:
ws = msm.linear.weights.detach().numpy()
bs = msm.linear.bias.cpu().detach().numpy()
np.savetxt(args.output+'_'+str(epoch)+'_ws.csv', ws[:,i_bestfit])
np.savetxt(args.output+'_'+str(epoch)+'_b.csv', bs[[i_bestfit.cpu()]])
with open(args.output+'_'+str(epoch)+'_ms_train.csv', 'w') as stream:
print('Cross Entropy (bits)', 'Accuracy (%)', sep=',', file=stream)
print(float(es_train[i_bestfit])/np.log(2.0), 100.0*float(as_train[i_bestfit]), sep=',', file=stream)
with open(args.output+'_'+str(epoch)+'_ms_val.csv', 'w') as stream:
print('Cross Entropy (bits)', 'Accuracy (%)', sep=',', file=stream)
print(float(es_val[i_bestfit])/np.log(2.0), 100.0*float(as_val[i_bestfit]), sep=',', file=stream)
with open(args.output+'_'+str(epoch)+'_ps_train.csv', 'w') as stream:
print('Subject', 'Label', 'Weight', 'Prediction', sep=',', file=stream)
for sample in samples_train:
print(sample['subject'], float(sample['label']), float(sample['weight']), float(sample['predictions'][i_bestfit]), sep=',', file=stream)
with open(args.output+'_'+str(epoch)+'_ps_val.csv', 'w') as stream:
print('Subject', 'Label', 'Weight', 'Prediction', sep=',', file=stream)
for sample in samples_val:
print(sample['subject'], float(sample['label']), float(sample['weight']), float(sample['predictions'][i_bestfit]), sep=',', file=stream)
optimizer.step()
torch.save(msm, args.output+'_model.p')
================================================
FILE: ovarian-cancer/README.md
================================================
# Instructions
This 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.
## Dataset
T 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.
```
cd dataset
unzip '*.zip'
cd ../
```
## Modeling
This 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.
```
mkdir -p bin
python3 train_val.py --seed 1 --holdouts O-10M --output bin/1
python3 train_val.py --seed 1 --holdouts O-10N --output bin/2
python3 train_val.py --seed 1 --holdouts O-1M --output bin/3
python3 train_val.py --seed 1 --holdouts O-1N --output bin/4
python3 train_val.py --seed 1 --holdouts O-2M --output bin/5
python3 train_val.py --seed 1 --holdouts O-2N --output bin/6
python3 train_val.py --seed 1 --holdouts O-3M --output bin/7
python3 train_val.py --seed 1 --holdouts O-3N --output bin/8
python3 train_val.py --seed 1 --holdouts O-4M --output bin/9
python3 train_val.py --seed 1 --holdouts O-4N --output bin/10
python3 train_val.py --seed 1 --holdouts O-5M --output bin/11
python3 train_val.py --seed 1 --holdouts O-5N --output bin/12
python3 train_val.py --seed 1 --holdouts O-6M --output bin/13
python3 train_val.py --seed 1 --holdouts O-6N --output bin/14
python3 train_val.py --seed 1 --holdouts O-7M --output bin/15
python3 train_val.py --seed 1 --holdouts O-7N --output bin/16
python3 train_val.py --seed 1 --holdouts O-8M --output bin/17
python3 train_val.py --seed 1 --holdouts O-8N --output bin/18
python3 train_val.py --seed 1 --holdouts O-9M --output bin/19
python3 train_val.py --seed 1 --holdouts O-9N --output bin/20
```
The 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.
## How does this differ from the other examples in this repository?
This 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.
## Evaluation
The results are stored in a CSV file that can be opened by your favorite spreadsheet viewer. There are nine columns that represent:
```
python3 report.py > report.csv
```
The results are stored in a CSV file that can be opened by your favorite spreadsheet viewer. There are nine columns that represent:
1. The training step.
2. The accuracy on the training data averaged over the cross-validation.
3. The true negative rate (specificity) on the training data averaged over the cross-validation.
4. The true positive rate (sensitivity) on the training data averaged over the cross-validation.
5. The cross-entropy on the training data averaged over the cross-validation.
6. The accuracy on the holdout data averaged over the cross-validation.
7. The true negative rate (specificity) on the holdout data averaged over the cross-validation.
8. The true positive rate (sensitivity) on the holdout data averaged over the cross-validation.
9. The cross-entropy on the holdout data averaged over the cross-validation.
## Publication
* [Ovarian Cancer](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7058380/)
================================================
FILE: ovarian-cancer/dataplumbing.py
================================================
#########################################################################################
# Author: Jared L. Ostmeyer
# Date Started: 2021-11-16
# Environment: Python3
# Purpose: Utilities for loading immune receptor sequences
##########################################################################################
##########################################################################################
# Libraries
##########################################################################################
import csv
from itertools import combinations
##########################################################################################
# Utilities
##########################################################################################
def load_cdr3s(path_tsv, min_length=4, max_length=32, version='v2'):
receptors = {}
with open(path_tsv, 'r') as stream:
reader = csv.DictReader(stream, delimiter='\t')
for row in reader:
if version == 'v2':
cdr3 = row['aminoAcid']
# quantity = float(row['frequencyCount (%)'])
quantity = float(row['count (templates/reads)'])
status = row['sequenceStatus']
elif version == 'v3':
cdr3 = row['amino_acid']
# quantity = float(row['frequency'])
quantity = float(row['templates'])
status = row['frame_type']
else:
print('ERROR: Unsupported version')
exit()
if 'In' in status and min_length <= len(cdr3) and len(cdr3) <= max_length and quantity > 0.0 and 'X' not in cdr3:
if cdr3 not in receptors:
receptors[cdr3] = quantity
else:
receptors[cdr3] += quantity
return receptors
def trim_cdr3s(receptors, trim_front=0, trim_rear=0):
cdr3s = {}
for cdr3, quantity in receptors.items():
cdr3_trim = cdr3[trim_front:]
if trim_rear > 0:
cdr3_trim = cdr3_trim[:-trim_rear]
if len(cdr3_trim) > 0:
if cdr3_trim not in cdr3s:
cdr3s[cdr3_trim] = quantity
else:
cdr3s[cdr3_trim] += quantity
return cdr3s
def cdr3s_to_kmers(cdr3s, kmer_size):
kmers = {}
for cdr3, quantity in cdr3s.items():
if len(cdr3) >= kmer_size:
for i in range(len(cdr3)-kmer_size+1):
kmer = cdr3[i:i+kmer_size]
if kmer not in kmers:
kmers[kmer] = quantity
else:
kmers[kmer] += quantity
return kmers
def cdr3s_to_motifs(cdr3s, window_size, motif_size):
templates = []
for template in list(combinations(range(window_size), motif_size)):
if template[0] == 0:
templates.append(template)
motifs = {}
for cdr3, quantity in cdr3s.items():
if len(cdr3) >= motif_size:
for i in range(len(cdr3)-motif_size+1):
window = cdr3[i:i+window_size]
for template in templates:
if template[-1] < len(window):
motif = ''
for i in template:
motif += window[i]
if motif not in motifs:
motifs[motif] = quantity
else:
motifs[motif] += quantity
return motifs
def flatten_sample(sequences):
return { sequence: 1.0 for sequence in sequences.keys() }
def normalize_sample(sequences):
total = 0.0
for quantity in sorted(sequences.values()):
total += quantity
sequences_ = {}
for sequence, quantity in sequences.items():
sequences_[sequence] = quantity/total
return sequences_
def merge_samples(samples):
sequences = {}
for sample in samples:
for sequence, quantity in sample.items():
if sequence not in sequences:
sequences[sequence] = quantity/float(len(samples))
else:
sequences[sequence] += quantity/float(len(samples))
return sequences
def debug_insert_sequence(receptors, sequence, count):
if sequence not in receptors:
receptors[sequence] = count
else:
receptors[sequence] += count
return receptors
================================================
FILE: ovarian-cancer/dataset.py
================================================
#########################################################################################
# Author: Jared L. Ostmeyer
# Date Started: 2021-11-16
# Environment: Python3
# Purpose: Utilities for converting immune receptor sequences into numeric features
##########################################################################################
##########################################################################################
# Libraries
##########################################################################################
import csv
import numpy as np
##########################################################################################
# Utilities
##########################################################################################
def load_aminoacid_embedding_dict(path_embedding):
# Amino acid factors
#
names = []
factors = []
with open(path_embedding, 'r') as stream:
for line in stream:
rows = line.split(',')
names.append(rows[0])
factors.append(np.array(rows[1:], dtype=np.float32))
names = np.array(names)
factors = np.array(factors)
# Convert into a dictionary
#
aminoacids_dict = { name: factors[i,:] for i, name in enumerate(names) }
return aminoacids_dict
def assemble_samples(cases, controls, aminoacids_dict):
# Determine tensor dimensions
#
max_steps = -1
for sequences in cases.values():
for sequence in sequences.keys():
if len(sequence) > max_steps:
max_steps = len(sequence)
for sequences in controls.values():
for sequence in sequences.keys():
if len(sequence) > max_steps:
max_steps = len(sequence)
num_factors = len(list(aminoacids_dict.values())[0])
# Assemble dataset
#
samples = []
for subject in sorted(cases.keys()):
sequences = cases[subject]
# Initialize tensors
#
xs = np.zeros([ len(sequences), max_steps*num_factors+1 ], dtype=np.float32)
# Fill tensors
#
for i, ( sequence, quantity ) in enumerate(sorted(sequences.items())):
for j, aa in enumerate(sequence):
xs[i,num_factors*j:num_factors*(j+1)] = aminoacids_dict[aa]
xs[i,-1] = np.log(quantity)
u = np.mean(xs[:,-1])
v = np.var(xs[:,-1])
xs[:,-1] = (xs[:,-1]-u)/np.sqrt(v)
samples.append(
{
'subject': subject,
'features': xs,
'label': 1.0
}
)
for subject in sorted(controls.keys()):
sequences = controls[subject]
# Initialize tensors
#
xs = np.zeros([ len(sequences), max_steps*num_factors+1 ], dtype=np.float32)
# Fill tensors
#
for i, ( sequence, quantity ) in enumerate(sorted(sequences.items())):
for j, aa in enumerate(sequence):
xs[i,num_factors*j:num_factors*(j+1)] = aminoacids_dict[aa]
xs[i,-1] = np.log(quantity)
u = np.mean(xs[:,-1])
v = np.var(xs[:,-1])
xs[:,-1] = (xs[:,-1]-u)/np.sqrt(v)
samples.append(
{
'subject': subject,
'features': xs,
'label': 0.0
}
)
return samples
def split_samples(samples, holdouts):
samples_train = []
samples_val = []
for sample in samples:
if sample['subject'] not in holdouts:
samples_train.append(sample)
else:
samples_val.append(sample)
return samples_train, samples_val
def weight_samples(samples):
num_case = 0
num_control = 0
for sample in samples:
if sample['label'] > 0.5:
num_case += 1
else:
num_control += 1
for sample in samples:
if sample['label'] > 0.5:
sample['weight'] = 0.5/num_case if num_control > 0 else 1.0/num_case
else:
sample['weight'] = 0.5/num_control if num_case > 0 else 1.0/num_control
return samples
def normalize_samples(samples_train, samples_holdout):
# Calculate normalization statistics from the training samples
#
us = 0.0
us2 = 0.0
for sample in samples_train:
xs_sample = sample['features']
us_sample = np.mean(xs_sample, axis=0)
us2_sample = np.mean(xs_sample**2, axis=0)
us += sample['weight']*us_sample
us2 += sample['weight']*us2_sample
vs = us2-us**2
# Normalize the training samples
#
for sample in samples_train:
xs_sample = sample['features']
xs_sample = (xs_sample-us)/np.sqrt(vs)
sample['features'] = xs_sample
# Normalize the holdout samples
#
for sample in samples_holdout:
xs_sample = sample['features']
xs_sample = (xs_sample-us)/np.sqrt(vs)
sample['features'] = xs_sample
return samples_train, samples_holdout
def debug_permute_labels(samples):
labels = []
for sample in samples:
labels.append(sample['label'])
np.random.shuffle(labels)
for sample, label in zip(samples, labels):
sample['label'] = label
return samples
================================================
FILE: ovarian-cancer/gold.report.csv
================================================
Step,Accuracy_Train,TRP_Train,FPR_Train,Cost_train,Accuracy_Val,TRP_Val,FPR_Val,Cost_Val
0,50.000000558793545,100.0,0.0,1.0365936592801854,50.0,100.0,0.0,1.053734415443118
32,50.000000558793545,100.0,0.0,0.9457275844220987,50.0,100.0,0.0,0.9521947011631451
64,51.86111168935895,100.0,3.7222222222222223,0.9173581467213623,50.0,100.0,0.0,0.9362032431566807
96,61.333334017544985,100.0,22.666666666666668,0.8897864747897849,55.0,100.0,10.0,0.9138892262835843
128,73.25000081211329,100.0,46.5,0.8622117969742218,60.0,100.0,20.0,0.8933784246978418
160,86.38888984918594,100.0,72.77777777777779,0.8349512024155757,80.0,100.0,60.0,0.869854996615784
192,93.9166677184403,100.0,87.83333333333333,0.8079039280915398,80.0,100.0,60.0,0.8469194746369686
224,95.25000106543303,100.0,90.5,0.7816135581196335,80.0,90.0,70.0,0.8275820896617134
256,95.25000106543303,100.0,90.49999999999999,0.7567312342808346,80.0,90.0,70.0,0.8071864255777736
288,95.52777884528041,100.0,91.05555555555556,0.7328786795241862,85.0,90.0,80.0,0.7887767919786073
320,95.52777884528041,100.0,91.05555555555557,0.7098933654731956,85.0,90.0,80.0,0.7689075815972282
352,96.63888996466994,100.0,93.27777777777779,0.6879672937503374,85.0,90.0,80.0,0.7519116439578173
384,97.38888997584581,100.0,94.77777777777779,0.6670572165352502,90.0,100.0,80.0,0.7267877282394819
416,98.94444555044174,100.0,97.88888888888889,0.6470529204055335,90.0,100.0,80.0,0.707885453170132
448,99.7222233377397,100.0,99.44444444444444,0.6278908228197596,95.0,100.0,90.0,0.6905346270594236
480,100.00000111758709,100.0,100.0,0.6096233055829081,95.0,100.0,90.0,0.6781916343268548
512,100.00000111758709,100.0,100.0,0.5920660224461953,95.0,100.0,90.0,0.6640477000409764
544,100.00000111758709,100.0,100.0,0.5753083104294501,95.0,100.0,90.0,0.6503199255223708
576,100.00000111758709,100.0,100.0,0.5589253495562464,95.0,100.0,90.0,0.6366496359304342
608,100.00000111758709,100.0,100.0,0.5432534700153104,95.0,100.0,90.0,0.6244075318577076
640,100.00000111758709,100.0,100.0,0.5282158401170938,95.0,100.0,90.0,0.6128997276029248
672,100.00000111758709,100.0,100.0,0.5138654622392067,90.0,90.0,90.0,0.6017583106087383
704,100.00000111758709,100.0,100.0,0.5000623705611038,90.0,90.0,90.0,0.590825447223445
736,100.00000111758709,100.0,100.0,0.48684374270568787,95.0,90.0,100.0,0.5782254056093944
768,100.00000111758709,100.0,100.0,0.4741169244519874,95.0,90.0,100.0,0.5684024076401123
800,100.00000111758709,100.0,100.0,0.46195317693568294,95.0,90.0,100.0,0.5581231700201241
832,100.00000111758709,100.0,100.0,0.45028973981363174,95.0,90.0,100.0,0.5484136721696521
864,100.00000111758709,100.0,100.0,0.4389629335160132,95.0,90.0,100.0,0.5375965943507595
896,100.00000111758709,100.0,100.0,0.4280574290433732,95.0,90.0,100.0,0.5297755064326588
928,100.00000111758709,100.0,100.0,0.4176026136917771,95.0,90.0,100.0,0.5216564912294647
960,100.00000111758709,100.0,100.0,0.4074523138478397,95.0,90.0,100.0,0.5134361414385197
992,100.00000111758709,100.0,100.0,0.39777359406335816,95.0,90.0,100.0,0.5049372061110985
1024,100.00000111758709,100.0,100.0,0.38836321196962514,95.0,90.0,100.0,0.4970579486596722
1056,100.00000111758709,100.0,100.0,0.3792962122463345,95.0,90.0,100.0,0.49127351752597176
1088,100.00000111758709,100.0,100.0,0.3705926858408387,95.0,90.0,100.0,0.48535818041470524
1120,100.00000111758709,100.0,100.0,0.36218755251354484,95.0,90.0,100.0,0.47837351165870634
1152,100.00000111758709,100.0,100.0,0.35407859271871234,95.0,90.0,100.0,0.4729071859863523
1184,100.00000111758709,100.0,100.0,0.3462821212907713,95.0,90.0,100.0,0.4665835793381013
1216,100.00000111758709,100.0,100.0,0.338692420943195,95.0,90.0,100.0,0.46210833328654816
1248,100.00000111758709,100.0,100.0,0.3313764813681741,95.0,90.0,100.0,0.45604253442672815
1280,100.00000111758709,100.0,100.0,0.3243162694793336,95.0,90.0,100.0,0.4515586959041891
1312,100.00000111758709,100.0,100.0,0.3175235311984152,95.0,90.0,100.0,0.4468846051338997
1344,100.00000111758709,100.0,100.0,0.3109138439736886,95.0,90.0,100.0,0.44157299072729145
1376,100.00000111758709,100.0,100.0,0.30448979218288896,95.0,90.0,100.0,0.4365165014256018
1408,100.00000111758709,100.0,100.0,0.2983435353743342,95.0,90.0,100.0,0.4308327025918729
1440,100.00000111758709,100.0,100.0,0.29240556195744166,95.0,90.0,100.0,0.42403151793405386
1472,100.00000111758709,100.0,100.0,0.2865611275197513,95.0,90.0,100.0,0.4205571672247593
1504,100.00000111758709,100.0,100.0,0.28095418242576214,95.0,90.0,100.0,0.4161738706359409
1536,100.00000111758709,100.0,100.0,0.2755610349446828,95.0,90.0,100.0,0.4120982358530646
1568,100.00000111758709,100.0,100.0,0.270299678602454,95.0,90.0,100.0,0.4062375990454443
1600,100.00000111758709,100.0,100.0,0.26517320919942977,95.0,90.0,100.0,0.4039691460886542
1632,100.00000111758709,100.0,100.0,0.26018200741182473,95.0,90.0,100.0,0.39965023115332954
1664,100.00000111758709,100.0,100.0,0.2553767035143239,95.0,90.0,100.0,0.39618380143984677
1696,100.00000111758709,100.0,100.0,0.2506901729754958,95.0,90.0,100.0,0.39397577668149797
1728,100.00000111758709,100.0,100.0,0.24612113579653422,95.0,90.0,100.0,0.3916619430153634
1760,100.00000111758709,100.0,100.0,0.2416658876462623,95.0,90.0,100.0,0.3906025837666053
1792,100.00000111758709,100.0,100.0,0.23734113966146766,95.0,90.0,100.0,0.3896043942462871
1824,100.00000111758709,100.0,100.0,0.23310908908556463,95.0,90.0,100.0,0.38870543940374896
1856,100.00000111758709,100.0,100.0,0.22903719926413862,95.0,90.0,100.0,0.38585061401509607
1888,100.00000111758709,100.0,100.0,0.225015971355118,95.0,90.0,100.0,0.3828368833285537
1920,100.00000111758709,100.0,100.0,0.22109123290831584,95.0,90.0,100.0,0.3816345447835901
1952,100.00000111758709,100.0,100.0,0.21729761440695397,95.0,90.0,100.0,0.3789834054120344
1984,100.00000111758709,100.0,100.0,0.21360048249148603,95.0,90.0,100.0,0.37814051140292076
2016,100.00000111758709,100.0,100.0,0.20999734441149975,95.0,90.0,100.0,0.37531046687184993
================================================
FILE: ovarian-cancer/report.py
================================================
#!/usr/bin/env python3
##########################################################################################
# Author: Jared L. Ostmeyer
# Date Started: 2018-02-05
# Purpose: Print results of the holdout cross-validation
##########################################################################################
##########################################################################################
# Libraries
##########################################################################################
import glob
import csv
from scipy.special import xlogy
import numpy as np
##########################################################################################
# Load data
##########################################################################################
costs_train = {}
accuracies_train = {}
tprs_train = {}
fprs_train = {}
for path in glob.glob('bin/*_ps_train.csv'):
with open(path, 'r') as stream:
reader = csv.DictReader(stream)
costs = []
accuracies = []
tprs = []
fprs = []
for row in reader:
label = float(row['Label'])
weight = float(row['Weight'])
prediction = float(row['Prediction'])
costs.append(
weight*(-xlogy(label, prediction)-xlogy(1.0-label, 1.0-prediction))/np.log(2.0)
)
accuracies.append(
100.0*weight*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
if label == 1.0:
tprs.append(
100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
elif label == 0.0:
fprs.append(
100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
else:
print('ERROR: Unrecognized value in the label.')
exit()
filename = path.split('/')[-1].split('.')[0]
_, step, _, _ = filename.split('_')
i = int(step)
if i not in costs_train:
costs_train[i] = []
costs_train[i].append(
np.sum(costs)
)
if i not in accuracies_train:
accuracies_train[i] = []
accuracies_train[i].append(
np.sum(accuracies)
)
if len(tprs) > 0:
if i not in tprs_train:
tprs_train[i] = []
tprs_train[i].append(
np.mean(tprs)
)
if len(fprs) > 0:
if i not in fprs_train:
fprs_train[i] = []
fprs_train[i].append(
np.mean(fprs)
)
costs_val = {}
accuracies_val = {}
tprs_val = {}
fprs_val = {}
for path in glob.glob('bin/*_ps_val.csv'):
with open(path, 'r') as stream:
reader = csv.DictReader(stream)
costs = []
accuracies = []
tprs = []
fprs = []
for row in reader:
label = float(row['Label'])
weight = float(row['Weight'])
prediction = float(row['Prediction'])
costs.append(
weight*(-xlogy(label, prediction)-xlogy(1.0-label, 1.0-prediction))/np.log(2.0)
)
accuracies.append(
100.0*weight*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
if label == 1.0:
tprs.append(
100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
elif label == 0.0:
fprs.append(
100.0*np.equal(np.round(label), np.round(prediction)).astype(np.float64)
)
else:
print('ERROR: Unrecognized value in the label.')
exit()
filename = path.split('/')[-1].split('.')[0]
_, step, _, _ = filename.split('_')
i = int(step)
if i not in costs_val:
costs_val[i] = []
costs_val[i].append(
np.sum(costs)
)
if i not in accuracies_val:
accuracies_val[i] = []
accuracies_val[i].append(
np.sum(accuracies)
)
if len(tprs) > 0:
if i not in tprs_val:
tprs_val[i] = []
tprs_val[i].append(
np.mean(tprs)
)
if len(fprs) > 0:
if i not in fprs_val:
fprs_val[i] = []
fprs_val[i].append(
np.mean(fprs)
)
##########################################################################################
# Results
##########################################################################################
print(
'Step',
'Accuracy_Train', 'TRP_Train', 'FPR_Train', 'Cost_train',
'Accuracy_Val', 'TRP_Val', 'FPR_Val', 'Cost_Val',
sep=','
)
for i in sorted(accuracies_train.keys()):
print(
i,
np.mean(accuracies_train[i]), np.mean(tprs_train[i]), np.mean(fprs_train[i]), np.mean(costs_train[i]),
np.mean(accuracies_val[i]), np.mean(tprs_val[i]), np.mean(fprs_val[i]), np.mean(costs_val[i]),
sep=','
)
================================================
FILE: ovarian-cancer/train_val.py
================================================
#!/usr/bin/env python3
##########################################################################################
# Author: Jared L. Ostmeyer
# Date Started: 2021-11-16
# Purpose: Train and validate a classifier for immune repertoires
##########################################################################################
##########################################################################################
# Libraries
##########################################################################################
import argparse
import csv
import glob
import dataplumbing as dp
import dataset as ds
import numpy as np
import torch
##########################################################################################
# Arguments
##########################################################################################
parser = argparse.ArgumentParser()
parser.add_argument('--holdouts', help='Holdout samples', type=str, nargs='+', required=True)
parser.add_argument('--restart', help='Basename for restart files', type=str, default=None)
parser.add_argument('--output', help='Basename for output files', type=str, required=True)
parser.add_argument('--seed', help='Seed value for randomly initializing fits', type=int, default=1)
parser.add_argument('--device', help='Examples are cuda:0 or cpu', type=str, default='cuda:0')
parser.add_argument('--num_fits', help='Number of fits to the training data', type=int, default=2**17)
args = parser.parse_args()
##########################################################################################
# Assemble sequences
##########################################################################################
# Settings
#
trim_front = 3
trim_rear = 3
window_size = 4
motif_size = 3
# To hold sequences from each subject
#
cases = {}
controls = {}
# Load immune repertoires
#
for path in glob.glob('dataset/*.tsv'):
sample = path.split('/')[-1].split('.')[0]
label = sample[-1]
if label == 'M' or label == 'N':
cdr3s = dp.load_cdr3s(path, min_length=motif_size+trim_front+trim_rear, max_length=32)
cdr3s = dp.trim_cdr3s(cdr3s, trim_front=trim_front, trim_rear=trim_rear)
motifs = dp.cdr3s_to_motifs(cdr3s, window_size, motif_size)
motifs = dp.normalize_sample(motifs)
if label == 'M':
cases[sample] = motifs
else:
controls[sample] = motifs
##########################################################################################
# Assemble datasets
##########################################################################################
# Load embeddings
#
aminoacids_dict = ds.load_aminoacid_embedding_dict('../aminoacid-representation/atchley_factors_normalized.csv')
# Convert to numeric representations
#
samples = ds.assemble_samples(cases, controls, aminoacids_dict)
# Split into a training and validation cohort
#
samples_train, samples_val = ds.split_samples(samples, args.holdouts)
# Weight samples
#
samples_train = ds.weight_samples(samples_train)
samples_val = ds.weight_samples(samples_val)
# Normalize features
#
samples_train, samples_val = ds.normalize_samples(samples_train, samples_val)
##########################################################################################
# Assemble tensors
##########################################################################################
# Settings
#
device = torch.device(args.device)
# Convert numpy arrays to pytorch tensors
#
for sample in samples_train:
sample['features'] = torch.from_numpy(sample['features']).to(device)
sample['label'] = torch.tensor(sample['label']).to(device)
sample['weight'] = torch.tensor(sample['weight']).to(device)
# Convert numpy arrays to pytorch tensors
#
for sample in samples_val:
sample['features'] = torch.from_numpy(sample['features']).to(device)
sample['label'] = torch.tensor(sample['label']).to(device)
sample['weight'] = torch.tensor(sample['weight']).to(device)
##########################################################################################
# Model
##########################################################################################
# Settings
#
num_features = samples_train[0]['features'].shape[1]
num_fits = args.num_fits
torch.manual_seed(args.seed)
# Function for initializing the weights of the model
#
def init_weights():
return torch.cat(
[
0.5**0.5*torch.rand([ num_features-1, num_fits ])/(num_features-1.0)**0.5, # Weights for the Atchley factors
0.5**0.5*torch.rand([ 1, num_fits ])/(1.0)**0.5, # Weight for the abundance term
],
0
)
# Class defining the model
#
class MaxSnippetModel(torch.nn.Module):
def __init__(self):
super(MaxSnippetModel, self).__init__()
self.linear = torch.nn.Linear(num_features, num_fits)
with torch.no_grad():
self.linear.weights = init_weights() # Initialize the weights
def forward(self, x):
ls = self.linear(x)
ms, _ = torch.max(ls, axis=0)
return ms
# Instantiation of the model
#
msm = MaxSnippetModel()
# Turn on GPU acceleration
#
msm.to(device)
##########################################################################################
# Metrics and optimization
##########################################################################################
# Settings
#
learning_rate = 0.01
# Optimizer
#
optimizer = torch.optim.Adam(msm.parameters(), lr=learning_rate) # Adam is based on gradient descent but better
# Metrics
#
loss = torch.nn.BCEWithLogitsLoss(reduction='none') # The loss function is calculated seperately for each fit by setting reduction to none
def accuracy(ls_block, ys_block): # The binary accuracy is calculated seperate for each fit
a = torch.nn.Sigmoid()
ps_block = a(ls_block)
cs_block = (torch.round(ps_block) == torch.round(ys_block)).to(ys_block.dtype)
return cs_block
##########################################################################################
# Fit and evaluate model
##########################################################################################
# Settings
#
num_epochs = 2048
# Restore saved models
#
if args.restart is not None:
msm = torch.load(args.output+'_model.p')
# Each iteration represents one batch
#
for epoch in range(0, num_epochs):
# Reset the gradients
#
optimizer.zero_grad()
es_train = 0.0 # Cross-entropy error
as_train = 0.0 # Accuracy
for sample in samples_train:
xs_block = sample['features']
ys_block = torch.tile(sample['label'], [ num_fits ])
w_block = sample['weight']
ls_block = msm(xs_block)
sample['predictions'] = torch.sigmoid(ls_block)
es_block = w_block*loss(ls_block, ys_block) # The loss function is calculated seperately for each fit
as_block = w_block*accuracy(ls_block, ys_block) # The binary accuracy is calculated seperate for each fit
es_train += es_block.detach()
as_train += as_block.detach()
e_block = torch.sum(es_block)
e_block.backward()
i_bestfit = torch.argmin(es_train) # Very important index selects the best fit to the training data
es_val = 0.0
as_val = 0.0
with torch.no_grad():
for sample in samples_val:
xs_block = sample['features']
ys_block = torch.tile(sample['label'], [ num_fits ])
w_block = sample['weight']
ls_block = msm(xs_block)
sample['predictions'] = torch.sigmoid(ls_block)
es_block = w_block*loss(ls_block, ys_block) # The loss function is calculated seperately for each fit
as_block = w_block*accuracy(ls_block, ys_block) # The binary accuracy is calculated seperate for each fit
es_val += es_block.detach()
as_val += as_block.detach()
# Print report
#
print(
'Epoch:', epoch,
'Accuracy (train):', round(100.0*float(as_train[i_bestfit]), 2), '%',
'Accuracy (val):', round(100.0*float(as_val[i_bestfit]), 2), '%',
flush=True
)
# Save parameters and results from the best fit to the training data
#
if epoch%32 == 0:
ws = msm.linear.weights.detach().numpy()
bs = msm.linear.bias.cpu().detach().numpy()
np.savetxt(args.output+'_'+str(epoch)+'_ws.csv', ws[:,i_bestfit])
np.savetxt(args.output+'_'+str(epoch)+'_b.csv', bs[[i_bestfit.cpu()]])
with open(args.output+'_'+str(epoch)+'_ms_train.csv', 'w') as stream:
print('Cross Entropy (bits)', 'Accuracy (%)', sep=',', file=stream)
print(float(es_train[i_bestfit])/np.log(2.0), 100.0*float(as_train[i_bestfit]), sep=',', file=stream)
with open(args.output+'_'+str(epoch)+'_ms_val.csv', 'w') as stream:
print('Cross Entropy (bits)', 'Accuracy (%)', sep=',', file=stream)
print(float(es_val[i_bestfit])/np.log(2.0), 100.0*float(as_val[i_bestfit]), sep=',', file=stream)
with open(args.output+'_'+str(epoch)+'_ps_train.csv', 'w') as stream:
print('Subject', 'Label', 'Weight', 'Prediction', sep=',', file=stream)
for sample in samples_train:
print(sample['subject'], float(sample['label']), float(sample['weight']), float(sample['predictions'][i_bestfit]), sep=',', file=stream)
with open(args.output+'_'+str(epoch)+'_ps_val.csv', 'w') as stream:
print('Subject', 'Label', 'Weight', 'Prediction', sep=',', file=stream)
for sample in samples_val:
print(sample['subject'], float(sample['label']), float(sample['weight']), float(sample['predictions'][i_bestfit]), sep=',', file=stream)
optimizer.step()
torch.save(msm, args.output+'_model.p')