Skip to content

Module dcm2bids.utils.schema⚓︎

View Source
   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
import json

import logging

import time

from datetime import datetime, timezone

from pathlib import Path

from urllib import request, error

from dcm2bids.utils.io import load_json, save_json

import dcm2bids.utils.tools as tools

from dcm2bids.utils import schema_data

from dcm2bids.version import __BIDSversion__

# Defaults for BIDS schema handling.

BIDS_SCHEMA_BASEURL = "https://bids-specification.readthedocs.io/en"

SCHEMA_ALIAS_CACHE_TTL = 7 * 24 * 60 * 60  # 1 week

logger = logging.getLogger(__name__)

def _schema_file_path(schema_version, log_dir):

    """

    Path to the full schema JSON on disk, e.g.:

      log/bids_schema_v1.9.0.json

      log/bids_schema_stable.json

    """

    log_dir = Path(log_dir)

    safe_ver = str(schema_version).replace("/", "_")

    return log_dir / f"bids_schema_{safe_ver}.json"

def _build_schema_url(

    schema_baseurl=BIDS_SCHEMA_BASEURL, schema_version=__BIDSversion__

):

    """

    Build the URL to the precompiled BIDS schema JSON for a given BIDS version

    (e.g. 'stable', 'latest', 'v1.9.0').

    """

    return f"{schema_baseurl}/{schema_version}/schema.json"

def _download_schema(schema_version, baseurl=BIDS_SCHEMA_BASEURL):

    """

    Download BIDS schema JSON for a given version label from the official URL.

    Performs HTTP + JSON parsing.

    Caching, disk paths, and fallbacks are handled in _get_schema.

    Returns:

        dict or None

    """

    url = _build_schema_url(schema_baseurl=baseurl, schema_version=schema_version)

    logger.info("Downloading BIDS schema from %s", url)

    try:

        req = request.Request(

            url,

            # need the headers, otherwise not allowed by readthedocs

            headers={"User-Agent": "Mozilla/5.0 (compatible; Dcm2Bids/1.0)"},

        )

        with request.urlopen(req, timeout=3) as resp:

            raw = resp.read()

    except error.HTTPError as e:

        logger.warning(

            "Failed to download BIDS schema (version=%s) from %s: %s",

            schema_version,

            url,

            e,

        )

        return None

    try:

        return json.loads(raw.decode())

    except json.JSONDecodeError:

        logger.warning(

            "Downloaded schema for version %s is not valid JSON.", schema_version

        )

        logger.debug("Schema JSON decode error:", exc_info=True)

        return None

def _load_schema_cache(log_dir):

    """

    Reuse tools' version cache file as a generic JSON cache, and

    keep schema entries under a dedicated 'schema' key.

    """

    cache = tools.load_version_cache(log_dir) if log_dir is not None else {}

    return cache.get("schema", {}), cache

def _save_schema_cache(schema_cache, full_cache, log_dir):

    """

    Update the 'schema' key and write back using tools' cache writer.

    """

    full_cache["schema"] = schema_cache

    tools.save_version_cache(full_cache, log_dir)

def _load_default_schema():

    """

    Load the schema that is default with dcm2bids.

    The JSON is packaged under `dcm2bids.utils.schema_data` as

    `bids_schema_<__BIDSversion__>.json`.

    """

    filename = f"bids_schema_{__BIDSversion__}.json"

    try:

        path = schema_data.file / filename

        with path.open("r", encoding="utf-8") as f:

            schema = json.load(f)

        logger.info(

            "Loading default BIDS schema (version=%s) from %s.",

            __BIDSversion__,

            path,

        )

        return schema

    except FileNotFoundError:

        logger.warning(

            "default BIDS schema file not found for version=%s (expected at %s).",

            __BIDSversion__,

            filename,

        )

        logger.debug("default schema load FileNotFoundError:", exc_info=True)

    except (OSError, json.JSONDecodeError):

        logger.warning(

            "Failed to load default BIDS schema (version=%s).",

            __BIDSversion__,

        )

        logger.debug("default schema load exception:", exc_info=True)

    return None

