Example #1
0
 def set_record(self, document, step=120.0):
     self.document = document
     self.fs = self.document.record.fs
     self.signal = self.document.record.signal
     self.envelope = env.envelope(self.signal)
     self.cf = self.document.record.cf
     self.time = np.linspace(0,
                             len(self.signal) / self.fs,
                             num=len(self.signal),
                             endpoint=False)
     self.xmax = self.time[-1]
     # Draw minimap
     self.minimap.set_record(self.document.record, step)
     # Plot signal
     self._signal_data = self.signal_ax.plot(self.time,
                                             self.signal,
                                             color='black',
                                             rasterized=True)[0]
     # Plot envelope
     self._envelope_data = self.signal_ax.plot(self.time,
                                               self.envelope,
                                               color='red',
                                               rasterized=True)[0]
     plotting.adjust_axes_height(self.signal_ax)
     # Plot CF
     cf_loaded = (self.cf.size != 0)
     self.set_cf_visible(cf_loaded)
     self.CF_loaded.emit(cf_loaded)
     self._cf_data = self.cf_ax.plot(self.time[:len(self.cf)],
                                     self.cf,
                                     color='black',
                                     rasterized=True)[0]
     plotting.adjust_axes_height(self.signal_ax)
     self.thresholdMarker = ThresholdMarker(self.cf_ax)
     # Plot espectrogram
     plotting.plot_specgram(self.specgram_ax,
                            self.signal,
                            self.fs,
                            nfft=self.specgram_windowlen,
                            noverlap=self.specgram_noverlap,
                            window=self.specgram_window)
     # Set the span selector
     self.selector.fs = self.fs
     self.selector.set_active(False)
     self.selector.set_selection_limits(self.xmin, self.xmax)
     # Set the playback marker
     self.playback_marker = PlayBackMarker(self.fig, self)
     # Set the initial xlimits
     self.set_xlim(0, step)
     self.subplots_adjust()
Example #2
0
 def set_record(self, document, step=120.0):
     self.document = document
     self.fs = self.document.record.fs
     self.signal = self.document.record.signal
     self.envelope = env.envelope(self.signal)
     self.cf = self.document.record.cf
     self.time = np.linspace(0, len(self.signal) / self.fs, num=len(self.signal), endpoint=False)
     self.xmax = self.time[-1]
     # Draw minimap
     self.minimap.set_record(self.document.record, step)
     # Plot signal
     self._signal_data = self.signal_ax.plot(self.time,
                                               self.signal,
                                               color='black',
                                               rasterized=True)[0]
     # Plot envelope
     self._envelope_data = self.signal_ax.plot(self.time,
                                                 self.envelope,
                                                 color='red',
                                                 rasterized=True)[0]
     plotting.adjust_axes_height(self.signal_ax)
     # Plot CF
     cf_loaded = (self.cf.size != 0)
     self.set_cf_visible(cf_loaded)
     self.CF_loaded.emit(cf_loaded)
     self._cf_data = self.cf_ax.plot(self.time[:len(self.cf)],
                                           self.cf,
                                           color='black', rasterized=True)[0]
     plotting.adjust_axes_height(self.signal_ax)
     self.thresholdMarker = ThresholdMarker(self.cf_ax)
     # Plot espectrogram
     plotting.plot_specgram(self.specgram_ax, self.signal, self.fs,
                            nfft=self.specgram_windowlen,
                            noverlap=self.specgram_noverlap,
                            window=self.specgram_window)
     # Set the span selector
     self.selector.fs = self.fs
     self.selector.set_active(False)
     self.selector.set_selection_limits(self.xmin, self.xmax)
     # Set the playback marker
     self.playback_marker = PlayBackMarker(self.fig, self)
     # Set the initial xlimits
     self.set_xlim(0, step)
     self.subplots_adjust()
