Exemple #1
0
def fit_polarized_flux_modified_plaw_combined(restnu, polarnu, polarflux, spflux, fitwindow, normflux, plotout, qmjd, nuorig, p, sp, plaw_params, polspec):
########### Fit the polarized flux with a modified power-law###################
##########  F = (A * nu + B) * Norm * nu^(-alpha)##############################
########## Start with fitting the polarization with P = (A nu + B)##############
    linepol_params = Parameters()
    linepol_params.add('slope', value = 1.0/gom(np.median(restnu)))
    linepol_params.add('intercept', value = 1.0)
    linepol_output = minimize(find_line_resid, linepol_params, 
    args=(polarnu, p, sp))
    linepol_model = find_line(linepol_params, polarnu)
    ### Use the Slope and Intercept as fixed paramters for the modified power-law
    modified_plaw_params = Parameters()
    minslope = linepol_params['slope'].value - 3*linepol_params['slope'].stderr
    maxslope = linepol_params['slope'].value + 3*linepol_params['slope'].stderr
    minint = linepol_params['intercept'].value - 3*linepol_params['intercept'].stderr
    maxint = linepol_params['intercept'].value + 3*linepol_params['intercept'].stderr
    modified_plaw_params.add('slope', value = linepol_params['slope'].value, 
    min=minslope, max=maxslope)
    modified_plaw_params.add('intercept', value= 
    linepol_params['intercept'].value, min=minint, max=maxint)
    modified_plaw_params.add('normal', value = plaw_params['norm'].value, 
    min=np.float64(0.0))
    modified_plaw_params.add('alpha', value =  plaw_params['alpha'].value)
    modified_plaw_output = minimize(find_modified_plaw_resid, 
    modified_plaw_params, args=(polarnu[fitwindow], polarflux[fitwindow]/normflux, 
    spflux[fitwindow]/polarflux[fitwindow]), method = 'nelder')
    modified_plaw_output = minimize(find_modified_plaw_resid, 
    modified_plaw_params, args=(polarnu[fitwindow], polarflux[fitwindow]/normflux, 
    spflux[fitwindow]/polarflux[fitwindow]))    
    modified_plaw_model = find_modified_plaw(modified_plaw_params, polarnu)*normflux
    name='modified_plaw'
    plot_polarized_flux_fit_combined(polarflux, spflux, polarnu, qmjd, plotout, restnu, 
    nuorig, modified_plaw_model, name, polspec)
    return linepol_params, linepol_output, linepol_model, modified_plaw_params, modified_plaw_model
def plot_spectrum(fframe, pframe, framnum):
    import numpy as np
    import scipy as sp
    import matplotlib
    import matplotlib.pyplot as plt
    from bin_array import bin_array as ba
    from get_order_of_magnitude import get_order_of_magnitude as gom
    fig = plt.figure(2, figsize=(10, 7))
    #ax1 = plt.subplot(211)
    ynorm = gom(fframe[fframe.columns[3]])
    plt.ylabel(
        r'$F_\lambda \; (10^{' + str(np.trunc(np.log10(ynorm)).astype(int)) +
        r'} \; \mathrm{erg \; s}^{-1}\;\mathrm{cm}^{-2}\mathrm{\AA}^{-1}$)')
    plt.xlabel(r'$\lambda \;(\mathrm{\AA})$')
    plt.plot(fframe['wl'], fframe[fframe.columns[framnum]] / ynorm)
    # Label some of the emission lines on the plot to motivate their removal
    plt.arrow(4860,
              0.3,
              0,
              -0.05,
              color='blue',
              head_width=75,
              head_length=0.05)
    plt.arrow(4350,
              0.3,
              0,
              -0.05,
              color='blue',
              head_width=75,
              head_length=0.05)
    plt.arrow(4100,
              0.3,
              0,
              -0.05,
              color='blue',
              head_width=75,
              head_length=0.05)
    plt.text(4350, 0.31, 'Hydrogen', color='blue', fontsize=15)
    plt.arrow(3300,
              0.05,
              0,
              0.15,
              color='red',
              head_width=75,
              head_length=0.05)
    plt.arrow(3800, 0.05, 0, 0.1, color='red', head_width=75, head_length=0.05)
    plt.text(3500, 0.03, 'Ionized Iron', color='red', fontsize=15)
    plt.arrow(3500,
              0.5,
              -500,
              0,
              color='green',
              head_length=100,
              head_width=0.01)
    plt.text(3700, 0.5, 'Mg II', color='green', fontsize=15)