def _is_alias_label(schema_version):

    """

    Return True if the given schema_version is an alias

    """

    return str(schema_version) in {"stable", "latest"}

def _schema_cached_entry_info(schema_version, schema_cache):

    """

    Return (cached_entry, cached_schema_path, cache_fresh, is_alias) for a

    given schema_version from schema_cache.

    """

    is_alias = _is_alias_label(schema_version)

    cached_entry = schema_cache.get(schema_version)

    cached_schema_path = None

    cache_fresh = False

    if not isinstance(cached_entry, dict):

        return None, None, False, is_alias

    schema_path_str = cached_entry.get("path")

    ts_str = cached_entry.get("timestamp")

    now = time.time()

    if is_alias and ts_str:

        try:

            ts_dt = datetime.fromisoformat(ts_str)

            age = now - ts_dt.timestamp()

            cache_fresh = age < SCHEMA_ALIAS_CACHE_TTL

            logger.debug(

                "Schema cache: alias '%s' cached at %s "

                "(age=%.1fs, fresh=%s, ttl=%ds)",

                schema_version,

                ts_str,

                age,

                cache_fresh,

                SCHEMA_ALIAS_CACHE_TTL,

            )

        except ValueError:

            logger.debug(

                "Failed to parse schema cache timestamp '%s' for %s",

                ts_str,

                schema_version,

                exc_info=True,

            )

    if schema_path_str:

        schema_path = Path(schema_path_str)

        if schema_path.exists():

            cached_schema_path = schema_path

    return cached_entry, cached_schema_path, cache_fresh, is_alias

def _get_schema_from_cache(schema_version, log_dir, schema_cache, full_cache):

    """

    Try to load schema from cache. Returns (schema, cached_schema_path, is_alias).

    """

    cached_entry, cached_schema_path, cache_fresh, is_alias = _schema_cached_entry_info(

        schema_version, schema_cache

    )

    if cached_schema_path is None:

        return None, None, is_alias

    # For fixed versions, always try cache. For aliases, only if fresh.

    if is_alias and not cache_fresh:

        return None, cached_schema_path, is_alias

    try:

        schema = load_json(cached_schema_path)

        if is_alias:

            logger.debug(

                "Verifying cached alias BIDS schema for version '%s' from %s.",

                schema_version,

                cached_schema_path,

            )

        else:

            logger.info(

                "Using cached BIDS schema for version '%s' from %s.",

                schema_version,

                cached_schema_path,

            )

    except (OSError, json.JSONDecodeError):

        logger.debug(

            "Failed to load cached schema JSON from %s; "

            "will try re-download.",

            cached_schema_path,

            exc_info=True,

        )

        return None, cached_schema_path, is_alias

    # If we didn't have bids_version recorded (old cache),

    # update it now and ensure timestamp is set.

    if log_dir is not None and isinstance(cached_entry, dict):

        bids_ver = cached_entry.get("bids_version")

        changed = False

        if bids_ver is None:

            cached_entry["bids_version"] = schema.get("bids_version")

            changed = True

        if not cached_entry.get("timestamp"):

            cached_entry["timestamp"] = datetime.now(timezone.utc).replace(

                microsecond=0

            ).isoformat()

            changed = True

        if changed:

            schema_cache[schema_version] = cached_entry

            _save_schema_cache(schema_cache, full_cache, log_dir)

    return schema, cached_schema_path, is_alias

