예제 #1
0
    def plot(self, outfile, **params):
        """
        Plot the spectrum of this NoiseTerm.

        Arguments:

        outfile : str
            path to output file for this plot
        """
        # labels
        xlabel   = params.pop("xlabel", "Frequency (Hz)")
        ylabel   = params.pop("ylabel", "Strain amplitude spectral density "
                                        "$/\sqrt{\mbox{Hz}}$")
        title    = params.pop("title", "%s noise curve"\
                                       % plotutils.display_name(self.name))
        subtitle = params.pop("subtitle", "")

        # extract params
        bbox_inches     = params.pop("bbox_inches", "tight")
        hidden_colorbar = params.pop("hidden_colorbar", False)
        logx   = params.pop("logx", True)
        logy   = params.pop("logy", True)

        # build limits
        minx = self.deltaF
        maxx = self.spectrum.size*self.deltaF + self.f0
        xlim   = params.pop("xlim", [minx, maxx])
        ylim   = params.pop("ylim", None)

        # set plot object
        plot = plotutils.DataPlot(xlabel, ylabel, title, subtitle)

        f = numpy.arange(self.spectrum.size) * self.deltaF +\
                         self.f0
        plot.add_content(f, self.spectrum,\
                         label=plotutils.display_name(self.name),\
                         color=self.color, **params)
       
        if self.ref_spectrum is not None:
            params["linestyle"] = "--"
            params['linewidth'] = 0.3
            f = numpy.arange(self.ref_spectrum.size) *\
                self.ref_frequencyseries.deltaF + self.frequencyseries.f0
            plot.add_content(f, self.ref_spectrum,\
                         label=plotutils.display_name(self.name),\
                         color=self.color, **params)

        # finalize plot
        plot.finalize(logx=logx, logy=logy, loc='upper right',\
                      hidden_colorbar=hidden_colorbar)
        if xlim: plot.ax.set_xlim(xlim)
        if ylim: plot.ax.set_ylim(ylim)

        # save
        plot.savefig(outfile, bbox_inches=bbox_inches,\
                     bbox_extra_artists=plot.ax.texts)