def plot_models_mc(mjdarr, bbb_integratedflux, sigbump,
                   synchrotron_integratedflux, sigsyn, total_integratedflux,
                   sigflux, plotout, name):
    plt.cla()
    #convert the MJD to the year in order to obtain a second axis scale
    yeararr = mjdarr - 51544.0
    yeararr = yeararr / 365.25
    yeararr = yeararr + 2000.0

    def tick_function(X):
        V = 2000.00 + (X - 51544.00) / 365.25
        return ["%.2f" % z for z in V]

    normalize = gom(np.median(total_integratedflux))
    fig = plt.figure(15, figsize=(10, 7))
    ax1 = fig.add_subplot(111)
    ax2 = ax1.twiny()
    line2, = ax1.plot(mjdarr,
                      bbb_integratedflux / normalize,
                      color=(0, 0, 1),
                      marker='s',
                      ms=6,
                      label='Big Blue Bump Flux',
                      ls='')
    ax1.errorbar(mjdarr,
                 bbb_integratedflux / normalize,
                 yerr=sigbump / normalize,
                 color=(0, 0, 1),
                 marker='s',
                 ms=6,
                 ls='')
    line3, = ax1.plot(mjdarr,
                      synchrotron_integratedflux / normalize,
                      color=(1, 0, 0),
                      marker='o',
                      label='Synchrotron Flux',
                      ms=6,
                      ls='')
    ax1.errorbar(mjdarr,
                 synchrotron_integratedflux / normalize,
                 yerr=sigsyn / normalize,
                 color=(1, 0, 0),
                 marker='o',
                 ms=6,
                 ls='')
    line1, = ax1.plot(mjdarr,
                      total_integratedflux / normalize,
                      color=(1, 0, 1),
                      marker='^',
                      ms=6,
                      label='Total Flux',
                      ls='')
    ax1.errorbar(mjdarr,
                 total_integratedflux / normalize,
                 yerr=sigflux / normalize,
                 color=(1, 0, 1),
                 marker='^',
                 ms=6,
                 ls='')
    ax1.set_xlabel('MJD', fontsize=18)
    ax1.set_ylim([
        0.0,
        np.amax(total_integratedflux / normalize) +
        np.std(total_integratedflux / normalize)
    ])
    #ax1.legend(handler_map={type(line1): HandlerLine2D(numpoints=1)},loc='upper left')
    ax2.set_xlabel(r'$Year$', fontsize=18)
    tickarr = ax1.get_xticks()
    xtickarr = ax1.get_xticks().tolist()
    xticks = xtickarr
    xticks[0] = ' '
    ax1.set_xticklabels(xticks)
    ax2xticks = tick_function(tickarr)
    ax2xticks[0] = ' '
    ax2.set_xticklabels(ax2xticks)
    ax1.set_ylabel(r'$F \; (10^{' +
                   str(np.fix(np.log10(normalize)).astype(int)) +
                   '} \mathrm{erg \; s}^{-1} \mathrm{cm}^{-2})$',
                   fontsize=18)
    #plt.show()
    plt.savefig(plotout + name + '.png')
    plt.clf()
    plt.close()
    chiratio2 = chisquareplaw/chisquarequad
    dof1 = len(model) - 2
    dof2 = len(model) - 3
    dof3 = len(model) - 4
    red_chisquareplaw = chisquareplaw/dof1
    red_chisquarelinear = chisquarelinear/dof2
    red_chisquarequad = chisquarequad/dof3
    sf_polarized_flux = stats.f.sf(chiratio1, dof1, dof2)
    sf_polarized_flux2 = stats.f.sf(chiratio2, dof1, dof3)
    polarized_flux_sf = np.append(polarized_flux_sf, sf_polarized_flux)
    polarized_flux_sf2 = np.append(polarized_flux_sf2, sf_polarized_flux2)
    plawchi = np.append(plawchi, red_chisquareplaw)
    linearchi = np.append(linearchi, red_chisquarelinear)
    quadchi = np.append(quadchi, red_chisquarequad)
################################################################################
    normalflux = gom(fitflux)
    twocomp_params = Parameters()  
####################Perform the fit for the two component model#################
    modelflux, modelsyn, synmodel, mymodel, bumpmodel, model_chisq,  model_reduced_chi, twocomp_params, model_for_spectrum, mydatamodel, df1, modelbump =fit_flux_two_comp_model(restnu, polarnu, polarflux, spflux, fitwindow, normflux, plotout, qmjd, oldq, oldu, nuorig, fitflux, plaw_params, normalflux, normnu, sfitflux)
    mybbbindex = np.append(mybbbindex, twocomp_params['bumpindex'].value) 
    bbb_integratedflux= np.append(bbb_integratedflux, modelbump)
    synchrotron_integratedflux=np.append(synchrotron_integratedflux, modelsyn)
    total_integratedflux = np.append(total_integratedflux, modelflux)
    #create the parameters for the two component model
 ###############################################################################


####################Perform the fit for the model###############################
#############with the cutoff exponential synchrotron############################
    modelflux_ec, modelsyn_ec, synmodel_ec, mymodel_ec, bumpmodel_ec, model_chisq_ec,  model_reduced_chi_ec, twocomp_params_ec, model_for_spectrum_ec, mydatamodel_ec, df1, modelbump_ec =fit_flux_two_comp_model_expon_cutoff(restnu, polarnu, polarflux, spflux, fitwindow, normflux, plotout, qmjd, oldq, oldu, nuorig, fitflux, plaw_params_expon, normalflux, normnu, sfitflux)
    mybbbindex_ec = np.append(mybbbindex, twocomp_params_ec['bumpindex'].value) 
    initialnormal = np.float64(np.median(polarflux)*np.median(polarnu))/normflux
    plaw_params.add('norm', value=initialnormal, min=np.float64(0.0))
    plaw_params.add('alpha', value=np.float64(1.5))
    output = minimize(find_plaw_resid, plaw_params, args=(polarnu, polarflux/normflux, 4.0*spflux/normflux))
    model = find_plaw(plaw_params, polarnu)*normflux
    lmfit.printfuncs.report_fit(output.params)
    name='justplaw'
    plot_polarized_flux_fit(polarflux, spflux, polarnu, qmjd, plotout, restnu, oldq, oldu, nuorig, model, name)
    ci = lmfit.conf_interval(output, maxiter=1000)
