Пример #1
0
def examine_draws(draws, parname, params=None, plot=True, verbose=True):
    """Use the cumulative-distribution of the draws to get mode and sigma values for a parameter.

    The return value is (median, lower 1-sigma value, upper 1-sigma value).

    If params is not None then it should be the return value of
    get_parameter_info().

    If plot is True then the cumulative distribution function will
    be displayed.

    If verbose is True then a quick comparison of the fit
    results will be displayed.
    """

    if parname not in draws["parnames"]:
        raise RuntimeError, "Unknown parameter '%s'" % parname

    # Exclude any point with an iteration number of 0
    #
    idx = draws["iteration"] > 0
    x = np.sort(draws[parname][idx])

    sigfrac = 0.682689
    median = _quantile(x, 0.5)
    lval = _quantile(x, (1 - sigfrac) / 2.0)
    hval = _quantile(x, (1 + sigfrac) / 2.0)

    y = (np.arange(x.size) + 1) * 1.0 / x.size

    # Get the best-fit value if available
    if params != None:
        idx = params["parnames"] == parname
        p0 = params["parvals"][idx][0]
        psigma = params["parmaxes"][idx][0]

    if plot:

        chips.lock()
        try:
            chips.open_undo_buffer()
            chips.erase()

            chips.add_curve(x, y, ["symbol.style", "none", "line.style", "solid"])

            chips.add_vline(median, ["style", "dot"])
            chips.add_vline(lval, ["style", "dot"])
            chips.add_vline(hval, ["style", "dot"])

            if params != None:
                chips.add_vline(p0, ["line.color", "green", "line.style", "longdash"])
                chips.add_vline(p0 - psigma, ["line.color", "green", "line.style", "longdash"])
                chips.add_vline(p0 + psigma, ["line.color", "green", "line.style", "longdash"])

            chips.set_plot_xlabel(parname)
            chips.set_plot_ylabel(r"p(\leq x)")
        except:
            chips.discard_undo_buffer()
            chips.unlock()
            raise
        chips.close_undo_buffer()
        chips.unlock()

    if verbose:
        print ""
        print "CDF of draws for parameter %s gives" % parname
        print "     median   = %g" % median
        print "     sigma    = %g , %g" % (lval - median, hval - median)
        print ""

        if params != None:
            print "     best fit = %g" % p0
            print "  covar sigma = %g" % psigma
            print ""

    return (median, lval, hval)
Пример #2
0
def examine_draws(draws, parname, params=None, plot=True, verbose=True):
    """Use the cumulative-distribution of the draws to get mode and sigma values for a parameter.

    The return value is (median, lower 1-sigma value, upper 1-sigma value).

    If params is not None then it should be the return value of
    get_parameter_info().

    If plot is True then the cumulative distribution function will
    be displayed.

    If verbose is True then a quick comparison of the fit
    results will be displayed.
    """

    if parname not in draws["parnames"]:
        raise RuntimeError, "Unknown parameter '%s'" % parname

    # Exclude any point with an iteration number of 0
    #
    idx = draws["iteration"] > 0
    x = np.sort(draws[parname][idx])

    sigfrac = 0.682689
    median = _quantile(x, 0.5)
    lval = _quantile(x, (1 - sigfrac) / 2.0)
    hval = _quantile(x, (1 + sigfrac) / 2.0)

    y = (np.arange(x.size) + 1) * 1.0 / x.size

    # Get the best-fit value if available
    if params != None:
        idx = params["parnames"] == parname
        p0 = params["parvals"][idx][0]
        psigma = params["parmaxes"][idx][0]

    if plot:

        chips.lock()
        try:
            chips.open_undo_buffer()
            chips.erase()

            chips.add_curve(x, y,
                            ["symbol.style", "none", "line.style", "solid"])

            chips.add_vline(median, ["style", "dot"])
            chips.add_vline(lval, ["style", "dot"])
            chips.add_vline(hval, ["style", "dot"])

            if params != None:
                chips.add_vline(
                    p0, ["line.color", "green", "line.style", "longdash"])
                chips.add_vline(
                    p0 - psigma,
                    ["line.color", "green", "line.style", "longdash"])
                chips.add_vline(
                    p0 + psigma,
                    ["line.color", "green", "line.style", "longdash"])

            chips.set_plot_xlabel(parname)
            chips.set_plot_ylabel(r"p(\leq x)")
        except:
            chips.discard_undo_buffer()
            chips.unlock()
            raise
        chips.close_undo_buffer()
        chips.unlock()

    if verbose:
        print ""
        print "CDF of draws for parameter %s gives" % parname
        print "     median   = %g" % median
        print "     sigma    = %g , %g" % (lval - median, median - hval)
        print ""

        if params != None:
            print "     best fit = %g" % p0
            print "  covar sigma = %g" % psigma
            print ""

    return (median, lval, hval)
