示例#1
0
def findAGNnumber(limits, QSOTemplate):
    AGN = createOzDESAGN(QSOTemplate)
    rFilter = AGN.getFilter('rFilter')
    iFilter = AGN.getFilter('iFilter')
    
    # Extract data from file
    name = '/Users/natsomme/Dropbox/Uni/Thesis/Run007_MasterInput.cat'
    data = np.loadtxt(name)
    mag  = data[:, 3]
    z    = data[:, 4]
    
    # Extract physically reasonable AGN
    mag = mag[z>0]
    z   = z[z>0]
    n   = np.size(z)
    Mag = np.zeros(n)
    
    # Calculate absMag using QSO-functions
    for i in range(n):
        Lbol   = AGN.getQSObol(mag[i], z[i], rFilter)
        Mag[i] = AGN.getQSOabsMag(Lbol, 0.0, iFilter)
    # End for-loop
    
    # Extract limits
    zMin = limits[0]
    zMax = limits[1]
    MagMin = limits[2]
    MagMax = limits[3]
    
    num = 0
    for i in range(n):
        if (z[i] >= zMin and z[i] < zMax and Mag[i] > MagMin and Mag[i] <= MagMax):
            num = num + 1
        # End if-statement
    # End for-loop
    
    return num
示例#2
0
def compareToTheory():
    # Do theoretical calculations
    QSOTemplate = ascii.read('/Users/natsomme/Dropbox/Uni/Thesis/fake_data_code/sdssqsocomposite.txt')
    create = createOzDESAGN(QSOTemplate)

    z = 0.0                                 # Redshift at which AGN are to be created (zero due to filter)
    n = 100                                 # Number of points to create a smooth theoretical curve
    lag = np.zeros(n)                       # Initialising array for all the lags we'll be considering
    absmag = np.linspace(-28, -18.5, n)     # Initialising array with magnitudes we're interested in

    # Calculate a continuus time lag curve for the magnitudes we have
    for i in range(n):
        Lbol         = create.getQSObolFromAbsMag(absmag[i], z, create.iFilter)
        _, lag[i], _ = create.getLag(Lbol, z)
    # End for-loop
    
    # Check how the time lag changes over time
    gradlag = np.gradient(lag)              # Calculate gradient of time lag
    graddiv = gradlag/lag                   # Calculate the gradient of the lag divided by the lag

    # Get hold of time lag estimates to compare theory to
    matr = np.loadtxt('/Volumes/mimsy/Obelix/Mhas50binsKcorr/test.dat')
    nbin    = matr[:,0]     # Which bin the current bin starts on (no longer a thing)
    mag     = matr[:,1]     # The lower end of the magnitude bin
    nagn    = matr[:,2]     # Number of AGN in bin
    tmean   = matr[:,3]     # Average mean time lag for AGN in bin
    tstd    = matr[:,4]     # Standard deviation of lags for AGN in bin
    tlo     = matr[:,5]     # Difference between average lag and shortest lag
    thi     = matr[:,6]     # Difference between average lag and longest lag
    sgmean  = matr[:,7]     # Time lag estimate based on fitted skewed gaussian
    sglo    = matr[:,8]     # Lower uncertainty estimate based on fitted skewed gaussian
    sghi    = matr[:,9]     # Upper uncertainty estimate based on fitted skewed gaussian
    llhmean = matr[:,10]    # Time lag estimate using maximum likelihood
    llhlo   = matr[:,11]    # Lower uncertainty estimate for maximum likelihood
    llhhi   = matr[:,12]    # Upper uncertainty estimate for maximum likelihood
    med1    = matr[:,13]    # Time lag estimate based on median
    med1lo  = matr[:,14]    # Lower uncertainty estimate for median
    med1hi  = matr[:,15]    # Upper uncertainty estimate for median
    med2    = matr[:,16]    # Time lag estimate based on median of maximum likelihoods
    med2lo  = matr[:,17]    # Lower uncertainty estimate for median of max llhs
    med2hi  = matr[:,18]    # Upper uncertainty estimate for median of max llhs

    # Find average uncertainty where there is an upper and lower limit
    sgstd = 0.5*(sglo+sghi)
    llstd = 0.5*(llhlo+llhhi)
    med1std = 0.5*(med1lo+med1hi)
    med2std = 0.5*(med2lo+med2hi)

    # Perform a chi2 fit
    N = 1000                                    # Number of values to check for with chi2 test
    fitconst = np.linspace(0.0002,0.0004,N)     # Values to check for with chi2 test
    chi2     = np.zeros(N)                      # Initialise

    for i in range(N):

        # Print some information for values close to the the lowest chi2 value
        if (i > 360 and i < 375):
            print 'mag -- C*10^{-0.22 mag} - tau_D_stacked - std(tau_D_stacked) -- chi2'
        # End if-statement

        for j in range(len(tmean)):
            # Calculate chi2 value using all data points
            chi2[i] = chi2[i] + ( ( (fitconst[i]*10**(-0.22*mag[j])) - tmean[j]) / tstd[j] )**2

            # Print some information for values close to the the lowest chi2 value
            if (i > 360 and i < 375):
                print mag[j], '--', fitconst[i]*10**(-0.22*mag[j]), '-', tmean[j], '-', tstd[j], \
                     '--', ( ( (fitconst[i]*10**(-0.22*mag[j])) - tmean[j]) / tstd[j] )**2
            # End if-statement 

        # End for-loop

        # Print some information for values close to the the lowest chi2 value
        if (i > 360 and i < 375):
            print '\n'
        if (i == 368 or i == 369):
            print '-------------'
        # End if-statements

    # End for-loop

    chi2dof = np.min(chi2)/9.0                  # Calculate chi2 pr dof
    a       = fitconst[np.argmin(chi2)]         # Calculate the best constant based on chi2 test
    Dchi2   = chi2 - np.min(chi2)               # Calculate difference between all chi2 values and min(chi2)

    # Print information about chi2 test to screen
    print 'Chi2 best fit slope: a =', a
    print 'Chi2DOF =', chi2dof

    # Define remaining parameters to draw best fit line
    b = 0.
    m = np.linspace(-30.0, -18.5, 100)
    tau = a * 10**( -0.22*m ) + b               # Best fit line based on chi2 test on estimates

    # Create figure showing the comparison between theory and data
    fig = plt.figure()
    ax  = plt.axes()
    ratio = float((np.max(absmag) - np.min(absmag))/(np.max(lag) - np.min(lag)))

    # Plot theory and data
    plt.plot([0,0], [0,0], 'w', label=' ')      # Plot nothing just to get a prettier legend
    plt.errorbar(mag, tmean, yerr=[tlo, thi], fmt='o', color='grey')
    plt.errorbar(mag, tmean, yerr=tstd,       fmt='o', label='Average true lag')
    plt.errorbar(mag+0.1, sgmean,  yerr=[sglo,  sghi],  fmt='x', label='Skewed Gaussian')
    plt.errorbar(mag+0.2, llhmean, yerr=[llhlo, llhhi], fmt='x', label='Maximum likelihood')
    plt.errorbar(mag+0.3, med1, yerr=[med1lo, med1hi],  fmt='x', label='Stacked median')
    plt.errorbar(mag+0.4, med2, yerr=[med2lo, med2hi],  fmt='x', label='Bootstrap median')
    plt.plot(m, tau, label=r'$\tau$ = C$\cdot$10$^{-0.22M}$')
    plt.plot(absmag, lag, label='R-L relationship')

    # Customise figure
    plt.xlabel('Magnitude', fontsize='large')
    plt.ylabel('Time lag [days]', fontsize='large')
    plt.legend(loc="center right", bbox_to_anchor=(1.02, 1.13), ncol=2)
    plt.axis([np.min(absmag), np.max(absmag), np.min(lag), np.max(lag)])

    ax.xaxis.set_major_locator(tck.MultipleLocator(1))
    ax.xaxis.set_minor_locator(tck.MultipleLocator(0.5))
    ax.yaxis.set_major_locator(tck.MultipleLocator(50))
    ax.yaxis.set_minor_locator(tck.MultipleLocator(25))
    ax.set_aspect(ratio)
    
    plt.subplots_adjust(wspace=0, hspace=0, bottom=0.015)           # Ensure neat output
    plt.savefig('/Users/natsomme/Documents/TheoryAndObservations.png', bbox_inches='tight', figsize=(10,10), dpi=500)

    plt.figure()
    plt.subplot(211)
    plt.plot(absmag, gradlag)
    plt.xlabel('Magnitude', fontsize='large')
    plt.ylabel('Gradient of time lag', fontsize='large')
    plt.axis([np.min(absmag), np.max(absmag), np.min(gradlag), np.max(gradlag)])
    plt.subplot(212)
    plt.plot(absmag, graddiv)
    plt.xlabel('Magnitude', fontsize='large')
    plt.ylabel('Gradient of time lag by lag', fontsize='large')
    plt.axis([np.min(absmag), np.max(absmag), np.min(graddiv), np.max(graddiv)])