def _get_schema_from_remote(schema_version, log_dir, schema_cache, full_cache):

    """

    Try to download schema from remote and update cache. Returns (schema, schema_path).

    """

    schema = _download_schema(schema_version)

    if schema is None:

        return None, None

    schema_path = None

    if log_dir is not None:

        schema_path = _schema_file_path(schema_version, log_dir)

        try:

            save_json(filename=schema_path, data=schema)

            logger.info(

                "Saved BIDS schema for version '%s' to %s.",

                schema_version,

                schema_path,

            )

        except OSError:

            logger.debug(

                "Failed to write schema JSON to %s; cache metadata will "

                "still be updated but file-based cache is missing.",

                schema_path,

                exc_info=True,

            )

            schema_path = None

        schema_cache[schema_version] = {

            "path": str(schema_path) if schema_path is not None else None,

            "bids_version": schema.get("bids_version"),

            "timestamp": datetime.now(timezone.utc).replace(microsecond=0).isoformat(),

        }

        _save_schema_cache(schema_cache, full_cache, log_dir)

    return schema, schema_path

def get_schema(schema_version=__BIDSversion__, log_dir=None):

    """

    Fetch the BIDS schema JSON for a given version label, with caching and fallback.

    Returns:

        dict or None

    """

    if schema_version == "default":

        return _load_default_schema()

    # If no log_dir, we can still download but won't persist cache metadata or files.

    schema_cache, full_cache = _load_schema_cache(log_dir) if log_dir else ({}, {})

    # 1) Cache lookup: metadata -> load from file if present (with TTL for aliases)

    schema, cached_schema_path, is_alias = _get_schema_from_cache(

        schema_version, log_dir, schema_cache, full_cache

    )

    if schema is not None:

        return schema

    # 2) Remote download path

    if tools.has_internet():

        schema, _ = _get_schema_from_remote(

            schema_version, log_dir, schema_cache, full_cache

        )

        if schema is not None:

            return schema

        # Download failed; for aliases, fall back to any cached file if present.

        if is_alias and cached_schema_path is not None:

            try:

                logger.info(

                    "Failed to refresh '%s' schema from internet; "

                    "falling back to previously cached file at %s.",

                    schema_version,

                    cached_schema_path,

                )

                schema = load_json(cached_schema_path)

                return schema

            except Exception:

                logger.debug(

                    "Fallback to cached alias schema at %s failed.",

                    cached_schema_path,

                    exc_info=True,

                )

    else:

        logger.info(

            "No internet connection; cannot download BIDS schema (version=%s) "

            "from %s. If this is your first run with this label, you must either "

            "run once with internet or use the 'default' schema or a pinned, "

            "previously-cached version.",

            schema_version,

            BIDS_SCHEMA_BASEURL,

        )

        # If offline and there is a cached file (alias or not), try to use it.

        if cached_schema_path is not None:

            try:

                logger.info(

                    "Using previously cached BIDS schema for version '%s' from %s "

                    "while offline.",

                    schema_version,

                    cached_schema_path,

                )

                schema = load_json(cached_schema_path)

                return schema

            except (OSError, json.JSONDecodeError):

                logger.debug(

                    "Failed to load cached schema JSON from %s while offline.",

                    cached_schema_path,

                    exc_info=True,

                )

    # 3) Fallback to default only if requested version == default

    schema = None

    if schema_version in (__BIDSversion__, f"v{__BIDSversion__}"):

        logger.info(

            "Falling back to default BIDS schema for default version %s.",

            __BIDSversion__,

        )

        schema = _load_default_schema()

    if schema is None:

        logger.error("BIDS schema: no schema loaded (version=%s)", schema_version)

    return schema

def _get_entities_ordered(schema):

    """

    Return the list of entity definitions ordered according to `rules.entities`.

    Each item is one of the entries from `schema['objects']['entities']`.

    """

    entities = schema["objects"]["entities"]

    entities_order = schema["rules"]["entities"]

    return [entities[key] for key in entities_order]

def _get_entity_table_keys(schema):

    """

    Return the list of entity short names,

    ordered according to `rules.entities`.

    This is the schema-driven version of former DEFAULT.entityTableKeys.

    """

    ordered_entities = _get_entities_ordered(schema)

    return [ent["name"] for ent in ordered_entities]

