コード例 #1
0
    def from_txt(self, fname, style='difmap'):
        """
        Function that reads TXT-files with models in difmap or AIPS format.

        :param fname:
            File with components.
        :param style: (optional)
            Style of model file. ``difmap`` or ``aips``. (default: ``difmap``)
        """
        if style not in ['difmap', 'aips']:
            raise Exception
        if style == 'aips':
            raise NotImplementedError
        mdlo = open(fname)
        lines = mdlo.readlines()
        comps = list()
        for line in lines:
            if line.startswith('!'):
                continue
            line = line.strip('\n ')
            flux, radius, theta, major, axial, phi, type_, freq, spec =\
                line.split()
            x = -float(radius[:-1]) * np.sin(np.deg2rad(float(theta[:-1])))
            y = -float(radius[:-1]) * np.cos(np.deg2rad(float(theta[:-1])))
            flux = float(flux[:-1])
            if int(type_) == 0:
                comp = DeltaComponent(flux, x, y)
            elif int(type_) == 1:
                try:
                    bmaj = float(major)
                except ValueError:
                    bmaj = float(major[:-1])
                if float(axial[:-1]) == 1:
                    comp = CGComponent(flux, x, y, bmaj)
                else:
                    try:
                        e = float(axial)
                    except ValueError:
                        e = float(axial[:-1])
                    try:
                        bpa = -np.deg2rad(float(phi)) + np.pi / 2.
                    except ValueError:
                        bpa = -np.deg2rad(float(phi[:-1])) + np.pi / 2.
                    comp = EGComponent(flux, x, y, bmaj, e, bpa)
            else:
                raise NotImplementedError("Only CC, CG & EG are implemented")
            comps.append(comp)
        self.add_components(comps)
コード例 #2
0
ファイル: spydiff.py プロジェクト: akutkin/SACA
def sum_components(comp0, comp1, type="eg"):
    print("Summing components {} and {}".format(comp0, comp1))
    flux = comp0.p[0] + comp1.p[0]
    x = (comp0.p[0] * comp0.p[1] + comp1.p[0] * comp1.p[1]) / flux
    y = (comp0.p[0] * comp0.p[2] + comp1.p[0] * comp1.p[2]) / flux
    bmaj = (comp0.p[0] * comp0.p[3] + comp1.p[0] * comp1.p[3]) / flux
    if type == "cg":
        component = CGComponent(flux, x, y, bmaj)
    elif type == "eg":
        dx = comp0.p[1] - comp1.p[1]
        dy = comp0.p[2] - comp1.p[2]
        bpa = 180 * np.arctan(dx / dy) / np.pi
        e = 0.5 * (comp0.p[3] + comp1.p[3]) / np.hypot(comp0.p[1] - comp1.p[1],
                                                       comp0.p[2] - comp1.p[2])
        component = EGComponent(flux, x, y, bmaj, e, bpa)
    else:
        raise Exception
    print("Sum = {}".format(component))
    return component
コード例 #3
0

