예제 #1
0
def time_freq_plot(database, instrument, sim):
    fig = SnglBurstUtils.figure.Figure()
    SnglBurstUtils.FigureCanvas(fig)
    # 6.5" wide, golden ratio high
    fig.set_size_inches(6.5, 6.5 / ((1 + math.sqrt(5)) / 2))

    #
    # top plot --- triggers that matched injection
    #

    t_sim = sim.time_at_instrument(instrument)

    axes = fig.add_subplot(211)
    axes.grid(True)
    #axes.set_xlabel("$t - t_{\mathrm{injection}}$ (s)")
    axes.set_ylabel("$f - f_{\mathrm{injection}}$ (Hz)")
    axes.set_title("%s Triggers Matching %g Hz Injection at GPS %s" %
                   (instrument, sim.frequency, t_sim))

    xmin = xmax = 0.0
    ymin = ymax = 0.0
    verts = []
    colours = []
    peakx = []
    peaky = []
    match_ids = []
    # find triggers from the desired instrument that are coincident
    # with the injection, and iterate over them in order from least to
    # most confident
    for burst in map(
            database.sngl_burst_table.row_from_cols,
            database.connection.cursor().execute(
                """
SELECT sngl_burst.* FROM
	sngl_burst
	JOIN coinc_event_map AS a ON (
		sngl_burst.event_id == a.event_id
		AND a.table_name == 'sngl_burst'
	)
	JOIN coinc_event_map AS b ON (
		a.coinc_event_id == b.coinc_event_id
		AND b.table_name == 'sim_burst'
	)
WHERE
	sngl_burst.ifo == ?
	AND b.event_id == ?
ORDER BY
	sngl_burst.confidence ASC
	""", (instrument, sim.simulation_id))):
        match_ids.append(burst.event_id)

        # Add time-frequency tile to collection
        tmin = float(burst.start - t_sim)
        tmax = float(burst.start + burst.duration - t_sim)
        fmin = burst.central_freq - burst.bandwidth / 2 - sim.frequency
        fmax = burst.central_freq + burst.bandwidth / 2 - sim.frequency
        verts.append(((tmin, fmin), (tmax, fmin), (tmax, fmax), (tmin, fmax)))
        colours.append(burst.confidence)

        try:
            # draw most significant tile if there is one
            tmin = float(burst.ms_start - t_sim)
            tmax = float(burst.ms_start + burst.ms_duration - t_sim)
            fmin = burst.ms_flow - sim.frequency
            fmax = burst.ms_flow + burst.ms_bandwidth - sim.frequency
            verts.append(
                ((tmin, fmin), (tmax, fmin), (tmax, fmax), (tmin, fmax)))
            colours.append(burst.ms_confidence)
        except AttributeError:
            pass

        peakx.append(float(burst.peak - t_sim))
        try:
            # use peak_frequency col if it exists
            peaky.append(burst.peak_frequency - sim.frequency)
        except AttributeError:
            peaky.append(burst.central_freq - sim.frequency)

        # update bounding box
        tmin = float(burst.start - t_sim)
        tmax = float(burst.start + burst.duration - t_sim)
        fmin = burst.central_freq - burst.bandwidth / 2 - sim.frequency
        fmax = burst.central_freq + burst.bandwidth / 2 - sim.frequency
        xmin = min(xmin, tmin)
        xmax = max(xmax, tmax)
        ymin = min(ymin, fmin)
        ymax = max(ymax, fmax)

    polys = collections.PolyCollection(verts)
    polys.set_array(numpy.array(colours))
    polys.set_alpha(0.3)
    polys.set_cmap(cm.get_cmap())
    polys.set_norm(colors.normalize())
    axes.add_collection(polys)

    axes.plot(peakx, peaky, "k+")

    axes.axvline(0, color="k")
    axes.axhline(0, color="k")

    # set the bounding box
    axes.set_xlim([1.4 * xmin, 1.4 * xmax])
    axes.set_ylim([1.4 * ymin, 1.4 * ymax])

    #
    # bottom plot --- triggers near injection
    #

    axes = fig.add_subplot(212)
    axes.grid(True)
    axes.set_xlabel("$t - t_{\mathrm{injection}}$ (s)")
    axes.set_ylabel("$f - f_{\mathrm{injection}}$ (Hz)")

    xmin = xmax = 0.0
    ymin = ymax = 0.0
    verts = []
    colours = []
    edgecolours = []
    peakx = []
    peaky = []
    # find triggers from the desired instrument that are near the
    # injection, and iterate over them in order from least to most
    # confident
    for burst in map(
            database.sngl_burst_table.row_from_cols,
            database.connection.cursor().execute(
                """
SELECT * FROM
	sngl_burst
WHERE
	ifo == ?
	AND start_time BETWEEN ? AND ?
	AND central_freq BETWEEN ? AND ?
ORDER BY
	sngl_burst.confidence ASC
	""", (instrument, int(t_sim - 2), int(t_sim + 2), sim.frequency - 300,
       sim.frequency + 300))):
        # Add time-frequency tile to collection
        tmin = float(burst.start - t_sim)
        tmax = float(burst.start + burst.duration - t_sim)
        fmin = burst.central_freq - burst.bandwidth / 2 - sim.frequency
        fmax = burst.central_freq + burst.bandwidth / 2 - sim.frequency
        verts.append(((tmin, fmin), (tmax, fmin), (tmax, fmax), (tmin, fmax)))
        colours.append(burst.confidence)
        if burst.event_id in match_ids:
            edgecolours.append("g")
        else:
            edgecolours.append("k")

        peakx.append(float(burst.peak - t_sim))
        try:
            # use peak_frequency col if it exists
            peaky.append(burst.peak_frequency - sim.frequency)
        except:
            peaky.append(burst.central_freq - sim.frequency)

        # update bounding box
        xmin = min(xmin, tmin)
        xmax = max(xmax, tmax)
        ymin = min(ymin, fmin)
        ymax = max(ymax, fmax)

    polys = collections.PolyCollection(verts, edgecolors=edgecolours)
    polys.set_array(numpy.array(colours))
    polys.set_alpha(0.3)
    polys.set_cmap(cm.get_cmap())
    polys.set_norm(colors.normalize())
    axes.add_collection(polys)

    axes.plot(peakx, peaky, "k+")

    axes.axvline(0, color="k")
    axes.axhline(0, color="k")

    # set the bounding box
    axes.set_xlim([1.4 * xmin, 1.4 * xmax])
    axes.set_ylim([1.4 * ymin, 1.4 * ymax])

    return fig
