diff --git a/.Rbuildignore b/.Rbuildignore index bfb0f62ca..7442342ca 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -13,3 +13,4 @@ CODE_OF_CONDUCT.md ^pkgdown$ ^index\.md$ ^vignettes$ +^LICENSE\.md$ diff --git a/DESCRIPTION b/DESCRIPTION index fc7a6d677..ca4569e1f 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: Seurat -Version: 4.0.5 -Date: 2021-10-04 +Version: 4.0.6 +Date: 2021-12-16 Title: Tools for Single Cell Genomics Description: A toolkit for quality control, analysis, and exploration of single cell RNA sequencing data. 'Seurat' aims to enable users to identify and interpret sources of heterogeneity from single cell transcriptomic measurements, and to integrate diverse types of single cell data. See Satija R, Farrell J, Gennert D, et al (2015) , Macosko E, Basu A, Satija R, et al (2015) , Stuart T, Butler A, et al (2019) , and Hao, Hao, et al (2020) for more details. Authors@R: c( @@ -66,7 +66,7 @@ Imports: scales, scattermore (>= 0.7), sctransform (>= 0.3.2), - SeuratObject (>= 4.0.2), + SeuratObject (>= 4.0.4), shiny, spatstat.core, spatstat.geom, @@ -76,7 +76,7 @@ Imports: utils, uwot (>= 0.1.9) LinkingTo: Rcpp (>= 0.11.0), RcppEigen, RcppProgress -License: GPL-3 | file LICENSE +License: MIT + file LICENSE LazyData: true Collate: 'RcppExports.R' @@ -119,4 +119,5 @@ Suggests: limma, metap, enrichR, - mixtools + mixtools, + ggrastr diff --git a/LICENSE b/LICENSE index 9cecc1d46..95c337c65 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,2 @@ - 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 -. +YEAR: 2021 +COPYRIGHT HOLDER: Seurat authors diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 000000000..3d63d994c --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +# MIT License + +Copyright (c) 2021 Seurat authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/NAMESPACE b/NAMESPACE index c847f2c78..8700c46f3 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -69,6 +69,9 @@ S3method(RunLDA,default) S3method(RunPCA,Assay) S3method(RunPCA,Seurat) S3method(RunPCA,default) +S3method(RunSLSI,Assay) +S3method(RunSLSI,Seurat) +S3method(RunSLSI,default) S3method(RunSPCA,Assay) S3method(RunSPCA,Seurat) S3method(RunSPCA,default) @@ -124,6 +127,7 @@ export(AggregateExpression) export(AnnotateAnchors) export(Assays) export(AugmentPlot) +export(AutoPointSize) export(AverageExpression) export(BGTextColor) export(BarcodeInflectionsPlot) @@ -247,6 +251,7 @@ export(NormalizeData) export(PCAPlot) export(PCASigGenes) export(PCHeatmap) +export(PercentAbove) export(PercentageFeatureSet) export(PlotClusterTree) export(PlotPerturbScore) @@ -284,6 +289,7 @@ export(RunMarkVario) export(RunMixscape) export(RunMoransI) export(RunPCA) +export(RunSLSI) export(RunSPCA) export(RunTSNE) export(RunUMAP) @@ -299,8 +305,15 @@ export(SelectIntegrationFeatures) export(SetAssayData) export(SetIdent) export(SetIntegrationData) +export(SetQuantile) export(SeuratAxes) export(SeuratTheme) +export(SingleCorPlot) +export(SingleDimPlot) +export(SingleExIPlot) +export(SingleImageMap) +export(SingleRasterMap) +export(SingleSpatialPlot) export(SpatialDimPlot) export(SpatialFeaturePlot) export(SpatialPlot) @@ -347,7 +360,6 @@ exportClasses(SeuratCommand) exportClasses(SpatialImage) exportClasses(TransferAnchorSet) exportClasses(VisiumV1) -import(Matrix) importClassesFrom(Matrix,dgCMatrix) importClassesFrom(SeuratObject,Assay) importClassesFrom(SeuratObject,DimReduc) @@ -360,6 +372,7 @@ importClassesFrom(SeuratObject,SpatialImage) importFrom(KernSmooth,bkde) importFrom(MASS,glm.nb) importFrom(MASS,lda) +importFrom(Matrix,Matrix) importFrom(Matrix,as.matrix) importFrom(Matrix,colMeans) importFrom(Matrix,colSums) @@ -369,6 +382,7 @@ importFrom(Matrix,rowMeans) importFrom(Matrix,rowSums) importFrom(Matrix,sparse.model.matrix) importFrom(Matrix,sparseMatrix) +importFrom(Matrix,t) importFrom(RANN,nn2) importFrom(RColorBrewer,brewer.pal) importFrom(RColorBrewer,brewer.pal.info) @@ -399,6 +413,7 @@ importFrom(SeuratObject,CreateAssayObject) importFrom(SeuratObject,CreateDimReducObject) importFrom(SeuratObject,CreateSeuratObject) importFrom(SeuratObject,DefaultAssay) +importFrom(SeuratObject,DefaultDimReduc) importFrom(SeuratObject,Distances) importFrom(SeuratObject,Embeddings) importFrom(SeuratObject,FetchData) @@ -417,6 +432,7 @@ importFrom(SeuratObject,Loadings) importFrom(SeuratObject,LogSeuratCommand) importFrom(SeuratObject,Misc) importFrom(SeuratObject,Neighbors) +importFrom(SeuratObject,PackageCheck) importFrom(SeuratObject,Project) importFrom(SeuratObject,Radius) importFrom(SeuratObject,Reductions) @@ -545,11 +561,13 @@ importFrom(grDevices,col2rgb) importFrom(grDevices,colorRampPalette) importFrom(grDevices,rgb) importFrom(graphics,axis) +importFrom(graphics,image) importFrom(graphics,locator) importFrom(graphics,par) importFrom(graphics,plot) importFrom(graphics,plot.new) importFrom(graphics,smoothScatter) +importFrom(graphics,title) importFrom(grid,addGrob) importFrom(grid,editGrob) importFrom(grid,gTree) @@ -617,6 +635,7 @@ importFrom(reticulate,py_module_available) importFrom(reticulate,py_set_seed) importFrom(rlang,"!!") importFrom(rlang,as_label) +importFrom(rlang,invoke) importFrom(scales,brewer_pal) importFrom(scales,hue_pal) importFrom(scales,rescale) @@ -690,6 +709,7 @@ importFrom(utils,argsAnywhere) importFrom(utils,capture.output) importFrom(utils,file_test) importFrom(utils,globalVariables) +importFrom(utils,head) importFrom(utils,isS3method) importFrom(utils,isS3stdGeneric) importFrom(utils,methods) @@ -698,8 +718,10 @@ importFrom(utils,read.csv) importFrom(utils,read.delim) importFrom(utils,read.table) importFrom(utils,setTxtProgressBar) +importFrom(utils,tail) importFrom(utils,txtProgressBar) importFrom(utils,write.table) importFrom(uwot,umap) importFrom(uwot,umap_transform) +importMethodsFrom(Matrix,t) useDynLib(Seurat) diff --git a/NEWS.md b/NEWS.md index 57e6f81a4..2877cc185 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,10 +1,24 @@ -# Seurat 4.0.5 (2020-10-04) +# Seurat 4.0.6 (2021-12-16) +## Added + +- Implement supervised LSI + +## Changes +- Add `raster` parameter to `VlnPlot` to optionally rasterize individual points ([#5076](https://github.com/satijalab/seurat/pull/5076)) +- Add `min.cells.group` parameter to `FindConservedMarkers` ([#5079](https://github.com/satijalab/seurat/pull/5079)) +- Set `do.center` to FALSE for `lsiproject` in `FindTransferAnchors` +- Fix error message in `ReadMtx()` ([#5158](https://github.com/satijalab/seurat/issues/5158)) +- Add `label.color` parameter to `FeaturePlot` ([#5314](https://github.com/satijalab/seurat/pull/5314)) +- Fix issues in `ProjectUMAP` ([#5257](https://github.com/satijalab/seurat/issues/5257), [#5104](https://github.com/satijalab/seurat/issues/5104), [#5373](https://github.com/satijalab/seurat/issues/5373)) + +# Seurat 4.0.5 (2021-10-04) ## Changes - Update documentation for `to.upper` parameter in `Load10X_Spatial()` ([#4576](https://github.com/satijalab/seurat/issues/4576)) - Update concept tags for `RunSPCA()` ([#4978](https://github.com/satijalab/seurat/discussions/4987)) - Conditionally run tests/packages that use suggested packages ([#5160](https://github.com/satijalab/seurat/pull/5160)) +- Set random state in `RunUMAP()` when using the `umap-learn` method ([#5194](https://github.com/satijalab/seurat/issues/5194)) -# Seurat 4.0.4 (2020-08-19) +# Seurat 4.0.4 (2021-08-19) ## Added - Add `reduction` parameter to `BuildClusterTree()` ([#4598](https://github.com/satijalab/seurat/issues/4598)) - Add DensMAP option to `RunUMAP()` ([#4630](https://github.com/satijalab/seurat/pull/4630)) @@ -15,6 +29,7 @@ - Add the `image.alpha` parameter to `SpatialDimPlot()` and `SpatialFeaturePlot()` - Add support for the correlation metric in `RunUMAP` ([#4972](https://github.com/satijalab/seurat/issues/4972)) + ## Changes - Warn and continue rather than erroring if not all features are available in `FindSpatiallyVariableFeatures()` ([#4611](https://github.com/satijalab/seurat/issues/4611)) - Bug fix for SCT-based integration in selecting proper reference model ([#4355](https://github.com/satijalab/seurat/issues/4355)) @@ -26,7 +41,7 @@ - Fix issue in SingleCellExperiment conversion where the mainExp would not be set properly - Fix for default dispersion info displayed in `VariableFeaturePlot()` -# Seurat 4.0.3 (2020-06-10) +# Seurat 4.0.3 (2021-06-10) ## Added - Add `jitter` parameter to `FeatureScatter()` diff --git a/R/RcppExports.R b/R/RcppExports.R index dc597cc64..bf0f9e645 100644 --- a/R/RcppExports.R +++ b/R/RcppExports.R @@ -109,3 +109,15 @@ SNN_SmallestNonzero_Dist <- function(snn, mat, n, nearest_dist) { .Call('_Seurat_SNN_SmallestNonzero_Dist', PACKAGE = 'Seurat', snn, mat, n, nearest_dist) } +row_sum_dgcmatrix <- function(x, i, rows, cols) { + .Call('_Seurat_row_sum_dgcmatrix', PACKAGE = 'Seurat', x, i, rows, cols) +} + +row_mean_dgcmatrix <- function(x, i, rows, cols) { + .Call('_Seurat_row_mean_dgcmatrix', PACKAGE = 'Seurat', x, i, rows, cols) +} + +row_var_dgcmatrix <- function(x, i, rows, cols) { + .Call('_Seurat_row_var_dgcmatrix', PACKAGE = 'Seurat', x, i, rows, cols) +} + diff --git a/R/differential_expression.R b/R/differential_expression.R index a579d36ef..b4134fa14 100644 --- a/R/differential_expression.R +++ b/R/differential_expression.R @@ -241,6 +241,7 @@ FindConservedMarkers <- function( grouping.var, assay = 'RNA', slot = 'data', + min.cells.group = 3, meta.method = metap::minimump, verbose = TRUE, ... @@ -298,6 +299,20 @@ FindConservedMarkers <- function( } ident.2 <- ident.2.save cells.1 <- WhichCells(object = object, idents = ident.use.1) + if (length(cells.1) < min.cells.group) { + warning( + level.use, + " has fewer than ", + min.cells.group, + " cells in Identity: ", + paste(ident.1, collapse = ", "), + ". Skipping ", + level.use, + call. = FALSE, + immediate. = TRUE + ) + next + } if (is.null(x = ident.2)) { cells.2 <- setdiff(x = cells[[i]], y = cells.1) ident.use.2 <- names(x = which(x = table(Idents(object = object)[cells.2]) > 0)) diff --git a/R/dimensional_reduction.R b/R/dimensional_reduction.R index 322ff6880..581f35427 100644 --- a/R/dimensional_reduction.R +++ b/R/dimensional_reduction.R @@ -335,7 +335,7 @@ ProjectUMAP.default <- function( query.dims = NULL, reference, reference.dims = NULL, - k.param = 20, + k.param = 30, nn.method = "annoy", n.trees = 50, annoy.metric = "cosine", @@ -389,7 +389,7 @@ ProjectUMAP.DimReduc <- function( query.dims = NULL, reference, reference.dims = NULL, - k.param = 20, + k.param = 30, nn.method = "annoy", n.trees = 50, annoy.metric = "cosine", @@ -439,7 +439,7 @@ ProjectUMAP.Seurat <- function( reference, reference.reduction, reference.dims = NULL, - k.param = 20, + k.param = 30, nn.method = "annoy", n.trees = 50, annoy.metric = "cosine", @@ -479,6 +479,7 @@ ProjectUMAP.Seurat <- function( neighbor.name = neighbor.name, reduction.model = reference[[reduction.model]], reduction.key = reduction.key, + assay = DefaultAssay(query), ... ) query[[reduction.name]] <- proj.umap$proj.umap @@ -1265,6 +1266,9 @@ RunUMAP.default <- function( if (!py_module_available(module = 'umap')) { stop("Cannot find UMAP, please install through pip (e.g. pip install umap-learn).") } + if (!py_module_available(module = 'sklearn')) { + stop("Cannot find sklearn, please install through pip (e.g. pip install scikit-learn).") + } if (!is.null(x = seed.use)) { py_set_seed(seed = seed.use) } @@ -1272,11 +1276,13 @@ RunUMAP.default <- function( n.epochs <- as.integer(x = n.epochs) } umap_import <- import(module = "umap", delay_load = TRUE) + sklearn <- import("sklearn", delay_load = TRUE) if (densmap && numeric_version(x = umap_import$pkg_resources$get_distribution("umap-learn")$version) < numeric_version(x = "0.5.0")) { stop("densmap is only supported by versions >= 0.5.0 of umap-learn. Upgrade umap-learn (e.g. pip install --upgrade umap-learn).") } + random.state <- sklearn$utils$check_random_state(seed = as.integer(x = seed.use)) umap.args <- list( n_neighbors = as.integer(x = n.neighbors), n_components = as.integer(x = n.components), @@ -1289,6 +1295,7 @@ RunUMAP.default <- function( local_connectivity = local.connectivity, repulsion_strength = repulsion.strength, negative_sample_rate = negative.sample.rate, + random_state = random.state, a = a, b = b, metric_kwds = metric.kwds, @@ -1379,7 +1386,12 @@ RunUMAP.default <- function( ) } if (is.list(x = object)) { - uwot::umap_transform( + if (ncol(object$idx) != model$n_neighbors) { + warning("Number of neighbors between query and reference ", + "is not equal to the number of neighbros within reference") + model$n_neighbors <- ncol(object$idx) + } + umap_transform( X = NULL, nn_method = object, model = model, @@ -2259,13 +2271,14 @@ L2Norm <- function(vec) { PrepDR <- function( object, features = NULL, + slot = 'scale.data', verbose = TRUE ) { if (length(x = VariableFeatures(object = object)) == 0 && is.null(x = features)) { stop("Variable features haven't been set. Run FindVariableFeatures() or provide a vector of feature names.") } - data.use <- GetAssayData(object = object, slot = "scale.data") - if (nrow(x = data.use ) == 0) { + data.use <- GetAssayData(object = object, slot = slot) + if (nrow(x = data.use ) == 0 && slot == "scale.data") { stop("Data has not been scaled. Please run ScaleData and retry") } features <- features %||% VariableFeatures(object = object) @@ -2277,7 +2290,13 @@ PrepDR <- function( } } features <- features.keep - features.var <- apply(X = data.use[features, ], MARGIN = 1, FUN = var) + + if (inherits(x = data.use, what = 'dgCMatrix')) { + features.var <- RowVarSparse(mat = data.use[features, ]) + } + else { + features.var <- RowVar(x = data.use[features, ]) + } features.keep <- features[features.var > 0] if (length(x = features.keep) < length(x = features)) { features.exclude <- setdiff(x = features, y = features.keep) @@ -2419,3 +2438,143 @@ RunSPCA.Seurat <- function( object <- LogSeuratCommand(object = object) return(object) } + +#' @param assay Name of Assay SLSI is being run on +#' @param n Total Number of SLSI components to compute and store +#' @param verbose Display messages +#' @param reduction.key dimensional reduction key, specifies the string before +#' the number for the dimension names +#' @param graph Graph used supervised by SLSI +#' @param seed.use Set a random seed. Setting NULL will not set a seed. +#' +#' @importFrom irlba irlba +#' @importMethodsFrom Matrix t +#' +#' @concept dimensional_reduction +#' @rdname RunSLSI +#' @export +RunSLSI.default <- function( + object, + assay = NULL, + n = 50, + reduction.key = "SLSI_", + graph = NULL, + verbose = TRUE, + seed.use = 42, + ... +) { + if (!is.null(x = seed.use)) { + set.seed(seed = seed.use) + } + n <- min(n, nrow(x = object) - 1) + + if (verbose) { + message("Smoothing peaks matrix") + } + object.smooth <- t(x = graph) %*% (t(x = object) %*% object) %*% graph + if (verbose) { + message("Performing eigendecomposition") + } + svd.V <- irlba(A = object.smooth, nv = n, nu = n, ...) + sigma <- sqrt(x = svd.V$d) + feature.loadings <- object %*% (graph %*% svd.V$u) %*% diag(x = 1/sigma) + feature.loadings <- as.matrix(x = feature.loadings) + cell.embeddings <- t(x = object) %*% feature.loadings %*% diag(x = 1/sigma) + cell.embeddings <- as.matrix(x = cell.embeddings) + + # construct svd list stored in misc for LSI projection + svd.lsi <- svd.V + svd.lsi$d <- sigma + svd.lsi$u <- feature.loadings + svd.lsi$v <- cell.embeddings + + colnames(x = cell.embeddings) <- paste0(reduction.key, 1:ncol(cell.embeddings)) + reduction.data <- CreateDimReducObject( + embeddings = cell.embeddings, + loadings = feature.loadings, + key = reduction.key, + assay = assay, + misc = svd.lsi + ) + return(reduction.data) +} + +#' @param features Features to compute SLSI on. If NULL, SLSI will be run +#' using the variable features for the Assay. +#' +#' @rdname RunSLSI +#' @concept dimensional_reduction +#' @export +#' @method RunSLSI Assay +#' +RunSLSI.Assay <- function( + object, + assay = NULL, + features = NULL, + n = 50, + reduction.key = "SLSI_", + graph = NULL, + verbose = TRUE, + seed.use = 42, + ... +) { + data.use <- PrepDR( + object = object, + features = features, + slot = "data", + verbose = verbose + ) + reduction.data <- RunSLSI( + object = data.use, + assay = assay, + n = n, + reduction.key = reduction.key, + graph = graph, + verbose = verbose, + seed.use = seed.use, + ... + ) + return(reduction.data) +} + +#' @param reduction.name dimensional reduction name +#' @rdname RunSLSI +#' @concept dimensional_reduction +#' @export +#' @method RunSLSI Seurat +#' +RunSLSI.Seurat <- function( + object, + assay = NULL, + features = NULL, + n = 50, + reduction.name = "slsi", + reduction.key = "SLSI_", + graph = NULL, + verbose = TRUE, + seed.use = 42, + ... +) { + assay <- assay %||% DefaultAssay(object = object) + assay.data <- GetAssay(object = object, assay = assay) + if (is.null(x = graph)) { + stop("Graph is not provided") + } else if (is.character(x = graph)) { + graph <- object[[graph]] + } + reduction.data <- RunSLSI( + object = assay.data, + assay = assay, + features = features, + n = n, + reduction.name = reduction.name, + reduction.key = reduction.key, + graph = graph, + verbose = verbose, + seed.use = seed.use, + ... + ) + object[[reduction.name]] <- reduction.data + object <- LogSeuratCommand(object = object) + return(object) +} diff --git a/R/generics.R b/R/generics.R index ba893f0df..f1a10e795 100644 --- a/R/generics.R +++ b/R/generics.R @@ -441,9 +441,30 @@ RunPCA <- function(object, ...) { UseMethod(generic = 'RunPCA', object = object) } +#' Run Supervised Latent Semantic Indexing +#' +#' Run a supervised LSI (SLSI) dimensionality reduction supervised by a +#' cell-cell kernel. SLSI is used to capture a linear transformation of peaks +#' that maximizes its dependency to the given cell-cell kernel. +#' +#' @param object An object +#' @param ... Arguments passed to IRLBA irlba +#' +#' @return Returns Seurat object with the SLSI calculation stored in the +#' reductions slot +#' +#' @export +#' +#' @rdname RunSLSI +#' @export RunSLSI +#' +RunSLSI <- function(object, ...) { + UseMethod(generic = 'RunSLSI', object = object) +} + #' Run Supervised Principal Component Analysis #' -#' Run a supervied PCA (SPCA) dimensionality reduction supervised by a cell-cell kernel. +#' Run a supervised PCA (SPCA) dimensionality reduction supervised by a cell-cell kernel. #' SPCA is used to capture a linear transformation which maximizes its dependency to #' the given cell-cell kernel. We use SNN graph as the kernel to supervise the linear #' matrix factorization. diff --git a/R/integration.R b/R/integration.R index 81c34006b..00b7e5e58 100644 --- a/R/integration.R +++ b/R/integration.R @@ -1041,7 +1041,7 @@ FindTransferAnchors <- function( reduction = query[[reference.reduction]], data = GetAssayData(object = reference, assay = reference.assay, slot = "data"), mode = "lsi", - do.center = TRUE, + do.center = FALSE, do.scale = FALSE, use.original.stats = FALSE, verbose = verbose @@ -1053,7 +1053,7 @@ FindTransferAnchors <- function( reduction = reference[[reference.reduction]], data = GetAssayData(object = query, assay = query.assay, slot = "data"), mode = "lsi", - do.center = TRUE, + do.center = FALSE, do.scale = FALSE, use.original.stats = FALSE, verbose = verbose @@ -1749,6 +1749,7 @@ IntegrateEmbeddings.TransferAnchorSet <- function( } slot(object = anchorset, name = "object.list") <- object.list new.reduction.name.safe <- gsub(pattern = "_", replacement = "", x = new.reduction.name) + new.reduction.name.safe <- gsub(pattern = "[.]", replacement = "", x = new.reduction.name) slot(object = anchorset, name = "reference.objects") <- 1 anchors <- as.data.frame(x = anchors) anchors$dataset1 <- 1 @@ -1910,6 +1911,8 @@ LocalStruct <- function( #' reference UMAP using \code{\link{ProjectUMAP}}} #' } #' +#' @importFrom rlang invoke +#' #' @export #' @concept integration #' @@ -2002,9 +2005,9 @@ MapQuery <- function( slot(object = query, name = "tools")$TransferData <- NULL reuse.weights.matrix <- FALSE if (!is.null(x = refdata)) { - query <- do.call( - what = TransferData, - args = c(list( + query <- invoke( + .fn = TransferData, + .args = c(list( anchorset = anchorset, reference = reference, query = query, @@ -2019,9 +2022,9 @@ MapQuery <- function( } } if (anchor.reduction != "cca"){ - query <- do.call( - what = IntegrateEmbeddings, - args = c(list( + query <- invoke( + .fn = IntegrateEmbeddings, + .args = c(list( anchorset = anchorset, reference = reference, query = query, @@ -2040,16 +2043,18 @@ MapQuery <- function( message("Query and reference dimensions are not equal, proceeding with reference dimensions.") query.dims <- reference.dims } - query <- do.call( - what = ProjectUMAP, - args = c(list( + ref_nn.num <- Misc(object = reference[[reduction.model]], slot = "model")$n_neighbors + query <- invoke( + .fn = ProjectUMAP, + .args = c(list( query = query, query.reduction = new.reduction.name, query.dims = query.dims, reference = reference, reference.dims = reference.dims, reference.reduction = reference.reduction, - reduction.model = reduction.model + reduction.model = reduction.model, + k.param = ref_nn.num ), projectumap.args ) ) @@ -2615,6 +2620,8 @@ PrepSCTIntegration <- function( #' #' @return A vector of selected features #' +#' @importFrom utils head +#' #' @export #' @concept integration #' @@ -3966,7 +3973,7 @@ MapQueryData <- function( X = query.datasets, FUN = function(dataset1) { if (verbose) { - message("Integrating dataset ", dataset1, " with reference dataset") + message("\nIntegrating dataset ", dataset1, " with reference dataset") } filtered.anchors <- anchors[anchors$dataset1 %in% reference.datasets & anchors$dataset2 == dataset1, ] integrated <- RunIntegration( diff --git a/R/objects.R b/R/objects.R index e20b99b85..f772f8e33 100644 --- a/R/objects.R +++ b/R/objects.R @@ -2309,6 +2309,8 @@ setMethod( } ) +#' @importFrom utils head +# setMethod( f = 'show', signature = 'SCTAssay', @@ -2631,6 +2633,8 @@ SubsetVST <- function(sct.info, cells, features) { # @return The top \code{num} # @seealso \{code{\link{TopCells}}} \{code{\link{TopFeatures}}} # +#' @importFrom utils head tail +# Top <- function(data, num, balanced) { nr <- nrow(x = data) if (num > nr) { @@ -2833,6 +2837,8 @@ UpdateSlots <- function(object) { # @return Returns the data matrix if present (i.e.) not 0x0. Otherwise, returns an # appropriately sized empty sparse matrix # +#' @importFrom Matrix Matrix +# ValidateDataForMerge <- function(assay, slot) { mat <- GetAssayData(object = assay, slot = slot) if (any(dim(x = mat) == c(0, 0))) { diff --git a/R/preprocessing.R b/R/preprocessing.R index 335dd78d4..f04537494 100644 --- a/R/preprocessing.R +++ b/R/preprocessing.R @@ -606,7 +606,6 @@ LoadSTARmap <- function( #' #' @return Returns a matrix with the normalize and log transformed data #' -#' @import Matrix #' @importFrom methods as #' #' @export @@ -649,8 +648,6 @@ LogNormalize <- function(data, scale.factor = 1e4, verbose = TRUE) { #' #' @return A Seurat object with demultiplexing results stored at \code{object$MULTI_ID} #' -#' @import Matrix -#' #' @export #' @concept preprocessing #' @@ -1224,7 +1221,7 @@ ReadMtx <- function( if (length(x = feature.names) != nrow(x = data)) { stop( "Matrix has ", - ncol(data), + nrow(data), " rows but found ", length(feature.names), " features. ", ifelse( @@ -1284,8 +1281,8 @@ ReadSlideSeq <- function(coord.file, assay = 'Spatial') { #' @param verbose Print progress #' @return Returns a matrix with the relative counts #' -#' @import Matrix #' @importFrom methods as +#' @importFrom Matrix colSums #' #' @export #' @concept preprocessing @@ -1307,7 +1304,7 @@ RelativeCounts <- function(data, scale.factor = 1, verbose = TRUE) { cat("Performing relative-counts-normalization\n", file = stderr()) } norm.data <- data - norm.data@x <- norm.data@x / rep.int(colSums(norm.data), diff(norm.data@p)) * scale.factor + norm.data@x <- norm.data@x / rep.int(Matrix::colSums(norm.data), diff(norm.data@p)) * scale.factor return(norm.data) } @@ -1432,7 +1429,6 @@ RunMoransI <- function(data, pos, verbose = TRUE) { #' @param upsample Upsamples all cells with fewer than max.umi #' @param verbose Display the progress bar #' -#' @import Matrix #' @importFrom methods as #' #' @return Matrix with downsampled data @@ -2008,6 +2004,8 @@ FindVariableFeatures.default <- function( #' #' @rdname FindVariableFeatures #' @concept preprocessing +#' +#' @importFrom utils head #' @export #' @method FindVariableFeatures Assay #' @@ -3091,9 +3089,9 @@ ComputeRMetric <- function(mv, r.metric = 5) { # # @return Returns a matrix with the custom normalization # +#' @importFrom Matrix t #' @importFrom methods as #' @importFrom pbapply pbapply -# @import Matrix # CustomNormalize <- function(data, custom_function, margin, verbose = TRUE) { if (is.data.frame(x = data)) { @@ -3117,7 +3115,7 @@ CustomNormalize <- function(data, custom_function, margin, verbose = TRUE) { MARGIN = margin, FUN = custom_function) if (margin == 1) { - norm.data = t(x = norm.data) + norm.data = Matrix::t(x = norm.data) } colnames(x = norm.data) <- colnames(x = data) rownames(x = norm.data) <- rownames(x = data) diff --git a/R/reexports.R b/R/reexports.R index 29820e40b..0763d0a0b 100644 --- a/R/reexports.R +++ b/R/reexports.R @@ -146,349 +146,299 @@ NULL #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #' @importFrom SeuratObject AddMetaData -#' @rdname reexports #' @export #' SeuratObject::AddMetaData #' @importFrom SeuratObject as.Graph -#' @rdname reexports #' @export #' SeuratObject::as.Graph #' @importFrom SeuratObject as.Neighbor -#' @rdname reexports #' @export #' SeuratObject::as.Neighbor #' @importFrom SeuratObject as.Seurat -#' @rdname reexports #' @export #' SeuratObject::as.Seurat #' @importFrom SeuratObject as.sparse -#' @rdname reexports #' @export #' SeuratObject::as.sparse #' @importFrom SeuratObject Assays -#' @rdname reexports #' @export #' SeuratObject::Assays #' @importFrom SeuratObject Cells -#' @rdname reexports #' @export #' SeuratObject::Cells #' @importFrom SeuratObject CellsByIdentities -#' @rdname reexports #' @export #' SeuratObject::CellsByIdentities #' @importFrom SeuratObject Command -#' @rdname reexports + #' @export #' SeuratObject::Command #' @importFrom SeuratObject CreateAssayObject -#' @rdname reexports + #' @export #' SeuratObject::CreateAssayObject #' @importFrom SeuratObject CreateDimReducObject -#' @rdname reexports #' @export #' SeuratObject::CreateDimReducObject #' @importFrom SeuratObject CreateSeuratObject -#' @rdname reexports + #' @export #' SeuratObject::CreateSeuratObject #' @importFrom SeuratObject DefaultAssay -#' @rdname reexports #' @export #' SeuratObject::DefaultAssay #' @importFrom SeuratObject DefaultAssay<- -#' @rdname reexports #' @export #' SeuratObject::`DefaultAssay<-` #' @importFrom SeuratObject Distances -#' @rdname reexports #' @export #' SeuratObject::Distances #' @importFrom SeuratObject Embeddings -#' @rdname reexports #' @export #' SeuratObject::Embeddings #' @importFrom SeuratObject FetchData -#' @rdname reexports #' @export #' SeuratObject::FetchData #' @importFrom SeuratObject GetAssayData -#' @rdname reexports #' @export #' SeuratObject::GetAssayData #' @importFrom SeuratObject GetImage -#' @rdname reexports #' @export #' SeuratObject::GetImage #' @importFrom SeuratObject GetTissueCoordinates -#' @rdname reexports #' @export #' SeuratObject::GetTissueCoordinates #' @importFrom SeuratObject HVFInfo -#' @rdname reexports #' @export #' SeuratObject::HVFInfo #' @importFrom SeuratObject Idents -#' @rdname reexports #' @export #' SeuratObject::Idents #' @importFrom SeuratObject Idents<- -#' @rdname reexports #' @export #' SeuratObject::`Idents<-` #' @importFrom SeuratObject Images -#' @rdname reexports #' @export #' SeuratObject::Images #' @importFrom SeuratObject Index -#' @rdname reexports #' @export #' SeuratObject::Index #' @importFrom SeuratObject Index<- -#' @rdname reexports #' @export #' SeuratObject::`Index<-` #' @importFrom SeuratObject Indices -#' @rdname reexports #' @export #' SeuratObject::Indices #' @importFrom SeuratObject IsGlobal -#' @rdname reexports #' @export #' SeuratObject::IsGlobal #' @importFrom SeuratObject JS -#' @rdname reexports #' @export #' SeuratObject::JS #' @importFrom SeuratObject JS<- -#' @rdname reexports + #' @export #' SeuratObject::`JS<-` #' @importFrom SeuratObject Key -#' @rdname reexports #' @export #' SeuratObject::Key #' @importFrom SeuratObject Key<- -#' @rdname reexports + #' @export #' SeuratObject::`Key<-` #' @importFrom SeuratObject Loadings -#' @rdname reexports + #' @export #' SeuratObject::Loadings #' @importFrom SeuratObject Loadings<- -#' @rdname reexports #' @export #' SeuratObject::`Loadings<-` #' @importFrom SeuratObject LogSeuratCommand -#' @rdname reexports + #' @export #' SeuratObject::LogSeuratCommand #' @importFrom SeuratObject Misc -#' @rdname reexports #' @export #' SeuratObject::Misc #' @importFrom SeuratObject Misc<- -#' @rdname reexports #' @export #' SeuratObject::`Misc<-` #' @importFrom SeuratObject Neighbors -#' @rdname reexports #' @export #' SeuratObject::Neighbors #' @importFrom SeuratObject Project -#' @rdname reexports #' @export #' SeuratObject::Project #' @importFrom SeuratObject Project<- -#' @rdname reexports #' @export #' SeuratObject::`Project<-` #' @importFrom SeuratObject Radius -#' @rdname reexports #' @export #' SeuratObject::Radius #' @importFrom SeuratObject Reductions -#' @rdname reexports #' @export #' SeuratObject::Reductions #' @importFrom SeuratObject RenameCells -#' @rdname reexports #' @export #' SeuratObject::RenameCells #' @importFrom SeuratObject RenameIdents -#' @rdname reexports #' @export #' SeuratObject::RenameIdents #' @importFrom SeuratObject ReorderIdent -#' @rdname reexports #' @export #' SeuratObject::ReorderIdent #' @importFrom SeuratObject RowMergeSparseMatrices -#' @rdname reexports #' @export #' SeuratObject::RowMergeSparseMatrices #' @importFrom SeuratObject SetAssayData -#' @rdname reexports #' @export #' SeuratObject::SetAssayData #' @importFrom SeuratObject SetIdent -#' @rdname reexports #' @export #' SeuratObject::SetIdent #' @importFrom SeuratObject SpatiallyVariableFeatures -#' @rdname reexports #' @export #' SeuratObject::SpatiallyVariableFeatures #' @importFrom SeuratObject StashIdent -#' @rdname reexports #' @export #' SeuratObject::StashIdent #' @importFrom SeuratObject Stdev -#' @rdname reexports #' @export #' SeuratObject::Stdev #' @importFrom SeuratObject SVFInfo -#' @rdname reexports #' @export #' SeuratObject::SVFInfo #' @importFrom SeuratObject Tool -#' @rdname reexports #' @export #' SeuratObject::Tool #' @importFrom SeuratObject Tool<- -#' @rdname reexports #' @export #' SeuratObject::`Tool<-` #' @importFrom SeuratObject UpdateSeuratObject -#' @rdname reexports #' @export #' SeuratObject::UpdateSeuratObject #' @importFrom SeuratObject VariableFeatures -#' @rdname reexports + #' @export #' SeuratObject::VariableFeatures #' @importFrom SeuratObject VariableFeatures<- -#' @rdname reexports #' @export #' SeuratObject::`VariableFeatures<-` #' @importFrom SeuratObject WhichCells -#' @rdname reexports #' @export #' SeuratObject::WhichCells diff --git a/R/utilities.R b/R/utilities.R index 6ae270517..65741c2a2 100644 --- a/R/utilities.R +++ b/R/utilities.R @@ -1,4 +1,5 @@ #' @include generics.R +#' @importFrom SeuratObject PackageCheck #' NULL @@ -580,6 +581,7 @@ CellCycleScoring <- function( #' \code{ncontrols} most highly expressed features are kept, and the #' prefix is kept. All other rows are retained. #' +#' @importFrom utils head #' @importFrom Matrix rowSums #' #' @export @@ -983,6 +985,27 @@ GroupCorrelation <- function( return(object) } +#' Load the Annoy index file +#' +#' @param object Neighbor object +#' @param file Path to file with annoy index +#' +#' @return Returns the Neighbor object with the index stored +#' @export +#' @concept utilities +#' +LoadAnnoyIndex <- function(object, file){ + metric <- slot(object = object, name = "alg.info")$metric + ndim <- slot(object = object, name = "alg.info")$ndim + if (is.null(x = metric)) { + stop("Provided Neighbor object wasn't generated with annoy") + } + annoy.idx <- CreateAnn(name = metric, ndim = ndim) + annoy.idx$load(path.expand(path = file)) + Index(object = object) <- annoy.idx + return(object) +} + #' Calculate the variance to mean ratio of logged values #' #' Calculate the variance to mean ratio (VMR) in non-logspace (return answer in @@ -1081,6 +1104,24 @@ MinMax <- function(data, min, max) { return(data2) } +#' Calculate the percentage of a vector above some threshold +#' +#' @param x Vector of values +#' @param threshold Threshold to use when calculating percentage +#' +#' @return Returns the percentage of \code{x} values above the given threshold +#' +#' @export +#' @concept utilities +#' +#' @examples +#' set.seed(42) +#' PercentAbove(sample(1:100, 10), 75) +#' +PercentAbove <- function(x, threshold) { + return(length(x = x[x > threshold]) / length(x = x)) +} + #' Calculate the percentage of all counts that belong to a given set of features #' #' This function enables you to easily calculate the percentage of all the counts belonging to a @@ -1412,24 +1453,34 @@ PseudobulkExpression <- function( } } -#' Load the Annoy index file +#' Regroup idents based on meta.data info #' -#' @param object Neighbor object -#' @param file Path to file with annoy index +#' For cells in each ident, set a new identity based on the most common value +#' of a specified metadata column. +#' +#' @param object Seurat object +#' @param metadata Name of metadata column +#' @return A Seurat object with the active idents regrouped #' -#' @return Returns the Neighbor object with the index stored #' @export #' @concept utilities #' -LoadAnnoyIndex <- function(object, file){ - metric <- slot(object = object, name = "alg.info")$metric - ndim <- slot(object = object, name = "alg.info")$ndim - if (is.null(x = metric)) { - stop("Provided Neighbor object wasn't generated with annoy") +#' @examples +#' data("pbmc_small") +#' pbmc_small <- RegroupIdents(pbmc_small, metadata = "groups") +#' +RegroupIdents <- function(object, metadata) { + for (ii in levels(x = object)) { + ident.cells <- WhichCells(object = object, idents = ii) + if (length(x = ident.cells) == 0) { + next + } + new.ident <- names(x = which.max(x = table(object[[metadata]][ident.cells, ]))) + if (is.null(x = new.ident)) { + stop("Cluster ", ii, " contains only cells with NA values in the '", metadata, "' metadata column.") + } + Idents(object = object, cells = ident.cells) <- new.ident } - annoy.idx <- CreateAnn(name = metric, ndim = ndim) - annoy.idx$load(path.expand(path = file)) - Index(object = object) <- annoy.idx return(object) } @@ -1452,35 +1503,39 @@ SaveAnnoyIndex <- function( index$save(path.expand(path = file)) } -#' Regroup idents based on meta.data info +#' Find the Quantile of Data #' -#' For cells in each ident, set a new identity based on the most common value -#' of a specified metadata column. +#' Converts a quantile in character form to a number regarding some data. +#' String form for a quantile is represented as a number prefixed with +#' \dQuote{q}; for example, 10th quantile is \dQuote{q10} while 2nd quantile is +#' \dQuote{q2}. Will only take a quantile of non-zero data values #' -#' @param object Seurat object -#' @param metadata Name of metadata column -#' @return A Seurat object with the active idents regrouped +#' @param cutoff The cutoff to turn into a quantile +#' @param data The data to turn find the quantile of +#' +#' @return The numerical representation of the quantile +#' +#' @importFrom stats quantile #' #' @export #' @concept utilities #' #' @examples -#' data("pbmc_small") -#' pbmc_small <- RegroupIdents(pbmc_small, metadata = "groups") -#' -RegroupIdents <- function(object, metadata) { - for (ii in levels(x = object)) { - ident.cells <- WhichCells(object = object, idents = ii) - if (length(x = ident.cells) == 0) { - next - } - new.ident <- names(x = which.max(x = table(object[[metadata]][ident.cells, ]))) - if (is.null(x = new.ident)) { - stop("Cluster ", ii, " contains only cells with NA values in the '", metadata, "' metadata column.") - } - Idents(object = object, cells = ident.cells) <- new.ident - } - return(object) +#' set.seed(42) +#' SetQuantile('q10', sample(1:100, 10)) +#' +SetQuantile <- function(cutoff, data) { + if (grepl(pattern = '^q[0-9]{1,2}$', x = as.character(x = cutoff), perl = TRUE)) { + this.quantile <- as.numeric(x = sub( + pattern = 'q', + replacement = '', + x = as.character(x = cutoff) + )) / 100 + data <- unlist(x = data) + data <- data[data > 0] + cutoff <- quantile(x = data, probs = this.quantile) + } + return(as.numeric(x = cutoff)) } #' @rdname UpdateSymbolList @@ -2158,31 +2213,6 @@ Online <- function(url, strict = FALSE, seconds = 5L) { return(comp(x = status_code(x = request), y = code)) } -# Check the existence of a package -# -# @param ... Package names -# @param error If true, throw an error if the package doesn't exist -# -# @return Invisibly returns boolean denoting if the package is installed -# -PackageCheck <- function(..., error = TRUE) { - pkgs <- unlist(x = c(...), use.names = FALSE) - package.installed <- vapply( - X = pkgs, - FUN = requireNamespace, - FUN.VALUE = logical(length = 1L), - quietly = TRUE - ) - if (error && any(!package.installed)) { - stop( - "Cannot find the following packages: ", - paste(pkgs[!package.installed], collapse = ', '), - ". Please install" - ) - } - invisible(x = package.installed) -} - # Parenting parameters from one environment to the next # # This function allows one to modify a parameter in a parent environment @@ -2231,17 +2261,6 @@ Parenting <- function(parent.find = 'Seurat', ...) { } } -# Calculate the percentage of a vector above some threshold -# -# @param x Vector of values -# @param threshold Threshold to use when calculating percentage -# -# @return Returns the percentage of `x` values above the given threshold -# -PercentAbove <- function(x, threshold) { - return(length(x = x[x > threshold]) / length(x = x)) -} - # Generate a random name # # Make a name from randomly sampled lowercase letters, @@ -2285,6 +2304,71 @@ RemoveLastField <- function(string, delim = "_") { } } +# Calculate row mean of a sparse matrix +# @param mat sparse matrix +# @return A vector of row mean +# +RowMeanSparse <- function(mat) { + mat <- RowSparseCheck(mat = mat) + output <- row_mean_dgcmatrix( + x = slot(object = mat, name = "x"), + i = slot(object = mat, name = "i"), + rows = nrow(x = mat), + cols = ncol(x = mat) + ) + names(x = output) <- rownames(x = mat) + return(output) +} + +# Calculate row sum of a sparse matrix +# +# @param mat sparse matrix +# @return A vector of row sum +# +RowSumSparse <- function(mat) { + mat <- RowSparseCheck(mat = mat) + output <- row_sum_dgcmatrix( + x = slot(object = mat, name = "x"), + i = slot(object = mat, name = "i"), + rows = nrow(x = mat), + cols = ncol(x = mat) + ) + names(x = output) <- rownames(x = mat) + return(output) +} + +# Calculate row variance of a sparse matrix +# +# @param mat sparse matrix +# @return A vector of row variance +# +RowVarSparse <- function(mat) { + mat <- RowSparseCheck(mat = mat) + output <- row_var_dgcmatrix( + x = slot(object = mat, name = "x"), + i = slot(object = mat, name = "i"), + rows = nrow(x = mat), + cols = ncol(x = mat) + ) + names(x = output) <- rownames(x = mat) + return(output) +} + +# Check if the input matrix is dgCMatrix +# +# @param mat sparse matrix +# @return A dgCMatrix +# +RowSparseCheck <- function(mat) { + if (!inherits(x = mat, what = "sparseMatrix")) { + stop("Input should be sparse matrix") + } else if (class(x = mat) != "dgCMatrix") { + warning("Input matrix is converted to dgCMatrix.") + mat <- as.sparse(x = mat) + } + return(mat) +} + # Sweep out array summaries # # Reimplmentation of \code{\link[base]{sweep}} to maintain compatability with diff --git a/R/visualization.R b/R/visualization.R index e0d06af24..067af9fb2 100644 --- a/R/visualization.R +++ b/R/visualization.R @@ -1,5 +1,6 @@ #' @importFrom utils globalVariables #' @importFrom ggplot2 ggproto GeomViolin +#' @importFrom SeuratObject DefaultDimReduc #' NULL @@ -16,7 +17,7 @@ NULL #' @param dims Dimensions to plot #' @param nfeatures Number of genes to plot #' @param cells A list of cells to plot. If numeric, just plots the top cells. -#' @param reduction Which dimmensional reduction to use +#' @param reduction Which dimensional reduction to use #' @param balanced Plot an equal number of genes with both + and - scores. #' @param projected Use the full projected dimensional reduction #' @param ncol Number of columns to plot @@ -554,6 +555,9 @@ RidgePlot <- function( #' single violin shapes. #' @param adjust Adjust parameter for geom_violin #' @param flip flip plot orientation (identities on x-axis) +#' @param raster Convert points to raster format. Requires 'ggrastr' to be installed. +# default is \code{NULL} which automatically rasterizes if ggrastr is installed and +# number of points exceed 100,000. #' #' @return A \code{\link[patchwork]{patchwork}ed} ggplot object if #' \code{combine = TRUE}; otherwise, a list of ggplot objects @@ -588,7 +592,8 @@ VlnPlot <- function( stack = FALSE, combine = TRUE, fill.by = 'feature', - flip = FALSE + flip = FALSE, + raster = NULL ) { if ( !is.null(x = split.by) & @@ -623,7 +628,8 @@ VlnPlot <- function( stack = stack, combine = combine, fill.by = fill.by, - flip = flip + flip = flip, + raster = raster )) } @@ -981,6 +987,7 @@ FeaturePlot <- function( blend.threshold = 0.5, label = FALSE, label.size = 4, + label.color = "black", repel = FALSE, ncol = NULL, coord.fixed = FALSE, @@ -1263,7 +1270,8 @@ FeaturePlot <- function( plot = plot, id = 'ident', repel = repel, - size = label.size + size = label.size, + color = label.color ) } # Make FeatureHeatmaps look nice(ish) @@ -3997,6 +4005,30 @@ AugmentPlot <- function(plot, width = 10, height = 10, dpi = 100) { return(blank) } +#' Automagically calculate a point size for ggplot2-based scatter plots +#' +#' It happens to look good +#' +#' @param data A data frame being passed to ggplot2 +#' @param raster If TRUE, point size is set to 1 +#' +#' @return The "optimal" point size for visualizing these data +#' +#' @export +#' @concept visualization +#' +#' @examples +#' df <- data.frame(x = rnorm(n = 10000), y = runif(n = 10000)) +#' AutoPointSize(data = df) +#' +AutoPointSize <- function(data, raster = NULL) { + return(ifelse( + test = isTRUE(x = raster), + yes = 1, + no = min(1583 / nrow(x = data), 1) + )) +} + #' Determine text color based on background color #' #' @param background A vector of background colors; supports R color names and @@ -5261,27 +5293,6 @@ WhiteBackground <- function(...) { # Internal #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -# Automagically calculate a point size for ggplot2-based scatter plots -# -# It happens to look good -# -# @param data A data frame being passed to ggplot2 -# @param raster If TRUE, point size is set to 1 -# -# @return The "optimal" point size for visualizing these data -# -# @examples -# df <- data.frame(x = rnorm(n = 10000), y = runif(n = 10000)) -# AutoPointSize(data = df) -# -AutoPointSize <- function(data, raster = NULL) { - return(ifelse( - test = isTRUE(x = raster), - yes = 1, - no = min(1583 / nrow(x = data), 1) - )) -} - # Calculate bandwidth for use in ggplot2-based smooth scatter plots # # Inspired by MASS::bandwidth.nrd and graphics:::.smoothScatterCalcDensity @@ -5494,60 +5505,6 @@ Col2Hex <- function(...) { return(colors) } -# Find the default DimReduc -# -# Searches for DimReducs matching 'umap', 'tsne', or 'pca', case-insensitive, and -# in that order. Priority given to DimReducs matching the DefaultAssay or assay specified -# (eg. 'pca' for the default assay weights higher than 'umap' for a non-default assay) -# -# @param object A Seurat object -# @param assay Name of assay to use; defaults to the default assay of the object -# -# @return The default DimReduc, if possible -# -DefaultDimReduc <- function(object, assay = NULL) { - object <- UpdateSlots(object = object) - assay <- assay %||% DefaultAssay(object = object) - drs.use <- c('umap', 'tsne', 'pca') - dim.reducs <- FilterObjects(object = object, classes.keep = 'DimReduc') - drs.assay <- Filter( - f = function(x) { - return(DefaultAssay(object = object[[x]]) == assay) - }, - x = dim.reducs - ) - if (length(x = drs.assay) > 0) { - index <- lapply( - X = drs.use, - FUN = grep, - x = drs.assay, - ignore.case = TRUE - ) - index <- Filter(f = length, x = index) - if (length(x = index) > 0) { - return(drs.assay[min(index[[1]])]) - } - } - index <- lapply( - X = drs.use, - FUN = grep, - x = dim.reducs, - ignore.case = TRUE - ) - index <- Filter(f = length, x = index) - if (length(x = index) < 1) { - stop( - "Unable to find a DimReduc matching one of '", - paste(drs.use[1:(length(x = drs.use) - 1)], collapse = "', '"), - "', or '", - drs.use[length(x = drs.use)], - "', please specify a dimensional reduction to use", - call. = FALSE - ) - } - return(dim.reducs[min(index[[1]])]) -} - # Plot feature expression by identity # # Basically combines the codebase for VlnPlot and RidgePlot @@ -5574,6 +5531,8 @@ DefaultDimReduc <- function(object, assay = NULL) { # ggplot object. If \code{FALSE}, return a list of ggplot objects # @param fill.by Color violins/ridges based on either 'feature' or 'ident' # @param flip flip plot orientation (identities on x-axis) +# @param raster Convert points to raster format, default is \code{NULL} which +# automatically rasterizes if plotting more than 100,000 cells # # @return A \code{\link[patchwork]{patchwork}ed} ggplot object if # \code{combine = TRUE}; otherwise, a list of ggplot objects @@ -5602,7 +5561,8 @@ ExIPlot <- function( stack = FALSE, combine = TRUE, fill.by = NULL, - flip = FALSE + flip = FALSE, + raster = NULL ) { assay <- assay %||% DefaultAssay(object = object) DefaultAssay(object = object) <- assay @@ -5703,7 +5663,8 @@ ExIPlot <- function( adjust = adjust, cols = cols, pt.size = pt.size, - log = log + log = log, + raster = raster )) } ) @@ -6800,35 +6761,6 @@ SetHighlight <- function( )) } -# Find the quantile of a data -# -# Converts a quantile in character form to a number regarding some data -# String form for a quantile is represented as a number prefixed with 'q' -# For example, 10th quantile is 'q10' while 2nd quantile is 'q2' -# -# Will only take a quantile of non-zero data values -# -# @param cutoff The cutoff to turn into a quantile -# @param data The data to turn find the quantile of -# -# @return The numerical representation of the quantile -# -#' @importFrom stats quantile -# -SetQuantile <- function(cutoff, data) { - if (grepl(pattern = '^q[0-9]{1,2}$', x = as.character(x = cutoff), perl = TRUE)) { - this.quantile <- as.numeric(x = sub( - pattern = 'q', - replacement = '', - x = as.character(x = cutoff) - )) / 100 - data <- unlist(x = data) - data <- data[data > 0] - cutoff <- quantile(x = data, probs = this.quantile) - } - return(as.numeric(x = cutoff)) -} - #' @importFrom shiny brushedPoints # ShinyBrush <- function(plot.data, brush, outputs, inverts = character(length = 0L)) {#}, selected = NULL) { @@ -6847,30 +6779,35 @@ ShinyBrush <- function(plot.data, brush, outputs, inverts = character(length = 0 } globalVariables(names = '..density..', package = 'Seurat') -# A single correlation plot -# -# @param data.plot A data frame with two columns to be plotted -# @param col.by A vector or factor of values to color the plot by -# @param cols An optional vector of colors to use -# @param pt.size Point size for the plot -# @param smooth Make a smoothed scatter plot -# @param rows.highight A vector of rows to highlight (like cells.highlight in SingleDimPlot) -# @param legend.title Optional legend title -# @param raster Convert points to raster format, default is \code{NULL} -# which will automatically use raster if the number of points plotted is greater than -# 100,000 -# @param jitter Jitter for easier visualization of crowded points -# -# @param ... Extra parameters to MASS::kde2d -# +#' A single correlation plot +#' +#' @param data A data frame with two columns to be plotted +#' @param col.by A vector or factor of values to color the plot by +#' @param cols An optional vector of colors to use +#' @param pt.size Point size for the plot +#' @param smooth Make a smoothed scatter plot +#' @param rows.highight A vector of rows to highlight (like cells.highlight in +#' \code{\link{SingleDimPlot}}) +#' @param legend.title Optional legend title +#' @param raster Convert points to raster format, default is \code{NULL} +#' which will automatically use raster if the number of points plotted is +#' greater than 100,000 +#' @param plot.cor ... +#' @param jitter Jitter for easier visualization of crowded points +#' +#' @return A ggplot2 object +#' #' @importFrom stats cor -# #' @importFrom MASS kde2d #' @importFrom cowplot theme_cowplot #' @importFrom RColorBrewer brewer.pal.info #' @importFrom ggplot2 ggplot aes_string geom_point labs scale_color_brewer #' scale_color_manual guides stat_density2d aes scale_fill_continuous #' @importFrom scattermore geom_scattermore #' +#' @keywords internal +#' +#' @export +#' SingleCorPlot <- function( data, col.by = NULL, @@ -7024,44 +6961,51 @@ SingleCorPlot <- function( return(plot) } -# Plot a single dimension -# -# @param data Data to plot -# @param dims A two-length numeric vector with dimensions to use -# @param pt.size Adjust point size for plotting -# @param col.by ... -# @param cols Vector of colors, each color corresponds to an identity class. This may also be a single character -# or numeric value corresponding to a palette as specified by \code{\link[RColorBrewer]{brewer.pal.info}}. -# By default, ggplot2 assigns colors -# @param shape.by If NULL, all points are circles (default). You can specify any cell attribute -# (that can be pulled with FetchData) allowing for both different colors and different shapes on -# cells. -# @param alpha.by Mapping variable for the point alpha value -# @param order Specify the order of plotting for the idents. This can be useful for crowded plots if -# points of interest are being buried. Provide either a full list of valid idents or a subset to be -# plotted last (on top). -# @param label Whether to label the clusters -# @param repel Repel labels -# @param label.size Sets size of labels -# @param cells.highlight A list of character or numeric vectors of cells to -# highlight. If only one group of cells desired, can simply -# pass a vector instead of a list. If set, colors selected cells to the color(s) -# in \code{cols.highlight} and other cells black (white if dark.theme = TRUE); -# will also resize to the size(s) passed to \code{sizes.highlight} -# @param cols.highlight A vector of colors to highlight the cells as; will -# repeat to the length groups in cells.highlight -# @param sizes.highlight Size of highlighted cells; will repeat to the length -# groups in cells.highlight -# @param na.value Color value for NA points when using custom scale. -# @param raster Convert points to raster format, default is \code{NULL} -# which will automatically use raster if the number of points plotted is greater than -# 100,000 -# +#' Plot a single dimension +#' +#' @param data Data to plot +#' @param dims A two-length numeric vector with dimensions to use +#' @param col.by ... +#' @param cols Vector of colors, each color corresponds to an identity class. +#' This may also be a single character or numeric value corresponding to a +#' palette as specified by \code{\link[RColorBrewer]{brewer.pal.info}}.By +#' default, ggplot2 assigns colors +#' @param pt.size Adjust point size for plotting +#' @param shape.by If NULL, all points are circles (default). You can specify +#' any cell attribute (that can be pulled with \code{\link{FetchData}}) +#' allowing for both different colors and different shapes on cells. +#' @param alpha.by Mapping variable for the point alpha value +#' @param order Specify the order of plotting for the idents. This can be +#' useful for crowded plots if points of interest are being buried. Provide +#' either a full list of valid idents or a subset to be plotted last (on top). +#' @param label Whether to label the clusters +#' @param repel Repel labels +#' @param label.size Sets size of labels +#' @param cells.highlight A list of character or numeric vectors of cells to +#' highlight. If only one group of cells desired, can simply +#' pass a vector instead of a list. If set, colors selected cells to the color(s) +#' in \code{cols.highlight} and other cells black (white if dark.theme = TRUE); +#' will also resize to the size(s) passed to \code{sizes.highlight} +#' @param cols.highlight A vector of colors to highlight the cells as; will +#' repeat to the length groups in cells.highlight +#' @param sizes.highlight Size of highlighted cells; will repeat to the length +#' groups in cells.highlight +#' @param na.value Color value for NA points when using custom scale. +#' @param raster Convert points to raster format, default is \code{NULL} +#' which will automatically use raster if the number of points plotted is +#' greater than 100,000 +#' +#' @return A ggplot2 object +#' #' @importFrom cowplot theme_cowplot #' @importFrom RColorBrewer brewer.pal.info #' @importFrom ggplot2 ggplot aes_string geom_point labs guides scale_color_brewer #' scale_color_manual element_rect guide_legend discrete_scale #' +#' @keywords internal +#' +#' @export +#' SingleDimPlot <- function( data, dims, @@ -7210,29 +7154,37 @@ SingleDimPlot <- function( return(plot) } -# Plot a single expression by identity on a plot -# -# @param type Make either a 'ridge' or 'violin' plot -# @param data Data to plot -# @param idents Idents to use -# @param sort Sort identity classes (on the x-axis) by the average -# expression of the attribute being potted -# @param y.max Maximum Y value to plot -# @param adjust Adjust parameter for geom_violin -# @param cols Colors to use for plotting -# @param log plot Y axis on log scale -# @param seed.use Random seed to use. If NULL, don't set a seed -# -# @return A ggplot-based Expression-by-Identity plot -# -# @import ggplot2 +#' Plot a single expression by identity on a plot +#' +#' @param data Data to plot +#' @param idents Idents to use +#' @param split Use a split violin plot +#' @param type Make either a \dQuote{ridge} or \dQuote{violin} plot +#' @param sort Sort identity classes (on the x-axis) by the average +#' expression of the attribute being potted +#' @param y.max Maximum Y value to plot +#' @param adjust Adjust parameter for geom_violin +#' @param pt.size Size of points for violin plots +#' @param cols Colors to use for plotting +#' @param seed.use Random seed to use. If NULL, don't set a seed +#' @param log plot Y axis on log scale +#' @param raster Convert points to raster format. Requires 'ggrastr' to be installed. +#' default is \code{NULL} which automatically rasterizes if ggrastr is installed and +#' number of points exceed 100,000. +#' +#' @return A ggplot-based Expression-by-Identity plot +#' #' @importFrom stats rnorm #' @importFrom utils globalVariables #' @importFrom ggridges geom_density_ridges theme_ridges -#' @importFrom ggplot2 ggplot aes_string theme labs geom_violin geom_jitter ylim position_jitterdodge -#' scale_fill_manual scale_y_log10 scale_x_log10 scale_y_discrete scale_x_continuous waiver +#' @importFrom ggplot2 ggplot aes_string theme labs geom_violin geom_jitter +#' ylim position_jitterdodge scale_fill_manual scale_y_log10 scale_x_log10 +#' scale_y_discrete scale_x_continuous waiver #' @importFrom cowplot theme_cowplot #' +#' @keywords internal +#' @export +#' SingleExIPlot <- function( data, idents, @@ -7244,8 +7196,23 @@ SingleExIPlot <- function( pt.size = 0, cols = NULL, seed.use = 42, - log = FALSE + log = FALSE, + raster = NULL ) { + if (!is.null(x = raster) && isTRUE(x = raster)){ + if (!PackageCheck('ggrastr', error = FALSE)) { + stop("Please install ggrastr from CRAN to enable rasterization.") + } + } + if (PackageCheck('ggrastr', error = FALSE)) { + # Set rasterization to true if ggrastr is installed and + # number of points exceeds 100,000 + if ((nrow(x = data) > 1e5) & !isFALSE(raster)){ + message("Rasterizing points since number of points exceeds 100,000.", + "\nTo disable this behavior set `raster=FALSE`") + } + raster <- TRUE + } if (!is.null(x = seed.use)) { set.seed(seed = seed.use) } @@ -7305,13 +7272,25 @@ SingleExIPlot <- function( theme(axis.text.x = element_text(angle = 45, hjust = 1)) ) if (is.null(x = split)) { - jitter <- geom_jitter(height = 0, size = pt.size, show.legend = FALSE) + if (isTRUE(x = raster)) { + jitter <- ggrastr::rasterize(geom_jitter(height = 0, size = pt.size, show.legend = FALSE)) + } else { + jitter <- geom_jitter(height = 0, size = pt.size, show.legend = FALSE) + } } else { - jitter <- geom_jitter( - position = position_jitterdodge(jitter.width = 0.4, dodge.width = 0.9), - size = pt.size, - show.legend = FALSE - ) + if (isTRUE(x = raster)) { + jitter <- ggrastr::rasterize(geom_jitter( + position = position_jitterdodge(jitter.width = 0.4, dodge.width = 0.9), + size = pt.size, + show.legend = FALSE + )) + } else { + jitter <- geom_jitter( + position = position_jitterdodge(jitter.width = 0.4, dodge.width = 0.9), + size = pt.size, + show.legend = FALSE + ) + } } log.scale <- scale_y_log10() axis.scale <- ylim @@ -7386,14 +7365,20 @@ SingleExIPlot <- function( return(plot) } -# A single heatmap from base R using image -# -# @param data matrix of data to plot -# @param order optional vector of cell names to specify order in plot -# @param title Title for plot -# -#' @importFrom graphics par plot.new -# +#' A single heatmap from base R using \code{\link[graphics]{image}} +#' +#' @param data matrix of data to plot +#' @param order optional vector of cell names to specify order in plot +#' @param title Title for plot +#' +#' @return No return, generates a base-R heatmap using \code{\link[graphics]{image}} +#' +#' @importFrom graphics axis image par plot.new title +#' +#' @keywords internal +#' +#' @export +#' SingleImageMap <- function(data, order = NULL, title = NULL) { if (!is.null(x = order)) { data <- data[order, ] @@ -7439,20 +7424,27 @@ SinglePolyPlot <- function(data, group.by, ...) { return(plot) } -# A single heatmap from ggplot2 using geom_raster -# -# @param data A matrix or data frame with data to plot -# @param raster switch between geom_raster and geom_tile -# @param cell.order ... -# @param feature.order ... -# @param cols A vector of colors to use -# @param disp.min Minimum display value (all values below are clipped) -# @param disp.max Maximum display value (all values above are clipped) -# @param limits A two-length numeric vector with the limits for colors on the plot -# @param group.by A vector to group cells by, should be one grouping identity per cell +#' A single heatmap from ggplot2 using geom_raster +#' +#' @param data A matrix or data frame with data to plot +#' @param raster switch between geom_raster and geom_tile +#' @param cell.order ... +#' @param feature.order ... +#' @param colors A vector of colors to use +#' @param disp.min Minimum display value (all values below are clipped) +#' @param disp.max Maximum display value (all values above are clipped) +#' @param limits A two-length numeric vector with the limits for colors on the plot +#' @param group.by A vector to group cells by, should be one grouping identity per cell +#' +#' @return A ggplot2 object # #' @importFrom ggplot2 ggplot aes_string geom_raster scale_fill_gradient -#' scale_fill_gradientn theme element_blank labs geom_point guides guide_legend geom_tile +#' scale_fill_gradientn theme element_blank labs geom_point guides +#' guide_legend geom_tile +#' +#' @keywords internal +#' +#' @export # SingleRasterMap <- function( data, @@ -7498,37 +7490,46 @@ SingleRasterMap <- function( return(plot) } -# Base plotting function for all Spatial plots -# -# @param data Data.frame with info to be plotted -# @param image SpatialImage object to be plotted -# @param cols Vector of colors, each color corresponds to an identity class. This may also be a single character -# or numeric value corresponding to a palette as specified by \code{\link[RColorBrewer]{brewer.pal.info}}. -# By default, ggplot2 assigns colors -# @param image.alpha Adjust the opacity of the background images. Set to 0 to -# remove. -# @param pt.alpha Adjust the opacity of the points if plotting a SpatialDimPlot -# @param crop Crop the plot in to focus on points plotted. Set to FALSE to show -# entire background image. -# @param pt.size.factor Sets the size of the points relative to spot.radius -# @param stroke Control the width of the border around the spots -# @param col.by Mapping variable for the point color -# @param alpha.by Mapping variable for the point alpha value -# @param cells.highlight A list of character or numeric vectors of cells to -# highlight. If only one group of cells desired, can simply pass a vector -# instead of a list. If set, colors selected cells to the color(s) in -# cols.highlight -# @param cols.highlight A vector of colors to highlight the cells as; ordered -# the same as the groups in cells.highlight; last color corresponds to -# unselected cells. -# @param geom Switch between normal spatial geom and geom to enable hover -# functionality -# @param na.value Color for spots with NA values - +#' Base plotting function for all Spatial plots +#' +#' @param data Data.frame with info to be plotted +#' @param image \code{SpatialImage} object to be plotted +#' @param cols Vector of colors, each color corresponds to an identity class. +#' This may also be a single character +#' or numeric value corresponding to a palette as specified by +#' \code{\link[RColorBrewer]{brewer.pal.info}}. By default, ggplot2 assigns +#' colors +#' @param image.alpha Adjust the opacity of the background images. Set to 0 to +#' remove. +#' @param pt.alpha Adjust the opacity of the points if plotting a +#' \code{SpatialDimPlot} +#' @param crop Crop the plot in to focus on points plotted. Set to \code{FALSE} +#' to show entire background image. +#' @param pt.size.factor Sets the size of the points relative to spot.radius +#' @param stroke Control the width of the border around the spots +#' @param col.by Mapping variable for the point color +#' @param alpha.by Mapping variable for the point alpha value +#' @param cells.highlight A list of character or numeric vectors of cells to +#' highlight. If only one group of cells desired, can simply pass a vector +#' instead of a list. If set, colors selected cells to the color(s) in +#' cols.highlight +#' @param cols.highlight A vector of colors to highlight the cells as; ordered +#' the same as the groups in cells.highlight; last color corresponds to +#' unselected cells. +#' @param geom Switch between normal spatial geom and geom to enable hover +#' functionality +#' @param na.value Color for spots with NA values +#' +#' @return A ggplot2 object +#' #' @importFrom tibble tibble #' @importFrom ggplot2 ggplot aes_string coord_fixed geom_point xlim ylim #' coord_cartesian labs theme_void theme scale_fill_brewer #' +#' @keywords internal +#' +#' @export +#' SingleSpatialPlot <- function( data, image, diff --git a/_pkgdown.yaml b/_pkgdown.yaml index 4f2139554..37dd42fd5 100644 --- a/_pkgdown.yaml +++ b/_pkgdown.yaml @@ -1,9 +1,14 @@ +url: https://satijalab.org/seurat + destination: docs template: params: bootswatch: flatly ganalytics: UA-82807227-1 + docsearch: + api_key: ead918d7fe8467a2fd38e97f5bbe3ecb + index_name: seurat navbar: title: "Seurat" @@ -149,3 +154,8 @@ reference: desc: "Functions included for user convenience and to keep maintain backwards compatability" - contents: - has_concept("convenience") + +- title: "Re-exports" + desc: "Functions re-exported from other packages" +- contents: + - reexports diff --git a/cran-comments.md b/cran-comments.md index 8ae6a6d5b..5799d0411 100644 --- a/cran-comments.md +++ b/cran-comments.md @@ -1,7 +1,7 @@ -# Seurat v4.0.5 +# Seurat v4.0.6 ## Test environments -* local Ubuntu 20.04 install, R 4.1.0 +* local Ubuntu 20.04 install, R 4.1.2 * Ubuntu 16.04.6 (on travis-ci), R 4.0.0, R devel * macOS 10.13.6 (on travis-ci), R 4.0.2 * Windows Server 2012 R2 (on AppVeyor), R 4.1.0 Patched @@ -12,8 +12,8 @@ There were no ERRORs, WARNINGs, or NOTEs ## Downstream dependencies -There is one package that depends on Seurat: tidyseurat; this update does not impact its functionality +There no packages that depend on Seurat -There are ten packages that import Seurat: CDSeq, DUBStepR, PhitestR, rPanglaoDB, scDiffCom, scMappR, scRNAstat, Signac, SignacX, and SoupX; this update does not impact their functionality +There are sixteen packages that import Seurat: CAMML, CDSeq, CIDER, DR.SC, DUBStepR, PhitestR, Platypus, rPanglaoDB, scDiffCom, scMappR, SCRIP, scRNAstat, Signac, SignacX, SoupX, and tidyseurat; this update does not impact their functionality There are ten packages that suggest Seurat: BisqueRNA, ClustAssess, clustree, conos, DIscBIO, dyngen, harmony, rliger, Rmagic, and VAM; this update does not impact their functionality. diff --git a/man/AutoPointSize.Rd b/man/AutoPointSize.Rd new file mode 100644 index 000000000..7e908dda1 --- /dev/null +++ b/man/AutoPointSize.Rd @@ -0,0 +1,25 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/visualization.R +\name{AutoPointSize} +\alias{AutoPointSize} +\title{Automagically calculate a point size for ggplot2-based scatter plots} +\usage{ +AutoPointSize(data, raster = NULL) +} +\arguments{ +\item{data}{A data frame being passed to ggplot2} + +\item{raster}{If TRUE, point size is set to 1} +} +\value{ +The "optimal" point size for visualizing these data +} +\description{ +It happens to look good +} +\examples{ +df <- data.frame(x = rnorm(n = 10000), y = runif(n = 10000)) +AutoPointSize(data = df) + +} +\concept{visualization} diff --git a/man/DimHeatmap.Rd b/man/DimHeatmap.Rd index 5a9603788..79dee9b6a 100644 --- a/man/DimHeatmap.Rd +++ b/man/DimHeatmap.Rd @@ -34,7 +34,7 @@ PCHeatmap(object, ...) \item{cells}{A list of cells to plot. If numeric, just plots the top cells.} -\item{reduction}{Which dimmensional reduction to use} +\item{reduction}{Which dimensional reduction to use} \item{disp.min}{Minimum display value (all values below are clipped)} diff --git a/man/FeaturePlot.Rd b/man/FeaturePlot.Rd index f869e4c98..9d334631c 100644 --- a/man/FeaturePlot.Rd +++ b/man/FeaturePlot.Rd @@ -25,6 +25,7 @@ FeaturePlot( blend.threshold = 0.5, label = FALSE, label.size = 4, + label.color = "black", repel = FALSE, ncol = NULL, coord.fixed = FALSE, @@ -94,6 +95,8 @@ different colors and different shapes on cells. Only applicable if \code{raster \item{label.size}{Sets size of labels} +\item{label.color}{Sets the color of the label text} + \item{repel}{Repel labels} \item{ncol}{Number of columns to combine multiple feature plots to, ignored if \code{split.by} is not \code{NULL}} diff --git a/man/FindConservedMarkers.Rd b/man/FindConservedMarkers.Rd index f8595291a..429c7dd9e 100644 --- a/man/FindConservedMarkers.Rd +++ b/man/FindConservedMarkers.Rd @@ -11,6 +11,7 @@ FindConservedMarkers( grouping.var, assay = "RNA", slot = "data", + min.cells.group = 3, meta.method = metap::minimump, verbose = TRUE, ... @@ -31,6 +32,8 @@ use all other cells for comparison.} \item{slot}{Slot to pull data from; note that if \code{test.use} is "negbinom", "poisson", or "DESeq2", \code{slot} will be set to "counts"} +\item{min.cells.group}{Minimum number of cells in one of the groups} + \item{meta.method}{method for combining p-values. Should be a function from the metap package (NOTE: pass the function, not a string)} diff --git a/man/PercentAbove.Rd b/man/PercentAbove.Rd new file mode 100644 index 000000000..646e77670 --- /dev/null +++ b/man/PercentAbove.Rd @@ -0,0 +1,25 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/utilities.R +\name{PercentAbove} +\alias{PercentAbove} +\title{Calculate the percentage of a vector above some threshold} +\usage{ +PercentAbove(x, threshold) +} +\arguments{ +\item{x}{Vector of values} + +\item{threshold}{Threshold to use when calculating percentage} +} +\value{ +Returns the percentage of \code{x} values above the given threshold +} +\description{ +Calculate the percentage of a vector above some threshold +} +\examples{ +set.seed(42) +PercentAbove(sample(1:100, 10), 75) + +} +\concept{utilities} diff --git a/man/ProjectUMAP.Rd b/man/ProjectUMAP.Rd index 080f1da4f..0e40dc4e4 100644 --- a/man/ProjectUMAP.Rd +++ b/man/ProjectUMAP.Rd @@ -14,7 +14,7 @@ ProjectUMAP(query, ...) query.dims = NULL, reference, reference.dims = NULL, - k.param = 20, + k.param = 30, nn.method = "annoy", n.trees = 50, annoy.metric = "cosine", @@ -31,7 +31,7 @@ ProjectUMAP(query, ...) query.dims = NULL, reference, reference.dims = NULL, - k.param = 20, + k.param = 30, nn.method = "annoy", n.trees = 50, annoy.metric = "cosine", @@ -50,7 +50,7 @@ ProjectUMAP(query, ...) reference, reference.reduction, reference.dims = NULL, - k.param = 20, + k.param = 30, nn.method = "annoy", n.trees = 50, annoy.metric = "cosine", diff --git a/man/RunSLSI.Rd b/man/RunSLSI.Rd new file mode 100644 index 000000000..c89ed6886 --- /dev/null +++ b/man/RunSLSI.Rd @@ -0,0 +1,80 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/generics.R, R/dimensional_reduction.R +\name{RunSLSI} +\alias{RunSLSI} +\alias{RunSLSI.default} +\alias{RunSLSI.Assay} +\alias{RunSLSI.Seurat} +\title{Run Supervised Latent Semantic Indexing} +\usage{ +RunSLSI(object, ...) + +\method{RunSLSI}{default}( + object, + assay = NULL, + n = 50, + reduction.key = "SLSI_", + graph = NULL, + verbose = TRUE, + seed.use = 42, + ... +) + +\method{RunSLSI}{Assay}( + object, + assay = NULL, + features = NULL, + n = 50, + reduction.key = "SLSI_", + graph = NULL, + verbose = TRUE, + seed.use = 42, + ... +) + +\method{RunSLSI}{Seurat}( + object, + assay = NULL, + features = NULL, + n = 50, + reduction.name = "slsi", + reduction.key = "SLSI_", + graph = NULL, + verbose = TRUE, + seed.use = 42, + ... +) +} +\arguments{ +\item{object}{An object} + +\item{...}{Arguments passed to IRLBA irlba} + +\item{assay}{Name of Assay SLSI is being run on} + +\item{n}{Total Number of SLSI components to compute and store} + +\item{reduction.key}{dimensional reduction key, specifies the string before +the number for the dimension names} + +\item{graph}{Graph used supervised by SLSI} + +\item{verbose}{Display messages} + +\item{seed.use}{Set a random seed. Setting NULL will not set a seed.} + +\item{features}{Features to compute SLSI on. If NULL, SLSI will be run +using the variable features for the Assay.} + +\item{reduction.name}{dimensional reduction name} +} +\value{ +Returns Seurat object with the SLSI calculation stored in the +reductions slot +} +\description{ +Run a supervised LSI (SLSI) dimensionality reduction supervised by a +cell-cell kernel. SLSI is used to capture a linear transformation of peaks +that maximizes its dependency to the given cell-cell kernel. +} +\concept{dimensional_reduction} diff --git a/man/RunSPCA.Rd b/man/RunSPCA.Rd index 8c05b3839..fb166c30c 100644 --- a/man/RunSPCA.Rd +++ b/man/RunSPCA.Rd @@ -74,7 +74,7 @@ using the variable features for the Assay.} Returns Seurat object with the SPCA calculation stored in the reductions slot } \description{ -Run a supervied PCA (SPCA) dimensionality reduction supervised by a cell-cell kernel. +Run a supervised PCA (SPCA) dimensionality reduction supervised by a cell-cell kernel. SPCA is used to capture a linear transformation which maximizes its dependency to the given cell-cell kernel. We use SNN graph as the kernel to supervise the linear matrix factorization. diff --git a/man/SetQuantile.Rd b/man/SetQuantile.Rd new file mode 100644 index 000000000..3b4980029 --- /dev/null +++ b/man/SetQuantile.Rd @@ -0,0 +1,28 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/utilities.R +\name{SetQuantile} +\alias{SetQuantile} +\title{Find the Quantile of Data} +\usage{ +SetQuantile(cutoff, data) +} +\arguments{ +\item{cutoff}{The cutoff to turn into a quantile} + +\item{data}{The data to turn find the quantile of} +} +\value{ +The numerical representation of the quantile +} +\description{ +Converts a quantile in character form to a number regarding some data. +String form for a quantile is represented as a number prefixed with +\dQuote{q}; for example, 10th quantile is \dQuote{q10} while 2nd quantile is +\dQuote{q2}. Will only take a quantile of non-zero data values +} +\examples{ +set.seed(42) +SetQuantile('q10', sample(1:100, 10)) + +} +\concept{utilities} diff --git a/man/SingleCorPlot.Rd b/man/SingleCorPlot.Rd new file mode 100644 index 000000000..3fc762922 --- /dev/null +++ b/man/SingleCorPlot.Rd @@ -0,0 +1,52 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/visualization.R +\name{SingleCorPlot} +\alias{SingleCorPlot} +\title{A single correlation plot} +\usage{ +SingleCorPlot( + data, + col.by = NULL, + cols = NULL, + pt.size = NULL, + smooth = FALSE, + rows.highlight = NULL, + legend.title = NULL, + na.value = "grey50", + span = NULL, + raster = NULL, + plot.cor = TRUE, + jitter = TRUE +) +} +\arguments{ +\item{data}{A data frame with two columns to be plotted} + +\item{col.by}{A vector or factor of values to color the plot by} + +\item{cols}{An optional vector of colors to use} + +\item{pt.size}{Point size for the plot} + +\item{smooth}{Make a smoothed scatter plot} + +\item{legend.title}{Optional legend title} + +\item{raster}{Convert points to raster format, default is \code{NULL} +which will automatically use raster if the number of points plotted is +greater than 100,000} + +\item{plot.cor}{...} + +\item{jitter}{Jitter for easier visualization of crowded points} + +\item{rows.highight}{A vector of rows to highlight (like cells.highlight in +\code{\link{SingleDimPlot}})} +} +\value{ +A ggplot2 object +} +\description{ +A single correlation plot +} +\keyword{internal} diff --git a/man/SingleDimPlot.Rd b/man/SingleDimPlot.Rd new file mode 100644 index 000000000..5ec9911af --- /dev/null +++ b/man/SingleDimPlot.Rd @@ -0,0 +1,80 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/visualization.R +\name{SingleDimPlot} +\alias{SingleDimPlot} +\title{Plot a single dimension} +\usage{ +SingleDimPlot( + data, + dims, + col.by = NULL, + cols = NULL, + pt.size = NULL, + shape.by = NULL, + alpha.by = NULL, + order = NULL, + label = FALSE, + repel = FALSE, + label.size = 4, + cells.highlight = NULL, + cols.highlight = "#DE2D26", + sizes.highlight = 1, + na.value = "grey50", + raster = NULL +) +} +\arguments{ +\item{data}{Data to plot} + +\item{dims}{A two-length numeric vector with dimensions to use} + +\item{col.by}{...} + +\item{cols}{Vector of colors, each color corresponds to an identity class. +This may also be a single character or numeric value corresponding to a +palette as specified by \code{\link[RColorBrewer]{brewer.pal.info}}.By +default, ggplot2 assigns colors} + +\item{pt.size}{Adjust point size for plotting} + +\item{shape.by}{If NULL, all points are circles (default). You can specify +any cell attribute (that can be pulled with \code{\link{FetchData}}) +allowing for both different colors and different shapes on cells.} + +\item{alpha.by}{Mapping variable for the point alpha value} + +\item{order}{Specify the order of plotting for the idents. This can be +useful for crowded plots if points of interest are being buried. Provide +either a full list of valid idents or a subset to be plotted last (on top).} + +\item{label}{Whether to label the clusters} + +\item{repel}{Repel labels} + +\item{label.size}{Sets size of labels} + +\item{cells.highlight}{A list of character or numeric vectors of cells to +highlight. If only one group of cells desired, can simply +pass a vector instead of a list. If set, colors selected cells to the color(s) +in \code{cols.highlight} and other cells black (white if dark.theme = TRUE); +will also resize to the size(s) passed to \code{sizes.highlight}} + +\item{cols.highlight}{A vector of colors to highlight the cells as; will +repeat to the length groups in cells.highlight} + +\item{sizes.highlight}{Size of highlighted cells; will repeat to the length +groups in cells.highlight} + +\item{na.value}{Color value for NA points when using custom scale.} + +\item{raster}{Convert points to raster format, default is \code{NULL} +which will automatically use raster if the number of points plotted is +greater than 100,000} +} +\value{ +A ggplot2 object +} +\description{ +Plot a single dimension +} +\keyword{internal} diff --git a/man/SingleExIPlot.Rd b/man/SingleExIPlot.Rd new file mode 100644 index 000000000..9ceede508 --- /dev/null +++ b/man/SingleExIPlot.Rd @@ -0,0 +1,56 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/visualization.R +\name{SingleExIPlot} +\alias{SingleExIPlot} +\title{Plot a single expression by identity on a plot} +\usage{ +SingleExIPlot( + data, + idents, + split = NULL, + type = "violin", + sort = FALSE, + y.max = NULL, + adjust = 1, + pt.size = 0, + cols = NULL, + seed.use = 42, + log = FALSE, + raster = NULL +) +} +\arguments{ +\item{data}{Data to plot} + +\item{idents}{Idents to use} + +\item{split}{Use a split violin plot} + +\item{type}{Make either a \dQuote{ridge} or \dQuote{violin} plot} + +\item{sort}{Sort identity classes (on the x-axis) by the average +expression of the attribute being potted} + +\item{y.max}{Maximum Y value to plot} + +\item{adjust}{Adjust parameter for geom_violin} + +\item{pt.size}{Size of points for violin plots} + +\item{cols}{Colors to use for plotting} + +\item{seed.use}{Random seed to use. If NULL, don't set a seed} + +\item{log}{plot Y axis on log scale} + +\item{raster}{Convert points to raster format. Requires 'ggrastr' to be installed. +default is \code{NULL} which automatically rasterizes if ggrastr is installed and +number of points exceed 100,000.} +} +\value{ +A ggplot-based Expression-by-Identity plot +} +\description{ +Plot a single expression by identity on a plot +} +\keyword{internal} diff --git a/man/SingleImageMap.Rd b/man/SingleImageMap.Rd new file mode 100644 index 000000000..9aee51ba1 --- /dev/null +++ b/man/SingleImageMap.Rd @@ -0,0 +1,22 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/visualization.R +\name{SingleImageMap} +\alias{SingleImageMap} +\title{A single heatmap from base R using \code{\link[graphics]{image}}} +\usage{ +SingleImageMap(data, order = NULL, title = NULL) +} +\arguments{ +\item{data}{matrix of data to plot} + +\item{order}{optional vector of cell names to specify order in plot} + +\item{title}{Title for plot} +} +\value{ +No return, generates a base-R heatmap using \code{\link[graphics]{image}} +} +\description{ +A single heatmap from base R using \code{\link[graphics]{image}} +} +\keyword{internal} diff --git a/man/SingleRasterMap.Rd b/man/SingleRasterMap.Rd new file mode 100644 index 000000000..ded269968 --- /dev/null +++ b/man/SingleRasterMap.Rd @@ -0,0 +1,44 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/visualization.R +\name{SingleRasterMap} +\alias{SingleRasterMap} +\title{A single heatmap from ggplot2 using geom_raster} +\usage{ +SingleRasterMap( + data, + raster = TRUE, + cell.order = NULL, + feature.order = NULL, + colors = PurpleAndYellow(), + disp.min = -2.5, + disp.max = 2.5, + limits = NULL, + group.by = NULL +) +} +\arguments{ +\item{data}{A matrix or data frame with data to plot} + +\item{raster}{switch between geom_raster and geom_tile} + +\item{cell.order}{...} + +\item{feature.order}{...} + +\item{colors}{A vector of colors to use} + +\item{disp.min}{Minimum display value (all values below are clipped)} + +\item{disp.max}{Maximum display value (all values above are clipped)} + +\item{limits}{A two-length numeric vector with the limits for colors on the plot} + +\item{group.by}{A vector to group cells by, should be one grouping identity per cell} +} +\value{ +A ggplot2 object +} +\description{ +A single heatmap from ggplot2 using geom_raster +} +\keyword{internal} diff --git a/man/SingleSpatialPlot.Rd b/man/SingleSpatialPlot.Rd new file mode 100644 index 000000000..de8d25c46 --- /dev/null +++ b/man/SingleSpatialPlot.Rd @@ -0,0 +1,72 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/visualization.R +\name{SingleSpatialPlot} +\alias{SingleSpatialPlot} +\title{Base plotting function for all Spatial plots} +\usage{ +SingleSpatialPlot( + data, + image, + cols = NULL, + image.alpha = 1, + pt.alpha = NULL, + crop = TRUE, + pt.size.factor = NULL, + stroke = 0.25, + col.by = NULL, + alpha.by = NULL, + cells.highlight = NULL, + cols.highlight = c("#DE2D26", "grey50"), + geom = c("spatial", "interactive", "poly"), + na.value = "grey50" +) +} +\arguments{ +\item{data}{Data.frame with info to be plotted} + +\item{image}{\code{SpatialImage} object to be plotted} + +\item{cols}{Vector of colors, each color corresponds to an identity class. +This may also be a single character +or numeric value corresponding to a palette as specified by +\code{\link[RColorBrewer]{brewer.pal.info}}. By default, ggplot2 assigns +colors} + +\item{image.alpha}{Adjust the opacity of the background images. Set to 0 to +remove.} + +\item{pt.alpha}{Adjust the opacity of the points if plotting a +\code{SpatialDimPlot}} + +\item{crop}{Crop the plot in to focus on points plotted. Set to \code{FALSE} +to show entire background image.} + +\item{pt.size.factor}{Sets the size of the points relative to spot.radius} + +\item{stroke}{Control the width of the border around the spots} + +\item{col.by}{Mapping variable for the point color} + +\item{alpha.by}{Mapping variable for the point alpha value} + +\item{cells.highlight}{A list of character or numeric vectors of cells to +highlight. If only one group of cells desired, can simply pass a vector +instead of a list. If set, colors selected cells to the color(s) in +cols.highlight} + +\item{cols.highlight}{A vector of colors to highlight the cells as; ordered +the same as the groups in cells.highlight; last color corresponds to +unselected cells.} + +\item{geom}{Switch between normal spatial geom and geom to enable hover +functionality} + +\item{na.value}{Color for spots with NA values} +} +\value{ +A ggplot2 object +} +\description{ +Base plotting function for all Spatial plots +} +\keyword{internal} diff --git a/man/VlnPlot.Rd b/man/VlnPlot.Rd index c2ed98302..75a30f331 100644 --- a/man/VlnPlot.Rd +++ b/man/VlnPlot.Rd @@ -24,7 +24,8 @@ VlnPlot( stack = FALSE, combine = TRUE, fill.by = "feature", - flip = FALSE + flip = FALSE, + raster = NULL ) } \arguments{ @@ -71,6 +72,8 @@ ggplot object. If \code{FALSE}, return a list of ggplot} \item{fill.by}{Color violins/ridges based on either 'feature' or 'ident'} \item{flip}{flip plot orientation (identities on x-axis)} + +\item{raster}{Convert points to raster format. Requires 'ggrastr' to be installed.} } \value{ A \code{\link[patchwork]{patchwork}ed} ggplot object if diff --git a/src/RcppExports.cpp b/src/RcppExports.cpp index 7ec3c42e2..7a3302c6b 100644 --- a/src/RcppExports.cpp +++ b/src/RcppExports.cpp @@ -359,6 +359,48 @@ BEGIN_RCPP return rcpp_result_gen; END_RCPP } +// row_sum_dgcmatrix +NumericVector row_sum_dgcmatrix(NumericVector& x, IntegerVector& i, int rows, int cols); +RcppExport SEXP _Seurat_row_sum_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_sum_dgcmatrix(x, i, rows, cols)); + return rcpp_result_gen; +END_RCPP +} +// row_mean_dgcmatrix +NumericVector row_mean_dgcmatrix(NumericVector& x, IntegerVector& i, int rows, int cols); +RcppExport SEXP _Seurat_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_var_dgcmatrix +NumericVector row_var_dgcmatrix(NumericVector& x, IntegerVector& i, int rows, int cols); +RcppExport SEXP _Seurat_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 +} RcppExport SEXP isnull(SEXP); @@ -390,6 +432,9 @@ static const R_CallMethodDef CallEntries[] = { {"_Seurat_WriteEdgeFile", (DL_FUNC) &_Seurat_WriteEdgeFile, 3}, {"_Seurat_DirectSNNToFile", (DL_FUNC) &_Seurat_DirectSNNToFile, 4}, {"_Seurat_SNN_SmallestNonzero_Dist", (DL_FUNC) &_Seurat_SNN_SmallestNonzero_Dist, 4}, + {"_Seurat_row_sum_dgcmatrix", (DL_FUNC) &_Seurat_row_sum_dgcmatrix, 4}, + {"_Seurat_row_mean_dgcmatrix", (DL_FUNC) &_Seurat_row_mean_dgcmatrix, 4}, + {"_Seurat_row_var_dgcmatrix", (DL_FUNC) &_Seurat_row_var_dgcmatrix, 4}, {"isnull", (DL_FUNC) &isnull, 1}, {NULL, NULL, 0} }; diff --git a/src/stats.cpp b/src/stats.cpp new file mode 100644 index 000000000..76d1ca8a4 --- /dev/null +++ b/src/stats.cpp @@ -0,0 +1,42 @@ +#include + +using namespace Rcpp; + +// the following code in-parts taken from sparseMatrixStats (http://www.bioconductor.org/packages/release/bioc/html/sparseMatrixStats.html). +// [[Rcpp::export]] +NumericVector row_sum_dgcmatrix(NumericVector &x, IntegerVector &i, int rows, int cols) { + NumericVector rowsum(rows, 0.0); + int x_length = x.length(); + for (int k=0; k