#################################################################################    

########### Fit the polarized flux with a modified power-law###################
##########  F = (A * nu + B) * Norm * nu^(-alpha)##############################
########## Start with fitting the polarization with P = (A nu + B)##############
    linepol_params = Parameters()
    linepol_params.add('slope', value = 1/gom(np.median(restnu)))
    linepol_params.add('intercept', value = 1.0)
    linepol_output = minimize(find_line_resid, linepol_params, args=(polarnu, p, sp))
    linepol_model = find_line(linepol_params, polarnu)
    ### Use the Slope and Intercept as fixed paramters for the modified power-law
    modified_plaw_params = Parameters()
    minslope = linepol_params['slope'].value - 2*linepol_params['slope'].stderr
    maxslope = linepol_params['slope'].value + 2*linepol_params['slope'].stderr
    minint = linepol_params['intercept'].value - 2*linepol_params['intercept'].stderr
    maxint = linepol_params['intercept'].value + 2*linepol_params['intercept'].stderr
    modified_plaw_params.add('slope', value = linepol_params['slope'].value, min=minslope, max=maxslope)
    modified_plaw_params.add('intercept', value= linepol_params['intercept'].value, min=minint, max=maxint)
    modified_plaw_params.add('normal', value = plaw_params['norm'].value, min=np.float64(0.0))
    modified_plaw_params.add('alpha', value =  plaw_params['alpha'].value)
    modified_plaw_output = minimize(find_modified_plaw_resid, modified_plaw_params, args=(polarnu, polarflux/normflux, 4.0*spflux/polarflux))
    modified_plaw_model = find_modified_plaw(modified_plaw_params, polarnu)*normflux
def plot_polarized_flux_fit_combined(polarflux, spolarflux, polarnu, mjd,
                                     plotout, restnu, nuspec, model, name,
                                     polspec):
    fig = plt.figure(8, figsize=(10, 7))
    gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1])
    ax1 = plt.subplot(gs[0])
    nunorm, fluxnorm, modelnorm = gom(polarnu), gom(polarflux), gom(model)
    ax1.errorbar(polarnu / nunorm,
                 polarflux / fluxnorm,
                 yerr=4.0 * spolarflux / fluxnorm,
                 fmt='o',
                 color=(0, 1, 1))
    ax1.plot(restnu / nunorm, polspec / fluxnorm)
    ax1.errorbar(polarnu / nunorm,
                 polarflux / fluxnorm,
                 yerr=4.0 * spolarflux / fluxnorm,
                 fmt='o',
                 color=(0, 1, 1))
    ax1.plot(polarnu / nunorm,
             model / fluxnorm,
             ls='--',
             color=(0, 0, 0),
             lw=3)
    ytick = ax1.get_yticks().tolist()
    xtick = ax1.get_xticks().tolist()
    for i in range(0, len(xtick)):
        xtick[i] = str(xtick[i]) + r'$\times \; \mathrm{10}^{' + str(
            np.log10(gom(nunorm)).astype(int)) + '}$'
    ytick[0] = ' '
    ax2 = plt.subplot(gs[1])
    ax1.set_yticklabels(ytick)
    ax1.set_xticklabels(xtick)
    ax2.set_xlabel(r'$\nu \; \mathrm{(Hz)}$').set_fontsize(15)
    ax1.set_ylabel(
        r'$F_{\mathrm{p,\nu\;}} (10^{' +
        str(np.trunc(np.log10(fluxnorm)).astype(int)) +
        r'}\mathrm{erg\;s}^{-1} \mathrm{\;cm}^{-2} \mathrm{\;Hz}^{-1}\;)$'
    ).set_fontsize(15)
    ax1.set_title("MJD = " + str(format(mjd, '.2f'))).set_fontsize(18)
    ax2.errorbar(polarnu / nunorm, (polarflux - model) / (model),
                 yerr=4.0 * spolarflux / model,
                 fmt='o',
                 color=(0, 1, 1))
    ax2.plot(polarnu / nunorm, polarflux * 0, ls='--', lw=3, color=(0, 0, 0))
    ax2.set_ylabel(r'$\frac{\mathrm{Residual}}{\mathrm{Model}}$').set_fontsize(
        15)
    xtick = ax2.get_xticks().tolist()
    for i in range(0, len(xtick)):
        xtick[i] = str(xtick[i]) + r'$\times \; \mathrm{10}^{' + str(
            np.log10(gom(nunorm)).astype(int)) + '}$'
    ax2.set_xticklabels(xtick)
    plt.savefig(plotout + str(mjd) + name + '_fit2polflux.png')
    #make a histogram of the residuals
    plt.clf()
    plt.figure(10, figsize=(10, 7))
    #print (polarflux-polarmodel)/(polarmodel)
    plt.hist((polarflux - model) / model, 7, facecolor='g')
    plt.ylabel('Frequency')
    plt.xlabel(r'$\frac{\mathrm{Residual}}{\mathrm{Model}}$').set_fontsize(15)
    plt.savefig(plotout + str(mjd) + name + '_fit2polflux_resid_hist.png')
    plt.close()
