Example #1
0
def make_psf(vis_mxds, img_xds, grid_parms, vis_sel_parms, img_sel_parms):
    """
    Creates a cube or continuum point spread function (psf) image from the user specified uvw and imaging weight data. Only the prolate spheroidal convolutional gridding function is supported (this will change in a future releases.)
    
    Parameters
    ----------
    vis_mxds : xarray.core.dataset.Dataset
        Input multi-xarray Dataset with global data.
    img_xds : xarray.core.dataset.Dataset
        Input image dataset.
    grid_parms : dictionary
    grid_parms['image_size'] : list of int, length = 2
        The image size (no padding).
    grid_parms['cell_size']  : list of number, length = 2, units = arcseconds
        The image cell size.
    grid_parms['chan_mode'] : {'continuum'/'cube'}, default = 'continuum'
        Create a continuum or cube image.
    grid_parms['fft_padding'] : number, acceptable range [1,100], default = 1.2
        The factor that determines how much the gridded visibilities are padded before the fft is done.
    vis_sel_parms : dictionary
    vis_sel_parms['xds'] : str
        The xds within the mxds to use to calculate the imaging weights for.
    vis_sel_parms['data_group_in_id'] : int, default = first id in xds.data_groups
        The data group in the xds to use.
    img_sel_parms : dictionary
    img_sel_parms['data_group_in_id'] : int, default = first id in xds.data_groups
        The data group in the image xds to use.
    img_sel_parms['psf'] : str, default ='PSF'
        The created image name.
    img_sel_parms['psf_sum_weight'] : str, default ='PSF_SUM_WEIGHT'
        The created sum of weights name.
    Returns
    -------
    img_xds : xarray.core.dataset.Dataset
        The image_dataset will contain the image created and the sum of weights.
    """
    print('######################### Start make_psf #########################')
    import numpy as np
    from numba import jit
    import time
    import math
    import dask.array.fft as dafft
    import xarray as xr
    import dask.array as da
    import matplotlib.pylab as plt
    import dask
    import copy, os
    from numcodecs import Blosc
    from itertools import cycle
    
    from cngi._utils._check_parms import _check_sel_parms, _check_existence_sel_parms
    from ._imaging_utils._check_imaging_parms import _check_grid_parms
    from ._imaging_utils._gridding_convolutional_kernels import _create_prolate_spheroidal_kernel, _create_prolate_spheroidal_kernel_1D
    from ._imaging_utils._standard_grid import _graph_standard_grid
    from ._imaging_utils._remove_padding import _remove_padding
    from ._imaging_utils._aperture_grid import _graph_aperture_grid
    from cngi.image import make_empty_sky_image
    from cngi.image import fit_gaussian
    
    #print('****',sel_parms,'****')
    _mxds = vis_mxds.copy(deep=True)
    _img_xds = img_xds.copy(deep=True)
    _vis_sel_parms = copy.deepcopy(vis_sel_parms)
    _img_sel_parms = copy.deepcopy(img_sel_parms)
    _grid_parms = copy.deepcopy(grid_parms)

    ##############Parameter Checking and Set Defaults##############
    assert(_check_grid_parms(_grid_parms)), "######### ERROR: grid_parms checking failed"
    assert('xds' in _vis_sel_parms), "######### ERROR: xds must be specified in sel_parms" #Can't have a default since xds names are not fixed.
    _vis_xds = _mxds.attrs[_vis_sel_parms['xds']]
    
    #Check vis data_group
    _check_sel_parms(_vis_xds,_vis_sel_parms)
    
    #Check img data_group
    _check_sel_parms(_img_xds,_img_sel_parms,new_or_modified_data_variables={'sum_weight':'PSF_SUM_WEIGHT','psf':'PSF','psf_fit':'PSF_FIT'},append_to_in_id=True)

    ##################################################################################
    
    # Creating gridding kernel
    _grid_parms['oversampling'] = 100
    _grid_parms['support'] = 7
    
    cgk, correcting_cgk_image = _create_prolate_spheroidal_kernel(_grid_parms['oversampling'], _grid_parms['support'], _grid_parms['image_size_padded'])
    cgk_1D = _create_prolate_spheroidal_kernel_1D(_grid_parms['oversampling'], _grid_parms['support'])
    
    _grid_parms['complex_grid'] = False
    _grid_parms['do_psf'] = True
    _grid_parms['do_imaging_weight'] = False
    grids_and_sum_weights = _graph_standard_grid(_vis_xds, cgk_1D, _grid_parms, _vis_sel_parms)
    uncorrected_dirty_image = dafft.fftshift(dafft.ifft2(dafft.ifftshift(grids_and_sum_weights[0], axes=(0, 1)), axes=(0, 1)), axes=(0, 1))
    
    #Remove Padding
    correcting_cgk_image = _remove_padding(correcting_cgk_image,_grid_parms['image_size'])
    uncorrected_dirty_image = _remove_padding(uncorrected_dirty_image,_grid_parms['image_size']).real * (_grid_parms['image_size_padded'][0] * _grid_parms['image_size_padded'][1])
    
    #############Normalize#############
    def correct_image(uncorrected_dirty_image, sum_weights, correcting_cgk):
        sum_weights_copy = copy.deepcopy(sum_weights) ##Don't mutate inputs, therefore do deep copy (https://docs.dask.org/en/latest/delayed-best-practices.html).
        sum_weights_copy[sum_weights_copy == 0] = 1
        # corrected_image = (uncorrected_dirty_image/sum_weights[:,:,None,None])/correcting_cgk[None,None,:,:]
        corrected_image = (uncorrected_dirty_image / sum_weights_copy) / correcting_cgk
        return corrected_image

    corrected_dirty_image = da.map_blocks(correct_image, uncorrected_dirty_image, grids_and_sum_weights[1][None, None, :, :],correcting_cgk_image[:, :, None, None])
    ####################################################

    if _grid_parms['chan_mode'] == 'continuum':
        freq_coords = [da.mean(_vis_xds.coords['chan'].values)]
        chan_width = da.from_array([da.mean(_vis_xds['chan_width'].data)],chunks=(1,))
        imag_chan_chunk_size = 1
    elif _grid_parms['chan_mode'] == 'cube':
        freq_coords = _vis_xds.coords['chan'].values
        chan_width = _vis_xds['chan_width'].data
        imag_chan_chunk_size = _vis_xds.DATA.chunks[2][0]
    
    phase_center = _grid_parms['phase_center']
    image_size = _grid_parms['image_size']
    cell_size = _grid_parms['cell_size']
    phase_center = _grid_parms['phase_center']

    pol_coords = _vis_xds.pol.data
    time_coords = [_vis_xds.time.mean().data]
    
    _img_xds = make_empty_sky_image(_img_xds,phase_center,image_size,cell_size,freq_coords,chan_width,pol_coords,time_coords)
    
    
    
    _img_xds[_img_sel_parms['data_group_out']['sum_weight']] = xr.DataArray(grids_and_sum_weights[1][None,:,:], dims=['time','chan','pol'])
    _img_xds[_img_sel_parms['data_group_out']['psf']] = xr.DataArray(corrected_dirty_image[:,:,None,:,:], dims=['l', 'm', 'time', 'chan', 'pol'])
    _img_xds.attrs['data_groups'][0] = {**_img_xds.attrs['data_groups'][0],**{_img_sel_parms['data_group_out']['id']:_img_sel_parms['data_group_out']}}
    
    _img_xds = fit_gaussian(_img_xds,dv=_img_sel_parms['data_group_out']['psf'],beam_set_name=_img_sel_parms['data_group_out']['psf_fit'])

    
    print('######################### Created graph for make_psf #########################')
    return _img_xds
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    '''
Example #2
0
def make_psf_with_gcf(mxds, gcf_dataset, img_dataset, grid_parms, norm_parms,
                      vis_sel_parms, img_sel_parms):
    """
    Creates a cube or continuum dirty image from the user specified visibility, uvw and imaging weight data. A gridding convolution function (gcf_dataset), primary beam image (img_dataset) and a primary beam weight image (img_dataset) must be supplied.
    
    Parameters
    ----------
    vis_dataset : xarray.core.dataset.Dataset
        Input visibility dataset.
    gcf_dataset : xarray.core.dataset.Dataset
         Input gridding convolution dataset.
    img_dataset : xarray.core.dataset.Dataset
         Input image dataset.
    grid_parms : dictionary
    grid_parms['image_size'] : list of int, length = 2
        The image size (no padding).
    grid_parms['cell_size']  : list of number, length = 2, units = arcseconds
        The image cell size.
    grid_parms['chan_mode'] : {'continuum'/'cube'}, default = 'continuum'
        Create a continuum or cube image.
    grid_parms['fft_padding'] : number, acceptable range [1,100], default = 1.2
        The factor that determines how much the gridded visibilities are padded before the fft is done.
    norm_parms : dictionary
    norm_parms['norm_type'] : {'none'/'flat_noise'/'flat_sky'}, default = 'flat_sky'
         Gridded (and FT'd) images represent the PB-weighted sky image.
         Qualitatively it can be approximated as two instances of the PB
         applied to the sky image (one naturally present in the data
         and one introduced during gridding via the convolution functions).
         normtype='flat_noise' : Divide the raw image by sqrt(sel_parms['weight_pb']) so that
                                             the input to the minor cycle represents the
                                             product of the sky and PB. The noise is 'flat'
                                             across the region covered by each PB.
        normtype='flat_sky' : Divide the raw image by sel_parms['weight_pb'] so that the input
                                         to the minor cycle represents only the sky.
                                         The noise is higher in the outer regions of the
                                         primary beam where the sensitivity is low.
        normtype='none' : No normalization after gridding and FFT.
    sel_parms : dictionary
    sel_parms['uvw'] : str, default ='UVW'
        The name of uvw data variable that will be used to grid the visibilities.
    sel_parms['data'] : str, default = 'DATA'
        The name of the visibility data to be gridded.
    sel_parms['imaging_weight'] : str, default ='IMAGING_WEIGHT'
        The name of the imaging weights to be used.
    sel_parms['image'] : str, default ='IMAGE'
        The created image name.
    sel_parms['sum_weight'] : str, default ='SUM_WEIGHT'
        The created sum of weights name.
    sel_parms['pb'] : str, default ='PB'
         The primary beam image to use for normalization.
    sel_parms['weight_pb'] : str, default ='WEIGHT_PB'
         The primary beam weight image to use for normalization.
    Returns
    -------
    image_dataset : xarray.core.dataset.Dataset
        The image_dataset will contain the image created and the sum of weights.
    """
    print(
        '######################### Start make_psf_with_gcf #########################'
    )
    import numpy as np
    from numba import jit
    import time
    import math
    import dask.array.fft as dafft
    import xarray as xr
    import dask.array as da
    import matplotlib.pylab as plt
    import dask
    import copy, os
    from numcodecs import Blosc
    from itertools import cycle

    from cngi._utils._check_parms import _check_sel_parms, _check_existence_sel_parms
    from ._imaging_utils._check_imaging_parms import _check_grid_parms, _check_norm_parms
    #from ._imaging_utils._gridding_convolutional_kernels import _create_prolate_spheroidal_kernel, _create_prolate_spheroidal_kernel_1D
    from ._imaging_utils._standard_grid import _graph_standard_grid
    from ._imaging_utils._remove_padding import _remove_padding
    from ._imaging_utils._aperture_grid import _graph_aperture_grid
    from ._imaging_utils._normalize import _normalize
    from cngi.image import make_empty_sky_image
    from cngi.image import fit_gaussian

    #Deep copy so that inputs are not modified
    _mxds = mxds.copy(deep=True)
    _img_dataset = img_dataset.copy(deep=True)
    _vis_sel_parms = copy.deepcopy(vis_sel_parms)
    _img_sel_parms = copy.deepcopy(img_sel_parms)
    _grid_parms = copy.deepcopy(grid_parms)
    _norm_parms = copy.deepcopy(norm_parms)

    ##############Parameter Checking and Set Defaults##############
    assert (
        'xds' in _vis_sel_parms
    ), "######### ERROR: xds must be specified in sel_parms"  #Can't have a default since xds names are not fixed.
    _vis_dataset = _mxds.attrs[_vis_sel_parms['xds']]

    assert (_check_grid_parms(_grid_parms)
            ), "######### ERROR: grid_parms checking failed"
    assert (_check_norm_parms(_norm_parms)
            ), "######### ERROR: norm_parms checking failed"

    #Check vis data_group
    _check_sel_parms(_vis_dataset, _vis_sel_parms)

    #Check img data_group

    _check_sel_parms(_img_dataset,
                     _img_sel_parms,
                     new_or_modified_data_variables={
                         'sum_weight': 'PSF_SUM_WEIGHT',
                         'psf': 'PSF',
                         'psf_fit': 'PSF_FIT'
                     },
                     required_data_variables={
                         'pb': 'PB',
                         'weight_pb': 'WEIGHT_PB'
                     },
                     append_to_in_id=False)
    #'pb':'PB','weight_pb':'WEIGHT_PB',
    #print('did this work',_img_sel_parms)

    _grid_parms['grid_weights'] = False
    _grid_parms['do_psf'] = True
    _grid_parms['oversampling'] = np.array(gcf_dataset.oversampling)

    grids_and_sum_weights = _graph_aperture_grid(_vis_dataset, gcf_dataset,
                                                 _grid_parms, _vis_sel_parms)
    uncorrected_dirty_image = dafft.fftshift(dafft.ifft2(dafft.ifftshift(
        grids_and_sum_weights[0], axes=(0, 1)),
                                                         axes=(0, 1)),
                                             axes=(0, 1))

    #Remove Padding
    #print('grid sizes',_grid_parms['image_size_padded'][0], _grid_parms['image_size_padded'][1])
    uncorrected_dirty_image = _remove_padding(
        uncorrected_dirty_image, _grid_parms['image_size']).real * (
            _grid_parms['image_size_padded'][0] *
            _grid_parms['image_size_padded'][1])

    #print(_img_sel_parms)
    normalized_image = _normalize(uncorrected_dirty_image,
                                  grids_and_sum_weights[1], img_dataset,
                                  gcf_dataset, 'forward', _norm_parms,
                                  _img_sel_parms)

    normalized_image = normalized_image / normalized_image[
        _grid_parms['image_center'][0], _grid_parms['image_center'][1], :, :]

    if _grid_parms['chan_mode'] == 'continuum':
        freq_coords = [da.mean(_vis_dataset.coords['chan'].values)]
        chan_width = da.from_array([da.mean(_vis_dataset['chan_width'].data)],
                                   chunks=(1, ))
        imag_chan_chunk_size = 1
    elif _grid_parms['chan_mode'] == 'cube':
        freq_coords = _vis_dataset.coords['chan'].values
        chan_width = _vis_dataset['chan_width'].data
        imag_chan_chunk_size = _vis_dataset.DATA.chunks[2][0]

    ###Create Image Dataset
    chunks = _vis_dataset.DATA.chunks
    n_imag_pol = chunks[3][0]

    #coords = {'d0': np.arange(_grid_parms['image_size'][0]), 'd1': np.arange(_grid_parms['image_size'][1]),
    #          'chan': freq_coords, 'pol': np.arange(n_imag_pol), 'chan_width' : ('chan',chan_width)}
    #img_dataset = img_dataset.assign_coords(coords)
    #img_dataset[_sel_parms['sum_weight']] = xr.DataArray(grids_and_sum_weights[1], dims=['chan','pol'])
    #img_dataset[_sel_parms['image']] = xr.DataArray(normalized_image, dims=['d0', 'd1', 'chan', 'pol'])

    phase_center = _grid_parms['phase_center']
    image_size = _grid_parms['image_size']
    cell_size = _grid_parms['cell_size']
    phase_center = _grid_parms['phase_center']

    pol_coords = _vis_dataset.pol.data
    time_coords = [_vis_dataset.time.mean().data]

    _img_dataset = make_empty_sky_image(_img_dataset, phase_center, image_size,
                                        cell_size, freq_coords, chan_width,
                                        pol_coords, time_coords)

    _img_dataset[_img_sel_parms['data_group_out']
                 ['sum_weight']] = xr.DataArray(
                     grids_and_sum_weights[1][None, :, :],
                     dims=['time', 'chan', 'pol'])
    _img_dataset[_img_sel_parms['data_group_out']['psf']] = xr.DataArray(
        normalized_image[:, :, None, :, :],
        dims=['l', 'm', 'time', 'chan', 'pol'])
    _img_dataset.attrs['data_groups'][0] = {
        **_img_dataset.attrs['data_groups'][0],
        **{
            _img_sel_parms['data_group_out']['id']:
            _img_sel_parms['data_group_out']
        }
    }

    #list_xarray_data_variables = [img_dataset[_sel_parms['image']],img_dataset[_sel_parms['sum_weight']]]
    #return _store(img_dataset,list_xarray_data_variables,_storage_parms)
    _img_dataset = fit_gaussian(
        _img_dataset,
        dv=_img_sel_parms['data_group_out']['psf'],
        beam_set_name=_img_sel_parms['data_group_out']['psf_fit'])

    print(
        '#########################  Created graph for make_psf_with_gcf #########################'
    )
    return _img_dataset
    '''