Example #3
0
    def plot_signal(self,
                    t_start=0.0,
                    t_end=np.inf,
                    show_events=True,
                    show_x=True,
                    show_cf=True,
                    show_specgram=True,
                    show_envelope=True,
                    threshold=None,
                    num=None,
                    **kwargs):
        """Plots record data.

        Draws a figure containing several plots for data stored and computed
        by a Record object: magnitude, envelope and spectrogram plots for
        self.signal, as well as characteristic function if calculated.

        Args:
            t_start: Start time of the plotted data segment, in seconds.
                Default: 0.0, that is the beginning of 'signal'.
            t_end: End time of the plotted data segment, in seconds.
                Default: numpy.inf, that is the end of 'signal'
            show_events: Boolean value to specify whether to plot
                event arrival times or not. Arrival times will be
                indicated by using a vertical line.
                Default: True.
            show_x: Boolean value to specify whether to plot the
                magnitude value of 'signal' or not. This function
                will be drawn preferably on the first axis.
                Default: True.
            show_cf: Boolean value to specify whether to plot the
                characteristic function or not. This function
                will be drawn preferably on the second axis.
                Default: True.
            show_specgram: Boolean value to specify whether to plot the
                spectrogram of 'signal' or not. It will be drawn preferably
                on the third axis.
                Default: True.
            show_envelope: Boolean value to specify whether to plot the
                envelope of 'signal' or not. This function will be drawn
                preferably on the first axis together with amplitude of
                'signal'.
                Default: True.
            threshold: Boolean value to specify whether to plot threshold
                or not. Threshold will be drawn as an horizontal dashed line
                together with characteristic function.
                Default: True.
            num: Identifier of the returned MatplotLib figure, integer type.
                Default None, which means an identifier value will be
                automatically generated.

        Returns:
            fig: A MatplotLib Figure instance.
        """
        # Lazy matplotlib import
        import matplotlib.pyplot as pl
        from matplotlib import ticker
        # Set limits
        i_from = int(max(0.0, t_start * self.fs))
        if show_cf:
            i_to = int(min(len(self.cf), t_end * self.fs))
        else:
            i_to = int(min(len(self.signal), t_end * self.fs))
        # Create time sequence
        t = np.arange(i_from, i_to) / float(self.fs)
        # Create figure
        nplots = show_x + show_cf + show_specgram
        fig, _ = pl.subplots(nplots, 1, sharex='all', num=num)
        fig.canvas.set_window_title(self.label)
        fig.set_tight_layout(True)
        # Configure axes
        for ax in fig.axes:
            ax.cla()
            ax.grid(True, which='both')
            formatter = ticker.FuncFormatter(
                lambda x, pos: clt.float_secs_2_string_date(x, self.starttime))
            ax.xaxis.set_major_formatter(formatter)
            ax.xaxis.set_major_locator(
                ticker.MaxNLocator(nbins=5, prune='lower'))
            ax.set_xlabel('Time (seconds)')
            pl.setp(ax.get_xticklabels(), visible=True)
        # Draw axes
        ax_idx = 0
        # Draw signal
        if show_x:
            fig.axes[ax_idx].set_title("Signal Amplitude (%gHz)" % self.fs)
            fig.axes[ax_idx].set_ylabel('Amplitude')
            fig.axes[ax_idx].plot(
                t, self.signal[i_from:i_to], color='black', label='Signal')
            # Draw signal envelope
            if show_envelope:
                fig.axes[ax_idx].plot(
                    t,
                    env.envelope(self.signal[i_from:i_to]),
                    color='r',
                    label='Envelope')
                fig.axes[ax_idx].legend(loc=0, fontsize='small')
            ax_idx += 1
        # Draw Characteristic function
        if show_cf:
            fig.axes[ax_idx].set_title('Characteristic Function')
            fig.axes[ax_idx].plot(t, self.cf[i_from:i_to])
            # Draw threshold
            if threshold:
                hline = fig.axes[ax_idx].axhline(threshold, label="Threshold")
                hline.set(color='b', ls='--', lw=2, alpha=0.8)
                fig.axes[ax_idx].legend(loc=0, fontsize='small')
            ax_idx += 1
        # Draw spectrogram
        if show_specgram:
            fig.axes[ax_idx].set_title('Spectrogram')
            fig.axes[ax_idx].set_ylabel('Frequency (Hz)')
            fig.axes[ax_idx].specgram(
                self.signal[i_from:i_to],
                Fs=self.fs,
                xextent=(i_from / self.fs, i_to / self.fs))
            ax_idx += 1
        # Draw event markers
        if show_events:
            for event in self.events:
                arrival_time = event.stime / self.fs
                for ax in fig.axes:
                    xmin, xmax = ax.get_xlim()
                    if arrival_time > xmin and arrival_time < xmax:
                        vline = ax.axvline(arrival_time, label="Event")
                        vline.set(color='r', ls='--', lw=2)
                        ax.legend(loc=0, fontsize='small')
        # Configure limits and draw legend
        for ax in fig.axes:
            ax.set_xlim(t[0], t[-1])
        return fig
