def test_acceleration():
    datafiles, _ = read_data_dir("geonet", "us1000778i", "20161113_110259_WTMC_20.V2A")
    acc_file = datafiles[0]
    acc = read_data(acc_file)[0]
    target_g = acc[0].data * GAL_TO_PCTG
    target_m = acc[0].data / 100
    target_cm = acc[0].data

    acc_g = get_acceleration(acc, units="%%g")
    assert acc_g[0].stats["units"] == "%%g"
    np.testing.assert_allclose(acc_g[0], target_g)

    acc_m = get_acceleration(acc, units="m/s/s")
    assert acc_m[0].stats["units"] == "m/s/s"
    np.testing.assert_allclose(acc_m[0], target_m)

    acc_cm = get_acceleration(acc, units="cm/s/s")
    assert acc_cm[0].stats["units"] == "cm/s/s"
    np.testing.assert_allclose(acc_cm[0], target_cm)
def test_acceleration():
    datafiles, _ = read_data_dir('geonet', 'us1000778i',
                                 '20161113_110259_WTMC_20.V2A')
    acc_file = datafiles[0]
    acc = read_data(acc_file)[0]
    target_g = acc[0].data * GAL_TO_PCTG
    target_m = acc[0].data / 100
    target_cm = acc[0].data

    acc_g = get_acceleration(acc, units='%%g')
    assert acc_g[0].stats['units'] == '%%g'
    np.testing.assert_allclose(acc_g[0], target_g)

    acc_m = get_acceleration(acc, units='m/s/s')
    assert acc_m[0].stats['units'] == 'm/s/s'
    np.testing.assert_allclose(acc_m[0], target_m)

    acc_cm = get_acceleration(acc, units='cm/s/s')
    assert acc_cm[0].stats['units'] == 'cm/s/s'
    np.testing.assert_allclose(acc_cm[0], target_cm)
def test_acceleration():
    datafiles, _ = read_data_dir(
        'geonet', 'us1000778i', '20161113_110259_WTMC_20.V2A')
    acc_file = datafiles[0]
    acc = read_data(acc_file)[0]
    target_g = acc[0].data * GAL_TO_PCTG
    target_m = acc[0].data / 100
    target_cm = acc[0].data

    acc_g = get_acceleration(acc, units='%%g')
    assert acc_g[0].stats['units'] == '%%g'
    np.testing.assert_allclose(acc_g[0], target_g)

    acc_m = get_acceleration(acc, units='m/s/s')
    assert acc_m[0].stats['units'] == 'm/s/s'
    np.testing.assert_allclose(acc_m[0], target_m)

    acc_cm = get_acceleration(acc, units='cm/s/s')
    assert acc_cm[0].stats['units'] == 'cm/s/s'
    np.testing.assert_allclose(acc_cm[0], target_cm)
Beispiel #4
0
    def generate_oscillators(self,
                             imts,
                             sa_periods,
                             fas_periods,
                             rotate=False):
        """
        Create dictionary of requested imt and its coinciding oscillators.

        Args:
            imts (list): List of imts.
            sa_periods (list): List of periods. Used to generate the SA
                    oscillators.
            fas_periods (list): List of periods. Used to generate the FAS
                    oscillators.
            rotate (bool): Whether to rotate the sa oscillators for the ROTD
                    component.

        Returns:
            dictionary: dictionary of oscillators for each imt.

        Notes:
            Damping value must be set.
        """
        if self.stream is None:
            raise Exception('StationSummary.stream is not set.')
        oscillator_dict = OrderedDict()
        for imt in imts:
            stream = self.stream.copy()
            if imt.upper() == 'PGA':
                oscillator = get_acceleration(stream)
                oscillator_dict['PGA'] = oscillator
            elif imt.upper() == 'PGV':
                oscillator = get_velocity(stream)
                oscillator_dict['PGV'] = oscillator
            elif imt.upper() == 'FAS':
                oscillator = get_acceleration(stream, 'cm/s/s')
                oscillator_dict['FAS'] = oscillator
            elif imt.upper().startswith('SA'):
                for period in sa_periods:
                    tag = 'SA(' + str(period) + ')'
                    oscillator = get_spectral(period,
                                              stream,
                                              damping=self.damping)
                    oscillator_dict[tag] = oscillator
                    if rotate:
                        oscillator = get_spectral(period,
                                                  stream,
                                                  damping=self.damping,
                                                  rotation='nongm')
                        oscillator_dict[tag + '_ROT'] = oscillator
            elif imt.upper() == 'ARIAS':
                oscillator = get_acceleration(stream, units='m/s/s')
                oscillator_dict['ARIAS'] = oscillator
            else:
                fmt = "Invalid imt: %r. Skipping..."
                logging.warning(fmt % (imt))
        imts = []
        for key in oscillator_dict:
            if key == 'FAS':
                for period in fas_periods:
                    imts += ['FAS(' + str(period) + ')']
            elif key.find('ROT') < 0:
                imts += [key]

        self.imts = imts
        self.oscillators = oscillator_dict
