-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.nf
1228 lines (982 loc) · 39.1 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
#!/usr/bin/env nextflow
/*
========================================================================================
nf-core/metabolinden
========================================================================================
nf-core/metabolinden Analysis Pipeline.
#### Homepage / Documentation
https://github.com/nf-core/metabolinden
----------------------------------------------------------------------------------------
*/
log.info Headers.nf_core(workflow, params.monochrome_logs)
////////////////////////////////////////////////////
/* -- PRINT HELP -- */
////////////////////////////////////////////////////+
def json_schema = "$projectDir/nextflow_schema.json"
if (params.help) {
def command = "nextflow run nf-core/metabolinden --input '*.mzML' -profile docker"
log.info NfcoreSchema.params_help(workflow, params, json_schema, command)
exit 0
}
////////////////////////////////////////////////////
/* -- VALIDATE PARAMETERS -- */
////////////////////////////////////////////////////+
if (params.validate_params) {
NfcoreSchema.validateParameters(params, json_schema, log)
}
////////////////////////////////////////////////////
/* -- randomize files -- */
////////////////////////////////////////////////////
def group_files( input,samples_in_chunks=2,randomize=false,seed=42){
old_key=input[0]
input=input[1]
if(samples_in_chunks<=1 || samples_in_chunks>=input.size())
{
step_wise_linking=false
return input
}
def range_of_vec = (0..input.size()-1).toList()
if(randomize==true){
range_of_vec.shuffle(new Random(seed))
}
if((range_of_vec.size()%samples_in_chunks)<2)
{
while((range_of_vec.size()%samples_in_chunks)<2)
{
samples_in_chunks = (samples_in_chunks+1)
}
println 'The minimum number of samples must be one. Adjusting samples_in_chunks to '+ (samples_in_chunks)
}
chunks=range_of_vec.collate(samples_in_chunks)
def vector_sizes=[]
groups=[]
for(n in 0..chunks.size()-1)
{
vector_sizes.add(chunks[n].size())
aa=["chunk"+(n+1)+"_chunkend_"+old_key]*chunks[n].size()
for(i in chunks[n])
{
groups.add(["chunk"+(n+1)+old_key,old_key,file(input[i])])
}
}
return(groups)
}
////////////////////////////////////////////////////
/* -- Collect configuration parameters -- */
////////////////////////////////////////////////////
Channel.fromPath(params.input,checkIfExists: true)
.map{def key = "start"
return tuple(key, it)}
.into { mzml_input;cut_mzml_mzmlraw}//.map { tag, files -> tuple( groupKey(tag, files.size()), files ) }
//.transpose()
/*
* Create a channel for centroiding parameters
*/
if(params.need_centroiding==true)
{
Channel.fromPath(params.peak_picker_param,checkIfExists: true)
.set { peak_picker_param }
}
if(params.need_filtering==true)
{
Channel.fromPath(params.file_filter_param,checkIfExists: true)
.set { file_filter_param }
}
/*
* Create a channel for recalibration parameters
*/
if(params.need_recalibration==true)
{
Channel.fromPath(params.peak_recalibration_param,checkIfExists: true)
.into { peak_recalibration_param;c3 }
/*
* Create a channel for recalibration standards
*/
Channel.fromPath(params.recalibration_masses,checkIfExists: true)
.into { recalibration_masses;c4 }
}
/*
* Create a channel for feature_detection
*/
if(params.need_quantification==true)
{
Channel.fromPath(params.feature_finder_param,checkIfExists: true)
.set { feature_finder_param }
}else{
params.need_alignment=false
params.need_linking=false
params.need_identification=false
}
/*
* Create a channel for feature aligment parameters
*/
if(params.need_alignment==true)
{
Channel.fromPath(params.feature_alignment_param,checkIfExists: true)
.set { feature_alignment_param }
}
/*
* Create a channel for feature linker parameters
*/
if(params.need_linking==true)
{
Channel.fromPath(params.feature_linker_param,checkIfExists: true)
.set { feature_linker_param }
if(params.step_wise_linking==true)
if(params.use_same_setting_for_second_linking==false)
{
Channel.fromPath(params.feature_linker_param2,checkIfExists: true)
.set { feature_linker_param2 }
}
}
/*
* Create a channel for feature linker parameters
*/
if(params.need_identification==true)
{
Channel.fromPath(params.identification_input,checkIfExists: true)
.into { identification_input;identification_input_qc }
}
if(params.need_qc==true)
{
Channel.fromPath(params.qc_file,checkIfExists: true)
.set { experimental_design }
}
/*
* Create a channel for feature linker parameters
*/
// Check AWS batch settings
if (workflow.profile.contains('awsbatch')) {
// AWSBatch sanity checking
if (!params.awsqueue || !params.awsregion) exit 1, 'Specify correct --awsqueue and --awsregion parameters on AWSBatch!'
// Check outdir paths to be S3 buckets if running on AWSBatch
// related: https://github.com/nextflow-io/nextflow/issues/813
if (!params.outdir.startsWith('s3:')) exit 1, 'Outdir not on S3 - specify S3 Bucket to run on AWSBatch!'
// Prevent trace files to be stored on S3 since S3 does not support rolling files.
if (params.tracedir.startsWith('s3:')) exit 1, 'Specify a local tracedir or run without trace! S3 cannot be used for tracefiles.'
}
// Stage config files
ch_output_docs = file("$projectDir/docs/output.md", checkIfExists: true)
ch_output_docs_images = file("$projectDir/docs/images/", checkIfExists: true)
ch_output_qc_rmd = channel.fromPath("$projectDir/assets/qc.Rmd", checkIfExists: true)
////////////////////////////////////////////////////
/* -- PRINT PARAMETER SUMMARY -- */
////////////////////////////////////////////////////
log.info NfcoreSchema.params_summary_log(workflow, params, json_schema)
// Header log info
def summary = [:]
if (workflow.revision) summary['Pipeline Release'] = workflow.revision
summary['Run Name'] = workflow.runName
// TODO nf-core: Report custom parameters here
summary['Input'] = params.input
summary['Max Resources'] = "$params.max_memory memory, $params.max_cpus cpus, $params.max_time time per job"
if (workflow.containerEngine) summary['Container'] = "$workflow.containerEngine - $workflow.container"
summary['Output dir'] = params.outdir
summary['Launch dir'] = workflow.launchDir
summary['Working dir'] = workflow.workDir
summary['Script dir'] = workflow.projectDir
summary['User'] = workflow.userName
if (workflow.profile.contains('awsbatch')) {
summary['AWS Region'] = params.awsregion
summary['AWS Queue'] = params.awsqueue
summary['AWS CLI'] = params.awscli
}
summary['Config Profile'] = workflow.profile
if (params.config_profile_description) summary['Config Profile Description'] = params.config_profile_description
if (params.config_profile_contact) summary['Config Profile Contact'] = params.config_profile_contact
if (params.config_profile_url) summary['Config Profile URL'] = params.config_profile_url
summary['Config Files'] = workflow.configFiles.join(', ')
if (params.email || params.email_on_fail) {
summary['E-mail Address'] = params.email
summary['E-mail on failure'] = params.email_on_fail
}
// Check the hostnames against configured profiles
checkHostname()
Channel.from(summary.collect{ [it.key, it.value] })
.map { k,v -> "<dt>$k</dt><dd><samp>${v ?: '<span style=\"color:#999999;\">N/A</a>'}</samp></dd>" }
.reduce { a, b -> return [a, b].join("\n ") }
.map { x -> """
id: 'nf-core-metabolinden-summary'
description: " - this information is collected when the pipeline is started."
section_name: 'nf-core/metabolinden Workflow Summary'
section_href: 'https://github.com/nf-core/metabolinden'
plot_type: 'html'
data: |
<dl class=\"dl-horizontal\">
$x
</dl>
""".stripIndent() }
.set { ch_workflow_summary }
/*
* Parse software version numbers
*/
process get_software_versions {
publishDir "${params.outdir}/pipeline_info", mode: params.publish_dir_mode,
saveAs: { filename ->
if (filename.indexOf('.csv') > 0) filename
else null
}
output:
file 'software_versions_mqc.yaml' into ch_software_versions_yaml
file 'software_versions.csv'
script:
"""
echo $workflow.manifest.version > v_pipeline.txt
echo $workflow.nextflow.version > v_nextflow.txt
OpenMSInfo | grep -oP -m 1 '([0-9][.][0-9][.][0-9])' &> v_openms.txt
scrape_software_versions.py &> software_versions_mqc.yaml
"""
}
///////////////////////////////////////////////////////////
/* -- main functions of the workflow -- */
//////////////////////////////////////////////////////////
/*
* Step 1. Do centroiding if needed
*/
if(params.need_centroiding==true){
process process_peak_picker_openms {
label 'openms'
//label 'process_low'
tag "${mzMLFile} using ${setting_file} parameter"
publishDir "${params.outdir}/process_peak_picker_pos_openms", mode: params.publish_dir_mode, enabled: params.publishDir_intermediate
input:
set val(key), file(mzMLFile) from mzml_input
each file(setting_file) from peak_picker_param
output:
tuple val("${key}_${setting_file.baseName}"), file("output_${key}_${setting_file.baseName}/${mzMLFile}") into filter_channel
script:
"""
mkdir "output_${key}_${setting_file.baseName}"
PeakPickerHiRes -in $mzMLFile -out "output_${key}_${setting_file.baseName}/$mzMLFile" -ini $setting_file
"""
}
}else{
filter_channel=mzml_input
log.info "skipping centroiding!"
}
if(params.need_filtering==true){
process process_file_filter_openms {
label 'openms'
//label 'process_low'
tag "${mzMLFile} using ${setting_file} parameter"
publishDir "${params.outdir}/process_file_filter_openms", mode: params.publish_dir_mode, enabled: params.publishDir_intermediate
input:
set val(key), file(mzMLFile) from filter_channel
each file(setting_file) from file_filter_param
output:
tuple val("${key}_${setting_file.baseName}"), file("output_${key}_${setting_file.baseName}/${mzMLFile}") into recalibration_channel
script:
"""
mkdir "output_${key}_${setting_file.baseName}"
FileFilter -in $mzMLFile -out "output_${key}_${setting_file.baseName}/$mzMLFile" -ini $setting_file
"""
}
}else{
recalibration_channel=filter_channel
log.info "skipping filtering!"
}
/*
* Step 2. Do recalibration if needed
*/
if(params.need_recalibration==true){
process process_recalibration_openms {
label 'openms'
//label 'process_low'
tag "processing ${mzMLFile} using ${setting_file}"
publishDir "${params.outdir}/process_recalibration_openms", mode: params.publish_dir_mode, enabled: params.publishDir_intermediate
input:
set val(key), file(mzMLFile) from recalibration_channel
each file(setting_file) from peak_recalibration_param
each file(recal_masses) from recalibration_masses
output:
set val("${key}_${setting_file.baseName}"), file("output_${key}_${setting_file.baseName}/${mzMLFile}") into quant_feature_detection
set val("${key}_${setting_file.baseName}"), file("output_${key}_${setting_file.baseName}/*.png") into recal_plots
set val("${key}_${setting_file.baseName}"), file("output_${key}_${setting_file.baseName}/*.csv") into recal_info
script:
"""
mkdir "output_${key}_${setting_file.baseName}"
InternalCalibration -in $mzMLFile -out "output_${key}_${setting_file.baseName}/$mzMLFile" \\
-ini $setting_file -cal:lock_in $recal_masses -quality_control:models_plot "output_${key}_${setting_file.baseName}/${mzMLFile.baseName}_models_plot.png" \\
-quality_control:residuals_plot "output_${key}_${setting_file.baseName}/${mzMLFile.baseName}_residuals_plot.png" \\
-quality_control:residuals "output_${key}_${setting_file.baseName}/${mzMLFile.baseName}_residuals.csv" \\
-quality_control:models "output_${key}_${setting_file.baseName}/${mzMLFile.baseName}_models.csv"
"""
}
}else{
quant_feature_detection=recalibration_channel
}
/*
* Step 3. Do quantification if needed
*/
if(params.need_quantification==true){
process process_masstrace_detection_openms {
label 'openms'
//label 'process_low'
tag "processing ${mzMLFile} using ${setting_file}"
publishDir "${params.outdir}/process_masstrace_detection_pos_openms", mode: params.publish_dir_mode, enabled: params.publishDir_intermediate
input:
set val(key), file(mzMLFile) from quant_feature_detection
each file(setting_file) from feature_finder_param
output:
set val("${key}_${setting_file.baseName}"), file("output_${key}_${setting_file.baseName}/${mzMLFile}.featureXML") into quant_feature_alignment_tmp
script:
"""
mkdir "output_${key}_${setting_file.baseName}"
FeatureFinderMetabo -in $mzMLFile -out "output_${key}_${setting_file.baseName}/${mzMLFile}.featureXML" -ini $setting_file
"""
}
}else{
quant_feature_alignment_tmp=quant_feature_detection
}
/*
* Step 4. Do alignment if needed
*/
quant_feature_alignment_tmp
.groupTuple().set{alignment_input}
if(params.need_alignment==true)
{
process process_masstrace_alignment_openms {
label 'openms'
//label 'process_low'
tag "$key"
publishDir "${params.outdir}/process_masstrace_alignment_openms", mode: params.publish_dir_mode, enabled: params.publishDir_intermediate
input:
set val(key), file(mzMLFile) from alignment_input
each file(setting_file) from feature_alignment_param
output:
set val("${key}_${setting_file.baseName}"), file("output_${key}_${setting_file.baseName}/*.*") into feature_linker_input_tmp
script:
def inputs_aggregated = mzMLFile.collect{ "$it" }.join(" ")
def output_aggregated = mzMLFile.collect{ "\"output_${key}_${setting_file.baseName}/$it\"" }.join(" ")
"""
mkdir "output_${key}_${setting_file.baseName}"
MapAlignerPoseClustering -in $inputs_aggregated -out $output_aggregated -ini $setting_file
"""
}
}else{
feature_linker_input_tmp=alignment_input
}
/*
* Step 5. Do linking if needed
*/
feature_linker_input_tmp.set{feature_linker_input}
if(params.need_linking==true)
{
if(params.step_wise_linking==false)
{
process process_masstrace_linker_openms {
label 'openms'
//label 'process_low'
tag "$setting_file"
publishDir "${params.outdir}/process_masstrace_linker_openms", mode: params.publish_dir_mode, enabled: params.publishDir_intermediate
input:
set val(key), file(mzMLFile) from feature_linker_input
each file(setting_file) from feature_linker_param
output:
set val("${key}_${setting_file.baseName}"), file("output_${key}_${setting_file.baseName}/*.*") into feature_identification_input,feature_export_minimal
script:
def inputs_aggregated = mzMLFile.collect{ "$it" }.join(" ")
"""
mkdir "output_${key}_${setting_file.baseName}"
FeatureLinkerUnlabeledQT -in $inputs_aggregated -out "output_${key}_${setting_file.baseName}/linked_features.consensusXML" -ini $setting_file
"""
}
}else{
feature_linker_input.set{chunker}
process group_files_chunks {
//label 'process_low'
input:
set val(key), file(mzMLFile) from chunker
output:
set val(a), val(key), file(otfile) into chunked_output
script:
def old_key=key
def input = mzMLFile.sort{ a,b -> a[0] <=> b[0] }.collect()
def samples_in_chunks=params.number_of_files
if(samples_in_chunks<=1 || samples_in_chunks>=input.size())
{
step_wise_linking=false
return input
}
def range_of_vec = (0..input.size()-1).toList()
if(params.randomize_files==true){
range_of_vec.shuffle(new Random(params.seed_for_linking))
}
if((range_of_vec.size()%samples_in_chunks)<2)
{
while((range_of_vec.size()%samples_in_chunks)<2)
{
samples_in_chunks = (samples_in_chunks+1)
}
println 'The minimum number of samples must be one. Adjusting samples_in_chunks to '+ (samples_in_chunks)
}
def chunks=range_of_vec.collate(samples_in_chunks)
def vector_sizes=[]
def groups=[]
def ids=[]
def outfiles=[]
for(n in 0..chunks.size()-1)
{
vector_sizes.add(chunks[n].size())
aa=["chunk"+(n+1)+"_chunkend_"+old_key]*chunks[n].size()
for(i in chunks[n])
{
ids.add("chunk"+(n+1)+old_key)
outfiles.add(input[i])
}
}
a=ids
otfile=outfiles
"""
echo "dummy"
"""
}
chunked_output
.transpose().groupTuple().into{chunked_input_for_linking}
process process_masstrace_linker_openms_chunks {
label 'openms'
//label 'process_low'
tag "${key.unique().join("")}"
publishDir "${params.outdir}/process_masstrace_linker_openms_chunks", mode: params.publish_dir_mode, enabled: params.publishDir_intermediate
input:
set val(key_group),val(key), file(mzMLFile) from chunked_input_for_linking
each file(setting_file) from feature_linker_param
output:
set val("${key.unique().join("")}_${setting_file.baseName}"), file("output_${key_group}_${setting_file.baseName}/*.*"),file("setting_${key_group}_${setting_file.baseName}/*.ini") into feature_linking2_input_tmp
script:
def inputs_aggregated = mzMLFile.collect{ "$it" }.join(" ")
"""
mkdir "output_${key_group}_${setting_file.baseName}"
mkdir "setting_${key_group}_${setting_file.baseName}"
FeatureLinkerUnlabeledQT -in $inputs_aggregated -out "output_${key_group}_${setting_file.baseName}/${key_group}_linked_features.consensusXML" -ini $setting_file
cp ${setting_file} "setting_${key_group}_${setting_file.baseName}"
"""
}
feature_linking2_input_tmp.groupTuple(by:0).map{a,b,c->tuple(a,b,c[0])}.into{feature_linking2_input}
if(params.use_same_setting_for_second_linking==false)
{
process process_masstrace_linker_openms_chunks_join {
label 'openms'
//label 'process_low'
tag "$st_file"
publishDir "${params.outdir}/process_masstrace_linker_openms_chunks_join", mode: params.publish_dir_mode, enabled: params.publishDir_intermediate
input:
set val(key), file(mzMLFile),file(st_file) from feature_linking2_input
each file(setting_file) from feature_linker_param2
output:
set val("${key}_${st_file.baseName}"), file("output_${key}_${st_file.baseName}/*.*") into feature_identification_input, feature_export_minimal
script:
def inputs_aggregated = mzMLFile.collect{ "$it" }.join(" ")
"""
mkdir "output_${key}_${st_file.baseName}"
FeatureLinkerUnlabeledQT -in $inputs_aggregated -out "output_${key}_${st_file.baseName}/linked_features.consensusXML" -ini $setting_file -keep_subelements
"""
}
}else{
process process_masstrace_linker_openms_chunks_join_samesetting {
label 'openms'
//label 'process_low'
tag "${st_file.baseName}"
publishDir "${params.outdir}/process_masstrace_linker_openms_chunks_join", mode: params.publish_dir_mode, enabled: params.publishDir_intermediate
input:
set val(key), file(mzMLFile),file(st_file) from feature_linking2_input
output:
set val("${key}_${st_file.baseName}"), file("output_${key}_${st_file.baseName}/*.*") into feature_identification_input, feature_export_minimal
script:
def inputs_aggregated = mzMLFile.collect{ "$it" }.join(" ")
def setting = st_file.collect()
"""
mkdir "output_${key}_${st_file.baseName}"
FeatureLinkerUnlabeledQT -in $inputs_aggregated -out "output_${key}_${st_file.baseName}/linked_features.consensusXML" -ini $st_file -keep_subelements
"""
}
}
}
}else{
feature_linker_input.into{feature_identification_input;feature_export_minimal}
}
if(params.need_minimal_exporting==true)
{
process process_minimal_export {
label 'openms'
//label 'process_low'
tag "${key}"
publishDir "${params.outdir}/minimal_export", mode: params.publish_dir_mode, enabled: params.publishDir_intermediate
input:
set val(key), file(input) from feature_export_minimal
output:
set val("${key}_${input.baseName}"), file("output_${key}/${input.baseName}.tsv") into exit_export
"""
#!/usr/bin/env python3.9
import pyopenms as po
import numpy as np
import os
import hashlib
os.mkdir("output_${key}")
inputs="${input}"
output="output_${key}/${input.baseName}.tsv"
cmap = po.ConsensusMap()
po.ConsensusXMLFile().load("${input}", cmap)
cmap.sortBySize()
column_headers=["met_id","mz_cf","rt_cf","charge_cf","intensity_cf"]
headers_name=cmap.getColumnHeaders()
header_keys=[]
for hdr in headers_name:
header_keys.append(hdr)
column_headers.append("intensity_"+headers_name[hdr].filename)
i=0
with open(output, 'w') as f:
f.write('\\t'.join(column_headers) + '\\n')
for cfeature in cmap:
i=i+1
int_info=["NA" for number in range(len(column_headers))]
#cfeature.computeConsensus()
int_info[0]=str(i)
int_info[1]=str(cfeature.getMZ())
int_info[2]=str(cfeature.getRT())
int_info[3]=str(cfeature.getCharge())
int_info[4]=str(cfeature.getIntensity())
for fh in cfeature.getFeatureList():
int_info[header_keys.index(fh.getMapIndex())+5]=str(fh.getIntensity())
f.write('\\t'.join(int_info) + '\\n')
"""
}
}
/*
* Step 5. Do identification if needed
*/
if(params.need_identification==true)
{
process convert_library_to_idXML {
label 'openms'
//label 'process_low'
tag "$libfile"
publishDir "${params.outdir}/convert_library_to_idXML", mode: params.publish_dir_mode, enabled: params.publishDir_intermediate
echo true
input:
file libfile from identification_input
output:
file "${libfile.baseName}/${libfile.baseName}.idXML" into libsearch_database,cut_mzml_id
"""
#!/usr/bin/env python3.9
import pyopenms as py
import csv
import re
import numpy as np
import os
import xml.etree.ElementTree as ET
from pathlib import Path
os.mkdir("${libfile.baseName}")
inputs=list(filter((lambda x: re.search(r'tsv\$', x)), os.listdir()))
if len(inputs)>1:
sys.exit('Expect one tsv file')
inputs="${libfile}"
file_stem=Path(inputs).stem
header=[]
line_nr=0
use_rt="$params.identification_use_rt"=="true"
convert_to_seconds="$params.identification_convert_rt_to_seconds"=="true"
fm=[]
pm=[]
id_trace=1
with open(inputs) as tsvfile:
tsvreader = csv.reader(tsvfile, delimiter="\t")
for line in tsvreader:
if line_nr==0:
header=line
all_mzs=[i for i, x in enumerate(header) if "$params.identification_mz_column" in x]
all_rt=[i for i, x in enumerate(header) if "$params.identification_rt_column" in x]
if(use_rt==True):
rest=[i for i, x in enumerate(header) if "$params.identification_rt_column" not in x and "$params.identification_mz_column" not in x]
rt_range=[0]
else:
rest=[i for i, x in enumerate(header) if "$params.identification_mz_column" not in x]
rt_range=np.arange ($params.identification_min_rt, $params.identification_max_rt, $params.identification_scan_time)
all_rt=[i for i, x in enumerate(header) if "$params.identification_rt_column" in x]
#all_mzs=np.repeat(all_mzs,len(rt_range))
convert_to_seconds=False
else:
mz=np.float(line[all_mzs[0]])
rt_ex=np.float(line[all_rt[0]])
for i in range(0,len(rt_range)):
if(use_rt==False):
rt_ex=np.float(rt_range[i])
if(convert_to_seconds==True):
rt_ex=rt_ex*60
pid= py.PeptideIdentification()
pid.setMZ(mz)
pid.setRT(rt_ex);
pid.setIdentifier(header[all_mzs[0]]+"_"+header[all_rt[0]]+"_"+str(mz)+"_"+str(rt_ex))
#pid.setMetaValue("mz_adduct",header[all_mzs[i]])
#pid.setMetaValue("cc_adduct",header[all_ccs[i]])
#pid.setMetaValue("mz_adduct_value",line[all_mzs[i]])
#pid.setMetaValue("cc_adduct_value",line[all_ccs[i]])
pid.setIdentifier(str(id_trace))
hit=py.PeptideHit()
hit.setSequence(py.AASequence.fromString("METABOLITE"))
phit=py.ProteinHit()
phit.setAccession(str(id_trace))
pe=py.PeptideEvidence()
pe.setProteinAccession(str(id_trace));
hit.addPeptideEvidence(pe)
pid.insertHit(hit)
pid.setHits([hit])
ppp=py.ProteinIdentification()
ppp.insertHit(phit)
ppp.setIdentifier(str(id_trace))
id_trace=id_trace+1
for j in range(0,len(rest)):
pid.setMetaValue(header[rest[j]],line[rest[j]])
fm.append(pid)
pm.append(ppp)
line_nr=line_nr+1
f=py.IdXMLFile()
f.store("${libfile.baseName}/"+file_stem+".idXML",pm,fm)
"""
}
process process_masstrace_matchlib_openms {
label 'openms'
//label 'process_low'
tag "$input"
publishDir "${params.outdir}/process_masstrace_matchlib_openms", mode: params.publish_dir_mode, enabled: params.publishDir_intermediate
input:
set val(key), file(input) from feature_identification_input
each file(idfile) from libsearch_database
output:
set val("${key}_${idfile.baseName}"), file("output_${key}_${idfile.baseName}/$input") into qc_input
"""
mkdir "output_${key}_${idfile.baseName}"
IDMapper -in $input -id $idfile -out "output_${key}_${idfile.baseName}/$input" -mz_reference 'precursor' \\
-mz_measure 'ppm' -rt_tolerance $params.internal_database_rt_tolerance -mz_tolerance $params.internal_database_ppm_tolerance
"""
}
if(params.output_ranges==true)
{
process output_ranges_rawmzml {
label 'openms'
//label 'process_low'
tag "$mzml_input"
publishDir "${params.outdir}/output_ranges_rawmzml", mode: params.publish_dir_mode, enabled: params.publishDir_intermediate
stageInMode 'copy'
input:
set val(key), file(mzml_input) from cut_mzml_mzmlraw
each file(idfile) from cut_mzml_id
output:
file "${mzml_input.baseName}.mzML" into output_output_ranges_rawmzml
"""
#!/usr/bin/env python3.9
from pyopenms import *
prot_ids = []; pep_ids = [];
IdXMLFile().load("$idfile", prot_ids, pep_ids)
exp = MSExperiment()
MzMLFile().load("$mzml_input", exp)
def ppm_calc(th,exp):
return ((th-exp)/th)*1000000
scaller_mz=$params.scaller_internal_database_ppm_tolerance
ppm_tol=$params.internal_database_ppm_tolerance*scaller_mz
scaller_rt=$params.scaller_internal_database_rt_tolerance
rt_tol=$params.internal_database_rt_tolerance*scaller_rt
spec = []
for spectrum in exp:
spectrum_tr = MSSpectrum()
spectrum_tr.setRT(spectrum.getRT())
spectrum_tr.setMSLevel(1)
for peptide_id in pep_ids:
if abs(peptide_id.getRT()-spectrum.getRT())<rt_tol:
for peak in spectrum:
if abs(ppm_calc(peptide_id.getMZ(),peak.getMZ()))<ppm_tol:
spectrum_tr.push_back(peak)
if spectrum_tr.size() > 0:
spec.append(spectrum_tr)
## get max and min
max_mz=0
min_mz=10000000
max_rt=0
min_rt=10000000
for spectrum in exp:
spectrum_tr = MSSpectrum()
spectrum_tr.setRT(spectrum.getRT())
spectrum_tr.setMSLevel(1)
if spectrum.getRT()>max_rt:
max_rt=spectrum.getRT()
if spectrum.getRT()<min_rt:
min_rt=spectrum.getRT()
for peak in spectrum:
if peak.getMZ()>max_mz:
max_mz=peak.getMZ()
if peak.getMZ()<min_mz:
min_mz=peak.getMZ()
spectrum_tr = MSSpectrum()
spectrum_tr.setRT(max_rt)
spectrum_tr.setMSLevel(1)
peak = Peak1D()
peak.setMZ(max_mz)
peak.setIntensity(10000 )
spectrum_tr.push_back(peak)
peak = Peak1D()
peak.setMZ(min_mz)
peak.setIntensity(10000 )
spectrum_tr.push_back(peak)
spec.append(spectrum_tr)
spectrum_tr = MSSpectrum()
spectrum_tr.setRT(min_rt)
spectrum_tr.setMSLevel(1)
peak = Peak1D()
peak.setMZ(min_mz)
peak.setIntensity(10000 )
spectrum_tr.push_back(peak)
peak = Peak1D()
peak.setMZ(max_mz)
peak.setIntensity(10000 )
spectrum_tr.push_back(peak)
spec.append(spectrum_tr)
exp.setSpectra(spec)
MzMLFile().store("${mzml_input.baseName}.mzML", exp)
"""
}
}
}else{
qc_input=feature_identification_input
}
/*
* Step 6. Export the data
*/
if(params.need_exporting==true)
{
process process_feature_exporter_openms {
label 'openms'
//label 'process_low'
tag "$consensusXML - $key"
publishDir "${params.outdir}/process_feature_exporter_openms", mode: params.publish_dir_mode, enabled: params.publishDir_intermediate
input:
set val(key), file(consensusXML) from qc_input
output:
set val(key), file("output_${key}/${consensusXML.baseName}.tsv") into output_formatting
"""
mkdir "output_${key}"
TextExporter -in $consensusXML -out "output_${key}/${consensusXML.baseName}.tsv" -feature:add_metavalues 0 -id:add_metavalues 0 -consensus:sort_by_size
"""
}
process process_feature_output_formatting_openms {
label 'openms'
//label 'process_low'
tag "$consensusXML - $key"
publishDir "${params.outdir}/process_feature_output_formatting_openms", mode: params.publish_dir_mode, enabled: params.publishDir_intermediate
input:
set val(key), file(consensusXML) from output_formatting
output:
set val(key), file("output_${key}/*.tsv") into sum_calc
"""
#!/usr/bin/env Rscript
dir.create("output_${key}")
filepath<-"$consensusXML"
output_file_feature <- "output_${key}/${consensusXML.baseName}_quantification.tsv"
output_file_id <- "output_${key}/${consensusXML.baseName}_identification.tsv"
# Open the connection
con = file(filepath, "r")
# read line by line until the feature headers
# consensus header
consensus_header <- NA
id_header <- NA
line = readLines(con, n = 1)
con_pre <- FALSE
f_line_nr <- 0
while ( TRUE ) {
line = readLines(con, n = 1)
if ( length(line) == 0 ) {
break
}
#data[max(grep(data,pattern = "#CONSENSUS",fixed = T))]
line_split<-strsplit(line,split = "\t")[[1]]
if(line_split[1]=="#CONSENSUS")
{
consensus_header <- c("Met_ID",line_split)
}