示例#1
0
    def has_repository (self, alias=None, path=None, ) :
        if alias :
            return self._config.has_section(self._r(utils.normpath(alias, )), )
        elif path :
            path = utils.normpath(path, )
            for i in self.repositories :
                if self.get_repository_property(i, "path", "", ) == path :
                    return True

        return False
示例#2
0
 def imap_rename(self, tag, argparser):
     old = argparser.parse()
     new = argparser.parse()
     old = utils.normpath(old)
     new = utils.normpath(new)
     mailmanager = self._account.get_mailmanager()
     if not mailmanager.folder_exists(old):
         return 'NO RENAME failed; old folder does not exist'
     if mailmanager.folder_exists(new):
         return 'NO RENAME failed; new folder already exists'
     if mailmanager.rename_folder(old, new):
         return 'OK RENAME completed'
     return 'NO RENAME failed'
示例#3
0
 def imap_lsub(self, tag, argparser):
     ref = argparser.parse()
     name = argparser.parse()
     fullname = '\\'.join([ref, name]) if ref else name
     matcher = utils.mailbox_matcher(utils.normpath(fullname))
     matched_folders = filter(lambda x: matcher.match(x),
                              self._subscriptions)
     for folder in matched_folders:
         fullname = '\\'.join([ref, folder]) if ref else folder
         path = utils.normpath(fullname)
         flags = []
         escapedpath = utils.imap_escape(path)
         self._sock.sendline('* LSUB (%s) "\\\\" "%s"' %
                   (' '.join(flags), escapedpath))
     return 'OK LSUB completed'
示例#4
0
 def imap_status(self, tag, argparser):
     original_name = argparser.parse()
     items = argparser.parse()
     name = utils.normpath(original_name)
     mailmanager = self._account.get_mailmanager()
     if not mailmanager.folder_exists(name):
         return 'NO command failed; folder does not exist'
     results = []
     for item in items:
         results.append(item)
         if item == 'MESSAGES':
             results.append(str(mailmanager.get_count(name)))
         elif item == 'RECENT':
             results.append('0')
         elif item == 'UIDVALIDITY':
             results.append(str(UID_VALIDITY))
         elif item == 'UNSEEN':
             results.append(str(mailmanager.get_count_unread(name)))
         elif item == 'UIDNEXT':
             results.append(str(mailmanager.next_uid_peek(name)))
         else:
             return 'BAD STATUS failed; item %s invalid' % (item)
     self._sock.sendline('* STATUS "%s" (%s)' %
               (utils.imap_escape(original_name), ' '.join(results)))
     return 'OK STATUS completed'
示例#5
0
    def replace_path(self, a, b):
        # clone from `http://rosettacode.org/wiki/Copy_a_string#Python`
        _command = "".join(self._command)
        (a, b) = map(utils.normpath, (a, b))

        _matches_len = list(self.RE_LEN.finditer(_command))
        _r_repo = list(self.RE_REPOSITORY.finditer(_command))

        for i in xrange(len(_r_repo) - 1, -1, -1):
            j = _r_repo[i]
            _ml = filter(lambda x: x.start(1) < j.start(2), _matches_len)[-1]

            _parsed = list(urlparse.urlsplit(j.group(2)))
            _parsed[2] = re.compile("^(%s)" % (re.escape(a),)).sub(b, utils.normpath(_parsed[2]))

            _new_path = urlparse.urlunsplit(_parsed)

            _command = "%s%s%s" % (_command[: j.start(2)], _new_path, _command[j.end(2) :])
            _command = "%s%s%s" % (
                _command[: _ml.start(1)],
                int(_command[_ml.start(1) : _ml.end(1)]) + (len(_new_path) - len(j.group(2))),
                _command[_ml.end(1) :],
            )

        return _command
示例#6
0
 def imap_list(self, tag, argparser):
     ref = argparser.parse()
     name = argparser.parse()
     # TODO: worth supporting \Marked and \Umarked attributes?
     if len(name) == 0:
         self._sock.sendline('* LIST (\Noselect) "\\\\" "%s"' %
                   (utils.imap_escape(ref)))
         return 'OK LIST completed'
     fullname = '\\'.join([ref, name]) if ref else name
     matcher = utils.mailbox_matcher(utils.normpath(fullname))
     all_folders = self._account.get_mailmanager().get_folders()
     matched_folders = filter(lambda x: matcher.match(x), all_folders)
     for folder in matched_folders:
         fullname = '\\'.join([ref, folder]) if ref else folder
         name = utils.imap_escape(utils.normpath(fullname))
         self._sock.sendline('* LIST () "\\\\" "%s"' % (name))
     return 'OK LIST completed'