def _get_raw_mri_entity_table_keys(schema):

    """

    Return ordered entity short names that are actually used

    in the raw MRI datatype rules.

    This is like `_get_entity_table_keys`, but restricted to entities that

    are referenced in `rules.files['raw']` for MRI datatypes.

    Note: A small quirk for (datatype == 'task') *only* when

    they target MRI datatypes, so that entities like 'rec' that appear

    in task timeseries__* rules for MRI are included.

    """

    rules = schema["rules"]

    raw_rules = rules["files"].get("raw", {})

    mri_datatypes = _get_mri_datatypes(schema)

    # Collect schema-level entity *keys* that appear in raw MRI rules

    used_schema_entities = set()

    for datatype, groups in raw_rules.items():

        if datatype in mri_datatypes:

            for spec in groups.values():

                for ent_key in (spec.get("entities") or {}):

                    used_schema_entities.add(ent_key)

        # Task rules that target MRI datatypes (timeseries__*)

        if datatype == "task":

            for spec in groups.values():

                target_dts = spec.get("datatypes", [])

                if all(dt not in mri_datatypes for dt in target_dts):

                    continue

                for ent_key in (spec.get("entities") or {}):

                    used_schema_entities.add(ent_key)

    # Walk rules.entities in order, but keep only those used in raw MRI

    entities = schema["objects"]["entities"]

    ordered_schema_keys = rules["entities"]

    ordered_entities = [

        entities[key]

        for key in ordered_schema_keys

        if key in used_schema_entities

    ]

    return [ent["name"] for ent in ordered_entities]

def _get_schema_to_bids_entity_map(schema):

    """

    Build mapping from schema entity key (used in rules) -> short entity names

    used in filenames, e.g., 'acquisition' -> 'acq', 'direction' -> 'dir'.

    """

    entities = schema["objects"]["entities"]

    return {schema_key: ent_def["name"] for schema_key, ent_def in entities.items()}

def _get_mri_datatypes(schema):

    """

    Return the list of MRI-related datatypes defined in the schema.

    This follows `rules.modalities['mri']['datatypes']`

    """

    rules = schema["rules"]

    mri = rules["modalities"].get("mri", {})

    datatypes = list(mri.get("datatypes", []))

    return datatypes

def _get_auto_entities_from_schema(schema):

    """

    Derive the 'auto entities' mapping from the schema.

    Keys look like 'anat_VFA', 'func_bold', 'fmap_epi', etc.

    Values are lists of entity short names (e.g. ['task'], ['dir'], ['flip', 'mt']).

    This is the schema-driven version of former DEFAULT.auto_entities.

    """

    raw_rules = schema["rules"]["files"]['raw']

    schema_to_bids = _get_schema_to_bids_entity_map(schema)

    mri_datatypes = _get_mri_datatypes(schema)

    # Quirk: Add task into the list if it's not explicitly listed.

    mri_datatypes_with_task = mri_datatypes + ["task"]

    auto_required_entities = {}

    # Loop over datatype groups

    for datatype, groups in raw_rules.items():

        # Skip non-mri datatype

        if datatype not in mri_datatypes_with_task:

            continue

        for group_name, spec in groups.items():

            ent_spec = spec.get("entities", {})

            # don't keep 'subject' as is mandatory for all of them

            required_schema_entities = [

                key

                for key, requirement in ent_spec.items()

                if requirement == "required" and key != "subject"

            ]

            if not required_schema_entities:

                continue

            # Map schema keys -> BIDS abbreviations via schema_to_bids

            required_bids_entities = [

                schema_to_bids[key]

                for key in required_schema_entities

                if key in schema_to_bids

            ]

            if not required_bids_entities:

                continue

            suffixes = spec.get("suffixes", [])

            target_datatypes = spec.get("datatypes", [datatype])

            if datatype != "task":

                # For "plain" MRI datatypes (anat/func/fmap/perf/dwi/pet...),

                # keep same behavior (eg, anat_MP2RAGE)

                for suffix in suffixes:

                    key = f"{datatype}_{suffix}"

                    auto_required_entities[key] = required_bids_entities

            else:

                # task-* rules are trickier (timeseries__*) applicable to multiple

                # datatypes, so keys per *target* datatype, (eg anat_physio)

                for target_dt in target_datatypes:

                    if target_dt not in mri_datatypes_with_task:

                        continue

                    for suffix in suffixes:

                        key = f"{target_dt}_{suffix}"

                        auto_required_entities[key] = required_bids_entities

    return auto_required_entities

