biopipen 0.21.0__py3-none-any.whl → 0.34.26__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (290) hide show
  1. biopipen/__init__.py +1 -1
  2. biopipen/core/config.toml +28 -0
  3. biopipen/core/filters.py +79 -4
  4. biopipen/core/proc.py +12 -3
  5. biopipen/core/testing.py +75 -3
  6. biopipen/ns/bam.py +148 -6
  7. biopipen/ns/bed.py +75 -0
  8. biopipen/ns/cellranger.py +186 -0
  9. biopipen/ns/cellranger_pipeline.py +126 -0
  10. biopipen/ns/cnv.py +19 -3
  11. biopipen/ns/cnvkit.py +1 -1
  12. biopipen/ns/cnvkit_pipeline.py +20 -12
  13. biopipen/ns/delim.py +34 -35
  14. biopipen/ns/gene.py +68 -23
  15. biopipen/ns/gsea.py +63 -37
  16. biopipen/ns/misc.py +39 -14
  17. biopipen/ns/plot.py +304 -1
  18. biopipen/ns/protein.py +183 -0
  19. biopipen/ns/regulatory.py +290 -0
  20. biopipen/ns/rnaseq.py +142 -5
  21. biopipen/ns/scrna.py +2053 -473
  22. biopipen/ns/scrna_metabolic_landscape.py +228 -382
  23. biopipen/ns/snp.py +659 -0
  24. biopipen/ns/stats.py +484 -0
  25. biopipen/ns/tcr.py +683 -98
  26. biopipen/ns/vcf.py +236 -2
  27. biopipen/ns/web.py +97 -6
  28. biopipen/reports/bam/CNVpytor.svelte +4 -9
  29. biopipen/reports/cellranger/CellRangerCount.svelte +18 -0
  30. biopipen/reports/cellranger/CellRangerSummary.svelte +16 -0
  31. biopipen/reports/cellranger/CellRangerVdj.svelte +18 -0
  32. biopipen/reports/cnvkit/CNVkitDiagram.svelte +1 -1
  33. biopipen/reports/cnvkit/CNVkitHeatmap.svelte +1 -1
  34. biopipen/reports/cnvkit/CNVkitScatter.svelte +1 -1
  35. biopipen/reports/common.svelte +15 -0
  36. biopipen/reports/protein/ProdigySummary.svelte +16 -0
  37. biopipen/reports/scrna/CellsDistribution.svelte +4 -39
  38. biopipen/reports/scrna/DimPlots.svelte +1 -1
  39. biopipen/reports/scrna/MarkersFinder.svelte +6 -126
  40. biopipen/reports/scrna/MetaMarkers.svelte +3 -75
  41. biopipen/reports/scrna/RadarPlots.svelte +4 -20
  42. biopipen/reports/scrna_metabolic_landscape/MetabolicFeatures.svelte +61 -22
  43. biopipen/reports/scrna_metabolic_landscape/MetabolicPathwayActivity.svelte +88 -82
  44. biopipen/reports/scrna_metabolic_landscape/MetabolicPathwayHeterogeneity.svelte +70 -10
  45. biopipen/reports/snp/PlinkCallRate.svelte +24 -0
  46. biopipen/reports/snp/PlinkFreq.svelte +18 -0
  47. biopipen/reports/snp/PlinkHWE.svelte +18 -0
  48. biopipen/reports/snp/PlinkHet.svelte +18 -0
  49. biopipen/reports/snp/PlinkIBD.svelte +18 -0
  50. biopipen/reports/tcr/CDR3AAPhyschem.svelte +19 -66
  51. biopipen/reports/tcr/ClonalStats.svelte +16 -0
  52. biopipen/reports/tcr/CloneResidency.svelte +3 -93
  53. biopipen/reports/tcr/Immunarch.svelte +4 -155
  54. biopipen/reports/tcr/TCRClusterStats.svelte +3 -45
  55. biopipen/reports/tcr/TESSA.svelte +11 -28
  56. biopipen/reports/utils/misc.liq +22 -7
  57. biopipen/scripts/bam/BamMerge.py +11 -15
  58. biopipen/scripts/bam/BamSampling.py +90 -0
  59. biopipen/scripts/bam/BamSort.py +141 -0
  60. biopipen/scripts/bam/BamSplitChroms.py +10 -10
  61. biopipen/scripts/bam/BamSubsetByBed.py +38 -0
  62. biopipen/scripts/bam/CNAClinic.R +41 -5
  63. biopipen/scripts/bam/CNVpytor.py +153 -54
  64. biopipen/scripts/bam/ControlFREEC.py +13 -14
  65. biopipen/scripts/bam/SamtoolsView.py +33 -0
  66. biopipen/scripts/bed/Bed2Vcf.py +5 -5
  67. biopipen/scripts/bed/BedConsensus.py +5 -5
  68. biopipen/scripts/bed/BedLiftOver.sh +6 -4
  69. biopipen/scripts/bed/BedtoolsIntersect.py +54 -0
  70. biopipen/scripts/bed/BedtoolsMakeWindows.py +47 -0
  71. biopipen/scripts/bed/BedtoolsMerge.py +4 -4
  72. biopipen/scripts/cellranger/CellRangerCount.py +138 -0
  73. biopipen/scripts/cellranger/CellRangerSummary.R +181 -0
  74. biopipen/scripts/cellranger/CellRangerVdj.py +112 -0
  75. biopipen/scripts/cnv/AneuploidyScore.R +55 -20
  76. biopipen/scripts/cnv/AneuploidyScoreSummary.R +221 -163
  77. biopipen/scripts/cnv/TMADScore.R +25 -9
  78. biopipen/scripts/cnv/TMADScoreSummary.R +57 -86
  79. biopipen/scripts/cnvkit/CNVkitAccess.py +7 -6
  80. biopipen/scripts/cnvkit/CNVkitAutobin.py +26 -18
  81. biopipen/scripts/cnvkit/CNVkitBatch.py +6 -6
  82. biopipen/scripts/cnvkit/CNVkitCall.py +3 -3
  83. biopipen/scripts/cnvkit/CNVkitCoverage.py +4 -3
  84. biopipen/scripts/cnvkit/CNVkitDiagram.py +5 -5
  85. biopipen/scripts/cnvkit/CNVkitFix.py +3 -3
  86. biopipen/scripts/cnvkit/CNVkitGuessBaits.py +12 -8
  87. biopipen/scripts/cnvkit/CNVkitHeatmap.py +5 -5
  88. biopipen/scripts/cnvkit/CNVkitReference.py +6 -5
  89. biopipen/scripts/cnvkit/CNVkitScatter.py +5 -5
  90. biopipen/scripts/cnvkit/CNVkitSegment.py +5 -5
  91. biopipen/scripts/cnvkit/guess_baits.py +166 -93
  92. biopipen/scripts/delim/RowsBinder.R +1 -1
  93. biopipen/scripts/delim/SampleInfo.R +116 -118
  94. biopipen/scripts/gene/GeneNameConversion.R +67 -0
  95. biopipen/scripts/gene/GenePromoters.R +61 -0
  96. biopipen/scripts/gsea/Enrichr.R +5 -5
  97. biopipen/scripts/gsea/FGSEA.R +184 -50
  98. biopipen/scripts/gsea/GSEA.R +2 -2
  99. biopipen/scripts/gsea/PreRank.R +5 -5
  100. biopipen/scripts/misc/Config2File.py +2 -2
  101. biopipen/scripts/misc/Plot.R +80 -0
  102. biopipen/scripts/misc/Shell.sh +15 -0
  103. biopipen/scripts/misc/Str2File.py +2 -2
  104. biopipen/scripts/plot/Heatmap.R +3 -3
  105. biopipen/scripts/plot/Manhattan.R +147 -0
  106. biopipen/scripts/plot/QQPlot.R +146 -0
  107. biopipen/scripts/plot/ROC.R +88 -0
  108. biopipen/scripts/plot/Scatter.R +112 -0
  109. biopipen/scripts/plot/VennDiagram.R +5 -9
  110. biopipen/scripts/protein/MMCIF2PDB.py +33 -0
  111. biopipen/scripts/protein/PDB2Fasta.py +60 -0
  112. biopipen/scripts/protein/Prodigy.py +119 -0
  113. biopipen/scripts/protein/ProdigySummary.R +140 -0
  114. biopipen/scripts/protein/RMSD.py +178 -0
  115. biopipen/scripts/regulatory/MotifAffinityTest.R +102 -0
  116. biopipen/scripts/regulatory/MotifAffinityTest_AtSNP.R +127 -0
  117. biopipen/scripts/regulatory/MotifAffinityTest_MotifBreakR.R +104 -0
  118. biopipen/scripts/regulatory/MotifScan.py +159 -0
  119. biopipen/scripts/regulatory/VariantMotifPlot.R +78 -0
  120. biopipen/scripts/regulatory/motifs-common.R +324 -0
  121. biopipen/scripts/rnaseq/Simulation-ESCO.R +180 -0
  122. biopipen/scripts/rnaseq/Simulation-RUVcorr.R +45 -0
  123. biopipen/scripts/rnaseq/Simulation.R +21 -0
  124. biopipen/scripts/rnaseq/UnitConversion.R +325 -54
  125. biopipen/scripts/scrna/AnnData2Seurat.R +40 -0
  126. biopipen/scripts/scrna/CCPlotR-patch.R +161 -0
  127. biopipen/scripts/scrna/CellCellCommunication.py +150 -0
  128. biopipen/scripts/scrna/CellCellCommunicationPlots.R +93 -0
  129. biopipen/scripts/scrna/CellSNPLite.py +30 -0
  130. biopipen/scripts/scrna/CellTypeAnnotation-celltypist.R +185 -0
  131. biopipen/scripts/scrna/CellTypeAnnotation-direct.R +68 -31
  132. biopipen/scripts/scrna/CellTypeAnnotation-hitype.R +27 -22
  133. biopipen/scripts/scrna/CellTypeAnnotation-sccatch.R +28 -20
  134. biopipen/scripts/scrna/CellTypeAnnotation-sctype.R +48 -25
  135. biopipen/scripts/scrna/CellTypeAnnotation.R +37 -1
  136. biopipen/scripts/scrna/CellsDistribution.R +456 -167
  137. biopipen/scripts/scrna/DimPlots.R +1 -1
  138. biopipen/scripts/scrna/ExprImputation-alra.R +109 -0
  139. biopipen/scripts/scrna/ExprImputation-rmagic.R +256 -0
  140. biopipen/scripts/scrna/{ExprImpution-scimpute.R → ExprImputation-scimpute.R} +8 -5
  141. biopipen/scripts/scrna/ExprImputation.R +7 -0
  142. biopipen/scripts/scrna/LoomTo10X.R +51 -0
  143. biopipen/scripts/scrna/MQuad.py +25 -0
  144. biopipen/scripts/scrna/MarkersFinder.R +679 -400
  145. biopipen/scripts/scrna/MetaMarkers.R +265 -161
  146. biopipen/scripts/scrna/ModuleScoreCalculator.R +66 -11
  147. biopipen/scripts/scrna/PseudoBulkDEG.R +678 -0
  148. biopipen/scripts/scrna/RadarPlots.R +355 -134
  149. biopipen/scripts/scrna/ScFGSEA.R +298 -100
  150. biopipen/scripts/scrna/ScSimulation.R +65 -0
  151. biopipen/scripts/scrna/ScVelo.py +617 -0
  152. biopipen/scripts/scrna/Seurat2AnnData.R +7 -0
  153. biopipen/scripts/scrna/SeuratClusterStats-clustree.R +87 -0
  154. biopipen/scripts/scrna/SeuratClusterStats-dimplots.R +36 -30
  155. biopipen/scripts/scrna/SeuratClusterStats-features.R +138 -187
  156. biopipen/scripts/scrna/SeuratClusterStats-ngenes.R +81 -0
  157. biopipen/scripts/scrna/SeuratClusterStats-stats.R +78 -89
  158. biopipen/scripts/scrna/SeuratClusterStats.R +47 -10
  159. biopipen/scripts/scrna/SeuratClustering.R +36 -233
  160. biopipen/scripts/scrna/SeuratLoading.R +2 -2
  161. biopipen/scripts/scrna/SeuratMap2Ref.R +84 -113
  162. biopipen/scripts/scrna/SeuratMetadataMutater.R +16 -6
  163. biopipen/scripts/scrna/SeuratPreparing.R +223 -173
  164. biopipen/scripts/scrna/SeuratSubClustering.R +64 -0
  165. biopipen/scripts/scrna/SeuratTo10X.R +27 -0
  166. biopipen/scripts/scrna/Slingshot.R +65 -0
  167. biopipen/scripts/scrna/Subset10X.R +2 -2
  168. biopipen/scripts/scrna/TopExpressingGenes.R +169 -135
  169. biopipen/scripts/scrna/celltypist-wrapper.py +195 -0
  170. biopipen/scripts/scrna/scvelo_paga.py +313 -0
  171. biopipen/scripts/scrna/seurat_anndata_conversion.py +98 -0
  172. biopipen/scripts/scrna_metabolic_landscape/MetabolicFeatures.R +447 -82
  173. biopipen/scripts/scrna_metabolic_landscape/MetabolicPathwayActivity.R +348 -241
  174. biopipen/scripts/scrna_metabolic_landscape/MetabolicPathwayHeterogeneity.R +188 -166
  175. biopipen/scripts/snp/MatrixEQTL.R +217 -0
  176. biopipen/scripts/snp/Plink2GTMat.py +148 -0
  177. biopipen/scripts/snp/PlinkCallRate.R +199 -0
  178. biopipen/scripts/snp/PlinkFilter.py +100 -0
  179. biopipen/scripts/snp/PlinkFreq.R +291 -0
  180. biopipen/scripts/snp/PlinkFromVcf.py +81 -0
  181. biopipen/scripts/snp/PlinkHWE.R +85 -0
  182. biopipen/scripts/snp/PlinkHet.R +96 -0
  183. biopipen/scripts/snp/PlinkIBD.R +196 -0
  184. biopipen/scripts/snp/PlinkSimulation.py +124 -0
  185. biopipen/scripts/snp/PlinkUpdateName.py +124 -0
  186. biopipen/scripts/stats/ChowTest.R +146 -0
  187. biopipen/scripts/stats/DiffCoexpr.R +152 -0
  188. biopipen/scripts/stats/LiquidAssoc.R +135 -0
  189. biopipen/scripts/stats/Mediation.R +108 -0
  190. biopipen/scripts/stats/MetaPvalue.R +130 -0
  191. biopipen/scripts/stats/MetaPvalue1.R +74 -0
  192. biopipen/scripts/tcgamaf/Maf2Vcf.py +2 -2
  193. biopipen/scripts/tcgamaf/MafAddChr.py +2 -2
  194. biopipen/scripts/tcr/Attach2Seurat.R +3 -2
  195. biopipen/scripts/tcr/CDR3AAPhyschem.R +211 -143
  196. biopipen/scripts/tcr/CDR3Clustering.R +343 -0
  197. biopipen/scripts/tcr/ClonalStats.R +526 -0
  198. biopipen/scripts/tcr/CloneResidency.R +255 -131
  199. biopipen/scripts/tcr/CloneSizeQQPlot.R +4 -4
  200. biopipen/scripts/tcr/GIANA/GIANA.py +1356 -797
  201. biopipen/scripts/tcr/GIANA/GIANA4.py +1362 -789
  202. biopipen/scripts/tcr/GIANA/query.py +164 -162
  203. biopipen/scripts/tcr/Immunarch-basic.R +31 -9
  204. biopipen/scripts/tcr/Immunarch-clonality.R +25 -5
  205. biopipen/scripts/tcr/Immunarch-diversity.R +352 -134
  206. biopipen/scripts/tcr/Immunarch-geneusage.R +45 -5
  207. biopipen/scripts/tcr/Immunarch-kmer.R +68 -8
  208. biopipen/scripts/tcr/Immunarch-overlap.R +84 -4
  209. biopipen/scripts/tcr/Immunarch-spectratyping.R +35 -6
  210. biopipen/scripts/tcr/Immunarch-tracking.R +38 -6
  211. biopipen/scripts/tcr/Immunarch-vjjunc.R +165 -0
  212. biopipen/scripts/tcr/Immunarch.R +63 -11
  213. biopipen/scripts/tcr/Immunarch2VDJtools.R +2 -2
  214. biopipen/scripts/tcr/ImmunarchFilter.R +4 -4
  215. biopipen/scripts/tcr/ImmunarchLoading.R +38 -29
  216. biopipen/scripts/tcr/SampleDiversity.R +1 -1
  217. biopipen/scripts/tcr/ScRepCombiningExpression.R +40 -0
  218. biopipen/scripts/tcr/ScRepLoading.R +166 -0
  219. biopipen/scripts/tcr/TCRClusterStats.R +176 -22
  220. biopipen/scripts/tcr/TCRDock.py +110 -0
  221. biopipen/scripts/tcr/TESSA.R +102 -118
  222. biopipen/scripts/tcr/VJUsage.R +5 -5
  223. biopipen/scripts/tcr/immunarch-patched.R +142 -0
  224. biopipen/scripts/tcr/vdjtools-patch.sh +1 -1
  225. biopipen/scripts/vcf/BcftoolsAnnotate.py +91 -0
  226. biopipen/scripts/vcf/BcftoolsFilter.py +90 -0
  227. biopipen/scripts/vcf/BcftoolsMerge.py +31 -0
  228. biopipen/scripts/vcf/BcftoolsSort.py +113 -0
  229. biopipen/scripts/vcf/BcftoolsView.py +73 -0
  230. biopipen/scripts/vcf/TruvariBench.sh +14 -7
  231. biopipen/scripts/vcf/TruvariBenchSummary.R +16 -13
  232. biopipen/scripts/vcf/TruvariConsistency.R +1 -1
  233. biopipen/scripts/vcf/Vcf2Bed.py +2 -2
  234. biopipen/scripts/vcf/VcfAnno.py +11 -11
  235. biopipen/scripts/vcf/VcfDownSample.sh +22 -10
  236. biopipen/scripts/vcf/VcfFilter.py +5 -5
  237. biopipen/scripts/vcf/VcfFix.py +7 -7
  238. biopipen/scripts/vcf/VcfFix_utils.py +13 -4
  239. biopipen/scripts/vcf/VcfIndex.py +3 -3
  240. biopipen/scripts/vcf/VcfIntersect.py +3 -3
  241. biopipen/scripts/vcf/VcfLiftOver.sh +5 -0
  242. biopipen/scripts/vcf/VcfSplitSamples.py +4 -4
  243. biopipen/scripts/vcf/bcftools_utils.py +52 -0
  244. biopipen/scripts/web/Download.py +8 -4
  245. biopipen/scripts/web/DownloadList.py +5 -5
  246. biopipen/scripts/web/GCloudStorageDownloadBucket.py +82 -0
  247. biopipen/scripts/web/GCloudStorageDownloadFile.py +23 -0
  248. biopipen/scripts/web/gcloud_common.py +49 -0
  249. biopipen/utils/gene.py +108 -60
  250. biopipen/utils/misc.py +146 -20
  251. biopipen/utils/reference.py +64 -20
  252. biopipen/utils/reporter.py +177 -0
  253. biopipen/utils/vcf.py +1 -1
  254. biopipen-0.34.26.dist-info/METADATA +27 -0
  255. biopipen-0.34.26.dist-info/RECORD +292 -0
  256. {biopipen-0.21.0.dist-info → biopipen-0.34.26.dist-info}/WHEEL +1 -1
  257. {biopipen-0.21.0.dist-info → biopipen-0.34.26.dist-info}/entry_points.txt +6 -2
  258. biopipen/ns/bcftools.py +0 -111
  259. biopipen/ns/scrna_basic.py +0 -255
  260. biopipen/reports/delim/SampleInfo.svelte +0 -36
  261. biopipen/reports/scrna/GeneExpressionInvistigation.svelte +0 -32
  262. biopipen/reports/scrna/ScFGSEA.svelte +0 -35
  263. biopipen/reports/scrna/SeuratClusterStats.svelte +0 -82
  264. biopipen/reports/scrna/SeuratMap2Ref.svelte +0 -20
  265. biopipen/reports/scrna/SeuratPreparing.svelte +0 -38
  266. biopipen/reports/scrna/TopExpressingGenes.svelte +0 -55
  267. biopipen/reports/scrna_metabolic_landscape/MetabolicFeaturesIntraSubset.svelte +0 -31
  268. biopipen/reports/utils/gsea.liq +0 -110
  269. biopipen/scripts/bcftools/BcftoolsAnnotate.py +0 -42
  270. biopipen/scripts/bcftools/BcftoolsFilter.py +0 -79
  271. biopipen/scripts/bcftools/BcftoolsSort.py +0 -19
  272. biopipen/scripts/gene/GeneNameConversion.py +0 -66
  273. biopipen/scripts/scrna/ExprImpution-alra.R +0 -32
  274. biopipen/scripts/scrna/ExprImpution-rmagic.R +0 -29
  275. biopipen/scripts/scrna/ExprImpution.R +0 -7
  276. biopipen/scripts/scrna/GeneExpressionInvistigation.R +0 -132
  277. biopipen/scripts/scrna/Write10X.R +0 -11
  278. biopipen/scripts/scrna_metabolic_landscape/MetabolicFeaturesIntraSubset.R +0 -150
  279. biopipen/scripts/tcr/TCRClustering.R +0 -280
  280. biopipen/utils/common_docstrs.py +0 -61
  281. biopipen/utils/gene.R +0 -49
  282. biopipen/utils/gsea.R +0 -193
  283. biopipen/utils/io.R +0 -20
  284. biopipen/utils/misc.R +0 -114
  285. biopipen/utils/mutate_helpers.R +0 -433
  286. biopipen/utils/plot.R +0 -173
  287. biopipen/utils/rnaseq.R +0 -48
  288. biopipen/utils/single_cell.R +0 -115
  289. biopipen-0.21.0.dist-info/METADATA +0 -22
  290. biopipen-0.21.0.dist-info/RECORD +0 -218
