Beispiel #1
0
def makeSBmap(config, fitresult):
    """

    Make a surface brightness map of the lensed image for a given set of model
    parameters.

    """

    import lensutil
    from astropy.io import fits
    import os
    import setuputil
    import re
    import numpy

    # Loop over each region

    # read the input parameters
    paramData = setuputil.loadParams(config)
    nlensedsource = paramData['nlensedsource']
    nlensedregions = paramData['nlensedregions']
    npar_previous = 0

    configkeys = config.keys()
    configkeystring = " ".join(configkeys)
    regionlist = re.findall('Region.', configkeystring)
    SBmap_all = 0
    LensedSBmap_all = 0
    nregion = len(regionlist)
    for regioni in range(nregion):
        regstring = 'Region' + str(regioni)
        #indx = paramData['regionlist'].index(regstring)
        cr = config[regstring]

        nmu = 2 * (numpy.array(nlensedsource).sum() + nlensedregions)
        if nmu > 0:
            allparameters0 = list(fitresult)[1:-nmu]
        else:
            allparameters0 = list(fitresult)[1:]

        # search poff_models for parameters fixed relative to other parameters
        fixindx = setuputil.fixParams(paramData)
        poff = paramData['poff']
        ndim_total = len(poff)
        fixed = (numpy.where(fixindx >= 0))[0]
        nfixed = fixindx[fixed].size
        parameters_offset = numpy.zeros(ndim_total)
        for ifix in range(nfixed):
            ifixed = fixed[ifix]
            subindx = fixindx[ifixed]
            par0 = 0
            if fixindx[subindx] > 0:
                par0 = fitresult[fixindx[subindx] + 1]
            parameters_offset[ifixed] = fitresult[subindx + 1] + par0

        allparameters = allparameters0 + parameters_offset

        # count the number of lenses
        configkeys = cr.keys()
        configkeystring = " ".join(configkeys)
        lenslist = re.findall('Lens.', configkeystring)
        nlens = len(lenslist)

        # count the number of sources
        sourcelist = re.findall('Source.', configkeystring)
        nsource = len(sourcelist)

        nparperlens = 5
        nparpersource = 6
        nparlens = nparperlens * nlens
        nparsource = nparpersource * nsource
        npar = nparlens + nparsource + npar_previous
        parameters = allparameters[npar_previous:npar]
        npar_previous = npar

        #nlens = paramData['nlens_regions'][indx]
        #nsource = paramData['nsource_regions'][indx]
        x = paramData['x'][regioni]
        y = paramData['y'][regioni]
        modelheader = paramData['modelheader'][regioni]
        model_types = paramData['model_types'][regioni]

        SBmap, LensedSBmap, Aperture, LensedAperture, mu_tot, mu_mask = \
                lensutil.sbmap(x, y, nlens, nsource, parameters, model_types, \
                computeamp=True)

        caustics = False
        if caustics:
            deltapar = parameters[0:nparlens + nparpersource]
            refine = 2
            nx = x[:, 0].size * refine
            ny = y[:, 0].size * refine
            x1 = x[0, :].min()
            x2 = x[0, :].max()
            linspacex = numpy.linspace(x1, x2, nx)
            y1 = y[:, 0].min()
            y2 = y[:, 0].max()
            linspacey = numpy.linspace(y1, y2, ny)
            onex = numpy.ones(nx)
            oney = numpy.ones(ny)
            finex = numpy.outer(oney, linspacex)
            finey = numpy.outer(linspacey, onex)

            mumap = numpy.zeros([ny, nx])
            for ix in range(nx):
                for iy in range(ny):
                    deltapar[-nparpersource + 0] = finex[ix, iy]
                    deltapar[-nparpersource + 1] = finey[ix, iy]
                    xcell = paramData['celldata']
                    deltapar[-nparpersource + 2] = xcell
                    deltaunlensed, deltalensed, A1, A2, mu_xy, mu_xymask = \
                            lensutil.sbmap(finex, finey, nlens, 1, deltapar, ['Delta'])
                    mumap[ix, iy] = mu_xy[0]

            import matplotlib.pyplot as plt
            plt.imshow(mumap, origin='lower')
            plt.contour(mumap, levels=[mumap.max() / 1.1])
            import pdb
            pdb.set_trace()
        SBmap_all += SBmap
        LensedSBmap_all += LensedSBmap

    LensedSBmapLoc = 'LensedSBmap.fits'
    SBmapLoc = 'SBmap_Region.fits'
    cmd = 'rm -rf ' + LensedSBmapLoc + ' ' + SBmapLoc
    os.system(cmd)

    fits.writeto(LensedSBmapLoc, LensedSBmap_all, modelheader)
    fits.writeto(SBmapLoc, SBmap_all, modelheader)

    return
Beispiel #2
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
Beispiel #3
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
Beispiel #4
0
    crpix2 = nymod / 2 + 1
    cdelt1 = -1 * celldata / 3600 / oversample
    cdelt2 = celldata / 3600 / oversample    
    modelheader.update('naxis1', nxmod)
    modelheader.update('cdelt1', cdelt1)
    modelheader.update('crpix1', crpix1)
    modelheader.update('crval1', ra_centroid)
    modelheader.update('ctype1', 'RA---SIN')
    modelheader.update('naxis2', nymod)
    modelheader.update('cdelt2', cdelt2)
    modelheader.update('crpix2', crpix2)
    modelheader.update('crval2', dec_centroid)
    modelheader.update('ctype2', 'DEC--SIN')

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

    #--------------------------------------------------------------------------
    # Compute magnification
    numer = g_lensimage.sum()
    denom = g_image.sum()
    mu_fluxratio = numer / denom
    print 'F_out / F_in = ', mu_fluxratio
    #--------------------------------------------------------------------------

    # write the lensed and unlensed surface brightness maps to disk
    outfits = 'sbmap_image_Region' + sri + '.fits'
    outfits_miriad = 'sbmap_image' + sri
    outfits_unlens = 'sbmap_source' + sri + '.fits'
    os.system('rm -rf ' + outfits)
    os.system('rm -rf ' + outfits_unlens)