def derive_entities_from_schema(schema):

    """

    Helper that loads the BIDS schema and returns a small bundle

    of derived structures to integrate into DEFAULT.

    Returned dict includes:

      - 'raw_mri_entity_table_keys': Entity short names in order for MRI only

      - 'auto_entities': schema-driven auto-entities (MRI datatypes)

    """

    if schema is None:

        raise RuntimeError(

            f"Failed to load BIDS schema for version '{schema['bids_version']}'."

            "This indicates a broken dcm2bids installation or an invalid "

            "schema_version override."

        )

    # All entities in schema order

    auto_entities = _get_auto_entities_from_schema(schema)

    # Entities for raw MRI datatypes only

    raw_mri_entity_table_keys = _get_raw_mri_entity_table_keys(schema)

    # Make raw MRI entities the default

    # makes it backward compatible with manual tables in default

    return {

        # default set

        "entity_table_keys": raw_mri_entity_table_keys,

        "auto_entities": auto_entities

    }

def _resolve_bids_version_label(args_bids_version, log_dir):

    """

    Decide which schema label to use and log messages.

    Returns the actual label in used (e.g. 'default', 'stable', 'v1.11.1', etc)

    """

    if args_bids_version is None:

        default_version = __BIDSversion__

        logger.info(

            "No --bids_version provided; using 'default' BIDS spec (version=%s) "

            "for reproducible behavior.",

            default_version,

        )

        # Simplest place to check when default is used

        if tools.has_internet():

            _check_latest_stable(default_version, log_dir)

        return "default"

    logger.info(

        "Specific BIDS version requested via --bids_version=%s",

        args_bids_version,

    )

    if args_bids_version == "latest":

        logger.warning(

            "You requested BIDS version 'latest'. This typically tracks the "

            "current development version of the BIDS specification and may be "

            "unstable or change without notice. For reproducible pipelines, "

            "consider using a fixed version tag (e.g. 'v1.11.1') or 'default'."

        )

    elif args_bids_version == "stable":

        logger.info(

            "You requested BIDS version 'stable'. This label may point to "

            "different BIDS releases over time. For reproducible pipelines, "

            "consider using a fixed version tag (e.g. 'v1.11.1') or 'default'."

        )

    return args_bids_version

def _check_latest_stable(version, log_dir):

    """

    If possible, check remote 'stable' and suggest upgrading if newer.

    """

    logger.info("Checking for BIDS update")

    logger.debug(

        "Checking remote 'stable' BIDS spec to see if a newer version "

        "is available."

    )

    stable_schema = get_schema(schema_version="stable", log_dir=log_dir)

    stable_version = None

    if stable_schema is not None:

        stable_version = stable_schema.get("bids_version", "stable")

    if isinstance(stable_version, str):

        logger.debug(

            "default BIDS version: %s; remote 'stable' version: %s",

            version,

            stable_version,

        )

        if tools.version_newer(stable_version, version):

            logger.warning(

                "A newer 'stable' BIDS specification (%s) is available than the "

                "default version (%s). The default schema is still used "

                "for this run. Consider updating using "

                "--bids_version %s.",

                stable_version,

                version,

                stable_version,

            )

        else:

            logger.info("Using latest stable BIDS specification.")

    else:

        logger.info(

            "Could not determine version for 'stable'; "

            "continuing with default BIDS specification (%s).",

            version,

        )