示例#3
0
def plotOzDESAGN(QSOTemplate, plotIndividuals=False, binends=None, name=None):
    AGN = createOzDESAGN(QSOTemplate)
    rFilter = AGN.getFilter('rFilter')
    iFilter = AGN.getFilter('iFilter')
    
    # Extract data from file
    catalogue = '/Users/natsomme/Dropbox/Uni/Thesis/Run007_MasterInput.cat'
    data = np.loadtxt(catalogue)
    mag  = data[:, 3]
    z    = data[:, 4]
    
    # Extract physically reasonable AGN
    mag = mag[z>0]
    z   = z[z>0]
    n   = np.size(z)
    Mag = np.zeros(n)
    
    # Calculate absMag using QSO-functions
    for i in range(n):
        Lbol   = AGN.getQSObol(mag[i], z[i], rFilter)
        Mag[i] = AGN.getQSOabsMag(Lbol, 0.0, iFilter)
    # End for-loop
    
    # Plot redshift and magnitude histograms if desired
    if (plotIndividuals == True):
        # Create bins
        zBins = np.logspace(-3, np.log10(0.69), 20)
        zBins = np.concatenate(( zBins, np.logspace(np.log10(0.74), np.log10(1.58), 4) ))  
        zBins = np.concatenate(( zBins, np.logspace(np.log10(1.94), np.log10(4.0), 5)))
        MagBins = np.linspace(np.min(Mag), np.max(Mag), 50)
    
        plt.figure(dpi=500)
        plt.hist(z, bins=zBins, facecolor='g')
        plt.xlabel('Redshift z')
        plt.ylabel('Number of objects')
        
        plt.figure(dpi=500)
        plt.hist(Mag, bins=MagBins, facecolor='g')
        plt.xlabel('Absolute magnitude')
        plt.ylabel('Number of objects')
    # End if-statement
    
    # Create a figure with the distributions of the OzDES AGN sample
    plt.figure(figsize=(9,15), dpi=500)
    
    # Annotate z-values corresponding to emission lines
    plt.plot([0.69, 0.69], [-40, -10], color = '0.4')
    plt.plot([0.74, 0.74], [-40, -10], color = '0.4')
    plt.plot([1.58, 1.58], [-40, -10], color = '0.4')    
    plt.plot([1.94, 1.94], [-40, -10], color = '0.4')
    
    if (binends != None):
        # Fill out optimised bins
        for i in range(np.size(binends)):
            if (i < np.size(binends)-1):
                if (np.remainder(i, 2) == 0):
                    shade = 0.2
                else:
                    shade = 0.4
                # End if-statement 
                plt.fill_between([0.69, 1.94], [binends[i], binends[i]], y2=[binends[i+1], binends[i+1]], 
                                 color='deeppink', alpha=shade)
            # End if-statement
            plt.plot([0.69, 1.94], [binends[i], binends[i]], color = '0.3', alpha=0.2)
        # End for-loop
    # End if-statement
        
    # Plot the AGN in the OzDES sample
    plt.plot(z, Mag, 'o', color='mediumvioletred')
    
    # Figure properties
    plt.axis([0.1, 4, -27.7, -18.9])
    plt.xlabel('Redshift', fontsize='large')
    plt.ylabel('Absolute magnitude', fontsize='large')
    
    ax = plt.axes()
    ax.xaxis.set_major_locator(MultipleLocator(0.5))
    ax.xaxis.set_minor_locator(MultipleLocator(0.125))
    ax.yaxis.set_major_locator(MultipleLocator(1))
    ax.yaxis.set_minor_locator(MultipleLocator(0.25))
    ax.set_aspect(3.9/(27.7-18.9))
    
    if (name==None):
        plt.savefig('/Users/natsomme/Documents/OzDES_AGN.png', dpi=500, bbox_inches='tight')
    else:
        plt.savefig('/Users/natsomme/Documents/OzDES_AGN'+name+'.png', dpi=500, bbox_inches='tight')