def fit_flux_two_comp_wbb_mc(restnu, polarnu, polarflux, spflux, fitwindow,
                             normflux, plotout, qmjd, oldq, oldu, nuorig,
                             fitflux, plaw_params, normalflux, normnu,
                             sfitflux, twocomp_params, nuspec, name,
                             just1plaw_model):
    fitspectrum = fitflux * 0.0
    synarr = np.array([])
    bumparr = np.array([])
    alpharr = np.array([])
    modelfluxarr = np.array([])
    modelsynarr = np.array([])
    modelbumparr = np.array([])
    modelbbodyarr = np.array([])
    maxiter = 250
    fitflux = fitflux  #-polarflux
    for myi in range(0, maxiter):
        randomarray = np.random.randn(len(fitflux))
        #print randomarray[2]
        fitspectrum[0:] = fitflux[0:] + (randomarray[0:] * sfitflux[0:])
        if myi == (maxiter - 1):
            fitspectrum = fitflux
        #plt.plot(polarnu, fitspectrum)
        #amin = plaw_params['alpha'].value-(1.0*plaw_params['alpha'].stderr)
        #plaw_params['alpha'].value =  plaw_params['alpha'].value -0.05
        amin = plaw_params['alpha'].value - (0.1)
        amin = plaw_params['alpha'].value - (1.0)
        #amax = plaw_params['alpha'].value+ (1.0*plaw_params['alpha'].stderr)
        amax = plaw_params['alpha'].value + (0.1)
        amax = plaw_params['alpha'].value + (1.0)
        minsyn = plaw_params['norm'].value * normalflux
        abegin = (np.mean(fitflux / normalflux) / 2) * np.mean(
            polarnu / normnu)**((-1.0) * plaw_params['alpha'].value)
        abegin = (np.mean(fitflux / normalflux) / 2.0) * np.mean(
            polarnu / normnu)**((-1.0) * plaw_params['alpha'].value)
        twocomp_BB_params = Parameters()
        twocomp_BB_params.add('synnormal', value=abegin, min=minsyn)
        #twocomp_BB_params.add('synalpha', value = plaw_params['alpha'].value , min= amin, max = amax)
        twocomp_BB_params.add('synalpha',
                              value=plaw_params['alpha'].value,
                              vary=False)
        twocomp_BB_params.add('bumpindex',
                              value=np.float64(-1.0 / 3.0),
                              vary=False)
        # twocomp_BB_params.add('bumpindex', value = np.float64(-0.46), vary=False)
        twocomp_BB_params.add('temperature',
                              value=np.float64(12000.0),
                              min=5000.,
                              max=60000)
        #twocomp_BB_params.add('temperature', value=np.float64(20000.0), min = 5000, max = 50000)
        twocomp_BB_params.add('blackbody_norm',
                              value=0.2,
                              min=np.float64(0.0),
                              max=100)
        #twocomp_BB_params.add('blackbody_norm', value = 20.0, vary=False)
        blackbody = bb(polarnu, twocomp_BB_params['temperature'].value)
        blackbodymodel = bb(restnu, twocomp_BB_params['temperature'].value)
        blackbodymodel = blackbodymodel / np.max(blackbodymodel)
        blackbody = blackbody / np.max(blackbody)
        #bbegin = (np.mean(fitflux/normalflux)/3.)*np.mean(polarnu/normnu)**(-1./3.)
        bbegin = 0.145  #1222+216
        #bbegin = 0.03 #CTA26
        #bbegin = 0.1 #BLLAC
        bbegin = 0.0  #3C66A and other BL Lacs
        #bbegin = .06 #3C273
        #bbegin = 0.04 #CTA102
        #bbegin = 0.005 # 3C454.3
        minbumpflux = np.float64(1.84644587168e-12)
        integrated = np.max(restnu)**(
            (-1) * twocomp_params['bumpindex'].value + 1.0) - np.min(restnu)**(
                (-1) * twocomp_params['bumpindex'].value + 1.0)
        minbumpnorm = minbumpflux * (
            (-1) * twocomp_params['bumpindex'].value + 1.0) * np.power(
                normnu, (-1) * twocomp_params['bumpindex'].value) / integrated
        minbumpnorm = minbumpnorm / normalflux
        aaa = 2.808E-17 / (np.power(normnu, (0.77)) * normflux)
        aaa = 8 * 1.80505565259e-23 / (normalflux *
                                       np.power(normnu, (1. / 3.)))
        minbumpnorm = aaa / 2.0
        #print 'aaa', aaa
        #if np.absolute(qmjd - 56714.0) < 1.0:
        #  aaa= 2.808E-17/(np.power(normnu, (0.77))*normflux)
        #aaa = 0.46601200360
        #aaa = 8*1.80505565259e-23/(normalflux*np.power(normnu, (1./3.)))

        #   print 'aaa', aaa
        #twocomp_BB_params.add('bumpnormal', value=aaa, vary=False)
        #twocomp_BB_params.add('bumpnormal', value = aaa, min=minbumpnorm/5.0)
        #twocomp_BB_params.add('bumpnormal', value = aaa, min=0.0)
        twocomp_BB_params.add('bumpnormal', value=bbegin, vary=False)
        #twocomp_BB_params.add('bumpnormal', value = bbegin, min=0.0, vary = True)
        #else:
        # twocomp_BB_params.add('bumpnormal', value = aaa, min=minbumpnorm/5.0)
        #   twocomp_BB_params.add('bumpnormal', value = aaa, min=0.0)
        #twocomp_BB_params.add('bumpnormal', value=aaa, vary=False)
        #Now solve with Levenberg-Marquadt
        #print twocomp_BB_params , 'now with blackbody'
        #print normalflux
        #print twocomp_BB_params['temperature'].value, 'temperature'
        #model_for_spectrum_bb = lmfit.minimize(twocomponentmodel_BB_resid,
        #twocomp_BB_params, args=((polarnu[fitwindow]/normnu), normnu, (fitflux[fitwindow]/gom(nuspec)),
        #sfitflux[fitwindow]/gom(nuspec) ), method='Nelder')
        bumpmodelpolnu = get_bigbluebump(twocomp_BB_params,
                                         polarnu / normnu) * normalflux
        model_for_spectrum_bb = minimize(
            twocomponentmodel_BB_resid,
            twocomp_BB_params,
            args=(polarnu[fitwindow] / normnu, normnu,
                  (fitspectrum[fitwindow] / normalflux),
                  sfitflux[fitwindow] / gom(nuspec)))
        #model_for_spectrum_bb = curve_fit(twocomponentmodel_BB, polarnu[fitwindow]/normnu, normnu, (fitflux[fitwindow]/gom(nuspec)), p0=model_for_spectrum_bb, sigma =  sfitflux[fitwindow]/gom(nuspec))
        #get initial values for parameters with  Nelder-Mead
        #print fitflux/normalflux
        #print blackbody
        #get the blackbody flux
        blackbodymodel = bb(
            restnu, twocomp_BB_params['temperature'].value
        ) * twocomp_BB_params['blackbody_norm'].value * normalflux
        bbmodelpolnu = bb(
            polarnu, twocomp_BB_params['temperature'].value
        ) * twocomp_BB_params['blackbody_norm'].value * normalflux
        # blackbodymodel =  bb(restnu, twocomp_BB_params['temperature'].value)* twocomp_BB_params['blackbody_norm'].value*1.0e-26
        # bbmodelpolnu =  bb(polarnu, twocomp_BB_params['temperature'].value)* twocomp_BB_params['blackbody_norm'].value*1.0e-26
        #plt.plot(restnu, blackbodymodel)
        #plt.show()
        bumpmodelwbb = get_bigbluebump(twocomp_BB_params,
                                       restnu / normnu) * normalflux
        bumpmodelpolnu = get_bigbluebump(twocomp_BB_params,
                                         polarnu / normnu) * normalflux
        synmodelwbb = get_synchrotron(
            twocomp_BB_params,
            restnu / normnu) * normalflux  #+rebin(polarflux, restnu.shape)
        synmodelpolnu = get_synchrotron(
            twocomp_BB_params, polarnu / normnu) * normalflux  #+ polarflux
        modelwbb = (blackbodymodel + synmodelwbb + bumpmodelwbb
                    ) / normalflux  #+rebin(polarflux, restnu.shape)
        modelfluxarr = np.append(
            modelfluxarr,
            np.trapz(bumpmodelwbb + synmodelwbb + blackbodymodel, restnu) *
            (-1))  #+ np.trapz(polarflux, polarnu)*(-1.0))
        modelsynarr = np.append(
            modelsynarr,
            np.trapz(synmodelwbb, restnu) *
            (-1.0))  #+ np.trapz(polarflux, polarnu)*(-1.0))
        modelbumparr = np.append(modelbumparr,
                                 np.trapz(bumpmodelwbb, restnu) * (-1))
        #print synfluxmodel, 'synfluxmodel'
        modelbbodyarr = np.append(modelbbodyarr,
                                  np.trapz(blackbodymodel, restnu) * (-1))
        #print modelwbb
        modelwbbscale = bb(restnu, twocomp_BB_params['temperature'].value)
        modelwbbscale = modelwbbscale / normalflux
        mymodel = (synmodelpolnu + bumpmodelpolnu + bbmodelpolnu)
        mymodel = mymodel / normalflux
        mmodel = synmodelpolnu + bumpmodelpolnu + bbmodelpolnu
    fig = plt.figure(33, figsize=(10, 7))
    gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1])
    ax1 = plt.subplot(gs[0])
    #print len(just1plaw_model), 'len just1plaw_model'
    #print len(restnu), 'len restnu'
    fitflux = fitflux  #+polarflux
    ax1.set_title("MJD = " + str(format(qmjd, '.2f'))).set_fontsize(18)
    ax1.plot(restnu / normnu, nuspec / normalflux, color=(0, 0, 1))
    ax1.plot(restnu / normnu,
             synmodelwbb / normalflux,
             ls=':',
             color=(1, 0, 0),
             lw=3)
    ax1.plot(restnu / normnu,
             bumpmodelwbb / normalflux,
             ls='--',
             color=(0, 0, 1),
             lw=3)
    ax1.plot(restnu / normnu,
             blackbodymodel / normalflux,
             ls='-.',
             color=(0, 0, 0),
             lw=3)
    ax1.plot(polarnu / normnu,
             just1plaw_model / normalflux,
             color=(1, 0, 1),
             lw=4)
    ax1.plot(polarnu / normnu,
             fitflux / normalflux,
             marker='o',
             ls='',
             color=(1, 0, 0))
    ax1.plot(polarnu[fitwindow] / normnu,
             fitflux[fitwindow] / normalflux,
             marker='s',
             color=(0, 1, 1),
             ms=12,
             ls='')
    ax1.errorbar(polarnu / normnu,
                 fitflux / normalflux,
                 yerr=sfitflux / normalflux,
                 color=(1, 0, 0),
                 marker='o',
                 ls='')
    xtick = ax1.get_xticks().tolist()
    for i in range(0, len(xtick)):
        xtick[i] = str(xtick[i]) + r'$\times \; \mathrm{10}^{' + str(
            np.log10(gom(normnu)).astype(int)) + '}$'
    ax1.set_xticklabels(xtick)
    #ax1.set_xlabel(r'$\nu\; $(10$^{14} \;$Hz)').set_fontsize(15)
    ax1.set_ylabel(
        r'$F_{\mathrm{\nu\;}} (10^{' +
        str(np.trunc(np.log10(normalflux)).astype(int)) +
        r'}\mathrm{erg} \; \mathrm{s}^{-1} \; \mathrm{cm}^{-2} \mathrm{\;Hz}^{-1}\;)$'
    ).set_fontsize(15)
    ax1.plot(restnu / normnu, modelwbb, ls='--', color=(0.5, 0, 0.5), lw=4)
    ax2 = plt.subplot(gs[1])
    resid = ((nuspec / normalflux) - modelwbb) / modelwbb
    resid2 = (fitflux - mymodel) / mymodel
    ax2.plot(restnu / normnu, resid)
    #print mymodel

    ax2.plot(polarnu / normnu, (fitflux - mmodel) / mmodel,
             marker='o',
             color=(1, 0, 0),
             ls='')
    ax2.plot(polarnu[fitwindow] / normnu,
             (fitflux[fitwindow] - mmodel[fitwindow]) / mmodel[fitwindow],
             marker='s',
             color=(0, 1, 1),
             ls='',
             ms=12)
    ax2.errorbar(polarnu[fitwindow] / normnu,
                 (fitflux[fitwindow] - mmodel[fitwindow]) / mmodel[fitwindow],
                 yerr=sfitflux[fitwindow] / mmodel[fitwindow],
                 color=(1, 0, 0),
                 ls='',
                 marker='o')
    ax2.plot(restnu / normnu, restnu * 0, color=(0, 0, 0), lw=3, ls='--')
    xtick = ax2.get_xticks().tolist()
    for i in range(0, len(xtick)):
        xtick[i] = str(xtick[i]) + r'$\times \; \mathrm{10}^{' + str(
            np.log10(gom(normnu)).astype(int)) + '}$'
    ax2.set_xticklabels(xtick)
    ax2.set_ylabel(r'$ \frac{\mathrm{Residual}}{\mathrm{Model}} $')
    ax2.set_xlabel(r'$\nu \; \mathrm{(Hz)}$').set_fontsize(15)
    #plt.plot(restnu, modelwbbscale)
    #print plotout, 'plotout'
    plt.savefig(plotout + name + 'two_comp_with_BB.png', padinches=2)
    plt.clf()
    plt.close()
    #plt.plot(restnu, modelwbbscale)
    #plt.show()
    #print synmodelwbb, 'synmodelwbb'

    #Get the chi square for this particular model
    scfitflux = fitflux / normalflux
    scsfitflux = sfitflux / normalflux
    #print mmodel
    mychisquarewbb = chi_square(mmodel[fitwindow], fitflux[fitwindow],
                                sfitflux[fitwindow])
    print 'mychisquarewbb', mychisquarewbb, 'mychisquarewbb'
    #print ( (modelwbb[fitwindow]-scfitflux[fitwindow])**2)
    #print np.shape(fitwindow), 'shape of window'
    dof = len(fitwindow[0]) - 4.0
    print 'dof', dof
    #print "len(fitwindow) - 4", len(fitwindow) - 4.0
    #print 'modelwbb[fitwindow], fitflux[fitwindow], sfitflux[fitwindow]', modelwbb[fitwindow], fitflux[fitwindow]/gom(nuspec), sfitflux[fitwindow]/gom(nuspec)
    mychisquarewbb = mychisquarewbb / dof
    print 'mychisquarewbb', mychisquarewbb
    bbbumpfluxmodel, blackbodyfluxmodel, synfluxmodel = modelbumparr[
        maxiter - 1], modelbbodyarr[maxiter - 1], modelsynarr[maxiter - 1]
    sigbbbumpfluxmodel, sigblackbodyfluxmodel, sigsynfluxmodel, sigfluxmodel = np.std(
        modelbumparr) * 1.0, np.std(modelbbodyarr) * 1.0, np.std(
            modelsynarr) * 1.0, np.std(modelfluxarr) * 1.0
    return blackbodyfluxmodel, twocomp_BB_params, synmodelwbb, bumpmodelwbb, blackbodymodel, synfluxmodel, bbbumpfluxmodel, mychisquarewbb, mmodel, sigbbbumpfluxmodel, sigblackbodyfluxmodel, sigsynfluxmodel, sigfluxmodel
