Esempio n. 1
0
def getVis(sbmodelloc, visdataloc):

    #print(sbmodelloc, visdataloc)
    # read in the surface brightness map of the model
    modelimage = fits.getdata(sbmodelloc)
    modelheader = fits.getheader(sbmodelloc)

    # load the uv data, including the phase center of the data
    uu, vv, ww = uvutil.uvload(visdataloc)

    # load the uv data, including the phase center of the data
    pcd = uvutil.pcdload(visdataloc)

    # sample the uv visfile[0].data using the model
    uushape = uu.shape
    if len(uushape) == 2:
        npol = uushape[0]
        nrow = uushape[1]
        uushape = (npol, 1, nrow)
    uu = uu.flatten()
    vv = vv.flatten()
    model_complex = sample_vis.uvmodel(modelimage, modelheader, \
            uu, vv, pcd)

    vis_complex = model_complex.reshape(uushape)
    return vis_complex
Esempio n. 2
0
def getVis(sbmodelloc, visdataloc):

    #print(sbmodelloc, visdataloc)
    # read in the surface brightness map of the model
    modelimage = fits.getdata(sbmodelloc)
    modelheader = fits.getheader(sbmodelloc)
     
    # load the uv data, including the phase center of the data
    uu, vv, ww = uvutil.uvload(visdataloc)
     
    # load the uv data, including the phase center of the data
    pcd = uvutil.pcdload(visdataloc)

    # sample the uv visfile[0].data using the model
    uushape = uu.shape
    if len(uushape) == 2:
        npol = uushape[0]
        nrow = uushape[1]
        uushape = (npol, 1, nrow)
    uu = uu.flatten()
    vv = vv.flatten()
    model_complex = sample_vis.uvmodel(modelimage, modelheader, \
            uu, vv, pcd)

    vis_complex = model_complex.reshape(uushape)
    return vis_complex
Esempio n. 3
0
def add(sbmodelloc, visdataloc, WeightByRMS=True, ExcludeChannels='none'):

    # read in the surface brightness map of the model
    modelimage = fits.getdata(sbmodelloc)
    modelheader = fits.getheader(sbmodelloc)

    # read in the uvfits data
    visfile = fits.open(visdataloc)
    visibilities = visfile[0].data
     
    # load the uv data, including the phase center of the data
    uu, vv, pcd = uvutil.uvload(visfile)

    # get the number of visibilities, spws, frequencies, polarizations
    if uu.ndim == 4:
        nvis = uu[:, 0, 0, 0]
        nspw = uu[0, :, 0, 0]
        nfreq = uu[0, 0, :, 0]
        npol = uu[0, 0, 0, :]
    if uu.ndim == 3:
        nvis = uu[:, 0, 0]
        nspw = 0
        nfreq = uu[0, :, 0]
        npol = uu[0, 0, :]

    # sample the uv visibilities using the model
    uu = uu.flatten()
    vv = vv.flatten()
    model_complex = sample_vis.uvmodel(modelimage, modelheader, \
            uu, vv, pcd)

    if nspw > 0:
        # get the real and imaginary components
        real = numpy.real(model_complex).reshape(nvis, nspw, nfreq, npol)
        imag = numpy.imag(model_complex).reshape(nvis, nspw, nfreq, npol)
        uu = uu.reshape(nvis, nspw, nfreq, npol)
        vv = vv.reshape(nvis, nspw, nfreq, npol)

        # replace data visibilities with model visibilities
        visibilities['DATA'][:, 0, 0, :, :, :, 0] = real_raw + real
        visibilities['DATA'][:, 0, 0, :, :, :, 1] = imag_raw + imag
        visibilities['DATA'][:, 0, 0, :, :, :, 2] = wgt
    else:
        # get the real and imaginary components
        real = numpy.real(model_complex).reshape(nvis, nfreq, npol)
        imag = numpy.imag(model_complex).reshape(nvis, nfreq, npol)
        uu = uu.reshape(nvis, nfreq, npol)
        vv = vv.reshape(nvis, nfreq, npol)

        # replace data visibilities with model visibilities
        visibilities['DATA'][:, 0, 0, :, :, 0] = real_raw + real
        visibilities['DATA'][:, 0, 0, :, :, 1] = imag_raw + imag
        visibilities['DATA'][:, 0, 0, :, :, 2] = wgt

    # replace the data visibilities with the model visibilities
    visfile[0].data = visibilities

    #visfile[0].data = vismodel

    return visfile
