Esempio n. 1
0
    def test_plot_tfr(self):
        n = 295
        t, dt = np.linspace(0., 20 * np.pi, n, retstep=True)
        sig = np.sin(t)

        with np.errstate(all='ignore'):
            with ImageComparison(self.path,
                                 'time_frequency_representation.png') as ic:
                plot_tfr(sig, dt=dt, show=False)
                plt.savefig(ic.name)
Esempio n. 2
0
    def test_plot_tfr(self):
        n = 295
        t, dt = np.linspace(0., 20 * np.pi, n, retstep=True)
        sig = np.sin(t)

        with np.errstate(all='ignore'):
            with ImageComparison(self.path,
                                 'time_frequency_representation.png') as ic:
                plot_tfr(sig, dt=dt, show=False)
                plt.savefig(ic.name)
Esempio n. 3
0
    def test_plot_tfr(self):
        n = 295
        t, dt = np.linspace(0., 20 * np.pi, n, retstep=True)
        sig = np.sin(t)

        _t = np.geterr()
        np.seterr(all="ignore")
        try:
            with ImageComparison(self.path,
                                 'time_frequency_representation.png') as ic:
                plot_tfr(sig, dt=dt, show=False)
                plt.savefig(ic.name)
        finally:
            np.seterr(**_t)
Esempio n. 4
0
def plot_tf(
    data: np.ndarray,
    delta: float,
    freqmin: float = None,
    freqmax: float = None,
):
    """
    Plots a time frequency representation of any time series. Right now it is
    basically limited to plotting source time functions.

    :param data: Signal represented in a numpy array
    :type data: np.ndarray
    :param delta: Time discretization in seconds
    :type delta: float
    :param freqmin: minimum frequency of signal, defaults to None
    :type freqmin: float, optional
    :param freqmax: maximum frequency of signal, defaults to None
    :type freqmax: float, optional
    """
    npts = len(data)

    fig = plot_tfr(
        data,
        dt=delta,
        fmin=1.0 / (npts * delta),
        fmax=1.0 / (2.0 * delta),
        show=False,
    )

    # Get the different axes...use some kind of logic to determine which is
    # which. This is super flaky as dependent on the ObsPy version and what
    # not.
    axes = {}
    for ax in fig.axes:
        xlim = ax.get_xlim()
        ylim = ax.get_ylim()

        # Colorbar.
        if xlim == ylim:
            continue

        # Spectral axis.
        elif xlim[0] > xlim[1]:
            axes["spec"] = ax

        elif ylim[0] < 0:
            axes["time"] = ax

        else:
            axes["tf"] = ax

    fig.suptitle("Source Time Function")

    if len(axes) != 3:
        msg = "Could not plot frequency limits!"
        print(msg)
        plt.gcf().patch.set_alpha(0.0)
        plt.show()
        return

    axes["spec"].grid()
    axes["time"].grid()
    axes["tf"].grid()

    axes["spec"].xaxis.tick_top()
    axes["spec"].set_ylabel("Frequency [Hz]")

    axes["time"].set_xlabel("Time [s]")
    axes["time"].set_ylabel("Velocity [m/s]")

    if freqmin is not None and freqmax is not None:
        xmin, xmax = axes["tf"].get_xlim()
        axes["tf"].hlines(freqmin, xmin, xmax, color="green", lw=2)
        axes["tf"].hlines(freqmax, xmin, xmax, color="red", lw=2)
        axes["tf"].text(
            xmax - (0.02 * (xmax - xmin)),
            freqmin,
            "%.1f s" % (1.0 / freqmin),
            color="green",
            horizontalalignment="right",
            verticalalignment="top",
        )
        axes["tf"].text(
            xmax - (0.02 * (xmax - xmin)),
            freqmax,
            "%.1f s" % (1.0 / freqmax),
            color="red",
            horizontalalignment="right",
            verticalalignment="bottom",
        )

        xmin, xmax = axes["spec"].get_xlim()
        axes["spec"].hlines(freqmin, xmin, xmax, color="green", lw=2)
        axes["spec"].hlines(freqmax, xmin, xmax, color="red", lw=2)

    plt.gcf().patch.set_alpha(0.0)
    plt.show()
Esempio n. 5
0
 def test_plot_tfr(self, state, ignore_numpy_errors, image_path):
     n = 295
     t, dt = np.linspace(0., 20 * np.pi, n, retstep=True)
     sig = np.sin(t)
     plot_tfr(sig, dt=dt, show=False)
     plt.savefig(image_path)
Esempio n. 6
0
t2 = t1 + 3600
st = client.get_waveforms("UW", "HOLY", "--", "ENN", t1, t2)
plt.figure(0)
st.plot(outfile="quicktest.png")
tr = st[0]

N = tr.stats.npts
T = tr.stats.delta

x = tr.data
y = np.sin(50.0 * 2.0 * np.pi * x) + 0.5 * np.sin(80.0 * 2.0 * np.pi * x)
yf = fft(y)
xf = np.linspace(0.0, 1.0 / (2.0 * T), int(N / 2))
plt.figure()
plt.loglog(xf, 2.0 / N * np.abs(yf[0:int(N / 2)]))
plt.plot(xf, 2.0 / N * np.abs(
    yf[0:int(N / 2)]))  #test this works as linear plot, if comment out loglog
