FifFile.inspect()   F
last analyzed

Complexity

Conditions 11

Size

Total Lines 65

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
c 1
b 0
f 0
dl 0
loc 65
rs 3.8571

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like FifFile.inspect() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
from __future__ import division
2
import logging
3
from datetime import datetime
4
from functools import partial
5
from niprov.basefile import BaseFile
6
from niprov.libraries import Libraries
7
8
9
class FifFile(BaseFile):
10
11
    def __init__(self, location, **kwargs):
12
        super(FifFile, self).__init__(location, **kwargs)
13
        self.libs = self.dependencies.getLibraries()
14
15
    def inspect(self):
16
        provenance = super(FifFile, self).inspect()
17
        """ try:
18
                img = self.libs.mne.io.Raw(self.path, allow_maxshield=True)
19
                except ValueError:
20
                    pass
21
                else:
22
                    inspect file
23
                    Return
24
        """
25
        ftypes = [
26
            ('cov', self.libs.mne.read_cov),
27
            ('epo', self.libs.mne.read_epochs),
28
            ('ave', self.libs.mne.read_evokeds),
29
            ('fwd', self.libs.mne.read_forward_solution),
30
            ('trans', self.libs.mne.read_trans),
31
            ('raw', partial(self.libs.mne.io.read_raw_fif,
32
                            allow_maxshield=True)),
33
            ('proj', self.libs.mne.read_proj),
34
        ]
35
        oldLevel = logging.getLogger('mne').getEffectiveLevel()
36
        logging.getLogger('mne').setLevel(logging.ERROR)
37
        for ftype, readfif in ftypes:
38
            try:
39
                img = readfif(self.path)
40
                if img == []:
41
                    continue
42
                break
43
            except (ValueError, IOError):
44
                continue
45
        else:
46
            ftype = 'other'
47
        logging.getLogger('mne').setLevel(oldLevel)
48
49
        if ftype == 'raw':
50
            sub = img.info['subject_info']
51
            if sub is not None:
52
                provenance['subject'] = sub['first_name']+' '+sub['last_name']
53
            provenance['project'] = img.info['proj_name']
54
            acqTS = img.info['meas_date'][0]
55
            provenance['acquired'] = datetime.fromtimestamp(acqTS)
56
            T = img.last_samp - img.first_samp + 1
57
            provenance['dimensions'] = [img.info['nchan'], T]
58
            provenance['sampling-frequency'] = img.info['sfreq']
59
            provenance['duration'] = T/img.info['sfreq']
60
61
        if ftype == 'epo':
62
            provenance['lowpass'] = img.info['lowpass']
63
            provenance['highpass'] = img.info['highpass']
64
            provenance['bad-channels'] = img.info['bads']
65
            provenance['dimensions'] = [img.events.shape[0], img.times.shape[0]]
66
67
        if ftype == 'ave':
68
            nEvokeds = len(img)
69
            provenance['dimensions'] = [nEvokeds] + list(img[0].data.shape)
70
71
        if ftype == 'cov':
72
            provenance['dimensions'] = list(img.data.shape)
73
74
        if ftype == 'proj':
75
            provenance['projection-description'] = img[0]['desc']
76
77
        provenance['fif-type'] = ftype
78
        provenance['modality'] = 'MEG'
79
        return provenance
80
81
    def attach(self, form='json'):
82
        """
83
        Attach the current provenance to the file by appending it as a
84
        json-encoded string to the 'description' header field.
85
86
        This is only attempted if the file has been inspect()-ed and
87
        has been determined to be a raw fif file.
88
89
        Args:
90
            form (str): Data format in which to serialize provenance. Defaults 
91
                to 'json'.
92
        """
93
        if 'fif-type' in self.provenance:
94
            if self.provenance['fif-type'] == 'raw':
95
                info = self.libs.mne.io.read_info(self.path)
96
                provstr = self.getProvenance(form)
97
                info['description'] = info['description']+' NIPROV:'+provstr
98
                self.libs.mne.io.write_info(self.path, info)
99
100