'''
Plot spectrograms computed with ``squirrel spectrogram``.

One figure per channel is saved as PNG file in the current directory.
'''

from pyrocko.example import get_example_data
import numpy as num
import matplotlib.pyplot as plt
from pyrocko import squirrel, plot

# Download an example file with spectrograms computed with
# squirrel spectrogram.
get_example_data('test.carpet')

# The spectrogram files are read with Squirrel, just like waveform files.
# Usually, we would add the directory given as --out-storage-path to
# squirrel spectrogram here.
sq = squirrel.Squirrel()
sq.add('test.carpet')

# Get one pyrocko.carpet.Carpet per channel, joined across files.
# Use e.g. codes='*.STA*.*.*Z.*', tmin=..., tmax=... to restrict the
# selection.
carpets = sq.get_carpets()

for carpet in carpets:
    # carpet.data: 2D array (frequency x time) with the natural logarithm of
    #     spectral power,
    # carpet.times: time axis [s],
    # carpet.component_axes['frequency']: frequency axis [Hz].
    fig = plt.figure(figsize=(12, 5))
    axes = fig.add_subplot(1, 1, 1)

    frequencies = carpet.component_axes['frequency']

    # Convert ln(power) to dB. Samples without data are NaN and stay blank.
    data_db = carpet.masked_data * 10. / num.log(10.)

    mesh = axes.pcolormesh(
        carpet.times, frequencies, data_db,
        cmap='viridis', shading='nearest')

    axes.set_yscale('log')
    axes.set_ylabel('Frequency [Hz]')
    plot.mpl_time_axis(axes)
    fig.colorbar(mesh, ax=axes, label='Power [dB]')
    axes.set_title(carpet.codes.safe_str)

    filename = 'spectrogram_%s.png' % carpet.codes.safe_str
    fig.tight_layout()
    fig.savefig(filename, dpi=150)
    plt.close(fig)
    print('Saved', filename)

# For a quick look without custom styling, use:
#     carpet.plot(component_axis_scale='log')
