Full Code of satijalab/seurat-wrappers for AI

master ffaf74e30627 cached
118 files
51.6 MB
10.8M tokens
1 requests
Copy disabled (too large) Download .txt
Showing preview only (43,101K chars total). Download the full file to get everything.
Repository: satijalab/seurat-wrappers
Branch: master
Commit: ffaf74e30627
Files: 118
Total size: 51.6 MB

Directory structure:
gitextract_4pdtb5c6/

├── .Rbuildignore
├── .github/
│   ├── no-response.yml
│   └── workflows/
│       └── test-vignettes.yml
├── .gitignore
├── DESCRIPTION
├── LICENSE
├── NAMESPACE
├── R/
│   ├── alevin.R
│   ├── alra.R
│   ├── banksy.R
│   ├── cellbrowser.R
│   ├── cogaps.R
│   ├── conos.R
│   ├── fast_mnn.R
│   ├── fast_mnn_v5.R
│   ├── glmpca.R
│   ├── internal.R
│   ├── liger.R
│   ├── miqc.R
│   ├── monocle3.R
│   ├── pacmap.R
│   ├── presto.R
│   ├── scVI.R
│   ├── tricycle.R
│   └── velocity.R
├── README.md
├── docs/
│   ├── README.md
│   ├── alevin.Rmd
│   ├── alevin.html
│   ├── alevin.md
│   ├── alra.Rmd
│   ├── alra.html
│   ├── alra.md
│   ├── banksy.Rmd
│   ├── banksy.md
│   ├── cellbrowser.Rmd
│   ├── cellbrowser.html
│   ├── cellbrowser.md
│   ├── cipr.Rmd
│   ├── cipr.html
│   ├── cipr.md
│   ├── cogaps.html
│   ├── cogaps.md
│   ├── cogaps.rmd
│   ├── conos.Rmd
│   ├── conos.html
│   ├── conos.md
│   ├── fast_mnn.Rmd
│   ├── fast_mnn.html
│   ├── fast_mnn.md
│   ├── glmpca.Rmd
│   ├── glmpca.html
│   ├── glmpca.md
│   ├── harmony.Rmd
│   ├── harmony.html
│   ├── harmony.md
│   ├── liger.Rmd
│   ├── liger.html
│   ├── liger.md
│   ├── miQC.Rmd
│   ├── miQC.html
│   ├── miQC.md
│   ├── monocle3.Rmd
│   ├── monocle3.html
│   ├── monocle3.md
│   ├── nebulosa.Rmd
│   ├── nebulosa.html
│   ├── nebulosa.md
│   ├── pacmap.Rmd
│   ├── pacmap.html
│   ├── pacmap.md
│   ├── presto.html
│   ├── presto.md
│   ├── presto.rmd
│   ├── schex.Rmd
│   ├── schex.html
│   ├── schex.md
│   ├── scvelo.Rmd
│   ├── scvelo.html
│   ├── scvelo.md
│   ├── tricycle.Rmd
│   ├── tricycle.html
│   ├── tricycle.md
│   ├── velocity.Rmd
│   ├── velocity.html
│   └── velocity.md
├── man/
│   ├── ALRAChooseKPlot.Rd
│   ├── CellBrowser.Rd
│   ├── FastMNNIntegration.Rd
│   ├── LearnGraph.Rd
│   ├── PlotMiQC.Rd
│   ├── ReadAlevin.Rd
│   ├── ReadVelocity.Rd
│   ├── RunALRA.Rd
│   ├── RunBanksy.Rd
│   ├── RunCoGAPS.Rd
│   ├── RunFastMNN.Rd
│   ├── RunGLMPCA.Rd
│   ├── RunMiQC.Rd
│   ├── RunOptimizeALS.Rd
│   ├── RunPaCMAP.Rd
│   ├── RunPresto.Rd
│   ├── RunPrestoAll.Rd
│   ├── RunQuantileAlignSNF.Rd
│   ├── RunQuantileNorm.Rd
│   ├── RunSNF.Rd
│   ├── RunVelocity.Rd
│   ├── Runtricycle.Rd
│   ├── SeuratWrappers-package.Rd
│   ├── StopCellbrowser.Rd
│   ├── VeloPlot.Rd
│   ├── as.Seurat.extras.Rd
│   ├── as.cell_data_set.Rd
│   ├── findMatrix.Rd
│   ├── scVIIntegration.Rd
│   └── writeSparseTsvChunks.Rd
├── seurat-wrappers.Rproj
└── test-vignettes.sh

================================================
FILE CONTENTS
================================================

================================================
FILE: .Rbuildignore
================================================
^.*\.Rproj$
^\.Rproj\.user$
^docs$


================================================
FILE: .github/no-response.yml
================================================
# Configuration for probot-no-response - https://github.com/probot/no-response

# Number of days of inactivity before an Issue is closed for lack of response
daysUntilClose: 14
# Label requiring a response
responseRequiredLabel: more-information-needed
# Comment to post when closing an Issue for lack of response. Set to `false` to disable
closeComment: >
  This issue has been automatically closed because there has been no response
  to our request for more information from the original author. With only the
  information that is currently in the issue, we don't have enough information
  to take action. Please reach out if you have or find the answers we need so
  that we can investigate further.


================================================
FILE: .github/workflows/test-vignettes.yml
================================================
on: [push, pull_request]

jobs:
  test-vignettes:
    name: Test any changes to vignettes
    runs-on: ubuntu-latest
    container:
      image: satijalab/seurat-wrappers:latest
    env:
      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }}

    steps:
      - uses: actions/checkout@v2

      - name: Set R repo
        run: echo 'options(repos = "https://cloud.r-project.org")' > ~/.Rprofile

      - name: Install SeuratWrappers
        run: devtools::install(upgrade = FALSE)
        shell: Rscript {0}

      - name: Test Vignettes
        run: bash test-vignettes.sh

      - name: Upload files
        uses: actions/upload-artifact@master
        with:
          name: test-build
          path: test-build


================================================
FILE: .gitignore
================================================
.Rproj.user
.Rhistory
.RData
.Ruserdata
*_cache
*.h5Seurat
*.h5seurat
*.h5ad


================================================
FILE: DESCRIPTION
================================================
Package: SeuratWrappers
Title: Community-Provided Methods and Extensions for the Seurat Object
Version: 0.4.0
Date: 2024-11-20
Authors@R: c(
  person(given = 'Andrew', family = 'Butler', email = 'abutler@nygenome.org', role = 'aut', comment = c(ORCID = '0000-0003-3608-0463')),
  person(given = "Saket", family = "Choudhary", email = "schoudhary@nygenome.org", role = "ctb", comment = c(ORCID = "0000-0001-5202-7633")),
  person(given = 'David', family = 'Collins', email = 'dcollins@nygenome.org', role = 'ctb', comment = c(ORCID = '0000-0001-9243-7821')),
  person(given = "Yuhan", family = "Hao", email = "yhao@nygenome.org", role = "ctb", comment = c(ORCID = "0000-0002-1810-0822")),
  person(given = "Austin", family = "Hartman", email = "ahartman@nygenome.org", role = "ctb", comment = c(ORCID = "0000-0001-7278-1852")),
  person(given = 'Paul', family = 'Hoffman', email = 'nygcSatijalab@nygenome.org', role = c('aut', 'cre'), comment = c(ORCID = '0000-0002-7693-8957')),
  person(given = "Gesmira", family = "Molla", email = 'gmolla@nygenome.org', role = 'ctb', comment = c(ORCID = '0000-0002-8628-5056')),
  person(given = 'Rahul', family = 'Satija', email = 'rsatija@nygenome.org', role = 'aut', comment = c(ORCID = '0000-0001-9448-8833')),
  person(given = 'Tim', family = 'Stuart', email = 'tstuart@nygenome.org', role = 'aut', comment = c(ORCID = '0000-0002-3044-0897'))
  )
Description: SeuratWrappers is a collection of community-provided methods and
    extensions for Seurat, curated by the Satija Lab at NYGC. These methods
    comprise functionality not presently found in Seurat, and are able to be
    updated much more frequently.
License: GPL-3 | file LICENSE
Remotes: welch-lab/liger,
    hms-dbmi/conos,
    immunogenomics/harmony,
    immunogenomics/presto,
    satijalab/seurat-data,
    velocyto-team/velocyto.R,
    SaskiaFreytag/schex@031320d,
    cole-trapnell-lab/monocle3,
    mojaveazure/seurat-disk,
    powellgenomicslab/Nebulosa,
    atakanekiz/CIPR-Package,
    prabhakarlab/Banksy
Depends:
    R (>= 3.5.0)
biocViews:
Imports:
    BiocManager,
    cowplot,
    ggplot2,
    igraph,
    Matrix,
    methods,
    remotes,
    rsvd,
    Seurat (>= 5.0.0),
    stats,
    utils,
    rlang
Collate:
    'internal.R'
    'alevin.R'
    'alra.R'
    'banksy.R'
    'cellbrowser.R'
    'cogaps.R'
    'conos.R'
    'fast_mnn.R'
    'fast_mnn_v5.R'
    'glmpca.R'
    'liger.R'
    'miqc.R'
    'monocle3.R'
    'pacmap.R'
    'presto.R'
    'scVI.R'
    'tricycle.R'
    'velocity.R'
Encoding: UTF-8
LazyData: true
RoxygenNote: 7.3.2
Suggests:
    cipr,
    conos,
    rliger (>= 0.5.0),
    harmony,
    batchelor,
    SeuratData,
    SeuratDisk,
    velocyto.R,
    schex,
    tximport,
    fishpond,
    monocle3,
    CoGAPS,
    glmpca,
    Nebulosa,
    presto,
    flexmix,
    tricycle,
    Banksy


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 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 <https://www.gnu.org/licenses/>.

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:

    <program>  Copyright (C) <year>  <name of author>
    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
<https://www.gnu.org/licenses/>.

  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
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: NAMESPACE
================================================
# Generated by roxygen2: do not edit by hand

S3method(RunALRA,Seurat)
S3method(RunALRA,default)
S3method(RunPaCMAP,Seurat)
S3method(RunPaCMAP,default)
S3method(as.Seurat,Conos)
S3method(as.Seurat,cell_data_set)
S3method(as.Seurat,list)
S3method(as.cell_data_set,Seurat)
export(ALRAChooseKPlot)
export(ExportToCellbrowser)
export(FastMNNIntegration)
export(PlotMiQC)
export(ReadAlevin)
export(ReadVelocity)
export(RunALRA)
export(RunBanksy)
export(RunCoGAPS)
export(RunFastMNN)
export(RunGLMPCA)
export(RunMiQC)
export(RunOptimizeALS)
export(RunPaCMAP)
export(RunPresto)
export(RunPrestoAll)
export(RunQuantileAlignSNF)
export(RunQuantileNorm)
export(RunSNF)
export(RunVelocity)
export(Runtricycle)
export(StopCellbrowser)
export(as.cell_data_set)
export(scVIIntegration)
importFrom(BiocManager,install)
importFrom(Matrix,Matrix)
importFrom(Matrix,writeMM)
importFrom(R.utils,gzip)
importFrom(Seurat,"DefaultAssay<-")
importFrom(Seurat,"Idents<-")
importFrom(Seurat,"Key<-")
importFrom(Seurat,"Loadings<-")
importFrom(Seurat,"Misc<-")
importFrom(Seurat,"Tool<-")
importFrom(Seurat,"VariableFeatures<-")
importFrom(Seurat,CombinePlots)
importFrom(Seurat,CreateAssayObject)
importFrom(Seurat,CreateDimReducObject)
importFrom(Seurat,CreateSeuratObject)
importFrom(Seurat,DefaultAssay)
importFrom(Seurat,Embeddings)
importFrom(Seurat,FetchData)
importFrom(Seurat,FindAllMarkers)
importFrom(Seurat,FindMarkers)
importFrom(Seurat,GetAssayData)
importFrom(Seurat,Idents)
importFrom(Seurat,IsGlobal)
importFrom(Seurat,Loadings)
importFrom(Seurat,LogSeuratCommand)
importFrom(Seurat,Project)
importFrom(Seurat,Reductions)
importFrom(Seurat,SelectIntegrationFeatures)
importFrom(Seurat,SplitObject)
importFrom(Seurat,Stdev)
importFrom(Seurat,Tool)
importFrom(Seurat,VariableFeatures)
importFrom(Seurat,as.Graph)
importFrom(Seurat,as.Seurat)
importFrom(Seurat,as.SingleCellExperiment)
importFrom(cowplot,theme_cowplot)
importFrom(data.table,data.table)
importFrom(data.table,fwrite)
importFrom(data.table,setDTthreads)
importFrom(ggplot2,aes_string)
importFrom(ggplot2,geom_line)
importFrom(ggplot2,geom_point)
importFrom(ggplot2,geom_vline)
importFrom(ggplot2,ggplot)
importFrom(ggplot2,labs)
importFrom(ggplot2,scale_x_continuous)
importFrom(igraph,get.adjacency)
importFrom(methods,"slot<-")
importFrom(methods,as)
importFrom(methods,new)
importFrom(methods,slot)
importFrom(remotes,install_github)
importFrom(reticulate,import)
importFrom(reticulate,py_module_available)
importFrom(rlang,"%||%")
importFrom(rlang,check_installed)
importFrom(rlang,duplicate)
importFrom(rsvd,rsvd)
importFrom(stats,as.dist)
importFrom(stats,pnorm)
importFrom(stats,quantile)
importFrom(stats,sd)
importFrom(stats,setNames)
importFrom(stats,wilcox.test)
importFrom(tools,file_ext)
importFrom(utils,assignInNamespace)
importFrom(utils,browseURL)
importFrom(utils,capture.output)
importFrom(utils,install.packages)
importFrom(utils,menu)
importFrom(utils,packageVersion)
importFrom(utils,setTxtProgressBar)
importFrom(utils,txtProgressBar)
importFrom(utils,write.table)


================================================
FILE: R/alevin.R
================================================
#' @include internal.R
#'
NULL

#' Load alevin quantification data
#'
#' A wrapper around tximport to create a \code{SeuratObject}
#' from alevin quantification data.
#'
#' @param file path to \code{quants_mat.gz} file within
#' alevin directory
#' @param getMeta logical, option to use \code{tximeta} to
#' programmatically obtain gene range information, default
#' is FALSE. Ranges are stored in \code{chr}, \code{start},
#' and \code{end} in the \code{meta.features} slot.
#' @param meanAndVariance logical, should mean and variance
#' of counts be returned in \code{counts} and \code{data}
#' slots, respectively
#' @param ... extra arguments passed to \code{tximport},
#' for example,
#' \code{alevinArgs=list(filterBarcodes=TRUE)}.
#'
#' @return returns a Seurat object with alevin counts
#' @seealso \code{\link[alevin]{alevin}}
#' @author Avi Srivastava
#' @references Srivastava, Avi, et al. "Alevin efficiently 
#' estimates accurate gene abundances from dscRNA-seq data." 
#' Genome biology 20.1 (2019): 65.
#' @export
ReadAlevin <- function(file, getMeta=FALSE, meanAndVariance=FALSE, ...) {
  CheckPackage(package = 'tximport', repository = 'bioconductor')
  CheckPackage(package = 'fishpond', repository = 'bioconductor')
  hasTximeta <- requireNamespace("tximeta", quietly=TRUE)
  metaSuccess <- FALSE
  if (getMeta) {
    if (!hasTximeta)
      stop("tximeta is not installed, use BiocManager::install()")
    se <- tximeta::tximeta(file, type="alevin", ...)
    metaSuccess <- !is.null(SummarizedExperiment::rowRanges(se))
    if (meanAndVariance &
        all(c("mean","variance") %in% SummarizedExperiment::assayNames(se))) {
      txi <- list(mean=SummarizedExperiment::assays(se)[["mean"]],
                  variance=SummarizedExperiment::assays(se)[["variance"]])
    } else {
      txi <- list(counts=SummarizedExperiment::assays(se)[["counts"]])
    }
  } else {
    txi <- tximport::tximport(file, type="alevin", ...)
  }
  if (meanAndVariance) {
    if (!all(c("mean","variance") %in% names(txi)))
      stop("mean and variance not present in alevin directory")
    obj <- CreateSeuratObject(counts=txi$mean)
    obj <- Seurat::SetAssayData(obj, "data", txi$variance)
  } else {
    obj <- CreateSeuratObject(counts=txi$counts)
  }
  if (metaSuccess) {
    r <- SummarizedExperiment::rowRanges(se)
    obj[["RNA"]][["chr"]] <- as.character(GenomicRanges::seqnames(r))
    obj[["RNA"]][["start"]] <- GenomicRanges::start(r)
    obj[["RNA"]][["end"]] <- GenomicRanges::end(r)
  }
  return(obj)
}


================================================
FILE: R/alra.R
================================================
#' Run Adaptively-thresholded Low Rank Approximation (ALRA)
#'
#' Runs ALRA, a method for imputation of dropped out values in scRNA-seq data.
#' Computes the k-rank approximation to A_norm and adjusts it according to the
#' error distribution learned from the negative values. Described in
#' Linderman, G. C., Zhao, J., Kluger, Y. (2018). "Zero-preserving imputation
#' of scRNA-seq data using low rank approximation." (bioRxiv:138677)
#'
#' @param object An object
#' @param k  The rank of the rank-k approximation. Set to NULL for automated choice of k.
#' @param q  The number of additional power iterations in randomized SVD when
#' computing rank k approximation. By default, q=10.
#' @param quantile.prob The quantile probability to use when calculating threshold.
#' By default, quantile.prob = 0.001.
#' @param use.mkl Use the Intel MKL based implementation of SVD. Needs to be
#' installed from https://github.com/KlugerLab/rpca-mkl.
#' @param mkl.seed Only relevant if use.mkl=T. Set the seed for the random
#' generator for the Intel MKL implementation of SVD. Any number <0 will
#' use the current timestamp. If use.mkl=F, set the seed using
#' set.seed() function as usual.
#' @param assay Assay to use
#' @param slot slot to use
#' @param setDefaultAssay If TRUE, will set imputed results as default Assay
#' @param genes.use genes to impute
#' @param K Number of singular values to compute when choosing k. Must be less
#' than the smallest dimension of the matrix. Default 100 or smallest dimension.
#' @param p.val.th  The threshold for ''significance'' when choosing k. Default 1e-10.
#' @param noise.start  Index for which all smaller singular values are considered noise.
#' Default K - 20.
#' @param q.k  Number of additional power iterations when choosing k. Default 2.
#' @param k.only If TRUE, only computes optimal k WITHOUT performing ALRA
#'
#' @param ... Arguments passed to other methods
#'
#' @importFrom rsvd rsvd
#' @importFrom Matrix Matrix
#' @importFrom stats pnorm sd setNames quantile
#' @importFrom Seurat DefaultAssay Tool GetAssayData Tool<- CreateAssayObject
#' DefaultAssay<-
#'
#'
#' @rdname RunALRA
#' @export RunALRA
#'
#' @author Jun Zhao, George Linderman
#' @references Linderman, G. C., Zhao, J., Kluger, Y. (2018). "Zero-preserving imputation
#' of scRNA-seq data using low rank approximation." (bioRxiv:138677)
#' @seealso \code{\link{ALRAChooseKPlot}}
#'
#' @examples
#' \dontrun{
#' pbmc_small
#' # Example 1: Simple usage, with automatic choice of k.
#' pbmc_small_alra <- RunALRA(object = pbmc_small)
#' # Example 2: Visualize choice of k, then run ALRA
#' # First, choose K
#' pbmc_small_alra <- RunALRA(pbmc_small, k.only=TRUE)
#' # Plot the spectrum, spacings, and p-values which are used to choose k
#' ggouts <- ALRAChooseKPlot(pbmc_small_alra)
#' do.call(gridExtra::grid.arrange, c(ggouts, nrow=1))
#' # Run ALRA with the chosen k
#' pbmc_small_alra <- RunALRA(pbmc_small_alra)
#' }
#'
RunALRA <- function(object, ...) {
  UseMethod(generic = 'RunALRA', object = object)
}

#' @rdname RunALRA
#' @export
#'
RunALRA.default <- function(
  object,
  k = NULL,
  q = 10,
  quantile.prob = 0.001,
  use.mkl = FALSE,
  mkl.seed = -1,
  ...
) {
  A.norm <- t(x = as.matrix(x = object))
  message("Identifying non-zero values")
  originally.nonzero <- A.norm > 0
  message("Computing Randomized SVD")
  if (use.mkl) {
    CheckPackage(package = 'KlugerLab/rpca-mkl/fastRPCA', repository = 'github')
    fastDecomp.noc <- setNames(
      object = vector(mode = "list", length = 3),
      nm = c("u", "d", "v")
    )
    fastPCAOut <- fastRPCA::fastPCA(
      inputMatrix = A.norm,
      k = k,
      its = q,
      l = (k + 10),
      seed = mkl.seed
    )
    fastDecomp.noc$u <- fastPCAOut$U
    fastDecomp.noc$v <- fastPCAOut$V
    fastDecomp.noc$d <- diag(x = fastPCAOut$S)
  } else {
    fastDecomp.noc <- rsvd(A = A.norm, k = k, q = q)
  }
  A.norm.rank.k <- fastDecomp.noc$u[, 1:k] %*%
    diag(x = fastDecomp.noc$d[1:k]) %*%
    t(x = fastDecomp.noc$v[,1:k])
  message(sprintf("Find the %f quantile of each gene", quantile.prob))
  # A.norm.rank.k.mins <- abs(x = apply(X = A.norm.rank.k, MARGIN = 2, FUN = min))
  A.norm.rank.k.mins <- abs(x = apply(
    X = A.norm.rank.k,
    MARGIN = 2,
    FUN = function(x) {
      return(quantile(x = x, probs = quantile.prob))
    }
  ))
  message("Thresholding by the most negative value of each gene")
  A.norm.rank.k.cor <- replace(
    x = A.norm.rank.k,
    list = A.norm.rank.k <= A.norm.rank.k.mins[col(A.norm.rank.k)],
    values = 0
  )
  sd.nonzero <- function(x) {
    return(sd(x = x[!x == 0]))
  }
  sigma.1 <- apply(X = A.norm.rank.k.cor, MARGIN = 2, FUN = sd.nonzero)
  sigma.2 <- apply(X = A.norm, MARGIN = 2, FUN = sd.nonzero)
  mu.1 <- colSums(x = A.norm.rank.k.cor) / colSums(x = !!A.norm.rank.k.cor)
  mu.2 <- colSums(x = A.norm) / colSums(x = !!A.norm)
  toscale <- !is.na(sigma.1) & !is.na(sigma.2) & !(sigma.1 == 0 & sigma.2 == 0) & !(sigma.1 == 0)
  message(sprintf(fmt = "Scaling all except for %d columns", sum(!toscale)))
  sigma.1.2 <- sigma.2 / sigma.1
  toadd <- -1 * mu.1 * sigma.2 / sigma.1 + mu.2
  A.norm.rank.k.temp <- A.norm.rank.k.cor[, toscale]
  A.norm.rank.k.temp <- sweep(
    x = A.norm.rank.k.temp,
    MARGIN = 2,
    STATS = sigma.1.2[toscale],
    FUN = "*"
  )
  A.norm.rank.k.temp <- sweep(
    x = A.norm.rank.k.temp,
    MARGIN = 2,
    STATS = toadd[toscale],
    FUN = "+"
  )
  A.norm.rank.k.cor.sc <- A.norm.rank.k.cor
  A.norm.rank.k.cor.sc[, toscale] <- A.norm.rank.k.temp
  A.norm.rank.k.cor.sc[A.norm.rank.k.cor == 0] <- 0
  lt0 <- A.norm.rank.k.cor.sc < 0
  A.norm.rank.k.cor.sc[lt0] <- 0
  message(sprintf(
    fmt = "%.2f%% of the values became negative in the scaling process and were set to zero",
    100 * sum(lt0) / prod(dim(x = A.norm))
  ))
  A.norm.rank.k.cor.sc[originally.nonzero & A.norm.rank.k.cor.sc == 0] <-
    A.norm[originally.nonzero & A.norm.rank.k.cor.sc == 0]
  colnames(x = A.norm.rank.k) <- colnames(x = A.norm.rank.k.cor.sc) <-
    colnames(x = A.norm.rank.k.cor) <- colnames(x = A.norm)
  original.nz <- sum(A.norm > 0) / prod(dim(x = A.norm))
  completed.nz <- sum(A.norm.rank.k.cor.sc > 0) / prod(dim(x = A.norm))
  message(sprintf(
    fmt = "The matrix went from %.2f%% nonzero to %.2f%% nonzero",
    100 * original.nz,
    100 * completed.nz
  ))
  return(A.norm.rank.k.cor.sc)
}