Example #3
0
def make_mosaic_pb(mxds, gcf_dataset, img_dataset, vis_sel_parms,
                   img_sel_parms, grid_parms):
    """
    The make_pb function currently supports rotationally symmetric airy disk primary beams. Primary beams can be generated for any number of dishes.
    The make_pb_parms['list_dish_diameters'] and make_pb_parms['list_blockage_diameters'] must be specified for each dish.
    
    Parameters
    ----------
    vis_dataset : xarray.core.dataset.Dataset
        Input visibility dataset.
    gcf_dataset : xarray.core.dataset.Dataset
        Input gridding convolution function dataset.
    img_dataset : xarray.core.dataset.Dataset
        Input image dataset. ()
    make_pb_parms : dictionary
    make_pb_parms['function'] : {'airy'}, default='airy'
        Only the airy disk function is currently supported.
    grid_parms['imsize'] : list of int, length = 2
        The image size (no padding).
    grid_parms['cell']  : list of number, length = 2, units = arcseconds
        The image cell size.
    make_pb_parms['list_dish_diameters'] : list of number
        The list of dish diameters.
    make_pb_parms['list_blockage_diameters'] = list of number
        The list of blockage diameters for each dish.
    vis_sel_parms : dictionary
    vis_sel_parms['xds'] : str
        The xds within the mxds to use to calculate the imaging weights for.
    vis_sel_parms['data_group_in_id'] : int, default = first id in xds.data_groups
        The data group in the xds to use.
    img_sel_parms : dictionary
    img_sel_parms['data_group_in_id'] : int, default = first id in xds.data_groups
        The data group in the image xds to use.
    img_sel_parms['pb'] : str, default ='PB'
        The mosaic primary beam.
    img_sel_parms['weight_pb'] : str, default ='WEIGHT_PB'
        The weight image.
    img_sel_parms['weight_pb_sum_weight'] : str, default ='WEIGHT_PB_SUM_WEIGHT'
        The sum of weight calculated when gridding the gcfs to create the weight image.
    Returns
    -------
    img_xds : xarray.core.dataset.Dataset
    """
    print(
        '######################### Start make_mosaic_pb #########################'
    )

    #from ngcasa._ngcasa_utils._store import _store
    #from ngcasa._ngcasa_utils._check_parms import _check_storage_parms, _check_sel_parms, _check_existence_sel_parms
    from cngi._utils._check_parms import _check_sel_parms, _check_existence_sel_parms
    from ._imaging_utils._check_imaging_parms import _check_grid_parms, _check_mosaic_pb_parms
    from ._imaging_utils._aperture_grid import _graph_aperture_grid
    import dask.array.fft as dafft
    import matplotlib.pylab as plt
    import numpy as np
    import dask.array as da
    import copy
    import xarray as xr
    from ._imaging_utils._remove_padding import _remove_padding
    from ._imaging_utils._normalize import _normalize
    from cngi.image import make_empty_sky_image
    import dask

    #Deep copy so that inputs are not modified
    _mxds = mxds.copy(deep=True)
    _img_dataset = img_dataset.copy(deep=True)
    _vis_sel_parms = copy.deepcopy(vis_sel_parms)
    _img_sel_parms = copy.deepcopy(img_sel_parms)
    _grid_parms = copy.deepcopy(grid_parms)

    ##############Parameter Checking and Set Defaults##############
    assert (
        'xds' in _vis_sel_parms
    ), "######### ERROR: xds must be specified in sel_parms"  #Can't have a default since xds names are not fixed.
    _vis_dataset = _mxds.attrs[_vis_sel_parms['xds']]

    assert (_check_grid_parms(_grid_parms)
            ), "######### ERROR: grid_parms checking failed"

    #Check vis data_group
    _check_sel_parms(_vis_dataset, _vis_sel_parms)
    #print(_vis_sel_parms)

    #Check img data_group
    _check_sel_parms(_img_dataset,
                     _img_sel_parms,
                     new_or_modified_data_variables={
                         'pb': 'PB',
                         'weight_pb': 'WEIGHT_PB',
                         'weight_pb_sum_weight': 'WEIGHT_PB_SUM_WEIGHT'
                     },
                     append_to_in_id=True)
    #print('did this work',_img_sel_parms)

    _grid_parms['grid_weights'] = True
    _grid_parms['do_psf'] = False
    #_grid_parms['image_size_padded'] = _grid_parms['image_size']
    _grid_parms['oversampling'] = np.array(gcf_dataset.attrs['oversampling'])
    grids_and_sum_weights = _graph_aperture_grid(_vis_dataset, gcf_dataset,
                                                 _grid_parms, _vis_sel_parms)

    #grids_and_sum_weights = _graph_aperture_grid(_vis_dataset,gcf_dataset,_grid_parms)
    weight_image = _remove_padding(
        dafft.fftshift(dafft.ifft2(dafft.ifftshift(grids_and_sum_weights[0],
                                                   axes=(0, 1)),
                                   axes=(0, 1)),
                       axes=(0, 1)), _grid_parms['image_size']).real * (
                           _grid_parms['image_size_padded'][0] *
                           _grid_parms['image_size_padded'][1])

    #############Move this to Normalizer#############
    def correct_image(weight_image, sum_weights):
        sum_weights_copy = copy.deepcopy(
            sum_weights
        )  ##Don't mutate inputs, therefore do deep copy (https://docs.dask.org/en/latest/delayed-best-practices.html).
        sum_weights_copy[sum_weights_copy == 0] = 1
        weight_image = (weight_image / sum_weights_copy[None, None, :, :])
        return weight_image

    weight_image = da.map_blocks(correct_image,
                                 weight_image,
                                 grids_and_sum_weights[1],
                                 dtype=np.double)
    mosaic_primary_beam = da.sqrt(np.abs(weight_image))

    if _grid_parms['chan_mode'] == 'continuum':
        freq_coords = [da.mean(_vis_dataset.coords['chan'].values)]
        chan_width = da.from_array([da.mean(_vis_dataset['chan_width'].data)],
                                   chunks=(1, ))
        imag_chan_chunk_size = 1
    elif _grid_parms['chan_mode'] == 'cube':
        freq_coords = _vis_dataset.coords['chan'].values
        chan_width = _vis_dataset['chan_width'].data
        imag_chan_chunk_size = _vis_dataset.DATA.chunks[2][0]

    phase_center = _grid_parms['phase_center']
    image_size = _grid_parms['image_size']
    cell_size = _grid_parms['cell_size']
    phase_center = _grid_parms['phase_center']

    pol_coords = _vis_dataset.pol.data
    time_coords = [_vis_dataset.time.mean().data]

    _img_dataset = make_empty_sky_image(_img_dataset, phase_center, image_size,
                                        cell_size, freq_coords, chan_width,
                                        pol_coords, time_coords)

    _img_dataset[_img_sel_parms['data_group_out']['pb']] = xr.DataArray(
        mosaic_primary_beam[:, :, None, :, :],
        dims=['l', 'm', 'time', 'chan', 'pol'])
    _img_dataset[_img_sel_parms['data_group_out']['weight_pb']] = xr.DataArray(
        weight_image[:, :, None, :, :], dims=['l', 'm', 'time', 'chan', 'pol'])
    _img_dataset[_img_sel_parms['data_group_out']
                 ['weight_pb_sum_weight']] = xr.DataArray(
                     grids_and_sum_weights[1][None, :, :],
                     dims=['time', 'chan', 'pol'])
    _img_dataset.attrs['data_groups'][0] = {
        **_img_dataset.attrs['data_groups'][0],
        **{
            _img_sel_parms['data_group_out']['id']:
            _img_sel_parms['data_group_out']
        }
    }

    #list_xarray_data_variables = [_img_dataset[_sel_parms['pb']],_img_dataset[_sel_parms['weight']]]
    #return _store(_img_dataset,list_xarray_data_variables,_storage_parms)

    print(
        '#########################  Created graph for make_mosaic_pb #########################'
    )
    return _img_dataset
    '''
def synthesis_imaging_cube(vis_mxds, img_xds, grid_parms,
                           imaging_weights_parms, pb_parms, vis_sel_parms,
                           img_sel_parms):
    print('v3')

    print(
        '######################### Start Synthesis Imaging Cube #########################'
    )
    import numpy as np
    from numba import jit
    import time
    import math
    import dask.array.fft as dafft
    import xarray as xr
    import dask.array as da
    import matplotlib.pylab as plt
    import dask
    import copy, os
    from numcodecs import Blosc
    from itertools import cycle
    import itertools
    from cngi._utils._check_parms import _check_sel_parms, _check_existence_sel_parms
    from ._imaging_utils._check_imaging_parms import _check_imaging_weights_parms, _check_grid_parms, _check_pb_parms
    from ._imaging_utils._make_pb_symmetric import _airy_disk, _casa_airy_disk
    from cngi.image import make_empty_sky_image

    _mxds = vis_mxds.copy(deep=True)
    _vis_sel_parms = copy.deepcopy(vis_sel_parms)
    _img_sel_parms = copy.deepcopy(img_sel_parms)
    _grid_parms = copy.deepcopy(grid_parms)
    _imaging_weights_parms = copy.deepcopy(imaging_weights_parms)
    _img_xds = copy.deepcopy(img_xds)
    _pb_parms = copy.deepcopy(pb_parms)

    assert (
        'xds' in _vis_sel_parms
    ), "######### ERROR: xds must be specified in sel_parms"  #Can't have a default since xds names are not fixed.
    _vis_xds = _mxds.attrs[_vis_sel_parms['xds']]
    assert _vis_xds.dims['pol'] <= 2, "Full polarization is not supported."
    assert (_check_imaging_weights_parms(_imaging_weights_parms)
            ), "######### ERROR: imaging_weights_parms checking failed"
    assert (_check_grid_parms(_grid_parms)
            ), "######### ERROR: grid_parms checking failed"
    assert (_check_pb_parms(_img_xds, _pb_parms)
            ), "######### ERROR: user_imaging_weights_parms checking failed"

    #Check vis data_group
    _check_sel_parms(_vis_xds, _vis_sel_parms)

    #Check img data_group
    _check_sel_parms(_img_xds,
                     _img_sel_parms,
                     new_or_modified_data_variables={
                         'image_sum_weight': 'IMAGE_SUM_WEIGHT',
                         'image': 'IMAGE',
                         'psf_sum_weight': 'PSF_SUM_WEIGHT',
                         'psf': 'PSF',
                         'pb': 'PB',
                         'restore_parms': 'RESTORE_PARMS'
                     },
                     append_to_in_id=True)

    parms = {
        'grid_parms': _grid_parms,
        'imaging_weights_parms': _imaging_weights_parms,
        'pb_parms': _pb_parms,
        'vis_sel_parms': _vis_sel_parms,
        'img_sel_parms': _img_sel_parms
    }

    chunk_sizes = list(
        _vis_xds[_vis_sel_parms["data_group_in"]["data"]].chunks)
    chunk_sizes[0] = (np.sum(chunk_sizes[2]), )
    chunk_sizes[1] = (np.sum(chunk_sizes[1]), )
    chunk_sizes[3] = (np.sum(chunk_sizes[3]), )
    n_pol = _vis_xds.dims['pol']

    #assert n_chunks_in_each_dim[3] == 1, "Chunking is not allowed on pol dim."
    n_chunks_in_each_dim = list(
        _vis_xds[_vis_sel_parms["data_group_in"]["data"]].data.numblocks)
    n_chunks_in_each_dim[0] = 1  #time
    n_chunks_in_each_dim[1] = 1  #baseline
    n_chunks_in_each_dim[3] = 1  #pol

    #Iter over time,baseline,chan
    iter_chunks_indx = itertools.product(np.arange(n_chunks_in_each_dim[0]),
                                         np.arange(n_chunks_in_each_dim[1]),
                                         np.arange(n_chunks_in_each_dim[2]),
                                         np.arange(n_chunks_in_each_dim[3]))

    image_list = _ndim_list(n_chunks_in_each_dim)
    image_sum_weight_list = _ndim_list(n_chunks_in_each_dim[2:])
    psf_list = _ndim_list(n_chunks_in_each_dim)
    psf_sum_weight_list = _ndim_list(n_chunks_in_each_dim[2:])

    pb_list = _ndim_list(tuple(n_chunks_in_each_dim) + (1, ))
    ellipse_parms_list = _ndim_list(tuple(n_chunks_in_each_dim[2:]) + (1, ))
    n_dish_type = len(_pb_parms['list_dish_diameters'])
    n_elps = 3

    freq_chan = da.from_array(
        _vis_xds.coords['chan'].values,
        chunks=(_vis_xds[_vis_sel_parms["data_group_in"]["data"]].chunks[2]))

    # Build graph
    for c_time, c_baseline, c_chan, c_pol in iter_chunks_indx:
        #c_time, c_baseline, c_chan, c_pol
        #print(_vis_xds[_vis_sel_parms["data_group_in"]["data"]].data.partitions[:, :, c_chan, :].shape)
        synthesis_chunk = dask.delayed(_synthesis_imaging_cube_std_chunk)(
            _vis_xds[_vis_sel_parms["data_group_in"]
                     ["data"]].data.partitions[:, :, c_chan, :],
            _vis_xds[_vis_sel_parms["data_group_in"]
                     ["uvw"]].data.partitions[:, :, :],
            _vis_xds[_vis_sel_parms["data_group_in"]
                     ["weight"]].data.partitions[:, :, c_chan, :],
            _vis_xds[_vis_sel_parms["data_group_in"]
                     ["flag"]].data.partitions[:, :, c_chan, :],
            freq_chan.partitions[c_chan], dask.delayed(parms))

        image_list[c_time][c_baseline][c_chan][c_pol] = da.from_delayed(
            synthesis_chunk[0],
            (_grid_parms['image_size'][0], _grid_parms['image_size'][1],
             chunk_sizes[2][c_chan], chunk_sizes[3][c_pol]),
            dtype=np.double)
        image_sum_weight_list[c_chan][c_pol] = da.from_delayed(
            synthesis_chunk[1],
            (chunk_sizes[2][c_chan], chunk_sizes[3][c_pol]),
            dtype=np.double)

        psf_list[c_time][c_baseline][c_chan][c_pol] = da.from_delayed(
            synthesis_chunk[2],
            (_grid_parms['image_size'][0], _grid_parms['image_size'][1],
             chunk_sizes[2][c_chan], chunk_sizes[3][c_pol]),
            dtype=np.double)
        psf_sum_weight_list[c_chan][c_pol] = da.from_delayed(
            synthesis_chunk[3],
            (chunk_sizes[2][c_chan], chunk_sizes[3][c_pol]),
            dtype=np.double)

        pb_list[c_time][c_baseline][c_chan][c_pol][0] = da.from_delayed(
            synthesis_chunk[4],
            (_grid_parms['image_size'][0], _grid_parms['image_size'][1],
             chunk_sizes[2][c_chan], chunk_sizes[3][c_pol], n_dish_type),
            dtype=np.double)

        ellipse_parms_list[c_chan][c_pol][0] = da.from_delayed(
            synthesis_chunk[5],
            (chunk_sizes[2][c_chan], chunk_sizes[3][c_pol], n_elps),
            dtype=np.double)

        #return image, image_sum_weight, psf, psf_sum_weight, pb

    if _grid_parms['chan_mode'] == 'continuum':
        freq_coords = [da.mean(_vis_xds.coords['chan'].values)]
        chan_width = da.from_array([da.mean(_vis_xds['chan_width'].data)],
                                   chunks=(1, ))
        imag_chan_chunk_size = 1
    elif _grid_parms['chan_mode'] == 'cube':
        freq_coords = _vis_xds.coords['chan'].values
        chan_width = _vis_xds['chan_width'].data
        imag_chan_chunk_size = _vis_xds.DATA.chunks[2][0]

    phase_center = _grid_parms['phase_center']
    image_size = _grid_parms['image_size']
    cell_size = _grid_parms['cell_size']
    phase_center = _grid_parms['phase_center']

    pol_coords = _vis_xds.pol.data
    time_coords = [_vis_xds.time.mean().data]

    _img_xds = make_empty_sky_image(_img_xds, phase_center, image_size,
                                    cell_size, freq_coords, chan_width,
                                    pol_coords, time_coords)

    #print(da.block(image_list))
    #print(da.block(psf_list))
    #print(pb_list)
    #print(da.block(pb_list))

    _img_xds[_img_sel_parms['data_group_out']['image']] = xr.DataArray(
        da.block(image_list)[:, :, None, :, :],
        dims=['l', 'm', 'time', 'chan', 'pol'])
    _img_xds[_img_sel_parms['data_group_out']
             ['image_sum_weight']] = xr.DataArray(
                 da.block(image_sum_weight_list)[None, :, :],
                 dims=['time', 'chan', 'pol'])

    print(da.block(ellipse_parms_list))

    _img_xds[_img_sel_parms['data_group_out']['restore_parms']] = xr.DataArray(
        da.block(ellipse_parms_list)[None, :, :, :],
        dims=['time', 'chan', 'pol', 'elps_index'])

    _img_xds[_img_sel_parms['data_group_out']['psf']] = xr.DataArray(
        da.block(psf_list)[:, :, None, :, :],
        dims=['l', 'm', 'time', 'chan', 'pol'])
    _img_xds[_img_sel_parms['data_group_out']
             ['psf_sum_weight']] = xr.DataArray(
                 da.block(psf_sum_weight_list)[None, :, :],
                 dims=['time', 'chan', 'pol'])

    _img_xds[_img_sel_parms['data_group_out']['pb']] = xr.DataArray(
        da.block(pb_list)[:, :, None, :, :, :],
        dims=['l', 'm', 'time', 'chan', 'pol', 'dish_type'])
    _img_xds = _img_xds.assign_coords(
        {'dish_type': np.arange(len(_pb_parms['list_dish_diameters']))})
    _img_xds.attrs['data_groups'][0] = {
        **_img_xds.attrs['data_groups'][0],
        **{
            _img_sel_parms['data_group_out']['id']:
            _img_sel_parms['data_group_out']
        }
    }

    return _img_xds
Example #5
0
def make_grid(vis_mxds, img_xds, grid_parms,  vis_sel_parms, img_sel_parms):
    """

    
    Parameters
    ----------
    vis_mxds : xarray.core.dataset.Dataset
        Input multi-xarray Dataset with global data.
    img_xds : xarray.core.dataset.Dataset
        Input image dataset.
    grid_parms : dictionary
    grid_parms['image_size'] : list of int, length = 2
        The image size (no padding).
    grid_parms['cell_size']  : list of number, length = 2, units = arcseconds
        The image cell size.
    grid_parms['chan_mode'] : {'continuum'/'cube'}, default = 'continuum'
        Create a continuum or cube image.
    grid_parms['fft_padding'] : number, acceptable range [1,100], default = 1.2
        The factor that determines how much the gridded visibilities are padded before the fft is done.
    vis_sel_parms : dictionary
    vis_sel_parms['xds'] : str
        The xds within the mxds to use to calculate the imaging weights for.
    vis_sel_parms['data_group_in_id'] : int, default = first id in xds.data_groups
        The data group in the xds to use.
    img_sel_parms : dictionary
    img_sel_parms['data_group_in_id'] : int, default = first id in xds.data_groups
        The data group in the image xds to use.
    img_sel_parms['image'] : str, default ='IMAGE'
        The created image name.
    img_sel_parms['sum_weight'] : str, default ='SUM_WEIGHT'
        The created sum of weights name.
    Returns
    -------
    img_xds : xarray.core.dataset.Dataset
        The image_dataset will contain the image created and the sum of weights.
    """
    print('######################### Start make_image #########################')
    import numpy as np
    from numba import jit
    import time
    import math
    import dask.array.fft as dafft
    import xarray as xr
    import dask.array as da
    import matplotlib.pylab as plt
    import dask
    import copy, os
    from numcodecs import Blosc
    from itertools import cycle
    
    from cngi._utils._check_parms import _check_sel_parms, _check_existence_sel_parms
    from ._imaging_utils._check_imaging_parms import _check_grid_parms
    from ._imaging_utils._gridding_convolutional_kernels import _create_prolate_spheroidal_kernel, _create_prolate_spheroidal_kernel_1D
    from ._imaging_utils._standard_grid import _graph_standard_grid
    from ._imaging_utils._remove_padding import _remove_padding
    from ._imaging_utils._aperture_grid import _graph_aperture_grid
    from cngi.image import make_empty_sky_image
    
    #print('****',sel_parms,'****')
    _mxds = vis_mxds.copy(deep=True)
    _img_xds = img_xds.copy(deep=True)
    _vis_sel_parms = copy.deepcopy(vis_sel_parms)
    _img_sel_parms = copy.deepcopy(img_sel_parms)
    _grid_parms = copy.deepcopy(grid_parms)

    ##############Parameter Checking and Set Defaults##############
    assert(_check_grid_parms(_grid_parms)), "######### ERROR: grid_parms checking failed"
    assert('xds' in _vis_sel_parms), "######### ERROR: xds must be specified in sel_parms" #Can't have a default since xds names are not fixed.
    _vis_xds = _mxds.attrs[_vis_sel_parms['xds']]
    
    #Check vis data_group
    _check_sel_parms(_vis_xds,_vis_sel_parms)
    
    #Check img data_group
    _check_sel_parms(_img_xds,_img_sel_parms,new_or_modified_data_variables={'sum_weight':'SUM_WEIGHT','grid':'GRID'},append_to_in_id=True)

    ##################################################################################
    
    # Creating gridding kernel
    _grid_parms['oversampling'] = 100
    _grid_parms['support'] = 7
    
    cgk, correcting_cgk_image = _create_prolate_spheroidal_kernel(_grid_parms['oversampling'], _grid_parms['support'], _grid_parms['image_size_padded'])
    cgk_1D = _create_prolate_spheroidal_kernel_1D(_grid_parms['oversampling'], _grid_parms['support'])
    
    _grid_parms['complex_grid'] = True
    _grid_parms['do_psf'] = False
    grids_and_sum_weights = _graph_standard_grid(_vis_xds, cgk_1D, _grid_parms, _vis_sel_parms)
    
    
    if _grid_parms['chan_mode'] == 'continuum':
        freq_coords = [da.mean(_vis_xds.coords['chan'].values)]
        chan_width = da.from_array([da.mean(_vis_xds['chan_width'].data)],chunks=(1,))
        imag_chan_chunk_size = 1
    elif _grid_parms['chan_mode'] == 'cube':
        freq_coords = _vis_xds.coords['chan'].values
        chan_width = _vis_xds['chan_width'].data
        imag_chan_chunk_size = _vis_xds.DATA.chunks[2][0]
    
    phase_center = _grid_parms['phase_center']
    image_size = _grid_parms['image_size']
    cell_size = _grid_parms['cell_size']
    phase_center = _grid_parms['phase_center']
    
    pol_coords = _vis_xds.pol.data
    time_coords = [_vis_xds.time.mean().data]
    
    _img_xds = make_empty_sky_image(_img_xds,grid_parms['phase_center'],image_size,cell_size,freq_coords,chan_width,pol_coords,time_coords)
    
    _img_xds[_img_sel_parms['data_group_out']['sum_weight']] = xr.DataArray(grids_and_sum_weights[1][None,:,:], dims=['time','chan','pol'])
    _img_xds[_img_sel_parms['data_group_out']['grid']] = xr.DataArray(grids_and_sum_weights[0][:,:,None,:,:], dims=['u', 'v', 'time', 'chan', 'pol'])
    _img_xds.attrs['data_groups'][0] = {**_img_xds.attrs['data_groups'][0],**{_img_sel_parms['data_group_out']['id']:_img_sel_parms['data_group_out']}}
    
    
    print('######################### Created graph for make_image #########################')
    return _img_xds