예제 #2
0
def plot_confidence_likelihood_scatter_data(slope, verbose = False):
	#
	# Start plot
	#

	fig = SnglBurstUtils.figure.Figure()
	SnglBurstUtils.FigureCanvas(fig)
	fig.set_size_inches(6.5, 6.5 / ((1 + math.sqrt(5)) / 2))
	axes = fig.gca()
	axes.grid(True)
	axes.loglog()
	axes.set_xlabel(r"Confidence")
	axes.set_ylabel(r"Likelihood Ratio")
	axes.set_title(r"Likelihood Ratio vs.\ Confidence Scatter Plot")

	#
	# Plot scatter data
	#

	def read_and_plot(filename, colour, verbose = False):
		if verbose:
			print("reading '%s' ..." % filename, file=sys.stderr)
		X = []
		Y = []
		for line in file(filename):
			if line[0] == "#":
				continue
			y, x = map(float, line.strip().split())
			X.append(x)
			Y.append(y)
		if verbose:
			print("plotting ...", file=sys.stderr)
		return axes.plot(X, Y, colour)

	set1 = read_and_plot("lalapps_excesspowerfinal_injections_scatter.dat", "r+", verbose = verbose)
	set2 = read_and_plot("lalapps_excesspowerfinal_background_scatter.dat", "k+", verbose = verbose)
	#set3 = read_and_plot("lalapps_excesspowerfinal_zero_lag_scatter.dat", "b+", verbose = verbose)

	#axes.legend((set1, set2, set3), (r"Injections", r"Background (time slides)", r"Zero lag"), loc = "lower right")
	axes.legend((set1, set2), (r"Injections", r"Background (time slides)"), loc = "lower right")

	#
	# Plot threshold contours
	#

	def fit(x, lnb):
		return numpy.exp(slope * numpy.log(x) + lnb)

	if verbose:
		print("plotting contours ...", file=sys.stderr)
	ymin, ymax = axes.get_ylim()
	for lnb in range(10, 110, 10):
		x = 10**numpy.arange(0.85, 3.0, 0.01)
		y = fit(x, lnb)
		x = numpy.compress((ymin <= y) & (y <= ymax), x)
		y = numpy.compress((ymin <= y) & (y <= ymax), y)
		axes.plot(x, y, "g-")

	#
	# Adjust plot range and add likelihood = 1.0 marker
	#

	axes.plot(axes.get_xlim(), (1, 1), "k-")
	axes.set_xlim(10**0.85, 10**3)

	#
	# Write plot
	#

	if verbose:
		print("writing 'lalapps_excesspowerfinal_scatter.png' ...", file=sys.stderr)
	fig.savefig("lalapps_excesspowerfinal_scatter.png")

	#
	# Done
	#

	if verbose:
		print("done.", file=sys.stderr)