예제 #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()
예제 #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()
예제 #4
0
파일: plotdata.py 프로젝트: Solaro/lalsuite
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()
예제 #5
0
파일: plotdata.py 프로젝트: Solaro/lalsuite
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()
def plottable(lsctable, outfile, xcolumn="time", ycolumn="snr",\
              colorcolumn=None, rankcolumn=None, t0=None, **kwargs):
    """
    Plot any column of a valid LigoLW table against any other, coloured by any
    other, or plot all the same if you're that way inclined. Multiple tables
    can be given for any non-coloured plot.

    "time" as a column means the output of get_peak for Burst tables, get_end
    for Inspiral tables, and get_start for ringdown tables

    Arguments:

        tables : [ dict | glue.ligolw.table.Table ]
            dict of ("name", table) pairs, or single LigoLW tables
        outfile : string
            string path for output plot

    Keyword arguments:

        xcolumn : string
            valid column of triggers table to plot on x-axis
        ycolumn : string
            valid column of triggers table to plot on y-axis
        zcolumn : string
            valid column of triggers table to use for colorbar (optional).
    """
    # work out dictionary or table
    if isinstance(lsctable, table.Table):
        tables = {"_": lsctable}
    else:
        tables = lsctable
    tablenames = tables.keys()
    tables = [tables[n] for n in tablenames]

    # get axis limits
    xlim = kwargs.pop('xlim', None)
    ylim = kwargs.pop('ylim', None)
    zlim = kwargs.pop('zlim', None)
    colorlim = kwargs.pop('colorlim', None)
    if zlim and not colorlim:
        colorlim = zlim

    # set up columns
    columns = list(map(str.lower, [xcolumn, ycolumn]))
    if colorcolumn:
        columns.append(colorcolumn.lower())
        if rankcolumn:
            columns.append(rankcolumn.lower())
        else:
            columns.append(colorcolumn.lower())

    # set up limits
    limits = [xlim, ylim, zlim, None]

    # get zero
    if "time" in columns and not t0:
        if xlim:
            t0 = float(xlim[0])
        else:
            t0 = numpy.infty
            for t in tables:
                timedata = get_column(t, "time").astype(float)
                if len(timedata):
                    t0 = min(t0, timedata.min())
            if numpy.isinf(t0):
                t0 = 0
            t0 = int(t0)

    #
    # get data
    #

    # extract columns
    data = list()
    for i, name in enumerate(tablenames):
        data.append(list())
        for c in columns:
            c = c.lower()
            if ((c not in tables[i].columnnames and c != "time")
                    and not hasattr(tables[i], "get_%s" % c.lower())):
                raise RuntimeError("Column '%s' not found in table '%s'."\
                                   % (c,name))
            data[-1].append(get_column(tables[i], c.lower()).astype(float))
            if not len(data[-1][-1].shape)\
            or data[-1][-1].shape[0] != len(tables[i]):
                raise AttributeError("No data loaded for column \"%s\" and "\
                                     "table \"%s\"" % (c, name))

    # add our own limits
    for i in range(len(columns)):
        if not limits[i]:
            mins = [data[j][i].min() for j in range(len(tablenames))\
                    if len(data[j][i].shape) and data[j][i].shape[0] != 0]
            if len(mins):
                lmin = min(mins)
                lmax = max(data[j][i].max() for j in range(len(tablenames))\
                           if len(data[j][i]))
                limits[i] = [lmin, lmax]

    # get time unit
    if "time" in columns:
        idx = columns.index("time")
        if limits[idx]:
            unit, timestr = plotutils.time_axis_unit(limits[idx][1]\
                                                     - limits[idx][0])
        else:
            unit, timestr = plotutils.time_axis_unit(1)

    # format data
    for i, name in enumerate(tablenames):
        for j, column in enumerate(columns):
            if column == "time":
                data[i][j] = (data[i][j] - t0) / unit
                if i == 0 and limits[j]:
                    limits[j] = [float(limits[j][0] - t0) / unit,\
                                 float(limits[j][1] - t0) / unit]

        # format a condition to reject triggers outside the plot range
        plotted = True
        for j, column in enumerate(columns):
            if limits[j]:
                plotted = plotted & (limits[j][0] <= data[i][j])\
                                  & (limits[j][1] >=  data[i][j])

        # apply the limits
        if not isinstance(plotted, bool):
            for j, d in enumerate(data[i]):
                data[i][j] = d[plotted]

    #
    # find loudest event
    #

    loudest = None
    if len(columns) == 4 and len(tablenames) == 1 and len(data[0][0]) > 0:
        idx = data[0][3].argmax()
        loudest = [data[0][j][idx] for j in range(len(columns))]

    #
    # get or set the labels
    #

    label = {}
    for i,(label,column) in enumerate(zip(["xlabel", "ylabel", "colorlabel"],\
                                          columns)):
        # get given label
        l = kwargs.pop(label, None)
        if l is None:
            # format time string
            if column == "time" and limits[i]:
                zerostr = datetime.datetime(\
                              *date.XLALGPSToUTC(LIGOTimeGPS(t0))[:6])\
                                       .strftime("%B %d %Y, %H:%M:%S %ZUTC")
                l = "Time (%s) since %s (%s)" % (timestr, zerostr, t0)
            # format any other column
            else:
                l = plotutils.display_name(column)
        if label == "xlabel":
            xlabel = l
        elif label == "ylabel":
            ylabel = l
        else:
            colorlabel = l

    title = kwargs.pop("title", "")
    subtitle = kwargs.pop("subtitle", None)
    if subtitle is None and loudest:
        subtitle = "Loudest event by %s:" % plotutils.display_name(columns[-1])
        for j, c in enumerate(columns):
            if j != 0 and c == columns[j - 1]: continue
            lstr = loudest[j]
            if c == "time":
                lstr = lstr * unit + t0
            subtitle += " %s=%.2f" % (plotutils.display_name(c), lstr)
    else:
        loudest = None

    #
    # get parameters
    #

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

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

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

    # get detchar plot params
    dqstyle = (kwargs.pop("detchar", False)
               or kwargs.pop('detchar_style', False))
    dqthresh = (kwargs.pop('dcthreshold', False)
                or kwargs.pop('detchar_style_threshold', 10))

    # get greyscale param
    greyscale = kwargs.pop("greyscale", False)
    if greyscale and not kwargs.has_key("cmap"):
        kwargs["cmap"] =\
            pylab.matplotlib.colors.LinearSegmentedColormap("clrs",\
                                        pylab.matplotlib.cm.hot_r._segmentdata)
    elif not kwargs.has_key("cmap"):
        kwargs["cmap"] = jet

    #
    # make the plot
    #

    tablenames = map(plotutils.display_name, tablenames)

    if len(columns) == 2:
        plot = plotutils.ScatterPlot(xlabel, ylabel, title, subtitle)
        for i in range(len(tablenames)):
            plot.add_content(data[i][0], data[i][1], label=tablenames[i],\
                             **kwargs)
        plot.finalize(loc=loc)
        if hidden_colorbar:
            plotutils.add_colorbar(plot.ax, visible=False)
    else:
        if dqstyle:
            plot = plotutils.DQScatterPlot(xlabel, ylabel, colorlabel,\
                                           title, subtitle)
        else:
            plot = plotutils.ColorbarScatterPlot(xlabel, ylabel, colorlabel,\
                                                 title, subtitle)
        plot.add_content(data[0][0], data[0][1], data[0][2],\
                         label=tablenames[0], **kwargs)
        kwargs.pop("cmap", None)
        if dqstyle:
            plot.finalize(logcolor=logcolor, clim=colorlim, loc=loc,\
                          threshold=dqthresh)
        else:
            plot.finalize(logcolor=logcolor, clim=colorlim, loc=loc)

    # plot loudest
    if loudest:
        plot.ax.plot([loudest[0]], [loudest[1]], marker="*", color="gold",\
                     markersize=15)

    # set axes
    if logx:
        plot.ax.set_xscale("log")
    if logy:
        plot.ax.set_yscale("log")
    plot.ax.autoscale_view(tight=True, scalex=True, scaley=True)

    if limits[0]:
        plot.ax.set_xlim(limits[0])
    if limits[1]:
        plot.ax.set_ylim(limits[1])

    plot.ax.grid(True, which="both")
    if xcolumn == "time":
        plotutils.set_time_ticks(plot.ax)
    plotutils.set_minor_ticks(plot.ax)

    # save and close
    if greyscale:
        plot.ax.patch.set_facecolor("#E8E8E8")
    plot.savefig(outfile, bbox_inches=bbox_inches,\
                 bbox_extra_artists=plot.ax.texts)
    plot.close()