Beispiel #5
0
def plot_arias(stream,
               axes=None,
               axis_index=None,
               figsize=None,
               file=None,
               minfontsize=14,
               show=False,
               show_maximum=True,
               title=None,
               xlabel=None,
               ylabel=None):
    """
    Create plots of arias intensity.

    Args:
        stream (obspy.core.stream.Stream):
            Set of acceleration data with units of gal (cm/s/s).
        axes (ndarray):
            Array of subplots. Default is None.
        axis_index (int):
            First index of axes array to plot the traces. Default is None.
            Required if axes is not None.
        figsize (tuple):
            Tuple of height and width. Default is None.
        file (str):
            File where the image will be saved. Default is None.
        minfontsize (int):
            Minimum font size. Default is 14.
        show (bool):
            Plot the figure. Default is False.
        show_maximum (bool):
            Show the maximum value.
        title (str):
            Title for plot. Default is None.
        xlabel (str):
            Label for x axis. Default is None.
        ylabel (str):
            Label for y axis. Default is None.

    Returns:
        numpy.ndarray: Array of matplotlib.axes._subplots.AxesSubplot.
    """
    if len(stream) < 1:
        raise Exception('No traces contained within the provided stream.')

    stream = get_acceleration(stream, units='m/s/s')
    Ia = calculate_arias(stream, ['channels'], True)[0]

    starttime = stream[0].stats.starttime
    if title is None:
        title = ('Event on ' + str(starttime.month) + '/' +
                 str(starttime.day) + '/' + str(starttime.year))
    if xlabel is None:
        xlabel = 'Time (s)'
    if ylabel is None:
        ylabel = 'Ia (m/s)'

    if figsize is None:
        figsize = (6.5, 7.5)
    if axes is None:
        fig, axs = plt.subplots(len(Ia), 1, figsize=figsize)
        axis_numbers = np.linspace(0, len(Ia) - 1, len(Ia))
    elif axis_index is not None:
        axs = axes
        axis_numbers = np.linspace(axis_index, axis_index + len(Ia) - 1,
                                   len(Ia))
    for idx, trace in zip(axis_numbers.astype(int), Ia):
        ax = axs[idx]
        dt = trace.stats['delta']
        npts = len(trace.data)
        t = np.linspace(0, (npts - 1) * dt, num=npts)
        network = trace.stats['network']
        station = trace.stats['station']
        channel = trace.stats['channel']
        trace_label = network + '.' + station + '.' + channel
        ax.set_title(trace_label, fontsize=minfontsize)
        ax.plot(t, trace.data)
        if show_maximum:
            abs_arr = np.abs(trace.data.copy())
            idx = np.argmax(abs_arr)
            max_value = abs_arr[idx]
            ax.plot([t[idx]], [trace.data[idx]], marker='o', color="red")
            ax.annotate('%.2E' % max_value, (t[idx], trace.data[idx]),
                        xycoords='data',
                        xytext=(.85, 0.25),
                        textcoords='axes fraction',
                        arrowprops=dict(facecolor='black',
                                        shrink=0.05,
                                        width=1,
                                        headwidth=4),
                        horizontalalignment='right',
                        verticalalignment='top')
        ax.set_xlabel(xlabel, fontsize=minfontsize)
        ax.set_ylabel(ylabel, fontsize=minfontsize)
        ax.xaxis.set_tick_params(labelsize=minfontsize - 2)
        ax.yaxis.set_tick_params(labelsize=minfontsize - 2)
    plt.suptitle(title, y=1.01, fontsize=minfontsize + 4)
    plt.tight_layout()
    if show and axes is None:
        plt.show()
    if file is not None and axes is None:
        fig.savefig(file, format='png')
    return axs
