diff --git a/niworkflows/utils/bids.py b/niworkflows/utils/bids.py index fdcfbd586f3..8f79f7d5dd9 100644 --- a/niworkflows/utils/bids.py +++ b/niworkflows/utils/bids.py @@ -488,3 +488,37 @@ def check_pipeline_version(cvers, data_desc): dvers = desc.get("PipelineDescription", {}).get("Version", "0+unknown") if Version(cvers).public != Version(dvers).public: return "Previous output generated by version {} found.".format(dvers) + +def corresponding_file(in_file, bids_dir, extension, bids_validate=True): + """ + Returns the corresponding file with the given extension + + Parameters + ---------- + in_file : :obj:`str` + Filename + bids_dir : :obj:`str` or :obj:`bids.layout.BIDSLayout` + The BIDS directory + extension : :obj: `str` + An extension string + bids_validate : :obj:`bool` + Whether the `bids_dir` is validated upon initialization + + Returns + ------- + filename : :obj:`str` + The path to the corresponding file + """ + + if isinstance(bids_dir, BIDSLayout): + layout = bids_dir + else: + layout = BIDSLayout(str(bids_dir), validate=bids_validate) + + entities = layout.parse_file_entities(in_file) + entities.pop("extension", None) + entities.pop("echo", None) + entities.pop("part", None) + corresponding_filename = layout.build_path(entities, extension=extension) + + return corresponding_filename