def _abort_if_schema_missing(schema_version, schema):

    """

    Centralized error logging + exit when schema cannot be loaded.

    """

    if schema is not None:

        return

    # Be explicit so users know how to recover, aborting so user actually reads the log ;)

    logger.error(

        "Failed to load BIDS schema for '%s'. If you are running offline and "

        "this label has never been used before on this machine, there may be "

        "no cached file available.",

        schema_version,

    )

    logger.error(

        "To proceed offline, either:\n"

        "  * Run once with internet so the schema for '%s' can be cached, or\n"

        "  * Use the default schema without using '--bids_version', or\n",

        "  * Use the default schema with using '--bids_version default', or\n"

        "  * Pin to a specific BIDS version tag that is already cached.",

        schema_version,

    )

    logger.error(

        "BIDS version '%s' could not be found; verify the version provided.",

        schema_version,

    )

    logger.error(

        "dcm2bids cannot continue without a valid BIDS version. Aborting."

    )

    raise SystemExit(1)

def load_schema(args_bids_version, log_dir):

    """

    Helper to resolve and load the requested BIDS schema version for the current run.

    This function decides which BIDS version label to use, checks for updates, and

    aborts if the schema cannot be loaded.

    Args:

        args_bids_version: BIDS version label requested by the user.

        log_dir: Directory used for caching schema files and version checks.

    Returns:

        dict: Loaded BIDS schema JSON corresponding to the actual version label.

    Raises:

        SystemExit: If no valid BIDS schema can be loaded for the requested label.

    """

    actual_label = _resolve_bids_version_label(args_bids_version, log_dir)

    schema = get_schema(schema_version=actual_label, log_dir=log_dir)

    _abort_if_schema_missing(actual_label, schema)

    derived = derive_entities_from_schema(schema)

    return schema, derived

Variables⚓︎

1
BIDS_SCHEMA_BASEURL
1
SCHEMA_ALIAS_CACHE_TTL
1
logger

Functions⚓︎

derive_entities_from_schema⚓︎

1
2
3
def derive_entities_from_schema(
    schema
)

Helper that loads the BIDS schema and returns a small bundle

of derived structures to integrate into DEFAULT.

Returned dict includes: - 'raw_mri_entity_table_keys': Entity short names in order for MRI only - 'auto_entities': schema-driven auto-entities (MRI datatypes)

View Source
 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
def derive_entities_from_schema(schema):

    """

    Helper that loads the BIDS schema and returns a small bundle

    of derived structures to integrate into DEFAULT.

    Returned dict includes:

      - 'raw_mri_entity_table_keys': Entity short names in order for MRI only

      - 'auto_entities': schema-driven auto-entities (MRI datatypes)

    """

    if schema is None:

        raise RuntimeError(

            f"Failed to load BIDS schema for version '{schema['bids_version']}'."

            "This indicates a broken dcm2bids installation or an invalid "

            "schema_version override."

        )

    # All entities in schema order

    auto_entities = _get_auto_entities_from_schema(schema)

    # Entities for raw MRI datatypes only

    raw_mri_entity_table_keys = _get_raw_mri_entity_table_keys(schema)

    # Make raw MRI entities the default

    # makes it backward compatible with manual tables in default

    return {

        # default set

        "entity_table_keys": raw_mri_entity_table_keys,

        "auto_entities": auto_entities

    }

get_schema⚓︎

1
2
3
4
def get_schema(
    schema_version='v1.11.1',
    log_dir=None
)

Fetch the BIDS schema JSON for a given version label, with caching and fallback.

Returns:

Type Description
None dict or None
View Source
  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