示例#7
0
 def imap_subscribe(self, tag, argparser):
     name = argparser.parse()
     name = utils.normpath(name)
     mailmanager = self._account.get_mailmanager()
     if not mailmanager.folder_exists(name):
         return 'NO SUBSCRIBE failed; folder does not exist'
     self._subscriptions.add(name)
     return 'OK SUBSCRIBE completed'
示例#8
0
 def imap_delete(self, tag, argparser):
     name = argparser.parse()
     name = utils.normpath(name)
     mailmanager = self._account.get_mailmanager()
     if not mailmanager.folder_exists(name):
         return 'NO DELETE failed; folder does not exist'
     if mailmanager.remove_folder(name):
         return 'OK DELETE completed'
     return 'NO DELETE failed'
示例#9
0
 def imap_create(self, tag, argparser):
     name = argparser.parse()
     name = utils.normpath(name)
     mailmanager = self._account.get_mailmanager()
     if mailmanager.folder_exists(name):
         return 'NO CREATE failed; folder already exists'
     if mailmanager.add_folder(name):
         return 'OK CREATE completed'
     return 'NO CREATE failed'
示例#10
0
    def get_repository_path(self,):
        _command = "".join(self._command)

        _r_repo = list(self.RE_REPOSITORY.finditer(_command))
        for i in xrange(len(_r_repo) - 1, -1, -1):
            j = _r_repo[i]

            _parsed = list(urlparse.urlsplit(j.group(2)))
            return utils.normpath(_parsed[2])
示例#11
0
    def get_alias(self, avalable_aliases):
        _aliases = list(avalable_aliases)[:]
        _aliases.sort()
        _aliases.reverse()

        _path = self.get_repository_path()
        for i in _aliases:
            if re.compile("^%s" % re.escape(utils.normpath(i))).search(_path):
                return i

        return None
示例#12
0
文件: storage.py 项目: relic7/nd1404
 def relpath(self, path, in_cache=False):
     """ This is the inverse of abspath
     """
     path = os.path.abspath(path)
     path = normpath(path)
     rel = os.path.relpath(path, self._root)
     if in_cache:
         if rel.startswith('..'):
             raise StorageError('%s is not under %s' % (path, self._root))
     else:
         return rel
示例#13
0
    def get_repository_property (self, alias, p, default=None, ) :
        if not self.has_repository(alias, ) :
            raise KeyError("'%s' does not exist." % alias, )

        if p not in self.default_repository :
            raise KeyError("'%s' does not exist." % p, )

        try :
            _r = self._config.get(self._r(utils.normpath(alias), ), p, )
        except :
            return default

        return list(self.to_python_properties(
            datatype=self.datatype_repository, **{p: _r, }))[0][1]
示例#14
0
def plot_spectrum(signal=None, sampling_rate=1000., path=None, show=True):
    """Plot the power spectrum of a signal (one-sided).

    Parameters
    ----------
    signal : array
        Input signal.
    sampling_rate : int, float, optional
        Sampling frequency (Hz).
    path : str, optional
        If provided, the plot will be saved to the specified file.
    show : bool, optional
        If True, show the plot immediately.

    """

    freqs, power = st.power_spectrum(signal,
                                     sampling_rate,
                                     pad=0,
                                     pow2=False,
                                     decibel=True)

    fig = plt.figure()
    ax = fig.add_subplot(111)

    ax.plot(freqs, power, linewidth=MAJOR_LW)
    ax.set_xlabel('Frequency (Hz)')
    ax.set_ylabel('Power (dB)')
    ax.grid()

    # make layout tight
    fig.tight_layout()

    # save to file
    if path is not None:
        path = utils.normpath(path)
        root, ext = os.path.splitext(path)
        ext = ext.lower()
        if ext not in ['png', 'jpg']:
            path = root + '.png'

        fig.savefig(path, dpi=200, bbox_inches='tight')

    # show
    if show:
        plt.show()
    else:
        # close
        plt.close(fig)
示例#15
0
    def update_repository (self, alias, **properties) :
        if not self.has_repository(alias, ) :
            raise KeyError("'%s' does not exist." % alias, )

        for i, j in self.to_config_properties(
                self.default_repository, **properties) :
            if i == "path" and j :
                j = utils.normpath(j, )

            if j is None :
                self._config.remove_option(self._r(alias), i, )
            else :
                self._config.set(self._r(alias), i, j, )

        return self
示例#16
0
 def imap_copy(self, tag, argparser, uid_command=False):
     msgset = argparser.parse()
     destination = argparser.parse()
     destination = utils.normpath(destination)
     mailmanager = self._account.get_mailmanager()
     if not mailmanager.folder_exists(destination):
         return 'NO [TRYCREATE] COPY failed; destination does not exist'
     for seq, uid in self._expand_msgset(msgset, uid_command):
         msg = mailmanager.get_message(self._mailbox, uid=uid)
         if not msg:
             continue
         # TODO: set flags from old message
         # TODO: set timestamp from old message
         mailmanager.add_message(destination, msg)
     return 'OK COPY completed'
示例#17
0
文件: storage.py 项目: relic7/nd1404
    def abspath(self, path, in_cache=False):
        """absolute path of path, relative to the cache_dir defined in mprocessor.cfg

        If the argument path is already an absolute path, returns it unchanged, unless
        in_cache = True. In this case raise an exception unless path points inside 
        cache_dir
        """
        if os.path.isabs(path):
            abs = path
        else:
            abs = os.path.abspath(os.path.join(self._root, path))
        abs = normpath(abs)
        if in_cache:
            if not abs.startswith(self._root):
                raise StorageError('%s is not under %s' % (abs, self._root))
        return abs
示例#18
0
    def add_repository (self, path, alias, **properties) :
        if self.has_repository(alias, ) :
            raise KeyError("'%s' already exists." % alias, )

        self._config.add_section(self._r(alias), )

        if not utils.is_remote_repository_path(path, ) :
            path = utils.normpath(path, )

        properties["path"] = path
        if "description" in properties :
            properties["description"] = " ".join(
                    properties.get("description"), )

        for i, j in self.to_config_properties(
                self.default_repository, **properties) :
            self._config.set(self._r(alias), i, j, )

        return self
示例#19
0
    def get_client_base(self, alias):
        _command = "".join(self._command)
        _alias = utils.normpath(alias)
        _base = None

        _r_repo = list(self.RE_REPOSITORY.finditer(_command))
        for i in xrange(len(_r_repo) - 1, -1, -1):
            j = _r_repo[i]

            _parsed = list(urlparse.urlsplit(j.group(2)))
            _parsed[2] = _alias
            _base = urlparse.urlunsplit(_parsed)

            break

        if _base is None:
            raise _exceptions.BAD_SVN_REPOSITORY_COMMAND

        return _base
示例#20
0
    def rename_repository (self, old, new, ) :
        if not self.has_repository(old, ) :
            raise KeyError("'%s' does not exist." % old, )

        new = utils.normpath(new, )
        if self.has_repository(new, ) :
            raise KeyError("'%s' alreay exists." % new, )

        _r = self.rename_section(self._r(old), self._r(new), )

        # apply the changes to the `repository` property in user
        for _username in self.users :
            _l = self.get_user_property(_username, "repository", list(), )
            if old not in _l :
                continue

            _l[_l.index(old, )] = new
            self.update_user(_username, repository=_l, )

        return _r
示例#21
0
 def _select(self, argparser):
     name = argparser.parse()
     name = utils.normpath(name)
     mailmanager = self._account.get_mailmanager()
     if not mailmanager.folder_exists(name):
         return 'NO command failed; folder does not exist'
     self._mailbox = name
     self._status = SELECTED
     msg_count = self._account.get_mailmanager().get_count(self._mailbox)
     self._sock.sendline('* FLAGS (\\Seen \\Answered \\Flagged \\Deleted '
                         + '\\Draft)')
     self._sock.sendline('* %i EXISTS' % msg_count)
     self._sock.sendline('* %i RECENT' % msg_count)
     self._sock.sendline('* OK [PERMANENTFLAGS (\\Deleted \\Seen \\Flagged '
                         + '\\Draft \\Answered)]')
     self._sock.sendline('* OK [UIDVALIDITY %i] UIDs valid' % UID_VALIDITY)
     self._sock.sendline('* OK [UIDNEXT %i] Predicted next UID' %
                         (mailmanager.next_uid_peek(self._mailbox)))
     #self._sock.sendline('* OK [UNSEEN 1] Message 1 is first unseen')  # TODO
     return ('OK [READ-%s] SELECT or EXAMINE completed' %
             ('ONLY' if self._readonly else 'WRITE'))
示例#22
0
    def getAllObjectsMetadataIndexedByPath(self, path, ignored_exts=None, prefix=None):
        """
            {
                u'/volume/toto' : {u'name': '/volume/toto', 'hash' : 'md5hash', 'last_modified': '', 'bytes': '193'}
            }
        """
        logger.info("Building local file list & checksums")
        files_dict = {}
        files = generateTree(path)
        for file in files:
            file = normpath(file)
            if ignored_exts is not None:
                ignore_file = False
                for ign_ext in ignored_exts:
                    if file.endswith(ign_ext):
                        logger.debug("Ignoring file %s (based on extension)"%(file))
                        ignore_file = True
                        continue
            if ignore_file:
                continue

            is_dir = os.path.isdir(file)
            if is_dir:
                md5_hash = None
            else:
                md5_hash = md5(file)
            file_metadata = {
                'name': file,
                'hash': md5_hash,
                'last_modified': datetime.fromtimestamp(os.path.getmtime(file)),
                'bytes': os.path.getsize(file),
                'is_dir': is_dir
                }
            if prefix is not None:
                file_k = file.replace(prefix, "")
            files_dict[file_k] = file_metadata
        logger.info("Done %s files found"%len(files_dict))
        return files_dict
示例#23
0
 def imap_append(self, tag, argparser):
     name = argparser.parse()
     args = []
     while len(argparser._arg) > 0:
         nextarg = argparser.parse()
         args.append(nextarg)
     msg = args[-1]
     flags = []
     timestamp = datetime.datetime.now()
     # TODO: implement time parser function
     if len(args) > 1:
         if isinstance(args[0], list):
             flags = args[0]
             if len(args) == 3:
                 timestamp = utils.parse_time(args[1])
         else:
             timestamp = utils.parse_time(args[0])
     # TODO: set timestamp
     # TODO: set flags
     name = utils.normpath(name)
     if not self._account.get_mailmanager().folder_exists(name):
         return 'NO [TRYCREATE] APPEND failed; folder does not exist'
     self._account.get_mailmanager().add_message(name, msg)
     return 'OK APPEND completed'
示例#24
0
def plot_ecg(ts=None,
             raw=None,
             filtered=None,
             rpeaks=None,
             templates_ts=None,
             templates=None,
             heart_rate_ts=None,
             heart_rate=None,
             path=None,
             show=False):
    """Create a summary plot from the output of signals.ecg.ecg.

    Parameters
    ----------
    ts : array
        Signal time axis reference (seconds).
    raw : array
        Raw ECG signal.
    filtered : array
        Filtered ECG signal.
    rpeaks : array
        R-peak location indices.
    templates_ts : array
        Templates time axis reference (seconds).
    templates : array
        Extracted heartbeat templates.
    heart_rate_ts : array
        Heart rate time axis reference (seconds).
    heart_rate : array
        Instantaneous heart rate (bpm).
    path : str, optional
        If provided, the plot will be saved to the specified file.
    show : bool, optional
        If True, show the plot immediately.

    """

    fig = plt.figure()
    fig.suptitle('ECG Summary')
    gs = gridspec.GridSpec(6, 2)
    # print(gs)
    # raw signal
    ax1 = fig.add_subplot(gs[:2, 0])

    ax1.plot(ts, raw, linewidth=MAJOR_LW, label='Raw')

    ax1.set_ylabel('Amplitude')
    ax1.legend()
    ax1.grid()

    # filtered signal with rpeaks
    ax2 = fig.add_subplot(gs[2:4, 0], sharex=ax1)

    ymin = np.min(filtered)
    ymax = np.max(filtered)
    alpha = 0.1 * (ymax - ymin)
    ymax += alpha
    ymin -= alpha

    ax2.plot(ts, filtered, linewidth=MAJOR_LW, label='Filtered')
    ax2.vlines(ts[rpeaks],
               ymin,
               ymax,
               color='m',
               linewidth=MINOR_LW,
               label='R-peaks')

    ax2.set_ylabel('Amplitude')
    ax2.legend()
    ax2.grid()

    # heart rate
    ax3 = fig.add_subplot(gs[4:, 0], sharex=ax1)

    ax3.plot(heart_rate_ts, heart_rate, linewidth=MAJOR_LW, label='Heart Rate')

    ax3.set_xlabel('Time (s)')
    ax3.set_ylabel('Heart Rate (bpm)')
    ax3.legend()
    ax3.grid()

    # templates
    ax4 = fig.add_subplot(gs[1:5, 1])

    ax4.plot(templates_ts, templates.T, 'm', linewidth=MINOR_LW, alpha=0.7)

    ax4.set_xlabel('Time (s)')
    ax4.set_ylabel('Amplitude')
    ax4.set_title('Templates')
    ax4.grid()

    # make layout tight
    gs.tight_layout(fig)

    # save to file
    if path is not None:
        path = utils.normpath(path)
        root, ext = os.path.splitext(path)
        ext = ext.lower()
        if ext not in ['png', 'jpg']:
            path = root + '.png'

        fig.savefig(path, dpi=200, bbox_inches='tight')

    # show
    if show:
        plt.show()
    else:
        # close
        plt.close(fig)
示例#25
0
def plot_filter(ftype='FIR',
                band='lowpass',
                order=None,
                frequency=None,
                sampling_rate=1000.,
                path=None,
                show=True,
                **kwargs):
    """Plot the frequency response of the filter specified with the given
    parameters.

    Parameters
    ----------
    ftype : str
        Filter type:
            * Finite Impulse Response filter ('FIR');
            * Butterworth filter ('butter');
            * Chebyshev filters ('cheby1', 'cheby2');
            * Elliptic filter ('ellip');
            * Bessel filter ('bessel').
    band : str
        Band type:
            * Low-pass filter ('lowpass');
            * High-pass filter ('highpass');
            * Band-pass filter ('bandpass');
            * Band-stop filter ('bandstop').
    order : int
        Order of the filter.
    frequency : int, float, list, array
        Cutoff frequencies; format depends on type of band:
            * 'lowpass' or 'bandpass': single frequency;
            * 'bandpass' or 'bandstop': pair of frequencies.
    sampling_rate : int, float, optional
        Sampling frequency (Hz).
    path : str, optional
        If provided, the plot will be saved to the specified file.
    show : bool, optional
        If True, show the plot immediately.
    ``**kwargs`` : dict, optional
        Additional keyword arguments are passed to the underlying
        scipy.signal function.

    """

    # get filter
    b, a = st.get_filter(ftype=ftype,
                         band=band,
                         order=order,
                         frequency=frequency,
                         sampling_rate=sampling_rate,
                         **kwargs)

    # plot
    fig = _plot_filter(b, a, sampling_rate)

    # make layout tight
    fig.tight_layout()

    # save to file
    if path is not None:
        path = utils.normpath(path)
        root, ext = os.path.splitext(path)
        ext = ext.lower()
        if ext not in ['png', 'jpg']:
            path = root + '.png'

        fig.savefig(path, dpi=200, bbox_inches='tight')

    # show
    if show:
        plt.show()
    else:
        # close
        plt.close(fig)
示例#26
0
def plot_eeg(ts=None,
             raw=None,
             filtered=None,
             labels=None,
             features_ts=None,
             theta=None,
             alpha_low=None,
             alpha_high=None,
             beta=None,
             gamma=None,
             plf_pairs=None,
             plf=None,
             path=None,
             show=False):
    """Create a summary plot from the output of signals.eeg.eeg.

    Parameters
    ----------
    ts : array
        Signal time axis reference (seconds).
    raw : array
        Raw EEG signal.
    filtered : array
        Filtered EEG signal.
    labels : list
        Channel labels.
    features_ts : array
        Features time axis reference (seconds).
    theta : array
        Average power in the 4 to 8 Hz frequency band; each column is one
        EEG channel.
    alpha_low : array
        Average power in the 8 to 10 Hz frequency band; each column is one
        EEG channel.
    alpha_high : array
        Average power in the 10 to 13 Hz frequency band; each column is one
        EEG channel.
    beta : array
        Average power in the 13 to 25 Hz frequency band; each column is one
        EEG channel.
    gamma : array
        Average power in the 25 to 40 Hz frequency band; each column is one
        EEG channel.
    plf_pairs : list
        PLF pair indices.
    plf : array
        PLF matrix; each column is a channel pair.
    path : str, optional
        If provided, the plot will be saved to the specified file.
    show : bool, optional
        If True, show the plot immediately.

    """

    nrows = MAX_ROWS
    alpha = 2.

    figs = []

    # raw
    fig = _plot_multichannel(ts=ts,
                             signal=raw,
                             labels=labels,
                             nrows=nrows,
                             alpha=alpha,
                             title='EEG Summary - Raw',
                             xlabel='Time (s)',
                             ylabel='Amplitude')
    figs.append(('_Raw', fig))

    # filtered
    fig = _plot_multichannel(ts=ts,
                             signal=filtered,
                             labels=labels,
                             nrows=nrows,
                             alpha=alpha,
                             title='EEG Summary - Filtered',
                             xlabel='Time (s)',
                             ylabel='Amplitude')
    figs.append(('_Filtered', fig))

    # band-power
    names = ('Theta Band', 'Lower Alpha Band', 'Higher Alpha Band',
             'Beta Band', 'Gamma Band')
    args = (theta, alpha_low, alpha_high, beta, gamma)
    for n, a in zip(names, args):
        fig = _plot_multichannel(ts=features_ts,
                                 signal=a,
                                 labels=labels,
                                 nrows=nrows,
                                 alpha=alpha,
                                 title='EEG Summary - %s' % n,
                                 xlabel='Time (s)',
                                 ylabel='Power')
        figs.append(('_' + n.replace(' ', '_'), fig))

    # PLF
    plf_labels = ['%s vs %s' % (labels[p[0]], labels[p[1]]) for p in plf_pairs]
    fig = _plot_multichannel(ts=features_ts,
                             signal=plf,
                             labels=plf_labels,
                             nrows=nrows,
                             alpha=alpha,
                             title='EEG Summary - Phase-Locking Factor',
                             xlabel='Time (s)',
                             ylabel='PLF')
    figs.append(('_PLF', fig))

    # save to file
    if path is not None:
        path = utils.normpath(path)
        root, ext = os.path.splitext(path)
        ext = ext.lower()
        if ext not in ['png', 'jpg']:
            ext = '.png'

        for n, fig in figs:
            path = root + n + ext
            fig.savefig(path, dpi=200, bbox_inches='tight')

    # show
    if show:
        plt.show()
    else:
        # close
        for _, fig in figs:
            plt.close(fig)
示例#27
0
def plot_resp(ts=None,
              raw=None,
              filtered=None,
              zeros=None,
              resp_rate_ts=None,
              resp_rate=None,
              path=None,
              show=False):
    """Create a summary plot from the output of signals.bvp.bvp.

    Parameters
    ----------
    ts : array
        Signal time axis reference (seconds).
    raw : array
        Raw Resp signal.
    filtered : array
        Filtered Resp signal.
    zeros : array
        Indices of Respiration zero crossings.
    resp_rate_ts : array
        Respiration rate time axis reference (seconds).
    resp_rate : array
        Instantaneous respiration rate (Hz).
    path : str, optional
        If provided, the plot will be saved to the specified file.
    show : bool, optional
        If True, show the plot immediately.

    """

    fig = plt.figure()
    fig.suptitle('Respiration Summary')

    # raw signal
    ax1 = fig.add_subplot(311)

    ax1.plot(ts, raw, linewidth=MAJOR_LW, label='Raw')

    ax1.set_ylabel('Amplitude')
    ax1.legend()
    ax1.grid()

    # filtered signal with zeros
    ax2 = fig.add_subplot(312, sharex=ax1)

    ymin = np.min(filtered)
    ymax = np.max(filtered)
    alpha = 0.1 * (ymax - ymin)
    ymax += alpha
    ymin -= alpha

    ax2.plot(ts, filtered, linewidth=MAJOR_LW, label='Filtered')
    ax2.vlines(ts[zeros],
               ymin,
               ymax,
               color='m',
               linewidth=MINOR_LW,
               label='Zero crossings')

    ax2.set_ylabel('Amplitude')
    ax2.legend()
    ax2.grid()

    # heart rate
    ax3 = fig.add_subplot(313, sharex=ax1)

    ax3.plot(resp_rate_ts,
             resp_rate,
             linewidth=MAJOR_LW,
             label='Respiration Rate')

    ax3.set_xlabel('Time (s)')
    ax3.set_ylabel('Respiration Rate (Hz)')
    ax3.legend()
    ax3.grid()

    # make layout tight
    fig.tight_layout()

    # save to file
    if path is not None:
        path = utils.normpath(path)
        root, ext = os.path.splitext(path)
        ext = ext.lower()
        if ext not in ['png', 'jpg']:
            path = root + '.png'

        fig.savefig(path, dpi=200, bbox_inches='tight')

    # show
    if show:
        plt.show()
    else:
        # close
        plt.close(fig)
示例#28
0
def plot_emg(ts=None,
             sampling_rate=None,
             raw=None,
             filtered=None,
             onsets=None,
             processed=None,
             path=None,
             show=False):
    """Create a summary plot from the output of signals.emg.emg.

    Parameters
    ----------
    ts : array
        Signal time axis reference (seconds).
    sampling_rate : int, float
        Sampling frequency (Hz).
    raw : array
        Raw EMG signal.
    filtered : array
        Filtered EMG signal.
    onsets : array
        Indices of EMG pulse onsets.
    processed : array, optional
        Processed EMG signal according to the chosen onset detector.
    path : str, optional
        If provided, the plot will be saved to the specified file.
    show : bool, optional
        If True, show the plot immediately.

    """

    fig = plt.figure()
    fig.suptitle('EMG Summary')

    if processed is not None:
        ax1 = fig.add_subplot(311)
        ax2 = fig.add_subplot(312, sharex=ax1)
        ax3 = fig.add_subplot(313)

        # processed signal
        L = len(processed)
        T = (L - 1) / sampling_rate
        ts_processed = np.linspace(0, T, L, endpoint=False)
        ax3.plot(ts_processed,
                 processed,
                 linewidth=MAJOR_LW,
                 label='Processed')
        ax3.set_xlabel('Time (s)')
        ax3.set_ylabel('Amplitude')
        ax3.legend()
        ax3.grid()
    else:
        ax1 = fig.add_subplot(211)
        ax2 = fig.add_subplot(212, sharex=ax1)

    # raw signal
    ax1.plot(ts, raw, linewidth=MAJOR_LW, label='Raw')

    ax1.set_ylabel('Amplitude')
    ax1.legend()
    ax1.grid()

    # filtered signal with onsets
    ymin = np.min(filtered)
    ymax = np.max(filtered)
    alpha = 0.1 * (ymax - ymin)
    ymax += alpha
    ymin -= alpha

    ax2.plot(ts, filtered, linewidth=MAJOR_LW, label='Filtered')
    ax2.vlines(ts[onsets],
               ymin,
               ymax,
               color='m',
               linewidth=MINOR_LW,
               label='Onsets')

    ax2.set_xlabel('Time (s)')
    ax2.set_ylabel('Amplitude')
    ax2.legend()
    ax2.grid()

    # make layout tight
    fig.tight_layout()

    # save to file
    if path is not None:
        path = utils.normpath(path)
        root, ext = os.path.splitext(path)
        ext = ext.lower()
        if ext not in ['png', 'jpg']:
            path = root + '.png'

        fig.savefig(path, dpi=200, bbox_inches='tight')

    # show
    if show:
        plt.show()
    else:
        # close
        plt.close(fig)
