1515from bids .layout .models import Config
1616from bids .layout .index import BIDSLayoutIndexer , _check_path_matches_patterns , _regexfy
1717from bids .layout .utils import PaddedInt
18- from bids .utils import natural_sort
18+ from bids .utils import natural_sort , bids_sort
1919
2020from bids .exceptions import (
2121 BIDSChildDatasetError ,
@@ -1268,3 +1268,34 @@ def test_get_return_type_dir_with_legacy_config_no_template():
12681268 # because task entity has no directory template
12691269 with pytest .raises (ValueError , match = 'Return type set to directory' ):
12701270 layout .get (target = 'task' , return_type = 'dir' )
1271+
1272+ def test_bids_sort (layout_7t_trt ):
1273+ files = layout_7t_trt .get (task = 'rest' , extension = '.nii.gz' )
1274+ assert len (files ) > 0
1275+ from bidsschematools .schema import load_schema
1276+ import random
1277+ import copy
1278+ # we apply bids_sort at the model level, but just to be extra sure
1279+ # we sort here one more time
1280+ first_file_ents_sorted = bids_sort (files [0 ].get_entities ())
1281+ schema_order = list (load_schema ().rules .entities ) + ['suffix' , 'extension' , 'datatype' ]
1282+
1283+ # collect keys from file entity then unsort them
1284+ sorted_keys = list (first_file_ents_sorted .keys ())
1285+ unsorted_keys = copy .copy (sorted_keys )
1286+ while unsorted_keys == sorted_keys :
1287+ random .shuffle (unsorted_keys )
1288+
1289+ first_file_ents_unsorted = {}
1290+ for key in unsorted_keys :
1291+ first_file_ents_unsorted [key ] = first_file_ents_sorted [key ]
1292+
1293+ # check order of sorted entities against schema
1294+ for i , entity in enumerate (sorted_keys ):
1295+ for j in sorted_keys [i + 1 :]:
1296+ if entity in schema_order and j in schema_order :
1297+ assert schema_order .index (entity ) < schema_order .index (j )
1298+
1299+ assert list (first_file_ents_unsorted .keys ()) != sorted_keys
1300+ assert list (bids_sort (first_file_ents_unsorted ).keys ()) == sorted_keys
1301+
0 commit comments