Esempio n. 4
0
def replace(sbmodelloc, visdataloc):

    # read in the surface brightness map of the model
    modelimage = fits.getdata(sbmodelloc)
    modelheader = fits.getheader(sbmodelloc)

    # read in the uvfits data
    visfile = fits.open(visdataloc)
     
    # load the uv data, including the phase center of the data
    uu, vv = uvutil.uvload(visfile)
     
    # load the uv data, including the phase center of the data
    pcd = uvutil.pcdload(visfile)

    # get the number of visfile[0].data, spws, frequencies, polarizations
    if uu.ndim == 4:
        nvis = uu[:, 0, 0, 0].size
        nspw = uu[0, :, 0, 0].size
        nfreq = uu[0, 0, :, 0].size
        npol = uu[0, 0, 0, :].size
    if uu.ndim == 3:
        nvis = uu[:, 0, 0].size
        nspw = 0
        nfreq = uu[0, :, 0].size
        npol = uu[0, 0, :].size

    # sample the uv visfile[0].data using the model
    uu = uu.flatten()
    vv = vv.flatten()
    model_complex = sample_vis.uvmodel(modelimage, modelheader, \
            uu, vv, pcd)

    if nspw > 0:
        # deflatten the real and imaginary components
        real = numpy.real(model_complex).reshape(nvis, nspw, nfreq, npol)
        imag = numpy.imag(model_complex).reshape(nvis, nspw, nfreq, npol)
        # replace data visfile[0].data with model visfile[0].data
        visfile[0].data['DATA'][:, 0, 0, :, :, :, 0] = real
        visfile[0].data['DATA'][:, 0, 0, :, :, :, 1] = imag
    else:
        # deflatten the real and imaginary components
        real = numpy.real(model_complex).reshape(nvis, nfreq, npol)
        imag = numpy.imag(model_complex).reshape(nvis, nfreq, npol)
        # replace data visfile[0].data with model visfile[0].data
        visfile[0].data['DATA'][:, 0, 0, :, :, 0] = real
        visfile[0].data['DATA'][:, 0, 0, :, :, 1] = imag

    print "Exiting replace"

    #visfile[0].data = vismodel

    return visfile
Esempio n. 5
0
def lnprob(pzero_regions, p_u_regions, p_l_regions, fixindx, \
        real, imag, wgt, uuu, vvv, pcd, lnlikemethod, \
        x_regions, y_regions, headmod_regions, celldata, \
        model_types_regions, nregions, nlens_regions, nsource_regions):

    # impose constraints on parameters by setting chi^2 to enormously high
    # value when a walker chooses a parameter outside the constraints
    if (pzero_regions < p_l_regions).any():
        probln = -numpy.inf
        mu_flux = 0
        #print probln, mu_flux, pzero
        #print probln, ["%0.2f" % i for i in pzero]
        return probln, mu_flux
    if (pzero_regions > p_u_regions).any():
        probln = -numpy.inf
        mu_flux = 0
        #print probln, ["%0.2f" % i for i in pzero]
        return probln, mu_flux
    if (pzero_regions * 0 != 0).any():
        probln = -numpy.inf
        mu_flux = 0
        #print probln, ["%0.2f" % i for i in pzero]
        return probln, mu_flux

    # search poff_models for parameters fixed relative to other parameters
    fixed = (numpy.where(fixindx >= 0))[0]
    nfixed = fixindx[fixed].size
    poff_regions = p_u_regions.copy()
    poff_regions[:] = 0.
    for ifix in range(nfixed):
        poff_regions[fixed[ifix]] = pzero_regions[fixindx[fixed[ifix]]]

    parameters_regions = pzero_regions + poff_regions

    model_real = 0.
    model_imag = 0.
    npar_previous = 0
    prindx = 0

    amp = []

    for regioni in range(nregions):

        # get the model info for this model
        x = x_regions[regioni]
        y = y_regions[regioni]
        headmod = headmod_regions[regioni]
        nlens = nlens_regions[regioni]
        nsource = nsource_regions[regioni]
        model_types = model_types_regions[prindx:prindx + nsource]
        prindx += nsource
        #model_types_regioni = model_types[regioni]

        # get pzero, p_u, and p_l for this specific model
        nparlens = 5 * nlens
        nparsource = 6 * nsource
        npar = nparlens + nparsource + npar_previous
        parameters = parameters_regions[npar_previous:npar]
        npar_previous += npar

        #-----------------------------------------------------------------
        # Create a surface brightness map of lensed emission for the given set
        # of foreground lens(es) and background source parameters.
        #-----------------------------------------------------------------

        g_image, g_lensimage, e_image, e_lensimage, amp_tot, amp_mask = \
                lensutil.sbmap(x, y, nlens, nsource, parameters, model_types)
        amp.extend(amp_tot)
        amp.extend(amp_mask)

        #----------------------------------------------------------------------
        # Python version of UVMODEL:
        # "Observe" the lensed emission with the interferometer
        #----------------------------------------------------------------------

        if nlens > 0:
            # Evaluate amplification for each region
            lensmask = e_lensimage != 0
            mask = e_image != 0
            numer = g_lensimage[lensmask].sum()
            denom = g_image[mask].sum()
            amp_mask = numer / denom
            numer = g_lensimage.sum()
            denom = g_image.sum()
            amp_tot = numer / denom
            if amp_tot > 1e2:
                amp_tot = 1e2
            if amp_mask > 1e2:
                amp_mask = 1e2
            amp.extend([amp_tot])
            amp.extend([amp_mask])

        model_complex = sample_vis.uvmodel(g_image, headmod, uuu, vvv, pcd)
        model_real += numpy.real(model_complex)
        model_imag += numpy.imag(model_complex)

        #fits.writeto('g_lensimage.fits', g_lensimage, headmod, clobber=True)
        #import matplotlib.pyplot as plt
        #print pzero_regions
        #plt.imshow(g_lensimage, origin='lower')
        #plt.colorbar()
        #plt.show()

    # use all visibilities
    goodvis = (real * 0 == 0)

    # calculate chi^2 assuming natural weighting
    #fnuisance = 0.0
    modvariance_real = 1 / wgt #+ fnuisance ** 2 * model_real ** 2
    modvariance_imag = 1 / wgt #+ fnuisance ** 2 * model_imag ** 2
    #wgt = wgt / 4.
    chi2_real_all = (real - model_real) ** 2. / modvariance_real
    chi2_imag_all = (imag - model_imag) ** 2. / modvariance_imag
    chi2_all = numpy.append(chi2_real_all, chi2_imag_all)

    # compute the sigma term
    sigmaterm_real = numpy.log(2 * numpy.pi * modvariance_real)
    sigmaterm_imag = numpy.log(2 * numpy.pi * modvariance_imag)
    sigmaterm_all = numpy.append(sigmaterm_real, sigmaterm_imag)

    # compute the ln likelihood
    if lnlikemethod == 'chi2':
        lnlike = chi2_all
    else:
        lnlike = chi2_all + sigmaterm_all

    # compute number of degrees of freedom
    #nmeasure = lnlike.size
    #nparam = (pzero != 0).size
    #ndof = nmeasure - nparam

    # assert that lnprob is equal to -1 * maximum likelihood estimate
    probln = -0.5 * lnlike[goodvis].sum()
    if probln * 0 != 0:
        probln = -numpy.inf
    #print ndof, probln, sigmaterm_all.sum(), chi2_all.sum()

    return probln, amp