@@ -1,52 +1,57 @@
1
- source("{{biopipen_dir}}/utils/misc.R")
2
- source("{{biopipen_dir}}/utils/plot.R")
3
-
4
- library(scater)
5
- library(reshape2)
6
- library(RColorBrewer)
1
+ library(rlang)
7
2
  library(parallel)
8
- library(ggprism)
3
+ library(matrixStats)
4
+ library(enrichit)
9
5
  library(Seurat)
10
- library(ComplexHeatmap)
6
+ library(biopipen.utils)
7
+ library(plotthis)
8
+ library(tidyseurat)
11
9
 
12
10
  sobjfile <- {{ in.sobjfile | r }}
13
11
  outdir <- {{ out.outdir | r }}
14
- gmtfile <- {{ envs.gmtfile | r }}
15
12
  ntimes <- {{ envs.ntimes | r }}
16
13
  ncores <- {{ envs.ncores | r }}
17
- heatmap_devpars <- {{ envs.heatmap_devpars | r }}
18
- violin_devpars <- {{ envs.violin_devpars | r }}
19
- grouping <- {{ envs.grouping | r }}
20
- grouping_prefix <- {{ envs.grouping_prefix | r }}
21
- subsetting_cols <- {{ envs.subsetting | r }}
22
- subsetting_prefix <- {{ envs.subsetting_prefix | r }}
23
-
24
- if (!is.null(grouping_prefix) && nchar(grouping_prefix) > 0) {
25
- grouping_prefix = paste0(grouping_prefix, "_")
26
- }
27
-
28
- if (!is.null(subsetting_prefix) && nchar(subsetting_prefix) > 0) {
29
- subsetting_prefix = paste0(subsetting_prefix, "_")
30
- }
14
+ gmtfile <- {{ envs.gmtfile | r }}
15
+ subset_by <- {{ envs.subset_by | r }}
16
+ group_by <- {{ envs.group_by | r }}
17
+ plots <- {{ envs.plots | r }}
18
+ cases <- {{ envs.cases | r }}
31
19
 
