├── .Rhistory ├── .ipynb_checkpoints └── example-checkpoint.ipynb ├── .readthedocs.yaml ├── LICENSE.txt ├── README.md ├── cellchat_eg.ipynb ├── deconvolution_example.ipynb ├── docs ├── Makefile ├── make.bat ├── requirements.txt └── source │ ├── _templates │ ├── README.md │ ├── class.rst │ └── module.rst │ ├── api.rst │ ├── conf.py │ ├── contact.rst │ ├── covid_individual_deconv.jpg │ ├── covidreconsemi.jpg │ ├── credits.rst │ ├── environment.txt │ ├── example.ipynb │ ├── gallery.rst │ ├── index.rst │ ├── install.rst │ ├── references.rst │ ├── release.rst │ ├── requirements.txt │ └── tutorials.rst ├── environment.txt ├── example.ipynb ├── example_data ├── bulkdata.h5ad └── scdata.h5ad ├── genesets ├── Mouse_TF_targets.txt ├── c2.cp.v7.4.symbols.gmt ├── c2.cp.wikipathways.v7.4.symbols.gmt ├── c5.go.bp.v7.4.symbols.gmt └── c8.all.v7.4.symbols.gmt ├── inference_example.jpg ├── overview.jpg ├── pyproject.toml ├── recon_example.jpg ├── scSemiProfiler ├── .ipynb_checkpoints │ ├── __init__-checkpoint.py │ ├── activeselect-checkpoint.py │ ├── fast_functions-checkpoint.py │ ├── fast_generator-checkpoint.py │ ├── initsetup-checkpoint.py │ ├── scinfer-checkpoint.py │ └── scprocess-checkpoint.py ├── __init__.py ├── fast_generator.py ├── get_eg_representatives.py ├── hamster_to_human_gene.txt ├── inference.py ├── initial_setup.py ├── oldinference.py ├── representative_selection.py ├── singlecell_process.py ├── utils.py └── vaegan.py └── setup.py /.Rhistory: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcgilldinglab/scSemiProfiler/5a9c10e3ac06eeec73cb4ddcada495a216f3d849/.Rhistory -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | version: "2" 2 | 3 | build: 4 | os: "ubuntu-22.04" 5 | tools: 6 | python: "3.9" 7 | 8 | python: 9 | install: 10 | - method: pip 11 | path: . 12 | extra_requirements: 13 | - doc 14 | 15 | sphinx: 16 | configuration: docs/source/conf.py 17 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | scSemiProfiler - Dual Licensing 2 | 3 | 4 | 5 | PART 1: Open Source License for Academic Use 6 | ------------------------------------------------------ 7 | GNU GENERAL PUBLIC LICENSE 8 | Version 3, 29 June 2007 9 | 10 | Copyright © 2007 Free Software Foundation, Inc. 11 | 12 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 13 | 14 | Preamble 15 | The GNU General Public License is a free, copyleft license for software and other kinds of works. 16 | 17 | The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. 18 | 19 | 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. 20 | 21 | To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. 22 | 23 | For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. 24 | 25 | Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. 26 | 27 | For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. 28 | 29 | Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. 30 | 31 | Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. 32 | 33 | The precise terms and conditions for copying, distribution and modification follow. 34 | 35 | TERMS AND CONDITIONS 36 | 0. Definitions. 37 | “This License” refers to version 3 of the GNU General Public License. 38 | 39 | “Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. 40 | 41 | “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. 42 | 43 | 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. 44 | 45 | A “covered work” means either the unmodified Program or a work based on the Program. 46 | 47 | 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. 48 | 49 | 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. 50 | 51 | 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. 52 | 53 | 1. Source Code. 54 | 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. 55 | 56 | 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. 57 | 58 | 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. 59 | 60 | 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. 61 | 62 | The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. 63 | 64 | The Corresponding Source for a work in source code form is that same work. 65 | 66 | 2. Basic Permissions. 67 | 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. 68 | 69 | 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. 70 | 71 | Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 72 | 73 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 74 | 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. 75 | 76 | 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. 77 | 78 | 4. Conveying Verbatim Copies. 79 | 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. 80 | 81 | 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. 82 | 83 | 5. Conveying Modified Source Versions. 84 | 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: 85 | 86 | a) The work must carry prominent notices stating that you modified it, and giving a relevant date. 87 | 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”. 88 | 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. 89 | 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. 90 | 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. 91 | 92 | 6. Conveying Non-Source Forms. 93 | 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: 94 | 95 | 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. 96 | 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. 97 | 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. 98 | 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. 99 | 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. 100 | 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. 101 | 102 | 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. 103 | 104 | “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. 105 | 106 | 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). 107 | 108 | 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. 109 | 110 | 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. 111 | 112 | 7. Additional Terms. 113 | “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. 114 | 115 | 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. 116 | 117 | 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: 118 | 119 | a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or 120 | 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 121 | 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 122 | d) Limiting the use for publicity purposes of names of licensors or authors of the material; or 123 | e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or 124 | 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. 125 | 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. 126 | 127 | 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. 128 | 129 | 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. 130 | 131 | 8. Termination. 132 | 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). 133 | 134 | 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. 135 | 136 | 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. 137 | 138 | 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. 139 | 140 | 9. Acceptance Not Required for Having Copies. 141 | 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. 142 | 143 | 10. Automatic Licensing of Downstream Recipients. 144 | 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. 145 | 146 | 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. 147 | 148 | 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. 149 | 150 | 11. Patents. 151 | 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”. 152 | 153 | 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. 154 | 155 | 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. 156 | 157 | 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. 158 | 159 | 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. 160 | 161 | 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. 162 | 163 | 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. 164 | 165 | 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. 166 | 167 | 12. No Surrender of Others' Freedom. 168 | 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. 169 | 170 | 13. Use with the GNU Affero General Public License. 171 | Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 172 | 173 | 14. Revised Versions of this License. 174 | The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 175 | 176 | Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. 177 | 178 | If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. 179 | 180 | 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. 181 | 182 | 15. Disclaimer of Warranty. 183 | 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. 184 | 185 | 16. Limitation of Liability. 186 | 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. 187 | 188 | 17. Interpretation of Sections 15 and 16. 189 | 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. 190 | 191 | END OF TERMS AND CONDITIONS 192 | 193 | 194 | PART 2: Commercial License 195 | ------------------------------------------------------ 196 | For commercial use of scSemiProfiler, a commercial license is required. This 197 | includes any use of scSemiProfiler in a commercial entity or for commercial 198 | purposes, including but not limited to integration into commercial products, 199 | use in a commercial environment, or redistribution in a commercial context. 200 | If you are interested in using scSemiProfiler for commercial purposes, please 201 | contact us at jingtao.wang@mail.mcgill.ca for more information about obtaining 202 | a commercial license. 203 | 204 | 205 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # scSemiProfiler: Advancing Large-scale Single-cell Studies through Semi-profiling with Deep Generative Models and Active Learning 4 | 5 | 6 | **scSemiProfiler** is an innovative computational tool that combines deep generative models and active learning to economically generate single-cell data for biological studies. It supports two main application scenarios: **semi-profiling**, which uses deep generative learning and active learning to generate a single-cell cohort with 1/10 to 1/3 sequencing cost, and **single-cell level deconvolution**, which generates single-cell data from bulk data and single-cell references. For more insights, check out our [manuscript in _Nature Communications_](https://www.nature.com/articles/s41467-024-50150-1), and please consider citing it if you find our method beneficial. 7 | 8 | Explore comprehensive details, including API references, usage examples, and tutorials (in [Jupyter notebook](https://jupyter.org/) format), in our [full documentation](https://scsemiprofiler.readthedocs.io/en/latest/) and the README below. 9 | 10 | 11 | *Updates:* 12 | - **Bulk Deconvolution (Single-cell level) Pipeline:** A simplified pipeline has been added to scSemiProfiler for generating single-cell data from bulk RNA-seq profiles using a single-cell reference sample. See the [Application Scenarios](#application-scenarios) section for details. 13 | 14 | - **Global Mode Functions:** New global mode functions `"inspect_data"` and `"global_stop_checking"` have been introduced. For details, use `print(scSemiProfiler.utils.inspect_data.__doc__)` and `print(scSemiProfiler.utils.global_stop_checking.__doc__)`. 15 | 16 | ## Table of Contents 17 | - [Application Scenarios](#application-scenarios) 18 | - [Methods Overview](#methods-overview) 19 | - [Prerequisites](#prerequisites) 20 | - [Installation](#installation) 21 | - [Credits and Acknowledgements](#credits-and-acknowledgements) 22 | - [Contacts](#contacts) 23 | 24 | ## Application Scenarios 25 | 26 | ### 1. Bulk Deconvolution (Single-Cell Level) 27 | This process allows users to deconvolute bulk RNA-seq data from a target sample into single-cell data, using a single-cell reference sample as a guide. Users need to provide bulk data for both the target and reference samples. The single-cell reference can be derived from real sequencing data or any similar online dataset. Once the pipeline is completed, single-cell data for the target sample is generated and can be used for cell type annotation. This includes de novo annotation or utilizing a classifier trained on the reference data. For further guidance, please refer to the [deconvolution_example.ipynb](deconvolution_example.ipynb). 28 | 29 | ### 2. Semi-Profile a Cohort 30 | With bulk data for a cohort, select a few representative samples using active learning for real single-cell sequencing and computationally generate single-cell data for the rest target samples. Getting single-cell data using less than 1/3 cost. Example in [example.ipynb](example.ipynb). 31 | 32 | --- 33 | 34 | 35 | ## Methods Overview 36 | ![flowchart](./overview.jpg) 37 | 38 | **scSemiProfiler Overview:** scSemiProfiler offers a cost-effective AI-generated alternative to real-profiled single-cell data with high fidelity. 39 | 40 | **a, Curating bulk and reference single-cell data:** Bulk sequencing is performed across the entire cohort. The single-cell reference data can either be provided by the user (e.g., a public reference dataset) or obtained from selected representative samples within the cohort under study. Representative samples can be chosen based on clustering analysis of the bulk data (the global mode of scSemiProfiler) or by using the active learning module. 41 | 42 | **b, In silico inference of target single-cell data from bulk profiles:** For each target sample, a deep generative model first learns the distribution of the reference single-cell data, generating reconstructions of the reference cells. Subsequently, the bulk information of the target sample is incorporated into the cell generation process via fine-tuning, producing single-cell data that matches the target bulk. This AI-powered semi-profiling framework significantly reduces single-cell profiling costs for large cohorts (e.g., a 66.3% savings in the example COVID-19 study). Cost estimates are based on rates from the McGill Genome Centre and costpercell as of 2023. 43 | 44 | **c, High fidelity between cost-effective AI-generated semi-profiled and ground-truth single-cell data:** Left: UMAP visualization shows that the inferred target sample’s single cells (red), generated based on reference cells (blue), closely resemble the real-profiled ground truth of the target sample (red; unknown to the model). Middle: UMAP visualizations compare the real-profiled and semi-profiled COVID-19 cohort with 124 samples, which are similar in terms of cell distribution and cell types (indicated by colors, which are consistent with the legends on the right). Right: Stacked bar plots indicate that the semi-profiled cohort has nearly identical cell type proportions across disease conditions compared to the real-profiled ground truth. 45 | 46 | ## Prerequisites 47 | First, install [Anaconda](https://www.anaconda.com/). You can find specific instructions for different operating systems [here](https://conda.io/projects/conda/en/latest/user-guide/getting-started.html). 48 | 49 | Second, create a new conda environment and activate it: 50 | ``` 51 | conda create -n semiprofiler python=3.9 52 | ``` 53 | ``` 54 | conda activate semiprofiler 55 | ``` 56 | Finally, install the version of PyTorch compatible with your devices by following the [instructions on the official website](https://pytorch.org/get-started/locally/). 57 | ## Installation 58 | 59 | There are 2 options to install scSemiProfiler. 60 | * __Option 1: Install from download directory__ 61 | download scSemiProfiler from this repository, go to the downloaded scSemiProfiler package root directory, and use the pip tool to install 62 | 63 | ```shell 64 | pip install . 65 | ``` 66 | 67 | * __Option 2: Install from Github__: 68 | ```shell 69 | pip install --upgrade https://github.com/mcgilldinglab/scSemiProfiler/zipball/main 70 | ``` 71 | 72 | 73 | 74 | ## Credits and Acknowledgements 75 | **scSemiProfiler** was developed by [Jingtao Wang](https://github.com/JingtaoWang22), [Gregory Fonseca](https://www.mcgill.ca/expmed/dr-gregory-fonseca-0), and [Jun Ding](https://github.com/phoenixding) at McGill University, with support from the Canadian Institutes of Health Research (CIHR), Fonds de recherche du Québec – Santé (FRQS), and the Natural Sciences and Engineering Research Council of Canada (NSERC). Additional funding was provided by the Meakins-Christie Chair in Respiratory Research. This work is part of the Human Cell Atlas (HCA) publication bundle (HCA-8). 76 | 77 | ## Contacts 78 | Please don't hesitate to contact us if you have any questions and we will be happy to help: 79 | * jingtao.wang at mail.mcgill.ca 80 | * gregory.fonseca at mcgill.ca 81 | * jun.ding at mcgill.ca 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = source 9 | BUILDDIR = build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=source 11 | set BUILDDIR=build 12 | 13 | if "%1" == "" goto help 14 | 15 | %SPHINXBUILD% >NUL 2>NUL 16 | if errorlevel 9009 ( 17 | echo. 18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 19 | echo.installed, then set the SPHINXBUILD environment variable to point 20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 21 | echo.may add the Sphinx directory to PATH. 22 | echo. 23 | echo.If you don't have Sphinx installed, grab it from 24 | echo.http://sphinx-doc.org/ 25 | exit /b 1 26 | ) 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | #sphinx==3.5.4 2 | #sphinx-rtd-theme==1.3.0rc1 3 | sphinxcontrib-applehelp==1.0.7 # 4 | -------------------------------------------------------------------------------- /docs/source/_templates/README.md: -------------------------------------------------------------------------------- 1 | # Templates 2 | 3 | These templates are adapted from [JamesALeedham/Sphinx-Autosummary-Recursion](https://github.com/JamesALeedham/Sphinx-Autosummary-Recursion). 4 | -------------------------------------------------------------------------------- /docs/source/_templates/class.rst: -------------------------------------------------------------------------------- 1 | {{ fullname | escape | underline}} 2 | 3 | .. currentmodule:: {{ module }} 4 | 5 | .. autoclass:: {{ objname }} 6 | :show-inheritance: 7 | 8 | {% block methods %} 9 | {% if methods %} 10 | .. rubric:: {{ _('Methods') }} 11 | 12 | .. autosummary:: 13 | :toctree: 14 | :nosignatures: 15 | {% for item in methods %} 16 | {%- if item in members and item not in inherited_members and not item.startswith('_') %} 17 | ~{{ name }}.{{ item }} 18 | {%- endif -%} 19 | {%- endfor %} 20 | {% endif %} 21 | {% endblock %} 22 | 23 | {% block attributes %} 24 | {% if attributes %} 25 | .. rubric:: {{ _('Attributes') }} 26 | 27 | .. autosummary:: 28 | {% for item in attributes %} 29 | {%- if item in members and item not in inherited_members and not item.startswith('_') %} 30 | ~{{ name }}.{{ item }} 31 | {%- endif -%} 32 | {%- endfor %} 33 | {% endif %} 34 | {% endblock %} 35 | -------------------------------------------------------------------------------- /docs/source/_templates/module.rst: -------------------------------------------------------------------------------- 1 | {{ fullname | escape | underline}} 2 | 3 | .. automodule:: {{ fullname }} 4 | 5 | {% block attributes %} 6 | {% if attributes %} 7 | .. rubric:: Module attributes 8 | 9 | .. autosummary:: 10 | :toctree: 11 | {% for item in attributes %} 12 | {{ item }} 13 | {%- endfor %} 14 | {% endif %} 15 | {% endblock %} 16 | 17 | {% block functions %} 18 | {% if functions %} 19 | .. rubric:: {{ _('Functions') }} 20 | 21 | .. autosummary:: 22 | :toctree: 23 | :nosignatures: 24 | {% for item in functions %} 25 | {{ item }} 26 | {%- endfor %} 27 | {% endif %} 28 | {% endblock %} 29 | 30 | {% block classes %} 31 | {% if classes %} 32 | .. rubric:: {{ _('Classes') }} 33 | 34 | .. autosummary:: 35 | :toctree: 36 | :template: class.rst 37 | :nosignatures: 38 | {% for item in classes %} 39 | {{ item }} 40 | {%- endfor %} 41 | {% endif %} 42 | {% endblock %} 43 | 44 | {% block exceptions %} 45 | {% if exceptions %} 46 | .. rubric:: {{ _('Exceptions') }} 47 | 48 | .. autosummary:: 49 | :toctree: 50 | {% for item in exceptions %} 51 | {{ item }} 52 | {%- endfor %} 53 | {% endif %} 54 | {% endblock %} 55 | 56 | {% block modules %} 57 | {% if modules %} 58 | .. rubric:: Submodules 59 | 60 | .. autosummary:: 61 | :toctree: 62 | :template: module.rst 63 | :recursive: 64 | {% for item in modules %} 65 | {{ item }} 66 | {%- endfor %} 67 | {% endif %} 68 | {% endblock %} 69 | -------------------------------------------------------------------------------- /docs/source/api.rst: -------------------------------------------------------------------------------- 1 | API documentation 2 | ================= 3 | 4 | This section provides detailed API documentation for all public functions 5 | and classes in ``seSemiProfiler``. 6 | 7 | 8 | 9 | Initial Setup 10 | ~~~~~ 11 | 12 | 13 | .. module:: scSemiProfiler.initial_setup 14 | .. currentmodule:: scSemiProfiler 15 | 16 | .. autosummary:: 17 | :toctree: api 18 | 19 | scSemiProfiler.initial_setup.initsetup 20 | 21 | 22 | 23 | Get Representatives Single-cell (used in example) 24 | ~~~~~ 25 | 26 | 27 | .. module:: scSemiProfiler.get_eg_representatives 28 | .. currentmodule:: scSemiProfiler 29 | 30 | .. autosummary:: 31 | :toctree: api 32 | 33 | scSemiProfiler.get_eg_representatives.get_eg_representatives 34 | 35 | 36 | Single-cell Processing & Feature Augmentation 37 | ~~~~~ 38 | 39 | 40 | .. module:: scSemiProfiler.singlecell_process 41 | .. currentmodule:: scSemiProfiler 42 | 43 | .. autosummary:: 44 | :toctree: api 45 | 46 | scSemiProfiler.singlecell_process.scprocess 47 | 48 | 49 | Single-cell Inference 50 | ~~~~~ 51 | 52 | 53 | .. module:: scSemiProfiler.inference 54 | .. currentmodule:: scSemiProfiler 55 | 56 | .. autosummary:: 57 | :toctree: api 58 | 59 | scSemiProfiler.inference.tgtinfer 60 | scSemiProfiler.inference.scinfer 61 | 62 | 63 | Representatives Selection 64 | ~~~~~ 65 | 66 | 67 | .. module:: scSemiProfiler.representative_selection 68 | .. currentmodule:: scSemiProfiler 69 | 70 | .. autosummary:: 71 | :toctree: api 72 | 73 | scSemiProfiler.representative_selection.activeselection 74 | 75 | 76 | Global Mode 77 | ~~~~~ 78 | 79 | 80 | .. module:: scSemiProfiler.utils 81 | .. currentmodule:: scSemiProfiler 82 | 83 | .. autosummary:: 84 | :toctree: api 85 | 86 | scSemiProfiler.utils.inspect_data 87 | scSemiProfiler.utils.global_stop_checking 88 | 89 | 90 | 91 | Utils - Downstream Analysis 92 | ~~~~~ 93 | 94 | 95 | .. module:: scSemiProfiler.utils 96 | .. currentmodule:: scSemiProfiler 97 | 98 | .. autosummary:: 99 | :toctree: api 100 | 101 | scSemiProfiler.utils.estimate_cost 102 | scSemiProfiler.utils.visualize_recon 103 | scSemiProfiler.utils.visualize_inferred 104 | scSemiProfiler.utils.loss_curve 105 | scSemiProfiler.utils.assemble_cohort 106 | scSemiProfiler.utils.assemble_representatives 107 | scSemiProfiler.utils.compare_umaps 108 | scSemiProfiler.utils.compare_adata_umaps 109 | scSemiProfiler.utils.celltype_proportion 110 | scSemiProfiler.utils.composition_by_group 111 | scSemiProfiler.utils.geneset_pattern 112 | scSemiProfiler.utils.celltype_signature_comparison 113 | scSemiProfiler.utils.rrho 114 | scSemiProfiler.utils.enrichment_comparison 115 | scSemiProfiler.utils.get_error 116 | scSemiProfiler.utils.errorcurve 117 | 118 | 119 | 120 | Utils - Statistics 121 | ~~~~~ 122 | 123 | 124 | .. module:: scSemiProfiler.utils 125 | .. currentmodule:: scSemiProfiler 126 | 127 | .. autosummary:: 128 | :toctree: api 129 | 130 | scSemiProfiler.utils.comb 131 | scSemiProfiler.utils.hyperp 132 | scSemiProfiler.utils.hypert 133 | scSemiProfiler.utils.faiss_knn 134 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | r""" 2 | Sphinx configuration 3 | """ 4 | import os, sys 5 | import inspect 6 | import sphinx_autodoc_typehints 7 | 8 | sys.path.insert(0, os.path.abspath('../..')) 9 | 10 | 11 | import scSemiProfiler 12 | project = 'scSemiProfiler' 13 | version = '1.0.0' 14 | release = '1.0.0' 15 | author = "Jingtao Wang" 16 | copyright = "McGill Ding Lab, 2023" 17 | 18 | 19 | 20 | extensions = [ 21 | 'sphinx.ext.duration', 22 | 'sphinx.ext.doctest', 23 | 'sphinx.ext.autodoc', 24 | 'sphinx.ext.autosummary', 25 | 'sphinx.ext.intersphinx', 26 | 27 | 'sphinx.ext.napoleon', 28 | 'sphinx.ext.viewcode', 29 | 'sphinx.ext.mathjax', 30 | 'sphinx_autodoc_typehints', 31 | 'sphinx_copybutton', 32 | 'nbsphinx' 33 | ] 34 | 35 | intersphinx_mapping = { 36 | 'python': ('https://docs.python.org/3/', None), 37 | 'sphinx': ('https://www.sphinx-doc.org/en/master/', None), 38 | } 39 | 40 | intersphinx_mapping = dict( 41 | python=('https://docs.python.org/3/', None), 42 | numpy=('https://numpy.org/doc/stable/', None), 43 | scipy=('https://docs.scipy.org/doc/scipy/reference/', None), 44 | pandas=('https://pandas.pydata.org/pandas-docs/stable/', None), 45 | sklearn=('https://scikit-learn.org/stable/', None), 46 | matplotlib=('https://matplotlib.org/stable/', None), 47 | seaborn=('https://seaborn.pydata.org/', None), 48 | networkx=('https://networkx.org/documentation/stable/', None), 49 | anndata=('https://anndata.readthedocs.io/en/stable/', None), 50 | scanpy=('https://scanpy.readthedocs.io/en/stable/', None), 51 | torch=('https://pytorch.org/docs/stable/', None), 52 | ignite=('https://pytorch.org/ignite/', None), 53 | plotly=('https://plotly.com/python-api-reference/', None) 54 | ) 55 | 56 | qualname_overrides = { 57 | 'anndata._core.anndata.AnnData': 'anndata.AnnData', 58 | 'matplotlib.axes._axes.Axes': 'matplotlib.axes.Axes', 59 | 'networkx.classes.graph.Graph': 'networkx.Graph', 60 | 'networkx.classes.digraph.DiGraph': 'networkx.DiGraph', 61 | 'networkx.classes.multigraph.MultiGraph': 'networkx.MultiGraph', 62 | 'networkx.classes.multidigraph.MultiDiGraph': 'networkx.MultiDiGraph', 63 | 'numpy.random.mtrand.RandomState': 'numpy.random.RandomState', 64 | 'pandas.core.frame.DataFrame': 'pandas.DataFrame', 65 | 'scipy.sparse.base.spmatrix': 'scipy.sparse.spmatrix', 66 | 'seaborn.axisgrid.JointGrid': 'seaborn.JointGrid', 67 | 'torch.device': 'torch.torch.device', 68 | 'torch.nn.modules.module.Module': 'torch.nn.Module' 69 | } 70 | 71 | 72 | intersphinx_disabled_domains = ['std'] 73 | 74 | templates_path = ['_templates'] 75 | 76 | 77 | source_suffix = '.rst' 78 | master_doc = 'index' 79 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store',\ 80 | 'scSemiProfiler.fast_generator.reparameterize_gaussian', 'scSemiProfiler.fast_generator.AdversarialTrainingPlan'] 81 | 82 | html_show_sourcelink = True 83 | set_type_checking_flag = True 84 | typehints_fully_qualified = True 85 | napoleon_use_rtype = False 86 | autosummary_generate = True 87 | autosummary_generate_overwrite = True 88 | autodoc_preserve_defaults = True 89 | autodoc_inherit_docstrings = True 90 | autodoc_default_options = { 91 | 'autosummary': True 92 | } 93 | 94 | 95 | # -- Options for HTML output 96 | html_theme = 'sphinx_rtd_theme' 97 | 98 | # -- Options for EPUB output 99 | epub_show_urls = 'footnote' 100 | 101 | 102 | -------------------------------------------------------------------------------- /docs/source/contact.rst: -------------------------------------------------------------------------------- 1 | Contact Us 2 | ========== 3 | 4 | For more information or to reach out, please contact us at: 5 | 6 | - Email: jingtao.wang@mail.mcgill.ca 7 | - McGill Ding Lab: http://junding.lab.mcgill.ca/ -------------------------------------------------------------------------------- /docs/source/covid_individual_deconv.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcgilldinglab/scSemiProfiler/5a9c10e3ac06eeec73cb4ddcada495a216f3d849/docs/source/covid_individual_deconv.jpg -------------------------------------------------------------------------------- /docs/source/covidreconsemi.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcgilldinglab/scSemiProfiler/5a9c10e3ac06eeec73cb4ddcada495a216f3d849/docs/source/covidreconsemi.jpg -------------------------------------------------------------------------------- /docs/source/credits.rst: -------------------------------------------------------------------------------- 1 | Credicts 2 | ========== 3 | 4 | scSemiProfiler is jointly developed by `Jingtao Wang `_, `Gregory Fonseca `_, and `Jun Ding `_ from McGill University. 5 | -------------------------------------------------------------------------------- /docs/source/environment.txt: -------------------------------------------------------------------------------- 1 | ## Environment Information 2 | 3 | - **Conda Version**: conda 22.9.0 4 | - **Python Version**: 3.9.18 5 | - **Operating System**: 20.04.5 LTS (Focal Fossa) 6 | 7 | ### Installed Packages 8 | # 9 | # Name Version Build Channel 10 | _libgcc_mutex 0.1 conda_forge conda-forge 11 | _openmp_mutex 4.5 2_gnu conda-forge 12 | absl-py 2.0.0 pyhd8ed1ab_0 conda-forge 13 | aiohttp 3.9.1 pypi_0 pypi 14 | aiosignal 1.3.1 pypi_0 pypi 15 | anndata 0.10.3 pyhd8ed1ab_0 conda-forge 16 | annotated-types 0.6.0 pyhd8ed1ab_0 conda-forge 17 | anyio 3.7.1 pyhd8ed1ab_0 conda-forge 18 | aom 3.7.1 h59595ed_0 conda-forge 19 | array-api-compat 1.4 pyhd8ed1ab_0 conda-forge 20 | arrow 1.3.0 pyhd8ed1ab_0 conda-forge 21 | asttokens 2.4.1 pypi_0 pypi 22 | async-timeout 4.0.3 pypi_0 pypi 23 | attrs 23.1.0 pypi_0 pypi 24 | backoff 2.2.1 pyhd8ed1ab_0 conda-forge 25 | beautifulsoup4 4.12.2 pyha770c72_0 conda-forge 26 | blessed 1.19.1 pyhe4f9e05_2 conda-forge 27 | blosc 1.21.5 h0f2a231_0 conda-forge 28 | boto3 1.33.2 pyhd8ed1ab_0 conda-forge 29 | botocore 1.33.2 pyhd8ed1ab_0 conda-forge 30 | brotli 1.1.0 hd590300_1 conda-forge 31 | brotli-bin 1.1.0 hd590300_1 conda-forge 32 | brotli-python 1.1.0 py39h3d6467e_1 conda-forge 33 | bzip2 1.0.8 hd590300_5 conda-forge 34 | c-ares 1.22.1 hd590300_0 conda-forge 35 | ca-certificates 2023.11.17 hbcca054_0 conda-forge 36 | cachecontrol 0.13.1 pyhd8ed1ab_0 conda-forge 37 | cachecontrol-with-filecache 0.13.1 pyhd8ed1ab_0 conda-forge 38 | cached-property 1.5.2 hd8ed1ab_1 conda-forge 39 | cached_property 1.5.2 pyha770c72_1 conda-forge 40 | certifi 2023.11.17 pyhd8ed1ab_0 conda-forge 41 | cffi 1.16.0 py39h7a31438_0 conda-forge 42 | charset-normalizer 3.3.2 pyhd8ed1ab_0 conda-forge 43 | chex 0.1.7 pypi_0 pypi 44 | cleo 2.1.0 pyhd8ed1ab_0 conda-forge 45 | click 8.1.7 unix_pyh707e725_0 conda-forge 46 | colorama 0.4.6 pyhd8ed1ab_0 conda-forge 47 | comm 0.2.0 pypi_0 pypi 48 | contextlib2 21.6.0 pyhd8ed1ab_0 conda-forge 49 | contourpy 1.2.0 py39h7633fee_0 conda-forge 50 | crashtest 0.4.1 pyhd8ed1ab_0 conda-forge 51 | croniter 1.3.15 pypi_0 pypi 52 | cryptography 41.0.7 py39hd4f0224_0 conda-forge 53 | cycler 0.12.1 pyhd8ed1ab_0 conda-forge 54 | dateutils 0.6.12 py_0 conda-forge 55 | dav1d 1.2.1 hd590300_0 conda-forge 56 | dbus 1.13.6 h5008d03_3 conda-forge 57 | debugpy 1.8.0 pypi_0 pypi 58 | decorator 5.1.1 pypi_0 pypi 59 | deepdiff 6.7.1 pyhd8ed1ab_0 conda-forge 60 | distlib 0.3.7 pyhd8ed1ab_0 conda-forge 61 | dm-tree 0.1.8 pypi_0 pypi 62 | docrep 0.3.2 pyh44b312d_0 conda-forge 63 | dulwich 0.21.6 py39hd1e30aa_2 conda-forge 64 | et_xmlfile 1.1.0 pyhd8ed1ab_0 conda-forge 65 | etils 1.5.1 pyhd8ed1ab_1 conda-forge 66 | exceptiongroup 1.2.0 pyhd8ed1ab_0 conda-forge 67 | executing 2.0.1 pypi_0 pypi 68 | expat 2.5.0 hcb278e6_1 conda-forge 69 | faiss-cpu 1.7.4 pypi_0 pypi 70 | fastapi 0.88.0 pypi_0 pypi 71 | filelock 3.13.1 pyhd8ed1ab_0 conda-forge 72 | flax 0.7.5 pyhd8ed1ab_0 conda-forge 73 | fonttools 4.45.1 py39hd1e30aa_0 conda-forge 74 | freetype 2.12.1 h267a509_2 conda-forge 75 | frozenlist 1.4.0 pypi_0 pypi 76 | fsspec 2023.10.0 pyhca7485f_0 conda-forge 77 | get-annotations 0.1.2 pypi_0 pypi 78 | gettext 0.21.1 h27087fc_0 conda-forge 79 | gmp 6.3.0 h59595ed_0 conda-forge 80 | gmpy2 2.1.2 py39h376b7d2_1 conda-forge 81 | gseapy 1.1.0 pypi_0 pypi 82 | h11 0.14.0 pyhd8ed1ab_0 conda-forge 83 | h5py 3.10.0 nompi_py39h87cadad_100 conda-forge 84 | hdf5 1.14.2 nompi_h4f84152_100 conda-forge 85 | idna 3.6 pyhd8ed1ab_0 conda-forge 86 | igraph 0.11.3 pypi_0 pypi 87 | importlib-metadata 6.8.0 pyha770c72_0 conda-forge 88 | importlib-resources 6.1.1 pyhd8ed1ab_0 conda-forge 89 | importlib_metadata 6.8.0 hd8ed1ab_0 conda-forge 90 | importlib_resources 6.1.1 pyhd8ed1ab_0 conda-forge 91 | inquirer 3.1.4 pyhd8ed1ab_0 conda-forge 92 | ipykernel 6.27.1 pypi_0 pypi 93 | ipython 8.18.1 pypi_0 pypi 94 | itsdangerous 2.1.2 pyhd8ed1ab_0 conda-forge 95 | jaraco.classes 3.3.0 pyhd8ed1ab_0 conda-forge 96 | jax 0.4.21 pypi_0 pypi 97 | jaxlib 0.4.21+cuda11.cudnn86 pypi_0 pypi 98 | jedi 0.19.1 pypi_0 pypi 99 | jeepney 0.8.0 pyhd8ed1ab_0 conda-forge 100 | jinja2 3.1.2 pyhd8ed1ab_1 conda-forge 101 | jmespath 1.0.1 pyhd8ed1ab_0 conda-forge 102 | joblib 1.3.2 pyhd8ed1ab_0 conda-forge 103 | jupyter-client 8.6.0 pypi_0 pypi 104 | jupyter-core 5.5.0 pypi_0 pypi 105 | keyring 24.3.0 py39hf3d152e_0 conda-forge 106 | keyutils 1.6.1 h166bdaf_0 conda-forge 107 | kiwisolver 1.4.5 py39h7633fee_1 conda-forge 108 | krb5 1.21.2 h659d440_0 conda-forge 109 | lcms2 2.15 hb7c19ff_3 conda-forge 110 | ld_impl_linux-64 2.40 h41732ed_0 conda-forge 111 | lerc 4.0.0 h27087fc_0 conda-forge 112 | libabseil 20230802.1 cxx17_h59595ed_0 conda-forge 113 | libaec 1.1.2 h59595ed_1 conda-forge 114 | libavif16 1.0.2 hed45d22_0 conda-forge 115 | libblas 3.9.0 20_linux64_openblas conda-forge 116 | libbrotlicommon 1.1.0 hd590300_1 conda-forge 117 | libbrotlidec 1.1.0 hd590300_1 conda-forge 118 | libbrotlienc 1.1.0 hd590300_1 conda-forge 119 | libcblas 3.9.0 20_linux64_openblas conda-forge 120 | libcurl 8.4.0 hca28451_0 conda-forge 121 | libdeflate 1.19 hd590300_0 conda-forge 122 | libedit 3.1.20191231 he28a2e2_2 conda-forge 123 | libev 4.33 h516909a_1 conda-forge 124 | libexpat 2.5.0 hcb278e6_1 conda-forge 125 | libffi 3.4.2 h7f98852_5 conda-forge 126 | libgcc-ng 13.2.0 h807b86a_3 conda-forge 127 | libgfortran-ng 13.2.0 h69a702a_3 conda-forge 128 | libgfortran5 13.2.0 ha4646dd_3 conda-forge 129 | libglib 2.78.1 h783c2da_1 conda-forge 130 | libgomp 13.2.0 h807b86a_3 conda-forge 131 | libiconv 1.17 h166bdaf_0 conda-forge 132 | libjpeg-turbo 3.0.0 hd590300_1 conda-forge 133 | liblapack 3.9.0 20_linux64_openblas conda-forge 134 | libllvm14 14.0.6 hcd5def8_4 conda-forge 135 | libnghttp2 1.58.0 h47da74e_0 conda-forge 136 | libnsl 2.0.1 hd590300_0 conda-forge 137 | libopenblas 0.3.25 pthreads_h413a1c8_0 conda-forge 138 | libpng 1.6.39 h753d276_0 conda-forge 139 | libprotobuf 4.24.4 hf27288f_0 conda-forge 140 | libsqlite 3.44.2 h2797004_0 conda-forge 141 | libssh2 1.11.0 h0841786_0 conda-forge 142 | libstdcxx-ng 13.2.0 h7e041cc_3 conda-forge 143 | libtiff 4.6.0 ha9c0a0a_2 conda-forge 144 | libuuid 2.38.1 h0b41bf4_0 conda-forge 145 | libuv 1.46.0 hd590300_0 conda-forge 146 | libwebp-base 1.3.2 hd590300_0 conda-forge 147 | libxcb 1.15 h0b41bf4_0 conda-forge 148 | libzlib 1.2.13 hd590300_5 conda-forge 149 | lightning 2.0.0 pypi_0 pypi 150 | lightning-cloud 0.5.55 pyhd8ed1ab_0 conda-forge 151 | lightning-utilities 0.10.0 pyhd8ed1ab_0 conda-forge 152 | llvmlite 0.41.1 py39h174d805_0 conda-forge 153 | lz4-c 1.9.4 hcb278e6_0 conda-forge 154 | markdown-it-py 3.0.0 pyhd8ed1ab_0 conda-forge 155 | markupsafe 2.1.3 py39hd1e30aa_1 conda-forge 156 | matplotlib-base 3.8.2 py39he9076e7_0 conda-forge 157 | matplotlib-inline 0.1.6 pypi_0 pypi 158 | mdurl 0.1.0 pyhd8ed1ab_0 conda-forge 159 | ml-collections 0.1.1 pyhd8ed1ab_0 conda-forge 160 | ml_dtypes 0.3.1 py39hddac248_2 conda-forge 161 | more-itertools 10.1.0 pyhd8ed1ab_0 conda-forge 162 | mpc 1.3.1 hfe3b2da_0 conda-forge 163 | mpfr 4.2.1 h9458935_0 conda-forge 164 | mpmath 1.3.0 pyhd8ed1ab_0 conda-forge 165 | msgpack-python 1.0.7 py39h7633fee_0 conda-forge 166 | mudata 0.2.3 pyhd8ed1ab_0 conda-forge 167 | multidict 6.0.4 pypi_0 pypi 168 | multipledispatch 0.6.0 py_0 conda-forge 169 | munkres 1.1.4 pyh9f0ad1d_0 conda-forge 170 | natsort 8.4.0 pyhd8ed1ab_0 conda-forge 171 | ncurses 6.4 h59595ed_2 conda-forge 172 | nest-asyncio 1.5.8 pyhd8ed1ab_0 conda-forge 173 | networkx 3.2.1 pyhd8ed1ab_0 conda-forge 174 | nomkl 1.0 h5ca1d4c_0 conda-forge 175 | numba 0.58.1 py39h615d6bd_0 conda-forge 176 | numpy 1.26.2 py39h474f0d3_0 conda-forge 177 | numpyro 0.13.2 pyhd8ed1ab_1 conda-forge 178 | nvidia-cublas-cu11 11.11.3.6 pypi_0 pypi 179 | nvidia-cuda-cupti-cu11 11.8.87 pypi_0 pypi 180 | nvidia-cuda-nvcc-cu11 11.8.89 pypi_0 pypi 181 | nvidia-cuda-nvrtc-cu11 11.8.89 pypi_0 pypi 182 | nvidia-cuda-runtime-cu11 11.8.89 pypi_0 pypi 183 | nvidia-cudnn-cu11 8.9.6.50 pypi_0 pypi 184 | nvidia-cufft-cu11 10.9.0.58 pypi_0 pypi 185 | nvidia-cusolver-cu11 11.4.1.48 pypi_0 pypi 186 | nvidia-cusparse-cu11 11.7.5.86 pypi_0 pypi 187 | nvidia-nccl-cu11 2.19.3 pypi_0 pypi 188 | openjpeg 2.5.0 h488ebb8_3 conda-forge 189 | openpyxl 3.1.2 py39hd1e30aa_1 conda-forge 190 | openssl 3.2.0 hd590300_1 conda-forge 191 | opt-einsum 3.3.0 hd8ed1ab_2 conda-forge 192 | opt_einsum 3.3.0 pyhc1e730c_2 conda-forge 193 | optax 0.1.7 pyhd8ed1ab_0 conda-forge 194 | orbax-checkpoint 0.4.3 pyhd8ed1ab_0 conda-forge 195 | ordered-set 4.1.0 pyhd8ed1ab_0 conda-forge 196 | orjson 3.9.10 py39h10b2342_0 conda-forge 197 | packaging 23.2 pyhd8ed1ab_0 conda-forge 198 | pandas 2.1.3 py39hddac248_0 conda-forge 199 | parso 0.8.3 pypi_0 pypi 200 | patsy 0.5.3 pypi_0 pypi 201 | pcre2 10.42 hcad00b1_0 conda-forge 202 | pexpect 4.8.0 pyh1a96a4e_2 conda-forge 203 | pillow 10.1.0 py39had0adad_0 conda-forge 204 | pip 23.3.1 pyhd8ed1ab_0 conda-forge 205 | pkginfo 1.9.6 pyhd8ed1ab_0 conda-forge 206 | platformdirs 3.11.0 pyhd8ed1ab_0 conda-forge 207 | poetry 1.7.1 linux_pyha804496_0 conda-forge 208 | poetry-core 1.8.1 pyhd8ed1ab_0 conda-forge 209 | poetry-plugin-export 1.6.0 pyhd8ed1ab_0 conda-forge 210 | prompt-toolkit 3.0.41 pypi_0 pypi 211 | protobuf 4.24.4 py39h60f6b12_0 conda-forge 212 | psutil 5.9.5 py39hd1e30aa_1 conda-forge 213 | pthread-stubs 0.4 h36c2ea0_1001 conda-forge 214 | ptyprocess 0.7.0 pyhd3deb0d_0 conda-forge 215 | pure-eval 0.2.2 pypi_0 pypi 216 | pybind11-abi 4 hd8ed1ab_3 conda-forge 217 | pycparser 2.21 pyhd8ed1ab_0 conda-forge 218 | pydantic 1.10.13 pypi_0 pypi 219 | pydantic-core 2.3.0 py39h9fdd4d6_0 conda-forge 220 | pygments 2.17.2 pyhd8ed1ab_0 conda-forge 221 | pyjwt 2.8.0 pyhd8ed1ab_0 conda-forge 222 | pynndescent 0.5.11 pypi_0 pypi 223 | pyparsing 3.1.1 pyhd8ed1ab_0 conda-forge 224 | pyproject_hooks 1.0.0 pyhd8ed1ab_0 conda-forge 225 | pyro-api 0.1.2 pyhd8ed1ab_0 conda-forge 226 | pyro-ppl 1.8.6 pyhd8ed1ab_0 conda-forge 227 | pysocks 1.7.1 pyha2e5f31_6 conda-forge 228 | python 3.9.18 h0755675_0_cpython conda-forge 229 | python-build 1.0.3 pyhd8ed1ab_0 conda-forge 230 | python-dateutil 2.8.2 pyhd8ed1ab_0 conda-forge 231 | python-editor 1.0.4 py_0 conda-forge 232 | python-fastjsonschema 2.19.0 pyhd8ed1ab_0 conda-forge 233 | python-installer 0.7.0 pyhd8ed1ab_0 conda-forge 234 | python-multipart 0.0.6 pyhd8ed1ab_0 conda-forge 235 | python-tzdata 2023.3 pyhd8ed1ab_0 conda-forge 236 | python_abi 3.9 4_cp39 conda-forge 237 | pytorch-lightning 2.1.1 pyhd8ed1ab_0 conda-forge 238 | pytz 2023.3.post1 pyhd8ed1ab_0 conda-forge 239 | pyyaml 6.0.1 py39hd1e30aa_1 conda-forge 240 | pyzmq 25.1.1 pypi_0 pypi 241 | rapidfuzz 3.5.2 py39h3d6467e_0 conda-forge 242 | rav1e 0.6.6 he8a937b_2 conda-forge 243 | readchar 4.0.5 pyhd8ed1ab_0 conda-forge 244 | readline 8.2 h8228510_1 conda-forge 245 | requests 2.31.0 pyhd8ed1ab_0 conda-forge 246 | requests-toolbelt 1.0.0 pyhd8ed1ab_0 conda-forge 247 | rich 13.7.0 pyhd8ed1ab_0 conda-forge 248 | s3transfer 0.8.1 pyhd8ed1ab_0 conda-forge 249 | scanpy 1.9.6 pypi_0 pypi 250 | scikit-learn 1.3.2 py39ha22ef79_1 conda-forge 251 | scipy 1.11.4 py39h474f0d3_0 conda-forge 252 | scsemiprofiler 1.0.0 pypi_0 pypi 253 | scvi-tools 1.0.4 pyhd8ed1ab_0 conda-forge 254 | seaborn 0.12.2 pypi_0 pypi 255 | secretstorage 3.3.3 py39hf3d152e_2 conda-forge 256 | session-info 1.0.0 pypi_0 pypi 257 | setuptools 68.2.2 pyhd8ed1ab_0 conda-forge 258 | shellingham 1.5.4 pyhd8ed1ab_0 conda-forge 259 | six 1.16.0 pyh6c4a22f_0 conda-forge 260 | sleef 3.5.1 h9b69904_2 conda-forge 261 | snappy 1.1.10 h9fff704_0 conda-forge 262 | sniffio 1.3.0 pyhd8ed1ab_0 conda-forge 263 | soupsieve 2.5 pyhd8ed1ab_1 conda-forge 264 | sparse 0.14.0 pyhd8ed1ab_0 conda-forge 265 | stack-data 0.6.3 pypi_0 pypi 266 | starlette 0.22.0 pypi_0 pypi 267 | starsessions 1.3.0 pyhd8ed1ab_0 conda-forge 268 | statsmodels 0.14.0 pypi_0 pypi 269 | stdlib-list 0.10.0 pypi_0 pypi 270 | svt-av1 1.7.0 h59595ed_0 conda-forge 271 | sympy 1.12 pypyh9d50eac_103 conda-forge 272 | tensorstore 0.1.50 py39hfddb6fb_0 conda-forge 273 | texttable 1.7.0 pypi_0 pypi 274 | threadpoolctl 3.2.0 pyha21a80b_0 conda-forge 275 | tk 8.6.13 noxft_h4845f30_101 conda-forge 276 | tomli 2.0.1 pyhd8ed1ab_0 conda-forge 277 | tomlkit 0.12.3 pyha770c72_0 conda-forge 278 | toolz 0.12.0 pyhd8ed1ab_0 conda-forge 279 | torch 1.12.1+cu113 pypi_0 pypi 280 | torchaudio 0.12.1+cu113 pypi_0 pypi 281 | torchmetrics 1.2.0 pyhd8ed1ab_0 conda-forge 282 | torchvision 0.13.1+cu113 pypi_0 pypi 283 | tornado 6.4 pypi_0 pypi 284 | tqdm 4.66.1 pyhd8ed1ab_0 conda-forge 285 | traitlets 5.14.0 pyhd8ed1ab_0 conda-forge 286 | trove-classifiers 2023.11.22 pyhd8ed1ab_0 conda-forge 287 | types-python-dateutil 2.8.19.14 pyhd8ed1ab_0 conda-forge 288 | typing-extensions 4.8.0 hd8ed1ab_0 conda-forge 289 | typing_extensions 4.8.0 pyha770c72_0 conda-forge 290 | tzdata 2023c h71feb2d_0 conda-forge 291 | umap-learn 0.5.5 pypi_0 pypi 292 | unicodedata2 15.1.0 py39hd1e30aa_0 conda-forge 293 | urllib3 1.26.18 pyhd8ed1ab_0 conda-forge 294 | uvicorn 0.24.0 py39hf3d152e_0 conda-forge 295 | virtualenv 20.24.7 pyhd8ed1ab_0 conda-forge 296 | wcwidth 0.2.12 pyhd8ed1ab_0 conda-forge 297 | websocket-client 1.6.4 pyhd8ed1ab_0 conda-forge 298 | websockets 11.0.3 pypi_0 pypi 299 | wheel 0.42.0 pyhd8ed1ab_0 conda-forge 300 | xarray 2023.11.0 pyhd8ed1ab_0 conda-forge 301 | xlrd 1.2.0 pyh9f0ad1d_1 conda-forge 302 | xorg-libxau 1.0.11 hd590300_0 conda-forge 303 | xorg-libxdmcp 1.1.3 h7f98852_0 conda-forge 304 | xz 5.2.6 h166bdaf_0 conda-forge 305 | yaml 0.2.5 h7f98852_2 conda-forge 306 | yarl 1.9.3 pypi_0 pypi 307 | zipp 3.17.0 pyhd8ed1ab_0 conda-forge 308 | zstd 1.5.5 hfc55251_0 conda-forge 309 | -------------------------------------------------------------------------------- /docs/source/gallery.rst: -------------------------------------------------------------------------------- 1 | Gallery 2 | ========= 3 | 4 | .. image:: covidreconsemi.jpg 5 | :width: 800 6 | :alt: convidreconsemi 7 | 8 | **Reconstruction and Inference:** Images in the first row show the deep generative model's reconstruction ability. Images in the second row show the inferred single-cell data for the target sample is highly similar to the ground truth. 9 | 10 | 11 | 12 | .. image:: covid_individual_deconv.jpg 13 | :width: 800 14 | :alt: covid_individual_deconv 15 | 16 | **Cell Type Deconvolution:** Samples in the semi-profiled dataset have nearly identical cell type compositions as the ones in the real-profiled datset. 17 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | Welcome to the documentation for scSemiProfiler! 2 | ================================== 3 | 4 | 5 | 6 | ``scSemiProfiler`` is a computational tool combining deep generative models and active learning to economically generate single-cell data for biological studies. It efficiently transforms bulk cohort data into detailed single-cell data using templates from selected representative samples. More details are in our `paper `_. 7 | 8 | Methods Overview 9 | ---------------- 10 | 11 | .. image:: ../../method.jpg 12 | :width: 800 13 | :alt: Mothod Overview 14 | 15 | For an interested cohort, scSemiProfiler runs the following steps to generate single-cell data for all samples. 16 | 17 | **a**, Initial Setup: Bulk sequencing is first performed on the entire cohort, with subsequent clustering analysis of this data to pinpoint representative samples, typically those closest to the cluster centroids. 18 | 19 | **b**, Representative Profiling: The identified representatives are then subjected to single-cell sequencing. The data obtained from this sequencing is further processed to determine gene set scores and feature importance weights, enriching the subsequent analysis steps. 20 | 21 | **c**, Deep Generative Inference: This phase uses a VAE-GAN-based model to estimate single-cell data for a target sample. In its three-stage training, the model initially reconstructs the representative cells, and then produces target cells by analyzing the differences between the two samples as indicated by the bulk data. 22 | 23 | **d**, Representative Selection Decision: Decisions are made on selecting additional representatives, considering budget limits and current representative effectiveness. An active learning algorithm, leveraging bulk data and the generative model insights, identifies new optimal representatives. These are then sequenced (**b**) and serve as and integrated as new references in the single-cell inference process (**c**). 24 | 25 | **e**, Comprehensive Downstream Analyses: This final panel highlights the extensive analyses possible with semi-profiled single-cell data. It underscores the model’s ability to yield deep, diverse insights, demonstrating the full potential and broad applicability of the semi-profiled data. 26 | 27 | 28 | .. note:: 29 | 30 | This project is under active development. 31 | 32 | Contents 33 | -------- 34 | 35 | .. toctree:: 36 | :maxdepth: 2 37 | 38 | install 39 | tutorials 40 | api 41 | gallery 42 | release 43 | credits 44 | contact 45 | references 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /docs/source/install.rst: -------------------------------------------------------------------------------- 1 | Installation 2 | ============ 3 | This page includes instructions for installing scSemiProfiler. 4 | 5 | Prerequisites 6 | ------------- 7 | 8 | First, install `Anaconda `_ for your operating system if you have not. You can find specific instructions for different operating systems `here `_. 9 | 10 | Second, create a new conda environment and activate it:: 11 | 12 | conda create -n semiprofiler python=3.9 13 | conda activate semiprofiler 14 | 15 | Finally, install the version of PyTorch compatible with your devices by following the `instructions on the official website `_. 16 | 17 | Installing scSemiProfiler 18 | ------------------------- 19 | 20 | There are 2 options to install scSemiProfiler. 21 | 22 | Option 1: Install from download directory 23 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 24 | 25 | Download scSemiProfiler from the `GitHub repository `_, go to the downloaded scSemiProfiler root directory and use pip tool to install:: 26 | 27 | pip install . 28 | 29 | Option 2: Install from Github 30 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 31 | 32 | :: 33 | 34 | pip install --upgrade https://github.com/mcgilldinglab/scSemiProfiler/zipball/main 35 | 36 | The installation should take less than 2 minutes. 37 | The `environment.txt `_ file includes information about the environment that we used to test scSemiProfiler. 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /docs/source/references.rst: -------------------------------------------------------------------------------- 1 | References 2 | ========= 3 | 4 | .. [1] Jingtao Wang, Gregory Fonseca, Jun Ding. (2023) scSemiProfiler: Advancing Large-scale Single-cell Studies through Semi-profiling with Deep Generative Models and Active Learning. *bioRxiv*. https://www.biorxiv.org/content/10.1101/2023.11.20.567929v1 5 | 6 | -------------------------------------------------------------------------------- /docs/source/release.rst: -------------------------------------------------------------------------------- 1 | Release notes 2 | ============= 3 | 4 | 5 | v0.1.0 6 | ------ 7 | 8 | First public release. 9 | 10 | -------------------------------------------------------------------------------- /docs/source/requirements.txt: -------------------------------------------------------------------------------- 1 | sphinx==7.1.2 2 | sphinx-rtd-theme==1.3.0rc1 3 | -------------------------------------------------------------------------------- /docs/source/tutorials.rst: -------------------------------------------------------------------------------- 1 | Tutorials 2 | ========= 3 | 4 | We provide an example going through how to use ``scSemiProfiler`` to preprocess and semi-profile a small dataset with 12 COVID-19 samples from patients of 6 different severity levels (stored in the `example_data `_ folder in our GitHub repository). To semi-profile a cohort, the following steps will be executed: (1) initial setup, which includes preprocessing and clustering bulk data, and selecting initial representatives; (1.5) obtaining single-cell data for representatives; (2) processing single-cell data and performing feature augmentations; (3) single-cell inference using deep generative models. 5 | 6 | Then, once the inference is complete, the semi-profiled cohort can be utilized for various single-cell-level downstream analyses and compared with the results of the real-profiled cohort. The high similarity between the real and semi-profiled versions demonstrates the reliable performance of scSemiProfiler. If the budget allows, you have the option to employ an active learning algorithm to select additional representatives and proceed to the next round of semi-profiling. As more representatives are selected, the semi-profiling performance typically improves, but the costs also increase. We illustrate this trade-off relationship with an overall error versus cost curve. 7 | 8 | You can also download our `GitHub repository `_ and run the `example `_ locally. Before running the notebook, your need to install scSemiProfiler and then install the conda environment as a Jupyter Notebook kernel:: 9 | 10 | conda install ipykernel 11 | python -m ipykernel install --user --name=semiprofiler --display-name="scSemiProfiler" 12 | 13 | Then open the notebook. You can now select the kernel "scSemiProfiler" in Jupyter Notebook and run our example notebook. Instructions of running Jupyter Notebook can be found `here `_. 14 | 15 | 16 | .. toctree:: 17 | example.ipynb 18 | -------------------------------------------------------------------------------- /environment.txt: -------------------------------------------------------------------------------- 1 | ## Environment Information 2 | 3 | - **Conda Version**: conda 22.9.0 4 | - **Python Version**: 3.9.18 5 | - **Operating System**: 20.04.5 LTS (Focal Fossa) 6 | 7 | ### Installed Packages 8 | # 9 | # Name Version Build Channel 10 | _libgcc_mutex 0.1 conda_forge conda-forge 11 | _openmp_mutex 4.5 2_gnu conda-forge 12 | absl-py 2.0.0 pyhd8ed1ab_0 conda-forge 13 | aiohttp 3.9.1 pypi_0 pypi 14 | aiosignal 1.3.1 pypi_0 pypi 15 | anndata 0.10.3 pyhd8ed1ab_0 conda-forge 16 | annotated-types 0.6.0 pyhd8ed1ab_0 conda-forge 17 | anyio 3.7.1 pyhd8ed1ab_0 conda-forge 18 | aom 3.7.1 h59595ed_0 conda-forge 19 | array-api-compat 1.4 pyhd8ed1ab_0 conda-forge 20 | arrow 1.3.0 pyhd8ed1ab_0 conda-forge 21 | asttokens 2.4.1 pypi_0 pypi 22 | async-timeout 4.0.3 pypi_0 pypi 23 | attrs 23.1.0 pypi_0 pypi 24 | backoff 2.2.1 pyhd8ed1ab_0 conda-forge 25 | beautifulsoup4 4.12.2 pyha770c72_0 conda-forge 26 | blessed 1.19.1 pyhe4f9e05_2 conda-forge 27 | blosc 1.21.5 h0f2a231_0 conda-forge 28 | boto3 1.33.2 pyhd8ed1ab_0 conda-forge 29 | botocore 1.33.2 pyhd8ed1ab_0 conda-forge 30 | brotli 1.1.0 hd590300_1 conda-forge 31 | brotli-bin 1.1.0 hd590300_1 conda-forge 32 | brotli-python 1.1.0 py39h3d6467e_1 conda-forge 33 | bzip2 1.0.8 hd590300_5 conda-forge 34 | c-ares 1.22.1 hd590300_0 conda-forge 35 | ca-certificates 2023.11.17 hbcca054_0 conda-forge 36 | cachecontrol 0.13.1 pyhd8ed1ab_0 conda-forge 37 | cachecontrol-with-filecache 0.13.1 pyhd8ed1ab_0 conda-forge 38 | cached-property 1.5.2 hd8ed1ab_1 conda-forge 39 | cached_property 1.5.2 pyha770c72_1 conda-forge 40 | certifi 2023.11.17 pyhd8ed1ab_0 conda-forge 41 | cffi 1.16.0 py39h7a31438_0 conda-forge 42 | charset-normalizer 3.3.2 pyhd8ed1ab_0 conda-forge 43 | chex 0.1.7 pypi_0 pypi 44 | cleo 2.1.0 pyhd8ed1ab_0 conda-forge 45 | click 8.1.7 unix_pyh707e725_0 conda-forge 46 | colorama 0.4.6 pyhd8ed1ab_0 conda-forge 47 | comm 0.2.0 pypi_0 pypi 48 | contextlib2 21.6.0 pyhd8ed1ab_0 conda-forge 49 | contourpy 1.2.0 py39h7633fee_0 conda-forge 50 | crashtest 0.4.1 pyhd8ed1ab_0 conda-forge 51 | croniter 1.3.15 pypi_0 pypi 52 | cryptography 41.0.7 py39hd4f0224_0 conda-forge 53 | cycler 0.12.1 pyhd8ed1ab_0 conda-forge 54 | dateutils 0.6.12 py_0 conda-forge 55 | dav1d 1.2.1 hd590300_0 conda-forge 56 | dbus 1.13.6 h5008d03_3 conda-forge 57 | debugpy 1.8.0 pypi_0 pypi 58 | decorator 5.1.1 pypi_0 pypi 59 | deepdiff 6.7.1 pyhd8ed1ab_0 conda-forge 60 | distlib 0.3.7 pyhd8ed1ab_0 conda-forge 61 | dm-tree 0.1.8 pypi_0 pypi 62 | docrep 0.3.2 pyh44b312d_0 conda-forge 63 | dulwich 0.21.6 py39hd1e30aa_2 conda-forge 64 | et_xmlfile 1.1.0 pyhd8ed1ab_0 conda-forge 65 | etils 1.5.1 pyhd8ed1ab_1 conda-forge 66 | exceptiongroup 1.2.0 pyhd8ed1ab_0 conda-forge 67 | executing 2.0.1 pypi_0 pypi 68 | expat 2.5.0 hcb278e6_1 conda-forge 69 | faiss-cpu 1.7.4 pypi_0 pypi 70 | fastapi 0.88.0 pypi_0 pypi 71 | filelock 3.13.1 pyhd8ed1ab_0 conda-forge 72 | flax 0.7.5 pyhd8ed1ab_0 conda-forge 73 | fonttools 4.45.1 py39hd1e30aa_0 conda-forge 74 | freetype 2.12.1 h267a509_2 conda-forge 75 | frozenlist 1.4.0 pypi_0 pypi 76 | fsspec 2023.10.0 pyhca7485f_0 conda-forge 77 | get-annotations 0.1.2 pypi_0 pypi 78 | gettext 0.21.1 h27087fc_0 conda-forge 79 | gmp 6.3.0 h59595ed_0 conda-forge 80 | gmpy2 2.1.2 py39h376b7d2_1 conda-forge 81 | gseapy 1.1.0 pypi_0 pypi 82 | h11 0.14.0 pyhd8ed1ab_0 conda-forge 83 | h5py 3.10.0 nompi_py39h87cadad_100 conda-forge 84 | hdf5 1.14.2 nompi_h4f84152_100 conda-forge 85 | idna 3.6 pyhd8ed1ab_0 conda-forge 86 | igraph 0.11.3 pypi_0 pypi 87 | importlib-metadata 6.8.0 pyha770c72_0 conda-forge 88 | importlib-resources 6.1.1 pyhd8ed1ab_0 conda-forge 89 | importlib_metadata 6.8.0 hd8ed1ab_0 conda-forge 90 | importlib_resources 6.1.1 pyhd8ed1ab_0 conda-forge 91 | inquirer 3.1.4 pyhd8ed1ab_0 conda-forge 92 | ipykernel 6.27.1 pypi_0 pypi 93 | ipython 8.18.1 pypi_0 pypi 94 | itsdangerous 2.1.2 pyhd8ed1ab_0 conda-forge 95 | jaraco.classes 3.3.0 pyhd8ed1ab_0 conda-forge 96 | jax 0.4.21 pypi_0 pypi 97 | jaxlib 0.4.21+cuda11.cudnn86 pypi_0 pypi 98 | jedi 0.19.1 pypi_0 pypi 99 | jeepney 0.8.0 pyhd8ed1ab_0 conda-forge 100 | jinja2 3.1.2 pyhd8ed1ab_1 conda-forge 101 | jmespath 1.0.1 pyhd8ed1ab_0 conda-forge 102 | joblib 1.3.2 pyhd8ed1ab_0 conda-forge 103 | jupyter-client 8.6.0 pypi_0 pypi 104 | jupyter-core 5.5.0 pypi_0 pypi 105 | keyring 24.3.0 py39hf3d152e_0 conda-forge 106 | keyutils 1.6.1 h166bdaf_0 conda-forge 107 | kiwisolver 1.4.5 py39h7633fee_1 conda-forge 108 | krb5 1.21.2 h659d440_0 conda-forge 109 | lcms2 2.15 hb7c19ff_3 conda-forge 110 | ld_impl_linux-64 2.40 h41732ed_0 conda-forge 111 | lerc 4.0.0 h27087fc_0 conda-forge 112 | libabseil 20230802.1 cxx17_h59595ed_0 conda-forge 113 | libaec 1.1.2 h59595ed_1 conda-forge 114 | libavif16 1.0.2 hed45d22_0 conda-forge 115 | libblas 3.9.0 20_linux64_openblas conda-forge 116 | libbrotlicommon 1.1.0 hd590300_1 conda-forge 117 | libbrotlidec 1.1.0 hd590300_1 conda-forge 118 | libbrotlienc 1.1.0 hd590300_1 conda-forge 119 | libcblas 3.9.0 20_linux64_openblas conda-forge 120 | libcurl 8.4.0 hca28451_0 conda-forge 121 | libdeflate 1.19 hd590300_0 conda-forge 122 | libedit 3.1.20191231 he28a2e2_2 conda-forge 123 | libev 4.33 h516909a_1 conda-forge 124 | libexpat 2.5.0 hcb278e6_1 conda-forge 125 | libffi 3.4.2 h7f98852_5 conda-forge 126 | libgcc-ng 13.2.0 h807b86a_3 conda-forge 127 | libgfortran-ng 13.2.0 h69a702a_3 conda-forge 128 | libgfortran5 13.2.0 ha4646dd_3 conda-forge 129 | libglib 2.78.1 h783c2da_1 conda-forge 130 | libgomp 13.2.0 h807b86a_3 conda-forge 131 | libiconv 1.17 h166bdaf_0 conda-forge 132 | libjpeg-turbo 3.0.0 hd590300_1 conda-forge 133 | liblapack 3.9.0 20_linux64_openblas conda-forge 134 | libllvm14 14.0.6 hcd5def8_4 conda-forge 135 | libnghttp2 1.58.0 h47da74e_0 conda-forge 136 | libnsl 2.0.1 hd590300_0 conda-forge 137 | libopenblas 0.3.25 pthreads_h413a1c8_0 conda-forge 138 | libpng 1.6.39 h753d276_0 conda-forge 139 | libprotobuf 4.24.4 hf27288f_0 conda-forge 140 | libsqlite 3.44.2 h2797004_0 conda-forge 141 | libssh2 1.11.0 h0841786_0 conda-forge 142 | libstdcxx-ng 13.2.0 h7e041cc_3 conda-forge 143 | libtiff 4.6.0 ha9c0a0a_2 conda-forge 144 | libuuid 2.38.1 h0b41bf4_0 conda-forge 145 | libuv 1.46.0 hd590300_0 conda-forge 146 | libwebp-base 1.3.2 hd590300_0 conda-forge 147 | libxcb 1.15 h0b41bf4_0 conda-forge 148 | libzlib 1.2.13 hd590300_5 conda-forge 149 | lightning 2.0.0 pypi_0 pypi 150 | lightning-cloud 0.5.55 pyhd8ed1ab_0 conda-forge 151 | lightning-utilities 0.10.0 pyhd8ed1ab_0 conda-forge 152 | llvmlite 0.41.1 py39h174d805_0 conda-forge 153 | lz4-c 1.9.4 hcb278e6_0 conda-forge 154 | markdown-it-py 3.0.0 pyhd8ed1ab_0 conda-forge 155 | markupsafe 2.1.3 py39hd1e30aa_1 conda-forge 156 | matplotlib-base 3.8.2 py39he9076e7_0 conda-forge 157 | matplotlib-inline 0.1.6 pypi_0 pypi 158 | mdurl 0.1.0 pyhd8ed1ab_0 conda-forge 159 | ml-collections 0.1.1 pyhd8ed1ab_0 conda-forge 160 | ml_dtypes 0.3.1 py39hddac248_2 conda-forge 161 | more-itertools 10.1.0 pyhd8ed1ab_0 conda-forge 162 | mpc 1.3.1 hfe3b2da_0 conda-forge 163 | mpfr 4.2.1 h9458935_0 conda-forge 164 | mpmath 1.3.0 pyhd8ed1ab_0 conda-forge 165 | msgpack-python 1.0.7 py39h7633fee_0 conda-forge 166 | mudata 0.2.3 pyhd8ed1ab_0 conda-forge 167 | multidict 6.0.4 pypi_0 pypi 168 | multipledispatch 0.6.0 py_0 conda-forge 169 | munkres 1.1.4 pyh9f0ad1d_0 conda-forge 170 | natsort 8.4.0 pyhd8ed1ab_0 conda-forge 171 | ncurses 6.4 h59595ed_2 conda-forge 172 | nest-asyncio 1.5.8 pyhd8ed1ab_0 conda-forge 173 | networkx 3.2.1 pyhd8ed1ab_0 conda-forge 174 | nomkl 1.0 h5ca1d4c_0 conda-forge 175 | numba 0.58.1 py39h615d6bd_0 conda-forge 176 | numpy 1.26.2 py39h474f0d3_0 conda-forge 177 | numpyro 0.13.2 pyhd8ed1ab_1 conda-forge 178 | nvidia-cublas-cu11 11.11.3.6 pypi_0 pypi 179 | nvidia-cuda-cupti-cu11 11.8.87 pypi_0 pypi 180 | nvidia-cuda-nvcc-cu11 11.8.89 pypi_0 pypi 181 | nvidia-cuda-nvrtc-cu11 11.8.89 pypi_0 pypi 182 | nvidia-cuda-runtime-cu11 11.8.89 pypi_0 pypi 183 | nvidia-cudnn-cu11 8.9.6.50 pypi_0 pypi 184 | nvidia-cufft-cu11 10.9.0.58 pypi_0 pypi 185 | nvidia-cusolver-cu11 11.4.1.48 pypi_0 pypi 186 | nvidia-cusparse-cu11 11.7.5.86 pypi_0 pypi 187 | nvidia-nccl-cu11 2.19.3 pypi_0 pypi 188 | openjpeg 2.5.0 h488ebb8_3 conda-forge 189 | openpyxl 3.1.2 py39hd1e30aa_1 conda-forge 190 | openssl 3.2.0 hd590300_1 conda-forge 191 | opt-einsum 3.3.0 hd8ed1ab_2 conda-forge 192 | opt_einsum 3.3.0 pyhc1e730c_2 conda-forge 193 | optax 0.1.7 pyhd8ed1ab_0 conda-forge 194 | orbax-checkpoint 0.4.3 pyhd8ed1ab_0 conda-forge 195 | ordered-set 4.1.0 pyhd8ed1ab_0 conda-forge 196 | orjson 3.9.10 py39h10b2342_0 conda-forge 197 | packaging 23.2 pyhd8ed1ab_0 conda-forge 198 | pandas 2.1.3 py39hddac248_0 conda-forge 199 | parso 0.8.3 pypi_0 pypi 200 | patsy 0.5.3 pypi_0 pypi 201 | pcre2 10.42 hcad00b1_0 conda-forge 202 | pexpect 4.8.0 pyh1a96a4e_2 conda-forge 203 | pillow 10.1.0 py39had0adad_0 conda-forge 204 | pip 23.3.1 pyhd8ed1ab_0 conda-forge 205 | pkginfo 1.9.6 pyhd8ed1ab_0 conda-forge 206 | platformdirs 3.11.0 pyhd8ed1ab_0 conda-forge 207 | poetry 1.7.1 linux_pyha804496_0 conda-forge 208 | poetry-core 1.8.1 pyhd8ed1ab_0 conda-forge 209 | poetry-plugin-export 1.6.0 pyhd8ed1ab_0 conda-forge 210 | prompt-toolkit 3.0.41 pypi_0 pypi 211 | protobuf 4.24.4 py39h60f6b12_0 conda-forge 212 | psutil 5.9.5 py39hd1e30aa_1 conda-forge 213 | pthread-stubs 0.4 h36c2ea0_1001 conda-forge 214 | ptyprocess 0.7.0 pyhd3deb0d_0 conda-forge 215 | pure-eval 0.2.2 pypi_0 pypi 216 | pybind11-abi 4 hd8ed1ab_3 conda-forge 217 | pycparser 2.21 pyhd8ed1ab_0 conda-forge 218 | pydantic 1.10.13 pypi_0 pypi 219 | pydantic-core 2.3.0 py39h9fdd4d6_0 conda-forge 220 | pygments 2.17.2 pyhd8ed1ab_0 conda-forge 221 | pyjwt 2.8.0 pyhd8ed1ab_0 conda-forge 222 | pynndescent 0.5.11 pypi_0 pypi 223 | pyparsing 3.1.1 pyhd8ed1ab_0 conda-forge 224 | pyproject_hooks 1.0.0 pyhd8ed1ab_0 conda-forge 225 | pyro-api 0.1.2 pyhd8ed1ab_0 conda-forge 226 | pyro-ppl 1.8.6 pyhd8ed1ab_0 conda-forge 227 | pysocks 1.7.1 pyha2e5f31_6 conda-forge 228 | python 3.9.18 h0755675_0_cpython conda-forge 229 | python-build 1.0.3 pyhd8ed1ab_0 conda-forge 230 | python-dateutil 2.8.2 pyhd8ed1ab_0 conda-forge 231 | python-editor 1.0.4 py_0 conda-forge 232 | python-fastjsonschema 2.19.0 pyhd8ed1ab_0 conda-forge 233 | python-installer 0.7.0 pyhd8ed1ab_0 conda-forge 234 | python-multipart 0.0.6 pyhd8ed1ab_0 conda-forge 235 | python-tzdata 2023.3 pyhd8ed1ab_0 conda-forge 236 | python_abi 3.9 4_cp39 conda-forge 237 | pytorch-lightning 2.1.1 pyhd8ed1ab_0 conda-forge 238 | pytz 2023.3.post1 pyhd8ed1ab_0 conda-forge 239 | pyyaml 6.0.1 py39hd1e30aa_1 conda-forge 240 | pyzmq 25.1.1 pypi_0 pypi 241 | rapidfuzz 3.5.2 py39h3d6467e_0 conda-forge 242 | rav1e 0.6.6 he8a937b_2 conda-forge 243 | readchar 4.0.5 pyhd8ed1ab_0 conda-forge 244 | readline 8.2 h8228510_1 conda-forge 245 | requests 2.31.0 pyhd8ed1ab_0 conda-forge 246 | requests-toolbelt 1.0.0 pyhd8ed1ab_0 conda-forge 247 | rich 13.7.0 pyhd8ed1ab_0 conda-forge 248 | s3transfer 0.8.1 pyhd8ed1ab_0 conda-forge 249 | scanpy 1.9.6 pypi_0 pypi 250 | scikit-learn 1.3.2 py39ha22ef79_1 conda-forge 251 | scipy 1.11.4 py39h474f0d3_0 conda-forge 252 | scsemiprofiler 1.0.0 pypi_0 pypi 253 | scvi-tools 1.0.4 pyhd8ed1ab_0 conda-forge 254 | seaborn 0.12.2 pypi_0 pypi 255 | secretstorage 3.3.3 py39hf3d152e_2 conda-forge 256 | session-info 1.0.0 pypi_0 pypi 257 | setuptools 68.2.2 pyhd8ed1ab_0 conda-forge 258 | shellingham 1.5.4 pyhd8ed1ab_0 conda-forge 259 | six 1.16.0 pyh6c4a22f_0 conda-forge 260 | sleef 3.5.1 h9b69904_2 conda-forge 261 | snappy 1.1.10 h9fff704_0 conda-forge 262 | sniffio 1.3.0 pyhd8ed1ab_0 conda-forge 263 | soupsieve 2.5 pyhd8ed1ab_1 conda-forge 264 | sparse 0.14.0 pyhd8ed1ab_0 conda-forge 265 | stack-data 0.6.3 pypi_0 pypi 266 | starlette 0.22.0 pypi_0 pypi 267 | starsessions 1.3.0 pyhd8ed1ab_0 conda-forge 268 | statsmodels 0.14.0 pypi_0 pypi 269 | stdlib-list 0.10.0 pypi_0 pypi 270 | svt-av1 1.7.0 h59595ed_0 conda-forge 271 | sympy 1.12 pypyh9d50eac_103 conda-forge 272 | tensorstore 0.1.50 py39hfddb6fb_0 conda-forge 273 | texttable 1.7.0 pypi_0 pypi 274 | threadpoolctl 3.2.0 pyha21a80b_0 conda-forge 275 | tk 8.6.13 noxft_h4845f30_101 conda-forge 276 | tomli 2.0.1 pyhd8ed1ab_0 conda-forge 277 | tomlkit 0.12.3 pyha770c72_0 conda-forge 278 | toolz 0.12.0 pyhd8ed1ab_0 conda-forge 279 | torch 1.12.1+cu113 pypi_0 pypi 280 | torchaudio 0.12.1+cu113 pypi_0 pypi 281 | torchmetrics 1.2.0 pyhd8ed1ab_0 conda-forge 282 | torchvision 0.13.1+cu113 pypi_0 pypi 283 | tornado 6.4 pypi_0 pypi 284 | tqdm 4.66.1 pyhd8ed1ab_0 conda-forge 285 | traitlets 5.14.0 pyhd8ed1ab_0 conda-forge 286 | trove-classifiers 2023.11.22 pyhd8ed1ab_0 conda-forge 287 | types-python-dateutil 2.8.19.14 pyhd8ed1ab_0 conda-forge 288 | typing-extensions 4.8.0 hd8ed1ab_0 conda-forge 289 | typing_extensions 4.8.0 pyha770c72_0 conda-forge 290 | tzdata 2023c h71feb2d_0 conda-forge 291 | umap-learn 0.5.5 pypi_0 pypi 292 | unicodedata2 15.1.0 py39hd1e30aa_0 conda-forge 293 | urllib3 1.26.18 pyhd8ed1ab_0 conda-forge 294 | uvicorn 0.24.0 py39hf3d152e_0 conda-forge 295 | virtualenv 20.24.7 pyhd8ed1ab_0 conda-forge 296 | wcwidth 0.2.12 pyhd8ed1ab_0 conda-forge 297 | websocket-client 1.6.4 pyhd8ed1ab_0 conda-forge 298 | websockets 11.0.3 pypi_0 pypi 299 | wheel 0.42.0 pyhd8ed1ab_0 conda-forge 300 | xarray 2023.11.0 pyhd8ed1ab_0 conda-forge 301 | xlrd 1.2.0 pyh9f0ad1d_1 conda-forge 302 | xorg-libxau 1.0.11 hd590300_0 conda-forge 303 | xorg-libxdmcp 1.1.3 h7f98852_0 conda-forge 304 | xz 5.2.6 h166bdaf_0 conda-forge 305 | yaml 0.2.5 h7f98852_2 conda-forge 306 | yarl 1.9.3 pypi_0 pypi 307 | zipp 3.17.0 pyhd8ed1ab_0 conda-forge 308 | zstd 1.5.5 hfc55251_0 conda-forge 309 | -------------------------------------------------------------------------------- /example_data/bulkdata.h5ad: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcgilldinglab/scSemiProfiler/5a9c10e3ac06eeec73cb4ddcada495a216f3d849/example_data/bulkdata.h5ad -------------------------------------------------------------------------------- /example_data/scdata.h5ad: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcgilldinglab/scSemiProfiler/5a9c10e3ac06eeec73cb4ddcada495a216f3d849/example_data/scdata.h5ad -------------------------------------------------------------------------------- /inference_example.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcgilldinglab/scSemiProfiler/5a9c10e3ac06eeec73cb4ddcada495a216f3d849/inference_example.jpg -------------------------------------------------------------------------------- /overview.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcgilldinglab/scSemiProfiler/5a9c10e3ac06eeec73cb4ddcada495a216f3d849/overview.jpg -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["flit_core >=3.2,<4"] 3 | build-backend = "flit_core.buildapi" 4 | 5 | [project] 6 | name = "scSemiProfiler" 7 | authors = [{name = "Jingtao Wang", email = "jingtao.wang@mail.mcgill.ca"}] 8 | dynamic = ["version", "description"] 9 | dependencies = [ 10 | 'numpy== 1.26.2', 11 | 'scanpy== 1.9.6', 12 | 'scipy== 1.11.4', 13 | 'anndata== 0.10.3', 14 | 'faiss-cpu== 1.7.4', 15 | 'torch== 1.12.1', 16 | 'scikit-learn== 1.3.2', 17 | 'pandas== 2.1.3', 18 | 'jax== 0.4.19', 19 | 'igraph==0.9.9', 20 | 'gseapy==1.0.4', 21 | 'lightning==2.0.0', 22 | 'lightning-cloud==0.5.55', 23 | 'lightning-utilities==0.10.0', 24 | 'pytorch-lightning==2.1.1', 25 | 'scvi-tools== 1.0.4'] 26 | 27 | [project.optional-dependencies] 28 | doc = [ 29 | #"sphinx==7.1.2", 30 | "sphinx<4", 31 | "sphinx-rtd-theme==1.3.0rc1", 32 | "sphinx-copybutton", 33 | "nbsphinx", 34 | "sphinx-rtd-theme", 35 | "ipython", 36 | "jinja2<3.1", 37 | "prompt-toolkit<3.0.0", 38 | "sphinxcontrib-applehelp==1.0.1" , 39 | #"sphinx_autodoc_typehints" 40 | "sphinx-autodoc-typehints<1.12", 41 | "sphinxcontrib_devhelp==1.0.2", 42 | "sphinxcontrib_htmlhelp==2.0.1", 43 | "sphinxcontrib-jquery==4.1", 44 | "sphinxcontrib-qthelp==1.0.3", 45 | "sphinxcontrib-serializinghtml==1.1.5" 46 | ] 47 | -------------------------------------------------------------------------------- /recon_example.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcgilldinglab/scSemiProfiler/5a9c10e3ac06eeec73cb4ddcada495a216f3d849/recon_example.jpg -------------------------------------------------------------------------------- /scSemiProfiler/.ipynb_checkpoints/__init__-checkpoint.py: -------------------------------------------------------------------------------- 1 | import pdb,sys,os 2 | 3 | __all__=['activeselect','initsetup','scinfer','scprocess'] 4 | dir_path = os.path.dirname(os.path.realpath(__file__)) 5 | sys.path.append(dir_path) 6 | 7 | for i in __all__: 8 | __import__(i) -------------------------------------------------------------------------------- /scSemiProfiler/.ipynb_checkpoints/activeselect-checkpoint.py: -------------------------------------------------------------------------------- 1 | import pdb,sys,os 2 | import anndata 3 | import scanpy as sc 4 | import argparse 5 | import copy 6 | import numpy as np 7 | import faiss 8 | import scipy 9 | 10 | ### evaluation functions 11 | 12 | def faiss_knn(query, x, n_neighbors=1): 13 | n_samples = x.shape[0] 14 | n_features = x.shape[1] 15 | x = np.ascontiguousarray(x) 16 | 17 | index = faiss.IndexFlatL2(n_features) 18 | #index = faiss.IndexFlatIP(n_features) 19 | 20 | index.add(x) 21 | 22 | if n_neighbors < 2: 23 | neighbors = 2 24 | else: 25 | neighbors = n_neighbors 26 | 27 | weights, targets = index.search(query, neighbors) 28 | 29 | #sources = np.repeat(np.arange(n_samples), neighbors) 30 | #targets = targets.flatten() 31 | #weights = weights.flatten() 32 | weights = weights[:,:n_neighbors] 33 | if -1 in targets: 34 | raise InternalError("Not enough neighbors were found. Please consider " 35 | "reducing the number of neighbors.") 36 | return weights 37 | 38 | def pearson_compare(query,x): 39 | return 0 40 | 41 | def cos_compare(query,x): 42 | return 0 43 | 44 | 45 | def pca_compare(query,x): 46 | qx = np.concatenate([query,x],axis=0) 47 | qxpca = PCA(n_components=100) 48 | dx=qxpca.fit_transform(qx) 49 | 50 | newq = dx[:query.shape[0],:].copy(order='C') 51 | newx = dx[query.shape[0]:,:].copy(order='C') 52 | score = faiss_knn(newq,newx,n_neighbors=1) 53 | return score 54 | 55 | def umap_compare(query,x): 56 | qx = np.concatenate([query,x],axis=0) 57 | qxpca = PCA(n_components=100) 58 | dpca=qxpca.fit_transform(qx) 59 | umap_reduc=umap.UMAP(min_dist=0.5,spread=1.0,negative_sample_rate=5 ) 60 | dx = umap_reduc.fit_transform(dpca) 61 | newq = dx[:query.shape[0],:].copy(order='C') 62 | newx = dx[query.shape[0]:,:].copy(order='C') 63 | score = faiss_knn(newq,newx,n_neighbors=1) 64 | return score 65 | 66 | def knncompare(query,x,n_neighbors=1,dist='PCA'): 67 | if dist == 'Euclidean': 68 | score = faiss_knn(query,x,n_neighbors=n_neighbors) 69 | score2 = faiss_knn(x,query,n_neighbors=n_neighbors) 70 | elif dist == 'Pearson': 71 | score = pearson_compare(query,x) 72 | score2 = pearson_compare(x,query) 73 | elif dist == 'cos': 74 | score = cos_compare(query,x) 75 | score2 = cos_compare(x,query) 76 | elif dist == 'PCA': 77 | score = pca_compare(query,x) 78 | score2 = pca_compare(x,query) 79 | elif dist == 'UMAP': 80 | score = umap_compare(query,x) 81 | score2 = umap_compare(x,query) 82 | else: 83 | score = 0 84 | print('distance option not found') 85 | 86 | return (score.mean() + score2.mean())/2 87 | 88 | def normtotal(x,h=1e4): 89 | ratios = h/x.sum(axis=1) 90 | x=(x.T*ratios).T 91 | return x 92 | 93 | ## active learning functions 94 | def pick_batch(reduced_bulk=None,\ 95 | representatives=None,\ 96 | cluster_labels=None,\ 97 | xdimsemis=None,\ 98 | xdimgts=None,\ 99 | discount_rate = 1,\ 100 | semi_dis_rate = 1,\ 101 | batch_size=8\ 102 | ): 103 | # 104 | lhet = [] 105 | lmp = [] 106 | for i in range(len(representatives)): 107 | cluster_heterogeneity,in_cluster_uncertainty,uncertain_patient=compute_cluster_heterogeneity(cluster_number=i,\ 108 | reduced_bulk=reduced_bulk,\ 109 | representatives=init_representatives,\ 110 | cluster_labels=init_cluster_labels,\ 111 | xdimsemis=xdimsemis,\ 112 | xdimgts=xdimgts,\ 113 | discount_rate = 1,\ 114 | semi_dis_rate = 1\ 115 | ) 116 | lhet.append(cluster_heterogeneity) 117 | lmp.append(uncertain_patient) 118 | 119 | 120 | new_representatives = copy.deepcopy(representatives) 121 | for i in range(batch_size): 122 | mp_index = np.array(lhet).argmax() 123 | mp = lmp[mp_index] 124 | 125 | new_representatives.append(mp) 126 | lhet.pop(mp_index) 127 | lmp.pop(mp_index) 128 | 129 | new_cluster_labels= update_membership(reduced_bulk=reduced_bulk,\ 130 | representatives=new_representatives) 131 | 132 | return new_representatives,new_cluster_labels 133 | 134 | def pick_batch_eee(reduced_bulk=None,\ 135 | representatives=None,\ 136 | cluster_labels=None,\ 137 | xdimsemis=None,\ 138 | xdimgts=None,\ 139 | discount_rate = 1,\ 140 | semi_dis_rate = 1,\ 141 | batch_size=8\ 142 | ): 143 | # 144 | lhet = [] 145 | lmp = [] 146 | for i in range(len(representatives)): 147 | cluster_heterogeneity,in_cluster_uncertainty,uncertain_patient=compute_cluster_heterogeneity(cluster_number=i,\ 148 | reduced_bulk=reduced_bulk,\ 149 | representatives=representatives,\ 150 | cluster_labels=cluster_labels,\ 151 | xdimsemis=xdimsemis,\ 152 | xdimgts=xdimgts,\ 153 | discount_rate = 1,\ 154 | semi_dis_rate = 1\ 155 | ) 156 | lhet.append(cluster_heterogeneity) 157 | lmp.append(uncertain_patient) 158 | 159 | new_representatives = copy.deepcopy(representatives) 160 | new_cluster_labels = copy.deepcopy(cluster_labels) 161 | print('heterogeneities: ',lhet) 162 | for i in range(batch_size): 163 | new_num = len(new_representatives) 164 | mp_index = np.array(lhet).argmax() 165 | print(mp_index) 166 | lhet[mp_index] = -999 167 | bestp, new_cluster_labels, hets = best_patient(cluster_labels=new_cluster_labels,representatives=new_representatives,\ 168 | reduced_bulk=reduced_bulk,cluster_num=mp_index,new_num=new_num) 169 | 170 | new_representatives = new_representatives + [bestp] 171 | 172 | return new_representatives,new_cluster_labels 173 | 174 | def best_patient(cluster_labels=None,representatives=None,\ 175 | reduced_bulk=None,cluster_num=0,new_num=None): 176 | if new_num == None: 177 | new_num = len(representatives) 178 | pindices = np.where(np.array(cluster_labels)==cluster_num)[0] 179 | representative = representatives[cluster_num] 180 | hets=[] 181 | potential_new_labels = [] 182 | for i in range(len(pindices)): 183 | potential_new_label = copy.deepcopy(cluster_labels) 184 | newrepre = pindices[i] 185 | het = 0 186 | if newrepre in representatives: 187 | hets.append(9999) 188 | potential_new_labels.append(potential_new_label) 189 | continue 190 | for j in range(len(pindices)): 191 | brepre = reduced_bulk[representative] 192 | brepre2 = reduced_bulk[newrepre] 193 | bj = reduced_bulk[pindices[j]] 194 | bdist1 = (brepre - bj)**2 195 | bdist1 = bdist1.sum() 196 | bdist1 = bdist1**0.5 197 | bdist2 = (brepre2 - bj)**2 198 | bdist2 = bdist2.sum() 199 | bdist2 = bdist2**0.5 200 | 201 | if bdist1 > bdist2: 202 | #print(pindices[j]) 203 | het = het + bdist2 204 | potential_new_label[pindices[j]]=new_num 205 | else: 206 | het = het + bdist1 207 | hets.append(het) 208 | potential_new_labels.append(potential_new_label) 209 | hets = np.array(hets) 210 | bestp = pindices[np.argmin(hets)] 211 | new_cluster_labels = potential_new_labels[np.argmin(hets)] 212 | return bestp, new_cluster_labels, hets 213 | 214 | def update_membership(reduced_bulk=None,\ 215 | representatives=None,\ 216 | 217 | ): 218 | new_cluster_labels = [] 219 | for i in range(len(reduced_bulk)): 220 | 221 | dists=[] 222 | #dist to repres 223 | for j in representatives: 224 | bdist = (reduced_bulk[j] - reduced_bulk[i])**2 225 | bdist = bdist.sum() 226 | bdist = bdist**0.5 227 | dists.append(bdist) 228 | membership = np.array(dists).argmin() 229 | new_cluster_labels.append(membership) 230 | return new_cluster_labels 231 | 232 | def compute_cluster_heterogeneity(cluster_number=0,\ 233 | reduced_bulk=None,\ 234 | representatives=None,\ 235 | cluster_labels=None,\ 236 | xdimsemis=None,\ 237 | xdimgts=None,\ 238 | discount_rate = 1,\ 239 | semi_dis_rate = 1\ 240 | ): 241 | semiflag=0 242 | representative = representatives[cluster_number] 243 | in_cluster_uncertainty = [] 244 | cluster_labels = np.array(cluster_labels) 245 | cluster_patient_indices = np.where(cluster_labels==cluster_number)[0] 246 | 247 | for i in range(len(cluster_patient_indices)): # number of patients in this cluster except the representative 248 | 249 | patient_index = cluster_patient_indices[i] 250 | 251 | if patient_index in representatives: 252 | in_cluster_uncertainty.append(0) 253 | continue 254 | 255 | # distance between this patient and representative 256 | bdist = (reduced_bulk[representative] - reduced_bulk[patient_index])**2 257 | bdist = bdist.sum() 258 | bdist = bdist**0.5 259 | 260 | ma = np.array(xdimsemis[patient_index]).copy(order='C') 261 | mb = np.array(xdimgts[representative]).copy(order='C') 262 | sdist = (faiss_knn(ma,mb,n_neighbors=1).mean()) 263 | 264 | semiloss = np.log(1+gts[patient_index].sum(axis=0))- np.log(1+semis[patient_index].sum(axis=0)) 265 | semiloss = semiloss**2 266 | semiloss = semiloss.sum() 267 | semiloss = semiloss**0.5 268 | 269 | uncertainty = bdist + sdist*discount_rate + semi_dis_rate * semiloss 270 | 271 | in_cluster_uncertainty.append(uncertainty) 272 | 273 | cluster_heterogeneity = np.array(in_cluster_uncertainty).sum() 274 | uncertain_patient = cluster_patient_indices[np.array(in_cluster_uncertainty).argmax()] 275 | 276 | return cluster_heterogeneity,in_cluster_uncertainty,uncertain_patient 277 | 278 | 279 | 280 | def activeselection(representatives,cluster,lambdasc,lambdapb): 281 | 282 | rep = [] 283 | f = open(representatives,'r') 284 | lines = f.readlines() 285 | for l in lines: 286 | rep.append(l) 287 | f.close() 288 | 289 | cl=[] 290 | f = open(cluster,'r') 291 | lines = f.readlines() 292 | for l in lines: 293 | cl.append(l) 294 | f.close() 295 | 296 | bulkdata = anndata.read_h5ad('processed_bulkdata.h5ad') 297 | reduced_bulk = bulkdata.obsm['X_pca'] 298 | 299 | #acquire semi-profiled cohort 300 | 301 | hvgenes = np.load('hvgenes.npy') 302 | 303 | adata = anndata.read_h5ad('sample_sc/' + rep[0] + '.h5ad') 304 | hvmask = [] 305 | for g in adata.var.index: 306 | if g in hvgenes: 307 | hvmask.append(True) 308 | else: 309 | hvmask.append(False) 310 | hvmask = np.array(hvmask) 311 | 312 | xsemi = [] 313 | for i in range(len(sids)): 314 | sid = sids[i] 315 | representative = rep[cl[i]] 316 | xsemi.append(np.load('inferreddata/'+sids[representative]+'to'+sid+'.npy')) 317 | print(i,end=', ') 318 | 319 | 320 | 321 | nrep, nlabels = pick_batch_eee(reduced_bulk = reduced_bulk,\ 322 | representatives = rep,\ 323 | cluster_labels = cl,\ 324 | xdimsemis=xsemi,\ 325 | xdimgts=xsemi,\ 326 | discount_rate = lambdasc,\ 327 | semi_dis_rate = lambdapb,\ 328 | batch_size=4\ 329 | ) 330 | new_representatives = nrep 331 | new_cluster_labels = nlabels 332 | f=open('status/eer_cluster_labels_'+str(rnd+1)+'.txt','w') 333 | for i in range(len(new_cluster_labels)): 334 | f.write(str(new_cluster_labels[i])+'\n') 335 | f.close() 336 | f=open('status/eer_representatives_'+str(rnd+1)+'.txt','w') 337 | for i in range(len(new_representatives)): 338 | f.write(str(new_representatives[i])+'\n') 339 | f.close() 340 | 341 | 342 | return 343 | 344 | 345 | 346 | 347 | def main(): 348 | parser=argparse.ArgumentParser(description="scSemiProfiler initsetup") 349 | parser._action_groups.pop() 350 | required = parser.add_argument_group('required arguments') 351 | optional = parser.add_argument_group('optional arguments') 352 | 353 | required.add_argument('--representatives',required=True,help="A txt file including all the IDs of the representatives used in the current round of semi-profiling.") 354 | 355 | required.add_argument('--cluster',required=True,help="A txt file specifying the cluster membership.") 356 | 357 | optional.add_argument('--lambdasc',required=False,default='1.0', help="Scaling factor for the single-cell transformation difficulty from the representative to the target (Default: 1.0)") 358 | 359 | optional.add_argument('--lambdapb',required=False, default='1.0', help="Scaling factor for the pseudobulk data difference (Default: 1.0)") 360 | 361 | args = parser.parse_args() 362 | representatives = args.representatives 363 | cluster = args.cluster 364 | lambdasc = float(args.lambdasc) 365 | lambdapb = float(args.lambdapb) 366 | activeselection(representatives,cluster,lambdasc,lambdapb) 367 | 368 | if __name__=="__main__": 369 | main() 370 | -------------------------------------------------------------------------------- /scSemiProfiler/.ipynb_checkpoints/fast_functions-checkpoint.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | import os 4 | import timeit 5 | import copy 6 | 7 | import anndata 8 | from anndata import AnnData 9 | import scanpy as sc 10 | from sklearn.neighbors import kneighbors_graph 11 | 12 | from fast_generator_covid import * 13 | 14 | 15 | def fast_cellgraph(adata,k,diagw): 16 | adj = kneighbors_graph(np.array(adata.X), k, mode='connectivity', include_self=True) 17 | adj = adj.toarray() 18 | diag = np.array(np.identity(adj.shape[0]).astype('float32'))*diagw 19 | adj = adj + diag 20 | adj = adj/adj.sum(axis=1) 21 | selfw = np.zeros(adj.shape[0]) 22 | for i in range(adj.shape[0]): 23 | selfw[i] = adj[i,i] 24 | selfw=selfw.astype('float32') 25 | adata.obs['selfw']=selfw 26 | #remove self so that not in neighbors 27 | for i in range(adj.shape[0]): 28 | adj[i,i]=0 29 | adj = torch.from_numpy(adj.astype('float32'))#.type(torch.FloatTensor) 30 | neighboridx = np.where(adj!=0) 31 | xs = neighboridx[0] 32 | ys = neighboridx[1] 33 | 34 | maxn=k 35 | neighbors = np.zeros((adj.shape[0],maxn-1)) - 1 36 | for i in range(len(adata.obs)): 37 | ns=np.zeros(maxn-1)-1 38 | flag=0 39 | j=0 40 | k=0 41 | while flag!=2 and j 0: 166 | X = scdata.X 167 | cutoff = 1e4*threshold 168 | X = X*[X>cutoff] 169 | nscdata = anndata.AnnData(X) 170 | nscdata.obs = scdata.obs 171 | nscdata.var = scdata.var 172 | nscdata.uns = scdata.uns 173 | scdata = nscdata 174 | 175 | 176 | 177 | # store singlecell data, geneset score 178 | if (os.path.isdir('sample_sc')) == False: 179 | os.sys('mkdir sample_sc') 180 | if (os.path.isdir('geneset_scores')) == False: 181 | os.sys('mkdir geneset_scores') 182 | 183 | if geneset != 'none': 184 | prior_name = "c2.cp.v7.4.symbols.gmt" # "c5.go.bp.v7.4.symbols.gmt+c2.cp.v7.4.symbols.gmt+TF-DNA" 185 | 186 | 187 | 188 | print('Computing geneset scores') 189 | zps=[] 190 | for sid in sids: 191 | adata = scdata[scdata.obs['sample_ids'] == 'sid'] 192 | X = adata.X 193 | 194 | gene_sets_path = "genesets/" 195 | expression_only = AnnDataset(data_filepath, label_name=label_name, variable_gene_name=variable_gene_name) 196 | exp_variable_genes = expression_only.exp_variable_genes 197 | variable_genes_names = expression_only.variable_genes_names 198 | genes_upper = expression_only.genes_upper 199 | clusters_true = expression_only.clusters_true 200 | N = expression_only.N 201 | G = expression_only.G 202 | gene_set_matrix, keys_all = getGeneSetMatrix(prior_name, genes_upper, gene_sets_path) 203 | 204 | zp = X.dot(np.array(gene_set_matrix).T) 205 | eps = 1e-6 206 | den = (np.array(gene_set_matrix.sum(axis=1))+eps) 207 | zp = (zp+eps)/den 208 | zp = zp - eps/den 209 | np.save('geneset_scores/'+pid,zp) 210 | zps.append(zp) 211 | 212 | if 'hvset.npy' not in os.listdir(): 213 | zps=np.array(zps) 214 | zdata = anndata.AnnData(zps) 215 | sc.pp.log1p(zdata) 216 | sc.pp.highly_variable_genes(zdata) 217 | hvset = zdata.var.highly_variable 218 | np.save('hvset.npy',hvset) 219 | 220 | 221 | 222 | # select highly variable genes 223 | hvgenes = np.load('hvgenes.npy') 224 | hvmask = [] 225 | for i in scdata.var.index: 226 | if i in hvgenes: 227 | hvmask.append(True) 228 | else: 229 | hvmask.append(False) 230 | hvmask = np.array(hvmask) 231 | scdata = scdata[:,hvmask] 232 | 233 | 234 | 235 | for sid in sids: 236 | adata = scdata[scdata.obs['sample_ids'] == 'sid'] 237 | 238 | #gcn 239 | adata.obs['cellidx']=range(len(adata.obs)) 240 | adata,adj = fast_cellgraph(adata,k,diagw) 241 | 242 | variances = (adata.X.var(dim=0)) 243 | 244 | adata.write('sample_sc/' + sid + '.h5ad') 245 | 246 | print('Finished processing representative single-cell data') 247 | return 248 | 249 | 250 | 251 | 252 | def main(): 253 | parser=argparse.ArgumentParser(description="scSemiProfiler scprocess") 254 | parser._action_groups.pop() 255 | required = parser.add_argument_group('required arguments') 256 | optional = parser.add_argument_group('optional arguments') 257 | 258 | required.add_argument('--singlecell',required=True,help="Input representatives' single-cell data as a h5ad file. Sample IDs should be stored in obs.['sample_ids']. Cell IDs should be stored in obs.index. Gene symbols should be stored in var.index. Values should either be raw read counts or normalized expression.") 259 | 260 | 261 | optional.add_argument('--cellfilter',required=False, default='yes', help="Whether to perform cell filtering: 'yes' or 'no'. (Default: yes)") 262 | optional.add_argument('--threshold',required=False, default='1e-3', help="The threshold for removing extremely low expressed background noise, as a proportion of the library size. (Default: 1e-3)") 263 | optional.add_argument('--geneset',required=False, default='human', help="Specify the gene set file: 'human', 'mouse', 'none', or path to the file (Default: 'human')") 264 | optional.add_argument('--weight',required=False, default=0.5, help="The proportion of top highly variable features to increase importance weight. (Default: 0.5)") 265 | optional.add_argument('--k',required=False, default=15, help="K-nearest cell neighbors used for cell graph convolution. (Default: 15)") 266 | 267 | args = parser.parse_args() 268 | singlecell = args.singlecell 269 | cellfilter = args.cellfilter 270 | threshold = args.threshold 271 | geneset = args.geneset 272 | weight = args.weight 273 | k = args.k 274 | 275 | scprocess(singlecell,cellfilter,threshold,geneset,weight,k) 276 | 277 | if __name__=="__main__": 278 | main() 279 | -------------------------------------------------------------------------------- /scSemiProfiler/__init__.py: -------------------------------------------------------------------------------- 1 | """This is scSemiProfiler, a tool for semi-profiling single-cell sequencing data.""" 2 | 3 | __version__ = '0.1.0' 4 | 5 | import pdb,sys,os 6 | 7 | 8 | from .representative_selection import activeselection 9 | from .get_eg_representatives import get_eg_representatives 10 | from .initial_setup import initsetup 11 | #from .initial_setup import inspect_data 12 | 13 | from .inference import scinfer 14 | from .singlecell_process import scprocess 15 | from .utils import * 16 | 17 | __all__=['fast_generator','activeselect','initsetup','scinfer','scprocess','get_eg_representatives'] 18 | dir_path = os.path.dirname(os.path.realpath(__file__)) 19 | sys.path.append(dir_path) 20 | 21 | #for i in __all__: 22 | # __import__(i) 23 | 24 | -------------------------------------------------------------------------------- /scSemiProfiler/get_eg_representatives.py: -------------------------------------------------------------------------------- 1 | import pdb,sys,os 2 | import argparse 3 | import anndata 4 | import scanpy as sc 5 | import numpy as np 6 | from scipy import sparse 7 | 8 | 9 | 10 | def get_eg_representatives(name:str) -> None: 11 | """ 12 | Used for acquiring representatives' single-cell data in the example. Automatically check the latest representatives and store their single-cell data as /representative_sc.h5ad under the project's directory. 13 | 14 | Parameters 15 | ---------- 16 | name 17 | Project name 18 | 19 | Returns 20 | ------- 21 | None 22 | 23 | Example 24 | ------- 25 | >>> name = 'project_name' 26 | >>> scSemiProfiler.get_eg_representatives(name) 27 | 28 | """ 29 | 30 | 31 | scdata = anndata.read_h5ad('example_data/scdata.h5ad') 32 | sids = [] 33 | f = open(name + '/sids.txt', 'r') 34 | lines = f.readlines() 35 | for l in lines: 36 | sids.append(l.strip()) 37 | f.close() 38 | 39 | # get the latest round 40 | representatives = [] 41 | files = os.listdir(name+'/status/') 42 | rounds = [0] 43 | for file in files: 44 | if 'representative' in file: 45 | f = open(name + '/status/' + file, 'r') 46 | lines = f.readlines() 47 | if len(lines) > len(representatives): 48 | representatives = [] 49 | for l in lines: 50 | representatives.append(int(l.strip())) 51 | f.close() 52 | 53 | rsids=[] 54 | for r in representatives: 55 | sid = sids[r] 56 | rsids.append(sid) 57 | 58 | rmask=[] 59 | for i in range(len(scdata.obs.index)): 60 | sid = scdata.obs['sample_ids'][i] 61 | if sid in rsids: 62 | rmask.append(True) 63 | else: 64 | rmask.append(False) 65 | rmask = np.array(rmask) 66 | 67 | repredata = scdata[rmask,:] 68 | 69 | X = repredata.X 70 | X = np.array(X.todense()) 71 | X = np.exp(X) - 1 72 | X = sparse.csr_matrix(X) 73 | adata = anndata.AnnData(X) 74 | adata.obs = repredata.obs 75 | adata.var = repredata.var 76 | 77 | adata.write(name + '/representative_sc.h5ad') 78 | 79 | print('Obtained single-cell data for representatives.') 80 | 81 | return 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | def main(): 92 | parser = argparse.ArgumentParser(description="scSemiProfiler initsetup") 93 | #parser._action_groups.pop() 94 | parser.add_argument('--name', help='Project name.') 95 | args = parser.parse_args() 96 | #required = parser.add_argument_group('required arguments') 97 | #optional = parser.add_argument_group('optional arguments') 98 | 99 | #required.add_argument('--name',required=True,help="Project name.") 100 | 101 | #optional.add_argument('--na',required=False, default='new_project', help="Pe.") 102 | 103 | name = args.name 104 | 105 | get_eg_representatives(name) 106 | 107 | if __name__=="__main__": 108 | main() 109 | 110 | -------------------------------------------------------------------------------- /scSemiProfiler/initial_setup.py: -------------------------------------------------------------------------------- 1 | import pdb,sys,os 2 | import anndata 3 | import scanpy as sc 4 | import argparse 5 | import copy 6 | import numpy as np 7 | from sklearn.cluster import KMeans 8 | from sklearn.metrics import silhouette_samples, silhouette_score 9 | from typing import Union 10 | 11 | import matplotlib.pyplot as plt 12 | 13 | 14 | 15 | def initsetup(name:str, bulk:str,logged:bool=False,normed:bool = True, geneselection:Union[bool,int]=True,batch:int=4) -> None: 16 | """ 17 | Initial setup of the semi-profiling pipeline, including processing the bulk data, clustering for finding the initial representatives. Bulk data should be provided as an 'h5ad' file. Sample IDs should be stored in adata.obs['sample_ids'] and gene names should be stored in adata.var.index. If not using active learning for iterative representative selection, directly set the batch size to be the total number of representatives desired. 18 | 19 | Parameters 20 | ---------- 21 | name 22 | Project name. 23 | bulk 24 | Path to bulk data as an h5ad file. Sample IDs should be stored in adata.obs['sample_ids'] and gene names should be stored in adata.var.index. 25 | logged 26 | Whether the data has been logged or not 27 | normed 28 | Whether the library size has been normalized or not 29 | geneselection 30 | Either a boolean value indicating whether to perform gene selection using the bulk data or not, or a integer specifying the number of highly variable genes should be selected. 31 | batch 32 | Representative selection batch size. 33 | 34 | Returns 35 | ------- 36 | None 37 | 38 | Example 39 | -------- 40 | >>> import scSemiProfiler 41 | >>> name = 'runexample' 42 | >>> bulk = 'example_data/bulkdata.h5ad' 43 | >>> logged = False 44 | >>> normed = True 45 | >>> geneselection = False 46 | >>> batch = 2 47 | >>> scSemiProfiler.initsetup(name, bulk,logged,normed,geneselection,batch) 48 | 49 | """ 50 | 51 | print('Start initial setup') 52 | 53 | if (os.path.isdir(name)) == False: 54 | os.system('mkdir '+name) 55 | else: 56 | print(name + ' exists. Please choose another name.') 57 | return 58 | 59 | if (os.path.isdir(name+'/figures')) == False: 60 | os.system('mkdir '+name+'/figures') 61 | 62 | bulkdata = anndata.read_h5ad(bulk) 63 | 64 | 65 | if normed == False: 66 | if logged == True: 67 | print('Bad data preprocessing. Please normalize the library size before log-transformation.') 68 | return 69 | sc.pp.normalize_total(bulkdata, target_sum=1e4) 70 | 71 | if logged == False: 72 | sc.pp.log1p(bulkdata) 73 | 74 | # write sample ids 75 | sids = list(bulkdata.obs['sample_ids']) 76 | f = open(name+'/sids.txt','w') 77 | for sid in sids: 78 | f.write(sid+'\n') 79 | f.close() 80 | 81 | 82 | if geneselection == False: 83 | hvgenes = np.array(bulkdata.var.index) 84 | elif geneselection == True: 85 | sc.pp.highly_variable_genes(bulkdata, n_top_genes=6000) 86 | #sc.pp.highly_variable_genes(bulkdata, min_mean=0.0125, max_mean=3, min_disp=0.5) 87 | bulkdata = bulkdata[:, bulkdata.var.highly_variable] 88 | hvgenes = (np.array(bulkdata.var.index))[bulkdata.var.highly_variable] 89 | else: 90 | sc.pp.highly_variable_genes(bulkdata, n_top_genes = int(geneselection)) 91 | #sc.pp.highly_variable_genes(bulkdata, min_mean=0.0125, max_mean=3, min_disp=0.5) 92 | bulkdata = bulkdata[:, bulkdata.var.highly_variable] 93 | hvgenes = (np.array(bulkdata.var.index))[bulkdata.var.highly_variable] 94 | np.save(name+'/hvgenes.npy',hvgenes) 95 | 96 | #dim reduction and clustering 97 | 98 | if bulkdata.X.shape[0]>100: 99 | n_comps = 100 100 | else: 101 | n_comps = bulkdata.X.shape[0]-1 102 | 103 | sc.tl.pca(bulkdata,n_comps=n_comps) 104 | 105 | bulkdata.write(name + '/processed_bulkdata.h5ad') 106 | 107 | #cluster 108 | BATCH_SIZE = batch 109 | kmeans = KMeans(n_clusters=BATCH_SIZE, random_state=1).fit(bulkdata.obsm['X_pca']) 110 | cluster_labels = kmeans.labels_ 111 | #find representatives and cluster labels 112 | pnums = [] 113 | for i in range(len(bulkdata.X)): 114 | pnums.append(i) 115 | pnums=np.array(pnums) 116 | centers=[] 117 | representatives=[] 118 | repredic={} 119 | for i in range(len(np.unique(cluster_labels))): 120 | mask = (cluster_labels==i) 121 | cluster = bulkdata.obsm['X_pca'][mask] 122 | cluster_patients = pnums[mask] 123 | center = cluster.mean(axis=0) 124 | centers.append(center) 125 | # find the closest patient 126 | sqdist = ((cluster - center)**2).sum(axis=1) 127 | cluster_representative = cluster_patients[np.argmin(sqdist)] 128 | representatives.append(cluster_representative) 129 | repredic[i] = cluster_representative 130 | centers = np.array(centers) 131 | #store representatives cluster labels 132 | if (os.path.isdir(name + '/status')) == False: 133 | os.system('mkdir ' + name + '/status') 134 | 135 | 136 | f=open(name + '/status/init_cluster_labels.txt','w') 137 | for i in range(len(cluster_labels)): 138 | f.write(str(cluster_labels[i])+'\n') 139 | f.close() 140 | 141 | f=open(name + '/status/init_representatives.txt','w') 142 | for i in range(len(representatives)): 143 | f.write(str(representatives[i])+'\n') 144 | f.close() 145 | 146 | print('Initial setup finished. Among ' + str(len(sids)) + ' total samples, selected '+str(batch)+' representatives:') 147 | for i in range(batch): 148 | print(sids[representatives[i]]) 149 | 150 | return 151 | 152 | 153 | 154 | 155 | 156 | def main(): 157 | parser=argparse.ArgumentParser(description="scSemiProfiler initsetup") 158 | parser._action_groups.pop() 159 | required = parser.add_argument_group('required arguments') 160 | optional = parser.add_argument_group('optional arguments') 161 | 162 | required.add_argument('--bulk',required=True,help="Input bulk data as a h5ad file. Sample IDs should be stored in obs.['sample_ids']. Gene symbols should be stored in var.index.") 163 | 164 | required.add_argument('--name',required=True, help="Project name.") 165 | 166 | optional.add_argument('--normed',required=False, default='no', help="Whether the library size normalization has already been done (Default: no)") ### 167 | 168 | optional.add_argument('--geneselection',required=False,default='yes', help="Whether to perform highly variable gene selection: 'yes' or 'no'. (Default: yes)") 169 | 170 | optional.add_argument('--batch',required=False, default=4, help="The representative sample batch size (Default: 4)") 171 | 172 | args = parser.parse_args() 173 | bulk = args.bulk 174 | name = args.name 175 | geneselection = args.geneselection 176 | normed = args.normed 177 | batch = int(args.batch) 178 | 179 | initsetup(name,bulk,normed,geneselection,batch) 180 | 181 | if __name__=="__main__": 182 | main() 183 | -------------------------------------------------------------------------------- /scSemiProfiler/representative_selection.py: -------------------------------------------------------------------------------- 1 | import pdb,sys,os 2 | import anndata 3 | import scanpy as sc 4 | import argparse 5 | import copy 6 | import numpy as np 7 | import faiss 8 | import scipy 9 | from sklearn.decomposition import PCA 10 | 11 | ### evaluation functions 12 | 13 | def faiss_knn(query:np.array, x:np.array, n_neighbors:int=1) -> np.array: 14 | 15 | 16 | n_samples = x.shape[0] 17 | n_features = x.shape[1] 18 | x = np.ascontiguousarray(x) 19 | index = faiss.IndexFlatL2(n_features) 20 | index.add(x) 21 | if n_neighbors < 2: 22 | neighbors = 2 23 | else: 24 | neighbors = n_neighbors 25 | weights, targets = index.search(query, neighbors) 26 | weights = weights[:,:n_neighbors] 27 | if -1 in targets: 28 | raise InternalError("Not enough neighbors were found. Please consider " 29 | "reducing the number of neighbors.") 30 | return weights 31 | 32 | 33 | 34 | ## active learning functions 35 | 36 | def pick_batch_eee(reduced_bulk=None,\ 37 | representatives=None,\ 38 | cluster_labels=None,\ 39 | xdim=None,\ 40 | pseudobulk=None,\ 41 | semis=None,\ 42 | discount_rate = 1,\ 43 | semi_dis_rate = 1,\ 44 | batch_size=8\ 45 | ): 46 | # 47 | lhet = [] 48 | lmp = [] 49 | for i in range(len(representatives)): 50 | cluster_heterogeneity,in_cluster_uncertainty,uncertain_patient=compute_cluster_heterogeneity(cluster_number=i,\ 51 | reduced_bulk=reduced_bulk,\ 52 | representatives=representatives,\ 53 | cluster_labels=cluster_labels,\ 54 | xdim=xdim,\ 55 | pseudobulk= pseudobulk,\ 56 | semis=semis,\ 57 | discount_rate = 1,\ 58 | semi_dis_rate = 1\ 59 | ) 60 | lhet.append(cluster_heterogeneity) 61 | lmp.append(uncertain_patient) 62 | 63 | new_representatives = copy.deepcopy(representatives) 64 | new_cluster_labels = copy.deepcopy(cluster_labels) 65 | #print('heterogeneities: ',lhet) 66 | for i in range(batch_size): 67 | new_num = len(new_representatives) 68 | mp_index = np.array(lhet).argmax() 69 | #print(mp_index) 70 | lhet[mp_index] = -999 71 | bestp, new_cluster_labels, hets = best_patient(cluster_labels=new_cluster_labels,representatives=new_representatives,\ 72 | reduced_bulk=reduced_bulk,cluster_num=mp_index,new_num=new_num) 73 | 74 | new_representatives = new_representatives + [bestp] 75 | 76 | return new_representatives,new_cluster_labels 77 | 78 | def best_patient(cluster_labels=None,representatives=None,\ 79 | reduced_bulk=None,cluster_num=0,new_num=None): 80 | if new_num == None: 81 | new_num = len(representatives) 82 | pindices = np.where(np.array(cluster_labels)==cluster_num)[0] 83 | representative = representatives[cluster_num] 84 | hets=[] 85 | potential_new_labels = [] 86 | for i in range(len(pindices)): 87 | potential_new_label = copy.deepcopy(cluster_labels) 88 | newrepre = pindices[i] 89 | het = 0 90 | if newrepre in representatives: 91 | hets.append(9999) 92 | potential_new_labels.append(potential_new_label) 93 | continue 94 | for j in range(len(pindices)): 95 | brepre = reduced_bulk[representative] 96 | brepre2 = reduced_bulk[newrepre] 97 | bj = reduced_bulk[pindices[j]] 98 | bdist1 = (brepre - bj)**2 99 | bdist1 = bdist1.sum() 100 | bdist1 = bdist1**0.5 101 | bdist2 = (brepre2 - bj)**2 102 | bdist2 = bdist2.sum() 103 | bdist2 = bdist2**0.5 104 | 105 | if bdist1 > bdist2: 106 | het = het + bdist2 107 | potential_new_label[pindices[j]]=new_num 108 | else: 109 | het = het + bdist1 110 | hets.append(het) 111 | potential_new_labels.append(potential_new_label) 112 | hets = np.array(hets) 113 | bestp = pindices[np.argmin(hets)] 114 | new_cluster_labels = potential_new_labels[np.argmin(hets)] 115 | return bestp, new_cluster_labels, hets 116 | 117 | def update_membership(reduced_bulk=None,\ 118 | representatives=None,\ 119 | 120 | ): 121 | new_cluster_labels = [] 122 | for i in range(len(reduced_bulk)): 123 | 124 | dists=[] 125 | #dist to repres 126 | for j in representatives: 127 | bdist = (reduced_bulk[j] - reduced_bulk[i])**2 128 | bdist = bdist.sum() 129 | bdist = bdist**0.5 130 | dists.append(bdist) 131 | membership = np.array(dists).argmin() 132 | new_cluster_labels.append(membership) 133 | return new_cluster_labels 134 | 135 | def compute_cluster_heterogeneity(cluster_number=0,\ 136 | reduced_bulk=None,\ 137 | representatives=None,\ 138 | cluster_labels=None,\ 139 | xdim=None,\ 140 | pseudobulk=None,\ 141 | semis=None,\ 142 | discount_rate = 1,\ 143 | semi_dis_rate = 1,\ 144 | ): 145 | semiflag=0 146 | representative = representatives[cluster_number] 147 | in_cluster_uncertainty = [] 148 | cluster_labels = np.array(cluster_labels) 149 | cluster_patient_indices = np.where(cluster_labels==cluster_number)[0] 150 | 151 | for i in range(len(cluster_patient_indices)): # number of patients in this cluster except the representative 152 | 153 | patient_index = cluster_patient_indices[i] 154 | 155 | if patient_index in representatives: 156 | in_cluster_uncertainty.append(0) 157 | continue 158 | 159 | # distance between this patient and representative 160 | bdist = (reduced_bulk[representative] - reduced_bulk[patient_index])**2 161 | bdist = bdist.sum() 162 | bdist = bdist**0.5 163 | 164 | ma = np.array(xdim[patient_index]).copy(order='C') 165 | mb = np.array(xdim[representative]).copy(order='C') 166 | sdist = (faiss_knn(ma,mb,n_neighbors=1).mean()) 167 | 168 | 169 | semiloss = np.log(1+pseudobulk[patient_index]) - np.log(1+semis[patient_index].mean(axis=0)) 170 | semiloss = semiloss**2 171 | semiloss = semiloss.sum() 172 | semiloss = semiloss**0.5 173 | 174 | uncertainty = bdist + sdist*discount_rate + semi_dis_rate * semiloss 175 | 176 | in_cluster_uncertainty.append(uncertainty) 177 | 178 | cluster_heterogeneity = np.array(in_cluster_uncertainty).sum() 179 | uncertain_patient = cluster_patient_indices[np.array(in_cluster_uncertainty).argmax()] 180 | 181 | return cluster_heterogeneity,in_cluster_uncertainty,uncertain_patient 182 | 183 | 184 | 185 | def activeselection(name:str, representatives:str,cluster:str,batch:int,lambdasc:float,lambdapb:float) -> None: 186 | """ 187 | Use active learning to select the next batch of representatives 188 | 189 | Parameters 190 | ---------- 191 | name 192 | Project name. 193 | representatives 194 | Path to a `.txt` file specifying the representatives. 195 | cluster 196 | Path to a `.txt` file specifying the cluster labels. 197 | batch 198 | Representative selection batch size. 199 | lambdasc 200 | Scaling factor for the single-cell transformation difficulty from the representative to the target. 201 | lambdapb 202 | Scaling factor for the pseudobulk data.difference. 203 | 204 | Returns 205 | ------- 206 | None 207 | 208 | Example 209 | ------- 210 | >>> name = 'project_name' 211 | >>> representatives = name + '/status/init_representatives.txt' 212 | >>> cluster = name + '/status/init_cluster_labels.txt' 213 | >>> semidev.activeselection(name, representatives,cluster,batch=2,lambdasc=1,lambdapb=1) 214 | 215 | """ 216 | 217 | 218 | print('Running active learning to select new representatives') 219 | 220 | sids = [] 221 | f = open(name + '/sids.txt', 'r') 222 | lines = f.readlines() 223 | for l in lines: 224 | sids.append(l.strip()) 225 | f.close() 226 | 227 | if representatives[-3:]=='txt': 228 | rep = [] 229 | f = open(representatives,'r') 230 | lines = f.readlines() 231 | for l in lines: 232 | rep.append(int(l.strip())) 233 | f.close() 234 | 235 | if cluster[-3:]=='txt': 236 | cl=[] 237 | f = open(cluster,'r') 238 | lines = f.readlines() 239 | for l in lines: 240 | cl.append(int(l.strip())) 241 | f.close() 242 | 243 | bulkdata = anndata.read_h5ad(name + '/processed_bulkdata.h5ad') 244 | reduced_bulk = bulkdata.obsm['X_pca'] 245 | 246 | #acquire semi-profiled cohort 247 | 248 | hvgenes = np.load(name+'/hvgenes.npy',allow_pickle=True) 249 | 250 | genelen = len(hvgenes) 251 | 252 | 253 | xs = [] 254 | datalen = [] 255 | for i in range(len(sids)): 256 | if i not in rep: 257 | sid = sids[i] 258 | representative = rep[cl[i]] 259 | x = np.load(name + '/inferreddata/'+sids[representative]+'_to_'+sid+'.npy') 260 | xs.append(np.log(x+1)) 261 | datalen.append(x.shape[0]) 262 | else: 263 | sid = sids[i] 264 | adata = anndata.read_h5ad(name + '/sample_sc/' + sid + '.h5ad') 265 | x = np.array(adata.X[:,:genelen]) 266 | xs.append(x) 267 | datalen.append(x.shape[0]) 268 | 269 | xs = np.concatenate(xs, axis=0) 270 | 271 | 272 | pca = PCA(n_components=100) 273 | xpcas = pca.fit_transform(xs) 274 | 275 | xpca = [] 276 | semis = [] 277 | offset = 0 278 | for i in range(len(sids)): 279 | xpca.append(xpcas[offset:offset+datalen[i],:]) 280 | semis.append(xs[offset:offset+datalen[i],:]) 281 | offset = offset + datalen[i] 282 | 283 | bdata = anndata.read_h5ad(name+'/processed_bulkdata.h5ad') 284 | pseudobulk = np.exp(bdata.X) - 1 285 | 286 | nrep, nlabels = pick_batch_eee(reduced_bulk = reduced_bulk,\ 287 | representatives = rep,\ 288 | cluster_labels = cl,\ 289 | xdim=xpca,\ 290 | pseudobulk = pseudobulk,\ 291 | semis=semis,\ 292 | discount_rate = lambdasc,\ 293 | semi_dis_rate = lambdapb,\ 294 | batch_size=batch\ 295 | ) 296 | 297 | new_representatives = nrep 298 | new_cluster_labels = nlabels 299 | 300 | rnd = len(os.listdir(name + '/status'))//2+1 301 | 302 | f=open(name + '/status/eer_cluster_labels_'+str(rnd)+'.txt','w') 303 | for i in range(len(new_cluster_labels)): 304 | f.write(str(new_cluster_labels[i])+'\n') 305 | f.close() 306 | f=open(name + '/status/eer_representatives_'+str(rnd)+'.txt','w') 307 | for i in range(len(new_representatives)): 308 | f.write(str(new_representatives[i])+'\n') 309 | 310 | print('selection finished') 311 | f.close() 312 | 313 | 314 | 315 | def main(): 316 | parser=argparse.ArgumentParser(description="Selecting new representatives using active learning") 317 | parser._action_groups.pop() 318 | required = parser.add_argument_group('required arguments') 319 | optional = parser.add_argument_group('optional arguments') 320 | 321 | required.add_argument('--representatives',required=True,help="A txt file including all the IDs of the representatives used in the current round of semi-profiling.") 322 | 323 | required.add_argument('--cluster',required=True,help="A txt file specifying the cluster membership.") 324 | 325 | required.add_argument('--name',required=True,help="Project name.") 326 | 327 | optional.add_argument('--batch',required=False, default='4', help="The batch size of representative selection (Default: 4)") 328 | 329 | optional.add_argument('--lambdasc',required=False,default='1.0', help="Scaling factor for the single-cell transformation difficulty from the representative to the target (Default: 1.0)") 330 | 331 | optional.add_argument('--lambdapb',required=False, default='1.0', help="Scaling factor for the pseudobulk data difference (Default: 1.0)") 332 | 333 | args = parser.parse_args() 334 | representatives = args.representatives 335 | cluster = args.cluster 336 | name = args.name 337 | batch = int(args.batch) 338 | lambdasc = float(args.lambdasc) 339 | lambdapb = float(args.lambdapb) 340 | activeselection(name, representatives,cluster,batch,lambdasc,lambdapb) 341 | 342 | if __name__=="__main__": 343 | main() 344 | -------------------------------------------------------------------------------- /scSemiProfiler/singlecell_process.py: -------------------------------------------------------------------------------- 1 | import pdb,sys,os 2 | import anndata 3 | import scanpy as sc 4 | import argparse 5 | import copy 6 | import torch 7 | import numpy as np 8 | import gc 9 | import pandas as pd 10 | import timeit 11 | import scipy 12 | import warnings 13 | warnings.filterwarnings('ignore') 14 | import faiss 15 | from sklearn.cluster import KMeans 16 | import sklearn 17 | from scipy import stats 18 | from sklearn.neighbors import kneighbors_graph 19 | from matplotlib.pyplot import figure 20 | 21 | from typing import Tuple,Union 22 | from torch.utils.data import Dataset 23 | 24 | 25 | 26 | def hamster_to_human(hamster_gene_list): 27 | f=open('scSemiProfiler/hamster_to_human_gene.txt','r') 28 | lines = f.readlines() 29 | dic = {} 30 | for l in lines: 31 | l = l.strip().split() 32 | if len(l)==2: 33 | dic[l[0]]=l[1] 34 | human_gene_list = [] 35 | for g in hamster_gene_list: 36 | if g in dic.keys(): 37 | human_gene_list.append(dic[g]) 38 | else: 39 | human_gene_list.append(g) 40 | 41 | return human_gene_list 42 | 43 | def gen_tf_gene_table(genes, tf_list, dTD): 44 | """ 45 | Adapted from: 46 | Author: Jun Ding 47 | Project: SCDIFF2 48 | Ref: Ding, J., Aronow, B. J., Kaminski, N., Kitzmiller, J., Whitsett, J. A., & Bar-Joseph, Z. 49 | (2018). Reconstructing differentiation networks and their regulation from time series 50 | single-cell expression data. Genome research, 28(3), 383-395. 51 | """ 52 | 53 | 54 | gene_names = [g.upper() for g in genes] 55 | TF_names = [g.upper() for g in tf_list] 56 | tf_gene_table = dict.fromkeys(tf_list) 57 | 58 | for i, tf in enumerate(tf_list): 59 | tf_gene_table[tf] = np.zeros(len(gene_names)) 60 | _genes = dTD[tf] 61 | 62 | _existed_targets = list(set(_genes).intersection(gene_names)) 63 | _idx_targets = map(lambda x: gene_names.index(x), _existed_targets) 64 | 65 | for _g in _idx_targets: 66 | tf_gene_table[tf][_g] = 1 67 | 68 | del gene_names 69 | del TF_names 70 | del _genes 71 | del _existed_targets 72 | del _idx_targets 73 | 74 | gc.collect() 75 | 76 | return tf_gene_table 77 | 78 | 79 | 80 | def getGeneSetMatrix(_name, genes_upper, gene_sets_path): 81 | """ 82 | 83 | Adapted from: 84 | Author: Jun Ding 85 | Project: SCDIFF2 86 | Ref: Ding, J., Aronow, B. J., Kaminski, N., Kitzmiller, J., Whitsett, J. A., & Bar-Joseph, Z. 87 | (2018). Reconstructing differentiation networks and their regulation from time series 88 | single-cell expression data. Genome research, 28(3), 383-395. 89 | 90 | """ 91 | if _name[-3:] == 'gmt': 92 | print(f"GMT file {_name} loading ... ") 93 | filename = _name 94 | filepath = os.path.join(gene_sets_path, f"{filename}") 95 | 96 | with open(filepath) as genesets: 97 | pathway2gene = {line.strip().split("\t")[0]: line.strip().split("\t")[2:] 98 | for line in genesets.readlines()} 99 | 100 | print(len(pathway2gene)) 101 | 102 | gs = [] 103 | for k, v in pathway2gene.items(): 104 | gs += v 105 | 106 | print(f"Number of genes in {_name} {len(set(gs).intersection(genes_upper))}") 107 | 108 | pathway_list = pathway2gene.keys() 109 | pathway_gene_table = gen_tf_gene_table(genes_upper, pathway_list, pathway2gene) 110 | gene_set_matrix = np.array(list(pathway_gene_table.values())) 111 | keys = pathway_gene_table.keys() 112 | 113 | del pathway2gene 114 | del gs 115 | del pathway_list 116 | del pathway_gene_table 117 | 118 | gc.collect() 119 | 120 | 121 | elif _name == 'TF-DNA': 122 | 123 | # get TF-DNA dictionary 124 | # TF->DNA 125 | def getdTD(tfDNA): 126 | dTD = {} 127 | with open(tfDNA, 'r') as f: 128 | tfRows = f.readlines() 129 | tfRows = [item.strip().split() for item in tfRows] 130 | for row in tfRows: 131 | itf = row[0].upper() 132 | itarget = row[1].upper() 133 | if itf not in dTD: 134 | dTD[itf] = [itarget] 135 | else: 136 | dTD[itf].append(itarget) 137 | 138 | del tfRows 139 | del itf 140 | del itarget 141 | gc.collect() 142 | 143 | return dTD 144 | 145 | from collections import defaultdict 146 | 147 | def getdDT(dTD): 148 | gene_tf_dict = defaultdict(lambda: []) 149 | for key, val in dTD.items(): 150 | for v in val: 151 | gene_tf_dict[v.upper()] += [key.upper()] 152 | 153 | return gene_tf_dict 154 | 155 | tfDNA_file = os.path.join(gene_sets_path, f"Mouse_TF_targets.txt") 156 | dTD = getdTD(tfDNA_file) 157 | dDT = getdDT(dTD) 158 | 159 | tf_list = list(sorted(dTD.keys())) 160 | tf_list.remove('TF') 161 | 162 | tf_gene_table = gen_tf_gene_table(genes_upper, tf_list, dTD) 163 | gene_set_matrix = np.array(list(tf_gene_table.values())) 164 | keys = tf_gene_table.keys() 165 | 166 | del dTD 167 | del dDT 168 | del tf_list 169 | del tf_gene_table 170 | 171 | gc.collect() 172 | 173 | else: 174 | gene_set_matrix = None 175 | 176 | return gene_set_matrix, keys 177 | 178 | 179 | def fast_cellgraph(adata: anndata.AnnData,k: int = 15,diagw: float=1.0) -> Tuple[anndata.AnnData, np.ndarray]: 180 | """ 181 | Augment an anndata object using a cell neighbor graph. 182 | 183 | Parameters 184 | ---------- 185 | adata 186 | The dataset to be augmented 187 | k 188 | The number of neighbors to consider 189 | diagw 190 | The weight of the original cell when agregating the information 191 | 192 | Returns 193 | ------- 194 | adata 195 | The augmented anndata object. 196 | adj 197 | The adjacency matrix of the cell neighbor graph. 198 | """ 199 | 200 | 201 | adj = kneighbors_graph(np.array(adata.X), k, mode='connectivity', include_self=True) 202 | adj = adj.toarray() 203 | diag = np.array(np.identity(adj.shape[0]).astype('float32'))*diagw 204 | adj = adj + diag 205 | adj = adj/adj.sum(axis=1) 206 | selfw = np.zeros(adj.shape[0]) 207 | for i in range(adj.shape[0]): 208 | selfw[i] = adj[i,i] 209 | selfw=selfw.astype('float32') 210 | adata.obs['selfw']=selfw 211 | #remove self so that not in neighbors 212 | for i in range(adj.shape[0]): 213 | adj[i,i]=0 214 | 215 | adata.obsm['adj'] = adj 216 | adj = torch.from_numpy(adj.astype('float32'))#.type(torch.FloatTensor) 217 | neighboridx = np.where(adj!=0) 218 | xs = neighboridx[0] 219 | ys = neighboridx[1] 220 | 221 | maxn=k 222 | neighbors = np.zeros((adj.shape[0],maxn-1)) - 1 223 | for i in range(len(adata.obs)): 224 | ns=np.zeros(maxn-1)-1 225 | flag=0 226 | j=0 227 | k=0 228 | while flag!=2 and j None: 257 | """ 258 | Process the reprsentatives' single-cell data, including preprocessing and feature augmentations. 259 | 260 | Parameters 261 | ---------- 262 | name 263 | Project name. 264 | singlecell 265 | Path to representatives' single-cell data. 266 | logged 267 | Whether the data has been logged or not 268 | normed 269 | Whether the library size has been normalized or not 270 | cellfilter 271 | Whether to perform standard cell filtering. 272 | threshold 273 | Threshold for background noise removal. 274 | geneset 275 | Whether to use gene set to augment gene expression features or no. 276 | weight 277 | The proportion of top features to increase importance weight. 278 | k 279 | K for the K-NN graph built for cells. 280 | 281 | Returns 282 | ------- 283 | None 284 | 285 | Example 286 | ------- 287 | >>> scSemiProfiler.scprocess(name = 'project_name', singlecell = name+'/representative_sc.h5ad', logged = False, normed = True, cellfilter = False, threshold=1e-3, geneset=True, weight = 0.5, k = 15) 288 | 289 | 290 | """ 291 | 292 | print('Processing representative single-cell data') 293 | 294 | scdata = anndata.read_h5ad(singlecell) 295 | sids = np.unique(scdata.obs['sample_ids']) 296 | 297 | # cell filtering 298 | if cellfilter == True: 299 | print('Filtering cells') 300 | sc.pp.filter_cells(scdata, min_genes=200) 301 | scdata.var['mt'] = scdata.var_names.str.startswith('MT-') # annotate the group of mitochondrial genes as 'mt' 302 | sc.pp.calculate_qc_metrics(scdata, qc_vars=['mt'], percent_top=None, log1p=False, inplace=True) 303 | scdata = scdata[scdata.obs.n_genes_by_counts < 2500, :] 304 | scdata = scdata[scdata.obs.pct_counts_mt < 5, :] 305 | 306 | if logged == True: 307 | print('recovering log-transformed data to count data') 308 | adata = scdata 309 | bdata = anndata.AnnData((np.exp(adata.X)-1)) 310 | bdata.obs = adata.obs 311 | bdata.var = adata.var 312 | bdata.obsm = adata.obsm 313 | bdata.uns = adata.uns 314 | scdata = bdata 315 | 316 | if normed == False: 317 | print('Library size normalization.') 318 | sc.pp.normalize_total(scdata, target_sum=1e4) 319 | 320 | # convert to dense if sparse 321 | if scipy.sparse.issparse(scdata.X): 322 | X = np.array(scdata.X.todense()) 323 | tempdata = anndata.AnnData(X) 324 | tempdata.obs = scdata.obs 325 | tempdata.var = scdata.var 326 | scdata = tempdata 327 | 328 | 329 | # norm remove noise 330 | if float(threshold) > 0: 331 | print('Removing background noise') 332 | X = np.array(scdata.X) 333 | cutoff = 1e4*threshold 334 | X = X * np.array(X>cutoff) 335 | nscdata = anndata.AnnData(X) 336 | nscdata.obs = scdata.obs 337 | nscdata.obsm = scdata.obsm 338 | nscdata.var = scdata.var 339 | nscdata.uns = scdata.uns 340 | scdata = nscdata 341 | 342 | 343 | 344 | # store singlecell data, geneset score 345 | if (os.path.isdir(name + '/sample_sc')) == False: 346 | os.system('mkdir ' + name + '/sample_sc') 347 | 348 | 349 | 350 | 351 | 352 | if geneset != False: 353 | if (os.path.isdir(name + '/geneset_scores')) == False: 354 | os.system('mkdir ' + name + '/geneset_scores') 355 | 356 | prior_name = "c2.cp.v7.4.symbols.gmt" 357 | if (geneset == True) or (geneset == 'human'): 358 | print('Computing human geneset scores') 359 | elif geneset == 'hamster': 360 | print('Computing hamster geneset scores') 361 | zps=[] 362 | for sid in sids: 363 | adata = scdata[scdata.obs['sample_ids'] == sid] 364 | X = adata.X 365 | 366 | gene_sets_path = "genesets/" 367 | genes = list(adata.var.index) 368 | 369 | if geneset == 'hamster': 370 | genes = hamster_to_human(genes) 371 | genes_upper = [g.upper() for g in genes] 372 | N = adata.X.shape[0] 373 | G = len(genes_upper) 374 | gene_set_matrix, keys_all = getGeneSetMatrix(prior_name, genes_upper, gene_sets_path) 375 | 376 | zp = X.dot(np.array(gene_set_matrix).T) 377 | eps = 1e-6 378 | den = (np.array(gene_set_matrix.sum(axis=1))+eps) 379 | zp = (zp+eps)/den 380 | zp = zp - eps/den 381 | np.save(name + '/geneset_scores/' + sid,zp) 382 | zps.append(zp) 383 | 384 | if 'hvset.npy' not in os.listdir(name): 385 | zps=np.concatenate(zps,axis=0) 386 | zdata = anndata.AnnData(zps) 387 | sc.pp.log1p(zdata) 388 | sc.pp.highly_variable_genes(zdata) 389 | hvset = zdata.var.highly_variable 390 | np.save(name + '/hvset.npy',hvset) 391 | 392 | # select highly variable genes (genes in preprocessed bulk data) 393 | hvgenes = np.load(name + '/hvgenes.npy', allow_pickle = True) 394 | 395 | for g in hvgenes: 396 | if g not in scdata.var.index: 397 | print('Error. Bulk data contains genes that are not in single-cell data. Please remove those genes from the bulk data and try again.') 398 | return 399 | 400 | hvmask = [] 401 | for i in scdata.var.index: 402 | if i in hvgenes: 403 | hvmask.append(True) 404 | else: 405 | hvmask.append(False) 406 | hvmask = np.array(hvmask) 407 | scdata = scdata[:,hvmask] 408 | np.save(name + '/hvmask.npy',hvmask) 409 | 410 | 411 | print('Augmenting and saving single-cell data.') 412 | for sid in sids: 413 | adata = scdata[scdata.obs['sample_ids'] == sid] 414 | 415 | # gcn 416 | adata.obs['cellidx']=range(len(adata.obs)) 417 | adata,adj = fast_cellgraph(adata,k=k,diagw=1.0) 418 | 419 | 420 | if geneset == True: 421 | # # importance weight 422 | sample_geneset = np.load(name + '/geneset_scores/'+sid+'.npy') 423 | setmask = np.load(name + '/hvset.npy') 424 | sample_geneset = sample_geneset[:,setmask] 425 | sample_geneset = sample_geneset.astype('float32') 426 | 427 | features = np.concatenate([adata.X,sample_geneset],1) 428 | else: 429 | features = adata.X 430 | 431 | variances = np.var(features,axis=0) 432 | adata.uns['feature_var'] = variances 433 | 434 | adata.write(name + '/sample_sc/' + sid + '.h5ad') 435 | 436 | print('Finished processing representative single-cell data') 437 | return 438 | 439 | 440 | 441 | 442 | def main(): 443 | parser=argparse.ArgumentParser(description="scSemiProfiler scprocess") 444 | parser._action_groups.pop() 445 | required = parser.add_argument_group('required arguments') 446 | optional = parser.add_argument_group('optional arguments') 447 | 448 | required.add_argument('--singlecell',required=True,help="Input representatives' single-cell data as a h5ad file. Sample IDs should be stored in obs.['sample_ids']. Cell IDs should be stored in obs.index. Gene symbols should be stored in var.index. Values should either be raw read counts or normalized expression.") 449 | 450 | required.add_argument('--name',required=True, help="Project name.") 451 | 452 | optional.add_argument('--normed',required=False, default='no', help="Whether the library size normalization has already been done (Default: no)") ### 453 | 454 | 455 | optional.add_argument('--cellfilter',required=False, default='yes', help="Whether to perform cell filtering: 'yes' or 'no'. (Default: yes)") 456 | optional.add_argument('--threshold',required=False, default='1e-3', help="The threshold for removing extremely low expressed background noise, as a proportion of the library size. (Default: 1e-3)") 457 | optional.add_argument('--geneset',required=False, default='human', help="Specify the gene set file: 'human', 'mouse', 'none', or path to the file (Default: 'human')") 458 | optional.add_argument('--weight',required=False, default=0.5, help="The proportion of top highly variable features to increase importance weight. (Default: 0.5)") 459 | optional.add_argument('--k',required=False, default=15, help="K-nearest cell neighbors used for cell graph convolution. (Default: 15)") 460 | 461 | args = parser.parse_args() 462 | singlecell = args.singlecell 463 | normed = args.normed 464 | name = args.name 465 | cellfilter = args.cellfilter 466 | threshold = float(args.threshold) 467 | geneset = args.geneset 468 | weight = args.weight 469 | k = args.k 470 | 471 | scprocess(name,singlecell,normed,cellfilter,threshold,geneset,weight,k) 472 | 473 | if __name__=="__main__": 474 | main() 475 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup( 4 | name="scSemiProfiler", 5 | version="1.0.0", 6 | description='scSemiProfiler package 1.0', 7 | author='Jingtao Wang', 8 | author_email = 'jingtao.wang@mail.mcgill.ca', 9 | url='https://github.com/mcgilldinglab/scSemiProfiler', 10 | entry_points={'console_scripts':['activeselect=scSemiProfiler.representative_selection:main','scprocess=scSemiProfiler.singlecell_process:main','initsetup=scSemiProfiler.initial_setup:main','scinfer=scSemiProfiler.inference:main','get_eg_representatives=scSemiProfiler.get_eg_representatives:main']}, 11 | #packages=['scSemiProfiler'], 12 | packages=find_packages(), 13 | classifiers=[ 14 | 'Programming Language :: Python :: 3.9'], 15 | install_requires=['numpy== 1.26.2', 16 | 'scanpy== 1.9.6', 17 | 'scipy== 1.11.4', 18 | 'anndata== 0.10.3', 19 | 'faiss-cpu== 1.7.4', 20 | 'torch>= 1.12.1', 21 | 'scikit-learn== 1.3.2', 22 | 'pandas== 2.1.3', 23 | 'jax== 0.4.19', 24 | 'jaxlib== 0.4.19', 25 | 'igraph==0.9.9', 26 | 'gseapy==1.0.4' 27 | 'mpmath'==1.3.0, 28 | 'scvi-tools == 1.0.4'], 29 | ) 30 | 31 | 32 | 33 | --------------------------------------------------------------------------------