def plothistogram(lsctable, outfile, column="snr", numbins=100,\
                  colorcolumn=None, colorbins=10, normalize=None,\
                  cumulative=None, bar=False, **kwargs):
    """
    Plot any column of a valid LigoLW table against any other, coloured by any
    other, or plot all the same if you're that way inclined. Multiple tables
    can be given for any non-coloured plot.

    "time" as a column means the output of get_peak for Burst tables, get_end
    for Inspiral tables, and get_start for ringdown tables

    Arguments:

        table : [ dict | glue.ligolw.table.Table ]
            dict of ("name", table) pairs, or single LigoLW table
        outfile : string
            string path for output plot

    Keyword arguments:
        xcolumn : string
            valid column of triggers table to plot on x-axis
        ycolumn : string
            valid column of triggers table to plot on y-axis
        zcolumn : string
            valid column of triggers table to use for colorbar (optional).
    """
    # work out dictionary or table
    if isinstance(lsctable, table.Table):
        tables = {"_": lsctable}
    else:
        tables = lsctable
    tablenames = sorted(tables.keys())
    tables = [tables[n] for n in tablenames]

    # get axis limits
    xlim = kwargs.pop("xlim", None)
    ylim = kwargs.pop("ylim", None)
    zlim = kwargs.pop("zlim", None)
    clim = kwargs.pop("clim", zlim)

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

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

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

    # get fill
    fill = kwargs.pop("fill", False)

    # get extras
    rate = kwargs.pop("rate", False)
    if normalize:
        rate = True
        if not hasattr(normalize, "__iter__"):
            normalize = [normalize] * len(tablenames)
    else:
        normalize = [1] * len(tablenames)
    loc = kwargs.pop("loc", 0)

    # set labels
    xlabel = kwargs.pop("xlabel", plotutils.display_name(column))
    if rate and cumulative:
        ylabel = kwargs.pop("ylabel", "Cumulative rate (Hz)")
    elif rate:
        ylabel = kwargs.pop("ylabel", "Rate (Hz)")
    elif not rate and cumulative:
        ylabel = kwargs.pop("ylabel", "Cumulative number")
    else:
        ylabel = kwargs.pop("ylabel", "Number")

    title = kwargs.pop("title", "")
    subtitle = kwargs.pop("subtitle", "")
    colorlabel  = kwargs.pop("colorlabel", colorcolumn\
                                  and plotutils.display_name(colorcolumn) or "")

    #
    # get column data
    #

    if colorcolumn:
        colordata = get_column(tables[0], colorcolumn).astype(float)
        if not clim and colordata.size != 0:
            clim = [colordata.min(), colordata.max()]
        elif not clim:
            clim = [1, 10]
        if isinstance(colorbins, int):
            numcolorbins = colorbins
            if logcolor:
                colorbins = numpy.logspace(*numpy.log10(clim),
                                           num=numcolorbins)
            else:
                colorbins = numpy.linspace(*clim, num=numcolorbins)
        else:
            numcolorbins = len(colorbins)

    data = list()
    for i, lsctable in enumerate(tables):
        d = get_column(lsctable, column).astype(float)
        if i == 0 and colorcolumn:
            data.append(list())
            for j in range(numcolorbins):
                data[i].append(d[d >= colorbins[j]])
        else:
            data.append(d)

    #
    # generate plot and make
    #

    if colorcolumn:
        raise NotImplementedError("This has not been implemented in "+\
                                  "plotutils yet, here's your chance!")
        plot = plotutils.ColorbarLineHistogram(xlabel, ylabel, colorlabel,\
                                               title, subtitle)
        for dataset, colorbin in zip(data[0], colorbins):
            plot.add_content(dataset, normalize=normalize[0],\
                             colorvalue=colorbin, label=tablenames[0], **kwargs)
        for i, name in enumerate(tablenames[1:]):
            plot.add_content(data[i+1], normalize=normalize[i+1],\
                             label=name, **kwargs)
        plot.finalize(logcolor=logcolor, colorlabel=colorlabel, loc=loc)
    else:
        color = kwargs.pop("color", None)
        if isinstance(color, str):
            color = color.split(',')
            if len(color) == 1:
                color = [color[0]] * len(serieslist)
        plot = plotutils.LineHistogram(xlabel, ylabel, title, subtitle)
        for i, name in enumerate(tablenames):
            if color:
                kwargs["color"] = color[i]
            plot.add_content(data[i], normalize=normalize[i], label=name,\
                             **kwargs)
        plot.finalize(loc=loc, logx=logx, logy=logy, bar=bar, num_bins=numbins,\
                      cumulative=cumulative)

    plot.ax.autoscale_view(tight=True, scalex=True, scaley=True)

    if xlim:
        plot.ax.set_xlim(xlim)
    if ylim:
        plot.ax.set_ylim(ylim)

    # save and close
    plot.savefig(outfile, bbox_inches=bbox_inches,\
                 bbox_extra_artists=plot.ax.texts)
    plot.close()
