-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathbidsmri2nidm.py
executable file
·1491 lines (1379 loc) · 64.5 KB
/
bidsmri2nidm.py
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 python
# **************************************************************************************
# **************************************************************************************
# bidsmri2nidm.py
# License: Apache License, Version 2.0
# **************************************************************************************
# **************************************************************************************
# Date: 10-2-17 Coded by: David Keator ([email protected])
# Filename: bidsmri2nidm.py
#
# Program description: This program will convert a BIDS MRI dataset to a NIDM-Experiment
# RDF document. It will parse phenotype information and simply store variables/values
# and link to the associated json data dictionary file.
#
# **************************************************************************************
# Development environment: Python - PyCharm IDE
#
# **************************************************************************************
# System requirements: Python 3.X
# Libraries: pybids, numpy, matplotlib, pandas, scipy, math, dateutil, datetime,argparse,
# os,sys,getopt,csv
# **************************************************************************************
# Programmer comments:
#
#
# **************************************************************************************
# **************************************************************************************
from argparse import ArgumentParser, RawTextHelpFormatter
import csv
import glob
# Python program to find SHA256 hash string of a file
import hashlib
from io import StringIO
import json
import logging
import os
from os.path import isfile, join
import bids
from pandas import DataFrame
from prov.model import PROV_TYPE, Namespace, QualifiedName
from rdflib import RDF, Graph, Literal, URIRef
from nidm.core import BIDS_Constants, Constants
from nidm.experiment import (
AcquisitionObject,
AssessmentAcquisition,
AssessmentObject,
MRAcquisition,
MRObject,
Project,
Session,
)
from nidm.experiment.Utils import (
add_attributes_with_cde,
addGitAnnexSources,
map_variables_to_terms,
)
def getRelPathToBIDS(filepath, bids_root):
"""
This function returns a relative file link that is relative to the BIDS root directory.
:param filename: absolute path + file
:param bids_root: absolute path to BIDS directory
:return: relative path to file, relative to BIDS root
"""
path, file = os.path.split(filepath)
relpath = path.replace(bids_root, "")
return os.path.join(relpath, file)
def getsha512(filename):
"""
This function computes the SHA512 sum of a file
:param filename: path+filename of file to compute SHA512 sum for
:return: hexadecimal sha512 sum of file.
"""
sha512_hash = hashlib.sha512()
with open(filename, "rb") as f:
# Read and update hash string value in blocks of 4K
for byte_block in iter(lambda: f.read(4096), b""):
sha512_hash.update(byte_block)
return sha512_hash.hexdigest()
def main():
parser = ArgumentParser(
description="""This program will represent a BIDS MRI dataset as a NIDM RDF document and provide user with opportunity to annotate
the dataset (i.e. create sidecar files) and associate selected variables with broader concepts to make datasets more
FAIR. \n\n
Note, you must obtain an API key to Interlex by signing up for an account at scicrunch.org then going to My Account
and API Keys. Then set the environment variable INTERLEX_API_KEY with your key. """,
formatter_class=RawTextHelpFormatter,
)
parser.add_argument(
"-d",
dest="directory",
required=True,
help="Full path to BIDS dataset directory",
)
parser.add_argument(
"-jsonld",
"--jsonld",
action="store_true",
help="If flag set, output is json-ld not TURTLE",
)
# parser.add_argument('-png', '--png', action='store_true', help='If flag set, tool will output PNG file of NIDM graph')
parser.add_argument(
"-bidsignore",
"--bidsignore",
action="store_true",
default=False,
help="If flag set, tool will add NIDM-related files to .bidsignore file",
)
parser.add_argument(
"-no_concepts",
"--no_concepts",
action="store_true",
default=False,
help="If flag set, tool will no do concept mapping",
)
# adding argument group for var->term mappings
mapvars_group = parser.add_argument_group("map variables to terms arguments")
mapvars_group.add_argument(
"-json_map",
"--json_map",
dest="json_map",
required=False,
default=False,
help="Optional full path to user-suppled JSON file containing variable-term mappings.",
)
# parser.add_argument('-nidm', dest='nidm_file', required=False, help="Optional full path of NIDM file to add BIDS data to. ")
parser.add_argument(
"-log",
"--log",
dest="logfile",
required=False,
default=None,
help="Full path to directory to save log file. Log file name is bidsmri2nidm_[basename(args.directory)].log",
)
parser.add_argument(
"-o",
dest="outputfile",
required=False,
default="nidm.ttl",
help="Outputs turtle file called nidm.ttl in BIDS directory by default..or whatever path/filename is set here",
)
args = parser.parse_args()
directory = args.directory
if args.logfile is not None:
logging.basicConfig(
filename=join(
args.logfile, "bidsmri2nidm_" + args.outputfile.split("/")[-2] + ".log"
),
level=logging.DEBUG,
)
# add some logging info
logging.info("bidsmri2nidm %s" % args)
# if args.owl is None:
# args.owl = 'nidm'
# importlib.reload(sys)
# sys.setdefaultencoding('utf8')
project, cde, cde_pheno = bidsmri2project(directory, args)
# convert to rdflib Graph and add CDEs
rdf_graph = Graph()
rdf_graph.parse(source=StringIO(project.serializeTurtle()), format="turtle")
rdf_graph = rdf_graph + cde
# add rest of phenotype CDEs
for entry in cde_pheno:
rdf_graph = rdf_graph + entry
logging.info("Writing NIDM file....")
# logging.info(project.serializeTurtle())
logging.info("Serializing NIDM graph and creating graph visualization..")
# serialize graph
# if args.outputfile was defined by user then use it else use default which is args.directory/nidm.ttl
if args.outputfile == "nidm.ttl":
# if we're choosing json-ld, make sure file extension is .json
# if args.jsonld:
# outputfile=os.path.join(directory,os.path.splitext(args.outputfile)[0]+".json")
# if flag set to add to .bidsignore then add
# if (args.bidsignore):
# addbidsignore(directory,os.path.splitext(args.outputfile)[0]+".json")
outputfile = os.path.join(directory, args.outputfile)
if args.bidsignore:
addbidsignore(directory, args.outputfile)
rdf_graph.serialize(destination=outputfile, format="turtle")
# else:
# outputfile=os.path.join(directory,args.outputfile)
# if (args.bidsignore):
# addbidsignore(directory,args.outputfile)
else:
# if we're choosing json-ld, make sure file extension is .json
# if args.jsonld:
# outputfile = os.path.splitext(args.outputfile)[0]+".json"
# if (args.bidsignore):
# addbidsignore(directory,os.path.splitext(args.outputfile)[0]+".json")
# else:
# outputfile = args.outputfile
# if (args.bidsignore):
# addbidsignore(directory,args.outputfile)
outputfile = args.outputfile
if args.bidsignore:
addbidsignore(directory, args.outputfile)
rdf_graph.serialize(destination=outputfile, format="turtle")
# serialize NIDM file
# with open(outputfile,'w') as f:
# if args.jsonld:
# f.write(project.serializeJSONLD())
# else:
# f.write(project.serializeTurtle())
# save a DOT graph as PNG
# if (args.png):
# project.save_DotGraph(str(outputfile + ".png"), format="png")
# # if flag set to add to .bidsignore then add
# if (args.bidsignore):
# addbidsignore(directory,os.path.basename(str(outputfile + ".png")))
def addbidsignore(directory, filename_to_add):
logging.info("Adding file %s to %s/.bidsignore..." % (filename_to_add, directory))
# adds filename_to_add to .bidsignore file in directory
if not isfile(os.path.join(directory, ".bidsignore")):
with open(os.path.join(directory, ".bidsignore"), "w") as text_file:
text_file.write("%s\n" % filename_to_add)
else:
with open(os.path.join(directory, ".bidsignore")) as fp:
if filename_to_add not in fp.read():
with open(os.path.join(directory, ".bidsignore"), "a") as text_file:
text_file.write("%s\n" % filename_to_add)
def addimagingsessions(
bids_layout, subject_id, session, participant, directory, img_session=None
):
"""
This function adds imaging acquistions to the NIDM file and deals with BIDS structures potentially having
separate ses-* directories or not
:param bids_layout:
:param subject_id:
:param session:
:param participant:
:param directory:
:param img_session:
:return:
"""
for file_tpl in bids_layout.get(
subject=subject_id, session=img_session, extension=[".nii", ".nii.gz"]
):
# create an acquisition activity
acq = MRAcquisition(session)
# check whether participant (i.e. agent) for this subject already exists (i.e. if participants.tsv file exists) else create one
if (subject_id not in participant) and (
subject_id.lstrip("0") not in participant
):
participant[subject_id] = {}
participant[subject_id]["person"] = acq.add_person(
attributes=({Constants.NIDM_SUBJECTID: subject_id})
)
acq.add_qualified_association(
person=participant[subject_id]["person"],
role=Constants.NIDM_PARTICIPANT,
)
# added to account for errors in BIDS datasets where participants.tsv may have no leading 0's but
# subject directories do. Since bidsmri2nidm starts with the participants.tsv file those are the IDs unless
# there's a subject directory and no entry in participants.tsv...
elif subject_id.lstrip("0") in participant:
# then link acquisition to the agent with participant ID without leading 00's
acq.add_qualified_association(
person=participant[subject_id.lstrip("0")]["person"],
role=Constants.NIDM_PARTICIPANT,
)
else:
# add qualified association with person
acq.add_qualified_association(
person=participant[subject_id]["person"],
role=Constants.NIDM_PARTICIPANT,
)
if file_tpl.entities["datatype"] == "anat":
# do something with anatomicals
acq_obj = MRObject(acq)
# add image contrast type
if file_tpl.entities["suffix"] in BIDS_Constants.scans:
acq_obj.add_attributes(
{
Constants.NIDM_IMAGE_CONTRAST_TYPE: BIDS_Constants.scans[
file_tpl.entities["suffix"]
]
}
)
else:
logging.info(
"WARNING: No matching image contrast type found in BIDS_Constants.py for %s"
% file_tpl.entities["suffix"]
)
# add image usage type
if file_tpl.entities["datatype"] in BIDS_Constants.scans:
acq_obj.add_attributes(
{
Constants.NIDM_IMAGE_USAGE_TYPE: BIDS_Constants.scans[
file_tpl.entities["datatype"]
]
}
)
else:
logging.info(
"WARNING: No matching image usage type found in BIDS_Constants.py for %s"
% file_tpl.entities["datatype"]
)
# add file link
# make relative link to
acq_obj.add_attributes(
{
Constants.NIDM_FILENAME: getRelPathToBIDS(
join(file_tpl.dirname, file_tpl.filename), directory
)
}
)
# add git-annex info if exists
num_sources = addGitAnnexSources(
obj=acq_obj,
filepath=join(file_tpl.dirname, file_tpl.filename),
bids_root=directory,
)
# if there aren't any git annex sources then just store the local directory information
if num_sources == 0:
# WIP: add absolute location of BIDS directory on disk for later finding of files
acq_obj.add_attributes(
{
Constants.PROV["Location"]: "file:/"
+ join(file_tpl.dirname, file_tpl.filename)
}
)
# add sha512 sum
if isfile(join(directory, file_tpl.dirname, file_tpl.filename)):
acq_obj.add_attributes(
{
Constants.CRYPTO_SHA512: getsha512(
join(directory, file_tpl.dirname, file_tpl.filename)
)
}
)
else:
logging.info(
"WARNING file %s doesn't exist! No SHA512 sum stored in NIDM files..."
% join(directory, file_tpl.dirname, file_tpl.filename)
)
# get associated JSON file if exists
# There is T1w.json file with information
json_data = (
bids_layout.get(suffix=file_tpl.entities["suffix"], subject=subject_id)
)[0].metadata
if len(json_data.info) > 0:
for key in json_data.info.items():
if key in BIDS_Constants.json_keys:
if type(json_data.info[key]) is list:
acq_obj.add_attributes(
{
BIDS_Constants.json_keys[
key.replace(" ", "_")
]: "".join(str(e) for e in json_data.info[key])
}
)
else:
acq_obj.add_attributes(
{
BIDS_Constants.json_keys[
key.replace(" ", "_")
]: json_data.info[key]
}
)
# Parse T1w.json file in BIDS directory to add the attributes contained inside
if os.path.isdir(os.path.join(directory)):
try:
with open(os.path.join(directory, "T1w.json")) as data_file:
dataset = json.load(data_file)
except OSError:
logging.warning(
"Cannot find T1w.json file...looking for session-specific one"
)
try:
if img_session is not None:
with open(
os.path.join(
directory, "ses-" + img_session + "_T1w.json"
)
) as data_file:
dataset = json.load(data_file)
else:
dataset = {}
except OSError:
logging.warning(
"Cannot find session-specific T1w.json file which is required in the BIDS spec..continuing anyway"
)
dataset = {}
else:
logging.critical(
"Error: BIDS directory %s does not exist!" % os.path.join(directory)
)
exit(-1)
# add various attributes if they exist in BIDS dataset
for key in dataset:
# if key from T1w.json file is mapped to term in BIDS_Constants.py then add to NIDM object
if key in BIDS_Constants.json_keys:
if type(dataset[key]) is list:
acq_obj.add_attributes(
{BIDS_Constants.json_keys[key]: "".join(dataset[key])}
)
else:
acq_obj.add_attributes(
{BIDS_Constants.json_keys[key]: dataset[key]}
)
elif file_tpl.entities["datatype"] == "func":
# do something with functionals
acq_obj = MRObject(acq)
# add image contrast type
if file_tpl.entities["suffix"] in BIDS_Constants.scans:
acq_obj.add_attributes(
{
Constants.NIDM_IMAGE_CONTRAST_TYPE: BIDS_Constants.scans[
file_tpl.entities["suffix"]
]
}
)
else:
logging.info(
"WARNING: No matching image contrast type found in BIDS_Constants.py for %s"
% file_tpl.entities["suffix"]
)
# add image usage type
if file_tpl.entities["datatype"] in BIDS_Constants.scans:
acq_obj.add_attributes(
{
Constants.NIDM_IMAGE_USAGE_TYPE: BIDS_Constants.scans[
file_tpl.entities["datatype"]
]
}
)
else:
logging.info(
"WARNING: No matching image usage type found in BIDS_Constants.py for %s"
% file_tpl.entities["datatype"]
)
# make relative link to
acq_obj.add_attributes(
{
Constants.NIDM_FILENAME: getRelPathToBIDS(
join(file_tpl.dirname, file_tpl.filename), directory
)
}
)
# add git-annex/datalad info if exists
num_sources = addGitAnnexSources(
obj=acq_obj,
filepath=join(file_tpl.dirname, file_tpl.filename),
bids_root=directory,
)
# if there aren't any git annex sources then just store the local directory information
if num_sources == 0:
# WIP: add absolute location of BIDS directory on disk for later finding of files
acq_obj.add_attributes(
{
Constants.PROV["Location"]: "file:/"
+ join(file_tpl.dirname, file_tpl.filename)
}
)
# add sha512 sum
if isfile(join(directory, file_tpl.dirname, file_tpl.filename)):
acq_obj.add_attributes(
{
Constants.CRYPTO_SHA512: getsha512(
join(directory, file_tpl.dirname, file_tpl.filename)
)
}
)
else:
logging.info(
"WARNING file %s doesn't exist! No SHA512 sum stored in NIDM files..."
% join(directory, file_tpl.dirname, file_tpl.filename)
)
if "run" in file_tpl.entities:
acq_obj.add_attributes(
{BIDS_Constants.json_keys["run"]: file_tpl.entities["run"]}
)
# get associated JSON file if exists
json_data = (
bids_layout.get(suffix=file_tpl.entities["suffix"], subject=subject_id)
)[0].metadata
if len(json_data.info) > 0:
for key in json_data.info.items():
if key in BIDS_Constants.json_keys:
if type(json_data.info[key]) is list:
acq_obj.add_attributes(
{
BIDS_Constants.json_keys[
key.replace(" ", "_")
]: "".join(str(e) for e in json_data.info[key])
}
)
else:
acq_obj.add_attributes(
{
BIDS_Constants.json_keys[
key.replace(" ", "_")
]: json_data.info[key]
}
)
# get associated events TSV file
if "run" in file_tpl.entities:
events_file = bids_layout.get(
subject=subject_id,
extension=[".tsv"],
modality=file_tpl.entities["datatype"],
task=file_tpl.entities["task"],
run=file_tpl.entities["run"],
)
else:
events_file = bids_layout.get(
subject=subject_id,
extension=[".tsv"],
modality=file_tpl.entities["datatype"],
task=file_tpl.entities["task"],
)
# if there is an events file then this is task-based so create an acquisition object for the task file and link
if events_file:
# for now create acquisition object and link it to the associated scan
events_obj = AcquisitionObject(acq)
# add prov type, task name as prov:label, and link to filename of events file
events_obj.add_attributes(
{
PROV_TYPE: Constants.NIDM_MRI_BOLD_EVENTS,
BIDS_Constants.json_keys["TaskName"]: json_data["TaskName"],
Constants.NIDM_FILENAME: getRelPathToBIDS(
events_file[0].filename, directory
),
}
)
# link it to appropriate MR acquisition entity
events_obj.wasAttributedTo(acq_obj)
# add source links for this file
# add git-annex/datalad info if exists
num_sources = addGitAnnexSources(
obj=events_obj, filepath=events_file, bids_root=directory
)
# if there aren't any git annex sources then just store the local directory information
if num_sources == 0:
# WIP: add absolute location of BIDS directory on disk for later finding of files
events_obj.add_attributes(
{Constants.PROV["Location"]: "file:/" + events_file}
)
# Parse task-rest_bold.json file in BIDS directory to add the attributes contained inside
if os.path.isdir(os.path.join(directory)):
try:
with open(
os.path.join(directory, "task-rest_bold.json")
) as data_file:
dataset = json.load(data_file)
except OSError:
logging.warning(
"Cannot find task-rest_bold.json file looking for session-specific one"
)
try:
if img_session is not None:
with open(
os.path.join(
directory,
"ses-" + img_session + "_task-rest_bold.json",
)
) as data_file:
dataset = json.load(data_file)
else:
dataset = {}
except OSError:
logging.warning(
"Cannot find session-specific task-rest_bold.json file which is required in the BIDS spec..continuing anyway"
)
dataset = {}
else:
logging.critical(
"Error: BIDS directory %s does not exist!" % os.path.join(directory)
)
exit(-1)
# add various attributes if they exist in BIDS dataset
for key in dataset:
# if key from task-rest_bold.json file is mapped to term in BIDS_Constants.py then add to NIDM object
if key in BIDS_Constants.json_keys:
if type(dataset[key]) is list:
acq_obj.add_attributes(
{
BIDS_Constants.json_keys[key]: ",".join(
map(str, dataset[key])
)
}
)
else:
acq_obj.add_attributes(
{BIDS_Constants.json_keys[key]: dataset[key]}
)
# DBK added for ASL support 3/16/21
# WIP: Waiting for pybids > 0.12.4 to support perfusion scans
elif file_tpl.entities["datatype"] == "perf":
acq_obj = MRObject(acq)
# add image contrast type
if file_tpl.entities["suffix"] in BIDS_Constants.scans:
acq_obj.add_attributes(
{
Constants.NIDM_IMAGE_CONTRAST_TYPE: BIDS_Constants.scans[
file_tpl.entities["suffix"]
]
}
)
else:
logging.info(
"WARNING: No matching image contrast type found in BIDS_Constants.py for %s"
% file_tpl.entities["suffix"]
)
# add image usage type
if file_tpl.entities["datatype"] in BIDS_Constants.scans:
acq_obj.add_attributes(
{Constants.NIDM_IMAGE_USAGE_TYPE: BIDS_Constants.scans["asl"]}
)
else:
logging.info(
"WARNING: No matching image usage type found in BIDS_Constants.py for %s"
% file_tpl.entities["datatype"]
)
# make relative link to
acq_obj.add_attributes(
{
Constants.NIDM_FILENAME: getRelPathToBIDS(
join(file_tpl.dirname, file_tpl.filename), directory
)
}
)
# add sha512 sum
if isfile(join(directory, file_tpl.dirname, file_tpl.filename)):
acq_obj.add_attributes(
{
Constants.CRYPTO_SHA512: getsha512(
join(directory, file_tpl.dirname, file_tpl.filename)
)
}
)
else:
logging.info(
"WARNING file %s doesn't exist! No SHA512 sum stored in NIDM files..."
% join(directory, file_tpl.dirname, file_tpl.filename)
)
# add git-annex/datalad info if exists
num_sources = addGitAnnexSources(
obj=acq_obj,
filepath=join(file_tpl.dirname, file_tpl.filename),
bids_root=directory,
)
if num_sources == 0:
acq_obj.add_attributes(
{
Constants.PROV["Location"]: "file:/"
+ join(file_tpl.dirname, file_tpl.filename)
}
)
if "run" in file_tpl.entities:
acq_obj.add_attributes({BIDS_Constants.json_keys["run"]: file_tpl.run})
# get associated JSON file if exists
json_data = (
bids_layout.get(suffix=file_tpl.entities["suffix"], subject=subject_id)
)[0].metadata
if len(json_data.info) > 0:
for key in json_data.info.items():
if key in BIDS_Constants.json_keys:
if type(json_data.info[key]) is list:
acq_obj.add_attributes(
{
BIDS_Constants.json_keys[
key.replace(" ", "_")
]: "".join(str(e) for e in json_data.info[key])
}
)
else:
acq_obj.add_attributes(
{
BIDS_Constants.json_keys[
key.replace(" ", "_")
]: json_data.info[key]
}
)
# check if separate M0 scan exists, if so add location and filename
# WIP, waiting for pybids > 0.12.4 to support...
# WIP support B0 maps...waiting for pybids > 0.12.4
# elif file_tpl.entities['datatype'] == 'fmap':
elif file_tpl.entities["datatype"] == "dwi":
# do stuff with with dwi scans...
acq_obj = MRObject(acq)
# add image contrast type
if file_tpl.entities["suffix"] in BIDS_Constants.scans:
acq_obj.add_attributes(
{
Constants.NIDM_IMAGE_CONTRAST_TYPE: BIDS_Constants.scans[
file_tpl.entities["suffix"]
]
}
)
else:
logging.info(
"WARNING: No matching image contrast type found in BIDS_Constants.py for %s"
% file_tpl.entities["suffix"]
)
# add image usage type
if file_tpl.entities["datatype"] in BIDS_Constants.scans:
acq_obj.add_attributes(
{Constants.NIDM_IMAGE_USAGE_TYPE: BIDS_Constants.scans["dti"]}
)
else:
logging.info(
"WARNING: No matching image usage type found in BIDS_Constants.py for %s"
% file_tpl.entities["datatype"]
)
# make relative link to
acq_obj.add_attributes(
{
Constants.NIDM_FILENAME: getRelPathToBIDS(
join(file_tpl.dirname, file_tpl.filename), directory
)
}
)
# add sha512 sum
if isfile(join(directory, file_tpl.dirname, file_tpl.filename)):
acq_obj.add_attributes(
{
Constants.CRYPTO_SHA512: getsha512(
join(directory, file_tpl.dirname, file_tpl.filename)
)
}
)
else:
logging.info(
"WARNING file %s doesn't exist! No SHA512 sum stored in NIDM files..."
% join(directory, file_tpl.dirname, file_tpl.filename)
)
# add git-annex/datalad info if exists
num_sources = addGitAnnexSources(
obj=acq_obj,
filepath=join(file_tpl.dirname, file_tpl.filename),
bids_root=directory,
)
if num_sources == 0:
acq_obj.add_attributes(
{
Constants.PROV["Location"]: "file:/"
+ join(file_tpl.dirname, file_tpl.filename)
}
)
if "run" in file_tpl.entities:
acq_obj.add_attributes({BIDS_Constants.json_keys["run"]: file_tpl.run})
# get associated JSON file if exists
json_data = (
bids_layout.get(suffix=file_tpl.entities["suffix"], subject=subject_id)
)[0].metadata
if len(json_data.info) > 0:
for key in json_data.info.items():
if key in BIDS_Constants.json_keys:
if type(json_data.info[key]) is list:
acq_obj.add_attributes(
{
BIDS_Constants.json_keys[
key.replace(" ", "_")
]: "".join(str(e) for e in json_data.info[key])
}
)
else:
acq_obj.add_attributes(
{
BIDS_Constants.json_keys[
key.replace(" ", "_")
]: json_data.info[key]
}
)
# for bval and bvec files, what to do with those?
# for now, create new generic acquisition objects, link the files, and associate with the one for the DWI scan?
acq_obj_bval = AcquisitionObject(acq)
acq_obj_bval.add_attributes({PROV_TYPE: BIDS_Constants.scans["bval"]})
# add file link to bval files
acq_obj_bval.add_attributes(
{
Constants.NIDM_FILENAME: getRelPathToBIDS(
join(
file_tpl.dirname,
bids_layout.get_bval(
join(file_tpl.dirname, file_tpl.filename)
),
),
directory,
)
}
)
# add git-annex/datalad info if exists
num_sources = addGitAnnexSources(
obj=acq_obj_bval,
filepath=join(
file_tpl.dirname,
bids_layout.get_bval(join(file_tpl.dirname, file_tpl.filename)),
),
bids_root=directory,
)
if num_sources == 0:
# WIP: add absolute location of BIDS directory on disk for later finding of files
acq_obj_bval.add_attributes(
{
Constants.PROV["Location"]: "file:/"
+ join(
file_tpl.dirname,
bids_layout.get_bval(
join(file_tpl.dirname, file_tpl.filename)
),
)
}
)
# add sha512 sum
if isfile(join(directory, file_tpl.dirname, file_tpl.filename)):
acq_obj_bval.add_attributes(
{
Constants.CRYPTO_SHA512: getsha512(
join(directory, file_tpl.dirname, file_tpl.filename)
)
}
)
else:
logging.info(
"WARNING file %s doesn't exist! No SHA512 sum stored in NIDM files..."
% join(directory, file_tpl.dirname, file_tpl.filename)
)
acq_obj_bvec = AcquisitionObject(acq)
acq_obj_bvec.add_attributes({PROV_TYPE: BIDS_Constants.scans["bvec"]})
# add file link to bvec files
acq_obj_bvec.add_attributes(
{
Constants.NIDM_FILENAME: getRelPathToBIDS(
join(
file_tpl.dirname,
bids_layout.get_bvec(
join(file_tpl.dirname, file_tpl.filename)
),
),
directory,
)
}
)
# add git-annex/datalad info if exists
num_sources = addGitAnnexSources(
obj=acq_obj_bvec,
filepath=join(
file_tpl.dirname,
bids_layout.get_bvec(join(file_tpl.dirname, file_tpl.filename)),
),
bids_root=directory,
)
if num_sources == 0:
# WIP: add absolute location of BIDS directory on disk for later finding of files
acq_obj_bvec.add_attributes(
{
Constants.PROV["Location"]: "file:/"
+ join(
file_tpl.dirname,
bids_layout.get_bvec(
join(file_tpl.dirname, file_tpl.filename)
),
)
}
)
if isfile(join(directory, file_tpl.dirname, file_tpl.filename)):
# add sha512 sum
acq_obj_bvec.add_attributes(
{
Constants.CRYPTO_SHA512: getsha512(
join(directory, file_tpl.dirname, file_tpl.filename)
)
}
)
else:
logging.info(
"WARNING file %s doesn't exist! No SHA512 sum stored in NIDM files..."
% join(directory, file_tpl.dirname, file_tpl.filename)
)
# link bval and bvec acquisition object entities together or is their association with DWI scan...
def bidsmri2project(directory, args):
# initialize empty cde graph...it may get replaced if we're doing variable to term mapping or not
cde = Graph()
# Parse dataset_description.json file in BIDS directory
if os.path.isdir(os.path.join(directory)):
try:
with open(os.path.join(directory, "dataset_description.json")) as data_file:
dataset = json.load(data_file)
except OSError:
logging.critical(
"Cannot find dataset_description.json file which is required in the BIDS spec"
)
exit("-1")
else:
logging.critical(
"Error: BIDS directory %s does not exist!" % os.path.join(directory)
)
exit("-1")
# create project / nidm-exp doc
project = Project()
# if there are git annex sources then add them
num_sources = addGitAnnexSources(obj=project.get_uuid(), bids_root=directory)
# else just add the local path to the dataset
if num_sources == 0:
project.add_attributes({Constants.PROV["Location"]: "file:/" + directory})
# add various attributes if they exist in BIDS dataset description file
for key in dataset:
# if key from dataset_description file is mapped to term in BIDS_Constants.py then add to NIDM object
if key in BIDS_Constants.dataset_description:
if type(dataset[key]) is list:
project.add_attributes(
{BIDS_Constants.dataset_description[key]: "".join(dataset[key])}
)
else:
project.add_attributes(
{BIDS_Constants.dataset_description[key]: dataset[key]}
)
# added special case to include DOI of project in hash for data element UUIDs to prevent collisions with
# similar data elements from other projects and make the bids2nidm conversion deterministic in the sense
# that if you re-convert the same dataset to NIDM, the data element UUIDs will remain the same.
if key == "DatasetDOI":
if dataset[key] == "":
dataset_doi = None
else:
dataset_doi = dataset[key]
else: