Example #1
0
def df_contour(df,
               xcol,
               ycol,
               zcol,
               df_min,
               lim_params,
               correct=None,
               logscale=False,
               dof=1):
    df_lim = df.copy()
    for param in lim_params:
        df_lim = df_lim[df_lim[param] == df_min[param].values[0]]

    dfpivot = df_lim.pivot(xcol, ycol, zcol)

    Y = dfpivot.columns.values
    X = dfpivot.index.values
    Z = dfpivot.values
    print(X, Y, Z.shape)

    x, y = np.meshgrid(X, Y, indexing="ij")

    fig, ax = plt.subplots()
    if logscale:
        c = ax.contourf(x, y, Z, locator=ticker.LogLocator(), cmap=cm.viridis)
    else:
        c = ax.contourf(x, y, Z, cmap=cm.viridis)

    # Chi levels values
    print("Using chisquare dof=", dof)
    sigmas = [
        Z.ravel()[Z.argmin()] + chi2_at_sigma(sigma, dof=dof)
        for sigma in range(1, 6)
    ]
    sigma_labels = {
        sigmas[sig - 1]: "${}-\sigma$".format(sig)
        for sig in range(1, 6)
    }

    c2 = plt.contour(c, levels=sigmas)
    plt.clabel(c2, fmt=sigma_labels, colors='w', fontsize=14)
    cbar = plt.colorbar(c)
    cbar.ax.set_ylabel(zcol)
    plt.xlabel(xcol)
    plt.ylabel(ycol)

    if correct:
        # Correct location of simulation
        plt.plot(correct[xcol], correct[ycol], "ro", markersize=7)

    # Mark minimum with a +.
    min_i, min_j = divmod(Z.argmin(), Z.shape[1])
    plt.plot(X[min_i], Y[min_j], "g*", markersize=7, label="$Min \chi^2$")

    plt.show()
Example #2
0
def chi2_individual_parabola_plots(table, params):
    extractor = DBExtractor(table)
    parabola_list = ["teff_1", "logg_1", "feh_1", "gamma"]
    for par in parabola_list:
        df = extractor.simple_extraction(columns=[par])
        unique_par = list(set(df[par].values))
        unique_par.sort()

        for chi2_val, npix_val in zip(chi2_names, npix_names):
            min_chi2 = []
            for unique_val in unique_par:
                df_chi2 = extractor.fixed_ordered_extraction(
                    columns=[par, chi2_val],
                    order_by=chi2_val,
                    limit=3,
                    fixed={par: float(unique_val)},
                    asc=True)
                min_chi2.append(df_chi2[chi2_val].values[0])

            # min_chi2 = reduced_chi_squared(min_chi2, params["npix"][npix_val], params["npars"])

            min_chi2 = min_chi2 - min(min_chi2)

            plt.plot(unique_par, min_chi2, ".-", label=chi2_val)

            # popt, _ = curve_fit(parabola, unique_par, min_chi2)
            popt, _ = fit_chi2_parabola(unique_par, min_chi2)
            # print("params", popt)
            x = np.linspace(unique_par[0], unique_par[-1], 40)
            plt.plot(x, parabola(x, *popt))  # , label="parabola")
            plt.xlabel(r"${0}$".format(par))
            plt.ylabel(r"$\Delta \chi^2$ from mimimum")
            plt.ylim([-0.05 * np.max(min_chi2), np.max(min_chi2)])
            # Find roots

            try:
                residual = lambda x: parabola(x, *popt) - chi2_at_sigma(
                    1, params["npars"])
                min_chi2_par = unique_par[np.argmin(min_chi2)]
                min_chi2_par.astype(np.float64)
                try:
                    lower_bound = newton(
                        residual,
                        (min_chi2_par + unique_par[0]) / 2) - min_chi2_par
                except RuntimeError as e:
                    print(e)
                    lower_bound = np.nan
                try:
                    upper_bound = newton(
                        residual,
                        (min_chi2_par + unique_par[-1]) / 2) - min_chi2_par
                except RuntimeError as e:
                    print(e)
                    upper_bound = np.nan
                print("min_chi2_par", min_chi2_par,
                      type(min_chi2_par), "\nlower_bound", lower_bound,
                      type(lower_bound), "\nupper_bound", upper_bound,
                      type(upper_bound))
                print("{0} solution {1: 5.3} {2:+5.3} {3:+5.3}".format(
                    chi2_val, float(min_chi2_par), float(lower_bound),
                    float(upper_bound)))
                plt.annotate("{0: 5.3f} {1:+5.3f} {2:+5.3f}".format(
                    float(min_chi2_par), (lower_bound), (upper_bound)),
                             xy=(float(min_chi2_par), 0),
                             xytext=(0.4, 0.5),
                             textcoords="figure fraction",
                             arrowprops={"arrowstyle": "->"})
            except Exception as e:
                print(e)
                logging.warning("Could not Annotate the contour plot")

            plt.axhline(y=chi2_at_sigma(1, params["npars"]), label="1 sigma")
            plt.axhline(y=chi2_at_sigma(2, params["npars"]), label="2 sigma")
            plt.axhline(y=chi2_at_sigma(3, params["npars"]), label="3 sigma")

            plt.legend()
            filename = "Chi2_Parabola_fit_{0}-{1}_{2}_param_{3}_{4}_individual_{5}.png".format(
                params["star"], params["obsnum"], params["chip"], par,
                params["suffix"], chi2_val)

            plt.savefig(os.path.join(params["path"], "plots", filename))
            plt.close()
            print("saved individual chi2 parabolas for ", par)
            plt.close()