Example #4
0
    def plot_aic(self, show_envelope=True, num=None, **kwargs):
        """Plots AIC values for a given event object.

        Draws a figure with two axes: the first one plots magnitude and
        envelope of 'self.signal' and the second one plots AIC values computed
        after applying Takanami AR method to 'event'. Plotted data goes from
        'event.n0_aic' to 'event.n0_aic + len(event.aic)'.

        Args:
            show_envelope: Boolean value to specify whether to plot the
                envelope of 'signal' or not. This function will be drawn
                preferably on the first axis together with amplitude of
                'signal'.
                Default: True.
            num: Identifier of the returned MatplotLib figure, integer type.
                Default None, which means an identifier value will be
                automatically generated.

        Returns:
            fig: A MatplotLib Figure instance.
        """
        if self.aic is None or self.n0_aic is None:
            raise ValueError("Event doesn't have AIC data to plot")

        # Lazy matplotlib import
        import matplotlib.pyplot as pl
        from matplotlib import ticker

        # Set limits
        i_from = int(max(0, self.n0_aic))
        i_to = int(min(len(self.trace.signal), self.n0_aic + len(self.aic)))
        # Create time sequence
        t = np.arange(i_from, i_to) / float(self.trace.fs)
        # Create figure
        fig, _ = pl.subplots(2, 1, sharex='all', num=num)
        fig.canvas.set_window_title(self.trace.label)
        fig.set_tight_layout(True)
        # Configure axes
        for ax in fig.axes:
            ax.cla()
            ax.grid(True, which='both')
            formatter = ticker.FuncFormatter(lambda x, pos: clt.float_secs_2_string_date(x, self.trace.starttime))
            ax.xaxis.set_major_formatter(formatter)
            ax.xaxis.set_major_locator(
                ticker.MaxNLocator(nbins=5, prune='lower'))
            ax.set_xlabel('Time (seconds)')
            pl.setp(ax.get_xticklabels(), visible=True)
        # Draw signal
        fig.axes[0].set_title('Signal Amplitude')
        fig.axes[0].set_ylabel('Amplitude')
        fig.axes[0].plot(
            t, self.trace.signal[i_from:i_to], color='black', label='Signal')
        # Draw envelope
        if show_envelope:
            fig.axes[0].plot(
                t,
                env.envelope(self.trace.signal[i_from:i_to]),
                color='r',
                label='Envelope')
            fig.axes[0].legend(loc=0, fontsize='small')
        # Draw AIC
        fig.axes[1].set_title('AIC')
        fig.axes[1].plot(t, self.aic)
        # Draw event
        for ax in fig.axes:
            vline = ax.axvline(self.stime / self.trace.fs, label="Event")
            vline.set(color='r', ls='--', lw=2)
        # Configure limits and draw legend
        for ax in fig.axes:
            ax.set_xlim(t[0], t[-1])
            ax.legend(loc=0, fontsize='small')
        return fig