if __name__ == '__main__':
    # Test LS_estimates
    import sys
    from components import CGComponent, EGComponent
    from uv_data import UVData
    from model import Model
    try:
        from scipy.optimize import minimize, fmin
    except ImportError:
        sys.exit("install scipy for ml estimation")
    uv_fname = '/home/ilya/vlbi_errors/examples/L/1633+382/1633+382.l18.2010_05_21.uvf'
    uvdata = UVData(uv_fname)
    # Create model
    cg1 = EGComponent(1.0, -0.8, 0.2, .7, 0.5, 0)
    cg2 = CGComponent(0.8, 2.0, -.3, 2.3)
    cg3 = CGComponent(0.2, 5.0, .0, 2.)
    mdl = Model(stokes='I')
    mdl.add_components(cg1, cg2, cg3)
    # Create log of likelihood function
    lnlik = LnLikelihood(uvdata, mdl, average_freq=True, amp_only=False)
    # Nelder-Mead simplex algorithm
    p_ml = fmin(lambda p: -lnlik(p), mdl.p)
    # Various methods of minimization (some require jacobians)
    # TODO: Implement analitical grad of likelihood (it's gaussian)
    fit = minimize(lambda p: -lnlik(p),
                   mdl.p,
                   method='L-BFGS-B',
                   options={
                       'maxiter': 30000,
コード例 #4
0
ファイル: test_ft.py プロジェクト: akutkin/SACA
import os
import copy
from astropy.io import fits as pf
from uv_data import UVData
from model import Model
from components import EGComponent, CGComponent
from spydiff import modelfit_difmap, import_difmap_model

data_dir = '/home/ilya/code/vlbi_errors/tests/ft'
uv_fits = '1308+326.U1.2009_08_28.UV_CAL'
hdus_orig = pf.open(os.path.join(data_dir, uv_fits))
print "orig", hdus_orig[0].data[0][0]
uvdata = UVData(os.path.join(data_dir, uv_fits))
noise = uvdata.noise(use_V=False)
# noise = {bl: 0.1*noise_ for bl, noise_ in noise.items()}
eg1 = EGComponent(5., 0, 0, 0.15, 0.33, 0.2)
eg2 = EGComponent(2.5, 1, 1, 0.5, 0.5, 0.)
model = Model(stokes='I')
model.add_components(eg1, eg2)
# model.add_components(eg1, eg2)
uvdata_c = copy.deepcopy(uvdata)
uvdata_c.substitute([model])
uvdata_c.noise_add(noise)
uvdata_c.save(os.path.join(data_dir, 'fake.fits'), rewrite=True)
modelfit_difmap('fake.fits',
                'mod_c2_2ee.mdl',
                'out_2c.mdl',
                path=data_dir,
                mdl_path=data_dir,
                out_path=data_dir,
                niter=100)
コード例 #5
0
    # uv_fits_file = '1038+064.l22.2010_05_21.uvf'
    # ccmodel = CCModel(stokes='I')
    # ccmodel.add_cc_from_fits(cc_fits_file)
    # uvdata = create_uvdata_from_fits_file(uv_fits_file)
    # uv = uvdata.uvw[:, :2]
    # ft = ccmodel.ft(uv)
    # ccmodel.uvplot(uv)

    # TESTING fitting gaussian components to uv-data
    # Load uv-data
    from uv_data import UVData
    uvdata = UVData('1308+326.U1.2009_08_28.UV_CAL')
    uv = uvdata.uvw[:, :2]
    #twickle
    # Create several components
    cg1 = EGComponent(2.44, 0.02, -0.02, 0.10, 0.5, -1.)
    cg2 = CGComponent(0.041, 0.71, -1.05, 1.18)
    cg3 = CGComponent(0.044, 2.60, -3.20, 0.79)
    cg4 = CGComponent(0.021, 1.50, -5.60, 2.08)
    cg1.add_prior(flux=(
        sp.stats.uniform.logpdf,
        [0., 3.],
        dict(),
    ),
                  bmaj=(
                      sp.stats.uniform.logpdf,
                      [0, 1.],
                      dict(),
                  ),
                  e=(
                      sp.stats.uniform.logpdf,
コード例 #6
0
ファイル: spydiff.py プロジェクト: akutkin/SACA
def import_difmap_model(mdl_fname, mdl_dir=None):
    """
    Function that reads difmap-format model and returns list of ``Components``
    instances.

    :param mdl_fname:
        File name with difmap model.
    :param mdl_dir: (optional)
        Directory with difmap model. If ``None`` then use CWD. (default:
        ``None``)
    :return:
        List of ``Components`` instances.
    """
    if mdl_dir is None:
        mdl_dir = os.getcwd()
    mdl = os.path.join(mdl_dir, mdl_fname)
    mdlo = open(mdl)
    lines = mdlo.readlines()
    comps = list()
    for line in lines:
        if line.startswith('!'):
            continue
        line = line.strip('\n ')
        try:
            flux, radius, theta, major, axial, phi, type_, freq, spec = line.split(
            )
        except ValueError:
            try:
                flux, radius, theta, major, axial, phi, type_ = line.split()
            except ValueError:
                try:
                    flux, radius, theta = line.split()
                except ValueError:
                    print "Problem parsing line :\n"
                    print line
                    raise ValueError
                axial = 1.0
                major = 0.0
                type_ = 0

        list_fixed = list()
        if flux[-1] != 'v':
            list_fixed.append('flux')

        x = -float(radius[:-1]) * np.sin(np.deg2rad(float(theta[:-1])))
        y = -float(radius[:-1]) * np.cos(np.deg2rad(float(theta[:-1])))
        flux = float(flux[:-1])

        if int(type_) == 0:
            comp = DeltaComponent(flux, x, y)
        elif int(type_) == 1:

            try:
                bmaj = float(major)
                list_fixed.append('bmaj')
            except ValueError:
                bmaj = float(major[:-1])
            if float(axial[:-1]) == 1:
                comp = CGComponent(flux, x, y, bmaj, fixed=list_fixed)
            else:
                try:
                    e = float(axial)
                except ValueError:
                    e = float(axial[:-1])
                try:
                    bpa = np.deg2rad(float(phi)) + np.pi / 2.
                except ValueError:
                    bpa = np.deg2rad(float(phi[:-1])) + np.pi / 2.
                comp = EGComponent(flux, x, y, bmaj, e, bpa, fixed=list_fixed)
        else:
            raise NotImplementedError("Only CC, CG & EG are implemented")
        comps.append(comp)
    return comps
コード例 #7
0
import os
from uv_data import UVData
from model import Model
from stats import LnPost
from components import EGComponent
import emcee
import corner
import matplotlib.pyplot as plt
import scipy as sp
import numpy as np

data_dir = '/home/ilya/Dropbox/ACC/BK/simulations/0952'
uv_fits = '0952_15GHz_BK.fits'
eg = EGComponent(10., 0., 0., 0.3, 0.5, 1.)
eg.add_prior(flux=(
    sp.stats.uniform.logpdf,
    [0., 30.],
    dict(),
),
             bmaj=(
                 sp.stats.uniform.logpdf,
                 [0, 3.],
                 dict(),
             ),
             e=(
                 sp.stats.uniform.logpdf,
                 [0, 1.],
                 dict(),
             ),
             bpa=(
                 sp.stats.uniform.logpdf,
コード例 #8
0
ファイル: test_mcmc.py プロジェクト: akutkin/SACA
except ImportError:
    sys.exit("install scipy for ml estimation")
import scipy as sp
from stats import LnLikelihood, LnPost
from image import find_bbox
from image import plot as iplot
from image_ops import rms_image
import emcee
import corner

data_dir = '/home/ilya/Dropbox/Ilya/0235_bk150_uvf_data/'
uv_fname = '1803+784.u.2012_11_28.uvf'

uvdata = UVData(os.path.join(data_dir, uv_fname))
noise = uvdata.noise()
cg1 = EGComponent(2., 0., 0., 0.15, 0.33, 0.3)
cg1.add_prior(flux=(
    sp.stats.uniform.logpdf,
    [0., 5.],
    dict(),
),
              bmaj=(
                  sp.stats.uniform.logpdf,
                  [0, 20.],
                  dict(),
              ),
              e=(
                  sp.stats.uniform.logpdf,
                  [0, 1.],
                  dict(),
              ),