#' @rdname RunALRA
#' @export
#' @method RunALRA Seurat
#'
RunALRA.Seurat <- function(
  object,
  k = NULL,
  q = 10,
  quantile.prob = 0.001,
  use.mkl = FALSE,
  mkl.seed=-1,
  assay = NULL,
  slot = "data",
  setDefaultAssay = TRUE,
  genes.use = NULL,
  K = NULL,
  thresh=6,
  noise.start = NULL,
  q.k = 2,
  k.only = FALSE,
  ...
) {
  if (!is.null(x = k) && k.only) {
    warning("Stop: k is already given, set k.only = FALSE or k = NULL")
  }
  genes.use <- genes.use %||% rownames(x = object)
  assay <- assay %||% DefaultAssay(object = object)
  alra.previous <- Tool(object = object, slot = 'RunALRA')
  alra.info <- list()
  # Check if k is already stored
  if (is.null(x = k) & !is.null(alra.previous[["k"]])) {
    k <- alra.previous[["k"]]
    message("Using previously computed value of k")
  }
  data.used <- GetAssayData(object = object, assay = assay, layer = slot)[genes.use,]
  # Choose k with heuristics if k is not given
  if (is.null(x = k)) {
    # set K based on data dimension
    if (is.null(x = K)) {
      K <- 100
      if (K > min(dim(x = data.used))) {
        K <- min(dim(x = data.used))
        warning("For best performance, we recommend using ALRA on expression matrices larger than 100 by 100")
      }
    }
    if (K > min(dim(x = data.used))) {
      stop("For an m by n data, K must be smaller than the min(m,n)")
    }
    # set noise.start based on K
    if (is.null(x = noise.start)) {
      noise.start <- K - 20
      if (noise.start <= 0) {
        noise.start <- max(K - 5, 1)
      }
    }
    if (noise.start > K - 5) {
      stop("There need to be at least 5 singular values considered noise")
    }
    noise.svals <- noise.start:K
    if (use.mkl) {
      CheckPackage(package = 'KlugerLab/rpca-mkl/fastRPCA', repository = 'github')
      L <- min(K + 10, min(dim(x = data.used)))
      rsvd.out <- setNames(
        object = vector(mode = "list", length = 3),
        nm = c("u", "d", "v")
      )
      fastPCAOut <- fastRPCA::fastPCA(
        inputMatrix = as.matrix(x = data.used),
        k = K,
        its = q.k,
        l = L,
        seed = mkl.seed
      )
      rsvd.out$u <- fastPCAOut$U
      rsvd.out$v <- fastPCAOut$V
      rsvd.out$d <- diag(x = fastPCAOut$S)
    } else {
      rsvd.out <- rsvd(A = t(x = as.matrix(x = data.used)), k = K, q = q.k)
    }
    diffs <- rsvd.out$d[1:(length(x = rsvd.out$d) - 1)] - rsvd.out$d[2:length(x = rsvd.out$d)]
    mu <- mean(x = diffs[noise.svals - 1])
    sigma <- sd(x = diffs[noise.svals - 1])
    num_of_sds <- (diffs - mu) / sigma
    k <- max(which(x = num_of_sds > thresh))
    alra.info[["d"]] <- rsvd.out$d
    alra.info[["k"]] <- k
    alra.info[["diffs"]] <- diffs
    Tool(object = object) <- alra.info
  }
  if (k.only) {
    message("Chose rank k = ", k, ", WITHOUT performing ALRA")
    return(object)
  }
  message("Rank k = ", k)
  # Perform ALRA on data.used
  output.alra <- RunALRA(
    object = data.used,
    k = k,
    q = q,
    quantile.prob = quantile.prob,
    use.mkl = use.mkl,
    mkl.seed = mkl.seed
  )
  # Save ALRA data in object@assay
  data.alra <- Matrix(data = t(x = output.alra), sparse = TRUE)
  rownames(x = data.alra) <- genes.use
  colnames(x = data.alra) <- colnames(x = object)
  assay.alra <- CreateAssayObject(data = data.alra)
  object[["alra"]] <- assay.alra
  if (setDefaultAssay) {
    message("Setting default assay as alra")
    DefaultAssay(object = object) <- "alra"
  }
  return(object)
}


#' ALRA Approximate Rank Selection Plot
#'
#' Plots the results of the approximate rank selection process for ALRA.
#'
#'
#' @param object Seurat object
#' @param start Index to start plotting singular value spacings from.
#' The transition from "signal" to "noise" in the is hard to see because the
#' first singular value spacings are so large. Nicer visualizations result from
#' skipping the first few. If set to 0 (default) starts from k/2.
#' @param combine Combine plots into a single gg object; note that if TRUE,
#' themeing will not work when plotting multiple features
#'
#' @return A list of 3 ggplot objects splotting the singular values, the
#' spacings of the singular values, and the p-values of the singular values.
#'
#' @author Jun Zhao, George Linderman
#' @seealso \code{\link{RunALRA}}
#'
#' @importFrom Seurat CombinePlots
#' @importFrom cowplot theme_cowplot
#' @importFrom ggplot2 ggplot aes_string geom_point geom_line
#' geom_vline scale_x_continuous labs
#' @export
#'
ALRAChooseKPlot <- function(object, start = 0, combine = TRUE) {
  alra.data <- Tool(object = object, slot = 'RunALRA')
  if (is.null(x = alra.data)) {
    stop('RunALRA should be run prior to using this function.')
  }
  d <- alra.data[["d"]]
  diffs <- alra.data[["diffs"]]
  pvals <- alra.data[["pvals"]]
  k <- alra.data[["k"]]
  if (start == 0) {
    start <- floor(x = k / 2)
  }
  if (start > k) {
    stop("Plots should include k (i.e. starting.from should be less than k)")
  }
  breaks <- seq(from = 10, to = length(x = d), by = 10)
  ggdata <- data.frame(x = 1:length(x = d), y = d)
  gg1 <- ggplot(data = ggdata, mapping = aes_string(x = 'x', y = 'y')) +
    geom_point(size = 1) +
    geom_line(size = 0.5) +
    geom_vline(xintercept = k) +
    theme_cowplot() +
    scale_x_continuous(breaks = breaks) +
    labs(x = NULL, y = 's_i', title = 'Singular values')
  ggdata <- data.frame(x = 2:length(x = d), y = diffs)[-(1:(start - 1)), ]
  gg2 <- ggplot(data = ggdata, mapping = aes_string(x = 'x', y = 'y')) +
    geom_point(size = 1) +
    geom_line(size = 0.5) +
    geom_vline(xintercept = k + 1) +
    theme_cowplot() +
    scale_x_continuous(breaks = breaks) +
    labs(x = NULL, y = 's_{i} - s_{i-1}', title = 'Singular value spacings')
  ggdata <- data.frame(x = 2:length(x = d), y = pvals)
  gg3 <- ggplot(data = ggdata, mapping = aes_string(x = 'x', y = 'y')) +
    geom_point(size = 1) +
    geom_vline(xintercept = k + 1) +
    theme_cowplot() +
    scale_x_continuous(breaks = breaks) +
    labs(x = NULL, y = 'p.val', title = 'Singular value spacing p-values')
  plots <- list(spectrum = gg1, spacings = gg2, pvals = gg3)
  if (combine) {
    plots <- CombinePlots(plots = plots)
  }
  return(plots)
}


================================================
FILE: R/banksy.R
================================================

#' @include internal.R
#'
NULL

#' Run Banksy on a Seurat Object
#'
#' @param object A Seurat object
#' @param lambda (numeric) Spatial weight parameter
#' @param assay (character) Assay in Seurat object to use
#' @param slot (character) Slot in Seurat assay to use
#' @param use_agf (boolean) Whether to use the AGF
#' @param dimx (character) Column name of spatial x dimension (must be in metadata)
#' @param dimy (character) Column name of spatial y dimension (must be in metadata)
#' @param dimz (character) Column name of spatial z dimension (must be in metadata)
#' @param ndim (integer) Number of spatial dimensions to extract
#' @param features (character) Features to compute. Can be 'all', 'variable' or
#'   a vector of feature names
#' @param group (character) Column name of a grouping variable (must be in metadata)
#' @param split.scale (boolean) Whether to separate scaling by group
#' @param k_geom (numeric) kNN parameter - number of neighbors to use
#' @param n (numeric) kNN_rn parameter - exponent of radius
#' @param sigma (numeric) rNN parameter - standard deviation of Gaussian kernel
#' @param alpha (numeric) rNN parameter - determines radius used
#' @param k_spatial (numeric) rNN parameter - number of neighbors to use
#' @param spatial_mode (character) Kernel for neighborhood computation
#' \itemize{
#'  \item{kNN_median: k-nearest neighbors with median-scaled Gaussian kernel}
#'  \item{kNN_r: k-nearest neighbors with $1/r$ kernel}
#'  \item{kNN_rn: k-nearest neighbors with $1/r^n$ kernel}
#'  \item{kNN_rank: k-nearest neighbors with rank Gaussian kernel}
#'  \item{kNN_unif: k-nearest neighbors wth uniform kernel}
#'  \item{rNN_gauss: radial nearest neighbors with Gaussian kernel}
#' }
#' @param assay_name (character) Name for Banksy assay in Seurat object
#' @param M (numeric) Advanced usage. Highest azimuthal harmonic
#' @param verbose (boolean) Print messages
#'
#' @return A Seurat object with new assay holding a Banksy matrix
#'
#' @seealso \code{\link[Banksy]{ComputeBanksy}}
#'
#' @author Joseph Lee, Vipul Singhal
#'
#' @references Vipul Singhal, Nigel Chou et. al. BANKSY: A Spatial Omics
#' Algorithm that Unifies Cell Type Clustering and Tissue Domain Segmentation
#'
#' @export
RunBanksy <- function(object, lambda, assay='RNA', slot='data', use_agf=FALSE,
                      dimx=NULL, dimy=NULL, dimz=NULL, ndim=2,
                      features='variable',
                      group=NULL, split.scale=TRUE,
                      k_geom=15, n=2, sigma=1.5,
                      alpha=0.05, k_spatial=10, spatial_mode='kNN_median',
                      assay_name='BANKSY', M=NULL, verbose=TRUE) {
    # Check packages
    SeuratWrappers:::CheckPackage(package = 'data.table', repository = 'CRAN')
    SeuratWrappers:::CheckPackage(package = 'Matrix', repository = 'CRAN')
    SeuratWrappers:::CheckPackage(package = 'Banksy', repository = 'github')

    # Check lambda param
    if (lambda < 0 || lambda > 1) stop('Lambda must be between 0 and 1')

    # Get data
    data_own <- get_data(object, assay, slot, features, verbose)

    # Get locs
    locs <- get_locs(object, dimx, dimy, dimz, ndim, data_own, group, verbose)
    if (!is.null(group)) {
        object <- AddMetaData(
            object, metadata = locs,
            col.name = paste0('staggered_', colnames(locs)))
    }

    # Compute neighbor matrix
    knn_list <- lapply(k_geom, function(kg) {
      Banksy:::computeNeighbors(locs,
                                spatial_mode = spatial_mode, k_geom = kg, n = n,
                                sigma=sigma, alpha=alpha, k_spatial=k_spatial,
                                verbose=verbose)
    })

    # Create Banksy matrix
    M <- seq(0, max(Banksy:::getM(use_agf, M)))
    # Compute harmonics
    center <- rep(TRUE, length(M))
    # Only center higher harmonics
    center[1] <- FALSE
    har <- Map(function(knn_df, M, center) {
      x <- Banksy:::computeHarmonics(data_own, knn_df, M, center, verbose)
      rownames(x) <- paste0(rownames(x), '.m', M)
      x
    }, knn_list, M, center)

    # Scale by lambdas
    lambdas <- Banksy:::getLambdas(lambda, n_harmonics = length(har))

    # Merge with own expression
    if (verbose) message('Creating Banksy matrix')
    data_banksy <- c(list(data_own), har)
    if (verbose) message('Scaling BANKSY matrix. Do not call ScaleData on assay ', assay_name)
    data_scaled <- lapply(data_banksy, fast_scaler,
                          object, group, split.scale, verbose)

    # Multiple by lambdas
    data_banksy <- Map(function(lam, mat) lam * mat, lambdas, data_banksy)
    data_scaled <- Map(function(lam, mat) lam * mat, lambdas, data_scaled)

    # Rbind
    data_banksy <- do.call(rbind, data_banksy)
    data_scaled <- do.call(rbind, data_scaled)

    # Create an assay object
    if (grepl(pattern = 'counts', x = slot)) {
        banksy_assay <- Seurat::CreateAssayObject(counts = data_banksy)
    } else {
        banksy_assay <- Seurat::CreateAssayObject(data = data_banksy)
    }

    # Add assay to Seurat object and set as default
    if (verbose) message('Setting default assay to ', assay_name)
    object[[assay_name]] <- banksy_assay
    DefaultAssay(object) <- assay_name
    object <- SetAssayData(object, layer = 'scale.data', new.data = data_scaled,
                           assay = assay_name)

    # Log commands
    object <- Seurat::LogSeuratCommand(object = object)

  return(object)
}

# Get own expression matrix from Seurat object
get_data <- function(object, assay, slot, features, verbose) {
    # Fetch data from Seurat
    if (verbose) message('Fetching data from slot ', slot,' from assay ', assay)
    data_own <- Seurat::GetAssayData(object = object, assay = assay, layer = slot)
    # Feature subset
    if (features[1] != 'all') {
        if (verbose) message('Subsetting by features')
        if (features[1] == 'variable') {
            feat <- Seurat::VariableFeatures(object)
            if (length(feat) == 0) {
                warning('No variable features found. Running Seurat::FindVariableFeatures')
                object <- Seurat::FindVariableFeatures(object)
                feat <- Seurat::VariableFeatures(object)
            }
        } else {
            feat <- features[which(rownames(object) %in% features)]
            if (length(feat) == 0) stop('None of the specified features found. Check if features in Seurat object')
        }
        data_own <- data_own[feat,,drop=FALSE]
    }
    data_own <- as.matrix(x = data_own)
    return(data_own)
}

# Get locations from Seurat object
get_locs <- function(object, dimx, dimy, dimz, ndim, data_own, group, verbose) {

    if (!is.null(dimx) & !is.null(dimy)) {
        # Extract locations from metadata
        locs <- data.frame(
            sdimx = unlist(object[[dimx]]),
            sdimy = unlist(object[[dimy]])
        )
        rownames(locs) <- colnames(object)

        # Add z-dim if present
        if (!is.null(dimz)) locs$sdimz = object[[dimz]]

        # Check locations
        obj_samples <- colnames(data_own)
        locs_samples <- rownames(locs)
        if (any(is.na(match(obj_samples, locs_samples)))) {
            na_id <- which(is.na(match(obj_samples, locs_samples)))
            warning('No centroids found for samples: ',
                    paste(obj_samples[na_id], collapse = ', '), '. Dropping samples.')
            data_own <- data_own[, -na_id, drop = FALSE]
        }
        locs <- locs[match(obj_samples, locs_samples),,drop=FALSE]

    } else {
        # Extract locations with Seurat accessor
        locs <- Seurat::GetTissueCoordinates(object)[,seq_len(ndim)]
    }

    dim_names <- paste0('sdim', c('x','y','z'))
    colnames(locs) <- dim_names[seq_len(ncol(locs))]

    if (!is.null(group)) {
        # Stagger locations by group
        if (verbose) message('Staggering locations by ', group)
        locs[,1] = locs[,1] + abs(min(locs[,1]))
        max_x = max(locs[,1]) * 2
        n_groups = length(unique(unlist(object[[group]])))
        shift = seq(from = 0, length.out = n_groups, by = max_x)
        locs[,1] = locs[,1] + rep(shift, table(object[[group]]))
    }

    return(locs)
}

# Scaling
fast_scaler = function(data, object, group, split.scale, verbose) {
    # Split scaling by group
    if (!is.null(group) & split.scale) {
        groups = unlist(object[[group]])
        ugroups = unique(groups)
        for (curr_group in ugroups) {
            if (verbose) message('Scaling group: ', curr_group)
            curr_group_id <- which(curr_group == groups)
            data[, curr_group_id] <- Seurat:::FastRowScale(
              data[, curr_group_id])
        }
    } else {
        data <- Seurat::FastRowScale(data)
    }
    data
}


================================================
FILE: R/cellbrowser.R
================================================
# Build a UCSC cell browser website from a \code{Seurat} object
#
NULL
#require(reticulate)
#require(Matrix)
#require(R.utils)

#' Used by \code{ExportToCellbrowser}:
#' Write a big sparse matrix to a .tsv.gz file by writing chunks, concating them with the Unix cat command,
#' then gziping the result. This does not work on Windows, we'd have to use the copy /b command there.
#'
#' @param inMat input matrix
#' @param outFname output file name, has to end with .gz
#' @param sliceSize=1000, size of each chunk in number of lines
#'
#' @return Invisibly returns \code{NULL}
#'
#' @importFrom data.table setDTthreads data.table fwrite
#'
#' @examples
#' \dontrun{
#' writeSparseTsvChunks( pbmc_small@data, "exprMatrix.tsv.gz")
#' }
#'
writeSparseTsvChunks = function (inMat, outFname, sliceSize=1000) {
    fnames = c()
    setDTthreads(threads = 8)  # otherwise this would use dozens of CPUs on a fat server
    mat = inMat
    geneCount = nrow(mat)
    message("Writing expression matrix to ", outFname)
    startIdx = 1
    while (startIdx < geneCount) {
        endIdx <- min(startIdx+sliceSize-1, geneCount)
        matSlice <- mat[startIdx:endIdx,]
        denseSlice <- as.matrix(x = matSlice)
        dt <- data.table(denseSlice)
        dt <- cbind(gene = rownames(x = matSlice), dt)
        writeHeader <- startIdx == 1
        sliceFname <- paste0("temp", startIdx,".txt")
        fwrite(dt, sep="\t", file=sliceFname, quote = FALSE, col.names = writeHeader)
        fnames <- append(x = fnames, values = sliceFname);
        startIdx <- startIdx + sliceSize
    }
    message("Concatenating chunks")
    system(command = paste(
       "cat",
       paste(fnames, collapse=" "),
       "| gzip >",
       outFname,
       sep = " "
    ))
    unlink(x = fnames)
    return(invisible(x = NULL))
}

#' used by ExportToCellbrowser:
#' Return a matrix object from a Seurat object or show an error message
#'
#' @param object Seurat object
#' @param matrix.slot the name of the slot
#'
findMatrix = function(object, matrix.slot ) {
  if (matrix.slot == "counts") {
    counts <- GetAssayData(object = object, slot = "counts")
  } else if (matrix.slot == "scale.data") {
    counts <- GetAssayData(object = object, slot="scale.data")
  }
  else if (matrix.slot=="data") {
    counts <- GetAssayData(object = object)
  } else {
    stop("matrix.slot can only be one of: counts, scale.data, data")
  }
}

#' Export \code{Seurat} objects for UCSC cell browser and stop open cell browser
#' instances from R
#'
#' @param object Seurat object
#' @param dir path to directory where to save exported files. These are:
#' exprMatrix.tsv, tsne.coords.tsv, meta.tsv, markers.tsv and a default
#' cellbrowser.conf
#' @param dataset.name name of the dataset. Defaults to Seurat project name
#' @param reductions vector of reduction names to export, defaults to all reductions.
#' @param markers.file path to file with marker genes. By defaults, marker
#' are searched in the object itself as misc$markers. If none are supplied in
#' object or via this argument, they are recalculated with \code{FindAllMarkers}
#' @param markers.n if no markers were supplied, FindAllMarkers is run.
#' This parameter indicates how many markers to calculate, default is 100
#' @param matrix.slot matrix to use, default is 'counts'
#' @param use.mtx export the matrix in .mtx.gz format. Default is False,
#'        unless the matrix is bigger than R's maximum matrix size.
#' @param cluster.field name of the metadata field containing cell cluster
#' @param cb.dir path to directory where to create UCSC cellbrowser static
#' website content root, e.g. an index.html, .json files, etc. These files
#' can be copied to any webserver. If this is specified, the cellbrowser
#' package has to be accessible from R via reticulate.
#' @param meta.fields vector of meta fields to export, default is all.
#' @param meta.fields.names vector meta field names to show in UI. Must have
#'        same length as meta.fields. Default is meta.fields.
#' @param skip.markers whether to skip exporting markers
#' @param skip.expr.matrix whether to skip exporting expression matrix
#' @param skip.metadata whether to skip exporting metadata
#' @param skip.reductions whether to skip exporting reductions
#' @param port on which port to run UCSC cellbrowser webserver after export
#' @param ... specifies the metadata fields to export. To supply a field and its
#' human readable name, pass name as \code{field="name"} parameter.
#'
#' @return This function exports Seurat object as a set of tsv files
#' to \code{dir} directory, copying the \code{markers.file} if it is
#' passed. It also creates the default \code{cellbrowser.conf} in the
#' directory. This directory could be read by \code{cbBuild} to
#' create a static website viewer for the dataset. If \code{cb.dir}
#' parameter is passed, the function runs \code{cbBuild} (if it is
#' installed) to create this static website in \code{cb.dir} directory.
#' If \code{port} parameter is passed, it also runs the webserver for
#' that directory and opens a browser.
#'
#' @author Maximilian Haeussler, Nikolay Markov
#'
#' @importFrom tools file_ext
#' @importFrom utils browseURL packageVersion write.table
#' @importFrom R.utils gzip
#' @importFrom reticulate py_module_available import
#' @importFrom Seurat Project Idents GetAssayData Embeddings FetchData
#' @importFrom Matrix  writeMM
#'
#' @export
#'
#' @name CellBrowser
#' @rdname CellBrowser
#'
#' @importFrom methods slot
#' @importFrom utils packageVersion
#' @importFrom reticulate py_module_available import
#'
#' @examples
#' \dontrun{
#' ExportToCellbrowser(pbmc_small, dataset.name = "PBMC", dir = "out")
#' }
#'
ExportToCellbrowser <- function(
  object,
  dir,
  dataset.name = Project(object = object),
  reductions = NULL,
  markers.file = NULL,
  cluster.field = NULL,
  cb.dir = NULL,
  port = NULL,
  use.mtx = FALSE,
  meta.fields = NULL,
  meta.fields.names = NULL,
  matrix.slot = "counts",
  markers.n = 100,
  skip.markers = FALSE,
  skip.expr.matrix = FALSE,
  skip.metadata = FALSE,
  skip.reductions = FALSE
) {
  if (!requireNamespace("Seurat", quietly = TRUE)) {
    stop("This script requires that Seurat (V2 or V3) is installed")
  }

  message("Seurat Version installed: ", packageVersion("Seurat"))
  message("Object was created with Seurat version ", object@version)

  objMaj = package_version(object@version)$major
  pkgMaj = package_version(packageVersion("Seurat"))$major

  if (objMaj!=2 && objMaj!=3) {
          stop("can only process Seurat2 or Seurat3 objects, object was made with Seurat ", object@version)
  }

  if (objMaj != pkgMaj) {
          stop("The installed major version of Seurat is different from Seurat input object. You have to down- or upgrade your installed Seurat version. See the Seurat documentation.")
  }

  reducNames = reductions

  # compatibility layer for Seurat 2 vs 3
  # see https://satijalab.org/seurat/essential_commands.html
  if (inherits(x = object, what = 'seurat')) {
      # Seurat v2 objects are called "seurat" (Paul Hoffman)
      # -> Seurat 2 data access
      idents <- object@ident # Idents() in Seurat3
      meta <- object@meta.data
      cellOrder <- object@cell.names
      if (matrix.slot=="counts") {
          counts <- object@raw.data
      } else if (matrix.slot=="scale.data") {
          counts <- object@scale.data
      }
      else if (matrix.slot=="data") {
          counts <- object@data
      } else {
          error("matrix.slot can only be one of: counts, scale.data, data")
      }
      genes <- rownames(x = object@data)
      dr <- object@dr
  } else {
    # Seurat 3 functions
    idents <- Idents(object = object)
    meta <- object[[]]
    cellOrder <- colnames(x = object)
    counts <- findMatrix(object = object, matrix.slot = matrix.slot)
    if (dim(x = counts)[1] == 0) {
      message(paste0("The Seurat data slot '", matrix.slot, "' contains no data. Trying default assay."))
      defAssay <- DefaultAssay(object)
      assay <- GetAssay(object, defAssay)
      message(paste0("Default assay is ", defAssay))
      counts <- findMatrix(assay, matrix.slot)
      genes <- rownames(counts)
      if (dim(x = counts)[1] == 0) {
        stop(
          "Could not find an expression matrix",
          "Please select the correct slot where the matrix is stored, possible ",
          "values are 'counts', 'scale.data' or 'data'. To select a slot, ",
          "use the option 'matrix.slot' from R or the cbImportSeurat option -s from the command line."
        )
      }
    }
    else {
      genes <- rownames(x = object)
    }
    dr <- object@reductions
  }
  if (is.null(x = cluster.field)) {
    cluster.field = "Cluster"
  }
  if (is.null(x = meta.fields)) {
    meta.fields <- colnames(x = meta)
    if (length(x = levels(x = idents)) > 1) {
      meta.fields <- c(meta.fields, ".ident")
    }
  }
  if (!is.null(x = port) && is.null(x = cb.dir)) {
    stop("cb.dir parameter is needed when port is set")
  }
  if (!dir.exists(paths = dir)) {
    dir.create(path = dir)
  }
  if (!dir.exists(paths = dir)) {
    stop("Output directory ", dir, " cannot be created or is a file")
  }
  if (dataset.name == "SeuratProject") {
    warning("Using default project name means that you may overwrite project with the same name in the cellbrowser html output folder")
  }
  enum.fields <- c()

  # Export expression matrix
  if (!skip.expr.matrix) {
      too.big = ((((ncol(counts)/1000)*(nrow(counts)/1000))>2000) && is(counts, 'sparseMatrix'))
      if (use.mtx || (too.big && (.Platform$OS.type=="windows"))) {
            # we have to write the matrix to an mtx file
            matrixPath <- file.path(dir, "matrix.mtx")
            genesPath <- file.path(dir, "features.tsv")
            barcodesPath <- file.path(dir, "barcodes.tsv")
            message("Writing expression matrix to ", matrixPath)
            writeMM(counts, matrixPath)
            # easier to load if the genes file has at least two columns. Even though seurat objects
            # don't have yet explicit geneIds/geneSyms data, we just duplicate whatever the matrix has now
            write.table(as.data.frame(cbind(rownames(counts), rownames(counts))), file=genesPath, sep="\t", row.names=F, col.names=F, quote=F)
            write(colnames(counts), file = barcodesPath)
            message("Gzipping expression matrix")
            gzip(matrixPath)
            gzip(genesPath)
            gzip(barcodesPath)
      } else {
          # we can write the matrix as a tsv file
          gzPath <- file.path(dir, "exprMatrix.tsv.gz")
          if (too.big) {
              writeSparseTsvChunks(counts, gzPath);
          } else {
              mat = as.matrix(counts)
              df <- as.data.frame(mat, check.names=FALSE)
              df <- data.frame(gene=genes, df, check.names = FALSE)
              z <- gzfile(gzPath, "w")
              message("Writing expression matrix to ", gzPath)
              write.table(x = df, sep="\t", file=z, quote = FALSE, row.names = FALSE)
              close(con = z)
          }
      }
  }

  # Export cell embeddings/reductions
  if (is.null(reducNames)) {
      reducNames = names(dr)
      message("Using all embeddings contained in the Seurat object: ", reducNames)
  }

  foundEmbedNames = c()
  for (embedding in reducNames) {
    emb <- dr[[embedding]]
    if (is.null(x = emb)) {
        message("Embedding ", embedding, " does not exist in Seurat object. Skipping. ")
        next
    }
    df <-  emb@cell.embeddings
    if (ncol(x = df) > 2) {
      warning('Embedding ', embedding, ' has more than 2 coordinates, taking only the first 2')
      df <- df[, 1:2]
    }
    colnames(x = df) <- c("x", "y")
    df <- data.frame(cellId = rownames(x = df), df, check.names = FALSE)
    fname <- file.path(
      dir,
      sprintf("%s.coords.tsv", embedding)
    )
    message("Writing embeddings to ", fname)
    write.table(df[cellOrder, ], sep="\t", file=fname, quote = FALSE, row.names = FALSE)
    foundEmbedNames = append(foundEmbedNames, embedding)
  }
  # by default, the embeddings are sorted in the object by order of creation (pca, tsne, umap).
  # But that is usually the opposite of what users want, they want the last embedding to appear first
  # in the UI, so reverse the order here
  foundEmbedNames = sort(foundEmbedNames, decreasing=T)
  embeddings.conf <- c()
  for (embedName in foundEmbedNames) {
      conf <- sprintf(
        '{"file": "%s.coords.tsv", "shortLabel": "Seurat %1$s"}',
        embedName
      )
      embeddings.conf <- c(embeddings.conf, conf)
   }
  # Export metadata
  df <- data.frame(row.names = cellOrder, check.names = FALSE)
  for (field in meta.fields) {
    if (field == ".ident") {
      df$Cluster <- idents
      enum.fields <- c(enum.fields, "Cluster")
    } else {
      name <- meta.fields.names[[field]]
      if (is.null(name)) {
        name <- field
      }
      df[[name]] <- meta[[field]]
      if (!is.numeric(df[[name]])) {
        enum.fields <- c(enum.fields, name)
      }
    }
  }
  df <- data.frame(Cell = rownames(df), df, check.names = FALSE)
  fname <- file.path(dir, "meta.tsv")
  message("Writing meta data to ", fname)
  write.table(as.matrix(df[cellOrder, ]), sep = "\t", file = fname, quote = FALSE, row.names = FALSE)
  # Export markers
  markers.string <- ''
  if (is.null(markers.file)) {
    ext <- "tsv"
  } else {
    ext <- tools::file_ext(markers.file)
  }
  file <- paste0("markers.", ext)
  fname <- file.path(dir, file)
  if (!is.null(markers.file) && !skip.markers) {
    message("Copying ", markers.file, " to ", fname)
    file.copy(markers.file, fname)
  }
  if (is.null(markers.file) && skip.markers) {
    file <- NULL
  }
  if (is.null(markers.file) && !skip.markers) {
    if (length(levels(idents)) > 1) {
      markers.helper <- function(x) {
        partition <- markers[x,]
        ord <- order(partition$p_val_adj < 0.05, -partition$avg_logFC)
        res <- x[ord]
        naCount <- max(0, length(x) - markers.n)
        res <- c(res[1:markers.n], rep(NA, naCount))
        return(res)
      }
      if (.hasSlot(object, "misc") && !is.null(x = object@misc["markers"][[1]])) {
        message("Found precomputed markers in obj@misc['markers']")
        markers <- object@misc["markers"]$markers
      } else {
        message("Running FindAllMarkers(), using wilcox test, min logfc diff 0.25")
        markers <- FindAllMarkers(
          object,
          do.print = TRUE,
          print.bar = TRUE,
          test.use = "wilcox",
          logfc.threshold = 0.25
        )
      }
      message("Writing top ", markers.n, ", cluster markers to ", fname)
      markers.order <- ave(x = rownames(x = markers), markers$cluster, FUN = markers.helper)
      top.markers <- markers[markers.order[!is.na(x = markers.order)], ]
      write.table(x = top.markers, file = fname, quote = FALSE, sep = "\t", col.names = NA)
    } else {
      message("No clusters found in Seurat object and no external marker file provided, so no marker genes can be computed")
      file <- NULL
    }
  }
  if (!is.null(file)) {
    markers.string <- sprintf(
      'markers = [{"file": "%s", "shortLabel": "Seurat Cluster Markers"}]',
      file
    )
  }
  matrixOutPath <- "exprMatrix.tsv.gz"
  if (use.mtx) {
    matrixOutPath <- "matrix.mtx.gz"
  }
  config <- '
# This is a bare-bones cellbrowser config file auto-generated from R.
# Look at https://github.com/maximilianh/cellBrowser/blob/master/src/cbPyLib/cellbrowser/sampleConfig/cellbrowser.conf
# for a full file that shows all possible options
name="%s"
shortLabel="%1$s"
exprMatrix="%s"
#tags = ["10x", "smartseq2"]
meta="meta.tsv"
# possible values: "gencode-human", "gencode-mouse", "symbol" or "auto"
geneIdType="auto"
# file with gene,description (one per line) with highlighted genes, called "Dataset Genes" in the user interface
# quickGenesFile="quickGenes.csv"
clusterField="%s"
labelField="%s"
enumFields=%s
%s
coords=%s'
  enum.string <- paste0(
    "[",
    paste(paste0('"', enum.fields, '"'), collapse = ", "),
    "]"
  )
  coords.string <- paste0(
    "[",
    paste(embeddings.conf, collapse = ",\n"),
    "]"
  )
  config <- sprintf(
    config,
    dataset.name,
    matrixOutPath,
    cluster.field,
    cluster.field,
    enum.string,
    markers.string,
    coords.string
  )
  confPath = file.path(dir, "cellbrowser.conf")
  message("Writing cellbrowser config to ", confPath)
  cat(config, file = confPath)
  message("Prepared cellbrowser directory ", dir)
  if (!is.null(x = cb.dir)) {
    if (!py_module_available(module = "cellbrowser")) {
      stop(
        "The Python package `cellbrowser` is required to prepare and run ",
        "Cellbrowser. Please install it ",
        "on the Unix command line with `sudo pip install cellbrowser` (if root) ",
        "or `pip install cellbrowser --user` (as a non-root user). ",
        "To adapt the Python that is used, you can either set the env. variable RETICULATE_PYTHON ",
        "or do `require(reticulate) and use one of these functions: use_python(), use_virtualenv(), use_condaenv(). ",
        "See https://rstudio.github.io/reticulate/articles/versions.html; ",
        "at the moment, R's reticulate is using this Python: ",
        import(module = 'sys')$executable,
        ". "
      )
    }
    if (!is.null(x = port)) {
      port <- as.integer(x = port)
    }
    message("Converting cellbrowser directory to html/json files")
    cb <- import(module = "cellbrowser")
    cb$cellbrowser$build(dir, cb.dir)
    message("HTML files are ready in ", cb.dir)
    if (!is.null(port)) {
      message("Starting http server")
      cb$cellbrowser$stop()
      cb$cellbrowser$serve(cb.dir, port)
      Sys.sleep(time = 0.4)
      browseURL(url = paste0("http://localhost:", port))
    }
  }
}