Esempio n. 6
0
def lnlike(pzero_regions, vis_complex, wgt, uuu, vvv, pcd,
           fixindx, paramSetup, computeamp=True, miriad=False):
    """ Function that computes the Ln likelihood of the data"""

    # search poff_models for parameters fixed relative to other parameters
    fixed = (numpy.where(fixindx >= 0))[0]
    nfixed = fixindx[fixed].size
    p_u_regions = paramSetup['p_u']
    poff_regions = p_u_regions.copy()
    poff_regions[:] = 0.
    #for ifix in range(nfixed):
    #    poff_regions[fixed[ifix]] = pzero_regions[fixindx[fixed[ifix]]]
    for ifix in range(nfixed):
        ifixed = fixed[ifix]
        subindx = int(fixindx[ifixed])
        par0 = 0
        if fixindx[subindx] > 0:
            par0 = pzero_regions[fixindx[subindx]]
        poff_regions[ifixed] = pzero_regions[subindx] + par0

    parameters_regions = pzero_regions + poff_regions

    npar_previous = 0

    amp = []  # Will contain the 'blobs' we compute
    g_image_all = 0.
    g_lensimage_all = 0.
    e_image_all = 0.
    e_lensimage_all = 0.

    nregions = paramSetup['nregions']
    for regioni in range(nregions):

        # get the model info for this model
        x = paramSetup['x'][regioni]
        y = paramSetup['y'][regioni]
        headmod = paramSetup['modelheader'][regioni]
        nlens = paramSetup['nlens_regions'][regioni]
        nsource = paramSetup['nsource_regions'][regioni]
        model_types = paramSetup['model_types'][regioni]

        # get pzero, p_u, and p_l for this specific model
        nparlens = 5 * nlens
        nparsource = 6 * nsource
        npar = nparlens + nparsource + npar_previous
        parameters = parameters_regions[npar_previous:npar]
        npar_previous = npar

        #-----------------------------------------------------------------
        # Create a surface brightness map of lensed emission for the given set
        # of foreground lens(es) and background source parameters.
        #-----------------------------------------------------------------

        g_image, g_lensimage, e_image, e_lensimage, amp_tot, amp_mask = \
                lensutil.sbmap(x, y, nlens, nsource, parameters, model_types,
                computeamp=computeamp)
        e_image_all += e_image
        e_lensimage_all += e_lensimage
        g_image_all += g_image
        g_lensimage_all += g_lensimage
        amp.extend(amp_tot)
        amp.extend(amp_mask)

        # --------------------------------------------------------------------
        # Python version of UVMODEL:
        # "Observe" the lensed emission with the interferometer
        # --------------------------------------------------------------------

        if nlens > 0:
            if computeamp:
                # Evaluate amplification for each region
                lensmask = e_lensimage != 0
                mask = e_image != 0
                numer = g_lensimage[lensmask].sum()
                denom = g_image[mask].sum()
                amp_mask = numer / denom
                numer = g_lensimage.sum()
                denom = g_image.sum()
                amp_tot = numer / denom
                if amp_tot > 1e2:
                    amp_tot = 1e2
                if amp_mask > 1e2:
                    amp_mask = 1e2
                amp.extend([amp_tot])
                amp.extend([amp_mask])
            else:
                amp.extend([1.0])
                amp.extend([1.0])

    if miriad:
        # save the fits image of the lensed source
        ptag = str(os.getpid())
        SBmapLoc = 'LensedSBmap' + ptag + '.fits'
        fits.writeto(SBmapLoc, g_lensimage_all, header=headmod, clobber=True)

        # convert fits format to miriad format
        SBmapMiriad = 'LensedSBmap' + ptag + '.miriad'
        os.system('rm -rf ' + SBmapMiriad)
        cmd = 'fits op=xyin in=' + SBmapLoc + ' out=' + SBmapMiriad
        call(cmd + ' > /dev/null 2>&1', shell=True)

        # compute simulated visibilities
        modelvisfile = 'SimulatedVisibilities' + ptag + '.miriad'
        call('rm -rf ' + modelvisfile, shell=True)
        cmd = 'uvmodel options=subtract vis=' + visfilemiriad + \
                ' model=' + SBmapMiriad + ' out=' + modelvisfile
        call(cmd + ' > /dev/null 2>&1', shell=True)

        # convert simulated visibilities to uvfits format
        mvuvfits = 'SimulatedVisibilities' + ptag + '.uvfits'
        call('rm -rf ' + mvuvfits, shell=True)
        cmd = 'fits op=uvout in=' + modelvisfile + ' out=' + mvuvfits
        call(cmd + ' > /dev/null 2>&1', shell=True)

        # read simulated visibilities
        mvuv = fits.open(mvuvfits)
        diff_real = mvuv[0].data['DATA'][:, 0, 0, 0, 0, 0]
        diff_imag = mvuv[0].data['DATA'][:, 0, 0, 0, 0, 1]
        wgt = mvuv[0].data['DATA'][:, 0, 0, 0, 0, 2]
        #model_complex = model_real[goodvis] + 1.0j * model_imag[goodvis]
        diff_all = numpy.append(diff_real, diff_imag)
        wgt = numpy.append(wgt, wgt)
        goodvis = wgt > 0
        diff_all = diff_all[goodvis]
        wgt = wgt[goodvis]
        chi2_all = wgt * diff_all * diff_all
    else:
        model_complex = sample_vis.uvmodel(g_lensimage_all, headmod,
                uuu, vvv, pcd)
