-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.py
More file actions
1169 lines (1006 loc) · 50.6 KB
/
Copy pathtools.py
File metadata and controls
1169 lines (1006 loc) · 50.6 KB
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
"""Module providing a sub commands to the client ot interact with the server"""
import argparse
import csv
import json
import logging
import sys
import urllib.parse
import shtab
import bs4
logger = logging.getLogger(__name__)
class Error(Exception):
"""docstring for Error"""
def __init__(self, message):
self.message = message
class BadArgumentError(Error):
"""docstring for BadArgumentError"""
def __init__(self, message=None):
super().__init__(message)
if message:
self.message = message
else:
self.message = "Either use --input-json OR general option --data/--data-file from pt_cli"
self.args = (f"{type(self).__name__}: {self.message}",)
sys.exit(self)
class EmptyGetError(Error):
"""docstring for EmptyGetError"""
def __init__(self, message=None):
super().__init__(message)
if message:
self.message = message
else:
self.message = "Database returned nothing, it's most likely unreachable"
self.args = (f"{type(self).__name__}: {self.message}",)
sys.exit(self)
class JSONDecodeError(Error):
"""Raised when JSON decoding fails."""
def __init__(self, context, original_exception):
message = f"Failed to decode JSON {context}: {original_exception}\n This is most likely not a JSON file or it's malformed."
super().__init__(message)
self.args = (f"{type(self).__name__}: {self.message}",)
sys.exit(self)
def safe_json_loads(data, context=""):
"""
Safely load JSON data, raising a custom error with context if decoding fails.
"""
try:
return json.loads(data)
except json.JSONDecodeError as e:
raise JSONDecodeError(context, e) from e
def unroll(string):
"""
string: includes number in the "1,3-7,9" form
return: a list if int of the form [1,3,4,5,6,7,9]
"""
elem = [e for e in string.split(',') if e]
unroll_list = []
for e in elem:
if '-' in e:
first = int(e.split('-')[0])
last = int(e.split('-')[-1])
for i in range(min(first,last), max(first,last) + 1):
unroll_list.append(int(i))
else:
unroll_list.append(int(e))
return unroll_list
class Digest:
"""
Digest is a subparser of the client in which all digestion sub-commands will be added.
"""
__tool_name__ = 'digest'
def __init__(self, subparser=argparse.ArgumentParser().add_subparsers()):
self.subparser = subparser.add_parser(self.__tool_name__, help=self.help(), add_help=True).add_subparsers()
def help(self):
"""
:return: the tool help string
"""
return f"All {self.__tool_name__} sub commands, those encapsulate all operation pulling information from the database. Use 'pt_cli {self.__tool_name__} --help' to see more details."
class Ingest:
"""
Ingest is a subparser of the client in which all digestion sub-commands will be added.
"""
__tool_name__ = 'ingest'
def __init__(self, subparser=argparse.ArgumentParser().add_subparsers()):
self.subparser = subparser.add_parser(self.__tool_name__, help=self.help(), add_help=True).add_subparsers()
def help(self):
"""
:return: the tool help string
"""
return f"All {self.__tool_name__} sub commands, those encapsulate all operation pushing information into the database. Use 'pt_cli {self.__tool_name__} --help' to see more details."
class AddCMD:
"""
AddCMD is the basic class to write pt_cli tools.
To create a new subcommand, create a child class
and write help(), arguments() and func() methods
"""
__tool_name__ = 'tool_name'
_POSTED_DATA = None
def __init__(self, connection_obj, subparser=argparse.ArgumentParser().add_subparsers()):
"""
:param connection_obj: helps to Connect and identify yourself to the Database api
:param subparser: arguments that triggers the tool, The default is set here to help the autocomplete
"""
self.connection_obj = connection_obj
self.subparser = subparser
self.parser = subparser.add_parser(self.__tool_name__, help=self.help(), add_help=True)
self.arguments()
self.parser.set_defaults(func=self.func)
self.project_id = self.connection_obj.project_id
self.parsed_args = None
def data(self, error_if_missing=False):
"""
:param error_if_missing: Will raise Error when true and no
data is provided
:return: The data to be posted to the server. This will be a
string coming from a user provided file or directly from the
command line
"""
if self._POSTED_DATA is None:
if self.parsed_args.data:
self._POSTED_DATA = self.parsed_args.data
elif self.parsed_args.data_file:
self._POSTED_DATA = self.parsed_args.data_file.read()
self.parsed_args.data_file.close()
elif error_if_missing:
raise BadArgumentError(f'Data inputs is needed for the "{self.__tool_name__}" subcommand')
return self._POSTED_DATA
def post(self, path, data):
"""
:return: the post query on the server
"""
return self.connection_obj.post(path, data=data)
def get(self, path):
"""
:return: the get query on the server
"""
return self.connection_obj.get(path)
def help(self):
"""
:return: the tool help string
"""
raise NotImplementedError
def arguments(self):
"""
Add your arguments to self.parser here.
:return:
"""
def func(self, parsed_args):
"""
This function is the entry point of the tool/object. It receives parsed arguments.
It needs to be reimplemented in children classes in this way:
def func(self, parsed_args):
super().func(parsed_args)
:param parsed_args: arguments form the command lines
:return: None
"""
self.parsed_args = parsed_args
class ReadsetFile(AddCMD):
"""
ReadsetFile is a sub-command of Digest subparser using base AddCMD class
"""
__tool_name__ = 'readset_file'
READSET_HEADER = [
"Sample",
"Readset",
"LibraryType",
"RunType",
"Run",
"Lane",
"Adapter1",
"Adapter2",
"QualityOffset",
"BED",
"FASTQ1",
"FASTQ2",
"BAM"
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.parsed_input = None
self.output_file = None
def help(self):
return "Will return a Genpipes readset file in a tsv format. /!\\ Either use --input-json OR --sample_<name|id>/--readset_<name|id> + --endpoint arguments"
def arguments(self):
self.parser.add_argument('--output', '-o', default="readset_file.tsv", help="Name of readset file returned (Default: readset_file.tsv)")
self.parser.add_argument('--specimen_name', help='Specimen Name to be selected', nargs='+')
self.parser.add_argument('--sample_name', help='Sample Name to be selected', nargs='+')
self.parser.add_argument('--readset_name', help='Readset Name to be selected', nargs='+')
self.parser.add_argument('--specimen_id', help='Specimen ID to be selected', nargs='+')
self.parser.add_argument('--sample_id', help='Sample ID to be selected', nargs='+')
self.parser.add_argument('--readset_id', help='Readset ID to be selected', nargs='+')
self.parser.add_argument('--nucleic_acid_type', help="nucleic_acid_type data type", required=False, choices=["DNA", "RNA"])
self.parser.add_argument('--endpoint', help="Endpoint in which data is located")
self.parser.add_argument('--input-json', help="Json file with sample/readset and endpoint to be selected", type=argparse.FileType('r')).complete = shtab.FILE
@property
def readset_file(self):
'''
:return: list of readset lines of GenPipes of the API call for digest_readset_file
'''
json_payload = json.dumps(self.parsed_input)
encoded_json = urllib.parse.quote(json_payload)
return self.get(f'project/{self.project_id}/digest_readset_file?json={encoded_json}')
def jsonify_input(self, parsed_args):
'''
:return: jsonified input args
'''
json = {
"location_endpoint": parsed_args.endpoint,
"experiment_nucleic_acid_type": parsed_args.nucleic_acid_type
}
if parsed_args.specimen_name:
json["specimen_name"] = list(parsed_args.specimen_name)
if parsed_args.specimen_id:
if len(parsed_args.specimen_id) == 1:
json["specimen_id"] = unroll(parsed_args.specimen_id[0])
else:
json["specimen_id"] = parsed_args.specimen_id
if parsed_args.sample_name:
json["sample_name"] = list(parsed_args.sample_name)
if parsed_args.sample_id:
if len(parsed_args.sample_id) == 1:
json["sample_id"] = unroll(parsed_args.sample_id[0])
else:
json["sample_id"] = parsed_args.sample_id
if parsed_args.readset_name:
json["readset_name"] = list(parsed_args.readset_name)
if parsed_args.readset_id:
if len(parsed_args.readset_id) == 1:
json["readset_id"] = unroll(parsed_args.readset_id[0])
else:
json["readset_id"] = parsed_args.readset_id
return json
def json_to_readset_file(self):
"""
Writes the output file
"""
readset_file = self.readset_file
if not readset_file:
raise EmptyGetError
readset_file = readset_file["DB_ACTION_OUTPUT"]
if not readset_file:
sys.stdout.write("Nothing returned.")
return
with open(self.output_file, "w", encoding="utf-8") as out_readset_file:
tsv_writer = csv.DictWriter(out_readset_file, delimiter='\t', fieldnames=self.READSET_HEADER)
tsv_writer.writeheader()
for readset_line in readset_file:
tsv_writer.writerow(readset_line)
logger.info(f"Readset file written to {self.output_file}")
def func(self, parsed_args):
super().func(parsed_args)
# Dev case when using --data-file
self.parsed_input = self.data()
# When --data-file is empty
if not self.parsed_input:
# --input-json alone
if parsed_args.input_json:
self.parsed_input = parsed_args.input_json.read()
parsed_args.input_json.close()
# --sample_<name|id>/--readset_<name|id> + --endpoint + --nucleic_acid_type
elif (parsed_args.specimen_name or parsed_args.sample_name or parsed_args.readset_name or parsed_args.specimen_id or parsed_args.sample_id or parsed_args.readset_id) and parsed_args.endpoint and parsed_args.nucleic_acid_type:
self.parsed_input = json.dumps(self.jsonify_input(parsed_args), ensure_ascii=False, indent=4)
else:
raise BadArgumentError("Either use --input-json OR --specimen_<name|id>/--sample_<name|id>/--readset_<name|id> + --endpoint + --nucleic_acid_type arguments.")
self.output_file = parsed_args.output
self.json_to_readset_file()
class PairFile(AddCMD):
"""
PairFile is a sub-command of Digest subparser using base AddCMD class
"""
__tool_name__ = 'pair_file'
PAIR_HEADER = [
"Specimen",
"Sample_N",
"Sample_T"
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.parsed_input = None
self.output_file = None
def help(self):
return "Will return a Genpipes pair file in a csv format. /!\\ Either use the --input-json or the --sample/--readset + --endpoint arguments"
def arguments(self):
self.parser.add_argument('--output', '-o', default="pair_file.csv", help="Name of pair file returned (Default: pair_file.csv)")
self.parser.add_argument('--specimen_name', help='Specimen Name to be selected', nargs='+')
self.parser.add_argument('--sample_name', help='Sample Name to be selected', nargs='+')
self.parser.add_argument('--readset_name', help='Readset Name to be selected', nargs='+')
self.parser.add_argument('--specimen_id', help='Specimen ID to be selected', nargs='+')
self.parser.add_argument('--sample_id', help='Sample ID to be selected', nargs='+')
self.parser.add_argument('--readset_id', help='Readset ID to be selected', nargs='+')
self.parser.add_argument('--nucleic_acid_type', help="nucleic_acid_type data type", required=False, choices=["DNA", "RNA"])
self.parser.add_argument('--endpoint', help="Without effect, only here to be able to use the same command as the one used with 'pt_cli digest readset_file'")
self.parser.add_argument('--input-json', help="Json file with sample/readset and endpoint to be selected", type=argparse.FileType('r')).complete = shtab.FILE
@property
def pair_file(self):
'''
Returns a list of pair lines of GenPipes of the API call for digest_pair_file
:return:
'''
json_payload = json.dumps(self.parsed_input)
encoded_json = urllib.parse.quote(json_payload)
return self.get(f'project/{self.project_id}/digest_pair_file?json={encoded_json}')
def jsonify_input(self, parsed_args):
'''
:return: jsonified input args
'''
json = {
"location_endpoint": parsed_args.endpoint,
"experiment_nucleic_acid_type": parsed_args.nucleic_acid_type
}
if parsed_args.specimen_name:
json["specimen_name"] = list(parsed_args.specimen_name)
if parsed_args.specimen_id:
if len(parsed_args.specimen_id) == 1:
json["specimen_id"] = unroll(parsed_args.specimen_id[0])
else:
json["specimen_id"] = parsed_args.specimen_id
if parsed_args.sample_name:
json["sample_name"] = list(parsed_args.sample_name)
if parsed_args.sample_id:
if len(parsed_args.sample_id) == 1:
json["sample_id"] = unroll(parsed_args.sample_id[0])
else:
json["sample_id"] = parsed_args.sample_id
if parsed_args.readset_name:
json["readset_name"] = list(parsed_args.readset_name)
if parsed_args.readset_id:
if len(parsed_args.readset_id) == 1:
json["readset_id"] = unroll(parsed_args.readset_id[0])
else:
json["readset_id"] = parsed_args.readset_id
return json
def json_to_pair_file(self):
"""
Writes the pair file
"""
pair_file = self.pair_file
if not pair_file:
raise EmptyGetError
pair_file = pair_file["DB_ACTION_OUTPUT"]
if not pair_file:
sys.stdout.write("Nothing returned.")
return
with open(self.output_file, "w", encoding="utf-8") as out_pair_file:
tsv_writer = csv.DictWriter(out_pair_file, delimiter=',', fieldnames=self.PAIR_HEADER)
# tsv_writer.writeheader()
for pair_line in pair_file:
tsv_writer.writerow(pair_line)
logger.info(f"Pair file written to {self.output_file}")
def func(self, parsed_args):
super().func(parsed_args)
# Dev case when using --data-file
self.parsed_input = self.data()
# When --data-file is empty
if not self.parsed_input:
# --input-json alone
if parsed_args.input_json:
self.parsed_input = parsed_args.input_json.read()
parsed_args.input_json.close()
# --sample_<name|id>/--readset_<name|id> + --endpoint + --nucleic_acid_type
elif (parsed_args.specimen_name or parsed_args.sample_name or parsed_args.readset_name or parsed_args.specimen_id or parsed_args.sample_id or parsed_args.readset_id) and parsed_args.endpoint and parsed_args.nucleic_acid_type:
self.parsed_input = json.dumps(self.jsonify_input(parsed_args), ensure_ascii=False, indent=4)
else:
raise BadArgumentError("Either use --input-json OR --specimen_<name|id>/--sample_<name|id>/--readset_<name|id> + --endpoint + --nucleic_acid_type arguments.")
# Checking if odd amount of sample/readset is given as input and Warn user about potential malformed file
loaded_json = safe_json_loads(self.parsed_input)
if loaded_json.get("sample_name") and not (len(loaded_json["sample_name"]) % 2) == 0:
logger.warning("An odd amount of 'sample_name' has been given, the pair file won't be properly formatted for GenPipes!")
if loaded_json.get("sample_id") and not (len(loaded_json["sample_id"]) % 2) == 0:
logger.warning("An odd amount of 'sample_id' has been given, the pair file won't be properly formatted for GenPipes!")
if loaded_json.get("readset_name") and not (len(loaded_json["readset_name"]) % 2) == 0:
logger.warning("An odd amount of 'readset_name' has been given, the pair file won't be properly formatted for GenPipes!")
if loaded_json.get("readset_id") and not (len(loaded_json["readset_id"]) % 2) == 0:
logger.warning("An odd amount of 'readset_id' has been given, the pair file won't be properly formatted for GenPipes!")
self.output_file = parsed_args.output
self.json_to_pair_file()
class Unanalyzed(AddCMD):
"""
Unanalyzed is a sub-command of Digest subparser using base AddCMD class
"""
__tool_name__ = 'unanalyzed'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.parsed_input = None
self.output_file = None
def help(self):
return "Will return unanalyzed Samples name/ID or Readsets name/ID"
def arguments(self):
self.parser.add_argument('--sample_name', help='Sample Name will be selected', action='store_true', default=False)
self.parser.add_argument('--readset_name', help='Readset Name will be selected', action='store_true', default=False)
self.parser.add_argument('--sample_id', help='Sample ID will be selected', action='store_true', default=False)
self.parser.add_argument('--readset_id', help='Readset ID will be selected', action='store_true', default=False)
self.parser.add_argument('--run_name', help="Run Name in which Samples/Readsets are", required=False, default=None)
self.parser.add_argument('--run_id', help="Run ID in which Samples/Readsets are", required=False, default=None)
self.parser.add_argument('--experiment_nucleic_acid_type', help="Experiment nucleic_acid_type characterizing the Samples/Readsets (RNA or DNA)", required=True)
self.parser.add_argument('--endpoint', help="Endpoint in which data is located", required=True)
self.parser.add_argument('--output', '-o', help="Name of output file (Default: terminal), formatted as Json file with sample/readset and endpoint")
# self.parser.add_argument('--input-json', help="Json file with all parameters")
@property
def unanalyzed(self):
'''
Returns a list of pair lines of GenPipes of the API call for digest_unanalyzed
:return:
'''
json_payload = json.dumps(self.parsed_input)
encoded_json = urllib.parse.quote(json_payload)
return self.get(f'project/{self.project_id}/digest_unanalyzed?json={encoded_json}')
def jsonify_input(self, parsed_args):
'''
:return: jsonified input args
'''
json = {
"sample_name": parsed_args.sample_name,
"sample_id": parsed_args.sample_id,
"readset_name": parsed_args.readset_name,
"readset_id": parsed_args.readset_id,
"run_name": parsed_args.run_name,
"run_id": parsed_args.run_id,
"experiment_nucleic_acid_type": parsed_args.experiment_nucleic_acid_type,
"location_endpoint": parsed_args.endpoint,
}
return json
def json_to_unanalyzed(self):
"""
Writes the output file/prints to terminal
"""
unanalyzed = self.unanalyzed
if not self.output_file:
if isinstance(unanalyzed, str):
soup = bs4.BeautifulSoup(unanalyzed, features="html5lib")
return sys.stdout.write(soup.get_text())
# else case, not explicitely written
return sys.stdout.write(json.dumps(unanalyzed))
if not unanalyzed:
raise EmptyGetError
with open(self.output_file, "w", encoding="utf-8") as out_pair_file:
json.dump(unanalyzed, out_pair_file, ensure_ascii=False, indent=4)
logger.info(f"Unanalyzed file written to {self.output_file}")
def func(self, parsed_args):
super().func(parsed_args)
# Dev case when using --data-file
self.parsed_input = self.data()
# When --data-file is empty
if not self.parsed_input:
if parsed_args.sample_name or parsed_args.readset_name or parsed_args.sample_id or parsed_args.readset_id:
self.parsed_input = json.dumps(self.jsonify_input(parsed_args), ensure_ascii=False, indent=4)
else:
raise BadArgumentError("Use at least one of the following --sample_<name|id>/--readset_<name|id> argument.")
self.output_file = parsed_args.output
self.json_to_unanalyzed()
class Delivery(AddCMD):
"""
Delivery is a sub-command of Digest subparser using base AddCMD class
"""
__tool_name__ = 'delivery'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.parsed_input = None
self.output_file = None
def help(self):
return "Will return delivery Samples name/ID or Readsets name/ID"
def arguments(self):
self.parser.add_argument('--specimen_name', help='Specimen Name to be selected', nargs='+')
self.parser.add_argument('--sample_name', help='Sample Name to be selected', nargs='+')
self.parser.add_argument('--readset_name', help='Readset Name to be selected', nargs='+')
self.parser.add_argument('--specimen_id', help='Specimen ID to be selected', nargs='+')
self.parser.add_argument('--sample_id', help='Sample ID to be selected', nargs='+')
self.parser.add_argument('--readset_id', help='Readset ID to be selected', nargs='+')
self.parser.add_argument('--experiment_nucleic_acid_type', help="Experiment nucleic_acid_type characterizing the Samples/Readsets (RNA or DNA)", required=True)
self.parser.add_argument('--endpoint', help="Endpoint in which data is located", required=True)
self.parser.add_argument('--output', '-o', help="Name of output file (Default: terminal), formatted as Json file with sample/readset and endpoint")
@property
def delivery(self):
'''
Returns a list of pair lines of GenPipes of the API call for digest_delivery
:return:
'''
json_payload = json.dumps(self.parsed_input)
encoded_json = urllib.parse.quote(json_payload)
return self.get(f'project/{self.project_id}/digest_delivery?json={encoded_json}')
def jsonify_input(self, parsed_args):
'''
:return: jsonified input args
'''
json = {
"location_endpoint": parsed_args.endpoint,
"experiment_nucleic_acid_type": parsed_args.experiment_nucleic_acid_type
}
if parsed_args.specimen_name:
json["specimen_name"] = list(parsed_args.specimen_name)
if parsed_args.specimen_id:
if len(parsed_args.specimen_id) == 1:
json["specimen_id"] = unroll(parsed_args.specimen_id[0])
else:
json["specimen_id"] = parsed_args.specimen_id
if parsed_args.sample_name:
json["sample_name"] = list(parsed_args.sample_name)
if parsed_args.sample_id:
if len(parsed_args.sample_id) == 1:
json["sample_id"] = unroll(parsed_args.sample_id[0])
else:
json["sample_id"] = parsed_args.sample_id
if parsed_args.readset_name:
json["readset_name"] = list(parsed_args.readset_name)
if parsed_args.readset_id:
if len(parsed_args.readset_id) == 1:
json["readset_id"] = unroll(parsed_args.readset_id[0])
else:
json["readset_id"] = parsed_args.readset_id
return json
def json_to_delivery(self):
"""
Writes the output file/prints to terminal
"""
delivery = self.delivery
if not self.output_file:
if isinstance(delivery, str):
soup = bs4.BeautifulSoup(delivery, features="html5lib")
return sys.stdout.write(soup.get_text())
# else case, not explicitely written
return sys.stdout.write(json.dumps(delivery["DB_ACTION_OUTPUT"]))
if not delivery:
raise EmptyGetError
with open(self.output_file, "w", encoding="utf-8") as out_pair_file:
json.dump(delivery["DB_ACTION_OUTPUT"], out_pair_file, ensure_ascii=False, indent=4)
logger.info(f"Delivery file written to {self.output_file}")
def func(self, parsed_args):
super().func(parsed_args)
# Dev case when using --data-file
self.parsed_input = self.data()
# When --data-file is empty
if not self.parsed_input:
if parsed_args.specimen_name or parsed_args.sample_name or parsed_args.readset_name or parsed_args.specimen_id or parsed_args.sample_id or parsed_args.readset_id:
self.parsed_input = self.jsonify_input(parsed_args)
else:
raise BadArgumentError("Use at least one of the following --specimen_<name|id>/--sample_<name|id>/--readset_<name|id> argument.")
self.output_file = parsed_args.output
self.json_to_delivery()
class RunProcessing(AddCMD):
"""
RunProcessing is a sub-command of Ingest subparser using base AddCMD class
"""
__tool_name__ = 'run_processing'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.run_processing_input = None
def help(self):
return "Will push Run Processing data into the database"
def arguments(self):
self.parser.add_argument('--input-json', help="Json file containing all information to add data from Run Processing into the database", type=argparse.FileType('r')).complete = shtab.FILE
@property
def run_processing(self):
'''
:return: list of readset lines of GenPipes of the API call for ingest_run_processing
'''
return self.post(f'project/{self.project_id}/ingest_run_processing', data=self.run_processing_input)
def func(self, parsed_args):
super().func(parsed_args)
# Dev case when using --data-file
self.run_processing_input = self.data()
# When --data-file is empty
if not self.run_processing_input and parsed_args.input_json:
self.run_processing_input = parsed_args.input_json.read()
file_name = parsed_args.input_json.name
parsed_args.input_json.close()
payload = safe_json_loads(self.run_processing_input)
payload["_source_file"] = file_name
self.run_processing_input = json.dumps(payload)
if not self.run_processing_input:
raise BadArgumentError
response = self.run_processing
if isinstance(response, str) and response.startswith("Welcome"):
pass
else:
sys.stdout.write("\n".join([json.dumps(i) for i in response["DB_ACTION_OUTPUT"]]))
class Transfer(AddCMD):
"""
Transfer is a sub-command of Ingest subparser using base AddCMD class
"""
__tool_name__ = 'transfer'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.transfer_input = None
self.output_file = None
def help(self):
return "Will push a Transfer of data (copy, rsync, mv, etc) into the database"
def arguments(self):
self.parser.add_argument('--input-json', help="Json file containing all information to add data from a Transfer into the database", type=argparse.FileType('r')).complete = shtab.FILE
@property
def transfer(self):
'''
:return: list of readset lines of GenPipes of the API call for ingest_transfer
'''
return self.post(f'project/{self.project_id}/ingest_transfer', data=self.transfer_input)
def func(self, parsed_args):
super().func(parsed_args)
# Dev case when using --data-file
self.transfer_input = self.data()
# When --data-file is empty
if not self.transfer_input and parsed_args.input_json:
self.transfer_input = parsed_args.input_json.read()
file_name = parsed_args.input_json.name
parsed_args.input_json.close()
payload = safe_json_loads(self.transfer_input)
payload["_source_file"] = file_name
self.transfer_input = json.dumps(payload)
if not self.transfer_input:
raise BadArgumentError
response = self.transfer
if isinstance(response, str) and response.startswith("Welcome"):
pass
else:
sys.stdout.write("\n".join([json.dumps(i) for i in response["DB_ACTION_OUTPUT"]]))
class GenPipes(AddCMD):
"""
GenPipes is a sub-command of Ingest subparser using base AddCMD class
"""
__tool_name__ = 'genpipes'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.genpipes_input = None
self.output_file = None
def help(self):
return "Will push a GenPipes analysis into the database"
def arguments(self):
self.parser.add_argument('--input-json', help="Json file containing all information to add a GenPipes analysis into the database", type=argparse.FileType('r')).complete = shtab.FILE
@property
def genpipes(self):
'''
:return: list of readset lines of GenPipes of the API call for ingest_genpipes
'''
return self.post(f'project/{self.project_id}/ingest_genpipes', data=self.genpipes_input)
def func(self, parsed_args):
super().func(parsed_args)
# Dev case when using --data-file
self.genpipes_input = self.data()
# When --data-file is empty
if not self.genpipes_input and parsed_args.input_json:
self.genpipes_input = parsed_args.input_json.read()
file_name = parsed_args.input_json.name
parsed_args.input_json.close()
payload = safe_json_loads(self.genpipes_input)
payload["_source_file"] = file_name
self.genpipes_input = json.dumps(payload)
if not self.genpipes_input:
raise BadArgumentError
response = self.genpipes
if isinstance(response, str) and response.startswith("Welcome"):
pass
else:
sys.stdout.write("\n".join([json.dumps(i) for i in response["DB_ACTION_OUTPUT"]]))
class DeliveryIngest(AddCMD):
"""
DeliveryIngest is a sub-command of Ingest subparser using base AddCMD class
"""
__tool_name__ = 'delivery'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.delivery_input = None
def help(self):
return "Will push a Delivery of data into the database"
def arguments(self):
self.parser.add_argument('--input-json', help="Json file containing all information to add data from a Delivery into the database", type=argparse.FileType('r')).complete = shtab.FILE
self.parser.add_argument('--delete', action='store_true', default=True, help="By default, delivery will delete the files from their original location after transfer. If you want to keep the original files, set this flag to False.")
@property
def delivery(self):
'''
:return: list of readset lines of GenPipes of the API call for ingest_delivery
'''
return self.post(f'project/{self.project_id}/ingest_delivery', data=self.delivery_input)
def func(self, parsed_args):
super().func(parsed_args)
# Dev case when using --data-file
self.delivery_input = self.data()
# When --data-file is empty
if not self.delivery_input and parsed_args.input_json:
self.delivery_input = parsed_args.input_json.read()
file_name = parsed_args.input_json.name
parsed_args.input_json.close()
payload = safe_json_loads(self.delivery_input)
payload["_source_file"] = file_name
self.delivery_input = json.dumps(payload)
if not self.delivery_input:
raise BadArgumentError
self.delivery_input = safe_json_loads(self.delivery_input)
self.delivery_input["delete"] = parsed_args.delete
self.delivery_input = json.dumps(self.delivery_input, ensure_ascii=False, indent=4)
response = self.delivery
if isinstance(response, str) and response.startswith("Welcome"):
pass
else:
sys.stdout.write("\n".join([json.dumps(i) for i in response["DB_ACTION_OUTPUT"]]))
class Edit(AddCMD):
"""
Edit is a sub-command base AddCMD class
"""
__tool_name__ = 'edit'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.edit_input = None
def help(self):
return "Will Edit an existing entry of the database. /!\\ This action is not reversible."
def arguments(self):
self.parser.add_argument('--input-json', help="Json file containing all information to be edited on the database", type=argparse.FileType('r')).complete = shtab.FILE
self.parser.add_argument('--dry_run', action='store_true', default=False, help="If set, will only print the entries that will be curated without actually curating them.")
@property
def edit(self):
'''
:return: list of readset lines of GenPipes of the API call for ingest_edit
'''
return self.post('modification/edit', data=self.edit_input)
def func(self, parsed_args):
super().func(parsed_args)
# Dev case when using --data-file
self.edit_input = self.data()
# When --data-file is empty
if not self.edit_input and parsed_args.input_json:
self.edit_input = parsed_args.input_json.read()
parsed_args.input_json.close()
if not self.edit_input:
raise BadArgumentError
# Add dry_run flag if set
if parsed_args.dry_run:
self.edit_input = safe_json_loads(self.edit_input)
self.edit_input["dry_run"] = True
self.edit_input = json.dumps(self.edit_input, ensure_ascii=False, indent=4)
response = self.edit
if isinstance(response, str) and response.startswith("Welcome"):
pass
else:
sys.stdout.write("\n".join(response["DB_ACTION_OUTPUT"]))
class Delete(AddCMD):
"""
Delete is a sub-command base AddCMD class
"""
__tool_name__ = 'delete'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.delete_input = None
def help(self):
return "Will Delete an existing entry of the database: set deleted flag to True"
def arguments(self):
self.parser.add_argument('--input-json', help="Json file containing all information to be deleted on the database", type=argparse.FileType('r')).complete = shtab.FILE
self.parser.add_argument('--dry_run', action='store_true', default=False, help="If set, will only print the entries that will be curated without actually curating them.")
self.parser.add_argument('--cascade_down', help="Cascade delete, will delete all children of the entry and orphan", action='store_true', default=False)
self.parser.add_argument('--cascade_up', help="Cascade delete, will delete all parents of the entry and orphan", action='store_true', default=False)
self.parser.add_argument('--cascade', help="Cascade delete, will delete all parents and children of the entry and orphan", action='store_true', default=False)
@property
def delete(self):
'''
:return: list of readset lines of GenPipes of the API call for ingest_delete
'''
return self.post('modification/delete', data=self.delete_input)
def func(self, parsed_args):
super().func(parsed_args)
# Dev case when using --data-file
self.delete_input = self.data()
# When --data-file is empty
if not self.delete_input and parsed_args.input_json:
self.delete_input = parsed_args.input_json.read()
parsed_args.input_json.close()
if not self.delete_input:
raise BadArgumentError
# Add dry_run flag if set
if parsed_args.dry_run:
self.delete_input = safe_json_loads(self.delete_input)
self.delete_input["dry_run"] = True
self.delete_input = json.dumps(self.delete_input, ensure_ascii=False, indent=4)
# Adding cascade options to the input
if parsed_args.cascade_down:
self.delete_input = safe_json_loads(self.delete_input)
self.delete_input["cascade_down"] = True
self.delete_input = json.dumps(self.delete_input, ensure_ascii=False, indent=4)
elif parsed_args.cascade_up:
self.delete_input = safe_json_loads(self.delete_input)
self.delete_input["cascade_up"] = True
self.delete_input = json.dumps(self.delete_input, ensure_ascii=False, indent=4)
elif parsed_args.cascade:
self.delete_input = safe_json_loads(self.delete_input)
self.delete_input["cascade"] = True
self.delete_input = json.dumps(self.delete_input, ensure_ascii=False, indent=4)
response = self.delete
if isinstance(response, str) and response.startswith("Welcome"):
pass
else:
sys.stdout.write("\n".join(response["DB_ACTION_OUTPUT"]))
class UnDelete(AddCMD):
"""
UnDelete is a sub-command base AddCMD class
"""
__tool_name__ = 'undelete'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.undelete_input = None
def help(self):
return "Will UnDelete an existing entry of the database: set deleted flag to False"
def arguments(self):
self.parser.add_argument('--input-json', help="Json file containing all information to be undeleted on the database", type=argparse.FileType('r')).complete = shtab.FILE
self.parser.add_argument('--dry_run', action='store_true', default=False, help="If set, will only print the entries that will be curated without actually curating them.")
self.parser.add_argument('--cascade_down', help="Cascade undelete, will undelete all children of the entry and orphan", action='store_true', default=False)
self.parser.add_argument('--cascade_up', help="Cascade undelete, will undelete all parents of the entry and orphan", action='store_true', default=False)
self.parser.add_argument('--cascade', help="Cascade undelete, will undelete all parents and children of the entry and orphan", action='store_true', default=False)
@property
def undelete(self):
'''
:return: list of readset lines of GenPipes of the API call for ingest_undelete
'''
return self.post('modification/undelete', data=self.undelete_input)
def func(self, parsed_args):
super().func(parsed_args)
# Dev case when using --data-file
self.undelete_input = self.data()
# When --data-file is empty
if not self.undelete_input and parsed_args.input_json:
self.undelete_input = parsed_args.input_json.read()
parsed_args.input_json.close()
if not self.undelete_input:
raise BadArgumentError
# Add dry_run flag if set
if parsed_args.dry_run:
self.undelete_input = safe_json_loads(self.undelete_input)
self.undelete_input["dry_run"] = True
self.undelete_input = json.dumps(self.undelete_input, ensure_ascii=False, indent=4)
# Adding cascade options to the input
if parsed_args.cascade_down:
self.undelete_input = safe_json_loads(self.undelete_input)
self.undelete_input["cascade_down"] = True
self.undelete_input = json.dumps(self.undelete_input, ensure_ascii=False, indent=4)
elif parsed_args.cascade_up:
self.undelete_input = safe_json_loads(self.undelete_input)
self.undelete_input["cascade_up"] = True
self.undelete_input = json.dumps(self.undelete_input, ensure_ascii=False, indent=4)
elif parsed_args.cascade:
self.undelete_input = safe_json_loads(self.undelete_input)
self.undelete_input["cascade"] = True
self.undelete_input = json.dumps(self.undelete_input, ensure_ascii=False, indent=4)
response = self.undelete
if isinstance(response, str) and response.startswith("Welcome"):
pass
else:
sys.stdout.write("\n".join(response["DB_ACTION_OUTPUT"]))
class Deprecate(AddCMD):
"""
Deprecate is a sub-command base AddCMD class
"""
__tool_name__ = 'deprecate'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.deprecate_input = None
def help(self):
return "Will Deprecate an existing entry of the database: set deprecated flag to True"
def arguments(self):
self.parser.add_argument('--input-json', help="Json file containing all information to be deprecated on the database", type=argparse.FileType('r')).complete = shtab.FILE
self.parser.add_argument('--dry_run', action='store_true', default=False, help="If set, will only print the entries that will be curated without actually curating them.")
self.parser.add_argument('--cascade_down', help="Cascade undelete, will undelete all children of the entry and orphan", action='store_true', default=False)
self.parser.add_argument('--cascade_up', help="Cascade undelete, will undelete all parents of the entry and orphan", action='store_true', default=False)
self.parser.add_argument('--cascade', help="Cascade undelete, will undelete all parents and children of the entry and orphan", action='store_true', default=False)
@property
def deprecate(self):
'''
:return: list of readset lines of GenPipes of the API call for ingest_deprecate