#' Stop Cellbrowser web server
#'
#' @export
#'
#' @importFrom reticulate py_module_available
#' @importFrom reticulate import
#'
#' @examples
#' \dontrun{
#' StopCellbrowser()
#' }
#'
StopCellbrowser <- function() {
  if (py_module_available("cellbrowser")) {
    cb <- import("cellbrowser")
    cb$cellbrowser$stop()
  } else {
    stop("The `cellbrowser` package is not available in the Python used by R's reticulate")
  }
}


================================================
FILE: R/cogaps.R
================================================
#' @include internal.R
#'
NULL

#' Run CoGAPs on a Seurat object
#'
#' @param object Seurat object
#' @param assay Assay to pull data from
#' @param slot Slot to pull data from.
#' @param params \code{\link[CoGAPS]{CogapsParams}} object for specifying parameter settings
#' @param temp.file Name of temporary data matrix file to create if running in a distributed mode.
#' Setting to TRUE will generate the file name using \code{tempfile}.
#' @param reduction.name Name of the CoGAPS reduction returned
#' @param reduction.key Key for the CoGAPS reduction returned
#'
#' @return Returns a Seurat object with the CoGAPS results stored as a \code{\link{DimReduc}} object
#' @seealso \code{\link[CoGAPS]{CoGAPS}}
#' @references E.J. Fertig, J. Ding, A.V. Favorov, G. Parmigiani, and M.F. Ochs (2010) CoGAPS: an
#' integrated R/C++ package to identify overlapping patterns of activation of biological processes
#' from expression data. Bioinformatics 26:2792-2793.
#'
#' @importFrom Matrix writeMM
#'
#' @export
RunCoGAPS <- function(
  object,
  assay = NULL,
  slot = "counts",
  params = NULL,
  temp.file = NULL,
  reduction.name = "CoGAPS",
  reduction.key = "CoGAPS_",
  ...
) {
  SeuratWrappers:::CheckPackage(package = 'CoGAPS', repository = 'bioconductor')
  assay <- assay %||% DefaultAssay(object = object)
  dat <- GetAssayData(object = object, assay = assay, slot = slot)
  dat <- log2(x = dat + 1)
  geneNames <- rownames(x = dat)
  sampleNames <- colnames(x = dat)
  if (!is.null(temp.file)) {
    if (isTRUE(x = temp.file)) {
      temp.file <- paste0(tempfile(), ".mtx")
    } else if (file.exists(temp.file)) {
      stop("temp.file already exists and would be overwritten. Please either remove or specify a new name.")
    }
    dat <- as(object = dat, Class = "dgCMatrix")
    Matrix::writeMM(obj = dat, file = temp.file)
    dat <- temp.file
  } else {
    dat <- as.matrix(x = dat)
  }
  if (!is.null(x = params)) {
    CoGAPS_results <- CoGAPS::CoGAPS(
      data = dat,
      params = params,
      geneNames = geneNames,
      sampleNames = sampleNames,
      ...
    )
  } else {
    CoGAPS_results <- CoGAPS::CoGAPS(
      data = dat,
      geneNames = geneNames,
      sampleNames = sampleNames,
      ...
    )
  }
  object[["CoGAPS"]] <- CreateDimReducObject(
    embeddings = slot(object = CoGAPS_results, name = "sampleFactors"),
    loadings = slot(object = CoGAPS_results, name = "featureLoadings"),
    key = "CoGAPS_",
    assay = assay
  )
  return(object)
}


================================================
FILE: R/conos.R
================================================
#' Extra conversions to Seurat objects
#'
#' @inheritParams Seurat::as.Seurat
#'
#' @rdname as.Seurat.extras
#' @name as.Seurat
#'
#' @seealso \code{\link[Seurat]{as.Seurat}}
#'
#' @aliases as.Seurat
#'
NULL

#' @param method Name of matching method graph was built using
#' @param reduction Name of graph embedding, if calculated
#' @param idents Name of clutering method to set as identity class
#'
#' @details
#' The \code{Conos} method for \code{\link[Seurat]{as.Seurat}} only works if all
#' samples are \code{Seurat} objects. The object is initially constructed by merging
#' all samples together using \code{\link[Seurat]{merge}}, any sample-level dimensional
#' reductions and graphs will be lost during the merge. Extra information is added
#' to the resulting Seurat object as follows:
#' \itemize{
#'   \item Pairwise alignments will be stored in miscellaneous data, as will any
#'   other miscellaneous information
#'   \item If a graph is present in the \code{graph} field, it will be stored as
#'   a \code{Graph} object, reordered to match cell order in the new \code{Seurat}
#'   object. It will be named "\code{DefaultAssay(SeuratObject)}_\code{method}"
#'   \item If an embedding is present in the \code{embedding} field as a
#'   \code{\link{matrix}}, it will be stored as a \code{DimReduc} object with the
#'   name \code{reduction} and a key value of "\code{toupper(reduction)}_"
#'   \item If the length of the \code{clusters} field is greater than zero,
#'   clustering information (\code{groups} field) will be added to object metadata.
#'   Extra information (\code{result} field) will be added to miscellaneous data
#'   with the name "conos.\code{clustering}.result"
#'   \item If present, the first clustering entry in the \code{clusters} field
#'   will be set as object identity classes
#' }
#'
#' @importFrom igraph get.adjacency
#' @importFrom utils txtProgressBar setTxtProgressBar
#' @importFrom Seurat as.Seurat Misc<- DefaultAssay as.Graph
#' CreateDimReducObject Idents<-
#'
#' @rdname as.Seurat.extras
#' @export
#' @method as.Seurat Conos
#'
as.Seurat.Conos <- function(
  x,
  method = 'mnn',
  reduction = 'largeVis',
  idents = names(x = x$clusters)[1],
  verbose = TRUE,
  ...
) {
  if (!all(sapply(X = x$samples, FUN = inherits, what = 'Seurat'))) {
    stop(
      "Converting a Conos object to a Seurat object requires that all samples are Seurat v3 objects",
      call. = FALSE
    )
  }
  if (verbose) {
    message("Merging ", length(x = x$samples), " samples")
  }
  object <- merge(x = x$samples[[1]], x$samples[2:length(x = x$samples)])
  # Add pairs
  if (length(x = x$pairs) > 0) {
    if (verbose) {
      message("Adding pairwise alignments to 'conos.pairs' in miscellaneous data")
    }
    Misc(object = object, slot = 'conos.pairs') <- x$pairs
  }
  # Add graph
  if (!is.null(x = x$graph)) {
    graph <- paste(DefaultAssay(object = object), method, sep = '_')
    message("Adding graph as '", graph, "'")
    object[[graph]] <- as.Graph(x = get.adjacency(graph = x$graph)[colnames(x = object), colnames(x = object)])
  }
  # Add graph embedding
  if (is.matrix(x = x$embedding)) {
    if (verbose) {
      message("Adding graph embedding as ", reduction)
    }
    object[[reduction]] <- suppressWarnings(expr = CreateDimReducObject(
      embeddings = x$embedding,
      assay = DefaultAssay(object = object),
      key = paste0(toupper(x = reduction), '_')
    ))
  }
  # Add clustering information
  if (length(x = x$clusters) > 0) {
    if (verbose) {
      message("Adding clustering information")
      pb <- txtProgressBar(min = 0, max = length(x = x$clusters), style = 3, file = stderr())
    }
    for (clustering in names(x = x$clusters)) {
      object[[clustering]] <- x$clusters[[clustering]]$groups
      clustering.misc <- paste('conos', clustering, 'result', sep = '.')
      Misc(object = object, slot = clustering.misc) <- x$clusters[[clustering]]$result
      if (clustering == idents) {
        Idents(object = object) <- clustering
      }
      if (verbose) {
        setTxtProgressBar(pb = pb, value = 1 + pb$getVal())
      }
    }
  }
  if (verbose) {
    close(con = pb)
  }
  # Add miscellaneous information
  if (length(x = x$misc) > 0) {
    if (verbose) {
      message("Adding extra information to 'conos.misc' in miscellaneous data")
    }
    Misc(object = object, slot = 'conos.misc') <- x$misc
  }
  return(object)
}


================================================
FILE: R/fast_mnn.R
================================================
#' @include internal.R
#'
NULL

#' Run fastMNN
#'
#' @param object.list A list of Seurat objects
#' @param assay Assay to use, defaults to the default assay of the first object
#' @param features Either a list of features to use when calculating batch
#' correction, or a number (2000 by default) of variable features to select.
#' @param reduction.name Name to store resulting DimReduc object as
#' @param reduction.key Key for resulting DimReduc
#' @param reconstructed.assay Name for the assay containing the low-rank
#' reconstruction of the expression matrix.
#' @param verbose Print messages from \code{\link[Seurat]{SelectIntegrationFeatures}}
#' @param ... Extra parameters passed to \code{\link[batchelor]{fastMNN}}
#'
#' @return A Seurat object merged from the objects in \code{object.list} and a
#' new DimReduc of name \code{reduction.name} (key set to \code{reduction.key})
#' with corrected embeddings matrix as well as the rotation matrix used for the
#' PCA stored in the feature loadings slot. Also returns an expression matrix
#' reconstructed from the low-rank approximation in the
#' \code{reconstructed.assay} assay; all other metadata info
#' \code{\link[batchelor]{fastMNN}} is stored in the \code{tool} slot,
#' accessible with \code{\link[Seurat]{Tool}}
#'
#' @importFrom Seurat DefaultAssay DefaultAssay<- SelectIntegrationFeatures VariableFeatures VariableFeatures<-
#' as.SingleCellExperiment CreateDimReducObject Tool<- LogSeuratCommand
#'
#' @export
#'
#' @seealso \code{\link[batchelor]{fastMNN}} \code{\link[Seurat]{Tool}}
#'
RunFastMNN <- function(
  object.list,
  assay = NULL,
  features = 2000,
  reduction.name = "mnn",
  reduction.key = "mnn_",
  reconstructed.assay = "mnn.reconstructed",
  verbose = TRUE,
  ...
) {
  CheckPackage(package = "batchelor", repository = "bioconductor")
  if (!all(sapply(X = object.list, FUN = inherits, what = "Seurat"))) {
    stop("'object.list' must be a list of Seurat objects",
         call. = FALSE)
  }
  if (length(x = object.list) < 2) {
    stop("'object.list' must contain multiple Seurat objects for integration",
         call. = FALSE)
  }
  assay <- assay %||% DefaultAssay(object = object.list[[1]])
  for (i in 1:length(x = object.list)) {
    DefaultAssay(object = object.list[[i]]) <- assay
  }
  if (is.numeric(x = features)) {
    if (verbose) {
      message(paste("Computing", features, "integration features"))
    }
    features <- SelectIntegrationFeatures(
      object.list = object.list,
      nfeatures = features,
      assay = rep(assay, length(x = object.list))
    )
  }
  objects.sce <- lapply(
    X = object.list,
    FUN = function(x, f) {
      return(as.SingleCellExperiment(x = subset(x = x, features = f)))
    },
    f = features
  )
  integrated <- merge(
    x = object.list[[1]],
    y = object.list[2:length(x = object.list)]
  )
  out <- do.call(
    what = batchelor::fastMNN,
    args = c(
      objects.sce,
      list(...)
    )
  )
  rownames(x = SingleCellExperiment::reducedDim(x = out)) <- colnames(x = integrated)
  colnames(x = SingleCellExperiment::reducedDim(x = out)) <- paste0(reduction.key, 1:ncol(x = SingleCellExperiment::reducedDim(x = out)))
  integrated[[reduction.name]] <- CreateDimReducObject(
    embeddings = SingleCellExperiment::reducedDim(x = out),
    loadings = as.matrix(SingleCellExperiment::rowData(x = out)),
    assay = DefaultAssay(object = integrated),
    key = reduction.key
  )
  # Add reconstructed matrix (gene x cell)
  integrated[[reconstructed.assay]] <- CreateAssayObject(
    data = as(object = SummarizedExperiment::assay(x = out), Class = "sparseMatrix"),
  )
  # Add variable features
  VariableFeatures(object = integrated[[reconstructed.assay]]) <- features
  Tool(object = integrated) <- S4Vectors::metadata(x = out)
  integrated <- LogSeuratCommand(object = integrated)
  return(integrated)
}



================================================
FILE: R/fast_mnn_v5.R
================================================
#' @include internal.R
#'
NULL

#' Run fastMNN in Seurat 5
#'
#' @param object A merged seurat object
#' @param groups A one-column data frame with grouping information
#' @param layers Layers to use
#' @param assay Assay to use, defaults to the default assay of the first object
#' @param features Either a list of features to use when calculating batch
#' correction, or a number (2000 by default) of variable features to select.
#' @param reduction.name Name to store resulting DimReduc object as
#' @param reduction.key Key for resulting DimReduc
#' @param reconstructed.assay Name for the assay containing the low-rank
#' reconstruction of the expression matrix.
#' @param verbose Print messages
#' @param ... Extra parameters passed to \code{\link[batchelor]{fastMNN}}
#'
#' @return A Seurat object merged from the objects in \code{object.list} and a
#' new DimReduc of name \code{reduction.name} (key set to \code{reduction.key})
#' with corrected embeddings matrix as well as the rotation matrix used for the
#' PCA stored in the feature loadings slot. Also returns an expression matrix
#' reconstructed from the low-rank approximation in the
#' \code{reconstructed.assay} assay; all other metadata info
#' \code{\link[batchelor]{fastMNN}} is stored in the \code{tool} slot,
#' accessible with \code{\link[Seurat]{Tool}}
#'
#' @importFrom Seurat DefaultAssay DefaultAssay<- SelectIntegrationFeatures VariableFeatures VariableFeatures<-
#' as.SingleCellExperiment CreateDimReducObject Tool<- LogSeuratCommand
#' @importFrom rlang check_installed
#'
#' @export
#'@note This function requires the
#' \href{https://rdrr.io/github/LTLA/batchelor/}{\pkg{batchelor}} package
#' to be installed
#'
#' @examples
#' \dontrun{
#' # Preprocessing
#' obj <- SeuratData::LoadData("pbmcsca")
#' obj[["RNA"]] <- split(obj[["RNA"]], f = obj$Method)
#' obj <- NormalizeData(obj)
#' obj <- FindVariableFeatures(obj)
#' obj <- ScaleData(obj)
#' obj <- RunPCA(obj)
#'
#' # After preprocessing, we integrate layers:
#' obj <- IntegrateLayers(object = obj, method = FastMNNIntegration,
#'   new.reduction = 'integrated.mnn', verbose = FALSE)
#'
#' # We can also add parameters specific to FastMNN.
#' # Here we set `k` to specify the number of nearest neighbors to use when identifying MNNs:
#' obj <- IntegrateLayers(object = obj, method = FastMNNIntegration,
#'   new.reduction = 'integrated.mnn', k = 15, verbose = FALSE)
#' }
#'
#' @seealso \code{\link[batchelor]{fastMNN}} \code{\link[Seurat]{Tool}}
#'
FastMNNIntegration <- function(
    object,
    assay = NULL,
    orig = NULL,
    groups = NULL,
    layers = NULL,
    scale.layer = NULL,
    features = 2000,
    new.reduction = "integrated.mnn",
    reduction.key = "mnn_",
    reconstructed.assay = "mnn.reconstructed",
    verbose = TRUE,
    ...
) {
  check_installed(
    pkg = "batchelor",
    reason = "for running integration with mnnCorrect"
  )
  object <- CreateSeuratObject(object)
  if (is.numeric(x = features)) {
    if (verbose) {
      message(paste("Computing", features, "integration features"))
    }
    features <- SelectIntegrationFeatures5(object = object, features = features)
  }
  layers <- layers %||% Layers(object, search = 'data')
  if (verbose) {
    message("Converting layers to SingleCellExperiment")
  }
  objects.sce <- lapply(
    X = layers,
    FUN = function(x, f) {
      return(as.SingleCellExperiment(
        x = subset(x = object,
                   features = f,
                   cells = colnames(LayerData(object, layer = x)))
            )
        )
    },
    f = features
  )
  if (verbose) {
    message("Running fastMNN")
  }
  out <- do.call(
    what = batchelor::fastMNN,
    args = c(
      objects.sce,
      list(...)
    )
  )
  colnames(x = SingleCellExperiment::reducedDim(x = out)) <- paste0(reduction.key, 1:ncol(x = SingleCellExperiment::reducedDim(x = out)))
  reduction <- CreateDimReducObject(
    embeddings = SingleCellExperiment::reducedDim(x = out),
    loadings = as.matrix(SingleCellExperiment::rowData(x = out)),
    assay = DefaultAssay(object = object),
    key = reduction.key
  )
  # Add reconstructed matrix (gene x cell)
  reconstructed_assay <- CreateAssayObject(
    data = as(object = SummarizedExperiment::assay(x = out), Class = "sparseMatrix"),
  )
  # Add variable features
  VariableFeatures(object = reconstructed_assay) <- features
  #Tool(object = object) <- S4Vectors::metadata(x = out)
  #object <- LogSeuratCommand(object = object)
  output.list <- list(reduction, reconstructed_assay)
  names(output.list) <- c(new.reduction, reconstructed.assay)
  return(output.list)
}

attr(x = FastMNNIntegration, which = 'Seurat.method') <- 'integration'


================================================
FILE: R/glmpca.R
================================================
#' @include internal.R
#'
NULL

#' Run GLMPCA
#'
#' @param object A Seurat object
#' @param L The number of dimensions to return (defaults to 5)
#' @param assay Assay to use, defaults to the default assay
#' @param features A list of features to use when performing GLM-PCA. If null, defaults to variable features.
#' @param reduction.name Name to store resulting DimReduc object as. Defaults to glmpca
#' @param reduction.key Key for resulting DimReduc. Defaults to GLMPC_
#' @param ... Extra parameters passed to \code{\link[glmpca]{glmpca}}
#'
#' @return A Seurat object containing the output of GLMPCA stored as a DimReduc object.
#' @importFrom Seurat DefaultAssay DefaultAssay<- CreateDimReducObject Tool<- LogSeuratCommand
#'
#' @author Will Townes
#' @references Townes, W., Hicks, SC, Aryee, MJ, Irizarry, RA. (2019). "Feature selection and dimension reduction for single-cell RNA-Seq based on a multinomial model."
#' Genome Biology.
#'
#' @examples
#' \dontrun{
#' pbmc_small
#' pbmc_small <- RunGLMPCA(pbmc_small)
#' DimPlot(pbmc_small, redunction = 'glmpca')
#' }
#'
#' @export
#'
RunGLMPCA <- function(
  object,
  L = 5,
  assay = NULL,
  features = NULL,
  reduction.name = 'glmpca',
  reduction.key = 'GLMPC_',
  verbose = TRUE,
  ...
) {
  CheckPackage(package = 'glmpca', repository = 'CRAN')
  if (!inherits(x = object,what = 'Seurat')) {
    stop("'object' must be a Seurat object", call. = FALSE)
  }
  assay <- assay %||% DefaultAssay(object = object)
  DefaultAssay(object = object) <- assay
  features <- features %||% VariableFeatures(object)
  data <- GetAssayData(object = object, slot = 'counts')
  features <- intersect(x = features, y = rownames(x = data))
  if (length(x = features) == 0) {
    stop("Please specify a subset of features for GLM-PCA")
  }
  data <- data[features, ]
  glmpca_results <- glmpca:::glmpca(Y = data, L = L, ...)
  glmpca_dimnames <- paste0(reduction.key, 1:L)
  factors<-as.matrix(glmpca_results$factors)
  loadings<-as.matrix(glmpca_results$loadings)
  colnames(x = factors) <- glmpca_dimnames
  colnames(x = loadings) <- glmpca_dimnames
  factors_l2_norm <- sqrt(colSums(factors^2))
  #strip S3 class "glmpca" to enable it to pass validObject()
  class(glmpca_results)<-NULL
  #save memory by removing factors and loadings since they are stored separately
  glmpca_results$factors<-glmpca_results$loadings<-NULL
  object[[reduction.name]] <- CreateDimReducObject(
    embeddings = factors,
    key = reduction.key,
    loadings = loadings,
    stdev = factors_l2_norm,
    assay = assay,
    global = TRUE,
    misc = glmpca_results
  )
  object <- LogSeuratCommand(object = object)
  return(object)
}