32
20
  set.seed(8525)
33
21
 
34
- ## gmt_pathways is copied from fgsea package.
35
- gmt_pathways <- function(gmt_file) {
36
- pathway_lines <- strsplit(readLines(gmt_file), "\t")
37
- pathways <- lapply(pathway_lines, tail, -2)
38
- names(pathways) <- sapply(pathway_lines, head, 1)
39
- pathways
40
- }
22
+ log <- get_logger()
23
+ reporter <- get_reporter()
24
+
25
+ log$info("Loading Seurat object ...")
26
+ sobj <- read_obj(sobjfile)
27
+ assay <- DefaultAssay(sobj)
28
+
29
+ defaults <- list(
30
+ ntimes = ntimes,
31
+ subset_by = subset_by,
32
+ group_by = group_by,
33
+ plots = plots
34
+ )
35
+ log$info("Expanding cases ...")
36
+ default_case <- subset_by %||% "DEFAULT"
37
+ cases <- expand_cases(
38
+ cases,
39
+ defaults,
40
+ function(name, case) {
41
+ if (is.null(case$group_by)) {
42
+ stop("'group_by' is required in case: ", name)
43
+ }
44
+ stats::setNames(list(case), name)
45
+ },
46
+ default_case = default_case)
41
47
 
42
- pathways <- gmt_pathways(gmtfile)
48
+ log$info("Loading metabolic pathways ...")
49
+ pathways <- ParseGMT(gmtfile)
43
50
  pathway_names <- names(pathways)