示例#29
0
def plot_eda(ts=None,
             raw=None,
             filtered=None,
             onsets=None,
             peaks=None,
             amplitudes=None,
             path=None,
             show=False):
    """Create a summary plot from the output of signals.eda.eda.

    Parameters
    ----------
    ts : array
        Signal time axis reference (seconds).
    raw : array
        Raw EDA signal.
    filtered : array
        Filtered EDA signal.
    onsets : array
        Indices of SCR pulse onsets.
    peaks : array
        Indices of the SCR peaks.
    amplitudes : array
        SCR pulse amplitudes.
    path : str, optional
        If provided, the plot will be saved to the specified file.
    show : bool, optional
        If True, show the plot immediately.

    """

    fig = plt.figure()
    fig.suptitle('EDA Summary')

    # raw signal
    ax1 = fig.add_subplot(311)

    ax1.plot(ts, raw, linewidth=MAJOR_LW, label='raw')

    ax1.set_ylabel('Amplitude')
    ax1.legend()
    ax1.grid()

    # filtered signal with onsets, peaks
    ax2 = fig.add_subplot(312, sharex=ax1)

    ymin = np.min(filtered)
    ymax = np.max(filtered)
    alpha = 0.1 * (ymax - ymin)
    ymax += alpha
    ymin -= alpha

    ax2.plot(ts, filtered, linewidth=MAJOR_LW, label='Filtered')
    ax2.vlines(ts[onsets],
               ymin,
               ymax,
               color='m',
               linewidth=MINOR_LW,
               label='Onsets')
    ax2.vlines(ts[peaks],
               ymin,
               ymax,
               color='g',
               linewidth=MINOR_LW,
               label='Peaks')

    ax2.set_ylabel('Amplitude')
    ax2.legend()
    ax2.grid()

    # amplitudes
    ax3 = fig.add_subplot(313, sharex=ax1)

    ax3.plot(ts[onsets], amplitudes, linewidth=MAJOR_LW, label='Amplitudes')

    ax3.set_xlabel('Time (s)')
    ax3.set_ylabel('Amplitude')
    ax3.legend()
    ax3.grid()

    # make layout tight
    fig.tight_layout()

    # save to file
    if path is not None:
        path = utils.normpath(path)
        root, ext = os.path.splitext(path)
        ext = ext.lower()
        if ext not in ['png', 'jpg']:
            path = root + '.png'

        fig.savefig(path, dpi=200, bbox_inches='tight')

    # show
    if show:
        plt.show()
    else:
        # close
        plt.close(fig)