def plotdutycycle(segdict, outfile, binlength=3600, keys=None, t0=None,\
                  showmean=False, **kwargs):
    """
    Plot the percentage duty cycle each flag in the given
    glue.segments.segmentlistdict, binned over the given duration.
    """
    # get time limits
    xlim = kwargs.pop("xlim", None)
    if xlim is None:
        try:
            extents = [seg.extent() for seg in segdict.values()]
            start = min(s[0] for s in extents)
            end = max(s[1] for s in extents)
        except ValueError:
            start = 0
            end = 1
        xlim = start, end
    else:
        start, end = xlim

    # get unit for plot
    unit, timestr = plotutils.time_axis_unit(end - start)

    # set xlabel and renomalize time
    xlabel = kwargs.pop("xlabel", None)
    if not xlabel:
        if not t0:
            t0 = start
        unit, timestr = plotutils.time_axis_unit(end - start)
        t0 = LIGOTimeGPS(float(t0))
        if t0.nanoseconds == 0:
            xlabel = datetime.datetime(*date.XLALGPSToUTC(t0)[:6])\
                         .strftime("%B %d %Y, %H:%M:%S %ZUTC")
            xlabel = "Time (%s) since %s (%s)" % (timestr, xlabel, int(t0))
        else:
            xlabel = datetime.datetime(*date.XLALGPSToUTC(\
                                                  LIGOTimeGPS(t0.seconds))[:6])\
                          .strftime("%B %d %Y, %H:%M:%S %ZUTC")
            xlabel = "Time (%s) since %s (%s)"\
                     % (timestr,
                        xlabel.replace(" UTC", ".%.3s UTC" % t0.nanoseconds),\
                        t0)
        t0 = float(t0)
        xlim[0] = (start - t0) / unit
        xlim[1] = (end - t0) / unit
    ylabel = kwargs.pop("ylabel", "")
    title = kwargs.pop("title", "")
    subtitle = kwargs.pop("subtitle", "")

    # get other parameters
    loc = kwargs.pop("loc", 0)
    legalpha = kwargs.pop("alpha", 0.8)
    labels_inset = kwargs.pop("labels_inset", False)
    bbox_inches = kwargs.pop("bbox_inches", "tight")
    hidden_colorbar = kwargs.pop("hidden_colorbar", False)

    # escape underscores for latex text
    if not keys:
        keys = segdict.keys()
    if pylab.rcParams["text.usetex"]:
        newdict = segments.segmentlistdict()
        for i, key in enumerate(keys):
            newkey = re.sub('(?<!\\\\)_', '\_', key)
            keys[i] = newkey
            newdict[newkey] = segdict[key]
        segdict = newdict

    #
    # generate duty cycle info
    #

    # generate bins
    binlength = float(binlength)
    if int(end - start) % binlength == 0:
        numbins = int(end - start) / binlength
    else:
        numbins = float(end - start) // binlength + 1
    bins = numpy.arange(float(start), float(end), binlength) + binlength / 2
    duty = dict((key, numpy.zeros(numbins)) for key in keys)

    bs = float(start)
    for i in range(numbins):
        be = float(bs + binlength)
        seg = segments.segmentlist([segments.segment(bs, be)])
        for key in keys:
            duty[key][i] = float(abs(segdict[key] & seg)) / abs(seg) * 100
        bs += binlength

    if showmean:
        mean = dict((key, numpy.zeros(numbins)) for key in keys)
        for key in keys:
            mean[key] = [duty[key][:i + 1].mean() for i in range(numbins)]

    #
    # generate plot
    #

    bins = (bins - t0) / unit

    plot = plotutils.BarPlot(xlabel, ylabel, title, subtitle)
    for i, key in enumerate(keys):
        if showmean:
            thislabel = plotutils.display_name(
                key) + ' (%.2f\%%)' % (mean[key][-1])
        else:
            thislabel = plotutils.display_name(key)
        plot.add_content(bins, duty[key], label=thislabel,\
                           alpha=0.8, width=binlength/unit)
    plot.finalize(loc=loc, alpha=legalpha)

    # add running mean
    if showmean:
        for i, key in enumerate(keys):
            print i, key
            plot.ax.plot(bins, mean[key], linestyle='--')
        plot.ax.get_legend().get_frame().set_alpha(0.5)

    # add colorbar
    if hidden_colorbar:
        plotutils.add_colorbar(plot.ax, visible=False)

    # set limits
    plot.ax.autoscale_view(tight=True, scalex=True)
    if xlim:
        plot.ax.set_xlim(map(float, xlim))
    plot.ax.set_ylim(0, 100)

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

    # save figure
    plot.savefig(outfile, bbox_inches=bbox_inches,\
                 bbox_extra_artists=plot.ax.texts)