Пример #3
0
def fit_draws(draws, parname, nbins=50, params=None, plot=True, verbose=True):
    """Fit a gaussian to the histogram of the given parameter.

    Before using this routine you should use get_parameter_info()
    to extract the parameter info for use by get_draws(). This is
    because using this routine will invalidate the internal
    data structures that get_draws() uses when its params argument
    is None.

    If params is not None then it should be the return value of
    get_parameter_info().

    If plot is True then a plot of the histogram and fit will be
    made.

    If verbose is True then a quick comparison of the fit
    results will be displayed.
    """

    if parname not in draws["parnames"]:
        raise RuntimeError, "Unknown parameter '%s'" % parname

    # Exclude any point with an iteration number of 0
    #
    idx = draws["iteration"] > 0
    parvals = draws[parname][idx]

    (hy, hx) = np.histogram(parvals, bins=nbins, new=True)
    xlo = hx[:-1]
    xhi = hx[1:]

    id = parname
    ui.load_arrays(id, 0.5 * (xlo + xhi), hy)

    # We can guess the amplitude and position fairly reliably;
    # for the FWHM we just use the inter-quartile range of the
    # X axis.
    #
    ui.set_source(id, ui.gauss1d.gparam)
    gparam.pos = xlo[xlo.size // 2]
    gparam.ampl = hy[xlo.size // 2]
    gparam.fwhm = xlo[xlo.size * 3 // 4] - xlo[xlo.size // 4]

    # Get the best-fit value if available
    if params != None:
        p0 = dict(zip(params["parnames"], params["parvals"]))[parname]

    logger = logging.getLogger("sherpa")
    olvl = logger.level
    logger.setLevel(40)

    ostat = ui.get_stat_name()
    ui.set_stat("leastsq")
    ui.fit(id)
    ui.set_stat(ostat)

    logger.setLevel(olvl)

    if plot:
        # We manually create the plot since we want to use a histogram for the
        # data and the Sherpa plots use curves.
        #
        ##dplot = ui.get_data_plot(id)
        mplot = ui.get_model_plot(id)

        chips.lock()
        try:
            chips.open_undo_buffer()
            chips.erase()
            chips.add_histogram(xlo, xhi, hy)
            ##chips.add_histogram(xlo, xhi, mplot.y, ["line.color", "red", "line.style", "dot"])
            chips.add_curve(mplot.x, mplot.y, ["line.color", "red", "symbol.style", "none"])

            if params != None:
                chips.add_vline(p0, ["line.color", "green", "line.style", "longdash"])

            chips.set_plot_xlabel(parname)
        except:
            chips.discard_undo_buffer()
            chips.unlock()
            raise
        chips.close_undo_buffer()
        chips.unlock()

    sigma = gparam.fwhm.val / (2.0 * np.sqrt(2 * np.log(2)))

    if verbose:
        print ""
        print "Fit to histogram of draws for parameter %s gives" % parname
        print "     mean     = %g" % gparam.pos.val
        print "     sigma    = %g" % sigma
        print ""

        if params != None:
            idx = params["parnames"] == parname
            print "     best fit = %g" % p0
            print "  covar sigma = %g" % params["parmaxes"][idx][0]
            print ""

    return (gparam.pos.val, sigma, gparam.ampl.val)
Пример #4
0
def fit_draws(draws, parname, nbins=50, params=None, plot=True, verbose=True):
    """Fit a gaussian to the histogram of the given parameter.

    Before using this routine you should use get_parameter_info()
    to extract the parameter info for use by get_draws(). This is
    because using this routine will invalidate the internal
    data structures that get_draws() uses when its params argument
    is None.

    If params is not None then it should be the return value of
    get_parameter_info().

    If plot is True then a plot of the histogram and fit will be
    made.

    If verbose is True then a quick comparison of the fit
    results will be displayed.
    """

    if parname not in draws["parnames"]:
        raise RuntimeError, "Unknown parameter '%s'" % parname

    # Exclude any point with an iteration number of 0
    #
    idx = draws["iteration"] > 0
    parvals = draws[parname][idx]

    (hy, hx) = np.histogram(parvals, bins=nbins, new=True)
    xlo = hx[:-1]
    xhi = hx[1:]

    id = parname
    ui.load_arrays(id, 0.5 * (xlo + xhi), hy)

    # We can guess the amplitude and position fairly reliably;
    # for the FWHM we just use the inter-quartile range of the
    # X axis.
    #
    ui.set_source(id, ui.gauss1d.gparam)
    gparam.pos = xlo[xlo.size // 2]
    gparam.ampl = hy[xlo.size // 2]
    gparam.fwhm = xlo[xlo.size * 3 // 4] - xlo[xlo.size // 4]

    # Get the best-fit value if available
    if params != None:
        p0 = dict(zip(params["parnames"], params["parvals"]))[parname]

    logger = logging.getLogger("sherpa")
    olvl = logger.level
    logger.setLevel(40)

    ostat = ui.get_stat_name()
    ui.set_stat("leastsq")
    ui.fit(id)
    ui.set_stat(ostat)

    logger.setLevel(olvl)

    if plot:
        # We manually create the plot since we want to use a histogram for the
        # data and the Sherpa plots use curves.
        #
        ##dplot = ui.get_data_plot(id)
        mplot = ui.get_model_plot(id)

        chips.lock()
        try:
            chips.open_undo_buffer()
            chips.erase()
            chips.add_histogram(xlo, xhi, hy)
            ##chips.add_histogram(xlo, xhi, mplot.y, ["line.color", "red", "line.style", "dot"])
            chips.add_curve(mplot.x, mplot.y,
                            ["line.color", "red", "symbol.style", "none"])

            if params != None:
                chips.add_vline(
                    p0, ["line.color", "green", "line.style", "longdash"])

            chips.set_plot_xlabel(parname)
        except:
            chips.discard_undo_buffer()
            chips.unlock()
            raise
        chips.close_undo_buffer()
        chips.unlock()

    sigma = gparam.fwhm.val / (2.0 * np.sqrt(2 * np.log(2)))

    if verbose:
        print ""
        print "Fit to histogram of draws for parameter %s gives" % parname
        print "     mean     = %g" % gparam.pos.val
        print "     sigma    = %g" % sigma
        print ""

        if params != None:
            idx = params["parnames"] == parname
            print "     best fit = %g" % p0
            print "  covar sigma = %g" % params["parmaxes"][idx][0]
            print ""

    return (gparam.pos.val, sigma, gparam.ampl.val)