prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Add get_fieldmap() method
  Option 1 (simple):
  
  ```
  >> layout = BIDSLayout("/data/ds")
  >> layout.get_fieldmap("sub-01/func/sub-01_task-rest_bold.nii.gz")
  [
   "/data/ds/sub-01/fmap/sub-01_magnitude1.nii.gz", 
   "/data/ds/sub-01/fmap/sub-01_magnitude2.nii.gz", 
   "/data/ds/sub-01/fmap/sub-01_phasediff.nii.gz"
  ]
  ```
  
  Option 2 (extensive):
  
  ```
  >> layout = BIDSLayout("/data/ds")
  >> layout.get_fieldmap("sub-01/func/sub-01_task-rest_bold.nii.gz")
  {
  'type': 'phasediff',
  'metadata': {
                      "EchoTime1" : 0.00600,
                      "EchoTime2" : 0.00746,
                      "IntendedFor" : "func/sub­01_task­motor_bold.nii.gz" 
                      },
  'data' : [
               "/data/ds/sub-01/fmap/sub-01_magnitude1.nii.gz", 
               "/data/ds/sub-01/fmap/sub-01_magnitude2.nii.gz", 
               "/data/ds/sub-01/fmap/sub-01_phasediff.nii.gz"
              ]
  }
  ```
  
  WDYT @rwblair @oesteban @yarikoptic @tyarkoni @satra?
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `bids/grabbids/bids_layout.py`
  Content:
  ```
  1 import os
  2 import re
  3 import json
  4 
  5 from itertools import combinations
  6 from os.path import dirname
  7 from os.path import realpath
  8 from os.path import join as pathjoin
  9 from os.path import split as pathsplit
  10 
  11 from grabbit import Layout
  12 
  13 __all__ = ['BIDSLayout']
  14 
  15 
  16 class BIDSLayout(Layout):
  17     def __init__(self, path, config=None):
  18         if config is None:
  19             root = dirname(realpath(__file__))
  20             config = pathjoin(root, 'config', 'bids.json')
  21         super(BIDSLayout, self).__init__(path, config)
  22 
  23     def get_metadata(self, path):
  24         sidecarJSON = path.replace(".nii.gz", ".json").replace(".nii", ".json")
  25         path_components = pathsplit(sidecarJSON)
  26         filename_components = path_components[-1].split("_")
  27         ses = None
  28         suffix = filename_components[-1]
  29 
  30         sub = filename_components[0]
  31         keyword_components = filename_components[1:-1]
  32         if filename_components[1][:3] == "ses":
  33             ses = filename_components[1]
  34             keyword_components = filename_components[2:-1]
  35 
  36         potentialJSONs = []
  37         for prefixes, conditional in (  # Levels
  38                 (tuple(), True),        # top
  39                 ((sub,), True),         # subject
  40                 ((sub, ses), ses)       # session
  41         ):
  42             if not conditional:
  43                 continue
  44             for k in range(len(keyword_components) + 1):
  45                 # print(k)
  46                 for components in combinations(keyword_components, k):
  47                     # print(components)
  48                     potentialJSONs.append(
  49                         pathjoin(
  50                             self.root,
  51                             *(prefixes +
  52                               ("_".join(prefixes + components + (suffix,)),))))
  53 
  54         merged_param_dict = {}
  55         for json_file_path in potentialJSONs:
  56             if os.path.exists(json_file_path):
  57                 param_dict = json.load(open(json_file_path, "r"))
  58                 merged_param_dict.update(param_dict)
  59 
  60         return merged_param_dict
  61 
  62     def find_match(self, target, source=None):
  63 
  64         # Try to take the easy way out
  65         if source is not None:
  66             _target = source.split('.')[0] + '.' + target
  67             if os.path.exists(_target):
  68                 return target
  69 
  70         if target in list(self.entities.keys()):
  71             candidates = list(self.entities[target].files.keys())
  72         else:
  73             candidates = []
  74 
  75             for root, directories, filenames in os.walk(self.root):
  76                 for f in filenames:
  77                     if re.search(target + '$', f):
  78                         if os.path.sep == "\\":
  79                             f = f.replace("\\", "\\\\")
  80                         candidates.append(f)
  81 
  82         if source is None:
  83             return candidates
  84 
  85         # Walk up the file hierarchy from source, find first match
  86         if not os.path.exists(source):
  87             raise OSError("The file '%s' doesn't exist." % source)
  88         elif not source.startswith(self.root):
  89             raise ValueError("The file '%s' is not contained "
  90                              "within the current project "
  91                              "directory (%s)." % (source, self.root))
  92         rel = os.path.relpath(dirname(source), self.root)
  93         sep = os.path.sep
  94         chunks = rel.split(sep)
  95         n_chunks = len(chunks)
  96         for i in range(n_chunks, -1, -1):
  97             path = pathjoin(self.root, *chunks[:i])
  98             patt = path + '\%s[^\%s]+$' % (sep, sep)
  99             if sep == "\\":
  100                 patt = path + '\\[^\\]+$'
  101                 patt = patt.replace("\\", "\\\\")
  102             matches = [x for x in candidates if re.search(patt, x)]
  103             if matches:
  104                 if len(matches) == 1:
  105                     return matches[0]
  106                 else:
  107                     raise ValueError("Ambiguous target: more than one "
  108                                      "candidate file found in "
  109                                      "directory '%s'." % path)
  110         return None
  111
  ```
  
  Path: `setup.py`
  Content:
  ```
  1 #!/usr/bin/env python
  2 
  3 import os
  4 from setuptools import setup, find_packages
  5 PACKAGES = find_packages()
  6 
  7 # Get version and release info, which is all stored in bids/version.py
  8 ver_file = os.path.join('bids', 'version.py')
  9 with open(ver_file) as f:
  10     exec(f.read())
  11 
  12 opts = dict(name=NAME,
  13             maintainer=MAINTAINER,
  14             maintainer_email=MAINTAINER_EMAIL,
  15             description=DESCRIPTION,
  16             long_description=LONG_DESCRIPTION,
  17             url=URL,
  18             download_url=DOWNLOAD_URL,
  19             license=LICENSE,
  20             classifiers=CLASSIFIERS,
  21             author=AUTHOR,
  22             author_email=AUTHOR_EMAIL,
  23             platforms=PLATFORMS,
  24             version=VERSION,
  25             packages=PACKAGES,
  26             requires=REQUIRES,
  27             install_requires=REQUIRES)
  28 
  29 
  30 if __name__ == '__main__':
  31     setup(**opts)
  32
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/bids/grabbids/bids_layout.py b/bids/grabbids/bids_layout.py
  --- a/bids/grabbids/bids_layout.py
  +++ b/bids/grabbids/bids_layout.py
  @@ -18,7 +18,7 @@
           if config is None:
               root = dirname(realpath(__file__))
               config = pathjoin(root, 'config', 'bids.json')
  -        super(BIDSLayout, self).__init__(path, config)
  +        super(BIDSLayout, self).__init__(path, config, dynamic_getters=True)
   
       def get_metadata(self, path):
           sidecarJSON = path.replace(".nii.gz", ".json").replace(".nii", ".json")
  @@ -34,21 +34,21 @@
               keyword_components = filename_components[2:-1]
   
           potentialJSONs = []
  -        for prefixes, conditional in (  # Levels
  -                (tuple(), True),        # top
  -                ((sub,), True),         # subject
  -                ((sub, ses), ses)       # session
  +        for prefixes, midlayer, conditional in (  # Levels
  +                (tuple(), tuple(), True),        # top
  +                ((sub,), tuple(), True),         # subject
  +                ((sub, ), (pathsplit(path_components[-2])[-1],), True),
  +                ((sub, ses), tuple(), ses),  # session
  +                ((sub, ses), (pathsplit(path_components[-2])[-1],), ses)
           ):
               if not conditional:
                   continue
               for k in range(len(keyword_components) + 1):
  -                # print(k)
                   for components in combinations(keyword_components, k):
  -                    # print(components)
                       potentialJSONs.append(
                           pathjoin(
                               self.root,
  -                            *(prefixes +
  +                            *(prefixes + midlayer +
                                 ("_".join(prefixes + components + (suffix,)),))))
   
           merged_param_dict = {}
  @@ -59,6 +59,45 @@
   
           return merged_param_dict
   
  +    def get_fieldmap(self, path):
  +        sub = os.path.split(path)[1].split("_")[0].split("sub-")[1]
  +        fieldmap_set = {}
  +        for file in self.get(subject=sub,
  +                             type='(phase1|phase2|phasediff|epi|fieldmap)',
  +                             extensions=['nii.gz', 'nii']):
  +            metadata = self.get_metadata(file.filename)
  +            if metadata and "IntendedFor" in metadata.keys():
  +                if path.endswith(metadata["IntendedFor"]):
  +                    if file.type == "phasediff":
  +                        fieldmap_set = {"phasediff": file.filename,
  +                                        "magnitude1": file.filename.replace(
  +                                            "phasediff", "magnitude1"),
  +                                        "magnitude2": file.filename.replace(
  +                                            "phasediff", "magnitude2"),
  +                                        "type": "phasediff"}
  +                        break
  +                    elif file.type == "phase1":
  +                        fieldmap_set["phase1"] = file.filename
  +                        fieldmap_set["magnitude1"] = \
  +                            file.filename.replace("phase1", "magnitude1")
  +                        fieldmap_set["type"] = "phase"
  +                    elif file.type == "phase2":
  +                        fieldmap_set["phase2"] = file.filename
  +                        fieldmap_set["magnitude2"] = \
  +                            file.filename.replace("phase2", "magnitude2")
  +                        fieldmap_set["type"] = "phase"
  +                    elif file.type == "epi":
  +                        if "epi" not in fieldmap_set.keys():
  +                            fieldmap_set["epi"] = []
  +                        fieldmap_set["epi"].append(file.filename)
  +                        fieldmap_set["type"] = "epi"
  +                    elif file.type == "fieldmap":
  +                        fieldmap_set["fieldmap"] = file.filename
  +                        fieldmap_set["magnitude"] = \
  +                            file.filename.replace("fieldmap", "magnitude")
  +                        fieldmap_set["type"] = "fieldmap"
  +        return fieldmap_set
  +
       def find_match(self, target, source=None):
   
           # Try to take the easy way out
  diff --git a/setup.py b/setup.py
  --- a/setup.py
  +++ b/setup.py
  @@ -23,6 +23,7 @@
               platforms=PLATFORMS,
               version=VERSION,
               packages=PACKAGES,
  +            package_data={'bids': ['grabbids/config/bids.json']},
               requires=REQUIRES,
               install_requires=REQUIRES)
  
verification_info: {"golden_diff": "diff --git a/bids/grabbids/bids_layout.py b/bids/grabbids/bids_layout.py\n--- a/bids/grabbids/bids_layout.py\n+++ b/bids/grabbids/bids_layout.py\n@@ -18,7 +18,7 @@\n         if config is None:\n             root = dirname(realpath(__file__))\n             config = pathjoin(root, 'config', 'bids.json')\n-        super(BIDSLayout, self).__init__(path, config)\n+        super(BIDSLayout, self).__init__(path, config, dynamic_getters=True)\n \n     def get_metadata(self, path):\n         sidecarJSON = path.replace(\".nii.gz\", \".json\").replace(\".nii\", \".json\")\n@@ -34,21 +34,21 @@\n             keyword_components = filename_components[2:-1]\n \n         potentialJSONs = []\n-        for prefixes, conditional in (  # Levels\n-                (tuple(), True),        # top\n-                ((sub,), True),         # subject\n-                ((sub, ses), ses)       # session\n+        for prefixes, midlayer, conditional in (  # Levels\n+                (tuple(), tuple(), True),        # top\n+                ((sub,), tuple(), True),         # subject\n+                ((sub, ), (pathsplit(path_components[-2])[-1],), True),\n+                ((sub, ses), tuple(), ses),  # session\n+                ((sub, ses), (pathsplit(path_components[-2])[-1],), ses)\n         ):\n             if not conditional:\n                 continue\n             for k in range(len(keyword_components) + 1):\n-                # print(k)\n                 for components in combinations(keyword_components, k):\n-                    # print(components)\n                     potentialJSONs.append(\n                         pathjoin(\n                             self.root,\n-                            *(prefixes +\n+                            *(prefixes + midlayer +\n                               (\"_\".join(prefixes + components + (suffix,)),))))\n \n         merged_param_dict = {}\n@@ -59,6 +59,45 @@\n \n         return merged_param_dict\n \n+    def get_fieldmap(self, path):\n+        sub = os.path.split(path)[1].split(\"_\")[0].split(\"sub-\")[1]\n+        fieldmap_set = {}\n+        for file in self.get(subject=sub,\n+                             type='(phase1|phase2|phasediff|epi|fieldmap)',\n+                             extensions=['nii.gz', 'nii']):\n+            metadata = self.get_metadata(file.filename)\n+            if metadata and \"IntendedFor\" in metadata.keys():\n+                if path.endswith(metadata[\"IntendedFor\"]):\n+                    if file.type == \"phasediff\":\n+                        fieldmap_set = {\"phasediff\": file.filename,\n+                                        \"magnitude1\": file.filename.replace(\n+                                            \"phasediff\", \"magnitude1\"),\n+                                        \"magnitude2\": file.filename.replace(\n+                                            \"phasediff\", \"magnitude2\"),\n+                                        \"type\": \"phasediff\"}\n+                        break\n+                    elif file.type == \"phase1\":\n+                        fieldmap_set[\"phase1\"] = file.filename\n+                        fieldmap_set[\"magnitude1\"] = \\\n+                            file.filename.replace(\"phase1\", \"magnitude1\")\n+                        fieldmap_set[\"type\"] = \"phase\"\n+                    elif file.type == \"phase2\":\n+                        fieldmap_set[\"phase2\"] = file.filename\n+                        fieldmap_set[\"magnitude2\"] = \\\n+                            file.filename.replace(\"phase2\", \"magnitude2\")\n+                        fieldmap_set[\"type\"] = \"phase\"\n+                    elif file.type == \"epi\":\n+                        if \"epi\" not in fieldmap_set.keys():\n+                            fieldmap_set[\"epi\"] = []\n+                        fieldmap_set[\"epi\"].append(file.filename)\n+                        fieldmap_set[\"type\"] = \"epi\"\n+                    elif file.type == \"fieldmap\":\n+                        fieldmap_set[\"fieldmap\"] = file.filename\n+                        fieldmap_set[\"magnitude\"] = \\\n+                            file.filename.replace(\"fieldmap\", \"magnitude\")\n+                        fieldmap_set[\"type\"] = \"fieldmap\"\n+        return fieldmap_set\n+\n     def find_match(self, target, source=None):\n \n         # Try to take the easy way out\ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -23,6 +23,7 @@\n             platforms=PLATFORMS,\n             version=VERSION,\n             packages=PACKAGES,\n+            package_data={'bids': ['grabbids/config/bids.json']},\n             requires=REQUIRES,\n             install_requires=REQUIRES)\n", "issue": "Add get_fieldmap() method\nOption 1 (simple):\n\n```\n>> layout = BIDSLayout(\"/data/ds\")\n>> layout.get_fieldmap(\"sub-01/func/sub-01_task-rest_bold.nii.gz\")\n[\n \"/data/ds/sub-01/fmap/sub-01_magnitude1.nii.gz\", \n \"/data/ds/sub-01/fmap/sub-01_magnitude2.nii.gz\", \n \"/data/ds/sub-01/fmap/sub-01_phasediff.nii.gz\"\n]\n```\n\nOption 2 (extensive):\n\n```\n>> layout = BIDSLayout(\"/data/ds\")\n>> layout.get_fieldmap(\"sub-01/func/sub-01_task-rest_bold.nii.gz\")\n{\n'type': 'phasediff',\n'metadata': {\n                    \"EchoTime1\" : 0.00600,\n                    \"EchoTime2\" : 0.00746,\n                    \"IntendedFor\" : \"func/sub\u00ad01_task\u00admotor_bold.nii.gz\" \n                    },\n'data' : [\n             \"/data/ds/sub-01/fmap/sub-01_magnitude1.nii.gz\", \n             \"/data/ds/sub-01/fmap/sub-01_magnitude2.nii.gz\", \n             \"/data/ds/sub-01/fmap/sub-01_phasediff.nii.gz\"\n            ]\n}\n```\n\nWDYT @rwblair @oesteban @yarikoptic @tyarkoni @satra?\n\n", "before_files": [{"content": "import os\nimport re\nimport json\n\nfrom itertools import combinations\nfrom os.path import dirname\nfrom os.path import realpath\nfrom os.path import join as pathjoin\nfrom os.path import split as pathsplit\n\nfrom grabbit import Layout\n\n__all__ = ['BIDSLayout']\n\n\nclass BIDSLayout(Layout):\n    def __init__(self, path, config=None):\n        if config is None:\n            root = dirname(realpath(__file__))\n            config = pathjoin(root, 'config', 'bids.json')\n        super(BIDSLayout, self).__init__(path, config)\n\n    def get_metadata(self, path):\n        sidecarJSON = path.replace(\".nii.gz\", \".json\").replace(\".nii\", \".json\")\n        path_components = pathsplit(sidecarJSON)\n        filename_components = path_components[-1].split(\"_\")\n        ses = None\n        suffix = filename_components[-1]\n\n        sub = filename_components[0]\n        keyword_components = filename_components[1:-1]\n        if filename_components[1][:3] == \"ses\":\n            ses = filename_components[1]\n            keyword_components = filename_components[2:-1]\n\n        potentialJSONs = []\n        for prefixes, conditional in (  # Levels\n                (tuple(), True),        # top\n                ((sub,), True),         # subject\n                ((sub, ses), ses)       # session\n        ):\n            if not conditional:\n                continue\n            for k in range(len(keyword_components) + 1):\n                # print(k)\n                for components in combinations(keyword_components, k):\n                    # print(components)\n                    potentialJSONs.append(\n                        pathjoin(\n                            self.root,\n                            *(prefixes +\n                              (\"_\".join(prefixes + components + (suffix,)),))))\n\n        merged_param_dict = {}\n        for json_file_path in potentialJSONs:\n            if os.path.exists(json_file_path):\n                param_dict = json.load(open(json_file_path, \"r\"))\n                merged_param_dict.update(param_dict)\n\n        return merged_param_dict\n\n    def find_match(self, target, source=None):\n\n        # Try to take the easy way out\n        if source is not None:\n            _target = source.split('.')[0] + '.' + target\n            if os.path.exists(_target):\n                return target\n\n        if target in list(self.entities.keys()):\n            candidates = list(self.entities[target].files.keys())\n        else:\n            candidates = []\n\n            for root, directories, filenames in os.walk(self.root):\n                for f in filenames:\n                    if re.search(target + '$', f):\n                        if os.path.sep == \"\\\\\":\n                            f = f.replace(\"\\\\\", \"\\\\\\\\\")\n                        candidates.append(f)\n\n        if source is None:\n            return candidates\n\n        # Walk up the file hierarchy from source, find first match\n        if not os.path.exists(source):\n            raise OSError(\"The file '%s' doesn't exist.\" % source)\n        elif not source.startswith(self.root):\n            raise ValueError(\"The file '%s' is not contained \"\n                             \"within the current project \"\n                             \"directory (%s).\" % (source, self.root))\n        rel = os.path.relpath(dirname(source), self.root)\n        sep = os.path.sep\n        chunks = rel.split(sep)\n        n_chunks = len(chunks)\n        for i in range(n_chunks, -1, -1):\n            path = pathjoin(self.root, *chunks[:i])\n            patt = path + '\\%s[^\\%s]+$' % (sep, sep)\n            if sep == \"\\\\\":\n                patt = path + '\\\\[^\\\\]+$'\n                patt = patt.replace(\"\\\\\", \"\\\\\\\\\")\n            matches = [x for x in candidates if re.search(patt, x)]\n            if matches:\n                if len(matches) == 1:\n                    return matches[0]\n                else:\n                    raise ValueError(\"Ambiguous target: more than one \"\n                                     \"candidate file found in \"\n                                     \"directory '%s'.\" % path)\n        return None\n", "path": "bids/grabbids/bids_layout.py"}, {"content": "#!/usr/bin/env python\n\nimport os\nfrom setuptools import setup, find_packages\nPACKAGES = find_packages()\n\n# Get version and release info, which is all stored in bids/version.py\nver_file = os.path.join('bids', 'version.py')\nwith open(ver_file) as f:\n    exec(f.read())\n\nopts = dict(name=NAME,\n            maintainer=MAINTAINER,\n            maintainer_email=MAINTAINER_EMAIL,\n            description=DESCRIPTION,\n            long_description=LONG_DESCRIPTION,\n            url=URL,\n            download_url=DOWNLOAD_URL,\n            license=LICENSE,\n            classifiers=CLASSIFIERS,\n            author=AUTHOR,\n            author_email=AUTHOR_EMAIL,\n            platforms=PLATFORMS,\n            version=VERSION,\n            packages=PACKAGES,\n            requires=REQUIRES,\n            install_requires=REQUIRES)\n\n\nif __name__ == '__main__':\n    setup(**opts)\n", "path": "setup.py"}], "after_files": [{"content": "import os\nimport re\nimport json\n\nfrom itertools import combinations\nfrom os.path import dirname\nfrom os.path import realpath\nfrom os.path import join as pathjoin\nfrom os.path import split as pathsplit\n\nfrom grabbit import Layout\n\n__all__ = ['BIDSLayout']\n\n\nclass BIDSLayout(Layout):\n    def __init__(self, path, config=None):\n        if config is None:\n            root = dirname(realpath(__file__))\n            config = pathjoin(root, 'config', 'bids.json')\n        super(BIDSLayout, self).__init__(path, config, dynamic_getters=True)\n\n    def get_metadata(self, path):\n        sidecarJSON = path.replace(\".nii.gz\", \".json\").replace(\".nii\", \".json\")\n        path_components = pathsplit(sidecarJSON)\n        filename_components = path_components[-1].split(\"_\")\n        ses = None\n        suffix = filename_components[-1]\n\n        sub = filename_components[0]\n        keyword_components = filename_components[1:-1]\n        if filename_components[1][:3] == \"ses\":\n            ses = filename_components[1]\n            keyword_components = filename_components[2:-1]\n\n        potentialJSONs = []\n        for prefixes, midlayer, conditional in (  # Levels\n                (tuple(), tuple(), True),        # top\n                ((sub,), tuple(), True),         # subject\n                ((sub, ), (pathsplit(path_components[-2])[-1],), True),\n                ((sub, ses), tuple(), ses),  # session\n                ((sub, ses), (pathsplit(path_components[-2])[-1],), ses)\n        ):\n            if not conditional:\n                continue\n            for k in range(len(keyword_components) + 1):\n                for components in combinations(keyword_components, k):\n                    potentialJSONs.append(\n                        pathjoin(\n                            self.root,\n                            *(prefixes + midlayer +\n                              (\"_\".join(prefixes + components + (suffix,)),))))\n\n        merged_param_dict = {}\n        for json_file_path in potentialJSONs:\n            if os.path.exists(json_file_path):\n                param_dict = json.load(open(json_file_path, \"r\"))\n                merged_param_dict.update(param_dict)\n\n        return merged_param_dict\n\n    def get_fieldmap(self, path):\n        sub = os.path.split(path)[1].split(\"_\")[0].split(\"sub-\")[1]\n        fieldmap_set = {}\n        for file in self.get(subject=sub,\n                             type='(phase1|phase2|phasediff|epi|fieldmap)',\n                             extensions=['nii.gz', 'nii']):\n            metadata = self.get_metadata(file.filename)\n            if metadata and \"IntendedFor\" in metadata.keys():\n                if path.endswith(metadata[\"IntendedFor\"]):\n                    if file.type == \"phasediff\":\n                        fieldmap_set = {\"phasediff\": file.filename,\n                                        \"magnitude1\": file.filename.replace(\n                                            \"phasediff\", \"magnitude1\"),\n                                        \"magnitude2\": file.filename.replace(\n                                            \"phasediff\", \"magnitude2\"),\n                                        \"type\": \"phasediff\"}\n                        break\n                    elif file.type == \"phase1\":\n                        fieldmap_set[\"phase1\"] = file.filename\n                        fieldmap_set[\"magnitude1\"] = \\\n                            file.filename.replace(\"phase1\", \"magnitude1\")\n                        fieldmap_set[\"type\"] = \"phase\"\n                    elif file.type == \"phase2\":\n                        fieldmap_set[\"phase2\"] = file.filename\n                        fieldmap_set[\"magnitude2\"] = \\\n                            file.filename.replace(\"phase2\", \"magnitude2\")\n                        fieldmap_set[\"type\"] = \"phase\"\n                    elif file.type == \"epi\":\n                        if \"epi\" not in fieldmap_set.keys():\n                            fieldmap_set[\"epi\"] = []\n                        fieldmap_set[\"epi\"].append(file.filename)\n                        fieldmap_set[\"type\"] = \"epi\"\n                    elif file.type == \"fieldmap\":\n                        fieldmap_set[\"fieldmap\"] = file.filename\n                        fieldmap_set[\"magnitude\"] = \\\n                            file.filename.replace(\"fieldmap\", \"magnitude\")\n                        fieldmap_set[\"type\"] = \"fieldmap\"\n        return fieldmap_set\n\n    def find_match(self, target, source=None):\n\n        # Try to take the easy way out\n        if source is not None:\n            _target = source.split('.')[0] + '.' + target\n            if os.path.exists(_target):\n                return target\n\n        if target in list(self.entities.keys()):\n            candidates = list(self.entities[target].files.keys())\n        else:\n            candidates = []\n\n            for root, directories, filenames in os.walk(self.root):\n                for f in filenames:\n                    if re.search(target + '$', f):\n                        if os.path.sep == \"\\\\\":\n                            f = f.replace(\"\\\\\", \"\\\\\\\\\")\n                        candidates.append(f)\n\n        if source is None:\n            return candidates\n\n        # Walk up the file hierarchy from source, find first match\n        if not os.path.exists(source):\n            raise OSError(\"The file '%s' doesn't exist.\" % source)\n        elif not source.startswith(self.root):\n            raise ValueError(\"The file '%s' is not contained \"\n                             \"within the current project \"\n                             \"directory (%s).\" % (source, self.root))\n        rel = os.path.relpath(dirname(source), self.root)\n        sep = os.path.sep\n        chunks = rel.split(sep)\n        n_chunks = len(chunks)\n        for i in range(n_chunks, -1, -1):\n            path = pathjoin(self.root, *chunks[:i])\n            patt = path + '\\%s[^\\%s]+$' % (sep, sep)\n            if sep == \"\\\\\":\n                patt = path + '\\\\[^\\\\]+$'\n                patt = patt.replace(\"\\\\\", \"\\\\\\\\\")\n            matches = [x for x in candidates if re.search(patt, x)]\n            if matches:\n                if len(matches) == 1:\n                    return matches[0]\n                else:\n                    raise ValueError(\"Ambiguous target: more than one \"\n                                     \"candidate file found in \"\n                                     \"directory '%s'.\" % path)\n        return None\n", "path": "bids/grabbids/bids_layout.py"}, {"content": "#!/usr/bin/env python\n\nimport os\nfrom setuptools import setup, find_packages\nPACKAGES = find_packages()\n\n# Get version and release info, which is all stored in bids/version.py\nver_file = os.path.join('bids', 'version.py')\nwith open(ver_file) as f:\n    exec(f.read())\n\nopts = dict(name=NAME,\n            maintainer=MAINTAINER,\n            maintainer_email=MAINTAINER_EMAIL,\n            description=DESCRIPTION,\n            long_description=LONG_DESCRIPTION,\n            url=URL,\n            download_url=DOWNLOAD_URL,\n            license=LICENSE,\n            classifiers=CLASSIFIERS,\n            author=AUTHOR,\n            author_email=AUTHOR_EMAIL,\n            platforms=PLATFORMS,\n            version=VERSION,\n            packages=PACKAGES,\n            package_data={'bids': ['grabbids/config/bids.json']},\n            requires=REQUIRES,\n            install_requires=REQUIRES)\n\n\nif __name__ == '__main__':\n    setup(**opts)\n", "path": "setup.py"}]}