#        print(vis_complex.shape, model_complex.shape)     # remove
        diff_all = numpy.abs(vis_complex - model_complex)
        chi2_all = wgt * diff_all * diff_all
    #model_real += numpy.real(model_complex)
    #model_imag += numpy.imag(model_complex)

    #fits.writeto('g_lensimage.fits', g_lensimage_all, headmod, clobber=True)
    #import matplotlib.pyplot as plt
    #print(pzero_regions)
    #plt.imshow(g_lensimage, origin='lower')
    #plt.colorbar()
    #plt.show()
    #plt.imshow(g_image, origin='lower')
    #plt.colorbar()
    #plt.show()

    # calculate chi^2 assuming natural weighting
    #fnuisance = 0.0
    #modvariance_real = 1 / wgt #+ fnuisance ** 2 * model_real ** 2
    #modvariance_imag = 1 / wgt #+ fnuisance ** 2 * model_imag ** 2
    #wgt = wgt / 4.
    #chi2_real_all = (real - model_real) ** 2. / modvariance_real
    #chi2_imag_all = (imag - model_imag) ** 2. / modvariance_imag
    #chi2_all = numpy.append(chi2_real_all, chi2_imag_all)

    # compute the sigma term
    #sigmaterm_real = numpy.log(2 * numpy.pi / wgt)
    #sigmaterm_imag = numpy.log(2 * numpy.pi * modvariance_imag)

    # compute the ln likelihood
    lnlikemethod = paramSetup['lnlikemethod']
    if lnlikemethod == 'chi2':
        lnlike = chi2_all
    else:
        # by definition, loglike = -n/2*ln(2pi sigma^2) - 1/(2sigma^2) sum of (data-model)^2 over i=1 to n; but the constant term doesn't matter
        sigmaterm_all = len(wgt) * numpy.log(2 * numpy.pi / wgt)
        lnlike = chi2_all   # + sigmaterm_all
        # * -1/2 factor in latter step

    # compute number of degrees of freedom
    #nmeasure = lnlike.size
    #nparam = (pzero != 0).size
    #ndof = nmeasure - nparam

    # assert that lnlike is equal to -1 * maximum likelihood estimate
    # use visibilities where weight is greater than 0
    #goodvis = wgt > 0
    #likeln = -0.5 * lnlike[goodvis].sum()
    likeln = -0.5 * lnlike.sum()
    #print(pcd, likeln)
    if likeln * 0 != 0:
        likeln = -numpy.inf

    return likeln, amp
