1#!/usr/local/bin/python3.8
2
3########################################################################
4## 05/2018 Justin Rajendra
5## do stuff with info from bids json file or any json file
6
7## system libraries
8import sys, os, glob, subprocess, csv, re, argparse, signal, textwrap, json
9
10## locations of stuff
11from afnipy import afni_base, abids_lib
12from collections import OrderedDict
13
14########################################################################
15## parse command line arguments / build help
16
17## make parser with help
18parser = argparse.ArgumentParser(prog=str(sys.argv[0]),add_help=False,
19                                 formatter_class=argparse.RawDescriptionHelpFormatter,
20                                 description=textwrap.dedent('''\
21------------------------------------------
22Overview ~1~
23
24    This program extracts info from BIDS formatted json files created
25    with dcm2niix_afni or dcm2niix. This is mostly for internal use as a
26    python library. It will also extract fields from any json formatted file.
27
28Caveats ~1~
29
30    This assumes that the json file was converted from dicoms using
31    dcm2niix_afni or dcm2niix with the -b (BIDS) option. So a json file and
32    matching dataset should be present.
33
34Example ~1~
35
36    abids_json_info.py -TR -json my_bids_fmri.json
37
38------------------------------------------
39
40Options ~1~
41
42                                 '''),epilog=textwrap.dedent('''\
43------------------------------------------
44Justin Rajendra circa 05/2018
45Keep on keeping on!
46------------------------------------------
47                                 '''))
48
49## setup the groups
50bids = parser.add_argument_group('BIDS specific arguments')
51required = parser.add_argument_group('Required arguments')
52parser._optionals.title = 'Optional arguments'
53parser._action_groups.reverse()
54
55## required
56required.add_argument('-json',type=str,metavar='JSON',default="",nargs='+',
57                    help='Specify .json file(s).')
58## bids specific
59bids.add_argument('-TR',action="store_true",default=False,
60                     help=('Print the TR from the json file in seconds,'+
61                           ' from the "RepetitionTime" field.'))
62bids.add_argument('-TE',action="store_true",default=False,
63                     help=('Print out the "EchoTime" field in milliseconds '+
64                           '(the json file stores it in seconds)'))
65bids.add_argument('-TE_sec',action="store_true",default=False,
66                     help=('Print the "EchoTime" field in seconds'))
67bids.add_argument('-match_nii',action="store_true",default=False,
68                     help=('Is there a .nii or .nii.gz file that matches '+
69                           'the .json file? (1 if the dataset is loadable)'))
70## optional
71parser.add_argument('-field',type=str,metavar='STR',nargs='+',
72                     help=('Print any field or list of fields from the '+
73                           ' json file.'))
74parser.add_argument('-list_fields',action="store_true",default=False,
75                     help=('Print a list of the available fields from'+
76                           ' the .json file. (This must be the only argument'+
77                           ' specified)'))
78parser.add_argument('-help',action='help',help='Show this help and exit.')
79
80## if nothing, show help
81if len(sys.argv) == 1:
82    parser.print_help()
83    sys.exit(1)
84
85########################################################################
86## collect the arguments
87args = parser.parse_args()
88json_files = args.json
89TR = args.TR
90EchoTime = args.TE
91EchoTime_sec = args.TE_sec
92json_field = args.field
93field_list = args.list_fields
94match_nii = args.match_nii
95
96## get order of arguments that they request
97arg_list = [i for i in sys.argv if i.startswith('-')]
98arg_list.remove('-json')
99
100## make sure that field_list is not in there
101if '-list_fields' in arg_list and len(arg_list) > 1:
102    print("\nError: -list_fields must be specified ALONE!!\n")
103    sys.exit(1)
104
105########################################################################
106## go for all
107for i in json_files:
108
109    ## create the json_info object and a list to print
110    j = abids_lib.json_info(i)
111    out_list = []
112
113    ########################################################################
114    ## print out all available fields from the json file
115    if field_list:
116        j.dict = OrderedDict(j.dict)
117        for key, value in j.dict.items():
118            print(key)
119        continue
120
121    ########################################################################
122    ## loop through the order of arguments
123    for a in arg_list:
124
125        ## tr
126        if a in ['-TR'] and TR:
127            out_list.append(j.tr)
128
129        ## te ms and sec
130        if a in ['-TE'] and EchoTime:
131            out_list.append(j.te)
132        if a in ['-TE_sec'] and EchoTime_sec:
133            out_list.append(j.te_sec)
134
135        ## is there a nifti?
136        if a in ['-match_nii'] and match_nii:
137            afni_cmd = ("3dinfo -exists "+j.nii.rppv())
138            check_info = subprocess.check_output(afni_cmd,shell=True).split()
139            out_list.append(check_info[0])
140
141        ## is there a nifti?
142        if a in ['-field'] and json_field is not None:
143            for f in json_field:
144                out_list.append(j.field(f))
145
146    ## print out the combined string with spaces
147    print(' '.join(map(str,out_list)))
148
149## end dset loop
150sys.exit(0)
151
152
153