예제 #9
0
def plotdutycycle(segdict, outfile, binlength=3600, keys=None, t0=None,\
                  showmean=False, **kwargs):
    """
    Plot the percentage duty cycle each flag in the given
    glue.segments.segmentlistdict, binned over the given duration.
    """
    # get time limits
    xlim = kwargs.pop("xlim", None)
    if xlim is None:
        try:
            extents = [seg.extent() for seg in segdict.values()]
            start = min(s[0] for s in extents)
            end   = max(s[1] for s in extents)
        except ValueError:
            start = 0
            end   = 1 
        xlim  = start,end
    else:
        start,end = xlim

    # get unit for plot
    unit, timestr = plotutils.time_axis_unit(end-start)

    # set xlabel and renomalize time
    xlabel = kwargs.pop("xlabel", None)
    if not xlabel:
        if not t0:
            t0 = start
        unit, timestr = plotutils.time_axis_unit(end-start)
        t0 = LIGOTimeGPS(float(t0))
        if t0.nanoseconds==0:
            xlabel = datetime.datetime(*date.XLALGPSToUTC(t0)[:6])\
                         .strftime("%B %d %Y, %H:%M:%S %ZUTC")
            xlabel = "Time (%s) since %s (%s)" % (timestr, xlabel, int(t0))
        else:
            xlabel = datetime.datetime(*date.XLALGPSToUTC(\
                                                  LIGOTimeGPS(t0.seconds))[:6])\
                          .strftime("%B %d %Y, %H:%M:%S %ZUTC")
            xlabel = "Time (%s) since %s (%s)"\
                     % (timestr,
                        xlabel.replace(" UTC", ".%.3s UTC" % t0.nanoseconds),\
                        t0)
        t0 = float(t0)
        xlim[0] = (start - t0)/unit
        xlim[1] = (end - t0)/unit
    ylabel   = kwargs.pop("ylabel",   "")
    title    = kwargs.pop("title",    "")
    subtitle = kwargs.pop("subtitle", "")

    # get other parameters
    loc = kwargs.pop("loc", 0)
    legalpha = kwargs.pop("alpha", 0.8)
    labels_inset    = kwargs.pop("labels_inset", False)
    bbox_inches     = kwargs.pop("bbox_inches", "tight")
    hidden_colorbar = kwargs.pop("hidden_colorbar", False)

    # escape underscores for latex text
    if not keys:
        keys = segdict.keys()
    if pylab.rcParams["text.usetex"]:
        newdict = segments.segmentlistdict()
        for i,key in enumerate(keys):
           newkey = re.sub('(?<!\\\\)_', '\_', key)
           keys[i] = newkey
           newdict[newkey] = segdict[key]
        segdict = newdict

    #
    # generate duty cycle info
    #

    # generate bins
    binlength = float(binlength)
    if int(end-start) % binlength == 0:
        numbins = int(end-start)/binlength
    else:
        numbins = float(end-start)//binlength+1
    bins = numpy.arange(float(start), float(end), binlength) + binlength/2
    duty = dict((key, numpy.zeros(numbins)) for key in keys)

    bs = float(start)
    for i in range(numbins):
        be = float(bs + binlength)
        seg = segments.segmentlist([segments.segment(bs, be)])
        for key in keys:
            duty[key][i] = float(abs(segdict[key] & seg))/abs(seg) * 100
        bs += binlength

    if showmean:
      mean = dict((key, numpy.zeros(numbins)) for key in keys)
      for key in keys:
        mean[key] = [duty[key][:i+1].mean() for i in range(numbins)]

    #
    # generate plot
    #

    bins = (bins-t0)/unit

    plot = plotutils.BarPlot(xlabel, ylabel, title, subtitle)
    for i,key in enumerate(keys):
      if showmean:
        thislabel = plotutils.display_name(key) + ' (%.2f\%%)' % (mean[key][-1])
      else:
        thislabel = plotutils.display_name(key)
      plot.add_content(bins, duty[key], label=thislabel,\
                         alpha=0.8, width=binlength/unit)
    plot.finalize(loc=loc, alpha=legalpha)

    # add running mean
    if showmean:
      for i,key in enumerate(keys):
        print i, key
        plot.ax.plot(bins, mean[key], linestyle = '--')
      plot.ax.get_legend().get_frame().set_alpha(0.5)

    # add colorbar
    if hidden_colorbar:
        plotutils.add_colorbar(plot.ax, visible=False)

    # set limits
    plot.ax.autoscale_view(tight=True, scalex=True)
    if xlim:
        plot.ax.set_xlim(map(float, xlim))
    plot.ax.set_ylim(0, 100)

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

    # save figure
    plot.savefig(outfile, bbox_inches=bbox_inches,\
                 bbox_extra_artists=plot.ax.texts)