示例#30
0
def plot_clustering(data=None, clusters=None, path=None, show=False):
    """Create a summary plot of a data clustering.

    Parameters
    ----------
    data : array
        An m by n array of m data samples in an n-dimensional space.
    clusters : dict
        Dictionary with the sample indices (rows from `data`) for each cluster.
    path : str, optional
        If provided, the plot will be saved to the specified file.
    show : bool, optional
        If True, show the plot immediately.

    """

    fig = plt.figure()
    fig.suptitle('Clustering Summary')

    ymin, ymax = _yscaling(data, alpha=1.2)

    # determine number of clusters
    keys = list(clusters)
    nc = len(keys)

    if nc <= 4:
        nrows = 2
        ncols = 4
    else:
        area = nc + 4

        # try to fit to a square
        nrows = int(np.ceil(np.sqrt(area)))

        if nrows > MAX_ROWS:
            # prefer to increase number of columns
            nrows = MAX_ROWS

        ncols = int(np.ceil(area / float(nrows)))

    # plot grid
    gs = gridspec.GridSpec(nrows, ncols, hspace=0.2, wspace=0.2)

    # global axes
    ax_global = fig.add_subplot(gs[:2, :2])

    # cluster axes
    c_grid = np.ones((nrows, ncols), dtype='bool')
    c_grid[:2, :2] = False
    c_rows, c_cols = np.nonzero(c_grid)

    # generate color map
    x = np.linspace(0., 1., nc)
    cmap = plt.get_cmap('rainbow')

    for i, k in enumerate(keys):
        aux = data[clusters[k]]
        color = cmap(x[i])
        label = 'Cluster %s' % k
        ax = fig.add_subplot(gs[c_rows[i], c_cols[i]], sharex=ax_global)
        ax.set_ylim([ymin, ymax])
        ax.set_title(label)
        ax.grid()

        if len(aux) > 0:
            ax_global.plot(aux.T, color=color, lw=MINOR_LW, alpha=0.7)
            ax.plot(aux.T, color=color, lw=MAJOR_LW)

    ax_global.set_title('All Clusters')
    ax_global.set_ylim([ymin, ymax])
    ax_global.grid()

    # make layout tight
    gs.tight_layout(fig)

    # save to file
    if path is not None:
        path = utils.normpath(path)
        root, ext = os.path.splitext(path)
        ext = ext.lower()
        if ext not in ['png', 'jpg']:
            path = root + '.png'

        fig.savefig(path, dpi=200, bbox_inches='tight')

    # show
    if show:
        plt.show()
    else:
        # close
        plt.close(fig)
示例#31
0
def plot_biometrics(assessment=None, eer_idx=None, path=None, show=False):
    """Create a summary plot of a biometrics test run.

    Parameters
    ----------
    assessment : dict
        Classification assessment results.
    eer_idx : int, optional
        Classifier reference index for the Equal Error Rate.
    path : str, optional
        If provided, the plot will be saved to the specified file.
    show : bool, optional
        If True, show the plot immediately.

    """

    fig = plt.figure()
    fig.suptitle('Biometrics Summary')

    c_sub = ['#008bff', '#8dd000']
    c_global = ['#0037ff', 'g']

    ths = assessment['thresholds']

    auth_ax = fig.add_subplot(121)
    id_ax = fig.add_subplot(122)

    # subject results
    for sub in six.iterkeys(assessment['subject']):
        auth_rates = assessment['subject'][sub]['authentication']['rates']
        _ = _plot_rates(ths,
                        auth_rates, ['FAR', 'FRR'],
                        lw=MINOR_LW,
                        colors=c_sub,
                        alpha=0.4,
                        eer_idx=None,
                        labels=False,
                        ax=auth_ax)

        id_rates = assessment['subject'][sub]['identification']['rates']
        _ = _plot_rates(ths,
                        id_rates, ['MR', 'RR'],
                        lw=MINOR_LW,
                        colors=c_sub,
                        alpha=0.4,
                        eer_idx=None,
                        labels=False,
                        ax=id_ax)

    # global results
    auth_rates = assessment['global']['authentication']['rates']
    _ = _plot_rates(ths,
                    auth_rates, ['FAR', 'FRR'],
                    lw=MAJOR_LW,
                    colors=c_global,
                    alpha=1,
                    eer_idx=eer_idx,
                    labels=True,
                    ax=auth_ax)

    id_rates = assessment['global']['identification']['rates']
    _ = _plot_rates(ths,
                    id_rates, ['MR', 'RR'],
                    lw=MAJOR_LW,
                    colors=c_global,
                    alpha=1,
                    eer_idx=eer_idx,
                    labels=True,
                    ax=id_ax)

    # set labels and grids
    auth_ax.set_xlabel('Threshold')
    auth_ax.set_ylabel('Authentication')
    auth_ax.grid()
    auth_ax.legend()

    id_ax.set_xlabel('Threshold')
    id_ax.set_ylabel('Identification')
    id_ax.grid()
    id_ax.legend()

    # make layout tight
    fig.tight_layout()

    # save to file
    if path is not None:
        path = utils.normpath(path)
        root, ext = os.path.splitext(path)
        ext = ext.lower()
        if ext not in ['png', 'jpg']:
            path = root + '.png'

        fig.savefig(path, dpi=200, bbox_inches='tight')

    # show
    if show:
        plt.show()
    else:
        # close
        plt.close(fig)
示例#32
0
 def imap_unsubscribe(self, tag, argparser):
     name = argparser.parse()
     name = utils.normpath(name)
     if name in self._subscriptions:
         self._subscriptions.remove(name)
     return 'OK UNSUBSCRIBE completed'