We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Unknown version string with Freesurfer 7
### Summary

After update to freesurfer 7 `import nipype.interfaces.freesurfer` returns `RuntimeError: Unknown version string` error.

### Actual behavior
```
$ python
Python 3.8.2 (default, May  7 2020, 20:00:49) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from nipype.interfaces.freesurfer import Info
200518-18:18:10,4 nipype.utils WARNING:
	 Could not check for version updates: 
Connection to server could not be made
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/anaconda3/envs/neuromet_dev/lib/python3.8/site-packages/nipype/interfaces/freesurfer/__init__.py", line 7, in <module>
    from .preprocess import (
  File "/opt/anaconda3/envs/neuromet_dev/lib/python3.8/site-packages/nipype/interfaces/freesurfer/preprocess.py", line 36, in <module>
    FSVersion = Info.looseversion().vstring
  File "/opt/anaconda3/envs/neuromet_dev/lib/python3.8/site-packages/nipype/interfaces/freesurfer/base.py", line 80, in looseversion
    raise RuntimeError("Unknown version string: " + ver)
RuntimeError: Unknown version string: freesurfer-linux-centos7_x86_64-7.1.0-20200511-813297b
```

### How to replicate the behavior

1. Install Freesurfer 7 as described [here](https://surfer.nmr.mgh.harvard.edu/fswiki//FS7_linux) with Freesurfer from [here](https://surfer.nmr.mgh.harvard.edu/fswiki/rel7downloads) (file: `freesurfer-linux-centos7_x86_64-7.1.0.tar.gz`.
2. create a fresh new conda environment with 
`conda create -n $name python=3.8 nipype`
3. open python and try to import 'nipype.interfaces.freesurfer`

### Platform details:
```
$cat /etc/lsb-release 
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04.6 LTS"
```

<!-- Please run the following code from your shell and place the output between the triple ticks, below.
python -c "import nipype; from pprint import pprint; pprint(nipype.get_info())"
-->

```
$python -c "import nipype; from pprint import pprint; pprint(nipype.get_info())"
200518-18:29:34,82 nipype.utils WARNING:
	 Could not check for version updates: 
Connection to server could not be made
{'commit_hash': '%h',
 'commit_source': 'archive substitution',
 'networkx_version': '2.4',
 'nibabel_version': '3.1.0',
 'nipype_version': '1.5.0-rc1',
 'numpy_version': '1.18.1',
 'pkg_path': '/opt/anaconda3/envs/neuromet_dev/lib/python3.8/site-packages/nipype',
 'scipy_version': '1.4.1',
 'sys_executable': '/opt/anaconda3/envs/neuromet_dev/bin/python',
 'sys_platform': 'linux',
 'sys_version': '3.8.2 (default, May  7 2020, 20:00:49) \n[GCC 7.3.0]',
 'traits_version': '5.2.0'}
```

### Execution environment

Choose one
- My python environment outside container


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `nipype/interfaces/freesurfer/base.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
3 # vi: set ft=python sts=4 ts=4 sw=4 et:
4 """The freesurfer module provides basic functions for interfacing with
5 freesurfer tools.
6 
7 Currently these tools are supported:
8 
9      * Dicom2Nifti: using mri_convert
10      * Resample: using mri_convert
11 
12 Examples
13 --------
14 See the docstrings for the individual classes for 'working' examples.
15 
16 """
17 import os
18 
19 from ... import LooseVersion
20 from ...utils.filemanip import fname_presuffix
21 from ..base import (
22     CommandLine,
23     Directory,
24     CommandLineInputSpec,
25     isdefined,
26     traits,
27     TraitedSpec,
28     File,
29     PackageInfo,
30 )
31 
32 __docformat__ = "restructuredtext"
33 
34 
35 class Info(PackageInfo):
36     """ Freesurfer subject directory and version information.
37 
38     Examples
39     --------
40 
41     >>> from nipype.interfaces.freesurfer import Info
42     >>> Info.version()  # doctest: +SKIP
43     >>> Info.subjectsdir()  # doctest: +SKIP
44 
45     """
46 
47     if os.getenv("FREESURFER_HOME"):
48         version_file = os.path.join(os.getenv("FREESURFER_HOME"), "build-stamp.txt")
49 
50     @staticmethod
51     def parse_version(raw_info):
52         return raw_info.splitlines()[0]
53 
54     @classmethod
55     def looseversion(cls):
56         """ Return a comparable version object
57 
58         If no version found, use LooseVersion('0.0.0')
59         """
60         ver = cls.version()
61         if ver is None:
62             return LooseVersion("0.0.0")
63 
64         vinfo = ver.rstrip().split("-")
65         try:
66             int(vinfo[-1], 16)
67         except ValueError:
68             githash = ""
69         else:
70             githash = "." + vinfo[-1]
71 
72         # As of FreeSurfer v6.0.0, the final component is a githash
73         if githash:
74             if vinfo[3] == "dev":
75                 # This will need updating when v6.0.1 comes out
76                 vstr = "6.0.0-dev" + githash
77             elif vinfo[5][0] == "v":
78                 vstr = vinfo[5][1:]
79             else:
80                 raise RuntimeError("Unknown version string: " + ver)
81         # Retain pre-6.0.0 heuristics
82         elif "dev" in ver:
83             vstr = vinfo[-1] + "-dev"
84         else:
85             vstr = ver.rstrip().split("-v")[-1]
86 
87         return LooseVersion(vstr)
88 
89     @classmethod
90     def subjectsdir(cls):
91         """Check the global SUBJECTS_DIR
92 
93         Parameters
94         ----------
95 
96         subjects_dir :  string
97             The system defined subjects directory
98 
99         Returns
100         -------
101 
102         subject_dir : string
103             Represents the current environment setting of SUBJECTS_DIR
104 
105         """
106         if cls.version():
107             return os.environ["SUBJECTS_DIR"]
108         return None
109 
110 
111 class FSTraitedSpec(CommandLineInputSpec):
112     subjects_dir = Directory(exists=True, desc="subjects directory")
113 
114 
115 class FSCommand(CommandLine):
116     """General support for FreeSurfer commands.
117 
118        Every FS command accepts 'subjects_dir' input.
119     """
120 
121     input_spec = FSTraitedSpec
122 
123     _subjects_dir = None
124 
125     def __init__(self, **inputs):
126         super(FSCommand, self).__init__(**inputs)
127         self.inputs.on_trait_change(self._subjects_dir_update, "subjects_dir")
128         if not self._subjects_dir:
129             self._subjects_dir = Info.subjectsdir()
130         if not isdefined(self.inputs.subjects_dir) and self._subjects_dir:
131             self.inputs.subjects_dir = self._subjects_dir
132         self._subjects_dir_update()
133 
134     def _subjects_dir_update(self):
135         if self.inputs.subjects_dir:
136             self.inputs.environ.update({"SUBJECTS_DIR": self.inputs.subjects_dir})
137 
138     @classmethod
139     def set_default_subjects_dir(cls, subjects_dir):
140         cls._subjects_dir = subjects_dir
141 
142     def run(self, **inputs):
143         if "subjects_dir" in inputs:
144             self.inputs.subjects_dir = inputs["subjects_dir"]
145         self._subjects_dir_update()
146         return super(FSCommand, self).run(**inputs)
147 
148     def _gen_fname(self, basename, fname=None, cwd=None, suffix="_fs", use_ext=True):
149         """Define a generic mapping for a single outfile
150 
151         The filename is potentially autogenerated by suffixing inputs.infile
152 
153         Parameters
154         ----------
155         basename : string (required)
156             filename to base the new filename on
157         fname : string
158             if not None, just use this fname
159         cwd : string
160             prefix paths with cwd, otherwise os.getcwd()
161         suffix : string
162             default suffix
163         """
164         if basename == "":
165             msg = "Unable to generate filename for command %s. " % self.cmd
166             msg += "basename is not set!"
167             raise ValueError(msg)
168         if cwd is None:
169             cwd = os.getcwd()
170         fname = fname_presuffix(basename, suffix=suffix, use_ext=use_ext, newpath=cwd)
171         return fname
172 
173     @property
174     def version(self):
175         ver = Info.looseversion()
176         if ver > LooseVersion("0.0.0"):
177             return ver.vstring
178 
179 
180 class FSSurfaceCommand(FSCommand):
181     """Support for FreeSurfer surface-related functions.
182     For some functions, if the output file is not specified starting with 'lh.'
183     or 'rh.', FreeSurfer prepends the prefix from the input file to the output
184     filename. Output out_file must be adjusted to accommodate this. By
185     including the full path in the filename, we can also avoid this behavior.
186     """
187 
188     @staticmethod
189     def _associated_file(in_file, out_name):
190         """Based on MRIsBuildFileName in freesurfer/utils/mrisurf.c
191 
192         If no path information is provided for out_name, use path and
193         hemisphere (if also unspecified) from in_file to determine the path
194         of the associated file.
195         Use in_file prefix to indicate hemisphere for out_name, rather than
196         inspecting the surface data structure.
197         """
198         path, base = os.path.split(out_name)
199         if path == "":
200             path, in_file = os.path.split(in_file)
201             hemis = ("lh.", "rh.")
202             if in_file[:3] in hemis and base[:3] not in hemis:
203                 base = in_file[:3] + base
204         return os.path.join(path, base)
205 
206 
207 class FSScriptCommand(FSCommand):
208     """ Support for Freesurfer script commands with log terminal_output
209     """
210 
211     _terminal_output = "file"
212     _always_run = False
213 
214     def _list_outputs(self):
215         outputs = self._outputs().get()
216         outputs["log_file"] = os.path.abspath("output.nipype")
217         return outputs
218 
219 
220 class FSScriptOutputSpec(TraitedSpec):
221     log_file = File(
222         "output.nipype", usedefault=True, exists=True, desc="The output log"
223     )
224 
225 
226 class FSTraitedSpecOpenMP(FSTraitedSpec):
227     num_threads = traits.Int(desc="allows for specifying more threads")
228 
229 
230 class FSCommandOpenMP(FSCommand):
231     """Support for FS commands that utilize OpenMP
232 
233     Sets the environment variable 'OMP_NUM_THREADS' to the number
234     of threads specified by the input num_threads.
235     """
236 
237     input_spec = FSTraitedSpecOpenMP
238 
239     _num_threads = None
240 
241     def __init__(self, **inputs):
242         super(FSCommandOpenMP, self).__init__(**inputs)
243         self.inputs.on_trait_change(self._num_threads_update, "num_threads")
244         if not self._num_threads:
245             self._num_threads = os.environ.get("OMP_NUM_THREADS", None)
246             if not self._num_threads:
247                 self._num_threads = os.environ.get("NSLOTS", None)
248         if not isdefined(self.inputs.num_threads) and self._num_threads:
249             self.inputs.num_threads = int(self._num_threads)
250         self._num_threads_update()
251 
252     def _num_threads_update(self):
253         if self.inputs.num_threads:
254             self.inputs.environ.update(
255                 {"OMP_NUM_THREADS": str(self.inputs.num_threads)}
256             )
257 
258     def run(self, **inputs):
259         if "num_threads" in inputs:
260             self.inputs.num_threads = inputs["num_threads"]
261         self._num_threads_update()
262         return super(FSCommandOpenMP, self).run(**inputs)
263 
264 
265 def no_freesurfer():
266     """Checks if FreeSurfer is NOT installed
267     used with skipif to skip tests that will
268     fail if FreeSurfer is not installed"""
269 
270     if Info.version() is None:
271         return True
272     else:
273         return False
274
```
--- 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()

```

diff --git a/nipype/interfaces/freesurfer/base.py b/nipype/interfaces/freesurfer/base.py
--- a/nipype/interfaces/freesurfer/base.py
+++ b/nipype/interfaces/freesurfer/base.py
@@ -76,6 +76,9 @@
                 vstr = "6.0.0-dev" + githash
             elif vinfo[5][0] == "v":
                 vstr = vinfo[5][1:]
+            elif len([1 for val in vinfo[3] if val == '.']) == 2:
+                "version string: freesurfer-linux-centos7_x86_64-7.1.0-20200511-813297b"
+                vstr = vinfo[3]
             else:
                 raise RuntimeError("Unknown version string: " + ver)
         # Retain pre-6.0.0 heuristics

{"golden_diff": "diff --git a/nipype/interfaces/freesurfer/base.py b/nipype/interfaces/freesurfer/base.py\n--- a/nipype/interfaces/freesurfer/base.py\n+++ b/nipype/interfaces/freesurfer/base.py\n@@ -76,6 +76,9 @@\n                 vstr = \"6.0.0-dev\" + githash\n             elif vinfo[5][0] == \"v\":\n                 vstr = vinfo[5][1:]\n+            elif len([1 for val in vinfo[3] if val == '.']) == 2:\n+                \"version string: freesurfer-linux-centos7_x86_64-7.1.0-20200511-813297b\"\n+                vstr = vinfo[3]\n             else:\n                 raise RuntimeError(\"Unknown version string: \" + ver)\n         # Retain pre-6.0.0 heuristics\n", "issue": "Unknown version string with Freesurfer 7\n### Summary\r\n\r\nAfter update to freesurfer 7 `import nipype.interfaces.freesurfer` returns `RuntimeError: Unknown version string` error.\r\n\r\n### Actual behavior\r\n```\r\n$ python\r\nPython 3.8.2 (default, May  7 2020, 20:00:49) \r\n[GCC 7.3.0] :: Anaconda, Inc. on linux\r\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\r\n>>> from nipype.interfaces.freesurfer import Info\r\n200518-18:18:10,4 nipype.utils WARNING:\r\n\t Could not check for version updates: \r\nConnection to server could not be made\r\nTraceback (most recent call last):\r\n  File \"<stdin>\", line 1, in <module>\r\n  File \"/opt/anaconda3/envs/neuromet_dev/lib/python3.8/site-packages/nipype/interfaces/freesurfer/__init__.py\", line 7, in <module>\r\n    from .preprocess import (\r\n  File \"/opt/anaconda3/envs/neuromet_dev/lib/python3.8/site-packages/nipype/interfaces/freesurfer/preprocess.py\", line 36, in <module>\r\n    FSVersion = Info.looseversion().vstring\r\n  File \"/opt/anaconda3/envs/neuromet_dev/lib/python3.8/site-packages/nipype/interfaces/freesurfer/base.py\", line 80, in looseversion\r\n    raise RuntimeError(\"Unknown version string: \" + ver)\r\nRuntimeError: Unknown version string: freesurfer-linux-centos7_x86_64-7.1.0-20200511-813297b\r\n```\r\n\r\n### How to replicate the behavior\r\n\r\n1. Install Freesurfer 7 as described [here](https://surfer.nmr.mgh.harvard.edu/fswiki//FS7_linux) with Freesurfer from [here](https://surfer.nmr.mgh.harvard.edu/fswiki/rel7downloads) (file: `freesurfer-linux-centos7_x86_64-7.1.0.tar.gz`.\r\n2. create a fresh new conda environment with \r\n`conda create -n $name python=3.8 nipype`\r\n3. open python and try to import 'nipype.interfaces.freesurfer`\r\n\r\n### Platform details:\r\n```\r\n$cat /etc/lsb-release \r\nDISTRIB_ID=Ubuntu\r\nDISTRIB_RELEASE=16.04\r\nDISTRIB_CODENAME=xenial\r\nDISTRIB_DESCRIPTION=\"Ubuntu 16.04.6 LTS\"\r\n```\r\n\r\n<!-- Please run the following code from your shell and place the output between the triple ticks, below.\r\npython -c \"import nipype; from pprint import pprint; pprint(nipype.get_info())\"\r\n-->\r\n\r\n```\r\n$python -c \"import nipype; from pprint import pprint; pprint(nipype.get_info())\"\r\n200518-18:29:34,82 nipype.utils WARNING:\r\n\t Could not check for version updates: \r\nConnection to server could not be made\r\n{'commit_hash': '%h',\r\n 'commit_source': 'archive substitution',\r\n 'networkx_version': '2.4',\r\n 'nibabel_version': '3.1.0',\r\n 'nipype_version': '1.5.0-rc1',\r\n 'numpy_version': '1.18.1',\r\n 'pkg_path': '/opt/anaconda3/envs/neuromet_dev/lib/python3.8/site-packages/nipype',\r\n 'scipy_version': '1.4.1',\r\n 'sys_executable': '/opt/anaconda3/envs/neuromet_dev/bin/python',\r\n 'sys_platform': 'linux',\r\n 'sys_version': '3.8.2 (default, May  7 2020, 20:00:49) \\n[GCC 7.3.0]',\r\n 'traits_version': '5.2.0'}\r\n```\r\n\r\n### Execution environment\r\n\r\nChoose one\r\n- My python environment outside container\r\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n\"\"\"The freesurfer module provides basic functions for interfacing with\nfreesurfer tools.\n\nCurrently these tools are supported:\n\n     * Dicom2Nifti: using mri_convert\n     * Resample: using mri_convert\n\nExamples\n--------\nSee the docstrings for the individual classes for 'working' examples.\n\n\"\"\"\nimport os\n\nfrom ... import LooseVersion\nfrom ...utils.filemanip import fname_presuffix\nfrom ..base import (\n    CommandLine,\n    Directory,\n    CommandLineInputSpec,\n    isdefined,\n    traits,\n    TraitedSpec,\n    File,\n    PackageInfo,\n)\n\n__docformat__ = \"restructuredtext\"\n\n\nclass Info(PackageInfo):\n    \"\"\" Freesurfer subject directory and version information.\n\n    Examples\n    --------\n\n    >>> from nipype.interfaces.freesurfer import Info\n    >>> Info.version()  # doctest: +SKIP\n    >>> Info.subjectsdir()  # doctest: +SKIP\n\n    \"\"\"\n\n    if os.getenv(\"FREESURFER_HOME\"):\n        version_file = os.path.join(os.getenv(\"FREESURFER_HOME\"), \"build-stamp.txt\")\n\n    @staticmethod\n    def parse_version(raw_info):\n        return raw_info.splitlines()[0]\n\n    @classmethod\n    def looseversion(cls):\n        \"\"\" Return a comparable version object\n\n        If no version found, use LooseVersion('0.0.0')\n        \"\"\"\n        ver = cls.version()\n        if ver is None:\n            return LooseVersion(\"0.0.0\")\n\n        vinfo = ver.rstrip().split(\"-\")\n        try:\n            int(vinfo[-1], 16)\n        except ValueError:\n            githash = \"\"\n        else:\n            githash = \".\" + vinfo[-1]\n\n        # As of FreeSurfer v6.0.0, the final component is a githash\n        if githash:\n            if vinfo[3] == \"dev\":\n                # This will need updating when v6.0.1 comes out\n                vstr = \"6.0.0-dev\" + githash\n            elif vinfo[5][0] == \"v\":\n                vstr = vinfo[5][1:]\n            else:\n                raise RuntimeError(\"Unknown version string: \" + ver)\n        # Retain pre-6.0.0 heuristics\n        elif \"dev\" in ver:\n            vstr = vinfo[-1] + \"-dev\"\n        else:\n            vstr = ver.rstrip().split(\"-v\")[-1]\n\n        return LooseVersion(vstr)\n\n    @classmethod\n    def subjectsdir(cls):\n        \"\"\"Check the global SUBJECTS_DIR\n\n        Parameters\n        ----------\n\n        subjects_dir :  string\n            The system defined subjects directory\n\n        Returns\n        -------\n\n        subject_dir : string\n            Represents the current environment setting of SUBJECTS_DIR\n\n        \"\"\"\n        if cls.version():\n            return os.environ[\"SUBJECTS_DIR\"]\n        return None\n\n\nclass FSTraitedSpec(CommandLineInputSpec):\n    subjects_dir = Directory(exists=True, desc=\"subjects directory\")\n\n\nclass FSCommand(CommandLine):\n    \"\"\"General support for FreeSurfer commands.\n\n       Every FS command accepts 'subjects_dir' input.\n    \"\"\"\n\n    input_spec = FSTraitedSpec\n\n    _subjects_dir = None\n\n    def __init__(self, **inputs):\n        super(FSCommand, self).__init__(**inputs)\n        self.inputs.on_trait_change(self._subjects_dir_update, \"subjects_dir\")\n        if not self._subjects_dir:\n            self._subjects_dir = Info.subjectsdir()\n        if not isdefined(self.inputs.subjects_dir) and self._subjects_dir:\n            self.inputs.subjects_dir = self._subjects_dir\n        self._subjects_dir_update()\n\n    def _subjects_dir_update(self):\n        if self.inputs.subjects_dir:\n            self.inputs.environ.update({\"SUBJECTS_DIR\": self.inputs.subjects_dir})\n\n    @classmethod\n    def set_default_subjects_dir(cls, subjects_dir):\n        cls._subjects_dir = subjects_dir\n\n    def run(self, **inputs):\n        if \"subjects_dir\" in inputs:\n            self.inputs.subjects_dir = inputs[\"subjects_dir\"]\n        self._subjects_dir_update()\n        return super(FSCommand, self).run(**inputs)\n\n    def _gen_fname(self, basename, fname=None, cwd=None, suffix=\"_fs\", use_ext=True):\n        \"\"\"Define a generic mapping for a single outfile\n\n        The filename is potentially autogenerated by suffixing inputs.infile\n\n        Parameters\n        ----------\n        basename : string (required)\n            filename to base the new filename on\n        fname : string\n            if not None, just use this fname\n        cwd : string\n            prefix paths with cwd, otherwise os.getcwd()\n        suffix : string\n            default suffix\n        \"\"\"\n        if basename == \"\":\n            msg = \"Unable to generate filename for command %s. \" % self.cmd\n            msg += \"basename is not set!\"\n            raise ValueError(msg)\n        if cwd is None:\n            cwd = os.getcwd()\n        fname = fname_presuffix(basename, suffix=suffix, use_ext=use_ext, newpath=cwd)\n        return fname\n\n    @property\n    def version(self):\n        ver = Info.looseversion()\n        if ver > LooseVersion(\"0.0.0\"):\n            return ver.vstring\n\n\nclass FSSurfaceCommand(FSCommand):\n    \"\"\"Support for FreeSurfer surface-related functions.\n    For some functions, if the output file is not specified starting with 'lh.'\n    or 'rh.', FreeSurfer prepends the prefix from the input file to the output\n    filename. Output out_file must be adjusted to accommodate this. By\n    including the full path in the filename, we can also avoid this behavior.\n    \"\"\"\n\n    @staticmethod\n    def _associated_file(in_file, out_name):\n        \"\"\"Based on MRIsBuildFileName in freesurfer/utils/mrisurf.c\n\n        If no path information is provided for out_name, use path and\n        hemisphere (if also unspecified) from in_file to determine the path\n        of the associated file.\n        Use in_file prefix to indicate hemisphere for out_name, rather than\n        inspecting the surface data structure.\n        \"\"\"\n        path, base = os.path.split(out_name)\n        if path == \"\":\n            path, in_file = os.path.split(in_file)\n            hemis = (\"lh.\", \"rh.\")\n            if in_file[:3] in hemis and base[:3] not in hemis:\n                base = in_file[:3] + base\n        return os.path.join(path, base)\n\n\nclass FSScriptCommand(FSCommand):\n    \"\"\" Support for Freesurfer script commands with log terminal_output\n    \"\"\"\n\n    _terminal_output = \"file\"\n    _always_run = False\n\n    def _list_outputs(self):\n        outputs = self._outputs().get()\n        outputs[\"log_file\"] = os.path.abspath(\"output.nipype\")\n        return outputs\n\n\nclass FSScriptOutputSpec(TraitedSpec):\n    log_file = File(\n        \"output.nipype\", usedefault=True, exists=True, desc=\"The output log\"\n    )\n\n\nclass FSTraitedSpecOpenMP(FSTraitedSpec):\n    num_threads = traits.Int(desc=\"allows for specifying more threads\")\n\n\nclass FSCommandOpenMP(FSCommand):\n    \"\"\"Support for FS commands that utilize OpenMP\n\n    Sets the environment variable 'OMP_NUM_THREADS' to the number\n    of threads specified by the input num_threads.\n    \"\"\"\n\n    input_spec = FSTraitedSpecOpenMP\n\n    _num_threads = None\n\n    def __init__(self, **inputs):\n        super(FSCommandOpenMP, self).__init__(**inputs)\n        self.inputs.on_trait_change(self._num_threads_update, \"num_threads\")\n        if not self._num_threads:\n            self._num_threads = os.environ.get(\"OMP_NUM_THREADS\", None)\n            if not self._num_threads:\n                self._num_threads = os.environ.get(\"NSLOTS\", None)\n        if not isdefined(self.inputs.num_threads) and self._num_threads:\n            self.inputs.num_threads = int(self._num_threads)\n        self._num_threads_update()\n\n    def _num_threads_update(self):\n        if self.inputs.num_threads:\n            self.inputs.environ.update(\n                {\"OMP_NUM_THREADS\": str(self.inputs.num_threads)}\n            )\n\n    def run(self, **inputs):\n        if \"num_threads\" in inputs:\n            self.inputs.num_threads = inputs[\"num_threads\"]\n        self._num_threads_update()\n        return super(FSCommandOpenMP, self).run(**inputs)\n\n\ndef no_freesurfer():\n    \"\"\"Checks if FreeSurfer is NOT installed\n    used with skipif to skip tests that will\n    fail if FreeSurfer is not installed\"\"\"\n\n    if Info.version() is None:\n        return True\n    else:\n        return False\n", "path": "nipype/interfaces/freesurfer/base.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n\"\"\"The freesurfer module provides basic functions for interfacing with\nfreesurfer tools.\n\nCurrently these tools are supported:\n\n     * Dicom2Nifti: using mri_convert\n     * Resample: using mri_convert\n\nExamples\n--------\nSee the docstrings for the individual classes for 'working' examples.\n\n\"\"\"\nimport os\n\nfrom ... import LooseVersion\nfrom ...utils.filemanip import fname_presuffix\nfrom ..base import (\n    CommandLine,\n    Directory,\n    CommandLineInputSpec,\n    isdefined,\n    traits,\n    TraitedSpec,\n    File,\n    PackageInfo,\n)\n\n__docformat__ = \"restructuredtext\"\n\n\nclass Info(PackageInfo):\n    \"\"\" Freesurfer subject directory and version information.\n\n    Examples\n    --------\n\n    >>> from nipype.interfaces.freesurfer import Info\n    >>> Info.version()  # doctest: +SKIP\n    >>> Info.subjectsdir()  # doctest: +SKIP\n\n    \"\"\"\n\n    if os.getenv(\"FREESURFER_HOME\"):\n        version_file = os.path.join(os.getenv(\"FREESURFER_HOME\"), \"build-stamp.txt\")\n\n    @staticmethod\n    def parse_version(raw_info):\n        return raw_info.splitlines()[0]\n\n    @classmethod\n    def looseversion(cls):\n        \"\"\" Return a comparable version object\n\n        If no version found, use LooseVersion('0.0.0')\n        \"\"\"\n        ver = cls.version()\n        if ver is None:\n            return LooseVersion(\"0.0.0\")\n\n        vinfo = ver.rstrip().split(\"-\")\n        try:\n            int(vinfo[-1], 16)\n        except ValueError:\n            githash = \"\"\n        else:\n            githash = \".\" + vinfo[-1]\n\n        # As of FreeSurfer v6.0.0, the final component is a githash\n        if githash:\n            if vinfo[3] == \"dev\":\n                # This will need updating when v6.0.1 comes out\n                vstr = \"6.0.0-dev\" + githash\n            elif vinfo[5][0] == \"v\":\n                vstr = vinfo[5][1:]\n            elif len([1 for val in vinfo[3] if val == '.']) == 2:\n                \"version string: freesurfer-linux-centos7_x86_64-7.1.0-20200511-813297b\"\n                vstr = vinfo[3]\n            else:\n                raise RuntimeError(\"Unknown version string: \" + ver)\n        # Retain pre-6.0.0 heuristics\n        elif \"dev\" in ver:\n            vstr = vinfo[-1] + \"-dev\"\n        else:\n            vstr = ver.rstrip().split(\"-v\")[-1]\n\n        return LooseVersion(vstr)\n\n    @classmethod\n    def subjectsdir(cls):\n        \"\"\"Check the global SUBJECTS_DIR\n\n        Parameters\n        ----------\n\n        subjects_dir :  string\n            The system defined subjects directory\n\n        Returns\n        -------\n\n        subject_dir : string\n            Represents the current environment setting of SUBJECTS_DIR\n\n        \"\"\"\n        if cls.version():\n            return os.environ[\"SUBJECTS_DIR\"]\n        return None\n\n\nclass FSTraitedSpec(CommandLineInputSpec):\n    subjects_dir = Directory(exists=True, desc=\"subjects directory\")\n\n\nclass FSCommand(CommandLine):\n    \"\"\"General support for FreeSurfer commands.\n\n       Every FS command accepts 'subjects_dir' input.\n    \"\"\"\n\n    input_spec = FSTraitedSpec\n\n    _subjects_dir = None\n\n    def __init__(self, **inputs):\n        super(FSCommand, self).__init__(**inputs)\n        self.inputs.on_trait_change(self._subjects_dir_update, \"subjects_dir\")\n        if not self._subjects_dir:\n            self._subjects_dir = Info.subjectsdir()\n        if not isdefined(self.inputs.subjects_dir) and self._subjects_dir:\n            self.inputs.subjects_dir = self._subjects_dir\n        self._subjects_dir_update()\n\n    def _subjects_dir_update(self):\n        if self.inputs.subjects_dir:\n            self.inputs.environ.update({\"SUBJECTS_DIR\": self.inputs.subjects_dir})\n\n    @classmethod\n    def set_default_subjects_dir(cls, subjects_dir):\n        cls._subjects_dir = subjects_dir\n\n    def run(self, **inputs):\n        if \"subjects_dir\" in inputs:\n            self.inputs.subjects_dir = inputs[\"subjects_dir\"]\n        self._subjects_dir_update()\n        return super(FSCommand, self).run(**inputs)\n\n    def _gen_fname(self, basename, fname=None, cwd=None, suffix=\"_fs\", use_ext=True):\n        \"\"\"Define a generic mapping for a single outfile\n\n        The filename is potentially autogenerated by suffixing inputs.infile\n\n        Parameters\n        ----------\n        basename : string (required)\n            filename to base the new filename on\n        fname : string\n            if not None, just use this fname\n        cwd : string\n            prefix paths with cwd, otherwise os.getcwd()\n        suffix : string\n            default suffix\n        \"\"\"\n        if basename == \"\":\n            msg = \"Unable to generate filename for command %s. \" % self.cmd\n            msg += \"basename is not set!\"\n            raise ValueError(msg)\n        if cwd is None:\n            cwd = os.getcwd()\n        fname = fname_presuffix(basename, suffix=suffix, use_ext=use_ext, newpath=cwd)\n        return fname\n\n    @property\n    def version(self):\n        ver = Info.looseversion()\n        if ver > LooseVersion(\"0.0.0\"):\n            return ver.vstring\n\n\nclass FSSurfaceCommand(FSCommand):\n    \"\"\"Support for FreeSurfer surface-related functions.\n    For some functions, if the output file is not specified starting with 'lh.'\n    or 'rh.', FreeSurfer prepends the prefix from the input file to the output\n    filename. Output out_file must be adjusted to accommodate this. By\n    including the full path in the filename, we can also avoid this behavior.\n    \"\"\"\n\n    @staticmethod\n    def _associated_file(in_file, out_name):\n        \"\"\"Based on MRIsBuildFileName in freesurfer/utils/mrisurf.c\n\n        If no path information is provided for out_name, use path and\n        hemisphere (if also unspecified) from in_file to determine the path\n        of the associated file.\n        Use in_file prefix to indicate hemisphere for out_name, rather than\n        inspecting the surface data structure.\n        \"\"\"\n        path, base = os.path.split(out_name)\n        if path == \"\":\n            path, in_file = os.path.split(in_file)\n            hemis = (\"lh.\", \"rh.\")\n            if in_file[:3] in hemis and base[:3] not in hemis:\n                base = in_file[:3] + base\n        return os.path.join(path, base)\n\n\nclass FSScriptCommand(FSCommand):\n    \"\"\" Support for Freesurfer script commands with log terminal_output\n    \"\"\"\n\n    _terminal_output = \"file\"\n    _always_run = False\n\n    def _list_outputs(self):\n        outputs = self._outputs().get()\n        outputs[\"log_file\"] = os.path.abspath(\"output.nipype\")\n        return outputs\n\n\nclass FSScriptOutputSpec(TraitedSpec):\n    log_file = File(\n        \"output.nipype\", usedefault=True, exists=True, desc=\"The output log\"\n    )\n\n\nclass FSTraitedSpecOpenMP(FSTraitedSpec):\n    num_threads = traits.Int(desc=\"allows for specifying more threads\")\n\n\nclass FSCommandOpenMP(FSCommand):\n    \"\"\"Support for FS commands that utilize OpenMP\n\n    Sets the environment variable 'OMP_NUM_THREADS' to the number\n    of threads specified by the input num_threads.\n    \"\"\"\n\n    input_spec = FSTraitedSpecOpenMP\n\n    _num_threads = None\n\n    def __init__(self, **inputs):\n        super(FSCommandOpenMP, self).__init__(**inputs)\n        self.inputs.on_trait_change(self._num_threads_update, \"num_threads\")\n        if not self._num_threads:\n            self._num_threads = os.environ.get(\"OMP_NUM_THREADS\", None)\n            if not self._num_threads:\n                self._num_threads = os.environ.get(\"NSLOTS\", None)\n        if not isdefined(self.inputs.num_threads) and self._num_threads:\n            self.inputs.num_threads = int(self._num_threads)\n        self._num_threads_update()\n\n    def _num_threads_update(self):\n        if self.inputs.num_threads:\n            self.inputs.environ.update(\n                {\"OMP_NUM_THREADS\": str(self.inputs.num_threads)}\n            )\n\n    def run(self, **inputs):\n        if \"num_threads\" in inputs:\n            self.inputs.num_threads = inputs[\"num_threads\"]\n        self._num_threads_update()\n        return super(FSCommandOpenMP, self).run(**inputs)\n\n\ndef no_freesurfer():\n    \"\"\"Checks if FreeSurfer is NOT installed\n    used with skipif to skip tests that will\n    fail if FreeSurfer is not installed\"\"\"\n\n    if Info.version() is None:\n        return True\n    else:\n        return False\n", "path": "nipype/interfaces/freesurfer/base.py"}]}