├── DESCRIPTION
├── LICENSE
├── NAMESPACE
├── R
├── datasets.R
├── main.R
├── rotations.R
├── seurat_utils.R
└── utils.R
├── README.md
├── data
├── Hs2Mm.convert.table.RData
├── cell.cycle.obj.RData
└── query_example_seurat.RData
├── docs
├── CSI_Toolkit.png
├── Proj_modes.png
├── RSticker_ProjecTILS.png
├── _config.yml
├── functions.md
├── projectils_logo_B_square.png
├── projectils_logo_W_square.png
└── recalc_embeddings.png
├── inst
└── extdata
│ ├── reference_links.R
│ └── reference_links.csv
└── man
├── FindAllMarkers.bygroup.Rd
├── Hs2Mm.convert.table.Rd
├── ProjecTILs.classifier.Rd
├── Run.ProjecTILs.Rd
├── cell.cycle.obj.Rd
├── cellstate.predict.Rd
├── celltype.heatmap.Rd
├── compute_silhouette.Rd
├── find.discriminant.dimensions.Rd
├── find.discriminant.genes.Rd
├── get.reference.maps.Rd
├── list.reference.maps.Rd
├── load.reference.map.Rd
├── make.projection.Rd
├── make.reference.Rd
├── merge.Seurat.embeddings.Rd
├── plot.discriminant.3d.Rd
├── plot.projection.Rd
├── plot.statepred.composition.Rd
├── plot.states.radar.Rd
├── read.sc.query.Rd
└── recalculate.embeddings.Rd
/DESCRIPTION:
--------------------------------------------------------------------------------
1 | Package: ProjecTILs
2 | Type: Package
3 | Title: Reference-based analysis of scRNA-seq data
4 | Version: 3.6.0
5 | Authors@R: c(
6 | person(given = 'Massimo', family = 'Andreatta',
7 | email = 'massimo.andreatta@unil.ch',
8 | role = c('aut','cre'),
9 | comment = c(ORCID = '0000-0002-8036-2647')),
10 | person(given = 'Paul', family = 'Gueguen',
11 | email = 'paul.gueguen@unil.ch',
12 | role = c('aut'),
13 | comment = c(ORCID = '0000-0003-2930-6073')),
14 | person('Josep','Garnica',
15 | email = 'josep.garnicacaparros@unil.ch',
16 | role = c('aut'),
17 | comment = c(ORCID = '0000-0001-9493-1321')),
18 | person(given = 'Santiago', family = 'Carmona',
19 | email = 'santiago.carmona@unil.ch',
20 | role = c('aut'),
21 | comment = c(ORCID = '0000-0002-2495-0671'))
22 | )
23 | Description: This package implements methods to project single-cell RNA-seq data onto a reference atlas, enabling interpretation of unknown cell transcriptomic states in the the context of known, reference states.
24 | Depends: R(>= 4.3.0)
25 | Imports:
26 | Seurat(>= 5.0.0),
27 | SeuratObject(>= 5.0.0),
28 | uwot,
29 | umap,
30 | Matrix,
31 | BiocParallel,
32 | BiocNeighbors,
33 | patchwork,
34 | reshape2,
35 | ggplot2,
36 | grDevices,
37 | scales,
38 | pracma,
39 | STACAS,
40 | UCell,
41 | scGate,
42 | pheatmap,
43 | RColorBrewer,
44 | dplyr,
45 | tidyr,
46 | jsonlite,
47 | digest
48 | Suggests:
49 | fastICA,
50 | EnhancedVolcano,
51 | plotly,
52 | biocViews:
53 | BugReports: https://github.com/carmonalab/ProjecTILs/issues
54 | URL: https://github.com/carmonalab/ProjecTILs
55 | License: GPL-3 + file LICENSE
56 | Encoding: UTF-8
57 | LazyData: true
58 | RoxygenNote: 7.3.2
59 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/NAMESPACE:
--------------------------------------------------------------------------------
1 | # Generated by roxygen2: do not edit by hand
2 |
3 | export(FindAllMarkers.bygroup)
4 | export(ProjecTILs.classifier)
5 | export(Run.ProjecTILs)
6 | export(cellstate.predict)
7 | export(celltype.heatmap)
8 | export(compute_silhouette)
9 | export(find.discriminant.dimensions)
10 | export(find.discriminant.genes)
11 | export(get.reference.maps)
12 | export(list.reference.maps)
13 | export(load.reference.map)
14 | export(make.projection)
15 | export(make.reference)
16 | export(merge.Seurat.embeddings)
17 | export(plot.discriminant.3d)
18 | export(plot.projection)
19 | export(plot.statepred.composition)
20 | export(plot.states.radar)
21 | export(read.sc.query)
22 | export(recalculate.embeddings)
23 | import(RColorBrewer)
24 | import(Seurat)
25 | import(SeuratObject)
26 | import(ggplot2)
27 | import(pheatmap)
28 | importFrom(BiocNeighbors,AnnoyParam)
29 | importFrom(BiocNeighbors,queryKNN)
30 | importFrom(BiocParallel,MulticoreParam)
31 | importFrom(BiocParallel,SerialParam)
32 | importFrom(BiocParallel,SnowParam)
33 | importFrom(BiocParallel,bplapply)
34 | importFrom(Matrix,readMM)
35 | importFrom(STACAS,FindAnchors.STACAS)
36 | importFrom(STACAS,IntegrateData.STACAS)
37 | importFrom(digest,digest)
38 | importFrom(dplyr,"%>%")
39 | importFrom(dplyr,filter)
40 | importFrom(dplyr,group_by)
41 | importFrom(dplyr,left_join)
42 | importFrom(dplyr,pull)
43 | importFrom(dplyr,select)
44 | importFrom(dplyr,top_n)
45 | importFrom(grDevices,colorRampPalette)
46 | importFrom(grDevices,rainbow)
47 | importFrom(jsonlite,fromJSON)
48 | importFrom(patchwork,plot_annotation)
49 | importFrom(patchwork,wrap_plots)
50 | importFrom(pracma,distmat)
51 | importFrom(reshape2,melt)
52 | importFrom(scGate,scGate)
53 | importFrom(scales,alpha)
54 | importFrom(scales,hue_pal)
55 | importFrom(stats,aggregate)
56 | importFrom(stats,ks.test)
57 | importFrom(stats,prcomp)
58 | importFrom(stats,quantile)
59 | importFrom(stats,sd)
60 | importFrom(stats,t.test)
61 | importFrom(tidyr,drop_na)
62 | importFrom(umap,umap.defaults)
63 | importFrom(utils,read.table)
64 | importFrom(uwot,umap)
65 |
--------------------------------------------------------------------------------
/R/datasets.R:
--------------------------------------------------------------------------------
1 | #' Human-mouse ortholog conversion table
2 | #'
3 | #' A conversion table of stable orthologs between Hs and Mm.
4 | #'
5 | #' @format A dataframe containing gene ortholog mapping.
6 | #' @source \url{https://www.ensembl.org/Mus_musculus/Info/Index}
7 | 'Hs2Mm.convert.table'
8 |
9 | #' Cell cycling signatures
10 | #'
11 | #' A list of cell cycling signatures (G1.S and G2.M phases),
12 | #' for mouse and human.
13 | #'
14 | #' @format A list of cycling signatures.
15 | #' @source \doi{10.1126/science.aad0501}
16 | 'cell.cycle.obj'
--------------------------------------------------------------------------------
/R/rotations.R:
--------------------------------------------------------------------------------
1 | #Rotations
2 | run.umap.2 <- function(pca.obj, ndim=NULL, n.neighbors=15, n.components=2, min.dist=0.3, metric="cosine",seed=1234) {
3 |
4 | umap.config <- umap.defaults
5 | umap.config$n_neighbors = n.neighbors
6 | umap.config$min_dist = min.dist
7 | umap.config$metric = metric
8 | umap.config$n_components = n.components
9 | umap.config$random_state = seed
10 | umap.config$transform_state = seed
11 |
12 | if (is.null(ndim)) {
13 | ndim <- ncol(pca.obj$x)
14 | }
15 |
16 | ref.umap <- umap::umap(pca.obj$x[,1:ndim], config=umap.config)
17 | colnames(ref.umap$layout) <- c("UMAP_1","UMAP_2")
18 | return(ref.umap)
19 | }
20 |
21 | run.umap.uwot <- function(pca.obj, ndim=NULL, n.neighbors=15, n.components=2, min.dist=0.3, metric="cosine",seed=1234) {
22 |
23 | if (is.null(ndim)) {
24 | ndim <- ncol(pca.obj$x)
25 | }
26 |
27 | set.seed(seed)
28 | ref.umap <- uwot::umap(pca.obj$x[,1:ndim],
29 | metric=metric,
30 | min_dist=min.dist,
31 | n_neighbors = n.neighbors,
32 | ret_model=TRUE)
33 |
34 | colnames(ref.umap$embedding) <- c("UMAP_1","UMAP_2")
35 |
36 | return(ref.umap)
37 | }
38 |
39 | prcomp_seurat <- function(obj, assay=NULL, ndim=10, scale=TRUE) {
40 |
41 | if (is.null(assay)) {
42 | assay <- DefaultAssay(obj)
43 | }
44 | varfeat <- VariableFeatures(obj, assay=assay)
45 | mat <- GetAssayData(obj, assay=assay, slot="data")[varfeat,]
46 | refdata <- data.frame(t(as.matrix(mat)))
47 |
48 | refdata <- refdata[, sort(colnames(refdata))]
49 | ref.pca <- prcomp(refdata, rank. = ndim, scale. = scale, center = TRUE, retx=TRUE)
50 |
51 | #Save PCA rotation object
52 | obj@misc$pca_object <- ref.pca
53 |
54 | obj[["pca"]] <- CreateDimReducObject(embeddings=ref.pca$x, loadings=ref.pca$rotation, key = "PC_", assay = assay)
55 | return(obj)
56 | }
57 |
58 | apply.pca.obj.2 <- function(query, query.assay="RNA", pca.obj) {
59 |
60 | newdata <- data.frame(t(as.matrix(GetAssayData(query, assay=query.assay, slot="data"))))
61 | newdata <- newdata[ , order(names(newdata))]
62 |
63 | genes.use <- sort(intersect(colnames(newdata), names(pca.obj$center)))
64 |
65 | newdata.var <- newdata[, genes.use]
66 | center.use <- pca.obj$center[genes.use]
67 | scale.use <- pca.obj$scale[genes.use]
68 | rotation.use <- pca.obj$rotation[genes.use,]
69 |
70 | npca <- scale(newdata.var, center.use, scale.use) %*% rotation.use
71 |
72 | return(npca)
73 | }
74 |
75 | apply.ica.obj <- function(query, query.assay="RNA", ica.obj) {
76 |
77 | newdata <- data.frame(t(as.matrix(GetAssayData(query, assay=query.assay, slot="data"))))
78 | # newdata <- data.frame(t(as.matrix(query@assays[[query.assay]]@data)))
79 | newdata <- newdata[ , order(names(newdata))]
80 |
81 | genes.use <- sort(intersect(colnames(newdata), names(ica.obj$center)))
82 |
83 | newdata.var <- newdata[, genes.use]
84 | center.use <- ica.obj$center[genes.use]
85 | scale.use <- ica.obj$scale[genes.use]
86 |
87 | npca <- scale(newdata.var, center.use, scale.use) %*% ica.obj$K[genes.use,] %*% ica.obj$W
88 | colnames(npca) <- colnames(ica.obj$S)
89 | return(npca)
90 | }
91 |
92 | #dispatch to UMAP prediction method (complete of fast)
93 | make.umap.predict <- function(ref.umap, fast.umap.predict=FALSE, ...) {
94 |
95 | if (fast.umap.predict) {
96 | nproj <- make.umap.predict.weighted.mean(ref.umap=ref.umap, ...)
97 | } else if (class(ref.umap) == "umap") {
98 | nproj <- make.umap.predict.2(ref.umap=ref.umap,
99 | method="umap", ...)
100 | } else if (!is.null(ref.umap$embedding)) {
101 | nproj <- make.umap.predict.2(ref.umap=ref.umap,
102 | method="uwot", ...)
103 | } else {
104 | warning("No UMAP-predict model available. Using fast.umap.predict approximation.")
105 | nproj <- make.umap.predict.weighted.mean(ref.umap=ref.umap, ...)
106 | }
107 | return(nproj)
108 | }
109 |
110 | #UMAP predict usign the umap package
111 | make.umap.predict.2 <- function(ref.umap,
112 | query,
113 | query.assay="RNA",
114 | pca.obj,
115 | pca.query.emb=NULL,
116 | method="uwot") {
117 |
118 | #if PCA query cell embeddings have been pre-calculated, read them from variable
119 | if (is.null(pca.query.emb)) {
120 | pca.query.emb <- apply.pca.obj.2(query=query, query.assay=query.assay, pca.obj=pca.obj)
121 | }
122 |
123 | pca.dim <- dim(ref.umap$data)[2]
124 |
125 | if (method == "umap") {
126 | nproj.umap <- umap:::predict.umap(ref.umap, pca.query.emb[,1:pca.dim])
127 | } else if (method == "uwot") {
128 | nproj.umap <- uwot::umap_transform(pca.query.emb[,1:pca.dim], model = ref.umap)
129 | } else {
130 | stop("Unsupported UMAP method.")
131 | }
132 | return(nproj.umap)
133 | }
134 |
135 | #Fast projection mode: assign UMAP coordinates based on nearest neighbors in PCA space
136 | make.umap.predict.weighted.mean <- function(ref.umap, query,
137 | query.assay="RNA",
138 | pca.obj, pca.query.emb=NULL,
139 | k=8) {
140 |
141 | if (is.null(pca.query.emb)) {
142 | pca.query.emb <- apply.pca.obj.2(query=query, query.assay=query.assay, pca.obj=pca.obj)
143 | }
144 |
145 | ref.space <- ref.umap$data
146 | pca.dim <- ncol(ref.space)
147 | query.space <- pca.query.emb[,1:pca.dim]
148 |
149 | nn.ranked <- Seurat:::NNHelper(data=ref.space, query=query.space, k = k, method = "rann")
150 |
151 | cellnames <- rownames(query.space)
152 | nproj.umap <- matrix(data = NA, nrow = length(cellnames), ncol = 2,
153 | dimnames = list(cellnames, c("UMAP_1","UMAP_2")))
154 |
155 | for (cell in 1:length(cellnames)) {
156 | row <- exp(-nn.ranked@nn.dist[cell,]) #calculate exp(-dist) as weights for nearest neighbors
157 | weights = row/sum(row)
158 | nproj.umap[cell,] = weights %*% ref.umap$layout[nn.ranked@nn.idx[cell,],] #assign UMAP coordinates of (weighted) neighbors
159 | }
160 | return(nproj.umap)
161 |
162 | }
163 |
164 | run.ica <- function(object, assay="integrated", ndim=50) {
165 |
166 | set.seed(1234)
167 | varfeat <- VariableFeatures(object, assay=assay)
168 |
169 | x <- scale(Matrix::t(GetAssayData(object, assay=assay, slot="data")[varfeat,]))
170 | set.seed(1234)
171 | ref.ica <- fastICA(x, n.comp=ndim, row.norm=T, maxit=1000, verbose=FALSE, tol=1e-13, method="R")
172 |
173 | ids <- paste0("ICA_", seq_len(ncol(ref.ica$K)))
174 |
175 | rownames(ref.ica$X) <- colnames(object)
176 | colnames(ref.ica$X) <- varfeat
177 | rownames(ref.ica$K) <- varfeat
178 | colnames(ref.ica$K) <- ids
179 | rownames(ref.ica$A) <- ids
180 | colnames(ref.ica$A) <- colnames(ref.ica$X)
181 | rownames(ref.ica$S) <- colnames(object)
182 | colnames(ref.ica$S) <- ids
183 |
184 | ref.ica$center <- attr(x,"scaled:center")
185 | ref.ica$scale <- attr(x,"scaled:scale")
186 |
187 | object[["ica"]] <- CreateDimReducObject(embeddings=ref.ica$S, loadings=t(ref.ica$A), key = "ICA_", assay = assay)
188 | object@misc$ica <- ref.ica
189 | return(object)
190 | }
191 |
192 |
--------------------------------------------------------------------------------
/R/seurat_utils.R:
--------------------------------------------------------------------------------
1 | # A set of utils functions adapted and simplified from Seurat v4.0.1
2 | # Hao et al. Cell 2021 - https://github.com/satijalab/seurat
3 |
4 | ReadMtx.fix <- function(
5 | mtx,
6 | cells,
7 | features,
8 | cell.column = 1,
9 | feature.column = 2,
10 | skip.cell = 0,
11 | skip.feature = 0,
12 | unique.features = TRUE,
13 | strip.suffix = FALSE
14 | ) {
15 | all.files <- list(
16 | "expression matrix" = mtx,
17 | "barcode list" = cells,
18 | "feature list" = features
19 | )
20 | for (i in seq_along(along.with = all.files)) {
21 | all.files[[i]] <- normalizePath(all.files[[i]], mustWork = FALSE)
22 | }
23 |
24 | cell.barcodes <- read.table(
25 | file = all.files[['barcode list']],
26 | header = FALSE,
27 | sep = '\t',
28 | row.names = NULL,
29 | skip = skip.cell
30 | )
31 | feature.names <- read.table(
32 | file = all.files[['feature list']],
33 | header = FALSE,
34 | sep = '\t',
35 | row.names = NULL,
36 | skip = skip.feature
37 | )
38 | # read barcodes
39 | bcols <- ncol(x = cell.barcodes)
40 | if (bcols < cell.column) {
41 | stop(
42 | "cell.column was set to ",
43 | cell.column,
44 | " but ",
45 | cells,
46 | " only has ",
47 | bcols,
48 | " columns.",
49 | " Try setting the cell.column argument to a value <= to ",
50 | bcols,
51 | "."
52 | )
53 | }
54 | cell.names <- cell.barcodes[, cell.column]
55 | if (all(grepl(pattern = "\\-1$", x = cell.names)) & strip.suffix) {
56 | cell.names <- as.vector(x = as.character(x = sapply(
57 | X = cell.names,
58 | FUN = ExtractField,
59 | field = 1,
60 | delim = "-"
61 | )))
62 | }
63 | # read features
64 | fcols <- ncol(x = feature.names)
65 | if (fcols < feature.column) {
66 | stop(
67 | "feature.column was set to ",
68 | feature.column,
69 | " but ",
70 | features,
71 | " only has ",
72 | fcols, " column(s).",
73 | " Try setting the feature.column argument to a value <= to ",
74 | fcols,
75 | "."
76 | )
77 | }
78 | if (any(is.na(x = feature.names[, feature.column]))) {
79 | na.features <- which(x = is.na(x = feature.names[, feature.column]))
80 | replacement.column <- ifelse(test = feature.column == 2, yes = 1, no = 2)
81 | if (replacement.column > fcols) {
82 | stop(
83 | "Some features names are NA in column ",
84 | feature.column,
85 | ". Try specifiying a different column.",
86 | call. = FALSE
87 | )
88 | } else {
89 | warning(
90 | "Some features names are NA in column ",
91 | feature.column,
92 | ". Replacing NA names with ID from column ",
93 | replacement.column,
94 | ".",
95 | call. = FALSE
96 | )
97 | }
98 | feature.names[na.features, feature.column] <- feature.names[na.features, replacement.column]
99 | }
100 | feature.names <- feature.names[, feature.column]
101 | if (unique.features) {
102 | feature.names <- make.unique(names = feature.names)
103 | }
104 | data <- readMM(file = all.files[['expression matrix']])
105 | if (length(x = cell.names) != ncol(x = data)) {
106 | stop(
107 | "Matrix has ",
108 | ncol(data),
109 | " columns but found ", length(cell.names),
110 | " barcodes. ",
111 | ifelse(
112 | test = length(x = cell.names) > ncol(x = data),
113 | yes = "Try increasing `skip.cell`. ",
114 | no = ""
115 | ),
116 | call. = FALSE
117 | )
118 | }
119 | if (length(x = feature.names) != nrow(x = data)) {
120 | stop(
121 | "Matrix has ",
122 | ncol(data),
123 | " rows but found ", length(feature.names),
124 | " features. ",
125 | ifelse(
126 | test = length(x = feature.names) > nrow(x = data),
127 | yes = "Try increasing `skip.feature`. ",
128 | no = ""
129 | ),
130 | call. = FALSE
131 | )
132 | }
133 |
134 | colnames(x = data) <- cell.names
135 | rownames(x = data) <- feature.names
136 | data <- as(data, Class = "dgCMatrix")
137 | return(data)
138 | }
139 |
140 | #Find integration anchors using reciprocal PCA
141 | FindIntegrationAnchors_local <- function(
142 | object.list = NULL,
143 | assay = NULL,
144 | anchor.coverage = 1, #level of anchor filtering by distance [0,1]
145 | correction.scale = 100, #slope of the correction
146 | alpha=0.5,
147 | anchor.features = 2000,
148 | sct.clip.range = NULL,
149 | l2.norm = TRUE,
150 | dims = 1:30,
151 | k.anchor = 5,
152 | k.filter = NA,
153 | k.score = 30,
154 | remove.thr = 0,
155 | max.features = 200,
156 | nn.method = "annoy",
157 | n.trees = 50,
158 | eps = 0,
159 | verbose = TRUE
160 | ) {
161 |
162 | normalization.method <- "LogNormalize"
163 | reference <- NULL
164 | reduction <- "pca"
165 |
166 | object.ncells <- sapply(X = object.list, FUN = function(x) dim(x = x)[2])
167 | if (any(object.ncells <= max(dims))) {
168 | bad.obs <- which(x = object.ncells <= max(dims))
169 | stop("Max dimension too large: objects ", paste(bad.obs, collapse = ", "),
170 | " contain fewer than ", max(dims), " cells. \n Please specify a",
171 | " maximum dimensions that is less than the number of cells in any ",
172 | "object (", min(object.ncells), ").")
173 | }
174 | if (!is.null(x = assay)) {
175 | if (length(x = assay) != length(x = object.list)) {
176 | stop("If specifying the assay, please specify one assay per object in the object.list")
177 | }
178 | object.list <- sapply(
179 | X = 1:length(x = object.list),
180 | FUN = function(x) {
181 | DefaultAssay(object = object.list[[x]]) <- assay[x]
182 | return(object.list[[x]])
183 | }
184 | )
185 | } else {
186 | assay <- sapply(X = object.list, FUN = DefaultAssay)
187 | }
188 | object.list <- CheckDuplicateCellNames_local(object.list = object.list)
189 |
190 | slot <- "data"
191 |
192 | nn.reduction <- reduction
193 | internal.neighbors <- list()
194 |
195 | if (verbose) {
196 | message("Computing within dataset neighborhoods")
197 | }
198 | k.neighbor <- max(k.anchor, k.score)
199 | internal.neighbors <- lapply(
200 | X = 1:length(x = object.list),
201 | FUN = function(x) {
202 | Seurat:::NNHelper(
203 | data = Embeddings(object = object.list[[x]][[nn.reduction]])[, dims],
204 | k = k.neighbor + 1,
205 | method = nn.method,
206 | n.trees = n.trees,
207 | eps = eps
208 | )
209 | }
210 | )
211 | # determine the proper offsets for indexing anchors
212 | objects.ncell <- sapply(X = object.list, FUN = ncol)
213 | offsets <- as.vector(x = cumsum(x = c(0, objects.ncell)))[1:length(x = object.list)]
214 |
215 | if (verbose) {
216 | message("Finding all pairwise anchors")
217 | }
218 |
219 | i <- 1
220 | j <- 2
221 | object.1 <- DietSeurat(
222 | object = object.list[[i]],
223 | assays = assay[i],
224 | features = anchor.features,
225 | counts = FALSE,
226 | scale.data = TRUE,
227 | dimreducs = reduction
228 | )
229 | object.2 <- DietSeurat(
230 | object = object.list[[j]],
231 | assays = assay[j],
232 | features = anchor.features,
233 | counts = FALSE,
234 | scale.data = TRUE,
235 | dimreducs = reduction
236 | )
237 | # suppress key duplication warning
238 | suppressWarnings(object.1[["ToIntegrate"]] <- object.1[[assay[i]]])
239 | DefaultAssay(object = object.1) <- "ToIntegrate"
240 | if (reduction %in% Reductions(object = object.1)) {
241 | slot(object = object.1[[reduction]], name = "assay.used") <- "ToIntegrate"
242 | }
243 | object.1 <- DietSeurat(object = object.1,
244 | assays = "ToIntegrate",
245 | counts = FALSE,
246 | scale.data = TRUE,
247 | dimreducs = reduction)
248 | suppressWarnings(object.2[["ToIntegrate"]] <- object.2[[assay[j]]])
249 |
250 | DefaultAssay(object = object.2) <- "ToIntegrate"
251 | if (reduction %in% Reductions(object = object.2)) {
252 | slot(object = object.2[[reduction]], name = "assay.used") <- "ToIntegrate"
253 | }
254 | object.2 <- DietSeurat(object = object.2,
255 | assays = "ToIntegrate",
256 | counts = FALSE,
257 | scale.data = TRUE,
258 | dimreducs = reduction)
259 |
260 | #Reciprocal PCA
261 | common.features <- intersect(
262 | x = rownames(x = Loadings(object = object.1[["pca"]])),
263 | y = rownames(x = Loadings(object = object.2[["pca"]]))
264 | )
265 | common.features <- intersect(
266 | x = common.features,
267 | y = anchor.features
268 | )
269 | object.pair <- merge(x = object.1, y = object.2, merge.data = TRUE)
270 | projected.embeddings.1<- t(x = GetAssayData(object = object.1, slot = "scale.data")[common.features, ]) %*%
271 | Loadings(object = object.2[["pca"]])[common.features, ]
272 | object.pair[['projectedpca.1']] <- CreateDimReducObject(
273 | embeddings = rbind(projected.embeddings.1, Embeddings(object = object.2[["pca"]])),
274 | assay = DefaultAssay(object = object.1),
275 | key = "projectedpca1_"
276 | )
277 | projected.embeddings.2 <- t(x = GetAssayData(object = object.2, slot = "scale.data")[common.features, ]) %*%
278 | Loadings(object = object.1[["pca"]])[common.features, ]
279 | object.pair[['projectedpca.2']] <- CreateDimReducObject(
280 | embeddings = rbind(projected.embeddings.2, Embeddings(object = object.1[["pca"]])),
281 | assay = DefaultAssay(object = object.2),
282 | key = "projectedpca2_"
283 | )
284 | object.pair[["pca"]] <- CreateDimReducObject(
285 | embeddings = rbind(
286 | Embeddings(object = object.1[["pca"]]),
287 | Embeddings(object = object.2[["pca"]])),
288 | assay = DefaultAssay(object = object.1),
289 | key = "pca_"
290 | )
291 | reduction <- "projectedpca.1"
292 | reduction.2 <- "projectedpca.2"
293 | if (l2.norm){
294 | slot(object = object.pair[["projectedpca.1"]], name = "cell.embeddings") <- Sweep_local(
295 | x = Embeddings(object = object.pair[["projectedpca.1"]]),
296 | MARGIN = 2,
297 | STATS = apply(X = Embeddings(object = object.pair[["projectedpca.1"]]), MARGIN = 2, FUN = sd),
298 | FUN = "/"
299 | )
300 | slot(object = object.pair[["projectedpca.2"]], name = "cell.embeddings") <- Sweep_local(
301 | x = Embeddings(object = object.pair[["projectedpca.2"]]),
302 | MARGIN = 2,
303 | STATS = apply(X = Embeddings(object = object.pair[["projectedpca.2"]]), MARGIN = 2, FUN = sd),
304 | FUN = "/"
305 | )
306 | object.pair <- L2Dim(object = object.pair, reduction = "projectedpca.1")
307 | object.pair <- L2Dim(object = object.pair, reduction = "projectedpca.2")
308 | reduction <- paste0(reduction, ".l2")
309 | reduction.2 <- paste0(reduction.2, ".l2")
310 | }
311 |
312 | internal.neighbors <- internal.neighbors[c(i, j)]
313 |
314 | anchors <- FindAnchors_local(
315 | object.pair = object.pair,
316 | assay = c("ToIntegrate", "ToIntegrate"),
317 | slot = slot,
318 | cells1 = colnames(x = object.1),
319 | cells2 = colnames(x = object.2),
320 | internal.neighbors = internal.neighbors,
321 | reduction = reduction,
322 | reduction.2 = reduction.2,
323 | nn.reduction = nn.reduction,
324 | dims = dims,
325 | k.anchor = k.anchor,
326 | k.filter = k.filter,
327 | k.score = k.score,
328 | max.features = max.features,
329 | nn.method = nn.method,
330 | n.trees = n.trees,
331 | eps = eps,
332 | verbose = verbose
333 | )
334 | anchors[, 1] <- anchors[, 1] + offsets[i]
335 | anchors[, 2] <- anchors[, 2] + offsets[j]
336 |
337 | #Average distances
338 | anchors <- as.data.frame(anchors)
339 | anchors$dist.mean <- apply(anchors[,c("dist1.2","dist2.1")], MARGIN=1, mean)
340 | message(sprintf(" SD on anchor distances: %.3f",sd(anchors$dist.mean)))
341 |
342 | if (anchor.coverage < 1) {
343 |
344 | #Combine anchor distance with anchor score
345 | sigmoid_center <- unname(quantile(anchors$dist.mean, probs = anchor.coverage, na.rm = T))
346 |
347 | distance_factors <- sigmoid(x = anchors$dist.mean, center = sigmoid_center, scale = correction.scale)
348 |
349 | #anchors$score <- alpha*distance_factors + (1-alpha)*anchors$score
350 |
351 | #Multiply distance factors by score
352 | anchors$score <- anchors$score * distance_factors
353 |
354 | ##Remove distant anchors
355 | anchors <- anchors[distance_factors > remove.thr,]
356 |
357 | }
358 | nanchors <- nrow(anchors)
359 | #message(sprintf(" Retaining %i anchors after filtering by rPCA distance", nanchors))
360 |
361 | ##Include reciprocal anchors
362 | anchors <- rbind(anchors[, c("cell1","cell2","score","dist.mean")],
363 | anchors[, c("cell2","cell1","score","dist.mean")])
364 | anchors <- AddDatasetID_local(anchor.df = anchors, offsets = offsets, obj.lengths = objects.ncell)
365 |
366 | command <- LogSeuratCommand(object = object.list[[1]], return.command = TRUE)
367 | anchor.set <- new(Class = "IntegrationAnchorSet",
368 | object.list = object.list,
369 | reference.objects = seq_along(object.list),
370 | anchors = anchors,
371 | offsets = offsets,
372 | anchor.features = anchor.features,
373 | command = command
374 | )
375 |
376 | return(anchor.set)
377 | }
378 |
379 | sigmoid <- function(x, scale, center){
380 | sigm <- 1/(1 + exp(scale*(x-center)))
381 | return(sigm)
382 | }
383 |
384 | #Add dataset ID
385 | AddDatasetID_local <- function(
386 | anchor.df,
387 | offsets,
388 | obj.lengths
389 | ) {
390 | ndataset <- length(x = offsets)
391 | row.offset <- rep.int(x = offsets, times = obj.lengths)
392 | dataset <- rep.int(x = 1:ndataset, times = obj.lengths)
393 |
394 | anchor.df <- data.frame(
395 | 'cell1' = anchor.df[, 'cell1'] - row.offset[anchor.df[, 'cell1']],
396 | 'cell2' = anchor.df[, 'cell2'] - row.offset[anchor.df[, 'cell2']],
397 | 'score' = anchor.df[, 'score'],
398 | 'dataset1' = dataset[anchor.df[, 'cell1']],
399 | 'dataset2' = dataset[anchor.df[, 'cell2']],
400 | 'dist.mean' = anchor.df[, 'dist.mean']
401 | )
402 | return(anchor.df)
403 | }
404 |
405 | #Find anchors between a pair of objects
406 | FindAnchors_local <- function(
407 | object.pair,
408 | assay,
409 | slot,
410 | cells1,
411 | cells2,
412 | internal.neighbors,
413 | reduction,
414 | reduction.2 = character(),
415 | nn.reduction = reduction,
416 | dims = 1:10,
417 | k.anchor = 5,
418 | k.filter = NA,
419 | k.score = 30,
420 | max.features = 200,
421 | nn.method = "annoy",
422 | n.trees = 50,
423 | nn.idx1 = NULL,
424 | nn.idx2 = NULL,
425 | eps = 0,
426 | verbose = TRUE
427 | ) {
428 | # compute local neighborhoods, use max of k.anchor and k.score if also scoring to avoid
429 | # recomputing neighborhoods
430 | k.neighbor <- k.anchor
431 | if (!is.na(x = k.score)) {
432 | k.neighbor <- max(k.anchor, k.score)
433 | }
434 | object.pair <- FindNN_local(
435 | object = object.pair,
436 | cells1 = cells1,
437 | cells2 = cells2,
438 | internal.neighbors = internal.neighbors,
439 | dims = dims,
440 | reduction = reduction,
441 | reduction.2 = reduction.2,
442 | nn.reduction = nn.reduction,
443 | k = k.neighbor,
444 | nn.method = nn.method,
445 | n.trees = n.trees,
446 | nn.idx1 = nn.idx1,
447 | nn.idx2 = nn.idx2,
448 | eps = eps,
449 | verbose = verbose
450 | )
451 | object.pair <- FindAnchorPairs_local(
452 | object = object.pair,
453 | integration.name = "integrated",
454 | k.anchor = k.anchor,
455 | verbose = verbose
456 | )
457 | if (!is.na(x = k.score)) {
458 | object.pair = ScoreAnchors_local(
459 | object = object.pair,
460 | assay = DefaultAssay(object = object.pair),
461 | integration.name = "integrated",
462 | verbose = verbose,
463 | k.score = k.score
464 | )
465 | }
466 |
467 | ###Return distances
468 | anc.tab <- object.pair@tools$integrated@anchors
469 | d1.2 <- numeric(length = dim(anc.tab)[1])
470 | d2.1 <- numeric(length = dim(anc.tab)[1])
471 | for (r in 1:dim(anc.tab)[1]) {
472 | c1 <- anc.tab[r,"cell1"]
473 | c2 <- anc.tab[r,"cell2"]
474 | d1.2[r] <- object.pair@tools$integrated@neighbors$nnab@nn.dist[c1, which(object.pair@tools$integrated@neighbors$nnab@nn.idx[c1,] == c2 )]
475 | d2.1[r] <- object.pair@tools$integrated@neighbors$nnba@nn.dist[c2, which(object.pair@tools$integrated@neighbors$nnba@nn.idx[c2,] == c1 )]
476 | }
477 |
478 | object.pair@tools$integrated@anchors <- cbind(object.pair@tools$integrated@anchors, dist1.2=d1.2)
479 | object.pair@tools$integrated@anchors <- cbind(object.pair@tools$integrated@anchors, dist2.1=d2.1)
480 |
481 | anchors <- GetIntegrationData(
482 | object = object.pair,
483 | integration.name = 'integrated',
484 | slot = 'anchors'
485 | )
486 | return(anchors)
487 | }
488 |
489 | #Find anchor pairs
490 | FindAnchorPairs_local <- function(
491 | object,
492 | integration.name = 'integrated',
493 | k.anchor = 5,
494 | verbose = TRUE
495 | ) {
496 | neighbors <- GetIntegrationData(object = object, integration.name = integration.name, slot = 'neighbors')
497 | max.nn <- c(ncol(x = neighbors$nnab), ncol(x = neighbors$nnba))
498 | if (any(k.anchor > max.nn)) {
499 | message(paste0('warning: requested k.anchor = ', k.anchor, ', only ', min(max.nn), ' in dataset'))
500 | k.anchor <- min(max.nn)
501 | }
502 | if (verbose) {
503 | message("Finding anchors")
504 | }
505 | # convert cell name to neighbor index
506 | nn.cells1 <- neighbors$cells1
507 | nn.cells2 <- neighbors$cells2
508 | cell1.index <- suppressWarnings(which(colnames(x = object) == nn.cells1, arr.ind = TRUE))
509 | ncell <- 1:nrow(x = neighbors$nnab)
510 | ncell <- ncell[ncell %in% cell1.index]
511 | anchors <- list()
512 | # pre allocate vector
513 | anchors$cell1 <- rep(x = 0, length(x = ncell) * 5)
514 | anchors$cell2 <- anchors$cell1
515 | anchors$score <- anchors$cell1 + 1
516 | idx <- 0
517 | indices.ab <- Indices(object = neighbors$nnab)
518 | indices.ba <- Indices(object = neighbors$nnba)
519 | for (cell in ncell) {
520 | neighbors.ab <- indices.ab[cell, 1:k.anchor]
521 | mutual.neighbors <- which(
522 | x = indices.ba[neighbors.ab, 1:k.anchor, drop = FALSE] == cell,
523 | arr.ind = TRUE
524 | )[, 1]
525 | for (i in neighbors.ab[mutual.neighbors]){
526 | idx <- idx + 1
527 | anchors$cell1[idx] <- cell
528 | anchors$cell2[idx] <- i
529 | anchors$score[idx] <- 1
530 | }
531 | }
532 | anchors$cell1 <- anchors$cell1[1:idx]
533 | anchors$cell2 <- anchors$cell2[1:idx]
534 | anchors$score <- anchors$score[1:idx]
535 | anchors <- t(x = do.call(what = rbind, args = anchors))
536 | anchors <- as.matrix(x = anchors)
537 | object <- SetIntegrationData(
538 | object = object,
539 | integration.name = integration.name,
540 | slot = 'anchors',
541 | new.data = anchors
542 | )
543 | if (verbose) {
544 | message(paste0("\tFound ", nrow(x = anchors), " anchors"))
545 | }
546 | return(object)
547 | }
548 |
549 | #Calculate top feautures across a set of dimensions
550 | TopDimFeatures_local <- function(
551 | object,
552 | reduction,
553 | dims = 1:10,
554 | features.per.dim = 100,
555 | max.features = 200,
556 | projected = FALSE
557 | ) {
558 | dim.reduction <- object[[reduction]]
559 | max.features <- max(length(x = dims) * 2, max.features)
560 | num.features <- sapply(X = 1:features.per.dim, FUN = function(y) {
561 | length(x = unique(x = as.vector(x = sapply(X = dims, FUN = function(x) {
562 | unlist(x = TopFeatures(object = dim.reduction, dim = x, nfeatures = y, balanced = TRUE, projected = projected))
563 | }))))
564 | })
565 | max.per.pc <- which.max(x = num.features[num.features < max.features])
566 | features <- unique(x = as.vector(x = sapply(X = dims, FUN = function(x) {
567 | unlist(x = TopFeatures(object = dim.reduction, dim = x, nfeatures = max.per.pc, balanced = TRUE, projected = projected))
568 | })))
569 | features <- unique(x = features)
570 | return(features)
571 | }
572 |
573 | #Score anchors
574 | ScoreAnchors_local <- function(
575 | object,
576 | assay = NULL,
577 | integration.name = 'integrated',
578 | verbose = TRUE,
579 | k.score = 30
580 | ) {
581 | if (is.null(assay)) {
582 | assay <- DefaultAssay(object)
583 | }
584 | anchor.df <- as.data.frame(x = GetIntegrationData(object = object, integration.name = integration.name, slot = 'anchors'))
585 | neighbors <- GetIntegrationData(object = object, integration.name = integration.name, slot = "neighbors")
586 | offset <- length(x = neighbors$cells1)
587 | indices.aa <- Indices(object = neighbors$nnaa)
588 | indices.bb <- Indices(object = neighbors$nnbb)
589 | indices.ab <- Indices(object = neighbors$nnab)
590 | indices.ba <- Indices(object = neighbors$nnba)
591 | nbrsetA <- function(x) c(indices.aa[x, 1:k.score], indices.ab[x, 1:k.score] + offset)
592 | nbrsetB <- function(x) c(indices.ba[x, 1:k.score], indices.bb[x, 1:k.score] + offset)
593 | # score = number of shared neighbors
594 | anchor.new <- data.frame(
595 | 'cell1' = anchor.df[, 1],
596 | 'cell2' = anchor.df[, 2],
597 | 'score' = mapply(
598 | FUN = function(x, y) {
599 | length(x = intersect(x = nbrsetA(x = x), nbrsetB(x = y)))},
600 | anchor.df[, 1],
601 | anchor.df[, 2]
602 | )
603 | )
604 | # normalize the score
605 | max.score <- quantile(anchor.new$score, 0.9)
606 | min.score <- quantile(anchor.new$score, 0.01)
607 | anchor.new$score <- anchor.new$score - min.score
608 | anchor.new$score <- anchor.new$score / (max.score - min.score)
609 | anchor.new$score[anchor.new$score > 1] <- 1
610 | anchor.new$score[anchor.new$score < 0] <- 0
611 | anchor.new <- as.matrix(x = anchor.new)
612 | object <- SetIntegrationData(
613 | object = object,
614 | integration.name = integration.name,
615 | slot = 'anchors',
616 | new.data = anchor.new
617 | )
618 | return(object)
619 | }
620 |
621 | #Ensure no duplicate cell names
622 | CheckDuplicateCellNames_local <- function(object.list, verbose = TRUE, stop = FALSE) {
623 | cell.names <- unlist(x = lapply(X = object.list, FUN = colnames))
624 | if (any(duplicated(x = cell.names))) {
625 | if (stop) {
626 | stop("Duplicate cell names present across objects provided.")
627 | }
628 | if (verbose) {
629 | warning("Some cell names are duplicated across objects provided. Renaming to enforce unique cell names.")
630 | }
631 | object.list <- lapply(
632 | X = 1:length(x = object.list),
633 | FUN = function(x) {
634 | return(RenameCells(
635 | object = object.list[[x]],
636 | new.names = paste0(Cells(x = object.list[[x]]), "_", x)
637 | ))
638 | }
639 | )
640 | }
641 | return(object.list)
642 | }
643 |
644 | # Find nearest neighbors
645 | FindNN_local <- function(
646 | object,
647 | cells1 = NULL,
648 | cells2 = NULL,
649 | internal.neighbors,
650 | grouping.var = NULL,
651 | dims = 1:10,
652 | reduction = "cca.l2",
653 | reduction.2 = character(),
654 | nn.dims = dims,
655 | nn.reduction = reduction,
656 | k = 300,
657 | nn.method = "annoy",
658 | n.trees = 50,
659 | nn.idx1 = NULL,
660 | nn.idx2 = NULL,
661 | eps = 0,
662 | integration.name = 'integrated',
663 | verbose = TRUE
664 | ) {
665 | if (xor(x = is.null(x = cells1), y = is.null(x = cells2))) {
666 | stop("cells1 and cells2 must both be specified")
667 | }
668 | if (!is.null(x = cells1) && !is.null(x = cells2) && !is.null(x = grouping.var)) {
669 | stop("Specify EITHER grouping.var or cells1/2.")
670 | }
671 | if (is.null(x = cells1) && is.null(x = cells2) && is.null(x = grouping.var)) {
672 | stop("Please set either cells1/2 or grouping.var")
673 | }
674 | if (!is.null(x = grouping.var)) {
675 | if (nrow(x = unique(x = object[[grouping.var]])) != 2) {
676 | stop("Number of groups in grouping.var not equal to 2.")
677 | }
678 | groups <- names(x = sort(x = table(object[[grouping.var]]), decreasing = TRUE))
679 | cells1 <- colnames(x = object)[object[[grouping.var]] == groups[[1]]]
680 | cells2 <- colnames(x = object)[object[[grouping.var]] == groups[[2]]]
681 | }
682 | if (verbose) {
683 | message("Finding neighborhoods")
684 | }
685 | dim.data.self <- Embeddings(object = object[[nn.reduction]])[, nn.dims]
686 | if (!is.null(x = internal.neighbors[[1]])) {
687 | nnaa <- internal.neighbors[[1]]
688 | } else {
689 | dims.cells1.self <- dim.data.self[cells1, ]
690 | nnaa <- Seurat:::NNHelper(
691 | data = dims.cells1.self,
692 | k = k + 1,
693 | method = nn.method,
694 | n.trees = n.trees,
695 | eps = eps,
696 | index = nn.idx1
697 | )
698 | }
699 | if (!is.null(x = internal.neighbors[[2]])) {
700 | nnbb <- internal.neighbors[[2]]
701 | } else {
702 | dims.cells2.self <- dim.data.self[cells2, ]
703 | nnbb <- Seurat:::NNHelper(
704 | data = dims.cells2.self,
705 | k = k + 1,
706 | method = nn.method,
707 | n.trees = n.trees,
708 | eps = eps,
709 | index = nn.idx1
710 | )
711 | }
712 | if (length(x = reduction.2) > 0) {
713 | nnab <- Seurat:::NNHelper(
714 | data = Embeddings(object = object[[reduction.2]])[cells2, ],
715 | query = Embeddings(object = object[[reduction.2]])[cells1, ],
716 | k = k,
717 | method = nn.method,
718 | n.trees = n.trees,
719 | eps = eps,
720 | index = nn.idx2
721 | )
722 | nnba <- Seurat:::NNHelper(
723 | data = Embeddings(object = object[[reduction]])[cells1, ],
724 | query = Embeddings(object = object[[reduction]])[cells2, ],
725 | k = k,
726 | method = nn.method,
727 | n.trees = n.trees,
728 | eps = eps,
729 | index = nn.idx1
730 | )
731 | } else {
732 | dim.data.opposite <- Embeddings(object = object[[reduction]])[ ,dims]
733 | dims.cells1.opposite <- dim.data.opposite[cells1, ]
734 | dims.cells2.opposite <- dim.data.opposite[cells2, ]
735 | nnab <- Seurat:::NNHelper(
736 | data = dims.cells2.opposite,
737 | query = dims.cells1.opposite,
738 | k = k,
739 | method = nn.method,
740 | n.trees = n.trees,
741 | eps = eps,
742 | index = nn.idx2
743 | )
744 | nnba <- Seurat:::NNHelper(
745 | data = dims.cells1.opposite,
746 | query = dims.cells2.opposite,
747 | k = k,
748 | method = nn.method,
749 | n.trees = n.trees,
750 | eps = eps,
751 | index = nn.idx1
752 | )
753 | }
754 | object <- SetIntegrationData(
755 | object = object,
756 | integration.name = integration.name,
757 | slot = 'neighbors',
758 | new.data = list('nnaa' = nnaa, 'nnab' = nnab, 'nnba' = nnba, 'nnbb' = nnbb, 'cells1' = cells1, 'cells2' = cells2)
759 | )
760 | return(object)
761 | }
762 |
763 | Sweep_local <- function(x, MARGIN, STATS, FUN = '-', check.margin = TRUE, ...) {
764 | if (any(grepl(pattern = 'X', x = names(x = formals(fun = sweep))))) {
765 | return(sweep(
766 | X = x,
767 | MARGIN = MARGIN,
768 | STATS = STATS,
769 | FUN = FUN,
770 | check.margin = check.margin,
771 | ...
772 | ))
773 | } else {
774 | return(sweep(
775 | x = x,
776 | MARGIN = MARGIN,
777 | STATS = STATS,
778 | FUN = FUN,
779 | check.margin = check.margin,
780 | ...
781 | ))
782 | }
783 | }
784 |
785 |
--------------------------------------------------------------------------------
/R/utils.R:
--------------------------------------------------------------------------------
1 | filterCells <- function(query.object, species="mouse", gating.model=NULL){
2 |
3 | ncells <- ncol(query.object)
4 | if (ncells <= 1) {
5 | return(NULL)
6 | }
7 | if (is.null(gating.model)) {
8 | return(query.object)
9 | }
10 | pca.dim <- 30
11 | ncells <- ncol(query.object)
12 | if (ncells <= pca.dim) {
13 | pca.dim <- ncells - 1
14 | }
15 |
16 | data(cell.cycle.obj)
17 | query.object <- suppressWarnings(scGate::scGate(data=query.object,
18 | model = gating.model,
19 | pca.dim = pca.dim,
20 | verbose=FALSE,
21 | assay=DefaultAssay(query.object),
22 | additional.signatures = cell.cycle.obj[[species]]))
23 |
24 | ncells.keep <- sum(query.object$is.pure == 'Pure')
25 |
26 | message <- sprintf("%i out of %i ( %i%% ) non-pure cells removed. Use filter.cells=FALSE to avoid pre-filtering",
27 | ncells - ncells.keep, ncells, round(100*(ncells-ncells.keep)/ncells))
28 | print(message)
29 |
30 | if (ncells.keep <= 1) {
31 | return(NULL)
32 | }
33 |
34 | query.object <- subset(query.object, subset=is.pure=='Pure')
35 |
36 | #Parse metadata columns
37 | query.object$cycling.score <- query.object$cycling_UCell
38 | query.object$cycling.score.G1_S <- query.object$cycling_G1.S_UCell
39 | query.object$cycling.score.G2_M <- query.object$cycling_G2.M_UCell
40 |
41 | to_remove <- grep("is.pure", colnames(query.object@meta.data))
42 | to_remove <- c(to_remove, grep("_UCell$", colnames(query.object@meta.data), perl=T))
43 |
44 | query.object@meta.data <- query.object@meta.data[,-to_remove]
45 | return(query.object)
46 | }
47 |
48 | #Internal function to randomly split an object into subsets
49 | randomSplit <- function(obj, n=2, seed=44, verbose=F) {
50 | set.seed(seed)
51 | lgt <- dim(obj)[2]
52 | ind <- sample.int(n, lgt, replace = T)
53 | cell.list <- split(colnames(obj), ind)
54 | seurat.list <- list()
55 | if (verbose==TRUE) {
56 | message(sprintf("Splitting object into %i random subsets", n))
57 | }
58 | for (h in 1:n) {
59 | seurat.list[[h]] <- subset(obj, cells= cell.list[[h]])
60 | }
61 | return(seurat.list)
62 | }
63 |
64 | guess_raw_separator <- function(f, sep=c(" ","\t",",")) {
65 |
66 | lines <- readLines(f, n=10)
67 | if (length(lines) == 0) {
68 | return(NULL)
69 | }
70 | spl <- lapply(sep, grep, x=lines)
71 | counts <- unlist(lapply(spl, length))
72 | if (max(counts)==0) {
73 | return(NULL)
74 | }
75 | sep.index <- which(counts==max(counts))[1]
76 | return(sep[sep.index])
77 |
78 | }
79 |
80 | #Automatically determine species and gene ID column
81 | get.species <- function(genes, table=Hs2Mm.convert.table) {
82 |
83 | g.mm <- length(intersect(genes, table$Gene.MM))
84 | g.hs1 <- length(intersect(genes, table$Gene.stable.ID.HS))
85 | g.hs2 <- length(intersect(genes, table$Gene.HS))
86 | gg <- c(g.mm, g.hs1, g.hs2)
87 |
88 | if (max(gg)==g.mm) {
89 | species='mouse'
90 | col.id <- "Gene.MM"
91 | } else {
92 | species='human'
93 | col.id <- ifelse(g.hs1 > g.hs2, "Gene.stable.ID.HS", "Gene.HS")
94 | }
95 | res <- list("species"=species, "col.id"=col.id)
96 | return(res)
97 | }
98 |
99 |
100 | #Internal function for mouse-human ortholog conversion
101 | convert.orthologs <- function(obj, table, from="Gene.HS", to="Gene.MM",
102 | query.assay="RNA", slot="counts") {
103 |
104 | exp.mat <- GetAssayData(obj, assay=query.assay, layer=slot)
105 | genes.select <- rownames(exp.mat)[rownames(exp.mat) %in% table[[from]]]
106 |
107 | if (length(genes.select) < 100) {
108 | message("Warning: fewer than 100 genes with orthologs were found. Check your matrix format and gene names")
109 | }
110 |
111 | if (length(genes.select) > 0) {
112 | exp.mat <- exp.mat[genes.select, ]
113 | } else {
114 | stop(paste0("Error: No genes found in column ", from))
115 | }
116 |
117 | #Convert
118 | ortho.genes <- table[[to]][match(row.names(exp.mat), table[[from]])]
119 |
120 | #Update matrix gene names
121 | row.names(exp.mat) <- ortho.genes
122 |
123 | #Re-generate object
124 | if (slot=="counts") {
125 | this <- CreateAssayObject(counts=exp.mat)
126 | } else {
127 | this <- CreateAssayObject(data=exp.mat)
128 | }
129 | suppressWarnings(obj[[query.assay]] <- this)
130 | return(obj)
131 | }
132 |
133 | #Helper for projecting individual data sets
134 | projection.helper <- function(query, ref=NULL, filter.cells=TRUE, query.assay=NULL,
135 | direct.projection=FALSE, fast.umap.predict=FALSE,
136 | ortholog_table=NULL,
137 | STACAS.k.weight=100, STACAS.k.anchor=5,
138 | STACAS.anchor.coverage=1, STACAS.correction.scale=100,
139 | skip.normalize=FALSE, id="query1",
140 | alpha=0.5, remove.thr=0,
141 | scGate_model=NULL, ncores=1) {
142 |
143 | retry.direct <- FALSE
144 | do.orthology <- FALSE
145 |
146 | #Reference
147 | DefaultAssay(ref) <- "integrated"
148 | ref.var.features <- VariableFeatures(ref)
149 |
150 | #If query.assay not specified, use the default
151 | if (is.null(query.assay)) {
152 | query.assay <- DefaultAssay(query)
153 | } else {
154 | DefaultAssay(query) <- query.assay
155 | }
156 | print(paste0("Using assay ",query.assay," for ",id))
157 |
158 | if (!is.null(ref@misc$umap_object$data)) {
159 | pca.dim=ncol(ref@misc$umap_object$data) #use the number of PCs used to build the reference
160 | } else {
161 | pca.dim=10
162 | }
163 |
164 | species.ref <- get.species(genes=row.names(ref), table=ortholog_table)
165 | species.query <- get.species(genes=row.names(query), table=ortholog_table)
166 |
167 | if (species.ref$species != species.query$species) {
168 | do.orthology <- TRUE
169 | }
170 |
171 | #Check if slots are populated, and normalize data.
172 | if (skip.normalize) {
173 | gr <- grep("^data", Layers(query))
174 | if (length(gr) == 0) {
175 | stop("Data slot not found in your Seurat object. Please normalize the data")
176 | } else if (length(gr) > 1) {
177 | query <- JoinLayers(query)
178 | }
179 | query <- convert_to_v3(query, assay=query.assay, layer="data")
180 |
181 | } else {
182 | gr <- grep("^counts", Layers(query))
183 | if (length(gr) == 0) {
184 | stop("Counts slot not found in your Seurat object. If you already normalized your data, re-run with option skip.normalize=TRUE")
185 | } else if (length(gr) > 1) {
186 | query <- JoinLayers(query)
187 | }
188 | query <- convert_to_v3(query, assay=query.assay, layer="counts")
189 | query <- NormalizeData(query)
190 | }
191 |
192 | if(filter.cells){
193 | message("Pre-filtering cells with scGate...")
194 | if (is.null(scGate_model)) { #read filter model from atlas
195 | if (!is.null(ref@misc$scGate[[species.query$species]])) {
196 | scGate_model <- ref@misc$scGate[[species.query$species]]
197 | } else {
198 | scGate_model <- NULL
199 | message("No scGate model specified: all cells will be projected")
200 | }
201 | }
202 | query <- filterCells(query, species=species.query$species, gating.model=scGate_model)
203 | }
204 | if (is.null(query)) {
205 | message(sprintf("Warning! Skipping %s - all cells were removed by cell filter", id))
206 | return(NULL)
207 | }
208 |
209 | if (do.orthology) {
210 | print("Transforming expression matrix into space of orthologs")
211 | query <- convert.orthologs(query, table=ortholog_table, query.assay=query.assay, slot="data",
212 | from=species.query$col.id, to=species.ref$col.id)
213 | }
214 |
215 | query <- RenameCells(query, add.cell.id = "Q")
216 | query.metadata <- query@meta.data #back-up metadata (and re-add it after projection)
217 |
218 | genes4integration <- intersect(ref.var.features, row.names(query))
219 |
220 | if(length(genes4integration)/length(ref.var.features)<0.5) {
221 | stop("Too many genes missing. Check input object format") }
222 | #TODO implement ID mapping? e.g. from ENSEMBLID to symbol?
223 |
224 | if (length(genes4integration)/length(ref.var.features)<0.8) {
225 | print("Warning! more than 20% of variable genes not found in the query")
226 | }
227 |
228 | if (direct.projection) {
229 | projected <- query
230 |
231 | print("DIRECTLY projecting query onto Reference PCA space")
232 | query.pca.proj <-apply.pca.obj.2(query, pca.obj=ref@misc$pca_object,
233 | query.assay=query.assay)
234 | projected[["pca"]] <- CreateDimReducObject(embeddings = query.pca.proj,
235 | key = "PC_", assay = query.assay)
236 |
237 | print("DIRECTLY projecting query onto Reference UMAP space")
238 | query.umap.proj <- make.umap.predict(ref.umap=ref@misc$umap_obj,
239 | query.assay=query.assay,
240 | pca.query.emb = query.pca.proj,
241 | fast.umap.predict=fast.umap.predict)
242 | projected[["umap"]] <- CreateDimReducObject(embeddings = query.umap.proj,
243 | key = "UMAP_", assay = query.assay)
244 |
245 | DefaultAssay(projected) <- query.assay
246 | } else {
247 | tryCatch( #Try to do alignment, if it fails (too few cells?) do direct projection
248 | expr = {
249 |
250 | print(paste0("Aligning ", id, " to reference map for batch-correction..."))
251 |
252 | #for compatibility with older versions of STACAS
253 | is_x <- 'min.sample.size' %in% names(formals(FindAnchors.STACAS))
254 |
255 | if (is_x) {
256 | proj.anchors <- FindAnchors.STACAS(object.list = list(ref, query),
257 | assay = c("integrated", query.assay),
258 | anchor.features = genes4integration,
259 | dims = 1:pca.dim, alpha = alpha,
260 | k.anchor = STACAS.k.anchor,
261 | anchor.coverage = STACAS.anchor.coverage,
262 | correction.scale = STACAS.correction.scale,
263 | verbose = FALSE, min.sample.size = 1)
264 | } else {
265 | proj.anchors <- FindAnchors.STACAS(object.list = list(ref, query),
266 | assay = c("integrated", query.assay),
267 | anchor.features = genes4integration,
268 | dims = 1:pca.dim, alpha = alpha,
269 | k.anchor = STACAS.k.anchor,
270 | anchor.coverage = STACAS.anchor.coverage,
271 | correction.scale = STACAS.correction.scale,
272 | verbose = FALSE)
273 | }
274 | #always integrate query into reference
275 | tree <- matrix(c(-1,-2), nrow=1, ncol=2)
276 |
277 | projected <- suppressWarnings(IntegrateData.STACAS(proj.anchors, k.weight = STACAS.k.weight,
278 | dims=1:pca.dim, sample.tree = tree,
279 | features.to.integrate = genes4integration,
280 | verbose = FALSE))
281 |
282 | #Subset query data from integrated space
283 | cells_query <- colnames(query)
284 | projected <- suppressMessages(subset(projected, cells = cells_query))
285 |
286 | projected@meta.data <- query.metadata
287 |
288 | rm(proj.anchors)
289 |
290 | #Make PCA and UMAP projections
291 | cat("\nProjecting corrected query onto Reference PCA space\n")
292 | query.pca.proj <- apply.pca.obj.2(projected,
293 | pca.obj=ref@misc$pca_object,
294 | query.assay="integrated")
295 | projected[["pca"]] <- CreateDimReducObject(embeddings = query.pca.proj, key = "PC_", assay = "integrated")
296 |
297 | cat("\nProjecting corrected query onto Reference UMAP space\n")
298 | query.umap.proj <- make.umap.predict(ref.umap=ref@misc$umap_obj,
299 | pca.query.emb=query.pca.proj,
300 | query.assay="integrated",
301 | fast.umap.predict=fast.umap.predict)
302 | projected[["umap"]] <- CreateDimReducObject(embeddings = query.umap.proj, key = "UMAP_", assay = "integrated")
303 |
304 | DefaultAssay(projected) <- "integrated"
305 | },
306 | error = function(e) {
307 | message(paste("Alignment failed due to:", e, "\n"))
308 | message("Warning: alignment of query dataset failed - Trying direct projection...")
309 | retry.direct <<- TRUE
310 | }
311 | )
312 | if (retry.direct) {
313 | tryCatch( #Try Direct projection
314 | expr = {
315 | projected <- query
316 |
317 | print("DIRECTLY projecting query onto Reference PCA space")
318 | query.pca.proj <- apply.pca.obj.2(query, pca.obj=ref@misc$pca_object,
319 | query.assay=query.assay)
320 | projected[["pca"]] <- CreateDimReducObject(embeddings = query.pca.proj,
321 | key = "PC_", assay = query.assay)
322 |
323 | print("DIRECTLY projecting query onto Reference UMAP space")
324 | query.umap.proj <- make.umap.predict(ref.umap=ref@misc$umap_obj,
325 | pca.query.emb = query.pca.proj,
326 | query.assay=query.assay,
327 | fast.umap.predict=fast.umap.predict)
328 | projected[["umap"]] <- CreateDimReducObject(embeddings = query.umap.proj,
329 | key = "UMAP_", assay = query.assay)
330 |
331 | DefaultAssay(projected) <- query.assay
332 | },
333 | error = function(e) {
334 | message(paste("Direct projection failed due to:", e, "\n"))
335 | message(sprintf("Warning: failed to project dataset %s...", id))
336 | projected <- NULL
337 | }
338 | )
339 | }
340 | }
341 |
342 | if (!is.null(projected)) {
343 | VariableFeatures(projected, assay=query.assay) <- ref.var.features
344 | cellnames <- gsub("^Q_","",colnames(projected)) #remove prefix from cell names
345 | projected <- RenameCells(projected, new.names=cellnames)
346 | }
347 | return(projected)
348 | }
349 |
350 | #Utility to convert Seurat objects from v5 to v3
351 | convert_to_v3 <- function(object, assay="RNA", layer="counts") {
352 |
353 | if (inherits(object[[assay]], "Assay5")) {
354 | if (layer == "data") {
355 | assay_v3 <- CreateAssayObject(
356 | data = object[[assay]]$data
357 | )
358 | } else {
359 | assay_v3 <- CreateAssayObject(
360 | counts = object[[assay]]$counts
361 | )
362 | }
363 | suppressWarnings(object[[assay]] <- assay_v3)
364 | }
365 | object
366 | }
367 |
368 | #calculate Silhouette coefficient between for cells in rows compared to set in columns with same labels
369 | silhouette_2sets <- function(dist, labs.x, labs.y) {
370 |
371 | labs.x <- as.character(labs.x)
372 | labs.y <- as.character(labs.y)
373 |
374 | ids <- sort(unique(c(labs.x, labs.y)))
375 | k <- length(ids)
376 |
377 | if(k <= 1) #must give at least two classes
378 | return(NA)
379 |
380 | if (nrow(dist) != length(labs.x)) {
381 | stop(sprintf("Distance matrix has %i rows but %i row cluster labels are given", nrow(dist), length(labs.x)))
382 | }
383 | if (ncol(dist) != length(labs.y)) {
384 | stop(sprintf("Distance matrix has %i columns but %i column cluster labels are given", ncol(dist), length(labs.y)))
385 | }
386 |
387 | res <- data.frame(matrix(NA, nrow(dist), 2, dimnames = list(rownames(dist), c("cluster","sil_width"))))
388 |
389 | for (j in 1:k) {
390 | lab <- ids[j]
391 | ix <- labs.x == lab
392 | iy <- labs.y == lab
393 |
394 | Nx <- sum(ix)
395 | Ny <- sum(iy)
396 | Ny.n <- sum(!iy)
397 | if (Nx > 1) {
398 | a.i <- rowSums(dist[ix, iy])/Ny
399 | b.i <- rowSums(dist[ix, !iy])/Ny.n
400 |
401 | s.i <- (b.i - a.i) / pmax(b.i, a.i)
402 |
403 | res[ix, "cluster"] <- lab
404 | res[ix,"sil_width"] <- s.i
405 | }
406 | }
407 | res
408 | }
409 |
410 | #Combine labels from two runs of the classifier to return a consensus label and confidence score
411 | combine_labels_and_confidence <- function(labs1, labs2,
412 | labels.col = "functional.cluster",
413 | labels.col.conf = "functional.cluster.conf") {
414 | if (is.null(labs1)) {
415 | return(labs2)
416 | }
417 | if (is.null(labs2)) {
418 | return(labs1)
419 | }
420 | l1 <- labs1[[labels.col]]
421 | names(l1) <- rownames(labs1)
422 | l2 <- labs2[[labels.col]]
423 | names(l2) <- rownames(labs2)
424 | new.labs <- combine_labels(l1, l2)
425 |
426 | c1 <- labs1[[labels.col.conf]]
427 | names(c1) <- rownames(labs1)
428 | c2 <- labs2[[labels.col.conf]]
429 | names(c2) <- rownames(labs2)
430 | new.conf <- combine_confidence(c1, c2)
431 |
432 | new.conf[is.na(new.labs)] <- NA
433 |
434 | comb <- as.data.frame(new.labs)
435 | comb[,2] <- new.conf
436 | colnames(comb) <- c(labels.col, labels.col.conf)
437 | comb
438 | }
439 |
440 | #Combine labels from two runs of the classifier to return a consensus label
441 | combine_labels <- function(labs1, labs2) {
442 |
443 | #No prior labels
444 | if (is.null(labs1)) {
445 | consensus <- labs2
446 | return(consensus)
447 | } else if (is.null(labs2)) {
448 | consensus <- labs1
449 | return(consensus)
450 | }
451 |
452 | #Combine labels
453 | comb <- as.data.frame(labs1)
454 | comb[,"l2"] <- NA
455 | colnames(comb) <- c("l1","l2")
456 |
457 | comb[names(labs2),"l2"] <- labs2
458 |
459 | consensus <- apply(comb, 1, function(x) {
460 | if (is.na(x[["l1"]]) & is.na(x[["l2"]])) {
461 | NA
462 | } else if (is.na(x[["l1"]]) & !is.na(x[["l2"]])) {
463 | x[["l2"]]
464 | } else if (is.na(x[["l2"]]) & !is.na(x[["l1"]])) {
465 | x[["l1"]]
466 | } else if (x[["l1"]] == x[["l2"]]) {
467 | x[["l1"]]
468 | } else {
469 | NA
470 | }
471 | })
472 | return(consensus)
473 | }
474 |
475 | #Combine labels from two runs of the classifier to return a consensus label
476 | combine_confidence <- function(conf1, conf2) {
477 |
478 | #Combine labels
479 | comb <- as.data.frame(conf1)
480 | comb[,"l2"] <- NA
481 | colnames(comb) <- c("l1","l2")
482 |
483 | comb[names(conf2),"l2"] <- conf2
484 |
485 | consensus <- apply(comb, 1, function(x) {
486 | if (is.na(x[["l1"]]) & is.na(x[["l2"]])) {
487 | NA
488 | } else if (is.na(x[["l1"]]) & !is.na(x[["l2"]])) {
489 | x[["l2"]]
490 | } else if (is.na(x[["l2"]]) & !is.na(x[["l1"]])) {
491 | x[["l1"]]
492 | } else {
493 | (x[["l1"]] + x[["l2"]])/2
494 | }
495 | })
496 | return(consensus)
497 | }
498 |
499 | #Run ProjecTILs.classifier on a single object
500 | classifier.singleobject <- function(query,
501 | ref=NULL,
502 | filter.cells = TRUE,
503 | reduction="pca",
504 | ndim=NULL, k=5,
505 | nn.decay=0.1,
506 | min.confidence=0.2,
507 | labels.col="functional.cluster",
508 | overwrite=TRUE,
509 | ncores=1,
510 | ...) {
511 | #UMAP emb. only needed if we want to predict labels based on UMAP neighbors
512 | if (reduction=="umap") {
513 | fast.umap.predict <- FALSE
514 | } else {
515 | fast.umap.predict <- TRUE
516 | }
517 |
518 | if(is.list(query)) {
519 | stop("Query must be a single Seurat object")
520 | }
521 | labels.col.conf <- paste0(labels.col, ".conf")
522 |
523 | current.labs <- NULL
524 | if (labels.col %in% colnames(query[[]])) {
525 | current.labs <- query[[c(labels.col, labels.col.conf)]]
526 | }
527 |
528 | query <- make.projection(query=query, ref=ref, filter.cells=filter.cells,
529 | fast.umap.predict = fast.umap.predict, ncores=ncores, ...)
530 |
531 | query <- cellstate.predict(ref=ref, query=query,
532 | reduction=reduction,
533 | ndim=ndim, k=k,
534 | nn.decay=nn.decay,
535 | min.confidence=min.confidence,
536 | labels.col = labels.col)
537 |
538 | #Extract new labels and combine (or overwrite) old labels
539 | labs <- query[[c(labels.col,labels.col.conf)]]
540 |
541 | if (overwrite) {
542 | new.labs <- labs
543 | } else {
544 | new.labs <- combine_labels_and_confidence(current.labs, labs,
545 | labels.col, labels.col.conf)
546 | }
547 | return(new.labs)
548 | }
549 |
550 | #Set parallelization options
551 | set_parall <- function(ncores, progressbar=FALSE) {
552 | if (ncores == 1) {
553 | param <- SerialParam(progressbar = progressbar)
554 | } else if (.Platform$OS.type == "windows") {
555 | param <- SnowParam(workers=ncores, progressbar = progressbar)
556 | } else {
557 | param <- MulticoreParam(workers=ncores, progressbar = progressbar)
558 | }
559 | return(param)
560 | }
561 |
562 |
563 | # helper to load rds reference maps
564 | # reference should be a path to a.rds object or a URL to a .rds object, storing a Seurat object prepared using \link{make.reference}
565 | load.helper <- function(reference){
566 | tryCatch(ref <- readRDS(reference),
567 | error = function(e){
568 | stop(paste("Reference object",reference,"is invalid"))
569 | })
570 | tryCatch(print(paste0("Loaded Custom Reference map ",ref@misc$projecTILs)),
571 | error = function(e){stop("Invalid Reference object.\nConsider increasing downloading timeout running:\n `options(timeout = 1000)`\n")
572 | })
573 | return(ref)
574 | }
575 |
576 |
577 | # function to fetch the metadata of figshare entries
578 | get_figshare_metadata <- function(article_id) {
579 |
580 | url <- paste0("https://api.figshare.com/v2/articles/",
581 | article_id)
582 |
583 | # Make the HTTP GET request
584 | response <- readLines(url,
585 | warn = "F",
586 | encoding = "UTF-8")
587 |
588 | # Parse the JSON response
589 | metadata <- jsonlite::fromJSON(paste(response, collapse = ""))
590 |
591 | # get only url and md5 data
592 | df <- as.data.frame(metadata$files)
593 |
594 | return(df)
595 | }
596 |
597 | # function to donwload object form a url and check integrity
598 | download_integrity <- function(url,
599 | destfile,
600 | hash = NULL,
601 | quiet = F){
602 | r <- TRUE
603 |
604 | tryCatch({
605 | download.file(url,
606 | destfile = destfile,
607 | mode = "wb",
608 | quiet = quiet)
609 | }, error = function(e){
610 | r <<- FALSE
611 | file.remove(destfile)
612 | cat("Download failed for ", destfile,
613 | "\n Consider increasing downloading timeout running: `options(timeout = 1000)`\n")
614 |
615 |
616 | }
617 | )
618 |
619 | if(r && !is.null(hash)){
620 | # check file integrity
621 | downloaded_hash <- digest::digest(file = destfile)
622 | # return if file integrity check passed
623 | if(downloaded_hash == hash){
624 | r <- TRUE
625 | } else {
626 | r <- FALSE
627 | }
628 | }
629 |
630 | return(r)
631 | }
632 |
633 | # function to handle errors during downloading
634 | try.download <- function(url,
635 | destfile,
636 | hash = NULL,
637 | verbose = TRUE,
638 | # whether stop function or trown warning upon failing
639 | warn = FALSE){
640 |
641 |
642 | file_integrity <- download_integrity(url = url,
643 | destfile = destfile,
644 | hash = hash,
645 | quiet = !verbose)
646 | if(!file_integrity){
647 | message("File ", destfile, " did not pass integrity check. Redownloading file\nConsider increasing downloading timeout running:\n `options(timeout = 1000)`\n")
648 | file_integrity <- download_integrity(url = url,
649 | destfile = destfile,
650 | hash = hash,
651 | quiet = !verbose)
652 | }
653 |
654 | if(!file_integrity){
655 | if(warn){
656 | cat("File ", destfile, " did not pass integrity check!!\nConsider increasing downloading timeout running:\n `options(timeout = 1000)`\n")
657 | } else {
658 | stop("File ", destfile, " did not pass integrity check!!\nConsider increasing downloading timeout running:\n `options(timeout = 1000)`\n")
659 | }
660 | }
661 |
662 | }
663 |
664 |
665 |
666 |
667 |
668 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # A framework for reference-based single-cell RNA-seq data analysis
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | `ProjecTILs` is a computational method to project scRNA-seq data into reference single-cell atlases, enabling their direct comparison in a stable, annotated system of coordinates.
10 |
11 | In contrast to other methods, ProjecTILs allows not only accurately embedding new scRNA-seq data into a reference without altering its structure, but also characterizing previously unknown cell states that "deviate" from the reference. ProjecTILs accurately predicts the effects of cell perturbations and identifies gene programs that are altered in different conditions and tissues.
12 |
13 | You can use `ProjecTILs` pre-defined cell type-specific [reference maps](#reference-atlases) or create your own (see [Building a custom reference atlas for ProjecTILs](https://carmonalab.github.io/ProjecTILs.demo/build_ref_atlas.html)) for any cell type[s] of interest.
14 |
15 | For real-life applications, check out our list of [ProjecTILs Case Studies](https://carmonalab.github.io/ProjecTILs_CaseStudies/)
16 |
17 | Find the installation instructions for the package below, and a vignette detailing its functions at [Tutorial (html)](https://carmonalab.github.io/ProjecTILs.demo/tutorial.html) and [Tutorial (repository)](https://github.com/carmonalab/ProjecTILs.demo)
18 |
19 | ### Package Installation
20 |
21 | To install `ProjecTILs` directly from its Git repository, run the following code from within R or RStudio:
22 |
23 | ``` r
24 | install.packages("remotes")
25 | library(remotes)
26 |
27 | remotes::install_github("carmonalab/STACAS")
28 | remotes::install_github("carmonalab/ProjecTILs")
29 | ```
30 |
31 | ### Test the package
32 |
33 | Load sample data and test your installation:
34 |
35 | ``` r
36 | library(ProjecTILs)
37 | ref <- load.reference.map()
38 | data(query_example_seurat)
39 |
40 | query.projected <- Run.ProjecTILs(query_example_seurat, ref=ref)
41 | ```
42 |
43 | By default, `load.reference.map()` downloads and loads a reference for mouse tumor-infiltrating T cells. Read below where to find other references or how to build your own reference map.
44 |
45 | ### Data projection DEMO
46 |
47 | Find a step-by-step tutorial for `ProjecTILs` at: [ProjecTILs tutorial](https://carmonalab.github.io/ProjecTILs.demo/tutorial.html)
48 |
49 | ### Running ProjecTILs
50 |
51 | You can use ProjecTILs in two modes:
52 |
53 | **Mode 1:** just for label transfer, faster, doesn't alter your dimensionality reduction
54 |
55 | ``` r
56 | ProjecTILs.classifier(query = query_object, ref = reference_map)
57 | ```
58 |
59 | **Mode 2:** reference embedding, to explore your dataset in the context of a stable reference map
60 |
61 | ``` r
62 | Run.ProjecTILs(query = query_object, ref = reference_map)
63 | ```
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 | **Note:** ProjecTILs performs cell state quantifications in the PCA latent space. UMAP embeddings are provided for visual exploration only and should be interpreted with caution as cell-cell distances and densities in UMAP are highly distorted (see e.g. [Chari and Pachter (2023)](https://doi.org/10.1371/journal.pcbi.1011288))
72 |
73 | ### ProjecTILs CASE STUDIES
74 |
75 | For real-life applications on public datasets, check out our list of [ProjecTILs Case Studies](https://carmonalab.github.io/ProjecTILs_CaseStudies/)
76 |
77 | ### Documentation
78 |
79 | See a description of the functions implemented in ProjecTILs at: [ProjecTILs functions](docs/functions.md)
80 |
81 | ### Reference Maps
82 |
83 | Reference atlases are generated by comprehensive scRNA-seq multi-study integration and curation, and describe reference cell subtypes in a specific biological context.
84 |
85 | Currently available atlases:
86 |
87 | - **human CD8+ TIL atlas**: consists of 11,021 high-quality single-cell transcriptomes from 20 samples covering 7 tumor types. Generated from the collection of datasets found at N. Borcherding's [utility](https://github.com/ncborcherding/utility). Available at: and interactively at:
88 |
89 | - **human CD4+ TIL atlas**: consists of 12,631 high-quality single-cell transcriptomes from 20 samples covering 9 tumor types. Generated from the collection of datasets by [Zheng et al. Science 2021](https://www.science.org/doi/10.1126/science.abe6474). Available at: and interactively at:
90 |
91 | - **human blood and tumor-infiltrating DC atlas**: consists of 18,753 high-quality single-cell transcriptomes from 11 studies covering 5 tumor types and healthy patient for blood. Generated from the collection of datasets by [Gerhard et al. JEM, 2020](https://pubmed.ncbi.nlm.nih.gov/33601412/) and [Villani et al. Science 2017](https://pubmed.ncbi.nlm.nih.gov/28428369/) for the blood samples. Available at: and interactively at:
92 |
93 | - **mouse TIL atlas**: consists of 16,803 single-cell transcriptomes from 25 samples (B16 melanoma and MC38 colon adenocarcinoma tumors) from six different studies. Available at: and interactively at:
94 |
95 | - **mouse acute and chronic viral infection CD8 T cell atlas**: consists of 7,000 virus-specific CD8 T cells from 12 samples (spleen) from different timepoints (day 4.5, day 7/8 and day 30) from mice infected with lymphocytic choriomeningitis virus (LCMV) Arm (acute infection) or cl13 (chronic infection) strains. Available at: and interactively at:
96 |
97 | - **mouse acute and chronic viral infection CD4 T cell atlas**: consists of over 35,000 high-quality virus-specific (GP66:I-Ab+) CD4 T cells from 11 samples (spleen) from different timepoints following LCMV Armstrong or Clone 13 viral infection (7 or 21 days after Clone 13 infection, and 7, 21 and \>60 days after LCMV Armstrong infection). Available at: and interactively at:
98 |
99 | ### Custom Reference Maps
100 |
101 | If you wish to use your own **custom reference atlas**, we recommend to use [STACAS](https://github.com/carmonalab/STACAS) for single-cell data integration. Here is an example: [Building a custom reference atlas for ProjecTILs](https://carmonalab.github.io/ProjecTILs.demo/build_ref_atlas.html).
102 |
103 | ### Updating of reference map to include new cell states
104 |
105 | After projection, one may want to incorporate the projected data into an "updated" reference. To recalculate the embeddings of a reference to account for new, projected data, use:
106 |
107 | ``` r
108 | new_reference <- recalculate.embeddings( ref = old_reference, projected = projected_object )
109 | ```
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 | See an example in the following [workflow section](https://carmonalab.github.io/ProjecTILs_CaseStudies/novelstate.html#recalculate-map-with-novel-state).
118 |
119 | ### SPICA online portal
120 |
121 | You can now explore our atlases interactively and project your data through the [SPICA web portal](https://spica.unil.ch/). Find some tutorials for interacting with SPICA at
122 |
123 | ### Troubleshooting
124 |
125 | - If *load.reference.map()* fails with error "Reference object X is invalid" the first time you run it; it is likely that reference atlas download has failed due to Timeout. Try setting `options(timeout = 3000)` to increase download Timeout.
126 |
127 | - If a warning message prevented *remotes* from installing the package, try:
128 |
129 | ``` sys.setenv(r_remotes_no_errors_from_warnings="true")```
130 |
131 | * For analyzing datasets composed of multiple batches (e.g. different subjects, technologies), we recommend projecting each batch separately, by providing ProjecTILs a list of Seurat objects as input, e.g.:
132 | ```r
133 | data.seurat.list <- SplitObject(data.seurat, split.by = "batch")
134 | query.projected.list <- make.projection(data.seurat.list)
135 | ```
136 |
137 | ### Citation
138 |
139 | **Interpretation of T cell states from single-cell transcriptomics data using reference atlases** Massimo Andreatta, Jesus Corria-Osorio, Soren Muller, Rafael Cubas, George Coukos, Santiago J Carmona. *Nature Communications* **12** Article number: 2965 (2021) -
140 |
141 |
142 |
143 |
144 |
145 |
146 |
--------------------------------------------------------------------------------
/data/Hs2Mm.convert.table.RData:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/carmonalab/ProjecTILs/8bf4f8882bccca4ad8d927548bcf5493a4bb415e/data/Hs2Mm.convert.table.RData
--------------------------------------------------------------------------------
/data/cell.cycle.obj.RData:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/carmonalab/ProjecTILs/8bf4f8882bccca4ad8d927548bcf5493a4bb415e/data/cell.cycle.obj.RData
--------------------------------------------------------------------------------
/data/query_example_seurat.RData:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/carmonalab/ProjecTILs/8bf4f8882bccca4ad8d927548bcf5493a4bb415e/data/query_example_seurat.RData
--------------------------------------------------------------------------------
/docs/CSI_Toolkit.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/carmonalab/ProjecTILs/8bf4f8882bccca4ad8d927548bcf5493a4bb415e/docs/CSI_Toolkit.png
--------------------------------------------------------------------------------
/docs/Proj_modes.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/carmonalab/ProjecTILs/8bf4f8882bccca4ad8d927548bcf5493a4bb415e/docs/Proj_modes.png
--------------------------------------------------------------------------------
/docs/RSticker_ProjecTILS.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/carmonalab/ProjecTILs/8bf4f8882bccca4ad8d927548bcf5493a4bb415e/docs/RSticker_ProjecTILS.png
--------------------------------------------------------------------------------
/docs/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-cayman
--------------------------------------------------------------------------------
/docs/functions.md:
--------------------------------------------------------------------------------
1 | # ProjecTILs - Functions
2 |
3 | * `load.reference.map` Load or download the reference map for dataset projection. By the default it downloads the reference atlas of tumour-infiltrating lymphocytes (TILs).
4 |
5 | * `read.sc.query` Load a query expression matrix to be projected onto the reference atlas. Several formats (10x, hdf5, raw and log counts, etc.) are supported - see type parameter for details
6 |
7 | * `Run.ProjecTILs` A wrapper for `make.projection` and `cellstate.predict` (see below). It returns the query embedded in the PCA and UMAP space of the reference, and predict cell state labels for the query cells.
8 |
9 | * `ProjecTILs.classifier` Similarly to `Run.ProjecTILs`, it perform reference projection and cell state prediction. However, the query embeddings are left intact and only cell state labels are returned. Useful if you wish to use ProjecTILs as a classifier and annotate your data in their native space.
10 |
11 | * `make.projection` Project a single-cell RNA-seq dataset onto a reference map of cellular states.
12 |
13 | * `celltype.heatmap` Generate a averaged gene expression heatmap from a Seurat object
14 |
15 | * `plot.projection` Plots the UMAP representation of the reference map, together with the projected coordinates of a query dataset.
16 |
17 | * `cellstate.predict` Use a nearest-neighbor algorithm to predict a feature (e.g. the cell state) of the query cells.
18 |
19 | * `plot.statepred.composition` Makes a barplot of the frequency of cell states in a query object.
20 |
21 | * `plot.states.radar` Makes a radar plot of the expression level of a specified set of genes.
22 |
23 | * `find.discriminant.dimensions` Searches PCA or ICA dimensions where the query set deviates the most from a control set or from the reference map.
24 |
25 | * `plot.discriminant.3d` Add an extra dimension to the reference map to explore additional axes of variability in a query dataset compared to the reference map.
26 |
27 | * `find.discriminant.genes` Performs differential expression analysis between a projected query and a control (either the reference map or a control sample), for
28 | a selected reference subtype. Useful to detect whether specific cell states over/under-express genes between conditions or with respect to the reference.
29 |
30 | * `make.reference` Converts a Seurat object into a custom reference map for ProjecTILs.
31 |
32 | * `recalculate.embeddings` After projection of query data into a reference, you may want to recalculate the low-dimensional embeddings accounting for the new data. The resulting object can be used as a new reference.
33 |
34 | * `merge.Seurat.embeddings` Given two Seurat objects, merge counts and data as well as dim reductions (PCA, UMAP, ICA, etc.)
35 |
36 | * `compute_silhouette` Given a projected object and its reference, calculate silhouette coefficient for query cells with respect to reference cells with the same cell labels.
37 |
38 | Find more information, syntax and examples using the R help function e.g. `?Run.ProjecTILs`
39 |
40 |
--------------------------------------------------------------------------------
/docs/projectils_logo_B_square.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/carmonalab/ProjecTILs/8bf4f8882bccca4ad8d927548bcf5493a4bb415e/docs/projectils_logo_B_square.png
--------------------------------------------------------------------------------
/docs/projectils_logo_W_square.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/carmonalab/ProjecTILs/8bf4f8882bccca4ad8d927548bcf5493a4bb415e/docs/projectils_logo_W_square.png
--------------------------------------------------------------------------------
/docs/recalc_embeddings.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/carmonalab/ProjecTILs/8bf4f8882bccca4ad8d927548bcf5493a4bb415e/docs/recalc_embeddings.png
--------------------------------------------------------------------------------
/inst/extdata/reference_links.R:
--------------------------------------------------------------------------------
1 | # List of of reference atlaases links
2 |
3 | rl <- data.frame(collection.CSI = c("human",
4 | "human",
5 | "human",
6 | "human",
7 | "mouse",
8 | "mouse",
9 | "mouse"
10 | ),
11 | reference.atlas = c("CD4",
12 | "CD8",
13 | "DC",
14 | "MoMac",
15 | "Virus_CD4T",
16 | "Virus_CD8T",
17 | "TILs"
18 | ),
19 | name = c("sketched_CD4T_human_ref_v2.rds",
20 | "sketched_CD8T_human_ref_v1.rds",
21 | "sketched_DC_human_ref_v2.rds",
22 | "sketched_MoMac_human_v1.rds",
23 | "ref_LCMV_CD4_mouse_release_v1.rds",
24 | "ref_CD8_LCMV_mouse_v2.rds",
25 | "ref_TILAtlas_mouse_v1.rds"
26 | ),
27 | figshare_id = c("26310994",
28 | "26310994",
29 | "26310994",
30 | "26310994",
31 | "16592693",
32 | "23764572",
33 | "12478571"
34 | )
35 | )
36 |
37 | inst.dir <- "inst/extdata"
38 | dir.create(inst.dir,
39 | recursive = T)
40 |
41 | utils::write.table(rl,
42 | file.path(inst.dir, "reference_links.csv"),
43 | sep = ",",
44 | quote = F,
45 | row.names = F)
46 |
--------------------------------------------------------------------------------
/inst/extdata/reference_links.csv:
--------------------------------------------------------------------------------
1 | collection.CSI,reference.atlas,name,figshare_id
2 | human,CD4,sketched_CD4T_human_ref_v2.rds,26310994
3 | human,CD8,sketched_CD8T_human_ref_v1.rds,26310994
4 | human,DC,sketched_DC_human_ref_v2.rds,26310994
5 | human,MoMac,sketched_MoMac_human_v1.rds,26310994
6 | mouse,Virus_CD4T,ref_LCMV_CD4_mouse_release_v1.rds,16592693
7 | mouse,Virus_CD8T,ref_CD8_LCMV_mouse_v2.rds,23764572
8 | mouse,TILs,ref_TILAtlas_mouse_v1.rds,12478571
9 |
--------------------------------------------------------------------------------
/man/FindAllMarkers.bygroup.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{FindAllMarkers.bygroup}
4 | \alias{FindAllMarkers.bygroup}
5 | \title{Gene expression markers shared by multiple groups of cells}
6 | \usage{
7 | FindAllMarkers.bygroup(
8 | object,
9 | split.by = NULL,
10 | only.pos = TRUE,
11 | features = NULL,
12 | min.cells.group = 10,
13 | min.freq = 0.5,
14 | ...
15 | )
16 | }
17 | \arguments{
18 | \item{object}{A Seurat object}
19 |
20 | \item{split.by}{A metadata column name - the data will be split by this column to calculate \link[Seurat]{FindAllMarkers}
21 | separately for each data split}
22 |
23 | \item{only.pos}{Only return positive markers (TRUE by default)}
24 |
25 | \item{features}{Genes to test. Default is to use all genes}
26 |
27 | \item{min.cells.group}{Minimum number of cells in the group - if lower the group is skipped}
28 |
29 | \item{min.freq}{Only return markers which are differentially expressed in at least this fraction of datasets.}
30 |
31 | \item{...}{Additional paramters to \link[Seurat]{FindAllMarkers}}
32 | }
33 | \value{
34 | A list of marker genes for each identity class (typically clusters), with two associated numerical values:
35 | i) the fraction of datasets for which the marker was found to be differentially expressed; ii) the
36 | average log-fold change for the genes across datasets
37 | }
38 | \description{
39 | This function expands \link[Seurat]{FindAllMarkers} to find markers that are differentially expressed across multiple
40 | datasets or samples. Given a Seurat object with identity classes (for example annotated clusters) and a grouping
41 | variable (for example a Sample ID), it calculate differentially expressed genes (DEGs) individually for each sample.
42 | Then it determines the fraction of samples for which the gene was found to be differentially expressed.
43 | }
44 | \details{
45 | This function can be useful to find marker genes that are specific for individual cell types, and that are found
46 | to be so consistently across multiple samples.
47 | }
48 | \examples{
49 | \dontshow{if (interactive()) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
50 | library(Seurat)
51 | ref <- load.reference.map(ref = "https://figshare.com/ndownloader/files/38921366")
52 | Idents(ref) <- "functional.cluster"
53 | FindAllMarkers.bygroup(ref, split.by = "Sample", min.cells.group=30, min.freq=0.8)
54 | \dontshow{\}) # examplesIf}
55 | }
56 |
--------------------------------------------------------------------------------
/man/Hs2Mm.convert.table.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/datasets.R
3 | \docType{data}
4 | \name{Hs2Mm.convert.table}
5 | \alias{Hs2Mm.convert.table}
6 | \title{Human-mouse ortholog conversion table}
7 | \format{
8 | A dataframe containing gene ortholog mapping.
9 | }
10 | \source{
11 | \url{https://www.ensembl.org/Mus_musculus/Info/Index}
12 | }
13 | \usage{
14 | Hs2Mm.convert.table
15 | }
16 | \description{
17 | A conversion table of stable orthologs between Hs and Mm.
18 | }
19 | \keyword{datasets}
20 |
--------------------------------------------------------------------------------
/man/ProjecTILs.classifier.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{ProjecTILs.classifier}
4 | \alias{ProjecTILs.classifier}
5 | \title{Annotate query dataset using a reference object}
6 | \usage{
7 | ProjecTILs.classifier(
8 | query,
9 | ref = NULL,
10 | filter.cells = TRUE,
11 | split.by = NULL,
12 | reduction = "pca",
13 | ndim = NULL,
14 | k = 5,
15 | nn.decay = 0.1,
16 | min.confidence = 0.2,
17 | labels.col = "functional.cluster",
18 | overwrite = TRUE,
19 | ncores = 1,
20 | ...
21 | )
22 | }
23 | \arguments{
24 | \item{query}{Query data, either as single Seurat object or as a list of Seurat object}
25 |
26 | \item{ref}{Reference Atlas - if NULL, downloads the default TIL reference atlas}
27 |
28 | \item{filter.cells}{Pre-filter cells using `scGate`. Only set to FALSE if the dataset has
29 | been previously subset to cell types represented in the reference.}
30 |
31 | \item{split.by}{Grouping variable to split the query object (e.g. if the object contains multiple samples)}
32 |
33 | \item{reduction}{The dimensionality reduction used to assign cell type labels}
34 |
35 | \item{ndim}{The number of dimensions used for cell type classification}
36 |
37 | \item{k}{Number of neighbors for cell type classification}
38 |
39 | \item{nn.decay}{Weight decay for internal nearest neighbors (between 0 and 1)}
40 |
41 | \item{min.confidence}{Minimum confidence score to return cell type labels (otherwise NA)}
42 |
43 | \item{labels.col}{The metadata field with label annotations of the reference, which will
44 | be transferred to the query dataset}
45 |
46 | \item{overwrite}{Replace any existing labels in \code{labels.col} with new labels.
47 | This may be useful for predicting cell types using multiple reference maps; run
48 | this function with \code{overwrite=FALSE} to combine existing labels
49 | with new labels from a second reference map.}
50 |
51 | \item{ncores}{Number of cores for parallel processing}
52 |
53 | \item{...}{Additional parameters to \link[ProjecTILs]{make.projection}}
54 | }
55 | \value{
56 | The query object with a additional metadata columns containing predicted cell labels
57 | and confidence scores for the predicted cell labels
58 | If cells were filtered prior to projection, they will be labeled as 'NA'
59 | }
60 | \description{
61 | Apply label transfer to annotate a query dataset with the cell types of a reference object.
62 | Compared to \link{Run.ProjecTILs}, only cell labels are returned. The low-dim embeddings of
63 | the query object (PCA, UMAP) are not modified.
64 | }
65 | \details{
66 | See \link{load.reference.map} to load or download a reference atlas.
67 | See \link{Run.ProjecTILs} to embed the query in the same space of the reference
68 | }
69 | \examples{
70 | \dontrun{
71 | data(query_example_seurat)
72 | ref <- load.reference.map()
73 | q <- ProjecTILs.classifier(query_example_seurat, ref=ref)
74 | table(q$functional.cluster, useNA="ifany")
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/man/Run.ProjecTILs.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{Run.ProjecTILs}
4 | \alias{Run.ProjecTILs}
5 | \title{Project a query scRNA-seq dataset onto a reference atlas}
6 | \usage{
7 | Run.ProjecTILs(
8 | query,
9 | ref = NULL,
10 | filter.cells = TRUE,
11 | split.by = NULL,
12 | reduction = "pca",
13 | ndim = NULL,
14 | k = 5,
15 | nn.decay = 0.1,
16 | min.confidence = 0.2,
17 | labels.col = "functional.cluster",
18 | ...
19 | )
20 | }
21 | \arguments{
22 | \item{query}{Query data, either as single Seurat object or as a list of Seurat object}
23 |
24 | \item{ref}{Reference Atlas - if NULL, downloads the default TIL reference atlas}
25 |
26 | \item{filter.cells}{Pre-filter cells using `scGate`. Only set to FALSE if the dataset has
27 | been previously subset to cell types represented in the reference.}
28 |
29 | \item{split.by}{Grouping variable to split the query object (e.g. if the object contains multiple samples)}
30 |
31 | \item{reduction}{The dimensionality reduction used to assign cell type labels, based on
32 | majority voting of nearest neighbors between reference and query.}
33 |
34 | \item{ndim}{The number of dimensions used for cell type classification}
35 |
36 | \item{k}{Number of neighbors for cell type classification}
37 |
38 | \item{nn.decay}{Weight decay for internal nearest neighbors (between 0 and 1)}
39 |
40 | \item{min.confidence}{Minimum confidence score to return cell type labels (otherwise NA)}
41 |
42 | \item{labels.col}{The metadata field of the reference to annotate the clusters}
43 |
44 | \item{...}{Additional parameters to \link[ProjecTILs]{make.projection}}
45 | }
46 | \value{
47 | An augmented Seurat object with projected UMAP coordinates on the reference map and cell classifications
48 | }
49 | \description{
50 | This function allows projecting ("query") single-cell RNA-seq datasets onto a reference map
51 | (i.e. a curated and annotated scRNA-seq dataset).
52 | To project multiple datasets, submit a list of Seurat objects with the query parameter.
53 | The projection consists of 3 steps:
54 | \itemize{
55 | \item{pre-processing: optional steps which might include pre-filtering of cells by markers using `scGate`,
56 | data normalization, and ortholog conversion.}
57 | \item{batch-effect correction: uses built-in STACAS algorithm to detect and correct for batch effects
58 | (this step assumes that at least a fraction of the cells in the query are in the same state than cells in
59 | the reference)}
60 | \item{embedding of corrected query data in the reduced-dimensionality spaces (PCA and UMAP) of the reference map.}
61 | }
62 | This function acts as a wrapper for \link{make.projection} and \link{cellstate.predict}
63 | }
64 | \details{
65 | See \link{load.reference.map} to load or download a reference atlas. See
66 | also \link{ProjecTILs.classifier} to use ProjecTILs as a cell type classifier.
67 | }
68 | \examples{
69 | \dontshow{if (interactive()) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
70 | data(query_example_seurat)
71 | ref <- load.reference.map()
72 | q <- Run.ProjecTILs(query_example_seurat, ref=ref, fast.umap.predict=TRUE)
73 | plot.projection(ref=ref, query=q)
74 | \dontshow{\}) # examplesIf}
75 | }
76 |
--------------------------------------------------------------------------------
/man/cell.cycle.obj.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/datasets.R
3 | \docType{data}
4 | \name{cell.cycle.obj}
5 | \alias{cell.cycle.obj}
6 | \title{Cell cycling signatures}
7 | \format{
8 | A list of cycling signatures.
9 | }
10 | \source{
11 | \doi{10.1126/science.aad0501}
12 | }
13 | \usage{
14 | cell.cycle.obj
15 | }
16 | \description{
17 | A list of cell cycling signatures (G1.S and G2.M phases),
18 | for mouse and human.
19 | }
20 | \keyword{datasets}
21 |
--------------------------------------------------------------------------------
/man/cellstate.predict.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{cellstate.predict}
4 | \alias{cellstate.predict}
5 | \title{Predict cell states of a projected dataset}
6 | \usage{
7 | cellstate.predict(
8 | ref,
9 | query,
10 | reduction = "pca",
11 | ndim = NULL,
12 | k = 5,
13 | min.confidence = 0.2,
14 | nn.decay = 0.1,
15 | labels.col = "functional.cluster"
16 | )
17 | }
18 | \arguments{
19 | \item{ref}{Reference Atlas}
20 |
21 | \item{query}{Seurat object with query data}
22 |
23 | \item{reduction}{The dimensionality reduction used to calculate pairwise distances. One of "pca" or "umap"}
24 |
25 | \item{ndim}{How many dimensions in the reduced space to be used for distance calculations}
26 |
27 | \item{k}{Number of neighbors to assign the cell type}
28 |
29 | \item{min.confidence}{Minimum confidence score to return cell type labels (otherwise NA)}
30 |
31 | \item{nn.decay}{Weight decay for internal nearest neighbors (between 0 and 1)}
32 |
33 | \item{labels.col}{The metadata field of the reference to annotate the clusters (default: functional.cluster)}
34 | }
35 | \value{
36 | The query object submitted as parameter, with two additional metadata slots for predicted state and its confidence score
37 | }
38 | \description{
39 | This function uses a nearest-neighbor algorithm to predict a feature (e.g. the cell state) of the query cells. Distances between
40 | cells in the reference map and cells in the query are calculated in a reduced space (PCA or UMAP) and the feature is assigned to
41 | query cells based on a consensus of its nearest neighbors in the reference object.
42 | }
43 | \examples{
44 | \dontshow{if (interactive()) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
45 | data(query_example_seurat)
46 | ref <- load.reference.map()
47 | q <- make.projection(query_example_seurat, ref=ref)
48 | q <- cellstate.predict(ref, query=q)
49 | table(q$functional.cluster)
50 | \dontshow{\}) # examplesIf}
51 | }
52 |
--------------------------------------------------------------------------------
/man/celltype.heatmap.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{celltype.heatmap}
4 | \alias{celltype.heatmap}
5 | \title{Plot a averaged expression heatmap from a Seurat object}
6 | \usage{
7 | celltype.heatmap(
8 | data,
9 | assay = "RNA",
10 | slot = "data",
11 | genes,
12 | ref = NULL,
13 | scale = "row",
14 | method = c("ward.D2", "ward.D", "average"),
15 | brewer.palette = "RdBu",
16 | palette_reverse = F,
17 | palette = NULL,
18 | cluster.col = "functional.cluster",
19 | group.by = NULL,
20 | flip = FALSE,
21 | cluster_genes = FALSE,
22 | cluster_samples = FALSE,
23 | min.cells = 10,
24 | show_samplenames = FALSE,
25 | remove.NA.meta = TRUE,
26 | breaks = seq(-2, 2, by = 0.1),
27 | return.matrix = FALSE,
28 | ...
29 | )
30 | }
31 | \arguments{
32 | \item{data}{A Seurat object to be used for the heatmap}
33 |
34 | \item{assay}{A string indicating the assay type, default is "RNA"}
35 |
36 | \item{slot}{Data slot (layer) in Seurat object}
37 |
38 | \item{genes}{A vector of genes to be used in the heatmap}
39 |
40 | \item{ref}{A ProjecTILs reference Seurat object to define the order of functional.cluster}
41 |
42 | \item{scale}{A string indicating the scale of the heatmap, default is "row"}
43 |
44 | \item{method}{A string or vector of strings indicating the clustering method to be used, default is "ward.D2"}
45 |
46 | \item{brewer.palette}{A string indicating the color palette to be used, default is "RdBu"}
47 |
48 | \item{palette_reverse}{A boolean indicating if color palette should be reversed, default is FALSE}
49 |
50 | \item{palette}{A named list containing colors vectors compatible with pheatmap. The list is named by the metadata names, default is taking these palettes to plot metadata: "Paired","Set2","Accent","Dark2","Set1","Set3".}
51 |
52 | \item{cluster.col}{The metadata column name containing the cell type labels}
53 |
54 | \item{group.by}{The metadata column names used as grouping variables}
55 |
56 | \item{flip}{A boolean indicating if the heatmap should be flipped, default is FALSE}
57 |
58 | \item{cluster_genes}{A boolean indicating if genes should be clustered, default is FALSE}
59 |
60 | \item{cluster_samples}{A boolean indicating if samples should be clustered, default is FALSE}
61 |
62 | \item{min.cells}{A value defining the minimum number of cells a sample should have to be kept, default is 10}
63 |
64 | \item{show_samplenames}{A boolean indicating whether the heatmap should display the sample names or not, default is FALSE}
65 |
66 | \item{remove.NA.meta}{A boolean indicating if missing samples with missing metadata should be plotted, default is TRUE}
67 |
68 | \item{breaks}{Range of values for plotting (see 'breaks' parameter in pheatmap)}
69 |
70 | \item{return.matrix}{If true, return the pseudo-bulk data matrix instead of graphical output}
71 |
72 | \item{...}{Additional parameters for 'pheatmap'}
73 | }
74 | \value{
75 | A pheatmap plot, displaying averaged expression values across genes for each selected genes and samples.
76 | }
77 | \description{
78 | This function allows to calculate and plot pseudo-bulk gene expression by cell type and
79 | custom grouping variables. Data can be split in principle by any metadata present in the
80 | starting Seurat object (e.g. patient, tissue, study, etc.). This can be useful to evaluate
81 | consistency of expression profiles for different cell types across samples, studies or
82 | other grouping variables.
83 | }
84 | \examples{
85 | \dontshow{if (interactive()) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
86 | library(Seurat)
87 | ref <- load.reference.map(ref = "https://figshare.com/ndownloader/files/38921366")
88 | celltype.heatmap(ref, assay = "RNA", genes = c("LEF1","SELL","GZMK","FGFBP2"),
89 | ref = ref, cluster.col = "functional.cluster", group.by = c("orig.ident", "Tissue"))
90 | \dontshow{\}) # examplesIf}
91 | }
92 |
--------------------------------------------------------------------------------
/man/compute_silhouette.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{compute_silhouette}
4 | \alias{compute_silhouette}
5 | \title{Calculate Silhouette coefficient}
6 | \usage{
7 | compute_silhouette(
8 | ref,
9 | query = NULL,
10 | reduction = "pca",
11 | ndim = NULL,
12 | label_col = "functional.cluster",
13 | normalize.scores = FALSE,
14 | min.cells = 20
15 | )
16 | }
17 | \arguments{
18 | \item{ref}{Reference object}
19 |
20 | \item{query}{Query object. If not specified, the silhouette coefficient of only the reference will be calculated}
21 |
22 | \item{reduction}{Which dimensionality reduction to use for euclidian distance calculation}
23 |
24 | \item{ndim}{Number of dimensions in the dimred to use for distance calculation. If NULL, use all dimensions.}
25 |
26 | \item{label_col}{Metadata column with cell type annotations. Must be present both in reference and query}
27 |
28 | \item{normalize.scores}{Whether to normalize silhouette scores by the average cell type silhouettes of the reference}
29 |
30 | \item{min.cells}{Only report silhouette scores for cell type with at least this number of cells}
31 | }
32 | \value{
33 | A dataframe with average silhouette coefficient for each cell type
34 | }
35 | \description{
36 | Given a projected object and its reference, calculate silhouette coefficient for query cells with respect
37 | to reference cells with the same cell labels.
38 | }
39 | \examples{
40 | \dontshow{if (interactive()) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
41 | data(query_example_seurat)
42 | ref <- load.reference.map()
43 | q <- Run.ProjecTILs(query_example_seurat, ref=ref, fast.umap.predict=TRUE)
44 | combined <- compute_silhouette(ref, query=q)
45 | \dontshow{\}) # examplesIf}
46 | }
47 |
--------------------------------------------------------------------------------
/man/find.discriminant.dimensions.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{find.discriminant.dimensions}
4 | \alias{find.discriminant.dimensions}
5 | \title{Find discriminant dimensions}
6 | \usage{
7 | find.discriminant.dimensions(
8 | ref,
9 | query,
10 | query.control = NULL,
11 | query.assay = "RNA",
12 | state = "largest",
13 | labels.col = "functional.cluster",
14 | reduction = "ICA",
15 | test = c("ks", "t.test"),
16 | ndim = 50,
17 | print.n = 3,
18 | verbose = T
19 | )
20 | }
21 | \arguments{
22 | \item{ref}{Seurat object with reference atlas}
23 |
24 | \item{query}{Seurat object with query data}
25 |
26 | \item{query.control}{Optionally, you can compare your query with a control sample, instead of the reference}
27 |
28 | \item{query.assay}{The data slot to be used for enrichment analysis}
29 |
30 | \item{state}{Perform discriminant analysis on this cell state. Can be either:
31 | \itemize{
32 | \item{"largest" - Performs analysis on the cell state most represented in the query set(s)}
33 | \item{"all" - Performs analysis on the complete dataset, using all cells}
34 | \item{A specific cell state, one of the states in metadata field labels.col}
35 | }}
36 |
37 | \item{labels.col}{The metadata field used to annotate the clusters (default: functional.cluster)}
38 |
39 | \item{reduction}{Which dimensionality reduction to use (either ICA or PCA)}
40 |
41 | \item{test}{Which test to perform between the dataset distributions in each ICA/PCA dimension. One of `ks` (Kolmogorov-Smirnov) or `t.test` (T-test)}
42 |
43 | \item{ndim}{How many dimensions to consider in the reduced ICA/PCA space}
44 |
45 | \item{print.n}{The number of top dimensions to return to STDOUT}
46 |
47 | \item{verbose}{Print results to STDOUT}
48 | }
49 | \value{
50 | A dataframe, where rows are ICA/PCA dimensions. ICA/PCAs are ranked by statistical significance when comparing their distribution between query and control (or query vs. reference map)
51 | }
52 | \description{
53 | Searches PCA or ICA dimensions where the query set deviates the most from a control set or from the reference map. It can
54 | be useful to suggest novel cell states that escape from the main axes of diversity of the UMAP
55 | }
56 | \examples{
57 | \dontshow{if (interactive()) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
58 | find.discriminant.dimensions(ref, query=query.set)
59 | find.discriminant.dimensions(ref, query=query.set, query.control=control.set)
60 | \dontshow{\}) # examplesIf}
61 | }
62 |
--------------------------------------------------------------------------------
/man/find.discriminant.genes.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{find.discriminant.genes}
4 | \alias{find.discriminant.genes}
5 | \title{Find discriminant genes}
6 | \usage{
7 | find.discriminant.genes(
8 | ref,
9 | query,
10 | query.control = NULL,
11 | ref.assay = "RNA",
12 | query.assay = "RNA",
13 | state = "largest",
14 | labels.col = "functional.cluster",
15 | test = "wilcox",
16 | min.cells = 10,
17 | genes.use = c("variable", "all"),
18 | ...
19 | )
20 | }
21 | \arguments{
22 | \item{ref}{Seurat object with reference atlas}
23 |
24 | \item{query}{Seurat object with query data}
25 |
26 | \item{query.control}{Optionally, you can compare your query with a control sample, instead of the reference}
27 |
28 | \item{ref.assay}{The referece assay to be used for DE analysis}
29 |
30 | \item{query.assay}{The query assay to be used for DEG analyis, if comparing to the reference}
31 |
32 | \item{state}{Perform discriminant analysis on this cell state. Can be either:
33 | \itemize{
34 | \item{"largest" - Performs analysis on the cell state most represented in the query set(s)}
35 | \item{"all" - Performs analysis on the complete dataset, using all cells}
36 | \item{A specific cell state, one of the states in metadata field labels.col}
37 | }}
38 |
39 | \item{labels.col}{The metadata field used to annotate the clusters (default: functional.cluster)}
40 |
41 | \item{test}{Type of test for DE analysis. See help for `FindMarkers` for implemented tests.}
42 |
43 | \item{min.cells}{Minimum number of cells in the cell type to proceed with analysis.}
44 |
45 | \item{genes.use}{What subset of genes to consider for DE analysis:
46 | \itemize{
47 | \item{"variable" - Only consider variable genes of the reference}
48 | \item{"all" - Use intersection of all genes in query and control}
49 | \item{A custom list of genes}
50 | }}
51 |
52 | \item{...}{Adding parameters for `FindMarkers`}
53 | }
54 | \value{
55 | A dataframe with a ranked list of genes as rows, and statistics as columns (e.g. log fold-change, p-values). See help for `FindMarkers` for more details.
56 | }
57 | \description{
58 | Based on `FindMarkers`. It performs differential expression analysis between a projected query and a control (either the reference map or a control sample), for
59 | a given cell type. Useful to detect whether specific cell states over/under-express genes between conditions or with respect to the reference.
60 | }
61 | \examples{
62 | \dontshow{if (interactive()) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
63 | # Discriminant genes between query and reference in cell type "Tex"
64 | markers <- find.discriminant.genes(ref, query=query.set, state="Tex")
65 |
66 | # Discriminant genes between query and control sample in most represented cell type
67 | markers <- find.discriminant.genes(ref, query=query.set, query.control=control.set)
68 |
69 | # Pass results to EnhancedVolcano for visual results
70 | library(EnhancedVolcano)
71 | EnhancedVolcano(markers, lab = rownames(markers), x = 'avg_logFC', y = 'p_val')
72 | \dontshow{\}) # examplesIf}
73 | }
74 |
--------------------------------------------------------------------------------
/man/get.reference.maps.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{get.reference.maps}
4 | \alias{get.reference.maps}
5 | \title{Retrieve and load reference atlas}
6 | \usage{
7 | get.reference.maps(
8 | collection = NULL,
9 | reference = NULL,
10 | update = FALSE,
11 | directory = "./ProjecTILs_references",
12 | as.list = TRUE,
13 | verbose = TRUE
14 | )
15 | }
16 | \arguments{
17 | \item{collection}{Collection to download and load. See available collection using \link{list.reference.maps}. If NULL, all are downloaded and loaded (default)}
18 |
19 | \item{reference}{References to download and load. See available collection using \link{list.reference.maps}. If NULL, all are downloaded and loaded (default)}
20 |
21 | \item{update}{Boolean whether to delete current reference maps and download them again}
22 |
23 | \item{directory}{Directory where to download and load from reference maps. By default a directory named "ProjecTILs_references" is created in working directory.}
24 |
25 | \item{as.list}{Boolean whether to simplify list (\code{FALSE}) or, by default, keep a list of lists for each collection (\code{TRUE}).}
26 |
27 | \item{verbose}{Inform of the status of processes}
28 | }
29 | \description{
30 | Download and load reference atlases.
31 | }
32 | \examples{
33 | \dontshow{if (interactive()) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
34 | # explore available reference maps
35 | list.reference.maps()
36 |
37 | # consider increasing downloading timeout
38 | options(timeout = 1000)
39 |
40 | # get all available reference maps
41 | ref.maps <- get.reference.maps()
42 |
43 | # get certain collections or reference maps
44 | # all human references maps
45 | ref.maps.human <- get.reference.maps(collection = "human")
46 |
47 | # only some references
48 | ref.maps <- get.reference.maps(reference = "DC")
49 | ref.maps.CD4 <- get.reference.maps(reference = c("CD4", "Virus_CD4T"))
50 |
51 | # update previously downloaded maps
52 | ref.maps <- get.reference.maps(update = TRUE)
53 | \dontshow{\}) # examplesIf}
54 | }
55 |
--------------------------------------------------------------------------------
/man/list.reference.maps.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{list.reference.maps}
4 | \alias{list.reference.maps}
5 | \title{Available reference atlas for ProjecTILs}
6 | \usage{
7 | list.reference.maps()
8 | }
9 | \description{
10 | Obtain the list of available reference atlas for ProjecTILs to then download and load them using \link{get.reference.maps}.
11 | }
12 | \examples{
13 | # explore available reference maps
14 | list.reference.maps()
15 | }
16 |
--------------------------------------------------------------------------------
/man/load.reference.map.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{load.reference.map}
4 | \alias{load.reference.map}
5 | \title{Load Reference Atlas}
6 | \usage{
7 | load.reference.map(ref = "referenceTIL")
8 | }
9 | \arguments{
10 | \item{ref}{Reference atlas as a Seurat object (by default downloads a mouse reference TIL atlas).
11 | To use a custom reference atlas, provide a .rds object or a URL to a .rds object, storing a Seurat object
12 | prepared using \link{make.reference}}
13 | }
14 | \description{
15 | Load or download the reference map for dataset projection.
16 | By the default it downloads a reference atlas of tumour-infiltrating
17 | lymphocytes (TILs) from mouse.
18 | }
19 | \examples{
20 | \dontshow{if (interactive()) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
21 | # consider increasing downloading timeout, if downloading Default reference atlas or large reference
22 | options(timeout = 1000)
23 |
24 | # Download and load default reference map
25 | ref <- load.reference.map()
26 |
27 | # download reference map from url
28 | ref.web <- load.reference.map(ref = url)
29 |
30 | # Load any reference map
31 | ref <- load.reference.map(ref = "path/to/ref")
32 | \dontshow{\}) # examplesIf}
33 | }
34 |
--------------------------------------------------------------------------------
/man/make.projection.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{make.projection}
4 | \alias{make.projection}
5 | \title{Project a query scRNA-seq dataset onto a reference atlas}
6 | \usage{
7 | make.projection(
8 | query,
9 | ref = NULL,
10 | filter.cells = TRUE,
11 | query.assay = NULL,
12 | direct.projection = FALSE,
13 | STACAS.anchor.coverage = 0.7,
14 | STACAS.correction.scale = 100,
15 | STACAS.k.anchor = 5,
16 | STACAS.k.weight = "max",
17 | skip.normalize = FALSE,
18 | fast.umap.predict = FALSE,
19 | ortholog_table = NULL,
20 | scGate_model = NULL,
21 | ncores = 1,
22 | progressbar = TRUE
23 | )
24 | }
25 | \arguments{
26 | \item{query}{Query data, either as single Seurat object or as a list of Seurat object}
27 |
28 | \item{ref}{Reference Atlas - if NULL, downloads the default TIL reference atlas}
29 |
30 | \item{filter.cells}{Pre-filter cells using `scGate`. Only set to FALSE if the dataset has
31 | been previously subset to cell types represented in the reference.}
32 |
33 | \item{query.assay}{Which assay slot to use for the query (defaults to DefaultAssay(query))}
34 |
35 | \item{direct.projection}{If true, apply PCA transformation directly without alignment}
36 |
37 | \item{STACAS.anchor.coverage}{Focus on few robust anchors (low STACAS.anchor.coverage) or on a large amount
38 | of anchors (high STACAS.anchor.coverage). Must be number between 0 and 1.}
39 |
40 | \item{STACAS.correction.scale}{Slope of sigmoid function used to determine strength of batch effect correction.}
41 |
42 | \item{STACAS.k.anchor}{Integer. For alignment, how many neighbors (k) to use when picking anchors.}
43 |
44 | \item{STACAS.k.weight}{Number of neighbors to consider when weighting anchors.
45 | Default is "max", which disables local anchor weighting.}
46 |
47 | \item{skip.normalize}{By default, log-normalize the count data.
48 | If you have already normalized your data, you can skip normalization.}
49 |
50 | \item{fast.umap.predict}{Fast approximation for UMAP projection. Uses coordinates of nearest neighbors in
51 | PCA space to assign UMAP coordinates (credits to Changsheng Li for the implementation)}
52 |
53 | \item{ortholog_table}{Dataframe for conversion between ortholog genes
54 | (by default package object \code{Hs2Mm.convert.table})}
55 |
56 | \item{scGate_model}{scGate model used to filter target cell type from query data
57 | (if NULL use the model stored in \code{ref@misc$scGate})}
58 |
59 | \item{ncores}{Number of cores for parallel execution (requires \link{BiocParallel})}
60 |
61 | \item{progressbar}{Whether to show a progress bar for projection process or not (requires \link{BiocParallel})}
62 | }
63 | \value{
64 | An augmented Seurat object with projected UMAP coordinates on the reference map
65 | }
66 | \description{
67 | This function allows projecting ("query") single-cell RNA-seq datasets onto a reference map
68 | (i.e. a curated and annotated scRNA-seq dataset).
69 | To project multiple datasets, submit a list of Seurat objects with the query parameter.
70 | The projection consists of 3 steps:
71 | \itemize{
72 | \item{pre-processing: optional steps which might include pre-filtering of cells by markers using `scGate`,
73 | data normalization, and ortholog conversion.}
74 | \item{batch-effect correction: uses built-in STACAS algorithm to detect and correct for batch effects
75 | (this step assumes that at least a fraction of the cells in the query are in the same state than cells in
76 | the reference)}
77 | \item{embedding of corrected query data in the reduced-dimensionality spaces (PCA and UMAP) of the reference map.}
78 | }
79 | }
80 | \details{
81 | See \link{load.reference.map} to load or download a reference atlas. See
82 | also \link{ProjecTILs.classifier} to use ProjecTILs as a cell type classifier.
83 | }
84 | \examples{
85 | \dontshow{if (interactive()) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
86 | data(query_example_seurat)
87 | ref <- load.reference.map()
88 | make.projection(query_example_seurat, ref=ref)
89 | \dontshow{\}) # examplesIf}
90 | }
91 |
--------------------------------------------------------------------------------
/man/make.reference.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{make.reference}
4 | \alias{make.reference}
5 | \title{Make a ProjecTILs reference}
6 | \usage{
7 | make.reference(
8 | ref,
9 | assay = NULL,
10 | assay.raw = "RNA",
11 | atlas.name = "custom_reference",
12 | annotation.column = "functional.cluster",
13 | recalculate.umap = FALSE,
14 | umap.method = c("umap", "uwot"),
15 | metric = "cosine",
16 | min_dist = 0.3,
17 | n_neighbors = 30,
18 | ndim = 20,
19 | dimred = "umap",
20 | nfeatures = 1000,
21 | color.palette = NULL,
22 | scGate.model.human = NULL,
23 | scGate.model.mouse = NULL,
24 | store.markers = FALSE,
25 | n.markers = 10,
26 | seed = 123,
27 | layer1_link = NULL
28 | )
29 | }
30 | \arguments{
31 | \item{ref}{Seurat object with reference atlas}
32 |
33 | \item{assay}{The assay storing the reference expression data (e.g. "integrated")}
34 |
35 | \item{assay.raw}{The assay storing raw expression data (e.g. "RNA")}
36 |
37 | \item{atlas.name}{An optional name for your reference}
38 |
39 | \item{annotation.column}{The metadata column with the cluster annotations for this atlas}
40 |
41 | \item{recalculate.umap}{If TRUE, run the `umap` or `uwot` algorithm to generate embeddings.
42 | Otherwise use the embeddings stored in the `dimred` slot.}
43 |
44 | \item{umap.method}{Which method to use for calculating the umap reduction}
45 |
46 | \item{metric}{Distance metric to use to find nearest neighbors for UMAP}
47 |
48 | \item{min_dist}{Effective minimum distance between UMAP embedded points}
49 |
50 | \item{n_neighbors}{Size of local neighborhood for UMAP}
51 |
52 | \item{ndim}{Number of PCA dimensions}
53 |
54 | \item{dimred}{Use the pre-calculated embeddings stored at `Embeddings(ref, dimred)`}
55 |
56 | \item{nfeatures}{Number of variable features (only calculated if not already present)}
57 |
58 | \item{color.palette}{A (named) vector of colors for the reference plotting functions.
59 | One color for each cell type in 'functional.cluster'}
60 |
61 | \item{scGate.model.human}{A human \link[scGate]{scGate} model to purify the cell types represented in the
62 | map. For example, if the map contains CD4 T cell subtype, specify an scGate model for CD4 T cells.}
63 |
64 | \item{scGate.model.mouse}{A mouse \link[scGate]{scGate} model to purify the cell types represented in the
65 | map.}
66 |
67 | \item{store.markers}{Whether to store the top differentially expressed genes in `ref@misc$gene.panel`}
68 |
69 | \item{n.markers}{Store the top `n.markers` for each subtype given by differential
70 | expression analysis}
71 |
72 | \item{seed}{Random seed}
73 |
74 | \item{layer1_link}{Broad cell type contained in this reference atlas (i.e. CD4T, CL:0000624...) to link with broad cell type annotation (layer1).}
75 | }
76 | \value{
77 | A reference atlas compatible with ProjecTILs
78 | }
79 | \description{
80 | Converts a Seurat object to a ProjecTILs reference atlas. You can preserve your low-dimensionality embeddings
81 | (e.g. UMAP) in the reference atlas by setting `recalculate.umap=FALSE`, or recalculate the UMAP using one of
82 | the two methods umap::umap or uwot::umap. Recalculation allows exploting the
83 | 'predict' functionalities of these methods for embedding of new points; skipping recalculation will
84 | make the projection use an approximation for UMAP embedding of the query.
85 | }
86 | \examples{
87 | \dontshow{if (interactive()) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
88 | custom_reference <- ProjecTILs::make.reference(my_dataset, recalculate.umap=T)
89 | \dontshow{\}) # examplesIf}
90 | }
91 |
--------------------------------------------------------------------------------
/man/merge.Seurat.embeddings.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{merge.Seurat.embeddings}
4 | \alias{merge.Seurat.embeddings}
5 | \title{Merge Seurat objects, including reductions (e.g. PCA, UMAP, ICA)}
6 | \usage{
7 | \method{merge}{Seurat.embeddings}(x = NULL, y = NULL, merge.dr = TRUE, ...)
8 | }
9 | \arguments{
10 | \item{x}{First object to merge}
11 |
12 | \item{y}{Second object to merge}
13 |
14 | \item{merge.dr}{How to handle merging dimensional reductions (see merge.Seurat)}
15 |
16 | \item{...}{More parameters to \link{merge} function}
17 | }
18 | \value{
19 | A merged Seurat object
20 | }
21 | \description{
22 | Given two Seurat objects, merge counts and data as well as dim reductions (PCA, UMAP, ICA, etc.)
23 | }
24 | \examples{
25 | \dontshow{if (interactive()) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
26 | o1 <- query_example_seurat
27 | o2 <- query_example_seurat
28 | seurat.merged <- merge.Seurat.embeddings(o1, o2)
29 | #To merge multiple object stored in a list
30 | seurat.merged <- Reduce(f=merge.Seurat.embeddings, x=obj.list)
31 | \dontshow{\}) # examplesIf}
32 | }
33 |
--------------------------------------------------------------------------------
/man/plot.discriminant.3d.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{plot.discriminant.3d}
4 | \alias{plot.discriminant.3d}
5 | \title{3D plot of reference map with extra discriminant dimension}
6 | \usage{
7 | \method{plot}{discriminant.3d}(
8 | ref,
9 | query,
10 | query.control = NULL,
11 | query.assay = "RNA",
12 | labels.col = "functional.cluster",
13 | extra.dim = "ICA_1",
14 | query.state = NULL
15 | )
16 | }
17 | \arguments{
18 | \item{ref}{Seurat object with reference object}
19 |
20 | \item{query}{Seurat object with query data}
21 |
22 | \item{query.control}{Optionally, you can compare your query with a control sample, instead of the reference}
23 |
24 | \item{query.assay}{The data slot to be used for enrichment analysis}
25 |
26 | \item{labels.col}{The metadata field used to annotate the clusters}
27 |
28 | \item{extra.dim}{The additional dimension to be added on the z-axis of the plot. Can be either:
29 | \itemize{
30 | \item{An ICA or PCA dimension (e.g. ICA_10). See `find.discriminant.dimensions`}
31 | \item{Any numeric metadata field associated to the cells (e.g. 'cycling.score')}
32 | }}
33 |
34 | \item{query.state}{Only plot the query cells from this specific state}
35 | }
36 | \value{
37 | A three dimensional plot with UMAP_1 and UMAP_2 on the x and y axis respectively, and the specified `extra.dim` on the z-axis.
38 | }
39 | \description{
40 | Add an extra dimension to the reference map (it can be suggested by `find.discriminant.dimensions`), to explore additional axes of variability
41 | in a query dataset compared to the reference map.
42 | }
43 | \examples{
44 | \dontshow{if (interactive()) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
45 | plot.discriminant.3d(ref, query=query, extra.dim="ICA_19")
46 | plot.discriminant.3d(ref, query=treated.set, query.control=control.set, extra.dim="ICA_2")
47 | \dontshow{\}) # examplesIf}
48 | }
49 |
--------------------------------------------------------------------------------
/man/plot.projection.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{plot.projection}
4 | \alias{plot.projection}
5 | \title{Show UMAP projection of query on reference map}
6 | \usage{
7 | \method{plot}{projection}(
8 | ref,
9 | query = NULL,
10 | labels.col = "functional.cluster",
11 | cols = NULL,
12 | linesize = 1,
13 | pointsize = 1,
14 | ref.alpha = 0.3,
15 | ref.size = NULL,
16 | ...
17 | )
18 | }
19 | \arguments{
20 | \item{ref}{Reference object}
21 |
22 | \item{query}{Seurat object with query data}
23 |
24 | \item{labels.col}{The metadata field to annotate the clusters (default: functional.cluster)}
25 |
26 | \item{cols}{Custom color palette for clusters}
27 |
28 | \item{linesize}{Contour line thickness for projected query}
29 |
30 | \item{pointsize}{Point size for cells in projected query}
31 |
32 | \item{ref.alpha}{Transparency parameter for reference cells}
33 |
34 | \item{ref.size}{Adjust point size for reference cells}
35 |
36 | \item{...}{Additional parameters for \code{DimPlot}, e.g. raster=T to
37 | limit image size}
38 | }
39 | \value{
40 | UMAP plot of reference map with projected query set in the same space
41 | }
42 | \description{
43 | Plots the UMAP representation of the reference map, together with the projected coordinates of a query dataset.
44 | }
45 | \examples{
46 | \dontshow{if (interactive()) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
47 | data(query_example_seurat)
48 | ref <- load.reference.map()
49 | q <- Run.ProjecTILs(query_example_seurat, ref=ref, fast.umap.predict=TRUE)
50 | plot.projection(ref=ref, query=q)
51 | \dontshow{\}) # examplesIf}
52 | }
53 |
--------------------------------------------------------------------------------
/man/plot.statepred.composition.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{plot.statepred.composition}
4 | \alias{plot.statepred.composition}
5 | \title{Summarize the predicted cell states of an object}
6 | \usage{
7 | \method{plot}{statepred.composition}(
8 | ref,
9 | query,
10 | labels.col = "functional.cluster",
11 | cols = NULL,
12 | metric = c("Count", "Percent")
13 | )
14 | }
15 | \arguments{
16 | \item{ref}{Reference object}
17 |
18 | \item{query}{Seurat object with query data}
19 |
20 | \item{labels.col}{The metadata field used to annotate the clusters (default: functional.cluster)}
21 |
22 | \item{cols}{Custom color palette for clusters}
23 |
24 | \item{metric}{One of `Count` or `Percent`. `Count` plots the absolute number of cells, `Percent` the fraction on the total number of cells.}
25 | }
26 | \value{
27 | Barplot of predicted state composition
28 | }
29 | \description{
30 | Makes a barplot of the frequency of cell states in a query object.
31 | }
32 | \examples{
33 | \dontshow{if (interactive()) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
34 | data(query_example_seurat)
35 | ref <- load.reference.map()
36 | q <- make.projection(query_example_seurat, ref=ref)
37 | q <- cellstate.predict(ref, query=q)
38 | plot.statepred.composition(query_example.seurat)
39 | \dontshow{\}) # examplesIf}
40 | }
41 |
--------------------------------------------------------------------------------
/man/plot.states.radar.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{plot.states.radar}
4 | \alias{plot.states.radar}
5 | \title{Show expression level of key genes}
6 | \usage{
7 | \method{plot}{states.radar}(
8 | ref,
9 | query = NULL,
10 | labels.col = "functional.cluster",
11 | ref.assay = "RNA",
12 | query.assay = "RNA",
13 | genes4radar = c("Foxp3", "Cd4", "Cd8a", "Tcf7", "Ccr7", "Gzmb", "Gzmk", "Pdcd1",
14 | "Havcr2", "Tox", "Mki67"),
15 | meta4radar = NULL,
16 | norm.factor = 1,
17 | min.cells = 20,
18 | cols = NULL,
19 | return = FALSE,
20 | return.as.list = FALSE
21 | )
22 | }
23 | \arguments{
24 | \item{ref}{Reference object}
25 |
26 | \item{query}{Query data, either as a Seurat object or as a list of Seurat objects}
27 |
28 | \item{labels.col}{The metadata field used to annotate the clusters}
29 |
30 | \item{ref.assay}{The assay to pull the reference expression data}
31 |
32 | \item{query.assay}{The assay to pull the query expression data}
33 |
34 | \item{genes4radar}{Which genes to use for plotting}
35 |
36 | \item{meta4radar}{Which metadata columns (numeric) to use for plotting. If not NULL, \code{genes4radar} are ignored}
37 |
38 | \item{norm.factor}{Normalization factor for rescaling expression or metadata values}
39 |
40 | \item{min.cells}{Only display cell states with a minimum number of cells}
41 |
42 | \item{cols}{Custom color palette for samples in radar plot}
43 |
44 | \item{return}{Return the combined plots instead of printing them to the default device (deprecated)}
45 |
46 | \item{return.as.list}{Return plots in a list, instead of combining them in a single plot}
47 | }
48 | \value{
49 | Radar plot of gene expression of key genes by cell subtype
50 | }
51 | \description{
52 | Makes a radar plot of the expression level of a set of genes. It can be useful to compare
53 | the gene expression profile of different cell states in the reference atlas vs. a projected set.
54 | }
55 | \examples{
56 | \dontshow{if (interactive()) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
57 | ref <- load.reference.map()
58 | plot.states.radar(ref)
59 | \dontshow{\}) # examplesIf}
60 | }
61 |
--------------------------------------------------------------------------------
/man/read.sc.query.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{read.sc.query}
4 | \alias{read.sc.query}
5 | \title{Read to memory a query expression matrix}
6 | \usage{
7 | read.sc.query(
8 | filename,
9 | type = c("10x", "hdf5", "raw", "raw.log2"),
10 | project.name = "Query",
11 | min.cells = 3,
12 | min.features = 50,
13 | gene.column.10x = 2,
14 | raw.rownames = 1,
15 | raw.sep = c("auto", " ", "\\t", ","),
16 | raw.header = TRUE,
17 | use.readmtx = TRUE
18 | )
19 | }
20 | \arguments{
21 | \item{filename}{Path to expression matrix file or folder}
22 |
23 | \item{type}{Expression matrix format (10x, hdf5, raw, raw.log2)}
24 |
25 | \item{project.name}{Title for the project}
26 |
27 | \item{min.cells}{Only keep genes represented in at least min.cells number of cells}
28 |
29 | \item{min.features}{Only keep cells expressing at least min.features genes}
30 |
31 | \item{gene.column.10x}{For 10x format - which column of genes.tsv or features.tsv to use for gene names}
32 |
33 | \item{raw.rownames}{For raw matrix format - A vector of row names, or a single number giving the column of the table which contains the row names}
34 |
35 | \item{raw.sep}{For raw matrix format - Separator for raw expression matrix}
36 |
37 | \item{raw.header}{For raw matrix format - Use headers in expression matrix}
38 |
39 | \item{use.readmtx}{Use ReadMtx function to read in 10x files with custom names}
40 | }
41 | \value{
42 | A Seurat object populated with raw counts and normalized counts for single-cell expression
43 | }
44 | \description{
45 | Load a query expression matrix to be projected onto the reference atlas. Several formats (10x, hdf5, raw and log counts)
46 | are supported - see \code{type} parameter for details
47 | }
48 | \examples{
49 | \dontshow{if (interactive()) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
50 | fname <- "./sample_data"
51 | querydata <- read.sc.query(fname, type="10x")
52 | \dontshow{\}) # examplesIf}
53 | }
54 |
--------------------------------------------------------------------------------
/man/recalculate.embeddings.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/main.R
3 | \name{recalculate.embeddings}
4 | \alias{recalculate.embeddings}
5 | \title{Recalculate low dimensional embeddings after projection}
6 | \usage{
7 | recalculate.embeddings(
8 | ref,
9 | projected,
10 | ref.assay = "integrated",
11 | proj.assay = "integrated",
12 | ndim = NULL,
13 | n.neighbors = 20,
14 | min.dist = 0.3,
15 | recalc.pca = FALSE,
16 | resol = 0.4,
17 | k.param = 15,
18 | metric = "cosine",
19 | umap.method = c("umap", "uwot"),
20 | seed = 123
21 | )
22 | }
23 | \arguments{
24 | \item{ref}{Reference map}
25 |
26 | \item{projected}{A projected object (or list of projected objects) generated using \link{make.projection}}
27 |
28 | \item{ref.assay}{Assay for reference object}
29 |
30 | \item{proj.assay}{Assay for projected object(s)}
31 |
32 | \item{ndim}{Number of dimensions for recalculating dimensionality reductions}
33 |
34 | \item{n.neighbors}{Number of neighbors for UMAP algorithm}
35 |
36 | \item{min.dist}{Tightness parameter for UMAP embedding}
37 |
38 | \item{recalc.pca}{Whether to recalculate the PCA embeddings with the combined reference and projected data}
39 |
40 | \item{resol}{Resolution for unsupervised clustering}
41 |
42 | \item{k.param}{Number of nearest neighbors for clustering}
43 |
44 | \item{metric}{Distance metric to use to find nearest neighbors for UMAP}
45 |
46 | \item{umap.method}{Which method should be used to calculate UMAP embeddings}
47 |
48 | \item{seed}{Random seed for reproducibility}
49 | }
50 | \value{
51 | A combined reference object of reference and projected object(s), with new low dimensional embeddings
52 | }
53 | \description{
54 | Given a reference object and a (list of) projected objects, recalculate low-dim
55 | embeddings accounting for the projected cells
56 | }
57 | \examples{
58 | \dontshow{if (interactive()) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
59 | combined <- recalculate.embeddings(ref, projected, ndim=10)
60 | \dontshow{\}) # examplesIf}
61 | }
62 |
--------------------------------------------------------------------------------