|
1
|
|
|
import os |
|
2
|
|
|
from niprov.dependencies import Dependencies |
|
3
|
|
|
from basefile import BaseFile |
|
4
|
|
|
from dcm import DicomFile |
|
5
|
|
|
from parrec import ParrecFile |
|
6
|
|
|
from fif import FifFile |
|
7
|
|
|
from nifti import NiftiFile |
|
8
|
|
|
from niprov.cnt import NeuroscanFile |
|
9
|
|
|
|
|
10
|
|
|
|
|
11
|
|
|
class FileFactory(object): |
|
12
|
|
|
"""Creates customized File objects. |
|
13
|
|
|
|
|
14
|
|
|
Based on libraries (python packages) installed and the filename, will |
|
15
|
|
|
return an object that derives from niprov.basefile.BaseFile. |
|
16
|
|
|
""" |
|
17
|
|
|
|
|
18
|
|
|
formats = {'.par':('nibabel', ParrecFile), |
|
19
|
|
|
'.dcm':('dicom', DicomFile), |
|
20
|
|
|
'.cnt':(None, NeuroscanFile), |
|
21
|
|
|
'.nii':(None, NiftiFile), |
|
22
|
|
|
'.nii.gz':('nibabel', NiftiFile), |
|
23
|
|
|
'.fif':('mne',FifFile)} |
|
24
|
|
|
|
|
25
|
|
|
def __init__(self, dependencies=Dependencies()): |
|
26
|
|
|
self.libs = dependencies.getLibraries() |
|
27
|
|
|
self.listener = dependencies.getListener() |
|
28
|
|
|
self.dependencies = dependencies |
|
29
|
|
|
|
|
30
|
|
|
def locatedAt(self, location, provenance=None): |
|
31
|
|
|
"""Return an object to represent the image file at the given location. |
|
32
|
|
|
|
|
33
|
|
|
If no specific class is available to handle a file with the filename |
|
34
|
|
|
provided, will default to a BaseFile. Similarly, if missing the |
|
35
|
|
|
dependency to deal with the format, will fall back to a regular |
|
36
|
|
|
BaseFile. |
|
37
|
|
|
|
|
38
|
|
|
Args: |
|
39
|
|
|
location: Path to the file to represent. |
|
40
|
|
|
|
|
41
|
|
|
Returns: |
|
42
|
|
|
:class:`.BaseFile`: An object that derives from BaseFile |
|
43
|
|
|
""" |
|
44
|
|
|
if location.lower()[-2:] == 'gz': |
|
45
|
|
|
extension = '.'+('.'.join(location.lower().split('.')[-2:])) |
|
46
|
|
|
else: |
|
47
|
|
|
extension = os.path.splitext(location)[1].lower() |
|
48
|
|
|
if extension not in self.formats: |
|
49
|
|
|
return BaseFile(location, provenance=provenance, |
|
50
|
|
|
dependencies=self.dependencies) |
|
51
|
|
|
elif not self.libs.hasDependency(self.formats[extension][0]): |
|
52
|
|
|
self.listener.missingDependencyForImage( |
|
53
|
|
|
self.formats[extension][0], location) |
|
54
|
|
|
return BaseFile(location, provenance=provenance, |
|
55
|
|
|
dependencies=self.dependencies) |
|
56
|
|
|
return self.formats[extension][1](location, provenance=provenance, |
|
57
|
|
|
dependencies=self.dependencies) |
|
58
|
|
|
|
|
59
|
|
|
def fromProvenance(self, provenance): |
|
60
|
|
|
return self.locatedAt(provenance['location'], provenance) |
|
61
|
|
|
|
|
62
|
|
|
|
|
63
|
|
|
|
|
64
|
|
|
|
|
65
|
|
|
|