예제 #10
0
    def plot(self, outfile, **params):

        """
    Plot this NoiseBudget
        """

        # extract params
        bbox_inches     = params.pop("bbox_inches", "tight")
        hidden_colorbar = params.pop("hidden_colorbar", False)
        logx   = params.pop("logx", True)
        logy   = params.pop("logy", True)
        
        plot_component_ref = params.pop("plot_component_ref", False)
        if plot_component_ref == 'true':
          plot_component_ref = True

        # build limits
        minx = min(t.deltaF for t in self)
        maxx = max(t.spectrum.size*t.deltaF + t.f0 for t in self)
        xlim   = params.pop("xlim", [minx, maxx])
        ylim   = params.pop("ylim", None)

        # labels
        xlabel   = params.pop("xlabel", "Frequency (Hz)")
        ylabel   = params.pop("ylabel", "Strain amplitude spectral density "
                                        "$/\sqrt{\mbox{Hz}}$")
        title    = params.pop("title", plotutils.display_name(self.name))
        subtitle = params.pop("subtitle", "")

        # copy params for reference lines
        refparams = copy.deepcopy(params)
        refparams.setdefault('linestyle', '--')
        refparams['linewidth'] = 0.3

        # set plot object
        plot = plotutils.DataPlot(xlabel, ylabel, title, subtitle)
        reference_plotted = False

        # plot target and noise sum
        for term in ["target", "noise_sum"]:
            if hasattr(self, term) and getattr(self, term) is not None:
                term = getattr(self, term)
                f = numpy.arange(term.data.size) *term.frequencyseries.deltaF +\
                    term.frequencyseries.f0

                plot.add_content(f, term.data,\
                                 label=plotutils.display_name(term.name),\
                                 linecolor=term.color, **params)
 
                # plot reference
                if term.ref_spectrum is not None:
                    f = numpy.arange(term.ref_spectrum.size) *\
                        self.ref_frequencyseries.deltaF +\
                        self.ref_frequencyeries.f0
                    plot.add_content(f, term.ref_spectrum,\
                                     label=plotutils.display_name(self.name),\
                                     color=self.color, **refparams)
                    reference_plotted = True

        # plot terms in the budget
        for term in self:
            f = numpy.arange(term.spectrum.size) * term.deltaF +\
                term.f0
            plot.add_content(f, term.spectrum,\
                             label=plotutils.display_name(term.name),\
                             color=term.color, **params)
            if plot_component_ref and term.ref_spectrum is not None:
                    f = numpy.arange(term.ref_spectrum.size) *\
                        term.ref_frequencyseries.deltaF +\
                        term.ref_frequencyseries.f0
                    plot.add_content(f, term.ref_spectrum,\
                                     label=None, color=term.color, **refparams)
                    reference_plotted = True

        # finalize plot
        plot.finalize(logx=logx, logy=logy, loc='upper right',\
                      hidden_colorbar=hidden_colorbar)
        if xlim: plot.ax.set_xlim(xlim)
        if ylim: plot.ax.set_ylim(ylim)

        # add text box
        if reference_plotted:
            plot.ax.text(0.005, 0.99, 'Dashed line indicates reference',\
                         horizontalalignment='left', verticalalignment='top',\
                         transform=plot.ax.transAxes,\
                         backgroundcolor='white',\
                         bbox=dict(facecolor='white', alpha=0.6,\
                                   edgecolor='black'))

        # save
        plot.savefig(outfile, bbox_inches=bbox_inches,\
                     bbox_extra_artists=plot.ax.texts)
