예제 #1
0
def dataLoader(fitrs, QuietMode=True):
    """
    Load the data objects.  Import the module within the function.
    """
    from sedfit import sedclass as sedsc
    #-> Setup the data
    dataPck = fitrs["dataPck"]
    targname = dataPck["targname"]
    redshift = dataPck["redshift"]
    distance = dataPck["distance"]
    dataDict = dataPck["dataDict"]
    sedPck   = dataPck["sedPck"]
    sedData = sedsc.setSedData(targname, redshift, distance, dataDict, sedPck,
                               QuietMode)
    return sedData
예제 #2
0
def gsm_mocker(configName,
               targname=None,
               redshift=None,
               distance=None,
               sedFile=None,
               mockPars=None,
               uncModel=None,
               plot=False,
               cal_lnlike=False,
               **kwargs):
    """
    The wrapper of mocker() function. If the targname, redshift and sedFile
    are provided as arguments, they will be used overriding the values in the
    config file saved in configName. If they are not provided, then, the values
    in the config file will be used.

    Parameters
    ----------
    configName : str
        The full path of the config file.
    targname : str or None by default
        The name of the target.
    redshift : float (optional)
        The redshift of the target.
    distance : float (optional)
        The distance of the target.
    sedFile : str or None by default
        The full path of the sed data file.
    mockPars : list
        The parameters to generate the mock SED.
    uncModel : dict or None, by default
        {
            "lnf" : float, (-inf, 0]
                The ln of f, the imperfectness of the model.
            "lna" : float, (-inf, 1]
                The ln of a, the amplitude of the residual correlation.
            "lntau" : float, (-inf, 1]
                The ln of tau, the scale length of the residual correlation.
        }
    plot : bool, default: False
        Plot the SED to visually check if True.

    Returns
    -------
    mock : tuple
        The (wavelength, flux, sigma, band) of the mock data in the observed frame.
    lnlike : float (optional)
        The lnlikelihood of the mock SED and the model.
    FigAx : tuple (optional)
        The (fig, ax) of the SED figure, if plot is True.

    Notes
    -----
    None.
    """
    #config = importlib.import_module(configName.split(".")[0])
    config = configImporter(configName)
    if targname is None:
        assert redshift is None
        assert sedFile is None
        targname = config.targname
        redshift = config.redshift
        sedFile = config.sedFile
    else:
        assert not redshift is None
        assert not sedFile is None
    print("#--------------------------------#")
    print("Target: {0}".format(targname))
    print("SED file: {0}".format(sedFile))
    print("Config file: {0}".format(configName))
    print("#--------------------------------#")

    try:
        silent = config.silent
    except:
        silent = False
    ############################################################################
    #                                 Data                                     #
    ############################################################################
    dataDict = config.dataDict
    sedPck = sedt.Load_SED(sedFile)
    sedData = sedsc.setSedData(targname, redshift, distance, dataDict, sedPck,
                               silent)

    ############################################################################
    #                                 Model                                    #
    ############################################################################
    modelDict = config.modelDict
    print("The model info:")
    parCounter = 0
    for modelName in modelDict.keys():
        print("[{0}]".format(modelName))
        model = modelDict[modelName]
        for parName in model.keys():
            param = model[parName]
            if not isinstance(param, types.DictType):
                continue
            elif param["vary"]:
                print("-- {0}, {1}".format(parName, param["type"]))
                parCounter += 1
            else:
                pass
    print("Varying parameter number: {0}".format(parCounter))
    print("#--------------------------------#")

    #->Build up the model
    funcLib = sedmf.funcLib
    waveModel = config.waveModel
    try:
        parAddDict_all = config.parAddDict_all
    except:
        parAddDict_all = {}
    parAddDict_all["DL"] = sedData.dl
    parAddDict_all["z"] = redshift
    parAddDict_all["frame"] = "rest"
    sedModel = bc.Model_Generator(modelDict, funcLib, waveModel,
                                  parAddDict_all)
    sedModel.updateParList(
        mockPars)  #Set the model with the desiring parameters.

    ############################################################################
    #                                  Mock                                    #
    ############################################################################
    mockPck = mocker(sedData, sedModel, **kwargs)
    #->Reform the result and switch back to the observed frame
    sed = mockPck["sed"]
    pht = mockPck["pht"]
    spc = mockPck["spc"]
    sed = sedt.SED_to_obsframe(sed, redshift)
    pht = sedt.SED_to_obsframe(pht, redshift)
    spc = sedt.SED_to_obsframe(spc, redshift)
    phtwave = pht[0]
    phtband = pht[3]
    spcwave = spc[0]
    mockSedWave = sed[0]
    mockSedFlux = sed[1]
    mockSedSigma = sed[2]
    mockSedBand = np.concatenate(
        [phtband, np.zeros_like(spcwave, dtype="int")])
    mock = (mockSedWave, mockSedFlux, mockSedSigma, mockSedBand)
    result = [mock]
    #->Calculate the lnlike
    mockDict = {
        "phtName": dataDict["phtName"],
        "spcName": dataDict["spcName"],
        "bandList_use": dataDict["bandList_use"],
        "bandList_ignore": dataDict["bandList_ignore"],
        "frame": "obs",
    }
    mockPck = {"sed": sed, "pht": pht, "spc": spc}
    mockData = sedsc.setSedData(targname, redshift, distance, mockDict,
                                mockPck, silent)
    if cal_lnlike:
        lnlike = sedLnLike(mockData, sedModel, uncModel)
        result.append(lnlike)
    #->Plot
    if plot:
        FigAx = PlotMockSED(sedData, mockData, sedModel)
        result.append(FigAx)
    return result
예제 #3
0
def gsf_fitter(configName,
               targname=None,
               redshift=None,
               distance=None,
               sedFile=None,
               mpi_pool=None,
               refit=False):
    """
    The wrapper of fitter() function. If the targname, redshift and sedFile are
    provided as arguments, they will be used overriding the values in the config
    file saved in configName. If they are not provided, then, the values in the
    config file will be used.

    Parameters
    ----------
    configName : str
        The full path of the config file.
    targname : str or None by default
        The name of the target.
    redshift : float or None by default
        The redshift of the target.
    distance : float or None by default
        The distance of the source from the Sun.
    sedFile : str or None by default
        The full path of the sed data file.
    mpi_pool : (optional) emcee.mpi_pool.MPIPool object
        The pool of MPI to run, if provided.

    Returns
    -------
    None.

    Notes
    -----
    None.
    """
    ############################################################################
    #                                Setup                                     #
    ############################################################################
    config = configImporter(configName)
    if targname is None:
        assert redshift is None
        assert distance is None
        assert sedFile is None
        targname = config.targname
        redshift = config.redshift
        distance = config.distance
        sedFile = config.sedFile
    else:
        assert not redshift is None
        assert not sedFile is None
    print("#--------------------------------#")
    print("Target:      {0}".format(targname))
    print("Redshift:    {0}".format(redshift))
    print("Distance:    {0}".format(distance))
    print("SED file:    {0}".format(sedFile))
    print("Config file: {0}".format(configName))
    print("#--------------------------------#")
    #-> Verbose or not
    try:
        silent = config.silent
    except:
        silent = False
    #-> Check whether there is already fitting results
    try:
        ppDict = config.ppDict
    except:
        print("[gsf] Warning: cannot find ppDict in the configure file!")
        ppDict = {}
    savePath = ppDict.get("savepath", "results/")
    if os.path.isfile("{0}{1}.fitrs".format(savePath, targname)):
        if refit:
            print("The object {0} is overwrited!".format(targname))
        else:
            print("The object {0} is skipped!".format(targname))
            return 1
    #-> Dump the modelDict for model_functions.py to choose the modules to import
    modelDict = config.modelDict
    modelDictPath = "{0}temp_model.dict".format(root_path)
    fp = open(modelDictPath, "w")
    pickle.dump(modelDict, fp)
    fp.close()

    #->Setup the data Data
    dataDict = config.dataDict
    sedPck = sedt.Load_SED(sedFile)
    from sedfit import sedclass as sedsc
    sedData = sedsc.setSedData(targname, redshift, distance, dataDict, sedPck,
                               silent)

    #->Setup the model
    print("#--------------------------------#")
    print("The model info:")
    parCounter = 0
    for modelName in modelDict.keys():
        print("[{0}]".format(modelName))
        model = modelDict[modelName]
        for parName in model.keys():
            param = model[parName]
            if not isinstance(param, types.DictType):
                continue
            elif param["vary"]:
                print("-- {0}, {1}".format(parName, param["type"]))
                parCounter += 1
            else:
                pass
    print("Varying parameter number: {0}".format(parCounter))
    print("#--------------------------------#")
    #--> Import the model functions
    from sedfit import model_functions as sedmf
    funcLib = sedmf.funcLib
    waveModel = config.waveModel
    try:
        parAddDict_all = config.parAddDict_all
    except:
        parAddDict_all = {}
    parAddDict_all["DL"] = sedData.dl
    parAddDict_all["z"] = redshift
    parAddDict_all["frame"] = "rest"
    #from sedfit.fitter import basicclass as bc
    #sedModel  = bc.Model_Generator(modelDict, funcLib, waveModel, parAddDict_all)
    from sedfit.sedmodel import SedModel
    sedModel = SedModel(modelDict, funcLib, waveModel, parAddDict_all)

    ############################################################################
    #                                   Fit                                    #
    ############################################################################
    parTruth = config.parTruth  #Whether to provide the truth of the model
    unctDict = config.unctDict
    emceeDict = config.emceeDict
    em = fitter(sedData, sedModel, unctDict, parTruth, emceeDict, mpi_pool)

    ############################################################################
    #                              Post process                                #
    ############################################################################
    print("#--------------------------------#")
    #-> Remove the temp files
    os.remove(modelDictPath)

    #-> Load the post process information
    psLow = ppDict.get("low", 16)
    psCenter = ppDict.get("center", 50)
    psHigh = ppDict.get("high", 84)
    nuisance = ppDict.get("nuisance", True)
    fraction = ppDict.get("fraction", 0)
    burnIn = ppDict.get("burn-in", 50)

    #-> Dump the fitting results
    #--> Check the save path. Create the directory if it does not exists.
    if not os.path.isdir(savePath):
        os.makedirs(savePath)
    print("Save all the results to: {0}".format(savePath))
    dataPck = {
        "targname": targname,
        "redshift": redshift,
        "distance": sedData.dl,
        "sedPck": sedPck,
        "dataDict": dataDict
    }
    modelPck = {
        "modelDict": modelDict,
        "waveModel": waveModel,
        "parAddDict_all": parAddDict_all,
        "parTruth": parTruth,
        "unctDict": unctDict
    }
    fitrs = {
        "dataPck": dataPck,
        "modelPck": modelPck,
        "ppDict": ppDict,
        "posterior_sample": em.posterior_sample(burnin=burnIn,
                                                fraction=fraction),
        "chain": em.sampler.chain,
        "lnprobability": em.sampler.lnprobability
    }
    fp = open("{0}{1}.fitrs".format(savePath, targname), "w")
    pickle.dump(fitrs, fp)
    fp.close()
    #->Save the best-fit parameters
    em.Save_BestFit("{0}{1}_bestfit.txt".format(savePath, targname),
                    low=psLow,
                    center=psCenter,
                    high=psHigh,
                    burnin=burnIn,
                    fraction=fraction)
    #->Plot the chain of the final run
    em.plot_chain(filename="{0}{1}_chain.png".format(savePath, targname),
                  truths=parTruth)
    #->Plot the SED fitting result figure
    sedwave = sedData.get_List("x")
    sedflux = sedData.get_List("y")
    xmin = np.min(sedwave) * 0.9
    xmax = np.max(sedwave) * 1.1
    xlim = [xmin, xmax]
    ymin = np.min(sedflux) * 0.5
    ymax = np.max(sedflux) * 2.0
    ylim = [ymin, ymax]
    flag_two_panel = sedData.check_csData() & sedData.check_dsData()
    if flag_two_panel:
        fig, axarr = plt.subplots(2, 1)
        fig.set_size_inches(10, 10)
        em.plot_fit_spec(truths=parTruth,
                         FigAx=(fig, axarr[0]),
                         nSamples=100,
                         burnin=burnIn,
                         fraction=fraction)
        em.plot_fit(truths=parTruth,
                    FigAx=(fig, axarr[1]),
                    xlim=xlim,
                    ylim=ylim,
                    nSamples=100,
                    burnin=burnIn,
                    fraction=fraction)
        axarr[0].set_xlabel("")
        axarr[0].set_ylabel("")
        axarr[0].text(0.05,
                      0.8,
                      targname,
                      transform=axarr[0].transAxes,
                      fontsize=24,
                      verticalalignment='bottom',
                      horizontalalignment='left',
                      bbox=dict(facecolor='white', alpha=0.5,
                                edgecolor="none"))
    else:
        fig = plt.figure(figsize=(10, 5))
        ax = plt.gca()
        em.plot_fit(truths=parTruth,
                    FigAx=(fig, ax),
                    xlim=xlim,
                    ylim=ylim,
                    nSamples=100,
                    burnin=burnIn,
                    fraction=fraction)
        ax.text(0.05,
                0.95,
                targname,
                transform=ax.transAxes,
                fontsize=24,
                verticalalignment='top',
                horizontalalignment='left',
                bbox=dict(facecolor='white', alpha=0.5, edgecolor="none"))
        ax.legend(loc="lower right", framealpha=0.3, fontsize=15, numpoints=1)
    plt.savefig("{0}{1}_result.png".format(savePath, targname),
                bbox_inches="tight")
    plt.close()
    #->Plot the posterior probability distribution
    em.plot_corner(filename="{0}{1}_triangle.png".format(savePath, targname),
                   burnin=burnIn,
                   nuisance=nuisance,
                   truths=parTruth,
                   fraction=fraction,
                   quantiles=[psLow / 100., psCenter / 100., psHigh / 100.],
                   show_titles=True,
                   title_kwargs={"fontsize": 20})
    print("Post-processed!")
    return 0