44
51
  metabolics <- unique(as.vector(unname(unlist(pathways))))
45
- sobj <- readRDS(sobjfile)
46
- DefaultAssay(sobj) <- "RNA"
47
52
 
48
53
  ## calculate how many pathways of one gene involved.
49
- num_of_pathways <- function(gmtfile, overlapgenes) {
54
+ num_of_pathways <- function(overlapgenes) {
50
55
  filter_pathways <- list()
51
56
  for (p in pathway_names) {
52
57
  genes <- pathways[[p]]
@@ -69,79 +74,94 @@ num_of_pathways <- function(gmtfile, overlapgenes) {
69
74
  gene_times
70
75
  }
71
76
 
72
- do_one_subset <- function(s, subset_col, subset_prefix) {
73
- print(paste0(" Processing subset: ", s, "..."))
74
- if (is.null(s)) {
75
- subset_dir <- file.path(outdir, "ALL")
76
- dir.create(subset_dir, showWarnings = FALSE)
77
- subset_obj <- sobj
78
- } else {
79
- subset_dir <- file.path(outdir, paste0(subset_prefix, s))
80
- dir.create(subset_dir, showWarnings = FALSE)
81
-
82
- subset_code = paste0(
83
- "subset(sobj, subset = ", subset_col, " == '", s, "')"
77
+ do_subset <- function(
78
+ object,
79
+ caseinfo,
80
+ subset_by,
81
+ subset_val,
82
+ ntimes,
83
+ group_by,
84
+ plots
85
+ ) {
86
+ if (!is.null(subset_val)) {
87
+ log$info("- Handling subset: {subset_by} = {subset_val} ...")
88
+ object <- tryCatch(
89
+ filter(object, !!sym(subset_by) == subset_val & !is.na(!!sym(group_by))),
90
+ error = function(e) NULL
84
91
  )
85
- subset_obj = eval(parse(text = subset_code))
92
+
93
+ if (is.null(object) || ncol(object) < 5) {
94
+ msg <- paste0(" ! skipped. Subset has less than 5 cells: ", subset_by, " = ", subset_val)
95
+ log$warn(msg)
96
+ reporter$add(list(kind = "error", content = msg), h1 = caseinfo$name)
97
+ return(NULL)
98
+ }
86
99
  }
87
100
 
88
- all_cell_types <- subset_obj@meta.data[[grouping]]
89
- cell_types <- unique(all_cell_types)
101
+ all_groups <- object@meta.data[[group_by]]
102
+ if (!is.factor(all_groups)) {
103
+ all_groups <- factor(all_groups)
104
+ }
105
+ # order by levels(all_groups)
106
+ groups <- intersect(levels(all_groups), unique(all_groups))
90
107
 
91
- gene_pathway_number <- num_of_pathways(
92
- gmtfile,
93
- intersect(rownames(subset_obj), metabolics)
94
- )
108
+ gene_pathway_number <- num_of_pathways(intersect(rownames(object), metabolics))
95
109
 
96
110
  ## Calculate the pathway activities
97
111
  # mean ratio of genes in each pathway for each cell type
98
112
  mean_expression_shuffle <- matrix(
99
113
  NA,
100
114
  nrow = length(pathway_names),
101
- ncol = length(cell_types),
102
- dimnames = list(pathway_names, cell_types)
115
+ ncol = length(groups),
116
+ dimnames = list(pathway_names, groups)
103
117
  )
104
118
  mean_expression_noshuffle <- matrix(
105
119
  NA,
106
120
  nrow = length(pathway_names),
107
- ncol = length(cell_types),
108
- dimnames = list(pathway_names, cell_types)
121
+ ncol = length(groups),
122
+ dimnames = list(pathway_names, groups)
109
123
  )
110
124
  ### calculate the pvalues using shuffle method
111
125
  pvalues_mat <- matrix(
112
126
  NA,
113
127
  nrow = length(pathway_names),
114
- ncol = length(cell_types),
115
- dimnames = (list(pathway_names, cell_types))
128
+ ncol = length(groups),
129
+ dimnames = (list(pathway_names, groups))
116
130
  )
117
131
 
118
132
  for (pi in seq_along(pathway_names)) {
119
133
  p <- pathway_names[pi]
120
- print(paste0(" * Pathway (", pi, "): ", p, "..."))
134
+ log$info(" Pathway ({pi}/{length(pathway_names)}): {p} ...")
121
135
  genes <- pathways[[p]]
122
- genes_comm <- intersect(genes, rownames(subset_obj))
123
- genes_expressed <- names(rowSums(subset_obj)[rowSums(subset_obj) > 0])
124
- genes_comm <- intersect(genes_comm, genes_expressed)
136
+ genes_comm <- intersect(genes, rownames(object))
137
+ # genes_expressed <- names(rowSums(object)[rowSums(object) > 0])
138
+ # genes_comm <- intersect(genes_comm, genes_expressed)
125
139
  if (length(genes_comm) < 5) next
126
140
 
127
- pathway_metabolic_obj <- subset(subset_obj, features = genes_comm)
128
- mean_exp_eachCellType <- AverageExpression(pathway_metabolic_obj)$RNA
141
+ # Errored if default assay is SCT
142
+ # Issue with Seurat?
143
+ # pathway_metabolic_obj <- subset(object, features = genes_comm)
144
+ # assay <- DefaultAssay(object)
145
+ ## AggregateExpression raises Warning: The counts layer for the integrated assay is empty. Skipping assay.
146
+ mean_exp_eachCellType <- suppressMessages(AverageExpression(object, features = genes_comm, assays = assay, group.by = group_by))[[assay]]
129
147
 
130
148
  # remove genes which are zeros in any celltype to avoid extreme ratio value
131
- keep <- rownames(mean_exp_eachCellType)[rowAlls(mean_exp_eachCellType > 0.001)]
149
+ keep <- rownames(mean_exp_eachCellType)[rowAlls(as.matrix(mean_exp_eachCellType) > 0.001, useNames = F)]
132
150
  if (length(keep) < 3) next
133
151
 
134
152
  # using the loweset value to replace zeros for avoiding extreme ratio value
135
- pathway_metabolic_obj <- subset(pathway_metabolic_obj, features = keep)
136
- assay_data = GetAssayData(pathway_metabolic_obj)
153
+ # pathway_metabolic_obj <- subset(object, features = keep)
154
+ assay_data = GetAssayData(object, assay = assay, layer = "data")[keep, , drop = F]
137
155
  assay_data <- t(apply(assay_data, 1, function(x) {
138
156
  x[x <= 0] <- min(x[x > 0])
139
157
  x
140
158
  }))
141
- pathway_metabolic_obj <- SetAssayData(pathway_metabolic_obj, new.data = assay_data)
159
+ pathway_metabolic_obj <- suppressWarnings(CreateSeuratObject(CreateAssayObject(data = assay_data), assay = assay))
160
+ pathway_metabolic_obj[[group_by]] <- object[[group_by]]
161
+ Idents(pathway_metabolic_obj) <- Idents(object)
142
162
  pathway_number_weight <- 1 / gene_pathway_number[keep, ]
143
163
  #
144
- mean_exp_eachCellType <- t(AverageExpression(pathway_metabolic_obj)$RNA)
164
+ mean_exp_eachCellType <- t(suppressMessages(AverageExpression(pathway_metabolic_obj, assays = assay, group.by = group_by)[[assay]]))
145
165
  ratio_exp_eachCellType <- t(mean_exp_eachCellType) / colMeans(mean_exp_eachCellType)
146
166
  # exclude the extreme ratios
147
167
  col_quantile <- apply(ratio_exp_eachCellType, 2, function(x) quantile(x, na.rm = T))
@@ -156,21 +176,21 @@ do_one_subset <- function(s, subset_col, subset_prefix) {
156
176
  if (sum(!outliers) < 3) next
157
177
 
158
178
  keep <- names(outliers)[!outliers]
159
- pathway_metabolic_obj <- subset(pathway_metabolic_obj, features = keep)
179
+ pathway_metabolic_obj <- suppressWarnings(subset(pathway_metabolic_obj, features = keep))
160
180
  pathway_number_weight <- 1 / gene_pathway_number[keep, ]
161
- mean_exp_eachCellType <- t(AverageExpression(pathway_metabolic_obj)$RNA)
181
+ mean_exp_eachCellType <- t(suppressMessages(AverageExpression(pathway_metabolic_obj, assays = assay, group.by = group_by)[[assay]]))
162
182
  ratio_exp_eachCellType <- t(mean_exp_eachCellType) / colMeans(mean_exp_eachCellType)
163
183
  mean_exp_pathway <- apply(ratio_exp_eachCellType, 2, function(x) weighted.mean(x, pathway_number_weight / sum(pathway_number_weight)))
164
- mean_expression_shuffle[p, ] <- mean_exp_pathway[cell_types]
165
- mean_expression_noshuffle[p, ] <- mean_exp_pathway[cell_types]
184
+ mean_expression_shuffle[p, ] <- mean_exp_pathway[groups]
185
+ mean_expression_noshuffle[p, ] <- mean_exp_pathway[groups]
166
186
  pathway_metabolic_data <- GetAssayData(pathway_metabolic_obj)
167
187
 
168
188
  ## shuffle 5000 times:
169
189
  ## define the functions
170
190
  group_mean <- function(x) {
171
191
  sapply(
172
- cell_types,
173
- function(y) rowMeans(pathway_metabolic_data[, shuffle_cell_types_list[[x]] == y, drop = F])
192
+ groups,
193
+ function(y) rowMeans(pathway_metabolic_data[, shuffle_groups_list[[x]] == y, drop = F])
174
194
  )
175
195
  }
176
196
  column_weigth_mean <- function(x) {
@@ -179,9 +199,9 @@ do_one_subset <- function(s, subset_col, subset_prefix) {
179
199
  #####
180
200
  times <- 1:ntimes
181
201
  weight_values <- pathway_number_weight / sum(pathway_number_weight)
182
- shuffle_cell_types_list <- mclapply(times, function(x) sample(all_cell_types), mc.cores = ncores)
183
- # shuffle_cell_types_list <- lapply(times, function(x) sample(all_cell_types))
184
- names(shuffle_cell_types_list) <- times
202
+ shuffle_groups_list <- mclapply(times, function(x) sample(all_groups), mc.cores = ncores)
203
+ # shuffle_groups_list <- lapply(times, function(x) sample(all_groups))
204
+ names(shuffle_groups_list) <- times
185
205
  mean_exp_eachCellType_list <- mclapply(times, function(x) group_mean(x), mc.cores = ncores)
186
206
  # mean_exp_eachCellType_list <- lapply(times, function(x) group_mean(x))
187
207
  ratio_exp_eachCellType_list <- mclapply(times, function(x) mean_exp_eachCellType_list[[x]] / rowMeans(mean_exp_eachCellType_list[[x]]), mc.cores = ncores)
@@ -189,10 +209,10 @@ do_one_subset <- function(s, subset_col, subset_prefix) {
189
209
  mean_exp_pathway_list <- mclapply(times, function(x) column_weigth_mean(x), mc.cores = ncores)
190
210
  # mean_exp_pathway_list <- lapply(times, function(x) column_weigth_mean(x))
191
211
 
192
- shuffle_results <- matrix(unlist(mean_exp_pathway_list), ncol = length(cell_types), byrow = T)
212
+ shuffle_results <- matrix(unlist(mean_exp_pathway_list), ncol = length(groups), byrow = T)
193
213
  rownames(shuffle_results) <- times
194
- colnames(shuffle_results) <- cell_types
195
- for (c in cell_types) {
214
+ colnames(shuffle_results) <- groups
215
+ for (c in groups) {
196
216
  if (is.na(mean_expression_shuffle[p, c])) next
197
217
  if (mean_expression_shuffle[p, c] > 1) {
198
218
  pval <- sum(shuffle_results[, c] > mean_expression_shuffle[p, c]) / ntimes
@@ -203,8 +223,15 @@ do_one_subset <- function(s, subset_col, subset_prefix) {
203
223
  pvalues_mat[p, c] <- pval
204
224
  }
205
225
  }
206
- all_NA <- rowAlls(is.na(mean_expression_shuffle))
207
- mean_expression_shuffle <- mean_expression_shuffle[!all_NA, , drop = F]
226
+ all_NA <- rowAlls(is.na(as.matrix(mean_expression_shuffle)), useNames = F)
227
+ if (all(all_NA)) {
228
+ log$warn(" ! All pathways are NA after shuffling.")
229
+ # keep at least 3 pathways for plotting
230
+ mean_expression_shuffle <- mean_expression_shuffle[1:3, , drop = F]
231
+ mean_expression_shuffle[is.na(mean_expression_shuffle)] <- 1
232
+ } else {
233
+ mean_expression_shuffle <- mean_expression_shuffle[!all_NA, , drop = F]
234
+ }
208
235
  # heatmap
209
236
  dat <- mean_expression_shuffle
210
237
 
@@ -212,180 +239,260 @@ do_one_subset <- function(s, subset_col, subset_prefix) {
212
239
  sort_column <- c()
213
240
 
214
241
  for (i in colnames(dat)) {
215
- select_row <- which(rowMaxs(dat, na.rm = T) == dat[, i])
216
- tmp <- rownames(dat)[select_row][order(dat[select_row, i], decreasing = T)]
217
- sort_row <- c(sort_row, tmp)
242
+ select_row <- which(rowMaxs(dat, na.rm = TRUE, useNames = FALSE) == dat[, i])
243
+ tmp <- rownames(dat)[select_row][order(dat[select_row, i], decreasing = TRUE)]
244
+ sort_row <- unique(c(sort_row, tmp))
218
245
  }
219
- sort_column <- apply(dat[sort_row, , drop = F], 2, function(x) order(x)[nrow(dat)])
246
+ sort_column <- apply(dat[sort_row, , drop = FALSE], 2, function(x) order(x)[nrow(dat)])
220
247
  sort_column <- names(sort_column)
221
248
  dat[is.na(dat)] <- 1
222
-
223
- heatmapfile <- file.path(subset_dir, "KEGGpathway_activity_heatmap.png")
224
- hmdata <- dat[sort_row, sort_column, drop = F]
225
- cnames <- sapply(colnames(hmdata), function(x) {paste0(grouping_prefix, x)})
226
- colnames(hmdata) <- cnames
227
- hmdata = hmdata[, sort(cnames), drop=FALSE]
228
- hm_devpars = heatmap_devpars
229
- if (is.null(hm_devpars$res)) {
230
- hm_devpars$res = 100
231
- }
232
- if (is.null(hm_devpars$width)) {
233
- hm_devpars$width = 300 + max(nchar(rownames(hmdata))) * 8 + ncol(hmdata) * 15
234
- }
235
- if (is.null(hm_devpars$height)) {
236
- hm_devpars$height = 400 + max(nchar(colnames(hmdata))) * 8 + nrow(hmdata) * 20
249
+ dat <- dat[sort_row, sort_column, drop = FALSE]
250
+
251
+ if (!is.null(subset_by)) {
252
+ prefix <- file.path(caseinfo$prefix, paste0(slugify(subset_by), "_", slugify(subset_val), "."))
253
+ h2 <- paste0(subset_by, ": ", subset_val)
254
+ } else if (length(cases) > 1) {
255
+ prefix <- paste0(caseinfo$prefix, "/No_Subsetting/")
256
+ dir.create(prefix, showWarnings = FALSE, recursive = TRUE)
257
+ h2 <- "No Subsetting"
258
+ } else {
259
+ prefix <- paste0(caseinfo$prefix, "/")
260
+ h2 <- "#"
237
261
  }
238
- plotHeatmap(
239
- hmdata,
240
- args = list(
241
- name = "Pathway activity",
242
- rect_gp = gpar(col = "white", lwd = 0.5),
243
- row_names_side = "left",
244
- row_dend_side = "right",
245
- row_names_max_width = max_text_width(
246
- rownames(hmdata),
247
- gp = gpar(fontsize = 12)
248
- ),
249
- row_dend_width = unit(30, "mm"),
250
- cluster_columns = FALSE
251
- ),
252
- devpars = hm_devpars,
253
- outfile = heatmapfile
262
+
263
+ write.table(
264
+ mean_expression_noshuffle,
265
+ file = paste0(prefix, "pathway_activity_noshuffle.txt"),
266
+ row.names = TRUE,
267
+ col.names = TRUE,
268
+ quote = FALSE,
269
+ sep = "\t"
270
+ )
271
+ write.table(
272
+ mean_expression_shuffle,
273
+ file = paste0(prefix, "pathway_activity_shuffle.txt"),
274
+ row.names = TRUE,
275
+ col.names = TRUE,
276
+ quote = FALSE,
277
+ sep = "\t"
278
+ )
279
+ write.table(pvalues_mat,
280
+ file = paste0(prefix, "pathway_activity_shuffle_pvalue.txt"),
281
+ row.names = TRUE,
282
+ col.names = TRUE,
283
+ quote = FALSE,
284
+ sep = "\t"
254
285
  )
255
286
 
287
+ for (plotname in names(plots)) {
288
+ plotargs <- plots[[plotname]]
289
+ plotargs$devpars <- plotargs$devpars %||% list()
290
+ plotargs <- extract_vars(plotargs, "devpars", "plot_type")
291
+ devpars <- devpars %||% list()
292
+ devpars$res <- devpars$res %||% 100
293
+ if (plot_type == "merged_heatmap") { next }
294
+ log$info(" Plotting: {plotname} ...")
295
+ if (plot_type %in% c("violin", "box", "boxplot")) {
296
+ plotfn <- if (plot_type == "violin") plotthis::ViolinPlot else plotthis::BoxPlot
297
+ # boxplot show the distribution of pathway activity
298
+ scRNA_dat <- as.data.frame(mean_expression_noshuffle)
299
+ scRNA_dat$X <- NULL
300
+
301
+ # scRNA_df <- reshape2::melt(as.matrix(scRNA_dat))
302
+ # scRNA_df <- scRNA_df[!is.na(scRNA_df$value), ]
303
+ # colnames(scRNA_df)[ncol(scRNA_df) - 1] <- "variable"
304
+ scRNA_dat$Pathways <- rownames(scRNA_dat)
305
+ scRNA_dat <- tidyr::pivot_longer(
306
+ scRNA_dat,
307
+ cols = -c(Pathways),
308
+ names_to = group_by,
309
+ values_to = "Pathway Activity"
310
+ )
256
311
 
257
- write.table(mean_expression_noshuffle, file = file.path(subset_dir, "KEGGpathway_activity_noshuffle.txt"), row.names = T, col.names = T, quote = F, sep = "\t")
258
- write.table(mean_expression_shuffle, file = file.path(subset_dir, "KEGGpathway_activity_shuffle.txt"), row.names = T, col.names = T, quote = F, sep = "\t")
259
- write.table(pvalues_mat, file = file.path(subset_dir, "KEGGpathway_activity_shuffle_pvalue.txt"), row.names = T, col.names = T, quote = F, sep = "\t")
312
+ plotargs$data <- scRNA_dat
313
+ plotargs$x <- group_by
314
+ plotargs$y <- "Pathway Activity"
315
+ plotargs$keep_empty <- TRUE
316
+
317
+ p <- do_call(plotfn, plotargs)
318
+ devpars$width <- devpars$width %||% (attr(p, "width") * 2 * devpars$res) %||% 1000
319
+ devpars$height <- devpars$height %||% (attr(p, "height") * 2 * devpars$res) %||% 1000
320
+ } else { # heatmap
321
+ minval <- min(dat)
322
+ maxval <- max(dat)
323
+ dis <- max(1 - minval, maxval - 1)
324
+ minval <- 1 - dis
325
+ maxval <- 1 + dis
326
+ dat <- as.data.frame(t(dat)) # rows: groups, columns: pathways
327
+ dat[[group_by]] <- rownames(dat)
328
+ plotargs$data <- dat
329
+ plotargs$columns_by <- group_by
330
+ plotargs$in_form <- "wide-rows"
331
+ plotargs$name <- plotargs$name %||% "Pathway Activity"
332
+ plotargs$rows_name <- plotargs$rows_name %||% "Pathways"
333
+ plotargs$show_row_names <- plotargs$show_row_names %||% TRUE
334
+ plotargs$lower_cutoff <- plotargs$lower_cutoff %||% minval
335
+ plotargs$upper_cutoff <- plotargs$upper_cutoff %||% maxval
336
+ plotargs$row_name_annotation <- plotargs$row_name_annotation %||% FALSE
337
+ plotargs$row_names_side <- plotargs$row_names_side %||% "left"
338
+ plotargs$show_column_names <- plotargs$show_column_names %||% TRUE
339
+
340
+ p <- do_call(plotthis::Heatmap, plotargs)
341
+ devpars$width <- devpars$width %||% (attr(p, "width") * devpars$res) %||% 1000
342
+ devpars$height <- devpars$height %||% (attr(p, "height") * devpars$res) %||% 1000
343
+ }
260
344
 
261
- # boxplot show the distribution of pathway activity
262
- scRNA_dat <- as.data.frame(mean_expression_noshuffle)
263
- scRNA_dat$X <- NULL
345
+ plotprefix <- paste0(prefix, slugify(plotname))
346
+ png(paste0(plotprefix, ".png"), res = devpars$res, width = devpars$width, height = devpars$height)
347
+ print(p)
348
+ dev.off()
264
349
 
265
- scRNA_df <- melt(as.matrix(scRNA_dat))
266
- scRNA_df <- scRNA_df[!is.na(scRNA_df$value), ]
267
- colnames(scRNA_df)[ncol(scRNA_df) - 1] <- "variable"
268
- scRNA_df$variable <- sapply(scRNA_df$variable, function(x) {paste0(grouping_prefix, x)})
269
- violinfile <- file.path(subset_dir, "pathway_activity_violinplot.png")
270
- vio_devpars = violin_devpars
271
- if (is.null(vio_devpars$res)) {
272
- vio_devpars$res = 100
273
- }
274
- if (is.null(vio_devpars$width)) {
275
- vio_devpars$width = 100 + ncol(scRNA_df) * 100
276
- }
277
- if (is.null(hm_devpars$height)) {
278
- vio_devpars$height = 1000
350
+ descr <- plotargs$descr %||% paste0(
351
+ plotname, " a ", plotargs$plot_type, " plot of pathway activity for ", group_by, ". "
352
+ )
353
+
354
+ reporter$add(
355
+ list(name = plotname, contents = list(
356
+ list(kind = "descr", content = descr),
357
+ reporter$image(plotprefix, c(), FALSE))
358
+ ),
359
+ h1 = caseinfo$name,
360
+ h2 = h2,
361
+ ui = "tabs"
362
+ )
279
363
  }
280
- plotViolin(
281
- scRNA_df,
282
- args = list(
283
- mapping = aes(x = variable, y = value, fill = variable),
284
- trim = F,
285
- size = 0.2,
286
- show.legend = F,
287
- width = 1.2
288
- ),
289
- ggs = c(
290
- "scale_y_continuous(limits = c(0, 3), breaks = 0:3, labels = 0:3)",
291
- 'labs(y = "Metabolic Pathway Activity", x=NULL)',
292
- 'stat_summary(
293
- aes(x = variable, y = value),
294
- fun = median,
295
- geom = "point",
296
- size = 1,
297
- color = "black"
298
- )',
299
- "theme_prism(axis_text_angle = 90)"
300
- ),
301
- devpars = vio_devpars,
302
- outfile = violinfile
303
- )
304
364
 
305
- list(hmdata=as.data.frame(hmdata), hm_devpars=hm_devpars)
365
+ return(dat)
306
366
  }
307
367
 
308
- do_one_subset_col <- function(subset_col, subset_prefix) {
309
- print(paste0("- Handling subset column: ", subset_col, " ..."))
310
- if (is.null(subset_col)) {
311
- do_one_subset(NULL, subset_col = NULL, subset_prefix = NULL)
368
+
369
+ do_case <- function(casename) {
370
+ log$info("Processing case: {casename} ...")
371
+ case <- cases[[casename]]
372
+ if (is.null(case) || length(case) == 0) {
373
+ log$warn(" Case skipped.")
374
+ return(NULL)
375
+ }
376
+ caseinfo <- case_info(casename, outdir, create = TRUE)
377
+
378
+ if (is.null(case$subset_by)) {
379
+ result <- do_subset(
380
+ sobj,
381
+ caseinfo = caseinfo,
382
+ subset_by = NULL,
383
+ subset_val = NULL,
384
+ ntimes = case$ntimes,
385
+ group_by = case$group_by,
386
+ plots = case$plots
387
+ )
312
388
  } else {
313
- subsets <- na.omit(unique(sobj@meta.data[[subset_col]]))
314
-
315
- # if (ncores == 1) {
316
- x = lapply(subsets, do_one_subset, subset_col = subset_col, subset_prefix = subset_prefix)
317
- # } else {
318
- # x <- mclapply(subsets, do_one_subset, subset_col = subset_col, subset_prefix = subset_prefix, mc.cores = ncores)
319
- # if (any(unlist(lapply(x, class)) == "try-error")) {
320
- # stop("mclapply error")
321
- # }
322
- # }
323
- # x is a list of hmdata
324
- # merge all hmdata
325
- if (length(x) > 1) {
326
- pws = c()
327
- for (i in 1:length(x)) {
328
- pws <- unique(c(pws, rownames(x[[i]]$hmdata)))
329
- }
330
- for (i in 1:length(x)) {
331
- x[[i]]$hmdata[setdiff(pws, rownames(x[[i]]$hmdata)), ] <- NA
332
- colnames(x[[i]]$hmdata) <- paste0(subsets[i], "_", colnames(x[[i]]$hmdata))
333
- }
334
- hm_devpars = x[[1]]$hm_devpars
335
- hm_devpars$height = hm_devpars$height * length(pws) / nrow(x[[1]]$hmdata)
336
- hmdata <- x[[1]]$hmdata[pws, ]
337
- for (i in 2:length(x)) {
338
- hmdata <- cbind(hmdata, x[[i]]$hmdata[pws, ])
339
- if (hm_devpars$res != x[[i]]$hm_devpars$res) {
340
- stop("hm_devpars$res not equal for group heatmaps")
341
- }
342
- hm_devpars$width = sum(hm_devpars$width, x[[i]]$hm_devpars$width / 2)
343
- hm_devpars$height = max(hm_devpars$height, x[[i]]$hm_devpars$height * length(pws) / nrow(x[[i]]$hmdata))
344
- }
345
- # In case of NA values
346
- hmdata[is.na(hmdata)] = 0
347
- # Plot heatmap of the merged hmdata
348
- subset_heatmap_file <- file.path(outdir, paste0(subset_col, ".group-unclustered.png"))
349
- plotHeatmap(
350
- hmdata,
351
- args = list(
352
- name = "Pathway activity",
353
- rect_gp = gpar(col = "white", lwd = 0.5),
354
- row_names_side = "left",
355
- row_dend_side = "right",
356
- row_names_max_width = max_text_width(pws, gp = gpar(fontsize = 12)),
357
- row_dend_reorder = TRUE,
358
- row_dend_width = unit(30, "mm"),
359
- column_split = do_call(c, lapply(1:length(subsets), function(i) {rep(subsets[i], ncol(x[[i]]$hmdata))})),
360
- cluster_columns = FALSE
361
- ),
362
- devpars = hm_devpars,
363
- outfile = subset_heatmap_file
364
- )
365
- subset_heatmap_file <- file.path(outdir, paste0(subset_col, ".group-clustered.png"))
366
- plotHeatmap(
367
- hmdata,
368
- args = list(
369
- name = "Pathway activity",
370
- rect_gp = gpar(col = "white", lwd = 0.5),
371
- row_names_side = "left",
372
- row_dend_side = "right",
373
- row_names_max_width = max_text_width(pws, gp = gpar(fontsize = 12)),
374
- row_dend_reorder = TRUE,
375
- row_dend_width = unit(30, "mm"),
376
- cluster_columns = TRUE
377
- ),
378
- devpars = hm_devpars,
379
- outfile = subset_heatmap_file
389
+ sobj_avail <- filter(sobj, !is.na(!!sym(case$subset_by)))
390
+ if (ncol(sobj_avail) < 5) {
391
+ stop("Not enough cells (< 5) for subset: ", case$subset_by)
392
+ }
393
+
394
+ subsets <- unique(sobj@meta.data[[case$subset_by]])
395
+ result <- NULL
396
+ for (ss in subsets) {
397
+ tmp <- do_subset(
398
+ sobj_avail,
399
+ caseinfo = caseinfo,
400
+ subset_by = case$subset_by,
401
+ subset_val = ss,
402
+ ntimes = case$ntimes,
403
+ group_by = case$group_by,
404
+ plots = case$plots
380
405
  )
406
+ if (is.null(tmp)) { next }
407
+ tmp[[case$group_by]] <- rownames(tmp)
408
+ tmp[[case$subset_by]] <- ss
409
+ rownames(tmp) <- NULL
410
+ if (is.null(result)) {
411
+ result <- tmp
412
+ } else {
413
+ all_columns <- union(colnames(result), colnames(tmp))
414
+ result[, setdiff(all_columns, colnames(result))] <- 1
415
+ tmp[, setdiff(all_columns, colnames(tmp))] <- 1
416
+ result <- rbind(result, tmp)
417
+ }
381
418
  }
419
+ uniq_subsets <- unique(result[[case$subset_by]])
420
+ result[[case$subset_by]] <- factor(
421
+ result[[case$subset_by]],
422
+ levels = if (is.factor(sobj@meta.data[[case$subset_by]])) {
423
+ intersect(levels(sobj@meta.data[[case$subset_by]]), uniq_subsets)
424
+ } else {
425
+ uniq_subsets
426
+ }
427
+ )
382
428
  }
383
- }
429
+ uniq_groups <- unique(result[[case$group_by]])
430
+ result[[case$group_by]] <- factor(
431
+ result[[case$group_by]],
432
+ levels = if (is.factor(sobj@meta.data[[case$group_by]])) {
433
+ intersect(levels(sobj@meta.data[[case$group_by]]), uniq_groups)
434
+ } else {
435
+ uniq_groups
436
+ }
437
+ )
384
438
 
385
- if (is.null(subsetting_cols)) {
386
- do_one_subset_col(NULL)
387
- } else {
388
- for (i in seq_along(subsetting_cols)) {
389
- do_one_subset_col(subsetting_cols[i], subsetting_prefix[i])
439
+ for (plotname in names(case$plots)) {
440
+ plotargs <- case$plots[[plotname]]
441
+ if (is.null(plotargs$plot_type)) {
442
+ stop("'plot_type' is required in plot args: ", plotname, " in case: ", casename)
443
+ }
444
+ plotargs$devpars <- plotargs$devpars %||% list()
445
+ plotargs <- extract_vars(plotargs, "devpars", "plot_type")
446
+ if (plot_type != "merged_heatmap") {
447
+ next
448
+ }
449
+ log$info(" Plotting: {plotname} ...")
450
+
451
+ plotargs$data <- result
452
+ plotargs$name <- plotargs$name %||% "Pathway Activity"
453
+ plotargs$in_form <- "wide-rows"
454
+ plotargs$columns_by <- case$group_by
455
+ plotargs$show_row_names <- plotargs$show_row_names %||% TRUE
456
+ minval <- min(as.matrix(result[, setdiff(colnames(result), c(case$group_by, case$subset_by))]))
457
+ maxval <- max(as.matrix(result[, setdiff(colnames(result), c(case$group_by, case$subset_by))]))
458
+ dis <- max(1 - minval, maxval - 1)
459
+ minval <- 1 - dis
460
+ maxval <- 1 + dis
461
+ plotargs$lower_cutoff <- plotargs$lower_cutoff %||% minval
462
+ plotargs$upper_cutoff <- plotargs$upper_cutoff %||% maxval
463
+ plotargs$row_name_annotation <- plotargs$row_name_annotation %||% FALSE
464
+ plotargs$row_names_side <- plotargs$row_names_side %||% "left"
465
+ plotargs$show_column_names <- plotargs$show_column_names %||% TRUE
466
+
467
+ if (!is.null(case$subset_by)) {
468
+ plotargs$columns_split_by <- case$subset_by
469
+ }
470
+ p <- do_call(plotthis::Heatmap, plotargs)
471
+
472
+ devpars <- devpars %||% list()
473
+ devpars$res <- devpars$res %||% 100
474
+ devpars$width <- devpars$width %||% (attr(p, "width") * devpars$res) %||% 1000
475
+ devpars$height <- devpars$height %||% (attr(p, "height") * devpars$res) %||% 1000
476
+
477
+ prefix <- file.path(caseinfo$prefix, paste0(slugify(plotname), ".merged_heatmap"))
478
+ png(paste0(prefix, ".png"), res = devpars$res, width = devpars$width, height = devpars$height)
479
+ print(p)
480
+ dev.off()
481
+
482
+ descr <- plotargs$descr %||% "Merged Heatmaps for Pathway Activity of all subsets."
483
+
484
+ reporter$add(
485
+ list(name = plotname, contents = list(
486
+ list(kind = "descr", content = descr),
487
+ reporter$image(prefix, c(), FALSE)
488
+ )),
489
+ h1 = casename,
490
+ h2 = "Merged Heatmaps",
491
+ ui = "tabs"
492
+ )
390
493
  }
391
494
  }
495
+
496
+ sapply(names(cases), do_case)
497
+
498
+ reporter$save(dirname(outdir))