示例#4
0
 fName   = 'fakedata.dat'
 
 section = 'oneline'
 emLine  = 'Hb'
 binends = np.array([-26.15, -25.75, -25.35, -24.95, -24.55, -24.15, -23.75, -23.35, -22.85, -22.35])#, -21.55])
 
 pm = 1.3
 limits = np.array([0., 0.74, -22.90-pm, -22.90])#MagBins[30], MagBins[31]])
 number = findAGNnumber(limits, QSOtemplate)
 #number = 1
 print ' '
 print 'Limits:', limits
 print 'Number of AGN within limits:', number
 
 # Initialisation
 AGN = createOzDESAGN(QSOtemplate)
 stack = Stacking()
 stats = Stats()
 conv  = Convergence()
 
 plotOzDESAGN(QSOtemplate, plotIndividuals=False, binends=binends, name='MgII')
 
 # Create AGN
 AGN.generateAGN(limits, True, number, resDir, fName)
 output = AGN.generateLightCurveParameters(section, resDir+fName)
 AGN.printLightCurveParametersToFile(output, resDir+params)
 lag = printLagValueInParameterBin(resDir+params, limits, emLine=emLine)
 
 # Do the Javelin magic
 runJavelinOnFakeData(resDir+params, limits, number, resDir, string, emLine=emLine)