Exemple #8
0
def plot_modelswbb_mc(mjdarr,
                      bbb_integratedflux,
                      sigbump,
                      synchrotron_integratedflux,
                      sigsyn,
                      bb_flux,
                      sig_bbflux,
                      total_integratedflux,
                      sigflux,
                      plotout='/home/mmalmrose/Desktop/',
                      name='test'):
    plt.cla()
    #print bb_flux, sig_bbflux
    #convert the MJD to the year in order to obtain a second axis scale
    yeararr = mjdarr - 51544.00
    yeararr = yeararr / 365.25
    yeararr = yeararr + 2000.00

    print 'yeararr', yeararr

    def tick_function(X):
        V = 2000.00 + ((X - 51544.00) / 365.25)
        return ["%.1f" % z for z in V]

    normalize = gom(np.median(total_integratedflux))
    fig = plt.figure(25, figsize=(10, 7))
    ax1 = fig.add_subplot(111)
    ax2 = ax1.twiny()
    line2, = ax1.plot(mjdarr,
                      bbb_integratedflux / normalize,
                      color=(0, 0, 1),
                      marker='s',
                      ms=6,
                      label='Big Blue Bump Flux',
                      ls='')
    ax1.errorbar(mjdarr,
                 bbb_integratedflux / normalize,
                 yerr=sigbump / normalize,
                 color=(0, 0, 1),
                 marker='s',
                 ms=6,
                 ls='')
    line3, = ax1.plot(mjdarr,
                      synchrotron_integratedflux / normalize,
                      color=(1, 0, 0),
                      marker='o',
                      label='Synchrotron Flux',
                      ms=6,
                      ls='')
    ax1.errorbar(mjdarr,
                 synchrotron_integratedflux / normalize,
                 yerr=sigsyn / normalize,
                 color=(1, 0, 0),
                 marker='o',
                 ls='',
                 ms=6)
    line1, = ax1.plot(mjdarr,
                      total_integratedflux / normalize,
                      color=(1, 0, 1),
                      marker='^',
                      ms=6,
                      label='Total Flux',
                      ls='')
    ax1.errorbar(mjdarr,
                 total_integratedflux / normalize,
                 yerr=sigflux / normalize,
                 color=(1, 0, 1),
                 marker='^',
                 ms=6,
                 ls='')
    line4, = ax1.plot(mjdarr,
                      bb_flux / normalize,
                      color=(0, 0, 0),
                      marker='D',
                      ms=6,
                      label='Black Body Flux',
                      ls='')
    ax1.errorbar(mjdarr,
                 bb_flux / normalize,
                 yerr=sig_bbflux / normalize,
                 color=(0, 0, 0),
                 marker='D',
                 ms=6,
                 ls='')
    ax1.set_xlabel(r'MJD', fontsize=18)
    ax1.set_ylim([
        0.0,
        np.amax(total_integratedflux / normalize) +
        np.std(total_integratedflux / normalize)
    ])
    tickarr = ax1.get_xticks()
    ax2tickarr = tickarr
    xtickarr = ax1.get_xticks().tolist()
    xticks = xtickarr
    xticks[0] = ' '
    ax1.set_xticklabels(xticks)
    ax2.set_xlabel(r'Year', fontsize=18)
    #ax1.legend(handler_map={type(line2): HandlerLine2D(numpoints=1)},loc='upper left')
    tickyear = np.arange(2009, 2017)
    ax2.set_xticks(tickyear)
    #ax2_xticks[0]=' '
    ax2.set_xlim(2009, 2016)
    ax2.plot(yeararr, bbb_integratedflux / normalize, color=(1, 1, 1), ls='')
    xticks = ax2.get_xticks().tolist()
    xticks[0] = ' '
    ax2.set_xticklabels(xticks)
    #print 'tickarr', xticks, ax2_xticks
    print ax2.get_xticks(), 'top axis ticks'
    tickarr = ax1.get_xticks()
    ax1.set_ylabel(r'$F \; (10^{' +
                   str(np.fix(np.log10(normalize)).astype(int)) +
                   '} \mathrm{erg \; s}^{-1} \mathrm{cm}^{-2})$',
                   fontsize=18)
    myname = plotout + name + '.png'
    print 'myname', myname
    #plt.show()
    plt.savefig(myname)
    plt.clf()
    plt.close()
