r4.data = r4dat
assert (lal.swig_lal_test_copyinout_REAL4VectorSequence(r4))
assert ((r4.data == 3 * r4dat).all())
r4.data = r4dat
retn, r4 = lal.swig_lal_test_copyinout_REAL4VectorSequence(r4)
assert (retn)
assert ((r4.data == 3 * r4dat).all())
r4 = r4dat
retn, r4 = lal.swig_lal_test_copyinout_REAL4VectorSequence(r4)
assert (retn)
assert ((r4 == 3 * r4dat).all())
del r4
del r4out
del r4dat
lal.CheckMemoryLeaks()
r8 = lal.CreateREAL8VectorSequence(r8dat.shape[0], r8dat.shape[1])
r8.data = r8dat
r8out = lal.CreateREAL8VectorSequence(r8dat.shape[0], r8dat.shape[1])
r8out.data = numpy.zeros(numpy.shape(r8dat), dtype=r8dat.dtype)
assert (lal.swig_lal_test_viewin_REAL8VectorSequence(r8out, r8))
assert ((r8out.data == r8.data).all())
r8out.data = numpy.zeros(numpy.shape(r8dat), dtype=r8dat.dtype)
assert (lal.swig_lal_test_viewin_REAL8VectorSequence(r8out, r8dat))
assert ((r8out.data == r8dat).all())
r8out.data = numpy.zeros(numpy.shape(r8dat), dtype=r8dat.dtype)
assert (lal.swig_lal_test_viewinout_REAL8VectorSequence(r8out, r8))
assert ((2 * r8out.data == r8.data).all())
r8out.data = numpy.zeros(numpy.shape(r8dat), dtype=r8dat.dtype)
assert (lal.swig_lal_test_viewinout_REAL8VectorSequence(r8out, r8dat))
assert ((2 * r8out.data == r8dat).all())
r8.data = r8dat
Beispiel #2
0
def plotspectrogram(sequencelist, outfile, epoch=0, deltaT=1, f0=0, deltaF=1,\
                    t0=0, ydata=None, **kwargs):
    """
    Plots a list of REAL?VectorSequences on a time-frequency-amplitude colour
    map. The epochand deltaT arguments define the spacing in the x direction
    for the given VectorSequence, and similarly f0 and deltaF in the
    y-direction. If a list of VectorSequences is given, any of these arguments
    can be in list form, one for each sequence.

    ydata can be given as to explicitly define the frequencies at which the
    sequences are sampled.
    """
    # construct list of series
    if not hasattr(sequencelist, "__contains__"):
        sequencelist = [sequencelist]
    numseq = len(sequencelist)

    # format variables
    if isinstance(epoch, numbers.Number) or isinstance(epoch, lal.LIGOTimeGPS):
        epoch = [epoch] * numseq
        epoch = map(float, epoch)
    if not len(epoch) == numseq:
        raise ValueError("Wrong number of epoch arguments given.")
    if isinstance(deltaT, numbers.Number):
        deltaT = [deltaT] * numseq
        deltaT = map(float, deltaT)
    if not len(deltaT) == numseq:
        raise ValueError("Wrong number of deltaT arguments given.")
    if not ydata is None:
        if isinstance(f0, numbers.Number):
            f0 = [f0] * numseq
            f0 = map(float, f0)
        if not len(f0) == numseq:
            raise ValueError("Wrong number of f0 arguments given.")
        if isinstance(deltaF, numbers.Number):
            deltaF = [deltaF] * numseq
            deltaF = map(float, deltaF)
        if not len(deltaF) == numseq:
            raise ValueError("Wrong number of deltaF arguments given.")

    # get limits
    xlim = kwargs.pop("xlim", None)
    ylim = kwargs.pop("ylim", None)
    colorlim = kwargs.pop("colorlim", None)
    if xlim:
        start, end = xlim
    else:
        start = min(epoch)
        end   = max(e + l.length * dt\
                    for e,l,dt in zip(epoch, sequencelist, deltaT))
    if not ydata is None and not ylim:
        ylim = [ydata.min(), ydata.max()]

    # get axis scales
    logx = kwargs.pop("logx", False)
    logy = kwargs.pop("logy", False)
    logcolor = kwargs.pop("logcolor", False)

    # get legend loc
    loc = kwargs.pop("loc", 0)
    alpha = kwargs.pop("alpha", 0.8)

    # get colorbar options
    hidden_colorbar = kwargs.pop("hidden_colorbar", False)

    # get savefig option
    bbox_inches = kwargs.pop("bbox_inches", None)

    #
    # get labels
    #

    xlabel = kwargs.pop("xlabel", None)
    if xlabel:
        unit = 1
    if not xlabel:
        unit, timestr = plotutils.time_axis_unit(end - start)
        if not t0:
            t0 = start
        t0 = lal.LIGOTimeGPS(t0)
        if int(t0.gpsNanoSeconds) == 0:
            xlabel = datetime.datetime(*lal.GPSToUTC(int(t0))[:6])\
                         .strftime("%B %d %Y, %H:%M:%S %ZUTC")
            xlabel = "Time (%s) since %s (%s)" % (timestr, xlabel, int(t0))
        else:
            xlabel = datetime.datetime(*lal.GPSToUTC(t0.gpsSeconds)[:6])\
                          .strftime("%B %d %Y, %H:%M:%S %ZUTC")
            xlabel = "Time (%s) since %s (%s)"\
                     % (timestr,
                        xlabel.replace(" UTC",".%.3s UTC" % t0.gpsNanoSeconds),\
                        t0)
        t0 = float(t0)
    ylabel = kwargs.pop("ylabel", "Frequency (Hz)")
    colorlabel = kwargs.pop("colorlabel", "Amplitude")
    title = kwargs.pop("title", "")
    subtitle = kwargs.pop("subtitle", "")

    #
    # restrict data to the correct limits for plotting
    #

    interpolate = logy and ydata is None

    for i, sequence in enumerate(sequencelist):
        if interpolate:
            # interpolate the data onto a log-scale
            sequence, ydata = loginterpolate(sequence, f0[i], deltaF[i])
        if logy and ylim:
            plotted = (ydata > ylim[0]) & (ydata <= ylim[1])
            newVectorLength = int(plotted.sum())
            newsequence = lal.CreateREAL8VectorSequence(sequence.length,\
                                                            newVectorLength)
            for j in range(sequence.length):
                newsequence.data[j, :] = sequence.data[j, :][plotted]
            del sequence
            sequencelist[i] = newsequence
    if len(sequencelist) and logy and ylim:
        ydata = ydata[plotted]

    #
    # format bins
    #

    xbins = []
    for i in range(numseq):
        xmin = epoch[i]
        xmax = epoch[i] + sequencelist[i].length * deltaT[i]
        xbins.append(rate.LinearBins(float(xmin-t0)/unit, float(xmax-t0)/unit,\
                                     2))

    ybins = []
    for i in range(numseq):
        if ydata is not None:
            ydata = numpy.asarray(ydata)
            ymin = ydata.min()
            ymax = ydata.max()
        else:
            ymin = f0[i]
            ymax = f0[i] + sequencelist[i].vectorLength * deltaF[i]
        if logy:
            if ymin == 0:
                ymin = deltaF[i]
            ybins.append(rate.LogarithmicBins(ymin, ymax, 2))
        else:
            ybins.append(rate.LinearBins(ymin, ymax, 2))

    #
    # plot
    #

    kwargs.setdefault("interpolation", "kaiser")

    plot = plotutils.ImagePlot(xlabel=xlabel, ylabel=ylabel, title=title,\
                               subtitle=subtitle, colorlabel=colorlabel)

    for sequence, x, y in zip(sequencelist, xbins, ybins):
        data = numpy.ma.masked_where(numpy.isnan(sequence.data), sequence.data,\
                                     copy=False)
        plot.add_content(data.T, x, y, **kwargs)

    # finalize
    plot.finalize(colorbar=True, logcolor=logcolor, minorticks=True,\
                  clim=colorlim)
    if hidden_colorbar:
        plotutils.add_colorbar(plot.ax, visible=False)

    # set logscale
    if logx:
        plot.ax.xaxis.set_scale("log")
    if logy:
        plot.ax.yaxis.set_scale("log")
    plot.ax._update_transScale()

    # format axes
    if xlim:
        xlim = (numpy.asarray(xlim).astype(float) - t0) / unit
        plot.ax.set_xlim(xlim)
    if ylim:
        plot.ax.set_ylim(ylim)

    # set grid and ticks
    plot.ax.grid(True, which="both")
    plotutils.set_time_ticks(plot.ax)
    plotutils.set_minor_ticks(plot.ax)

    # save and close
    plot.savefig(outfile, bbox_inches=bbox_inches,\
                 bbox_extra_artists=plot.ax.texts)
    plot.close()