├── .gitignore
├── LICENSE
├── README.md
├── bin
├── run_snake.sh
└── run_snakemake_v7.sh
├── config
├── R_proj_packages.txt
├── config.yaml
├── group_chroms.R
├── grouped_contigs.tsv
└── samplesheet
│ ├── comparisons.tsv
│ ├── make_units_template.R
│ ├── make_units_template.sh
│ └── units.tsv
├── raw_data
└── .keep
├── resources
├── deseq_template.Rmd
├── gsea_template.Rmd
├── iSEE_app.R
└── report_template
│ ├── _site.yml
│ ├── footer.html
│ ├── images
│ └── VAI_2_Line_White.png
│ ├── index.Rmd
│ ├── multiqc.Rmd
│ ├── references.bib
│ └── styles.css
├── schema
└── units.schema.yaml
└── workflow
├── Snakefile
├── rules
├── RNAseq.smk
├── deseq2.smk
├── gsea.smk
├── isee.smk
├── make_Rprojects.smk
├── make_report.smk
├── qc.smk
├── variants.smk
└── visualisation.smk
└── scripts
├── add_DE_to_SCE.R
├── install_renv_pkges.R
├── make_Rproject.R
├── make_sce.R
└── snprelate.Rmd
/.gitignore:
--------------------------------------------------------------------------------
1 | rnaseq_workflow.e
2 | rnaseq_workflow.o
3 | raw_data/
4 | results/
5 | logs/
6 | benchmarks/
7 | .snakemake/
8 | config/samplesheet/*
9 | !config/samplesheet/make_units_template*
10 | !config/samplesheet/units.tsv
11 | !config/samplesheet/comparisons.tsv
12 | *.DS_Store
13 | *._.DS_Store
14 | iSEE/.*
15 | tmp/
16 | .Rproj.user
17 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Bulk RNAseq Workflow
2 |
3 | * [Bulk RNAseq Workflow](#bulk-rnaseq-workflow)
4 | * [Usage](#usage)
5 | * [Step 1: Configure the workflow](#step-1-configure-the-workflow)
6 | * [Step 1b (optional): Specify contig groups for variant calling](#step-1b-optional-specify-contig-groups-for-variant-calling)
7 | * [Step 2: Test and run the workflow](#step-2-test-and-run-the-workflow)
8 | * [Troubleshooting](#troubleshooting)
9 |
10 | ## Usage
11 |
12 | **NOTE** this workflow is optimized for the HPC @ Van Andel Institute.
13 |
14 |
15 | ### Step 1: Configure the workflow
16 | * Move your sequencing reads to `raw_data/`
17 |
18 | * Modify the config, comparisons, and samplesheet:
19 | * config/samplesheet/units.tsv; To make a template based in the files in `raw_data/`, run `./make_units_template.sh`.
20 | * **sample** - ID of biological sample; Must be unique.
21 | * **group** - Experimental group
22 | * **fq1** - name of read1 fastq
23 | * **fq2** - name of read2 fastq
24 | * **RG** - space-delimited read group specification e.g. ID:XYZ PU:XYZ LB:LIB01 PL:ILLUMINA SM:SAMPLE01
25 |
26 | * config/samplesheet/comparisons.tsv; fill this out with you
27 | * **comparison_name** - Name of your comparison (use only letters, numbers, and underscores -- special characters or spaces will result in errors).
28 | * **group_test** - Experimental group (treated/condition/phenotype)
29 | * **group_reference** - Reference group (control/wildtype/baseline)
30 |
31 | * config/config.yaml
32 | * **iSEE**
33 | 1. Deployment of iSEE to shinyapps.io can be enabled/disabled using `deploy_to_shinyio`. If set to False, the following steps can be ignored.
34 | 2. `iSEE_app_name` should be a new app name that does not already exist in your shinyapps.io account. Otherwise, the deployment will fail or your old app may be overwritten.
35 | 3. In R, run `rsconnect::accounts()`. Choose one of the values in the 'name' column to fill in `shinyio_account_name`. If `rsconnect::accounts()` does not return any results, you need to first follow the instructions [here](https://docs.posit.co/shinyapps.io/guide/getting_started/#configure-rsconnect) to set up your shinyapps.io credentials.
36 |
37 | ### Step 1b (_optional_): Specify contig groups for variant calling
38 |
39 | Certain parts of the variant calling will parallelize by splitting by contig. The non-standard chromosomes can be grouped together since they are usually very small. The contig groupings are specified by the file `config/grouped_contigs.tsv`; column 1 is the name for the group of contigs and column 2 is a comma-separated list of the contigs.
40 |
41 | ```
42 | cd config
43 | module load bbc2/R/alt/R-4.2.1-setR_LIBS_USER
44 | Rscript --vanilla group_chroms.R
45 | ```
46 |
47 | ### Step 2: Test and run the workflow
48 | Test your configuration by performing a dry-run via
49 |
50 | ```
51 | snakemake -npr
52 | ```
53 |
54 | Execute from within your project directory as a SLURM job.
55 |
56 | ```
57 | sbatch bin/run_snake.sh
58 | ```
59 |
60 | ## Troubleshooting
61 |
62 | - If running the workflow on an older version of R, incompatibilities with the latest CRAN packages can occur if an older version of the CRAN package is not available in the renv cache or in the user library. To install an older version of a CRAN package, replace/add the package name in the `config/R_proj_packages.txt` file with `package_name@version_number`. The version number should be as listed in the package's reference manual e.g. `arules@1.7-10`. Note that this version number is only considered if the workflow was unable to copy from the cache or user library.
63 |
--------------------------------------------------------------------------------
/bin/run_snake.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #SBATCH --export=NONE
3 | #SBATCH -J rnaseq_workflow
4 | #SBATCH -o rnaseq_workflow.o
5 | #SBATCH -e rnaseq_workflow.e
6 | #SBATCH --ntasks 1
7 | #SBATCH --time 120:00:00
8 | #SBATCH --mem=8G
9 | #SBATCH --partition=long
10 |
11 | cd $SLURM_SUBMIT_DIR
12 |
13 | snakemake_module="bbc2/snakemake/snakemake-9.4.0"
14 |
15 | module load $snakemake_module
16 |
17 | # make logs dir if it does not exist already.
18 | logs_dir="logs/"
19 | [[ -d $logs_dir ]] || mkdir -p $logs_dir
20 |
21 |
22 | echo "Start snakemake workflow." >&1
23 | echo "Start snakemake workflow." >&2
24 |
25 | snakemake \
26 | -p \
27 | --latency-wait 20 \
28 | --use-envmodules \
29 | --jobs 100 \
30 | --executor cluster-generic --cluster-generic-submit-cmd "mkdir -p logs/{rule}; sbatch \
31 | -p ${SLURM_JOB_PARTITION} \
32 | --export=ALL \
33 | --nodes 1 \
34 | --ntasks-per-node {threads} \
35 | --mem={resources.mem_gb}G \
36 | -t 120:00:00 \
37 | -o logs/{rule}/{resources.log_prefix}.o \
38 | -e logs/{rule}/{resources.log_prefix}.e" # SLURM hangs if output dir does not exist, so we create it before running sbatch on the snakemake jobs.
39 | #--slurm \
40 | #--default-resources slurm_account=${SLURM_JOB_USER} slurm_partition=${SLURM_JOB_PARTITION}
41 |
42 | echo "snakemake workflow done." >&1
43 | echo "snakemake workflow done." >&2
44 |
--------------------------------------------------------------------------------
/bin/run_snakemake_v7.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #SBATCH --export=NONE
3 | #SBATCH -J rnaseq_workflow
4 | #SBATCH -o rnaseq_workflow.o
5 | #SBATCH -e rnaseq_workflow.e
6 | #SBATCH --ntasks 1
7 | #SBATCH --time 120:00:00
8 | #SBATCH --mem=8G
9 | #SBATCH --partition=long
10 |
11 | cd $SLURM_SUBMIT_DIR
12 |
13 | snakemake_module="bbc2/snakemake/snakemake-7.25.0"
14 |
15 | module load $snakemake_module
16 |
17 | # make logs dir if it does not exist already.
18 | logs_dir="logs/"
19 | [[ -d $logs_dir ]] || mkdir -p $logs_dir
20 |
21 |
22 | echo "Start snakemake workflow." >&1
23 | echo "Start snakemake workflow." >&2
24 |
25 | snakemake \
26 | -p \
27 | --latency-wait 20 \
28 | --use-envmodules \
29 | --jobs 100 \
30 | --cluster "mkdir -p logs/{rule}; sbatch \
31 | -p ${SLURM_JOB_PARTITION} \
32 | --export=ALL \
33 | --nodes 1 \
34 | --ntasks-per-node {threads} \
35 | --mem={resources.mem_gb}G \
36 | -t 120:00:00 \
37 | -o logs/{rule}/{resources.log_prefix}.o \
38 | -e logs/{rule}/{resources.log_prefix}.e" # SLURM hangs if output dir does not exist, so we create it before running sbatch on the snakemake jobs.
39 | #--slurm \
40 | #--default-resources slurm_account=${SLURM_JOB_USER} slurm_partition=${SLURM_JOB_PARTITION}
41 |
42 | echo "snakemake workflow done." >&1
43 | echo "snakemake workflow done." >&2
44 |
--------------------------------------------------------------------------------
/config/R_proj_packages.txt:
--------------------------------------------------------------------------------
1 | AnnotationDbi
2 | ashr
3 | clusterProfiler
4 | ComplexHeatmap
5 | DESeq2
6 | edgeR
7 | enrichplot
8 | genefilter
9 | GenomicFeatures
10 | ggprism
11 | ggsci
12 | GO.db
13 | GSVA
14 | iSEE
15 | limma
16 | msigdbr
17 | openxlsx
18 | patchwork
19 | PCAtools
20 | ReactomePA
21 | rjson
22 | rmarkdown
23 | scater
24 | SNPRelate
25 | tidyverse
26 | txdbmaker
27 | tximport
28 | vegan
29 | arules
30 | ievaKer/aPEAR
31 | configr
32 | kableExtra
33 | SummarizedExperiment
34 | iSEE
35 | jose
36 | packrat
37 | PKI
38 | rsconnect
39 | usethis
40 | rtracklayer
41 |
--------------------------------------------------------------------------------
/config/config.yaml:
--------------------------------------------------------------------------------
1 | quick_ref:
2 | # Only fill this if you are NOT doing SNP calling. "ref_genome_verison" is the dir of the date and version of the reference. Check what is available at /varidata/research/projects/bbc/versioned_references. If you are not sure, you can use the latest one. "species_name" is the dir name of the reference genome, check /varidata/research/projects/bbc/versioned_references/latest/data/ to see species are there. The most commonly used species are mmm10_gencode and hg38_gencode. ref_genome_version is optional whereas species_name is MANDATORY; if you leave quick_ref section blank, the workflow will use references from "ref" section below.
3 | ref_genome_version: # The earliest recommended version is 2021-08-10_11.12.27_v6. Note that the Salmon index might not exist for earlier versions.
4 | species_name: #hg38_gencode
5 | ref:
6 | index: /varidata/research/projects/bbc/versioned_references/2023-05-03_15.28.41_v12/data/hg38_gencode/indexes/star
7 | salmon_index: /varidata/research/projects/bbc/versioned_references/2023-05-03_15.28.41_v12/data/hg38_gencode/indexes/salmon/hg38_gencode
8 | annotation: /varidata/research/projects/bbc/versioned_references/2023-05-03_15.28.41_v12/data/hg38_gencode/annotation/hg38_gencode.gtf
9 | # Below used only for variant calling
10 | dict: /varidata/research/projects/bbc/versioned_references/2023-05-03_15.28.41_v12/data/hg38_gencode/sequence/hg38_gencode.dict
11 | snpeff_db_id: hg38
12 | known_snps: /varidata/research/projects/bbc/versioned_references/2023-05-03_15.28.41_v12/data/hg38_gencode/gatk_resource_bundle/Homo_sapiens_assembly38.dbsnp138.vcf
13 | known_indels: /varidata/research/projects/bbc/versioned_references/2023-05-03_15.28.41_v12/data/hg38_gencode/gatk_resource_bundle/Mills_and_1000G_gold_standard.indels.hg38.vcf.gz
14 | sequence: /varidata/research/projects/bbc/versioned_references/2023-05-03_15.28.41_v12/data/hg38_gencode/sequence/hg38_gencode.fa
15 | fai: /varidata/research/projects/bbc/versioned_references/2023-05-03_15.28.41_v12/data/hg38_gencode/sequence/hg38_gencode.fa.fai
16 |
17 | # OrgDB R package for covnerting gene names. Common choices are 'org.Mm.eg.db' for mouse and 'org.Hs.eg.db' for human.
18 | orgdb: org.Hs.eg.db
19 | fdr_cutoff: 0.1
20 | genes_of_interest: #DUSP1,KLF15,CRISPLD2 # create table in report of these genes, keep empty if no initial genes of interest.
21 |
22 | # For GSEA quick_ref can only handle human, mouse, rat, and fly; all other organisms need to be filled in manually
23 | # kegg_org should be a three or four letter string corresponding to your reference species. List of KEGG species is found here: https://www.genome.jp/kegg/tables/br08606.html
24 | kegg_org: hsa
25 | # reactome_org can be "human", "mouse", "rat", "celegans", "yeast", "zebrafish", "fly"
26 | reactome_org: human
27 | # Full species name. Applicable input strings can be found by installing the msigdbr library in R and using msigdbr::msigdbr_species()
28 | msigdb_organism: Homo sapiens
29 | # Choose which gene sets you would like to test against
30 | pathway_str: Reactome,BP,BP-simplified,KEGG,H,C1,C2,C3,C4,C5,C6,C7,C8
31 |
32 |
33 | # are the sequencing reads paired-end ('PE') or single-end ('SE')
34 | PE_or_SE: PE
35 |
36 | call_variants: False
37 | grouped_contigs: config/grouped_contigs.tsv
38 |
39 | run_vis_bigwig : True
40 | run_rseqc: False
41 |
42 | # R project config
43 | Rproj_dirname: "VBCS-000_Rproj"
44 | ## use renv cache or install/copy all packages in project.
45 | renv_use_cache: True
46 | ## copy packages from user library if available?
47 | renv_use_user_lib: True
48 | renv_symlink_from_cache: True #False
49 | # Use Pak to install packages
50 | renv_use_pak: False # I couldn't get pak to install to the renv cache which resulted in rebuilding the library each time; see https://github.com/r-lib/pak/issues/284
51 | ## if using renv cache, this is the path to where the cache is/will be stored.
52 | renv_root_path: /varidata/research/projects/bbc/tools/renv_root
53 |
54 | # iSEE config
55 | iSEE_app_name: "RNAseq_devel_airway"
56 | deploy_to_shinyio: True
57 | shinyio_account_name: "vai-bbc" # valid account names can be found using rsconnect::accounts(); If blank, follow instructions at https://docs.posit.co/shinyapps.io/guide/getting_started/#configure-rsconnect
58 |
59 |
60 | ####################################################################
61 | # FOR MOST STANDARD USE CASES, THE BELOW DO NOT NEED TO BE CHANGED.#
62 | ####################################################################
63 |
64 | # path to sample sheet relative to the base project directory (containing config/, workflow/ etc)
65 | units: config/samplesheet/units.tsv
66 | comparisons: config/samplesheet/comparisons.tsv
67 |
68 | sortmerna:
69 | rfam5_8s: /varidata/research/software/BBC/sortmerna/sortmerna-4.3.6-Linux/rRNA_databases/rfam-5.8s-database-id98.fasta
70 | rfam5s: /varidata/research/software/BBC/sortmerna/sortmerna-4.3.6-Linux/rRNA_databases/rfam-5s-database-id98.fasta
71 | silva_arc_16s: /varidata/research/software/BBC/sortmerna/sortmerna-4.3.6-Linux/rRNA_databases/silva-arc-16s-id95.fasta
72 | silva_arc_23s: /varidata/research/software/BBC/sortmerna/sortmerna-4.3.6-Linux/rRNA_databases/silva-arc-23s-id98.fasta
73 | silva_bac_16s: /varidata/research/software/BBC/sortmerna/sortmerna-4.3.6-Linux/rRNA_databases/silva-bac-16s-id90.fasta
74 | silva_bac_23s: /varidata/research/software/BBC/sortmerna/sortmerna-4.3.6-Linux/rRNA_databases/silva-bac-23s-id98.fasta
75 | silva_euk_18s: /varidata/research/software/BBC/sortmerna/sortmerna-4.3.6-Linux/rRNA_databases/silva-euk-18s-id95.fasta
76 | silva_euk_28s: /varidata/research/software/BBC/sortmerna/sortmerna-4.3.6-Linux/rRNA_databases/silva-euk-28s-id98.fasta
77 | idx_dir: /varidata/research/software/BBC/sortmerna/sortmerna-4.3.6-Linux/indexes/idx/
78 |
79 | modules:
80 | deeptools: bbc2/deeptools/deeptools-3.5.2
81 | fastqc: bbc2/fastqc/fastqc-0.12.1
82 | fastq_screen: bbc2/fastq_screen/fastq_screen-0.14.0
83 | gatk: bbc2/gatk/gatk-4.3.0.0
84 | htslib: bbc2/htslib/htslib-1.17
85 | multiqc: bbc2/multiqc/multiqc-1.14
86 | pandoc: bbc2/pandoc/pandoc-3.1.2
87 | picard: bbc2/picard/picard-3.0.0
88 | # The easiest way to get renv to work is to make sure all packages are already installed and up to date in your user library which will then be simply copied to the project library
89 | R: bbc2/R/alt/R-4.5.0-setR_LIBS_USER
90 | rseqc: bbc2/rseqc/rseqc-5.0.4
91 | salmon: bbc2/salmon/salmon-1.10.0
92 | samtools: bbc2/samtools/samtools-1.17
93 | seqtk: bbc2/seqtk/seqtk-1.3-r115-dirty
94 | snpeff: bbc2/SnpEff/SnpEff-5.1
95 | sortmerna: bbc2/sortmerna/sortmerna-4.3.6
96 | star: bbc2/STAR/STAR-2.7.10a
97 | trim_galore: bbc2/trim_galore/trim_galore-0.6.10
98 | ucsctools: bbc2/ucsc_tools/ucsc_tools-20231127
99 | vt: bbc2/vt/vt-0.1.16
100 |
--------------------------------------------------------------------------------
/config/group_chroms.R:
--------------------------------------------------------------------------------
1 | library(yaml)
2 | library(readr)
3 | suppressPackageStartupMessages(library(GenomeInfoDb))
4 | suppressPackageStartupMessages(library(magrittr))
5 | suppressPackageStartupMessages(library(Rsamtools))
6 |
7 | # params from workflow
8 | # check if quick_ref is specified
9 | quick_ref <- read_yaml("config.yaml")$quick_ref
10 | if (is.null(quick_ref$species_name)) {
11 | cat("Using the index files manually specified in the config file.\n")
12 | ref_fasta <- read_yaml("config.yaml")$ref$sequence
13 | } else {
14 | cat("Using quick_ref instead of manually indicated index files.\n")
15 | if (is.null(quick_ref$ref_genome_version)) {
16 | cat("Version number not specified. Will use the latest version of the BBC-curated reference files.\n")
17 | quick_ref$ref_genome_version <- "latest"
18 | }
19 | ref_fasta <- paste0("/varidata/research/projects/bbc/versioned_references/",
20 | quick_ref$ref_genome_version,
21 | "/data/",
22 | quick_ref$species_name,
23 | "/sequence/",
24 | quick_ref$species_name,
25 | ".fa")
26 | if (!file.exists(ref_fasta)) {
27 | stop(paste("The quick_ref reference fasta file does not exist:", ref_fasta))
28 | }
29 | }
30 |
31 | outfile <- "grouped_contigs.tsv"
32 |
33 | # make GenomicRanges from the genome
34 | ref_gr <- as(seqinfo(FaFile(ref_fasta)), "GRanges")
35 |
36 | # output the standard chromosome names as a space-separated text file
37 | std_chroms <- standardChromosomes(ref_gr)
38 | nonstd <- seqlevels(ref_gr)[which(!seqlevels(ref_gr) %in% std_chroms)]
39 |
40 | std_df <- data.frame(name=std_chroms, contigs=std_chroms)
41 | nonstd_df <- data.frame(name="unplaced_contigs", contigs=paste(nonstd, collapse=','))
42 |
43 | if(nonstd_df$contigs != ""){
44 | outdf <- rbind(std_df, nonstd_df)
45 | } else{
46 | outdf <- std_df
47 | }
48 |
49 | write_tsv(outdf, outfile)
50 |
--------------------------------------------------------------------------------
/config/grouped_contigs.tsv:
--------------------------------------------------------------------------------
1 | name contigs
2 | chr1 chr1
3 | chr2 chr2
4 | chr3 chr3
5 | chr4 chr4
6 | chr5 chr5
7 | chr6 chr6
8 | chr7 chr7
9 | chr8 chr8
10 | chr9 chr9
11 | chr10 chr10
12 | chr11 chr11
13 | chr12 chr12
14 | chr13 chr13
15 | chr14 chr14
16 | chr15 chr15
17 | chr16 chr16
18 | chr17 chr17
19 | chr18 chr18
20 | chr19 chr19
21 | chr20 chr20
22 | chr21 chr21
23 | chr22 chr22
24 | chrX chrX
25 | chrY chrY
26 | chrM chrM
27 | unplaced_contigs GL000008.2,GL000009.2,GL000194.1,GL000195.1,GL000205.2,GL000208.1,GL000213.1,GL000214.1,GL000216.2,GL000218.1,GL000219.1,GL000220.1,GL000221.1,GL000224.1,GL000225.1,GL000226.1,KI270302.1,KI270303.1,KI270304.1,KI270305.1,KI270310.1,KI270311.1,KI270312.1,KI270315.1,KI270316.1,KI270317.1,KI270320.1,KI270322.1,KI270329.1,KI270330.1,KI270333.1,KI270334.1,KI270335.1,KI270336.1,KI270337.1,KI270338.1,KI270340.1,KI270362.1,KI270363.1,KI270364.1,KI270366.1,KI270371.1,KI270372.1,KI270373.1,KI270374.1,KI270375.1,KI270376.1,KI270378.1,KI270379.1,KI270381.1,KI270382.1,KI270383.1,KI270384.1,KI270385.1,KI270386.1,KI270387.1,KI270388.1,KI270389.1,KI270390.1,KI270391.1,KI270392.1,KI270393.1,KI270394.1,KI270395.1,KI270396.1,KI270411.1,KI270412.1,KI270414.1,KI270417.1,KI270418.1,KI270419.1,KI270420.1,KI270422.1,KI270423.1,KI270424.1,KI270425.1,KI270429.1,KI270435.1,KI270438.1,KI270442.1,KI270448.1,KI270465.1,KI270466.1,KI270467.1,KI270468.1,KI270507.1,KI270508.1,KI270509.1,KI270510.1,KI270511.1,KI270512.1,KI270515.1,KI270516.1,KI270517.1,KI270518.1,KI270519.1,KI270521.1,KI270522.1,KI270528.1,KI270529.1,KI270530.1,KI270538.1,KI270539.1,KI270544.1,KI270548.1,KI270579.1,KI270580.1,KI270581.1,KI270582.1,KI270583.1,KI270584.1,KI270587.1,KI270588.1,KI270589.1,KI270590.1,KI270591.1,KI270593.1,KI270706.1,KI270707.1,KI270708.1,KI270709.1,KI270710.1,KI270711.1,KI270712.1,KI270713.1,KI270714.1,KI270715.1,KI270716.1,KI270717.1,KI270718.1,KI270719.1,KI270720.1,KI270721.1,KI270722.1,KI270723.1,KI270724.1,KI270725.1,KI270726.1,KI270727.1,KI270728.1,KI270729.1,KI270730.1,KI270731.1,KI270732.1,KI270733.1,KI270734.1,KI270735.1,KI270736.1,KI270737.1,KI270738.1,KI270739.1,KI270740.1,KI270741.1,KI270742.1,KI270743.1,KI270744.1,KI270745.1,KI270746.1,KI270747.1,KI270748.1,KI270749.1,KI270750.1,KI270751.1,KI270752.1,KI270753.1,KI270754.1,KI270755.1,KI270756.1,KI270757.1
28 |
--------------------------------------------------------------------------------
/config/samplesheet/comparisons.tsv:
--------------------------------------------------------------------------------
1 | comparison_name group_test group_reference
2 | trt_vs_untrt trt untrt
3 |
--------------------------------------------------------------------------------
/config/samplesheet/make_units_template.R:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env Rscript
2 | library(optparse)
3 | suppressMessages(library(dplyr))
4 | library(readr)
5 | library(stringr)
6 |
7 | option_list <- list(
8 | make_option(c("-s", "--sample_rgx"), type="character", default="^([^_]+)",
9 | help="regex for sample [default= %default]", metavar="character"),
10 | make_option(c("-r", "--group_rgx"), type="character", default="^([^_]+)",
11 | help="regex for group [default= %default]", metavar="character")
12 | );
13 |
14 | opt_parser <- OptionParser(option_list=option_list);
15 | opt <- parse_args(opt_parser);
16 |
17 |
18 | fq_files <- list.files("../../raw_data/", pattern = "*fastq.gz", recursive=TRUE)
19 | R1_files <- grep("_R1[_\\.]", fq_files, value = TRUE)
20 |
21 | # sample group genotype condition unit fq1 fq2 strandedness
22 | df <- data.frame(fq1 = R1_files) %>%
23 | mutate(sample = str_extract(basename(fq1), opt$sample_rgx),
24 | group = str_extract(basename(fq1), opt$group_rgx),
25 | fq2 = str_replace(fq1, "_R1([_\\.])", "_R2\\1"),
26 | RG="") %>%
27 | arrange(sample) %>%
28 | select(sample,group,fq1,fq2,RG)
29 |
30 | # make sure no fq file listed more than once.
31 | stopifnot(length(df$fq1) == length(unique(df$fq1)))
32 | stopifnot(length(df$fq2) == length(unique(df$fq2)))
33 | stopifnot(length(c(df$fq1, df$fq2)) == length(unique(c(df$fq1, df$fq2))))
34 |
35 | # make sure all R2 files have 'R2' in the name
36 | stopifnot(sum(str_detect(df$fq2, "_R2[_\\.]")) == length(df$fq2))
37 | stopifnot(sum(str_detect(df$fq1, "_R1[_\\.]")) == length(df$fq1))
38 |
39 | # make sure all found fastq files listed
40 | stopifnot(all(sort(c(df$fq1, df$fq2)) == sort(fq_files)))
41 |
42 | write_tsv(df, "units_template.tsv")
43 |
--------------------------------------------------------------------------------
/config/samplesheet/make_units_template.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -e
4 | set -u
5 | set -o pipefail
6 |
7 | module load bbc2/R/alt/R-4.2.1-setR_LIBS_USER
8 | Rscript make_units_template.R
9 |
--------------------------------------------------------------------------------
/config/samplesheet/units.tsv:
--------------------------------------------------------------------------------
1 | sample group fq1 fq2 RG
2 | SRR1039508 untrt SRR1039508_L000_R1_001.fastq.gz SRR1039508_L000_R2_001.fastq.gz
3 | SRR1039509 trt SRR1039509_L000_R1_001.fastq.gz SRR1039509_L000_R2_001.fastq.gz
4 | SRR1039512 untrt SRR1039512_L000_R1_001.fastq.gz SRR1039512_L000_R2_001.fastq.gz
5 | SRR1039513 trt SRR1039513_L000_R1_001.fastq.gz SRR1039513_L000_R2_001.fastq.gz
6 | SRR1039516 untrt SRR1039516_L000_R1_001.fastq.gz SRR1039516_L000_R2_001.fastq.gz
7 | SRR1039517 trt SRR1039517_L000_R1_001.fastq.gz SRR1039517_L000_R2_001.fastq.gz
8 | SRR1039520 untrt SRR1039520_L000_R1_001.fastq.gz SRR1039520_L000_R2_001.fastq.gz
9 | SRR1039521 trt SRR1039521_L000_R1_001.fastq.gz SRR1039521_L000_R2_001.fastq.gz
10 |
--------------------------------------------------------------------------------
/raw_data/.keep:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/resources/deseq_template.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "DESeq2 Analysis"
3 | author: '`r paste0("BBC, Analyst: ", stringr::str_to_title(stringr::str_replace_all(Sys.getenv("USER"), "\\.", " ") ))`'
4 | date: '`r format(Sys.Date(), "%B %d, %Y")`'
5 | output:
6 | html_document:
7 | theme: yeti
8 | code_folding: hide
9 | self_contained: yes
10 | toc: true
11 | toc_depth: 5
12 | toc_float:
13 | collapsed: false
14 | smooth_scroll: false
15 | number_sections: true
16 | params:
17 | se_obj: ""
18 | comparison_name: ""
19 | group_test: ""
20 | group_reference: ""
21 | fdr_cutoff: ""
22 | genes_of_interest: ""
23 | ---
24 |
25 | # Analysis
26 |
27 | ```{r keep_figures, cache=TRUE}
28 | # this chunk is just to keep the _files directory even when we turn off cacheing
29 | ```
30 |
31 | ```{r starttime, echo=TRUE, warning=TRUE, message=TRUE, cache=FALSE, cache.lazy = FALSE}
32 | # save start time for script
33 | start_tm <- Sys.time()
34 | # start_tm
35 | ```
36 |
37 | ```{r make_outdir, echo=TRUE, warning=TRUE, message=TRUE, cache=FALSE, cache.lazy = FALSE}
38 | outdir <- file.path("deseq2_out_files", params$comparison_name)
39 |
40 | dir.create(outdir, recursive=TRUE, showWarnings = FALSE)
41 | if (!dir.exists(outdir)) {
42 | stop(paste0("Failed to create the output directory: '", outdir, "'. ",
43 | "Please check the 'comparison_name' parameter in the config file, ensure the path is valid, ",
44 | "and verify that you have sufficient permissions to create directories."))
45 | }
46 | # message("Output directory: ", outdir)
47 | ```
48 |
49 |
50 | This analysis was started on `r format(start_tm, "%B %d, %Y at %H:%M")`. In addition to this full report, individual result files can be accessed in the "DE Results" tab, under the "Supplementary files" header.
51 |
52 | ```{r setup, include=FALSE}
53 | knitr::opts_chunk$set(echo=TRUE, warning=TRUE, message=TRUE, cache=FALSE, cache.lazy = FALSE, dev=c('png','pdf'),
54 | fig.width=4, fig.height=4, fig.path=paste0(outdir, "/individual_figures/"))
55 | ```
56 |
57 | ## Data Processing
58 |
59 | ### Set Up DESeq2 Analysis
60 |
61 | ```{r load_pkges}
62 | suppressPackageStartupMessages({
63 | library(dplyr)
64 | library(stringr)
65 | library(ggplot2)
66 | library(readr)
67 | library(ggrepel)
68 | library(ComplexHeatmap)
69 | library(DESeq2)
70 | library(patchwork)
71 | library(vegan)
72 | })
73 | ```
74 |
75 |
76 |
77 | ```{r read_se}
78 | se <- readRDS(paste0("../../", params$se_obj))
79 |
80 | # subset se to just samples in this comparison (relevant esp if variance is diff between groups)
81 | se <- se[, colData(se)$group %in% c(params$group_test, params$group_reference)]
82 |
83 | # factor the group column to make sure the reference group is the first level
84 | se$group <- factor(se$group, levels=c(params$group_reference, params$group_test))
85 | ```
86 |
87 |
88 | ```{r check_all_assays, eval=FALSE}
89 | # Let's take a look to see what assays are stored in the SummarizedExperiment object.
90 | assayNames(se)
91 | ```
92 |
93 |
94 | ```{r check_assays}
95 | # Note that DESeq2 assumes the first assay is the raw counts.
96 | stopifnot(assayNames(se)[1] == "counts")
97 | ```
98 |
99 |
100 | ```{r look_se, eval=FALSE}
101 | # To print more information about this SummarizedExperiment object, you can just type its name.
102 | se
103 | ```
104 |
105 | Set up analysis using counts data from the previous steps of the workflow, and
106 | basic meta data given from units.tsv, with group as the variable we're testing.
107 | **Note that no covariates are included here**; if you have a more complex
108 | experimental setup with additional covariates and/or confounders,
109 | this model is overly simplistic and won't accurately model your data --
110 | please modify and/or contact the BBC.
111 |
112 |
113 |
114 |
115 | ```{r make_dds, message=FALSE}
116 | dds <- DESeqDataSet(se, design = ~ group)
117 | ```
118 |
119 | ### Remove genes with low/no expression
120 |
121 | We cannot do meaningful analyses of genes with very low counts. Keeping only genes
122 | with 10 or more total read counts across samples will speed up the analysis.
123 |
124 | ```{r filter_low_genes}
125 | # prefilter genes, keeping only genes with 10 or more total read counts across samples
126 | total_genes <- nrow(dds)
127 | # message(str_glue("Total number of genes: {total_genes}"))
128 |
129 | keep <- rowSums(counts(dds)) >= 10
130 | # message(str_glue("Keeping {sum(keep)} genes."))
131 |
132 | dds <- dds[keep, ]
133 | ```
134 |
135 | The original number of genes was `r total_genes`, and the number of genes kept after filtering is `r sum(keep)`.
136 |
137 | ### Different normalization approaches for different biases
138 |
139 | [Types of biases in RNA-seq](https://vanandelinstitute-my.sharepoint.com/:b:/g/personal/kin_lau_vai_org/EcruvwL-OrBIvCzXZ7HMPlcBo65fu0pucrivMmCwzM98dA?e=yCkfTa)
140 |
141 |
142 | ### Run the DE workflow
143 |
144 | The [DESeq](https://www.rdocumentation.org/packages/DESeq2/versions/1.12.3/topics/DESeq) function is a convenience function from DESeq2 that estimates size factors (normalization) and fits negative binomial GLMs.
145 | This includes the following steps:
146 |
147 | - estimating size factors
148 | - estimating dispersions
149 | - gene-wise dispersion estimates
150 | - mean-dispersion relationship
151 | - final dispersion estimates
152 | - fitting model and testing
153 |
154 | ```{r run_deseq2}
155 | dds <- DESeq(dds, quiet = TRUE)
156 | # message(paste0("Coefficient names are: ", paste(resultsNames(dds), collapse = " ")))
157 | ```
158 |
159 | Coefficients in the model are: `r paste(resultsNames(dds), collapse = ", ")`.
160 |
161 | After the models are fitted, we can test specific pairs of groups for differential expression. For DESeq2, it is recommended to provide the significance cutoff that you wish to use as it affects the multiple testing correction procedure (see [docs](https://www.rdocumentation.org/packages/DESeq2/versions/1.12.3/topics/results)). Here, we'll use the false discovery rate (FDR) cutoff that was provided in the config file (`r params$fdr_cutoff`).
162 |
163 | ```{r run_contrast}
164 | contrast <- c("group", params$group_test, params$group_reference)
165 | fdr_cutoff <- params$fdr_cutoff
166 |
167 | res <- results(dds, contrast=contrast, alpha=fdr_cutoff)
168 | res <- res[order(res$pvalue), ]
169 | ```
170 |
171 | ### Summarize DE results
172 |
173 | Below is a summary of the DE results, including the number of upregulated and downregulated genes, and the total number of genes tested.
174 |
175 | ```{r de_summ}
176 | df <- as.data.frame(res)
177 | data.frame(
178 | Up=sum(df$padj <= fdr_cutoff & df$log2FoldChange > 0, na.rm = TRUE),
179 | Down=sum(df$padj <= fdr_cutoff & df$log2FoldChange < 0, na.rm = TRUE),
180 | Tested=sum(!is.na(df$padj))
181 | ) %>%
182 | knitr::kable() %>%
183 | kableExtra::kable_styling(full_width = FALSE, font_size = 14)
184 | ```
185 |
186 |
187 | ### Shrink log fold changes for lowly expressed genes
188 |
189 | This step does not affect the identification of DE genes, but it can be useful to perform this to obtain more reliable estimates of the log fold changes for visualizations or for ranking genes (e.g. GSEA).
190 |
191 | ```{r lfc_shrink}
192 | lfc_shrink <- lfcShrink(dds, contrast=contrast, type="ashr")
193 |
194 | lfc_shrink <- lfc_shrink[order(lfc_shrink$pvalue), ]
195 |
196 | ```
197 |
198 | Below are MA-plots -- a scatter plot of log2 fold changes (on the y-axis) versus the mean of normalized counts (on the x-axis).
199 | Here, we show both the default log fold changes (LFC) and the shrunken log fold changes.
200 |
201 |
202 | ```{r ma_plots, fig.width=5, fig.height=5}
203 | DESeq2::plotMA(res, main="Default LFC")
204 |
205 | ```
206 |
207 | ```{r ma_plots_shrunken, fig.width=5, fig.height=5}
208 | DESeq2::plotMA(lfc_shrink, main="Shrunken LFC")
209 |
210 | ```
211 |
212 | ## Output results
213 |
214 | ### Output DE results
215 |
216 | Here, we merge the different gene name columns to the DE results and output to a tab-delimited file, which can be opened in Excel for manual perusal. This file is **`r params$comparison_name`_de_res.tsv**, within the *[deseq2_tables/](../extras/deseq2_tables/)* directory.
217 |
218 | ```{r out_de_res_prep}
219 | df <- cbind(as.data.frame(rowData(dds)[rownames(lfc_shrink), 1:4]),
220 | as.data.frame(lfc_shrink)) %>%
221 | tibble::rownames_to_column("ens_gene")
222 | ```
223 |
224 | ```{r out_de_res}
225 | write_tsv(df, file.path(outdir, "de_res.tsv"))
226 | write_rds(df, file.path(outdir, "de_res.rds"))
227 | ```
228 |
229 | ```{r specific_genes_check}
230 | # determine whether any genes have been specified in the config file
231 | genes_specified <- !(params$genes_of_interest %in% c("", "False", "FALSE", "None"))
232 | if (genes_specified) {
233 | genes_of_interest <- params$genes_of_interest %>% strsplit(",") %>% unlist() %>% gsub("\\s+", "", .)
234 | }
235 | ```
236 |
237 | `r if(genes_specified){"### Look for specific genes\nIf we're interested in specific genes (such as genes we'd expect, a priori, to be different),\nwe can check if they are differentially expressed.\nThis is useful for quickly checking if genes of interest are differentially expressed, without having to manually search through the results table.\n\nThe following genes are shown, based on genes specified in the 'genes_of_interest' parameter in the config file."}`
238 |
239 | `r if(genes_specified){"The genes of interest are: "}`
240 | `r if(genes_specified){paste(genes_of_interest, collapse=", ")}`
241 |
242 |
243 | ```{r specific_genes, eval=genes_specified, echo=genes_specified, include=genes_specified}
244 | # message("Genes of interest: ", paste(genes_of_interest, collapse=", "))
245 | df %>%
246 | dplyr::filter(Symbol %in% genes_of_interest) %>%
247 | dplyr::mutate(log2FoldChange = format(log2FoldChange, scientific=FALSE, digits=3),
248 | lfcSE = format(lfcSE, scientific=FALSE, digits=3),
249 | pvalue = format(pvalue, scientific=TRUE, digits=3),
250 | padj = format(padj, scientific=TRUE, digits=3)) %>%
251 | knitr::kable() %>%
252 | kableExtra::kable_styling() %>%
253 | kableExtra::column_spec(9:10, width = "6em")
254 | ```
255 |
256 | ### Output tables with raw counts
257 |
258 | Some folks also find it useful to have tables of the raw counts or the normalized counts. The raw counts can be extracted from the DESeq2 object using either `assay()` or `counts()`. This file is **`r params$comparison_name`_counts.tsv**, within the *[deseq2_tables/](../extras/deseq2_tables/)* directory.
259 |
260 | ```{r out_counts_prep}
261 | df <- cbind(as.data.frame(rowData(dds)[, 1:4]),
262 | assay(dds, "counts")) %>%
263 | tibble::rownames_to_column("ens_gene")
264 | ```
265 |
266 | ```{r out_counts}
267 | write_tsv(df, file.path(outdir, "counts.tsv"))
268 | ```
269 |
270 | ### Output tables with log2 normalized counts
271 |
272 | For the log2 normalized counts, we commonly use the variance stabilized transformation ([VST](https://rdrr.io/bioc/DESeq2/man/varianceStabilizingTransformation.html)). These values can be used for heatmaps, clustering or other downstream applications.
273 | This file is **`r params$comparison_name`_vst.tsv**, within the *[deseq2_tables/](../extras/deseq2_tables/)* directory.
274 |
275 | ```{r out_vst_prep}
276 | vsd <- vst(dds, blind=FALSE)
277 |
278 | vst_df <- as.data.frame(cbind(rowData(vsd)[, 1:4], assay(vsd))) %>%
279 | tibble::rownames_to_column("ens_gene")
280 | ```
281 |
282 | ```{r out_vst}
283 | write_rds(vsd, file.path(outdir, "vsd.rds"))
284 | write_tsv(vst_df, file.path(outdir, "vst.tsv"))
285 |
286 | ```
287 |
288 | ## Some common plots for DEG analysis
289 |
290 | The plots below are some common visualizations for differential expression analysis. Individual plots can be found in the *[deseq2_figures/`r params$comparison_name`/](../extras/deseq2_figures/`r params$comparison_name`/)* directory, for easy access to pdf and png files.
291 |
292 | ### PCA
293 |
294 | Principal Component Analysis (PCA) is a dimensionality reduction technique that
295 | transforms data into a new coordinate system, where the axes (principal components, or PCs)
296 | are ordered by the amount of variance they capture (shown as percentages in the plots below).
297 | PC 1 captures the most variance in the data, followed by PC 2, and so on.
298 | PCA is often used to visualize the variance in data and to identify how samples cluster together based on their expression profiles.
299 |
300 | If group has a significant effect on the variance in the data, we will see that samples cluster together by group in the PCA plot.
301 | If we see samples clustering by some *other* variable (e.g. batch, treatment, age, sex, genotype, etc.), this suggests that this other variable is confounding the results and should be accounted for in the analysis.
302 | If this is the case, you may need to include this variable as a covariate in the model design (e.g. `design = ~ batch + group`).
303 |
304 | **Note, again, that no covariates are included in this analysis**; if you have a more complex
305 | experimental setup with additional covariates and/or confounders,
306 | the model used in this report is overly simplistic and won't accurately model your data --
307 | please modify and/or contact the BBC.
308 |
309 | Here, we will plot the first four principal components, colored by group.
310 |
311 | ```{r pca_func}
312 | # Make PCA plots
313 | make_PCA <- function(in_dds, cols, PCx=1, PCy=2, ntop){
314 | if (ntop > nrow(in_dds)) {
315 | ntop <- nrow(in_dds)
316 | }
317 | mat <- assay(in_dds)
318 | col_data <- as.data.frame(colData(in_dds))
319 |
320 | # row variances
321 | vars <- genefilter::rowVars(mat)
322 | vars_rank <- order(vars, decreasing = TRUE)
323 |
324 | # get most variable genes
325 | mat <- mat[vars_rank[1:ntop], ]
326 |
327 | pcaData <- prcomp(t(mat))
328 |
329 | prop_var <- data.frame(t(summary(pcaData)$importance))
330 | names(prop_var) = c("sd", "prop", "cum")
331 | prop_var$num = 1:nrow(prop_var)
332 |
333 | #pcaData <- plotPCA(in_dds, intgroup=colnames(colData(in_dds)), returnData=TRUE, ...)
334 | percentVar <- round(100 * prop_var$prop)
335 |
336 |
337 | df <- cbind(pcaData$x, col_data)
338 |
339 | out_patchwork <- list()
340 |
341 | for (i in 1:length(cols)){
342 | gg_args <- list(x=str_glue("PC{PCx}"), y=str_glue("PC{PCy}"), color=cols[i], label="sample")
343 | gg_args <- lapply(gg_args, function(x) if (!is.null(x)) sym(x))
344 | out_patchwork <- c(out_patchwork, list(ggplot(df, aes(!!!gg_args)) +
345 | geom_point(size=1) +
346 | scale_color_manual(values = setNames(c("#440154FF","#2A788EFF", ggsci::pal_npg()(length(levels(dds$group))-2)),
347 | levels(dds$group))) +
348 | xlab(paste0(str_glue("PC{PCx}: "),percentVar[PCx],"% variance")) +
349 | ylab(paste0(str_glue("PC{PCy}: "),percentVar[PCy],"% variance")) +
350 | theme_bw() +
351 | ggrepel::geom_text_repel(max.overlaps=5)))
352 | }
353 | wrap_plots(out_patchwork)
354 | }
355 | ```
356 |
357 | ```{r plot_pca, fig.height=4.5, fig.width=9}
358 | (make_PCA(vsd, ntop=10000, cols="group") |
359 | (make_PCA(vsd, ntop=10000, cols="group", PCx = 3, PCy = 4))) +
360 | plot_layout(guides="collect") +
361 | plot_annotation(title = "PCA - All Samples")
362 | ```
363 |
364 | ```{r test_cluster_separation, fig.height=4.5, fig.width=9}
365 | test_clustering <- function(in_dds, ntop) {
366 | if (ntop > nrow(in_dds)) {
367 | ntop <- nrow(in_dds)
368 | }
369 |
370 | mat <- assay(in_dds)
371 | col_data <- as.data.frame(colData(in_dds))
372 |
373 | # row variances
374 | vars <- genefilter::rowVars(mat)
375 | vars_rank <- order(vars, decreasing = TRUE)
376 |
377 | # get most variable genes
378 | mat <- mat[vars_rank[1:ntop], ]
379 |
380 | mat_PERMANOVA <- mat %>%
381 | t() %>%
382 | scale()
383 | mat_PERMANOVA_df <- mat_PERMANOVA %>%
384 | as.data.frame() %>%
385 | tibble::rownames_to_column("sample") %>%
386 | left_join(., as.data.frame(colData(vsd)), by="sample")
387 |
388 | adonis2(mat_PERMANOVA ~ group, data = mat_PERMANOVA_df, method='eu')
389 | }
390 | res_clustering <- test_clustering(vsd, ntop=10000)
391 | res_clustering
392 | ```
393 |
394 | The PERMANOVA test above tests whether the groups are significantly different from each other based on the most variable genes in the dataset.
395 | A significant p-value (e.g. < 0.05) indicates that the groups are significantly different from each other, and that the PCA plot is likely to show separation between the groups.
396 | Here, we see that the groups appear `r if(res_clustering[[1,"Pr(>F)"]] >= 0.05) "*not*"` to be significantly different from each other
397 | (p-value = `r format.pval(res_clustering[[1,"Pr(>F)"]], digits=3)`), indicating that the PCA plot is `r if(res_clustering[[1,"Pr(>F)"]] >= 0.05) "not"` likely to show separation between the groups.
398 |
399 | ### Volcano plot
400 |
401 | Volcano plots are a common way to visualize the results of differential expression analyses.
402 | They plot a fold change metric (here, log2FoldChange) on the x-axis and a significance metric on the y-axis (here, the -log10 p-value).
403 | Genes that are significantly differentially expressed will appear as points in the upper right or upper left areas of the plot, depending on whether they are upregulated or downregulated, respectively.
404 | The directionality of the plot is dependent on which group was specified as the
405 | `group_test` and `group_reference` in the comparisons.tsv -- genes that are
406 | higher in your test group (here, "`r params$group_test`") will show up on the right side of the plot (upregulated).
407 | Genes that are higher in your reference group (here, "`r params$group_reference`") will show up on the left side of the plot (downregulated).
408 |
409 | Below is a volcano plot, with labels for the top 10 genes ranked by absolute log fold change.
410 |
411 |
412 | ```{r make_volc_func}
413 | make_volcano <- function(df, pval_nm, pval_cutoff=0.1){
414 | # remove genes with NA for pvalue
415 | df <- df[which(!is.na(df[[pval_nm]])), ]
416 |
417 | # add gene names
418 | df <- cbind(df, rowData(dds)[rownames(df), 1:4])
419 |
420 | top_genes <- df %>%
421 | dplyr::arrange(desc(abs(df$log2FoldChange))) %>%
422 | dplyr::filter(row_number() <= 10) %>%
423 | rownames()
424 |
425 | df$Sig <- ifelse(df$padj <= pval_cutoff, "Sig", "NS")
426 |
427 | df[[pval_nm]] <- -log10(df[[pval_nm]])
428 |
429 | ggplot(df, aes(x=log2FoldChange, y=.data[[pval_nm]])) +
430 | geom_point(aes(color=Sig), size=0.6) +
431 | scale_color_manual(values=c("black", "salmon")) +
432 | theme_bw() + ylab(str_glue("-log10(", pval_nm,")")) +
433 | geom_text_repel(data=df[top_genes, ],
434 | aes(label=Uniq_syms), max.overlaps=Inf, min.segment.length = 0)
435 | }
436 | ```
437 |
438 | ```{r volcano, fig.width=4, fig.height=4}
439 | make_volcano(as.data.frame(lfc_shrink),
440 | pval_nm="padj", pval_cutoff=fdr_cutoff)
441 | ```
442 |
443 | ### Heatmap
444 |
445 | Heatmaps are a common way to visualize the expression of genes across samples.
446 | Here, the top 20 genes (by absolute log2FoldChange) are selected and plotted,
447 | colored by group.
448 |
449 | ```{r heatmap, fig.width=6, fig.height=6}
450 | top_genes <- rownames(res)[1:20]
451 |
452 | top_se <- se[top_genes, ]
453 | mat <- assay(top_se, "vst")
454 | mat <- t(scale(t(mat), scale=FALSE, center = TRUE))
455 |
456 | # column annot
457 | ht_col_annot <- as.data.frame(colData(top_se)[, "group", drop=FALSE])
458 |
459 | group_lvls <- unique(ht_col_annot$group)
460 | ht_col_colors <- list(group=setNames(c("#440154FF","#2A788EFF", ggsci::pal_npg()(length(group_lvls)-2)),
461 | nm=group_lvls))
462 |
463 | Heatmap(mat,
464 | name = "Mean-centered",
465 | cluster_columns = FALSE,
466 | row_labels=rowData(top_se)$Uniq_syms,
467 | show_column_names = FALSE,
468 | top_annotation=HeatmapAnnotation(df=ht_col_annot,
469 | col=ht_col_colors),
470 | column_title = "Top DE genes",
471 | row_title = paste0(nrow(mat), " genes")
472 | )
473 |
474 |
475 | ```
476 |
477 | ### P value distribution
478 |
479 | The distribution of p-values can give us an idea of the number of differentially expressed genes (DE genes) in our analysis,
480 | and whether the model used for differential expression is appropriate.
481 | We expect the p-values to be uniformly distributed if there are not many DE genes, or anti-conservative (more p-values close to 0) if there are many DE genes.
482 | See [here](http://varianceexplained.org/statistics/interpreting-pvalue-histogram/) for more details about how to interpret these,
483 | and again, contact the BBC if you have questions about your results.
484 |
485 | ```{r pval, fig.width=4, fig.height=4}
486 |
487 | ggplot(data = as.data.frame(lfc_shrink) %>%
488 | dplyr::filter(!is.na(pvalue)),
489 | aes(x = pvalue)) +
490 | geom_histogram(color = "black", fill = "gray55",
491 | breaks = seq(0, 1, 0.05)) + theme_bw() + theme(plot.title=element_text(size=10))
492 |
493 | ```
494 |
495 | # Appendix
496 |
497 | *Want to make sense of your differential expression results on a broader level?*
498 |
499 | See [gsea_`r params$comparison_name`.html](gsea_`r params$comparison_name`.html) for a pathway-level analysis using GSEA (Gene Set Enrichment Analysis),
500 | a method for determining whether the changes you see between your groups (`r params$group_test` and `r params$group_reference`) are similar to known pathways/genesets. The report contains a summary of the results, including the top enriched pathways, as well as visualizations of the results. This can help you understand the biological significance of your results and identify potential pathways that are affected by the changes in gene expression.
501 |
502 | And, as always, contact the BBC if you have questions about your results!
503 |
504 |
505 | ## SessionInfo
506 |
507 | ```{r sessioninfo}
508 | sessionInfo()
509 | ```
510 |
511 | ## Runtime
512 |
513 | ```{r endtime}
514 | # output time taken to run script
515 | end_tm <- Sys.time()
516 | # end_tm
517 | # end_tm - start_tm
518 |
519 | ```
520 |
521 | This analysis was completed on `r format(end_tm, "%B %d, %Y at %H:%M")`, with a total runtime of
522 | `r ifelse(difftime(end_tm, start_tm, units = "mins") < 1, paste0(round(difftime(end_tm, start_tm, units = "secs"), 2), " seconds"), paste0(round(difftime(end_tm, start_tm, units = "mins"), 2), " minutes"))`.
523 |
--------------------------------------------------------------------------------
/resources/gsea_template.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "GSEA"
3 | author: '`r paste0("BBC, Analyst: ", stringr::str_to_title(stringr::str_replace_all(Sys.getenv("USER"), "\\.", " ") ))`'
4 | date: '`r format(Sys.Date(), "%B %d, %Y")`'
5 | output:
6 | html_document:
7 | theme: yeti
8 | code_folding: hide
9 | self_contained: yes
10 | toc: true
11 | toc_depth: 5
12 | toc_float:
13 | collapsed: false
14 | smooth_scroll: false
15 | number_sections: true
16 | params:
17 | orgdb: ""
18 | kegg_org: ""
19 | reactome_org: ""
20 | msigdb_organism: ""
21 | comparison_name: ""
22 | fdr_cutoff: ""
23 | de_res: ""
24 | vsd_rds: ""
25 | pathway_str: ""
26 | # params:
27 | # orgdb: "org.Mm.eg.db"
28 | # kegg_org: "mmu"
29 | # reactome_org: "mouse"
30 | # msigdb_organism: "Mus musculus"
31 | # comparison_name: "ko_v_ctrl"
32 | # fdr_cutoff: "0.1"
33 | # de_res: "../results/deseq2/deseq2_out_files/ko_v_ctrl/de_res.rds"
34 | # vsd_rds: "../results/deseq2/deseq2_out_files/ko_v_ctrl/vsd.rds"
35 | # pathway_str: "Reactome,BP,BP-simplified,KEGG,H,C1,C2,C3,C4,C5,C6,C7,C8"
36 | ---
37 |
38 | # Gene Set Enrichment Analysis
39 |
40 | ```{r keep_figures, cache=TRUE}
41 | # this chunk is just to keep the _files directory even when we turn off cacheing
42 | ```
43 |
44 | ```{r starttime, echo=TRUE, warning=TRUE, message=TRUE, cache=FALSE, cache.lazy = FALSE}
45 | # save start time for script
46 | start_tm <- Sys.time()
47 | start_tm
48 | ```
49 |
50 | ```{r outdir, include=TRUE}
51 |
52 | # Set output directory
53 | outdir <- paste0( params$comparison_name, "_out_files/")
54 |
55 | dir.create(outdir, recursive=TRUE, showWarnings = FALSE)
56 | if (!dir.exists(outdir)) {
57 | stop("Output directory does not exist. Please check the 'comparison_name' parameter in the config file.")
58 | }
59 | ```
60 |
61 |
62 | ```{r setup, include=FALSE}
63 | knitr::opts_chunk$set(echo=TRUE, warning=TRUE, message=TRUE, cache=FALSE, cache.lazy = FALSE, dev=c('png', 'pdf'), fig.width=8, fig.height=8, fig.path=paste0(outdir, "individual_figures/"))
64 |
65 | options(bitmapType='cairo')
66 | ```
67 |
68 | This analysis was started on `r format(start_tm, "%B %d, %Y at %H:%M")`, and the results will be saved in the *`r outdir`* directory.
69 |
70 | ## Data Processing
71 |
72 | ### Analysis setup
73 |
74 | Defining paths to find input data and output results
75 |
76 | ```{r Obtain input data and build output directory}
77 |
78 | DE_rds_path <- paste0("../deseq2/deseq2_out_files/", params$comparison_name, "/de_res.rds")
79 | vsd_rds_path <- paste0("../deseq2/deseq2_out_files/", params$comparison_name, "/vsd.rds")
80 |
81 | orgdb <- params$orgdb
82 | kegg_org <- params$kegg_org
83 | reactome_org <- params$reactome_org
84 | msigdb_organism <- params$msigdb_organism
85 |
86 | ```
87 |
88 | ### Load packages
89 |
90 | ```{r loadlibs, echo=TRUE, warning=TRUE, message=TRUE, cache=FALSE}
91 | suppressPackageStartupMessages({
92 | library(orgdb, character.only=TRUE) # load the org.db for your organism
93 | library(clusterProfiler)
94 | library(ComplexHeatmap)
95 | library(AnnotationDbi)
96 | library(enrichplot)
97 | library(ReactomePA)
98 | library(patchwork)
99 | library(openxlsx)
100 | library(ggplot2)
101 | library(msigdbr)
102 | library(stringr)
103 | library(DESeq2)
104 | library(tibble)
105 | library(aPEAR)
106 | library(dplyr)
107 | library(GO.db)
108 | library(readr)
109 | })
110 | ```
111 |
112 | ### Define user-defined functions
113 |
114 | These functions filter out genes from differential gene expression results, generate the ranking metric for GSEA, and match gene names to data set gene names.
115 |
116 | ```{r define_funcs}
117 | # Remove genes with 0 logFC and PValue = 1, calculate ranking metric then sort Entrez genes in descending order
118 | # Adapts code from
119 | # https://github.com/YuLab-SMU/DOSE/wiki/how-to-prepare-your-own-geneList.
120 | prep_clusterprofiler_genelist <- function(dge_table, rank_by="log2FoldChange", pval_col="pvalue", lfc_col="log2FoldChange"){
121 | geneList <- NULL
122 |
123 | # calculate rank_metric
124 | if(identical(rank_by, "log2FoldChange")){
125 | if(!pval_col %in% colnames(dge_table)){
126 | stop("Specify valid column for PValue.")
127 | }
128 | if(!lfc_col %in% colnames(dge_table)){
129 | stop("Specify valid column for log fold change.")
130 | }
131 | # filter away genes with exactly 0 logFC and PValue = 1.
132 | dge_table <- dge_table[dge_table[[lfc_col]] != 0 &
133 | dge_table[[pval_col]] != 1, ]
134 |
135 | ## feature 1: numeric vector
136 | geneList <-
137 | sign(dge_table[[lfc_col]]) * -log10(dge_table[[pval_col]])
138 |
139 | } else{
140 | if(!rank_by %in% colnames(dge_table)){
141 | message(rank_by)
142 | message(colnames(dge_table))
143 | stop("Specify valid ranking metric.")
144 | }
145 | # For genes with duplicated ranking metric value, we keep the first occurrence of the duplicated value only.
146 | dge_table <- dge_table[!duplicated(dge_table[[rank_by]]), ]
147 |
148 | ## feature 1: numeric vector
149 | geneList <- dge_table[[rank_by]]
150 | }
151 |
152 | ## feature 2: named vector
153 | names(geneList) <- as.character(dge_table$entrez)
154 | ## feature 3: decreasing order
155 | geneList <- sort(geneList, decreasing = TRUE)
156 |
157 | return(geneList)
158 | }
159 |
160 |
161 | # Get the genesets and format for clusterprofiler (dataframe with col1 = geneset name, col2 = entrez gene)
162 | # organisms is 'Homo sapiens' or 'Mus musculus'
163 | # if no msigdb subcat, then specify as NA
164 | get_geneset <- function(gene_set, msigdb_subcat=NA, organism){
165 | if (gene_set %in% c("H", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8")){
166 | msigdbr_args <- list(species = organism, category = gene_set, subcat=msigdb_subcat)
167 | msigdbr_args <- msigdbr_args[!sapply(msigdbr_args, is.na)] # remove 'subcat' param if it is NA
168 |
169 | msigdbr_gene_set <- do.call(msigdbr::msigdbr, msigdbr_args)
170 |
171 | # convert to clusterprofiler friendly format
172 | geneset_out <- msigdbr_gene_set[, c("gs_name", "entrez_gene")] %>%
173 | as.data.frame(stringsAsFactors = FALSE)
174 |
175 | } else{
176 | stop("Invalid value for gene_set parameter.")
177 | }
178 |
179 | return(geneset_out)
180 |
181 | }
182 |
183 | ```
184 |
185 | ### Read in DE results
186 |
187 | ```{r read_DE}
188 | # set seed for gsea
189 | gsea_seed <- 2024
190 |
191 | vsd <- readRDS(vsd_rds_path)
192 | vsd_mat <- assay(vsd)
193 | row_meta <- rowData(vsd)
194 |
195 | de_objs <- readRDS(DE_rds_path)
196 |
197 | de_res <- as.data.frame(de_objs)
198 |
199 | de_res <- list(de_res)
200 | ```
201 |
202 | ### Process the DE results
203 |
204 | ```{r calc_ranks}
205 | genes_and_score <- lapply(de_res, prep_clusterprofiler_genelist, rank_by="log2FoldChange")
206 | sapply(genes_and_score, length)
207 |
208 | # remove genes with no Entrez ID (isNA)
209 | genes_and_score <- lapply(genes_and_score, function(x) x[!is.na(names(x))])
210 | sapply(genes_and_score, length)
211 |
212 | # remove genes with duplicated Entrez ID
213 | genes_and_score <- lapply(genes_and_score, function(x) {
214 | ids <- names(x)
215 | duplicated_ids <- unique(ids[duplicated(ids)])
216 | x[!ids %in% duplicated_ids]
217 | })
218 | sapply(genes_and_score, length)
219 |
220 | # Confirm genes are ordered in decreasing order
221 | correct_ranking <- sapply(genes_and_score, function(x) {
222 | all(order(x, decreasing = TRUE) == 1:length(x))
223 | })
224 | stopifnot(all(correct_ranking))
225 |
226 | ```
227 |
228 | ## Run GSEA
229 |
230 | Gene ranking lists are processed through the gene sets listed in the config file.
231 |
232 | ```{r get_genesets_and_run_gsea, warning=FALSE, verbose=FALSE, message=FALSE, results='hide'}
233 |
234 | pathwayNames = unlist(strsplit(params$pathway_str, ",")[[1]])
235 |
236 | gsea_res <- lapply(setNames(nm=pathwayNames), function(ont){
237 | message("Running GSEA for ", ont)
238 | lapply(genes_and_score, function(y){
239 | set.seed(gsea_seed) # make reproducible
240 | if (ont %in% c("H", paste0("C", as.character(1:8)))){
241 | geneset <- get_geneset(gene_set=ont, msigdb_subcat=NA, organism=msigdb_organism)
242 | gsea_res <- clusterProfiler::GSEA(geneList = y,
243 | TERM2GENE = geneset,
244 | eps = 0.0 # need to set this or Pvalues will not reach below 1e-10
245 | )
246 |
247 | } else if (ont=="Reactome"){
248 | gsea_res <- gsePathway(geneList = y, organism = reactome_org,
249 | eps = 0.0 # need to set this or Pvalues will not reach below 1e-10
250 | )
251 | } else if (ont=="KEGG") {
252 | gsea_res <- gseKEGG(geneList = y, organism = kegg_org,
253 | eps = 0.0 # need to set this or Pvalues will not reach below 1e-10
254 | )
255 | } else{
256 | gsea_res <- clusterProfiler::gseGO(geneList = y,
257 | ont=gsub(ont, pattern = "-.*", replacement = ""),
258 | OrgDb = eval(as.symbol(orgdb)),
259 | eps = 0.0 # need to set this or Pvalues will not reach below 1e-10
260 | )
261 | }
262 |
263 | gsea_res_syms <- DOSE::setReadable(gsea_res,
264 | OrgDb = eval(as.symbol(orgdb)),
265 | keyType = "ENTREZID")
266 |
267 | list(entrez=gsea_res, symbols=gsea_res_syms)
268 |
269 | })
270 | })
271 |
272 | # output to file
273 | write_rds(gsea_res, paste0(outdir, "gsea_res.rds"))
274 |
275 | invisible(lapply(names(gsea_res), function(geneset){
276 | write.xlsx(
277 | lapply(gsea_res[[geneset]],
278 | function(res_list) as_tibble(res_list$symbols)),
279 | file = paste0(outdir, "/", geneset, "_gsea.xlsx"),
280 | overwrite = TRUE)
281 | }))
282 | ```
283 |
284 | ## Summary Plots
285 |
286 | ### Dot Plots
287 |
288 | Here, dot plots are built to recapitulate findings from our GSEA.
289 |
290 | ```{r plots, fig.width=7, fig.height=5}
291 | dotplots <- lapply(setNames(nm=names(gsea_res)), function(geneset){
292 | # lapply(setNames(nm=names(gsea_res[[geneset]])), function(contrast){
293 | if (geneset == "BP-simplified") {
294 | gseaResult <- clusterProfiler::simplify(gsea_res[[geneset]][[1]]$symbols)
295 | } else {
296 | gseaResult <- gsea_res[[geneset]][[1]]$symbols
297 | }
298 | #gseaResult <- filter(gseaResult, p.adjust < p_cutoff)
299 | if(nrow(gseaResult) > 0){
300 | dotplot(gseaResult, split=".sign") + ggtitle(paste0(params$comparison_name," -- ", geneset)) +
301 | scale_y_discrete(label=function(x) str_wrap(str_trunc(str_remove(x, paste0("HALLMARK_|\\s-\\s", params$msigdb_organism,".*")), 15), width = 60)) +
302 | facet_grid(.~.sign) #+
303 | # theme(text=element_text(size = 20),
304 | # axis.title.x = element_text(size = 20))
305 |
306 | } else {
307 | "No significant results"
308 | }
309 | # })
310 | })
311 |
312 | for (i in 1:length(dotplots)){
313 | dotplot_list <- dotplots[[i]]
314 | if (is(dotplot_list, "ggplot")) {
315 | print(wrap_plots(dotplot_list, ncol=1) + plot_annotation(title = names(dotplots)[i]))
316 | } else {
317 | isggplot <- sapply(dotplot_list, function(x) is(x, "ggplot"))
318 | if(sum(isggplot) > 0){
319 | print(wrap_plots(dotplot_list[isggplot], ncol=1) + plot_annotation(title = names(dotplots)[i]))
320 | }
321 | }
322 | }
323 | ```
324 |
325 | ### Gene networks
326 |
327 | We can use a package called aPEAR to display genes inside networks found in significant pathways from your data. Each ellipse encompasses a set of related pathways that contain similar genes.
328 |
329 | ```{r aPEAR}
330 |
331 | set.seed(gsea_seed)
332 |
333 | aPEARobj = lapply(seq_along(gsea_res), FUN = function(x){
334 |
335 | gseaResObj = gsea_res[[x]][[1]]$entrez
336 | resSetName = names(gsea_res)[[x]]
337 |
338 | tryCatch({
339 |
340 | p <- aPEAR::enrichmentNetwork(gseaResObj@result, drawEllipses = TRUE, fontSize = 6) + ggtitle(paste0(params$comparison_name," -- ", resSetName)) + theme(text=element_text(size = 20))
341 |
342 | return(p)
343 |
344 | }, error = function(cond) {
345 |
346 | p <- ggplot() + # Draw ggplot2 plot with text only
347 | annotate("text",
348 | x = 1,
349 | y = 1,
350 | size = 8,
351 | label = paste0("No networks for ", params$comparison_name," -- ", resSetName)) +
352 | theme_void()
353 |
354 | return(p)
355 |
356 | })
357 |
358 | })
359 |
360 | for (i in 1:length(aPEARobj)){
361 | dotplot_list <- aPEARobj[[i]]
362 | if (is(dotplot_list, "ggplot")) {
363 | # print(wrap_plots(dotplot_list, ncol=1) + plot_annotation(title = names(dotplots)[i]))
364 | print(wrap_plots(dotplot_list, ncol=1))
365 | } else {
366 | isggplot <- sapply(dotplot_list, function(x) is(x, "ggplot"))
367 | if(sum(isggplot) > 0){
368 | # print(wrap_plots(dotplot_list[isggplot], ncol=1) + plot_annotation(title = names(dotplots)[i]))
369 | print(wrap_plots(dotplot_list[isggplot], ncol=1))
370 | }
371 | }
372 | }
373 |
374 | ```
375 |
376 | ### Session Info
377 |
378 | This shows what software and the specific version used in the analysis, which is quite useful for useful reference and reproducibility.
379 |
380 | ```{r session_info, echo = TRUE, eval=TRUE}
381 | sessionInfo()
382 | ```
383 |
384 | ### Time
385 |
386 | Measure time passed for the analysis to gauge how long a re-run will take.
387 |
388 | ```{r endtime}
389 | # output time taken to run script
390 | end <- Sys.time()
391 | end
392 | end - start_tm
393 |
394 | ```
395 |
--------------------------------------------------------------------------------
/resources/iSEE_app.R:
--------------------------------------------------------------------------------
1 | library(iSEE)
2 |
3 | sce <- readRDS("sce.rds")
4 |
5 | rowData(sce) <- rowData(sce)[, setdiff(colnames(rowData(sce)), c("Uniq_syms"))]
6 | search_cols <- rep("", length(colnames(rowData(sce))))
7 | search_cols[grep("\\.rank$", colnames(rowData(sce)))[1]] <- "1 ... 50" # top 50 genes of the first contrast
8 |
9 | # To deploy to shinyapp.io, run manually:
10 | # usethis::proj_activate(<<>>)
11 | # options(repos = BiocManager::repositories())
12 | # rsconnect::deployApp(appDir=<<>>, appName = '<<>>')
13 | # You may need to follow the instructions at https://docs.posit.co/shinyapps.io/guide/getting_started/#configure-rsconnect to set up your shinyapps.io credentials
14 |
15 | iSEE(sce,
16 | initial=list(ComplexHeatmapPlot(PanelWidth=6L, PanelHeight=1000L,
17 | CustomRows=FALSE,
18 | Assay="vst",
19 | ClusterRows=TRUE,
20 | ShowColumnSelection=FALSE,
21 | ColumnData=c("group"),
22 | AssayCenterRows=TRUE, DataBoxOpen=TRUE,
23 | VisualBoxOpen=TRUE, NamesRowFontSize=14,
24 | NamesColumnFontSize=14, ShowDimNames=c("Rows","Columns"),
25 | RowSelectionSource="RowDataTable1",
26 | LegendPosition="Right",
27 | LegendDirection="Vertical"),
28 | RowDataTable(PanelWidth=6L, SearchColumns=search_cols,
29 | HiddenColumns=c("entrez","Gene_name","alias","ens_gene",
30 | grep("\\.LFC$", colnames(rowData(sce)), value = TRUE),
31 | grep("\\.padj$", colnames(rowData(sce)), value = TRUE))),
32 | FeatureAssayPlot(DataBoxOpen=TRUE, PanelWidth=6L, Assay="vst",
33 | XAxis="Column data", XAxisColumnData="group",
34 | ColorBy="Column data", ColorByColumnData="group",
35 | FontSize=1.5, PointSize=2),
36 | ReducedDimensionPlot(PanelWidth=6L, ColorBy="Column data", ColorByColumnData="group", FontSize=1.5, PointSize=2)
37 | ),
38 | appTitle="App for exploring RNA-seq dataset")
39 |
40 |
41 |
--------------------------------------------------------------------------------
/resources/report_template/_site.yml:
--------------------------------------------------------------------------------
1 | name: "BBC_RNAseq_Report"
2 | output_dir: "BBC_RNAseq_Report"
3 | navbar:
4 | title: "
"
5 | # get more icons from https://fontawesome.com/
6 | left:
7 | - text: "Home"
8 | href: index.html
9 | icon: fa-solid fa-house
10 | - text: "MultiQC"
11 | href: multiqc.html
12 | icon: fa-square-poll-vertical
13 | - text: "DE results"
14 | icon: glyphicon-sort
15 | menu:
16 | - text: "HTML reports"
17 | <<>>
18 | - text: "---------"
19 | - text: "Supplemental files"
20 | - text: "High-res figures"
21 | href: ./extras/deseq2_figures/
22 | - text: "DE result tables"
23 | href: ./extras/deseq2_tables/
24 | - text: "GSEA results"
25 | icon: glyphicon-signal
26 | menu:
27 | - text: "HTML reports"
28 | <<>>
29 | - text: "---------"
30 | - text: "Supplemental files"
31 | - text: "High-res figures"
32 | href: ./extras/gsea_figures/
33 | - text: "GSEA result tables"
34 | href: ./extras/gsea_tables/
35 | <<>>
36 | right:
37 | - href: https://github.com/vari-bbc/rnaseq_workflow
38 | icon: fa-github
39 | text: Code
40 | output:
41 | html_document:
42 | self_contained: true
43 | theme: bootstrap
44 | css: styles.css
45 | highlight: textmate
46 | include:
47 | after_body: footer.html
48 |
--------------------------------------------------------------------------------
/resources/report_template/footer.html:
--------------------------------------------------------------------------------
1 |
Generated by VAI BBC.
--------------------------------------------------------------------------------
/resources/report_template/images/VAI_2_Line_White.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vari-bbc/rnaseq_workflow/6ed33f19edefa31f321e4c98d5ec9079960564d5/resources/report_template/images/VAI_2_Line_White.png
--------------------------------------------------------------------------------
/resources/report_template/index.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "RNA-seq analysis"
3 |
4 | bibliography: references.bib
5 | ---
6 |
7 | This report summarizes the RNA-seq analysis performed using the [rnaseq_workflow](https://github.com/vari-bbc/rnaseq_workflow) developed by the Bioinformatics and Biostatistics Core at Van Andel Institute.
8 |
9 | The following sections describe the experimental design, summarize the differential expression results and analytical methods, and provide a list of software versions and references used in the analysis.
10 |
11 | For detailed results, please explore the individual tabs in the interactive report.
12 |
13 |
14 |
15 | ```{r load_lib, include=F, echo=F}
16 | library(configr)
17 | library(tidyverse)
18 | library(kableExtra)
19 | library(SummarizedExperiment)
20 | ```
21 |
22 | ## Experimental design
23 |
24 | We will list sample information for the experimental design below:
25 |
26 | ```{r print_meta, include=T, echo=F, message=F, warning=F}
27 | se <- readRDS("../../results/SummarizedExperiment/SummarizedExperiment.rds")
28 | meta <- colData(se) |>
29 | as.data.frame() |>
30 | tibble::rownames_to_column("sample_name") |>
31 | dplyr::select(-RG)
32 |
33 | meta |>
34 | kbl(caption = "Sample information", row.names = FALSE) |>
35 | kable_classic_2(full_width = F)
36 | ```
37 |
38 |
39 |
40 | ## DE gene summary
41 |
42 | ```{r deseq_sum, include=T, echo=F, message=F, warning=F}
43 | config_file <- read.config("../../config/config.yaml")
44 | fdr <- config_file$fdr_cutoff
45 | comparisons <- list.files("../../results/deseq2/deseq2_out_files/")
46 | comparisons <- setNames(comparisons, nm = comparisons)
47 |
48 | de_sum_all <- do.call(rbind, (lapply(comparisons, function(comparison) {
49 | de_res <- read_tsv(paste0("../../results/deseq2/deseq2_out_files/", comparison, "/de_res.tsv"))
50 | df_sum <- data.frame( Contrast = comparison,
51 | Num_up_genes = de_res |> filter(padj < fdr & log2FoldChange > 0) |> nrow(),
52 | Num_down_genes = de_res |> filter(padj < fdr & log2FoldChange < 0) |> nrow())
53 | return(df_sum)
54 | }) ) )
55 |
56 | de_sum_all |>
57 | kbl(caption = paste0("DE gene summary (FDR cutoff = ", fdr, ")"), row.names = FALSE) |>
58 | kable_classic_2(full_width = F)
59 |
60 | ```
61 |
62 |
63 |
64 | ## Method summary
65 |
66 | Adaptor sequences and low-quality bases were trimmed from RNA-seq reads using Trim Galore. Trimmed reads were then aligned to refernece genome using STAR with the "--quantMode GeneCounts" parameter enabled.
67 |
68 | Raw count data were input into DESeq2, where normalization was performed and dispersion estimates were then computed, and a generalized linear model was fit to test for differential expression. P-values were adjusted for multiple testing using the Benjamini–Hochberg method to control the false discovery rate (FDR). Genes with an adjusted p-value below 0.1 (default setup, you can change it in the config.yaml) were considered significantly differentially expressed. For more details about DESeq2 algorithms, please see [DESeq2 vignette](https://www.bioconductor.org/packages/devel/bioc/vignettes/DESeq2/inst/doc/DESeq2.html).
69 |
70 |
71 | Gene set enrichment and pathway enrichment analyses and visualizations are performed using the R Bioconductor package clusterProfiler. For more details about ClusterProfiler, please see [clusterProfiler vignette](https://yulab-smu.top/biomedical-knowledge-mining-book/)
72 |
73 |
74 |
75 | ## Software versions and references
76 |
77 | ---
78 | nocite: '@*'
79 | ...
80 |
--------------------------------------------------------------------------------
/resources/report_template/multiqc.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "MultiQC"
3 |
4 | ---
5 |
6 |
7 |
--------------------------------------------------------------------------------
/resources/report_template/references.bib:
--------------------------------------------------------------------------------
1 | @article{mccarthy_differential_2012,
2 | title = {Differential expression analysis of multifactor {RNA}-Seq experiments with respect to biological variation},
3 | volume = {40},
4 | issn = {0305-1048},
5 | url = {https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3378882/},
6 | doi = {10.1093/nar/gks042},
7 | abstract = {A flexible statistical framework is developed for the analysis of read counts from {RNA}-Seq gene expression studies. It provides the ability to analyse complex experiments involving multiple treatment conditions and blocking variables while still taking full account of biological variation. Biological variation between {RNA} samples is estimated separately from the technical variation associated with sequencing technologies. Novel empirical Bayes methods allow each gene to have its own specific variability, even when there are relatively few biological replicates from which to estimate such variability. The pipeline is implemented in the {edgeR} package of the Bioconductor project. A case study analysis of carcinoma data demonstrates the ability of generalized linear model methods ({GLMs}) to detect differential expression in a paired design, and even to detect tumour-specific expression changes. The case study demonstrates the need to allow for gene-specific variability, rather than assuming a common dispersion across genes or a fixed relationship between abundance and variability. Genewise dispersions de-prioritize genes with inconsistent results and allow the main analysis to focus on changes that are consistent between biological replicates. Parallel computational approaches are developed to make non-linear model fitting faster and more reliable, making the application of {GLMs} to genomic data more convenient and practical. Simulations demonstrate the ability of adjusted profile likelihood estimators to return accurate estimators of biological variability in complex situations. When variation is gene-specific, empirical Bayes estimators provide an advantageous compromise between the extremes of assuming common dispersion or separate genewise dispersion. The methods developed here can also be applied to count data arising from {DNA}-Seq applications, including {ChIP}-Seq for epigenetic marks and {DNA} methylation analyses.},
8 | pages = {4288--4297},
9 | number = {10},
10 | journaltitle = {Nucleic Acids Research},
11 | shortjournal = {Nucleic Acids Res},
12 | author = {{McCarthy}, Davis J. and Chen, Yunshun and Smyth, Gordon K.},
13 | urldate = {2020-08-05},
14 | date = {2012-05},
15 | pmid = {22287627},
16 | pmcid = {PMC3378882},
17 | file = {PubMed Central Full Text PDF:/Users/kin.lau/Zotero/storage/ZC8P9E3L/McCarthy et al. - 2012 - Differential expression analysis of multifactor RN.pdf:application/pdf},
18 | }
19 |
20 | @article{love_moderated_2014,
21 | title = {Moderated estimation of fold change and dispersion for {RNA}-seq data with {DESeq}2},
22 | volume = {15},
23 | issn = {1474-760X},
24 | url = {http://dx.doi.org/10.1186/s13059-014-0550-8},
25 | doi = {10.1186/s13059-014-0550-8},
26 | abstract = {In comparative high-throughput sequencing assays, a fundamental task is the analysis of count data, such as read counts per gene in {RNA}-seq, for evidence of systematic changes across experimental conditions. Small replicate numbers, discreteness, large dynamic range and the presence of outliers require a suitable statistical approach. We present {DESeq}2, a method for differential analysis of count data, using shrinkage estimation for dispersions and fold changes to improve stability and interpretability of estimates. This enables a more quantitative analysis focused on the strength rather than the mere presence of differential expression. The {DESeq}2 package is available at http://www.bioconductor.org/packages/release/bioc/html/{DESeq}2.html .},
27 | pages = {550},
28 | journaltitle = {Genome Biology},
29 | shortjournal = {Genome Biology},
30 | author = {Love, Michael I. and Huber, Wolfgang and Anders, Simon},
31 | urldate = {2017-05-15},
32 | date = {2014},
33 | file = {Full Text PDF:/Users/kin.lau/Zotero/storage/KZHZDWGC/Love et al. - 2014 - Moderated estimation of fold change and dispersion.pdf:application/pdf;Snapshot:/Users/kin.lau/Zotero/storage/8ZZ9CUZQ/s13059-014-0550-8.html:text/html},
34 | }
35 |
36 | @article{yu_omics_2012,
37 | title = {clusterProfiler: an R package for comparing biological themes among gene clusters},
38 | author = {Guangchuang Yu and Li-Gen Wang and Yanyan Han and Qing-Yu He},
39 | journal = {OMICS: A Journal of Integrative Biology},
40 | year = {2012},
41 | volume = {16},
42 | number = {5},
43 | pages = {284-287},
44 | pmid = {22455463},
45 | doi = {10.1089/omi.2011.0118},
46 | }
47 |
48 | @article{yu_cluster_4.0,
49 | title = {clusterProfiler 4.0: A universal enrichment tool for interpreting omics data},
50 | author = {Tianzhi Wu and Erqiang Hu and Shuangbin Xu and Meijun Chen and Pingfan Guo and Zehan Dai and Tingze Feng and Lang Zhou and Wenli Tang and Li Zhan and xiaochong Fu and Shanshan Liu and Xiaochen Bo and Guangchuang Yu},
51 | journal = {The Innovation},
52 | year = {2021},
53 | volume = {2},
54 | number = {3},
55 | pages = {100141},
56 | doi = {10.1016/j.xinn.2021.100141},
57 | }
58 |
59 | @article{yu_13years_clusterprofiler_2024,
60 | title = {Thirteen years of clusterProfiler},
61 | author = {Guangchuang Yu},
62 | url = {https://doi.org/10.1016/j.xinn.2024.100722},
63 | doi = {10.1016/j.xinn.2024.100722},
64 | journal = {The Innovation},
65 | month = {Nov},
66 | year = {2024},
67 | volume = {5},
68 | number = {6},
69 | pages = {100722},
70 | }
71 |
72 | @misc{felix_trim_galore_v0.6.10,
73 | doi = {10.5281/ZENODO.7598955},
74 | url = {https://zenodo.org/record/7598955},
75 | author = {Krueger, Felix and James, Frankie and Ewels, Phil and Afyounian, Ebrahim and Weinstein, Michael and Schuster-Boeckler, Benjamin and Hulselmans, Gert and {Sclamons}},
76 | title = {FelixKrueger/TrimGalore: v0.6.10 - add default decompression path},
77 | publisher = {Zenodo},
78 | year = {2023},
79 | copyright = {Open Access}
80 | }
81 |
--------------------------------------------------------------------------------
/resources/report_template/styles.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: Arial;
3 | font-size: 14pt;
4 | }
5 |
6 | .container{
7 | max-width: 80% !important;
8 | }
9 |
10 | .main-container {
11 | max-width: 80% !important;
12 | }
13 |
14 |
15 | h1 {
16 | font-size: 22pt;
17 | font-weight: bold;
18 | }
19 |
20 | h2, h3, h4, h5, h6 {
21 | font-size: 22pt;
22 | font-weight: bold;
23 | padding-top: 100px !important;
24 | }
25 |
26 | .navbar-default {
27 | background-color: #005596;
28 | min-height: 80px;
29 | }
30 |
31 | .navbar-brand {
32 | color: #fff !important;
33 | font-family: Arial, sans-serif !important;
34 | }
35 |
36 | .navbar.navbar-default ul li a {
37 | color: white;
38 | text-decoration: none;
39 | font-size: 14pt;
40 | font-family: Arial, sans-serif;
41 | padding-top: 26.5px;
42 | padding-bottom: 26.5px;
43 | line-height: 27px;
44 | }
45 |
46 | .navbar-default .navbar-nav > .active > a {
47 | color: #005596;
48 | background-color: #60abde !important;
49 | }
50 |
51 | .navbar-default .navbar-nav > .open > a,
52 | a.dropdown-toggle:hover {
53 | color: #60abde !important;
54 | background-color: #005596 !important;
55 | }
56 |
57 | .navbar-default .dropdown-menu {
58 | background-color: #005596 !important;
59 | }
60 |
61 | .navbar-default .dropdown-menu > li > a {
62 | background-color: #005596;
63 | padding-top: 6px !important;
64 | padding-bottom: 6px !important;
65 | }
66 |
67 | .navbar-default .dropdown-menu > li > a:hover {
68 | background-color: #60abde !important;
69 | color: #005596 !important;
70 | }
71 |
72 | .navbar-default .dropdown-header {
73 | background-color: #005596;
74 | color: white !important;
75 | font-weight: bold !important;
76 | text-decoration: underline !important;
77 | font-size: 14pt !important;
78 | margin-top: 10px;
79 | margin-bottom:
80 |
81 |
--------------------------------------------------------------------------------
/schema/units.schema.yaml:
--------------------------------------------------------------------------------
1 | $id: "http://json-schema.org/draft-06/schema#"
2 | $schema: "http://json-schema.org/draft-06/schema#"
3 | description: an entry in the sample sheet
4 | properties:
5 | sample:
6 | type: string
7 | description: sample name/identifier
8 | group:
9 | type: string
10 | description: Experimental group
11 | fq1:
12 | type: string
13 | description: fastq R1
14 | fq2:
15 | type: string
16 | description: fastq R2
17 | RG:
18 | type: string
19 | description: Read group to be assigned by STAR
20 |
21 | required:
22 | - sample
23 | - group
24 | - fq1
25 | - fq2
26 | - RG
27 |
--------------------------------------------------------------------------------
/workflow/Snakefile:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import numpy as np
3 | import os
4 | from shutil import which
5 | from snakemake.utils import validate, min_version
6 | import itertools
7 |
8 | ##### set minimum snakemake version #####
9 | min_version("7.25.0")
10 |
11 | ##### load config and sample sheets #####
12 |
13 | configfile: "config/config.yaml"
14 |
15 | units = pd.read_table(config["units"], dtype={"sample" : str, "group" : str, "fq1" : str, "fq2" : str, "RG" : str})
16 | units["RG"] = units["RG"].fillna("")
17 | validate(units, "../schema/units.schema.yaml")
18 | units['group_index'] = units.groupby('sample').cumcount().astype(str)
19 | print(units)
20 | if not (units['fq1'].is_unique and units['fq2'].is_unique):
21 | raise Exception('Same fastq specified in more than one row.')
22 |
23 | samples = units[["sample","group"]].drop_duplicates()
24 | if not samples['sample'].is_unique:
25 | raise Exception('A sample has more than one group.')
26 | valid_groups = samples.groupby(['group'])['group'].count() > 1
27 |
28 | if not (valid_groups.all()):
29 | raise Exception('Each group in the samplesheet must have at least two samples.')
30 |
31 |
32 | Rproj_packages_vals = pd.read_table("config/R_proj_packages.txt", header=None)[0].values
33 | Rproj_packages = "c('" + "','".join(Rproj_packages_vals) + "')"
34 |
35 | # comparisons: list of comparisons (contrasts) to be tested
36 | comparisons = pd.read_table(config["comparisons"]) #, dtype={"comparison_name" : str, "group_test" : str, "group_reference" : str})
37 | if not (comparisons['group_test'].isin(samples['group']).all() and comparisons['group_reference'].isin(samples['group']).all()):
38 | raise Exception('A group in the comparisons file is not in the samplesheet.')
39 |
40 |
41 | snakemake_dir = os.getcwd() + "/"
42 |
43 | # make a tmp directory for analyses
44 | tmp_dir = os.path.join(snakemake_dir, "tmp")
45 | if not os.path.exists(tmp_dir):
46 | os.mkdir(tmp_dir)
47 |
48 |
49 |
50 | # Need this directive because both PE and SE versions of these rules produce the trimmed R1 output files.
51 | ruleorder: trim_galore_PE > trim_galore_SE
52 |
53 |
54 |
55 | # below is to process quick ref genome information:
56 | quick_ref_id = config['quick_ref']['species_name']
57 | quick_vers = config['quick_ref']['ref_genome_version']
58 |
59 | print("\n")
60 | if quick_ref_id:
61 | if config['call_variants']:
62 | raise Exception("Quick references not supported when variant calling is requested.")
63 |
64 | print("Using quick_ref instead of manually indicated index files.")
65 |
66 | # erase manually specified files to prevent accidentally mixing files from different versions
67 | config['ref'] = {}
68 |
69 | ref_base_dir = "/varidata/research/projects/bbc/versioned_references"
70 |
71 | if quick_vers:
72 | ref_base_dir = f'{ref_base_dir}/{quick_vers}'
73 | else:
74 | print(f'Version number not specified. Will use the latest version of the BBC-curated reference files.')
75 | ref_base_dir = os.readlink(f"{ref_base_dir}/latest")
76 |
77 | ref_base_dir = f'{ref_base_dir}/data/{quick_ref_id}'
78 | print(f'Using the index files in {ref_base_dir}.\n')
79 |
80 | config['ref']['index'] = f'{ref_base_dir}/indexes/star'
81 | config['ref']['salmon_index'] = f'{ref_base_dir}/indexes/salmon/{quick_ref_id}'
82 | config['ref']['annotation'] = f'{ref_base_dir}/annotation/{quick_ref_id}.gtf'
83 | config['ref']['dict'] = f'{ref_base_dir}/sequence/{quick_ref_id}.dict'
84 |
85 | else:
86 | print("Using the index files manually specified in the config file.\n")
87 |
88 | quick_ref_dict = {
89 |
90 | "hg38_gencode" :["hsa", "human", "Homo sapiens", "org.Hs.eg.db"],
91 | "mm10_gencode" :["mmu", "mouse", "Mus musculus", "org.Mm.eg.db"],
92 | "rnor6_ensembl" :["rno", "rat", "Ratus norvegicus", "org.Rn.eg.db"],
93 | "dm6_BDGP6.28.100" :["dme", "fly", "Drosophila melanogaster", "org.Dm.eg.db"],
94 | "c.elegans-WBcel235" :["cel", "celegans", "Caenorhabditis elegans", "org.Ce.eg.db"]
95 |
96 | }
97 |
98 | if quick_ref_id in quick_ref_dict:
99 |
100 | # quick_ref python dictionary for quick implementation:
101 |
102 | # For GSEA
103 | # kegg_org should be a three or four letter string corresponding to your reference species. List of KEGG species is found here: https://www.genome.jp/kegg/tables/br08606.html
104 | config['kegg_org'] = quick_ref_dict[quick_ref_id][0]
105 |
106 | # reactome_org can be "human", "mouse", "rat", "celegans", "yeast", "zebrafish", "fly"
107 | config['reactome_org'] = quick_ref_dict[quick_ref_id][1]
108 |
109 | # Full species name. Applicable input strings can be found by installing the msigdbr library in R and using msigdbr::msigdbr_species()
110 | config['msigdb_organism'] = quick_ref_dict[quick_ref_id][2]
111 |
112 | # The species database for translating gene names and analyses
113 | config['orgdb'] = quick_ref_dict[quick_ref_id][3]
114 |
115 |
116 | if (config['call_variants']):
117 | # read grouped contigs
118 | contigs_file = config["grouped_contigs"]
119 | contig_groups = pd.read_table(contigs_file)
120 | contig_groups['contigs'] = contig_groups['contigs'].replace('', np.nan) # unplaced_contigs can be empty for certain references.
121 | contig_groups.dropna(subset=['contigs'], inplace=True)
122 |
123 | # check chromosomes/contigs parsed correctly by comparing to fai.
124 | fai_file = config["ref"]["fai"]
125 | contigs_fai = sorted(pd.read_table(fai_file, names=['name','len','offset','linebases','linewidth'])['name'].values)
126 | contigs_parsed = [x.split(',') for x in contig_groups['contigs'].values]
127 | contigs_parsed_flat = sorted(list(itertools.chain.from_iterable(contigs_parsed)))
128 |
129 | assert contigs_fai == contigs_parsed_flat, "Chromosomes in grouped contigs file do not match fai."
130 |
131 | include: 'rules/variants.smk'
132 |
133 | rule all:
134 | input:
135 | "results/multiqc/multiqc_report.html",
136 | expand("results/SummarizedExperiment/{pref}.rds", pref=['SummarizedExperiment', 'sce']),
137 | expand("results/avg_bigwigs/{group}.unstr.bw", group=pd.unique(samples['group'])) if (config["run_vis_bigwig"]) else [],
138 | expand("results/deseq2/DESeq2_{comparison_name}.html", comparison_name=pd.unique(comparisons["comparison_name"])),
139 | expand("results/gsea/gsea_{comparison_name}.html", comparison_name=pd.unique(comparisons["comparison_name"])),
140 | "results/variant_calling/final/07a_variant_annot/all.merged.filt.PASS.snpeff.vcf.gz" if (config["call_variants"]) else [],
141 | "results/variant_calling/final/07b_snp_pca_and_dendro/snprelate.html" if (config["call_variants"]) else [],
142 | "results/make_final_report/BBC_RNAseq_Report",
143 | "results/iSEE/app.R",
144 | "results/iSEE/deployed" if (config["deploy_to_shinyio"]) else [],
145 |
146 | include:
147 | 'rules/RNAseq.smk'
148 | include:
149 | 'rules/qc.smk'
150 | include:
151 | 'rules/visualisation.smk'
152 | include:
153 | 'rules/make_Rprojects.smk'
154 | include:
155 | 'rules/deseq2.smk'
156 | include:
157 | 'rules/gsea.smk'
158 | include:
159 | 'rules/make_report.smk'
160 | include:
161 | 'rules/isee.smk'
162 |
--------------------------------------------------------------------------------
/workflow/rules/RNAseq.smk:
--------------------------------------------------------------------------------
1 | import gzip
2 |
3 | def get_orig_fastq(wildcards):
4 | if wildcards.read == "R1":
5 | fastq = units[(units["sample"] == wildcards.sample) & (units["group_index"] == wildcards.group_index)]["fq1"]
6 | elif wildcards.read == "R2":
7 | fastq = units[(units["sample"] == wildcards.sample) & (units["group_index"] == wildcards.group_index)]["fq2"]
8 | return 'raw_data/' + fastq
9 |
10 | rule rename_fastqs:
11 | """
12 | Rename fastqs by biologically meaningful name.
13 | """
14 | input:
15 | get_orig_fastq
16 | output:
17 | "results/rename_fastqs/{sample}_{group_index}_{read}.fastq.gz"
18 | benchmark:
19 | "benchmarks/rename_fastqs/{sample}_{group_index}_{read}.txt"
20 | params:
21 | threads: 1
22 | resources:
23 | mem_gb=4,
24 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
25 | envmodules:
26 | shell:
27 | """
28 | # If the fastqs are not compressed, gzipped them with new name.
29 | if ( (file -L "{input}" | grep -q 'gzip compressed') || (file -L "{input}" | grep -q 'Blocked GNU Zip Format') ) ; then
30 | ln -sr {input} {output}
31 | elif ( file -L "{input}" | grep -q 'ASCII text' ) ; then
32 | gzip -c {input} > {output}
33 | else
34 | echo "Unrecognized input file format."
35 | exit 1
36 | fi
37 | """
38 |
39 | def trim_galore_input(wildcards):
40 | if config["PE_or_SE"] == "SE":
41 | reads = "results/rename_fastqs/{sample}_{group_index}_R1.fastq.gz".format(**wildcards)
42 | return reads
43 | elif config["PE_or_SE"] == "PE":
44 | R1 = "results/rename_fastqs/{sample}_{group_index}_R1.fastq.gz".format(**wildcards)
45 | R2 = "results/rename_fastqs/{sample}_{group_index}_R2.fastq.gz".format(**wildcards)
46 | return [R1,R2]
47 |
48 | rule trim_galore_PE:
49 | input:
50 | trim_galore_input
51 | output:
52 | #temp("results/trimmed_data/{sample}_{group_index}_R1_val_1.fq.gz"),
53 | "results/trimmed_data/{sample}_{group_index}_R1_val_1.fq.gz",
54 | "results/trimmed_data/{sample}_{group_index}_R1_val_1_fastqc.html",
55 | "results/trimmed_data/{sample}_{group_index}_R1_val_1_fastqc.zip",
56 | "results/trimmed_data/{sample}_{group_index}_R1.fastq.gz_trimming_report.txt",
57 | #temp("results/trimmed_data/{sample}_{group_index}_R2_val_2.fq.gz"),
58 | "results/trimmed_data/{sample}_{group_index}_R2_val_2.fq.gz",
59 | "results/trimmed_data/{sample}_{group_index}_R2_val_2_fastqc.html",
60 | "results/trimmed_data/{sample}_{group_index}_R2_val_2_fastqc.zip",
61 | "results/trimmed_data/{sample}_{group_index}_R2.fastq.gz_trimming_report.txt"
62 | params:
63 | outdir="results/trimmed_data/"
64 | benchmark:
65 | "benchmarks/trim_galore/{sample}_{group_index}.txt"
66 | envmodules:
67 | config['modules']['trim_galore']
68 | threads: 4
69 | resources:
70 | nodes = 1,
71 | mem_gb = 32,
72 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
73 | shell:
74 | """
75 | trim_galore \
76 | --paired \
77 | {input} \
78 | --output_dir {params.outdir} \
79 | --cores {threads} \
80 | -q 20 \
81 | --fastqc
82 | """
83 |
84 | rule trim_galore_SE:
85 | input:
86 | trim_galore_input
87 | output:
88 | temp("results/trimmed_data/{sample}_{group_index}_R1_trimmed.fq.gz"),
89 | "results/trimmed_data/{sample}_{group_index}_R1_trimmed_fastqc.zip",
90 | "results/trimmed_data/{sample}_{group_index}_R1_trimmed_fastqc.html",
91 | "results/trimmed_data/{sample}_{group_index}_R1.fastq.gz_trimming_report.txt",
92 | params:
93 | outdir="results/trimmed_data/"
94 | benchmark:
95 | "benchmarks/trim_galore/{sample}_{group_index}.txt"
96 | envmodules:
97 | config['modules']['trim_galore']
98 | threads: 4
99 | resources:
100 | nodes = 1,
101 | mem_gb = 32,
102 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
103 | shell:
104 | """
105 | trim_galore \
106 | {input} \
107 | --output_dir {params.outdir} \
108 | --cores {threads} \
109 | -q 20 \
110 | --fastqc
111 | """
112 |
113 | def STAR_input(wildcards):
114 | group_indices = units[units['sample'] == wildcards.sample]['group_index']
115 | if config["PE_or_SE"] == "SE":
116 | fq1 = expand("results/trimmed_data/{sample}_{group_index}_R1_trimmed.fq.gz", sample=wildcards.sample, group_index=group_indices)
117 | fq2 = []
118 | elif config["PE_or_SE"] == "PE":
119 | fq1 = expand("results/trimmed_data/{sample}_{group_index}_R1_val_1.fq.gz", sample=wildcards.sample, group_index=group_indices)
120 | fq2 = expand("results/trimmed_data/{sample}_{group_index}_R2_val_2.fq.gz", sample=wildcards.sample, group_index=group_indices)
121 | return {'fq1_files': fq1, 'fq2_files': fq2}
122 |
123 | def get_RG(wildcards, input):
124 | fq1_files = input.fq1_files
125 |
126 | ## Use the user-specified read group info if available
127 | rg_lines = units[units['sample'] == wildcards.sample]['RG'].values
128 |
129 | if(pd.isnull(rg_lines).any() or any(ele == '' for ele in rg_lines)):
130 |
131 | rg_lines = []
132 |
133 | ## Extract the first line of each fq1 file
134 | first_lines = []
135 | for fq_file in fq1_files:
136 | with gzip.open(fq_file,'rt') as f:
137 | first_lines.append(f.readline().strip())
138 |
139 | ## Compile the read group line for each library
140 | for i in range(len(fq1_files)):
141 |
142 | # replace spaces with underscore, mainly to account for accession ID for GEO/SRA samples, then split by colon
143 | first_line_split = first_lines[i].replace(" ", "_").split(':')
144 |
145 |
146 | flowcell = first_line_split[2] if (len(first_line_split) >= 3) else 'ABC'
147 | lane = first_line_split[3] if (len(first_line_split) >= 4) else '0'
148 |
149 | # if library barcode is in the header, parse it. If not, just use the sample name.
150 | lib_barcode = first_line_split[9] if (len(first_line_split) >= 10) else wildcards.sample
151 |
152 | sample = wildcards.sample
153 |
154 | rgid = '.'.join([flowcell, lane, lib_barcode])
155 | rgpu = '.'.join([flowcell, lane, lib_barcode])
156 | rgsm = sample
157 |
158 | # Assumes one library per sample
159 | rg_line = 'ID:' + rgid + ' PU:' + rgpu + ' LB:' + rgsm + ' PL:ILLUMINA SM:' + rgsm
160 | rg_lines.append(rg_line)
161 |
162 | read_groups = ' , '.join(rg_lines)
163 |
164 | return read_groups
165 |
166 | rule STAR:
167 | input:
168 | unpack(STAR_input)
169 | output:
170 | # see STAR manual for additional output files
171 | unsorted_bam = temp("results/star/{sample}.Aligned.out.bam"),
172 | log_final = "results/star/{sample}.Log.final.out",
173 | log = "results/star/{sample}.Log.out",
174 | rpg = "results/star/{sample}.ReadsPerGene.out.tab",
175 | sj = "results/star/{sample}.SJ.out.tab",
176 | g_dir = directory("results/star/{sample}._STARgenome"),
177 | pass1_dir = directory("results/star/{sample}._STARpass1"),
178 | bam = "results/star/{sample}.sorted.bam",
179 | bai = "results/star/{sample}.sorted.bam.bai",
180 | params:
181 | # path to STAR reference genome index
182 | index = config["ref"]["index"],
183 | outprefix = "results/star/{sample}.",
184 | in_fastqs = lambda wildcards, input: ','.join(input.fq1_files) + ' ' + ','.join(input.fq2_files),
185 | read_groups = get_RG
186 | benchmark:
187 | "benchmarks/star/{sample}.txt"
188 | envmodules:
189 | config['modules']['star'],
190 | config['modules']['samtools']
191 | threads: 8
192 | resources:
193 | nodes = 1,
194 | mem_gb = 120,
195 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
196 | shell:
197 | """
198 | STAR \
199 | --runThreadN {threads} \
200 | --genomeDir {params.index} \
201 | --readFilesIn {params.in_fastqs} \
202 | --outSAMattrRGline {params.read_groups} \
203 | --twopassMode Basic \
204 | --readFilesCommand zcat \
205 | --outSAMtype BAM Unsorted \
206 | --outFileNamePrefix {params.outprefix} \
207 | --quantMode GeneCounts \
208 | --outStd Log
209 |
210 | samtools sort -@ {threads} -o {output.bam} {output.unsorted_bam}
211 | samtools index {output.bam}
212 | """
213 |
214 | rule salmon:
215 | input:
216 | unpack(STAR_input),
217 | index=config["ref"]["salmon_index"]
218 | output:
219 | expand("results/salmon/{{sample}}/{file}", file=["libParams/flenDist.txt","aux_info/meta_info.json","quant.sf","lib_format_counts.json","cmd_info.json","logs/salmon_quant.log"])
220 | params:
221 | outdir=directory("results/salmon/{sample}"),
222 | reads=lambda wildcards, input: "-1 {fq1} -2 {fq2}".format(fq1=input.fq1_files, fq2=input.fq2_files) if config["PE_or_SE"] == "PE" else "-r {fq1}".format(fq1=input.fq1_files)
223 | benchmark:
224 | "benchmarks/salmon/{sample}.txt"
225 | envmodules:
226 | config['modules']['salmon']
227 | threads: 8
228 | resources:
229 | nodes = 1,
230 | mem_gb = 120,
231 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
232 | shell:
233 | """
234 | salmon quant \
235 | -p {threads} \
236 | -l A \
237 | -i {input.index} \
238 | {params.reads} \
239 | --validateMappings \
240 | -o {params.outdir}
241 | """
242 |
243 | rule SummarizedExperiment:
244 | input:
245 | star = expand("results/star/{samples.sample}.ReadsPerGene.out.tab", samples=samples.itertuples()),
246 | salmon = expand("results/salmon/{samples.sample}/{file}", samples=samples.itertuples(), file=['lib_format_counts.json', 'quant.sf']),
247 | renv_lock = ancient("results/{Rproj}/renv.lock".format(Rproj=config['Rproj_dirname']))
248 | output:
249 | se="results/SummarizedExperiment/SummarizedExperiment.rds",
250 | sce="results/SummarizedExperiment/sce.rds",
251 | sizeFactors="results/SummarizedExperiment/DESeq2_sizeFactors_reciprocal.tsv",
252 | txi="results/SummarizedExperiment/txi.rds",
253 | strandedness="results/SummarizedExperiment/inferred_strandedness.txt"
254 | benchmark:
255 | "benchmarks/SummarizedExperiment/SummarizedExperiment.txt"
256 | params:
257 | gtf=config['ref']['annotation'],
258 | orgdb=config['orgdb'],
259 | renv_rproj_dir = lambda wildcards, input: os.path.dirname(input.renv_lock)
260 | threads: 1
261 | envmodules:
262 | config['modules']['R']
263 | resources:
264 | mem_gb=64,
265 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
266 | shell:
267 | """
268 | Rscript --vanilla workflow/scripts/make_sce.R {params.gtf} {params.orgdb} {params.renv_rproj_dir} {output.se} {output.sce} {output.sizeFactors} {output.txi} {output.strandedness}
269 | """
270 |
--------------------------------------------------------------------------------
/workflow/rules/deseq2.smk:
--------------------------------------------------------------------------------
1 | rule deseq2:
2 | input:
3 | se="results/SummarizedExperiment/SummarizedExperiment.rds",
4 | renv_lock = ancient("results/{Rproj}/renv.lock".format(Rproj=config['Rproj_dirname']))
5 | output:
6 | rmd="results/deseq2/DESeq2_{comparison}.Rmd",
7 | html="results/deseq2/DESeq2_{comparison}.html",
8 | de_res="results/deseq2/deseq2_out_files/{comparison}/de_res.tsv",
9 | de_res_rds="results/deseq2/deseq2_out_files/{comparison}/de_res.rds",
10 | counts="results/deseq2/deseq2_out_files/{comparison}/counts.tsv",
11 | vst="results/deseq2/deseq2_out_files/{comparison}/vst.tsv",
12 | vsd_rds="results/deseq2/deseq2_out_files/{comparison}/vsd.rds",
13 | fig_dir=directory("results/deseq2/deseq2_out_files/{comparison}/individual_figures"),
14 | benchmark:
15 | "benchmarks/deseq2/{comparison}.txt"
16 | params:
17 | deseq_template = "resources/deseq_template.Rmd",
18 | fdr_cutoff = config['fdr_cutoff'],
19 | comparison = lambda wildcards: wildcards.comparison,
20 | group_test = lambda wildcards: comparisons.loc[comparisons['comparison_name'] == wildcards.comparison, 'group_test'].values[0],
21 | group_reference = lambda wildcards: comparisons.loc[comparisons['comparison_name'] == wildcards.comparison, 'group_reference'].values[0],
22 | genes_of_interest = config['genes_of_interest'],
23 | renv_rproj_dir = lambda wildcards, input: os.path.dirname(input.renv_lock)
24 | envmodules:
25 | config['modules']['R'],
26 | config['modules']['pandoc']
27 | threads: 8
28 | resources:
29 | nodes = 1,
30 | mem_gb = 16,
31 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
32 | shell:
33 | """
34 | cp {params.deseq_template} {output.rmd}
35 |
36 | Rscript --vanilla -e "renv::load('{params.renv_rproj_dir}'); rmarkdown::render('{output.rmd}',
37 | params = list(se_obj = '{input.se}',
38 | comparison_name = '{params.comparison}',
39 | group_test = '{params.group_test}',
40 | group_reference = '{params.group_reference}',
41 | fdr_cutoff = {params.fdr_cutoff},
42 | genes_of_interest = '{params.genes_of_interest}'))"
43 | """
44 |
45 | rule add_DE_to_SE:
46 | input:
47 | sce="results/SummarizedExperiment/sce.rds",
48 | res_rds=expand("results/deseq2/deseq2_out_files/{comparison}/de_res.rds", comparison = pd.unique(comparisons["comparison_name"])),
49 | renv_lock = ancient("results/{Rproj}/renv.lock".format(Rproj=config['Rproj_dirname'])),
50 | output:
51 | sce="results/add_DE_to_SE/sce.rds"
52 | benchmark:
53 | "benchmarks/add_DE_to_SE/bench.txt"
54 | params:
55 | renv_rproj_dir = lambda wildcards, input: os.path.dirname(input.renv_lock),
56 | de_res_outfiles_dir = lambda wildcards, input: os.path.dirname(os.path.dirname(input.res_rds[0])),
57 | comparisons = pd.unique(comparisons["comparison_name"]),
58 | envmodules:
59 | config['modules']['R'],
60 | threads: 8
61 | resources:
62 | nodes = 1,
63 | mem_gb = 96,
64 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
65 | script:
66 | "../scripts/add_DE_to_SCE.R"
67 |
--------------------------------------------------------------------------------
/workflow/rules/gsea.smk:
--------------------------------------------------------------------------------
1 | rule gsea:
2 | input:
3 | res_rds="results/deseq2/deseq2_out_files/{comparison}/de_res.rds",
4 | vsd_rds="results/deseq2/deseq2_out_files/{comparison}/vsd.rds",
5 | renv_lock = ancient("results/{Rproj}/renv.lock".format(Rproj=config['Rproj_dirname']))
6 | output:
7 | rmd="results/gsea/gsea_{comparison}.Rmd",
8 | html="results/gsea/gsea_{comparison}.html",
9 | figs=directory("results/gsea/{comparison}_out_files/individual_figures"),
10 | outfiles=expand("results/gsea/{{comparison}}_out_files/{collection}_gsea.xlsx", collection = config['pathway_str'].split(','))
11 | benchmark:
12 | "benchmarks/gsea/{comparison}.txt"
13 | params:
14 | orgdb = config['orgdb'],
15 | kegg_org = config['kegg_org'],
16 | reactome_org = config['reactome_org'],
17 | msigdb_organism = config['msigdb_organism'],
18 | pathway_str = config['pathway_str'],
19 | gsea_template = "resources/gsea_template.Rmd",
20 | fdr_cutoff = config['fdr_cutoff'],
21 | comparison = lambda wildcards: wildcards.comparison,
22 | renv_rproj_dir = lambda wildcards, input: os.path.dirname(input.renv_lock)
23 | envmodules:
24 | config['modules']['R'],
25 | config['modules']['pandoc']
26 | threads: 8
27 | resources:
28 | nodes = 1,
29 | mem_gb = 16,
30 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
31 | shell:
32 | """
33 | cp {params.gsea_template} {output.rmd}
34 |
35 | Rscript --vanilla -e "renv::load('{params.renv_rproj_dir}'); rmarkdown::render('{output.rmd}', params = list(orgdb = '{params.orgdb}', kegg_org = '{params.kegg_org}', comparison_name = '{params.comparison}', reactome_org = '{params.reactome_org}', msigdb_organism = '{params.msigdb_organism}', fdr_cutoff = '{params.fdr_cutoff}', de_res = '{input.res_rds}', vsd_rds = '{input.vsd_rds}', pathway_str = '{params.pathway_str}'))"
36 | """
37 |
--------------------------------------------------------------------------------
/workflow/rules/isee.smk:
--------------------------------------------------------------------------------
1 | rule isee:
2 | input:
3 | sce="results/add_DE_to_SE/sce.rds",
4 | app="resources/iSEE_app.R",
5 | renv_lock = ancient("results/{Rproj}/renv.lock".format(Rproj=config['Rproj_dirname']))
6 | output:
7 | sce="results/iSEE/sce.rds",
8 | app="results/iSEE/app.R",
9 | benchmark:
10 | "benchmarks/isee/isee.txt"
11 | params:
12 | envmodules:
13 | threads: 1
14 | resources:
15 | nodes = 1,
16 | mem_gb = 16,
17 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
18 | shell:
19 | """
20 | cp {input.sce} {output.sce}
21 | cp {input.app} {output.app}
22 |
23 | """
24 |
25 | rule deploy_isee_to_shinyappio:
26 | """
27 | Deploy iSEE to shinyapp.io and try to increase memory (may fail if account tier is too low).
28 | """
29 | input:
30 | sce="results/iSEE/sce.rds",
31 | app="results/iSEE/app.R",
32 | renv_lock = ancient("results/{Rproj}/renv.lock".format(Rproj=config['Rproj_dirname']))
33 | output:
34 | rsconnect=directory("results/iSEE/rsconnect/"), # meta data for this app for shinyapps.io
35 | deployed=touch("results/iSEE/deployed"),
36 | rscignore="results/iSEE/.rscignore"
37 | benchmark:
38 | "benchmarks/deploy_isee_to_shinyappio/bench.txt"
39 | params:
40 | deployed_file=lambda wildcards, output: os.path.basename(output.deployed),
41 | app_dir=lambda wildcards, input: f"appDir='{os.path.dirname(input.app)}'",
42 | app_info=f"appName = '{config['iSEE_app_name']}', account = '{config['shinyio_account_name']}'",
43 | renv_rproj_dir = lambda wildcards, input: os.path.dirname(input.renv_lock),
44 | envmodules:
45 | config['modules']['R'],
46 | threads: 1
47 | resources:
48 | nodes = 1,
49 | mem_gb = 16,
50 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
51 | shell:
52 | """
53 | echo '{params.deployed_file}' > {output.rscignore}
54 |
55 | Rscript --vanilla -e "renv::load('{params.renv_rproj_dir}'); options(repos = BiocManager::repositories()); rsconnect::deployApp({params.app_dir}, {params.app_info}); try(rsconnect::configureApp({params.app_dir}, {params.app_info}, size='xxxlarge'))"
56 |
57 | """
58 |
--------------------------------------------------------------------------------
/workflow/rules/make_Rprojects.smk:
--------------------------------------------------------------------------------
1 | rule make_Rproject:
2 | input:
3 | R_pkges="config/R_proj_packages.txt",
4 | output:
5 | rproj = "results/{Rproj}/{Rproj}.Rproj",
6 | gitignore = "results/{Rproj}/.gitignore",
7 | R_dir = directory("results/{Rproj}/R"),
8 | renv_lock = "results/{Rproj}/renv.lock",
9 | renv_dependencies = "results/{Rproj}/_dependencies.R",
10 | renviron = "results/{Rproj}/.Renviron",
11 | rprofile = "results/{Rproj}/.Rprofile",
12 | renv_dir = directory("results/{Rproj}/renv"),
13 | benchmark:
14 | "benchmarks/make_Rproject/{Rproj}.txt"
15 | params:
16 | Rproj_dir = lambda wildcards,output: os.path.dirname(output.rproj),
17 | Renv_root = config['renv_root_path'],
18 | # tell renv not to use cache (actually install packages in project instead of symlinking) if requested in config file.
19 | set_use_renv_cache = lambda wildcards, output: "RENV_CONFIG_CACHE_ENABLED={choice}".format(choice="TRUE" if config['renv_use_cache'] else "FALSE"),
20 | # tell renv not to copy from user library if requested in config file.
21 | set_use_user_lib = lambda wildcards, output: "RENV_CONFIG_INSTALL_SHORTCUTS={choice}".format(choice="TRUE" if config['renv_use_user_lib'] else "FALSE"),
22 | set_symlink_from_cache = lambda wildcards, output: "RENV_CONFIG_CACHE_SYMLINKS={choice}".format(choice="TRUE" if config['renv_symlink_from_cache'] else "FALSE"),
23 | set_use_pak = lambda wildcards, output: "RENV_CONFIG_PAK_ENABLED={choice}".format(choice="TRUE" if config['renv_use_pak'] else "FALSE"),
24 | install_pak = lambda wildcards, output: "library(pak)" if config['renv_use_pak'] else "",
25 | snakemake_dir=snakemake_dir,
26 | orgdb = config['orgdb'],
27 | threads: 1
28 | envmodules:
29 | config['modules']['R']
30 | resources:
31 | mem_gb=64,
32 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log",
33 | shell:
34 | """
35 | Rscript --vanilla workflow/scripts/make_Rproject.R {params.Rproj_dir}
36 |
37 | # Make R script with package dependencies
38 | echo '{params.install_pak}' > {output.renv_dependencies}
39 | (cat {input.R_pkges} && echo {params.orgdb}) | perl -lne 's:.*/::; s:@.*$::; print qq:library($_):' >> {output.renv_dependencies}
40 |
41 | # set RENV_PATHS_CACHE in .Renviron
42 | echo "RENV_PATHS_ROOT='{params.Renv_root}'" > {output.renviron}
43 |
44 | echo '{params.set_use_renv_cache}' >> {output.renviron}
45 | echo '{params.set_use_user_lib}' >> {output.renviron}
46 | echo '{params.set_symlink_from_cache}' >> {output.renviron}
47 | echo '{params.set_use_pak}' >> {output.renviron}
48 |
49 |
50 | cd {params.Rproj_dir}
51 |
52 | echo "Running script to set up renv library..."
53 | # Don't use --vanilla because we need to get the RENV_PATHS_ROOT from the .renviron file.
54 | Rscript {params.snakemake_dir}/workflow/scripts/install_renv_pkges.R {params.snakemake_dir}/{input.R_pkges}
55 |
56 | # Set up git
57 | echo "Setting up git now..."
58 | git init
59 | git add -A
60 | git commit -m "initial commit"
61 |
62 | """
63 |
64 |
--------------------------------------------------------------------------------
/workflow/rules/make_report.smk:
--------------------------------------------------------------------------------
1 | rule make_final_report:
2 | input:
3 | website_template = expand("resources/report_template/{fname}", fname=["_site.yml", "footer.html", "index.Rmd", "multiqc.Rmd", "references.bib", "styles.css", "images/VAI_2_Line_White.png"]),
4 | de_res = expand("results/deseq2/DESeq2_{comp}.html", comp=pd.unique(comparisons["comparison_name"])),
5 | de_res_figs = expand("results/deseq2/deseq2_out_files/{comp}/individual_figures", comp=pd.unique(comparisons["comparison_name"])),
6 | de_res_tables = expand("results/deseq2/deseq2_out_files/{comp}/de_res.tsv", comp=pd.unique(comparisons["comparison_name"])),
7 | gsea = expand("results/gsea/gsea_{comp}.html", comp=pd.unique(comparisons["comparison_name"])),
8 | gsea_figs = expand("results/gsea/{comp}_out_files/individual_figures", comp=pd.unique(comparisons["comparison_name"])),
9 | gsea_tables = expand("results/gsea/{comp}_out_files/{collection}_gsea.xlsx", comp=pd.unique(comparisons["comparison_name"]), collection = config['pathway_str'].split(',')),
10 | renv_lock = ancient("results/{Rproj}/renv.lock".format(Rproj=config['Rproj_dirname'])),
11 | multiqc = "results/multiqc/multiqc_report.html"
12 | output:
13 | site_files = expand("results/make_final_report/{fname}", fname=["_site.yml", "footer.html", "index.Rmd","references.bib", "styles.css", "images/VAI_2_Line_White.png"]),
14 | multiqc_rmd = "results/make_final_report/multiqc.Rmd",
15 | de_res = expand("results/make_final_report/external_reports/DESeq2_{comp}.html", comp=pd.unique(comparisons["comparison_name"])),
16 | de_res_rmd = expand("results/make_final_report/DESeq2_{comp}.Rmd", comp=pd.unique(comparisons["comparison_name"])),
17 | de_res_figs = directory(expand("results/make_final_report/extras/deseq2_figures/{comp}", comp=pd.unique(comparisons["comparison_name"]))),
18 | de_res_tables = expand("results/make_final_report/extras/deseq2_tables/{comp}_de_res.tsv", comp=pd.unique(comparisons["comparison_name"])),
19 | gsea = expand("results/make_final_report/external_reports/gsea_{comp}.html", comp=pd.unique(comparisons["comparison_name"])),
20 | gsea_rmd = expand("results/make_final_report/gsea_{comp}.Rmd", comp=pd.unique(comparisons["comparison_name"])),
21 | gsea_figs = directory(expand("results/make_final_report/extras/gsea_figures/{comp}", comp=pd.unique(comparisons["comparison_name"]))),
22 | gsea_tables = expand("results/make_final_report/extras/gsea_tables/{comp}/{collection}_gsea.xlsx", comp=pd.unique(comparisons["comparison_name"]), collection = config['pathway_str'].split(',')),
23 | multiqc = "results/make_final_report/external_reports/multiqc_report.html",
24 | website = directory("results/make_final_report/BBC_RNAseq_Report"),
25 | isee_rmd = "results/make_final_report/iSEE.Rmd",
26 | benchmark:
27 | "benchmarks/make_final_report/bench.txt"
28 | params:
29 | template_dir = lambda wildcards, input: os.path.commonprefix(input.website_template),
30 | template_files = lambda wildcards, input: [ fname.replace("resources/report_template/", "") for fname in input.website_template],
31 | de_res_comps = " ".join(["'" + comp + "'" for comp in pd.unique(comparisons["comparison_name"])]),
32 | de_res_yml = "\\n".join([f" - text: {comp}\\n href: DESeq2_{comp}.html" for comp in pd.unique(comparisons["comparison_name"])]),
33 | gsea_yml = "\\n".join([f" - text: {comp}\\n href: gsea_{comp}.html" for comp in pd.unique(comparisons["comparison_name"])]),
34 | ext_reports_dir = lambda wildcards, output: os.path.dirname(output.multiqc),
35 | renv_rproj_dir = lambda wildcards, input: os.path.dirname(input.renv_lock),
36 | root_dir = lambda wildcards, output: os.path.join(os.getcwd(), os.path.dirname(output.website)),
37 | de_res_outdir = lambda wildcards, input: os.path.dirname(os.path.dirname(input.de_res_figs[0])),
38 | gsea_dir = lambda wildcards, input: os.path.dirname(input.gsea[0]),
39 | isee_site_yml = " - text: iSEE\\n icon: fa-solid fa-gem\\n href: isee.html" if config['deploy_to_shinyio'] else "",
40 | isee_app_name = config['iSEE_app_name'],
41 | shinyio_account = config['shinyio_account_name']
42 | envmodules:
43 | config['modules']['R'],
44 | config['modules']['pandoc']
45 | threads: 8
46 | resources:
47 | nodes = 1,
48 | mem_gb = 16,
49 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
50 | shell:
51 | """
52 | cd {params.template_dir}
53 | cp --parents -r {params.template_files} {params.root_dir}/
54 | cd -
55 |
56 | perl -i -lnpe 's/<<>>/{params.de_res_yml}/' {params.root_dir}/_site.yml
57 | perl -i -lnpe 's/<<>>/{params.gsea_yml}/' {params.root_dir}/_site.yml
58 | perl -i -lnpe 's/<<>>/{params.isee_site_yml}/' {params.root_dir}/_site.yml
59 |
60 | ln -sr {input.multiqc} {output.multiqc}
61 | ln -sr {input.de_res} {params.ext_reports_dir}
62 | ln -sr {input.gsea} {params.ext_reports_dir}
63 |
64 | cat {output.multiqc_rmd} | perl -lnpe "s:MultiQC:iSEE:; s|./external_reports/multiqc_report.html|https://{params.shinyio_account}.shinyapps.io/{params.isee_app_name}|" > {output.isee_rmd}
65 |
66 | for comp in {params.de_res_comps}
67 | do
68 | mkdir -p {params.root_dir}/extras/deseq2_figures/${{comp}}/
69 | ln -sr {params.de_res_outdir}/${{comp}}/individual_figures/* {params.root_dir}/extras/deseq2_figures/${{comp}}/
70 |
71 | mkdir -p {params.root_dir}/extras/deseq2_tables/
72 | ln -sr {params.de_res_outdir}/${{comp}}/de_res.tsv {params.root_dir}/extras/deseq2_tables/${{comp}}_de_res.tsv
73 |
74 | cat {output.multiqc_rmd} | perl -lnpe "s:MultiQC:${{comp}}:; s:multiqc_report:DESeq2_${{comp}}:" > "{params.root_dir}/DESeq2_${{comp}}.Rmd"
75 |
76 | mkdir -p {params.root_dir}/extras/gsea_figures/${{comp}}/
77 | ln -sr {params.gsea_dir}/${{comp}}_out_files/individual_figures/* {params.root_dir}/extras/gsea_figures/${{comp}}/
78 |
79 | mkdir -p {params.root_dir}/extras/gsea_tables/
80 | ln -sr {params.gsea_dir}/${{comp}}_out_files/*_gsea.xlsx {params.root_dir}/extras/gsea_tables/${{comp}}/
81 |
82 | cat {output.multiqc_rmd} | perl -lnpe "s:MultiQC:${{comp}}:; s:multiqc_report:gsea_${{comp}}:" > "{params.root_dir}/gsea_${{comp}}.Rmd"
83 | done
84 |
85 |
86 | Rscript -e "renv::load('{params.renv_rproj_dir}'); rmarkdown::render_site('{params.root_dir}')"
87 | """
88 |
--------------------------------------------------------------------------------
/workflow/rules/qc.smk:
--------------------------------------------------------------------------------
1 | def concat_fqs_input(wildcards):
2 | if config["PE_or_SE"] == "SE":
3 | fqs = expand("results/trimmed_data/{sample}_{group_index}_R{read}_trimmed.fq.gz", group_index=units[units['sample'] == wildcards.sample]['group_index'], sample=wildcards.sample, read=wildcards.read)
4 | elif config["PE_or_SE"] == "PE":
5 | fqs = expand("results/trimmed_data/{sample}_{group_index}_R{read}_val_{read}.fq.gz", group_index=units[units['sample'] == wildcards.sample]['group_index'], sample=wildcards.sample, read=wildcards.read)
6 | return fqs
7 |
8 | rule concat_fastqs:
9 | """
10 | Concatenate fastqs.
11 | """
12 | input:
13 | concat_fqs_input
14 | output:
15 | "results/concat_fastqs/{sample}_R{read,[12]}.fastq.gz"
16 | benchmark:
17 | "benchmarks/concat_fastqs/{sample}_R{read}.txt"
18 | params:
19 | cat_or_symlink=lambda wildcards, input: "cat " + " ".join(input) + " > " if len(input) > 1 else "ln -sr " + input[0]
20 | threads: 1
21 | resources:
22 | mem_gb=4,
23 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
24 | envmodules:
25 | shell:
26 | """
27 | {params.cat_or_symlink} {output}
28 | """
29 |
30 | rule fastq_screen:
31 | input:
32 | "results/concat_fastqs/{fq_pref}.fastq.gz",
33 | output:
34 | html = "results/fastq_screen/{fq_pref}_screen.html",
35 | txt = "results/fastq_screen/{fq_pref}_screen.txt",
36 | benchmark:
37 | "benchmarks/fastq_screen/{fq_pref}.bmk"
38 | threads: 8
39 | resources:
40 | nodes = 1,
41 | mem_gb = 32,
42 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
43 | envmodules: config['modules']['fastq_screen']
44 | shell:
45 | """
46 | fastq_screen --threads {threads} --outdir results/fastq_screen/ {input}
47 | """
48 |
49 | rule fastqc:
50 | """
51 | Run fastqc on fastq files.
52 | """
53 | input:
54 | "results/concat_fastqs/{fq_pref}.fastq.gz"
55 | output:
56 | html="results/fastqc/{fq_pref}_fastqc.html",
57 | zip="results/fastqc/{fq_pref}_fastqc.zip"
58 | params:
59 | outdir="results/fastqc/"
60 | benchmark:
61 | "benchmarks/fastqc/{fq_pref}.txt"
62 | envmodules:
63 | config['modules']['fastqc']
64 | threads: 1
65 | resources:
66 | mem_gb = 32,
67 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
68 | shell:
69 | """
70 | fastqc --outdir {params.outdir} {input}
71 | """
72 |
73 | rule seqtk:
74 | input:
75 | "results/concat_fastqs/{fq_pref}.fastq.gz"
76 | output:
77 | temp("results/subsample/{fq_pref}.fastq.gz"),
78 | envmodules:
79 | config['modules']['seqtk']
80 | params:
81 | num_subsamp = 50000,
82 | threads: 1
83 | resources:
84 | nodes = 1,
85 | mem_gb = 16,
86 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
87 | shell:
88 | """
89 | seqtk sample -s 100 {input} {params.num_subsamp} | gzip -c > {output}
90 | """
91 |
92 | def sortmerna_input(wildcards):
93 | if config["PE_or_SE"] == "SE":
94 | fq1="results/subsample/{sample}_R1.fastq.gz".format(**wildcards)
95 | return fq1
96 | if config["PE_or_SE"] == "PE":
97 | fq1 = "results/subsample/{sample}_R1.fastq.gz".format(**wildcards)
98 | fq2 = "results/subsample/{sample}_R2.fastq.gz".format(**wildcards)
99 | return [fq1,fq2]
100 |
101 | rule sortmerna:
102 | input:
103 | sortmerna_input,
104 | output:
105 | directory("results/sortmerna/{sample}")
106 | envmodules:
107 | config['modules']['sortmerna']
108 | params:
109 | rfam5_8s = config["sortmerna"]["rfam5_8s"],
110 | rfam5s = config['sortmerna']['rfam5s'],
111 | silva_arc_16s = config['sortmerna']['silva_arc_16s'],
112 | silva_arc_23s = config['sortmerna']['silva_arc_23s'],
113 | silva_bac_16s = config['sortmerna']['silva_bac_16s'],
114 | silva_bac_23s = config['sortmerna']['silva_bac_23s'],
115 | silva_euk_18s = config['sortmerna']['silva_euk_18s'],
116 | silva_euk_28s = config['sortmerna']['silva_euk_28s'],
117 | idx_dir = config['sortmerna']['idx_dir'],
118 | fastqs = lambda wildcards, input: ' '.join(["-reads " + x for x in input])
119 | threads: 8
120 | resources:
121 | nodes = 1,
122 | mem_gb = 16,
123 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
124 | shell:
125 | """
126 | sortmerna --threads {threads} {params.fastqs} --workdir {output} \
127 | --idx-dir {params.idx_dir} \
128 | --ref {params.rfam5s} \
129 | --ref {params.rfam5_8s} \
130 | --ref {params.silva_arc_16s} \
131 | --ref {params.silva_arc_23s} \
132 | --ref {params.silva_bac_16s} \
133 | --ref {params.silva_bac_23s} \
134 | --ref {params.silva_euk_18s} \
135 | --ref {params.silva_euk_28s}
136 | """
137 |
138 | rule make_genes_ref_flat:
139 | """
140 | Make REF FLAT file from GTF.
141 | """
142 | input:
143 | gtf=config['ref']['annotation']
144 | output:
145 | ref_flat="results/misc/gene_annot.ref_flat.txt"
146 | benchmark:
147 | "benchmarks/make_genes_ref_flat/bench.txt"
148 | params:
149 | envmodules:
150 | config["modules"]["ucsctools"]
151 | threads: 4
152 | resources:
153 | mem_gb = 80,
154 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
155 | shell:
156 | """
157 | gtfToGenePred -genePredExt -geneNameAsName2 -ignoreGroupsWithoutExons {input.gtf} /dev/stdout | \
158 | perl -F"\\t" -lane 'print join("\\t", @F[11,0..9])' > {output.ref_flat}
159 | """
160 |
161 | rule make_genes_bed:
162 | """
163 | Make BED file from GTF.
164 | """
165 | input:
166 | gtf=config['ref']['annotation']
167 | output:
168 | bed="results/misc/gene_annot.bed"
169 | benchmark:
170 | "benchmarks/make_genes_bed/bench.txt"
171 | params:
172 | envmodules:
173 | config["modules"]["ucsctools"]
174 | threads: 4
175 | resources:
176 | mem_gb = 80,
177 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
178 | shell:
179 | """
180 | gtfToGenePred {input.gtf} /dev/stdout | genePredToBed /dev/stdin {output.bed}
181 | """
182 |
183 |
184 | rule get_rRNA_intervals_from_gtf:
185 | """
186 | Get rRNA intervals from GTF in BED format.
187 | """
188 | input:
189 | gtf=config['ref']['annotation'],
190 | ref_dict=config['ref']['dict'],
191 | renv_lock = ancient("results/{Rproj}/renv.lock".format(Rproj=config['Rproj_dirname'])),
192 | output:
193 | bed="results/misc/rrna.bed",
194 | interval_list="results/misc/rrna.interval_list"
195 | benchmark:
196 | "benchmarks/get_rRNA_intervals_from_gtf/bench.txt"
197 | params:
198 | renv_rproj_dir = lambda wildcards, input: os.path.dirname(input.renv_lock),
199 | envmodules:
200 | config["modules"]["picard"],
201 | config["modules"]["R"],
202 | threads: 4
203 | resources:
204 | mem_gb = 80,
205 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
206 | shell:
207 | """
208 | Rscript --vanilla -e 'renv::load("{params.renv_rproj_dir}"); library(rtracklayer); gtf <- import("{input.gtf}"); biotype_col <- na.omit(match(c("gene_biotype","gene_type"), colnames(mcols(gtf)))); stopifnot(length(biotype_col) > 0); rrna <- gtf[mcols(gtf)[[biotype_col[1]]]=="rRNA" & mcols(gtf)$type=="gene"]; score(rrna) <- 1; export(rrna, "{output.bed}")'
209 |
210 | java -Xms8g -Xmx{resources.mem_gb}g -Djava.io.tmpdir=./tmp -jar $PICARD BedToIntervalList \
211 | I={output.bed} \
212 | O={output.interval_list} \
213 | SD={input.ref_dict}
214 | """
215 |
216 | def get_library_strandedness(wildcards, input):
217 | with open(input.strandedness) as f:
218 | first_line = f.readline().strip('\n')
219 | if first_line in ("ISR","SR"):
220 | strandedness = "SECOND_READ_TRANSCRIPTION_STRAND"
221 | elif first_line in ("ISF","SF"):
222 | strandedness = "FIRST_READ_TRANSCRIPTION_STRAND"
223 | elif first_line in ("IU","U"):
224 | strandedness = "NONE"
225 | else:
226 | raise Exception("Unrecognized strand type")
227 | return strandedness
228 |
229 | rule CollectRnaSeqMetrics:
230 | """
231 | Run Picard CollectRnaSeqMetrics.
232 | """
233 | input:
234 | bam="results/star/{sample}.sorted.bam",
235 | ref_flat="results/misc/gene_annot.ref_flat.txt",
236 | strandedness="results/SummarizedExperiment/inferred_strandedness.txt",
237 | rrna="results/misc/rrna.interval_list"
238 | output:
239 | metrics="results/CollectRnaSeqMetrics/{sample}.txt"
240 | benchmark:
241 | "benchmarks/CollectRnaSeqMetrics/{sample}.txt"
242 | params:
243 | strand=get_library_strandedness,
244 | envmodules:
245 | config["modules"]["picard"]
246 | threads: 4
247 | resources:
248 | mem_gb = 80,
249 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
250 | shell:
251 | """
252 | java -Xms8g -Xmx{resources.mem_gb}g -Djava.io.tmpdir=./tmp -jar $PICARD CollectRnaSeqMetrics \
253 | -I {input.bam} \
254 | -O {output.metrics} \
255 | --REF_FLAT {input.ref_flat} \
256 | --STRAND_SPECIFICITY {params.strand} \
257 | --RIBOSOMAL_INTERVALS {input.rrna}
258 | """
259 |
260 | rule rseqc_genebody_cov:
261 | """
262 | Run RSeQC.
263 | """
264 | input:
265 | bam="results/star/{sample}.sorted.bam",
266 | genes="results/misc/gene_annot.bed"
267 | output:
268 | metrics="results/rseqc_genebody_cov/{sample}/{sample}.geneBodyCoverage.txt",
269 | r="results/rseqc_genebody_cov/{sample}/{sample}.geneBodyCoverage.r",
270 | log="results/rseqc_genebody_cov/{sample}/log.txt",
271 | benchmark:
272 | "benchmarks/rseqc_genebody_cov/{sample}.txt"
273 | params:
274 | prefix="{sample}",
275 | samp_dir=lambda wildcards, output: os.path.dirname(output.metrics)
276 | envmodules:
277 | config["modules"]["rseqc"]
278 | threads: 4
279 | resources:
280 | mem_gb = 80,
281 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
282 | shell:
283 | """
284 | cd {params.samp_dir}
285 |
286 | geneBody_coverage.py -r ../../../{input.genes} -i ../../../{input.bam} -o {params.prefix}
287 | """
288 |
289 | multiqc_input = []
290 | if config["PE_or_SE"] =="SE":
291 | multiqc_input.append(expand("results/fastq_screen/{samples.sample}_R1_trimmed_screen.txt", samples=samples.itertuples()))
292 | multiqc_input.append(expand("results/fastqc/{samples.sample}_R1_trimmed_fastqc.zip", samples=samples.itertuples()))
293 | multiqc_input.append(expand("results/fastqc/{samples.sample}_R1_trimmed_fastqc.html", samples=samples.itertuples()))
294 | multiqc_input.append(expand("results/salmon/{samples.sample}/{file}", samples=samples.itertuples(), file=["aux_info/meta_info.json"]))
295 | elif config["PE_or_SE"] =="PE":
296 | multiqc_input.append(expand("results/fastq_screen/{samples.sample}_R{read}_screen.txt", samples=samples.itertuples(), read=["1","2"]))
297 | multiqc_input.append(expand("results/fastqc/{samples.sample}_R{read}_fastqc.html", samples=samples.itertuples(), read=["1","2"]))
298 | multiqc_input.append(expand("results/fastqc/{samples.sample}_R{read}_fastqc.zip", samples=samples.itertuples(), read=["1","2"]))
299 | multiqc_input.append(expand("results/salmon/{samples.sample}/{file}", samples=samples.itertuples(), file=["libParams/flenDist.txt","aux_info/meta_info.json"]))
300 |
301 | multiqc_input.append(expand("results/star/{samples.sample}.Log.final.out", samples=samples.itertuples()))
302 | multiqc_input.append(expand("results/sortmerna/{samples.sample}",samples=samples.itertuples()))
303 | multiqc_input.append(expand("results/CollectRnaSeqMetrics/{samples.sample}.txt",samples=samples.itertuples()))
304 | if config['run_rseqc']:
305 | multiqc_input.append(expand("results/rseqc_genebody_cov/{samples.sample}/{samples.sample}.geneBodyCoverage.txt",samples=samples.itertuples()))
306 |
307 |
308 | rule multiqc:
309 | input:
310 | multiqc_input
311 | params:
312 | lambda wildcards, input: " ".join(pd.unique([os.path.dirname(x) for x in input]))
313 | output:
314 | "results/multiqc/multiqc_report.html",
315 | "results/multiqc/multiqc_report_data/multiqc.log",
316 | "results/multiqc/multiqc_report_data/multiqc_fastqc.txt",
317 | "results/multiqc/multiqc_report_data/multiqc_general_stats.txt",
318 | "results/multiqc/multiqc_report_data/multiqc_sources.txt",
319 | "results/multiqc/multiqc_report_data/multiqc_star.txt",
320 | benchmark:
321 | "benchmarks/multiqc/multiqc.txt"
322 | threads: 1
323 | resources:
324 | nodes = 1,
325 | mem_gb = 32,
326 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
327 | envmodules:
328 | config['modules']['multiqc']
329 | shell:
330 | """
331 | multiqc -f {params} \
332 | -o results/multiqc \
333 | --ignore '*._STARpass1/*' \
334 | -n multiqc_report.html \
335 | --cl-config 'max_table_rows: 999999'
336 | """
337 |
338 |
--------------------------------------------------------------------------------
/workflow/rules/variants.smk:
--------------------------------------------------------------------------------
1 | # variant calling based on the GATK best practices as documented at https://github.com/gatk-workflows/gatk4-rnaseq-germline-snps-indels/blob/master/gatk4-rna-best-practices.wdl -- accessed Aug 11, 2020
2 |
3 | rule markdups:
4 | input:
5 | "results/star/{sample}.Aligned.out.bam"
6 | output:
7 | bam="results/variant_calling/markdup/{sample}.Aligned.out.mrkdup.bam",
8 | metrics="results/variant_calling/markdup/{sample}.Aligned.out.mrkdup.metrics"
9 | params:
10 | benchmark:
11 | "benchmarks/variant_calling/markdup/{sample}.txt"
12 | envmodules:
13 | config['modules']['gatk']
14 | threads: 4
15 | resources:
16 | mem_gb = 120,
17 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
18 | shell:
19 | """
20 | gatk --java-options "-Xms8g -Xmx{resources.mem_gb}g -Djava.io.tmpdir=./tmp" \
21 | MarkDuplicatesSpark \
22 | --spark-master local[{threads}] \
23 | -I {input} \
24 | -O {output.bam} \
25 | -M {output.metrics} \
26 | --conf spark.executor.cores={threads} \
27 | --conf spark.local.dir=./tmp \
28 | --conf spark.driver.memory=6g \
29 | --conf spark.executor.memory=5g
30 |
31 | """
32 |
33 | rule splitncigar:
34 | input:
35 | "results/variant_calling/markdup/{sample}.Aligned.out.mrkdup.bam"
36 | output:
37 | "results/variant_calling/splitncigar/{sample}.Aligned.out.mrkdup.splitncigar.bam"
38 | benchmark:
39 | "benchmarks/variant_calling/splitncigar/{sample}.txt"
40 | params:
41 | ref_fasta=config["ref"]["sequence"],
42 | envmodules:
43 | config['modules']['gatk']
44 | threads: 4
45 | resources:
46 | mem_gb = 96,
47 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
48 | shell:
49 | """
50 | gatk --java-options "-Xms8g -Xmx{resources.mem_gb}g -Djava.io.tmpdir=./tmp" \
51 | SplitNCigarReads \
52 | -R {params.ref_fasta} \
53 | -I {input} \
54 | -O {output}
55 | """
56 |
57 | rule haplotypecaller:
58 | input:
59 | bam=lambda wildcards: "results/variant_calling/splitncigar/{sample}.Aligned.out.mrkdup.splitncigar.bam" if wildcards.round == "bqsr" else "results/variant_calling/final/00_BQSR/{sample}.bqsr.bam"
60 | output:
61 | "results/variant_calling/{round}/01_haplotypecaller/{sample}.{contig_group}.g.vcf.gz"
62 | benchmark:
63 | "benchmarks/variant_calling/{round}/01_haplotypecaller/{sample}.{contig_group}.txt"
64 | params:
65 | dbsnp=lambda wildcards: f'--dbsnp {config["ref"]["known_snps"]}' if config["ref"]["known_snps"] != "" else "",
66 | ref_fasta=config["ref"]["sequence"],
67 | contigs = lambda wildcards: "-L " + contig_groups[contig_groups.name == wildcards.contig_group]['contigs'].values[0].replace(",", " -L "),
68 |
69 | envmodules:
70 | config["modules"]["gatk"]
71 | threads: 4
72 | resources:
73 | mem_gb = 80,
74 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
75 | shell:
76 | """
77 | gatk --java-options "-Xms8g -Xmx{resources.mem_gb}g -Djava.io.tmpdir=./tmp" \
78 | HaplotypeCaller \
79 | -R {params.ref_fasta} \
80 | -I {input.bam} \
81 | -O {output} \
82 | -ERC GVCF \
83 | -dont-use-soft-clipped-bases \
84 | --native-pair-hmm-threads {threads} \
85 | --standard-min-confidence-threshold-for-calling 20 \
86 | {params.dbsnp} \
87 | {params.contigs}
88 | """
89 |
90 | rule combinevar:
91 | input:
92 | lambda wildcards: expand("results/variant_calling/{{round}}/01_haplotypecaller/{sample}.{contig_group}.g.vcf.gz", sample=samples['sample'].unique(), contig_group=wildcards.contig_group)
93 |
94 | output:
95 | touch=touch("results/variant_calling/{round}/02_combinevar/{contig_group}.done"),
96 | genomicsdb=directory("results/variant_calling/{round}/02_combinevar/{contig_group}.genomicsdb"),
97 | benchmark:
98 | "benchmarks/variant_calling/{round}/02_combinevar/{contig_group}.txt"
99 | params:
100 | sample_gvcfs = lambda wildcards, input: list(map("-V {}".format, input)),
101 | contigs = lambda wildcards: "-L " + contig_groups[contig_groups.name == wildcards.contig_group]['contigs'].values[0].replace(",", " -L "),
102 | envmodules:
103 | config["modules"]["gatk"]
104 | threads: 4
105 | resources:
106 | mem_gb = 120,
107 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
108 | shell:
109 | """
110 | gatk --java-options "-Xms8g -Xmx{resources.mem_gb}g -Djava.io.tmpdir=./tmp" \
111 | GenomicsDBImport \
112 | {params.sample_gvcfs} \
113 | --reader-threads {threads} \
114 | --genomicsdb-workspace-path {output.genomicsdb} \
115 | {params.contigs}
116 | """
117 |
118 | rule jointgeno:
119 | input:
120 | "results/variant_calling/{round}/02_combinevar/{contig_group}.done"
121 | output:
122 | vcf="results/variant_calling/{round}/03_jointgeno/all.{contig_group}.vcf.gz",
123 | benchmark:
124 | "benchmarks/variant_calling/{round}/03_jointgeno/all.{contig_group}.txt"
125 | params:
126 | ref_fasta=config["ref"]["sequence"],
127 | genomicsdb="results/variant_calling/{round}/02_combinevar/{contig_group}.genomicsdb"
128 | envmodules:
129 | config["modules"]["gatk"]
130 | threads: 4
131 | resources:
132 | mem_gb = 80,
133 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
134 | shell:
135 | """
136 | gatk --java-options "-Xms8g -Xmx{resources.mem_gb}g -Djava.io.tmpdir=./tmp" \
137 | GenotypeGVCFs \
138 | -R {params.ref_fasta} \
139 | -V gendb://{params.genomicsdb} \
140 | -O {output.vcf}
141 | """
142 |
143 | rule sortVCF:
144 | """
145 | Sort the output VCFs from joint genotyping. Merging errors out sometimes if we do not do this step.
146 | """
147 | input:
148 | vcf="results/variant_calling/{round}/03_jointgeno/all.{contig_group}.vcf.gz",
149 | output:
150 | sorted_vcf="results/variant_calling/{round}/04_sortvcf/all.{contig_group}.sort.vcf.gz"
151 | benchmark:
152 | "benchmarks/variant_calling/{round}/04_sortvcf/all.{contig_group}.txt"
153 | params:
154 | dictionary=config['ref']['dict'],
155 | envmodules:
156 | config["modules"]["gatk"]
157 | threads: 4
158 | resources:
159 | mem_gb = 80,
160 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
161 | shell:
162 | """
163 | gatk --java-options "-Xms8g -Xmx{resources.mem_gb}g -Djava.io.tmpdir=./tmp" \
164 | SortVcf \
165 | -I {input.vcf} \
166 | -O {output.sorted_vcf} \
167 | -SD {params.dictionary}
168 | """
169 |
170 | rule merge_vcf:
171 | """
172 | Merge the contig group VCFs into one unified VCF.
173 | """
174 | input:
175 | expand("results/variant_calling/{{round}}/04_sortvcf/all.{contig_grp}.sort.vcf.gz", contig_grp=contig_groups.name)
176 | output:
177 | raw="results/variant_calling/{round}/05_merge_vcf/all.merged.vcf.gz",
178 | raw_tbi="results/variant_calling/{round}/05_merge_vcf/all.merged.vcf.gz.tbi",
179 | vt_peek_raw="results/variant_calling/{round}/05_merge_vcf/all.merged.vcf.gz.vt_peek.txt",
180 | benchmark:
181 | "benchmarks/variant_calling/{round}/05_merge_vcf/benchmark.txt"
182 | params:
183 | ref_fasta=config["ref"]["sequence"],
184 | dictionary=config['ref']['dict'],
185 | in_vcfs = lambda wildcards, input: ' '.join(['--INPUT ' + vcf for vcf in input])
186 | envmodules:
187 | config["modules"]["gatk"],
188 | config["modules"]["vt"],
189 | threads: 4
190 | resources:
191 | mem_gb = 80,
192 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
193 | shell:
194 | """
195 | gatk --java-options "-Xms8g -Xmx{resources.mem_gb}g -Djava.io.tmpdir=./tmp" \
196 | MergeVcfs \
197 | {params.in_vcfs} \
198 | --SEQUENCE_DICTIONARY {params.dictionary} \
199 | --OUTPUT {output.raw}
200 |
201 | vt peek -r {params.ref_fasta} {output.raw} 2> {output.vt_peek_raw}
202 | """
203 |
204 | def get_filt_params (wildcards):
205 | # parameters adapted from https://gencore.bio.nyu.edu/variant-calling-pipeline-gatk4/
206 | if (wildcards.var_type == "SNP"):
207 | return """--cluster-window-size 35 \
208 | --cluster-size 3 \
209 | --filter-name 'FS' \
210 | --filter 'FS > 30.0' \
211 | --filter-name 'QD' \
212 | --filter 'QD < 2.0'"""
213 | elif (wildcards.var_type == "INDEL"):
214 | return """--cluster-window-size 35 \
215 | --cluster-size 3 \
216 | --filter-name 'FS' \
217 | --filter 'FS > 30.0' \
218 | --filter-name 'QD' \
219 | --filter 'QD < 2.0'"""
220 | else:
221 | raise Exception("var_type wildcard must be either SNP or INDEL.")
222 |
223 | rule filter_vcf:
224 | """
225 | Do quality filters. Use different paramters depending on SNPs verus indels ('SNP' or 'INDEL').
226 | """
227 | input:
228 | "results/variant_calling/{round}/05_merge_vcf/all.merged.vcf.gz"
229 | output:
230 | raw="results/variant_calling/{round}/06_filter_vcf/all.merged.{var_type}.vcf.gz",
231 | filt="results/variant_calling/{round}/06_filter_vcf/all.merged.filt.{var_type}.vcf.gz",
232 | pass_only="results/variant_calling/{round}/06_filter_vcf/all.merged.filt.PASS.{var_type}.vcf.gz",
233 | vt_peek_pass="results/variant_calling/{round}/06_filter_vcf/all.merged.filt.PASS.{var_type}.vcf.gz.vt_peek.txt"
234 | benchmark:
235 | "benchmarks/variant_calling/{round}/06_filter_vcf/{var_type}.txt"
236 | params:
237 | ref_fasta=config["ref"]["sequence"],
238 | filt_params=get_filt_params
239 | envmodules:
240 | config["modules"]["gatk"],
241 | config["modules"]["vt"]
242 | threads: 4
243 | resources:
244 | mem_gb = 80,
245 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
246 | shell:
247 | """
248 | gatk --java-options "-Xms8g -Xmx{resources.mem_gb}g -Djava.io.tmpdir=./tmp" \
249 | SelectVariants \
250 | -R {params.ref_fasta} \
251 | -V {input} \
252 | --select-type-to-include {wildcards.var_type} \
253 | -O {output.raw}
254 |
255 | echo "SelectVariants 1 done."
256 | echo "SelectVariants 1 done." 1>&2
257 |
258 | gatk --java-options "-Xms8g -Xmx{resources.mem_gb}g -Djava.io.tmpdir=./tmp" \
259 | VariantFiltration \
260 | --R {params.ref_fasta} \
261 | --V {output.raw} \
262 | {params.filt_params} \
263 | -O {output.filt}
264 |
265 | echo "VariantFiltration done."
266 | echo "VariantFiltration done." 1>&2
267 |
268 | gatk --java-options "-Xms8g -Xmx{resources.mem_gb}g -Djava.io.tmpdir=./tmp" \
269 | SelectVariants \
270 | -R {params.ref_fasta} \
271 | -V {output.filt} \
272 | --exclude-filtered \
273 | -O {output.pass_only}
274 |
275 | echo "SelectVariants 2 done."
276 | echo "SelectVariants 2 done." 1>&2
277 |
278 | vt peek -r {params.ref_fasta} {output.pass_only} 2> {output.vt_peek_pass}
279 | """
280 |
281 | rule BQSR:
282 | """
283 | Base quality score recalibrator
284 | """
285 | input:
286 | bam="results/variant_calling/splitncigar/{sample}.Aligned.out.mrkdup.splitncigar.bam",
287 | known_snps_vcf=config["ref"]["known_snps"] if config["ref"]["known_snps"] else "results/variant_calling/bqsr/06_filter_vcf/all.merged.filt.PASS.SNP.vcf.gz",
288 | known_indels_vcf=config["ref"]["known_indels"] if config["ref"]["known_indels"] else "results/variant_calling/bqsr/06_filter_vcf/all.merged.filt.PASS.INDEL.vcf.gz",
289 | output:
290 | recal_table="results/variant_calling/final/00_BQSR/{sample}.bqsr.table",
291 | recal_bam="results/variant_calling/final/00_BQSR/{sample}.bqsr.bam"
292 | benchmark:
293 | "benchmarks/variant_calling/final/00_BQSR/{sample}.txt"
294 | params:
295 | ref_fasta=config["ref"]["sequence"],
296 | envmodules:
297 | config["modules"]["gatk"],
298 | threads: 4
299 | resources:
300 | mem_gb = 80,
301 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
302 | shell:
303 | """
304 | gatk --java-options "-Xms8g -Xmx{resources.mem_gb}g -Djava.io.tmpdir=./tmp" \
305 | BaseRecalibrator \
306 | -R {params.ref_fasta} \
307 | -I {input.bam} \
308 | --known-sites {input.known_snps_vcf} \
309 | --known-sites {input.known_indels_vcf} \
310 | -O {output.recal_table}
311 |
312 | echo "BaseRecalibrator done."
313 | echo "BaseRecalibrator done." 1>&2
314 |
315 | gatk --java-options "-Xms8g -Xmx{resources.mem_gb}g -Djava.io.tmpdir=./tmp" \
316 | ApplyBQSR \
317 | -R {params.ref_fasta} \
318 | -I {input.bam} \
319 | -bqsr {output.recal_table} \
320 | -O {output.recal_bam}
321 |
322 | echo "ApplyBQSR done."
323 | echo "ApplyBQSR done." 1>&2
324 |
325 | """
326 |
327 | rule variant_annot:
328 | input:
329 | "results/variant_calling/final/06_filter_vcf/all.merged.filt.PASS.SNP.vcf.gz"
330 | output:
331 | html="results/variant_calling/final/07a_variant_annot/all.merged.filt.PASS.snpeff.html",
332 | vcf="results/variant_calling/final/07a_variant_annot/all.merged.filt.PASS.snpeff.vcf.gz",
333 | tbi="results/variant_calling/final/07a_variant_annot/all.merged.filt.PASS.snpeff.vcf.gz.tbi",
334 | html_canon="results/variant_calling/final/07a_variant_annot/all.merged.filt.PASS.snpeff_canonical.html",
335 | vcf_canon="results/variant_calling/final/07a_variant_annot/all.merged.filt.PASS.snpeff_canonical.vcf.gz",
336 | tbi_canon="results/variant_calling/final/07a_variant_annot/all.merged.filt.PASS.snpeff_canonical.vcf.gz.tbi",
337 | benchmark:
338 | "benchmarks/variant_calling/final/07a_variant_annot/benchmark.txt"
339 | params:
340 | db_id=config["ref"]["snpeff_db_id"],
341 | envmodules:
342 | config['modules']['snpeff'],
343 | config['modules']['htslib']
344 | threads: 4
345 | resources:
346 | mem_gb = 80,
347 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
348 | shell:
349 | """
350 | java -Xms8g -Xmx{resources.mem_gb}g -Djava.io.tmpdir=./tmp -jar $SNPEFF/snpEff.jar eff \
351 | -v \
352 | -canon \
353 | -onlyProtein \
354 | -stats {output.html_canon} \
355 | {params.db_id} \
356 | {input} | \
357 | bgzip > {output.vcf_canon}
358 |
359 | tabix {output.vcf_canon}
360 |
361 |
362 | java -Xms8g -Xmx{resources.mem_gb}g -Djava.io.tmpdir=./tmp -jar $SNPEFF/snpEff.jar eff \
363 | -v \
364 | -onlyProtein \
365 | -stats {output.html} \
366 | {params.db_id} \
367 | {input} | \
368 | bgzip > {output.vcf}
369 |
370 | tabix {output.vcf}
371 | """
372 |
373 | rule snprelate:
374 | input:
375 | vcf="results/variant_calling/final/06_filter_vcf/all.merged.filt.PASS.SNP.vcf.gz",
376 | renv_lock=ancient("results/{Rproj}/renv.lock".format(Rproj=config['Rproj_dirname']))
377 | output:
378 | symlink_rmd = "results/variant_calling/final/07b_snp_pca_and_dendro/snprelate.Rmd",
379 | symlink_vcf = "results/variant_calling/final/07b_snp_pca_and_dendro/all.merged.filt.PASS.SNP.vcf.gz",
380 | html = "results/variant_calling/final/07b_snp_pca_and_dendro/snprelate.html",
381 | outdir = directory("results/variant_calling/final/07b_snp_pca_and_dendro/snprelate_out_files")
382 | benchmark:
383 | "benchmarks/variant_calling/final/07b_snprelate/benchmark.txt"
384 | params:
385 | rmd='workflow/scripts/snprelate.Rmd',
386 | wd = lambda wildcards, output: os.path.dirname(output.html),
387 | in_vcf = lambda wildcards, input: os.path.basename(input.vcf),
388 | outdir = lambda wildcards, output: os.path.basename(output.outdir),
389 | renv_rproj_dir = lambda wildcards, input: os.path.dirname(input.renv_lock),
390 | snakemake_dir = snakemake_dir
391 | envmodules:
392 | config['modules']['R'],
393 | config['modules']['pandoc']
394 | threads: 1
395 | resources:
396 | mem_gb = 60,
397 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
398 | shell:
399 | """
400 | ln -sr {input.vcf} {output.symlink_vcf}
401 | ln -sr {params.rmd} {output.symlink_rmd}
402 |
403 | cd {params.wd}
404 |
405 | Rscript --vanilla -e "rmarkdown::render('snprelate.Rmd', params = list(in_vcf = '{params.in_vcf}', outdir = '{params.outdir}', renv_rproj_dir = '{params.snakemake_dir}/{params.renv_rproj_dir}'))"
406 | """
407 |
--------------------------------------------------------------------------------
/workflow/rules/visualisation.smk:
--------------------------------------------------------------------------------
1 | def get_bigwig_norm_factor(wildcards, input):
2 | df = pd.read_table(input.norm_factors, dtype={"sample" : str, "sizefactor" : float })
3 | scalefactor = df[df['sample']==wildcards.sample]['sizefactor'].values[0]
4 | return str(scalefactor)
5 |
6 | def get_bw_strand_param (wildcards):
7 | if wildcards.dir=="fwd":
8 | return "--filterRNAstrand forward"
9 | elif wildcards.dir=="rev":
10 | return "--filterRNAstrand reverse"
11 | else:
12 | return " "
13 |
14 | rule bigwigs:
15 | input:
16 | bam="results/star/{sample}.sorted.bam",
17 | norm_factors="results/SummarizedExperiment/DESeq2_sizeFactors_reciprocal.tsv"
18 | output:
19 | bw="results/bigwigs/{sample}.{dir}.bw"
20 | params:
21 | scale_factor=get_bigwig_norm_factor,
22 | strand=get_bw_strand_param,
23 | benchmark:
24 | "benchmarks/bigwigs/{sample}.{dir}.txt"
25 | envmodules:
26 | config['modules']['deeptools']
27 | threads: 8
28 | resources:
29 | nodes = 1,
30 | mem_gb = 16,
31 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
32 | shell:
33 | """
34 | bamCoverage -b {input.bam} -o {output.bw} --minMappingQuality 30 \
35 | --normalizeUsing "None" -p {threads} --binSize 10 \
36 | --scaleFactor {params.scale_factor} {params.strand}
37 | """
38 |
39 | rule avg_bigwigs:
40 | input:
41 | lambda wildcards: expand("results/bigwigs/{sample}.{dir}.bw", sample=samples[samples['group']==wildcards.group]['sample'], dir=wildcards.dir)
42 | output:
43 | bw="results/avg_bigwigs/{group}.{dir}.bw"
44 | params:
45 | benchmark:
46 | "benchmarks/avg_bigwigs/{group}.{dir}.txt"
47 | envmodules:
48 | config['modules']['deeptools']
49 | threads: 8
50 | resources:
51 | nodes = 1,
52 | mem_gb = 72,
53 | log_prefix=lambda wildcards: "_".join(wildcards) if len(wildcards) > 0 else "log"
54 | shell:
55 | """
56 | bigwigAverage -b {input} --binSize 10 -p {threads} -o {output.bw} -of "bigwig"
57 | """
58 |
59 |
--------------------------------------------------------------------------------
/workflow/scripts/add_DE_to_SCE.R:
--------------------------------------------------------------------------------
1 | renv::load(snakemake@params[["renv_rproj_dir"]])
2 | .libPaths()
3 |
4 | sce_file <- snakemake@input[['sce']]
5 | comps <- snakemake@params[['comparisons']]
6 | de_res_outfiles_dir <- snakemake@params[['de_res_outfiles_dir']]
7 | out_sce <- snakemake@output[['sce']]
8 |
9 | options(warn=1) # show all warnings
10 |
11 | library(dplyr)
12 | library(SingleCellExperiment)
13 | library(DESeq2)
14 | library(readr)
15 |
16 | sce <- readRDS(sce_file)
17 |
18 | for (i in seq_along(comps)){
19 | curr_comp <- comps[i]
20 | message("Parsing DE results for ", curr_comp, ".")
21 | de_res <- readRDS(file.path(de_res_outfiles_dir, curr_comp, "de_res.rds"))
22 | rowData(sce)[[paste0(curr_comp, ".padj")]] <- de_res$padj[match(rowData(sce)$ens_gene, de_res$ens_gene)]
23 | rowData(sce)[[paste0(curr_comp, ".LFC")]] <- de_res$log2FoldChange[match(rowData(sce)$ens_gene, de_res$ens_gene)]
24 | rowData(sce)[[paste0(curr_comp, ".rank")]] <- rank(rowData(sce)[[paste0(curr_comp, ".padj")]], ties.method = "min")
25 | }
26 |
27 | write_rds(sce, out_sce)
28 |
--------------------------------------------------------------------------------
/workflow/scripts/install_renv_pkges.R:
--------------------------------------------------------------------------------
1 | args <- commandArgs(trailingOnly = TRUE)
2 |
3 | pkges_file <- args[1]
4 |
5 | # https://github.com/rstudio/renv/issues/81#issuecomment-497131224
6 | options(repos = BiocManager::repositories())
7 |
8 | # Get list of packages available on BioConductor
9 | bioc_repos <- BiocManager::repositories()
10 | avail_bioc <- available.packages(repos=bioc_repos[grepl("BioC", names(bioc_repos))])
11 |
12 | message("Initiating renv...")
13 | renv::init(bioconductor=TRUE)
14 |
15 | # message("Updating packages in renv library...")
16 | # renv::update()
17 |
18 | message("Double check that all dependencies can be loaded.")
19 |
20 | pkges <- read.table(pkges_file)[[1]]
21 |
22 | for (pkg in pkges){
23 | req_pkg <- pkg
24 | if (grepl("\\/", req_pkg)){
25 | req_pkg <- basename(req_pkg) # remove Github account name if present
26 | message("Removed Github account name from ", pkg, " to obtain ", req_pkg, ".")
27 | }
28 | if (grepl("\\@", req_pkg)){
29 | req_pkg <- gsub("@\\S+$", "", req_pkg) # remove version number if present
30 | message("Removed verion number from ", pkg, " to obtain ", req_pkg, ".")
31 | }
32 | if(!suppressPackageStartupMessages(require(req_pkg, character.only=TRUE, quietly = TRUE, warn.conflicts = FALSE))){
33 |
34 | if (pkg %in% avail_bioc[, "Package"]){
35 | # adding "bioc::" as this has been reported to help prevent installing devel BioC packages and keep packages on the same BioC release. See https://github.com/rstudio/renv/issues/244
36 | # see also https://rstudio.github.io/renv/reference/install.html for syntax for 'packages' argument
37 | pkg <- paste0("bioc::", pkg)
38 | }
39 |
40 | message("Unable to load ", req_pkg, ". Trying to install ", pkg, " ...")
41 | renv::install(pkg)
42 | }
43 | }
44 |
45 | message("Run renv snapshot...")
46 | renv::snapshot()
47 |
48 | sessionInfo()
49 |
--------------------------------------------------------------------------------
/workflow/scripts/make_Rproject.R:
--------------------------------------------------------------------------------
1 | options(usethis.allow_nested_project = TRUE)
2 |
3 | args <- commandArgs(trailingOnly = TRUE)
4 |
5 | R_proj_name <- args[1]
6 |
7 | for (pkg in c("usethis","renv","BiocManager")){
8 | if(!require(pkg, character.only=TRUE)){
9 | # specify 'repos' to avoid being asked to choose mirror.
10 | install.packages(pkg, repos = "https://cloud.r-project.org/")
11 | }
12 | }
13 |
14 | usethis::create_project(path = R_proj_name, open = TRUE, rstudio = TRUE)
15 |
16 | sessionInfo()
17 |
18 |
--------------------------------------------------------------------------------
/workflow/scripts/make_sce.R:
--------------------------------------------------------------------------------
1 | args <- commandArgs(trailingOnly = TRUE)
2 |
3 | gtf_file <- args[1]
4 | orgdb <- args[2]
5 | renv_rproj_dir <- args[3]
6 | out_se <- args[4]
7 | out_sce <- args[5]
8 | out_sizeFactors <- args[6]
9 | out_txi <- args[7]
10 | out_strand <- args[8]
11 |
12 | # use the packages in the renv
13 | renv::load(renv_rproj_dir)
14 |
15 | star_dir <- "results/star"
16 | salmon_dir <- "results/salmon"
17 | samplesheet <- "config/samplesheet/units.tsv"
18 |
19 | # Packages loaded
20 |
21 | library(dplyr)
22 | library(stringr)
23 | library(readr)
24 | library(tibble)
25 | library(edgeR)
26 | library(rtracklayer)
27 | # load the org.db for your organism
28 | library(orgdb, character.only=TRUE)
29 | library(DESeq2)
30 | library(AnnotationDbi)
31 | library(tximport)
32 | library(GenomicFeatures)
33 | library(scater)
34 | library(rjson)
35 |
36 | # Infer the strand from Salmon results
37 | # ISR or SR = reverse
38 | # ISF or SF = forward
39 | # IU or U = unstranded
40 | salmon_lib_files <- list.files(salmon_dir, pattern = "lib_format_counts.json", recursive=TRUE, full.names = TRUE)
41 | lib_types <- unlist(lapply(salmon_lib_files, function(x) fromJSON(file=x)$expected_format))
42 | lib_type <- unique(lib_types)
43 |
44 | if(length(lib_type) > 1){
45 | stop("More than 1 library type detected.")
46 | }
47 |
48 | if(!lib_type %in% c("ISR", "SR", "ISF", "SF", "IU", "U")){
49 | stop("Unknown library type detected.")
50 | }
51 |
52 | message(str_glue("Salmon-inferred library type is {lib_type}."))
53 |
54 | fileConn <- file(out_strand)
55 | writeLines(lib_type, con = fileConn)
56 | close(fileConn)
57 |
58 | # Read counts
59 | files <- list.files(star_dir, pattern = "ReadsPerGene.out.tab", full.names = FALSE)
60 | names(files) <- str_remove_all(files, ".ReadsPerGene.out.tab$")
61 |
62 | counts_col <- case_when(
63 | lib_type %in% c("ISR", "SR") ~ 4,
64 | lib_type %in% c("ISF", "SF") ~ 3,
65 | lib_type %in% c("IU", "U") ~ 2,
66 | .default=999
67 | )
68 | stopifnot(counts_col %in% c(2, 3, 4))
69 |
70 | dge <- edgeR::readDGE(files, path = star_dir, columns = c(1, counts_col),
71 | skip=4, labels = names(files), header=FALSE)
72 |
73 |
74 | raw_cts <- edgeR::getCounts(dge)
75 | names(attributes(raw_cts)$dimnames) <- NULL
76 |
77 | # Read TPMs
78 |
79 | txdb <- makeTxDbFromGFF(gtf_file)
80 | k <- keys(txdb, keytype = "TXNAME")
81 | tx2gene <- AnnotationDbi::select(txdb, k, "GENEID", "TXNAME")
82 |
83 | files <- list.files(salmon_dir, recursive=TRUE, pattern = "quant.sf", full.names = TRUE)
84 | names(files) <- basename(str_remove(files, "\\/quant.sf"))
85 |
86 | # extract the first transcript from one of the salmon result files
87 | test_gtf_tx <- stringr::str_split_1(readLines(files[1], 2)[2], "\\t")[1]
88 | message("Using ", test_gtf_tx, " to decide whether to turn on ignoreTxVersion in tximport.")
89 |
90 | tximport_ignore_tx_ver <- NULL
91 | tximport_ignore_tx_ver <- if (test_gtf_tx %in% tx2gene$TXNAME) {
92 | tximport_ignore_tx_ver <- FALSE
93 | } else if (str_remove(test_gtf_tx, "\\.\\d+$") %in% tx2gene$TXNAME) {
94 | tximport_ignore_tx_ver <- TRUE
95 | } else{
96 | stop("No match between GTF and Salmon transcript names with or without removing transcript version.")
97 | }
98 | message("The 'ignoreTxVersion' parameter in tximport will be set to ", as.character(tximport_ignore_tx_ver))
99 |
100 | txi.salmon <- tximport(files, type = "salmon", tx2gene = tx2gene, ignoreTxVersion=tximport_ignore_tx_ver)
101 | write_rds(txi.salmon, out_txi)
102 |
103 | tpms <- txi.salmon$abundance
104 |
105 | # some genes are only in the STAR counts
106 | tpms <- tpms[match(rownames(raw_cts), rownames(tpms)), ]
107 | rownames(tpms) <- rownames(raw_cts)
108 |
109 |
110 | # Row annot
111 |
112 | # add gene symbols
113 | gene_names_df <- data.frame(row.names = rownames(raw_cts))
114 |
115 | ens_no_version <- str_remove(rownames(gene_names_df), "\\.\\d+$")
116 | stopifnot(length(ens_no_version) == length(unique(ens_no_version)))
117 |
118 | gene_names_df$Symbol <- AnnotationDbi::mapIds(eval(as.name(orgdb)), ens_no_version,
119 | keytype="ENSEMBL", column="SYMBOL",
120 | multiVals="first")
121 |
122 | gene_names_df$Uniq_syms <- scater::uniquifyFeatureNames(rownames(gene_names_df), gene_names_df$Symbol)
123 | gene_names_df$entrez <- AnnotationDbi::mapIds(eval(as.name(orgdb)), ens_no_version,
124 | keytype="ENSEMBL", column="ENTREZID",
125 | multiVals="first") # there are duplicates in here.
126 |
127 | gene_names_df$Gene_name <- AnnotationDbi::mapIds(eval(as.name(orgdb)), ens_no_version,
128 | keytype="ENSEMBL", column="GENENAME",
129 | multiVals="first")
130 |
131 | ## add alias column to gene_names_df
132 | gtf_df <- rtracklayer::import(gtf_file) |>
133 | as.data.frame() |>
134 | dplyr::select(gene_id, gene_name) |>
135 | dplyr::distinct() |>
136 | column_to_rownames("gene_id")
137 |
138 | stopifnot(all(rownames(gtf_df) %in% rownames((gene_names_df))))
139 | gene_names_df$alias <- gtf_df$gene_name[match(rownames(gene_names_df), rownames(gtf_df))]
140 |
141 | # Sample meta
142 |
143 | data_for_DE <- read_tsv(samplesheet) %>%
144 | as.data.frame() %>%
145 | dplyr::select(-fq1, -fq2) %>%
146 | unique() # samplesheet can have more than one row for a given sample (e.g. sequenced on more than one lane)
147 |
148 | stopifnot(length(data_for_DE$sample) == length(unique(data_for_DE$sample)))
149 |
150 | # samplesheet must have at least sample and group
151 | stopifnot(c("sample", "group") %in% colnames(data_for_DE))
152 |
153 | rownames(data_for_DE) <- data_for_DE$sample
154 |
155 | # make sure order of samples in the meta data matches the counts
156 | data_for_DE <- data_for_DE[colnames(raw_cts), ]
157 |
158 | stopifnot(all(!is.na(data_for_DE$group)))
159 |
160 | # Make DDS
161 |
162 | stopifnot(identical(rownames(data_for_DE), colnames(raw_cts)))
163 | stopifnot(identical(rownames(gene_names_df), rownames(raw_cts)))
164 | count_data <- list(counts=raw_cts, tpms=tpms[rownames(raw_cts), ])
165 |
166 | se <- SummarizedExperiment(assays = count_data, colData = data_for_DE, rowData = gene_names_df)
167 | se <- se[, order(se$group)] # order samples by group
168 |
169 | # Add vst
170 | dds <- DESeqDataSet(se, design = ~ group)
171 | dds <- DESeq(dds)
172 | vsd <- vst(dds, blind=FALSE)
173 |
174 | assays(se)$vst <- assay(vsd)
175 |
176 | write_rds(se, out_se)
177 |
178 | # PCA
179 | sce <- as(se, "SingleCellExperiment")
180 | sce <- runPCA(sce, ntop=5000, ncomponents = 4, exprs_values="vst")
181 |
182 | rowData(sce)$ens_gene <- rownames(sce)
183 | rownames(sce) <- rowData(sce)$Uniq_syms
184 | write_rds(sce, out_sce)
185 |
186 |
187 | # Output size factors for use with other tools
188 | sizefactors <- 1/dds$sizeFactor
189 | tibble::tibble(sample=names(sizefactors), sizefactor=sizefactors) %>%
190 | write_tsv(., out_sizeFactors) # "SizeFactors will now contain a factor for every sample which can be used to divide the 4th colun of a bedGraph/bigwig by. Both the aforementioned tools (bamCoverage and genomecov) have options though to directly scale the output by a factor (--scaleFactor or --scale respectively). !! Note though that these options will multiply rather than divide the 4th column with the factor, therefore you would need to provide the reciprocal as mentioned in the code chunk above." https://www.biostars.org/p/413626/#414440
191 |
192 | sessionInfo()
193 |
--------------------------------------------------------------------------------
/workflow/scripts/snprelate.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "snprelate"
3 | author: "Kin Lau"
4 | date: '`r format(Sys.Date(), "%B %d, %Y")`'
5 | output:
6 | html_document:
7 | code_folding: hide
8 | self_contained: yes
9 | toc: true
10 | toc_depth: 5
11 | toc_float:
12 | collapsed: true
13 | smooth_scroll: false
14 | number_sections: true
15 | params:
16 | in_vcf: ""
17 | outdir: ""
18 | renv_rproj_dir: ""
19 | ---
20 |
21 | ```{r starttime}
22 | # save start time for script
23 | start_ptm <- proc.time()
24 | start_ptm
25 |
26 | renv::load(params$renv_rproj_dir)
27 |
28 | outdir <- params$outdir
29 | dir.create(outdir, recursive=TRUE)
30 | ```
31 |
32 | ```{r setup, include=FALSE}
33 | knitr::opts_chunk$set(echo=TRUE, warning=TRUE, message=TRUE, cache=FALSE, fig.path=file.path(outdir, "individual_figures/"))
34 | ```
35 |
36 | # Packages loaded
37 |
38 | ```{r loadlibs, echo=TRUE, warning=TRUE, message=TRUE, cache=FALSE}
39 | library(SNPRelate)
40 | library(ggplot2)
41 | library(dplyr)
42 | ```
43 |
44 | # Convert VCF to GDS
45 |
46 | We keep only the biallelic variants.
47 |
48 | ```{r readvcf}
49 | vcf.fn <- params$in_vcf
50 |
51 | # convert to GDS
52 | gds_file <- file.path(outdir, 'all.gds')
53 |
54 | snpgdsVCF2GDS(vcf.fn, gds_file, method="biallelic.only")
55 |
56 | ```
57 |
58 | # Open the GDS file
59 |
60 | ```{r opengds}
61 | genofile <- snpgdsOpen(gds_file)
62 |
63 | ```
64 |
65 | # LD-pruned
66 |
67 | We use an LD threshold of 0.5. SNPrelate scans the genome with a sliding window, discarding SNPs within each window of the LD exceeds 0.5.
68 |
69 | We also keep only SNPs with a missing rate of 0 (no missing data).
70 |
71 | ```{r ldprune}
72 | set.seed(1000)
73 |
74 | # Try different LD thresholds for sensitivity analysis
75 | snpset <- snpgdsLDpruning(genofile, ld.threshold=0.5, missing.rate=0) # using LD threshold default used in SNPhylo
76 |
77 | # Get all selected snp id
78 | snpset.id <- unlist(snpset)
79 | ```
80 |
81 | ## Identity-By-State (IBS)
82 |
83 | Average IBS is a metric for each pair of samples describing the average porportion of shared alleles for each locus.
84 |
85 | ```{r ibs_mat}
86 | set.seed(100)
87 | ibs <- snpgdsIBS(genofile, num.thread=1, autosome.only=TRUE, missing.rate=0, snp.id = snpset.id)
88 |
89 | # we find 1- ibs so that the values become 'distances' where higher values represent more dissimilar pairs of samples
90 | one_minus_ibs <- 1 - ibs$ibs
91 | colnames(one_minus_ibs) <- ibs$sample.id
92 | rownames(one_minus_ibs) <- ibs$sample.id
93 | ```
94 |
95 | ### MDS
96 |
97 | ```{r mds}
98 | loc <- cmdscale(one_minus_ibs, k = 2)
99 | #x <- loc[, 1]; y <- loc[, 2]
100 | df <- tibble::as_tibble(loc, rownames="sample.id") %>%
101 | dplyr::rename(Dimension1=V1, Dimension2=V2)
102 | #df$sample.id <- ibs$sample.id
103 |
104 | # plot(x, y, xlab = "", ylab = "",
105 | # main = "Multidimensional Scaling Analysis (IBS)")
106 |
107 | ggplot(df, aes(x=Dimension1, y=Dimension2, label=sample.id)) +
108 | geom_point() + ggrepel::geom_label_repel() + ggtitle("MDS (based on IBS)")
109 |
110 | ```
111 |
112 | ### Dendrogram
113 |
114 | Make dendrogram using hierarchical clustering on the IBS.
115 |
116 | ```{r makedendro}
117 | ibs.hc <- snpgdsHCluster(ibs)
118 |
119 | rv <- snpgdsCutTree(ibs.hc)
120 |
121 | ```
122 |
123 | ```{r plot_dendro}
124 | plot(rv$dendrogram, main="Dendrogram based on IBS")
125 |
126 | ```
127 |
128 | ## PCA
129 |
130 | ```{r pca}
131 | #pca <- snpgdsPCA(genofile, snp.id=snpset.id, num.thread=1)
132 | pca <- snpgdsPCA(genofile, num.thread=1, autosome.only=TRUE, missing.rate=0, snp.id = snpset.id)
133 |
134 | # variance proportion (%)
135 | pc.percent <- pca$varprop*100
136 | head(round(pc.percent, 2))
137 |
138 | tab <- data.frame(sample.id = pca$sample.id,
139 | EV1 = pca$eigenvect[,1], # the first eigenvector
140 | EV2 = pca$eigenvect[,2], # the second eigenvector
141 | EV3 = pca$eigenvect[,3],
142 | EV4 = pca$eigenvect[,4],
143 | EV5 = pca$eigenvect[,5],
144 | stringsAsFactors = FALSE)
145 | head(tab)
146 |
147 | #plot(tab$EV1, tab$EV2, xlab="eigenvector 1", ylab="eigenvector 2")
148 | ggplot(tab, aes(x=EV1, y=EV2, label=sample.id)) + geom_point() + ggrepel::geom_label_repel() + ggtitle("PC1 and 2")
149 | ggplot(tab, aes(x=EV3, y=EV4, label=sample.id)) + geom_point() + ggrepel::geom_label_repel() + ggtitle("PC3 and 4")
150 |
151 | ```
152 |
153 | # No LD pruning
154 |
155 | Here we don't prune for LD but we keep the other filters of biallelic SNPs and no missing data.
156 |
157 | ## Identity-By-State (IBS)
158 |
159 | Average IBS is a metric for each pair of samples describing the average porportion of shared alleles for each locus.
160 |
161 | ```{r ibs_mat_noLDpruning}
162 | set.seed(100)
163 | ibs <- snpgdsIBS(genofile, num.thread=1, autosome.only=TRUE, missing.rate=0)
164 |
165 | # we find 1- ibs so that the values become 'distances' where higher values represent more dissimilar pairs of samples
166 | one_minus_ibs <- 1 - ibs$ibs
167 | colnames(one_minus_ibs) <- ibs$sample.id
168 | rownames(one_minus_ibs) <- ibs$sample.id
169 | ```
170 |
171 | ### MDS
172 |
173 | ```{r mds_noLDpruning}
174 | loc <- cmdscale(one_minus_ibs, k = 2)
175 |
176 | df <- tibble::as_tibble(loc, rownames="sample.id") %>%
177 | dplyr::rename(Dimension1=V1, Dimension2=V2)
178 |
179 | ggplot(df, aes(x=Dimension1, y=Dimension2, label=sample.id)) +
180 | geom_point() + ggrepel::geom_label_repel() + ggtitle("MDS (based on IBS)")
181 |
182 | ```
183 |
184 | ### Dendrogram
185 |
186 | Make dendrogram using hierarchical clustering on the IBS.
187 |
188 | ```{r makedendro_noLDpruning}
189 | ibs.hc <- snpgdsHCluster(ibs)
190 |
191 | rv <- snpgdsCutTree(ibs.hc)
192 |
193 | ```
194 |
195 | ```{r plot_dendro_noLDpruning}
196 | plot(rv$dendrogram, main="Dendrogram based on IBS")
197 |
198 | ```
199 |
200 | ## PCA
201 |
202 | ```{r pca_noLDpruning}
203 | #pca <- snpgdsPCA(genofile, snp.id=snpset.id, num.thread=1)
204 | pca <- snpgdsPCA(genofile, num.thread=1, autosome.only=TRUE, missing.rate=0)
205 |
206 | # variance proportion (%)
207 | pc.percent <- pca$varprop*100
208 | head(round(pc.percent, 2))
209 |
210 | tab <- data.frame(sample.id = pca$sample.id,
211 | EV1 = pca$eigenvect[,1], # the first eigenvector
212 | EV2 = pca$eigenvect[,2], # the second eigenvector
213 | EV3 = pca$eigenvect[,3],
214 | EV4 = pca$eigenvect[,4],
215 | EV5 = pca$eigenvect[,5],
216 | stringsAsFactors = FALSE)
217 | head(tab)
218 |
219 | #plot(tab$EV1, tab$EV2, xlab="eigenvector 1", ylab="eigenvector 2")
220 | ggplot(tab, aes(x=EV1, y=EV2, label=sample.id)) + geom_point() + ggrepel::geom_label_repel() + ggtitle("PC1 and 2")
221 | ggplot(tab, aes(x=EV3, y=EV4, label=sample.id)) + geom_point() + ggrepel::geom_label_repel() + ggtitle("PC3 and 4")
222 |
223 | ```
224 |
225 |
226 | # Close GDS
227 |
228 | ```{r closegds}
229 | closefn.gds(genofile)
230 |
231 | ```
232 |
233 | # SessionInfo
234 |
235 | ```{r sessioninfo}
236 | sessionInfo()
237 | ```
238 |
239 | # Time
240 |
241 | ```{r endtime}
242 | # output time taken to run script
243 | end_ptm <- proc.time()
244 | end_ptm
245 | end_ptm - start_ptm
246 |
247 | ```
248 |
--------------------------------------------------------------------------------