def plot_flux_onlyplaw(total_integratedflux, onlyplaw_alpha, mjdarr,
                       oldplotout, name):
    inverseflux = np.float64(1.0 / total_integratedflux)
    #get a linear fit to the inverse flux
    #group the arrays by mjd so that the plot can be color coded.
    bluegroup = np.where(mjdarr < 55450)
    redgroup = np.where(np.logical_and(mjdarr > 55450, mjdarr < 55800))
    greengroup = np.where(np.logical_and(mjdarr > 55800, mjdarr < 56200))
    brgroup = np.where(np.logical_and(mjdarr > 56200, mjdarr < 56500))
    rggroup = np.where(np.logical_and(mjdarr > 56500, mjdarr < 56717))
    blackgroup = np.where(mjdarr > 56717)
    normalinverse = gom(inverseflux)
    normalized = inverseflux / normalinverse
    linexarr = np.linspace(0.01, 7, num=400)
    linefit = np.polyfit(normalized, onlyplaw_alpha, 1)
    theline = linefit[0] * linexarr + linefit[1]
    # If the spectral index goes to -2, this would indicate a very hot
    #Blackbody.  Anything with a steeper spectral index will not be thermal
    #So figure out what the flux of a alpha=-2 power law is with this regression
    minbump = np.float64(linefit[0] / ((-2.0) - linefit[1]))
    minbump = (minbump / normalinverse)
    print linefit, 'linefit'
    fig = plt.figure(22, figsize=(10, 7))
    x = (1.0 / (inverseflux / normalinverse))
    line1, = plt.plot(x[bluegroup],
                      onlyplaw_alpha[bluegroup],
                      marker='o',
                      color=(0, 0, 1),
                      linestyle='',
                      label='MJD < 55450',
                      ms=10)
    line2, = plt.plot(x[redgroup],
                      onlyplaw_alpha[redgroup],
                      marker='<',
                      color=(1, 0, 0),
                      linestyle='',
                      label='55450 < MJD < 55800',
                      ms=10)
    line3, = plt.plot(x[greengroup],
                      onlyplaw_alpha[greengroup],
                      marker='>',
                      color=(0, 1, 0),
                      linestyle='',
                      label='55800 < MJD < 56200',
                      ms=10)
    line4, = plt.plot(x[brgroup],
                      onlyplaw_alpha[brgroup],
                      marker='H',
                      color=(1, 0, 1),
                      linestyle='',
                      label='56200 < MJD < 56500',
                      ms=10)
    line5, = plt.plot(x[rggroup],
                      onlyplaw_alpha[rggroup],
                      marker='D',
                      color=(1, 1, 0),
                      linestyle='',
                      label='56500< MJD < 56714')
    line6, = plt.plot(x[blackgroup],
                      onlyplaw_alpha[blackgroup],
                      marker='s',
                      color=(0, 0, 0),
                      linestyle='',
                      label='MJD > 56714',
                      ms=10)
    plt.plot(1.0 / linexarr, theline, color=(0, 0, 1), lw=4)
    plt.xlim([0.0, 3.0])
    plt.xlabel(r'$\mathrm{Flux} \; (10^{-' +
               str(np.trunc(np.log10(normalinverse)).astype(int)) +
               r'} \; \mathrm{erg} \; \mathrm{s}^{-1} \;\mathrm{cm}^{-2})$')
    plt.ylabel(r'$\alpha_{F_{\nu}}$')
    plt.ylim([-2.0, 1.0])
    #plt.legend(loc ='lower right')
    plt.legend(handler_map={type(line1): HandlerLine2D(numpoints=1)},
               loc='lower right')
    pp = oldplotout + name + '.png'
    plt.savefig(pp, padinches=0.85)
    plt.clf()
    plt.close()
    fig2 = plt.figure(23, figsize=(10, 7))
    x = (inverseflux / normalinverse)
    line1, = plt.plot(x[bluegroup],
                      onlyplaw_alpha[bluegroup],
                      marker='o',
                      color=(0, 0, 1),
                      linestyle='',
                      label='MJD < 55450',
                      ms=10)
    line2, = plt.plot(x[redgroup],
                      onlyplaw_alpha[redgroup],
                      marker='<',
                      color=(1, 0, 0),
                      linestyle='',
                      label='55450 < MJD < 55800',
                      ms=10)
    line3, = plt.plot(x[greengroup],
                      onlyplaw_alpha[greengroup],
                      marker='>',
                      color=(0, 1, 0),
                      linestyle='',
                      label='55800 < MJD < 56200',
                      ms=10)
    line4, = plt.plot(x[brgroup],
                      onlyplaw_alpha[brgroup],
                      marker='H',
                      color=(1, 0, 1),
                      linestyle='',
                      label='56200 < MJD < 56500',
                      ms=10)
    line5, = plt.plot(x[rggroup],
                      onlyplaw_alpha[rggroup],
                      marker='D',
                      color=(1, 1, 0),
                      linestyle='',
                      label='56500< MJD < 56714')
    line6, = plt.plot(x[blackgroup],
                      onlyplaw_alpha[blackgroup],
                      marker='s',
                      color=(0, 0, 0),
                      linestyle='',
                      label='MJD > 56714',
                      ms=10)
    plt.plot(linexarr, theline, color=(0, 0, 1), lw=4)
    plt.xlim([0.0, 5.0])
    plt.ylim([-2.0, 1.0])
    plt.xlabel(
        r'$\mathrm{Inverse\;Flux} \; (10^{-' +
        str(np.trunc(np.log10(normalinverse)).astype(int)) +
        r'} \; \mathrm{erg} \; \mathrm{s}^{-1} \;\mathrm{cm}^{-2})^{-1}$')
    plt.ylabel(r'$\alpha_{F_{\nu}}$')
    #plt.legend(loc ='lower left')
    plt.legend(handler_map={type(line1): HandlerLine2D(numpoints=1)},
               loc='lower left')
    pp = oldplotout + name + '_linear.png'
    plt.savefig(pp, padinches=0.85)
    plt.clf()
    plt.close()
    return minbump