예제 #11
0
def plottable(lsctable, outfile, xcolumn="time", ycolumn="snr",\
              colorcolumn=None, rankcolumn=None, t0=None, **kwargs):
    """
    Plot any column of a valid LigoLW table against any other, coloured by any
    other, or plot all the same if you're that way inclined. Multiple tables
    can be given for any non-coloured plot.

    "time" as a column means the output of get_peak for Burst tables, get_end
    for Inspiral tables, and get_start for ringdown tables

    Arguments:

        tables : [ dict | glue.ligolw.table.Table ]
            dict of ("name", table) pairs, or single LigoLW tables
        outfile : string
            string path for output plot

    Keyword arguments:

        xcolumn : string
            valid column of triggers table to plot on x-axis
        ycolumn : string
            valid column of triggers table to plot on y-axis
        zcolumn : string
            valid column of triggers table to use for colorbar (optional).
    """
    # work out dictionary or table
    if isinstance(lsctable, table.Table):
        tables = {"_":lsctable}
    else:
        tables = lsctable
    tablenames = tables.keys()
    tables     = [tables[n] for n in tablenames]

    # get axis limits
    xlim = kwargs.pop('xlim', None)
    ylim = kwargs.pop('ylim', None)
    zlim = kwargs.pop('zlim', None)
    colorlim = kwargs.pop('colorlim', None)
    if zlim and not colorlim:
        colorlim = zlim

    # set up columns
    columns = list(map(str.lower, [xcolumn, ycolumn]))
    if colorcolumn:
        columns.append(colorcolumn.lower())
        if rankcolumn:
            columns.append(rankcolumn.lower())
        else:
            columns.append(colorcolumn.lower())

    # set up limits
    limits = [xlim, ylim, zlim, None]

    # get zero
    if "time" in columns and not t0:
        if xlim:
            t0 = float(xlim[0])
        else:
            t0 = numpy.infty
            for t in tables:
                timedata = get_column(t, "time").astype(float)
                if len(timedata):
                    t0 = min(t0, timedata.min())
            if numpy.isinf(t0):
                t0 = 0
            t0 = int(t0)

    #
    # get data
    #

    # extract columns
    data = list()
    for i,name in enumerate(tablenames):
        data.append(list())
        for c in columns:
            c = c.lower()
            if ((c not in tables[i].columnnames and c != "time") and not
                    hasattr(tables[i], "get_%s" % c.lower())):
                raise RuntimeError("Column '%s' not found in table '%s'."\
                                   % (c,name))
            data[-1].append(get_column(tables[i], c.lower()).astype(float))
            if not len(data[-1][-1].shape)\
            or data[-1][-1].shape[0] != len(tables[i]):
                raise AttributeError("No data loaded for column \"%s\" and "\
                                     "table \"%s\"" % (c, name))

    # add our own limits
    for i in range(len(columns)):
        if not limits[i]:
            mins = [data[j][i].min() for j in range(len(tablenames))\
                    if len(data[j][i].shape) and data[j][i].shape[0] != 0]
            if len(mins):
                lmin = min(mins)
                lmax = max(data[j][i].max() for j in range(len(tablenames))\
                           if len(data[j][i]))
                limits[i] = [lmin, lmax]

    # get time unit
    if "time" in columns:
        idx = columns.index("time")
        if limits[idx]:
            unit, timestr = plotutils.time_axis_unit(limits[idx][1]\
                                                     - limits[idx][0])
        else:
            unit, timestr = plotutils.time_axis_unit(1)

    # format data
    for i,name in enumerate(tablenames):
        for j,column in enumerate(columns):
            if column == "time":
                data[i][j] = (data[i][j] - t0) / unit
                if i==0 and limits[j]:
                    limits[j] = [float(limits[j][0] - t0) / unit,\
                                 float(limits[j][1] - t0) / unit]

        # format a condition to reject triggers outside the plot range
        plotted = True
        for j,column in enumerate(columns):
            if limits[j]:
                plotted = plotted & (limits[j][0] <= data[i][j])\
                                  & (limits[j][1] >=  data[i][j])

        # apply the limits
        if not isinstance(plotted, bool):
            for j,d in enumerate(data[i]):
                data[i][j] = d[plotted]

    #
    # find loudest event
    #

    loudest = None
    if len(columns) == 4 and len(tablenames) == 1 and len(data[0][0]) > 0:
        idx = data[0][3].argmax()   
        loudest = [data[0][j][idx] for j in range(len(columns))]

    #
    # get or set the labels
    #

    label = {}
    for i,(label,column) in enumerate(zip(["xlabel", "ylabel", "colorlabel"],\
                                          columns)):
        # get given label
        l = kwargs.pop(label, None)
        if l is None:
            # format time string
            if column == "time" and limits[i]:
                zerostr = datetime.datetime(\
                              *date.XLALGPSToUTC(LIGOTimeGPS(t0))[:6])\
                                       .strftime("%B %d %Y, %H:%M:%S %ZUTC")
                l = "Time (%s) since %s (%s)" % (timestr, zerostr, t0)
            # format any other column
            else:
                l = plotutils.display_name(column)
        if label == "xlabel":
            xlabel = l
        elif label == "ylabel":
            ylabel = l
        else:
            colorlabel = l

    title = kwargs.pop("title", "")
    subtitle = kwargs.pop("subtitle", None)
    if subtitle is None and loudest:
        subtitle = "Loudest event by %s:" % plotutils.display_name(columns[-1])
        for j,c in enumerate(columns):
            if j!= 0 and c == columns[j-1]: continue
            lstr = loudest[j]
            if c == "time":
                lstr = lstr * unit + t0
            subtitle += " %s=%.2f" % (plotutils.display_name(c), lstr)
    else:
        loudest = None

    #
    # get parameters
    #

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

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

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

    # get detchar plot params
    dqstyle  = (kwargs.pop("detchar", False) or
                kwargs.pop('detchar_style', False))
    dqthresh = (kwargs.pop('dcthreshold', False) or
                kwargs.pop('detchar_style_threshold', 10))

    # get greyscale param
    greyscale = kwargs.pop("greyscale", False)
    if greyscale and not kwargs.has_key("cmap"):
        kwargs["cmap"] =\
            pylab.matplotlib.colors.LinearSegmentedColormap("clrs",\
                                        pylab.matplotlib.cm.hot_r._segmentdata)
    elif not kwargs.has_key("cmap"):
        kwargs["cmap"] = jet

    #
    # make the plot
    #

    tablenames = map(plotutils.display_name, tablenames)

    if len(columns) == 2:
        plot = plotutils.ScatterPlot(xlabel, ylabel,title, subtitle)
        for i in range(len(tablenames)):
            plot.add_content(data[i][0], data[i][1], label=tablenames[i],\
                             **kwargs)
        plot.finalize(loc=loc)
        if hidden_colorbar:
            plotutils.add_colorbar(plot.ax, visible=False)
    else:
        if dqstyle:
            plot = plotutils.DQScatterPlot(xlabel, ylabel, colorlabel,\
                                           title, subtitle)
        else:
            plot = plotutils.ColorbarScatterPlot(xlabel, ylabel, colorlabel,\
                                                 title, subtitle)
        plot.add_content(data[0][0], data[0][1], data[0][2],\
                         label=tablenames[0], **kwargs)
        kwargs.pop("cmap", None)
        if dqstyle:
            plot.finalize(logcolor=logcolor, clim=colorlim, loc=loc,\
                          threshold=dqthresh)
        else:
            plot.finalize(logcolor=logcolor, clim=colorlim, loc=loc)

    # plot loudest
    if loudest:
        plot.ax.plot([loudest[0]], [loudest[1]], marker="*", color="gold",\
                     markersize=15)

    # set axes
    if logx:
        plot.ax.set_xscale("log")
    if logy:
        plot.ax.set_yscale("log")
    plot.ax.autoscale_view(tight=True, scalex=True, scaley=True)

    if limits[0]:
        plot.ax.set_xlim(limits[0])
    if limits[1]:
        plot.ax.set_ylim(limits[1])

    plot.ax.grid(True, which="both")
    if xcolumn == "time":
        plotutils.set_time_ticks(plot.ax)
    plotutils.set_minor_ticks(plot.ax)

    # save and close
    if greyscale:
        plot.ax.patch.set_facecolor("#E8E8E8")
    plot.savefig(outfile, bbox_inches=bbox_inches,\
                 bbox_extra_artists=plot.ax.texts)
    plot.close()