Esempio n. 7
0
def lnlike(pzero_regions,
           vis_complex,
           wgt,
           uuu,
           vvv,
           pcd,
           fixindx,
           paramSetup,
           computeamp=True,
           miriad=False):
    """ Function that computes the Ln likelihood of the data"""

    # search poff_models for parameters fixed relative to other parameters
    fixed = (numpy.where(fixindx >= 0))[0]
    nfixed = fixindx[fixed].size
    p_u_regions = paramSetup['p_u']
    poff_regions = p_u_regions.copy()
    poff_regions[:] = 0.
    #for ifix in range(nfixed):
    #    poff_regions[fixed[ifix]] = pzero_regions[fixindx[fixed[ifix]]]
    for ifix in range(nfixed):
        ifixed = fixed[ifix]
        subindx = fixindx[ifixed]
        par0 = 0
        if fixindx[subindx] > 0:
            par0 = pzero_regions[fixindx[subindx]]
        poff_regions[ifixed] = pzero_regions[subindx] + par0

    parameters_regions = pzero_regions + poff_regions

    npar_previous = 0

    amp = []  # Will contain the 'blobs' we compute
    g_image_all = 0.
    g_lensimage_all = 0.
    e_image_all = 0.
    e_lensimage_all = 0.

    nregions = paramSetup['nregions']
    for regioni in range(nregions):

        # get the model info for this model
        x = paramSetup['x'][regioni]
        y = paramSetup['y'][regioni]
        headmod = paramSetup['modelheader'][regioni]
        nlens = paramSetup['nlens_regions'][regioni]
        nsource = paramSetup['nsource_regions'][regioni]
        model_types = paramSetup['model_types'][regioni]

        # get pzero, p_u, and p_l for this specific model
        nparlens = 5 * nlens
        nparsource = 6 * nsource
        npar = nparlens + nparsource + npar_previous
        parameters = parameters_regions[npar_previous:npar]
        npar_previous = npar

        #-----------------------------------------------------------------
        # Create a surface brightness map of lensed emission for the given set
        # of foreground lens(es) and background source parameters.
        #-----------------------------------------------------------------

        g_image, g_lensimage, e_image, e_lensimage, amp_tot, amp_mask = \
                lensutil.sbmap(x, y, nlens, nsource, parameters, model_types,
                computeamp=computeamp)
        e_image_all += e_image
        e_lensimage_all += e_lensimage
        g_image_all += g_image
        g_lensimage_all += g_lensimage
        amp.extend(amp_tot)
        amp.extend(amp_mask)

        # --------------------------------------------------------------------
        # Python version of UVMODEL:
        # "Observe" the lensed emission with the interferometer
        # --------------------------------------------------------------------

        if nlens > 0:
            if computeamp:
                # Evaluate amplification for each region
                lensmask = e_lensimage != 0
                mask = e_image != 0
                numer = g_lensimage[lensmask].sum()
                denom = g_image[mask].sum()
                amp_mask = numer / denom
                numer = g_lensimage.sum()
                denom = g_image.sum()
                amp_tot = numer / denom
                if amp_tot > 1e2:
                    amp_tot = 1e2
                if amp_mask > 1e2:
                    amp_mask = 1e2
                amp.extend([amp_tot])
                amp.extend([amp_mask])
            else:
                amp.extend([1.0])
                amp.extend([1.0])

    if miriad:
        configloc = 'sandbox.yaml'
        configfile = open(configloc, 'r')
        config = yaml.load(configfile)
        visfile = config['UVData']
        index = visfile.index('uvfits')
        visfilemiriad = visfile[0:index] + 'miriad'
        # save the fits image of the lensed source
        ptag = str(os.getpid())
        SBmapLoc = 'LensedSBmap' + ptag + '.fits'
        fits.writeto(SBmapLoc, g_lensimage_all, header=headmod, clobber=True)

        # convert fits format to miriad format
        SBmapMiriad = 'LensedSBmap' + ptag + '.miriad'
        os.system('rm -rf ' + SBmapMiriad)
        cmd = 'fits op=xyin in=' + SBmapLoc + ' out=' + SBmapMiriad
        call(cmd + ' > /dev/null 2>&1', shell=True)

        # compute simulated visibilities
        modelvisfile = 'SimulatedVisibilities' + ptag + '.miriad'
        call('rm -rf ' + modelvisfile, shell=True)
        cmd = 'uvmodel options=subtract vis=' + visfilemiriad + \
                ' model=' + SBmapMiriad + ' out=' + modelvisfile
        call(cmd + ' > /dev/null 2>&1', shell=True)

        # convert simulated visibilities to uvfits format
        mvuvfits = 'SimulatedVisibilities' + ptag + '.uvfits'
        call('rm -rf ' + mvuvfits, shell=True)
        cmd = 'fits op=uvout in=' + modelvisfile + ' out=' + mvuvfits
        call(cmd + ' > /dev/null 2>&1', shell=True)

        # read simulated visibilities
        mvuv = fits.open(mvuvfits)
        diff_real = mvuv[0].data['DATA'][:, 0, 0, 0, 0, 0]
        diff_imag = mvuv[0].data['DATA'][:, 0, 0, 0, 0, 1]
        wgt = mvuv[0].data['DATA'][:, 0, 0, 0, 0, 2]
        #model_complex = model_real[goodvis] + 1.0j * model_imag[goodvis]
        diff_all = numpy.append(diff_real, diff_imag)
        wgt = numpy.append(wgt, wgt)
        goodvis = wgt > 0
        diff_all = diff_all[goodvis]
        wgt = wgt[goodvis]
        chi2_all = wgt * diff_all * diff_all
    else:
        model_complex = sample_vis.uvmodel(g_lensimage_all, headmod, uuu, vvv,
                                           pcd)
        vis_complex -= model_complex
        diff_all = wgt * numpy.abs(vis_complex)**2
        chi2_all = diff_all  #wgt * diff_all * diff_all
        #import pdb; pdb.set_trace()
    #model_real += numpy.real(model_complex)
    #model_imag += numpy.imag(model_complex)

    #fits.writeto('g_lensimage.fits', g_lensimage_all, headmod, clobber=True)
    #import matplotlib.pyplot as plt
    #print(pzero_regions)
    #plt.imshow(g_lensimage, origin='lower')
    #plt.colorbar()
    #plt.show()
    #plt.imshow(g_image, origin='lower')
    #plt.colorbar()
    #plt.show()

    # calculate chi^2 assuming natural weighting
    #fnuisance = 0.0
    #modvariance_real = 1 / wgt #+ fnuisance ** 2 * model_real ** 2
    #modvariance_imag = 1 / wgt #+ fnuisance ** 2 * model_imag ** 2
    #wgt = wgt / 4.
    #chi2_real_all = (real - model_real) ** 2. / modvariance_real
    #chi2_imag_all = (imag - model_imag) ** 2. / modvariance_imag
    #chi2_all = numpy.append(chi2_real_all, chi2_imag_all)

    # compute the sigma term
    #sigmaterm_real = numpy.log(2 * numpy.pi / wgt)
    #sigmaterm_imag = numpy.log(2 * numpy.pi * modvariance_imag)

    # compute the ln likelihood
    lnlikemethod = paramSetup['lnlikemethod']
    if lnlikemethod == 'chi2':
        lnlike = chi2_all
    else:
        sigmaterm_all = 2 * numpy.log(2 * numpy.pi / wgt)
        lnlike = chi2_all + sigmaterm_all

    # compute number of degrees of freedom
    #nmeasure = lnlike.size
    #nparam = (pzero != 0).size
    #ndof = nmeasure - nparam

    # assert that lnlike is equal to -1 * maximum likelihood estimate
    # use visibilities where weight is greater than 0
    #goodvis = wgt > 0
    #likeln = -0.5 * lnlike[goodvis].sum()
    likeln = -0.5 * lnlike.sum()
    #print(pcd, likeln)
    if likeln * 0 != 0:
        likeln = -numpy.inf

    return likeln, amp
