Ejemplo n.º 1
0
    def lnlike(self, theta, model, **kwargs):
        r'''Compute the likelihood of the photometry given the model. 

        The likelihood is computed as 
        .. math::
        
            \frac{1}{2} N \ln\left(2\pi\right) - \frac{1}{2}\ln\left(\mathrm{det}C\right) - \frac{1}{2} \left(F_\mathrm{obs} - F_\mathrm{mod})^T C^{-1} \left(F_\mathrm{obs} - F_\mathrm{mod}\right)  

        where N is the number of photometric points, C is the covariance matrix, and F_obs and F_mod are the observed and predicted photmetry, respectively.

        Parameters
        ----------
        theta: None,
            included for compatibility reasons
        model: an instance of Model or a subclass,
            The model for which the likelihood will be computed

        Returns
        -------
        probFlux: float
            The natural logarithm of the likelihood of the data given the model
        '''
        ''' First take the model values (passed in) and compute synthetic photometry '''
        ''' I assume that the filter library etc is already setup '''
        filts, modSed = pyphot.extractPhotometry(model.wavelength,
                                                 model.modelFlux,
                                                 self.filters,
                                                 Fnu=True,
                                                 absFlux=False,
                                                 progress=False)
        ''' then update the covariance matrix for the parameters passed in '''
        #skip this for now
        self.covMat = self.cov()
        ''' then compute the likelihood for each photometric point in a vectorised statement '''
        a = self.value[self.mask] - modSed

        b = -0.5 * len(self.value[self.mask]) * np.log(2 * np.pi) - (
            0.5 * self.logDetCovMat)
        #np.log(1./((2*np.pi)**(len(self.value)) * np.linalg.det(self.covMat))
        #)
        probFlux = b + (
            -0.5 *
            (np.matmul(a.T, np.matmul(inv(self.covMat[self.cov_mask]), a))))
        return probFlux
Ejemplo n.º 2
0
"""We will use the same set of filters for both examples below"""
filterNames = ['MCPS_U', 'MCPS_B', 'MCPS_U', 'MCPS_I', '2MASS_J', '2MASS_H', '2MASS_Ks',
                                  'SPITZER_IRAC_36', 'SPITZER_IRAC_45', 'SPITZER_IRAC_58', 'SPITZER_IRAC_80',
                                  'SPITZER_MIPS_24']
libraryName = libsdir+'synphot_PhIReSSTARTer.hd5'
filterLibrary = pyphot.get_library(fname=libraryName)

#Input spectrum
spec = np.loadtxt(demodir+'IRC+10216_ISO_SWS.dat', comments='#', usecols=(0,1))
#Retrieve filter responses interpolated over input wavelength grid
filterList = filterLibrary.load_filters(filterNames, interp=True, lamb=spec[:,0]*pyphot.unit['micron'])

#Upon execution, cls contains the central wavelengths for each filter, and sed the
#   synthetic photometry in that filter.
cls, sed = pyphot.extractPhotometry(spec[:,0], spec[:,1], filterList, Fnu=True, absFlux=False)
lamCen = np.array([a.magnitude for a in cls])

#Plot results
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(spec[:,0], spec[:,1], '--', label='ISO SWS spectrum')
ax.plot(lamCen, sed, 'o', color='red', label='Synthetic photometry')
ax.set_xlabel('Wavelength (micron)')
ax.set_ylabel('Flux (Jy)', rotation=90.)
for i in range(len(filterNames)):
        ax.text(lamCen[i], sed[i]*1.2, filterNames[i], horizontalalignment='center', verticalalignment='bottom', fontsize=8, rotation=90.)
        plt.title('Example 1: IRC+10216')
        plt.show()

"""Read in the GRAMS C-star grid"""
Ejemplo n.º 3
0
     'WISE_RSR_W1',
     'WISE_RSR_W2',
     'WISE_RSR_W3',
     'WISE_RSR_W4',
     'HERSCHEL_PACS_BLUE'
 ]
 libDir = os.getcwd() + '/ampere/'
 libname = libDir + 'ampere_allfilters.hd5'
 print(libname)
 filterLib = pyphot.Library.from_hd5(libname)
 filts = filterLib.load_filters(filters,
                                interp=True,
                                lamb=modwaves * pyphot.unit['micron'])
 f, sed = pyphot.extractPhotometry(modwaves,
                                   TestData.modelFlux,
                                   filts,
                                   Fnu=True,
                                   absFlux=False)
 lamCen = np.array([b.magnitude for b in f])
 print(lamCen, sed)
 ''' now turn the numbers into a Photometry object '''
 phot = Photometry(np.array(filters),
                   np.array(sed),
                   np.array(0.1 * sed),
                   np.array(['Jy', 'Jy', 'Jy', 'Jy', 'Jy']),
                   bandUnits='um',
                   libName=libname)
 phot.reloadFilters(modwaves)
 print(phot)
 irs.append(phot)
 #exit()