Beispiel #5
0
def makeSBmap(config, fitresult):

    """

    Make a surface brightness map of the lensed image for a given set of model
    parameters.

    """

    import lensutil
    from astropy.io import fits
    import os
    import setuputil
    import re
    import numpy


    # Loop over each region

    # read the input parameters
    paramData = setuputil.loadParams(config)
    nlensedsource = paramData['nlensedsource']
    nlensedregions = paramData['nlensedregions']
    npar_previous = 0

    configkeys = config.keys()
    configkeystring = " ".join(configkeys)
    regionlist = re.findall('Region.', configkeystring)
    SBmap_all = 0
    LensedSBmap_all = 0
    nregion = len(regionlist)
    for regioni in range(nregion):
        regstring = 'Region' + str(regioni)
        #indx = paramData['regionlist'].index(regstring)
        cr = config[regstring]

        nmu = 2 * (numpy.array(nlensedsource).sum() + nlensedregions)
        if nmu > 0:
            allparameters0 = list(fitresult)[1:-nmu]
        else:
            allparameters0 = list(fitresult)[1:]

        # search poff_models for parameters fixed relative to other parameters
        fixindx = setuputil.fixParams(paramData)
        poff = paramData['poff']
        ndim_total = len(poff)
        fixed = (numpy.where(fixindx >= 0))[0]
        nfixed = fixindx[fixed].size
        parameters_offset = numpy.zeros(ndim_total)
        for ifix in range(nfixed):
            ifixed = fixed[ifix]
            subindx = fixindx[ifixed]
            par0 = 0
            if fixindx[subindx] > 0:
                par0 = fitresult[fixindx[subindx] + 1]
            parameters_offset[ifixed] = fitresult[subindx + 1] + par0

        allparameters = allparameters0 + parameters_offset

        # count the number of lenses
        configkeys = cr.keys()
        configkeystring = " ".join(configkeys)
        lenslist = re.findall('Lens.', configkeystring)
        nlens = len(lenslist)

        # count the number of sources
        sourcelist = re.findall('Source.', configkeystring)
        nsource = len(sourcelist)

        nparperlens = 5
        nparpersource = 6
        nparlens = nparperlens * nlens
        nparsource = nparpersource * nsource
        npar = nparlens + nparsource + npar_previous
        parameters = allparameters[npar_previous:npar]
        npar_previous = npar

        #nlens = paramData['nlens_regions'][indx]
        #nsource = paramData['nsource_regions'][indx]
        x = paramData['x'][regioni]
        y = paramData['y'][regioni]
        modelheader = paramData['modelheader'][regioni]
        model_types = paramData['model_types'][regioni]

        SBmap, LensedSBmap, Aperture, LensedAperture, mu_tot, mu_mask = \
                lensutil.sbmap(x, y, nlens, nsource, parameters, model_types, \
                computeamp=True)

        caustics = False
        if caustics:
            deltapar = parameters[0:nparlens + nparpersource]
            refine = 2
            nx = x[:, 0].size * refine
            ny = y[:, 0].size * refine
            x1 = x[0, :].min()
            x2 = x[0, :].max()
            linspacex = numpy.linspace(x1, x2, nx)
            y1 = y[:, 0].min()
            y2 = y[:, 0].max()
            linspacey = numpy.linspace(y1, y2, ny)
            onex = numpy.ones(nx)
            oney = numpy.ones(ny)
            finex = numpy.outer(oney, linspacex)
            finey = numpy.outer(linspacey, onex)
            
            mumap = numpy.zeros([ny, nx])
            for ix in range(nx):
                for iy in range(ny):
                    deltapar[-nparpersource + 0] = finex[ix, iy]
                    deltapar[-nparpersource + 1] = finey[ix, iy]
                    xcell = paramData['celldata']
                    deltapar[-nparpersource + 2] = xcell
                    deltaunlensed, deltalensed, A1, A2, mu_xy, mu_xymask = \
                            lensutil.sbmap(finex, finey, nlens, 1, deltapar, ['Delta'])
                    mumap[ix, iy] = mu_xy[0]

            import matplotlib.pyplot as plt
            plt.imshow(mumap, origin='lower')
            plt.contour(mumap, levels=[mumap.max()/1.1])
            import pdb; pdb.set_trace()
        SBmap_all += SBmap
        LensedSBmap_all += LensedSBmap

    LensedSBmapLoc = 'LensedSBmap.fits'
    SBmapLoc = 'SBmap_Region.fits'
    cmd = 'rm -rf ' + LensedSBmapLoc + ' ' + SBmapLoc
    os.system(cmd)

    fits.writeto(LensedSBmapLoc, LensedSBmap_all, modelheader)
    fits.writeto(SBmapLoc, SBmap_all, modelheader)

    return
Beispiel #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 = 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