================================================
FILE: R/internal.R
================================================
#' @importFrom BiocManager install
#' @importFrom remotes install_github
#' @importFrom Seurat IsGlobal Reductions
#'
NULL

#' @docType package
#' @name SeuratWrappers-package
#' @rdname SeuratWrappers-package
#'
"_PACKAGE"

# Set a default value if an object is null
#
# @param lhs An object to set if it's null
# @param rhs The value to provide if x is null
#
# @return rhs if lhs is null, else lhs
#
# @author Hadley Wickham
# @references https://adv-r.hadley.nz/functions.html#missing-arguments
#
`%||%` <- function(lhs, rhs) {
  if (!is.null(x = lhs)) {
    return(lhs)
  } else {
    return(rhs)
  }
}

# Set a default value if an object is NOT null
#
# @param lhs An object to set if it's NOT null
# @param rhs The value to provide if x is NOT null
#
# @return lhs if lhs is null, else rhs
#
# @author Hadley Wickham
# @references https://adv-r.hadley.nz/functions.html#missing-arguments
#
`%iff%` <- function(lhs, rhs) {
  if (!is.null(x = lhs)) {
    return(rhs)
  } else {
    return(lhs)
  }
}

# Get dimensional reduction information associated with an assay
#
# @param object A \code{Seurat} object
# @param assay Name of assay that dimensional reduction objects should be
# associated with
# @param global Include global dimensional reductions
#
# @return A vector of dimensional reduction names
#
# @keywords internal
#
AssociatedDimReducs <- function(
  object,
  assay = DefaultAssay(object = object),
  global = TRUE
) {
  return(Filter(
    f = function(x) {
      check <- DefaultAssay(object = object[[x]]) == assay
      if (global) {
        check <- c(check, IsGlobal(object = object[[x]]))
      }
      return(any(check))
    },
    x = Reductions(object = object)
  ))
}

# 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) {
  assay <- assay %||% DefaultAssay(object = object)
  drs.use <- c('umap', 'tsne', 'pca')
  dim.reducs <- Reductions(object = object)
  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]])])
}

# Check to ensure a package is installed
#
# @param package Name of pacakge to check
# @param repository Repository that package is available on;
# choose from 'bioconductor', 'github', or 'cran'
# @param ... Extra parameters passed to BiocManager::install, remotes::install_github, or install.packages, depending on \code{repository}
#
#' @importFrom utils menu install.packages
#
CheckPackage <- function(package, repository, ...) {
  if (!requireNamespace(package = basename(path = package), quietly = TRUE)) {
    if (interactive()) {
      message("Package ", package, " is not yet installed")
      message("Install now?")
      choice <- menu(choices = c('yes', 'no'))
      if (choice == 1) {
        repository <- match.arg(
          arg = tolower(x = repository),
          choices = c('github', 'bioconductor', 'cran')
        )
        switch(
          EXPR = repository,
          'github' = remotes::install_github(repo = package, ...),
          'bioconductor' = BiocManager::install(pkgs = package, ...),
          'cran' = install.packages(pkgs = package, ...),
          stop("Unknown repository ", repository, call. = FALSE)
        )
        return(invisible(x = NULL))
      }
    }
    stop("Unable to find package ", package, ", please install", call. = FALSE)
  }
}

# Check if a matrix is empty
#
# Takes a matrix and asks if it's empty (either 0x0 or 1x1 with a value of NA)
#
# @param x A matrix
#
# @return Whether or not \code{x} is empty
#
IsMatrixEmpty <- function(x) {
  matrix.dims <- dim(x = x)
  matrix.na <- all(matrix.dims == 1) && all(is.na(x = x))
  return(all(matrix.dims == 0) || matrix.na)
}


================================================
FILE: R/liger.R
================================================
#' @include internal.R
#'
NULL

#' Run optimizeALS on a Seurat object
#'
#' @inheritParams rliger::optimizeALS
#' @inheritParams RunFastMNN
#' @param object A merged Seurat object
#' @param split.by Attribute for splitting, defaults to "orig.ident"
#' @param ... Arguments passed to other methods
#'
#' @return A Seurat object with embeddings and loadings from \code{\link[liger]{optimizeALS}}
#' stored as a DimReduc object with name \code{reduction.name} (key set to \code{reduction.key});
#' per-dataset feature loadings matrices stored in the \code{tool} slot, accessible with
#' \code{\link[Seurat]{Tool}}
#'
# @importFrom rliger optimizeALS
#' @importFrom Seurat DefaultAssay SplitObject GetAssayData VariableFeatures
#' CreateDimReducObject Tool<- LogSeuratCommand
#'
#' @aliases optimizeALS
#' @seealso \code{\link[rliger]{optimizeALS}} \code{\link[Seurat]{Tool}}
#'
#' @export
# @method optimizeALS Seurat
#'
RunOptimizeALS <- function(
  object,
  k,
  assay = NULL,
  split.by = 'orig.ident',
  lambda = 5,
  thresh = 1e-6,
  max.iters = 30,
  reduction.name = 'iNMF_raw',
  reduction.key = 'riNMF_',
  nrep = 1,
  H.init = NULL,
  W.init = NULL,
  V.init = NULL,
  rand.seed = 1,
  print.obj = FALSE,
  ...
) {
  CheckPackage(package = 'rliger', repository = 'cran')
  assay <- assay %||% DefaultAssay(object = object)
  if (IsMatrixEmpty(x = GetAssayData(object = object, slot = 'scale.data'))) {
    stop("Data is unscaled, splease scale before running", call. = FALSE)
  }
  if (is.character(x = split.by) && length(x = split.by) == 1) {
    split.by <- object[[split.by]]
  }
  split.cells <- split(x = colnames(x = object), f = split.by)
  scale.data <- lapply(
    X = split.cells,
    FUN = function(x) {
      return(t(x = GetAssayData(
        object = object,
        slot = 'scale.data',
        assay = assay
      )[, x]))
    }
  )
  # scale.data <- sapply(X = scale.data, FUN = t, simplify = FALSE)
  out <- rliger::optimizeALS(
    object = scale.data,
    k = k,
    lambda = lambda,
    thresh = thresh,
    max.iters = max.iters,
    nrep = nrep,
    H.init = H.init,
    W.init = W.init,
    V.init = V.init,
    rand.seed = rand.seed,
    print.obj = print.obj
  )
  colnames(x = out$W) <- VariableFeatures(object = object)
  object[[reduction.name]] <- CreateDimReducObject(
    embeddings = do.call(what = 'rbind', args = out$H),
    loadings = t(x = out$W),
    assay = assay,
    key = reduction.key
  )
  Tool(object = object) <- sapply(
    X = out$V,
    FUN = function(x) {
      colnames(x = x) <- VariableFeatures(object = object)
      rownames(x = x) <- colnames(x = object[[reduction.name]])
      return(t(x = x))
    },
    simplify = FALSE
  )
  object <- LogSeuratCommand(object = object)
  return(object)
}

#' Generate shared factor neighborhood graph
#'
#' This is a deprecated function. Call 'RunQuantileNorm' instead.
#'
# @inheritParams rliger::SNF
#' @inheritParams RunOptimizeALS
#' @param reduction Name of reduction to use
#'
#' @return A Seurat object with the SNF list stored in the \code{tool} slot,
#' accessible with \code{\link[Seurat]{Tool}}
#'
#' @importFrom Seurat SplitObject Embeddings Tool<- LogSeuratCommand
#'
#' @aliases SNF
#' @seealso \code{\link[rliger]{RunQuantileNorm}} \code{\link[Seurat]{Tool}}
#'
#' @export
# @method SNF Seurat
#'
RunSNF <- function(
  object,
  split.by = 'orig.ident',
  reduction = 'iNMF_raw',
  dims.use = NULL,
  dist.use = 'CR',
  center = FALSE,
  knn_k = 20,
  k2 = 500,
  small.clust.thresh = knn_k,
  ...
) {
  CheckPackage(package = 'rliger', repository = 'cran')
  # cells <- sapply(
  #   X = SplitObject(object = object, split.by = split.by),
  #   FUN = colnames,
  #   simplify = FALSE
  # )
  # dims.use <- dims.use %||% 1:length(x = object[[reduction]])
  # embeddings <- sapply(
  #   X = cells,
  #   FUN = function(x) {
  #     return(Embeddings(object = object[[reduction]])[x, ])
  #   },
  #   simplify = FALSE,
  #   USE.NAMES = TRUE
  # )
  # snf <- liger::SNF(
  #   object = embeddings,
  #   dims.use = dims.use,
  #   dist.use = dist.use,
  #   center = center,
  #   knn_k = knn_k,
  #   k2 = k2,
  #   small.clust.thresh = small.clust.thresh,
  #   ...
  # )
  # Tool(object = object) <- snf
  # object <- LogSeuratCommand(object = object)
  # return(object)
  .Deprecated(
    new = 'RunQuantileNorm',
    msg = paste(
      "This is a deprecated function. Call 'RunQuantileNorm' instead."
    )
  )
}

#' Run quantileAlignSNF on a Seurat object
#'
#' This is a deprecated function. Call 'RunQuantileNorm' instead.
#' 
#' @inheritParams RunSNF
#' @inheritParams RunOptimizeALS
#' @inheritParams rliger::quantileAlignSNF
#' @param recalc.snf Recalculate \code{\link{SNF}}
#' @param ... Arguments passed to other methods, and to
#' \code{\link[seurat.wrappers]{SNF}} if \code{recalc.snf = TRUE} or
#' \code{\link[seurat.wrappers]{SNF}} hasn't been run
#'
#' @return A Seurat object with embeddings from \code{\link[liger]{quantileAlignSNF}}
#' stored as a DimReduc object with name \code{reduction.name} (key set to \code{reduction.key})
#'
# @importFrom rliger quantileAlignSNF
#' @importFrom Seurat Tool SplitObject Embeddings CreateDimReducObject
#' DefaultAssay Tool<- Idents<- LogSeuratCommand
#'
#' @aliases quantileAlignSNF
#' @seealso \code{\link[rliger]{RunQuantileNorm}}
#'
#' @export
# @method quantileAlignSNF Seurat
#'
RunQuantileAlignSNF <- function(
  object,
  split.by = 'orig.ident',
  reduction = 'iNMF_raw',
  reduction.name = 'iNMF',
  reduction.key = 'iNMF_',
  recalc.snf = FALSE,
  ref_dataset = NULL,
  prune.thresh = 0.2,
  min_cells = 2,
  quantiles = 50,
  nstart = 10,
  resolution = 1,
  center = FALSE,
  id.number = NULL,
  print.mod = FALSE,
  print.align.summary = FALSE,
  ...
) {
  # CheckPackage(package = 'rliger', repository = 'cran')
  # if (recalc.snf || is.null(x = Tool(object = object, slot = 'RunSNF'))) {
  #   object <- RunSNF(
  #     object = object,
  #     split.by = split.by,
  #     reduction = reduction,
  #     center = center,
  #     ...
  #   )
  # }
  # embeddings <- sapply(
  #   X = SplitObject(object = object, split.by = split.by),
  #   FUN = function(x) {
  #     return(Embeddings(object = x[[reduction]]))
  #   },
  #   simplify = FALSE,
  #   USE.NAMES = TRUE
  # )
  # if (is.null(x = ref_dataset)) {
  #   num.samples <- vapply(
  #     X = embeddings,
  #     FUN = nrow,
  #     FUN.VALUE = integer(length = 1L)
  #   )
  #   ref_dataset <- names(x = embeddings)[which.max(x = num.samples)]
  # } else if (is.numeric(x = ref_dataset)) {
  #   ref_dataset <- names(x = embeddings)[ref_dataset]
  # }
  # if (is.character(x = ref_dataset) && !ref_dataset %in% names(x = embeddings)) {
  #   stop("Cannot find reference dataset '", ref_dataset, "' in the split", call. = FALSE)
  # }
  # out <- rliger::quantileAlignSNF(
  #   object = embeddings,
  #   snf = Tool(object = object, slot = 'RunSNF'),
  #   cell.names = colnames(x = object),
  #   ref_dataset = ref_dataset,
  #   prune.thresh = prune.thresh,
  #   min_cells = min_cells,
  #   quantiles = quantiles,
  #   nstart = nstart,
  #   resolution = resolution,
  #   center = center,
  #   id.number = id.number,
  #   print.mod = print.mod,
  #   print.align.summary = print.align.summary,
  #   ...
  # )
  # object[[reduction.name]] <- CreateDimReducObject(
  #   embeddings = out$H.norm,
  #   assay = DefaultAssay(object = object[[reduction]]),
  #   key = reduction.key
  # )
  # out <- as.data.frame(x = out[names(x = out) != 'H.norm'])
  # object[[colnames(x = out)]] <- out
  # Idents(object = object) <- 'clusters'
  # object <- LogSeuratCommand(object = object)
  # return(object)
  message(paste(
      "This is a deprecated function. Calling 'RunQuantileNorm' instead.",
      "Note that not all parameters can be passed to 'RunQuantileNorm'.",
      "It's suggested to run 'louvainCluster' subsequently as well."
    ))

  .Deprecated(
    new = 'RunQuantileNorm',
    msg = paste(
      "This is a deprecated function. Calling 'quantile_norm' instead.",
      "Note that not all parameters can be passed to 'quantile_norm'.",
      "It's suggested to run 'louvainCluster' subsequently as well."
    )
  )

  return(RunQuantileNorm(object,
    split.by = split.by,
    reduction = reduction,
    reduction.name = reduction.name,
    reduction.key = reduction.key,
    quantiles = quantiles,
    ref_dataset = NULL,
    min_cells = 20,
    knn_k = 20,
    dims.use = NULL,
    do.center = FALSE,
    max_sample = 1000,
    eps = 0.9,
    refine.knn = TRUE,
    ...
  ))
}

#' Run quantile_norm on a Seurat object
#'
#' @inheritParams RunOptimizeALS
#' @inheritParams rliger::quantile_norm
#' @param ... Arguments passed to other methods
#'
#' @return A Seurat object with embeddings from \code{\link[liger]{quantile_norm}}
#' stored as a DimReduc object with name \code{reduction.name} (key set to \code{reduction.key})
#'
# @importFrom rliger quantile_norm
#' @importFrom Seurat Tool SplitObject Embeddings CreateDimReducObject
#' DefaultAssay Tool<- Idents<- LogSeuratCommand
#'
#' @aliases quantile_norm
#' @seealso \code{\link[rliger]{quantile_norm}}
#'
#' @export
# @method quantile_norm Seurat
#'
RunQuantileNorm <- function(
  object,
  split.by = 'orig.ident',
  reduction = 'iNMF_raw',
  reduction.name = 'iNMF',
  reduction.key = 'iNMF_',
  quantiles = 50,
  ref_dataset = NULL,
  min_cells = 20,
  knn_k = 20,
  dims.use = NULL,
  do.center = FALSE,
  max_sample = 1000,
  eps = 0.9,
  refine.knn = TRUE,
  ...
) {
  CheckPackage(package = 'rliger', repository = 'cran')
  embeddings <- sapply(
    X = SplitObject(object = object, split.by = split.by),
    FUN = function(x) {
      return(Embeddings(object = x[[reduction]]))
    },
    simplify = FALSE,
    USE.NAMES = TRUE
  )
  if (is.null(x = ref_dataset)) {
    num.samples <- vapply(
      X = embeddings,
      FUN = nrow,
      FUN.VALUE = integer(length = 1L)
    )
    ref_dataset <- names(x = embeddings)[which.max(x = num.samples)]
  } else if (is.numeric(x = ref_dataset)) {
    ref_dataset <- names(x = embeddings)[ref_dataset]
  }
  if (is.character(x = ref_dataset) && !ref_dataset %in% names(x = embeddings)) {
    stop("Cannot find reference dataset '", ref_dataset, "' in the split", call. = FALSE)
  }
  out <- rliger::quantile_norm(
    object = embeddings,
    quantiles = quantiles,
    ref_dataset = ref_dataset,
    min_cells = min_cells,
    knn_k = knn_k,
    dims.use = dims.use,
    do.center = do.center,
    max_sample = max_sample,
    eps = eps,
    refine.knn = refine.knn,
    ...
  )
  object[[reduction.name]] <- CreateDimReducObject(
    embeddings = out$H.norm,
    assay = DefaultAssay(object = object[[reduction]]),
    key = reduction.key
  )
  out <- as.data.frame(x = out[names(x = out) != 'H.norm'])
  object[[colnames(x = out)]] <- out
  Idents(object = object) <- 'clusters'
  object <- LogSeuratCommand(object = object)
  return(object)
}


================================================
FILE: R/miqc.R
================================================
#' @include internal.R
#'
NULL

#' Run miQC on a Seurat object
#'
#' @param object Seurat object
#' @param percent.mt (character) Name of the column in the Seurat metadata that
#'    contains the percent of reads attributed to mitochondrial genes.
#'    Defaults to "percent.mt".
#' @param nFeature_RNA (character) Name of the column in the Seurat metadata that
#'    contains the number of reads per cell. Defaults to "nFeature_RNA".
#' @param posterior.cutoff numeric) The posterior probability of a cell being
#'    part of the compromised distribution, a number between 0 and 1. Any cells
#'    below the appointed cutoff will be marked to keep.
#'    Defaults to 0.75.
#' @param model.type (character) What type of model to generate. A linear
#'    mixture model ("linear") is recommended, but currently b-spline ("spline")
#'    and two-degree polynomial ("polynomial") are also supported
#'    Default = "linear".
#' @param backup.option (character) In case flexmix fails to build a 2 cluster
#'    mixture model, what should RunMiQC do: "percent" (set miQC.keep values
#'    according to backup.percent), "percentile" (set miQC.keep values according
#'    to backup.percentile), "pass" (return original Seurat object), or "halt"
#'    (stop RunMiQC). "percent", "percentile", and "pass" are useful when
#'    processing multiple Seurat objects sequentially.
#' @param backup.percentile (numeric) What percentile to use as cutoff in case
#'    flexmix fails to build a 2 cluster mixture model. Will only be used if
#'    backup.option is "percentile".
#' @param backup.percent (numeric) What percent to use as cutoff in case flexmix
#'    fails to build a 2 cluster mixture model. Will only be used if
#'    backup.option is "percent".
#' @param verbose Boolean. TRUE to show progress messages, FALSE to hide progress messages
#' @details (Copied verbatim from miQC) _Function to fit a two-distribution mixture model on a Seurat object and find those cells probabistically determined to be compromised by the mixture model._
#'
#' @return Returns a Seurat object with probabilities and "keep" decisions stored as "miQC.probability" and "miQC.keep" in the object metadata, respectively.
#' @references Hippen et al. (2021) miQC: An adaptive probabilistic framework for quality control of single-cell RNA-sequencing data. bioRxiv doi: 10.1101/2021.03.03.433798
#'
#' @importFrom rlang %||%
#'
#' @export
RunMiQC <- function(
  object,
  percent.mt = "percent.mt",
  nFeature_RNA = "nFeature_RNA",
  posterior.cutoff = 0.75,
  model.type = "linear",
  model.slot = "flexmix_model",
  verbose = TRUE,
  backup.option = "percentile",
  backup.percentile = 0.99,
  backup.percent = 5,
  ...
) {
  SeuratWrappers:::CheckPackage(package = 'flexmix', repository = "CRAN")

  my_data <- Seurat::FetchData(object, vars = c(percent.mt, nFeature_RNA))
  colnames(my_data) <- c("percent.mt", "nFeature_RNA")


  if(!(model.type %in% c("linear", "spline", "polynomial"))){
    stop("model.type must be one of \"linear\", \"spline\", or \"polynomial\"")
  }

  #implementing tryCatch because of internal flexmix error when model fitting
  #fails. see https://github.com/satijalab/seurat-wrappers/issues/108
  my_model <- tryCatch({
    if (model.type == "linear") {
      my_model <- flexmix::flexmix(percent.mt~nFeature_RNA,
                                   data = my_data, k = 2)
    } else if (model.type == "spline") {
      my_model <- flexmix::flexmix(percent.mt~splines::bs(nFeature_RNA),
                                   data = my_data, k = 2)
    } else if (model.type == "polynomial") {
      my_model <- flexmix::flexmix(percent.mt~poly(nFeature_RNA, degree = 2),
                                   data = my_data, k = 2)
    }
  }, error=function(e){
    cat("flexmix fitting error:", conditionMessage(e),"\n")
    my_model <- NULL})

  #
  #set a variable = model_status to denote the status of the model fitting
  #1 = model fit successfully
  #2 = model fit only 1 cluster
  #3 = model fails at flexmix stage
  #

  if(is.null(my_model)){

    model_status <- 3
    model_message <- "flexmix internal failure"
  } else if (ncol(flexmix::parameters(my_model)) == 1){
    model_status <- 2
    model_message <- "flexmix returned only 1 cluster"
  } else if (ncol(flexmix::parameters(my_model)) == 2){
    model_status <- 1
    model_message <- "flexmix model fit successfully"
  } else {
    stop("model_status error, please post issue on GitHub")
  }

  if(model_status %in% c(2,3)){

    if(model_status == 2){
      warning(model_message)
    }
    if(model_status == 3){
      warning(model_message)
    }

    if(backup.option == "halt"){
      stop("Halting.")}
    else if (backup.option == "pass") {
      message("returning object without miQC model or stats")
      return(object)}
    else if (backup.option == "percentile") {
      message("defaulting to backup.percentile for filtering")
      compromised_probability <- 0
      raw_values <- my_data[,percent.mt]
      percentile_cutoff <- quantile(raw_values, probs = backup.percentile)
      cells_to_keep <- ifelse(raw_values <= percentile_cutoff, "keep", "discard")}
    else if (backup.option == "percent"){
      message("defaulting to backup.percent for filtering")
      compromised_probability <- 0
      raw_values <- my_data[,percent.mt]
      cells_to_keep <- ifelse(raw_values <= backup.percent, "keep", "discard")}
    else {
      stop("backup.option must be one of \"percentile\", \"percent\", \"halt\", or \"pass\"")
    }
  } else if (model_status == 1){

    Misc(object, model.slot) <- my_model

    my_model_parameters <- flexmix::parameters(my_model)
    my_model_posterior <- flexmix::posterior(my_model)

    intercept1 <- my_model_parameters[,1][1]
    intercept2 <- my_model_parameters[,2][1]
    if (intercept1 > intercept2) {
      compromised_dist <- 1
    } else {
      compromised_dist <- 2
    }
    compromised_probability <- my_model_posterior[,compromised_dist]
    cells_to_keep <- ifelse(compromised_probability <= posterior.cutoff, "keep", "discard")

  } else {
    stop("model_status error, please post issue on GitHub")
  }

  object <- Seurat::AddMetaData(object = object,
                                metadata = compromised_probability,
                                col.name = "miQC.probability")
  object <- Seurat::AddMetaData(object = object,
                                metadata = cells_to_keep,
                                col.name = "miQC.keep")
  object <- Seurat::LogSeuratCommand(object)

  return(object)
}


#' Run miQC on a Seurat object
#'
#' @param object Seurat object
#' @details _Function to plot the miQC mixture model stored in a Seurat object. `RunMiQC` must be run prior to plotting._
#' @references Hippen et al. (2021) miQC: An adaptive probabilistic framework for quality control of single-cell RNA-sequencing data. bioRxiv doi: 10.1101/2021.03.03.433798
#'
#' @importFrom rlang %||%
#'
#' @export
PlotMiQC <- function(seurat_object,
                     percent.mt = "percent.mt",
                     nFeature_RNA = "nFeature_RNA",
                     model.slot = "flexmix_model",
                     color.by = "miQC.probability") {

  features_to_fetch <- c(percent.mt, nFeature_RNA, "miQC.probability", "miQC.keep", color.by)
  features_to_fetch <- unique(features_to_fetch)
  my_data <- Seurat::FetchData(seurat_object, vars = features_to_fetch)
  colnames(my_data)[1:2] <- c("percent.mt", "nFeature_RNA")
  my_model <- Misc(seurat_object, model.slot)
  my_model_parameters <- cbind(my_data, flexmix::fitted(my_model))

  #<<< code from plotModel in miQC package >>>
  intercept1 <- flexmix::parameters(my_model, component = 1)[1]
  intercept2 <- flexmix::parameters(my_model, component = 2)[1]
  if (intercept1 > intercept2) {
    compromised_dist <- 1
  } else {
    compromised_dist <- 2
  }

  ggplot2::ggplot(my_data, ggplot2::aes(x = nFeature_RNA, y = percent.mt,
                                        colour = !!ggplot2::sym(color.by))) +
    ggplot2::labs(x = "Unique genes found", y = "Percent reads mitochondrial",
                  color = color.by) +
    ggplot2::geom_point() +
    ggplot2::geom_line(data = my_model_parameters, inherit.aes = FALSE,
                       ggplot2::aes(x = nFeature_RNA, y = Comp.1), lwd = 2) +
    ggplot2::geom_line(data = my_model_parameters, inherit.aes = FALSE,
                       ggplot2::aes(x = nFeature_RNA, y = Comp.2), lwd = 2) +
    ggplot2::ylim(c(0, NA))+
    cowplot::theme_cowplot()
}







================================================
FILE: R/monocle3.R
================================================
#' @include internal.R
#' @importFrom Seurat DefaultAssay Idents<-
#' @importFrom methods as slot<- slot
#'
NULL

clusters.key <- 'monocle3_clusters'
partitions.key <- 'monocle3_partitions'

#' Convert objects to Monocle3 \code{cell_data_set} objects
#'
#' @param x An object
#' @param ... Arguments passed to other methods
#'
#' @return A \code{cell_data_set} object
#'
#' @name as.cell_data_set
#' @rdname as.cell_data_set
#'
#' @aliases as.CellDataSet
#'
#' @export
#'
as.cell_data_set <- function(x, ...) {
  CheckPackage(package = 'cole-trapnell-lab/monocle3', repository = 'github')
  UseMethod(generic = 'as.cell_data_set', object = x)
}