Example #5
0
 def set_record(self, document, step=120.0):
     self.document = document
     self.fs = self.document.record.fs
     self.signal = self.document.record.signal
     self.envelope = env.envelope(self.signal)
     self.cf = self.document.record.cf
     self.time = np.linspace(0,
                             len(self.signal) / self.fs,
                             num=len(self.signal),
                             endpoint=False)
     self.xmax = self.time[-1]
     # Draw minimap
     self.minimap.minimapSelector.set(
         visible=False)  # Hide minimap selector while loading
     self.minimap.set_record(self.document.record, step)
     # Plot signal
     step_samples = step * self.fs
     self._signal_data = self.signal_ax.plot(self.time[:step_samples],
                                             self.signal[:step_samples],
                                             color='black',
                                             rasterized=True)[0]
     # Plot envelope
     self._envelope_data = self.signal_ax.plot(self.time[:step_samples],
                                               self.envelope[:step_samples],
                                               color='red',
                                               rasterized=True)[0]
     # Adjust y axis for signal plot
     signal_yaxis_max_value = max(np.max(self.signal),
                                  np.max(self.envelope))
     signal_yaxis_min_value = np.min(self.signal)
     plotting.adjust_axes_height(self.signal_ax,
                                 max_value=signal_yaxis_max_value,
                                 min_value=signal_yaxis_min_value)
     # Plot CF
     cf_loaded = (self.cf.size != 0)
     self.set_cf_visible(cf_loaded)
     self.CF_loaded.emit(cf_loaded)
     cf_step_samples = min(step_samples, len(self.cf))
     self._cf_data = self.cf_ax.plot(self.time[:cf_step_samples],
                                     self.cf[:cf_step_samples],
                                     color='black',
                                     rasterized=True)[0]
     # Adjust y axis for CF plot
     if cf_loaded:
         plotting.adjust_axes_height(self.cf_ax,
                                     max_value=np.max(self.cf),
                                     min_value=np.min(self.cf))
     self.thresholdMarker = ThresholdMarker(self.cf_ax)
     # Plot espectrogram
     plotting.plot_specgram(self.specgram_ax,
                            self.signal,
                            self.fs,
                            nfft=self.specgram_windowlen,
                            noverlap=self.specgram_noverlap,
                            window=self.specgram_window)
     # Set the span selector
     self.selector.fs = self.fs
     self.selector.set_active(False)
     self.selector.set_selection_limits(self.xmin, self.xmax)
     # Set the playback marker
     self.playback_marker = PlayBackMarker(self.fig, self)
     # Set the initial xlimits
     self.set_xlim(0, step)
     self.subplots_adjust()
     # Set event markers
     self.eventMarkers = {}
     for event in self.document.record.events:
         self.create_event(event)
     # Now activate selector again on minimap
     self.minimap.minimapSelector.set(visible=True)
     self.minimap.draw()