Beispiel #6
0
def plot_durations(stream,
                   durations,
                   axes=None,
                   axis_index=None,
                   figsize=None,
                   file=None,
                   minfontsize=14,
                   show=False,
                   title=None,
                   xlabel=None,
                   ylabel=None):
    """
    Create plots of durations.

    Args:
        stream (obspy.core.stream.Stream):
            Set of acceleration data with units of gal (cm/s/s).
        durations (list):
            List of percentage minimum and maximums (tuple).
        axes (ndarray):
            Array of subplots. Default is None.
        axis_index (int):
            First index of axes array to plot the traces. Default is None.
            Required if axes is not None.
        figsize (tuple):
            Tuple of height and width. Default is None.
        file (str):
            File where the image will be saved. Default is None.
        show (bool):
            Plot the figure. Default is False.
        title (str):
            Title for plot. Default is None.
        xlabel (str):
            Label for x axis. Default is None.
        ylabel (str):
            Label for y axis. Default is None.

    Returns:
        numpy.ndarray: Array of matplotlib.axes._subplots.AxesSubplot.
    """
    if len(stream) < 1:
        raise Exception('No traces contained within the provided stream.')

    stream = get_acceleration(stream, units='m/s/s')
    NIa = calculate_arias(stream, ['channels'], True)[1]

    starttime = stream[0].stats.starttime
    if title is None:
        title = ('Event on ' + str(starttime.month) + '/' +
                 str(starttime.day) + '/' + str(starttime.year))
    if xlabel is None:
        xlabel = 'Time (s)'
    if ylabel is None:
        ylabel = 'NIa (m/s)'

    if figsize is None:
        figsize = (6.5, 7.5)
    if axes is None:
        fig, axs = plt.subplots(len(NIa), 1, figsize=figsize)
        axis_numbers = np.linspace(0, len(NIa) - 1, len(NIa))
    elif axis_index is not None:
        axs = axes
        axis_numbers = np.linspace(axis_index, axis_index + len(NIa) - 1,
                                   len(NIa))
    for idx, trace in zip(axis_numbers.astype(int), NIa):
        ax = axs[idx]
        dt = trace.stats['delta']
        npts = len(trace.data)
        t = np.linspace(0, (npts - 1) * dt, num=npts)
        network = trace.stats['network']
        station = trace.stats['station']
        channel = trace.stats['channel']
        trace_label = network + '.' + station + '.' + channel
        ax.set_title(trace_label, fontsize=minfontsize)
        ax.plot(t, trace.data)
        if xlabel:
            ax.set_xlabel(xlabel)
        if xlabel:
            ax.set_ylabel(ylabel)
        for i, duration in enumerate(durations):
            first_percentile = duration[0]
            second_percentile = duration[1]
            t1 = get_time_from_percent(trace.data, first_percentile, dt)
            t2 = get_time_from_percent(trace.data, second_percentile, dt)
            height = (1 / (len(durations) + 1) * i) + 1 / (len(durations) + 1)
            ax.plot(t1, first_percentile, 'ok')
            ax.plot(t2, second_percentile, 'ok')
            ax.annotate('',
                        xy=(t1, height),
                        xytext=(t2, height),
                        arrowprops=dict(arrowstyle='<->'))
            label = '$D_{%i{-}%i}$' % (100 * duration[0], 100 * duration[1])
            ax.text(t2,
                    height,
                    label,
                    style='italic',
                    horizontalalignment='left',
                    verticalalignment='center')
            ax.set_xlabel(xlabel, fontsize=minfontsize)
            ax.set_ylabel(ylabel, fontsize=minfontsize)
            ax.xaxis.set_tick_params(labelsize=minfontsize - 2)
            ax.yaxis.set_tick_params(labelsize=minfontsize - 2)
    plt.suptitle(title, y=1.01, fontsize=minfontsize + 4)
    plt.tight_layout()
    if show and axes is None:
        plt.show()
    if file is not None and axes is None:
        if not file.endswith(".png"):
            file += ".png"
        fig.savefig(file)
    return axs