Ejemplo n.º 4
0
def Image_FilterConvolve(model, Source_Distance, Filter_Library, group_val):

    image = model.get_image(
        group=int(group_val),
        inclination=0,
        distance=Source_Distance,
        units='Jy')  #Full Image data cube holding all four wavelength images

    #Getting Frequency and Wavelength of the images in the output cubes (1 cube for each wavelength)
    RT_Image_Wavelengths = image.wav  #image.wav = list of wavelengths created based on the limits given during image creation at each wavelengths in RT modelling stage.Pre Convolution
    RT_Image_Fluxes = image.val  #Fluxes of the image derived during RT modelling. Pre Convolution

    #print('Wavelength of Image = ', RT_Image_Wavelengths, 'micron')
    #print(RT_Image_Fluxes.shape[:-1])

    Filter_ConvImage = np.zeros(
        RT_Image_Fluxes.shape[:-1]
    )  #Create a empty array in the same shape as the 1st two (everything up to the 1 before last element) axes (400 x 400 in our case) to store the filter convolved photometry.

    #Extracting the correct filters from the filt.library
    #Filter for PACS 70 image
    if RT_Image_Wavelengths[0] < 100:
        Filter_Name = ['HERSCHEL_PACS_BLUE']

    #Filter for PACS 160 image
    elif RT_Image_Wavelengths[0] < 300:
        Filter_Name = ['HERSCHEL_PACS_RED']

    #Filter for SCUBA-2 450 image
    elif RT_Image_Wavelengths[0] < 500:
        Filter_Name = ['JCMT_SCUBA2_450']

    #Filter for SCUBA-2 850 image
    elif RT_Image_Wavelengths[0] < 1000:
        Filter_Name = ['JCMT_SCUBA2_850']

    #Extracting the correct filters from the filt.library
    Filter = Filter_Library.load_filters(
        Filter_Name,
        interp=True,
        lamb=RT_Image_Wavelengths * pyphot.unit['micron']
    )  #pyphot.unit['micron'] tells pyphot that the wavlengths are in micron units.

    #Loop over each pixel in the image (400 x 400) to carry out filt.conv along the z axes
    #First get the row
    for row in range(RT_Image_Fluxes.shape[0]):
        #Then get the col. and therefore the pixel in the chosen row.
        for col in range(RT_Image_Fluxes.shape[1]):

            #Convolving with Filter Profiles
            filter_info, FiltConv_Image_Fluxes = pyphot.extractPhotometry(
                RT_Image_Wavelengths,
                RT_Image_Fluxes[row, col],
                Filter,
                Fnu=True,
                absFlux=False,
                progress=False
            )  #filter_info saves info about the filt. profiles. SED flux units = Jy. #progress=False - won't print progress on terminal.

            Filter_ConvImage[row, col] = FiltConv_Image_Fluxes

    #plt.imshow(Filter_ConvImage)
    #plt.show()

    return Filter_Name, Filter_ConvImage
Ejemplo n.º 5
0

    """ get synthetic photometry and spectra """
    filterName = np.array(['WISE_RSR_W4', 'WISE_RSR_W3', 'WISE_RSR_W2', 'WISE_RSR_W1', 'SPITZER_MIPS_24', 'SPITZER_MIPS_70']) #

    #libDir = pyphot.__file__.strip('__init__.py')+'libs/'
    #libName = libDir + 'synphot_nonhst.hd5' #PhIReSSTARTer.hd5'

    libDir = '/home/peter/pythonlibs/ampere/ampere/'
    libname = libDir + 'ampere_allfilters.hd5'
    filterLibrary = pyphot.get_library(fname=libname)
    filters = filterLibrary.load_filters(filterName, interp=True, lamb = wavelengths*pyphot.unit['micron'])
    filts, modSed = pyphot.extractPhotometry(wavelengths,
                                             model_flux,
                                             filters,
                                             Fnu = True,
                                             absFlux = False,
                                             progress=False
            )

    print(filts,modSed)

    """ (optionally) add some noise """
    print(modSed)
    modSed = modSed + np.random.randn(6) * 0.1 * modSed
    print(modSed)
    #exit()

    """ now we'll create a synthetic spectrum from the model"""
    dataDir = os.getcwd() + '/PGQuasars/PG1011-040/'
    specFileExample = 'cassis_yaaar_spcfw_14191360t.fits'
Ejemplo n.º 6
0
for filename in OutPutFiles:

	model = ModelOutput(filename)
	sed = model.get_sed(group=0, inclination='all', aperture=-1, distance=Source_Distance, units='Jy')

	#print(sed.wav)
	#print(sed.val)
	
	RT_SED_wavelengths = sed.wav #sed.wav = list of wavelengths created based on the limits (100, 0.3, 1200.) given during SED creation in RT modelling stage. Pre Convolution with Filters
	RT_SED_Fluxes = sed.val[0] #Fluxes of the SED derived during RT modelling. Pre Convolution with Filters #[0] - Hyperion has gives a list of arrays instead of an array. So we need to pick the zeroth element array even if the rest are empty.

	#Extracting the correct filters from the filt.library	
	Filters = Filter_Library.load_filters(Filter_Names, interp=True, lamb=RT_SED_wavelengths*pyphot.unit['micron'])  #pyphot.unit['micron'] tells pyphot that the wavlengths are in micron units. 

	#Convolving with Filter Profiles
	filter_info, Convolved_Model_SED_Fluxes = pyphot.extractPhotometry(RT_SED_wavelengths, RT_SED_Fluxes, Filters, Fnu=True, absFlux=False)#, progress=False) #filter_info saves info about the filt. profiles. SED flux units = Jy

	Conv_SED_Wavelengths = np.array([a.magnitude for a in filter_info]) #Extracting the convolved SED wavelengths from the filter_info. Units=micron
	
	
	#Final Convolved SED Model Output Table File
	Table_name = filename.strip('.rtout') + '_Filter_Convolved_SED.csv' #filename.strip('.rtout') - Get rid of .rtout from filename and add the +.. string after for the table name
	f = open(Table_name, 'w')
	f.write("Filter_Name" + "," + "Wavelength_micron" + "," + "Filt.Convolved_SED_Flux_Jy" + "\n")
	f.close()

	f = open(Table_name, 'a')
	for i in range(len(Filter_Names)):
		outstring = str(Filter_Names[i]) + ","  + str(Conv_SED_Wavelengths[i]) + ","  + str(Convolved_Model_SED_Fluxes[i]) + "\n"
		f.write(outstring)
	f.close()