Example #6
0
    def plot_signal(self, t_start=0.0, t_end=np.inf, show_events=True,
                    show_x=True, show_cf=True, show_specgram=True,
                    show_envelope=True, threshold=None, num=None, **kwargs):
        """Plots record data.

        Draws a figure containing several plots for data stored and computed
        by a Record object: magnitude, envelope and spectrogram plots for
        self.signal, as well as characteristic function if calculated.

        Args:
            t_start: Start time of the plotted data segment, in seconds.
                Default: 0.0, that is the beginning of 'signal'.
            t_end: End time of the plotted data segment, in seconds.
                Default: numpy.inf, that is the end of 'signal'
            show_events: Boolean value to specify whether to plot
                event arrival times or not. Arrival times will be
                indicated by using a vertical line.
                Default: True.
            show_x: Boolean value to specify whether to plot the
                magnitude value of 'signal' or not. This function
                will be drawn preferably on the first axis.
                Default: True.
            show_cf: Boolean value to specify whether to plot the
                characteristic function or not. This function
                will be drawn preferably on the second axis.
                Default: True.
            show_specgram: Boolean value to specify whether to plot the
                spectrogram of 'signal' or not. It will be drawn preferably
                on the third axis.
                Default: True.
            show_envelope: Boolean value to specify whether to plot the
                envelope of 'signal' or not. This function will be drawn
                preferably on the first axis together with amplitude of
                'signal'.
                Default: True.
            threshold: Boolean value to specify whether to plot threshold
                or not. Threshold will be drawn as an horizontal dashed line
                together with characteristic function.
                Default: True.
            num: Identifier of the returned MatplotLib figure, integer type.
                Default None, which means an identifier value will be
                automatically generated.

        Returns:
            fig: A MatplotLib Figure instance.
        """
        # Lazy matplotlib import
        import matplotlib.pyplot as pl
        from matplotlib import ticker
        # Set limits
        i_from = int(max(0.0, t_start * self.fs))
        if show_cf:
            i_to = int(min(len(self.cf), t_end * self.fs))
        else:
            i_to = int(min(len(self.signal), t_end * self.fs))
        # Create time sequence
        t = np.arange(i_from, i_to) / float(self.fs)
        # Create figure
        nplots = show_x + show_cf + show_specgram
        fig, _ = pl.subplots(nplots, 1, sharex='all', num=num)
        fig.canvas.set_window_title(self.label)
        fig.set_tight_layout(True)
        # Configure axes
        for ax in fig.axes:
            ax.cla()
            ax.grid(True, which='both')
            formatter = ticker.FuncFormatter(lambda x, pos: clt.float_secs_2_string_date(x, self.starttime))
            ax.xaxis.set_major_formatter(formatter)
            ax.xaxis.set_major_locator(ticker.MaxNLocator(nbins=5, prune='lower'))
            ax.set_xlabel('Time (seconds)')
            pl.setp(ax.get_xticklabels(), visible=True)
        # Draw axes
        ax_idx = 0
        # Draw signal
        if show_x:
            fig.axes[ax_idx].set_title("Signal Amplitude (%gHz)" % self.fs)
            fig.axes[ax_idx].set_ylabel('Amplitude')

            fig.axes[ax_idx].plot(t, self.signal[i_from:i_to], color='black',
                                  label='Signal')
            #fig.axes[ax_idx].plot(t, signal_norm, color='black',
                                  #label='Signal')
            # Draw signal envelope
            if show_envelope:
                fig.axes[ax_idx].plot(t, env.envelope(self.signal[i_from:i_to]),
                                  color='r', label='Envelope')
                fig.axes[ax_idx].legend(loc=0, fontsize='small')
            ax_idx += 1
        # Draw Characteristic function
        if show_cf:
            fig.axes[ax_idx].set_title('Characteristic Function')
            fig.axes[ax_idx].plot(t, self.cf[i_from:i_to])
            # Draw threshold
            if threshold:
                hline = fig.axes[ax_idx].axhline(threshold, label="Threshold")
                hline.set(color='b', ls='--', lw=2, alpha=0.8)
                fig.axes[ax_idx].legend(loc=0, fontsize='small')
            ax_idx += 1
        # Draw spectrogram
        if show_specgram:
            fig.axes[ax_idx].set_title('Spectrogram')
            fig.axes[ax_idx].set_ylabel('Frequency (Hz)')
            fig.axes[ax_idx].specgram(self.signal[i_from:i_to], Fs=self.fs,
                                  xextent=(i_from / self.fs, i_to / self.fs))
            ax_idx += 1
        # Draw event markers
        if show_events:
            for event in self.events:
                arrival_time = event.stime / self.fs
                for ax in fig.axes:
                    xmin, xmax = ax.get_xlim()
                    if arrival_time > xmin and arrival_time < xmax:
                        vline = ax.axvline(arrival_time, label="Event")
                        vline.set(color='r', ls='--', lw=2)
                        ax.legend(loc=0, fontsize='small')
        # Configure limits and draw legend
        for ax in fig.axes:
            ax.set_xlim(t[0], t[-1])
        return fig
Example #7
0
    def plot_aic(self, show_envelope=True, num=None, **kwargs):
        """Plots AIC values for a given event object.

        Draws a figure with two axes: the first one plots magnitude and
        envelope of 'self.signal' and the second one plots AIC values computed
        after applying Takanami AR method to 'event'. Plotted data goes from
        'event.n0_aic' to 'event.n0_aic + len(event.aic)'.

        Args:
            show_envelope: Boolean value to specify whether to plot the
                envelope of 'signal' or not. This function will be drawn
                preferably on the first axis together with amplitude of
                'signal'.
                Default: True.
            num: Identifier of the returned MatplotLib figure, integer type.
                Default None, which means an identifier value will be
                automatically generated.

        Returns:
            fig: A MatplotLib Figure instance.
        """
        if self.aic is None or self.n0_aic is None:
            raise ValueError("Event doesn't have AIC data to plot")

        # Lazy matplotlib import
        import matplotlib.pyplot as pl
        from matplotlib import ticker

        # Set limits
        i_from = int(max(0, self.n0_aic))
        i_to = int(min(len(self.trace.signal), self.n0_aic + len(self.aic)))
        # Create time sequence
        t = np.arange(i_from, i_to) / float(self.trace.fs)
        # Create figure
        fig, _ = pl.subplots(2, 1, sharex='all', num=num)
        fig.canvas.set_window_title(self.trace.label)
        fig.set_tight_layout(True)
        # Configure axes
        for ax in fig.axes:
            ax.cla()
            ax.grid(True, which='both')
            formatter = ticker.FuncFormatter(lambda x, pos: clt.float_secs_2_string_date(x, self.trace.starttime))
            ax.xaxis.set_major_formatter(formatter)
            ax.xaxis.set_major_locator(ticker.MaxNLocator(nbins=5, prune='lower'))
            ax.set_xlabel('Time (seconds)')
            pl.setp(ax.get_xticklabels(), visible=True)
        # Draw signal
        fig.axes[0].set_title('Signal Amplitude')
        fig.axes[0].set_ylabel('Amplitude')
        fig.axes[0].plot(t, self.trace.signal[i_from:i_to], color='black',
                         label='Signal')
        # Draw envelope
        if show_envelope:
            fig.axes[0].plot(t, env.envelope(self.trace.signal[i_from:i_to]),
                         color='r', label='Envelope')
            fig.axes[0].legend(loc=0, fontsize='small')
        # Draw AIC
        fig.axes[1].set_title('AIC')
        fig.axes[1].plot(t, self.aic)
        # Draw event
        for ax in fig.axes:
            vline = ax.axvline(self.stime / self.trace.fs, label="Event")
            vline.set(color='r', ls='--', lw=2)
        # Configure limits and draw legend
        for ax in fig.axes:
            ax.set_xlim(t[0], t[-1])
            ax.legend(loc=0, fontsize='small')
        return fig