def plot_coinc_params(distributions, gmst, plottype="LR", with_zero_lag=False):
    #
    # Create a figure.
    #

    fig = SnglBurstUtils.figure.Figure()
    SnglBurstUtils.FigureCanvas(fig)

    #
    # How many instrument pairs are there?
    #

    pairs = set(
        tuple(name.split("_")[:2])
        for name in distributions.denominator.densities if "_" in name)

    #
    # How many plots in each row?
    #

    n_horiz = len(pairs)

    #
    # How many rows?
    #

    n_vert = 5

    #
    # Each of the first len(pairs) sub plot's aspect ratio is the golden
    # ratio.
    #

    size = 4.0
    fig.set_size_inches(n_horiz * size,
                        n_vert / ((1 + math.sqrt(5)) / 2) * size)

    #
    # Plot layout.
    #

    vlabel_allowance = (n_vert * .05) / fig.figheight.get()
    hlabel_allowance = (n_horiz * .1) / fig.figwidth.get()
    border = .07 / fig.figwidth.get()
    width = 1.0 / n_horiz - hlabel_allowance - 2 * border
    height = 1.0 / n_vert

    #
    # Iterate over instrument pairs.
    #

    for i, pair in enumerate(pairs):
        #
        # Construct the axes for this instrument pair.
        #

        left = float(i) / n_horiz + hlabel_allowance + border

        dt_axes = fig.add_axes((left, 0 * height + vlabel_allowance + border,
                                width, height - vlabel_allowance - 2 * border))
        df_axes = fig.add_axes((left, 1 * height + vlabel_allowance + border,
                                width, height - vlabel_allowance - 2 * border))
        dh_axes = fig.add_axes((left, 2 * height + vlabel_allowance + border,
                                width, height - vlabel_allowance - 2 * border))
        dband_axes = fig.add_axes(
            (left, 3 * height + vlabel_allowance + border, width,
             height - vlabel_allowance - 2 * border))
        ddur_axes = fig.add_axes(
            (left, 4 * height + vlabel_allowance + border, width,
             height - vlabel_allowance - 2 * border))

        dt_axes.semilogy()
        df_axes.semilogy()
        dh_axes.semilogy()
        dband_axes.semilogy()
        ddur_axes.semilogy()

        dt_axes.set_xlabel(r"$t_{\mathrm{%s}} - t_{\mathrm{%s}}$ (ms)" % pair)
        df_axes.set_xlabel(
            r"$(f_{\mathrm{%s}} - f_{\mathrm{%s}}) / \left< f \right>$" % pair)
        dh_axes.set_xlabel(
            r"$({h_{\mathrm{rss}}}_{\mathrm{%s}} - {h_{\mathrm{rss}}}_{\mathrm{%s}}) / \left< h_{\mathrm{rss}} \right>$"
            % pair)
        dband_axes.set_xlabel(
            r"$(\Delta f_{\mathrm{%s}} - \Delta f_{\mathrm{%s}}) / \left< \Delta f \right>$"
            % pair)
        ddur_axes.set_xlabel(
            r"$(\Delta t_{\mathrm{%s}} - \Delta t_{\mathrm{%s}}) / \left< \Delta t \right>$"
            % pair)

        #
        # Plot the data on them.
        #

        prefix = "%s_%s_" % pair

        for axes, suffix in zip((df_axes, dh_axes, dband_axes, ddur_axes),
                                ("df", "dh", "dband", "ddur")):
            red = distributions.numerator.densities[prefix + suffix]
            black = distributions.denominator.densities[prefix + suffix]
            if with_zero_lag:
                blue = distributions.candidates.densities[prefix + suffix]
            else:
                blue = None
            add_to_plot(axes, red, black, blue, gmst, plottype=plottype)

        suffix = "dt"
        red = distributions.numerator.densities[prefix + suffix]
        black = distributions.denominator.densities[prefix + suffix]
        if with_zero_lag:
            blue = distributions.candidates.densities[prefix + suffix]
        else:
            blue = None
        add_to_dtplot(dt_axes, red, black, blue, gmst, plottype=plottype)

    #
    # Done.
    #

    return fig