sctransform/0000755000176200001440000000000014167760262012626 5ustar liggesuserssctransform/NAMESPACE0000644000176200001440000000330114167147332014037 0ustar liggesusers# Generated by roxygen2: do not edit by hand export(correct) export(correct_counts) export(diff_mean_test) export(diff_mean_test_conserved) export(generate) export(get_model_var) export(get_residual_var) export(get_residuals) export(plot_model) export(plot_model_pars) export(smooth_via_pca) export(umify) export(vst) import(Matrix) import(ggplot2) import(reshape2) importFrom(MASS,glm.nb) importFrom(MASS,negative.binomial) importFrom(MASS,theta.ml) importFrom(MASS,theta.mm) importFrom(dplyr,arrange) importFrom(dplyr,case_when) importFrom(dplyr,group_by) importFrom(dplyr,mutate) importFrom(dplyr,n) importFrom(dplyr,pull) importFrom(dplyr,summarise) importFrom(future.apply,future_lapply) importFrom(graphics,abline) importFrom(graphics,par) importFrom(graphics,plot) importFrom(gridExtra,grid.arrange) importFrom(magrittr,"%>%") importFrom(matrixStats,rowMeans2) importFrom(matrixStats,rowSds) importFrom(matrixStats,rowVars) importFrom(methods,as) importFrom(rlang,.data) importFrom(stats,aggregate) importFrom(stats,anova) importFrom(stats,approx) importFrom(stats,approxfun) importFrom(stats,as.formula) importFrom(stats,bw.SJ) importFrom(stats,bw.nrd0) importFrom(stats,density) importFrom(stats,df.residual) importFrom(stats,glm) importFrom(stats,glm.fit) importFrom(stats,ksmooth) importFrom(stats,mad) importFrom(stats,median) importFrom(stats,model.matrix) importFrom(stats,offset) importFrom(stats,p.adjust) importFrom(stats,pchisq) importFrom(stats,pnorm) importFrom(stats,poisson) importFrom(stats,predict) importFrom(stats,t.test) importFrom(stats,var) importFrom(utils,capture.output) importFrom(utils,packageVersion) importFrom(utils,setTxtProgressBar) importFrom(utils,txtProgressBar) useDynLib(sctransform) sctransform/LICENSE0000644000176200001440000010450514167140253013630 0ustar liggesusers GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . sctransform/README.md0000644000176200001440000000577214167142575014121 0ustar liggesusers# sctransform ## R package for normalization and variance stabilization of single-cell RNA-seq data using regularized negative binomial regression The sctransform package was developed by Christoph Hafemeister in [Rahul Satija's lab](https://satijalab.org/) at the New York Genome Center and described in [Hafemeister and Satija, Genome Biology 2019](https://genomebiology.biomedcentral.com/articles/10.1186/s13059-019-1874-1). Recent updates are described in [(Choudhary and Satija, Genome Biology, in press)](https://doi.org/10.1101/2021.07.07.451498). Core functionality of this package has been integrated into [Seurat](https://satijalab.org/seurat/), an R package designed for QC, analysis, and exploration of single cell RNA-seq data. ## Quick start Installation: ```r # Install sctransform from CRAN install.packages("sctransform") # Or the development version from GitHub: # the development version currently support v2 regularization # v2 regularization will be available on CRAN soon # install.packages("remotes") remotes::install_github("satijalab/sctransform", ref="develop") ``` Running sctransform: ```r # Runnning sctransform on a UMI matrix normalized_data <- sctransform::vst(umi_count_matrix)$y # v2 regularization normalized_data <- sctransform::vst(umi_count_matrix, vst.flavor="v2")$y # Runnning sctransform on a Seurat object seurat_object <- Seurat::SCTransform(seurat_object) #v2 regularization seurat_object <- Seurat::SCTransform(seurat_object, vst.flavor="v2") ``` ## Help For usage examples see vignettes in inst/doc or use the built-in help after installation `?sctransform::vst` Available vignettes: - [Variance stabilizing transformation](https://htmlpreview.github.io/?https://github.com/satijalab/sctransform/blob/supp_html/supplement/variance_stabilizing_transformation.html) - [Using sctransform in Seurat](https://htmlpreview.github.io/?https://github.com/satijalab/sctransform/blob/supp_html/supplement/seurat.html) ## Known Issues * `node stack overflow` error when Rfast package is loaded. The Rfast package does not play nicely with the future.apply package. Try to avoid loading the Rfast package. See discussions: https://github.com/RfastOfficial/Rfast/issues/5 https://github.com/satijalab/sctransform/issues/108 Please use [the issue tracker](https://github.com/satijalab/sctransform/issues) if you encounter a problem ## References - Hafemeister, C. & Satija, R. Normalization and variance stabilization of single-cell RNA-seq data using regularized negative binomial regression. Genome Biol 20, 296 (December 23, 2019). [https://doi.org/10.1186/s13059-019-1874-1](https://doi.org/10.1186/s13059-019-1874-1). An early version of this work was used in the paper [Developmental diversification of cortical inhibitory interneurons, Nature 555, 2018](https://github.com/ChristophH/in-lineage). - Choudhary, S. & Satija, R. Comparison and evaluation of statistical error models for scRNA-seq. bioRxiv (2021). [https://doi.org/10.1101/2021.07.07.451498](https://doi.org/10.1101/2021.07.07.451498) sctransform/data/0000755000176200001440000000000014167140301013521 5ustar liggesuserssctransform/data/pbmc.rda0000644000176200001440000022276414167140253015155 0ustar liggesusersBZh91AY&SY|Ш(:@ (PCR :4E(PEU*( hh$P@ P%U(*P(QB*QJ)ZUbE)j@B J(PR $%A $%P ( 9|>uR+1@wz_@jܘ[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+;sidιѼdVY'4R[0-GJX06t|9c&[L"17ձֶ'+1c\ɚ~ۊ~k1Sַ:,S\G¾)bj"/AT+DW4O2K劃R o>!yĎPr,Mg&.t+mG =+pH\~R}vswg1AKjĭ y 0aP# f!5L$̢HDqC9L8,ntA\=|зdQΨQ=O35fHԯcH>$/,~ %_ܦ4QsPXkPc':r٦G'@ieZ+eYP"%%;NƵ;=A&Iý50ylZ*&T xwƤvziL>1,&M181Ɋ2ާ':09J'Soz/Y")Q&LhYezaIжڶSQc%Z-pn?؋bٓ",1#(+O1PO4 QU&u<NyW'GjW?ɠ9IFZ)>] @]0ĈmnLzHl۪~37- `FT?-p:3>9\ 4}:B39WWTc^ؐfFjX;0zr. f`V0՚#gQG|ìƠI̚r7'b1&f&fy5=~TG܈JUۘ ZNE"jk"OSl7>o)ݔa̽:qxanpΛ ݌c^k{ UxC$a4hܥ1{.s_dJ%"8Ӯ`~r I,lj6n ,zqFk`rߚ+ﰦyX+ꞋųcjRXxS &_c9o$c+yT\xduKb͌XI3e+l強Q >64ͿNN NIiZY A`0u16M 0rxXq894vep/˴<=#Y;᭥KV#0uħx†wʹϏ*26.zo5)6e\xOF dزe.؍)';]9a ͂; \[?Ic[$wMw3hwc[\{sctransform/man/0000755000176200001440000000000014167147205013375 5ustar liggesuserssctransform/man/get_residuals.Rd0000644000176200001440000000331514167140254016515 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/utils.R \name{get_residuals} \alias{get_residuals} \title{Return Pearson or deviance residuals of regularized models} \usage{ get_residuals( vst_out, umi, residual_type = "pearson", res_clip_range = c(-sqrt(ncol(umi)), sqrt(ncol(umi))), min_variance = vst_out$arguments$min_variance, cell_attr = vst_out$cell_attr, bin_size = 256, verbosity = vst_out$arguments$verbosity, verbose = NULL, show_progress = NULL ) } \arguments{ \item{vst_out}{The output of a vst run} \item{umi}{The UMI count matrix that will be used} \item{residual_type}{What type of residuals to return; can be 'pearson' or 'deviance'; default is 'pearson'} \item{res_clip_range}{Numeric of length two specifying the min and max values the results will be clipped to; default is c(-sqrt(ncol(umi)), sqrt(ncol(umi)))} \item{min_variance}{Lower bound for the estimated variance for any gene in any cell when calculating pearson residual; default is vst_out$arguments$min_variance} \item{cell_attr}{Data frame of cell meta data} \item{bin_size}{Number of genes to put in each bin (to show progress)} \item{verbosity}{An integer specifying whether to show only messages (1), messages and progress bars (2) or nothing (0) while the function is running; default is 2} \item{verbose}{Deprecated; use verbosity instead} \item{show_progress}{Deprecated; use verbosity instead} } \value{ A matrix of residuals } \description{ Return Pearson or deviance residuals of regularized models } \examples{ \donttest{ vst_out <- vst(pbmc, return_cell_attr = TRUE) pearson_res <- get_residuals(vst_out, pbmc) deviance_res <- get_residuals(vst_out, pbmc, residual_type = 'deviance') } } sctransform/man/diff_mean_test.Rd0000644000176200001440000001034614167140301016625 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/differential_expression.R \name{diff_mean_test} \alias{diff_mean_test} \title{Non-parametric differential expression test for sparse non-negative data} \usage{ diff_mean_test( y, group_labels, compare = "each_vs_rest", R = 99, log2FC_th = log2(1.2), mean_th = 0.05, cells_th = 5, only_pos = FALSE, only_top_n = NULL, mean_type = "geometric", verbosity = 1 ) } \arguments{ \item{y}{A matrix of counts; must be (or inherit from) class dgCMatrix; genes are row, cells are columns} \item{group_labels}{The group labels (e.g. cluster identities); will be converted to factor} \item{compare}{Specifies which groups to compare, see details; default is 'each_vs_rest'} \item{R}{The number of random permutations used to derive the p-values; default is 99} \item{log2FC_th}{Threshold to remove genes from testing; absolute log2FC must be at least this large for a gene to be tested; default is \code{log2(1.2)}} \item{mean_th}{Threshold to remove genes from testing; gene mean must be at least this large for a gene to be tested; default is 0.05} \item{cells_th}{Threshold to remove genes from testing; gene must be detected (non-zero count) in at least this many cells in the group with higher mean; default is 5} \item{only_pos}{Test only genes with positive fold change (mean in group 1 > mean in group2); default is FALSE} \item{only_top_n}{Test only the this number of genes from both ends of the log2FC spectrum after all of the above filters have been applied; useful to get only the top markers; only used if set to a numeric value; default is NULL} \item{mean_type}{Which type of mean to use; if \code{'geometric'} (default) the geometric mean is used; to avoid \code{log(0)} we use \code{log1p} to add 1 to all counts and log-transform, calculate the arithmetic mean, and then back-transform and subtract 1 using \code{exp1m}; if this parameter is set to \code{'arithmetic'} the data is used as is} \item{verbosity}{Integer controlling how many messages the function prints; 0 is silent, 1 (default) is not} } \value{ Data frame of results } \description{ Non-parametric differential expression test for sparse non-negative data } \section{Details}{ This model-free test is applied to each gene (row) individually but is optimized to make use of the efficient sparse data representation of the input. A permutation null distribution us used to assess the significance of the observed difference in mean between two groups. The observed difference in mean is compared against a distribution obtained by random shuffling of the group labels. For each gene every random permutation yields a difference in mean and from the population of these background differences we estimate a mean and standard deviation for the null distribution. This mean and standard deviation are used to turn the observed difference in mean into a z-score and then into a p-value. Finally, all p-values (for the tested genes) are adjusted using the Benjamini & Hochberg method (fdr). The log2FC values in the output are \code{log2(mean1 / mean2)}. Empirical p-values are also calculated: \code{emp_pval = (b + 1) / (R + 1)} where b is the number of times the absolute difference in mean from a random permutation is at least as large as the absolute value of the observed difference in mean, R is the number of random permutations. This is an upper bound of the real empirical p-value that would be obtained by enumerating all possible group label permutations. There are multiple ways the group comparisons can be specified based on the compare parameter. The default, \code{'each_vs_rest'}, does multiple comparisons, one per group vs all remaining cells. \code{'all_vs_all'}, also does multiple comparisons, covering all groups pairs. If compare is set to a length two character vector, e.g. \code{c('T-cells', 'B-cells')}, one comparison between those two groups is done. To put multiple groups on either side of a single comparison, use a list of length two. E.g. \code{compare = list(c('cluster1', 'cluster5'), c('cluster3'))}. } \examples{ \donttest{ clustering <- 1:ncol(pbmc) \%\% 2 vst_out <- vst(pbmc, return_corrected_umi = TRUE) de_res <- diff_mean_test(y = vst_out$umi_corrected, group_labels = clustering) } } sctransform/man/robust_scale.Rd0000644000176200001440000000044714167140254016353 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/utils.R \name{robust_scale} \alias{robust_scale} \title{Robust scale using median and mad} \usage{ robust_scale(x) } \arguments{ \item{x}{Numeric} } \value{ Numeric } \description{ Robust scale using median and mad } sctransform/man/vst.Rd0000644000176200001440000002230614167147205014503 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/vst.R \name{vst} \alias{vst} \title{Variance stabilizing transformation for UMI count data} \usage{ vst( umi, cell_attr = NULL, latent_var = c("log_umi"), batch_var = NULL, latent_var_nonreg = NULL, n_genes = 2000, n_cells = NULL, method = "poisson", do_regularize = TRUE, theta_regularization = "od_factor", res_clip_range = c(-sqrt(ncol(umi)), sqrt(ncol(umi))), bin_size = 500, min_cells = 5, residual_type = "pearson", return_cell_attr = FALSE, return_gene_attr = TRUE, return_corrected_umi = FALSE, min_variance = -Inf, bw_adjust = 3, gmean_eps = 1, theta_estimation_fun = "theta.ml", theta_given = NULL, exclude_poisson = FALSE, use_geometric_mean = TRUE, use_geometric_mean_offset = FALSE, fix_intercept = FALSE, fix_slope = FALSE, scale_factor = NA, vst.flavor = NULL, verbosity = 2, verbose = NULL, show_progress = NULL ) } \arguments{ \item{umi}{A matrix of UMI counts with genes as rows and cells as columns} \item{cell_attr}{A data frame containing the dependent variables; if omitted a data frame with umi and gene will be generated} \item{latent_var}{The independent variables to regress out as a character vector; must match column names in cell_attr; default is c("log_umi")} \item{batch_var}{The dependent variables indicating which batch a cell belongs to; no batch interaction terms used if omiited} \item{latent_var_nonreg}{The non-regularized dependent variables to regress out as a character vector; must match column names in cell_attr; default is NULL} \item{n_genes}{Number of genes to use when estimating parameters (default uses 2000 genes, set to NULL to use all genes)} \item{n_cells}{Number of cells to use when estimating parameters (default uses all cells)} \item{method}{Method to use for initial parameter estimation; one of 'poisson', 'qpoisson', 'nb_fast', 'nb', 'nb_theta_given', 'glmGamPoi', 'offset', 'offset_shared_theta_estimate', 'glmGamPoi_offset'; default is 'poisson'} \item{do_regularize}{Boolean that, if set to FALSE, will bypass parameter regularization and use all genes in first step (ignoring n_genes); default is FALSE} \item{theta_regularization}{Method to use to regularize theta; use 'log_theta' for the behavior prior to version 0.3; default is 'od_factor'} \item{res_clip_range}{Numeric of length two specifying the min and max values the results will be clipped to; default is c(-sqrt(ncol(umi)), sqrt(ncol(umi)))} \item{bin_size}{Number of genes to process simultaneously; this will determine how often the progress bars are updated and how much memory is being used; default is 500} \item{min_cells}{Only use genes that have been detected in at least this many cells; default is 5} \item{residual_type}{What type of residuals to return; can be 'pearson', 'deviance', or 'none'; default is 'pearson'} \item{return_cell_attr}{Make cell attributes part of the output; default is FALSE} \item{return_gene_attr}{Calculate gene attributes and make part of output; default is TRUE} \item{return_corrected_umi}{If set to TRUE output will contain corrected UMI matrix; see \code{correct} function} \item{min_variance}{Lower bound for the estimated variance for any gene in any cell when calculating pearson residual; one of 'umi_median', 'model_median', 'model_mean' or a numeric. default is -Inf. When set to 'umi_median' uses (median of non-zero UMIs / 5)^2 as the minimum variance so that a median UMI (often 1) results in a maximum pearson residual of 5. When set to 'model_median' or 'model_mean' uses the mean/median of the model estimated mu per gene as the minimum_variance.#'} \item{bw_adjust}{Kernel bandwidth adjustment factor used during regurlarization; factor will be applied to output of bw.SJ; default is 3} \item{gmean_eps}{Small value added when calculating geometric mean of a gene to avoid log(0); default is 1} \item{theta_estimation_fun}{Character string indicating which method to use to estimate theta (when method = poisson); default is 'theta.ml', but 'theta.mm' seems to be a good and fast alternative} \item{theta_given}{If method is set to nb_theta_given, this should be a named numeric vector of fixed theta values for the genes; if method is offset, this should be a single value; default is NULL} \item{exclude_poisson}{Exclude poisson genes (i.e. mu < 0.001 or mu > variance) from regularization; default is FALSE} \item{use_geometric_mean}{Use geometric mean instead of arithmetic mean for all calculations ; default is TRUE} \item{use_geometric_mean_offset}{Use geometric mean instead of arithmetic mean in the offset model; default is FALSE} \item{fix_intercept}{Fix intercept as defined in the offset model; default is FALSE} \item{fix_slope}{Fix slope to log(10) (equivalent to using library size as an offset); default is FALSE} \item{scale_factor}{Replace all values of UMI in the regression model by this value instead of the median UMI; default is NA} \item{vst.flavor}{When set to `v2` sets method = glmGamPoi_offset, n_cells=2000, and exclude_poisson = TRUE which causes the model to learn theta and intercept only besides excluding poisson genes from learning and regularization; default is NULL which uses the original sctransform model} \item{verbosity}{An integer specifying whether to show only messages (1), messages and progress bars (2) or nothing (0) while the function is running; default is 2} \item{verbose}{Deprecated; use verbosity instead} \item{show_progress}{Deprecated; use verbosity instead} } \value{ A list with components \item{y}{Matrix of transformed data, i.e. Pearson residuals, or deviance residuals; empty if \code{residual_type = 'none'}} \item{umi_corrected}{Matrix of corrected UMI counts (optional)} \item{model_str}{Character representation of the model formula} \item{model_pars}{Matrix of estimated model parameters per gene (theta and regression coefficients)} \item{model_pars_outliers}{Vector indicating whether a gene was considered to be an outlier} \item{model_pars_fit}{Matrix of fitted / regularized model parameters} \item{model_str_nonreg}{Character representation of model for non-regularized variables} \item{model_pars_nonreg}{Model parameters for non-regularized variables} \item{genes_log_gmean_step1}{log-geometric mean of genes used in initial step of parameter estimation} \item{cells_step1}{Cells used in initial step of parameter estimation} \item{arguments}{List of function call arguments} \item{cell_attr}{Data frame of cell meta data (optional)} \item{gene_attr}{Data frame with gene attributes such as mean, detection rate, etc. (optional)} \item{times}{Time stamps at various points in the function} } \description{ Apply variance stabilizing transformation to UMI count data using a regularized Negative Binomial regression model. This will remove unwanted effects from UMI data and return Pearson residuals. Uses future_lapply; you can set the number of cores it will use to n with plan(strategy = "multicore", workers = n). If n_genes is set, only a (somewhat-random) subset of genes is used for estimating the initial model parameters. For details see \doi{10.1186/s13059-019-1874-1}. } \section{Details}{ In the first step of the algorithm, per-gene glm model parameters are learned. This step can be done on a subset of genes and/or cells to speed things up. If \code{method} is set to 'poisson', a poisson regression is done and the negative binomial theta parameter is estimated using the response residuals in \code{theta_estimation_fun}. If \code{method} is set to 'qpoisson', coefficients and overdispersion (phi) are estimated by quasi poisson regression and theta is estimated based on phi and the mean fitted value - this is currently the fastest method with results very similar to 'glmGamPoi' If \code{method} is set to 'nb_fast', coefficients and theta are estimated as in the 'poisson' method, but coefficients are then re-estimated using a proper negative binomial model in a second call to glm with \code{family = MASS::negative.binomial(theta = theta)}. If \code{method} is set to 'nb', coefficients and theta are estimated by a single call to \code{MASS::glm.nb}. If \code{method} is set to 'glmGamPoi', coefficients and theta are estimated by a single call to \code{glmGamPoi::glm_gp}. A special case is \code{method = 'offset'}. Here no regression parameters are learned, but instead an offset model is assumed. The latent variable is set to log_umi and a fixed slope of log(10) is used (offset). The intercept is given by log(gene_mean) - log(avg_cell_umi). See Lause et al. \doi{10.1186/s13059-021-02451-7} for details. Theta is set to 100 by default, but can be changed using the \code{theta_given} parameter (single numeric value). If the offset method is used, the following parameters are overwritten: \code{cell_attr <- NULL, latent_var <- c('log_umi'), batch_var <- NULL, latent_var_nonreg <- NULL, n_genes <- NULL, n_cells <- NULL, do_regularize <- FALSE}. Further, \code{method = 'offset_shared_theta_estimate'} exists where the 250 most highly expressed genes with detection rate of at least 0.5 are used to estimate a theta that is then shared across all genes. Thetas are estimated per individual gene using 5000 randomly selected cells. The final theta used for all genes is then the average. } \examples{ \donttest{ vst_out <- vst(pbmc) } } sctransform/man/get_nz_median.Rd0000644000176200001440000000113314167140301016453 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/utils.R \name{get_nz_median} \alias{get_nz_median} \title{Get median of non zero UMIs from a count matrix using a subset of genes (slow)} \usage{ get_nz_median(umi, genes = NULL) } \arguments{ \item{umi}{Count matrix} \item{genes}{List of genes to calculate statistics. Default is NULL which returns the non-zero median using all genes} } \value{ A numeric value representing the median of non-zero entries from the UMI matrix } \description{ Get median of non zero UMIs from a count matrix using a subset of genes (slow) } sctransform/man/get_nz_median2.Rd0000644000176200001440000000063214167140301016540 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/utils.R \name{get_nz_median2} \alias{get_nz_median2} \title{Get median of non zero UMIs from a count matrix} \usage{ get_nz_median2(umi) } \arguments{ \item{umi}{Count matrix} } \value{ A numeric value representing the median of non-zero entries from the UMI matrix } \description{ Get median of non zero UMIs from a count matrix } sctransform/man/smooth_via_pca.Rd0000644000176200001440000000175314167140254016662 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/denoise.R \name{smooth_via_pca} \alias{smooth_via_pca} \title{Smooth data by PCA} \usage{ smooth_via_pca( x, elbow_th = 0.025, dims_use = NULL, max_pc = 100, do_plot = FALSE, scale. = FALSE ) } \arguments{ \item{x}{A data matrix with genes as rows and cells as columns} \item{elbow_th}{The fraction of PC sdev drop that is considered significant; low values will lead to more PCs being used} \item{dims_use}{Directly specify PCs to use, e.g. 1:10} \item{max_pc}{Maximum number of PCs computed} \item{do_plot}{Plot PC sdev and sdev drop} \item{scale.}{Boolean indicating whether genes should be divided by standard deviation after centering and prior to PCA} } \value{ Smoothed data } \description{ Perform PCA, identify significant dimensions, and reverse the rotation using only significant dimensions. } \examples{ \donttest{ vst_out <- vst(pbmc) y_smooth <- smooth_via_pca(vst_out$y, do_plot = TRUE) } } sctransform/man/correct_counts.Rd0000644000176200001440000000263314167140301016712 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/denoise.R \name{correct_counts} \alias{correct_counts} \title{Correct data by setting all latent factors to their median values and reversing the regression model} \usage{ correct_counts( x, umi, cell_attr = x$cell_attr, scale_factor = NA, verbosity = 2, verbose = NULL, show_progress = NULL ) } \arguments{ \item{x}{A list that provides model parameters and optionally meta data; use output of vst function} \item{umi}{The count matrix} \item{cell_attr}{Provide cell meta data holding latent data info} \item{scale_factor}{Replace all values of UMI in the regression model by this value. Default is NA which uses median of total UMI as the latent factor.} \item{verbosity}{An integer specifying whether to show only messages (1), messages and progress bars (2) or nothing (0) while the function is running; default is 2} \item{verbose}{Deprecated; use verbosity instead} \item{show_progress}{Deprecated; use verbosity instead} } \value{ Corrected data as UMI counts } \description{ This version does not need a matrix of Pearson residuals. It takes the count matrix as input and calculates the residuals on the fly. The corrected UMI counts will be rounded to the nearest integer and negative values clipped to 0. } \examples{ \donttest{ vst_out <- vst(pbmc, return_cell_attr = TRUE) umi_corrected <- correct_counts(vst_out, pbmc) } } sctransform/man/diff_mean_test_conserved.Rd0000644000176200001440000000562114167140301020675 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/differential_expression.R \name{diff_mean_test_conserved} \alias{diff_mean_test_conserved} \title{Find differentially expressed genes that are conserved across samples} \usage{ diff_mean_test_conserved( y, group_labels, sample_labels, balanced = TRUE, compare = "each_vs_rest", pval_th = 1e-04, ... ) } \arguments{ \item{y}{A matrix of counts; must be (or inherit from) class dgCMatrix; genes are rows, cells are columns} \item{group_labels}{The group labels (i.e. clusters or time points); will be converted to factor} \item{sample_labels}{The sample labels; will be converted to factor} \item{balanced}{Boolean, see details for explanation; default is TRUE} \item{compare}{Specifies which groups to compare, see details; currently only 'each_vs_rest' (the default) is supported} \item{pval_th}{P-value threshold used to call a gene differentially expressed when summarizing the tests per gene} \item{...}{Parameters passed to diff_mean_test} } \value{ Data frame of results } \description{ Find differentially expressed genes that are conserved across samples } \section{Details}{ This function calls diff_mean_test repeatedly and aggregates the results per group and gene. If balanced is TRUE (the default), it is assumed that each sample spans multiple groups, as would be the case when merging or integrating samples from the same tissue followed by clustering. Here the group labels would be the clusters and cluster markers would have support in each sample. If balanced is FALSE, an unbalanced design is assumed where each sample contributes to one group. An example is a time series experiment where some samples are taken from time point 1 while other samples are taken from time point 2. The time point would be the group label and the goal would be to identify differentially expressed genes between time points that are supported by many between-sample comparisons. Output columns: \describe{ \item{group1}{Group label of the frist group of cells} \item{group2}{Group label of the second group of cells; currently fixed to 'rest'} \item{gene}{Gene name (from rownames of input matrix)} \item{n_tests}{The number of tests this gene participated in for this group} \item{log2FC_min,median,max}{Summary statistics for log2FC across the tests} \item{mean1,2_median}{Median of group mean across the tests} \item{pval_max}{Maximum of p-values across tests} \item{de_tests}{Number of tests that showed this gene having a log2FC going in the same direction as log2FC_median and having a p-value <= pval_th} } The output is ordered by group1, -de_tests, -abs(log2FC_median), pval_max } \examples{ \donttest{ clustering <- 1:ncol(pbmc) \%\% 2 sample_id <- 1:ncol(pbmc) \%\% 3 vst_out <- vst(pbmc, return_corrected_umi = TRUE) de_res <- diff_mean_test_conserved(y = vst_out$umi_corrected, group_labels = clustering, sample_labels = sample_id) } } sctransform/man/generate.Rd0000644000176200001440000000207314167140254015455 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/generate.R \name{generate} \alias{generate} \title{Generate data from regularized models.} \usage{ generate( vst_out, genes = rownames(vst_out$model_pars_fit), cell_attr = vst_out$cell_attr, n_cells = nrow(cell_attr) ) } \arguments{ \item{vst_out}{A list that provides model parameters and optionally meta data; use output of vst function} \item{genes}{The gene names for which to generate data; default is rownames(vst_out$model_pars_fit)} \item{cell_attr}{Provide cell meta data holding latent data info; default is vst_out$cell_attr} \item{n_cells}{Number of cells to generate; default is nrow(cell_attr)} } \value{ Generated data as dgCMatrix } \description{ Generate data from regularized models. This generates data from the background, i.e. no residuals are added to the simulated data. The cell attributes for the generated cells are sampled from the input with replacement. } \examples{ \donttest{ vst_out <- vst(pbmc, return_cell_attr = TRUE) generated_data <- generate(vst_out) } } sctransform/man/row_var.Rd0000644000176200001440000000044214167140254015340 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/utils.R \name{row_var} \alias{row_var} \title{Variance per row} \usage{ row_var(x) } \arguments{ \item{x}{matrix of class \code{matrix} or \code{dgCMatrix}} } \value{ variances } \description{ Variance per row } sctransform/man/row_gmean.Rd0000644000176200001440000000060614167140254015641 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/utils.R \name{row_gmean} \alias{row_gmean} \title{Geometric mean per row} \usage{ row_gmean(x, eps = 1) } \arguments{ \item{x}{matrix of class \code{matrix} or \code{dgCMatrix}} \item{eps}{small value to add to x to avoid log(0); default is 1} } \value{ geometric means } \description{ Geometric mean per row } sctransform/man/pbmc.Rd0000644000176200001440000000113414167140254014601 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/data.R \docType{data} \name{pbmc} \alias{pbmc} \title{Peripheral Blood Mononuclear Cells (PBMCs)} \format{ A sparse matrix (dgCMatrix, see Matrix package) of molecule counts. There are 914 rows (genes) and 283 columns (cells). This is a downsampled version of a 3K PBMC dataset available from 10x Genomics. } \source{ \url{https://support.10xgenomics.com/single-cell-gene-expression/datasets/1.1.0/pbmc3k} } \usage{ pbmc } \description{ UMI counts for a subset of cells freely available from 10X Genomics } \keyword{datasets} sctransform/man/is_outlier.Rd0000644000176200001440000000054314167140254016041 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/utils.R \name{is_outlier} \alias{is_outlier} \title{Identify outliers} \usage{ is_outlier(y, x, th = 10) } \arguments{ \item{y}{Dependent variable} \item{x}{Independent variable} \item{th}{Outlier score threshold} } \value{ Boolean vector } \description{ Identify outliers } sctransform/man/plot_model.Rd0000644000176200001440000000300114167140254016011 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plotting.R \name{plot_model} \alias{plot_model} \title{Plot observed UMI counts and model} \usage{ plot_model( x, umi, goi, x_var = x$arguments$latent_var[1], cell_attr = x$cell_attr, do_log = TRUE, show_fit = TRUE, show_nr = FALSE, plot_residual = FALSE, batches = NULL, as_poisson = FALSE, arrange_vertical = TRUE, show_density = FALSE, gg_cmds = NULL ) } \arguments{ \item{x}{The output of a vst run} \item{umi}{UMI count matrix} \item{goi}{Vector of genes to plot} \item{x_var}{Cell attribute to use on x axis; will be taken from x$arguments$latent_var[1] by default} \item{cell_attr}{Cell attributes data frame; will be taken from x$cell_attr by default} \item{do_log}{Log10 transform the UMI counts in plot} \item{show_fit}{Show the model fit} \item{show_nr}{Show the non-regularized model (if available)} \item{plot_residual}{Add panels for the Pearson residuals} \item{batches}{Manually specify a batch variable to break up the model plot in segments} \item{as_poisson}{Fix model parameter theta to Inf, effectively showing a Poisson model} \item{arrange_vertical}{Stack individual ggplot objects or place side by side} \item{show_density}{Draw 2D density lines over points} \item{gg_cmds}{Additional ggplot layer commands} } \value{ A ggplot object } \description{ Plot observed UMI counts and model } \examples{ \donttest{ vst_out <- vst(pbmc, return_cell_attr = TRUE) plot_model(vst_out, pbmc, 'EMC4') } } sctransform/man/correct.Rd0000644000176200001440000000313514167140301015315 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/denoise.R \name{correct} \alias{correct} \title{Correct data by setting all latent factors to their median values and reversing the regression model} \usage{ correct( x, data = "y", cell_attr = x$cell_attr, as_is = FALSE, do_round = TRUE, do_pos = TRUE, scale_factor = NA, verbosity = 2, verbose = NULL, show_progress = NULL ) } \arguments{ \item{x}{A list that provides model parameters and optionally meta data; use output of vst function} \item{data}{The name of the entry in x that holds the data} \item{cell_attr}{Provide cell meta data holding latent data info} \item{as_is}{Use cell attributes as is and do not use the median; set to TRUE if you want to manually control the values of the latent factors; default is FALSE} \item{do_round}{Round the result to integers} \item{do_pos}{Set negative values in the result to zero} \item{scale_factor}{Replace all values of UMI in the regression model by this value. Default is NA which uses median of total UMI as the latent factor.} \item{verbosity}{An integer specifying whether to show only messages (1), messages and progress bars (2) or nothing (0) while the function is running; default is 2} \item{verbose}{Deprecated; use verbosity instead} \item{show_progress}{Deprecated; use verbosity instead} } \value{ Corrected data as UMI counts } \description{ Correct data by setting all latent factors to their median values and reversing the regression model } \examples{ \donttest{ vst_out <- vst(pbmc, return_cell_attr = TRUE) umi_corrected <- correct(vst_out) } } sctransform/man/plot_model_pars.Rd0000644000176200001440000000213214167140301017033 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plotting.R \name{plot_model_pars} \alias{plot_model_pars} \title{Plot estimated and fitted model parameters} \usage{ plot_model_pars( vst_out, xaxis = "gmean", show_theta = FALSE, show_var = FALSE, verbosity = 2, verbose = NULL, show_progress = NULL ) } \arguments{ \item{vst_out}{The output of a vst run} \item{xaxis}{Variable to plot on X axis; default is "gmean"} \item{show_theta}{Whether to show the theta parameter; default is FALSE (only the overdispersion factor is shown)} \item{show_var}{Whether to show the average model variance; default is FALSE} \item{verbosity}{An integer specifying whether to show only messages (1), messages and progress bars (2) or nothing (0) while the function is running; default is 2} \item{verbose}{Deprecated; use verbosity instead} \item{show_progress}{Deprecated; use verbosity instead} } \value{ A ggplot object } \description{ Plot estimated and fitted model parameters } \examples{ \donttest{ vst_out <- vst(pbmc, return_gene_attr = TRUE) plot_model_pars(vst_out) } } sctransform/man/compare_expression.Rd0000644000176200001440000000347114167140254017573 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/differential_expression.R \name{compare_expression} \alias{compare_expression} \title{Compare gene expression between two groups} \usage{ compare_expression( x, umi, group, val1, val2, method = "LRT", bin_size = 256, cell_attr = x$cell_attr, y = x$y, min_cells = 5, weighted = TRUE, randomize = FALSE, verbosity = 2, verbose = NULL, show_progress = NULL ) } \arguments{ \item{x}{A list that provides model parameters and optionally meta data; use output of vst function} \item{umi}{A matrix of UMI counts with genes as rows and cells as columns} \item{group}{A vector indicating the groups} \item{val1}{A vector indicating the values of the group vector to treat as group 1} \item{val2}{A vector indicating the values of the group vector to treat as group 2} \item{method}{Either 'LRT' for likelihood ratio test, or 't_test' for t-test} \item{bin_size}{Number of genes that are processed between updates of progress bar} \item{cell_attr}{Data frame of cell meta data} \item{y}{Only used if methtod = 't_test', this is the residual matrix; default is x$y} \item{min_cells}{A gene has to be detected in at least this many cells in at least one of the groups being compared to be tested} \item{weighted}{Balance the groups by using the appropriate weights} \item{randomize}{Boolean indicating whether to shuffle group labels - only set to TRUE when testing methods} \item{verbosity}{An integer specifying whether to show only messages (1), messages and progress bars (2) or nothing (0) while the function is running; default is 2} \item{verbose}{Deprecated; use verbosity instead} \item{show_progress}{Deprecated; use verbosity instead} } \value{ Data frame of results } \description{ Compare gene expression between two groups } sctransform/man/umify.Rd0000644000176200001440000000235214167140301015005 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/umify.R \name{umify} \alias{umify} \title{Quantile normalization of cell-level data to match typical UMI count data} \usage{ umify(counts) } \arguments{ \item{counts}{A matrix of class dgCMatrix with genes as rows and columns as cells} } \value{ A UMI-fied count matrix } \description{ Quantile normalization of cell-level data to match typical UMI count data } \section{Details}{ sctransform::vst operates under the assumption that gene counts approximately follow a Negative Binomial dristribution. For UMI-based data that seems to be the case, however, non-UMI data does not behave in the same way. In some cases it might be better to to apply a transformation to such data to make it look like UMI data. This function applies such a transformation function. Cells in the input matrix are processed independently. For each cell the non-zero data is transformed to quantile values. Based on the number of genes detected a smooth function is used to predict the UMI-like counts. The functions have be trained on various public data sets and come as part of the package (see umify_data data set in this package). } \examples{ \donttest{ silly_example <- umify(pbmc) } } sctransform/man/get_model_var.Rd0000644000176200001440000000221514167140254016470 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/utils.R \name{get_model_var} \alias{get_model_var} \title{Return average variance under negative binomial model} \usage{ get_model_var( vst_out, cell_attr = vst_out$cell_attr, use_nonreg = FALSE, bin_size = 256, verbosity = 2, verbose = NULL, show_progress = NULL ) } \arguments{ \item{vst_out}{The output of a vst run} \item{cell_attr}{Data frame of cell meta data} \item{use_nonreg}{Use the non-regularized parameter estimates; boolean; default is FALSE} \item{bin_size}{Number of genes to put in each bin (to show progress)} \item{verbosity}{An integer specifying whether to show only messages (1), messages and progress bars (2) or nothing (0) while the function is running; default is 2} \item{verbose}{Deprecated; use verbosity instead} \item{show_progress}{Deprecated; use verbosity instead} } \value{ A named vector of variances (the average across all cells), one entry per gene. } \description{ This is based on the formula var = mu + mu^2 / theta } \examples{ \donttest{ vst_out <- vst(pbmc, return_cell_attr = TRUE) res_var <- get_model_var(vst_out) } } sctransform/man/umify_data.Rd0000644000176200001440000000111414167140301015771 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/data.R \docType{data} \name{umify_data} \alias{umify_data} \title{Transformation functions for umify} \format{ A list of length two. The first element is a data frame with group, quantile and log-counts values. The second element is a vector of breaks to be used with cut to group observations. } \usage{ umify_data } \description{ The functions have been trained on various public data sets and relate quantile values to log-counts. Here the expected values at various points are given. } \keyword{datasets} sctransform/man/get_residual_var.Rd0000644000176200001440000000330514167140254017201 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/utils.R \name{get_residual_var} \alias{get_residual_var} \title{Return variance of residuals of regularized models} \usage{ get_residual_var( vst_out, umi, residual_type = "pearson", res_clip_range = c(-sqrt(ncol(umi)), sqrt(ncol(umi))), min_variance = vst_out$arguments$min_variance, cell_attr = vst_out$cell_attr, bin_size = 256, verbosity = vst_out$arguments$verbosity, verbose = NULL, show_progress = NULL ) } \arguments{ \item{vst_out}{The output of a vst run} \item{umi}{The UMI count matrix that will be used} \item{residual_type}{What type of residuals to return; can be 'pearson' or 'deviance'; default is 'pearson'} \item{res_clip_range}{Numeric of length two specifying the min and max values the residuals will be clipped to; default is c(-sqrt(ncol(umi)), sqrt(ncol(umi)))} \item{min_variance}{Lower bound for the estimated variance for any gene in any cell when calculating pearson residual; default is vst_out$arguments$min_variance} \item{cell_attr}{Data frame of cell meta data} \item{bin_size}{Number of genes to put in each bin (to show progress)} \item{verbosity}{An integer specifying whether to show only messages (1), messages and progress bars (2) or nothing (0) while the function is running; default is 2} \item{verbose}{Deprecated; use verbosity instead} \item{show_progress}{Deprecated; use verbosity instead} } \value{ A vector of residual variances (after clipping) } \description{ This never creates the full residual matrix and can be used to determine highly variable genes. } \examples{ \donttest{ vst_out <- vst(pbmc, return_cell_attr = TRUE) res_var <- get_residual_var(vst_out, pbmc) } } sctransform/man/robust_scale_binned.Rd0000644000176200001440000000067014167140254017670 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/utils.R \name{robust_scale_binned} \alias{robust_scale_binned} \title{Robust scale using median and mad per bin} \usage{ robust_scale_binned(y, x, breaks) } \arguments{ \item{y}{Numeric vector} \item{x}{Numeric vector} \item{breaks}{Numeric vector of breaks} } \value{ Numeric vector of scaled score } \description{ Robust scale using median and mad per bin } sctransform/DESCRIPTION0000644000176200001440000000362614167760262014343 0ustar liggesusersPackage: sctransform Type: Package Title: Variance Stabilizing Transformations for Single Cell UMI Data Version: 0.3.3 Date: 2022-01-10 Authors@R: c( person(given = "Christoph", family = "Hafemeister", email = "christoph.hafemeister@nyu.edu", role = "aut", comment = c(ORCID = "0000-0001-6365-8254")), person(given = "Saket", family = "Choudhary", email = "schoudhary@nygenome.org", role = c("aut", "cre"), comment = c(ORCID = "0000-0001-5202-7633")), person(given = "Rahul", family = "Satija", email = "rsatija@nygenome.org", role = "ctb", comment = c(ORCID = "0000-0001-9448-8833")) ) Description: A normalization method for single-cell UMI count data using a variance stabilizing transformation. The transformation is based on a negative binomial regression model with regularized parameters. As part of the same regression framework, this package also provides functions for batch correction, and data correction. See Hafemeister and Satija (2019) , and Choudhary and Satija (2021) for more details. URL: https://github.com/satijalab/sctransform BugReports: https://github.com/satijalab/sctransform/issues License: GPL-3 | file LICENSE Encoding: UTF-8 LazyData: true Depends: R (>= 3.5.0) LinkingTo: RcppArmadillo, Rcpp (>= 0.11.0) SystemRequirements: C++11 Imports: dplyr, magrittr, MASS, Matrix, methods, future.apply, future, ggplot2, reshape2, rlang, gridExtra, matrixStats Suggests: irlba, testthat, knitr Enhances: glmGamPoi RoxygenNote: 7.1.2 NeedsCompilation: yes Packaged: 2022-01-11 01:13:27 UTC; choudharys Author: Christoph Hafemeister [aut] (), Saket Choudhary [aut, cre] (), Rahul Satija [ctb] () Maintainer: Saket Choudhary Repository: CRAN Date/Publication: 2022-01-13 08:20:02 UTC sctransform/build/0000755000176200001440000000000014167154667013733 5ustar liggesuserssctransform/build/partial.rdb0000644000176200001440000002352314167154667016065 0ustar liggesusers}kǕf4K@J4rK HYEfV7 BY3Hٹe=yifo7"ym%骨'9q;R4P@a+go(mf8n58Նn=lŲ=E}ZRiÀۍ 6%q˗\'v댍`w1!aꌤJ~B, ޸~qPM5j$xRzJf`?fq+/uk߬y/浫j/+&blM-n̛Gͩj0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Š='M\H'cw6tAod%HE`B控P:mP>fcp\DfGɎӦ "0[vTGg7I~mŞ}P:)eQt}[xYjSÃ(=nKVUڭ^P=NO ׃^YGz8O_Koa΄;A̰OzWJ9!]1FƙI h,%Y[\"w,jNv(k~UOF:2IJ8]mٖ+mW +nZIz13 s{Q_}Ò{ ?X)97X iXk/PP) O>č~8\LrΏJk!=] Jx;"gjWlV+|9qgџ9#df_Suy# T| *0pLRRm=rqq{ThF9ע+'lA⊗nlYbEf"3s\HKOnk%,[gI[+X$-K5T w_WSS!lyWFA~lԁZ&ouqCU1~3)!'h}.~r~I G,M{6O<nEEЈpזTO)4̚"O3~ , CIF_zj<"5bj7u:_ş$u7/v`Sbӱbm H;8iNљ++Zsa3wT^xcϴL1 S=m*wWԾX$@kkU ˸[AͮtOݢ/^ZQ=>3)ۓOIbۡ;Xƕ*K^}!39^KjւoQvs@~PxRqGoKMiid4UNtVXQz~6=yTqaw@I]FuD|STqxK*_B?:e i;OuCAJ!--<&2faÓMI#zV[ݻztj9ڪ6ؼW^ЉB#\ٖGc"ڤ/`9>lE}21|wkt Gj}&^X-v5񁡶Zg#QNaSW{{[PvzUIXoxlv} I?)lU}3T*M-8,M{(#P 8-O6J (XX&ql_OۮڐS F+s)(ˁC7ʭO@}蝇3喪e mA˯b.“Gރԯ{Gq/f9A׻8yE o\8%/KM!5fחZ;CC{еjO+- =v)>#Y'n*)7Һk 3Ij6/^5Ç~{raIC6 aolgXA_(tL/| E6{0N?f5DJB8 z:F f bF(Z=QQvˆi:w;}[5wwK8Bx|[3x~aWEnCyBݜ'G@;|9b&' /1ԿQbˆ$(w%B) /XYzFu~>~7;,‹(9a t-sO"P zOڳ5zBrč2ҿ^ ,!sctransform/tests/0000755000176200001440000000000014167140254013761 5ustar liggesuserssctransform/tests/testthat/0000755000176200001440000000000014167760262015630 5ustar liggesuserssctransform/tests/testthat/test_differential_expression.R0000644000176200001440000000160414167140254023717 0ustar liggesuserscontext("differential expression") # test_that('compare expression runs and returns expected output', { # skip_on_cran() # options(mc.cores = 2) # set.seed(42) # vst_out <- vst(pbmc, return_cell_attr = TRUE) # # create fake clusters # clustering <- 1:ncol(pbmc) %/% 100 # res <- compare_expression(x = vst_out, umi = pbmc, group = clustering, val1 = 0, val2 = 3) # expect_equal(c("AKAP17A", "LRBA", "SEC23A", "RRP8", "TRNT1"), rownames(res)[1:5]) # expect_equal(c(-27.35713, -27.05464, -26.62938, -26.41430, -26.25116), res$log_fc[1:5], tolerance = 1e-05) # res <- compare_expression(x = vst_out, umi = pbmc, group = clustering, val1 = 0, val2 = 3, method = 't_test') # expect_equal(c("TMSB4X", "AKAP17A", "CALM3", "TOMM40", "HSPB11"), rownames(res)[1:5]) # expect_equal(c(-0.6481318, -0.5870122, -0.7482577, -0.5022045, -0.5954648), res$log_fc[1:5], tolerance = 1e-05) # }) sctransform/tests/testthat/test_generate.R0000644000176200001440000000104414167140301020565 0ustar liggesuserscontext("generate function") test_that('generate runs and returns expected output', { skip_on_cran() suppressWarnings(RNGversion(vstr = "3.5.0")) set.seed(42) vst_out <- vst(pbmc, return_cell_attr = TRUE) generated_data <- generate(vst_out) expect_equal(c(0, 0, 0, 8, 1), generated_data['ERP29', 1:5]) genes <- sample(x = rownames(vst_out$model_pars_fit), size = 100) generated_data <- generate(vst_out = vst_out, genes = genes) expect_equal(c(100, 283), dim(generated_data)) expect_equal(genes, rownames(generated_data)) }) sctransform/tests/testthat/test_utils.R0000644000176200001440000000441714167140254020151 0ustar liggesuserscontext("Rcpp utility functions") test_that('row_mean_grouped runs and returns expected output', { skip_on_cran() suppressWarnings(RNGversion(vstr = "3.5.0")) set.seed(42) grouping <- as.factor(sample(c('a','b','c'), size = ncol(pbmc), replace = TRUE)) means <- sctransform:::row_mean_grouped_dgcmatrix(matrix = pbmc, group = grouping, shuffle = FALSE) means_agg <- t(apply(pbmc, 1, function(x) { aggregate(x = x, by = list(group = grouping), FUN = mean)$x })) colnames(means_agg) <- levels(grouping) expect_equal(means, means_agg) gmeans <- sctransform:::row_gmean_grouped_dgcmatrix(matrix = pbmc, group = grouping, eps = 1, shuffle = FALSE) gmeans_agg <- sapply(levels(grouping), function(g) { sctransform:::row_gmean(pbmc[, grouping == g]) }) expect_equal(gmeans, gmeans_agg) # very sparse input matrix mat <- Matrix::rsparsematrix(100, 1000, density = 0.01) grouping <- as.factor(sample(c('a','b','c'), size = ncol(mat), replace = TRUE)) means <- sctransform:::row_mean_grouped_dgcmatrix(matrix = mat, group = grouping, shuffle = FALSE) means_agg <- t(apply(mat, 1, function(x) { aggregate(x = x, by = list(group = grouping), FUN = mean)$x })) colnames(means_agg) <- levels(grouping) expect_equal(means, means_agg) mat[mat < 0] <- 0 means <- sctransform:::row_gmean_grouped_dgcmatrix(matrix = mat, group = grouping, eps = 1, shuffle = FALSE) means_agg <- t(apply(mat, 1, function(x) { aggregate(x = x, by = list(group = grouping), FUN = function(y) { expm1(mean(log1p(y))) })$x })) colnames(means_agg) <- levels(grouping) expect_equal(means, means_agg) }) test_that('row_nonzero_count runs and returns expected output', { skip_on_cran() suppressWarnings(RNGversion(vstr = "3.5.0")) set.seed(42) nzc <- sctransform:::row_nonzero_count_dgcmatrix(pbmc) nzc2 <- Matrix::rowSums(pbmc > 0) expect_equal(nzc, nzc2) grouping <- as.factor(sample(c('a','b','c'), size = ncol(pbmc), replace = TRUE)) nzc <- sctransform:::row_nonzero_count_grouped_dgcmatrix(pbmc, grouping) f2 <- function(mat, grp) { ret <- sapply(levels(grp), function(g) { rowSums(mat[, grp == g, drop = FALSE] > 0) }) colnames(ret) <- levels(grp) ret } nzc2 <- f2(pbmc, grouping) expect_equal(nzc, nzc2) }) sctransform/tests/testthat/test_denoising.R0000644000176200001440000000141314167140254020761 0ustar liggesuserscontext("correcting") test_that('correcting runs and returns expected output', { skip_on_cran() suppressWarnings(RNGversion(vstr = "3.5.0")) set.seed(42) vst_out <- vst(pbmc, return_cell_attr = TRUE, res_clip_range = c(-Inf, Inf)) y_smooth <- smooth_via_pca(vst_out$y, do_plot = FALSE) expect_equal(c(910, 283), dim(y_smooth)) expect_equal(c(0.0868, 0.0380, 0.6062, 0.3123, 0.0101, 0.8751, -0.0557, -0.2222, -0.9911), as.numeric(y_smooth[1:3, 1:3]), tolerance = 1e-3) umi_corrected <- correct(vst_out) expect_equal(c(0, 1, 28, 1, 1, 37, 0, 0, 7), as.numeric(umi_corrected[1:3, 1:3])) umi_corrected <- correct(vst_out, data = y_smooth) expect_equal(c(0, 0, 31, 0, 0, 34, 0, 0, 8), as.numeric(umi_corrected[1:3, 1:3])) }) sctransform/tests/testthat/test_vst.R0000644000176200001440000000637614167140301017624 0ustar liggesuserscontext("vst function") test_that('vst runs and returns expected output', { skip_on_cran() suppressWarnings(RNGversion(vstr = "3.5.0")) set.seed(42) vst_out <- vst(pbmc, return_gene_attr = TRUE, return_cell_attr = TRUE) expect_equal(c(910, 283), dim(vst_out$y)) ga <- vst_out$gene_attr[order(-vst_out$gene_attr$residual_variance), ] expect_equal(c("GNLY", "NKG7", "GZMB", "LYZ", "S100A9"), rownames(ga)[1:5]) expect_equal(c(27.8, 26.9, 18.7, 18.2, 16.8), ga$residual_variance[1:5], tolerance = 1e-01) }) test_that('vst runs with multicore futures', { skip_on_cran() suppressWarnings(RNGversion(vstr = "3.5.0")) set.seed(42) options(future.fork.enable = TRUE) options(future.globals.maxSize = 10 * 1024 ^ 3) future::plan(strategy = 'multicore', workers = 2) vst_out <- vst(pbmc, return_gene_attr = TRUE, return_cell_attr = TRUE) expect_equal(c(910, 283), dim(vst_out$y)) ga <- vst_out$gene_attr[order(-vst_out$gene_attr$residual_variance), ] expect_equal(c("GNLY", "NKG7", "GZMB", "LYZ", "S100A9"), rownames(ga)[1:5]) expect_equal(c(27.8, 26.9, 18.7, 18.2, 16.8), ga$residual_variance[1:5], tolerance = 1e-01) }) test_that('vst with batch variable works', { skip_on_cran() suppressWarnings(RNGversion(vstr = "3.5.0")) set.seed(42) ca <- data.frame(batch = sample(x = c('A', 'B'), size = ncol(pbmc), replace = TRUE)) rownames(ca) <- colnames(pbmc) vst_out <- vst(pbmc, batch_var = 'batch', cell_attr = ca, return_gene_attr = TRUE, return_cell_attr = TRUE) expect_equal(c(910, 283), dim(vst_out$y)) ga <- vst_out$gene_attr[order(-vst_out$gene_attr$residual_variance), ] expect_equal(c("GNLY", "NKG7", "GZMB", "LYZ", "S100A9"), rownames(ga)[1:5]) expect_equal(c(27.11, 26.11, 17.89, 17.66, 16), ga$residual_variance[1:5], tolerance = 1e-01) }) test_that('vst with pre-calculated cell attributes works', { skip_on_cran() suppressWarnings(RNGversion(vstr = "3.5.0")) ca <- data.frame(umi = colSums(pbmc)) set.seed(42) vst_out <- vst(pbmc, cell_attr = ca, latent_var = 'log_umi', return_gene_attr = TRUE, return_cell_attr = TRUE) expect_equal(c(910, 283), dim(vst_out$y)) ga <- vst_out$gene_attr[order(-vst_out$gene_attr$residual_variance), ] expect_equal(c("GNLY", "NKG7", "GZMB", "LYZ", "S100A9"), rownames(ga)[1:5]) expect_equal(c(27.8, 26.9, 18.7, 18.2, 16.8), ga$residual_variance[1:5], tolerance = 1e-01) ca <- data.frame(log_umi = log10(colSums(pbmc))) set.seed(42) vst_out <- vst(pbmc, cell_attr = ca, latent_var = 'umi', return_gene_attr = TRUE, return_cell_attr = TRUE) expect_equal(c(910, 283), dim(vst_out$y)) ga <- vst_out$gene_attr[order(-vst_out$gene_attr$residual_variance), ] expect_equal(c("GNLY", "NKG7", "LYZ", "S100A9", "GZMB"), rownames(ga)[1:5]) expect_equal(c(26.5, 20.5, 19.6, 16.6, 16.5), ga$residual_variance[1:5], tolerance = 1e-01) ca <- data.frame(log_umi = log10(colSums(pbmc))) set.seed(42) vst_out <- vst(pbmc, cell_attr = ca, latent_var = 'log_umi', return_gene_attr = TRUE, return_cell_attr = TRUE) expect_equal(c(910, 283), dim(vst_out$y)) ga <- vst_out$gene_attr[order(-vst_out$gene_attr$residual_variance), ] expect_equal(c("GNLY", "NKG7", "GZMB", "LYZ", "S100A9"), rownames(ga)[1:5]) expect_equal(c(27.8, 26.9, 18.7, 18.2, 16.8), ga$residual_variance[1:5], tolerance = 1e-01) }) sctransform/tests/testthat.R0000644000176200001440000000010214167140254015735 0ustar liggesuserslibrary(testthat) library(sctransform) test_check("sctransform") sctransform/src/0000755000176200001440000000000014167154667013423 5ustar liggesuserssctransform/src/Makevars0000644000176200001440000000010114167140254015072 0ustar liggesusersCXX_STD = CXX11 PKG_LIBS = $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS) sctransform/src/Makevars.win0000644000176200001440000000010114167140254015666 0ustar liggesusersCXX_STD = CXX11 PKG_LIBS = $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS) sctransform/src/utils.cpp0000644000176200001440000002450514167140254015260 0ustar liggesusers// [[Rcpp::depends(RcppArmadillo)]] #include "RcppArmadillo.h" #include "math.h" using namespace Rcpp; // from Rcpp gallery https://gallery.rcpp.org/articles/stl-random-shuffle/ // wrapper around R's RNG such that we get a uniform distribution over // [0,n) as required by the STL algorithm inline int randWrapper(const int n) { return floor(unif_rand()*n); } // [[Rcpp::export]] NumericVector row_mean_dgcmatrix(S4 matrix) { NumericVector x = matrix.slot("x"); IntegerVector i = matrix.slot("i"); IntegerVector dim = matrix.slot("Dim"); int rows = dim[0]; int cols = dim[1]; NumericVector ret(rows, 0.0); int x_length = x.length(); for (int k=0; k(dn[0]); } return ret; } // [[Rcpp::export]] NumericMatrix row_mean_grouped_dgcmatrix(S4 matrix, IntegerVector group, bool shuffle) { NumericVector x = matrix.slot("x"); IntegerVector i = matrix.slot("i"); IntegerVector p = matrix.slot("p"); IntegerVector dim = matrix.slot("Dim"); int rows = dim[0]; int cols = dim[1]; CharacterVector levs = group.attr("levels"); int groups = levs.length(); NumericMatrix ret(rows, groups); IntegerVector groupsize(groups, 0); int x_length = x.length(); if (shuffle) { group = clone(group); std::random_shuffle(group.begin(), group.end(), randWrapper); } int col = 0; for (int k=0; k=p[col]) { ++col; ++groupsize[group[col-1]-1]; } ret(i[k], group[col-1]-1) += x[k]; } while (col < cols) { ++col; ++groupsize[group[col-1]-1]; } for (int j=0; j(dn[0]); } return ret; } // [[Rcpp::export]] NumericVector row_gmean_dgcmatrix(S4 matrix, double eps) { NumericVector x = matrix.slot("x"); IntegerVector i = matrix.slot("i"); IntegerVector dim = matrix.slot("Dim"); int rows = dim[0]; int cols = dim[1]; NumericVector ret(rows, 0.0); IntegerVector nzero(rows, cols); int x_length = x.length(); double log_eps = log(eps); for (int k=0; k(dn[0]); } return ret; } // [[Rcpp::export]] NumericMatrix row_gmean_grouped_dgcmatrix(S4 matrix, IntegerVector group, double eps, bool shuffle) { NumericVector x = matrix.slot("x"); IntegerVector i = matrix.slot("i"); IntegerVector p = matrix.slot("p"); IntegerVector dim = matrix.slot("Dim"); int rows = dim[0]; int cols = dim[1]; CharacterVector levs = group.attr("levels"); int groups = levs.length(); NumericMatrix ret(rows, groups); IntegerVector groupsize(groups, 0); int x_length = x.length(); IntegerMatrix nonzero(rows, groups); double log_eps = log(eps); if (shuffle) { group = clone(group); std::random_shuffle(group.begin(), group.end(), randWrapper); } int col = 0; for (int k=0; k=p[col]) { ++col; ++groupsize[group[col-1]-1]; } ret(i[k], group[col-1]-1) += log(x[k] + eps); ++nonzero(i[k], group[col-1]-1); } while (col < cols) { ++col; ++groupsize[group[col-1]-1]; } for (int j=0; j(dn[0]); } return ret; } // [[Rcpp::export]] IntegerVector row_nonzero_count_dgcmatrix(S4 matrix) { IntegerVector i = matrix.slot("i"); IntegerVector dim = matrix.slot("Dim"); int rows = dim[0]; IntegerVector ret(rows, 0); int i_len = i.length(); for(int k = 0; k < i_len; ++k) { ret[i[k]]++; } List dn = matrix.slot("Dimnames"); if (dn[0] != R_NilValue) { ret.attr("names") = as(dn[0]); } return ret; } // [[Rcpp::export]] IntegerMatrix row_nonzero_count_grouped_dgcmatrix(S4 matrix, IntegerVector group) { IntegerVector p = matrix.slot("p"); IntegerVector i = matrix.slot("i"); int i_length = i.length(); IntegerVector dim = matrix.slot("Dim"); int rows = dim[0]; CharacterVector levs = group.attr("levels"); int groups = levs.length(); IntegerMatrix ret(rows, groups); int col = 0; for (int k=0; k=p[col]) { ++col; } ret(i[k], group[col-1]-1)++; } colnames(ret) = levs; List dn = matrix.slot("Dimnames"); if (dn[0] != R_NilValue) { rownames(ret) = as(dn[0]); } return ret; } // [[Rcpp::export]] NumericVector row_var_dgcmatrix(NumericVector x, IntegerVector i, int rows, int cols) { NumericVector rowmean(rows, 0.0); int x_length = x.length(); for (int k=0; k(x)); arma::uvec::const_iterator it = indices.begin(); arma::uvec::const_iterator it_end = indices.end(); for (; it != it_end; ++it) { if ((*it) < N) { cs += 1; if ((q0i < 3) & (r0 == qidx[q0i])) { res[q0i] = x[*it]; q0i++; } r0++; } else { cs -= 1; if ((q1i < 3) & (r1 == qidx[q1i])) { res[q1i+3] = x[*it]; q1i++; } r1++; } cs_sum += cs; } res[6] = (double) cs_sum / N / N; // add z-score-like score if (res[4] > res[1]) { // second group has higher mean sd0 = res[2] - res[1]; sd1 = res[4] - res[3]; } else { sd0 = res[1] - res[0]; sd1 = res[5] - res[4]; } //res[7] = (res[4] - res[1]) / sqrt(sd0 * sd1); //res[7] = (res[4] - res[1]) / ((sd0 + sd1) / 2); res[7] = (res[4] - res[1]) / sqrt((sd0*sd0 + sd1*sd1) / 2); return res; } // The following function was taken from the Rfast package // with kind permission from the authors. // It has been slightly adopted for our use case here. // [[Rcpp::export]] List qpois_reg(NumericMatrix X, NumericVector Y, const double tol, const int maxiters, const double minphi, const bool returnfit){ const unsigned int n=X.nrow(), pcols=X.ncol(), d=pcols; arma::colvec b_old(d, arma::fill::zeros), b_new(d), L1(d), yhat(n), y(Y.begin(), n, false), m(n), phi(n); arma::vec unique_vals; arma::mat L2, x(X.begin(), n, pcols, false), x_tr(n, pcols); double dif; // Identify the intercept term(s) and initialize the coefficients for(int i=0;itol;){ yhat=x*b_old; m=(exp(yhat)); phi=y-m; L1=x_tr*phi; L2=x.each_col()%m; L2=x_tr*L2; b_new=b_old+solve(L2,L1,arma::solve_opts::fast); dif=sum(abs(b_new-b_old)); b_old=b_new; if(++ij==maxiters) break; } double p=sum(arma::square(phi)/m)/(n-pcols); NumericVector coefs = NumericVector(b_new.begin(), b_new.end()); coefs.names() = colnames(X); List l; l["coefficients"]=coefs; l["phi"]=p; l["theta.guesstimate"]=mean(m)/(std::max(p, minphi)-1); if(returnfit){ l["fitted"]=NumericVector(m.begin(), m.end()); } return l; } sctransform/src/RcppExports.cpp0000644000176200001440000002102314167143520016400 0ustar liggesusers// Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #include #include using namespace Rcpp; #ifdef RCPP_USE_GLOBAL_ROSTREAM Rcpp::Rostream& Rcpp::Rcout = Rcpp::Rcpp_cout_get(); Rcpp::Rostream& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get(); #endif // row_mean_dgcmatrix NumericVector row_mean_dgcmatrix(S4 matrix); RcppExport SEXP _sctransform_row_mean_dgcmatrix(SEXP matrixSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< S4 >::type matrix(matrixSEXP); rcpp_result_gen = Rcpp::wrap(row_mean_dgcmatrix(matrix)); return rcpp_result_gen; END_RCPP } // row_mean_grouped_dgcmatrix NumericMatrix row_mean_grouped_dgcmatrix(S4 matrix, IntegerVector group, bool shuffle); RcppExport SEXP _sctransform_row_mean_grouped_dgcmatrix(SEXP matrixSEXP, SEXP groupSEXP, SEXP shuffleSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< S4 >::type matrix(matrixSEXP); Rcpp::traits::input_parameter< IntegerVector >::type group(groupSEXP); Rcpp::traits::input_parameter< bool >::type shuffle(shuffleSEXP); rcpp_result_gen = Rcpp::wrap(row_mean_grouped_dgcmatrix(matrix, group, shuffle)); return rcpp_result_gen; END_RCPP } // row_gmean_dgcmatrix NumericVector row_gmean_dgcmatrix(S4 matrix, double eps); RcppExport SEXP _sctransform_row_gmean_dgcmatrix(SEXP matrixSEXP, SEXP epsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< S4 >::type matrix(matrixSEXP); Rcpp::traits::input_parameter< double >::type eps(epsSEXP); rcpp_result_gen = Rcpp::wrap(row_gmean_dgcmatrix(matrix, eps)); return rcpp_result_gen; END_RCPP } // row_gmean_grouped_dgcmatrix NumericMatrix row_gmean_grouped_dgcmatrix(S4 matrix, IntegerVector group, double eps, bool shuffle); RcppExport SEXP _sctransform_row_gmean_grouped_dgcmatrix(SEXP matrixSEXP, SEXP groupSEXP, SEXP epsSEXP, SEXP shuffleSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< S4 >::type matrix(matrixSEXP); Rcpp::traits::input_parameter< IntegerVector >::type group(groupSEXP); Rcpp::traits::input_parameter< double >::type eps(epsSEXP); Rcpp::traits::input_parameter< bool >::type shuffle(shuffleSEXP); rcpp_result_gen = Rcpp::wrap(row_gmean_grouped_dgcmatrix(matrix, group, eps, shuffle)); return rcpp_result_gen; END_RCPP } // row_nonzero_count_dgcmatrix IntegerVector row_nonzero_count_dgcmatrix(S4 matrix); RcppExport SEXP _sctransform_row_nonzero_count_dgcmatrix(SEXP matrixSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< S4 >::type matrix(matrixSEXP); rcpp_result_gen = Rcpp::wrap(row_nonzero_count_dgcmatrix(matrix)); return rcpp_result_gen; END_RCPP } // row_nonzero_count_grouped_dgcmatrix IntegerMatrix row_nonzero_count_grouped_dgcmatrix(S4 matrix, IntegerVector group); RcppExport SEXP _sctransform_row_nonzero_count_grouped_dgcmatrix(SEXP matrixSEXP, SEXP groupSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< S4 >::type matrix(matrixSEXP); Rcpp::traits::input_parameter< IntegerVector >::type group(groupSEXP); rcpp_result_gen = Rcpp::wrap(row_nonzero_count_grouped_dgcmatrix(matrix, group)); return rcpp_result_gen; END_RCPP } // row_var_dgcmatrix NumericVector row_var_dgcmatrix(NumericVector x, IntegerVector i, int rows, int cols); RcppExport SEXP _sctransform_row_var_dgcmatrix(SEXP xSEXP, SEXP iSEXP, SEXP rowsSEXP, SEXP colsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< NumericVector >::type x(xSEXP); Rcpp::traits::input_parameter< IntegerVector >::type i(iSEXP); Rcpp::traits::input_parameter< int >::type rows(rowsSEXP); Rcpp::traits::input_parameter< int >::type cols(colsSEXP); rcpp_result_gen = Rcpp::wrap(row_var_dgcmatrix(x, i, rows, cols)); return rcpp_result_gen; END_RCPP } // grouped_mean_diff_per_row NumericVector grouped_mean_diff_per_row(NumericMatrix x, IntegerVector group, bool shuffle); RcppExport SEXP _sctransform_grouped_mean_diff_per_row(SEXP xSEXP, SEXP groupSEXP, SEXP shuffleSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< NumericMatrix >::type x(xSEXP); Rcpp::traits::input_parameter< IntegerVector >::type group(groupSEXP); Rcpp::traits::input_parameter< bool >::type shuffle(shuffleSEXP); rcpp_result_gen = Rcpp::wrap(grouped_mean_diff_per_row(x, group, shuffle)); return rcpp_result_gen; END_RCPP } // mean_boot NumericVector mean_boot(NumericVector x, int N, int S); RcppExport SEXP _sctransform_mean_boot(SEXP xSEXP, SEXP NSEXP, SEXP SSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< NumericVector >::type x(xSEXP); Rcpp::traits::input_parameter< int >::type N(NSEXP); Rcpp::traits::input_parameter< int >::type S(SSEXP); rcpp_result_gen = Rcpp::wrap(mean_boot(x, N, S)); return rcpp_result_gen; END_RCPP } // mean_boot_grouped NumericMatrix mean_boot_grouped(NumericVector x, IntegerVector group, int N, int S); RcppExport SEXP _sctransform_mean_boot_grouped(SEXP xSEXP, SEXP groupSEXP, SEXP NSEXP, SEXP SSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< NumericVector >::type x(xSEXP); Rcpp::traits::input_parameter< IntegerVector >::type group(groupSEXP); Rcpp::traits::input_parameter< int >::type N(NSEXP); Rcpp::traits::input_parameter< int >::type S(SSEXP); rcpp_result_gen = Rcpp::wrap(mean_boot_grouped(x, group, N, S)); return rcpp_result_gen; END_RCPP } // distribution_shift NumericVector distribution_shift(NumericMatrix x); RcppExport SEXP _sctransform_distribution_shift(SEXP xSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< NumericMatrix >::type x(xSEXP); rcpp_result_gen = Rcpp::wrap(distribution_shift(x)); return rcpp_result_gen; END_RCPP } // qpois_reg List qpois_reg(NumericMatrix X, NumericVector Y, const double tol, const int maxiters, const double minphi, const bool returnfit); RcppExport SEXP _sctransform_qpois_reg(SEXP XSEXP, SEXP YSEXP, SEXP tolSEXP, SEXP maxitersSEXP, SEXP minphiSEXP, SEXP returnfitSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< NumericMatrix >::type X(XSEXP); Rcpp::traits::input_parameter< NumericVector >::type Y(YSEXP); Rcpp::traits::input_parameter< const double >::type tol(tolSEXP); Rcpp::traits::input_parameter< const int >::type maxiters(maxitersSEXP); Rcpp::traits::input_parameter< const double >::type minphi(minphiSEXP); Rcpp::traits::input_parameter< const bool >::type returnfit(returnfitSEXP); rcpp_result_gen = Rcpp::wrap(qpois_reg(X, Y, tol, maxiters, minphi, returnfit)); return rcpp_result_gen; END_RCPP } static const R_CallMethodDef CallEntries[] = { {"_sctransform_row_mean_dgcmatrix", (DL_FUNC) &_sctransform_row_mean_dgcmatrix, 1}, {"_sctransform_row_mean_grouped_dgcmatrix", (DL_FUNC) &_sctransform_row_mean_grouped_dgcmatrix, 3}, {"_sctransform_row_gmean_dgcmatrix", (DL_FUNC) &_sctransform_row_gmean_dgcmatrix, 2}, {"_sctransform_row_gmean_grouped_dgcmatrix", (DL_FUNC) &_sctransform_row_gmean_grouped_dgcmatrix, 4}, {"_sctransform_row_nonzero_count_dgcmatrix", (DL_FUNC) &_sctransform_row_nonzero_count_dgcmatrix, 1}, {"_sctransform_row_nonzero_count_grouped_dgcmatrix", (DL_FUNC) &_sctransform_row_nonzero_count_grouped_dgcmatrix, 2}, {"_sctransform_row_var_dgcmatrix", (DL_FUNC) &_sctransform_row_var_dgcmatrix, 4}, {"_sctransform_grouped_mean_diff_per_row", (DL_FUNC) &_sctransform_grouped_mean_diff_per_row, 3}, {"_sctransform_mean_boot", (DL_FUNC) &_sctransform_mean_boot, 3}, {"_sctransform_mean_boot_grouped", (DL_FUNC) &_sctransform_mean_boot_grouped, 4}, {"_sctransform_distribution_shift", (DL_FUNC) &_sctransform_distribution_shift, 1}, {"_sctransform_qpois_reg", (DL_FUNC) &_sctransform_qpois_reg, 6}, {NULL, NULL, 0} }; RcppExport void R_init_sctransform(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); } sctransform/R/0000755000176200001440000000000014167147205013023 5ustar liggesuserssctransform/R/generate.R0000644000176200001440000000341414167140253014736 0ustar liggesusers#' Generate data from regularized models. #' #' Generate data from regularized models. This generates data from the background, #' i.e. no residuals are added to the simulated data. The cell attributes for the #' generated cells are sampled from the input with replacement. #' #' @param vst_out A list that provides model parameters and optionally meta data; use output of vst function #' @param genes The gene names for which to generate data; default is rownames(vst_out$model_pars_fit) #' @param cell_attr Provide cell meta data holding latent data info; default is vst_out$cell_attr #' @param n_cells Number of cells to generate; default is nrow(cell_attr) #' #' @return Generated data as dgCMatrix #' #' @importFrom methods as #' #' @export #' #' @examples #' \donttest{ #' vst_out <- vst(pbmc, return_cell_attr = TRUE) #' generated_data <- generate(vst_out) #' } #' generate <- function(vst_out, genes = rownames(vst_out$model_pars_fit), cell_attr = vst_out$cell_attr, n_cells = nrow(cell_attr)) { genes <- genes[genes %in% rownames(vst_out$model_pars_fit)] # get model parameters mp <- vst_out$model_pars_fit[genes, , drop = FALSE] coefs <- mp[, -1, drop=FALSE] theta <- mp[, 1] # we sample from the original list of cell attributes when we generate data # choose cells here idx <- sample(x = nrow(cell_attr), size = n_cells, replace = TRUE) regressor_data <- cbind(rep(1, length(idx)), cell_attr[idx, colnames(coefs)[-1]]) # calculate expected values mu <- exp(tcrossprod(coefs, regressor_data)) x.sim <- t(sapply(rownames(mu), function(gene) { gene.mu <- mu[gene, ] x <- MASS::rnegbin(n = length(gene.mu), mu = gene.mu, theta = theta[gene]) return(x) })) x.sim <- as(x.sim, Class = 'dgCMatrix') return(x.sim) } sctransform/R/utils.R0000644000176200001440000005056514167140301014307 0ustar liggesusers # Check cell attributes; add missing ones make_cell_attr <- function(umi, cell_attr, latent_var, batch_var, latent_var_nonreg, verbosity) { if (is.null(cell_attr)) { cell_attr <- data.frame(row.names = colnames(umi)) } # Make sure count matrix has row and column names if (is.null(rownames(umi)) || is.null(colnames(umi))) { stop('count matrix must have row and column names') } # Make sure rownames of cell attributes match cell names in count matrix if (!identical(rownames(cell_attr), colnames(umi))) { stop('cell attribute row names must match column names of count matrix') } # Do not allow certain variable names no_good <- c('(Intercept)', 'Intercept') if (any(no_good %in% c(latent_var, batch_var, latent_var_nonreg))) { stop('Do not use the following variable names for a latent variable or batch variable: ', paste(no_good, collapse = ', ')) } # these are the cell attributes that we know how to calculate given the count matrix known_attr <- c('umi', 'gene', 'log_umi', 'log_gene', 'umi_per_gene', 'log_umi_per_gene') # these are the missing cell attributes specified in latent_var missing_attr <- setdiff(c(latent_var, batch_var, latent_var_nonreg), colnames(cell_attr)) if (length(missing_attr) > 0) { if (verbosity > 0) { message('Calculating cell attributes from input UMI matrix: ', paste(missing_attr, collapse = ', ')) } unknown_attr <- setdiff(missing_attr, known_attr) if (length(unknown_attr) > 0) { stop(sprintf('Unknown cell attributes: %s. Check latent_var, batch_var and latent_var_nonreg and make sure the variables are in cell_attr', paste(unknown_attr, collapse = ', '))) } new_attr <- list() if (any(c('umi', 'log_umi', 'umi_per_gene', 'log_umi_per_gene') %in% missing_attr)) { new_attr$umi <- colSums(umi) new_attr$log_umi <- log10(new_attr$umi) } if (any(c('gene', 'log_gene', 'umi_per_gene', 'log_umi_per_gene') %in% missing_attr)) { new_attr$gene <- colSums(umi > 0) new_attr$log_gene <- log10(new_attr$gene) } if (any(c('umi_per_gene', 'log_umi_per_gene') %in% missing_attr)) { new_attr$umi_per_gene <- new_attr$umi / new_attr$gene new_attr$log_umi_per_gene <- log10(new_attr$umi_per_gene) } new_attr <- do.call(cbind, new_attr) cell_attr <- cbind(cell_attr, new_attr[, setdiff(colnames(new_attr), colnames(cell_attr)), drop = FALSE]) } # make sure no NA, NaN, Inf values are in cell attributes - they would cause # problems later on for (ca in c(latent_var, batch_var, latent_var_nonreg)) { ca_values <- cell_attr[, ca] if (any(is.na(ca_values)) || any(is.nan(ca_values)) || any(is.infinite(ca_values))) { stop('cell attribute "', ca, '" contains NA, NaN, or infinite value') } } return(cell_attr) } #' Geometric mean per row #' #' @param x matrix of class \code{matrix} or \code{dgCMatrix} #' @param eps small value to add to x to avoid log(0); default is 1 #' #' @return geometric means row_gmean <- function(x, eps = 1) { if (inherits(x = x, what = 'matrix')) { return(exp(rowMeans(log(x + eps))) - eps) } if (inherits(x = x, what = 'dgCMatrix')) { ret <- row_gmean_dgcmatrix(matrix = x, eps = eps) names(ret) <- rownames(x) return(ret) } stop('matrix x needs to be of class matrix or dgCMatrix') } #' Variance per row #' #' @param x matrix of class \code{matrix} or \code{dgCMatrix} #' #' @return variances #' #' @importFrom matrixStats rowVars row_var <- function(x) { if (inherits(x = x, what = 'matrix')) { ret <- rowVars(x) names(ret) <- rownames(x) return(ret) } if (inherits(x = x, what = 'dgCMatrix')) { ret <- row_var_dgcmatrix(x = x@x, i = x@i, rows = nrow(x), cols = ncol(x)) names(ret) <- rownames(x) return(ret) } stop('matrix x needs to be of class matrix or dgCMatrix') } #' Identify outliers #' #' @param y Dependent variable #' @param x Independent variable #' @param th Outlier score threshold #' #' @return Boolean vector #' #' @importFrom stats aggregate #' is_outlier <- function(y, x, th = 10) { #bin.width <- var(x) * bw.SJ(x) bin.width <- (max(x) - min(x)) * bw.SJ(x) / 2 eps <- .Machine$double.eps * 10 breaks1 <- seq(from = min(x) - eps, to = max(x) + bin.width, by = bin.width) breaks2 <- seq(from = min(x) - eps - bin.width/2, to = max(x) + bin.width, by = bin.width) score1 <- robust_scale_binned(y, x, breaks1) score2 <- robust_scale_binned(y, x, breaks2) return(pmin(abs(score1), abs(score2)) > th) } #' Robust scale using median and mad per bin #' #' @param y Numeric vector #' @param x Numeric vector #' @param breaks Numeric vector of breaks #' #' @return Numeric vector of scaled score #' #' @importFrom stats aggregate #' robust_scale_binned <- function(y, x, breaks) { bins <- cut(x = x, breaks = breaks, ordered_result = TRUE) tmp <- aggregate(x = y, by = list(bin=bins), FUN = robust_scale) score <- rep(0, length(x)) o <- order(bins) if (inherits(x = tmp$x, what = 'list')) { score[o] <- unlist(tmp$x) } else { score[o] <- as.numeric(t(tmp$x)) } return(score) } #' Robust scale using median and mad #' #' @param x Numeric #' #' @return Numeric #' #' @importFrom stats median mad #' robust_scale <- function(x) { return((x - median(x)) / (mad(x) + .Machine$double.eps)) } pearson_residual <- function(y, mu, theta, min_var = -Inf) { model_var <- mu + mu^2 / theta model_var[model_var < min_var] <- min_var return((y - mu) / sqrt(model_var)) } pearson_residual2 <- function(y, mu, theta, min_vars) { model_var <- mu + mu^2 / theta for (row in 1:nrow(model_var)){ var_row <- model_var[row,] min_var <- min_vars[row] var_row[var_row < min_var] <- min_var model_var[row,] <- var_row } return((y - mu) / sqrt(model_var)) } sq_deviance_residual <- function(y, mu, theta, wt=1) { 2 * wt * (y * log(pmax(1, y)/mu) - (y + theta) * log((y + theta)/(mu + theta))) } deviance_residual <- function(y, mu, theta, wt=1) { r <- 2 * wt * (y * log(pmax(1, y)/mu) - (y + theta) * log((y + theta)/(mu + theta))) sqrt(r) * sign(y - mu) } #' Return Pearson or deviance residuals of regularized models #' #' @param vst_out The output of a vst run #' @param umi The UMI count matrix that will be used #' @param residual_type What type of residuals to return; can be 'pearson' or 'deviance'; default is 'pearson' #' @param res_clip_range Numeric of length two specifying the min and max values the results will be clipped to; default is c(-sqrt(ncol(umi)), sqrt(ncol(umi))) #' @param min_variance Lower bound for the estimated variance for any gene in any cell when calculating pearson residual; default is vst_out$arguments$min_variance #' @param cell_attr Data frame of cell meta data #' @param bin_size Number of genes to put in each bin (to show progress) #' @param verbosity An integer specifying whether to show only messages (1), messages and progress bars (2) or nothing (0) while the function is running; default is 2 #' @param verbose Deprecated; use verbosity instead #' @param show_progress Deprecated; use verbosity instead #' #' @return A matrix of residuals #' #' @export #' #' @examples #' \donttest{ #' vst_out <- vst(pbmc, return_cell_attr = TRUE) #' pearson_res <- get_residuals(vst_out, pbmc) #' deviance_res <- get_residuals(vst_out, pbmc, residual_type = 'deviance') #' } #' get_residuals <- function(vst_out, umi, residual_type = 'pearson', res_clip_range = c(-sqrt(ncol(umi)), sqrt(ncol(umi))), min_variance = vst_out$arguments$min_variance, cell_attr = vst_out$cell_attr, bin_size = 256, verbosity = vst_out$arguments$verbosity, verbose = NULL, show_progress = NULL) { # Take care of deprecated arguments if (!is.null(verbose)) { warning("The 'verbose' argument is deprecated as of v0.3. Use 'verbosity' instead. (in sctransform::vst)", immediate. = TRUE, call. = FALSE) verbosity <- as.numeric(verbose) } if (!is.null(show_progress)) { warning("The 'show_progress' argument is deprecated as of v0.3. Use 'verbosity' instead. (in sctransform::vst)", immediate. = TRUE, call. = FALSE) if (show_progress) { verbosity <- 2 } else { verbosity <- min(verbosity, 1) } } # min_variance estimated using median umi if (min_variance == "umi_median"){ # Maximum pearson residual for non-zero median UMI is 5 min_var <- (get_nz_median(umi) / 5)^2 if (verbosity > 0) { message(paste("Setting min_variance based on median UMI: ", min_var)) } } else { if (verbosity > 0) { message(paste("Setting min_variance to: ", min_variance)) } min_var <- min_variance } regressor_data <- model.matrix(as.formula(gsub('^y', '', vst_out$model_str)), cell_attr) model_pars <- vst_out$model_pars_fit if (!is.null(dim(vst_out$model_pars_nonreg))) { regressor_data_nonreg <- model.matrix(as.formula(gsub('^y', '', vst_out$model_str_nonreg)), cell_attr) regressor_data <- cbind(regressor_data, regressor_data_nonreg) model_pars <- cbind(vst_out$model_pars_fit, vst_out$model_pars_nonreg) } genes <- rownames(umi)[rownames(umi) %in% rownames(model_pars)] if (verbosity > 0) { message('Calculating residuals of type ', residual_type, ' for ', length(genes), ' genes') } bin_ind <- ceiling(x = 1:length(x = genes) / bin_size) max_bin <- max(bin_ind) if (verbosity > 1) { pb <- txtProgressBar(min = 0, max = max_bin, style = 3) } res <- matrix(NA_real_, length(genes), nrow(regressor_data), dimnames = list(genes, rownames(regressor_data))) for (i in 1:max_bin) { genes_bin <- genes[bin_ind == i] mu <- exp(tcrossprod(model_pars[genes_bin, -1, drop=FALSE], regressor_data)) y <- as.matrix(umi[genes_bin, , drop=FALSE]) if (min_variance == "model_mean") { mu_mean_var <- matrixStats::rowMeans2(mu) res[genes_bin, ] <- switch(residual_type, 'pearson' = pearson_residual2(y, mu, model_pars[genes_bin, 'theta'], min_vars = mu_mean_var), 'deviance' = deviance_residual(y, mu, model_pars[genes_bin, 'theta']), stop('residual_type ', residual_type, ' unknown - only pearson and deviance supported at the moment')) } else if (min_variance == "model_median") { mu_median_var <- matrixStats::rowMedians(mu) res[genes_bin, ] <- switch(residual_type, 'pearson' = pearson_residual2(y, mu, model_pars[genes_bin, 'theta'], min_vars = mu_median_var), 'deviance' = deviance_residual(y, mu, model_pars[genes_bin, 'theta']), stop('residual_type ', residual_type, ' unknown - only pearson and deviance supported at the moment')) } else { res[genes_bin, ] <- switch(residual_type, 'pearson' = pearson_residual(y, mu, model_pars[genes_bin, 'theta'], min_var = min_var), 'deviance' = deviance_residual(y, mu, model_pars[genes_bin, 'theta']), stop('residual_type ', residual_type, ' unknown - only pearson and deviance supported at the moment')) } if (verbosity > 1) { setTxtProgressBar(pb, i) } } if (verbosity > 1) { close(pb) } res[res < res_clip_range[1]] <- res_clip_range[1] res[res > res_clip_range[2]] <- res_clip_range[2] return(res) } #' Return variance of residuals of regularized models #' #' This never creates the full residual matrix and can be used to determine highly variable genes. #' #' @param vst_out The output of a vst run #' @param umi The UMI count matrix that will be used #' @param residual_type What type of residuals to return; can be 'pearson' or 'deviance'; default is 'pearson' #' @param res_clip_range Numeric of length two specifying the min and max values the residuals will be clipped to; default is c(-sqrt(ncol(umi)), sqrt(ncol(umi))) #' @param min_variance Lower bound for the estimated variance for any gene in any cell when calculating pearson residual; default is vst_out$arguments$min_variance #' @param cell_attr Data frame of cell meta data #' @param bin_size Number of genes to put in each bin (to show progress) #' @param verbosity An integer specifying whether to show only messages (1), messages and progress bars (2) or nothing (0) while the function is running; default is 2 #' @param verbose Deprecated; use verbosity instead #' @param show_progress Deprecated; use verbosity instead #' #' @return A vector of residual variances (after clipping) #' #' @export #' #' @examples #' \donttest{ #' vst_out <- vst(pbmc, return_cell_attr = TRUE) #' res_var <- get_residual_var(vst_out, pbmc) #' } #' get_residual_var <- function(vst_out, umi, residual_type = 'pearson', res_clip_range = c(-sqrt(ncol(umi)), sqrt(ncol(umi))), min_variance = vst_out$arguments$min_variance, cell_attr = vst_out$cell_attr, bin_size = 256, verbosity = vst_out$arguments$verbosity, verbose = NULL, show_progress = NULL) { # Take care of deprecated arguments if (!is.null(verbose)) { warning("The 'verbose' argument is deprecated as of v0.3. Use 'verbosity' instead. (in sctransform::vst)", immediate. = TRUE, call. = FALSE) verbosity <- as.numeric(verbose) } if (!is.null(show_progress)) { warning("The 'show_progress' argument is deprecated as of v0.3. Use 'verbosity' instead. (in sctransform::vst)", immediate. = TRUE, call. = FALSE) if (show_progress) { verbosity <- 2 } else { verbosity <- min(verbosity, 1) } } regressor_data <- model.matrix(as.formula(gsub('^y', '', vst_out$model_str)), cell_attr) model_pars <- vst_out$model_pars_fit if (!is.null(dim(vst_out$model_pars_nonreg))) { regressor_data_nonreg <- model.matrix(as.formula(gsub('^y', '', vst_out$model_str_nonreg)), cell_attr) regressor_data <- cbind(regressor_data, regressor_data_nonreg) model_pars <- cbind(vst_out$model_pars_fit, vst_out$model_pars_nonreg) } genes <- rownames(umi)[rownames(umi) %in% rownames(model_pars)] # min_variance estimated using median umi if (min_variance == "umi_median"){ # Maximum pearson residual for non-zero median UMI is 5 min_var <- (get_nz_median(umi, genes) / 5)^2 if (verbosity > 0) { message(paste("Setting min_variance based on median UMI: ", min_var)) } } else { if (verbosity > 0) { message(paste("Setting min_variance to: ", min_variance)) } min_var <- min_variance } if (verbosity > 0) { message('Calculating variance for residuals of type ', residual_type, ' for ', length(genes), ' genes') } bin_ind <- ceiling(x = 1:length(x = genes) / bin_size) max_bin <- max(bin_ind) if (verbosity > 1) { pb <- txtProgressBar(min = 0, max = max_bin, style = 3) } res <- matrix(NA_real_, length(genes)) names(res) <- genes for (i in 1:max_bin) { genes_bin <- genes[bin_ind == i] mu <- exp(tcrossprod(model_pars[genes_bin, -1, drop=FALSE], regressor_data)) y <- as.matrix(umi[genes_bin, , drop=FALSE]) if (min_variance == "model_mean") { mu_mean_var <- matrixStats::rowMeans2(mu) res_mat <- switch(residual_type, 'pearson' = pearson_residual2(y, mu, model_pars[genes_bin, 'theta'], min_vars = mu_mean_var), 'deviance' = deviance_residual(y, mu, model_pars[genes_bin, 'theta']), stop('residual_type ', residual_type, ' unknown - only pearson and deviance supported at the moment')) } else if (min_variance == "model_median") { mu_median_var <- matrixStats::rowMedians(mu) res_mat <- switch(residual_type, 'pearson' = pearson_residual2(y, mu, model_pars[genes_bin, 'theta'], min_vars = mu_median_var), 'deviance' = deviance_residual(y, mu, model_pars[genes_bin, 'theta']), stop('residual_type ', residual_type, ' unknown - only pearson and deviance supported at the moment')) } else { res_mat <- switch(residual_type, 'pearson' = pearson_residual(y, mu, model_pars[genes_bin, 'theta'], min_var = min_var), 'deviance' = deviance_residual(y, mu, model_pars[genes_bin, 'theta']), stop('residual_type ', residual_type, ' unknown - only pearson and deviance supported at the moment')) } res_mat[res_mat < res_clip_range[1]] <- res_clip_range[1] res_mat[res_mat > res_clip_range[2]] <- res_clip_range[2] res[genes_bin] <- row_var(res_mat) if (verbosity > 1) { setTxtProgressBar(pb, i) } } if (verbosity > 1) { close(pb) } return(res) } #' Return average variance under negative binomial model #' #' This is based on the formula var = mu + mu^2 / theta #' #' @param vst_out The output of a vst run #' @param cell_attr Data frame of cell meta data #' @param use_nonreg Use the non-regularized parameter estimates; boolean; default is FALSE #' @param bin_size Number of genes to put in each bin (to show progress) #' @param verbosity An integer specifying whether to show only messages (1), messages and progress bars (2) or nothing (0) while the function is running; default is 2 #' @param verbose Deprecated; use verbosity instead #' @param show_progress Deprecated; use verbosity instead #' #' @return A named vector of variances (the average across all cells), one entry per gene. #' #' @export #' #' @examples #' \donttest{ #' vst_out <- vst(pbmc, return_cell_attr = TRUE) #' res_var <- get_model_var(vst_out) #' } #' get_model_var <- function(vst_out, cell_attr = vst_out$cell_attr, use_nonreg = FALSE, bin_size = 256, verbosity = 2, verbose = NULL, show_progress = NULL) { # Take care of deprecated arguments if (!is.null(verbose)) { warning("The 'verbose' argument is deprecated as of v0.3. Use 'verbosity' instead. (in sctransform::vst)", immediate. = TRUE, call. = FALSE) verbosity <- as.numeric(verbose) } if (!is.null(show_progress)) { warning("The 'show_progress' argument is deprecated as of v0.3. Use 'verbosity' instead. (in sctransform::vst)", immediate. = TRUE, call. = FALSE) if (show_progress) { verbosity <- 2 } else { verbosity <- min(verbosity, 1) } } regressor_data <- model.matrix(as.formula(gsub('^y', '', vst_out$model_str)), cell_attr) if (use_nonreg) { model_pars <- vst_out$model_pars } else { model_pars <- vst_out$model_pars_fit } if (!is.null(dim(vst_out$model_pars_nonreg))) { regressor_data_nonreg <- model.matrix(as.formula(gsub('^y', '', vst_out$model_str_nonreg)), cell_attr) regressor_data <- cbind(regressor_data, regressor_data_nonreg) model_pars <- cbind(vst_out$model_pars_fit, vst_out$model_pars_nonreg) } genes <- rownames(model_pars) if (verbosity > 0) { message('Calculating model variance for ', length(genes), ' genes') } bin_ind <- ceiling(x = 1:length(x = genes) / bin_size) max_bin <- max(bin_ind) if (verbosity > 1) { pb <- txtProgressBar(min = 0, max = max_bin, style = 3) } res <- matrix(NA_real_, length(genes)) names(res) <- genes for (i in 1:max_bin) { genes_bin <- genes[bin_ind == i] mu <- exp(tcrossprod(model_pars[genes_bin, -1, drop=FALSE], regressor_data)) model_var = mu + mu^2 / model_pars[genes_bin, 'theta'] res[genes_bin] <- rowMeans(model_var) if (verbosity > 1) { setTxtProgressBar(pb, i) } } if (verbosity > 1) { close(pb) } return(res) } #' Get median of non zero UMIs from a count matrix using a subset of genes (slow) #' #' @param umi Count matrix #' @param genes List of genes to calculate statistics. Default is NULL which returns the non-zero median using all genes #' #' @return A numeric value representing the median of non-zero entries from the UMI matrix get_nz_median <- function(umi, genes = NULL){ cm.T <- Matrix::t(umi) n_g <- dim(umi)[1] allnonzero <- c() if (is.null(genes)) { gene_index <- seq(1, nrow(umi)) } else { gene_index <- which(genes %in% rownames(umi)) } for (g in gene_index) { m_i <- cm.T@x[(cm.T@p[g] + 1):cm.T@p[g + 1]] allnonzero <- c(allnonzero, m_i) } return (median(allnonzero, na.rm = TRUE)) } #' Get median of non zero UMIs from a count matrix #' #' @param umi Count matrix #' #' @return A numeric value representing the median of non-zero entries from the UMI matrix get_nz_median2 <- function(umi){ return (median(umi@x)) } sctransform/R/vst.R0000644000176200001440000012505714167147205013774 0ustar liggesusers#' @useDynLib sctransform NULL #' Variance stabilizing transformation for UMI count data #' #' Apply variance stabilizing transformation to UMI count data using a regularized Negative Binomial regression model. #' This will remove unwanted effects from UMI data and return Pearson residuals. #' Uses future_lapply; you can set the number of cores it will use to n with plan(strategy = "multicore", workers = n). #' If n_genes is set, only a (somewhat-random) subset of genes is used for estimating the #' initial model parameters. For details see \doi{10.1186/s13059-019-1874-1}. #' #' @param umi A matrix of UMI counts with genes as rows and cells as columns #' @param cell_attr A data frame containing the dependent variables; if omitted a data frame with umi and gene will be generated #' @param latent_var The independent variables to regress out as a character vector; must match column names in cell_attr; default is c("log_umi") #' @param batch_var The dependent variables indicating which batch a cell belongs to; no batch interaction terms used if omiited #' @param latent_var_nonreg The non-regularized dependent variables to regress out as a character vector; must match column names in cell_attr; default is NULL #' @param n_genes Number of genes to use when estimating parameters (default uses 2000 genes, set to NULL to use all genes) #' @param n_cells Number of cells to use when estimating parameters (default uses all cells) #' @param method Method to use for initial parameter estimation; one of 'poisson', 'qpoisson', 'nb_fast', 'nb', 'nb_theta_given', 'glmGamPoi', 'offset', 'offset_shared_theta_estimate', 'glmGamPoi_offset'; default is 'poisson' #' @param do_regularize Boolean that, if set to FALSE, will bypass parameter regularization and use all genes in first step (ignoring n_genes); default is FALSE #' @param theta_regularization Method to use to regularize theta; use 'log_theta' for the behavior prior to version 0.3; default is 'od_factor' #' @param res_clip_range Numeric of length two specifying the min and max values the results will be clipped to; default is c(-sqrt(ncol(umi)), sqrt(ncol(umi))) #' @param bin_size Number of genes to process simultaneously; this will determine how often the progress bars are updated and how much memory is being used; default is 500 #' @param min_cells Only use genes that have been detected in at least this many cells; default is 5 #' @param residual_type What type of residuals to return; can be 'pearson', 'deviance', or 'none'; default is 'pearson' #' @param return_cell_attr Make cell attributes part of the output; default is FALSE #' @param return_gene_attr Calculate gene attributes and make part of output; default is TRUE #' @param return_corrected_umi If set to TRUE output will contain corrected UMI matrix; see \code{correct} function #' @param min_variance Lower bound for the estimated variance for any gene in any cell when calculating pearson residual; one of 'umi_median', 'model_median', 'model_mean' or a #' numeric. default is -Inf. When set to 'umi_median' uses (median of non-zero UMIs / 5)^2 as the minimum variance so that a median UMI (often 1) #' results in a maximum pearson residual of 5. When set to 'model_median' or 'model_mean' uses the mean/median of the model estimated mu per gene as the minimum_variance.#' #' @param bw_adjust Kernel bandwidth adjustment factor used during regurlarization; factor will be applied to output of bw.SJ; default is 3 #' @param gmean_eps Small value added when calculating geometric mean of a gene to avoid log(0); default is 1 #' @param theta_estimation_fun Character string indicating which method to use to estimate theta (when method = poisson); default is 'theta.ml', but 'theta.mm' seems to be a good and fast alternative #' @param theta_given If method is set to nb_theta_given, this should be a named numeric vector of fixed theta values for the genes; if method is offset, this should be a single value; default is NULL #' @param exclude_poisson Exclude poisson genes (i.e. mu < 0.001 or mu > variance) from regularization; default is FALSE #' @param use_geometric_mean Use geometric mean instead of arithmetic mean for all calculations ; default is TRUE #' @param use_geometric_mean_offset Use geometric mean instead of arithmetic mean in the offset model; default is FALSE #' @param fix_intercept Fix intercept as defined in the offset model; default is FALSE #' @param fix_slope Fix slope to log(10) (equivalent to using library size as an offset); default is FALSE #' @param scale_factor Replace all values of UMI in the regression model by this value instead of the median UMI; default is NA #' @param vst.flavor When set to `v2` sets method = glmGamPoi_offset, n_cells=2000, and exclude_poisson = TRUE which causes the model to learn theta and intercept only besides excluding poisson genes from learning and regularization; default is NULL which uses the original sctransform model #' @param verbosity An integer specifying whether to show only messages (1), messages and progress bars (2) or nothing (0) while the function is running; default is 2 #' @param verbose Deprecated; use verbosity instead #' @param show_progress Deprecated; use verbosity instead #' #' @return A list with components #' \item{y}{Matrix of transformed data, i.e. Pearson residuals, or deviance residuals; empty if \code{residual_type = 'none'}} #' \item{umi_corrected}{Matrix of corrected UMI counts (optional)} #' \item{model_str}{Character representation of the model formula} #' \item{model_pars}{Matrix of estimated model parameters per gene (theta and regression coefficients)} #' \item{model_pars_outliers}{Vector indicating whether a gene was considered to be an outlier} #' \item{model_pars_fit}{Matrix of fitted / regularized model parameters} #' \item{model_str_nonreg}{Character representation of model for non-regularized variables} #' \item{model_pars_nonreg}{Model parameters for non-regularized variables} #' \item{genes_log_gmean_step1}{log-geometric mean of genes used in initial step of parameter estimation} #' \item{cells_step1}{Cells used in initial step of parameter estimation} #' \item{arguments}{List of function call arguments} #' \item{cell_attr}{Data frame of cell meta data (optional)} #' \item{gene_attr}{Data frame with gene attributes such as mean, detection rate, etc. (optional)} #' \item{times}{Time stamps at various points in the function} #' #' @section Details: #' In the first step of the algorithm, per-gene glm model parameters are learned. This step can be done #' on a subset of genes and/or cells to speed things up. #' If \code{method} is set to 'poisson', a poisson regression is done and #' the negative binomial theta parameter is estimated using the response residuals in #' \code{theta_estimation_fun}. #' If \code{method} is set to 'qpoisson', coefficients and overdispersion (phi) are estimated by quasi #' poisson regression and theta is estimated based on phi and the mean fitted value - this is currently #' the fastest method with results very similar to 'glmGamPoi' #' If \code{method} is set to 'nb_fast', coefficients and theta are estimated as in the #' 'poisson' method, but coefficients are then re-estimated using a proper negative binomial #' model in a second call to glm with \code{family = MASS::negative.binomial(theta = theta)}. #' If \code{method} is set to 'nb', coefficients and theta are estimated by a single call to #' \code{MASS::glm.nb}. #' If \code{method} is set to 'glmGamPoi', coefficients and theta are estimated by a single call to #' \code{glmGamPoi::glm_gp}. #' #' A special case is \code{method = 'offset'}. Here no regression parameters are learned, but #' instead an offset model is assumed. The latent variable is set to log_umi and a fixed #' slope of log(10) is used (offset). The intercept is given by log(gene_mean) - log(avg_cell_umi). #' See Lause et al. \doi{10.1186/s13059-021-02451-7} for details. #' Theta is set #' to 100 by default, but can be changed using the \code{theta_given} parameter (single numeric value). #' If the offset method is used, the following parameters are overwritten: #' \code{cell_attr <- NULL, latent_var <- c('log_umi'), batch_var <- NULL, latent_var_nonreg <- NULL, #' n_genes <- NULL, n_cells <- NULL, do_regularize <- FALSE}. Further, \code{method = 'offset_shared_theta_estimate'} #' exists where the 250 most highly expressed genes with detection rate of at least 0.5 are used #' to estimate a theta that is then shared across all genes. Thetas are estimated per individual gene #' using 5000 randomly selected cells. The final theta used for all genes is then the average. #' #' #' @import Matrix #' @importFrom future.apply future_lapply #' @importFrom MASS theta.ml theta.mm glm.nb negative.binomial #' @importFrom stats glm glm.fit df.residual ksmooth model.matrix as.formula approx density poisson var bw.SJ #' @importFrom utils txtProgressBar setTxtProgressBar capture.output #' @importFrom methods as #' @importFrom utils packageVersion #' #' @export #' #' @examples #' \donttest{ #' vst_out <- vst(pbmc) #' } #' vst <- function(umi, cell_attr = NULL, latent_var = c('log_umi'), batch_var = NULL, latent_var_nonreg = NULL, n_genes = 2000, n_cells = NULL, method = 'poisson', do_regularize = TRUE, theta_regularization = 'od_factor', res_clip_range = c(-sqrt(ncol(umi)), sqrt(ncol(umi))), bin_size = 500, min_cells = 5, residual_type = 'pearson', return_cell_attr = FALSE, return_gene_attr = TRUE, return_corrected_umi = FALSE, min_variance = -Inf, bw_adjust = 3, gmean_eps = 1, theta_estimation_fun = 'theta.ml', theta_given = NULL, exclude_poisson = FALSE, use_geometric_mean = TRUE, use_geometric_mean_offset = FALSE, fix_intercept = FALSE, fix_slope = FALSE, scale_factor = NA, vst.flavor = NULL, verbosity = 2, verbose = NULL, show_progress = NULL) { if (!is.null(vst.flavor)){ if (vst.flavor == "v2"){ if (verbosity>0){ message("vst.flavor='v2' set, setting model to use fixed slope and exclude poisson genes.") } method <- "glmGamPoi_offset" exclude_poisson <- TRUE if (min_variance == -Inf) min_variance <- 'umi_median' if (is.null(n_cells)) n_cells <- 2000 } } arguments <- as.list(environment()) arguments <- arguments[!names(arguments) %in% c("umi", "cell_attr")] # Take care of deprecated arguments if (!is.null(verbose)) { warning("The 'verbose' argument is deprecated as of v0.3. Use 'verbosity' instead. (in sctransform::vst)", immediate. = TRUE, call. = FALSE) verbosity <- as.numeric(verbose) } if (!is.null(show_progress)) { warning("The 'show_progress' argument is deprecated as of v0.3. Use 'verbosity' instead. (in sctransform::vst)", immediate. = TRUE, call. = FALSE) if (show_progress) { verbosity <- 2 } else { verbosity <- min(verbosity, 1) } } # Check for suggested package if (method %in% c("glmGamPoi", "glmGamPoi_offset")) { glmGamPoi_check <- requireNamespace("glmGamPoi", quietly = TRUE) if (!glmGamPoi_check){ stop('Please install the glmGamPoi package. See https://github.com/const-ae/glmGamPoi for details.') } } # Special case offset model - override most parameters if (startsWith(x = method, prefix = 'offset')) { cell_attr <- NULL latent_var <- c('log_umi') batch_var <- NULL latent_var_nonreg <- NULL n_genes <- NULL n_cells <- NULL do_regularize <- FALSE if (is.null(theta_given)) { theta_given <- 100 } else { theta_given <- theta_given[1] } } times <- list(start_time = Sys.time()) cell_attr <- make_cell_attr(umi, cell_attr, latent_var, batch_var, latent_var_nonreg, verbosity) if (!is.null(batch_var)) { cell_attr[, batch_var] <- as.factor(cell_attr[, batch_var]) batch_levels <- levels(cell_attr[, batch_var]) } # we will generate output for all genes detected in at least min_cells cells # but for the first step of parameter estimation we might use only a subset of genes genes_cell_count <- rowSums(umi >= 0.01) genes <- rownames(umi)[genes_cell_count >= min_cells] umi <- umi[genes, ] if (use_geometric_mean){ genes_log_gmean <- log10(row_gmean(umi, eps = gmean_eps)) } else { genes_log_gmean <- log10(rowMeans(umi)) } if (!do_regularize && !is.null(n_genes)) { if (verbosity > 0) { message('do_regularize is set to FALSE, will use all genes') } n_genes <- NULL } if (!is.null(n_cells) && n_cells < ncol(umi)) { # downsample cells to speed up the first step cells_step1 <- sample(x = colnames(umi), size = n_cells) if (!is.null(batch_var)) { dropped_batch_levels <- setdiff(batch_levels, levels(droplevels(cell_attr[cells_step1, batch_var]))) if (length(dropped_batch_levels) > 0) { stop('Dropped batch levels ', dropped_batch_levels, ', set n_cells higher') } } genes_cell_count_step1 <- rowSums(umi[, cells_step1] > 0) genes_step1 <- rownames(umi)[genes_cell_count_step1 >= min_cells] if (use_geometric_mean){ genes_log_gmean_step1 <- log10(row_gmean(umi[genes_step1, ], eps = gmean_eps)) } else { genes_log_gmean_step1 <- log10(rowMeans(umi[genes_step1, ])) } } else { cells_step1 <- colnames(umi) genes_step1 <- genes genes_log_gmean_step1 <- genes_log_gmean } genes_amean <- NULL genes_var <- NULL # Exclude known poisson genes from the learning step if (do_regularize && exclude_poisson){ genes_amean <- rowMeans(umi) genes_var <- row_var(umi) overdispersion_factor <- genes_var - genes_amean overdispersion_factor_step1 <- overdispersion_factor[genes_step1] is_overdispersed <- (overdispersion_factor_step1 > 0) if (verbosity > 0) { message(paste("Total Step 1 genes:", length(genes_step1))) message(paste("Total overdispersed genes:", sum(is_overdispersed))) message(paste("Excluding", length(genes_step1) - sum(is_overdispersed), "genes from Step 1 because they are not overdispersed.")) } genes_step1 <- genes_step1[is_overdispersed] genes_log_gmean_step1 <- genes_log_gmean[genes_step1] } data_step1 <- cell_attr[cells_step1, , drop = FALSE] if (!is.null(n_genes) && n_genes < length(genes_step1)) { # density-sample genes to speed up the first step log_gmean_dens <- density(x = genes_log_gmean_step1, bw = 'nrd', adjust = 1) sampling_prob <- 1 / (approx(x = log_gmean_dens$x, y = log_gmean_dens$y, xout = genes_log_gmean_step1)$y + .Machine$double.eps) genes_step1 <- sample(x = genes_step1, size = n_genes, prob = sampling_prob) if (use_geometric_mean){ genes_log_gmean_step1 <- log10(row_gmean(umi[genes_step1, ], eps = gmean_eps)) } else { genes_log_gmean_step1 <- log10(rowMeans(umi[genes_step1, ])) } } if (!is.null(batch_var)) { model_str <- paste0('y ~ (', paste(latent_var, collapse = ' + '), ') : ', batch_var, ' + ', batch_var, ' + 0') } else { model_str <- paste0('y ~ ', paste(latent_var, collapse = ' + ')) } bin_ind <- ceiling(x = 1:length(x = genes_step1) / bin_size) max_bin <- max(bin_ind) if (verbosity > 0) { message('Variance stabilizing transformation of count matrix of size ', nrow(umi), ' by ', ncol(umi)) message('Model formula is ', model_str) } times$get_model_pars = Sys.time() model_pars <- get_model_pars(genes_step1, bin_size, umi, model_str, cells_step1, method, data_step1, theta_given, theta_estimation_fun, exclude_poisson, fix_intercept, fix_slope, use_geometric_mean, use_geometric_mean_offset, verbosity) # make sure theta is not too small min_theta <- 1e-7 if (any(model_pars[, 'theta'] < min_theta)) { if (verbosity > 0) { msg <- sprintf('There are %d estimated thetas smaller than %g - will be set to %g', sum(model_pars[, 'theta'] < min_theta), min_theta, min_theta) message(msg) } model_pars[, 'theta'] <- pmax(model_pars[, 'theta'], min_theta) } times$reg_model_pars = Sys.time() if (do_regularize) { model_pars_fit <- reg_model_pars(model_pars, genes_log_gmean_step1, genes_log_gmean, cell_attr, batch_var, cells_step1, genes_step1, umi, bw_adjust, gmean_eps, theta_regularization, genes_amean, genes_var, exclude_poisson, fix_intercept, fix_slope, use_geometric_mean, use_geometric_mean_offset, verbosity) model_pars_outliers <- attr(model_pars_fit, 'outliers') } else { model_pars_fit <- model_pars model_pars_outliers <- rep(FALSE, nrow(model_pars)) } # use all fitted values in NB model regressor_data <- model.matrix(as.formula(gsub('^y', '', model_str)), cell_attr) if (!is.null(latent_var_nonreg)) { if (verbosity > 0) { message('Estimating parameters for following non-regularized variables: ', latent_var_nonreg) } if (!is.null(batch_var)) { model_str_nonreg <- paste0('y ~ (', paste(latent_var_nonreg, collapse = ' + '), ') : ', batch_var, ' + ', batch_var, ' + 0') } else { model_str_nonreg <- paste0('y ~ ', paste(latent_var_nonreg, collapse = ' + ')) } times$get_model_pars_nonreg = Sys.time() model_pars_nonreg <- get_model_pars_nonreg(genes, bin_size, model_pars_fit, regressor_data, umi, model_str_nonreg, cell_attr, verbosity) regressor_data_nonreg <- model.matrix(as.formula(gsub('^y', '', model_str_nonreg)), cell_attr) model_pars_final <- cbind(model_pars_fit, model_pars_nonreg) regressor_data_final <- cbind(regressor_data, regressor_data_nonreg) #model_pars_final[, '(Intercept)'] <- model_pars_final[, '(Intercept)'] + model_pars_nonreg[, '(Intercept)'] #model_pars_final <- cbind(model_pars_final, model_pars_nonreg[, -1, drop=FALSE]) # model_str <- paste0(model_str, gsub('^y ~ 1', '', model_str2)) } else { model_str_nonreg <- '' model_pars_nonreg <- c() model_pars_final <- model_pars_fit regressor_data_final <- regressor_data } times$get_residuals = Sys.time() if (!residual_type == 'none') { # min_variance estimated using median umi if (min_variance == "umi_median"){ # Maximum pearson residual for non-zero median UMI is 5 min_var <- (get_nz_median2(umi) / 5)^2 if (verbosity > 0) { message(paste("Setting min_variance based on median UMI: ", min_var)) } arguments$set_min_var <- min_var } else { min_var <- min_variance } if (verbosity > 0) { message('Second step: Get residuals using fitted parameters for ', length(x = genes), ' genes') } bin_ind <- ceiling(x = 1:length(x = genes) / bin_size) max_bin <- max(bin_ind) if (verbosity > 1) { pb <- txtProgressBar(min = 0, max = max_bin, style = 3) } res <- matrix(NA_real_, length(genes), nrow(regressor_data_final), dimnames = list(genes, rownames(regressor_data_final))) for (i in 1:max_bin) { genes_bin <- genes[bin_ind == i] mu <- exp(tcrossprod(model_pars_final[genes_bin, -1, drop=FALSE], regressor_data_final)) y <- as.matrix(umi[genes_bin, , drop=FALSE]) if (min_variance == "model_mean") { mu_mean_var <- matrixStats::rowMeans2(mu) res[genes_bin, ] <- switch(residual_type, 'pearson' = pearson_residual2(y, mu, model_pars_final[genes_bin, 'theta'], min_vars = mu_mean_var), 'deviance' = deviance_residual(y, mu, model_pars_final[genes_bin, 'theta']), stop('residual_type ', residual_type, ' unknown - only pearson and deviance supported at the moment') ) } else if (min_variance == "model_median") { mu_median_var <- matrixStats::rowMedians(mu) res[genes_bin, ] <- switch(residual_type, 'pearson' = pearson_residual2(y, mu, model_pars_final[genes_bin, 'theta'], min_vars = mu_median_var), 'deviance' = deviance_residual(y, mu, model_pars_final[genes_bin, 'theta']), stop('residual_type ', residual_type, ' unknown - only pearson and deviance supported at the moment')) } else { res[genes_bin, ] <- switch(residual_type, 'pearson' = pearson_residual(y, mu, model_pars_final[genes_bin, 'theta'], min_var = min_var), 'deviance' = deviance_residual(y, mu, model_pars_final[genes_bin, 'theta']), stop('residual_type ', residual_type, ' unknown - only pearson and deviance supported at the moment') ) } if (verbosity > 1) { setTxtProgressBar(pb, i) } } if (verbosity > 1) { close(pb) } } else { if (verbosity > 0) { message('Skip calculation of full residual matrix') } res <- matrix(data = NA, nrow = 0, ncol = 0) } rv <- list(y = res, model_str = model_str, model_pars = model_pars, model_pars_outliers = model_pars_outliers, model_pars_fit = model_pars_fit, model_str_nonreg = model_str_nonreg, model_pars_nonreg = model_pars_nonreg, arguments = arguments, genes_log_gmean_step1 = genes_log_gmean_step1, cells_step1 = cells_step1, cell_attr = cell_attr) rm(res) gc(verbose = FALSE) times$correct_umi = Sys.time() if (return_corrected_umi) { if (residual_type != 'pearson') { message("Will not return corrected UMI because residual type is not set to 'pearson'") } else { rv$umi_corrected <- sctransform::correct(rv, do_round = TRUE, do_pos = TRUE, scale_factor = scale_factor, verbosity = verbosity) rv$umi_corrected <- as(object = rv$umi_corrected, Class = 'dgCMatrix') } } rv$y[rv$y < res_clip_range[1]] <- res_clip_range[1] rv$y[rv$y > res_clip_range[2]] <- res_clip_range[2] if (!return_cell_attr) { rv[['cell_attr']] <- NULL } times$get_gene_attr = Sys.time() if (return_gene_attr) { if (verbosity > 0) { message('Calculating gene attributes') } gene_attr <- data.frame( detection_rate = genes_cell_count[genes] / ncol(umi), gmean = 10 ^ genes_log_gmean, amean = rowMeans(umi), variance = row_var(umi)) if (ncol(rv$y) > 0) { gene_attr$residual_mean = rowMeans(rv$y) gene_attr$residual_variance = row_var(rv$y) } rv[['gene_attr']] <- gene_attr } if (verbosity > 0) { message('Wall clock passed: ', capture.output(print(Sys.time() - times$start_time))) } times$done = Sys.time() rv$times <- times return(rv) } get_model_pars <- function(genes_step1, bin_size, umi, model_str, cells_step1, method, data_step1, theta_given, theta_estimation_fun, exclude_poisson = FALSE, fix_intercept = FALSE, fix_slope = FALSE, use_geometric_mean = TRUE, use_geometric_mean_offset = FALSE, verbosity = 0) { if (fix_slope | fix_intercept) { gene_mean <- rowMeans(umi) mean_cell_sum <- mean(colSums(umi)) model_pars_fixed <- cbind(rep(NA, length(genes_step1)), log(gene_mean)[genes_step1] - log(mean_cell_sum), rep(log(10), length(genes_step1))) if (use_geometric_mean_offset){ gene_gmean <- row_gmean(umi) model_pars_fixed <- cbind(rep(NA, length(genes_step1)), log(gene_gmean)[genes_step1] - log(mean_cell_sum), rep(log(10), length(genes_step1))) } dimnames(model_pars_fixed) <- list(genes_step1, c('theta', '(Intercept)', 'log_umi')) regressor_data <- model.matrix(as.formula(gsub('^y', '', model_str)), data_step1[cells_step1, ]) y_fixed <- as.matrix(umi[genes_step1, cells_step1]) mu_fixed <- exp(tcrossprod(model_pars_fixed[genes_step1, -1, drop=FALSE], regressor_data)) } # Special case offset model with one theta for all genes if (startsWith(x = method, prefix = 'offset')) { gene_mean <- rowMeans(umi) mean_cell_sum <- mean(colSums(umi)) model_pars <- cbind(rep(theta_given, nrow(umi)), log(gene_mean) - log(mean_cell_sum), rep(log(10), nrow(umi))) dimnames(model_pars) <- list(rownames(umi), c('theta', '(Intercept)', 'log_umi')) if (method == 'offset_shared_theta_estimate') { # use all genes with detection rate > 0.5 to estimate theta # if there are more, use the 250 most highly expressed ones # use at most 5000 cells (random sample) use_genes <- rowMeans(umi > 0) > 0.5 if (sum(use_genes) > 250) { o <- order(-row_gmean(umi[use_genes, ])) use_genes <- which(use_genes)[o[1:250]] } use_cells <- sample(x = ncol(umi), size = min(ncol(umi), 5000), replace = FALSE) if (verbosity > 0) { message(sprintf('Estimate shared theta for offset model using %d genes, %d cells', length(x = use_genes), length(x = use_cells))) } y <- as.matrix(umi[use_genes, use_cells]) regressor_data <- model.matrix(as.formula(gsub('^y', '', model_str)), data_step1[use_cells, ]) mu <- exp(tcrossprod(model_pars[use_genes, -1, drop=FALSE], regressor_data)) if (requireNamespace("glmGamPoi", quietly = TRUE) && getNamespaceVersion('glmGamPoi') >= '1.2') { theta <- 1 / glmGamPoi::overdispersion_mle(y = y, mean = mu)$estimate theta <- theta[is.finite(theta)] } else { theta <- sapply(1:nrow(y), function(i) { as.numeric(MASS::theta.ml(y = y[i, ], mu = mu[i, ], limit = 100)) }) } model_pars[, 'theta'] <- mean(theta) } else if (method == 'offset_allshared_theta_estimate') { # use all genes with detection rate > 0.5 to estimate theta use_genes <- rowMeans(umi > 0) > 0.5 use_cells <- sample(x = ncol(umi), size = min(ncol(umi), 5000), replace = FALSE) if (verbosity > 0) { message(sprintf('Estimate shared theta for offset model using %d genes, %d cells', length(x = use_genes), length(x = use_cells))) } y <- as.matrix(umi[use_genes, use_cells]) regressor_data <- model.matrix(as.formula(gsub('^y', '', model_str)), data_step1[use_cells, ]) mu <- exp(tcrossprod(model_pars[use_genes, -1, drop=FALSE], regressor_data)) if (requireNamespace("glmGamPoi", quietly = TRUE) && getNamespaceVersion('glmGamPoi') >= '1.2') { theta <- 1 / glmGamPoi::overdispersion_mle(y = y, mean = mu)$estimate theta <- theta[is.finite(theta)] } else { theta <- sapply(1:nrow(y), function(i) { as.numeric(suppressWarnings(MASS::theta.ml(y = y[i, ], mu = mu[i, ], limit = 100))) }) } model_pars[, 'theta'] <- mean(theta) } return(model_pars) } bin_ind <- ceiling(x = 1:length(x = genes_step1) / bin_size) max_bin <- max(bin_ind) if (verbosity > 0) { message('Get Negative Binomial regression parameters per gene') message('Using ', length(x = genes_step1), ' genes, ', length(x = cells_step1), ' cells') } if (verbosity > 1) { pb <- txtProgressBar(min = 0, max = max_bin, style = 3) } model_pars <- list() for (i in 1:max_bin) { genes_bin_regress <- genes_step1[bin_ind == i] umi_bin <- as.matrix(umi[genes_bin_regress, cells_step1, drop=FALSE]) if (fix_slope | fix_intercept) { mu_bin <- as.matrix(mu_fixed[genes_bin_regress, cells_step1, drop=FALSE]) model_pars_bin <- model_pars_fixed[genes_bin_regress, ] intercept_bin <- model_pars_bin[, "(Intercept)"] slope_bin <- model_pars_bin[, "log_umi"] } if (!is.null(theta_given)) { theta_given_bin <- theta_given[genes_bin_regress] } # umi_bin is a matrix of counts - we want a model per row # if there are multiple workers, split up the matrix in chunks of n rows # where n is the number of workers n_workers <- 1 if (future::supportsMulticore()) { n_workers <- future::nbrOfWorkers() } genes_per_worker <- nrow(umi_bin) / n_workers + .Machine$double.eps index_vec <- 1:nrow(umi_bin) index_lst <- split(index_vec, ceiling(index_vec/genes_per_worker)) # the index list will have at most n_workers entries, each one defining which genes to work on par_lst <- future_lapply( X = index_lst, FUN = function(indices) { umi_bin_worker <- umi_bin[indices, , drop = FALSE] if (fix_intercept | fix_slope){ mu_bin_worker <- mu_bin[indices, , drop = FALSE] model_pars_bin_worker <- model_pars_bin[indices, , drop = FALSE] intercept_bin_worker <- model_pars_bin_worker[, "(Intercept)"] slope_bin_worker <- model_pars_bin_worker[, "log_umi"] } if (method == 'poisson') { return(fit_poisson(umi = umi_bin_worker, model_str = model_str, data = data_step1, theta_estimation_fun = theta_estimation_fun)) } if (method == 'qpoisson') { return(fit_qpoisson(umi = umi_bin_worker, model_str = model_str, data = data_step1)) } if (method == 'nb_theta_given') { theta_given_bin_worker <- theta_given_bin[indices] return(fit_nb_theta_given(umi = umi_bin_worker, model_str = model_str, data = data_step1, theta_given = theta_given_bin_worker)) } if (method == 'nb_fast') { return(fit_nb_fast(umi = umi_bin_worker, model_str = model_str, data = data_step1, theta_estimation_fun = theta_estimation_fun)) } if (method == 'nb') { return(fit_nb(umi = umi_bin_worker, model_str = model_str, data = data_step1)) } if (method == "glmGamPoi") { if (fix_slope | fix_intercept){ if (packageVersion("glmGamPoi")<"1.5.1"){ stop('Please install glmGamPoi >= 1.5.1 from https://github.com/const-ae/glmGamPoi') } return(fit_overdisp_mle(umi = umi_bin_worker, mu = mu_bin_worker, intercept = intercept_bin_worker, slope = slope_bin_worker)) } return(fit_glmGamPoi(umi = umi_bin_worker, model_str = model_str, data = data_step1, allow_inf_theta = exclude_poisson)) } if (method == "glmGamPoi_offset") { return(fit_glmGamPoi_offset(umi = umi_bin_worker, model_str = model_str, data = data_step1, allow_inf_theta = exclude_poisson)) } }, future.seed = TRUE ) model_pars[[i]] <- do.call(rbind, par_lst) if (verbosity > 1) { setTxtProgressBar(pb, i) } } model_pars <- do.call(rbind, model_pars) if (verbosity > 1) { close(pb) } rownames(model_pars) <- genes_step1 colnames(model_pars)[1] <- 'theta' if (exclude_poisson){ genes_amean <- rowMeans(umi) genes_var <- row_var(umi) genes_amean_step1 <- genes_amean[genes_step1] genes_var_step1 <- genes_var[genes_step1] predicted_theta <- genes_amean_step1^2/(genes_var_step1-genes_amean_step1) actual_theta <- model_pars[genes_step1, "theta"] diff_theta <- predicted_theta/actual_theta model_pars <- cbind(model_pars, diff_theta) # if the naive and estimated MLE are 1000x apart, set theta estimate to Inf diff_theta_index <- rownames(model_pars[model_pars[genes_step1, "diff_theta"]< 1e-3,]) if (verbosity>0){ message(paste("Setting estimate of ", length(diff_theta_index), "genes to inf as theta_mm/theta_mle < 1e-3")) } # Replace theta by infinity model_pars[diff_theta_index, 1] <- Inf # drop diff_theta column model_pars <- model_pars[, -dim(model_pars)[2]] } return(model_pars) } get_model_pars_nonreg <- function(genes, bin_size, model_pars_fit, regressor_data, umi, model_str_nonreg, cell_attr, verbosity) { bin_ind <- ceiling(x = 1:length(x = genes) / bin_size) max_bin <- max(bin_ind) if (verbosity > 1) { pb <- txtProgressBar(min = 0, max = max_bin, style = 3) } model_pars_nonreg <- list() for (i in 1:max_bin) { genes_bin <- genes[bin_ind == i] mu <- tcrossprod(model_pars_fit[genes_bin, -1, drop=FALSE], regressor_data) umi_bin <- as.matrix(umi[genes_bin, ]) model_pars_nonreg[[i]] <- do.call( rbind, future_lapply(X = genes_bin, FUN = function(gene) { fam <- negative.binomial(theta = model_pars_fit[gene, 'theta'], link = 'log') y <- umi_bin[gene, ] offs <- mu[gene, ] fit <- glm(as.formula(model_str_nonreg), data = cell_attr, family = fam, offset=offs) return(fit$coefficients)}, future.seed = TRUE)) if (verbosity > 1) { setTxtProgressBar(pb, i) } } if (verbosity > 1) { close(pb) } model_pars_nonreg <- do.call(rbind, model_pars_nonreg) rownames(model_pars_nonreg) <- genes return(model_pars_nonreg) } reg_model_pars <- function(model_pars, genes_log_gmean_step1, genes_log_gmean, cell_attr, batch_var, cells_step1, genes_step1, umi, bw_adjust, gmean_eps, theta_regularization, genes_amean = NULL, genes_var = NULL, exclude_poisson = FALSE, fix_intercept = FALSE, fix_slope = FALSE, use_geometric_mean = TRUE, use_geometric_mean_offset = FALSE, verbosity = 0) { genes <- names(genes_log_gmean) if (exclude_poisson | fix_slope | fix_intercept){ # exclude this from the fitting procedure entirely # at the regularization step if (is.null(genes_amean)) gene_amean <- rowMeans(umi) if (is.null(genes_var)) genes_var <- row_var(umi) genes_amean_step1 <- genes_amean[genes_step1] genes_var_step1 <- genes_var[genes_step1] overdispersion_factor <- genes_var - genes_amean overdispersion_factor_step1 <- overdispersion_factor[genes_step1] all_poisson_genes <- genes[overdispersion_factor<=0] # also set genes with mean < 1e-3 as poisson low_mean_genes <- genes[genes_amean<1e-3] all_poisson_genes <- union(all_poisson_genes, low_mean_genes) poisson_genes_step1 <- genes_step1[overdispersion_factor_step1<=0] if (verbosity>0){ message(paste("# of step1 poisson genes (variance < mean):", length(poisson_genes_step1))) message(paste("# of low mean genes (mean < 0.001):", length(low_mean_genes))) } poisson_genes2 <- rownames(model_pars[!is.finite(model_pars[, 'theta']),]) poisson_genes3 <- intersect(low_mean_genes, genes_step1) poisson_genes_step1 <- union(union(poisson_genes_step1, poisson_genes2),poisson_genes3) overdispersed_genes_step1 <- setdiff(genes_step1, poisson_genes_step1) if (verbosity>0){ message(paste("Total # of Step1 poisson genes (theta=Inf; variance < mean):", length(poisson_genes_step1))) message(paste("Total # of poisson genes (theta=Inf; variance < mean):", length(all_poisson_genes))) # call offset model message(paste("Calling offset model for all", length(all_poisson_genes), "poisson genes")) } # Call offset model with theta=inf # only the slope and intercept are used downstream mean_cell_sum <- mean(colSums(umi)) vst_out_offset <- cbind(rep(Inf, length(all_poisson_genes)), log(genes_amean[all_poisson_genes]) - log(mean_cell_sum), rep(log(10), length(all_poisson_genes) )) dimnames(vst_out_offset) <- list(all_poisson_genes, c('theta', '(Intercept)', 'log_umi')) dispersion_par <- rep(0, dim(vst_out_offset)[1]) vst_out_offset <- cbind(vst_out_offset, dispersion_par) } # we don't regularize theta directly # prior to v0.3 we regularized log10(theta) # now we transform to overdispersion factor # variance of NB is mu * (1 + mu / theta) # (1 + mu / theta) is what we call overdispersion factor here dispersion_par <- switch(theta_regularization, 'log_theta' = log10(model_pars[, 'theta']), 'od_factor' = log10(1 + 10^genes_log_gmean_step1 / model_pars[, 'theta']), stop('theta_regularization ', theta_regularization, ' unknown - only log_theta and od_factor supported at the moment') ) model_pars_all <- model_pars model_pars <- model_pars[, colnames(model_pars) != 'theta'] model_pars <- cbind(dispersion_par, model_pars) # look for outliers in the parameters # outliers are those that do not fit the overall relationship with the mean at all outliers <- apply(model_pars, 2, function(y) is_outlier(y, genes_log_gmean_step1)) outliers <- apply(outliers, 1, any) # also call theta=inf as outliers if (exclude_poisson){ is_theta_inf <- !is.finite(model_pars_all[, "theta"]) outliers <- outliers | is_theta_inf } if (sum(outliers) > 0) { if (verbosity > 0) { message('Found ', sum(outliers), ' outliers - those will be ignored in fitting/regularization step\n') } model_pars <- model_pars[!outliers, ] genes_step1 <- rownames(model_pars) genes_log_gmean_step1 <- genes_log_gmean_step1[!outliers] } if (exclude_poisson){ if (verbosity > 0) { message('Ignoring theta inf genes') } overdispersed_genes <- setdiff(rownames(model_pars), all_poisson_genes) model_pars <- model_pars[overdispersed_genes, ] genes_step1 <- rownames(model_pars) genes_log_gmean_step1 <- genes_log_gmean_step1[overdispersed_genes] } # select bandwidth to be used for smoothing bw <- bw.SJ(genes_log_gmean_step1) * bw_adjust # for parameter predictions x_points <- pmax(genes_log_gmean, min(genes_log_gmean_step1)) x_points <- pmin(x_points, max(genes_log_gmean_step1)) # take results from step 1 and fit/predict parameters to all genes o <- order(x_points) model_pars_fit <- matrix(NA_real_, length(genes), ncol(model_pars), dimnames = list(genes, colnames(model_pars))) # fit / regularize dispersion parameter model_pars_fit[o, 'dispersion_par'] <- ksmooth(x = genes_log_gmean_step1, y = model_pars[, 'dispersion_par'], x.points = x_points, bandwidth = bw, kernel='normal')$y if (is.null(batch_var)){ # global fit / regularization for all coefficients for (i in 2:ncol(model_pars)) { model_pars_fit[o, i] <- ksmooth(x = genes_log_gmean_step1, y = model_pars[, i], x.points = x_points, bandwidth = bw, kernel='normal')$y } } else { # fit / regularize per batch batches <- unique(cell_attr[, batch_var]) for (b in batches) { sel <- cell_attr[, batch_var] == b & rownames(cell_attr) %in% cells_step1 #batch_genes_log_gmean_step1 <- log10(rowMeans(umi[genes_step1, sel])) if (use_geometric_mean){ batch_genes_log_gmean_step1 <- log10(row_gmean(umi[genes_step1, sel], eps = gmean_eps)) } else { batch_genes_log_gmean_step1 <- log10(rowMeans(umi[genes_step1, sel])) } if (any(is.infinite(batch_genes_log_gmean_step1))) { if (verbosity > 0) { message('Some genes not detected in batch ', b, ' -- assuming a low mean.') } batch_genes_log_gmean_step1[is.infinite(batch_genes_log_gmean_step1) & batch_genes_log_gmean_step1 < 0] <- min(batch_genes_log_gmean_step1[!is.infinite(batch_genes_log_gmean_step1)]) } sel <- cell_attr[, batch_var] == b #batch_genes_log_gmean <- log10(rowMeans(umi[, sel])) if (use_geometric_mean){ batch_genes_log_gmean <- log10(row_gmean(umi[, sel], eps = gmean_eps)) } else { batch_genes_log_gmean <- log10(rowMeans(umi[, sel])) } # in case some genes have not been observed in this batch batch_genes_log_gmean <- pmax(batch_genes_log_gmean, min(batch_genes_log_gmean_step1)) batch_o <- order(batch_genes_log_gmean) for (i in which(grepl(paste0(batch_var, b), colnames(model_pars)))) { model_pars_fit[batch_o, i] <- ksmooth(x = batch_genes_log_gmean_step1, y = model_pars[, i], x.points = batch_genes_log_gmean, bandwidth = bw, kernel='normal')$y } } } if (exclude_poisson){ dispersion_par <- switch(theta_regularization, 'log_theta' = rep(Inf, length(all_poisson_genes)), 'od_factor' = rep(0, length(all_poisson_genes)), stop('theta_regularization ', theta_regularization, ' unknown - only log_theta and od_factor supported at the moment') ) model_pars_fit[all_poisson_genes, "dispersion_par"] <- dispersion_par } # back-transform dispersion parameter to theta theta <- switch(theta_regularization, 'log_theta' = 10^model_pars_fit[, 'dispersion_par'], 'od_factor' = 10^genes_log_gmean / (10^model_pars_fit[, 'dispersion_par'] - 1) ) model_pars_fit <- model_pars_fit[, colnames(model_pars_fit) != 'dispersion_par'] model_pars_fit <- cbind(theta, model_pars_fit) all_genes <- rownames(model_pars_fit) if (exclude_poisson){ if (verbosity > 0) { message(paste('Replacing fit params for', length(all_poisson_genes), 'poisson genes by theta=Inf')) } for (col in colnames(model_pars_fit)){ stopifnot(col %in% colnames(vst_out_offset)) model_pars_fit[all_poisson_genes, col] <- vst_out_offset[all_poisson_genes, col] } } if (fix_intercept){ # Replace the fitted intercepts by those calculated from offset model col <- "(Intercept)" if (verbosity > 0) { message(paste0('Replacing regularized parameter ', col, ' by offset')) } gene_mean <- rowMeans(umi) mean_cell_sum <- mean(colSums(umi)) intercept_fixed <- log(gene_mean)[all_genes] - log(mean_cell_sum) if (use_geometric_mean_offset){ gene_gmean <- row_gmean(umi) intercept_fixed <- log(gene_gmean)[all_genes] - log(mean_cell_sum) } model_pars_fit[all_genes, col] <- intercept_fixed } if (fix_slope){ # Replace the fitted slope by those calculated from offset model col <- "log_umi" if (verbosity > 0) { message(paste0('Replacing regularized parameter ', col, ' by offset')) } model_pars_fit[all_genes, col] <- rep(log(10), length(all_genes)) } attr(model_pars_fit, 'outliers') <- outliers return(model_pars_fit) } sctransform/R/umify.R0000644000176200001440000000764514167140301014301 0ustar liggesusersdata("umify_data", envir=environment()) #' Quantile normalization of cell-level data to match typical UMI count data #' #' @param counts A matrix of class dgCMatrix with genes as rows and columns as cells #' #' @return A UMI-fied count matrix #' #' @section Details: #' sctransform::vst operates under the assumption that gene counts approximately #' follow a Negative Binomial dristribution. For UMI-based data that seems to be #' the case, however, non-UMI data does not behave in the same way. #' In some cases it might be better to to apply a transformation to such data #' to make it look like UMI data. This function applies such a transformation function. #' #' Cells in the input matrix are processed independently. For each cell #' the non-zero data is transformed to quantile values. Based on the number of genes #' detected a smooth function is used to predict the UMI-like counts. #' #' The functions have be trained on various public data sets and come as part of the #' package (see umify_data data set in this package). #' #' @importFrom magrittr %>% #' @importFrom dplyr group_by summarise pull mutate case_when #' @importFrom stats approxfun #' @importFrom rlang .data #' #' @export #' #' @examples #' \donttest{ #' silly_example <- umify(pbmc) #' } umify <- function(counts) { # check input if (!inherits(x = counts, what = 'dgCMatrix')) { stop('counts must be a dgCMatrix') } # load the group breaks needed to place cells into groups grp_breaks <- umify_data$grp_breaks K <- length(grp_breaks) - 1 w <- mean(diff(grp_breaks)) # given the umify data models, create functions that # predict the log count from the distribution quantile # create one function per group membership (based on number of genes detected) apprx_funs <- group_by(umify_data$fit_df, .data$grp) %>% summarise(fun = list(approxfun(x = .data$q, y = .data$log_y, rule = 2:1)), .groups = 'drop') %>% pull(.data$fun) names(apprx_funs) <- levels(umify_data$fit_df$grp) # for each cell in the input we need to know how many genes are detected # then determine the primary and secondary group and the weights # to be used for the linear interpolation ca <- data.frame(genes = diff(counts@p)) %>% mutate(log_genes = log10(.data$genes), grp1 = cut(.data$log_genes, breaks = grp_breaks, right = FALSE), weight = ((.data$log_genes - grp_breaks[1]) / w) %% 1, grp2 = case_when(.data$weight >= 0.5 ~ as.numeric(.data$grp1)+1, TRUE ~ as.numeric(.data$grp1)-1), grp2 = case_when(.data$grp2 < 1 ~ 1, .data$grp2 > K ~ K, TRUE ~ .data$grp2), grp2 = factor(levels(.data$grp1)[.data$grp2], levels = levels(.data$grp1)), weight = -abs(.data$weight-0.5)+1) if (any(is.na(ca$grp1))) { warning(sprintf('Cells with very few or too many genes detected. The lower limit is %d, the upper limit is %d. Setting non-zero values to NA for %d cells.', floor(10^min(grp_breaks)), floor(10^max(grp_breaks)), sum(is.na(ca$grp1)))) } # predict UMIfied counts # per cell out_vec <- rep(NA_real_, length(counts@x)) j <- 1 while (j <= ncol(counts)) { if (!is.na(ca$grp1[j])) { i_start <- counts@p[j] + 1 i_end <- counts@p[j+1] sel <- i_start:i_end q <- rank(counts@x[sel], ties.method = 'max') / length(sel) pred1 <- apprx_funs[[ca$grp1[j]]](q) pred2 <- apprx_funs[[ca$grp2[j]]](q) out_vec[sel] <- round(10^(pred1 * ca$weight[j] + pred2 * (1 - ca$weight[j]))) } j <- j + 1 } counts_new <- sparseMatrix(i = counts@i, p = counts@p, x = out_vec, dims = counts@Dim, dimnames = counts@Dimnames, giveCsparse = TRUE, index1 = FALSE) return(counts_new) } sctransform/R/fit.R0000644000176200001440000001260214167140301013717 0ustar liggesusers# Fir NB regression models using different approaches fit_poisson <- function(umi, model_str, data, theta_estimation_fun) { regressor_data <- model.matrix(as.formula(gsub('^y', '', model_str)), data) dfr <- ncol(umi) - ncol(regressor_data) par_mat <- t(apply(umi, 1, function(y) { fit <- qpois_reg(regressor_data, y, 1e-9, 100, 1.0001, TRUE) theta <- switch(theta_estimation_fun, 'theta.ml' = as.numeric(x = suppressWarnings(theta.ml(y = y, mu = fit$fitted))), 'theta.mm' = as.numeric(x = theta.mm(y = y, mu = fit$fitted, dfr = dfr)), stop('theta_estimation_fun ', theta_estimation_fun, ' unknown - only theta.ml and theta.mm supported at the moment') ) return(c(theta, fit$coefficients)) })) return(par_mat) } fit_qpoisson <- function(umi, model_str, data) { regressor_data <- model.matrix(as.formula(gsub('^y', '', model_str)), data) par_mat <- t(apply(umi, 1, function(y) { fit <- qpois_reg(regressor_data, y, 1e-9, 100, 1.0001, FALSE) return(c(fit$theta.guesstimate, fit$coefficients)) })) return(par_mat) } fit_nb_theta_given <- function(umi, model_str, data, theta_given) { par_lst <- lapply(1:nrow(umi), function(j) { y <- umi[j, ] theta <- theta_given[j] fit2 <- 0 try(fit2 <- glm(as.formula(model_str), data = data, family = negative.binomial(theta=theta)), silent=TRUE) if (inherits(x = fit2, what = 'numeric')) { return(c(theta, glm(as.formula(model_str), data = data, family = poisson)$coefficients)) } else { return(c(theta, fit2$coefficients)) } }) return(do.call(rbind, par_lst)) } fit_nb_fast <- function(umi, model_str, data, theta_estimation_fun) { regressor_data <- model.matrix(as.formula(gsub('^y', '', model_str)), data) dfr <- ncol(umi) - ncol(regressor_data) par_mat <- apply(umi, 1, function(y) { fit <- qpois_reg(regressor_data, y, 1e-9, 100, 1.0001, TRUE) theta <- switch(theta_estimation_fun, 'theta.ml' = as.numeric(x = theta.ml(y = y, mu = fit$fitted)), 'theta.mm' = as.numeric(x = theta.mm(y = y, mu = fit$fitted, dfr = dfr)), stop('theta_estimation_fun ', theta_estimation_fun, ' unknown - only theta.ml and theta.mm supported at the moment') ) fit2 <- 0 try(fit2 <- glm(as.formula(model_str), data = data, family = negative.binomial(theta=theta)), silent=TRUE) if (inherits(x = fit2, what = 'numeric')) { return(c(theta, fit$coefficients)) } else { return(c(theta, fit2$coefficients)) } }) return(t(par_mat)) } fit_nb <- function(umi, model_str, data) { par_mat <- apply(umi, 1, function(y) { fit <- 0 try(fit <- glm.nb(as.formula(model_str), data = data), silent=TRUE) if (inherits(x = fit, what = 'numeric')) { fit <- glm(as.formula(model_str), data = data, family = poisson) fit$theta <- as.numeric(x = suppressWarnings(theta.ml(y = y, mu = fit$fitted))) } return(c(fit$theta, fit$coefficients)) }) return(t(par_mat)) } # allow_inf_theta: if FALSE, replace theta by min(theta, rowmeans(mu)/1e-4) # else allow theta = Inf (poisson) fit_glmGamPoi <- function(umi, model_str, data, allow_inf_theta=FALSE) { fit <- glmGamPoi::glm_gp(data = umi, design = as.formula(gsub("y", "", model_str)), col_data = data, size_factors = FALSE) fit$theta <- 1 / fit$overdispersions if (!allow_inf_theta){ fit$theta <- pmin(1 / fit$overdispersions, rowMeans(fit$Mu) / 1e-4) } colnames(fit$Beta)[match(x = 'Intercept', colnames(fit$Beta))] <- "(Intercept)" return(cbind(fit$theta, fit$Beta)) } fit_overdisp_mle <- function(umi, mu, intercept, slope){ fit <- glmGamPoi::overdispersion_mle(umi, mu, model_matrix = NULL, do_cox_reid_adjustment = TRUE, #!is.null(model_matrix), global_estimate = FALSE, subsample = FALSE, max_iter = 200, verbose = FALSE) theta <- 1 / fit$estimate model_pars <- cbind(theta, intercept, slope) colnames(model_pars) <- c("theta", "(Intercept)", "log_umi") return (model_pars) } # Use log_umi as offset using glmGamPoi fit_glmGamPoi_offset <- function(umi, model_str, data, allow_inf_theta=FALSE) { # only intercept varies new_formula <- gsub("y", "", model_str) # remove log_umi from model formula if it is with batch variables new_formula <- gsub("\\+ log_umi", "", new_formula) # replace log_umi with 1 if it is the only formula new_formula <- gsub("log_umi", "1", new_formula) log10_umi <- data$log_umi stopifnot(!is.null(log10_umi)) log_umi <- log(10^log10_umi) fit <- glmGamPoi::glm_gp(data = umi, design = as.formula(new_formula), col_data = data, offset = log_umi, size_factors = FALSE) fit$theta <- 1 / fit$overdispersions if (!allow_inf_theta){ fit$theta <- pmin(1 / fit$overdispersions, rowMeans(fit$Mu) / 1e-4) } model_pars <- cbind(fit$theta, fit$Beta[, "Intercept"], rep(log(10), nrow(umi))) dimnames(model_pars) <- list(rownames(umi), c('theta', '(Intercept)', 'log_umi')) return(model_pars) }sctransform/R/data.R0000644000176200001440000000155114167140301014047 0ustar liggesusers#' Peripheral Blood Mononuclear Cells (PBMCs) #' #' UMI counts for a subset of cells freely available from 10X Genomics #' #' @format A sparse matrix (dgCMatrix, see Matrix package) of molecule counts. #' There are 914 rows (genes) and 283 columns (cells). This is a downsampled #' version of a 3K PBMC dataset available from 10x Genomics. #' #' @source \url{https://support.10xgenomics.com/single-cell-gene-expression/datasets/1.1.0/pbmc3k} "pbmc" #' Transformation functions for umify #' #' The functions have been trained on various public data sets and relate quantile #' values to log-counts. Here the expected values at various points are given. #' #' @format A list of length two. The first element is a data frame with group, quantile and #' log-counts values. The second element is a vector of breaks to be used with cut to group #' observations. "umify_data" sctransform/R/denoise.R0000644000176200001440000002262314167140301014567 0ustar liggesusers #' Smooth data by PCA #' #' Perform PCA, identify significant dimensions, and reverse the rotation using only significant dimensions. #' #' @param x A data matrix with genes as rows and cells as columns #' @param elbow_th The fraction of PC sdev drop that is considered significant; low values will lead to more PCs being used #' @param dims_use Directly specify PCs to use, e.g. 1:10 #' @param max_pc Maximum number of PCs computed #' @param do_plot Plot PC sdev and sdev drop #' @param scale. Boolean indicating whether genes should be divided by standard deviation after centering and prior to PCA #' #' @return Smoothed data #' #' @importFrom graphics par plot abline #' #' @export #' #' @examples #' \donttest{ #' vst_out <- vst(pbmc) #' y_smooth <- smooth_via_pca(vst_out$y, do_plot = TRUE) #' } #' smooth_via_pca <- function(x, elbow_th = 0.025, dims_use = NULL, max_pc = 100, do_plot = FALSE, scale. = FALSE) { requireNamespace('irlba', quietly = TRUE) # perform pca if (scale.) { scale. <- apply(x, 1, 'sd') } else { scale. <- rep(1, nrow(x)) } pca <- irlba::prcomp_irlba(t(x), n = max_pc, center = TRUE, scale. = scale.) if (is.null(dims_use)) { pca_sdev_drop <- c(diff(pca$sdev), 0) / -pca$sdev max_dim <- rev(which(pca_sdev_drop > elbow_th))[1] dims_use <- 1:max_dim if (do_plot) { par(mfrow=c(1,2)) plot(pca$sdev) abline(v = max_dim + 0.5, col='red') plot(pca_sdev_drop) abline(h = elbow_th, col='red') abline(v = max_dim + 0.5, col='red') par(mfrow=c(1,1)) } } new_x <- pca$rotation[, dims_use] %*% t(pca$x[, dims_use]) * pca$scale + pca$center dimnames(new_x) <- dimnames(x) return(new_x) } #' Correct data by setting all latent factors to their median values and reversing the regression model #' #' @param x A list that provides model parameters and optionally meta data; use output of vst function #' @param data The name of the entry in x that holds the data #' @param cell_attr Provide cell meta data holding latent data info #' @param as_is Use cell attributes as is and do not use the median; set to TRUE if you want to #' manually control the values of the latent factors; default is FALSE #' @param do_round Round the result to integers #' @param do_pos Set negative values in the result to zero #' @param scale_factor Replace all values of UMI in the regression model by this value. Default is NA #' which uses median of total UMI as the latent factor. #' @param verbosity An integer specifying whether to show only messages (1), messages and progress bars (2) or nothing (0) while the function is running; default is 2 #' @param verbose Deprecated; use verbosity instead #' @param show_progress Deprecated; use verbosity instead #' #' @return Corrected data as UMI counts #' #' @export #' #' @examples #' \donttest{ #' vst_out <- vst(pbmc, return_cell_attr = TRUE) #' umi_corrected <- correct(vst_out) #' } #' correct <- function(x, data = 'y', cell_attr = x$cell_attr, as_is = FALSE, do_round = TRUE, do_pos = TRUE, scale_factor=NA, verbosity = 2, verbose = NULL, show_progress = NULL) { # Take care of deprecated arguments if (!is.null(verbose)) { warning("The 'verbose' argument is deprecated as of v0.3. Use 'verbosity' instead. (in sctransform::vst)", immediate. = TRUE, call. = FALSE) verbosity <- as.numeric(verbose) } if (!is.null(show_progress)) { warning("The 'show_progress' argument is deprecated as of v0.3. Use 'verbosity' instead. (in sctransform::vst)", immediate. = TRUE, call. = FALSE) if (show_progress) { verbosity <- 2 } else { verbosity <- min(verbosity, 1) } } if (is.character(data)) { data <- x[[data]] } # when correcting, set all latent variables to median values if (!as_is) { cell_attr[, x$arguments$latent_var] <- apply(cell_attr[, x$arguments$latent_var, drop=FALSE], 2, function(x) rep(median(x), length(x))) } if (!is.na(scale_factor) && !is.numeric(scale_factor)){ stop("`scale_factor` should be numeric") } if (!is.na(scale_factor)){ if (verbosity>0){ message(paste("Setting log_umi for correcting counts to", scale_factor)) } cell_attr[, "log_umi"] <- log10(scale_factor) } regressor_data <- model.matrix(as.formula(gsub('^y', '', x$model_str)), cell_attr) genes <- rownames(data) bin_size <- x$arguments$bin_size bin_ind <- ceiling(x = 1:length(x = genes) / bin_size) max_bin <- max(bin_ind) if (verbosity > 0) { message('Computing corrected count matrix for ', length(genes), ' genes') } if (verbosity > 1) { pb <- txtProgressBar(min = 0, max = max_bin, style = 3) } corrected_data <- matrix(NA_real_, length(genes), nrow(regressor_data), dimnames = list(genes, rownames(regressor_data))) for (i in 1:max_bin) { genes_bin <- genes[bin_ind == i] pearson_residual <- data[genes_bin, ] coefs <- x$model_pars_fit[genes_bin, -1] theta <- x$model_pars_fit[genes_bin, 1] mu <- exp(tcrossprod(coefs, regressor_data)) variance <- mu + mu^2 / theta corrected_data[genes_bin, ] <- mu + pearson_residual * sqrt(variance) if (verbosity > 1) { setTxtProgressBar(pb, i) } } if (verbosity > 1) { close(pb) } if (do_round) { corrected_data <- round(corrected_data, 0) } if (do_pos) { corrected_data[corrected_data < 0] <- 0 } return(corrected_data) } #' Correct data by setting all latent factors to their median values and reversing the regression model #' #' This version does not need a matrix of Pearson residuals. It takes the count matrix as input and #' calculates the residuals on the fly. The corrected UMI counts will be rounded to the nearest #' integer and negative values clipped to 0. #' #' @param x A list that provides model parameters and optionally meta data; use output of vst function #' @param umi The count matrix #' @param cell_attr Provide cell meta data holding latent data info #' @param scale_factor Replace all values of UMI in the regression model by this value. Default is NA #' which uses median of total UMI as the latent factor. #' @param verbosity An integer specifying whether to show only messages (1), messages and progress bars (2) or nothing (0) while the function is running; default is 2 #' @param verbose Deprecated; use verbosity instead #' @param show_progress Deprecated; use verbosity instead #' #' @return Corrected data as UMI counts #' #' @importFrom methods as #' #' @export #' #' @examples #' \donttest{ #' vst_out <- vst(pbmc, return_cell_attr = TRUE) #' umi_corrected <- correct_counts(vst_out, pbmc) #' } #' correct_counts <- function(x, umi, cell_attr = x$cell_attr, scale_factor = NA, verbosity = 2, verbose = NULL, show_progress = NULL) { # Take care of deprecated arguments if (!is.null(verbose)) { warning("The 'verbose' argument is deprecated as of v0.3. Use 'verbosity' instead. (in sctransform::vst)", immediate. = TRUE, call. = FALSE) verbosity <- as.numeric(verbose) } if (!is.null(show_progress)) { warning("The 'show_progress' argument is deprecated as of v0.3. Use 'verbosity' instead. (in sctransform::vst)", immediate. = TRUE, call. = FALSE) if (show_progress) { verbosity <- 2 } else { verbosity <- min(verbosity, 1) } } regressor_data_orig <- model.matrix(as.formula(gsub('^y', '', x$model_str)), cell_attr) # when correcting, set all latent variables to median values cell_attr[, x$arguments$latent_var] <- apply(cell_attr[, x$arguments$latent_var, drop=FALSE], 2, function(x) rep(median(x), length(x))) if (!is.na(scale_factor) && !is.numeric(scale_factor)){ stop("`scale_factor` should be numeric") } if (!is.na(scale_factor)){ if (verbosity>0){ message(paste("Setting log_umi for correcting counts to", scale_factor)) } cell_attr[, "log_umi"] <- log10(scale_factor) } regressor_data <- model.matrix(as.formula(gsub('^y', '', x$model_str)), cell_attr) genes <- rownames(umi)[rownames(umi) %in% rownames(x$model_pars_fit)] bin_size <- x$arguments$bin_size bin_ind <- ceiling(x = 1:length(x = genes) / bin_size) max_bin <- max(bin_ind) if (verbosity > 0) { message('Computing corrected UMI count matrix') } if (verbosity > 1) { pb <- txtProgressBar(min = 0, max = max_bin, style = 3) } #corrected_data <- matrix(NA_real_, length(genes), nrow(regressor_data), dimnames = list(genes, rownames(regressor_data))) corrected_data <- list() for (i in 1:max_bin) { genes_bin <- genes[bin_ind == i] coefs <- x$model_pars_fit[genes_bin, -1, drop=FALSE] theta <- x$model_pars_fit[genes_bin, 1] # get pearson residuals mu <- exp(tcrossprod(coefs, regressor_data_orig)) variance <- mu + mu^2 / theta y <- as.matrix(umi[genes_bin, , drop=FALSE]) pearson_residual <- (y - mu) / sqrt(variance) # generate output mu <- exp(tcrossprod(coefs, regressor_data)) variance <- mu + mu^2 / theta y.res <- mu + pearson_residual * sqrt(variance) y.res <- round(y.res, 0) y.res[y.res < 0] <- 0 corrected_data[[length(corrected_data) + 1]] <- as(y.res, Class = 'dgCMatrix') if (verbosity > 1) { setTxtProgressBar(pb, i) } } if (verbosity > 1) { close(pb) } corrected_data <- do.call(what = rbind, args = corrected_data) return(corrected_data) } reverse_regression <- function(pearson_residual, theta, coefs, data) { mu <- exp(data %*% coefs)[, 1] variance <- mu + mu^2 / theta return(mu + pearson_residual * sqrt(variance)) } sctransform/R/RcppExports.R0000644000176200001440000000351114167143520015433 0ustar liggesusers# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 row_mean_dgcmatrix <- function(matrix) { .Call('_sctransform_row_mean_dgcmatrix', PACKAGE = 'sctransform', matrix) } row_mean_grouped_dgcmatrix <- function(matrix, group, shuffle) { .Call('_sctransform_row_mean_grouped_dgcmatrix', PACKAGE = 'sctransform', matrix, group, shuffle) } row_gmean_dgcmatrix <- function(matrix, eps) { .Call('_sctransform_row_gmean_dgcmatrix', PACKAGE = 'sctransform', matrix, eps) } row_gmean_grouped_dgcmatrix <- function(matrix, group, eps, shuffle) { .Call('_sctransform_row_gmean_grouped_dgcmatrix', PACKAGE = 'sctransform', matrix, group, eps, shuffle) } row_nonzero_count_dgcmatrix <- function(matrix) { .Call('_sctransform_row_nonzero_count_dgcmatrix', PACKAGE = 'sctransform', matrix) } row_nonzero_count_grouped_dgcmatrix <- function(matrix, group) { .Call('_sctransform_row_nonzero_count_grouped_dgcmatrix', PACKAGE = 'sctransform', matrix, group) } row_var_dgcmatrix <- function(x, i, rows, cols) { .Call('_sctransform_row_var_dgcmatrix', PACKAGE = 'sctransform', x, i, rows, cols) } grouped_mean_diff_per_row <- function(x, group, shuffle) { .Call('_sctransform_grouped_mean_diff_per_row', PACKAGE = 'sctransform', x, group, shuffle) } mean_boot <- function(x, N, S) { .Call('_sctransform_mean_boot', PACKAGE = 'sctransform', x, N, S) } mean_boot_grouped <- function(x, group, N, S) { .Call('_sctransform_mean_boot_grouped', PACKAGE = 'sctransform', x, group, N, S) } distribution_shift <- function(x) { .Call('_sctransform_distribution_shift', PACKAGE = 'sctransform', x) } qpois_reg <- function(X, Y, tol, maxiters, minphi, returnfit) { .Call('_sctransform_qpois_reg', PACKAGE = 'sctransform', X, Y, tol, maxiters, minphi, returnfit) } sctransform/R/plotting.R0000644000176200001440000002615314167140301015003 0ustar liggesusers#' Plot estimated and fitted model parameters #' #' @param vst_out The output of a vst run #' @param xaxis Variable to plot on X axis; default is "gmean" #' @param show_theta Whether to show the theta parameter; default is FALSE (only the overdispersion factor is shown) #' @param show_var Whether to show the average model variance; default is FALSE #' @param verbosity An integer specifying whether to show only messages (1), messages and progress bars (2) or nothing (0) while the function is running; default is 2 #' @param verbose Deprecated; use verbosity instead #' @param show_progress Deprecated; use verbosity instead #' #' @return A ggplot object #' #' @import ggplot2 #' @import reshape2 #' #' @export #' #' @examples #' \donttest{ #' vst_out <- vst(pbmc, return_gene_attr = TRUE) #' plot_model_pars(vst_out) #' } #' plot_model_pars <- function(vst_out, xaxis="gmean", show_theta = FALSE, show_var = FALSE, verbosity = 2, verbose = NULL, show_progress = NULL) { # Take care of deprecated arguments if (!is.null(verbose)) { warning("The 'verbose' argument is deprecated as of v0.3. Use 'verbosity' instead. (in sctransform::vst)", immediate. = TRUE, call. = FALSE) verbosity <- as.numeric(verbose) } if (!is.null(show_progress)) { warning("The 'show_progress' argument is deprecated as of v0.3. Use 'verbosity' instead. (in sctransform::vst)", immediate. = TRUE, call. = FALSE) if (show_progress) { verbosity <- 2 } else { verbosity <- min(verbosity, 1) } } if (! 'gmean' %in% names(vst_out$gene_attr)) { stop('vst_out must contain a data frame named gene_attr with a column named gmean (perhaps call vst with return_gene_attr = TRUE)') } # first handle the per-gene estimates mp <- get_model_par_mat(vst_out, model_pars = vst_out$model_pars, use_nonreg = TRUE, show_theta = show_theta, show_var = show_var, verbosity = verbosity) ordered_par_names <- colnames(mp) # second the regularized estimates mp_fit <- get_model_par_mat(vst_out, model_pars = vst_out$model_pars_fit, use_nonreg = FALSE, show_theta = show_theta, show_var = show_var, verbosity = verbosity) mpnr <- vst_out$model_pars_nonreg if (!is.null(dim(mpnr))) { colnames(mpnr) <- paste0('nonreg:', colnames(mpnr)) mp <- cbind(mp, mpnr) ordered_par_names <- c(ordered_par_names, colnames(mpnr)) } # show estimated and regularized parameters df <- melt(mp, varnames = c('gene', 'parameter'), as.is = TRUE) df$parameter <- factor(df$parameter, levels = ordered_par_names) df_fit <- melt(mp_fit, varnames = c('gene', 'parameter'), as.is = TRUE) df_fit$parameter <- factor(df_fit$parameter, levels = ordered_par_names) df$is_outl <- vst_out$model_pars_outliers df$type <- 'single gene estimate' df_fit$type <- 'regularized' df_fit$is_outl <- FALSE if (startsWith(x = vst_out$arguments$method, prefix = 'offset') | (xaxis=="amean")) { df$x <- vst_out$gene_attr[df$gene, 'amean'] df_fit$x <- vst_out$gene_attr[df_fit$gene, 'amean'] xlab <- 'Arithmetic mean of gene [log10]' } else { df$x <- vst_out$gene_attr[df$gene, 'gmean'] df_fit$x <- vst_out$gene_attr[df_fit$gene, 'gmean'] xlab <- 'Geometric mean of gene [log10]' } df_plot <- rbind(df, df_fit) df_plot$parameter <- factor(df_plot$parameter, levels = ordered_par_names) if (!vst_out$arguments$do_regularize || startsWith(x = vst_out$arguments$method, prefix = 'offset')) { df_plot <- df_plot[df_plot$type == 'single gene estimate', ] legend_pos <- 'none' } else { legend_pos <- 'bottom' } g <- ggplot(df_plot, aes_(x=~log10(x), y=~value, color=~type)) + geom_point(data=df, aes_(shape=~is_outl), size=0.5, alpha=0.5) + scale_shape_manual(values=c(16, 4), guide = FALSE) + geom_point(data=df_fit, size=0.66, alpha=0.5, shape=16) + facet_wrap(~ parameter, scales = 'free_y', ncol = ncol(mp)) + theme(legend.position = legend_pos) + xlab(label = xlab) return(g) } # helper function to plot model parameters get_model_par_mat <- function(vst_out, model_pars, use_nonreg, show_theta = FALSE, show_var = FALSE, verbosity = 2) { mp <- model_pars # transform theta to overdispersion factor if (startsWith(x = vst_out$arguments$method, prefix = 'offset')) { mp[, 1] <- log10(1 + vst_out$gene_attr[rownames(mp), 'amean'] / mp[, 'theta']) } else { mp[, 1] <- log10(1 + vst_out$gene_attr[rownames(mp), 'gmean'] / mp[, 'theta']) } colnames(mp)[1] <- 'log10(od_factor)' ordered_par_names <- colnames(mp)[c(2:ncol(mp), 1)] if (show_theta) { mp <- cbind(mp, log10(model_pars[, 'theta'])) colnames(mp)[ncol(mp)] <- 'log10(theta)' ordered_par_names <- c(ordered_par_names, 'log10(theta)') } if (show_var) { mp <- cbind(mp, log10(get_model_var(vst_out, use_nonreg = use_nonreg, verbosity = verbosity))) colnames(mp)[ncol(mp)] <- 'log10(model var)' ordered_par_names <- c(ordered_par_names, 'log10(model var)') } return(mp[, ordered_par_names]) } # helper function to plot model fit for a single gene # returns list with mean, sd, pearson residual #' @importFrom stats model.matrix get_nb_fit <- function(x, umi, gene, cell_attr, as_poisson = FALSE) { regressor_data <- model.matrix(as.formula(gsub('^y', '', x$model_str)), cell_attr) coefs <- x$model_pars_fit[gene, -1, drop=FALSE] theta <- x$model_pars_fit[gene, 1] if (as_poisson) { theta <- Inf } mu <- exp(coefs %*% t(regressor_data))[1, ] sd <- sqrt(mu + mu^2 / theta) res <- (umi[gene, ] - mu) / sd res <- pmin(res, x$arguments$res_clip_range[2]) res <- pmax(res, x$arguments$res_clip_range[1]) ret_df <- data.frame(mu = mu, sd = sd, res = res) # in case we have individual (non-regularized) parameters if (gene %in% rownames(x$model_pars)) { coefs <- x$model_pars[gene, -1, drop=FALSE] theta <- x$model_pars[gene, 1] ret_df$mu_nr <- exp(coefs %*% t(regressor_data))[1, ] ret_df$sd_nr <- sqrt(ret_df$mu_nr + ret_df$mu_nr^2 / theta) ret_df$res_nr <- (umi[gene, ] - ret_df$mu_nr) / ret_df$sd_nr ret_df$res_nr <- pmin(ret_df$res_nr, x$arguments$res_clip_range[2]) ret_df$res_nr <- pmax(ret_df$res_nr, x$arguments$res_clip_range[1]) } else { ret_df$mu_nr <- NA_real_ ret_df$sd_nr <- NA_real_ ret_df$res_nr <- NA_real_ } return(ret_df) } #' Plot observed UMI counts and model #' #' @param x The output of a vst run #' @param umi UMI count matrix #' @param goi Vector of genes to plot #' @param x_var Cell attribute to use on x axis; will be taken from x$arguments$latent_var[1] by default #' @param cell_attr Cell attributes data frame; will be taken from x$cell_attr by default #' @param do_log Log10 transform the UMI counts in plot #' @param show_fit Show the model fit #' @param show_nr Show the non-regularized model (if available) #' @param plot_residual Add panels for the Pearson residuals #' @param batches Manually specify a batch variable to break up the model plot in segments #' @param as_poisson Fix model parameter theta to Inf, effectively showing a Poisson model #' @param arrange_vertical Stack individual ggplot objects or place side by side #' @param show_density Draw 2D density lines over points #' @param gg_cmds Additional ggplot layer commands #' #' @return A ggplot object #' #' @import ggplot2 #' @import reshape2 #' @importFrom gridExtra grid.arrange #' @importFrom stats bw.nrd0 #' #' @export #' #' @examples #' \donttest{ #' vst_out <- vst(pbmc, return_cell_attr = TRUE) #' plot_model(vst_out, pbmc, 'EMC4') #' } #' plot_model <- function(x, umi, goi, x_var = x$arguments$latent_var[1], cell_attr = x$cell_attr, do_log = TRUE, show_fit = TRUE, show_nr = FALSE, plot_residual = FALSE, batches = NULL, as_poisson = FALSE, arrange_vertical = TRUE, show_density = FALSE, gg_cmds = NULL) { if (is.null(batches)) { if (!is.null(x$arguments$batch_var)) { batches <- cell_attr[, x$arguments$batch_var] } else { batches <- rep(1, nrow(cell_attr)) } } df_list <- list() for (gene in goi) { nb_fit <- get_nb_fit(x, umi, gene, cell_attr, as_poisson) nb_fit$x <- cell_attr[, x_var] nb_fit$y <- umi[gene, ] nb_fit$batch <- batches nb_fit$gene <- gene nb_fit$ymin <- nb_fit$mu - nb_fit$sd nb_fit$ymax <- nb_fit$mu + nb_fit$sd nb_fit$ymin_nr <- nb_fit$mu_nr - nb_fit$sd_nr nb_fit$ymax_nr <- nb_fit$mu_nr + nb_fit$sd_nr if (do_log) { nb_fit$y <- log10(nb_fit$y + 1) nb_fit$mu <- log10(nb_fit$mu + 1) nb_fit$mu_nr <- log10(nb_fit$mu_nr + 1) nb_fit$ymin <- log10(pmax(nb_fit$ymin, 0) + 1) nb_fit$ymax <- log10(pmax(nb_fit$ymax, 0) + 1) nb_fit$ymin_nr <- log10(pmax(nb_fit$ymin_nr, 0) + 1) nb_fit$ymax_nr <- log10(pmax(nb_fit$ymax_nr, 0) + 1) } df_list[[length(df_list) + 1]] <- nb_fit[order(nb_fit$x), ] } df <- do.call(rbind, df_list) df$gene <- factor(df$gene, ordered=TRUE, levels=unique(df$gene)) g <- ggplot(df, aes_(~x, ~y)) + geom_point(alpha=0.5, shape=16) if (show_density) { bandwidths <- c(bw.nrd0(g$data$x), bw.nrd0(g$data$y)) g <- g + geom_density_2d(color = 'lightblue', size=0.5, h = bandwidths, contour_var = "ndensity") } if (show_fit) { for (b in unique(df$batch)) { g <- g + geom_line(data = df[df$batch == b, ], aes_(~x, ~mu), color='deeppink', size = 1) + geom_ribbon(data = df[df$batch == b, ], aes_(x = ~x, ymin = ~ymin, ymax = ~ymax), alpha = 0.5, fill='deeppink') } } if (show_nr) { for (b in unique(df$batch)) { g <- g + geom_line(aes_(~x, ~mu_nr), color='blue', size = 1) + geom_ribbon(aes_(x = ~x, ymin = ~ymin_nr, ymax = ~ymax_nr), alpha = 0.5, fill='blue') } } g <- g + facet_grid(~gene) + xlab(paste('Cell', x_var)) + ylab('Gene UMI counts') if (do_log) { g <- g + ylab('Gene log10(UMI + 1)') } g <- g + gg_cmds if (length(goi) == 1) { g <- g + theme(strip.text = element_blank()) } if (plot_residual) { ga_col = 1 res_range <- range(df$res) g2 <- ggplot(df, aes_(~x, ~res)) + geom_point(alpha = 0.5, shape=16) + coord_cartesian(ylim = res_range) + facet_grid(~gene) + xlab(x) + ylab('Pearson residual') + xlab(paste('Cell', x_var)) + gg_cmds + theme(strip.text = element_blank()) # strip.background = element_blank(), if (show_density) { g2 <- g2 + geom_density_2d(color = 'lightblue', size=0.5) } if (show_nr) { g3 <- ggplot(df, aes_(~x, ~res_nr)) + geom_point(alpha = 0.5, shape=16) + coord_cartesian(ylim = res_range) + facet_grid(~gene) + xlab(x) + ylab('Pearson residual non-reg.') + xlab(paste('Cell', x_var)) + gg_cmds + theme(strip.text = element_blank()) # strip.background = element_blank(), if (show_density) { g3 <- g3 + geom_density_2d(color = 'lightblue', size=0.5) } if (!arrange_vertical) { ga_col = 3 } return(grid.arrange(g, g2, g3, ncol=ga_col)) } else { if (!arrange_vertical) { ga_col = 2 } return(grid.arrange(g, g2, ncol=ga_col)) } } return(g) } sctransform/R/differential_expression.R0000644000176200001440000012047614167140301020061 0ustar liggesusers#' Compare gene expression between two groups #' #' @param x A list that provides model parameters and optionally meta data; use output of vst function #' @param umi A matrix of UMI counts with genes as rows and cells as columns #' @param group A vector indicating the groups #' @param val1 A vector indicating the values of the group vector to treat as group 1 #' @param val2 A vector indicating the values of the group vector to treat as group 2 #' @param method Either 'LRT' for likelihood ratio test, or 't_test' for t-test #' @param bin_size Number of genes that are processed between updates of progress bar #' @param cell_attr Data frame of cell meta data #' @param y Only used if methtod = 't_test', this is the residual matrix; default is x$y #' @param min_cells A gene has to be detected in at least this many cells in at least one of the groups being compared to be tested #' @param weighted Balance the groups by using the appropriate weights #' @param randomize Boolean indicating whether to shuffle group labels - only set to TRUE when testing methods #' @param verbosity An integer specifying whether to show only messages (1), messages and progress bars (2) or nothing (0) while the function is running; default is 2 #' @param verbose Deprecated; use verbosity instead #' @param show_progress Deprecated; use verbosity instead #' #' @return Data frame of results #' #' @import Matrix #' @importFrom future.apply future_lapply #' @importFrom stats model.matrix p.adjust pchisq #' compare_expression <- function(x, umi, group, val1, val2, method = 'LRT', bin_size = 256, cell_attr = x$cell_attr, y = x$y, min_cells = 5, weighted = TRUE, randomize = FALSE, verbosity = 2, verbose = NULL, show_progress = NULL) { # Take care of deprecated arguments if (!is.null(verbose)) { warning("The 'verbose' argument is deprecated as of v0.3. Use 'verbosity' instead. (in sctransform::vst)", immediate. = TRUE, call. = FALSE) verbosity <- as.numeric(verbose) } if (!is.null(show_progress)) { warning("The 'show_progress' argument is deprecated as of v0.3. Use 'verbosity' instead. (in sctransform::vst)", immediate. = TRUE, call. = FALSE) if (show_progress) { verbosity <- 2 } else { verbosity <- min(verbosity, 1) } } if (! method %in% c('LRT', 'LRT_free', 'LRT_reg', 't_test')) { stop('method needs to be either \'LRT\', \'LRT_free\', \'LRT_reg\' or \'t_test\'') } if ('DE_test_group' %in% colnames(cell_attr)) { stop('DE_test_group cannot be a column name in cell attributes') } sel1 <- which(group %in% val1) sel2 <- which(group %in% val2) # randomize # if (randomize) { # sel.rnd <- sample(x = c(sel1, sel2), replace = FALSE) # sel1 <- sel.rnd[1:length(sel1)] # sel2 <- sel.rnd[(length(sel1)+1):length(sel.rnd)] # } use_cells <- c(sel1, sel2) group <- factor(c(rep(0, length(sel1)), rep(1, length(sel2)))) cell_attr <- cell_attr[use_cells, ] cell_attr$DE_test_group <- group if (weighted) { weights <- c(rep(1/length(sel1), length(sel1)), rep(1/length(sel2), length(sel2))) #weights <- c(rep(1/length(sel2), length(sel1)), rep(1/length(sel1), length(sel2))) weights <- weights / sum(weights) * length(use_cells) } else { weights <- rep(1, length(use_cells)) } print(table(weights)) genes <- rownames(x$model_pars_fit)[rownames(x$model_pars_fit) %in% rownames(umi)] cells_group1 <- rowSums(umi[genes, sel1] > 0) cells_group2 <- rowSums(umi[genes, sel2] > 0) genes <- genes[cells_group1 >= min_cells | cells_group2 >= min_cells] if (verbosity > 0) { message('Testing for differential gene expression between two groups') message('Cells in group 1: ', length(sel1)) message('Cells in group 2: ', length(sel2)) message('Testing ', length(genes), ' genes') } regressor_data <- model.matrix(as.formula(gsub('^y', '', x$model_str)), cell_attr) if (!is.null(dim(x$model_pars_nonreg))) { regressor_data_nonreg <- model.matrix(as.formula(gsub('^y', '', x$model_str_nonreg)), cell_attr) regressor_data <- cbind(regressor_data, regressor_data_nonreg) } # process genes in batches bin_ind <- ceiling(x = 1:length(x = genes) / bin_size) max_bin <- max(bin_ind) if (verbosity > 1) { pb <- txtProgressBar(min = 0, max = max_bin, style = 3) } res <- list() for (i in 1:max_bin) { genes_bin <- genes[bin_ind == i] if (method == 't_test') { bin_res <- future_lapply( X = genes_bin, FUN = function(gene) {model_comparison_ttest(y[gene, use_cells], group)}, future.seed = TRUE) } if (method == 'LRT') { mu <- x$model_pars_fit[genes_bin, -1, drop=FALSE] %*% t(regressor_data) # in log space y <- as.matrix(umi[genes_bin, use_cells]) bin_res <- future_lapply( X = genes_bin, FUN = function(gene) { model_comparison_lrt(y[gene, ], mu[gene, ], x$model_pars_fit[gene, 'theta'], group, weights)}, future.seed = TRUE) } if (method == 'LRT_reg') { LB <- min(x$genes_log_mean_step1) UB <- max(x$genes_log_mean_step1) y <- as.matrix(umi[genes_bin, use_cells, drop=FALSE]) if (randomize) { y <- t(apply(y, 1, sample)) #y <- t(apply(y, 1, function(x) ceiling(pmax(0, rnorm(n = length(x), mean = 0, sd = 2))))) } # get estimated model parameters and expected counts for all cells combined #y_log_mean <- log10(base::rowMeans(y)) y_log_mean <- log10(apply(y, 1, function(x) mean(x * weights))) y_log_mean <- pmax(LB, pmin(y_log_mean, UB)) names(y_log_mean) <- rownames(y) mp <- reg_pars(x$genes_log_mean_step1, x$model_pars, y_log_mean, x$arguments$bw_adjust) if (!is.null(dim(x$model_pars_nonreg))) { mp <- cbind(mp, x$model_pars_nonreg[genes_bin, ]) } mu <- exp(tcrossprod(mp[, -1, drop=FALSE], regressor_data)) sq_dev <- sapply(1:nrow(mu), function(i) sq_deviance_residual(y[i, ], mu[i, ], mp[i, 'theta'])) # same per group y0 <- y[, group==0] y_log_mean0 <- log10(base::rowMeans(y0)) y_log_mean0 <- pmax(LB, pmin(y_log_mean0, UB)) names(y_log_mean0) <- rownames(y) mp0 <- reg_pars(x$genes_log_mean_step1, x$model_pars, y_log_mean0, x$arguments$bw_adjust) if (!is.null(dim(x$model_pars_nonreg))) { mp0 <- cbind(mp0, x$model_pars_nonreg[genes_bin, ]) } mu0 <- exp(tcrossprod(mp0[, -1, drop=FALSE], regressor_data[group==0, ])) sq_dev0 <- sapply(1:nrow(mu0), function(i) sq_deviance_residual(y0[i, ], mu0[i, ], mp0[i, 'theta'])) y1 <- y[, group==1] y_log_mean1 <- log10(base::rowMeans(y1)) y_log_mean1 <- pmax(LB, pmin(y_log_mean1, UB)) names(y_log_mean1) <- rownames(y) mp1 <- reg_pars(x$genes_log_mean_step1, x$model_pars, y_log_mean1, x$arguments$bw_adjust) if (!is.null(dim(x$model_pars_nonreg))) { mp1 <- cbind(mp1, x$model_pars_nonreg[genes_bin, ]) } mu1 <- exp(tcrossprod(mp1[, -1, drop=FALSE], regressor_data[group==1, ])) sq_dev1 <- sapply(1:nrow(mu1), function(i) sq_deviance_residual(y1[i, ], mu1[i, ], mp1[i, 'theta'])) #pvals <- pchisq(base::rowSums(cbind(sq_dev0, sq_dev1)) - base::rowSums(sq_dev), df = 1, lower.tail = FALSE) pvals <- pchisq(base::colSums(sq_dev * weights) - base::colSums(rbind(sq_dev0, sq_dev1) * weights), df = 3, lower.tail = FALSE) #fold_change <- log2(10 ^ (y_log_mean1 - y_log_mean0)) # tmp stuff for fold change mu0 <- tcrossprod(mp0[, -1, drop=FALSE], regressor_data) mu1 <- tcrossprod(mp1[, -1, drop=FALSE], regressor_data) fold_change <- apply(log2(exp(mu1 - mu0)), 1, mean) #if (max(fold_change) > 0.4) browser() if ('SON' %in% genes_bin) browser() bin_res <- list(cbind(pvals, fold_change)) } if (method == 'LRT_free') { y <- as.matrix(umi[genes_bin, use_cells]) # get estimated theta bw <- bw.SJ(x$genes_log_mean_step1) y_log_mean <- log10(base::rowMeans(y)) o <- order(y_log_mean) y_theta <- rep(NA_real_, nrow(y)) y_theta[o] <- 10 ^ ksmooth(x = x$genes_log_mean_step1, y = log10(x$model_pars[, 'theta']), x.points = y_log_mean, bandwidth = bw, kernel='normal')$y names(y_theta) <- genes_bin bin_res <- future_lapply( X = genes_bin, FUN = function(gene) { return(model_comparison_lrt_free3(gene, y[gene, ], y_theta[gene], x$model_str, cell_attr, group, weights, randomize)) }, future.seed = TRUE) } res[[i]] <- do.call(rbind, bin_res) if (verbosity > 1) { setTxtProgressBar(pb, i) } } if (verbosity > 1) { close(pb) } res <- do.call(rbind, res) rownames(res) <- genes colnames(res) <- c('p_value', 'log_fc') res <- as.data.frame(res) res$fdr <- p.adjust(res$p_value, method='fdr') res <- res[order(res$p_value, -abs(res$log_fc)), ] res$mean1 <- rowMeans(umi[rownames(res), sel1]) res$mean2 <- rowMeans(umi[rownames(res), sel2]) res$mean <- rowMeans(umi[rownames(res), use_cells]) res$mean_weighted <- (res$mean1 + res$mean2) / 2 return(res) } compare_expression_full <- function(umi, cell_attr, group, val1, val2, latent_var = c('log_umi'), batch_var = NULL, latent_var_nonreg = NULL, n_genes = 2000, method = 'poisson', bin_size = 256, min_cells = 3, bw_adjust = 2, min_frac = 0, verbosity = 2) { sel1 <- which(group %in% val1) sel2 <- which(group %in% val2) det1 <- rowMeans(umi[, sel1] > 0) det2 <- rowMeans(umi[, sel2] > 0) umi <- umi[det1 >= min_frac | det2 >= min_frac, ] cells1 <- rowSums(umi[, sel1] > 0) cells2 <- rowSums(umi[, sel2] > 0) umi <- umi[cells1 >= min_cells | cells2 >= min_cells, ] vst.out0 <- vst(umi = umi[, c(sel1, sel2)], cell_attr = cell_attr[c(sel1, sel2), ], latent_var = latent_var, batch_var = batch_var, latent_var_nonreg = latent_var_nonreg, n_genes = n_genes, n_cells = NULL, method = method, do_regularize = TRUE, res_clip_range = c(-Inf, Inf), bin_size = bin_size, min_cells = min_cells, return_cell_attr = FALSE, return_gene_attr = FALSE, residual_type = 'deviance', bw_adjust = bw_adjust, verbosity = verbosity) vst.out1 <- vst(umi = umi[, sel1], cell_attr = cell_attr[sel1, ], latent_var = latent_var, batch_var = batch_var, latent_var_nonreg = latent_var_nonreg, n_genes = n_genes, n_cells = NULL, method = 'nb_theta_given', #method, do_regularize = TRUE, res_clip_range = c(-Inf, Inf), bin_size = bin_size, min_cells = min_cells, return_cell_attr = FALSE, return_gene_attr = FALSE, residual_type = 'deviance', bw_adjust = bw_adjust, theta_given = vst.out0$model_pars_fit[, 'theta'], verbosity = verbosity) vst.out2 <- vst(umi = umi[, sel2], cell_attr = cell_attr[sel2, ], latent_var = latent_var, batch_var = batch_var, latent_var_nonreg = latent_var_nonreg, n_genes = n_genes, n_cells = NULL, method = 'nb_theta_given', #method do_regularize = TRUE, res_clip_range = c(-Inf, Inf), bin_size = bin_size, min_cells = min_cells, return_cell_attr = FALSE, return_gene_attr = FALSE, residual_type = 'deviance', bw_adjust = bw_adjust, theta_given = vst.out0$model_pars_fit[, 'theta'], verbosity = verbosity) genes <- union(rownames(vst.out1$y), rownames(vst.out2$y)) genes_both <- intersect(rownames(vst.out1$y), rownames(vst.out2$y)) genes1 <- setdiff(rownames(vst.out1$y), genes_both) genes2 <- setdiff(rownames(vst.out2$y), genes_both) sq_dev_one <- base::rowSums(vst.out0$y[genes, ]^2 * 1) sq_dev_two <- rep(0, length(sq_dev_one)) names(sq_dev_two) <- genes sq_dev_two[rownames(vst.out1$y)] <- base::rowSums(vst.out1$y^2 * 1) sq_dev_two[rownames(vst.out2$y)] <- sq_dev_two[rownames(vst.out2$y)] + base::rowSums(vst.out2$y^2 * 1) pvals <- pchisq(sq_dev_one - sq_dev_two, df = 3, lower.tail = FALSE) # get log-fold change log_fc <- rep(NA_real_, length(sq_dev_one)) names(log_fc) <- genes regressor_data <- model.matrix(as.formula(gsub('^y', '', vst.out0$model_str)), cell_attr[c(sel1, sel2), ]) if (!is.null(dim(vst.out0$model_pars_nonreg))) { regressor_data_nonreg <- model.matrix(as.formula(gsub('^y', '', vst.out0$model_str_nonreg)), cell_attr[c(sel1, sel2), ]) regressor_data <- cbind(regressor_data, regressor_data_nonreg) } mp1 <- cbind(vst.out1$model_pars_fit, vst.out1$model_pars_nonreg) mp2 <- cbind(vst.out2$model_pars_fit, vst.out2$model_pars_nonreg) mu1 <- tcrossprod(mp1[genes_both, -1, drop=FALSE], regressor_data) mu2 <- tcrossprod(mp2[genes_both, -1, drop=FALSE], regressor_data) log_fc[genes_both] <- apply(log2(exp(mu2 - mu1)), 1, mean) log_fc[genes1] <- -Inf log_fc[genes2] <- Inf res <- data.frame(p_value = pvals, log_fc = log_fc) res$fdr <- p.adjust(res$p_value, method='fdr') res <- res[order(res$p_value, -abs(res$log_fc)), ] res$mean1 <- rowMeans(umi[rownames(res), sel1]) res$mean2 <- rowMeans(umi[rownames(res), sel2]) res$det1 <- rowMeans(umi[rownames(res), sel1] > 0) res$det2 <- rowMeans(umi[rownames(res), sel2] > 0) # tmp stuff # goi <- 'MALAT1' # y <- umi[goi, c(sel1, sel2)] # grp <- c(rep('A', length(sel1)), rep('B', length(sel2))) # df <- data.frame(y=y, log_umi=cell_attr[c(sel1, sel2), 'log_umi'], grp=grp) # mod0 <- glm.nb(y ~ log_umi, data = df) # mod1 <- glm.nb(y ~ log_umi + grp, data = df) # mod1 <- glm(y ~ log_umi + grp, data = df, family = negative.binomial(theta=mod0$theta)) # mod1 <- glm(y ~ log_umi:grp, data = df, family = negative.binomial(theta=mod0$theta)) return(res) } # function to get regularized model parameters reg_pars <- function(x, y.mat, x.points, bw.adjust) { bw <- bw.SJ(x) * bw.adjust o <- order(x.points) y.mat.out <- matrix(NA_real_, length(x.points), ncol(y.mat)) y.mat.out[o, 1] <- 10 ^ ksmooth(x = x, y = log10(y.mat[, 1]), x.points = x.points, bandwidth = bw*3, kernel='normal')$y for (i in 2:ncol(y.mat)) { y.mat.out[o, i] <- ksmooth(x = x, y = y.mat[, i], x.points = x.points, bandwidth = bw, kernel='normal')$y } colnames(y.mat.out) <- colnames(y.mat) rownames(y.mat.out) <- names(x.points) if (any(apply(is.na(y.mat.out), 1, any))) { browser() } return(y.mat.out) } #' @importFrom stats glm offset anova #' @importFrom MASS negative.binomial model_comparison_lrt <- function(y, offs, theta, group, weights = NULL) { fam <- negative.binomial(theta = theta) mod0 <- glm(y ~ 1 + offset(offs), family = fam, weights = weights) mod1 <- glm(y ~ 1 + offset(offs) + group, family = fam, weights = weights) p_val <- anova(mod0, mod1, test = 'LRT')$'Pr(>Chi)'[2] fold_change <- log2(exp(mod1$coefficients[2])) return(c(p_val, fold_change)) } # fixed overdispersion (theta) # different slopes model_comparison_lrt_free1 <- function(gene, y, theta, model_str, cell_attr, group, weights = NULL, randomize = FALSE) { if (randomize) { y <- sample(y) } mod0 <- glm(as.formula(model_str), data = cell_attr, family = negative.binomial(theta=theta), weights = weights) mod1_str <- paste0(model_str, ' + DE_test_group') mod1 <- glm(as.formula(mod1_str), data = cell_attr, family = negative.binomial(theta=theta), weights = weights) p_val <- anova(mod0, mod1, test = 'Chisq', dispersion = 1)$'Pr(>Chi)'[2] fold_change <- log2(exp(rev(mod1$coefficients)[1])) return(c(p_val, fold_change)) } # fixed overdispersion (theta) # fixed slopes #' @importFrom stats pchisq model_comparison_lrt_free2 <- function(gene, y, theta, model_str, cell_attr, group, weights = NULL, randomize = FALSE) { if (randomize) { y <- sample(y) } mod0 <- glm(as.formula(model_str), data = cell_attr, family = negative.binomial(theta=theta), weights = weights) offs <- log(mod0$fitted.values) - mod0$coefficients[1] mod1 <- glm(y ~ 1 + offset(offs) + group, family = negative.binomial(theta=theta), weights = weights) deviance_diff <- mod0$deviance - mod1$deviance p_val <- pchisq(q = deviance_diff, df = 1, lower.tail = FALSE) fold_change <- log2(exp(rev(mod1$coefficients)[1])) return(c(p_val, fold_change)) } # fixed overdispersion (theta) # different per-group slopes #' @importFrom stats predict model_comparison_lrt_free3 <- function(gene, y, theta, model_str, cell_attr, group, weights = NULL, randomize = FALSE) { if (randomize) { y <- sample(y) } mod0 <- glm(as.formula(model_str), data = cell_attr, family = negative.binomial(theta=theta), weights = weights) mod1_str <- paste(c('y ~', '(', gsub('^y ~ ', '', model_str), ') : DE_test_group + DE_test_group'), collapse=' ') mod1 <- glm(as.formula(mod1_str), data = cell_attr, family = negative.binomial(theta=theta), weights = weights) p_val <- anova(mod0, mod1, test = 'Chisq', dispersion = 1)$'Pr(>Chi)'[2] # to get fold change, predict data tmp.ca0 <- cell_attr tmp.ca0$DE_test_group <- factor(0) tmp.ca1 <- cell_attr tmp.ca1$DE_test_group <- factor(1) fold_change <- log2(median(predict(mod1, newdata = tmp.ca1, type = 'response')/predict(mod0, newdata = tmp.ca0, type = 'response'))) return(c(p_val, fold_change)) } model_comparison_lrt_free <- function(gene, y, theta, model_str, cell_attr, group, weights = NULL) { #print(gene) # model 0 #mod0 <- MASS::glm.nb(as.formula(model_str), data = cell_attr, weights = weights) #fit1 <- glm(as.formula(model_str), data = cell_attr, family = poisson, weights = weights) #theta1 <- as.numeric(x = theta.ml(y = y, mu = fit1$fitted, weights = weights)) #theta1b <- max(0.1, theta1) mod0 <- 0 try(mod0 <- glm(as.formula(model_str), data = cell_attr, family = negative.binomial(theta=theta), weights = weights), silent = TRUE) if (class(mod0)[1] == 'numeric') { print('mod0 failed') browser() } # model 1 #mod1_str <- paste(c('y ~', '(', gsub('^y ~ ', '', model_str), ') : DE_test_group'), collapse=' ') #mod1_str <- paste0(model_str, ' + DE_test_group') #mod1 <- MASS::glm.nb(as.formula(mod1_str), data = cell_attr, weights = weights) #fit2 <- glm(as.formula(mod1_str), data = cell_attr, family = poisson, weights = weights) #theta2 <- as.numeric(x = theta.ml(y = y, mu = fit2$fitted, weights = weights)) #theta2b <- max(0.1, theta2) #mod1 <- 0 #try(mod1 <- glm(as.formula(mod1_str), data = cell_attr, family = negative.binomial(theta=theta), weights = weights), silent = TRUE) #if (class(mod1)[1] == 'numeric') { # print('mod1 failed') # browser() #} #if (sum(y[group==0]) == 0 | sum(y[group==1]) == 0) { # print(theta1) # print(theta1b) # print(theta2) # print(theta2b) #print(anova(mod0, mod1, test = 'Chisq')) #browser() #} #print(mod0) #print(mod1) #print(anova(mod0, mod1, test = 'Chisq')) #p_val <- anova(mod0, mod1, test = 'Chisq')$'Pr(Chi)'[2] #p_val <- anova(mod0, mod1, test = 'Chisq')$'Pr(>Chi)'[2] #fold_change <- log2(exp(rev(mod1$coefficients)[1])) # alternative model 1 and p-value calculation #mod0.o <- glm(y ~ 1 + offset(log(mod0$fitted.values)), family = negative.binomial(theta=theta), weights = weights) #offs <- predict(mod0, newdata = cell_attr) - mod0$coefficients[1] offs <- log(mod0$fitted.values) - mod0$coefficients[1] mod1.o <- glm(y ~ 1 + offset(offs) + group, family = negative.binomial(theta=theta), weights = weights) grp.intercept <- mod1.o$coefficients if (grp.intercept[1] > grp.intercept[2]) { p_val <- summary(mod1.o)$coefficients[1, 4] fold_change <- log2(exp(diff(grp.intercept))) } else { p_val <- summary(mod1.o)$coefficients[2, 4] fold_change <- log2(exp(diff(grp.intercept))) } #mod1.o <- glm(y ~ 1 + offset(log(mod0$fitted.values)) + group, family = negative.binomial(theta=theta), weights = weights) #p_val <- anova(mod0.o, mod1.o, test = 'Chisq')$'Pr(>Chi)'[2] #deviance_diff <- sum(residuals(mod0, type='deviance')^2) - sum(residuals(mod1.o, type='deviance')^2) #p_val <- pchisq(q = deviance_diff, df = 1, lower.tail = FALSE) #fold_change <- log2(exp(rev(mod1.o$coefficients)[1])) # if (mean(y[group==0]) > 0.03 & mean(y[group==1]) == 0) { if (gene == 'OGFOD1') { browser() } return(c(p_val, fold_change)) } #' @importFrom stats t.test model_comparison_ttest <- function(y, group) { tt <- t.test(y ~ group) return(c(tt$p.value, diff(tt$estimate))) } #' Non-parametric differential expression test for sparse non-negative data #' #' @param y A matrix of counts; must be (or inherit from) class dgCMatrix; genes are row, #' cells are columns #' @param group_labels The group labels (e.g. cluster identities); #' will be converted to factor #' @param compare Specifies which groups to compare, see details; default is 'each_vs_rest' #' @param R The number of random permutations used to derive the p-values; default is 99 #' @param log2FC_th Threshold to remove genes from testing; absolute log2FC must be at least #' this large for a gene to be tested; default is \code{log2(1.2)} #' @param mean_th Threshold to remove genes from testing; gene mean must be at least this #' large for a gene to be tested; default is 0.05 #' @param cells_th Threshold to remove genes from testing; gene must be detected (non-zero count) #' in at least this many cells in the group with higher mean; default is 5 #' @param only_pos Test only genes with positive fold change (mean in group 1 > mean in group2); #' default is FALSE #' @param only_top_n Test only the this number of genes from both ends of the log2FC spectrum #' after all of the above filters have been applied; useful to get only the top markers; #' only used if set to a numeric value; default is NULL #' @param mean_type Which type of mean to use; if \code{'geometric'} (default) the geometric mean is #' used; to avoid \code{log(0)} we use \code{log1p} to add 1 to all counts and log-transform, #' calculate the arithmetic mean, and then back-transform and subtract 1 using \code{exp1m}; if #' this parameter is set to \code{'arithmetic'} the data is used as is #' @param verbosity Integer controlling how many messages the function prints; #' 0 is silent, 1 (default) is not #' #' @return Data frame of results #' #' @section Details: #' This model-free test is applied to each gene (row) individually but is #' optimized to make use of the efficient sparse data representation of #' the input. A permutation null distribution us used to assess the #' significance of the observed difference in mean between two groups. #' #' The observed difference in mean is compared against a distribution #' obtained by random shuffling of the group labels. For each gene every #' random permutation yields a difference in mean and from the population of #' these background differences we estimate a mean and standard #' deviation for the null distribution. #' This mean and standard deviation are used to turn the observed #' difference in mean into a z-score and then into a p-value. Finally, #' all p-values (for the tested genes) are adjusted using the Benjamini & Hochberg #' method (fdr). The log2FC values in the output are \code{log2(mean1 / mean2)}. #' Empirical p-values are also calculated: \code{emp_pval = (b + 1) / (R + 1)} #' where b is the number of times the absolute difference in mean from a random #' permutation is at least as large as the absolute value of the observed difference #' in mean, R is the number of random permutations. This is an upper bound of #' the real empirical p-value that would be obtained by enumerating all possible #' group label permutations. #' #' There are multiple ways the group comparisons can be specified based on the compare #' parameter. The default, \code{'each_vs_rest'}, does multiple comparisons, one per #' group vs all remaining cells. \code{'all_vs_all'}, also does multiple comparisons, #' covering all groups pairs. If compare is set to a length two character vector, e.g. #' \code{c('T-cells', 'B-cells')}, one comparison between those two groups is done. #' To put multiple groups on either side of a single comparison, use a list of length two. #' E.g. \code{compare = list(c('cluster1', 'cluster5'), c('cluster3'))}. #' #' @import Matrix #' @importFrom matrixStats rowMeans2 rowSds #' @importFrom stats p.adjust pnorm #' #' @export #' #' @examples #' \donttest{ #' clustering <- 1:ncol(pbmc) %% 2 #' vst_out <- vst(pbmc, return_corrected_umi = TRUE) #' de_res <- diff_mean_test(y = vst_out$umi_corrected, group_labels = clustering) #' } #' diff_mean_test <- function(y, group_labels, compare = 'each_vs_rest', R = 99, log2FC_th = log2(1.2), mean_th = 0.05, cells_th = 5, only_pos = FALSE, only_top_n = NULL, mean_type = 'geometric', verbosity = 1) { if (is.na(match(x = mean_type, table = c('geometric', 'arithmetic')))) { stop('mean_type must be geometric or arithmetic') } if (!inherits(x = y, what = 'dgCMatrix')) { stop('y must be a dgCMatrix') } if (R < 13) { stop('R must be at least 13') } if (!is.null(only_top_n) & (!is.numeric(only_top_n) | length(only_top_n) > 1)) { stop('only_top_n must be NULL or a single numeric value') } group_labels <- droplevels(as.factor(group_labels)) lab_tab <- table(group_labels) group_levels <- levels(group_labels) G <- length(group_levels) if (length(group_labels) != ncol(y)) { stop('length of group labels must be equal to the number of columns in y') } if (verbosity > 0) { message('Non-parametric DE test for count data') message(sprintf('Using %s mean and %d random permutations', mean_type, R)) message('Input: ', nrow(y), ' genes, ', ncol(y), ' cells; ', G, ' groups') } # Set up the comparisons we want to do; each comparison is a list # name1, name2, labels grp1, labels grp2 if (compare[1] == 'each_vs_rest' && G == 2) { compare <- group_levels if (verbosity > 0) { message('There are only two groups in the data. Changing compare argument from "each_vs_rest" to group levels') } } if (compare[1] == 'each_vs_rest') { comparisons <- lapply(group_levels, function(x) list(x, 'rest', x, setdiff(group_levels, x))) } else if (compare[1] == 'all_vs_all') { comparisons <- list() for (i in 1:(G-1)) { for (j in (i+1):G) { comparisons[[length(comparisons) + 1]] <- list(group_levels[i], group_levels[j], group_levels[i], group_levels[j]) } } } else if (inherits(x = compare, what = 'character') && length(compare) == 2 && all(compare %in% group_levels)) { if (compare[1] == compare[2]) { stop('Group 1 and 2 need to be different - please check your compare argument') } comparisons <- list(list(compare[1], compare[2], compare[1], compare[2])) } else if (inherits(x = compare, what = 'list') && length(compare) == 2 && all(unlist(lapply(compare, inherits, what = 'character')))) { compare <- lapply(compare, unique) if (length(intersect(compare[[1]], compare[[2]])) > 0) { stop('Intersection between group 1 and 2 - please check your compare argument') } comparisons <- list(list('group1', 'group2', compare[[1]], compare[[2]])) } else { stop("Make sure the compare argument is 'each_vs_rest' or 'all_vs_all' or a length 2 character vector with both entries present in the group_labels argument or a list of length 2 with each entry being a character vector of group labels") } # for all the genes, get the number of non-zero observations per group cells <- row_nonzero_count_grouped_dgcmatrix(matrix = y, group = group_labels) # if we want to use the geometric mean, it's fastest to convert all counts to # log1p upfront, then use expm1 of arithmetic mean later on if (mean_type == 'geometric') { y@x <- log(y@x + 1) means <- row_mean_grouped_dgcmatrix(matrix = y, group = group_labels, shuffle = FALSE) } else { means <- row_mean_grouped_dgcmatrix(matrix = y, group = group_labels, shuffle = FALSE) } # Run the test for each comparison res_lst <- lapply(comparisons, function(comp) { # we might only be using a subset of the input cells; set up here sel_columns1 <- group_labels %in% comp[[3]] sel_columns2 <- group_labels %in% comp[[4]] sel_columns <- sel_columns1 | sel_columns2 comp_group_labels <- factor(sel_columns2[sel_columns]) if (verbosity > 0) { message(sprintf('Comparing %s (group1, N = %d) to %s (group2, N = %d)', comp[[1]], sum(sel_columns1), comp[[2]], sum(sel_columns2))) } if (sum(sel_columns1) == 0 || sum(sel_columns2) == 0) { return() } comp_cells <- do.call(cbind, lapply(comp[3:4], function(x) combine_counts(cells, x))) comp_means <- do.call(cbind, lapply(comp[3:4], function(x) combine_means(means, lab_tab, x, mean_type))) res <- data.frame(gene = rownames(means), group1 = comp[[1]], mean1 = comp_means[, 1], cells1 = comp_cells[, 1], group2 = comp[[2]], mean2 = comp_means[, 2], cells2 = comp_cells[, 2]) res$mean_diff <- res$mean1 - res$mean2 res$log2FC <- log2(res$mean1 / res$mean2) # remove genes according to the filters if (log2FC_th > 0 || mean_th > 0 || cells_th > 0 || only_pos || !is.null(only_top_n)) { sel1 <- abs(res$log2FC) >= log2FC_th sel2 <- res$mean1 >= mean_th | res$mean2 >= mean_th sel3 <- (res$log2FC >= 0 & res$cells1 >= cells_th) | (res$log2FC <= 0 & res$cells2 >= cells_th) if (only_pos) { sel4 <- res$log2FC > 0 } else { sel4 <- TRUE } res <- res[sel1 & sel2 & sel3 & sel4, , drop = FALSE] if (!is.null(only_top_n)) { sel0 <- rank(-res$log2FC) <= only_top_n if (!only_pos) { sel0 <- sel0 | rank(res$log2FC) <= only_top_n } res <- res[sel0, , drop = FALSE] } if (verbosity > 0) { message(sprintf('Keeping %d genes after initial filtering', nrow(res))) } # handle the case where no genes remain after filtering if (nrow(res) == 0) { return(res) } } # now get the empirical null distribution for mean_diff y_ss <- y[rownames(res), sel_columns, drop = FALSE] if (mean_type == 'geometric') { mean_diff_rnd <- do.call(cbind, lapply(1:R, function(i) { means_r <- expm1(row_mean_grouped_dgcmatrix(matrix = y_ss, group = comp_group_labels, shuffle = TRUE)) means_r[, 1, drop = FALSE] - means_r[, 2, drop = FALSE] })) } else { mean_diff_rnd <- do.call(cbind, lapply(1:R, function(i) { means_r <- row_mean_grouped_dgcmatrix(matrix = y_ss, group = comp_group_labels, shuffle = TRUE) means_r[, 1, drop = FALSE] - means_r[, 2, drop = FALSE] })) } # use null distribution to get empirical p-values # also approximate null with normal and derive z-scores and p-values res$emp_pval <- (rowSums((abs(mean_diff_rnd) - abs(res$mean_diff)) >= 0) + 1) / (R + 1) res$emp_pval_adj <- p.adjust(res$emp_pval, method = 'BH') #res$zscore <- (res$mean_diff - rowMeans2(mean_diff_rnd)) / rowSds(mean_diff_rnd) sds <- sqrt(rowSums(mean_diff_rnd^2)/(R-1)) res$zscore <- (res$mean_diff - rowMeans2(mean_diff_rnd)) / sds res$pval <- 2 * pnorm(-abs(res$zscore)) res$pval_adj <- p.adjust(res$pval, method = 'BH') if (length(comparisons) > 1) { rownames(res) <- NULL } return(res) }) res <- Reduce(rbind, res_lst) if (length(compare) == 1 && compare == 'each_vs_rest' && !is.null(res)) { res$group1 <- factor(res$group1, levels = group_levels) res$group2 <- factor(res$group2) } if (length(compare) == 1 && compare == 'all_vs_all' && !is.null(res)) { res$group1 <- factor(res$group1, levels = group_levels) res$group2 <- factor(res$group2, levels = group_levels) } return(res) } # helper functions combine_counts <- function(group_counts, columns) { as.matrix(rowSums(group_counts[, columns, drop = FALSE])) } # combine per-group-mean to get the mean spanning multiple groups # in an act of irrational premature optimization, we pass the # log-space mean when mean_type is geometric - need to make sure to # transform with exp1m before returning combine_means <- function(means, n_items, columns, mean_type) { if (length(columns) == 1) { if (mean_type == 'arithmetic') { return(means[, columns, drop = FALSE]) } if (mean_type == 'geometric') { return(expm1(means[, columns, drop = FALSE])) } } means <- means[, columns] n_items <- n_items[columns] tmp <- sweep(x = means, MARGIN = 2, STATS = n_items, FUN = '*') if (mean_type == 'arithmetic') { return(as.matrix(rowSums(tmp) / sum(n_items))) } if (mean_type == 'geometric') { return(as.matrix(expm1(rowSums(tmp) / sum(n_items)))) } } #' Find differentially expressed genes that are conserved across samples #' #' @param y A matrix of counts; must be (or inherit from) class dgCMatrix; genes are rows, #' cells are columns #' @param group_labels The group labels (i.e. clusters or time points); #' will be converted to factor #' @param sample_labels The sample labels; will be converted to factor #' @param balanced Boolean, see details for explanation; default is TRUE #' @param compare Specifies which groups to compare, see details; currently only 'each_vs_rest' #' (the default) is supported #' @param pval_th P-value threshold used to call a gene differentially expressed when summarizing #' the tests per gene #' @param ... Parameters passed to diff_mean_test #' #' @return Data frame of results #' #' @section Details: #' This function calls diff_mean_test repeatedly and aggregates the results per group and gene. #' #' If balanced is TRUE (the default), it is assumed that each sample spans multiple groups, #' as would be the case when merging or integrating samples from the same tissue followed by #' clustering. Here the group labels would be the clusters and cluster markers would have support #' in each sample. #' #' If balanced is FALSE, an unbalanced design is assumed where each sample contributes to one #' group. An example is a time series experiment where some samples are taken from time point #' 1 while other samples are taken from time point 2. The time point would be the group label #' and the goal would be to identify differentially expressed genes between time points that #' are supported by many between-sample comparisons. #' #' Output columns: #' \describe{ #' \item{group1}{Group label of the frist group of cells} #' \item{group2}{Group label of the second group of cells; currently fixed to 'rest'} #' \item{gene}{Gene name (from rownames of input matrix)} #' \item{n_tests}{The number of tests this gene participated in for this group} #' \item{log2FC_min,median,max}{Summary statistics for log2FC across the tests} #' \item{mean1,2_median}{Median of group mean across the tests} #' \item{pval_max}{Maximum of p-values across tests} #' \item{de_tests}{Number of tests that showed this gene having a log2FC going in the same #' direction as log2FC_median and having a p-value <= pval_th} #' } #' #' The output is ordered by group1, -de_tests, -abs(log2FC_median), pval_max #' #' @import Matrix #' @importFrom dplyr n group_by summarise arrange #' @importFrom rlang .data #' #' @export #' #' @examples #' \donttest{ #' clustering <- 1:ncol(pbmc) %% 2 #' sample_id <- 1:ncol(pbmc) %% 3 #' vst_out <- vst(pbmc, return_corrected_umi = TRUE) #' de_res <- diff_mean_test_conserved(y = vst_out$umi_corrected, #' group_labels = clustering, sample_labels = sample_id) #' } #' diff_mean_test_conserved <- function(y, group_labels, sample_labels, balanced = TRUE, compare = 'each_vs_rest', pval_th = 1e-4, ...) { if (!inherits(x = y, what = 'dgCMatrix')) { stop('y must be a dgCMatrix') } group_labels <- droplevels(as.factor(group_labels)) sample_labels <- droplevels(as.factor(sample_labels)) res <- NULL if (compare[1] == 'each_vs_rest') { if (balanced) { res_lst <- lapply(levels(sample_labels), function(sl) { sel <- sample_labels == sl res <- diff_mean_test(y = y[, sel], group_labels = group_labels[sel], compare = compare, ...) if (!is.null(res)) { res$sample <- sl } res }) } else { # fix special case when there are only two groups if (length(levels(group_labels)) == 2) { group_labels_to_do <- levels(group_labels)[1] gl_rest <- levels(group_labels)[2] } else { group_labels_to_do <- levels(group_labels) gl_rest <- 'rest' } # for each group, compare each sample against all samples that are not in group individually res_lst <- lapply(group_labels_to_do, function(gl) { gl_sel <- group_labels == gl samples_in_group <- sample_labels[gl_sel] res_lst <- lapply(unique(samples_in_group), function(sl_in_group) { sl_in_group_sel <- sample_labels == sl_in_group other_samples_not_in_group <- sample_labels[!(gl_sel | sl_in_group_sel)] res_lst <- lapply(unique(other_samples_not_in_group), function(osl_not_in_group) { sel <- (gl_sel & sl_in_group_sel) | (!gl_sel & sample_labels == osl_not_in_group) tmp_group <- c(gl, gl_rest)[as.numeric(!gl_sel & sample_labels == osl_not_in_group) + 1] res <- diff_mean_test(y = y[, sel], group_labels = tmp_group[sel], compare = c(gl, gl_rest), ...) if (!is.null(res)) { res$sample1 <- sl_in_group res$sample2 <- osl_not_in_group } res }) do.call(rbind, res_lst) }) do.call(rbind, res_lst) }) } res <- do.call(rbind, res_lst) levels(res$group1) <- levels(group_labels) } if (!is.null(res)) { res <- group_by(res, .data$group1, .data$group2, .data$gene) %>% summarise(n_tests = n(), log2FC_min = min(.data$log2FC), log2FC_median = median(.data$log2FC), log2FC_max = max(.data$log2FC), mean1_median = median(.data$mean1), mean2_median = median(.data$mean2), pval_max = max(.data$pval), de_tests = sum((sign(.data$log2FC) == sign(.data$log2FC_median)) & (.data$pval <= pval_th)), .groups = 'drop') %>% arrange(.data$group1, -.data$de_tests, -abs(.data$log2FC_median), .data$pval_max) } return(res) } # non-parametric differential expression test np_de_test <- function(y, labels, N = 100, S = 100, randomize = FALSE) { if (!inherits(x = y, what = 'matrix')) { stop('y must be a matrix') } labels <- droplevels(as.factor(labels)) if (length(levels(labels)) > 2) { stop('only two groups can be compared') } if (N < 50 || S < 50) { stop('N and S must both be at least 50') } if (ncol(y) != length(labels)) { stop('number of columns in y and length of label vector must match') } labels <- as.integer(labels)-1L if (randomize) { res <- apply(y, 1, function(x) distribution_shift(mean_boot_grouped(x, sample(labels), N = 100, S = 100))) } else { res <- apply(y, 1, function(x) distribution_shift(mean_boot_grouped(x, labels, N = 100, S = 100))) } #res <- data.frame(t(res)) #colnames(res) <- c('q16_a', 'q50_a', 'q84_a', 'q16_b', 'q50_b', 'q84_b', 'div', 'z') res <- data.frame(t(res[c(2, 5, 7, 8), ])) colnames(res) <- c('mu1', 'mu2', 'div', 'z') gene <- rownames(res) res <- cbind(gene, res) rownames(res) <- NULL return(res) } sctransform/NEWS.md0000644000176200001440000001056714167140301013717 0ustar liggesusers# News All notable changes will be documented in this file. ## [0.3.3] - UNRELEASED ### Added - `vst.flavor` argument to `vst()` to allow for invoking running updated regularization (sctransform v2, proposed in [Satija and Choudhary, 2021](https://doi.org/10.1101/2021.07.07.451498). See paper for details. - `scale_factor` to `correct()` to allow for a custom library size when correcting counts ## [0.3.2.9008] - 2021-07-28 ### Added - Add future.seed = TRUE to all `future_lapply()` calls ### Changed - Wrap MASS::theta.ml() in suppressWarnings() ### Fixed - Fix logical comparison of vectors of length one in `diff_mean_test()` ## [0.3.2.9003] - 2020-02-11 ### Added - `compare` argument to the nonparametric differential expression test `diff_mean_test()` to allow for multiple comparisons and various ways to specify which groups to compare - Input checking at various places in `vst()` and `diff_mean_test()` ### Changed - Major speed improvements for `diff_mean_test()` - Changed the `labels` argument to `group_labels` in `diff_mean_test()` ### Fixed - Fix bug where factors in cell attributes gave error when checking for NA, NaN, inf ## [0.3.2] - 2020-12-16 ### Added - Ability to control the values of latent variables when calculating corrected counts - Offset model as method, including the ability to use a single estimated theta for all genes - Nonparametric differential expression test for sparse non-negative data ### Changed - Improve poor coefficient initialization in quasi poisson regression - When plotting model, do not show density by default; change bandwidth to `bw.nrd0` - Updates to C++ code to use sparse matrices as S4 objects - Add check for NA, NaN, Inf values in cell attributes ### Fixed - Remove biocViews from DESCRIPTION - not needed and was causing problems with deploying shiny apps - Fix bug where a coefficient was given the wrong name when using `glmGamPoi` (only affected runs with a batch variable set) ## [0.3.1] - 2020-10-08 ### Added - Add a `qpoisson` method for parameter estimation that uses fast Rcpp quasi poisson regression where possible (based on `Rfast` package); this adds `RcppArmadillo` dependency ### Changed - Remove `poisson_fast` method (replaced by `qpoisson`) - Use `matrixStats` package and remove `RcppEigen` dependency - Use quasi poisson regression where possible - Define cell detection event as counts >= 0.01 (instead of > 0) - this only matters to people playing around with fractional counts (see [issue #65](https://github.com/satijalab/sctransform/issues/65)) - Internal code restructuring and improvements ### Fixed - Fix inefficiency of using `match.call()` in `vst()` when called via `do.call` ## [0.3] - 2020-09-19 ### Added - Add support for `glmGamPoi` as method to estimate the model parameters; thanks @yuhanH for his pull request - Add option to use `theta.mm` or`theta.ml` to estimate theta when `method = 'poisson'` or `method = 'nb_fast'` - Add a `poisson_fast` method for parameter estimation that uses the `speedglm` package and `theta.mm` by default - Add ability to plot overdispersion factor in `plot_model_pars` - Add and return time stamps at various steps in the `vst` function - Add functions to calculate grouped arithmetic and geometric mean per row for sparse matrices (`dgCMatrix`) - might come in handy some time ### Changed - Default theta regularization is now based on overdispersion factor (`1 + m / theta` where m is the geometric mean of the observed counts) not `log10(theta)`; old behavior available via `theta_regularization` parameter - Refactored model fitting code - is now more efficient when using parallel processing - Changed how message and progress bar output is controlled; integer `verbosity` parameter controls all output: 0 for no output, 1 for only messages, 2 for messages and progress bars - Increased default bin size (genes being processed simultaneously) from 256 to 500 - Better input checking for cell attributes; more efficient calculation of missing ones ### Fixed - Some non-regularized model parameters were not plotted ## [0.2.1] - 2019-12-17 ### Added - Add function to generate data given the output of a vst run - Add cpp support for dense integer matrices - Minimum variance parameter added to vst function ## [0.2.0] - 2019-04-12 ### Added - Rcpp versions of utility functions - Helper functions to get corrected UMI and variance of pearson residuals for large UMI matrices ### Changed - lots of things sctransform/MD50000644000176200001440000000522514167760262013142 0ustar liggesusersf3d9f9d36e51a2d64bb4586b61806d0b *DESCRIPTION 84dcc94da3adb52b53ae4fa38fe49e5d *LICENSE 6866258ae7ec352de8bb6ffba1cc012f *NAMESPACE d07fc801ed4fa1e8382a7a92afa8e177 *NEWS.md eb2dceb9a69aa46686fc844d8b461cce *R/RcppExports.R 7d5d18729ee57528b9bbac6adb59179f *R/data.R 6d94fad03fa5caab281ad9d3f6d057dc *R/denoise.R 45e19f393fb4b203f36d17718699ed45 *R/differential_expression.R f1b4448f9dfe139d511e7387e4e44df6 *R/fit.R 17a93d60f7a7b1d7722a2933d106fadc *R/generate.R a75ee9a21515467206c9189a4914836c *R/plotting.R df0c887d37e2813a4c8dfef3a96ed501 *R/umify.R 845c4719184d2968a838c478dbbaa894 *R/utils.R 6a6a6a71ac8343c7a8a100edb642c029 *R/vst.R bce70b423a311637ab8d9fee67eacf89 *README.md e9968f4ffbb6575c6587ee70f5d80f38 *build/partial.rdb 8c302f87e051c80640fd342cb5fd2cc6 *data/pbmc.rda 7b932528197e877027fee2b2aeea795b *data/umify_data.rda ca1570f49127fbaa4abad84ac9b2a2cc *inst/CITATION 9076a0fc5263f058dcd4c675bc31fde8 *man/compare_expression.Rd 3d582e0c9587ba1c59c407f1ed60df17 *man/correct.Rd ab5f93e4ccca66bea98a109da06650da *man/correct_counts.Rd d1229bed7812fbdbaa9dba22013484f7 *man/diff_mean_test.Rd 3b7d461ed5a5f5a359ef689458fca930 *man/diff_mean_test_conserved.Rd 1b6825faa5d563123976839954eb2310 *man/generate.Rd 820f6eaf2e8116c4e2dbd4f8cbc43cce *man/get_model_var.Rd 17bf44658b3d9cc88d5d53dfb92939d7 *man/get_nz_median.Rd e9ec276a5230bdcfce5edac3dd25a78b *man/get_nz_median2.Rd 0fa41a8f53e3a7b52331e4b38a4f2587 *man/get_residual_var.Rd a273f656d689519bd4fb50b42799dabe *man/get_residuals.Rd 9d48028b5e5b3ec38a8200df614e36d3 *man/is_outlier.Rd f3b7a893407d228075339e062b5444dd *man/pbmc.Rd cf9ea2eaa55560f7f00c79aefa19cb9c *man/plot_model.Rd c2de5c749823a723956a3aad2cf502a8 *man/plot_model_pars.Rd eb62f7766c3a1c2d33bc7b7ee7e53dc4 *man/robust_scale.Rd b6792b0e3741ac6d9c71cc0fb03aba2e *man/robust_scale_binned.Rd 050a994f9db03b10920b14a456598f3e *man/row_gmean.Rd 4568f18fd1059015a39fdd29ac67ea11 *man/row_var.Rd 9ea72124e0ca18a683e196d477572633 *man/smooth_via_pca.Rd b65ee204a196822c36aa958d60366cd8 *man/umify.Rd d1f1a6c3c0a06f11b10eb6d19218606f *man/umify_data.Rd 7be4e1f7b2c63ac71dee010aa6d1bfe9 *man/vst.Rd c21604b530295defd4ac92b19581a937 *src/Makevars c21604b530295defd4ac92b19581a937 *src/Makevars.win cc4e0d852b6931e99d687e0e75b9be8b *src/RcppExports.cpp e6ce03190b1c5dcce87ffc04c591f369 *src/utils.cpp 47a51cede5d9eb999d1040c9da1301c4 *tests/testthat.R a0c57f845f02156dafaec4e7f066aef1 *tests/testthat/test_denoising.R 5d16b85eb6ce0be774151373382ab900 *tests/testthat/test_differential_expression.R 08baae1e9bd52ae3de380cdd1c053771 *tests/testthat/test_generate.R dff88cd6cde7abb658d661b40b282e5c *tests/testthat/test_utils.R c443815912b3d9b81d9b157610f56076 *tests/testthat/test_vst.R sctransform/inst/0000755000176200001440000000000014167140253013573 5ustar liggesuserssctransform/inst/CITATION0000644000176200001440000000126514167140253014734 0ustar liggesuserscitHeader("To cite sctransform in publications, please use:") citEntry(entry = "article", author = personList(as.person("Christoph Hafemeister"), as.person("Rahul Satija")), title = "Normalization and variance stabilization of single-cell RNA-seq data using regularized negative binomial regression", journal = "Genome Biology", year = "2019", volume = "20", pages = "296", doi = "10.1186/s13059-019-1874-1", url = "https://doi.org/10.1186/s13059-019-1874-1", textVersion = "Hafemeister, C. & Satija, R. Normalization and variance stabilization of single-cell RNA-seq data using regularized negative binomial regression. Genome Biol 20, 296 (2019)." )