Example #8
0
 def set_record(self, document, step=120.0):
     self.document = document
     self.fs = self.document.record.fs
     self.signal = self.document.record.signal
     self.envelope = env.envelope(self.signal)
     self.cf = self.document.record.cf
     self.time = np.linspace(0, len(self.signal) / self.fs, num=len(self.signal), endpoint=False)
     self.xmax = self.time[-1]
     # Draw minimap
     self.minimap.minimapSelector.set(visible=False)  # Hide minimap selector while loading
     self.minimap.set_record(self.document.record, step)
     # Plot signal
     step_samples = step * self.fs
     self._signal_data = self.signal_ax.plot(self.time[:step_samples],
                                               self.signal[:step_samples],
                                               color='black',
                                               rasterized=True)[0]
     # Plot envelope
     self._envelope_data = self.signal_ax.plot(self.time[:step_samples],
                                                 self.envelope[:step_samples],
                                                 color='red',
                                                 rasterized=True)[0]
     # Adjust y axis for signal plot
     signal_yaxis_max_value = max(np.max(self.signal), np.max(self.envelope))
     signal_yaxis_min_value = np.min(self.signal)
     plotting.adjust_axes_height(self.signal_ax,
                                 max_value=signal_yaxis_max_value,
                                 min_value=signal_yaxis_min_value)
     # Plot CF
     cf_loaded = (self.cf.size != 0)
     self.set_cf_visible(cf_loaded)
     self.CF_loaded.emit(cf_loaded)
     cf_step_samples = min(step_samples,len(self.cf))
     self._cf_data = self.cf_ax.plot(self.time[:cf_step_samples],
                                     self.cf[:cf_step_samples],
                                     color='black',
                                     rasterized=True)[0]
     # Adjust y axis for CF plot
     if cf_loaded:
         plotting.adjust_axes_height(self.cf_ax,
                                     max_value=np.max(self.cf),
                                     min_value=np.min(self.cf))
     self.thresholdMarker = ThresholdMarker(self.cf_ax)
     # Plot espectrogram
     plotting.plot_specgram(self.specgram_ax, self.signal, self.fs,
                            nfft=self.specgram_windowlen,
                            noverlap=self.specgram_noverlap,
                            window=self.specgram_window)
     # Set the span selector
     self.selector.fs = self.fs
     self.selector.set_active(False)
     self.selector.set_selection_limits(self.xmin, self.xmax)
     # Set the playback marker
     self.playback_marker = PlayBackMarker(self.fig, self)
     # Set the initial xlimits
     self.set_xlim(0, step)
     self.subplots_adjust()
     # Set event markers
     self.eventMarkers = {}
     for event in self.document.record.events:
         self.create_event(event)
     # Now activate selector again on minimap
     self.minimap.minimapSelector.set(visible=True)
     self.minimap.draw()