Esempio n. 8
0
def log_likelihood_bussman(p, data, sources, xmap, ymap, dx, dy, u, v,
                           lowres_header, phase_center):
    """
    Same as ``log_likelihood_lens`` but borrowing the visibility generation routine from
    Shane Bussman's ``uvmcmcfit``. This one is slower since computes the grid every time and does not
    use rectangular bivariate interpolation. Allegedly implements "optimal gridding" algorithm by Schwab+84.

    NOTE: WE ASSUME ALL 2D ARRAYS TO BE SQUARE

    Parameters
    ----------
    p : array
        Array of proposed MCMC steps. Its length is the numbers of free parameters to fit.

    data : list
        List of ~visilens.VisData objects.

    sources : list
        List of objects of any subclass of
        ~astropy.modeling.models.Fittable2DModel

    xmap : array
        Full resolution array of x-coordinates (+x is West).


    ymap : array
        Full resolution array of y-coordinates (+y is North).

    dx: list
        List of full-resolution x-deflection field arrays.
        Assumes each source has different redshift so
        it must have the same length and same indices as `sources`.
        If two or more source have the same redshift one could
        pass as many copies of the same deflection field
        as needed.

    dy: list
        List of full-resolution y-deflection field arrays.
        Assumes each source has different redshift so
        it must have the same length and same indices as `sources`.
        If two or more source have the same redshift one could
        pass as many copies of the same deflection field
        as needed.

    u: array
        Irregular array of observed *u* coordinates in meters,
        not kilolambda.

    v: array
        Irregular array of observed *v* coordinates in meters,
        not kilolambda.

    lowres_header: FITS header object
        Header specifying the size and pixel scale of the downsampled image. Not necessarily the WCS.

    phase_center: list
        Right ascension and declination of the visibilities phase center, i.e [ra, dec] in degrees.

    """
    source_list = check_priors(p, sources)
    if source_list is None:
        return -np.inf

    logL = 0.0
    for i, dset in enumerate(data):
        npix = lowres_header['NAXIS1']
        immap = create_image(source_list, xmap, ymap, dx, dy)

        # Re-sample while keeping total flux
        pre_sum = np.sum(immap)
        immap = resize(immap, (npix, npix))
        post_sum = np.sum(immap)
        immap *= pre_sum / post_sum

        interpdata = uvmodel(immap, lowres_header, u, v, phase_center)
        logL -= np.sum(np.hypot(dset.real - interpdata.real,
                                dset.imag - interpdata.imag) /\
                      dset.sigma ** 2)
    return logL