plt.grid()
plt.show()
plt.savefig("quicktest2.png")

plt.figure(3)
plot_tfr(tr.data,
         dt=tr.stats.delta,
         fmin=.01,
         fmax=50.,
         w0=8.,
         nf=64,
         fft_zero_pad_fac=4)
plt.savefig("quicktest3.png")
# Remove mean and apply a bandpass filter
print('filtering')
st.detrend('demean')
st.filter('bandpass', freqmin=fmin, freqmax=fmax)

tr = st[0]

###############################
# Plot figure!

dt = tr.stats.starttime - t0  # time between start of window and quake origin

fig = plot_tfr(tr.data,
               dt=tr.stats.delta,
               fmin=fmin,
               fmax=fmax,
               w0=10,
               clim=1e3,
               cmap='magma',
               show=False)

# plot dispersion curves on top
T, u = np.loadtxt('t-vs-u.csv', unpack=True, delimiter=',')
f = 1. / T

# Optional: Plot predicted Rayleigh wave arrival times
# in t-vs-u.csv, digitized from Oliver (1962) Fig 2.
# https://pubs.geoscienceworld.org/ssa/bssa/article/52/1/81/101314

x_m, meh, meh = gps2dist_azimuth(elat, elon, slat, slon)
x = x_m / 1000.
earth_circ = 4e4  # circumference of Earth in km, roughly
import numpy as np

from obspy.signal.tf_misfit import plot_tfr


# general constants
tmax = 6.
dt = 0.01
npts = int(tmax / dt + 1)
t = np.linspace(0., tmax, npts)

fmin = .5
fmax = 10

# constants for the signal
A1 = 4.
t1 = 2.
f1 = 2.
phi1 = 0.

# generate the signal
H1 = (np.sign(t - t1) + 1) / 2
st1 = A1 * (t - t1) * np.exp(-2 * (t - t1))
st1 *= np.cos(2. * np.pi * f1 * (t - t1) + phi1 * np.pi) * H1

plot_tfr(st1, dt=dt, fmin=fmin, fmax=fmax)
Esempio n. 9
0
def plot_tf(data, delta, freqmin=None, freqmax=None):
    """
    Plots a time frequency representation of any time series. Right now it is
    basically limited to plotting source time functions.
    """
    npts = len(data)

    fig = plot_tfr(data, dt=delta, fmin=1.0 / (npts * delta),
                   fmax=1.0 / (2.0 * delta), show=False)

    # Get the different axes...use some kind of logic to determine which is
    # which. This is super flaky as dependent on the ObsPy version and what
    # not.
    axes = {}
    for ax in fig.axes:
        xlim = ax.get_xlim()
        ylim = ax.get_ylim()

        # Colorbar.
        if xlim == ylim:
            continue

        # Spectral axis.
        elif xlim[0] > xlim[1]:
            axes["spec"] = ax

        elif ylim[0] < 0:
            axes["time"] = ax

        else:
            axes["tf"] = ax

    fig.suptitle("Source Time Function")

    if len(axes) != 3:
        msg = "Could not plot frequency limits!"
        print msg
        plt.gcf().patch.set_alpha(0.0)
        plt.show()
        return

    axes["spec"].grid()
    axes["time"].grid()
    axes["tf"].grid()

    axes["spec"].xaxis.tick_top()
    axes["spec"].set_ylabel("Frequency [Hz]")

    axes["time"].set_xlabel("Time [s]")
    axes["time"].set_ylabel("Velocity [m/s]")

    if freqmin is not None and freqmax is not None:
        xmin, xmax = axes["tf"].get_xlim()
        axes["tf"].hlines(freqmin, xmin, xmax, color="green", lw=2)
        axes["tf"].hlines(freqmax, xmin, xmax, color="red", lw=2)
        axes["tf"].text(xmax - (0.02 * (xmax - xmin)),
                        freqmin,
                        "%.1f s" % (1.0 / freqmin),
                        color="green",
                        horizontalalignment="right", verticalalignment="top")
        axes["tf"].text(xmax - (0.02 * (xmax - xmin)),
                        freqmax,
                        "%.1f s" % (1.0 / freqmax),
                        color="red",
                        horizontalalignment="right",
                        verticalalignment="bottom")

        xmin, xmax = axes["spec"].get_xlim()
        axes["spec"].hlines(freqmin, xmin, xmax, color="green", lw=2)
        axes["spec"].hlines(freqmax, xmin, xmax, color="red", lw=2)

    plt.gcf().patch.set_alpha(0.0)
    plt.show()
Esempio n. 10
0
import numpy as np

from obspy.signal.tf_misfit import plot_tfr

# general constants
tmax = 6.
dt = 0.01
npts = int(tmax / dt + 1)
t = np.linspace(0., tmax, npts)

fmin = .5
fmax = 10

# constants for the signal
A1 = 4.
t1 = 2.
f1 = 2.
phi1 = 0.

# generate the signal
H1 = (np.sign(t - t1) + 1) / 2
st1 = A1 * (t - t1) * np.exp(-2 * (t - t1))
st1 *= np.cos(2. * np.pi * f1 * (t - t1) + phi1 * np.pi) * H1

plot_tfr(st1, dt=dt, fmin=fmin, fmax=fmax)