def plothistogram(serieslist, outfile, nonzero=False, num_bins=100,\ cumulative=False, bar=False, **kwargs): """ Plots a line histogram of the data contained in the series, or list of series'. """ # construct list of series if not hasattr(serieslist, "__contains__"): serieslist = [serieslist] # get limits xlim = kwargs.pop("xlim", None) ylim = kwargs.pop("ylim", None) # set labels xlabel = kwargs.pop("xlabel", "Amplitude") ylabel = kwargs.pop("ylabel", "Fraction of data") title = kwargs.pop("title", "") subtitle = kwargs.pop("subtitle", "") # get axis scales logx = kwargs.pop("logx", False) logy = kwargs.pop("logy", 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 legend loc loc = kwargs.pop("loc", 0) alpha = kwargs.pop("alpha", 0.8) # get colors to use color = kwargs.pop("color", None) if isinstance(color, str): color = color.split(',') if len(color) == 1: color = [color[0]] * len(serieslist) # # plot # plot = plotutils.LineHistogram(xlabel, ylabel, title, subtitle) for i, series in enumerate(serieslist): data = series.data.data if nonzero: data = data[data != 0] if color: kwargs["color"] = color[i] plot.add_content(data, normalize=data.size, label=series.name, **kwargs) plot.finalize(loc=loc, alpha=alpha, logx=logx, logy=logy, bar=bar,\ xlim=xlim, num_bins=num_bins, cumulative=cumulative) if hidden_colorbar: plotutils.add_colorbar(plot.ax, visible=False) plot.ax.autoscale_view(tight=True, scalex=True, scaley=True) if xlim: plot.ax.set_xlim(xlim) if ylim: plot.ax.set_ylim(ylim) 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 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()
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()
def plothistogram(serieslist, outfile, nonzero=False, num_bins=100,\ cumulative=False, bar=False, **kwargs): """ Plots a line histogram of the data contained in the series, or list of series'. """ # construct list of series if not hasattr(serieslist, "__contains__"): serieslist = [serieslist] # get limits xlim = kwargs.pop("xlim", None) ylim = kwargs.pop("ylim", None) # set labels xlabel = kwargs.pop("xlabel", "Amplitude") ylabel = kwargs.pop("ylabel", "Fraction of data") title = kwargs.pop("title", "") subtitle = kwargs.pop("subtitle","") # get axis scales logx = kwargs.pop("logx", False) logy = kwargs.pop("logy", 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 legend loc loc = kwargs.pop("loc", 0) alpha = kwargs.pop("alpha", 0.8) # get colors to use color = kwargs.pop("color", None) if isinstance(color, str): color = color.split(',') if len(color) == 1: color = [color[0]]*len(serieslist) # # plot # plot = plotutils.LineHistogram(xlabel, ylabel, title, subtitle) for i, series in enumerate(serieslist): data = series.data.data if nonzero: data = data[data!=0] if color: kwargs["color"] = color[i] plot.add_content(data, normalize=data.size, label=series.name, **kwargs) plot.finalize(loc=loc, alpha=alpha, logx=logx, logy=logy, bar=bar,\ xlim=xlim, num_bins=num_bins, cumulative=cumulative) if hidden_colorbar: plotutils.add_colorbar(plot.ax, visible=False) plot.ax.autoscale_view(tight=True, scalex=True, scaley=True) if xlim: plot.ax.set_xlim(xlim) if ylim: plot.ax.set_ylim(ylim) 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 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 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()
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()
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 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 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)
def plotrate(lsctable, outfile, stride=60, column="peak_frequency", bins=[],\ t0=None, **kwargs): """ Plot rate versus time for the given ligolw table triggers, binned by the given bincolumn using the bins list. Arguments: lsctable : glue.ligolw.table.Table LIGOLW table containing a list of triggers outfile : string string path for output plot """ # get column data timedata = get_column(lsctable, "time") ratedata = get_column(lsctable, column) # sort in time if timedata.size: timedata, ratedata = map(numpy.asarray,\ zip(*sorted(zip(timedata,ratedata),\ key=lambda (t,r): t))) # get x-axis limits xlim = kwargs.pop("xlim", None) if xlim: start, end = xlim elif timedata.size: start = timedata.min() end = timedata.max() xlim = start, end else: start = 0 end = 1 # get other params logx = kwargs.pop("logx", False) logy = kwargs.pop("logy", False) ylim = kwargs.pop("ylim", False) hidden_colorbar = kwargs.pop("hidden_colorbar", False) bbox_inches = kwargs.pop("bbox_inches", "tight") loc = kwargs.pop("loc", 0) # get bins xbins = numpy.arange(float(start), float(end), stride) if not bins: bins = [[0, float("inf")]] ybins = [map(float, bin_) for bin_ in bins] # remove all triggers not in any bins xextent = (xbins[0], xbins[-1] + stride) yextent = (ybins[0][0], ybins[-1][-1]) inanybin = (timedata > xextent[0]) & (timedata <= xextent[1])\ & (ratedata > yextent[0]) & (ratedata <= yextent[1]) timedata = timedata[inanybin] ratedata = ratedata[inanybin] ydata = numpy.zeros((len(xbins), len(ybins))) for i, xbin in enumerate(xbins): # work out index of first trigger outside x bin try: idx = (timedata >= xbin + stride).nonzero()[0][0] # get triggers in this time bin ratebin = numpy.asarray(sorted(ratedata[:idx])) break_ = False # get triggers in this time bin ratebin = numpy.asarray(sorted(ratedata[:idx])) except IndexError: idx = None ratebin = numpy.asarray(sorted(ratedata)) break_ = True # loop over ybins for j, ybin in enumerate(ybins): # work out index of first trigger outside this y bin try: yidx = (ratebin >= ybin[1]).nonzero()[0][0] except IndexError: ydata[i][j] = len(ratebin) / stride break ydata[i][j] = len(ratebin[:yidx]) / stride ratebin = ratebin[yidx:] if break_: break timedata = timedata[idx:] xdata = xbins + stride / 2 # set xlabel and renomalize time if t0: xdata -= t0 start -= t0 end -= t0 xlabel = kwargs.pop("xlabel", None) if not xlabel: if not t0: t0 = start start -= t0 end -= t0 xdata -= t0 unit, timestr = plotutils.time_axis_unit(end - start) start /= unit end /= unit xdata = xdata / unit t0 = LIGOTimeGPS(t0) if t0.nanoseconds == 0: xlabel = datetime.datetime(*date.XLALGPSToUTC(LIGOTimeGPS(t0))[:6])\ .strftime("%B %d %Y, %H:%M:%S %ZUTC") 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) ylabel = kwargs.pop("ylabel", "Rate (Hz)") title = kwargs.pop("title", "") subtitle = kwargs.pop("subtitle", "") # # plot object # plot = plotutils.ScatterPlot(xlabel, ylabel, title, subtitle) # mask zeros for log plot if logy: ydata = numpy.ma.masked_where(ydata == 0, ydata, copy=False) for i, ybin in enumerate(ybins): if list(ybin) == [0, numpy.inf]: label = "_" else: label = "%s-%s" % (ybin[0], ybin[1]) plot.add_content(xdata, ydata[:, i], label=label, **kwargs) plot.finalize(loc=loc) if hidden_colorbar: plotutils.add_colorbar(plot.ax, visible=False) if logx: plot.ax.set_xscale("log") if logy: plot.ax.set_yscale("log") plot.ax.autoscale_view(tight=True, scalex=True, scaley=True) plot.ax.set_xlim(start, end) 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 plot.savefig(outfile, bbox_inches=bbox_inches,\ bbox_extra_artists=plot.ax.texts) plot.close()
def plotsegmentlistdict(segdict, outfile, keys=None, t0=None,\ highlight_segments=None, insetlabels=None,\ **kwargs): """ Plots a glue.segments.segmentlistdict using the PlotSegmentsPlot class from pylal.plotutils. Arguments: segdict : glue.segments.segmentlistdict dictionary of (name, segmentlist) pairs to plot. outfile : str filepath to write to Keyword arguments: keys : list ordered list of keys to use in this order on the plot t0 : float GPS time around which to zero plot highlight_segments : glue.segments.segmentlistdict list of segments to highlight with vertical red dashed lines insetlabels : [ True | False ] write labels inside the plot axis Unnamed keyword arguments: xlabel : string label for x-axis ylabel : string label for y-axis title : string title for plot subtitle : string subtitle for plot bbox_inches : str use "tight" to get a bounding box tight to the axis. """ # 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) ylabel = kwargs.pop("ylabel", "") title = kwargs.pop("title", "") subtitle = kwargs.pop("subtitle", "") # get other parameters 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 plot plot = plotutils.PlotSegmentsPlot(xlabel, ylabel, title, subtitle,\ t0=t0, dt=unit) plot.add_content(segdict, keys, **kwargs) plot.finalize(labels_inset=insetlabels) # highlight segments if highlight_segments: for seg in highlight_segments: plot.highlight_segment(seg) # add colorbar if hidden_colorbar: plotutils.add_colorbar(plot.ax, visible=False) # set axis limits xlim = [float(start - t0) / unit, float(end - t0) / unit] plot.ax.set_xlim(*xlim) # set grid plot.ax.grid(True, which="both") plotutils.set_time_ticks(plot.ax) plotutils.set_minor_ticks(plot.ax, x=False) # save 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)
def plotsegmentlistdict(segdict, outfile, keys=None, t0=None,\ highlight_segments=None, insetlabels=None,\ **kwargs): """ Plots a glue.segments.segmentlistdict using the PlotSegmentsPlot class from pylal.plotutils. Arguments: segdict : glue.segments.segmentlistdict dictionary of (name, segmentlist) pairs to plot. outfile : str filepath to write to Keyword arguments: keys : list ordered list of keys to use in this order on the plot t0 : float GPS time around which to zero plot highlight_segments : glue.segments.segmentlistdict list of segments to highlight with vertical red dashed lines insetlabels : [ True | False ] write labels inside the plot axis Unnamed keyword arguments: xlabel : string label for x-axis ylabel : string label for y-axis title : string title for plot subtitle : string subtitle for plot bbox_inches : str use "tight" to get a bounding box tight to the axis. """ # 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) ylabel = kwargs.pop("ylabel", "") title = kwargs.pop("title", "") subtitle = kwargs.pop("subtitle", "") # get other parameters 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 plot plot = plotutils.PlotSegmentsPlot(xlabel, ylabel, title, subtitle,\ t0=t0, dt=unit) plot.add_content(segdict, keys, **kwargs) plot.finalize(labels_inset=insetlabels) # highlight segments if highlight_segments: for seg in highlight_segments: plot.highlight_segment(seg) # add colorbar if hidden_colorbar: plotutils.add_colorbar(plot.ax, visible=False) # set axis limits xlim = [float(start-t0)/unit, float(end-t0)/unit] plot.ax.set_xlim(*xlim) # set grid plot.ax.grid(True, which="both") plotutils.set_time_ticks(plot.ax) plotutils.set_minor_ticks(plot.ax, x=False) # save 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 plotrate(lsctable, outfile, stride=60, column="peak_frequency", bins=[],\ t0=None, **kwargs): """ Plot rate versus time for the given ligolw table triggers, binned by the given bincolumn using the bins list. Arguments: lsctable : glue.ligolw.table.Table LIGOLW table containing a list of triggers outfile : string string path for output plot """ # get column data timedata = get_column(lsctable, "time") ratedata = get_column(lsctable, column) # sort in time if timedata.size: timedata, ratedata = map(numpy.asarray,\ zip(*sorted(zip(timedata,ratedata),\ key=lambda (t,r): t))) # get x-axis limits xlim = kwargs.pop("xlim", None) if xlim: start,end = xlim elif timedata.size: start = timedata.min() end = timedata.max() xlim = start, end else: start = 0 end = 1 # get other params logx = kwargs.pop("logx", False) logy = kwargs.pop("logy", False) ylim = kwargs.pop("ylim", False) hidden_colorbar = kwargs.pop("hidden_colorbar", False) bbox_inches = kwargs.pop("bbox_inches", "tight") loc = kwargs.pop("loc", 0) # get bins xbins = numpy.arange(float(start), float(end), stride) if not bins: bins = [[0, float("inf")]] ybins = [map(float, bin_) for bin_ in bins] # remove all triggers not in any bins xextent = (xbins[0], xbins[-1]+stride) yextent = (ybins[0][0], ybins[-1][-1]) inanybin = (timedata > xextent[0]) & (timedata <= xextent[1])\ & (ratedata > yextent[0]) & (ratedata <= yextent[1]) timedata = timedata[inanybin] ratedata = ratedata[inanybin] ydata = numpy.zeros((len(xbins), len(ybins))) for i,xbin in enumerate(xbins): # work out index of first trigger outside x bin try: idx = (timedata >= xbin+stride).nonzero()[0][0] # get triggers in this time bin ratebin = numpy.asarray(sorted(ratedata[:idx])) break_ = False # get triggers in this time bin ratebin = numpy.asarray(sorted(ratedata[:idx])) except IndexError: idx = None ratebin = numpy.asarray(sorted(ratedata)) break_ = True # loop over ybins for j,ybin in enumerate(ybins): # work out index of first trigger outside this y bin try: yidx = (ratebin >= ybin[1]).nonzero()[0][0] except IndexError: ydata[i][j] = len(ratebin)/stride break ydata[i][j] = len(ratebin[:yidx])/stride ratebin = ratebin[yidx:] if break_: break timedata = timedata[idx:] xdata = xbins + stride/2 # set xlabel and renomalize time if t0: xdata -= t0 start -= t0 end -= t0 xlabel = kwargs.pop("xlabel", None) if not xlabel: if not t0: t0 = start start -= t0 end -= t0 xdata -= t0 unit, timestr = plotutils.time_axis_unit(end-start) start /= unit end /= unit xdata = xdata/unit t0 = LIGOTimeGPS(t0) if t0.nanoseconds==0: xlabel = datetime.datetime(*date.XLALGPSToUTC(LIGOTimeGPS(t0))[:6])\ .strftime("%B %d %Y, %H:%M:%S %ZUTC") 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) ylabel = kwargs.pop("ylabel", "Rate (Hz)") title = kwargs.pop("title", "") subtitle = kwargs.pop("subtitle", "") # # plot object # plot = plotutils.ScatterPlot(xlabel, ylabel, title, subtitle) # mask zeros for log plot if logy: ydata = numpy.ma.masked_where(ydata==0, ydata, copy=False) for i,ybin in enumerate(ybins): if list(ybin) == [0, numpy.inf]: label = "_" else: label = "%s-%s" % (ybin[0], ybin[1]) plot.add_content(xdata, ydata[:,i], label=label, **kwargs) plot.finalize(loc=loc) if hidden_colorbar: plotutils.add_colorbar(plot.ax, visible=False) if logx: plot.ax.set_xscale("log") if logy: plot.ax.set_yscale("log") plot.ax.autoscale_view(tight=True, scalex=True, scaley=True) plot.ax.set_xlim(start, end) 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 plot.savefig(outfile, bbox_inches=bbox_inches,\ bbox_extra_artists=plot.ax.texts) plot.close()