예제 #12
0
def plothistogram(lsctable, outfile, column="snr", numbins=100,\
                  colorcolumn=None, colorbins=10, normalize=None,\
                  cumulative=None, bar=False, **kwargs):
    """
    Plot any column of a valid LigoLW table against any other, coloured by any
    other, or plot all the same if you're that way inclined. Multiple tables
    can be given for any non-coloured plot.

    "time" as a column means the output of get_peak for Burst tables, get_end
    for Inspiral tables, and get_start for ringdown tables

    Arguments:

        table : [ dict | glue.ligolw.table.Table ]
            dict of ("name", table) pairs, or single LigoLW table
        outfile : string
            string path for output plot

    Keyword arguments:
        xcolumn : string
            valid column of triggers table to plot on x-axis
        ycolumn : string
            valid column of triggers table to plot on y-axis
        zcolumn : string
            valid column of triggers table to use for colorbar (optional).
    """
    # work out dictionary or table
    if isinstance(lsctable, table.Table):
        tables = {"_":lsctable}
    else:
        tables = lsctable
    tablenames = sorted(tables.keys())
    tables     = [tables[n] for n in tablenames]

    # get axis limits
    xlim = kwargs.pop("xlim", None)
    ylim = kwargs.pop("ylim", None)
    zlim = kwargs.pop("zlim", None)
    clim = kwargs.pop("clim", zlim)

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

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

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

    # get fill
    fill = kwargs.pop("fill", False)

    # get extras
    rate = kwargs.pop("rate", False)
    if normalize:
        rate = True
        if not hasattr(normalize, "__iter__"):
           normalize = [normalize]*len(tablenames)
    else:
        normalize = [1]*len(tablenames)
    loc        = kwargs.pop("loc", 0)

    # set labels
    xlabel = kwargs.pop("xlabel", plotutils.display_name(column))
    if rate and cumulative:
        ylabel = kwargs.pop("ylabel", "Cumulative rate (Hz)")
    elif rate:
        ylabel = kwargs.pop("ylabel", "Rate (Hz)")
    elif not rate and cumulative:
        ylabel = kwargs.pop("ylabel", "Cumulative number")
    else:
        ylabel = kwargs.pop("ylabel", "Number")

    title = kwargs.pop("title", "")
    subtitle = kwargs.pop("subtitle","")
    colorlabel  = kwargs.pop("colorlabel", colorcolumn\
                                  and plotutils.display_name(colorcolumn) or "")

    #
    # get column data
    #

    if colorcolumn:
        colordata = get_column(tables[0], colorcolumn).astype(float)
        if not clim and colordata.size != 0:
            clim = [colordata.min(), colordata.max()]
        elif not clim:
            clim = [1, 10]
        if isinstance(colorbins, int):
            numcolorbins = colorbins
            if logcolor:
                colorbins = numpy.logspace(*numpy.log10(clim), num=numcolorbins)
            else:
                colorbins = numpy.linspace(*clim, num=numcolorbins)
        else:
            numcolorbins = len(colorbins)

    data = list()
    for i,lsctable in enumerate(tables):
        d = get_column(lsctable, column).astype(float)
        if i==0 and colorcolumn:
            data.append(list())
            for j in range(numcolorbins):
                data[i].append(d[d>=colorbins[j]])
        else:
            data.append(d)

    #
    # generate plot and make
    #

    if colorcolumn:
        raise NotImplementedError("This has not been implemented in "+\
                                  "plotutils yet, here's your chance!")
        plot = plotutils.ColorbarLineHistogram(xlabel, ylabel, colorlabel,\
                                               title, subtitle)
        for dataset,colorbin in zip(data[0], colorbins):
            plot.add_content(dataset, normalize=normalize[0],\
                             colorvalue=colorbin, label=tablenames[0], **kwargs)
        for i,name in enumerate(tablenames[1:]):
            plot.add_content(data[i+1], normalize=normalize[i+1],\
                             label=name, **kwargs)
        plot.finalize(logcolor=logcolor, colorlabel=colorlabel, loc=loc)
    else:
        color = kwargs.pop("color", None)
        if isinstance(color, str):
            color = color.split(',')
            if len(color) == 1:
                color = [color[0]]*len(serieslist)
        plot = plotutils.LineHistogram(xlabel, ylabel, title, subtitle)
        for i,name in enumerate(tablenames):
            if color:
                kwargs["color"] = color[i]
            plot.add_content(data[i], normalize=normalize[i], label=name,\
                             **kwargs)
        plot.finalize(loc=loc, logx=logx, logy=logy, bar=bar, num_bins=numbins,\
                      cumulative=cumulative)

    plot.ax.autoscale_view(tight=True, scalex=True, scaley=True)

    if xlim:
        plot.ax.set_xlim(xlim)
    if ylim:
        plot.ax.set_ylim(ylim)

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