Exemple #1
0
def plottimeseries(series, outfile, t0=0, zeroline=False, **kwargs):
    """
    Plot a REALXTimeSeries.
    """
    # construct list of series
    if hasattr(series, "__contains__"):
        serieslist = series
    else:
        serieslist = [series]

    # get limits
    xlim = kwargs.pop("xlim", None)
    ylim = kwargs.pop("ylim", None)
    if xlim:
        start, end = xlim
    else:
        start = min(float(s.epoch) for s in serieslist)
        end = max(
            float(s.epoch + s.data.length * s.deltaT) for s in serieslist)

    # get axis scales
    logx = kwargs.pop("logx", False)
    logy = kwargs.pop("logy", 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", "Amplitude (counts)")
    title = kwargs.pop("title", "")
    subtitle = kwargs.pop("subtitle", "")

    #
    # set default line params
    #

    color = kwargs.pop("color", None)
    if isinstance(color, str):
        color = color.split(',')
        if len(color) == 1:
            color = [color[0]] * len(serieslist)
    kwargs2 = dict()
    kwargs2.update(kwargs)
    if kwargs.has_key("marker"):
        kwargs.setdefault("markersize", 5)
        kwargs2.setdefault("markersize", 2)
    else:
        kwargs.setdefault("linestyle", "-")
        kwargs.setdefault("linewidth", "1")
        kwargs2.setdefault("linewidth", "0.1")

    #
    # make plot
    #

    allnames = [s.name for s in serieslist]
    namedseries = [
        s for s in serieslist if not re.search("(min|max)\Z", s.name)
    ]

    plot = plotutils.SimplePlot(xlabel, ylabel, title, subtitle)
    for i,(series,c) in enumerate(itertools.izip(namedseries,\
                                                 plotutils.default_colors())):
        if color:
            c = color[serieslist.index(series)]
        x = numpy.arange(series.data.length) * series.deltaT +\
            float(series.epoch) - float(t0)
        x = x.astype(float)
        x /= unit
        d = series.data.data
        if logy and ylim:
            numpy.putmask(d, d == 0, ylim[0] - abs(ylim[0]) * 0.01)
        plot.add_content(x, d, color=c,\
                         label=plotutils.display_name(series.name), **kwargs)
        # find min/max and plot
        for i, name in enumerate(allnames):
            for ext in ["min", "max"]:
                if re.match("%s[- _]%s" % (re.escape(series.name), ext), name):
                    if color:
                        c = color[i]
                    series2 = serieslist[i]
                    x2 = numpy.arange(series2.data.length) * series2.deltaT\
                         + float(series2.epoch) - float(t0)
                    x2 /= unit
                    d2 = series2.data.data
                    if logy and ylim:
                        numpy.putmask(d2, d2 == 0,
                                      ylim[0] - abs(ylim[0]) * 0.01)
                    plot.ax.plot(x2, d2, color=c, **kwargs2)
                    plot.ax.fill_between(x2, d, d2, alpha=0.1,\
                                         color=c)

    # finalize
    plot.finalize(loc=loc, alpha=alpha)
    if hidden_colorbar:
        plotutils.add_colorbar(plot.ax, visible=False)

    # add zero line
    axis_lims = plot.ax.get_ylim()
    if zeroline:
        plot.ax.plot([0, 0], [axis_lims[0], axis_lims[1]], 'r--', linewidth=2)
        plot.ax.set_ylim([axis_lims[0], axis_lims[1]])

    # 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)

    plotutils.set_time_ticks(plot.ax)
    plotutils.set_minor_ticks(plot.ax, x=False)

    # save and close
    plot.savefig(outfile, bbox_inches=bbox_inches,\
                 bbox_extra_artists=plot.ax.texts)
    plot.close()
Exemple #2
0
def plottimeseries(series, outfile, t0=0, zeroline=False, **kwargs):
    """
    Plot a REALXTimeSeries.
    """
    # construct list of series
    if hasattr(series, "__contains__"):
        serieslist = series
    else:
        serieslist = [series]

    # get limits
    xlim = kwargs.pop("xlim", None)
    ylim = kwargs.pop("ylim", None)
    if xlim:
        start,end = xlim
    else:
        start = min(float(s.epoch) for s in serieslist)
        end   = max(float(s.epoch + s.data.length*s.deltaT) for s in serieslist)

    # get axis scales
    logx = kwargs.pop("logx", False)
    logy = kwargs.pop("logy", 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", "Amplitude (counts)")
    title    = kwargs.pop("title", "")
    subtitle = kwargs.pop("subtitle", "")

    #
    # set default line params
    #

    color = kwargs.pop("color", None)
    if isinstance(color, str):
        color = color.split(',')
        if len(color) == 1:
            color = [color[0]]*len(serieslist)
    kwargs2 = dict()
    kwargs2.update(kwargs)
    if kwargs.has_key("marker"):
        kwargs.setdefault("markersize", 5)
        kwargs2.setdefault("markersize", 2)
    else:
        kwargs.setdefault("linestyle", "-")
        kwargs.setdefault("linewidth", "1")
        kwargs2.setdefault("linewidth", "0.1")

    #
    # make plot
    #

    allnames    = [s.name for s in serieslist]
    namedseries = [s for s in serieslist if not re.search("(min|max)\Z",s.name)]

    plot = plotutils.SimplePlot(xlabel, ylabel, title, subtitle)
    for i,(series,c) in enumerate(itertools.izip(namedseries,\
                                                 plotutils.default_colors())):
        if color:
            c = color[serieslist.index(series)]
        x = numpy.arange(series.data.length) * series.deltaT +\
            float(series.epoch) - float(t0)
        x = x.astype(float)
        x /= unit
        d = series.data.data
        if logy and ylim:
            numpy.putmask(d, d==0, ylim[0]-abs(ylim[0])*0.01)
        plot.add_content(x, d, color=c,\
                         label=plotutils.display_name(series.name), **kwargs)
        # find min/max and plot
        for i,name in enumerate(allnames):
            for ext in ["min", "max"]:
                if re.match("%s[- _]%s" % (re.escape(series.name), ext), name):
                    if color:
                        c = color[i]
                    series2 = serieslist[i]
                    x2 = numpy.arange(series2.data.length) * series2.deltaT\
                         + float(series2.epoch) - float(t0)
                    x2 /= unit
                    d2 = series2.data.data
                    if logy and ylim:
                        numpy.putmask(d2, d2==0, ylim[0]-abs(ylim[0])*0.01)
                    plot.ax.plot(x2, d2, color=c, **kwargs2)
                    plot.ax.fill_between(x2, d, d2, alpha=0.1,\
                                         color=c)

    # finalize
    plot.finalize(loc=loc, alpha=alpha)
    if hidden_colorbar:
        plotutils.add_colorbar(plot.ax, visible=False)
    
    # add zero line
    axis_lims = plot.ax.get_ylim()
    if zeroline:
        plot.ax.plot([0, 0], [axis_lims[0], axis_lims[1]], 'r--', linewidth=2)
        plot.ax.set_ylim([ axis_lims[0], axis_lims[1] ])

    # 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)

    plotutils.set_time_ticks(plot.ax)
    plotutils.set_minor_ticks(plot.ax, x=False)

    # save and close
    plot.savefig(outfile, bbox_inches=bbox_inches,\
                 bbox_extra_artists=plot.ax.texts)
    plot.close()
Exemple #3
0
def plotfrequencyseries(series, outfile, **kwargs):
    """
    Plot a (swig)LAL FrequencySeries.
    """
    # construct list of series
    if hasattr(series, "__contains__"):
        serieslist = series
    else:
        serieslist = [series]

    # get limits
    xlim = kwargs.pop("xlim", None)
    ylim = kwargs.pop("ylim", None)
    if not xlim:
        fmin = min(float(s.f0) for s in serieslist)
        fmax = max(float(s.f0 + s.data.length * s.deltaF) for s in serieslist)
        xlim = [fmin, fmax]

    # get axis scales
    logx = kwargs.pop("logx", False)
    logy = kwargs.pop("logy", 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", "Frequency (Hz)")
    ylabel = kwargs.pop("ylabel", "Amplitude")
    title = kwargs.pop("title", "")
    subtitle = kwargs.pop("subtitle", "")

    #
    # set default line params
    #

    color = kwargs.pop("color", None)
    if isinstance(color, str):
        color = [color] * len(serieslist)
    kwargs2 = dict()
    kwargs2.update(kwargs)
    if kwargs.has_key("marker"):
        kwargs.setdefault("markersize", 5)
        kwargs2.setdefault("markersize", 2)
    else:
        kwargs.setdefault("linestyle", "-")
        kwargs.setdefault("linewidth", "1")
        kwargs2.setdefault("linewidth", "0.1")

    #
    # make plot
    #

    allnames = [s.name for s in serieslist]
    namedseries = [
        s for s in serieslist if not re.search("(min|max)\Z", s.name)
    ]

    plot = plotutils.SimplePlot(xlabel, ylabel, title, subtitle)
    for i,(series,c) in enumerate(itertools.izip(namedseries,\
                                                 plotutils.default_colors())):
        if color:
            c = color[serieslist.index(series)]
        if series.f_array is not None:
            x = series.f_array
        else:
            x = numpy.arange(series.data.length) * series.deltaF + series.f0
        x = x.astype(float)
        plot.add_content(x,
                         series.data.data,
                         color=c,
                         label=plotutils.display_name(series.name),
                         **kwargs)
        # find min/max and plot
        for i, name in enumerate(allnames):
            for ext in ["min", "max"]:
                if re.match("%s[- _]%s" % (re.escape(series.name), ext), name):
                    if color:
                        c = color[i]
                    series2 = serieslist[i]
                    if series2.f_array is not None:
                        x2 = series2.f_array
                    else:
                        x2 = numpy.arange(series2.data.length) * series2.deltaF\
                            + series2.f0
                    plot.ax.plot(x2, series2.data.data, color=c, **kwargs2)
                    # sanity check for malformed inputs
                    if series.data.data.shape == series2.data.data.shape:
                        plot.ax.fill_between(x2, series.data.data,\
                                                 series2.data.data, alpha=0.1,\
                                                 color=c)

    # finalize
    plot.finalize(loc=loc, alpha=alpha)
    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:
        plot.ax.set_xlim(xlim)
    if ylim:
        plot.ax.set_ylim(ylim)

    plot.ax.grid(True, which="both")
    plotutils.set_minor_ticks(plot.ax)

    # save and close
    plot.savefig(outfile, bbox_inches=bbox_inches,\
                 bbox_extra_artists=plot.ax.texts)
    plot.close()
Exemple #4
0
def plotfrequencyseries(series, outfile, **kwargs):
    """
    Plot a (swig)LAL FrequencySeries.
    """
    # construct list of series
    if hasattr(series, "__contains__"):
        serieslist = series
    else:
        serieslist = [series]

    # get limits
    xlim = kwargs.pop("xlim", None)
    ylim = kwargs.pop("ylim", None)
    if not xlim:
        fmin = min(float(s.f0) for s in serieslist)
        fmax = max(float(s.f0 + s.data.length*s.deltaF) for s in serieslist)
        xlim = [fmin, fmax]
        
    # get axis scales
    logx = kwargs.pop("logx", False)
    logy = kwargs.pop("logy", 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", "Frequency (Hz)")
    ylabel   = kwargs.pop("ylabel", "Amplitude")
    title    = kwargs.pop("title", "")
    subtitle = kwargs.pop("subtitle", "")

    #
    # set default line params
    #

    color = kwargs.pop("color", None)
    if isinstance(color, str):
        color = [color]*len(serieslist)
    kwargs2 = dict()
    kwargs2.update(kwargs)
    if kwargs.has_key("marker"):
        kwargs.setdefault("markersize", 5)
        kwargs2.setdefault("markersize", 2)
    else:
        kwargs.setdefault("linestyle", "-")
        kwargs.setdefault("linewidth", "1")
        kwargs2.setdefault("linewidth", "0.1")

    #
    # make plot
    #

    allnames    = [s.name for s in serieslist]
    namedseries = [s for s in serieslist if not re.search("(min|max)\Z",s.name)]

    plot = plotutils.SimplePlot(xlabel, ylabel, title, subtitle)
    for i,(series,c) in enumerate(itertools.izip(namedseries,\
                                                 plotutils.default_colors())):
        if color:
            c = color[serieslist.index(series)]
        if series.f_array is not None:
            x = series.f_array
        else:
            x = numpy.arange(series.data.length) * series.deltaF + series.f0 
        x = x.astype(float)
        plot.add_content(x, series.data.data, color=c,
                         label=plotutils.display_name(series.name), **kwargs)
        # find min/max and plot
        for i,name in enumerate(allnames):
            for ext in ["min", "max"]:
                if re.match("%s[- _]%s" % (re.escape(series.name), ext), name):
                    if color:
                        c = color[i]
                    series2 = serieslist[i]
                    if series2.f_array is not None:
                        x2 = series2.f_array
                    else:
                        x2 = numpy.arange(series2.data.length) * series2.deltaF\
                            + series2.f0 
                    plot.ax.plot(x2, series2.data.data, color=c, **kwargs2)
                    # sanity check for malformed inputs
                    if series.data.data.shape == series2.data.data.shape:
                        plot.ax.fill_between(x2, series.data.data,\
                                                 series2.data.data, alpha=0.1,\
                                                 color=c)

    # finalize
    plot.finalize(loc=loc, alpha=alpha)
    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:
        plot.ax.set_xlim(xlim)
    if ylim:
        plot.ax.set_ylim(ylim)

    plot.ax.grid(True, which="both")
    plotutils.set_minor_ticks(plot.ax)

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