#' @inheritParams Seurat::as.SingleCellExperiment
#' @param reductions A vector of dimensional reductions add to the
#' \code{cell_data_set} object; defaults to all dimensional reductions
#' calculated from \code{assay} and all \link[Seurat:IsGlobal]{global}
#' dimensional reductions
#' @param default.reduction Name of dimensional reduction to use for clustering
#' name
#' @param graph Name of graph to be used for clustering results
#' @param group.by Name of cell-level metadata column to use as identites; pass
# \code{NULL} to use the active identites
#'
#' @importFrom Seurat as.SingleCellExperiment GetAssayData Loadings
#' Embeddings Stdev Idents
#'
#' @details The \code{\link[Seurat]{Seurat}} method utilizes
#' \code{\link[Seurat]{as.SingleCellExperiment}} to transfer over expression
#' and cell-level metadata. The following additional information is also
#' transferred over:
#' \itemize{
#'  \item Cell emebeddings are transferred over to the
#'  \code{\link[SingleCellExperiment]{reducedDims}} slot. Dimensional reduction
#'  names are converted to upper-case (eg. \dQuote{umap} to \dQuote{UMAP}) to
#'  match Monocle 3 style
#'  \item Feature loadings are transfered to
#'  \code{cds@reduce_dim_aux$gene_loadings} if present. \strong{NOTE}: only the
#'  feature loadings of the last dimensional reduction are transferred over
#'  \item Standard deviations are added to
#'  \code{cds@reduce_dim_aux$prop_var_expl} if present. \strong{NOTE}: only the
#'  standard deviations of the last dimensional reduction are transferred over
#'  \item Clustering information is transferred over in the following manner: if
#'  cell-level metadata entries \dQuote{monocle3_clusters} and
#'  \dQuote{monocle3_partitions} exist, then these will be set as the clusters
#'  and partitions, with no nearest neighbor graph being added to the object;
#'  otherwise, Seurat's nearest-neighbor graph will be converted to an
#'  \code{\link[igraph]{igraph}} object and added to the \code{cell_data_set}
#'  object along with Seurat's clusters. No partition information is added when
#'  using Seurat's clsuters
#' }
#'
#' @seealso \code{\link[Seurat]{as.SingleCellExperiment}}
#'
#' @rdname as.cell_data_set
#' @method as.cell_data_set Seurat
#' @export
#'
as.cell_data_set.Seurat <- function(
  x,
  assay = DefaultAssay(object = x),
  reductions = AssociatedDimReducs(object = x, assay = assay),
  default.reduction = DefaultDimReduc(object = x, assay = assay),
  graph = paste0(assay, '_snn'),
  group.by = NULL,
  ...
) {
  # Add assay data
  # Cheat and use as.SingleCellExperiment
  cds <- as(
    object = as.SingleCellExperiment(x = x, assay = assay),
    Class = 'cell_data_set'
  )
  # Ensure we have a counts assay
  if (is.null(x = SummarizedExperiment::assays(x = cds)$counts)) {
    SummarizedExperiment::assays(x = cds)$counts <- SummarizedExperiment::assays(x = cds)[[1]]
  }
  # Add Size_factor
  if (!"Size_Factor" %in% colnames(x = SummarizedExperiment::colData(x = cds))) {
    size.factor <- paste0('nCount_', assay)
    if (size.factor %in% colnames(x = x[[]])) {
      SummarizedExperiment::colData(x = cds)$Size_Factor <- x[[size.factor, drop = TRUE]]
    }
  }
  # Add DimReducs: Embeddings become a reduced dim, Loadings go to
  # reduce_dim_aux$gene_loadings, Stdev goes go reduce_dim_aux$prop_var_expl
  # First, reset the ones from as.SingleCellExperiment
  SingleCellExperiment::reducedDims(x = cds)[SingleCellExperiment::reducedDimNames(x = cds)] <- NULL
  reductions <- intersect(
    x = reductions,
    y = AssociatedDimReducs(object = x, assay = assay)
  )
  for (reduc in reductions) {
    SingleCellExperiment::reducedDims(x = cds)[[toupper(x = reduc)]] <- Embeddings(object = x[[reduc]])
    loadings <- Loadings(object = x[[reduc]])
    if (!IsMatrixEmpty(x = loadings)) {
      slot(object = cds, name = 'reduce_dim_aux')[['gene_loadings']] <- loadings
    }
    stdev <- Stdev(object = x[[reduc]])
    if (length(x = stdev)) {
      slot(object = cds, name = 'reduce_dim_aux')[['prop_var_expl']] <- stdev
    }
  }
  # Add clustering information
  # TODO: Figure out if I need to add relations, distMatrix, or clusters/partitions
  if (!is.null(x = group.by)) {
    Idents(object = x) <- group.by
  }
  # if (clusters.key %in% colnames(x = x[[]])) {
  clusters.list <- if (is.null(x = group.by) && all(c(clusters.key, partitions.key) %in% colnames(x = x[[]]))) {
    message("Using existing Monocle 3 cluster membership and partitions")
    list(
      partitions = factor(x = x[[partitions.key, drop = TRUE]]),
      clusters = factor(x = x[[clusters.key, drop = TRUE]])
    )
  } else if (graph %in% names(x = x)) {
    g <- igraph::graph_from_adjacency_matrix(
      adjmatrix = x[[graph]],
      weighted = TRUE
    )
    # TODO: figure out proper partitioning scheme
    # partitions <- igraph::components(graph = g)$membership[colnames(x = x)]
    warning(
      "Monocle 3 trajectories require cluster partitions, which Seurat does not calculate. Please run 'cluster_cells' on your cell_data_set object",
      call. = FALSE,
      immediate. = TRUE
    )
    partitions <- rep_len(x = 1, length.out = ncol(x = x))
    list(
      cluster_result = list(
        g = g,
        relations = NULL,
        distMatrix = 'matrix',
        coord = NULL,
        edge_links = NULL,
        optim_res = list(
          membership = as.integer(x = Idents(object = x)),
          modularity = NA_real_
        )
      ),
      partitions = factor(x = partitions),
      clusters = Idents(object = x)
    )
  } else {
    list()
  }
  if (length(x = clusters.list)) {
    slot(object = cds, name = 'clusters')[[toupper(x = default.reduction)]] <- clusters.list
  }
  # TODO: Add translated results from learn_graph
  return(cds)
}

#' @param loadings Name of dimensional reduction to save loadings to, if present;
#' defaults to first dimensional reduction present (eg.
#' \code{SingleCellExperiment::reducedDimNames(x)[1]}); pass \code{NA} to
#' suppress transfer of loadings
#' @param clusters Name of clustering method to use for setting identity classes
#'
#' @importFrom Seurat as.Seurat Loadings<- as.Graph DefaultAssay<-
#'
#' @details The \code{cell_data_set} method for \code{\link[Seurat]{as.Seurat}}
#' utilizes the \code{\link[Seurat::as.Seurat]{SingleCellExperiment}} method of
#' \code{\link[Seurat]{as.Seurat}} to handle moving over expression data, cell
#' embeddings, and cell-level metadata. The following additional information
#' will also be transfered over:
#' \itemize{
#'  \item Feature loadings from \code{cds@reduce_dim_aux$gene_loadings} will be
#'  added to the dimensional reduction specified by \code{loadings} or the name
#'  of the first dimensional reduction that contains "pca" (case-insensitive) if
#'  \code{loadings} is not set
#'  \item Monocle 3 clustering will be set as the default identity class. In
#'  addition, the Monocle 3 clustering will be added to cell-level metadata as
#'  \dQuote{monocle3_clusters}, if present
#'  \item Monocle 3 partitions will be added to cell-level metadata as
#'  \dQuote{monocle3_partitions}, if present
#'  \item Monocle 3 pseudotime calculations will be added to
#'  \dQuote{monocle3_pseudotime}, if present
#'  \item The nearest-neighbor graph, if present, will be converted to a
#'  \code{\link[Seurat]{Graph}} object, and stored as
#'  \dQuote{\code{assay}_monocle3_graph}
#' }
#'
#' @seealso \code{\link[Seurat]{as.Seurat.SingleCellExperiment}}
#'
#' @rdname as.Seurat.extras
#' @method as.Seurat cell_data_set
#' @export
#'
as.Seurat.cell_data_set <- function(
  x,
  counts = 'counts',
  data = NULL,
  assay = 'RNA',
  project = 'cell_data_set',
  loadings = NULL,
  clusters = NULL,
  ...
) {
  CheckPackage(package = 'cole-trapnell-lab/monocle3', repository = 'github')
  # Cheat and pull most information using as.SingleCellExperiment
  # cell_data_set objects inherit SingleCellExperiment
  object <- suppressWarnings(expr = as.Seurat(
    x = as(object = x, Class = 'SingleCellExperiment'),
    assay = assay,
    counts = counts,
    data = data,
    project = project
  ))
  # Pull feature loadings
  lds.reduc <- ifelse(
    test = is.null(x = loadings),
    yes = grep(
      pattern = 'pca',
      x = SingleCellExperiment::reducedDimNames(x = x),
      ignore.case = TRUE,
      value = TRUE
    ),
    no = loadings
  )
  if (length(x = lds.reduc) && !is.na(x = lds.reduc)) {
    loadings <- slot(object = x, name = 'reduce_dim_aux')[['gene_loadings']]
    if (!is.null(x = loadings)) {
      Loadings(object = object[[lds.reduc]], projected = FALSE) <- loadings
    }
  }
  # Pull cluster information and pseudotime
  if (length(x = slot(object = x, name = 'clusters'))) {
    clusters <- clusters %||% DefaultDimReduc(object = object)
    object[[clusters.key]] <- Idents(object = object) <- monocle3::clusters(
      x = x,
      reduction_method = clusters
    )
    object[[partitions.key]] <- monocle3::partitions(
      x = x,
      reduction_method = clusters
    )
    graph <- slot(object = x, name = 'clusters')[[clusters]]$cluster_result$g[]
    try(
      expr = {
        graph <- as.Graph(x = graph)
        DefaultAssay(object = graph) <- DefaultAssay(object = object)
        object[[paste0(DefaultAssay(object = graph), '_monocle3_graph')]] <- graph
      },
      silent = TRUE
    )
    try(
      expr = object[['monocle3_pseudotime']] <- monocle3::pseudotime(
        x = cds,
        reduction_method = clusters
      ),
      silent = TRUE
    )
  }
  # TODO: Pull trajectory information
  return(object)
}

#' Run \code{link[monocle3]{learn_graph}} on a \code{\link[Seurat]{Seurat}} object
#'
#' @param object A \code{\link[Seurat]{Seurat}} object
#' @param reduction Name of reduction to use for learning the pseudotime graph
#' @param ... Arguments passed to \code{\link[monocle3]{learn_graph}}
#'
#' @return A \code{\link[monocle3]{cell_data_set}} object with the pseudotime graph
#'
#' @importFrom Seurat Reductions
#'
#' @seealso \code{\link[monocle3]{learn_graph}} \code{\link[monocle3]{cell_data_set}}
#'
# @export
#'
LearnGraph <- function(object, reduction = DefaultDimReduc(object = object), ...) {
  CheckPackage(package = 'cole-trapnell-lab/monocle3', repository = 'github')
  if (reduction != 'UMAP') {
    if ('UMAP' %in% Reductions(object = object)) {
      ''
    }
    reduc <- object[[reduction]]
    suppressWarnings(expr = object[['UMAP']] <- reduc)
  }
  cds <- as.cell_data_set(
    x = object,
    assay = DefaultAssay(object = object[['UMAP']]),
    reductions = 'UMAP',
    default.reduction = 'UMAP'
  )
  cds <- monocle3::learn_graph(cds = cds, ...)
  return(cds)
  # if (reduction != 'UMAP') {
  #   object[['UMAP']] <- NULL
  # }
  # return(object)
}


================================================
FILE: R/pacmap.R
================================================
#' Run PaCMAP (Pairwise Controlled Manifold Approximation)
#'
#' Runs PaCMAP, a method for dimensionality reduction for scRNA-seq data.
#' data. Constructs three kinds of pairs of points: neighbor pairs (pair_neighbors),
#' mid-near pair (pair_MN), and further pairs (pair_FP) based on positional relationship
#' in the original space, and optimize a low-dimensional embedding accordingly.
#' Described in Wang, Y., Huang, H., Rudin, C., & Shaposhnik, Y. (2021). "Understanding
#' how dimension reduction tools work: an empirical approach to deciphering t-SNE, UMAP,
#' TriMAP, and PaCMAP for data visualization." Journal of Machine Learning Research,
#' 22(201), 1-73.
#' This implementation is based on the work of Hao Zhang, as found in
#' https://github.com/zhanghao-njmu/SCP/. We made modifications to ensure compatibility
#' across multiple platforms, including Windows and macOS.
#'
#' @param object An object. This can be a Seurat object or a matrix-like object.
#'
#' @author Yiyang Sun, Haiyang Huang, Gaurav Rajesh Parikh
#' @references Wang, Y., Huang, H., Rudin, C., & Shaposhnik, Y. (2021). "Understanding
#' how dimension reduction tools work: an empirical approach to deciphering t-SNE, UMAP,
#' TriMAP, and PaCMAP for data visualization." Journal of Machine Learning Research,
#' 22(201), 1-73.
#'
#' @examples
#' pancreas_sub <- Seurat::FindVariableFeatures(pancreas_sub)
#' pancreas_sub <- RunPaCMAP(object = pancreas_sub, features = Seurat::VariableFeatures(pancreas_sub))
#' DimPlot(pancreas_sub, reduction = "pacmap")
#'
#' @rdname RunPaCMAP
#' @export
RunPaCMAP <- function(object, ...) {
  if (inherits(object, "Seurat")) {
    RunPaCMAP.Seurat(object, ...)
  } else {
    RunPaCMAP.default(object, ...)
  }
}


#' @rdname RunPaCMAP
#' @method RunPaCMAP Seurat
#' @param object An object. This can be a Seurat object or a matrix-like object.
#' @param reduction A character string specifying the reduction to be used as input. Default is "pca".
#' @param dims An integer vector specifying the dimensions to be used. Default is NULL.
#' @param features A character vector specifying the features to be used. Default is NULL.
#' @param assay A character string specifying the assay to be used. Default is NULL.
#' @param slot A character string specifying the slot name to be used. Default is "data".
#' @param reduction.name A character string specifying the name of the reduction to be stored in the Seurat object. Default is "pacmap".
#' @param reduction.key A character string specifying the prefix for the column names of the PaCMAP embeddings. Default is "PaCMAP_".
#'
#' @importFrom Seurat LogSeuratCommand
#' @export
RunPaCMAP.Seurat <- function(object, reduction = "pca", dims = NULL, features = NULL,
                             assay = NULL, layer = "data",
                             n_components = 2, n.neighbors = NULL, MN_ratio = 0.5, FP_ratio = 2,
                             distance_method = "euclidean",
                             lr = 1, num_iters = 250L, apply_pca = TRUE, init = "random",
                             reduction.name = "pacmap", reduction.key = "PaCMAP_",
                             verbose = TRUE, seed.use = 11L, ...) {
  if (is.null(dims) && is.null(features)) {
    stop("Please specify only one of `dims` or `features`.")
  }
  if (!is.null(x = features)) {
    assay <- assay %||% DefaultAssay(object = object)

    data.use <- t(as.matrix(x = GetAssayData(object = object, layer=layer, assay = assay)[features, , drop = FALSE]))
    if (ncol(x = data.use) < n_components) {
      stop(
        "Please provide as many or more features than n_components: ",
        length(x = features),
        " features provided, ",
        n_components,
        " PaCMAP components requested",
        call. = FALSE
      )
    }
  } else if (!is.null(x = dims)) {
    if (!is.null(x = assay) && assay != DefaultAssay(object = object[[reduction]])){
      warning("If both `assay` and `dims` are specified, the value of `assay` will get ignored.")
    }
    data.use <- Embeddings(object[[reduction]])[, dims]
    assay <- DefaultAssay(object = object[[reduction]])
    if (length(x = dims) < n_components) {
      stop(
        "Please provide as many or more dims than n_components: ",
        length(x = dims),
        " dims provided, ",
        n_components,
        " PaCMAP components requested",
        call. = FALSE
      )
    }
  } else {
    stop("Please specify one of dims or features")
  }
  object[[reduction.name]] <- RunPaCMAP(
    object = data.use, assay = assay,
    n_components = n_components, n.neighbors = n.neighbors, MN_ratio = MN_ratio, FP_ratio = FP_ratio,
    distance_method = distance_method,
    lr = lr, num_iters = num_iters, apply_pca = apply_pca, init = init,
    reduction.key = reduction.key, verbose = verbose, seed.use = seed.use
  )
  object <- LogSeuratCommand(object = object)
  return(object)
}


#' @rdname RunPaCMAP
#' @method RunPaCMAP default
#' @importFrom Seurat CreateDimReducObject
#' @importFrom reticulate import
#' @param object An object. This can be a Seurat object or a matrix-like object.
#' @param reduction A character string specifying the reduction to be used as input. Default is "pca".
#' @param dims An integer vector specifying the dimensions to be used. Default is NULL.
#' @param features A character vector specifying the features to be used. Default is NULL.
#' @param assay A character string specifying the assay to be used. Default is NULL.
#' @param layer A character string specifying the layer name to be used. Default is "data".
#' @param n_components An integer specifying the number of PaCMAP components. Default is 2.
#' @param n.neighbors An integer specifying the number of neighbors considered in the k-Nearest Neighbor graph. Default to 10 for dataset whose sample size is smaller than 10000. For large dataset whose sample size (n) is larger than 10000, the default value is: 10 + 15 * (log10(n) - 4).
#' @param MN_ratio A numeric value specifying the ratio of the ratio of the number of mid-near pairs to the number of neighbors. Default is 0.5.
#' @param FP_ratio A numeric value specifying the ratio of the ratio of the number of further pairs to the number of neighbors. Default is 2.
#' @param distance_method A character string specifying the distance metric to be used. Default is "euclidean".
#' @param lr A numeric value specifying the learning rate of the AdaGrad optimizer. Default is 1.
#' @param num_iters An integer specifying the number of iterations for PaCMAP optimization. Default is 450.
#' @param apply_pca A logical value indicating whether pacmap should apply PCA to the data before constructing the k-Nearest Neighbor graph. Using PCA to preprocess the data can largely accelerate the DR process without losing too much accuracy. Notice that this option does not affect the initialization of the optimization process. Default is TRUE.
#' @param init A character string specifying the initialization of the lower dimensional embedding. One of "pca" or "random". Default is "random".
#' @param reduction.name A character string specifying the name of the reduction to be stored in the Seurat object. Default is "pacmap".
#' @param reduction.key A character string specifying the prefix for the column names of the PaCMAP embeddings. Default is "PaCMAP_".
#' @param verbose A logical value indicating whether to print verbose output. Default is TRUE.
#' @param seed.use An integer specifying the random seed to be used. Default is 11.
#' @param ... Additional arguments to be passed to the pacmap.PaCMAP function.
#' @export
RunPaCMAP.default <- function(object, assay = NULL,
                              n_components = 2, n.neighbors = NULL, MN_ratio = 0.5, FP_ratio = 2,
                              distance_method = "euclidean",
                              lr = 1, num_iters = 250L, apply_pca = TRUE, init = "random",
                              reduction.key = "PaCMAP_", verbose = TRUE, seed.use = 11L, ...) {
  if (!is.null(x = seed.use)) {
    set.seed(seed = seed.use)
  }

  if (!py_module_available(module = 'pacmap')) {
    stop("Cannot find PaCMAP, please install through conda (e.g. conda install conda-forge::pacmap).")
  }
  pacmap <- reticulate::import("pacmap")

  operator <- pacmap$PaCMAP(
    n_components = as.integer(n_components), n_neighbors = n.neighbors, MN_ratio = MN_ratio, FP_ratio = FP_ratio,
    distance = distance_method,
    lr = lr, num_iters = num_iters, apply_pca = apply_pca,
    verbose = verbose, random_state = as.integer(seed.use)
  )
  embedding <- operator$fit_transform(object, init = init)

  colnames(x = embedding) <- paste0(reduction.key, seq_len(ncol(x = embedding)))
  rownames(x = embedding) <- rownames(object)

  reduction <- CreateDimReducObject(
    embeddings = embedding,
    key = reduction.key,
    assay = assay,
    global = TRUE
  )
  return(reduction)
}


================================================
FILE: R/presto.R
================================================
#' @include internal.R
#'
NULL

# Runs Wilcoxon Rank Sum using the Presto package
#
# @param data.use Data matrix to test
# @param cells.1 Group 1 cells
# @param cells.2 Group 2 cells
# @param verbose Print a progress bar
# @param ... Extra parameters passed to wilcox.test
#
# @return Returns a p-value ranked matrix of putative differentially expressed
# features
#
#' @importFrom stats wilcox.test
#
PrestoDETest <- function(
  data.use,
  cells.1,
  cells.2,
  verbose = TRUE,
  ...
) {
  data.use <- data.use[, c(cells.1, cells.2), drop = FALSE]
  # NOTE: do not use logfc from presto
  group.info <- factor(
    c(rep(x = "Group1", length = length(x = cells.1)),
      rep(x = "Group2", length = length(x = cells.2))),
    levels = c("Group1", "Group2"))
  names(x = group.info) <- c(cells.1, cells.2)
  data.use <- data.use[, names(x = group.info), drop = FALSE]
  res <- presto::wilcoxauc(X = data.use, y = group.info)
  res <- res[1:(nrow(x = res)/2), c('pval','auc')]
  colnames(x = res)[1] <- 'p_val'
  return(as.data.frame(x = res, row.names = rownames(x = data.use)))
}

#' A Presto-based implementation of FindMarkers that runs Wilcoxon tests for the given identity classes
#'
#' @param ident.1 Identity class to define markers for; pass an object of class
#' \code{phylo} or 'clustertree' to find markers for a node in a cluster tree;
#' passing 'clustertree' requires \code{\link{BuildClusterTree}} to have been run
#' @param ident.2 A second identity class for comparison; if \code{NULL},
#' use all other cells for comparison; if an object of class \code{phylo} or
#' 'clustertree' is passed to \code{ident.1}, must pass a node to find markers for
#' @param reduction Reduction to use in differential expression testing - will test for DE on cell embeddings
#' @param group.by Regroup cells into a different identity class prior to performing differential expression (see example)
#' @param subset.ident Subset a particular identity class prior to regrouping. Only relevant if group.by is set (see example)
#' @param assay Assay to use in differential expression testing
#' @param slot Slot to pull data from; note that if \code{test.use} is "negbinom", "poisson", or "DESeq2",
#' \code{slot} will be set to "counts"
#' @param mean.fxn Function to use for fold change or average difference calculation.
#' If NULL, the appropriate function will be chose according to the slot used
#' @param fc.name Name of the fold change, average difference, or custom function column
#' in the output data.frame. If NULL, the fold change column will be named
#' according to the logarithm base (eg, "avg_log2FC"), or if using the scale.data
#' slot "avg_diff".
#' @param base The base with respect to which logarithms are computed.
#'
#' @importFrom rlang duplicate
#' @importFrom utils assignInNamespace
#' @importFrom Seurat FindMarkers
#'
#' @export
#' @seealso https://github.com/immunogenomics/presto
RunPresto <- function(
  object,
  ident.1 = NULL,
  ident.2 = NULL,
  group.by = NULL,
  subset.ident = NULL,
  assay = NULL,
  slot = 'data',
  reduction = NULL,
  features = NULL,
  logfc.threshold = 0.25,
  test.use = "wilcox",
  min.pct = 0.1,
  min.diff.pct = -Inf,
  verbose = TRUE,
  only.pos = FALSE,
  max.cells.per.ident = Inf,
  random.seed = 1,
  latent.vars = NULL,
  min.cells.feature = 3,
  min.cells.group = 3,
  mean.fxn = NULL,
  fc.name = NULL,
  base = 2,
  ...
) {
  if (test.use != 'wilcox') {
    stop("Differential expression test must be `wilcox`")
  }

  CheckPackage(package = 'immunogenomics/presto', repository = 'github')
  orig.fxn <- rlang::duplicate(x = Seurat:::WilcoxDETest)
  assignInNamespace(
    x = "WilcoxDETest",
    value = PrestoDETest,
    ns = "Seurat")

  tryCatch(
    expr = res <- FindMarkers(
      object = object,
      ident.1 = ident.1,
      ident.2 = ident.2,
      group.by = group.by,
      subset.ident = subset.ident,
      assay = assay,
      slot = slot,
      reduction = reduction,
      features = features,
      logfc.threshold = logfc.threshold,
      test.use = "wilcox",
      min.pct = min.pct,
      min.diff.pct = min.diff.pct,
      verbose = verbose,
      only.pos = only.pos,
      max.cells.per.ident = max.cells.per.ident,
      random.seed = random.seed,
      latent.vars = latent.vars,
      min.cells.feature = min.cells.feature,
      min.cells.group = min.cells.group,
      mean.fxn = mean.fxn,
      fc.name = fc.name,
      base = base,
      ...
    ),
    finally = assignInNamespace(
      x = "WilcoxDETest",
      value = orig.fxn,
      ns = "Seurat")
  )

  return(res)
}

#' A Presto-based implementation of FindAllMarkers that runs Wilcoxon tests for all identity classes
#'
#' Finds markers (Wilcoxon-differentially expressed genes) for each of the identity classes in a dataset
#'
#' @inheritParams RunPresto
#' @param node A node to find markers for and all its children; requires
#' \code{\link{BuildClusterTree}} to have been run previously; replaces \code{FindAllMarkersNode}
#' @param return.thresh Only return markers that have a p-value < return.thresh, or a power > return.thresh (if the test is ROC)
#'
#' @return Matrix containing a ranked list of putative markers, and associated
#' statistics (p-values, logFC, etc.)
#'
#' @importFrom stats setNames
#' @importFrom rlang duplicate
#' @importFrom utils assignInNamespace
#' @importFrom Seurat FindAllMarkers
#'
#' @export
#'
#' @aliases RunPrestoAllNode
#' @seealso https://github.com/immunogenomics/presto
RunPrestoAll <- function(
  object,
  assay = NULL,
  features = NULL,
  logfc.threshold = 0.25,
  test.use = 'wilcox',
  slot = 'data',
  min.pct = 0.1,
  min.diff.pct = -Inf,
  node = NULL,
  verbose = TRUE,
  only.pos = FALSE,
  max.cells.per.ident = Inf,
  random.seed = 1,
  latent.vars = NULL,
  min.cells.feature = 3,
  min.cells.group = 3,
  mean.fxn = NULL,
  fc.name = NULL,
  base = 2,
  return.thresh = 1e-2,
  ...
) {
  if (test.use != 'wilcox') {
    stop("Differential expression test must be `wilcox`")
  }

  CheckPackage(package = 'immunogenomics/presto', repository = 'github')
  orig.fxn <- rlang::duplicate(x = Seurat:::WilcoxDETest)
  assignInNamespace(
    x = "WilcoxDETest",
    value = PrestoDETest,
    ns = "Seurat")

  tryCatch(
    expr = res <- FindAllMarkers(
      object = object,
      assay = assay,
      features = features,
      logfc.threshold = logfc.threshold,
      test.use = "wilcox",
      slot = slot,
      min.pct = min.pct,
      min.diff.pct = min.diff.pct,
      node = node,
      verbose = verbose,
      only.pos = only.pos,
      max.cells.per.ident = max.cells.per.ident,
      random.seed = random.seed,
      latent.vars = latent.vars,
      min.cells.feature = min.cells.feature,
      min.cells.group = min.cells.group,
      mean.fxn = mean.fxn,
      fc.name = fc.name,
      base = base,
      return.thresh = return.thresh,
      ...
    ),
    finally = assignInNamespace(
      x = "WilcoxDETest",
      value = orig.fxn,
      ns = "Seurat")
  )

  return(res)
}


