def check_off_distribution(self, pop_min, pop_max, far = False):

        data_list_by_grb = self.lik_by_grb
        if far:
           data_list_by_grb = self.ifar_by_grb
           
        # prepare the plot
        if far:
            tag = 'log(IFAR)'
            sname = 'far'
        else:
            tag = 'Likelihood'
            sname = 'lik'
        plot = plotutils.SimplePlot(tag, r"cumulative sum",\
                                    r"Cumulative distribution offsource")
        
        # create the hist data in a consistent binning
        nbins = 20
        bins = rate.LinearBins(pop_min, pop_max, nbins)
        px = bins.lower()
        
        for data_list in data_list_by_grb:

            grb_name = data_list.grb_name
            
            tmp_pop = data_list.off_by_trial
            tmp_arr = np.array(tmp_pop, dtype=float)
            off_pop = tmp_arr[~np.isinf(tmp_arr)]            
            off_pop.sort()
            py = range(len(off_pop), 0, -1)
            if far:
                off_pop = np.log10(off_pop)


            ifos = self.grb_data[grb_name]['ifos']
            if ifos=='H1L1':
                linestyle = '-'
            elif ifos == 'H1H2':
                linestyle = '-.'
            else:
                linestyle = ':'
            
            
            # add content to the plot
            plot.add_content(off_pop, py, color = self.colors.next(),\
                             linestyle = linestyle, label=grb_name)
        plot.finalize()
        plot.ax.set_yscale("log")
        return plot
    def create_cdf_plot(self):

        # create the cumulative data set
        self.off_list.sort()
        on_data = np.asarray(self.on_list)
        off_data = np.asarray(self.off_list)

        y_on = []
        y_off = []
        x_onoff = []
        counter = 0
        for value in off_data[::-1]:
            counter += 1
            x_onoff.append(value)
            y_off.append(counter)
            y_on.append((on_data>value).sum())

        # replace the infinite values by 0.0 for plotting purposes
        x_onoff = np.asarray(x_onoff)
        y_on = np.asarray(y_on)
        y_off = np.asarray(y_off)                    
        inf_ind = np.isinf(x_onoff)
        x_onoff[inf_ind] = 0.0

        # scale the values correspondingly
        scale = y_on.max()/y_off.max()
        y_off_scale = y_off*scale

        # create the plot
        plot = plotutils.SimplePlot(r"Likelihood", r"Cumulative sum",\
                                    r"Cumulative distribution")
        plot.add_content(x_onoff, y_off_scale, color = 'r', \
                         linewidth = 2, label = 'off-source')
        plot.add_content(x_onoff, y_on, color = 'b',\
                         linewidth = 3, label = 'on-source')
            
        plot.finalize()
        
        # make the plot nice
        plot.ax.set_xscale('log')
        plot.ax.axis([2, 20, 0.0, 22.0])
        plot.ax.set_xticks([2,3,5,10])
        plot.ax.set_xticklabels(['2','3','5','10'])

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

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

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

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

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

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

    #
    # get labels
    #

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

    #
    # set default line params
    #

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

    #
    # make plot
    #

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

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

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

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

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

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

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

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

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

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

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

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

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

    #
    # get labels
    #

    xlabel = kwargs.pop("xlabel", "Frequency (Hz)")
    ylabel = kwargs.pop("ylabel", "Amplitude")
    title = kwargs.pop("title", "")
    subtitle = kwargs.pop("subtitle", "")

    #
    # set default line params
    #

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

    #
    # make plot
    #

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

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

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

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

    # format axes
    if xlim:
        plot.ax.set_xlim(xlim)
    if ylim:
        plot.ax.set_ylim(ylim)

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

    # save and close
    plot.savefig(outfile, bbox_inches=bbox_inches,\
                 bbox_extra_artists=plot.ax.texts)
    plot.close()
    def create_hist_plot(self, n_bin, range = None):

        def create_area(x, dx, y, dy):
            px = [x-dx/2, x+dx/2, x+dx/2, x-dx/2, x-dx/2]
            py = [y-dy/2, y-dy/2, y+dy/2, y+dy/2, y-dy/2]
            return px, py
        
        def draw_error_boxes(plot, x, dx, y, dy, col):
            
            bx, by = create_area(x, dx, y, dy )
            plot.ax.fill(bx, by, ec='w', fc = col, alpha = 0.2)
            
            bx, by = create_area(x, dx, y, 2*dy )
            plot.ax.fill(bx, by, ec='w', fc = col, alpha = 0.2)
            
            bx, by = create_area(x, dx, y, 3*dy )
            plot.ax.fill(bx, by, ec='k', fc = col, alpha = 0.2)

            return plot
        

        # set the surroundings of the parameter space
        if range is None:
            data_on = np.asarray(self.on_list)                
            inf_ind = np.isinf(data_on)
            val_min = data_on[~inf_ind].min()
            val_max = data_on.max()
        else:
            val_min = range[0]
            val_max = range[1]

        # create the hists
        hist_on = np.zeros(n_bin)
        hist_off = np.zeros(n_bin)   
        
        # create the rate bins
        lik_bins = rate.LinearBins(val_min, val_max, n_bin) 

        # and fill the histograms
        for x in self.off_list:
            if x>=val_min and x<=val_max:            
                hist_off[lik_bins[x]] += 1
            
        for x in self.on_list:
            if x>=val_min and x<=val_max:            
                hist_on[lik_bins[x]] += 1

        # get the centres
        px = lik_bins.centres()
        dx = px[1]-px[0]

        # norm the histograms
        norm = self.n_grb/self.n_off
        hist_on_norm = hist_on
        hist_off_norm = norm*hist_off

        # create the plot
        plot = plotutils.SimplePlot(r"Likelihood", r"counts",\
                                    r"Histogramm of on/offsource with %d bins"%\
                                    (n_bin))

        # the norm of the normed histograms: 1.0
        plot.add_content(px, hist_on, color = 'r', marker = 'o',\
                 markersize = 10.0, label = 'on-source')
        plot.add_content(px, hist_off_norm, color = 'b',marker = 's', \
                 markersize = 10, label = 'off-source')

        # add the error shading
        for x,n in zip(px, hist_on):
            
            # calculate the error (just the statistic error)
            dn = np.sqrt(n)
            plot = draw_error_boxes(plot, x, dx, n, dn, 'r')

        plot.finalize()           
        plot.ax.axis([val_min, val_max, 0.0, 20.0])
        #return plot
            
        # insert the lines of the data itself
        for x in self.on_list:
            if x>=val_min and x<=val_max: 
                plot.ax.plot([x,x],[0.0, 1.0],'k')            
        plot.ax.axis([val_min, val_max, 0.0, 20.0])
        
        return plot
    def create_pdf_plot(self):
        """
        Create a pdf plot of the used data.
        """
    
        # get the data and sort them in reverse order
        data_off = np.sort(self.off_list)[::-1]
        data_on = np.sort(self.on_list)[::-1]

        # remove infinities
        data_on = self.remove_empty_trials(data_on)
        data_off = self.remove_empty_trials(data_off)
        n_grb = len(data_on)

        # prepare lists
        pdf_x = []
        pdf_off_y = []
        pdf_on_y = []
        pdf_on_r = []

        # prepare the main loop
        index = 0
        sum_off = 0.0
        sum_tot = 0
        for d in data_off:

            # add one counter to the offsource sum
            sum_off += 1
            sum_tot +=1

            # have we reached an onsource statistics value?
            if d<=data_on[index]:

                # compute the values to be stored
                sum_scale = sum_off/self.n_off
                y = 1.0/n_grb
                r = y-sum_scale
                
                # store these values in the lists
                pdf_x.append(d)
                pdf_off_y.append(sum_scale)
                pdf_on_y.append(y)        
                pdf_on_r.append(r)
                
                # check breaking condition
                if index==n_grb-1:
                    break

                # reset the sum and increase the index                
                index += 1
                sum_off = 0.0
        
        # double check the data
        remain_data = data_off[data_off<=d]
        sum_off = sum(pdf_off_y)+len(remain_data)/self.n_off
        sum_on = sum(pdf_on_y)
        print "Sum of the onsource: %.1f  offsource: %.1f" % \
              (sum_on, sum_off)
                
        # create the plot
        plot = plotutils.SimplePlot(r"Likelihood", r"pdf",\
                                    r"PDF Distribution")
        plot.add_content(pdf_x, pdf_off_y, color = 'r', \
                         linewidth = 2, label = 'off-source')
        plot.add_content(pdf_x, pdf_on_y, color = 'b', marker = 'o',\
                         markersize = 10.0, label = 'on-source')
        plot.finalize()

        return plot