From a22fb99e1197042c3326585c0b2a4dd2204aa9c6 Mon Sep 17 00:00:00 2001
From: Paul McCarthy <pauld.mccarthy@gmail.com>
Date: Tue, 6 Jan 2015 13:29:50 +0000
Subject: [PATCH] All imagefile functionality is now in image module.

---
 fsl/data/image.py                | 163 ++++++++++++++++++++++++++++-
 fsl/data/imagefile.py            | 170 -------------------------------
 fsl/fslview/actions/copyimage.py |   2 +-
 fsl/tools/bet.py                 |   7 +-
 4 files changed, 162 insertions(+), 180 deletions(-)
 delete mode 100644 fsl/data/imagefile.py

diff --git a/fsl/data/image.py b/fsl/data/image.py
index f3ba245a8..30abf8c48 100644
--- a/fsl/data/image.py
+++ b/fsl/data/image.py
@@ -18,7 +18,6 @@ import numpy      as np
 import nibabel    as nib
 
 import props
-import fsl.data.imagefile   as imagefile
 import fsl.utils.transform  as transform
 
 
@@ -43,6 +42,160 @@ NIFTI_XFORM_TALAIRACH    = 3
 NIFTI_XFORM_MNI_152      = 4
 
 
+ALLOWED_EXTENSIONS = ['.nii', '.img', '.hdr', '.nii.gz', '.img.gz']
+"""The file extensions which we understand. This list is used as the default
+if if the ``allowedExts`` parameter is not passed to any of the functions in
+this module.
+"""
+
+EXTENSION_DESCRIPTIONS = ['NIFTI1 images',
+                          'ANALYZE75 images',
+                          'NIFTI1/ANALYZE75 headers',
+                          'Compressed NIFTI1 images',
+                          'Compressed ANALYZE75/NIFTI1 images']
+"""Descriptions for each of the extensions in :data:`_allowedExts`. """
+
+
+DEFAULT_EXTENSION  = '.nii.gz'
+"""The default file extension (TODO read this from ``$FSLOUTPUTTYPE``)."""
+
+
+def makeWildcard(allowedExts=None):
+    """Returns a wildcard string for use in a file dialog, to limit
+    the acceptable file types.
+    
+    :arg allowedExts: A list of strings containing the allowed file
+                      extensions.
+    """
+    
+    if allowedExts is None:
+        allowedExts  = ALLOWED_EXTENSIONS
+        descs        = EXTENSION_DESCRIPTIONS
+    else:
+        descs        = allowedExts
+
+    exts = ['*{}'.format(ext) for ext in allowedExts]
+
+    wcParts = ['|'.join((desc, ext)) for (desc, ext) in zip(descs, exts)]
+
+    print  '|'.join(wcParts)
+    return '|'.join(wcParts)
+
+
+def isSupported(filename, allowedExts=None):
+    """
+    Returns ``True`` if the given file has a supported extension, ``False``
+    otherwise.
+
+    :arg filename:    The file name to test.
+    
+    :arg allowedExts: A list of strings containing the allowed file
+                      extensions.
+    """
+
+    if allowedExts is None: allowedExts = ALLOWED_EXTENSIONS
+
+    return any(map(lambda ext: filename.endswith(ext, allowedExts)))
+
+
+def removeExtension(filename, allowedExts=None):
+    """
+    Removes the extension from the given file name. Raises a :exc:`ValueError`
+    if the file has an unsupported extension.
+
+    :arg filename:    The file name to strip.
+    
+    :arg allowedExts: A list of strings containing the allowed file
+                      extensions.    
+    """
+
+    if allowedExts is None: allowedExts = ALLOWED_EXTENSIONS
+
+    # figure out the extension of the given file
+    extMatches = map(lambda ext: filename.endswith(ext), allowedExts)
+
+    # the file does not have a supported extension
+    if not any(extMatches):
+        raise ValueError('Unsupported file type')
+
+    # figure out the length of the matched extension
+    extIdx = extMatches.index(True)
+    extLen = len(allowedExts[extIdx])
+
+    # and trim it from the file name
+    return filename[:-extLen]
+
+
+def addExtension(
+        prefix,
+        mustExist=False,
+        allowedExts=None,
+        defaultExt=None):
+    """Adds a file extension to the given file ``prefix``.
+
+    If ``mustExist`` is False (the default), and the file does not already
+    have a supported extension, the default extension is appended and the new
+    file name returned. If the prefix already has a supported extension,
+    it is returned unchanged.
+
+    If ``mustExist`` is ``True``, the function checks to see if any files
+    exist that have the given prefix, and a supported file extension.  A
+    :exc:`ValueError` is raised if:
+
+       - No files exist with the given prefix and a supported extension.
+       - More than one file exists with the given prefix, and a supported
+         extension.
+
+    Otherwise the full file name is returned.
+
+    :arg prefix:      The file name refix to modify.
+    :arg mustExist:   Whether the file must exist or not.
+    :arg allowedExts: List of allowed file extensions.
+    :arg defaultExt:  Default file extension to use.
+    """
+
+    if allowedExts is None: allowedExts = ALLOWED_EXTENSIONS
+    if defaultExt  is None: defaultExt  = DEFAULT_EXTENSION
+
+    if not mustExist:
+
+        # the provided file name already
+        # ends with a supported extension 
+        if any(map(lambda ext: prefix.endswith(ext), allowedExts)):
+            return prefix
+
+        return prefix + defaultExt
+
+    # If the provided prefix already ends with a
+    # supported extension , check to see that it exists
+    if any(map(lambda ext: prefix.endswith(ext), allowedExts)):
+        extended = [prefix]
+        
+    # Otherwise, make a bunch of file names, one per
+    # supported extension, and test to see if exactly
+    # one of them exists.
+    else:
+        extended = map(lambda ext: prefix + ext, allowedExts)
+
+    exists = map(op.isfile, extended)
+
+    # Could not find any supported file
+    # with the specified prefix
+    if not any(exists):
+        raise ValueError(
+            'Could not find a supported file with prefix {}'.format(prefix))
+
+    # Ambiguity! More than one supported
+    # file with the specified prefix
+    if len(filter(bool, exists)) > 1:
+        raise ValueError('More than one file with prefix {}'.format(prefix))
+
+    # Return the full file name of the
+    # supported file that was found
+    extIdx = exists.index(True)
+    return extended[extIdx]
+
+
 def _loadImageFile(filename):
     """Given the name of an image file, loads it using nibabel.
 
@@ -174,7 +327,7 @@ class Image(props.HasProperties):
         # The image parameter may be the name of an image file
         if isinstance(image, basestring):
             
-            nibImage, filename = _loadImageFile(imagefile.addExt(image))
+            nibImage, filename = _loadImageFile(addExtension(image))
             self.nibImage      = nibImage
             self.imageFile     = image
 
@@ -182,10 +335,10 @@ class Image(props.HasProperties):
             # the provided file name, that means that the
             # image was opened from a temporary file
             if filename != image:
-                self.name     = op.basename(self.imageFile)
+                self.name     = removeExtension(op.basename(self.imageFile))
                 self.tempFile = nibImage.get_filename()
             else:
-                self.name     = op.basename(self.imageFile)
+                self.name     = removeExtension(op.basename(self.imageFile))
 
             self.saved = True
                 
@@ -459,7 +612,7 @@ class ImageList(props.HasProperties):
 
         # TODO wx wildcard handling is buggy,
         # so i'm disabling it for now
-        # wildcard = imagefile.wildcard()
+        # wildcard = wildcard()
         dlg = wx.FileDialog(app.GetTopWindow(),
                             message='Open image file',
                             defaultDir=fromDir,
diff --git a/fsl/data/imagefile.py b/fsl/data/imagefile.py
deleted file mode 100644
index f11c78054..000000000
--- a/fsl/data/imagefile.py
+++ /dev/null
@@ -1,170 +0,0 @@
-#!/usr/bin/env python
-#
-# imagefile.py - Convenience functions for adding/stripping supported
-# file extensions to/from image file names.
-#
-# Author: Paul McCarthy <pauldmccarthy@gmail.com>
-#
-"""Convenience functions for adding/stripping supported
-file extensions to/from image file names.
-"""
-
-import os
-import os.path as op
-
-
-_allowedExts = ['.nii', '.img', '.hdr', '.nii.gz', '.img.gz']
-"""The file extensions which we understand. This list is used as the default
-if if the ``allowedExts`` parameter is not passed to any of the functions in
-this module.
-"""
-
-_descriptions = ['NIFTI1 images',
-                 'ANALYZE75 images',
-                 'NIFTI1/ANALYZE75 headers',
-                 'Compressed NIFTI1 images',
-                 'Compressed ANALYZE75/NIFTI1 images']
-"""Descriptions for each of the extensions in :data:`_allowedExts`. """
-
-
-_defaultExt  = '.nii.gz'
-"""The default file extension (TODO read this from ``$FSLOUTPUTTYPE``)."""
-
-
-def wildcard(allowedExts=None):
-    """Returns a wildcard string for use in a file dialog, to limit
-    the acceptable file types.
-    
-    :arg allowedExts: A list of strings containing the allowed file
-                      extensions.
-    """
-    
-    if allowedExts is None:
-        allowedExts  = _allowedExts
-        descs        = _descriptions
-    else:
-        descs        = allowedExts
-
-
-    exts = ['*{}'.format(ext) for ext in allowedExts]
-
-    wcParts = ['|'.join((desc, ext)) for (desc, ext) in zip(descs, exts)]
-
-    print  '|'.join(wcParts)
-    return '|'.join(wcParts)
-    
-
-
-def isSupported(filename, allowedExts=None):
-    """
-    Returns ``True`` if the given file has a supported extension, ``False``
-    otherwise.
-
-    :arg filename:    The file name to test.
-    
-    :arg allowedExts: A list of strings containing the allowed file
-                      extensions.
-    """
-
-    if allowedExts is None: allowedExts = _allowedExts
-
-    return any(map(lambda ext: filename.endswith(ext, allowedExts)))
-
-
-def removeExt(filename, allowedExts=None):
-    """
-    Removes the extension from the given file name. Raises a :exc:`ValueError`
-    if the file has an unsupported extension.
-
-    :arg filename:    The file name to strip.
-    
-    :arg allowedExts: A list of strings containing the allowed file
-                      extensions.    
-    """
-
-    if allowedExts is None: allowedExts = _allowedExts
-
-    # figure out the extension of the given file
-    extMatches = map(lambda ext: filename.endswith(ext), allowedExts)
-
-    # the file does not have a supported extension
-    if not any(extMatches):
-        raise ValueError('Unsupported file type')
-
-    # figure out the length of the matched extension
-    extIdx = extMatches.index(True)
-    extLen = len(allowedExts[extIdx])
-
-    # and trim it from the file name
-    return filename[:-extLen]
-
-    
-
-def addExt(
-        prefix,
-        mustExist=False,
-        allowedExts=None,
-        defaultExt=None):
-    """Adds a file extension to the given file ``prefix``.
-
-    If ``mustExist`` is False (the default), and the file does not already
-    have a supported extension, the default extension is appended and the new
-    file name returned. If the prefix already has a supported extension,
-    it is returned unchanged.
-
-    If ``mustExist`` is ``True``, the function checks to see if any files
-    exist that have the given prefix, and a supported file extension.  A
-    :exc:`ValueError` is raised if:
-
-       - No files exist with the given prefix and a supported extension.
-       - More than one file exists with the given prefix, and a supported
-         extension.
-
-    Otherwise the full file name is returned.
-
-    :arg prefix:      The file name refix to modify.
-    :arg mustExist:   Whether the file must exist or not.
-    :arg allowedExts: List of allowed file extensions.
-    :arg defaultExt:  Default file extension to use.
-    """
-
-    if allowedExts is None: allowedExts = _allowedExts
-    if defaultExt  is None: defaultExt  = _defaultExt
-
-    if not mustExist:
-
-        # the provided file name already
-        # ends with a supported extension 
-        if any(map(lambda ext: prefix.endswith(ext), allowedExts)):
-            return prefix
-
-        return prefix + defaultExt
-
-    # If the provided prefix already ends with a
-    # supported extension , check to see that it exists
-    if any(map(lambda ext: prefix.endswith(ext), allowedExts)):
-        extended = [prefix]
-        
-    # Otherwise, make a bunch of file names, one per
-    # supported extension, and test to see if exactly
-    # one of them exists.
-    else:
-        extended = map(lambda ext: prefix + ext, allowedExts)
-
-    exists = map(op.isfile, extended)
-
-    # Could not find any supported file
-    # with the specified prefix
-    if not any(exists):
-        raise ValueError(
-            'Could not find a supported file with prefix {}'.format(prefix))
-
-    # Ambiguity! More than one supported
-    # file with the specified prefix
-    if len(filter(bool, exists)) > 1:
-        raise ValueError('More than one file with prefix {}'.format(prefix))
-
-    # Return the full file name of the
-    # supported file that was found
-    extIdx = exists.index(True)
-    return extended[extIdx]
diff --git a/fsl/fslview/actions/copyimage.py b/fsl/fslview/actions/copyimage.py
index e27994643..e641ed164 100644
--- a/fsl/fslview/actions/copyimage.py
+++ b/fsl/fslview/actions/copyimage.py
@@ -25,7 +25,7 @@ class CopyImageAction(actions.Action):
 
         data  = np.copy(image.data)
         xform = image.voxToWorldMat
-        name  = '{} copy'.format(image.name)
+        name  = '{}_copy'.format(image.name)
         copy  = fslimage.Image(data, xform, name)
 
         self._imageList.insert(imageIdx + 1, copy)
diff --git a/fsl/tools/bet.py b/fsl/tools/bet.py
index aad1f5996..85af2b83b 100644
--- a/fsl/tools/bet.py
+++ b/fsl/tools/bet.py
@@ -9,7 +9,6 @@ from collections import OrderedDict
 
 import props
 
-import fsl.data.imagefile           as imagefile
 import fsl.data.image               as fslimage
 import fsl.utils.transform          as transform
 import fsl.fslview.displaycontext   as displaycontext
@@ -34,12 +33,12 @@ class Options(props.HasProperties):
 
     inputImage           = props.FilePath(
         exists=True,
-        suffixes=imagefile._allowedExts,
+        suffixes=fslimage.ALLOWED_EXTENSIONS,
         required=True)
     outputImage          = props.FilePath(required=True)
     t2Image              = props.FilePath(
         exists=True,
-        suffixes=imagefile._allowedExts,
+        suffixes=fslimage.ALLOWED_EXTENSIONS,
         required=lambda i: i.runChoice == '-A2')
 
     runChoice            = props.Choice(runChoices)
@@ -66,7 +65,7 @@ class Options(props.HasProperties):
         """
 
         if not valid: return
-        value = imagefile.removeExt(value)
+        value = fslimage.removeExtension(value)
         self.outputImage = value + '_brain'
 
         
-- 
GitLab