예제 #4
0
def gsf_fitter(configName, targname=None, redshift=None, distance=None, sedFile=None, mpi_pool=None):
    """
    The wrapper of fitter() function. If the targname, redshift and sedFile are
    provided as arguments, they will be used overriding the values in the config
    file saved in configName. If they are not provided, then, the values in the
    config file will be used.

    Parameters
    ----------
    configName : str
        The full path of the config file.
    targname : str or None by default
        The name of the target.
    redshift : float or None by default
        The redshift of the target.
    distance : float or None by default
        The distance of the source from the Sun.
    sedFile : str or None by default
        The full path of the sed data file.
    mpi_pool : (optional) emcee.mpi_pool.MPIPool object
        The pool of MPI to run, if provided.

    Returns
    -------
    None.

    Notes
    -----
    None.
    """
    ############################################################################
    #                                Setup                                     #
    ############################################################################
    config = configImporter(configName)
    if targname is None:
        assert redshift is None
        assert distance is None
        assert sedFile is None
        targname = config.targname
        redshift = config.redshift
        distance = config.distance
        sedFile  = config.sedFile
    else:
        assert not redshift is None
        assert not sedFile is None
    print("#--------------------------------#")
    print("Target:      {0}".format(targname))
    print("Redshift:    {0}".format(redshift))
    print("Distance:    {0}".format(distance))
    print("SED file:    {0}".format(sedFile))
    print("Config file: {0}".format(configName))
    print("#--------------------------------#")

    try:
        silent = config.silent
    except:
        silent = False

    #->Setup the data Data
    dataDict = config.dataDict
    sedPck = sedt.Load_SED(sedFile)
    sedData = sedsc.setSedData(targname, redshift, distance, dataDict, sedPck, silent)

    #->Setup the model
    modelDict = config.modelDict
    print("The model info:")
    parCounter = 0
    for modelName in modelDict.keys():
        print("[{0}]".format(modelName))
        model = modelDict[modelName]
        for parName in model.keys():
            param = model[parName]
            if not isinstance(param, types.DictType):
                continue
            elif param["vary"]:
                print("-- {0}, {1}".format(parName, param["type"]))
                parCounter += 1
            else:
                pass
    print("Varying parameter number: {0}".format(parCounter))
    print("#--------------------------------#")
    funcLib   = sedmf.funcLib
    waveModel = config.waveModel
    try:
        parAddDict_all = config.parAddDict_all
    except:
        parAddDict_all = {}
    parAddDict_all["DL"]    = sedData.dl
    parAddDict_all["z"]     = redshift
    parAddDict_all["frame"] = "rest"
    sedModel  = bc.Model_Generator(modelDict, funcLib, waveModel, parAddDict_all)

    ############################################################################
    #                                   Fit                                    #
    ############################################################################
    modelUnct = config.modelUnct #Whether to consider the model uncertainty in the fitting
    parTruth  = config.parTruth  #Whether to provide the truth of the model
    unctDict = config.unctDict
    emceeDict = config.emceeDict
    em = fitter(sedData, sedModel, unctDict, parTruth, emceeDict, mpi_pool)

    ############################################################################
    #                              Post process                                #
    ############################################################################
    try:
        ppDict = config.ppDict
    except:
        print("[gsf] Warning: cannot find ppDict in the configure file!")
        ppDict = {}
    psLow    = ppDict.get("low", 16)
    psCenter = ppDict.get("center", 50)
    psHigh   = ppDict.get("high", 84)
    nuisance = ppDict.get("nuisance", True)
    fraction = ppDict.get("fraction", 0)
    burnIn   = ppDict.get("burn-in", 50)

    dataPck = {
        "targname": targname,
        "redshift": redshift,
        "distance": sedData.dl,
        "sedPck": sedPck,
        "dataDict": dataDict
    }
    modelPck = {
        "modelDict": modelDict,
        "waveModel": waveModel,
        "parAddDict_all": parAddDict_all,
        "parTruth": parTruth,
        "modelUnct": modelUnct
    }
    fitrs = {
        "dataPck": dataPck,
        "modelPck": modelPck,
        "ppDict": ppDict,
        "posterior_sample": em.posterior_sample(burnin=burnIn, fraction=fraction),
        "chain": em.sampler.chain,
        "lnprobability": em.sampler.lnprobability
    }
    fp = open("result/{0}.fitrs".format(targname), "w")
    pickle.dump(fitrs, fp)
    fp.close()
    #->Save the best-fit parameters
    em.Save_BestFit("result/{0}_bestfit.txt".format(targname), low=psLow, center=psCenter, high=psHigh,
                    burnin=burnIn, fraction=fraction)
    #->Plot the chain of the final run
    em.plot_chain(filename="result/{0}_chain.png".format(targname), truths=parTruth)
    #->Plot the SED fitting result figure
    # Plot the SED data and fit
    ps = fitrs['posterior_sample']
    sedwave = sedData.get_List("x")
    sedflux = sedData.get_List("y")
    spcwave = sedData.get_csList("x")
    spcflux = sedData.get_csList("y")
    if sedData.check_csData():
        fig = plt.figure(figsize=(8, 8))
        ax = fig.add_subplot(111)  # The big subplot
        ax1 = fig.add_subplot(211)
        ax2 = fig.add_subplot(212)
        # ->Plot the upper panel
        xmin = np.nanmin(spcwave) * 0.9
        xmax = np.nanmax(spcwave) * 1.1
        ymin = np.nanmin(spcflux) * 0.8
        ymax = np.nanmax(spcflux) * 1.2
        xlim = [xmin, xmax]
        ylim = [ymin, ymax]
        em.plot_fit(truths=parTruth, FigAx=(fig, ax1), xlim=xlim, ylim=ylim, nSamples=100,
                    burnin=burnIn, fraction=fraction, ps=ps, showLegend=False)
        # plot uncertainty of spectrum
        # spcsig = sedPck['spc'][2]
        # spcflux = np.array(spcflux)
        # spcsig = np.array(spcsig)
        # ax1.fill_between(spcwave, spcflux-spcsig, spcflux+spcsig, facecolors='grey', alpha=0.2)
        # -->Set the labels
        xTickLabels = [10., 20.]
        ax1.set_xticks(xTickLabels)
        ax1.set_xticklabels(xTickLabels)
        ax1.xaxis.set_major_formatter(FormatStrFormatter("%d"))
        yTL = ticksFinder(ymin, ymax, yTicksTry=np.linspace(ymin, ymax, 20))
        yTickLabels = [np.around(yTL, decimals=-1 * int(np.log10(yTL)))]
        ax1.set_yticks(yTickLabels)
        ax1.set_yticklabels(yTickLabels)
        ax1.yaxis.set_major_formatter(FormatStrFormatter("%d"))
        ax1.set_xlabel("")
        ax1.set_ylabel("")
        ax1.tick_params(axis="both", which="major", length=8, labelsize=18)
        ax1.tick_params(axis="both", which="minor", length=5)
        ax1.text(0.05, 0.9, targname,
                 verticalalignment='bottom', horizontalalignment='left',
                 transform=ax.transAxes, fontsize=24,
                 bbox=dict(facecolor='white', alpha=0.5, edgecolor="none"))
        # -->Set the legend
        phtName = dataDict["phtName"]
        spcName = dataDict["spcName"]
        handles, labels = ax1.get_legend_handles_labels()
        handleUse = []
        labelUse = []
        for loop in range(len(labels)):
            lb = labels[loop]
            hd = handles[loop]
            if lb == "Hot_Dust":
                lb = "BB"
            # if lb == "CLUMPY":
            #    lb = "CLU"
            if lb == phtName:
                hd = hd[0]
            if lb != spcName:
                labelUse.append(lb)
                handleUse.append(hd)
            else:
                label_spc = lb
                handle_spc = hd
        labelUse.append(label_spc)
        handleUse.append(handle_spc)
        ax1.legend(handleUse, labelUse, loc="lower right", ncol=2,
                   framealpha=0.9, edgecolor="white",  # frameon=False, #
                   fontsize=16, labelspacing=0.3, columnspacing=0.5,
                   handletextpad=0.3, numpoints=1, handlelength=(4. / 3.))
        # plotName = r"PG {0}${1}${2}".format(targname[2:6], targname[6], targname[7:])
        # ax1.text(0.05, 0.8, "{0}".format(plotName),
        #          verticalalignment='bottom', horizontalalignment='left',
        #          transform=ax1.transAxes, fontsize=24,
        #          bbox=dict(facecolor='white', alpha=0.5, edgecolor="none"))
        # ->Plot the lower panel
        xmin = np.min(sedwave) * 0.9
        xmax = np.max(sedwave) * 1.1
        ymin = np.min(sedflux) * 0.5
        ymax = np.max(sedflux) * 2.0
        xlim = [xmin, xmax]
        ylim = [ymin, ymax]
        em.plot_fit(truths=parTruth, FigAx=(fig, ax2), xlim=xlim, ylim=ylim, nSamples=100,
                    burnin=burnIn, fraction=fraction, ps=ps, showLegend=False)
        # plot uncertainty of spectrum
        # ax2.fill_between(spcwave, spcflux - spcsig, spcflux + spcsig, facecolors='grey', alpha=0.2)
        ax2.set_xlabel("")
        ax2.set_ylabel("")
        ax2.tick_params(axis="both", which="major", length=8, labelsize=18)
        ax2.tick_params(axis="both", which="minor", length=5)
        # -->Set the labels
        yTicksLabels = [ticksFinder(ymin, ymax)]  # [1e1, 1e2, 1e3] #
        ax2.set_yticks(yTicksLabels)
        ax2.set_yticklabels(yTicksLabels)
        ax2.yaxis.set_major_formatter(FuncFormatter(mjrFormatter))
        plt.tight_layout(pad=1.8)
        # ->Setup the shared axis label.
        ax.set_xlabel(r"Rest Wavelength ($\mu$m)", fontsize=24)
        ax.set_ylabel(r"$f_\nu \mathrm{(mJy)}$", fontsize=24)
        ax.xaxis.set_label_coords(0.5, -0.05)
        ax.yaxis.set_label_coords(-0.06, 0.5)
        ax.spines['top'].set_visible(False)
        ax.spines['bottom'].set_visible(False)
        ax.spines['left'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.tick_params(axis='both',  # changes apply to the x-axis
                       which='both',  # both major and minor ticks are affected
                       bottom='off',  # ticks along the bottom edge are off
                       top='off',  # ticks along the top edge are off
                       labelbottom='off',  # labels along the bottom edge are off)
                       labelleft="off")
    else:
        fig = plt.figure(figsize=(7, 7))
        ax = plt.gca()
        xmin = np.min(sedwave) * 0.9
        xmax = np.max(sedwave) * 1.1
        ymin = np.min(sedflux) * 0.001
        ymax = np.max(sedflux) * 2.0
        xlim = [xmin, xmax]
        ylim = [ymin, ymax]
        em.plot_fit(truths=parTruth, FigAx=(fig, ax), xlim=xlim, ylim=ylim, nSamples=100,
                    burnin=burnIn, fraction=fraction, ps=ps)
        ax.text(0.05, 0.9, targname,
                verticalalignment='bottom', horizontalalignment='left',
                transform=ax.transAxes, fontsize=24,
                bbox=dict(facecolor='white', alpha=0.5, edgecolor="none"))
        # plotName = r"PG {0}${1}${2}".format(targname[2:6], targname[6], targname[7:])
        # ax.text(0.58, 0.88, "{0}".format(plotName),
        #         verticalalignment='bottom', horizontalalignment='left',
        #         transform=ax.transAxes, fontsize=24,
        #         bbox=dict(facecolor='white', alpha=0.5, edgecolor="none"))

        # -->Set the legend
        phtName = dataDict["phtName"]
        spcName = dataDict["spcName"]
        handles, labels = ax.get_legend_handles_labels()
        handleUse = []
        labelUse = []
        for loop in range(len(labels)):
            lb = labels[loop]
            hd = handles[loop]
            if lb == "Hot_Dust":
                lb = "BB"
            if lb == "CLUMPY":
                lb = "CLU"
            if lb == "Cat3d":
                lb = "Cat3d"
            if lb == phtName:
                hd = hd[0]
            labelUse.append(lb)
            handleUse.append(hd)
        plt.legend(handleUse, labelUse, loc="lower left", fontsize=18, numpoints=1,
                   handletextpad=0.3, handlelength=(4. / 3.))
    plt.savefig("result/{0}_result.pdf".format(targname), bbox_inches="tight")
    plt.close()
    #->Plot the posterior probability distribution
    em.plot_corner(filename="result/{0}_triangle.png".format(targname), burnin=burnIn,
                   nuisance=nuisance, truths=parTruth, fraction=fraction,
                   quantiles=[psLow/100., psCenter/100., psHigh/100.], show_titles=True,
                   title_kwargs={"fontsize": 20})
    print("Post-processed!")
예제 #5
0
    return sedData

if __name__ == "__main__":
    import cPickle as pickle
    from sedfit import sedclass as sedsc
    from sedfit.fitter import basicclass as bc
    from sedfit import model_functions as sedmf

    fitrsPath = "./"
    f = open(fitrsPath+"SDSSJ0041-0952.fitrs", "r")
    fitrs = pickle.load(f)
    f.close()

    dataPck = fitrs["dataPck"]
    targname = dataPck["targname"]
    redshift = dataPck["redshift"]
    distance = dataPck["distance"]
    dataDict = dataPck["dataDict"]
    sedPck   = dataPck["sedPck"]
    sedData = sedsc.setSedData(targname, redshift, distance, dataDict, sedPck, True)

    #->Setup the model
    modelPck = fitrs["modelPck"]
    funcLib = sedmf.funcLib
    modelDict = modelPck["modelDict"]
    waveModel = modelPck["waveModel"]
    parAddDict_all = modelPck["parAddDict_all"]
    sedModel = bc.Model_Generator(modelDict, funcLib, waveModel, parAddDict_all)
    pars = sedModel.get_parList()
    print Flux_Pht_Component(pars, "BC03", sedModel, sedData)
예제 #6
0
    ],
    #    "bandList_ignore":[ ],
    "frame":
    "obs",
    #'FUV', 'NUV', 'U', 'B', 'V', 'R', 'I', 'JCMT_SCUBA1_450'
}

for filename in glob.glob("configs/*.py"):
    config = configImporter(filename)
    filename = filename.lstrip("configs/").rstrip(".py")
    f = open("result/" + filename + "_bestfit.txt", "a+")
    # f = open(filename + "_bestfit.txt", "a+")
    print(filename)
    sedFile = config.sedFile
    sedPck = sedt.Load_SED(sedFile)
    sedData1 = sedsc.setSedData(config.targname, config.redshift,
                                config.distance, dataDict, sedPck, False)
    sedData2 = sedsc.setSedData(config.targname, config.redshift,
                                config.distance, config.dataDict, sedPck,
                                False)
    modelDict = config.modelDict
    funcLib = sedmf.funcLib
    waveModel = config.waveModel
    parAddDict_all = {}
    parAddDict_all["DL"] = config.distance
    parAddDict_all["z"] = config.redshift
    parAddDict_all["frame"] = "rest"
    frequency = 1 / waveModel
    lib = model_functions.funcLib

    sedModel = bc.Model_Generator(modelDict, funcLib, waveModel,
                                  parAddDict_all)