================================================
FILE: R/scVI.R
================================================
#' @include internal.R
#'
NULL

#' scVI Integration
#' @param object A \code{StdAssay} or \code{STDAssay} instance containing
#' merged data
#' @param features Features to integrate
#' @param layers Layers to integrate
#' @param conda_env conda environment to run scVI
#' @param new.reduction Name under which to store resulting DimReduc object
#' @param ndims Dimensionality of the latent space
#' @param nlayers Number of hidden layers used for encoder and decoder NNs
#' @param gene_likelihood Distribution to use for modelling expression 
#' data: {"zinb", "nb", "poisson"}
#' @param max_epochs Number of passes through the dataset taken while
#' training the model
#' @param ... Unused - currently just capturing parameters passed in from
#' \code{Seurat::IntegrateLayers} intended for other integration methods
#'
#' @export
#'
#' @note This function requires the
#' \href{https://docs.scvi-tools.org/en/stable/installation.html}{\pkg{scvi-tools}}
#' package to be installed
#'
#' @examples
#' \dontrun{
#' # Preprocessing
#' obj <- SeuratData::LoadData("pbmcsca")
#' obj[["RNA"]] <- split(obj[["RNA"]], f = obj$Method)
#' obj <- NormalizeData(obj)
#' obj <- FindVariableFeatures(obj)
#' obj <- ScaleData(obj)
#' obj <- RunPCA(obj)
#'
#' # After preprocessing, we integrate layers, specifying a conda environment
#' obj <- IntegrateLayers(
#'   object = obj,
#'   method = scVIIntegration,
#'   new.reduction = "integrated.scvi",
#'   conda_env = "../miniconda3/envs/scvi-env",
#'   verbose = FALSE
#' )
#'
#' # Alternatively, we can integrate SCTransformed data
#' obj <- SCTransform(object = obj)
#' obj <- IntegrateLayers(
#'   object = obj, method = scVIIntegration,
#'   orig.reduction = "pca", new.reduction = "integrated.scvi",
#'   assay = "SCT", conda_env = "../miniconda3/envs/scvi-env", verbose = FALSE
#' )
#' }
#'
#' @seealso \href{https://docs.scvi-tools.org/en/stable/tutorials/notebooks/scvi_in_R.html}{scVI}
#'
#' @return A single-element named list \code{DimReduc} elements containing
#' the integrated data
scVIIntegration <- function(
    object,
    features = NULL,
    layers = "counts",
    conda_env = NULL,
    new.reduction = "integrated.dr",
    ndims = 30,
    nlayers = 2,
    gene_likelihood = "nb",
    max_epochs = NULL,
    ...) {
  
  # import python methods from specified conda env
  reticulate::use_condaenv(conda_env, required = TRUE)
  sc <- reticulate::import("scanpy", convert = FALSE)
  scvi <- reticulate::import("scvi", convert = FALSE)
  anndata <- reticulate::import("anndata", convert = FALSE)
  scipy <- reticulate::import("scipy", convert = FALSE)

  # if `max_epochs` is not set
  if (is.null(max_epochs)) {
    # convert `NULL` to python's `None`
    max_epochs <- reticulate::r_to_py(max_epochs)
  } else {
    # otherwise make sure it's an int
    max_epochs <- as.integer(max_epochs)
  }

  # build a meta.data-style data.frame indicating the batch for each cell
  # scVI expects a single counts matrix so we'll join our layers together
  # it also expects the raw counts matrix
  # TODO: avoid hardcoding this - users can rename their layers arbitrarily
  # so there's no gauruntee that the usual naming conventions will be followed
  if (inherits(object, what = "SCTAssay")) {
      batches <- .FindSCTBatches(object)
  } else {
      batches <- .FindBatches(object, layers = layers)
      object <- JoinLayers(object = object, layers = "counts")
  }
  
  # setup an `AnnData` python instance
  adata <- sc$AnnData(
    X = scipy$sparse$csr_matrix(
      # TODO: avoid hardcoding per comment above
      Matrix::t(LayerData(object, layer = "counts")[features, ])
    ),
    obs = batches,
    var = object[[]][features, ]
  )
  scvi$model$SCVI$setup_anndata(adata, batch_key = "batch")

  # initialize and train the model
  model <- scvi$model$SCVI(
    adata = adata,
    n_latent = as.integer(x = ndims),
    n_layers = as.integer(x = nlayers),
    gene_likelihood = gene_likelihood
  )
  model$train(max_epochs = max_epochs)

  # extract the latent representation of the merged data
  latent <- model$get_latent_representation()
  latent <- as.matrix(latent)
  # pull the cell identifiers back out of the `AnnData` instance
  # in case anything was sorted under the hood
  rownames(latent) <- reticulate::py_to_r(adata$obs$index$values)
  # prepend the latent space dimensions with `new.reduction` to
  # give the features more readable names
  colnames(latent) <- paste0(new.reduction, "_", 1:ncol(latent))

  # build a `DimReduc` instance
  suppressWarnings(
    latent.dr <- CreateDimReducObject(
      embeddings = latent, 
      key = new.reduction
    )
  )
  # to make it easier to add the reduction into a `Seurat` instance
  # we'll wrap it up in a named list
  output.list <- list(latent.dr)
  names(output.list) <- new.reduction

  return(output.list)
}

attr(x = scVIIntegration, which = "Seurat.method") <- "integration"


#' Builds a data.frame with batch identifiers to use when integrating
#' \code{object}. For \code{StdAssays}, batches are split by layer.
#'
#' Internal - essentially the same as \code{Seurat:::CreateIntegrationGroups} 
#' except that it does not take in a `scale.layer` param.
#'
#' @noRd
#'
#' @param object A \code{StdAssay} instance.
#' @param layers Layers in \code{object} to integrate.
#'
#' @return A dataframe indexed on the cell identifiers from \code{object} - 
#' the dataframe contains a single column, "batch", indicating the layer/batch each cell is from
.FindBatches <- function(object, layers) {
  # build a LogMap indicating which layer each cell is from
  layer.masks <- slot(object, name = "cells")[, layers]
  # get a named vector mapping each cell to its respective layer
  layer.map <- labels(
      layer.masks,
      values = Cells(object, layer = layers)
  )
  # wrap the vector up in a data.frame
  batch.df <- as.data.frame(layer.map)
  names(batch.df) <- "batch"
  
  return(batch.df)
}


#' Builds a data.frame with batch identifiers to use when integrating
#' \code{object}. For \code{SCTAssay}s, batches are split using their
#' model identifiers. 
#'
#' Internal - essentially the same as \code{Seurat:::CreateIntegrationGroups} 
#' except that it does not take in a `scale.layer` param.
#'
#' @noRd
#'
#' @param object A \code{SCTAssay} or \code{StdAssays} instance.
#' @param layers Layers in \code{object} to integrate.
#'
#' @return A dataframe indexed on the cell identifiers from \code{object} - 
#' the dataframe contains a single column, "batch", indicating the layer/batch each cell is from
.FindSCTBatches <- function(object) {
  # build an empty data.frame indexed
  # on the cell identifiers from `object`
  batch.df <- SeuratObject::EmptyDF(n = ncol(object))
  row.names(batch.df) <- Cells(object)
  # for each
  for (sct.model in levels(object)) {
      cell.identifiers <- Cells(object, layer = sct.model)
      batch.df[cell.identifiers, "batch"] <- sct.model
  }
  return(batch.df)
}








================================================
FILE: R/tricycle.R
================================================
#' @include internal.R
#'
NULL

#' Run estimate_cycle_position on a Seurat object
#'
#' This function run estimate_cycle_position function on Seurat object. It uses
#' the tricycle internal reference projection matrix.
#'
#' @param object Seurat object
#' @param assay Assay to use, defaults to the default assay
#' @param slot Slot to use. It should be library size adjusted **log-expression** values.
#' Note that it is convention that we rename "logcounts" to "data" when converting SingleCellExperiment to Seurat object.
#' See also \code{\link[Seurat]{as.Seurat}}. Defaults to "data"
#' @param reduction.name Name of the cell cycle projection returned
#' @param reduction.key Key for the cell cycle projection returned
#' @param gname Alternative rownames of \code{object}. If provided, this will be used to map genes within \code{object} with genes in reference.
#' If not provided, the rownames of \code{object} will be used instead. Default: NULL
#' @param gname.type The type of gene names as in \code{gname} or rownames of \code{object}. It can be either 'ENSEMBL' or 'SYMBOL'. Default: 'ENSEMBL'
#' @param species The type of species in \code{object}. It can be either 'mouse' or 'human'. Default: 'mouse'
#' @param AnnotationDb An AnnotationDb objects. If the user provides rownames in the format of Ensembl IDs and project human data,
#'  this object will be used to map Ensembl IDs to gene SYMBOLs. If no AnnotationDb object being given, the function will use \code{\link[org.Hs.eg.db]{org.Hs.eg.db}}.
#' @param center.pc1 The center of PC1 when defining the angle. Default: 0
#' @param center.pc2 The center of PC2 when defining the angle. Default: 0
#'
#' @export
Runtricycle <- function(
  object,
  assay = NULL,
  slot = "data",
  reduction.name = "tricycleEmbedding",
  reduction.key = "tricycleEmbedding_",
  gname = NULL,
  gname.type = c("ENSEMBL", "SYMBOL"),
  species = c("mouse", "human"),
  AnnotationDb = NULL,
  center.pc1 = 0,
  center.pc2 = 0) {
  SeuratWrappers:::CheckPackage(package = 'tricycle', repository = 'bioconductor')
  assay <- assay %||% DefaultAssay(object = object)
  data.m <- GetAssayData(object = object, assay = assay, slot = slot)

  projection.m <- tricycle:::.project_cycle_space(data.m, ref.m = NULL, gname = gname, gname.type = gname.type, species = species, AnnotationDb = AnnotationDb)
  object$tricyclePosition <- tricycle:::.getTheta(projection.m, center.pc1 = center.pc1, center.pc2 = center.pc2)

  object[[reduction.name]] <- CreateDimReducObject(
    embeddings = projection.m,
    key = reduction.key,
    assay = assay
  )
  return(object)

}


================================================
FILE: R/velocity.R
================================================
#' @include internal.R
#'
NULL

#' @inheritParams Seurat::CreateSeuratObject
#' @param default.assay Name or index of matrix to use as default assay;
#' defaults to name of first matrix in list
#' @param slot Name of slot to store matrix in; choose from 'counts' or 'data'
#'
#' @importFrom methods new
#' @importFrom utils txtProgressBar packageVersion setTxtProgressBar
#' @importFrom Seurat as.Seurat CreateAssayObject Key<- CreateSeuratObject
#'
#' @details
#' The \code{list} method for \code{\link[Seurat]{as.Seurat}} takes a named list
#' of matrices (dense or sparse) and creates a single \code{Seurat} object where
#' each matrix is its own assay. The names of the list are taken to be the names
#' of the assays. If not present, assays will be named as "Assay#" where "#" is
#' the index number in the list of matrices. Objects will be constructed as follows:
#' \itemize{
#'   \item By default, all matrices are assumed to be raw counts and will be stored
#'   in the \code{counts} slot. This can be changed to store in the matrix in the
#'   \code{data} slot instead. The \code{slot} parameter is vectorized, so different
#'   matrices can be stored in either \code{counts} or \code{data}
#'   \item For any and all matrices designated as \code{counts}, the \code{min.cells}
#'   and \code{min.features} filtering will be applied. These parameters are vectorized,
#'   so different filterings can be applied to different matrices
#'   \item No extra information (eg. \code{project}) can be provided to
#'   \code{\link[Seurat]{CreateSeuratObject}}
#' }
#'
#' @rdname as.Seurat.extras
#' @export
#' @method as.Seurat list
#'
as.Seurat.list <- function(
  x,
  default.assay = 1,
  slot = 'counts',
  min.cells = 0,
  min.features = 0,
  verbose = TRUE,
  ...
) {
  if (!all(sapply(X = x, FUN = inherits, what = c('matrix', 'dgCMatrix')))) {
    stop("All values must be either a matrix or dgCMatrix", call. = FALSE)
  }
  names(x = x) <- names(x = x) %||% rep_len(x = '', length.out = length(x = x))
  names(x = x)[nchar(x = names(x = x)) == 0] <- paste0('Assay', which(x = nchar(x = names(x = x)) == 0))
  if (is.numeric(x = default.assay)) {
    default.assay <- names(x = x)[default.assay]
  }
  if (!default.assay %in% names(x = x)) {
    stop(
      "Cannot find specified default assay '",
      default.assay,
      "' in the list of matrices",
      call. = FALSE
    )
  }
  slot <- rep_len(x = slot, length.out = length(x = x))
  min.cells <- rep_len(x = min.cells, length.out = length(x = x))
  min.features <- rep_len(x = min.features, length.out = length(x = x))
  if (!all(slot %in% c('counts', 'data'))) {
    stop("'slot' must be either 'counts' or 'data'")
  }
  names(x = slot) <- names(x = min.cells) <- names(x = min.features) <- names(x = x)
  if (verbose) {
    pb <- txtProgressBar(min = 0, max = length(x = x), style = 3, file = stderr())
  }
  if (slot[[default.assay]] == 'data') {
    assays <- list(CreateAssayObject(data = x[[default.assay]]))
    names(x = assays) <- default.assay
    suppressWarnings(expr = Key(object = assays[[default.assay]]) <- tolower(x = default.assay))
    object <- new(
      Class = 'Seurat',
      assays = assays,
      meta.data = data.frame(row.names = colnames(x = assays[[default.assay]])),
      version = packageVersion(pkg = 'Seurat'),
      project.name = 'SeuratProject'
    )
    DefaultAssay(object = object) <- default.assay
  } else {
    object <- CreateSeuratObject(
      counts = x[[default.assay]],
      assay = default.assay,
      min.cells = min.cells[[default.assay]],
      min.features = min.features[[default.assay]]
    )
  }
  if (verbose) {
    setTxtProgressBar(pb = pb, value = 1 + pb$getVal())
  }
  for (i in names(x = x)) {
    if (i == default.assay) {
      next
    }
    if (slot[[i]] == 'data') {
      suppressWarnings(expr = object[[i]] <- CreateAssayObject(data = x[[i]]))
    } else {
      suppressWarnings(
        expr = object[[i]] <- CreateAssayObject(
          counts = x[[i]],
          min.cells = min.cells[[i]],
          min.features = min.features[[i]]
        )
      )
    }
    if (verbose) {
      setTxtProgressBar(pb = pb, value = 1 + pb$getVal())
    }
  }
  if (verbose) {
    close(con = pb)
  }
  return(object)
}

#' Load RNA Velocity data from a loom file
#'
#' This is a wrapper around \code{\link[velocyto.R]{read.loom.matrices}}, but sends
#' messages to \code{stderr} instead of \code{stdout} (or silences messages with
#' \code{verbose = FALSE})
#'
#' @param file Path to loom file
#' @param engine Method to load data data, choose from 'hdf5r' or 'h5'
#' @param verbose Display progress updates
#'
#' @importFrom utils capture.output
#'
#' @export
#'
#' @seealso \code{\link[velocyto.R]{read.loom.matrices}}
#'
ReadVelocity <- function(file, engine = 'hdf5r', verbose = TRUE) {
  CheckPackage(package = 'velocyto-team/velocyto.R', repository = 'github')
  if (verbose) {
    sink(file = stderr(), type = 'output')
    on.exit(expr = sink())
    ldat <- velocyto.R::read.loom.matrices(file = file, engine = engine)
  } else {
    invisible(x = capture.output(ldat <- velocyto.R::read.loom.matrices(
      file = file,
      engine = engine
    )))
  }
  return(ldat)
}

#' Run RNA Velocty
#'
#' @param object A \code{Seurat} object
#' @param spliced Name of spliced assay
#' @param unspliced Name of unspliced assay
#' @param ambiguous Optional name of ambiguous assay
#' @param spliced.average,unspliced.average Required minimum average expression count for the spliced and unspliced expression matrices
#' @param reduction Name of reduction to use
#' @param group.by Factor to group cells by
#' @param cells Vector of cells to use; defaults to all cells
#' (see \code{\link[velocyto.R]{gene.relative.velocity.estimates}:steady.state.cells})
#' @param graph Optional name of nearest neighbor graph to use
#' @param ncores Number of cores to use
#' @param verbose Display progress updates
#' @param ... Extra parameters passed to \code{\link[velocyto.R]{gene.relative.velocity.estimates}}
#'
#' @return ...
#'
#' @importFrom stats as.dist
#' @importFrom Seurat FetchData GetAssayData
#'
#' @export
#'
#' @seealso \code{\link[velocyto.R]{gene.relative.velocity.estimates}} \code{\link[Seurat]{Tool}}
#'
RunVelocity <- function(
  object,
  spliced = 'spliced',
  unspliced = 'unspliced',
  ambiguous = NULL,
  spliced.average = 0.2,
  unspliced.average = 0.05,
  reduction = 'pca',
  group.by = 'ident',
  cells = NULL,
  graph = NULL,
  ncores = 1,
  verbose = TRUE,
  ...
) {
  CheckPackage(package = 'velocyto-team/velocyto.R', repository = 'github')
  # return(invisible(x = NULL))
  # Collect data from Seurat object
  clusters <- FetchData(object = object, vars = group.by)[, , drop = TRUE]
  names(x = clusters) <- colnames(x = object)
  if (!is.factor(x = clusters)) {
    clusters <- as.factor(x = clusters)
  }
  if (verbose) {
    message("Filtering genes in the spliced matrix")
  }
  spliced.matrix <- velocyto.R::filter.genes.by.cluster.expression(
    emat = GetAssayData(object = object, assay = spliced),
    clusters = clusters,
    min.max.cluster.average = spliced.average
  )
  if (verbose) {
    message("Filtering genes in the unspliced matrix")
  }
  unspliced.matrix <- velocyto.R::filter.genes.by.cluster.expression(
    emat = GetAssayData(object = object, assay = unspliced),
    clusters = clusters,
    min.max.cluster.average = unspliced.average
  )
  if (verbose) {
    message("Calculating embedding distance matrix")
  }
  cell.dist <- as.dist(
    m = 1 - velocyto.R::armaCor(
      mat = t(x = Embeddings(object = object, reduction = reduction))
    )
  )
  # Set arguments
  args <- list(...)
  defaults <- as.list(x = formals(fun = velocyto.R::gene.relative.velocity.estimates))
  args <- args[intersect(x = names(x = args), y = names(x = defaults))]
  defaults.use <- setdiff(x = names(x = defaults), y = names(x = args))
  args[defaults.use] <- defaults[defaults.use]
  args$emat <- spliced.matrix
  args$nmat <- unspliced.matrix
  args$smat <- ambiguous %iff% GetAssayData(object = object, assay = ambiguous)
  args$steady.state.cells <- cells %||% colnames(x = object)
  args$cell.dist <- cell.dist
  args$cellKNN <- graph %iff% object[[graph]]
  args$n.cores <- ncores
  args$verbose <- verbose
  # Run velocity
  sink(file = stderr(), type = 'output')
  on.exit(expr = sink())
  cd <- do.call(what = velocyto.R::gene.relative.velocity.estimates, args = args)
  Tool(object = object) <- cd
  return(object)
}

#' RNA Velocity Plot
#'
#' @inheritParams Seurat::DimPlot
#' @param ... Extra parameters passed on to \code{\link[velocyto.R]{show.velocity.on.embedding.cor}}
#'
#' @return Nothing, shows plot
#'
#' @importFrom Seurat Tool Embeddings
#'
# @export
#'
#' @keywords internal
#'
#' @seealso \code{\link[velocyto.R]{show.velocity.on.embedding.cor}}
#'
VeloPlot <- function(
  object,
  reduction = NULL,
  ...
) {
  .NotYetImplemented()
  CheckPackage(package = 'velocyto-team/velocyto.R', repository = 'github')
  velocity <- Tool(object = object, slot = 'RunVelocity')
  if (is.null(x = velocity)) {
    stop("Please run RunVelocity on this Seurat object")
  }
  reduction <- reduction %||% {
    default.reductions <- c("umap", "tsne", "pca")
    object.reductions <- Filter(
      f = function(x) {
        return(inherits(x = object[[x]], what = 'DimReduc'))
      },
      x = names(x = object)
    )
    reduc.use <- min(which(x = default.reductions %in% object.reductions))
    default.reductions[reduc.use]
  }
  embeddings <- Embeddings(object = object, reduction = reduction)
  velocyto.R::show.velocity.on.embedding.cor(
    emb = embeddings,
    vel = velocity,
    ...
  )
  return(invisible(x = NULL))
}


================================================
FILE: README.md
================================================
# SeuratWrappers