def get_schema(schema_version=__BIDSversion__, log_dir=None):

    """

    Fetch the BIDS schema JSON for a given version label, with caching and fallback.

    Returns:

        dict or None

    """

    if schema_version == "default":

        return _load_default_schema()

    # If no log_dir, we can still download but won't persist cache metadata or files.

    schema_cache, full_cache = _load_schema_cache(log_dir) if log_dir else ({}, {})

    # 1) Cache lookup: metadata -> load from file if present (with TTL for aliases)

    schema, cached_schema_path, is_alias = _get_schema_from_cache(

        schema_version, log_dir, schema_cache, full_cache

    )

    if schema is not None:

        return schema

    # 2) Remote download path

    if tools.has_internet():

        schema, _ = _get_schema_from_remote(

            schema_version, log_dir, schema_cache, full_cache

        )

        if schema is not None:

            return schema

        # Download failed; for aliases, fall back to any cached file if present.

        if is_alias and cached_schema_path is not None:

            try:

                logger.info(

                    "Failed to refresh '%s' schema from internet; "

                    "falling back to previously cached file at %s.",

                    schema_version,

                    cached_schema_path,

                )

                schema = load_json(cached_schema_path)

                return schema

            except Exception:

                logger.debug(

                    "Fallback to cached alias schema at %s failed.",

                    cached_schema_path,

                    exc_info=True,

                )

    else:

        logger.info(

            "No internet connection; cannot download BIDS schema (version=%s) "

            "from %s. If this is your first run with this label, you must either "

            "run once with internet or use the 'default' schema or a pinned, "

            "previously-cached version.",

            schema_version,

            BIDS_SCHEMA_BASEURL,

        )

        # If offline and there is a cached file (alias or not), try to use it.

        if cached_schema_path is not None:

            try:

                logger.info(

                    "Using previously cached BIDS schema for version '%s' from %s "

                    "while offline.",

                    schema_version,

                    cached_schema_path,

                )

                schema = load_json(cached_schema_path)

                return schema

            except (OSError, json.JSONDecodeError):

                logger.debug(

                    "Failed to load cached schema JSON from %s while offline.",

                    cached_schema_path,

                    exc_info=True,

                )

    # 3) Fallback to default only if requested version == default

    schema = None

    if schema_version in (__BIDSversion__, f"v{__BIDSversion__}"):

        logger.info(

            "Falling back to default BIDS schema for default version %s.",

            __BIDSversion__,

        )

        schema = _load_default_schema()

    if schema is None:

        logger.error("BIDS schema: no schema loaded (version=%s)", schema_version)

    return schema

load_schema⚓︎

1
2
3
4
def load_schema(
    args_bids_version,
    log_dir
)

Helper to resolve and load the requested BIDS schema version for the current run.

This function decides which BIDS version label to use, checks for updates, and aborts if the schema cannot be loaded.

Parameters:

Name Type Description Default
args_bids_version None BIDS version label requested by the user. None
log_dir None Directory used for caching schema files and version checks. None

Returns:

Type Description
dict Loaded BIDS schema JSON corresponding to the actual version label.

Raises:

Type Description
SystemExit If no valid BIDS schema can be loaded for the requested label.
View Source
 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
def load_schema(args_bids_version, log_dir):

    """

    Helper to resolve and load the requested BIDS schema version for the current run.

    This function decides which BIDS version label to use, checks for updates, and

    aborts if the schema cannot be loaded.

    Args:

        args_bids_version: BIDS version label requested by the user.

        log_dir: Directory used for caching schema files and version checks.

    Returns:

        dict: Loaded BIDS schema JSON corresponding to the actual version label.

    Raises:

        SystemExit: If no valid BIDS schema can be loaded for the requested label.

    """

    actual_label = _resolve_bids_version_label(args_bids_version, log_dir)

    schema = get_schema(schema_version=actual_label, log_dir=log_dir)

    _abort_if_schema_missing(actual_label, schema)

    derived = derive_entities_from_schema(schema)

    return schema, derived