sctransform/0000755000176200001440000000000013576166562012634 5ustar liggesuserssctransform/NAMESPACE0000644000176200001440000000216513576150071014043 0ustar liggesusers# Generated by roxygen2: do not edit by hand export(correct) export(correct_counts) 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(vst) import(Matrix) import(ggplot2) import(reshape2) importFrom(MASS,glm.nb) importFrom(MASS,negative.binomial) importFrom(MASS,theta.ml) importFrom(future.apply,future_lapply) importFrom(graphics,abline) importFrom(graphics,par) importFrom(graphics,plot) importFrom(gridExtra,grid.arrange) importFrom(methods,as) importFrom(stats,aggregate) importFrom(stats,anova) importFrom(stats,approx) importFrom(stats,as.formula) importFrom(stats,bw.SJ) importFrom(stats,density) importFrom(stats,glm) 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,poisson) importFrom(stats,predict) importFrom(stats,t.test) importFrom(stats,var) importFrom(utils,capture.output) importFrom(utils,setTxtProgressBar) importFrom(utils,txtProgressBar) useDynLib(sctransform) sctransform/LICENSE0000644000176200001440000010450513324136745013635 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.md0000644000176200001440000000262313453446232014103 0ustar liggesusers# sctransform ## R package for normalization and variance stabilization of single-cell RNA-seq data using regularized negative binomial regression This packaged was developed by Christoph Hafemeister in [Rahul Satija's lab](https://satijalab.org/) at the New York Genome Center. 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 `devtools::install_github(repo = 'ChristophH/sctransform')` `normalized_data <- sctransform::vst(umi_count_matrix)$y` ## 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://rawgit.com/ChristophH/sctransform/master/inst/doc/variance_stabilizing_transformation.html) [Using sctransform in Seurat](https://rawgit.com/ChristophH/sctransform/master/inst/doc/seurat.html) ## Reference [Hafemeister, C. & Satija, R. Normalization and variance stabilization of single-cell RNA-seq data using regularized negative binomial regression. bioRxiv 576827 (2019). doi:10.1101/576827](https://www.biorxiv.org/content/10.1101/576827v1) 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). sctransform/data/0000755000176200001440000000000013442316101013517 5ustar liggesuserssctransform/data/pbmc.rda0000644000176200001440000022276413442316101015145 0ustar liggesusersBZh91AY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FkHWRԪw~uuF:5KS/7(ڼޥZ iFN prVԶm)}FVȶP{EV\SG*n6qJS@Fw>9DS5!Rj8T߯V6$uMnުSP8p#>B' *qP' Ppp%vNmIm+rI5Pґ?K;|Ͽ^wo噶G~\q,Eր~|? /zn-gO,ÖMY_W3>RI='3ˏxf`̀y?_n[)jZRjGҐү-T=Fi>#.Q9촪ԖjPjU8*SR88pjW =#I?oAu.s-O=hٓѐ=ɨŇ`STlli)DR~j2j联U=nj h%$Uꔅ ɫ0R7k X[ԟJ P>KO}Ql{,Z!( ۥŅnhowT MZ[|W I||j0a'Ty~߭ >;7Y7Z1ETْhuRVC5|T Ϯ 6d\Ҫ/rn>ᴆ+J8G/55Iw≆ >U žCCHc(ny2l0ltILL Axu- 氞]}Hl{cўl7(R 7IQ!o)L:%~-4dٝ(Zzld4@ 8a]1d1f RtSos%7\fha2,]VLU^6M&&Bd<4ΕiAe&іǵCtFHgQ7^hsC%3ކn@yѲa]wi&tG ]H,-]Jͱpb3(9R](AIDE"fs'ٺРh"[\ҙՆ_'ԇ{ ozM>o[xPjZ_+{J{3[2tWܞ)bI0™υ ̪%QYV%1UN֐QPUH0%2UĠ EF(QQdт0j1FB1Or h(FlFNsF !!ob-I2hDdB3db5t"\5Qi75s\5፣pITc5hQfF5Y I$Ū+E0Ѷ-%fQbEF5q6 "A-Ѯ\,h2W??"ATli0k&#S,&Ŋ hbʼn!M5rhssb XLآԚsPPk'utZFNsh"DkTX@R0DTb(5r8V,lDdbS,˘sW78ؤ5pŒ cꂒ<Y1ߨnS}HJ\$[<bETܑN$)sctransform/man/0000755000176200001440000000000013576016340013373 5ustar liggesuserssctransform/man/get_residuals.Rd0000644000176200001440000000261713576016340016522 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, show_progress = TRUE) } \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{show_progress}{Whether to print progress bar} } \value{ A matrix of residuals } \description{ Return Pearson or deviance residuals of regularized models } \examples{ \dontrun{ vst_out <- vst(pbmc) pearson_res <- get_residuals(vst_out, pbmc) deviance_res <- get_residuals(vst_out, pbmc, residual_type = 'deviance') } } sctransform/man/robust_scale.Rd0000644000176200001440000000044713310701572016346 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.Rd0000644000176200001440000001252713576142544014513 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, res_clip_range = c(-sqrt(ncol(umi)), sqrt(ncol(umi))), bin_size = 256, 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_given = NULL, show_progress = TRUE) } \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', 'nb_fast', 'nb', 'nb_theta_given'} \item{do_regularize}{Boolean that, if set to FALSE, will bypass parameter regularization and use all genes in first step (ignoring n_genes).} \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 put in each bin (to show progress)} \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; default is -Inf} \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_given}{Named numeric vector of fixed theta values for the genes; will only be used if method is set to nb_theta_given; default is NULL} \item{show_progress}{Whether to print messages and show progress bar} } \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)} } \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. } \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', glm will be called with \code{family = poisson} and the negative binomial theta parameter will be estimated using the response residuals in \code{MASS::theta.ml}. If \code{method} is set to 'nb_fast', glm 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}. } \examples{ \donttest{ vst_out <- vst(pbmc) } } sctransform/man/smooth_via_pca.Rd0000644000176200001440000000173713576142544016673 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.Rd0000644000176200001440000000174213576142544016730 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, show_progress = TRUE) } \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{show_progress}{Whether to print progress bar} } \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/generate.Rd0000644000176200001440000000206213576142544015462 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 replacment. } \examples{ \donttest{ vst_out <- vst(pbmc, return_cell_attr = TRUE) generated_data <- generate(vst_out) } } sctransform/man/row_var.Rd0000644000176200001440000000044213454105530015334 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.Rd0000644000176200001440000000060613454105530015635 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.Rd0000644000176200001440000000113213454105530014573 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.Rd0000644000176200001440000000054313442316101016030 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.Rd0000644000176200001440000000275113453446232016026 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 = TRUE, 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{ \dontrun{ vst_out <- vst(pbmc, return_cell_attr = TRUE) plot_model(vst_out, pbmc, 'PPBP') } } sctransform/man/correct.Rd0000644000176200001440000000175613576142544015342 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, do_round = TRUE, do_pos = TRUE, show_progress = TRUE) } \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{do_round}{Round the result to integers} \item{do_pos}{Set negative values in the result to zero} \item{show_progress}{Whether to print progress bar} } \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.Rd0000644000176200001440000000106413576016340017046 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, show_var = FALSE) } \arguments{ \item{vst_out}{The output of a vst run} \item{show_var}{Whether to show the average model variance; boolean; default is FALSE} } \value{ A ggplot object } \description{ Plot estimated and fitted model parameters } \examples{ \dontrun{ vst_out <- vst(pbmc, return_gene_attr = TRUE) plot_model_pars(vst_out) } } sctransform/man/compare_expression.Rd0000644000176200001440000000336413454105530017570 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, show_progress = TRUE) } \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{show_progress}{Show progress bar} } \value{ Data frame of results } \description{ Compare gene expression between two groups } \examples{ \dontrun{ 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) } } sctransform/man/get_model_var.Rd0000644000176200001440000000155113576016340016473 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, show_progress = TRUE) } \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{show_progress}{Whether to print progress bar} } \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{ \dontrun{ vst_out <- vst(pbmc) res_var <- get_model_var(vst_out) } } sctransform/man/get_residual_var.Rd0000644000176200001440000000260713576016340017206 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, show_progress = TRUE) } \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{show_progress}{Whether to print progress bar} } \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{ \dontrun{ vst_out <- vst(pbmc) res_var <- get_residual_var(vst_out, pbmc) } } sctransform/man/robust_scale_binned.Rd0000644000176200001440000000067013454105530017664 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/DESCRIPTION0000644000176200001440000000250113576166562014340 0ustar liggesusersPackage: sctransform Type: Package Title: Variance Stabilizing Transformations for Single Cell UMI Data Version: 0.2.1 Authors@R: person(given = 'Christoph', family = 'Hafemeister', email = 'chafemeister@nygenome.org', role = c('aut', 'cre'), comment = c(ORCID = '0000-0001-6365-8254')) 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 for more details. URL: https://github.com/ChristophH/sctransform BugReports: https://github.com/ChristophH/sctransform/issues License: GPL-3 | file LICENSE Encoding: UTF-8 LazyData: true Depends: R (>= 3.0.2) Imports: MASS, Matrix, methods, future.apply, ggplot2, reshape2, gridExtra LinkingTo: Rcpp (>= 0.11.0), RcppEigen Suggests: irlba, testthat, knitr RoxygenNote: 6.1.1 NeedsCompilation: yes Packaged: 2019-12-17 12:55:24 UTC; chafemeister Author: Christoph Hafemeister [aut, cre] () Maintainer: Christoph Hafemeister Repository: CRAN Date/Publication: 2019-12-17 15:00:02 UTC sctransform/tests/0000755000176200001440000000000013325320035013751 5ustar liggesuserssctransform/tests/testthat/0000755000176200001440000000000013576166562015636 5ustar liggesuserssctransform/tests/testthat/test_differential_expression.R0000644000176200001440000000160413453446232023721 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.R0000644000176200001440000000104213576143532020577 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(1, 0, 0, 2, 0), generated_data['GPI', 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_denoising.R0000644000176200001440000000145513576143535020777 0ustar liggesuserscontext("correcting") test_that('correcting runs and returns expected output', { skip_on_cran() options(mc.cores = 2) 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.05809, -0.00707, 0.55978, 0.27358, -0.01979, 0.83436, 0.03495, -0.09587, -0.88417), as.numeric(y_smooth[1:3, 1:3]), tolerance = 1e-5) 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, 30, 0, 0, 34, 0, 0, 9), as.numeric(umi_corrected[1:3, 1:3])) }) sctransform/tests/testthat/test_vst.R0000644000176200001440000000104113576143550017620 0ustar liggesuserscontext("vst function") test_that('vst runs and returns expected output', { skip_on_cran() options(mc.cores = 2) 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) }) sctransform/tests/testthat.R0000644000176200001440000000010213325320035015725 0ustar liggesuserslibrary(testthat) library(sctransform) test_check("sctransform") sctransform/src/0000755000176200001440000000000013576150074013412 5ustar liggesuserssctransform/src/utils.cpp0000644000176200001440000000367513576150074015271 0ustar liggesusers#include #include using namespace Rcpp; // [[Rcpp::depends(RcppEigen)]] // [[Rcpp::export]] NumericVector row_mean_dgcmatrix(NumericVector x, IntegerVector i, int rows, int cols) { NumericVector ret(rows, 0.0); for (int k=0; k x) { NumericVector out(x.rows()); for(int i=0; i < x.rows(); ++i){ Eigen::ArrayXd r = x.row(i).array(); double rowMean = r.mean(); out[i] = (r - rowMean).square().sum() / (x.cols() - 1); } return out; } // [[Rcpp::export]] NumericVector row_var_dense_i(Eigen::Map x) { NumericVector out(x.rows()); for(int i=0; i < x.rows(); ++i){ Eigen::ArrayXd r = (x.row(i).array()).cast(); double rowMean = r.mean(); out[i] = (r - rowMean).square().sum() / (x.cols() - 1); } return out; } sctransform/src/RcppExports.cpp0000644000176200001440000000723613576150074016417 0ustar liggesusers// Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #include #include using namespace Rcpp; // row_mean_dgcmatrix NumericVector row_mean_dgcmatrix(NumericVector x, IntegerVector i, int rows, int cols); RcppExport SEXP _sctransform_row_mean_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_mean_dgcmatrix(x, i, rows, cols)); return rcpp_result_gen; END_RCPP } // row_gmean_dgcmatrix NumericVector row_gmean_dgcmatrix(NumericVector x, IntegerVector i, int rows, int cols, double eps); RcppExport SEXP _sctransform_row_gmean_dgcmatrix(SEXP xSEXP, SEXP iSEXP, SEXP rowsSEXP, SEXP colsSEXP, SEXP epsSEXP) { 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::traits::input_parameter< double >::type eps(epsSEXP); rcpp_result_gen = Rcpp::wrap(row_gmean_dgcmatrix(x, i, rows, cols, eps)); 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 } // row_var_dense_d NumericVector row_var_dense_d(Eigen::Map x); RcppExport SEXP _sctransform_row_var_dense_d(SEXP xSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Eigen::Map >::type x(xSEXP); rcpp_result_gen = Rcpp::wrap(row_var_dense_d(x)); return rcpp_result_gen; END_RCPP } // row_var_dense_i NumericVector row_var_dense_i(Eigen::Map x); RcppExport SEXP _sctransform_row_var_dense_i(SEXP xSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Eigen::Map >::type x(xSEXP); rcpp_result_gen = Rcpp::wrap(row_var_dense_i(x)); return rcpp_result_gen; END_RCPP } static const R_CallMethodDef CallEntries[] = { {"_sctransform_row_mean_dgcmatrix", (DL_FUNC) &_sctransform_row_mean_dgcmatrix, 4}, {"_sctransform_row_gmean_dgcmatrix", (DL_FUNC) &_sctransform_row_gmean_dgcmatrix, 5}, {"_sctransform_row_var_dgcmatrix", (DL_FUNC) &_sctransform_row_var_dgcmatrix, 4}, {"_sctransform_row_var_dense_d", (DL_FUNC) &_sctransform_row_var_dense_d, 1}, {"_sctransform_row_var_dense_i", (DL_FUNC) &_sctransform_row_var_dense_i, 1}, {NULL, NULL, 0} }; RcppExport void R_init_sctransform(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); } sctransform/R/0000755000176200001440000000000013576150065013024 5ustar liggesuserssctransform/R/generate.R0000644000176200001440000000341313576142226014742 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 replacment. #' #' @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.R0000644000176200001440000002542113576016340014310 0ustar liggesusers #' 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(x = x@x, i = x@i, rows = nrow(x), cols = ncol(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 row_var <- function(x) { if (inherits(x = x, what = 'matrix')) { ret <- switch(storage.mode(x), 'double' = row_var_dense_d(x), 'integer' = row_var_dense_i(x), stop('Unknown matrix storage mode')) 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)) } 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 show_progress Whether to print progress bar #' #' @return A matrix of residuals #' #' @export #' #' @examples #' \dontrun{ #' vst_out <- vst(pbmc) #' 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, show_progress = TRUE) { 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 (show_progress) { 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 (show_progress) { 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]) res[genes_bin, ] <- switch(residual_type, 'pearson' = pearson_residual(y, mu, model_pars[genes_bin, 'theta'], min_var = min_variance), 'deviance' = deviance_residual(y, mu, model_pars[genes_bin, 'theta']) ) if (show_progress) { setTxtProgressBar(pb, i) } } if (show_progress) { 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 show_progress Whether to print progress bar #' #' @return A vector of residual variances (after clipping) #' #' @export #' #' @examples #' \dontrun{ #' vst_out <- vst(pbmc) #' 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, show_progress = TRUE) { 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 (show_progress) { 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 (show_progress) { 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]) res_mat <- switch(residual_type, 'pearson' = pearson_residual(y, mu, model_pars[genes_bin, 'theta'], min_var = min_variance), 'deviance' = deviance_residual(y, mu, model_pars[genes_bin, 'theta'])) 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 (show_progress) { setTxtProgressBar(pb, i) } } if (show_progress) { 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 show_progress Whether to print progress bar #' #' @return A named vector of variances (the average across all cells), one entry per gene. #' #' @export #' #' @examples #' \dontrun{ #' vst_out <- vst(pbmc) #' 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, show_progress = TRUE) { 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 (show_progress) { message('Calculating model variance for ', length(genes), ' genes') } bin_ind <- ceiling(x = 1:length(x = genes) / bin_size) max_bin <- max(bin_ind) if (show_progress) { 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 (show_progress) { setTxtProgressBar(pb, i) } } if (show_progress) { close(pb) } return(res) } sctransform/R/vst.R0000644000176200001440000005515613576142254014000 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. #' #' @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', 'nb_fast', 'nb', 'nb_theta_given' #' @param do_regularize Boolean that, if set to FALSE, will bypass parameter regularization and use all genes in first step (ignoring n_genes). #' @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 put in each bin (to show progress) #' @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; default is -Inf #' @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_given Named numeric vector of fixed theta values for the genes; will only be used if method is set to nb_theta_given; default is NULL #' @param show_progress Whether to print messages and show progress bar #' #' @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)} #' #' @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', glm will be called with \code{family = poisson} and #' the negative binomial theta parameter will be estimated using the response residuals in #' \code{MASS::theta.ml}. #' If \code{method} is set to 'nb_fast', glm 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}. #' #' @import Matrix #' @importFrom future.apply future_lapply #' @importFrom MASS theta.ml glm.nb negative.binomial #' @importFrom stats glm ksmooth model.matrix as.formula approx density poisson var bw.SJ #' @importFrom utils txtProgressBar setTxtProgressBar capture.output #' @importFrom methods as #' #' @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, res_clip_range = c(-sqrt(ncol(umi)), sqrt(ncol(umi))), bin_size = 256, 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_given = NULL, show_progress = TRUE) { arguments <- as.list(environment())[-c(1, 2)] start_time <- Sys.time() if (is.null(cell_attr)) { cell_attr <- data.frame(row.names = colnames(umi)) } known_attr <- c('umi', 'gene', 'log_umi', 'log_gene', 'umi_per_gene', 'log_umi_per_gene') if (all(setdiff(latent_var, colnames(cell_attr)) %in% known_attr)) { if (show_progress) { message('Calculating cell attributes for input UMI matrix') } tmp_attr <- data.frame(umi = colSums(umi), gene = colSums(umi > 0)) tmp_attr$log_umi <- log10(tmp_attr$umi) tmp_attr$log_gene <- log10(tmp_attr$gene) tmp_attr$umi_per_gene <- tmp_attr$umi / tmp_attr$gene tmp_attr$log_umi_per_gene <- log10(tmp_attr$umi_per_gene) cell_attr <- cbind(cell_attr, tmp_attr[, setdiff(colnames(tmp_attr), colnames(cell_attr)), drop = TRUE]) } if (!all(latent_var %in% colnames(cell_attr))) { stop('Not all latent variables present in cell attributes') } if (!is.null(batch_var)) { if (!batch_var %in% colnames(cell_attr)) { stop('Batch variable not present in cell attributes; batch_var should be a column name of cell attributes') } 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) genes <- rownames(umi)[genes_cell_count >= min_cells] umi <- umi[genes, ] genes_log_gmean <- log10(row_gmean(umi, eps = gmean_eps)) if (!do_regularize) { if (show_progress) { 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] genes_log_gmean_step1 <- log10(row_gmean(umi[genes_step1, cells_step1], eps = gmean_eps)) } else { cells_step1 <- colnames(umi) genes_step1 <- genes genes_log_gmean_step1 <- genes_log_gmean } data_step1 <- cell_attr[cells_step1, ] 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) genes_log_gmean_step1 <- log10(row_gmean(umi[genes_step1, cells_step1], eps = gmean_eps)) } 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 (show_progress) { message('Variance stabilizing transformation of count matrix of size ', nrow(umi), ' by ', ncol(umi)) message('Model formula is ', model_str) } model_pars <- get_model_pars(genes_step1, bin_size, umi, model_str, cells_step1, method, data_step1, theta_given, show_progress) if (do_regularize) { model_pars[, 'theta'] <- log10(model_pars[, 'theta']) 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, show_progress) model_pars[, 'theta'] <- 10^model_pars[, 'theta'] model_pars_fit[, 'theta'] <- 10^model_pars_fit[, 'theta'] 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 (show_progress) { 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 = ' + ')) } model_pars_nonreg <- get_model_pars_nonreg(genes, bin_size, model_pars_fit, regressor_data, umi, model_str_nonreg, cell_attr, show_progress) 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 } if (!residual_type == 'none') { if (show_progress) { 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 (show_progress) { 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]) res[genes_bin, ] <- switch(residual_type, 'pearson' = pearson_residual(y, mu, model_pars_final[genes_bin, 'theta'], min_var = min_variance), 'deviance' = deviance_residual(y, mu, model_pars_final[genes_bin, 'theta']) ) if (show_progress) { setTxtProgressBar(pb, i) } } if (show_progress) { close(pb) } } else { if (show_progress) { 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) if (return_corrected_umi) { if (residual_type != 'pearson') { warning("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, show_progress = show_progress) 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 } if (return_gene_attr) { if (show_progress) { message('Calculating gene attributes') } gene_attr <- data.frame( detection_rate = genes_cell_count[genes] / ncol(umi), gmean = 10 ^ genes_log_gmean, 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 (show_progress) { message('Wall clock passed: ', capture.output(print(Sys.time() - start_time))) } return(rv) } get_model_pars <- function(genes_step1, bin_size, umi, model_str, cells_step1, method, data_step1, theta_given, show_progress) { bin_ind <- ceiling(x = 1:length(x = genes_step1) / bin_size) max_bin <- max(bin_ind) if (show_progress) { message('Get Negative Binomial regression parameters per gene') message('Using ', length(x = genes_step1), ' genes, ', length(x = cells_step1), ' cells') } if (show_progress) { 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]) model_pars[[i]] <- do.call(rbind, future_lapply( X = genes_bin_regress, FUN = function(j) { y <- umi_bin[j, ] if (method == 'poisson') { fit <- glm(as.formula(model_str), data = data_step1, family = poisson) theta <- as.numeric(x = theta.ml(y = y, mu = fit$fitted)) return(c(theta, fit$coefficients)) } if (method == 'nb_theta_given') { theta <- theta_given[j] fit2 <- 0 try(fit2 <- glm(as.formula(model_str), data = data_step1, family = negative.binomial(theta=theta)), silent=TRUE) if (inherits(x = fit2, what = 'numeric')) { return(c(theta, glm(as.formula(model_str), data = data_step1, family = poisson)$coefficients)) } else { return(c(theta, fit2$coefficients)) } } if (method == 'nb_fast') { fit <- glm(as.formula(model_str), data = data_step1, family = poisson) theta <- as.numeric(x = theta.ml(y = y, mu = fit$fitted)) fit2 <- 0 try(fit2 <- glm(as.formula(model_str), data = data_step1, family = negative.binomial(theta=theta)), silent=TRUE) if (inherits(x = fit2, what = 'numeric')) { return(c(theta, fit$coefficients)) } else { return(c(theta, fit2$coefficients)) } } if (method == 'nb') { fit <- 0 try(fit <- glm.nb(as.formula(model_str), data = data_step1), silent=TRUE) if (inherits(x = fit, what = 'numeric')) { fit <- glm(as.formula(model_str), data = data_step1, family = poisson) fit$theta <- as.numeric(x = theta.ml(y = y, mu = fit$fitted)) } return(c(fit$theta, fit$coefficients)) } } ) ) if (show_progress) { setTxtProgressBar(pb, i) } } model_pars <- do.call(rbind, model_pars) if (show_progress) { close(pb) } rownames(model_pars) <- genes_step1 colnames(model_pars)[1] <- 'theta' return(model_pars) } get_model_pars_nonreg <- function(genes, bin_size, model_pars_fit, regressor_data, umi, model_str_nonreg, cell_attr, show_progress) { bin_ind <- ceiling(x = 1:length(x = genes) / bin_size) max_bin <- max(bin_ind) if (show_progress) { 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(genes_bin, 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) })) if (show_progress) { setTxtProgressBar(pb, i) } } if (show_progress) { 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, verbose) { genes <- names(genes_log_gmean) # 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) if (sum(outliers) > 0) { if (verbose) { 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] } # 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 theta model_pars_fit[o, 'theta'] <- ksmooth(x = genes_log_gmean_step1, y = model_pars[, 'theta'], 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])) batch_genes_log_gmean_step1 <- log10(row_gmean(umi[genes_step1, sel], eps = gmean_eps)) if (any(is.infinite(batch_genes_log_gmean_step1))) { if (verbose) { 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])) batch_genes_log_gmean <- log10(row_gmean(umi[, sel], eps = gmean_eps)) # 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 } } } attr(model_pars_fit, 'outliers') <- outliers return(model_pars_fit) } sctransform/R/data.R0000644000176200001440000000070113454105530014046 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" sctransform/R/denoise.R0000644000176200001440000001516713576142344014610 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 do_round Round the result to integers #' @param do_pos Set negative values in the result to zero #' @param show_progress Whether to print progress bar #' #' @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, do_round = TRUE, do_pos = TRUE, show_progress = TRUE) { if (is.character(data)) { data <- x[[data]] } # 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))) 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 (show_progress) { message('Computing corrected count matrix for ', length(genes), ' genes') 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 (show_progress) { setTxtProgressBar(pb, i) } } if (show_progress) { 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 show_progress Whether to print progress bar #' #' @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, show_progress = TRUE) { 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))) 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 (show_progress) { message('Computing corrected UMI count matrix') 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 (show_progress) { setTxtProgressBar(pb, i) } } if (show_progress) { 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.R0000644000176200001440000000140713576150065015442 0ustar liggesusers# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 row_mean_dgcmatrix <- function(x, i, rows, cols) { .Call('_sctransform_row_mean_dgcmatrix', PACKAGE = 'sctransform', x, i, rows, cols) } row_gmean_dgcmatrix <- function(x, i, rows, cols, eps) { .Call('_sctransform_row_gmean_dgcmatrix', PACKAGE = 'sctransform', x, i, rows, cols, eps) } row_var_dgcmatrix <- function(x, i, rows, cols) { .Call('_sctransform_row_var_dgcmatrix', PACKAGE = 'sctransform', x, i, rows, cols) } row_var_dense_d <- function(x) { .Call('_sctransform_row_var_dense_d', PACKAGE = 'sctransform', x) } row_var_dense_i <- function(x) { .Call('_sctransform_row_var_dense_i', PACKAGE = 'sctransform', x) } sctransform/R/plotting.R0000644000176200001440000002053513576016340015011 0ustar liggesusers#' Plot estimated and fitted model parameters #' #' @param vst_out The output of a vst run #' @param show_var Whether to show the average model variance; boolean; default is FALSE #' #' @return A ggplot object #' #' @import ggplot2 #' @import reshape2 #' #' @export #' #' @examples #' \dontrun{ #' vst_out <- vst(pbmc, return_gene_attr = TRUE) #' plot_model_pars(vst_out) #' } #' plot_model_pars <- function(vst_out, show_var = FALSE) { 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)') } #tmp model pars mp <- vst_out$model_pars mp[, 1] <- log10(mp[, 1]) colnames(mp)[1] <- 'log10(theta)' ordered_par_names <- colnames(mp)[c(2:ncol(mp), 1)] if (show_var) { mp <- cbind(mp, log10(get_model_var(vst_out, use_nonreg = TRUE))) colnames(mp)[ncol(mp)] <- 'log10(model var)' ordered_par_names <- c(ordered_par_names, 'log10(model var)') } mp_fit <- vst_out$model_pars_fit mp_fit[, 1] <- log10(mp_fit[, 1]) colnames(mp_fit)[1] <- 'log10(theta)' if (show_var) { mp_fit <- cbind(mp_fit, log10(get_model_var(vst_out, use_nonreg = FALSE))) colnames(mp_fit)[ncol(mp_fit)] <- 'log10(model var)' } mpnr <- vst_out$model_pars_nonreg if (!is.null(dim(mpnr))) { colnames(mpnr) <- paste0('nonreg:', colnames(mpnr)) mp_fit <- cbind(mp_fit, 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$gene_gmean <- vst_out$gene_attr[df$gene, 'gmean'] df$is_outl <- vst_out$model_pars_outliers df_fit$gene_gmean <- vst_out$gene_attr[df_fit$gene, 'gmean'] df$type <- 'single gene estimate' df_fit$type <- 'regularized' df_fit$is_outl <- FALSE df_plot <- rbind(df, df_fit) df_plot$parameter <- factor(df_plot$parameter, levels = ordered_par_names) g <- ggplot(df_plot, aes_(x=~log10(gene_gmean), 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='bottom') return(g) } # 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 individaul (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 #' #' @export #' #' @examples #' \dontrun{ #' vst_out <- vst(pbmc, return_cell_attr = TRUE) #' plot_model(vst_out, pbmc, 'PPBP') #' } #' 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 = TRUE, 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) { g <- g + geom_density_2d(color = 'lightblue', size=0.5) } 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.R0000644000176200001440000005071313454105530020060 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 show_progress Show progress bar #' #' @return Data frame of results #' #' @import Matrix #' @importFrom future.apply future_lapply #' @importFrom stats model.matrix p.adjust pchisq #' #' @examples #' \dontrun{ #' 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) #' } #' 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, show_progress = TRUE) { 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 (show_progress) { 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 (show_progress) { 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(genes_bin, function(gene) { model_comparison_ttest(y[gene, use_cells], group) }) } 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(genes_bin, function(gene) { model_comparison_lrt(y[gene, ], mu[gene, ], x$model_pars_fit[gene, 'theta'], group, weights) }) } 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(genes_bin, function(gene) { return(model_comparison_lrt_free3(gene, y[gene, ], y_theta[gene], x$model_str, cell_attr, group, weights, randomize)) }) } res[[i]] <- do.call(rbind, bin_res) if (show_progress) { setTxtProgressBar(pb, i) } } if (show_progress) { 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, show_progress = TRUE) { 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, show_progress = show_progress) 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'], show_progress = show_progress) 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'], show_progress = show_progress) 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))) } sctransform/NEWS.md0000644000176200001440000000070413576016337013725 0ustar liggesusers# News All notable changes will be documented in this file. ## [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/MD50000644000176200001440000000367113576166562013153 0ustar liggesusersaac32a9a2ce0d1be4a00ba965035af18 *DESCRIPTION 84dcc94da3adb52b53ae4fa38fe49e5d *LICENSE 305782a53d9b95be55566b68c675e642 *NAMESPACE 8b748eb188021e32784677762832c344 *NEWS.md 50f755bc9138160bd3d68bc87dd19cb6 *R/RcppExports.R 350499fc5268f0340da805150556e3e6 *R/data.R 77d762408e291773682eae4e3a203a2a *R/denoise.R bc1f791a871fb45ab2409094b8d8e2e7 *R/differential_expression.R c0371cb897fb9f00539ab2dc01475dda *R/generate.R 36bfbf4199128ccff6ca4080170a3501 *R/plotting.R d82bce5c555e753ed92212d49d39dbca *R/utils.R 47fafc6fad0b8645d8fb766b2913d472 *R/vst.R 4860d1c8bfce4643562950cc14deb51b *README.md 8c302f87e051c80640fd342cb5fd2cc6 *data/pbmc.rda 825aa6ea8a8c50ef6895567a3a43193c *man/compare_expression.Rd 4e74c8d04490a13aa6c0d9b2b3a0739f *man/correct.Rd 95235199d1c2d6f642646f30b6753573 *man/correct_counts.Rd e49d8a2d0a614ca4a410a3936ed534e5 *man/generate.Rd 2e74aedc7f309a28786e2e9a29774891 *man/get_model_var.Rd 737ad9a6489f42c9aecbd3b7c7e58f1c *man/get_residual_var.Rd be7e228a16ff749b61df8565fb3043a6 *man/get_residuals.Rd 9d48028b5e5b3ec38a8200df614e36d3 *man/is_outlier.Rd 5001239a42ddbca94cfa114acf77744c *man/pbmc.Rd 5f29f69c49fd4bf37ff4f65e464046f5 *man/plot_model.Rd b3a1c1745ee71e2d9d4165e1fa1323c6 *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 5d8b5be97682e5ee452899b529619794 *man/smooth_via_pca.Rd c6c46aa3dcfaa40ecb5e1e9a1a5a80a3 *man/vst.Rd 8ee7624cdb27b45982c0d97cba864a6d *src/RcppExports.cpp fb083f5efda7e9831e0d43a59704e5fa *src/utils.cpp 47a51cede5d9eb999d1040c9da1301c4 *tests/testthat.R 4fc9dae46a68cfb16f5a45b5f132cdd8 *tests/testthat/test_denoising.R 5d16b85eb6ce0be774151373382ab900 *tests/testthat/test_differential_expression.R be2d7d7baedb37e8cd6044d7c9c9da81 *tests/testthat/test_generate.R 4eafe486469ca07592a4404531eeb119 *tests/testthat/test_vst.R