-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.nf
2962 lines (2667 loc) · 105 KB
/
main.nf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// popv main_build
//
// This wrapper script is auto-generated by viash 0.7.5 and is thus a derivative
// work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data
// Intuitive.
//
// The component may contain files which fall under a different license. The
// authors of this component should specify the license in the header of such
// files, or include a separate license file detailing the licenses of all included
// files.
//
// Component authors:
// * Matthias Beyens (author)
// * Robrecht Cannoodt (author)
nextflow.enable.dsl=2
// Required imports
import groovy.json.JsonSlurper
// initialise slurper
def jsonSlurper = new JsonSlurper()
// DEFINE CUSTOM CODE
// functionality metadata
thisConfig = processConfig(jsonSlurper.parseText('''{
"functionality" : {
"name" : "popv",
"namespace" : "annotate",
"version" : "main_build",
"authors" : [
{
"name" : "Matthias Beyens",
"roles" : [
"author"
],
"info" : {
"role" : "Contributor",
"links" : {
"github" : "MatthiasBeyens",
"orcid" : "0000-0003-3304-0706",
"email" : "matthias.beyens@gmail.com",
"linkedin" : "mbeyens"
},
"organizations" : [
{
"name" : "Janssen Pharmaceuticals",
"href" : "https://www.janssen.com",
"role" : "Principal Scientist"
}
]
}
},
{
"name" : "Robrecht Cannoodt",
"roles" : [
"author"
],
"info" : {
"role" : "Core Team Member",
"links" : {
"email" : "robrecht@data-intuitive.com",
"github" : "rcannood",
"orcid" : "0000-0003-3641-729X",
"linkedin" : "robrechtcannoodt"
},
"organizations" : [
{
"name" : "Data Intuitive",
"href" : "https://www.data-intuitive.com",
"role" : "Data Science Engineer"
},
{
"name" : "Open Problems",
"href" : "https://openproblems.bio",
"role" : "Core Member"
}
]
}
}
],
"argument_groups" : [
{
"name" : "Inputs",
"description" : "Arguments related to the input (aka query) dataset.",
"arguments" : [
{
"type" : "file",
"name" : "--input",
"alternatives" : [
"-i"
],
"description" : "Input h5mu file.",
"example" : [
"input.h5mu"
],
"must_exist" : true,
"create_parent" : true,
"required" : true,
"direction" : "input",
"multiple" : false,
"multiple_sep" : ":",
"dest" : "par"
},
{
"type" : "string",
"name" : "--modality",
"description" : "Which modality to process.",
"default" : [
"rna"
],
"required" : false,
"direction" : "input",
"multiple" : false,
"multiple_sep" : ":",
"dest" : "par"
},
{
"type" : "string",
"name" : "--input_layer",
"description" : "Which layer to use. If no value is provided, the counts are assumed to be in the `.X` slot. Otherwise, count data is expected to be in `.layers[input_layer]`.",
"required" : false,
"direction" : "input",
"multiple" : false,
"multiple_sep" : ":",
"dest" : "par"
},
{
"type" : "string",
"name" : "--input_obs_batch",
"description" : "Key in obs field of input adata for batch information. If no value is provided, batch label is assumed to be unknown.",
"required" : false,
"direction" : "input",
"multiple" : false,
"multiple_sep" : ":",
"dest" : "par"
},
{
"type" : "string",
"name" : "--input_var_subset",
"description" : "Subset the input object with this column.",
"required" : false,
"direction" : "input",
"multiple" : false,
"multiple_sep" : ":",
"dest" : "par"
},
{
"type" : "string",
"name" : "--input_obs_label",
"description" : "Key in obs field of input adata for label information. This is only used for training scANVI. Unlabelled cells should be set to `\\"unknown_celltype_label\\"`.",
"required" : false,
"direction" : "input",
"multiple" : false,
"multiple_sep" : ":",
"dest" : "par"
},
{
"type" : "string",
"name" : "--unknown_celltype_label",
"description" : "If `input_obs_label` is specified, cells with this value will be treated as unknown and will be predicted by the model.",
"default" : [
"unknown"
],
"required" : false,
"direction" : "input",
"multiple" : false,
"multiple_sep" : ":",
"dest" : "par"
}
]
},
{
"name" : "Reference",
"description" : "Arguments related to the reference dataset.",
"arguments" : [
{
"type" : "file",
"name" : "--reference",
"description" : "User-provided reference tissue. The data that will be used as reference to call cell types.",
"example" : [
"TS_Bladder_filtered.h5ad"
],
"must_exist" : true,
"create_parent" : true,
"required" : true,
"direction" : "input",
"multiple" : false,
"multiple_sep" : ":",
"dest" : "par"
},
{
"type" : "string",
"name" : "--reference_layer",
"description" : "Which layer to use. If no value is provided, the counts are assumed to be in the `.X` slot. Otherwise, count data is expected to be in `.layers[reference_layer]`.",
"required" : false,
"direction" : "input",
"multiple" : false,
"multiple_sep" : ":",
"dest" : "par"
},
{
"type" : "string",
"name" : "--reference_obs_label",
"description" : "Key in obs field of reference AnnData with cell-type information.",
"default" : [
"cell_ontology_class"
],
"required" : false,
"direction" : "input",
"multiple" : false,
"multiple_sep" : ":",
"dest" : "par"
},
{
"type" : "string",
"name" : "--reference_obs_batch",
"description" : "Key in obs field of input adata for batch information.",
"default" : [
"donor_assay"
],
"required" : false,
"direction" : "input",
"multiple" : false,
"multiple_sep" : ":",
"dest" : "par"
}
]
},
{
"name" : "Outputs",
"description" : "Output arguments.",
"arguments" : [
{
"type" : "file",
"name" : "--output",
"description" : "Output h5mu file.",
"example" : [
"output.h5mu"
],
"must_exist" : true,
"create_parent" : true,
"required" : true,
"direction" : "output",
"multiple" : false,
"multiple_sep" : ":",
"dest" : "par"
},
{
"type" : "string",
"name" : "--output_compression",
"example" : [
"gzip"
],
"required" : false,
"choices" : [
"gzip",
"lzf"
],
"direction" : "input",
"multiple" : false,
"multiple_sep" : ":",
"dest" : "par"
}
]
},
{
"name" : "Arguments",
"description" : "Other arguments.",
"arguments" : [
{
"type" : "string",
"name" : "--methods",
"description" : "Methods to call cell types. By default, runs to knn_on_scvi and scanvi.",
"example" : [
"knn_on_scvi",
"scanvi"
],
"required" : true,
"choices" : [
"celltypist",
"knn_on_bbknn",
"knn_on_scanorama",
"knn_on_scvi",
"onclass",
"rf",
"scanvi",
"svm"
],
"direction" : "input",
"multiple" : true,
"multiple_sep" : ":",
"dest" : "par"
}
]
}
],
"resources" : [
{
"type" : "python_script",
"path" : "script.py",
"is_executable" : true,
"parent" : "file:/home/runner/work/openpipeline/openpipeline/src/annotate/popv/"
},
{
"type" : "file",
"path" : "src/utils/setup_logger.py",
"parent" : "file:///home/runner/work/openpipeline/openpipeline/"
}
],
"description" : "Performs popular major vote cell typing on single cell sequence data using multiple algorithms. Note that this is a one-shot version of PopV.",
"test_resources" : [
{
"type" : "python_script",
"path" : "test.py",
"is_executable" : true,
"parent" : "file:/home/runner/work/openpipeline/openpipeline/src/annotate/popv/"
},
{
"type" : "file",
"path" : "resources_test/annotation_test_data/",
"parent" : "file:///home/runner/work/openpipeline/openpipeline/"
},
{
"type" : "file",
"path" : "resources_test/pbmc_1k_protein_v3/",
"parent" : "file:///home/runner/work/openpipeline/openpipeline/"
}
],
"status" : "enabled",
"requirements" : {
"commands" : [
"ps"
]
},
"set_wd_to_resources_dir" : false
},
"platforms" : [
{
"type" : "docker",
"id" : "docker",
"image" : "python:3.9-slim",
"target_organization" : "openpipelines-bio",
"target_registry" : "ghcr.io",
"namespace_separator" : "_",
"resolve_volume" : "Automatic",
"chown" : true,
"setup_strategy" : "ifneedbepullelsecachedbuild",
"target_image_source" : "https://github.com/openpipelines-bio/openpipeline",
"setup" : [
{
"type" : "apt",
"packages" : [
"procps",
"git",
"build-essential",
"wget"
],
"interactive" : false
},
{
"type" : "python",
"user" : false,
"packages" : [
"scanpy~=1.9.2",
"scvi-tools~=0.20.3",
"popv~=0.3.2"
],
"upgrade" : true
},
{
"type" : "python",
"user" : false,
"packages" : [
"mudata~=0.2.3",
"anndata~=0.9.1"
],
"upgrade" : true
},
{
"type" : "docker",
"run" : [
"cd /opt && git clone --depth 1 https://github.com/YosefLab/PopV.git && \\\\\n cd PopV && git fetch --depth 1 origin tag v0.2 && git checkout v0.2\n"
]
},
{
"type" : "python",
"user" : false,
"packages" : [
"jax==0.4.9",
"jaxlib==0.4.9"
],
"upgrade" : true
}
],
"test_setup" : [
{
"type" : "python",
"user" : false,
"packages" : [
"viashpy"
],
"upgrade" : true
}
]
},
{
"type" : "nextflow",
"id" : "nextflow",
"directives" : {
"label" : [
"highmem",
"highcpu"
],
"tag" : "$id"
},
"auto" : {
"simplifyInput" : true,
"simplifyOutput" : true,
"transcript" : false,
"publish" : false
},
"config" : {
"labels" : {
"mem1gb" : "memory = 1.GB",
"mem2gb" : "memory = 2.GB",
"mem4gb" : "memory = 4.GB",
"mem8gb" : "memory = 8.GB",
"mem16gb" : "memory = 16.GB",
"mem32gb" : "memory = 32.GB",
"mem64gb" : "memory = 64.GB",
"mem128gb" : "memory = 128.GB",
"mem256gb" : "memory = 256.GB",
"mem512gb" : "memory = 512.GB",
"mem1tb" : "memory = 1.TB",
"mem2tb" : "memory = 2.TB",
"mem4tb" : "memory = 4.TB",
"mem8tb" : "memory = 8.TB",
"mem16tb" : "memory = 16.TB",
"mem32tb" : "memory = 32.TB",
"mem64tb" : "memory = 64.TB",
"mem128tb" : "memory = 128.TB",
"mem256tb" : "memory = 256.TB",
"mem512tb" : "memory = 512.TB",
"cpu1" : "cpus = 1",
"cpu2" : "cpus = 2",
"cpu5" : "cpus = 5",
"cpu10" : "cpus = 10",
"cpu20" : "cpus = 20",
"cpu50" : "cpus = 50",
"cpu100" : "cpus = 100",
"cpu200" : "cpus = 200",
"cpu500" : "cpus = 500",
"cpu1000" : "cpus = 1000"
}
},
"debug" : false,
"container" : "docker"
}
],
"info" : {
"config" : "/home/runner/work/openpipeline/openpipeline/src/annotate/popv/config.vsh.yaml",
"platform" : "nextflow",
"output" : "/home/runner/work/openpipeline/openpipeline/target/nextflow/annotate/popv",
"viash_version" : "0.7.5",
"git_commit" : "679aa4eb97581c8dbc9fb9d68214dd2b579f1288",
"git_remote" : "https://github.com/openpipelines-bio/openpipeline"
}
}'''))
thisScript = '''set -e
tempscript=".viash_script.sh"
cat > "$tempscript" << VIASHMAIN
import sys
import re
import tempfile
import typing
import numpy as np
import mudata as mu
import anndata as ad
import popv
# todo: is this still needed?
from torch.cuda import is_available as cuda_is_available
try:
from torch.backends.mps import is_available as mps_is_available
except ModuleNotFoundError:
# Older pytorch versions
# MacOS GPUs
def mps_is_available():
return False
# where to find the obo files
cl_obo_folder = "/opt/PopV/ontology/"
## VIASH START
# The following code has been auto-generated by Viash.
par = {
'input': $( if [ ! -z ${VIASH_PAR_INPUT+x} ]; then echo "r'${VIASH_PAR_INPUT//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ),
'modality': $( if [ ! -z ${VIASH_PAR_MODALITY+x} ]; then echo "r'${VIASH_PAR_MODALITY//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ),
'input_layer': $( if [ ! -z ${VIASH_PAR_INPUT_LAYER+x} ]; then echo "r'${VIASH_PAR_INPUT_LAYER//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ),
'input_obs_batch': $( if [ ! -z ${VIASH_PAR_INPUT_OBS_BATCH+x} ]; then echo "r'${VIASH_PAR_INPUT_OBS_BATCH//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ),
'input_var_subset': $( if [ ! -z ${VIASH_PAR_INPUT_VAR_SUBSET+x} ]; then echo "r'${VIASH_PAR_INPUT_VAR_SUBSET//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ),
'input_obs_label': $( if [ ! -z ${VIASH_PAR_INPUT_OBS_LABEL+x} ]; then echo "r'${VIASH_PAR_INPUT_OBS_LABEL//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ),
'unknown_celltype_label': $( if [ ! -z ${VIASH_PAR_UNKNOWN_CELLTYPE_LABEL+x} ]; then echo "r'${VIASH_PAR_UNKNOWN_CELLTYPE_LABEL//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ),
'reference': $( if [ ! -z ${VIASH_PAR_REFERENCE+x} ]; then echo "r'${VIASH_PAR_REFERENCE//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ),
'reference_layer': $( if [ ! -z ${VIASH_PAR_REFERENCE_LAYER+x} ]; then echo "r'${VIASH_PAR_REFERENCE_LAYER//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ),
'reference_obs_label': $( if [ ! -z ${VIASH_PAR_REFERENCE_OBS_LABEL+x} ]; then echo "r'${VIASH_PAR_REFERENCE_OBS_LABEL//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ),
'reference_obs_batch': $( if [ ! -z ${VIASH_PAR_REFERENCE_OBS_BATCH+x} ]; then echo "r'${VIASH_PAR_REFERENCE_OBS_BATCH//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ),
'output': $( if [ ! -z ${VIASH_PAR_OUTPUT+x} ]; then echo "r'${VIASH_PAR_OUTPUT//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ),
'output_compression': $( if [ ! -z ${VIASH_PAR_OUTPUT_COMPRESSION+x} ]; then echo "r'${VIASH_PAR_OUTPUT_COMPRESSION//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ),
'methods': $( if [ ! -z ${VIASH_PAR_METHODS+x} ]; then echo "r'${VIASH_PAR_METHODS//\\'/\\'\\"\\'\\"r\\'}'.split(':')"; else echo None; fi )
}
meta = {
'functionality_name': $( if [ ! -z ${VIASH_META_FUNCTIONALITY_NAME+x} ]; then echo "r'${VIASH_META_FUNCTIONALITY_NAME//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ),
'resources_dir': $( if [ ! -z ${VIASH_META_RESOURCES_DIR+x} ]; then echo "r'${VIASH_META_RESOURCES_DIR//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ),
'executable': $( if [ ! -z ${VIASH_META_EXECUTABLE+x} ]; then echo "r'${VIASH_META_EXECUTABLE//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ),
'config': $( if [ ! -z ${VIASH_META_CONFIG+x} ]; then echo "r'${VIASH_META_CONFIG//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ),
'temp_dir': $( if [ ! -z ${VIASH_META_TEMP_DIR+x} ]; then echo "r'${VIASH_META_TEMP_DIR//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ),
'cpus': $( if [ ! -z ${VIASH_META_CPUS+x} ]; then echo "int(r'${VIASH_META_CPUS//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ),
'memory_b': $( if [ ! -z ${VIASH_META_MEMORY_B+x} ]; then echo "int(r'${VIASH_META_MEMORY_B//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ),
'memory_kb': $( if [ ! -z ${VIASH_META_MEMORY_KB+x} ]; then echo "int(r'${VIASH_META_MEMORY_KB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ),
'memory_mb': $( if [ ! -z ${VIASH_META_MEMORY_MB+x} ]; then echo "int(r'${VIASH_META_MEMORY_MB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ),
'memory_gb': $( if [ ! -z ${VIASH_META_MEMORY_GB+x} ]; then echo "int(r'${VIASH_META_MEMORY_GB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ),
'memory_tb': $( if [ ! -z ${VIASH_META_MEMORY_TB+x} ]; then echo "int(r'${VIASH_META_MEMORY_TB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ),
'memory_pb': $( if [ ! -z ${VIASH_META_MEMORY_PB+x} ]; then echo "int(r'${VIASH_META_MEMORY_PB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi )
}
## VIASH END
sys.path.append(meta["resources_dir"])
# START TEMPORARY WORKAROUND setup_logger
# reason: resources aren't available when using Nextflow fusion
# from setup_logger import setup_logger
def setup_logger():
import logging
from sys import stdout
logger = logging.getLogger()
logger.setLevel(logging.INFO)
console_handler = logging.StreamHandler(stdout)
logFormatter = logging.Formatter("%(asctime)s %(levelname)-8s %(message)s")
console_handler.setFormatter(logFormatter)
logger.addHandler(console_handler)
return logger
# END TEMPORARY WORKAROUND setup_logger
logger = setup_logger()
use_gpu = cuda_is_available() or mps_is_available()
logger.info("GPU enabled? %s", use_gpu)
# Helper functions
def get_X(adata: ad.AnnData, layer: typing.Optional[str], var_index: typing.Optional[str]):
"""Fetch the counts data from X or a layer. Subset columns by var_index if so desired."""
if var_index:
adata = adata[:, var_index]
if layer:
return adata.layers[layer]
else:
return adata.X
def get_obs(adata: ad.AnnData, obs_par_names):
"""Subset the obs dataframe to just the columns defined by the obs_label and obs_batch."""
obs_columns = [par[x] for x in obs_par_names if par[x]]
return adata.obs[obs_columns]
def get_var(adata: ad.AnnData, var_index: list[str]):
"""Fetch the var dataframe. Subset rows by var_index if so desired."""
return adata.var.loc[var_index]
def main(par, meta):
assert len(par["methods"]) >= 1, "Please, specify at least one method for cell typing."
logger.info("Cell typing methods: {}".format(par["methods"]))
### PREPROCESSING REFERENCE ###
logger.info("### PREPROCESSING REFERENCE ###")
# take a look at reference data
logger.info("Reading reference data '%s'", par["reference"])
reference = ad.read_h5ad(par["reference"])
logger.info("Setting reference var index to Ensembl IDs")
reference.var["gene_symbol"] = list(reference.var.index)
reference.var.index = [re.sub("\\\\\\\\.[0-9]+\\$", "", s) for s in reference.var["ensemblid"]]
logger.info("Detect number of samples per label")
min_celltype_size = np.min(reference.obs.groupby(par["reference_obs_batch"]).size())
n_samples_per_label = np.max((min_celltype_size, 100))
### PREPROCESSING INPUT ###
logger.info("### PREPROCESSING INPUT ###")
logger.info("Reading '%s'", par["input"])
input = mu.read_h5mu(par["input"])
input_modality = input.mod[par["modality"]]
# subset with var column
if par["input_var_subset"]:
logger.info("Subset input with .var['%s']", par["input_var_subset"])
assert par["input_var_subset"] in input_modality.var, f"--input_var_subset='{par['input_var_subset']}' needs to be a column in .var"
input_modality = input_modality[:,input_modality.var[par["input_var_subset"]]]
### ALIGN REFERENCE AND INPUT ###
logger.info("### ALIGN REFERENCE AND INPUT ###")
logger.info("Detecting common vars based on ensembl ids")
common_ens_ids = list(set(reference.var.index).intersection(set(input_modality.var.index)))
logger.info(" reference n_vars: %i", reference.n_vars)
logger.info(" input n_vars: %i", input_modality.n_vars)
logger.info(" intersect n_vars: %i", len(common_ens_ids))
assert len(common_ens_ids) >= 100, "The intersection of genes is too small."
# subset input objects to make sure popv is using the data we expect
input_modality = ad.AnnData(
X = get_X(input_modality, par["input_layer"], common_ens_ids),
obs = get_obs(input_modality, ["input_obs_label", "input_obs_batch"]),
var = get_var(input_modality, common_ens_ids)
)
reference = ad.AnnData(
X = get_X(reference, par["reference_layer"], common_ens_ids),
obs = get_obs(reference, ["reference_obs_label", "reference_obs_batch"]),
var = get_var(reference, common_ens_ids)
)
# remove layers that
### ALIGN REFERENCE AND INPUT ###
logger.info("### ALIGN REFERENCE AND INPUT ###")
with tempfile.TemporaryDirectory(prefix="popv-", dir=meta["temp_dir"]) as temp_dir:
logger.info("Run PopV processing")
pq = popv.preprocessing.Process_Query(
# input
query_adata=input_modality,
query_labels_key=par["input_obs_label"],
query_batch_key=par["input_obs_batch"],
query_layers_key=None, # this is taken care of by subset
# reference
ref_adata=reference,
ref_labels_key=par["reference_obs_label"],
ref_batch_key=par["reference_obs_batch"],
# options
unknown_celltype_label=par["unknown_celltype_label"],
n_samples_per_label=n_samples_per_label,
# pretrained model
# Might need to be parameterized at some point
prediction_mode="retrain",
pretrained_scvi_path=None,
# outputs
# Might need to be parameterized at some point
save_path_trained_models=temp_dir,
# hardcoded values
cl_obo_folder=cl_obo_folder,
use_gpu=use_gpu
)
method_kwargs = {}
if 'scanorama' in par['methods']:
method_kwargs['scanorama'] = {'approx': False}
logger.info("Annotate data")
popv.annotation.annotate_data(
adata=pq.adata,
methods=par["methods"],
methods_kwargs=method_kwargs
)
popv_input = pq.adata[input_modality.obs_names]
# select columns starting with "popv_"
popv_obs_cols = popv_input.obs.columns[popv_input.obs.columns.str.startswith("popv_")]
# create new data frame with selected columns
df_popv = popv_input.obs[popv_obs_cols]
# remove prefix from column names
df_popv.columns = df_popv.columns.str.replace("popv_", "")
# store output in mudata .obsm
input.mod[par["modality"]].obsm["popv_output"] = df_popv
# copy important output in mudata .obs
for col in ["popv_prediction"]:
if col in popv_input.obs.columns:
input.mod[par["modality"]].obs[col] = popv_input.obs[col]
# code to explore how the output differs from the original
# for attr in ["obs", "var", "uns", "obsm", "layers", "obsp"]:
# old_keys = set(getattr(pq_adata_orig, attr).keys())
# new_keys = set(getattr(pq.adata, attr).keys())
# diff_keys = list(new_keys.difference(old_keys))
# diff_keys.sort()
# print(f"{attr}:", flush=True)
# for key in diff_keys:
# print(f" {key}", flush=True)
# write output
logger.info("Writing %s", par["output"])
input.write_h5mu(par["output"], compression=par["output_compression"])
if __name__ == "__main__":
main(par, meta)
VIASHMAIN
python -B "$tempscript"
'''
thisDefaultProcessArgs = [
// key to be used to trace the process and determine output names
key: thisConfig.functionality.name,
// fixed arguments to be passed to script
args: [:],
// default directives
directives: jsonSlurper.parseText('''{
"container" : {
"registry" : "ghcr.io",
"image" : "openpipelines-bio/annotate_popv",
"tag" : "main_build"
},
"label" : [
"highmem",
"highcpu"
],
"tag" : "$id"
}'''),
// auto settings
auto: jsonSlurper.parseText('''{
"simplifyInput" : true,
"simplifyOutput" : true,
"transcript" : false,
"publish" : false
}'''),
// Apply a map over the incoming tuple
// Example: `{ tup -> [ tup[0], [input: tup[1].output] ] + tup.drop(2) }`
map: null,
// Apply a map over the ID element of a tuple (i.e. the first element)
// Example: `{ id -> id + "_foo" }`
mapId: null,
// Apply a map over the data element of a tuple (i.e. the second element)
// Example: `{ data -> [ input: data.output ] }`
mapData: null,
// Apply a map over the passthrough elements of a tuple (i.e. the tuple excl. the first two elements)
// Example: `{ pt -> pt.drop(1) }`
mapPassthrough: null,
// Filter the channel
// Example: `{ tup -> tup[0] == "foo" }`
filter: null,
// Rename keys in the data field of the tuple (i.e. the second element)
// Will likely be deprecated in favour of `fromState`.
// Example: `[ "new_key": "old_key" ]`
renameKeys: null,
// Fetch data from the state and pass it to the module without altering the current state.
//
// `fromState` should be `null`, `List[String]`, `Map[String, String]` or a function.
//
// - If it is `null`, the state will be passed to the module as is.
// - If it is a `List[String]`, the data will be the values of the state at the given keys.
// - If it is a `Map[String, String]`, the data will be the values of the state at the given keys, with the keys renamed according to the map.
// - If it is a function, the tuple (`[id, state]`) in the channel will be passed to the function, and the result will be used as the data.
//
// Example: `{ id, state -> [input: state.fastq_file] }`
// Default: `null`
fromState: null,
// Determine how the state should be updated after the module has been run.
//
// `toState` should be `null`, `List[String]`, `Map[String, String]` or a function.
//
// - If it is `null`, the state will be replaced with the output of the module.
// - If it is a `List[String]`, the state will be updated with the values of the data at the given keys.
// - If it is a `Map[String, String]`, the state will be updated with the values of the data at the given keys, with the keys renamed according to the map.
// - If it is a function, a tuple (`[id, output, state]`) will be passed to the function, and the result will be used as the new state.
//
// Example: `{ id, output, state -> state + [counts: state.output] }`
// Default: `{ id, output, state -> output }`
toState: null,
// Whether or not to print debug messages
// Default: `false`
debug: false
]
// END CUSTOM CODE
/////////////////////////////////////
// Viash Workflow helper functions //
/////////////////////////////////////
import java.util.regex.Pattern
import java.io.BufferedReader
import java.io.FileReader
import java.nio.file.Paths
import java.nio.file.Files
import groovy.json.JsonSlurper
import groovy.text.SimpleTemplateEngine
import org.yaml.snakeyaml.Yaml
// param helpers //
def paramExists(name) {
return params.containsKey(name) && params[name] != ""
}
def assertParamExists(name, description) {
if (!paramExists(name)) {
exit 1, "ERROR: Please provide a --${name} parameter ${description}"
}
}
// helper functions for reading params from file //
def getChild(parent, child) {
if (child.contains("://") || Paths.get(child).isAbsolute()) {
child
} else {
def parentAbsolute = Paths.get(parent).toAbsolutePath().toString()
parentAbsolute.replaceAll('/[^/]*$', "/") + child
}
}
def readCsv(file_path) {
def output = []
def inputFile = file_path !instanceof Path ? file(file_path) : file_path
// todo: allow escaped quotes in string
// todo: allow single quotes?
def splitRegex = Pattern.compile(''',(?=(?:[^"]*"[^"]*")*[^"]*$)''')
def removeQuote = Pattern.compile('''"(.*)"''')
def br = Files.newBufferedReader(inputFile)
def row = -1
def header = null
while (br.ready() && header == null) {
def line = br.readLine()
row++
if (!line.startsWith("#")) {
header = splitRegex.split(line, -1).collect{field ->
m = removeQuote.matcher(field)
m.find() ? m.replaceFirst('$1') : field
}
}
}
assert header != null: "CSV file should contain a header"
while (br.ready()) {
def line = br.readLine()
row++
if (line == null) {
br.close()
break
}
if (!line.startsWith("#")) {
def predata = splitRegex.split(line, -1)
def data = predata.collect{field ->
if (field == "") {
return null
}
m = removeQuote.matcher(field)
if (m.find()) {
return m.replaceFirst('$1')
} else {
return field
}
}
assert header.size() == data.size(): "Row $row should contain the same number as fields as the header"
def dataMap = [header, data].transpose().collectEntries().findAll{it.value != null}
output.add(dataMap)
}
}
output
}
def readJsonBlob(str) {
def jsonSlurper = new JsonSlurper()
jsonSlurper.parseText(str)
}
def readJson(file_path) {
def inputFile = file_path !instanceof Path ? file(file_path) : file_path
def jsonSlurper = new JsonSlurper()
jsonSlurper.parse(inputFile)
}
def readYamlBlob(str) {
def yamlSlurper = new Yaml()
yamlSlurper.load(str)
}
def readYaml(file_path) {
def inputFile = file_path !instanceof Path ? file(file_path) : file_path
def yamlSlurper = new Yaml()
yamlSlurper.load(inputFile)
}
// helper functions for reading a viash config in groovy //
// based on how Functionality.scala is implemented
def processArgument(arg) {
arg.multiple = arg.multiple != null ? arg.multiple : false
arg.required = arg.required != null ? arg.required : false
arg.direction = arg.direction != null ? arg.direction : "input"
arg.multiple_sep = arg.multiple_sep != null ? arg.multiple_sep : ":"
arg.plainName = arg.name.replaceAll("^-*", "")
if (arg.type == "file") {
arg.must_exist = arg.must_exist != null ? arg.must_exist : true
arg.create_parent = arg.create_parent != null ? arg.create_parent : true
}
if (arg.type == "file" && arg.direction == "output") {
def mult = arg.multiple ? "_*" : ""
def extSearch = ""
if (arg.default != null) {
extSearch = arg.default
} else if (arg.example != null) {
extSearch = arg.example
}
if (extSearch instanceof List) {
extSearch = extSearch[0]
}
def extSearchResult = extSearch.find("\\.[^\\.]+\$")
def ext = extSearchResult != null ? extSearchResult : ""
arg.default = "\$id.\$key.${arg.plainName}${mult}${ext}"
}
if (!arg.multiple) {
if (arg.default != null && arg.default instanceof List) {
arg.default = arg.default[0]
}
if (arg.example != null && arg.example instanceof List) {
arg.example = arg.example[0]
}
}
if (arg.type == "boolean_true") {
arg.default = false
}
if (arg.type == "boolean_false") {
arg.default = true
}
arg
}
// based on how Functionality.scala is implemented
def processArgumentGroup(argumentGroups, name, arguments) {
def argNamesInGroups = argumentGroups.collectMany{it.arguments.findAll{it instanceof String}}.toSet()
// Check if 'arguments' is in 'argumentGroups'.
def argumentsNotInGroup = arguments.findAll{arg -> !(argNamesInGroups.contains(arg.plainName))}
// Check whether an argument group of 'name' exists.
def existing = argumentGroups.find{gr -> name == gr.name}
// if there are no arguments missing from the argument group, just return the existing group (if any)
if (argumentsNotInGroup.isEmpty()) {
return existing == null ? [] : [existing]
// if there are missing arguments and there is an existing group, add the missing arguments to it
} else if (existing != null) {
def newEx = existing.clone()
newEx.arguments.addAll(argumentsNotInGroup.findAll{it !instanceof String})
return [newEx]
// else create a new group
} else {
def newEx = [name: name, arguments: argumentsNotInGroup.findAll{it !instanceof String}]
return [newEx]
}
}
// based on how Functionality.scala is implemented
def processConfig(config) {
// TODO: assert .functionality etc.
if (config.functionality.inputs) {
System.err.println("Warning: .functionality.inputs is deprecated. Please use .functionality.arguments instead.")
}
if (config.functionality.outputs) {
System.err.println("Warning: .functionality.outputs is deprecated. Please use .functionality.arguments instead.")
}
// set defaults for inputs
config.functionality.inputs =
(config.functionality.inputs != null ? config.functionality.inputs : []).collect{arg ->
arg.type = arg.type != null ? arg.type : "file"
arg.direction = "input"
processArgument(arg)
}
// set defaults for outputs
config.functionality.outputs =
(config.functionality.outputs != null ? config.functionality.outputs : []).collect{arg ->
arg.type = arg.type != null ? arg.type : "file"
arg.direction = "output"
processArgument(arg)