SeuratWrappers is a collection of community-provided methods and extensions for [Seurat](https://satijalab.org/seurat/), curated by the Satija Lab at NYGC. These methods comprise functionality not presently found in Seurat, and are able to be updated much more frequently.

Please see our [contribution guide](https://github.com/satijalab/seurat.wrappers/wiki) for assistance and guidelines in developing and adding new methods to SeuratWrappers

Individual method vignettes can be found in the [`docs/`](https://github.com/satijalab/seurat.wrappers/tree/master/docs) directory, we recommend looking at the standard markdown (`*.md`) files when viewing on GitHub

Installation can be accomplished through [remotes](https://cran.r-project.org/package=remotes)

```R
remotes::install_github('satijalab/seurat-wrappers')
```

## Method Listing

| Package | Vignette | Reference | Source |
| ------- | -------- | --------- | ------ |
| Monocle 3 | [Calculating Trajectories with Monocle 3 and Seurat](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/monocle3.html) | Cao et al, Nature 2019 | https://cole-trapnell-lab.github.io/monocle3 |
| scVelo | [Estimating RNA Velocity using Seurat and scVelo](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/scvelo.html) | Bergen et al, bioRxiv 2019 | https://scvelo.readthedocs.io |
| CoGAPS  | [Running CoGAPS on Seurat Objects](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/cogaps.html) | Stein-O’Brien et al, Cell Systems 2019 | https://www.bioconductor.org/packages/release/bioc/html/CoGAPS.html |
| glmpca  | [Running GLM-PCA on a Seurat Object](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/glmpca.html) | Townes et al, Genome Biology 2019 | https://github.com/willtownes/glmpca |
| Conos | [Integration of datasets using Conos](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/conos.html) | Barkas et al, Nature Methods 2019 | https://github.com/hms-dbmi/conos |
| LIGER | [Integrating Seurat objects using LIGER](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/liger.html) | Welch et al, Cell 2019 | https://github.com/MacoskoLab/liger |
| fastMNN | [Running fastMNN on Seurat Objects](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/fast_mnn.html) | Nature Biotechnology 2018 | https://bioconductor.org/packages/release/bioc/html/batchelor.html |
| Harmony | [Integration of datasets using Harmony](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/harmony.html) | Korsunsky et al, bioRxiv 2018 | https://github.com/immunogenomics/harmony |
| ALRA | [Zero-preserving imputation with ALRA](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/alra.html) | Linderman et al, bioRxiv 2018 | https://github.com/KlugerLab/ALRA |
| Velocity | [Estimating RNA Velocity using Seurat](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/velocity.html) | La Manno et al, Nature 2018 | https://velocyto.org |
| schex | [Using schex with Seurat](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/schex.html) | Freytag, R package 2019 | https://github.com/SaskiaFreytag/schex |
| alevin | [Import alevin counts into Seurat](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/alevin.html) | Srivastava et. al., Genome Biology 2019 | https://github.com/k3yavi/alevin-Rtools |
| Nebulosa | [Visualization of gene expression with Nebulosa](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/nebulosa.html) | Jose Alquicira-Hernandez and Joseph E. Powell, _Under Review_ | https://github.com/powellgenomicslab/Nebulosa |
| CIPR | [Using CIPR with human PBMC data](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/cipr.html) | Ekiz et. al., BMC Bioinformatics 2020 | https://github.com/atakanekiz/CIPR-Package |
| miQC | [Running miQC on Seurat objects](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/miQC.html) | Hippen et. al., bioRxiv 2021 | https://github.com/greenelab/miQC | 
| tricycle | [Running estimate_cycle_position from tricycle on Seurat Objects](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/tricycle.html) | Zheng et. al., bioRxiv 2021 | https://www.bioconductor.org/packages/release/bioc/html/tricycle.html | 
| PaCMAP | [Running PaCMAP on Seurat Objects](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/pacmap.html) | Wang et. al, JMLR 2021; Huang et. al, Communications Biology  2022 | https://github.com/YingfanWang/PaCMAP |


================================================
FILE: docs/README.md
================================================
# SeuratWrappers Vignettes

This directory contains individual method vignettes for each method provided by SeuratWrappers. Generally speaking, each vignette will have three files. Each file has the same content, just formatted and rendered differently:
 - `*.Rmd`: these are the source Rmarkdown files used to generate the other files. Viewing them will show only the raw code
 - `*.html`: these are knitted HTML files. Viewing them on GitHub will show only the raw HTML code. To view rendered HTML, checkout our [vignettes](https://satijalab.org/seurat/vignettes.html) page or use the wonderful [GitHub HTML Preview service](https://htmlpreview.github.io/); links to rendered HTMLs are also provided below
 - `*.md`: these are knited Markdown files. Viewing them will show the rendered Markdown content, useful for browsing here on GitHub

## Method Listing

| Package | Vignette | Reference | Source |
| ------- | -------- | --------- | ------ |
| Conos | [Integration of datasets using Conos](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/conos.html) | Barkas et al, Nature Methods 2019 | https://github.com/hms-dbmi/conos |
| LIGER | [Integrating Seurat objects using LIGER](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/liger.html) | Welch et al, Cell 2019 | https://github.com/MacoskoLab/liger |
| fastMNN | [Running fastMNN on Seurat Objects](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/fast_mnn.html) | Nature Biotechnology 2018 | https://bioconductor.org/packages/release/bioc/html/scran.html |
| Harmony | [Integration of datasets using Harmony](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/harmony.html) | Korsunsky et al, bioRxiv 2018 | https://github.com/immunogenomics/harmony |
| ALRA | [Zero-preserving imputation with ALRA](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/alra.html) | Linderman et al, bioRxiv 2018 | https://github.com/KlugerLab/ALRA |
| Velocity | [Estimating RNA Velocity using Seurat](http://htmlpreview.github.io/?https://github.com/satijalab/seurat-wrappers/blob/master/docs/velocity.html) | La Manno et al, Nature 2018 | https://velocyto.org |


================================================
FILE: docs/alevin.Rmd
================================================
---
title: "Import alevin counts & generate Seurat object"
date: 'Compiled: `r format(Sys.Date(), "%B %d, %Y")`'
output: 
  github_document:
    html_preview: true
    toc: true
    toc_depth: 3
    fig_width: 16
  html_document:
    df_print: kable
    theme: united
    fig_height: 5
    fig_width: 16
    out_height: 4
---

This vignette demonstrates the import of alevin quantified counts into Seurat. Commands and parameters are based off of the [alevin tutorial](https://combine-lab.github.io/alevin-tutorial/2018/running-alevin/). If you use alevin in your work, please cite:

> *Alevin efficiently estimates accurate gene abundances from dscRNA-seq data*
>
> Avi Srivastava, Laraib Malik, Tom Smith, Ian Sudbery & Rob Patro
>
> Genome Biology, 2019.
>
> doi: [10.1186/s13059-019-1670-y](https://doi.org/10.1186/s13059-019-1670-y)
>
> GitHub: https://github.com/COMBINE-lab/salmon


```{r setup, include=FALSE}
knitr::opts_chunk$set(
  tidy = TRUE,
  tidy.opts = list(width.cutoff = 95),
  message = FALSE,
  warning = FALSE
)
```

Prerequisites to install: 

* [SeuratWrappers](https://github.com/satijalab/seurat-wrappers)
* [tximport](https://bioconductor.org/packages/tximport)

```{r packages, eval=FALSE}
library(SeuratWrappers)
library(tximport)
```

## {.tabset .tabset-pills}

### Import alevin quantified counts

```{r pbmcsca, eval = FALSE, cache=TRUE}
pbmc <- ReadAlevin("~/alevin_out/alevin/quants_mat.gz")
```


================================================
FILE: docs/alevin.html
================================================
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />
<meta name="viewport" content="width=device-width, initial-scale=1">

<style type="text/css">
@font-face {
font-family: octicons-link;
src: url(data:font/woff;charset=utf-8;base64,d09GRgABAAAAAAZwABAAAAAACFQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABEU0lHAAAGaAAAAAgAAAAIAAAAAUdTVUIAAAZcAAAACgAAAAoAAQAAT1MvMgAAAyQAAABJAAAAYFYEU3RjbWFwAAADcAAAAEUAAACAAJThvmN2dCAAAATkAAAABAAAAAQAAAAAZnBnbQAAA7gAAACyAAABCUM+8IhnYXNwAAAGTAAAABAAAAAQABoAI2dseWYAAAFsAAABPAAAAZwcEq9taGVhZAAAAsgAAAA0AAAANgh4a91oaGVhAAADCAAAABoAAAAkCA8DRGhtdHgAAAL8AAAADAAAAAwGAACfbG9jYQAAAsAAAAAIAAAACABiATBtYXhwAAACqAAAABgAAAAgAA8ASm5hbWUAAAToAAABQgAAAlXu73sOcG9zdAAABiwAAAAeAAAAME3QpOBwcmVwAAAEbAAAAHYAAAB/aFGpk3jaTY6xa8JAGMW/O62BDi0tJLYQincXEypYIiGJjSgHniQ6umTsUEyLm5BV6NDBP8Tpts6F0v+k/0an2i+itHDw3v2+9+DBKTzsJNnWJNTgHEy4BgG3EMI9DCEDOGEXzDADU5hBKMIgNPZqoD3SilVaXZCER3/I7AtxEJLtzzuZfI+VVkprxTlXShWKb3TBecG11rwoNlmmn1P2WYcJczl32etSpKnziC7lQyWe1smVPy/Lt7Kc+0vWY/gAgIIEqAN9we0pwKXreiMasxvabDQMM4riO+qxM2ogwDGOZTXxwxDiycQIcoYFBLj5K3EIaSctAq2kTYiw+ymhce7vwM9jSqO8JyVd5RH9gyTt2+J/yUmYlIR0s04n6+7Vm1ozezUeLEaUjhaDSuXHwVRgvLJn1tQ7xiuVv/ocTRF42mNgZGBgYGbwZOBiAAFGJBIMAAizAFoAAABiAGIAznjaY2BkYGAA4in8zwXi+W2+MjCzMIDApSwvXzC97Z4Ig8N/BxYGZgcgl52BCSQKAA3jCV8CAABfAAAAAAQAAEB42mNgZGBg4f3vACQZQABIMjKgAmYAKEgBXgAAeNpjYGY6wTiBgZWBg2kmUxoDA4MPhGZMYzBi1AHygVLYQUCaawqDA4PChxhmh/8ODDEsvAwHgMKMIDnGL0x7gJQCAwMAJd4MFwAAAHjaY2BgYGaA4DAGRgYQkAHyGMF8NgYrIM3JIAGVYYDT+AEjAwuDFpBmA9KMDEwMCh9i/v8H8sH0/4dQc1iAmAkALaUKLgAAAHjaTY9LDsIgEIbtgqHUPpDi3gPoBVyRTmTddOmqTXThEXqrob2gQ1FjwpDvfwCBdmdXC5AVKFu3e5MfNFJ29KTQT48Ob9/lqYwOGZxeUelN2U2R6+cArgtCJpauW7UQBqnFkUsjAY/kOU1cP+DAgvxwn1chZDwUbd6CFimGXwzwF6tPbFIcjEl+vvmM/byA48e6tWrKArm4ZJlCbdsrxksL1AwWn/yBSJKpYbq8AXaaTb8AAHja28jAwOC00ZrBeQNDQOWO//sdBBgYGRiYWYAEELEwMTE4uzo5Zzo5b2BxdnFOcALxNjA6b2ByTswC8jYwg0VlNuoCTWAMqNzMzsoK1rEhNqByEyerg5PMJlYuVueETKcd/89uBpnpvIEVomeHLoMsAAe1Id4AAAAAAAB42oWQT07CQBTGv0JBhagk7HQzKxca2sJCE1hDt4QF+9JOS0nbaaYDCQfwCJ7Au3AHj+LO13FMmm6cl7785vven0kBjHCBhfpYuNa5Ph1c0e2Xu3jEvWG7UdPDLZ4N92nOm+EBXuAbHmIMSRMs+4aUEd4Nd3CHD8NdvOLTsA2GL8M9PODbcL+hD7C1xoaHeLJSEao0FEW14ckxC+TU8TxvsY6X0eLPmRhry2WVioLpkrbp84LLQPGI7c6sOiUzpWIWS5GzlSgUzzLBSikOPFTOXqly7rqx0Z1Q5BAIoZBSFihQYQOOBEdkCOgXTOHA07HAGjGWiIjaPZNW13/+lm6S9FT7rLHFJ6fQbkATOG1j2OFMucKJJsxIVfQORl+9Jyda6Sl1dUYhSCm1dyClfoeDve4qMYdLEbfqHf3O/AdDumsjAAB42mNgYoAAZQYjBmyAGYQZmdhL8zLdDEydARfoAqIAAAABAAMABwAKABMAB///AA8AAQAAAAAAAAAAAAAAAAABAAAAAA==) format('woff');
}
body {
-webkit-text-size-adjust: 100%;
text-size-adjust: 100%;
color: #333;
font-family: "Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
font-size: 16px;
line-height: 1.6;
word-wrap: break-word;
}
a {
background-color: transparent;
}
a:active,
a:hover {
outline: 0;
}
strong {
font-weight: bold;
}
h1 {
font-size: 2em;
margin: 0.67em 0;
}
img {
border: 0;
}
hr {
box-sizing: content-box;
height: 0;
}
pre {
overflow: auto;
}
code,
kbd,
pre {
font-family: monospace, monospace;
font-size: 1em;
}
input {
color: inherit;
font: inherit;
margin: 0;
}
html input[disabled] {
cursor: default;
}
input {
line-height: normal;
}
input[type="checkbox"] {
box-sizing: border-box;
padding: 0;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
td,
th {
padding: 0;
}
* {
box-sizing: border-box;
}
input {
font: 13px / 1.4 Helvetica, arial, nimbussansl, liberationsans, freesans, clean, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}
a {
color: #4078c0;
text-decoration: none;
}
a:hover,
a:active {
text-decoration: underline;
}
hr {
height: 0;
margin: 15px 0;
overflow: hidden;
background: transparent;
border: 0;
border-bottom: 1px solid #ddd;
}
hr:before {
display: table;
content: "";
}
hr:after {
display: table;
clear: both;
content: "";
}
h1,
h2,
h3,
h4,
h5,
h6 {
margin-top: 15px;
margin-bottom: 15px;
line-height: 1.1;
}
h1 {
font-size: 30px;
}
h2 {
font-size: 21px;
}
h3 {
font-size: 16px;
}
h4 {
font-size: 14px;
}
h5 {
font-size: 12px;
}
h6 {
font-size: 11px;
}
blockquote {
margin: 0;
}
ul,
ol {
padding: 0;
margin-top: 0;
margin-bottom: 0;
}
ol ol,
ul ol {
list-style-type: lower-roman;
}
ul ul ol,
ul ol ol,
ol ul ol,
ol ol ol {
list-style-type: lower-alpha;
}
dd {
margin-left: 0;
}
code {
font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace;
font-size: 12px;
}
pre {
margin-top: 0;
margin-bottom: 0;
font: 12px Consolas, "Liberation Mono", Menlo, Courier, monospace;
}
.select::-ms-expand {
opacity: 0;
}
.octicon {
font: normal normal normal 16px/1 octicons-link;
display: inline-block;
text-decoration: none;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.octicon-link:before {
content: '\f05c';
}
.markdown-body:before {
display: table;
content: "";
}
.markdown-body:after {
display: table;
clear: both;
content: "";
}
.markdown-body>*:first-child {
margin-top: 0 !important;
}
.markdown-body>*:last-child {
margin-bottom: 0 !important;
}
a:not([href]) {
color: inherit;
text-decoration: none;
}
.anchor {
display: inline-block;
padding-right: 2px;
margin-left: -18px;
}
.anchor:focus {
outline: none;
}
h1,
h2,
h3,
h4,
h5,
h6 {
margin-top: 1em;
margin-bottom: 16px;
font-weight: bold;
line-height: 1.4;
}
h1 .octicon-link,
h2 .octicon-link,
h3 .octicon-link,
h4 .octicon-link,
h5 .octicon-link,
h6 .octicon-link {
color: #000;
vertical-align: middle;
visibility: hidden;
}
h1:hover .anchor,
h2:hover .anchor,
h3:hover .anchor,
h4:hover .anchor,
h5:hover .anchor,
h6:hover .anchor {
text-decoration: none;
}
h1:hover .anchor .octicon-link,
h2:hover .anchor .octicon-link,
h3:hover .anchor .octicon-link,
h4:hover .anchor .octicon-link,
h5:hover .anchor .octicon-link,
h6:hover .anchor .octicon-link {
visibility: visible;
}
h1 {
padding-bottom: 0.3em;
font-size: 2.25em;
line-height: 1.2;
border-bottom: 1px solid #eee;
}
h1 .anchor {
line-height: 1;
}
h2 {
padding-bottom: 0.3em;
font-size: 1.75em;
line-height: 1.225;
border-bottom: 1px solid #eee;
}
h2 .anchor {
line-height: 1;
}
h3 {
font-size: 1.5em;
line-height: 1.43;
}
h3 .anchor {
line-height: 1.2;
}
h4 {
font-size: 1.25em;
}
h4 .anchor {
line-height: 1.2;
}
h5 {
font-size: 1em;
}
h5 .anchor {
line-height: 1.1;
}
h6 {
font-size: 1em;
color: #777;
}
h6 .anchor {
line-height: 1.1;
}
p,
blockquote,
ul,
ol,
dl,
table,
pre {
margin-top: 0;
margin-bottom: 16px;
}
hr {
height: 4px;
padding: 0;
margin: 16px 0;
background-color: #e7e7e7;
border: 0 none;
}
ul,
ol {
padding-left: 2em;
}
ul ul,
ul ol,
ol ol,
ol ul {
margin-top: 0;
margin-bottom: 0;
}
li>p {
margin-top: 16px;
}
dl {
padding: 0;
}
dl dt {
padding: 0;
margin-top: 16px;
font-size: 1em;
font-style: italic;
font-weight: bold;
}
dl dd {
padding: 0 16px;
margin-bottom: 16px;
}
blockquote {
padding: 0 15px;
color: #777;
border-left: 4px solid #ddd;
}
blockquote>:first-child {
margin-top: 0;
}
blockquote>:last-child {
margin-bottom: 0;
}
table {
display: block;
width: 100%;
overflow: auto;
word-break: normal;
word-break: keep-all;
}
table th {
font-weight: bold;
}
table th,
table td {
padding: 6px 13px;
border: 1px solid #ddd;
}
table tr {
background-color: #fff;
border-top: 1px solid #ccc;
}
table tr:nth-child(2n) {
background-color: #f8f8f8;
}
img {
max-width: 100%;
box-sizing: content-box;
background-color: #fff;
}
code {
padding: 0;
padding-top: 0.2em;
padding-bottom: 0.2em;
margin: 0;
font-size: 85%;
background-color: rgba(0,0,0,0.04);
border-radius: 3px;
}
code:before,
code:after {
letter-spacing: -0.2em;
content: "\00a0";
}
pre>code {
padding: 0;
margin: 0;
font-size: 100%;
word-break: normal;
white-space: pre;
background: transparent;
border: 0;
}
.highlight {
margin-bottom: 16px;
}
.highlight pre,
pre {
padding: 16px;
overflow: auto;
font-size: 85%;
line-height: 1.45;
background-color: #f7f7f7;
border-radius: 3px;
}
.highlight pre {
margin-bottom: 0;
word-break: normal;
}
pre {
word-wrap: normal;
}
pre code {
display: inline;
max-width: initial;
padding: 0;
margin: 0;
overflow: initial;
line-height: inherit;
word-wrap: normal;
background-color: transparent;
border: 0;
}
pre code:before,
pre code:after {
content: normal;
}
kbd {
display: inline-block;
padding: 3px 5px;
font-size: 11px;
line-height: 10px;
color: #555;
vertical-align: middle;
background-color: #fcfcfc;
border: solid 1px #ccc;
border-bottom-color: #bbb;
border-radius: 3px;
box-shadow: inset 0 -1px 0 #bbb;
}
.pl-c {
color: #969896;
}
.pl-c1,
.pl-s .pl-v {
color: #0086b3;
}
.pl-e,
.pl-en {
color: #795da3;
}
.pl-s .pl-s1,
.pl-smi {
color: #333;
}
.pl-ent {
color: #63a35c;
}
.pl-k {
color: #a71d5d;
}
.pl-pds,
.pl-s,
.pl-s .pl-pse .pl-s1,
.pl-sr,
.pl-sr .pl-cce,
.pl-sr .pl-sra,
.pl-sr .pl-sre {
color: #183691;
}
.pl-v {
color: #ed6a43;
}
.pl-id {
color: #b52a1d;
}
.pl-ii {
background-color: #b52a1d;
color: #f8f8f8;
}
.pl-sr .pl-cce {
color: #63a35c;
font-weight: bold;
}
.pl-ml {
color: #693a17;
}
.pl-mh,
.pl-mh .pl-en,
.pl-ms {
color: #1d3e81;
font-weight: bold;
}
.pl-mq {
color: #008080;
}
.pl-mi {
color: #333;
font-style: italic;
}
.pl-mb {
color: #333;
font-weight: bold;
}
.pl-md {
background-color: #ffecec;
color: #bd2c00;
}
.pl-mi1 {
background-color: #eaffea;
color: #55a532;
}
.pl-mdr {
color: #795da3;
font-weight: bold;
}
.pl-mo {
color: #1d3e81;
}
kbd {
display: inline-block;
padding: 3px 5px;
font: 11px Consolas, "Liberation Mono", Menlo, Courier, monospace;
line-height: 10px;
color: #555;
vertical-align: middle;
background-color: #fcfcfc;
border: solid 1px #ccc;
border-bottom-color: #bbb;
border-radius: 3px;
box-shadow: inset 0 -1px 0 #bbb;
}
.task-list-item {
list-style-type: none;
}
.task-list-item+.task-list-item {
margin-top: 3px;
}
.task-list-item input {
margin: 0 0.35em 0.25em -1.6em;
vertical-align: middle;
}
:checked+.radio-label {
z-index: 1;
position: relative;
border-color: #4078c0;
}
.sourceLine {
display: inline-block;
}
code .kw { color: #000000; }
code .dt { color: #ed6a43; }
code .dv { color: #009999; }
code .bn { color: #009999; }
code .fl { color: #009999; }
code .ch { color: #009999; }
code .st { color: #183691; }
code .co { color: #969896; }
code .ot { color: #0086b3; }
code .al { color: #a61717; }
code .fu { color: #63a35c; }
code .er { color: #a61717; background-color: #e3d2d2; }
code .wa { color: #000000; }
code .cn { color: #008080; }
code .sc { color: #008080; }
code .vs { color: #183691; }
code .ss { color: #183691; }
code .im { color: #000000; }
code .va {color: #008080; }
code .cf { color: #000000; }
code .op { color: #000000; }
code .bu { color: #000000; }
code .ex { color: #000000; }
code .pp { color: #999999; }
code .at { color: #008080; }
code .do { color: #969896; }
code .an { color: #008080; }
code .cv { color: #008080; }
code .in { color: #008080; }
</style>
<style>
body {
  box-sizing: border-box;
  min-width: 200px;
  max-width: 980px;
  margin: 0 auto;
  padding: 45px;
  padding-top: 0px;
}
</style>

</head>

<body>

<h1 id="import-alevin-counts-&amp;-generate-seurat-object">Import alevin counts &amp; generate Seurat object</h1>
<p>Compiled: May 18, 2020</p>
<p>This vignette demonstrates the import of alevin quantified counts into Seurat. Commands and parameters are based off of the <a href="https://combine-lab.github.io/alevin-tutorial/2018/running-alevin/">alevin tutorial</a>. If you use alevin in your work, please cite:</p>
<blockquote>
<p><em>Alevin efficiently estimates accurate gene abundances from dscRNA-seq data</em></p>
<p>Avi Srivastava, Laraib Malik, Tom Smith, Ian Sudbery &amp; Rob Patro</p>
<p>Genome Biology, 2019.</p>
<p>doi: <a href="https://doi.org/10.1186/s13059-019-1670-y">10.1186/s13059-019-1670-y</a></p>
<p>GitHub: <a href="https://github.com/COMBINE-lab/salmon">https://github.com/COMBINE-lab/salmon</a></p>
</blockquote>
<p>Prerequisites to install:</p>
<ul>
<li><a href="https://github.com/satijalab/seurat-wrappers">SeuratWrappers</a></li>
<li><a href="https://bioconductor.org/packages/tximport">tximport</a></li>
</ul>
<!-- end list -->

<div class="sourceCode" id="cb1"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb1-1" data-line-number="1"><span class="kw">library</span>(SeuratWrappers)</a>
<a class="sourceLine" id="cb1-2" data-line-number="2"><span class="kw">library</span>(tximport)</a></code></pre></div>
<h2></h2>
<h3 id="import-alevin-quantified-counts">Import alevin quantified counts</h3>
<div class="sourceCode" id="cb2"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb2-1" data-line-number="1">pbmc &lt;-<span class="st"> </span><span class="kw">ReadAlevin</span>(<span class="st">&quot;~/alevin_out/alevin/quants_mat.gz&quot;</span>)</a></code></pre></div>

</body>
</html>


================================================
FILE: docs/alevin.md
================================================
Import alevin counts & generate Seurat object
================
Compiled: May 18, 2020

This vignette demonstrates the import of alevin quantified counts into
Seurat. Commands and parameters are based off of the [alevin
tutorial](https://combine-lab.github.io/alevin-tutorial/2018/running-alevin/).
If you use alevin in your work, please cite:

> *Alevin efficiently estimates accurate gene abundances from dscRNA-seq
> data*
> 
> Avi Srivastava, Laraib Malik, Tom Smith, Ian Sudbery & Rob Patro
> 
> Genome Biology, 2019.
> 
> doi:
> [10.1186/s13059-019-1670-y](https://doi.org/10.1186/s13059-019-1670-y)
> 
> GitHub: <https://github.com/COMBINE-lab/salmon>

Prerequisites to install:

  - [SeuratWrappers](https://github.com/satijalab/seurat-wrappers)
  - [tximport](https://bioconductor.org/packages/tximport)

<!-- end list -->

``` r
library(SeuratWrappers)
library(tximport)
```

## 

### Import alevin quantified counts

``` r
pbmc <- ReadAlevin("~/alevin_out/alevin/quants_mat.gz")
```


================================================
FILE: docs/alra.Rmd
==
Download .txt
gitextract_4pdtb5c6/

├── .Rbuildignore
├── .github/
│   ├── no-response.yml
│   └── workflows/
│       └── test-vignettes.yml
├── .gitignore
├── DESCRIPTION
├── LICENSE
├── NAMESPACE
├── R/
│   ├── alevin.R
│   ├── alra.R
│   ├── banksy.R
│   ├── cellbrowser.R
│   ├── cogaps.R
│   ├── conos.R
│   ├── fast_mnn.R
│   ├── fast_mnn_v5.R
│   ├── glmpca.R
│   ├── internal.R
│   ├── liger.R
│   ├── miqc.R
│   ├── monocle3.R
│   ├── pacmap.R
│   ├── presto.R
│   ├── scVI.R
│   ├── tricycle.R
│   └── velocity.R
├── README.md
├── docs/
│   ├── README.md
│   ├── alevin.Rmd
│   ├── alevin.html
│   ├── alevin.md
│   ├── alra.Rmd
│   ├── alra.html
│   ├── alra.md
│   ├── banksy.Rmd
│   ├── banksy.md
│   ├── cellbrowser.Rmd
│   ├── cellbrowser.html
│   ├── cellbrowser.md
│   ├── cipr.Rmd
│   ├── cipr.html
│   ├── cipr.md
│   ├── cogaps.html
│   ├── cogaps.md
│   ├── cogaps.rmd
│   ├── conos.Rmd
│   ├── conos.html
│   ├── conos.md
│   ├── fast_mnn.Rmd
│   ├── fast_mnn.html
│   ├── fast_mnn.md
│   ├── glmpca.Rmd
│   ├── glmpca.html
│   ├── glmpca.md
│   ├── harmony.Rmd
│   ├── harmony.html
│   ├── harmony.md
│   ├── liger.Rmd
│   ├── liger.html
│   ├── liger.md
│   ├── miQC.Rmd
│   ├── miQC.html
│   ├── miQC.md
│   ├── monocle3.Rmd
│   ├── monocle3.html
│   ├── monocle3.md
│   ├── nebulosa.Rmd
│   ├── nebulosa.html
│   ├── nebulosa.md
│   ├── pacmap.Rmd
│   ├── pacmap.html
│   ├── pacmap.md
│   ├── presto.html
│   ├── presto.md
│   ├── presto.rmd
│   ├── schex.Rmd
│   ├── schex.html
│   ├── schex.md
│   ├── scvelo.Rmd
│   ├── scvelo.html
│   ├── scvelo.md
│   ├── tricycle.Rmd
│   ├── tricycle.html
│   ├── tricycle.md
│   ├── velocity.Rmd
│   ├── velocity.html
│   └── velocity.md
├── man/
│   ├── ALRAChooseKPlot.Rd
│   ├── CellBrowser.Rd
│   ├── FastMNNIntegration.Rd
│   ├── LearnGraph.Rd
│   ├── PlotMiQC.Rd
│   ├── ReadAlevin.Rd
│   ├── ReadVelocity.Rd
│   ├── RunALRA.Rd
│   ├── RunBanksy.Rd
│   ├── RunCoGAPS.Rd
│   ├── RunFastMNN.Rd
│   ├── RunGLMPCA.Rd
│   ├── RunMiQC.Rd
│   ├── RunOptimizeALS.Rd
│   ├── RunPaCMAP.Rd
│   ├── RunPresto.Rd
│   ├── RunPrestoAll.Rd
│   ├── RunQuantileAlignSNF.Rd
│   ├── RunQuantileNorm.Rd
│   ├── RunSNF.Rd
│   ├── RunVelocity.Rd
│   ├── Runtricycle.Rd
│   ├── SeuratWrappers-package.Rd
│   ├── StopCellbrowser.Rd
│   ├── VeloPlot.Rd
│   ├── as.Seurat.extras.Rd
│   ├── as.cell_data_set.Rd
│   ├── findMatrix.Rd
│   ├── scVIIntegration.Rd
│   └── writeSparseTsvChunks.Rd
├── seurat-wrappers.Rproj
└── test-vignettes.sh
Copy disabled (too large) Download .json
Condensed preview — 118 files, each showing path, character count, and a content snippet. Download the .json file for the full structured content (43,166K chars).
[
  {
    "path": ".Rbuildignore",
    "chars": 35,
    "preview": "^.*\\.Rproj$\n^\\.Rproj\\.user$\n^docs$\n"
  },
  {
    "path": ".github/no-response.yml",
    "chars": 705,
    "preview": "# Configuration for probot-no-response - https://github.com/probot/no-response\n\n# Number of days of inactivity before an"
  },
  {
    "path": ".github/workflows/test-vignettes.yml",
    "chars": 754,
    "preview": "on: [push, pull_request]\n\njobs:\n  test-vignettes:\n    name: Test any changes to vignettes\n    runs-on: ubuntu-latest\n   "
  },
  {
    "path": ".gitignore",
    "chars": 77,
    "preview": ".Rproj.user\n.Rhistory\n.RData\n.Ruserdata\n*_cache\n*.h5Seurat\n*.h5seurat\n*.h5ad\n"
  },
  {
    "path": "DESCRIPTION",
    "chars": 2836,
    "preview": "Package: SeuratWrappers\nTitle: Community-Provided Methods and Extensions for the Seurat Object\nVersion: 0.4.0\nDate: 2024"
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "NAMESPACE",
    "chars": 3042,
    "preview": "# Generated by roxygen2: do not edit by hand\n\nS3method(RunALRA,Seurat)\nS3method(RunALRA,default)\nS3method(RunPaCMAP,Seur"
  },
  {
    "path": "R/alevin.R",
    "chars": 2521,
    "preview": "#' @include internal.R\n#'\nNULL\n\n#' Load alevin quantification data\n#'\n#' A wrapper around tximport to create a \\code{Seu"
  },
  {
    "path": "R/alra.R",
    "chars": 12562,
    "preview": "#' Run Adaptively-thresholded Low Rank Approximation (ALRA)\n#'\n#' Runs ALRA, a method for imputation of dropped out valu"
  },
  {
    "path": "R/banksy.R",
    "chars": 8752,
    "preview": "\n#' @include internal.R\n#'\nNULL\n\n#' Run Banksy on a Seurat Object\n#'\n#' @param object A Seurat object\n#' @param lambda ("
  },
  {
    "path": "R/cellbrowser.R",
    "chars": 18268,
    "preview": "# Build a UCSC cell browser website from a \\code{Seurat} object\n#\nNULL\n#require(reticulate)\n#require(Matrix)\n#require(R."
  },
  {
    "path": "R/cogaps.R",
    "chars": 2492,
    "preview": "#' @include internal.R\n#'\nNULL\n\n#' Run CoGAPs on a Seurat object\n#'\n#' @param object Seurat object\n#' @param assay Assay"
  },
  {
    "path": "R/conos.R",
    "chars": 4414,
    "preview": "#' Extra conversions to Seurat objects\n#'\n#' @inheritParams Seurat::as.Seurat\n#'\n#' @rdname as.Seurat.extras\n#' @name as"
  },
  {
    "path": "R/fast_mnn.R",
    "chars": 3869,
    "preview": "#' @include internal.R\n#'\nNULL\n\n#' Run fastMNN\n#'\n#' @param object.list A list of Seurat objects\n#' @param assay Assay t"
  },
  {
    "path": "R/fast_mnn_v5.R",
    "chars": 4687,
    "preview": "#' @include internal.R\n#'\nNULL\n\n#' Run fastMNN in Seurat 5\n#'\n#' @param object A merged seurat object\n#' @param groups A"
  },
  {
    "path": "R/glmpca.R",
    "chars": 2664,
    "preview": "#' @include internal.R\n#'\nNULL\n\n#' Run GLMPCA\n#'\n#' @param object A Seurat object\n#' @param L The number of dimensions t"
  },
  {
    "path": "R/internal.R",
    "chars": 4866,
    "preview": "#' @importFrom BiocManager install\n#' @importFrom remotes install_github\n#' @importFrom Seurat IsGlobal Reductions\n#'\nNU"
  },
  {
    "path": "R/liger.R",
    "chars": 10929,
    "preview": "#' @include internal.R\n#'\nNULL\n\n#' Run optimizeALS on a Seurat object\n#'\n#' @inheritParams rliger::optimizeALS\n#' @inher"
  },
  {
    "path": "R/miqc.R",
    "chars": 8521,
    "preview": "#' @include internal.R\n#'\nNULL\n\n#' Run miQC on a Seurat object\n#'\n#' @param object Seurat object\n#' @param percent.mt (c"
  },
  {
    "path": "R/monocle3.R",
    "chars": 11379,
    "preview": "#' @include internal.R\n#' @importFrom Seurat DefaultAssay Idents<-\n#' @importFrom methods as slot<- slot\n#'\nNULL\n\ncluste"
  },
  {
    "path": "R/pacmap.R",
    "chars": 8896,
    "preview": "#' Run PaCMAP (Pairwise Controlled Manifold Approximation)\n#'\n#' Runs PaCMAP, a method for dimensionality reduction for "
  },
  {
    "path": "R/presto.R",
    "chars": 7012,
    "preview": "#' @include internal.R\n#'\nNULL\n\n# Runs Wilcoxon Rank Sum using the Presto package\n#\n# @param data.use Data matrix to tes"
  },
  {
    "path": "R/scVI.R",
    "chars": 6942,
    "preview": "#' @include internal.R\n#'\nNULL\n\n#' scVI Integration\n#' @param object A \\code{StdAssay} or \\code{STDAssay} instance conta"
  },
  {
    "path": "R/tricycle.R",
    "chars": 2608,
    "preview": "#' @include internal.R\n#'\nNULL\n\n#' Run estimate_cycle_position on a Seurat object\n#'\n#' This function run estimate_cycle"
  },
  {
    "path": "R/velocity.R",
    "chars": 9711,
    "preview": "#' @include internal.R\n#'\nNULL\n\n#' @inheritParams Seurat::CreateSeuratObject\n#' @param default.assay Name or index of ma"
  },
  {
    "path": "README.md",
    "chars": 5022,
    "preview": "# SeuratWrappers\n\nSeuratWrappers is a collection of community-provided methods and extensions for [Seurat](https://satij"
  },
  {
    "path": "docs/README.md",
    "chars": 2316,
    "preview": "# SeuratWrappers Vignettes\n\nThis directory contains individual method vignettes for each method provided by SeuratWrappe"
  },
  {
    "path": "docs/alevin.Rmd",
    "chars": 1431,
    "preview": "---\ntitle: \"Import alevin counts & generate Seurat object\"\ndate: 'Compiled: `r format(Sys.Date(), \"%B %d, %Y\")`'\noutput:"
  },
  {
    "path": "docs/alevin.html",
    "chars": 12897,
    "preview": "<!DOCTYPE html>\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n<head>\n\n<meta charset=\"utf-8\">\n<meta http-equiv=\"Content-T"
  },
  {
    "path": "docs/alevin.md",
    "chars": 993,
    "preview": "Import alevin counts & generate Seurat object\n================\nCompiled: May 18, 2020\n\nThis vignette demonstrates the im"
  },
  {
    "path": "docs/alra.Rmd",
    "chars": 1982,
    "preview": "---\ntitle: \"Zero-preserving imputation with ALRA\"\ndate: 'Compiled: `r format(Sys.Date(), \"%B %d, %Y\")`'\noutput: \n  githu"
  },
  {
    "path": "docs/alra.html",
    "chars": 1719824,
    "preview": "<!DOCTYPE html>\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n<head>\n\n<meta charset=\"utf-8\" />\n<meta http-equiv=\"Content"
  },
  {
    "path": "docs/alra.md",
    "chars": 1613,
    "preview": "Zero-preserving imputation with ALRA\n================\nCompiled: August 16, 2019\n\nThis vigettte demonstrates how to run A"
  },
  {
    "path": "docs/banksy.Rmd",
    "chars": 16702,
    "preview": "---\ntitle: \"Running BANKSY with Seurat\"\ndate: 'Compiled: `r format(Sys.Date(), \"%B %d, %Y\")`'\noutput:\n  github_document:"
  },
  {
    "path": "docs/banksy.md",
    "chars": 28616,
    "preview": "Running BANKSY with Seurat\n================\nCompiled: April 04, 2024\n\n- [Introduction](#introduction)\n- [Overview](#over"
  },
  {
    "path": "docs/cellbrowser.Rmd",
    "chars": 1458,
    "preview": "---\ntitle: \"Data Exploration with the UCSC Cell Browser\"\ndate: 'Compiled: `r format(Sys.Date(), \"%B %d, %Y\")`'\noutput: \n"
  },
  {
    "path": "docs/cellbrowser.html",
    "chars": 932685,
    "preview": "<!DOCTYPE html>\n\n<html>\n\n<head>\n\n<meta charset=\"utf-8\" />\n<meta name=\"generator\" content=\"pandoc\" />\n<meta http-equiv=\"X"
  },
  {
    "path": "docs/cellbrowser.md",
    "chars": 1083,
    "preview": "Data Exploration with the UCSC Cell Browser\n================\nCompiled: August 31, 2020\n\nThis vignette demonstrates how t"
  },
  {
    "path": "docs/cipr.Rmd",
    "chars": 12241,
    "preview": "---\ntitle: \"Using CIPR with human PBMC data\"\ndate: \"`r format(Sys.time(), '%d %B, %Y')`\"\nauthor: \"Atakan Ekiz\"\noutput: \n"
  },
  {
    "path": "docs/cipr.md",
    "chars": 20627,
    "preview": "Using CIPR with human PBMC data\n================\nAtakan Ekiz\n19 May, 2021\n\nThis vignette demonstrates how to run CIPR on"
  },
  {
    "path": "docs/cogaps.html",
    "chars": 1119700,
    "preview": "<!DOCTYPE html>\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n<head>\n\n<meta charset=\"utf-8\">\n<meta http-equiv=\"Content-T"
  },
  {
    "path": "docs/cogaps.md",
    "chars": 8196,
    "preview": "Running CoGAPS on Seurat Objects\n================\nCompiled: April 20, 2020\n\n-   [Running CoGAPS with Seurat Data Using C"
  },
  {
    "path": "docs/cogaps.rmd",
    "chars": 8335,
    "preview": "---\ntitle: \"Running CoGAPS on Seurat Objects\"\ndate: 'Compiled: `r format(Sys.Date(), \"%B %d, %Y\")`'\noutput: \n  html_docu"
  },
  {
    "path": "docs/conos.Rmd",
    "chars": 3897,
    "preview": "---\ntitle: \"Integration of datasets using Conos\"\ndate: 'Compiled: `r format(Sys.Date(), \"%B %d, %Y\")`'\noutput: \n  github"
  },
  {
    "path": "docs/conos.html",
    "chars": 2480330,
    "preview": "<!DOCTYPE html>\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n<head>\n\n<meta charset=\"utf-8\" />\n<meta http-equiv=\"Content"
  },
  {
    "path": "docs/conos.md",
    "chars": 3817,
    "preview": "Integration of datasets using Conos\n================\nCompiled: July 15, 2019\n\n-   [](#section)\n    -   [Systematic compa"
  },
  {
    "path": "docs/fast_mnn.Rmd",
    "chars": 3174,
    "preview": "---\ntitle: \"Running fastMNN on Seurat Objects\"\ndate: 'Compiled: `r format(Sys.Date(), \"%B %d, %Y\")`'\noutput: \n  github_d"
  },
  {
    "path": "docs/fast_mnn.html",
    "chars": 2172141,
    "preview": "<!DOCTYPE html>\n\n<html>\n\n<head>\n\n<meta charset=\"utf-8\" />\n<meta name=\"generator\" content=\"pandoc\" />\n<meta http-equiv=\"X"
  },
  {
    "path": "docs/fast_mnn.md",
    "chars": 3176,
    "preview": "Running fastMNN on Seurat Objects\n================\nCompiled: June 23, 2021\n\n  - [](#section)\n      - [Systematic compara"
  },
  {
    "path": "docs/glmpca.Rmd",
    "chars": 2577,
    "preview": "---\ntitle: \"Running GLM-PCA on a Seurat Object\"\ndate: 'Compiled: `r format(Sys.Date(), \"%B %d, %Y\")`'\noutput: \n  github_"
  },
  {
    "path": "docs/glmpca.html",
    "chars": 917901,
    "preview": "<!DOCTYPE html>\n\n<html>\n\n<head>\n\n<meta charset=\"utf-8\" />\n<meta name=\"generator\" content=\"pandoc\" />\n<meta http-equiv=\"X"
  },
  {
    "path": "docs/glmpca.md",
    "chars": 3042,
    "preview": "Running GLM-PCA on a Seurat Object\n================\nCompiled: July 15, 2020\n\nThis vignette demonstrates how to run GLM-P"
  },
  {
    "path": "docs/harmony.Rmd",
    "chars": 3173,
    "preview": "---\ntitle: \"Integration of datasets using Harmony\"\ndate: 'Compiled: `r format(Sys.Date(), \"%B %d, %Y\")`'\noutput:\n  githu"
  },
  {
    "path": "docs/harmony.html",
    "chars": 2239965,
    "preview": "<!DOCTYPE html>\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n<head>\n\n<meta charset=\"utf-8\" />\n<meta http-equiv=\"Content"
  },
  {
    "path": "docs/harmony.md",
    "chars": 3118,
    "preview": "Integration of datasets using Harmony\n================\nCompiled: July 15, 2019\n\n-   [](#section)\n    -   [Systematic com"
  },
  {
    "path": "docs/liger.Rmd",
    "chars": 5110,
    "preview": "---\ntitle: \"Integrating Seurat objects using LIGER\"\ndate: 'Compiled: `r format(Sys.Date(), \"%B %d, %Y\")`'\noutput: \n  git"
  },
  {
    "path": "docs/liger.html",
    "chars": 4641836,
    "preview": "<!DOCTYPE html>\n\n<html>\n\n<head>\n\n<meta charset=\"utf-8\" />\n<meta name=\"generator\" content=\"pandoc\" />\n<meta http-equiv=\"X"
  },
  {
    "path": "docs/liger.md",
    "chars": 5024,
    "preview": "Integrating Seurat objects using LIGER\n================\nCompiled: May 25, 2021\n\n  - [](#section)\n      - [Systematic com"
  },
  {
    "path": "docs/miQC.Rmd",
    "chars": 9716,
    "preview": "---\ntitle: \"Running miQC on Seurat objects\"\ndate: \"Compiled: `r format(Sys.time(), '%B %d, %Y')`\"\noutput:\n  html_documen"
  },
  {
    "path": "docs/miQC.html",
    "chars": 1474443,
    "preview": "<!DOCTYPE html>\n\n<html>\n\n<head>\n\n<meta charset=\"utf-8\" />\n<meta name=\"generator\" content=\"pandoc\" />\n<meta http-equiv=\"X"
  },
  {
    "path": "docs/miQC.md",
    "chars": 14654,
    "preview": "Running miQC on Seurat objects\n================\nCompiled: July 19, 2021\n\nThis vigettte demonstrates the use of the miQC "
  },
  {
    "path": "docs/monocle3.Rmd",
    "chars": 4120,
    "preview": "---\ntitle: \"Calculating Trajectories with Monocle 3 and Seurat\"\noutput:\n  html_document:\n    df_print: kable\n    theme: "
  },
  {
    "path": "docs/monocle3.html",
    "chars": 9065636,
    "preview": "<!DOCTYPE html>\n\n<html>\n\n<head>\n\n<meta charset=\"utf-8\" />\n<meta name=\"generator\" content=\"pandoc\" />\n<meta http-equiv=\"X"
  },
  {
    "path": "docs/monocle3.md",
    "chars": 3193,
    "preview": "Calculating Trajectories with Monocle 3 and Seurat\n================\nCompiled: June 17, 2020\n\nThis vigettte demonstrates "
  },
  {
    "path": "docs/nebulosa.Rmd",
    "chars": 7476,
    "preview": "---\ntitle: \"Visualization of gene expression with Nebulosa\"\ndate: 'Compiled: `r format(Sys.Date(), \"%B %d, %Y\")`'\noutput"
  },
  {
    "path": "docs/nebulosa.html",
    "chars": 2188605,
    "preview": "<!DOCTYPE html>\n\n<html>\n\n<head>\n\n<meta charset=\"utf-8\" />\n<meta name=\"generator\" content=\"pandoc\" />\n<meta http-equiv=\"X"
  },
  {
    "path": "docs/nebulosa.md",
    "chars": 7500,
    "preview": "Visualization of gene expression with Nebulosa\n================\nCompiled: September 29, 2020\n\nThis vignette demonstrates"
  },
  {
    "path": "docs/pacmap.Rmd",
    "chars": 3804,
    "preview": "---\ntitle: \"Running PaCMAP on a Seurat Object\"\ndate: 'Compiled: `r format(Sys.Date(), \"%B %d, %Y\")`'\noutput:\n  github_do"
  },
  {
    "path": "docs/pacmap.html",
    "chars": 869113,
    "preview": "<!DOCTYPE html>\n\n<html>\n\n<head>\n\n<meta charset=\"utf-8\" />\n<meta name=\"generator\" content=\"pandoc\" />\n<meta http-equiv=\"X"
  },
  {
    "path": "docs/pacmap.md",
    "chars": 9924,
    "preview": "Running PaCMAP on a Seurat Object\n================\nCompiled: Nov 20, 2024\n\nThis vignette demonstrates how to run PaCMAP,"
  },
  {
    "path": "docs/presto.html",
    "chars": 16304,
    "preview": "<!DOCTYPE html>\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n<head>\n\n<meta charset=\"utf-8\">\n<meta http-equiv=\"Content-T"
  },
  {
    "path": "docs/presto.md",
    "chars": 3112,
    "preview": "Fast Differential Expression with Presto\n================\nCompiled: October 07, 2020\n\nThis vignette demonstrates the use"
  },
  {
    "path": "docs/presto.rmd",
    "chars": 1926,
    "preview": "\n\n---\ntitle: \"Fast Differential Expression with Presto\"\ndate: 'Compiled: `r format(Sys.Date(), \"%B %d, %Y\")`'\noutput: \n "
  },
  {
    "path": "docs/schex.Rmd",
    "chars": 5693,
    "preview": "---\ntitle: \"Using schex with Seurat\"\ndate: 'Compiled: `r format(Sys.Date(), \"%B %d, %Y\")`'\noutput: \n  github_document:\n "
  },
  {
    "path": "docs/schex.html",
    "chars": 1297033,
    "preview": "<!DOCTYPE html>\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n<head>\n\n<meta charset=\"utf-8\" />\n<meta http-equiv=\"Content"
  },
  {
    "path": "docs/schex.md",
    "chars": 6788,
    "preview": "Using schex with Seurat\n================\nCompiled: August 07, 2019\n\nThis vigettte demonstrates how to run schex on Seura"
  },
  {
    "path": "docs/scvelo.Rmd",
    "chars": 3780,
    "preview": "---\ntitle: \"Estimating RNA Velocity using Seurat and scVelo\"\ndate: 'Compiled: `r format(Sys.Date(), \"%B %d, %Y\")`'\noutpu"
  },
  {
    "path": "docs/scvelo.html",
    "chars": 6663980,
    "preview": "<!DOCTYPE html>\n\n<html>\n\n<head>\n\n<meta charset=\"utf-8\" />\n<meta name=\"generator\" content=\"pandoc\" />\n<meta http-equiv=\"X"
  },
  {
    "path": "docs/scvelo.md",
    "chars": 3161,
    "preview": "Estimating RNA Velocity using Seurat and scVelo\n================\nCompiled: June 10, 2020\n\nThis vignette demonstrates ana"
  },
  {
    "path": "docs/tricycle.Rmd",
    "chars": 7780,
    "preview": "---\ntitle: \"Running estimate_cycle_position from tricycle on Seurat Objects\"\ndate: 'Compiled: `r format(Sys.Date(), \"%B "
  },
  {
    "path": "docs/tricycle.html",
    "chars": 1348805,
    "preview": "<!DOCTYPE html>\n\n<html>\n\n<head>\n\n<meta charset=\"utf-8\" />\n<meta name=\"generator\" content=\"pandoc\" />\n<meta http-equiv=\"X"
  },
  {
    "path": "docs/tricycle.md",
    "chars": 7575,
    "preview": "Running estimate\\_cycle\\_position from tricycle on Seurat Objects\n================\nCompiled: July 09, 2021\n\n  - [Introdu"
  },
  {
    "path": "docs/velocity.Rmd",
    "chars": 2716,
    "preview": "---\ntitle: \"Estimating RNA Velocity using Seurat\"\ndate: 'Compiled: `r format(Sys.Date(), \"%B %d, %Y\")`'\noutput: \n  githu"
  },
  {
    "path": "docs/velocity.html",
    "chars": 3434048,
    "preview": "<!DOCTYPE html>\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n<head>\n\n<meta charset=\"utf-8\" />\n<meta http-equiv=\"Content"
  },
  {
    "path": "docs/velocity.md",
    "chars": 2376,
    "preview": "Estimating RNA Velocity using Seurat\n================\nCompiled: July 15, 2019\n\nThis vignette demonstrates analysing RNA "
  },
  {
    "path": "man/ALRAChooseKPlot.Rd",
    "chars": 998,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/alra.R\n\\name{ALRAChooseKPlot}\n\\alias{ALRAC"
  },
  {
    "path": "man/CellBrowser.Rd",
    "chars": 3410,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/cellbrowser.R\n\\name{CellBrowser}\n\\alias{Ce"
  },
  {
    "path": "man/FastMNNIntegration.Rd",
    "chars": 2596,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/fast_mnn_v5.R\n\\name{FastMNNIntegration}\n\\a"
  },
  {
    "path": "man/LearnGraph.Rd",
    "chars": 773,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/monocle3.R\n\\name{LearnGraph}\n\\alias{LearnG"
  },
  {
    "path": "man/PlotMiQC.Rd",
    "chars": 701,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/miqc.R\n\\name{PlotMiQC}\n\\alias{PlotMiQC}\n\\t"
  },
  {
    "path": "man/ReadAlevin.Rd",
    "chars": 1169,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/alevin.R\n\\name{ReadAlevin}\n\\alias{ReadAlev"
  },
  {
    "path": "man/ReadVelocity.Rd",
    "chars": 654,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/velocity.R\n\\name{ReadVelocity}\n\\alias{Read"
  },
  {
    "path": "man/RunALRA.Rd",
    "chars": 3225,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/alra.R\n\\name{RunALRA}\n\\alias{RunALRA}\n\\ali"
  },
  {
    "path": "man/RunBanksy.Rd",
    "chars": 2677,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/banksy.R\n\\name{RunBanksy}\n\\alias{RunBanksy"
  },
  {
    "path": "man/RunCoGAPS.Rd",
    "chars": 1261,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/cogaps.R\n\\name{RunCoGAPS}\n\\alias{RunCoGAPS"
  },
  {
    "path": "man/RunFastMNN.Rd",
    "chars": 1644,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/fast_mnn.R\n\\name{RunFastMNN}\n\\alias{RunFas"
  },
  {
    "path": "man/RunGLMPCA.Rd",
    "chars": 1238,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/glmpca.R\n\\name{RunGLMPCA}\n\\alias{RunGLMPCA"
  },
  {
    "path": "man/RunMiQC.Rd",
    "chars": 2671,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/miqc.R\n\\name{RunMiQC}\n\\alias{RunMiQC}\n\\tit"
  },
  {
    "path": "man/RunOptimizeALS.Rd",
    "chars": 2700,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/liger.R\n\\name{RunOptimizeALS}\n\\alias{RunOp"
  },
  {
    "path": "man/RunPaCMAP.Rd",
    "chars": 4974,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/pacmap.R\n\\name{RunPaCMAP}\n\\alias{RunPaCMAP"
  },
  {
    "path": "man/RunPresto.Rd",
    "chars": 2405,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/presto.R\n\\name{RunPresto}\n\\alias{RunPresto"
  },
  {
    "path": "man/RunPrestoAll.Rd",
    "chars": 1969,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/presto.R\n\\name{RunPrestoAll}\n\\alias{RunPre"
  },
  {
    "path": "man/RunQuantileAlignSNF.Rd",
    "chars": 2522,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/liger.R\n\\name{RunQuantileAlignSNF}\n\\alias{"
  },
  {
    "path": "man/RunQuantileNorm.Rd",
    "chars": 2131,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/liger.R\n\\name{RunQuantileNorm}\n\\alias{RunQ"
  },
  {
    "path": "man/RunSNF.Rd",
    "chars": 864,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/liger.R\n\\name{RunSNF}\n\\alias{RunSNF}\n\\alia"
  },
  {
    "path": "man/RunVelocity.Rd",
    "chars": 1363,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/velocity.R\n\\name{RunVelocity}\n\\alias{RunVe"
  },
  {
    "path": "man/Runtricycle.Rd",
    "chars": 2054,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricycle.R\n\\name{Runtricycle}\n\\alias{Runtr"
  },
  {
    "path": "man/SeuratWrappers-package.Rd",
    "chars": 1631,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/internal.R\n\\docType{package}\n\\name{SeuratW"
  },
  {
    "path": "man/StopCellbrowser.Rd",
    "chars": 291,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/cellbrowser.R\n\\name{StopCellbrowser}\n\\alia"
  },
  {
    "path": "man/VeloPlot.Rd",
    "chars": 463,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/velocity.R\n\\name{VeloPlot}\n\\alias{VeloPlot"
  },
  {
    "path": "man/as.Seurat.extras.Rd",
    "chars": 5151,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/conos.R, R/monocle3.R, R/velocity.R\n\\name{"
  },
  {
    "path": "man/as.cell_data_set.Rd",
    "chars": 2643,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/monocle3.R\n\\name{as.cell_data_set}\n\\alias{"
  },
  {
    "path": "man/findMatrix.Rd",
    "chars": 476,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/cellbrowser.R\n\\name{findMatrix}\n\\alias{fin"
  },
  {
    "path": "man/scVIIntegration.Rd",
    "chars": 2266,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/scVI.R\n\\name{scVIIntegration}\n\\alias{scVII"
  },
  {
    "path": "man/writeSparseTsvChunks.Rd",
    "chars": 1008,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/cellbrowser.R\n\\name{writeSparseTsvChunks}\n"
  },
  {
    "path": "seurat-wrappers.Rproj",
    "chars": 396,
    "preview": "Version: 1.0\n\nRestoreWorkspace: Default\nSaveWorkspace: Default\nAlwaysSaveHistory: Default\n\nEnableCodeIndexing: Yes\nUseSp"
  },
  {
    "path": "test-vignettes.sh",
    "chars": 3480,
    "preview": "#!/bin/bash\n\n#   Check changed vignettes for SeuratWrappers\n#   Set global options to cause the script to fail upon fail"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the satijalab/seurat-wrappers GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 118 files (51.6 MB), approximately 10.8M tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!