Exemple #1
0
def concat(script,
           vis_paths,
           out_basename=None,
           out_dir=None,
           out_path=None,
           overwrite=False):
    """
    Concatenates multiple visibilities into one.

    By default, output basename is derived by concatenating
    the basenames of the input visibilities, with the prefix `concat_`.
    However, this can result in something very long and unwieldy. Alternatively
    you may specify the exact out_path, or just the out_basename.

    **Returns:** Path to concatenated ms.
    """
    vis_paths = byteify(vis_paths)
    concat_path = byteify(out_path)
    if concat_path is None:
        if out_basename is None:
            basenames = [
                os.path.splitext(os.path.basename(vp))[0] for vp in vis_paths
            ]
            concnames = 'concat_' + '_'.join(basenames) + '.ms'
        else:
            concnames = out_basename + '.ms'
        concat_path = os.path.join(out_dir, concnames)
    ensure_dir(os.path.dirname(concat_path))
    if overwrite:
        if os.path.isdir(concat_path):
            shutil.rmtree(concat_path)
    abs_vis_paths = [os.path.abspath(v) for v in vis_paths]
    script.append("concat(vis={0}, concatvis='{1}')".format(
        str(abs_vis_paths), os.path.abspath(concat_path)))
    return concat_path
Exemple #2
0
def concat(script, vis_paths, out_basename=None, out_dir=None, out_path=None,
           overwrite=False):
    """
    Concatenates multiple visibilities into one.

    By default, output basename is derived by concatenating
    the basenames of the input visibilities, with the prefix `concat_`.
    However, this can result in something very long and unwieldy. Alternatively
    you may specify the exact out_path, or just the out_basename.

    Returns:
        Path to concatenated ms.
    """
    vis_paths = byteify(vis_paths)
    concat_path = byteify(out_path)
    if concat_path is None:
        if out_basename is None:
            concat_path = derive_out_path(vis_paths, out_dir,
                                          out_extension='.ms',
                                          out_prefix='concat_')
        else:
            concnames = out_basename + '.ms'
            concat_path = os.path.join(out_dir, concnames)
    ensure_dir(os.path.dirname(concat_path))
    if overwrite:
        if os.path.isdir(concat_path):
            shutil.rmtree(concat_path)
    abs_vis_paths = [os.path.abspath(v) for v in vis_paths]
    script.append("concat(vis={0}, concatvis='{1}')".format(
        str(abs_vis_paths), os.path.abspath(concat_path))
    )
    return concat_path
Exemple #3
0
def export_fits(script,
                image_path,
                out_dir=None,
                out_path=None,
                overwrite=False):
    """
    Convert an image ms to FITS format.

    Returns:
        Path to resulting FITS file.
    """
    fits_path = out_path
    if fits_path is None:
        fits_path = derive_out_path(image_path,
                                    out_dir,
                                    '.fits',
                                    strip_in_extension=False)
    ensure_dir(os.path.dirname(fits_path))
    # NB Be sure to specify the abspath as seen from current ipython process,
    # in case the user has specified relative path:
    script.append(
        "exportfits(imagename='{0}', fitsimage='{1}', overwrite={2})".format(
            os.path.abspath(image_path), os.path.abspath(fits_path),
            str(overwrite)))
    return fits_path
def make_image_map_fits(vis_ms_path,
                        output_dir,
                        image_size,
                        cell_size,
                        niter=150,
                        threshold_in_jy=0.1):
    ensure_dir(output_dir)

    script = []

    img_n_pix = int(image_size.to(u.pixel).value)
    cell_arcsec = cell_size.to(u.arcsec).value
    clean_args = {
        "imsize": [img_n_pix, img_n_pix],
        "cell": [str(cell_arcsec) + 'arcsec'],
        "weighting": 'briggs',
        "robust": 0.5,
    }
    dirty_maps = drivecasa.commands.clean(script,
                                          vis_paths=vis_ms_path,
                                          niter=0,
                                          threshold_in_jy=threshold_in_jy,
                                          other_clean_args=clean_args,
                                          out_dir=output_dir,
                                          overwrite=True)

    dirty_fits_path = drivecasa.commands.export_fits(script,
                                                     dirty_maps.image,
                                                     overwrite=True)

    clean_maps = drivecasa.commands.clean(script,
                                          vis_paths=vis_ms_path,
                                          niter=niter,
                                          threshold_in_jy=threshold_in_jy,
                                          other_clean_args=clean_args,
                                          out_dir=output_dir,
                                          overwrite=True)

    clean_fits_path = drivecasa.commands.export_fits(script,
                                                     clean_maps.image,
                                                     overwrite=True)

    logfile_basename = os.path.basename(
        vis_ms_path) + ".casa-clean-commands.log"
    commands_logfile = os.path.join(output_dir, logfile_basename)
    if os.path.isfile(commands_logfile):
        os.unlink(commands_logfile)
    casa = drivecasa.Casapy(commands_logfile=commands_logfile)
    casa.run_script(script)
    return dirty_fits_path, clean_fits_path
def make_image_map_fits(vis_ms_path, output_dir,
                        image_size, cell_size,
                        niter=150, threshold_in_jy=0.1):
    ensure_dir(output_dir)


    script = []

    img_n_pix = int(image_size.to(u.pixel).value)
    cell_arcsec = cell_size.to(u.arcsec).value
    clean_args = {
        "imsize": [img_n_pix, img_n_pix],
        "cell": [str(cell_arcsec)+'arcsec'],
        "weighting": 'briggs',
        "robust": 0.5,
    }
    dirty_maps = drivecasa.commands.clean(script,
                                    vis_paths=vis_ms_path,
                                    niter=0,
                                    threshold_in_jy=threshold_in_jy,
                                    other_clean_args=clean_args,
                                    out_dir=output_dir,
                                    overwrite=True)

    dirty_fits_path = drivecasa.commands.export_fits(script, dirty_maps.image,
                                               overwrite=True)

    clean_maps = drivecasa.commands.clean(script,
                                    vis_paths=vis_ms_path,
                                    niter=niter,
                                    threshold_in_jy=threshold_in_jy,
                                    other_clean_args=clean_args,
                                    out_dir=output_dir,
                                    overwrite=True)

    clean_fits_path = drivecasa.commands.export_fits(script, clean_maps.image,
                                               overwrite=True)

    logfile_basename = os.path.basename(vis_ms_path)+".casa-clean-commands.log"
    commands_logfile = os.path.join(output_dir, logfile_basename)
    if os.path.isfile(commands_logfile):
        os.unlink(commands_logfile)
    casa = drivecasa.Casapy(commands_logfile=commands_logfile)
    casa.run_script(script)
    return dirty_fits_path, clean_fits_path
Exemple #6
0
def import_uvfits(script,
                  uvfits_path,
                  out_dir=None,
                  out_path=None,
                  overwrite=False):
    """
    Import UVFITS and convert to .ms format.


    If out_path is ``None``, a sensible output .ms directory path will be derived
    by taking the FITS basename, switching the extension to .ms, and locating
    as a subdirectory of ``out_dir``,
    e.g. if ``uvfits_path = '/my/data/obs1.fits', out_dir = '/tmp/junkdata'``
    then the output data will be located at */tmp/junkdata/obs1.ms*.


    **Args:**

    - script: List to which the relevant casapy command line will be appended.
    - uvfits_path: path to input data file.
    - out_dir: Directory in which to place output file. ``None`` signifies
      to place output .ms in same directory as the original FITS file.
    - out_path: Provides an override to the automatic output naming system.
      If this is not ``None`` then the ``out_dir`` arg is ignored and the
      specified path used instead.
    - overwrite: Delete any pre-existing data at the output path (danger!).


    **Returns:** Path to newly converted ms.
    """
    ms_path = out_path
    if ms_path is None:
        ms_path = derive_out_path(uvfits_path, out_dir, '.ms')
    ensure_dir(os.path.dirname(ms_path))
    if overwrite:
        if os.path.isdir(ms_path):
            shutil.rmtree(ms_path)
    # NB Be sure to specify the abspath as seen from current ipython process,
    # in case the user has specified relative path:
    script.append("importuvfits(fitsfile='{0}', vis='{1}')".format(
        os.path.abspath(uvfits_path), os.path.abspath(ms_path)))
    return ms_path
Exemple #7
0
def export_fits(script, image_path, out_dir=None, out_path=None,
                overwrite=False):
    """
    Convert an image ms to FITS format.

    **Returns:** Path to resulting FITS file.
    """
    fits_path = out_path
    if fits_path is None:
        fits_path = derive_out_path(image_path, out_dir, '.fits',
                                    strip_in_extension=False)
    ensure_dir(os.path.dirname(fits_path))
    # NB Be sure to specify the abspath as seen from current ipython process,
    # in case the user has specified relative path:
    script.append("exportfits(imagename='{0}', fitsimage='{1}', overwrite={2})"
                   .format(os.path.abspath(image_path),
                           os.path.abspath(fits_path),
                           str(overwrite))
                 )
    return fits_path
Exemple #8
0
def import_uvfits(script, uvfits_path, out_dir=None, out_path=None,
                  overwrite=False):
    """
    Import UVFITS and convert to .ms format.


    If out_path is ``None``, a sensible output .ms directory path will be derived
    by taking the FITS basename, switching the extension to .ms, and locating
    as a subdirectory of ``out_dir``,
    e.g. if ``uvfits_path = '/my/data/obs1.fits', out_dir = '/tmp/junkdata'``
    then the output data will be located at */tmp/junkdata/obs1.ms*.


    Args:
        script: List to which the relevant casapy command line will be appended.
        uvfits_path: path to input data file.
        out_dir: Directory in which to place output file. ``None`` signifies
            to place output .ms in same directory as the original FITS file.
        out_path: Provides an override to the automatic output naming system.
            If this is not ``None`` then the ``out_dir`` arg is ignored and the
            specified path used instead.
        overwrite: Delete any pre-existing data at the output path (danger!).


    Returns:
        Path to newly converted ms.
    """
    ms_path = out_path
    if ms_path is None:
        ms_path = derive_out_path(uvfits_path, out_dir, '.ms')
    ensure_dir(os.path.dirname(ms_path))
    if overwrite:
        if os.path.isdir(ms_path):
            shutil.rmtree(ms_path)
    # NB Be sure to specify the abspath as seen from current ipython process,
    # in case the user has specified relative path:
    script.append("importuvfits(fitsfile='{0}', vis='{1}')".format(
        os.path.abspath(uvfits_path), os.path.abspath(ms_path))
    )
    return ms_path
Exemple #9
0
def make_componentlist(script, source_list, out_path, overwrite=True):
    """
    Build a componentlist and save it to disk.

    Runs `cl.done()` to clear any previous entries, the `cl.addcomponent`
    for each source in the list, and finally `cl.rename`, `cl.close`.

    cf https://casa.nrao.edu/docs/CasaRef/componentlist-Tool.html

    Typically used when simulating observations.

    Args:
        script (list): List of strings to append commands to.
        source_list: List of (position, flux, frequency) tuples.
            Positions should be :class:`astropy.coordinates.SkyCoord`
            instances, while flux and frequency should be quantities supplied
            using the :mod:`astropy.units` functionality.
        out_path (str): Path to save the component list at
        overwrite (bool): Delete any pre-existing component list at out_path.

    """
    if os.path.isdir(out_path):
        if overwrite:
            shutil.rmtree(out_path)
        else:
            logger.warning(
                "Componentlist already exists (and overwrite=False).")
    ensure_dir(os.path.dirname(out_path))

    script.append("cl.done()")
    for (posn, flux, freq) in source_list:
        posn_str = "J2000 {}deg {}deg".format(posn.ra.deg, posn.dec.deg)
        freq_str = "{}Hz".format(freq.to(u.Hz).value)
        script.append(
            "cl.addcomponent(dir='{posn_str}', flux={flux}, fluxunit='Jy',"
            "freq='{freq_str}', shape='point')".format(
                posn_str=posn_str, flux=flux.to(u.Jy).value, freq_str=freq_str
            ))
    script.append("cl.rename('{}')".format(out_path))
    script.append("cl.close()")
Exemple #10
0
def clean(script,
          vis_paths,
          niter,
          threshold_in_jy,
          mask='',
          modelimage='',
          other_clean_args=None,
          out_dir=None,
          out_path=None,
          overwrite=False
          ):
    """
    Perform clean process to produce an image/map.

    If out_path is None, then the output basename is derived by
    appending a `.clean` or `.dirty` suffix to the input basename. The various
    outputs are then further suffixed by casa, e.g.
    `foo.clean.image`, `foo.clean.psf`, etc. Since multiple outputs are
    generated, this function returns a dictionary detailing the expected paths.

    NB Attempting to run with pre-existing outputs and ``overwrite=False``
    *will not* throw an error, in contrast to most other routines.
    From the CASA cookbook, w.r.t. the outputs:

        "If an image with that name already exists, it will in general be
        overwritten. Beware using names of existing images however. If the clean
        is run using an imagename where <imagename>.residual and
        <imagename>.model already exist then clean will continue starting from
        these (effectively restarting from the end of the previous clean).
        Thus, if multiple runs of clean are run consecutively with the same
        imagename, then the cleaning is incremental (as in the difmap package)."

    You can override this behaviour by specifying ``overwrite=True``, in which
    case all pre-existing outputs will be deleted.

    NB niter = 0 implies create a  'dirty' map, outputs will be named
    accordingly.

    .. warning::

        This function can accept a list of multiple input visibilities. This
        functionality is not extensively tested and should be considered
        experimental - the CASA cookbook is vague on how parameters should be
        passed in this use-case.


    Returns:
        expected_map_paths(:py:class:`.CleanMaps`): namedtuple,
            listing paths for resulting maps.
    """
    vis_paths = byteify(vis_paths)
    vis_paths = listify(vis_paths)
    vis_paths = [os.path.abspath(vp) for vp in vis_paths]
    out_path = byteify(out_path)

    if other_clean_args is None:
        other_clean_args = {}
    clean_args = other_clean_args.copy()

    cleaned_path = out_path
    if cleaned_path is None:
        if niter == 0:
            out_ext = '.dirty'
        else:
            out_ext = '.clean'
        cleaned_path = derive_out_path(vis_paths,
                                       out_dir,
                                       out_extension=out_ext)

    clean_args.update({
        'vis': vis_paths,
        'imagename': os.path.abspath(cleaned_path),
        'niter': niter,
        'threshold': str(threshold_in_jy) + 'Jy',
        'mask': mask,
        'modelimage': modelimage
    })
    script.append("clean(**{})".format(repr(clean_args)))

    ensure_dir(os.path.dirname(cleaned_path))
    expected_map_paths = CleanMaps(
        image=cleaned_path + '.image',
        model=cleaned_path + '.model',
        residual=cleaned_path + '.residual',
        psf=cleaned_path + '.psf',
        mask=cleaned_path + '.mask',
        flux=cleaned_path + '.flux',
    )

    if overwrite:
        for path in expected_map_paths:
            if os.path.isdir(path):
                shutil.rmtree(path)
    return expected_map_paths
Exemple #11
0
def copy_measurementset(src, dest):
    if os.path.isdir(dest):
        shutil.rmtree(dest)
    ensure_dir(os.path.dirname(dest))
    shutil.copytree(src, dest)
from __future__ import print_function

import os

import drivecasa
import drivecasa.commands as commands
from drivecasa.utils import ensure_dir

output_dir = './simulation_output'
ensure_dir(output_dir)

commands_logfile = os.path.join(output_dir, "./casa-clean-commands.log")
output_visibility = os.path.join(output_dir, './foovis.ms')
# output_visibility = os.path.join(output_dir, './vla-sim.MS')
output_image = os.path.join(output_dir, './foo')

if os.path.isfile(commands_logfile):
    os.unlink(commands_logfile)
casa = drivecasa.Casapy(commands_logfile=commands_logfile,
                        echo_to_stdout=True,
                        )
script = []
clean_args = {
   "imsize": [512, 512],
   "cell": ['3.5arcsec'],
}

outmaps = commands.clean(script, output_visibility, niter=100,
                         threshold_in_jy=1e-5,
                         out_path=output_image,
                         other_clean_args=clean_args,
def copy_measurementset(src, dest):
    if os.path.isdir(dest):
        shutil.rmtree(dest)
    ensure_dir(os.path.dirname(dest))
    shutil.copytree(src, dest)
def simulate_vis_with_casa(pointing_centre, source_list, noise_std_dev, vis_path,
                           overwrite=True, echo=False):
    """
    Use casapy to simulate a visibility measurementset with noise.

    (This also produces an initial set of UVW data)

    Args:
        pointing_centre (:class:`astropy.coordinates.SkyCoord`)
        source_list: list of :class:`fastimgproto.skymodel.helpers.SkySource`
        noise_std_dev (astropy.units.Quantity): Standard deviation of the noise
            (units of Jy).
        vis_path (str): Path to visibilities generated.
        echo (bool): Echo the CASA output to terminal during processing.

    Returns (str): Full path to `vis.ms`.
    """


    vis_abspath = os.path.abspath(vis_path)
    commands_logfile = vis_abspath + "_casa_commands.log"
    casa_logfile = vis_abspath + "_casa_log.log"
    component_list_path = vis_abspath + "_sources.cl"

    for outdir in vis_abspath, component_list_path:
        if os.path.isdir(outdir):
            if overwrite:
                shutil.rmtree(outdir)
            else:
                raise IOError("{} already present and overwrite==False.".format(
                    outdir
                ))
    if os.path.isfile(commands_logfile):
        os.remove(commands_logfile)
    ensure_dir(os.path.dirname(vis_abspath))

    casa = drivecasa.Casapy(commands_logfile=commands_logfile,
                            casa_logfile=casa_logfile,
                            echo_to_stdout=echo)
    script = []
    # Add subroutine definition, for manual reproduction with CASA:
    script.append(drivecasa.drivecasa.commands.subroutines.def_load_antennalist)

    # Define some observation parameters...
    # For VLA reference numbers, see:
    # https://science.nrao.edu/facilities/vla/docs/manuals/oss/performance/fov
    # https://science.nrao.edu/facilities/vla/docs/manuals/oss/performance/resolution
    obs_central_frequency = 3. * u.GHz
    obs_frequency_bandwidth = 0.125 * u.GHz
    primary_beam_fwhm = (45. * u.GHz / obs_central_frequency) * u.arcmin

    # Convert the sources to a CASA 'componentlist'
    component_list_path = sim.make_componentlist(
        script,
        source_list=[(s.position, s.flux, s.frequency) for s in source_list],
        out_path=component_list_path)

    # Open the visibility file
    sim.open_sim(script, vis_abspath)

    # Configure the virtual telescope
    # sim.setpb(script,
    #           telescope_name='VLA',
    #           primary_beam_hwhm=primary_beam_fwhm * 0.5,
    #           frequency=obs_central_frequency)
    sim.setconfig(script,
                  telescope_name='VLA',
                  antennalist_path=vla_c_antennalist_path)
    sim.setspwindow(script,
                    freq_start=obs_central_frequency - 0.5 * obs_frequency_bandwidth,
                    freq_resolution=obs_frequency_bandwidth,
                    freq_delta=obs_frequency_bandwidth,
                    n_channels=1,
                    )
    sim.setfeed(script, )
    sim.setfield(script, pointing_centre)
    sim.setlimits(script)
    sim.setauto(script)
    ref_time = Time('2014-05-01T19:55:45', format='isot', scale='tai')
    sim.settimes(script, integration_time=10 * u.s, reference_time=ref_time)

    # Generate the visibilities
    sim.observe(script, stop_delay=10 * u.s)

    sim.predict(script, component_list_path)

    sim.set_simplenoise(script, noise_std_dev=noise_std_dev)
    sim.corrupt(script)
    sim.close_sim(script)

    casa_output = casa.run_script(script)
    return casa_output
Exemple #15
0
def clean(script,
          vis_path,
          niter,
          threshold_in_jy,
          mask='',
          modelimage='',
          other_clean_args=None,
          out_dir=None,
          out_path=None,
          overwrite=False):
    """
    Perform clean process to produce an image/map.

    If out_path is None, then the output basename is derived by
    appending a `.clean` or `.dirty` suffix to the input basename. The various
    outputs are then further suffixed by casa, e.g.
    `foo.clean.image`, `foo.clean.psf`, etc. Since multiple outputs are
    generated, this function returns a dictionary detailing the expected paths.

    NB Attempting to run with pre-existing outputs and ``overwrite=False``
    *will not* throw an error, in contrast to most other routines.
    From the CASA cookbook, w.r.t. the outputs:

        "If an image with that name already exists, it will in general be
        overwritten. Beware using names of existing images however. If the clean
        is run using an imagename where <imagename>.residual and
        <imagename>.model already exist then clean will continue starting from
        these (effectively restarting from the end of the previous clean).
        Thus, if multiple runs of clean are run consecutively with the same
        imagename, then the cleaning is incremental (as in the difmap package)."

    You can override this behaviour by specifying ``overwrite=True``, in which
    case all pre-existing outputs will be deleted.

    NB niter = 0 implies create a  'dirty' map, outputs will be named
    accordingly.

    **Returns**:
    :py:class:`.CleanMaps` namedtuple, listing paths for resulting maps.
    """
    vis_path = byteify(vis_path)
    out_path = byteify(out_path)

    if other_clean_args is None:
        other_clean_args = {}
    clean_args = other_clean_args.copy()

    cleaned_path = out_path
    if cleaned_path is None:
        if niter == 0:
            out_ext = '.dirty'
        else:
            out_ext = '.clean'
        cleaned_path = derive_out_path(
            vis_path[0] if type(vis_path) is list else vis_path,
            out_dir,
            out_extension=out_ext)

    clean_args.update({
        'vis':
        vis_path if type(vis_path) is list else os.path.abspath(vis_path),
        'imagename':
        os.path.abspath(cleaned_path),
        'niter':
        niter,
        'threshold':
        str(threshold_in_jy) + 'Jy',
        'mask':
        mask,
        'modelimage':
        modelimage
    })
    script.append("clean(**{})".format(repr(clean_args)))

    ensure_dir(os.path.dirname(cleaned_path))
    expected_map_paths = CleanMaps(
        image=cleaned_path + '.image',
        model=cleaned_path + '.model',
        residual=cleaned_path + '.residual',
        psf=cleaned_path + '.psf',
        mask=cleaned_path + '.mask',
        flux=cleaned_path + '.flux',
    )

    if overwrite:
        for path in expected_map_paths:
            if os.path.isdir(path):
                shutil.rmtree(path)
    return expected_map_paths
def simulate_vis_with_casa(pointing_centre, source_list, output_dir):
    """
    Use casapy to simulate a visibility measurementset with noise.

    (This also produces an initial set of UVW data)

    Args:
        pointing_centre (:class:`astropy.coordinates.SkyCoord`)
        source_list: list of :class:`fastimgproto.skymodel.helpers.SkySource`
        output_dir (str): Output directory which will contain `vis.ms`

    Returns (str): Full path to `vis.ms`.
    """

    ensure_dir(output_dir)

    commands_logfile = os.path.join(
        output_dir, "./casa-visibilities_for_point_source-commands.log")
    component_list_path = os.path.join(output_dir, './sources.cl')
    output_visibility = os.path.abspath(os.path.join(output_dir, './vis.ms'))

    if os.path.isfile(commands_logfile):
        os.unlink(commands_logfile)
    casa = drivecasa.Casapy(commands_logfile=commands_logfile)
    script = []

    # For VLA reference numbers, see:
    # https://science.nrao.edu/facilities/vla/docs/manuals/oss/performance/fov
    # https://science.nrao.edu/facilities/vla/docs/manuals/oss/performance/resolution

    # Define some observation parameters:
    obs_central_frequency = 3. * u.GHz
    obs_frequency_bandwidth = 0.125 * u.GHz
    primary_beam_fwhm = (45. * u.GHz / obs_central_frequency) * u.arcmin

    # Convert the sources to a CASA 'componentlist'
    component_list_path = sim.make_componentlist(
        script,
        source_list=[(s.position, s.flux, s.frequency) for s in source_list],
        out_path=component_list_path)

    # Open the visibility file
    sim.open_sim(script, output_visibility)

    # Configure the virtual telescope
    # sim.setpb(script,
    #           telescope_name='VLA',
    #           primary_beam_hwhm=primary_beam_fwhm * 0.5,
    #           frequency=obs_central_frequency)
    sim.setconfig(script,
                  telescope_name='VLA',
                  antennalist_path=vla_c_antennalist_path)
    sim.setspwindow(
        script,
        freq_start=obs_central_frequency - 0.5 * obs_frequency_bandwidth,
        freq_resolution=obs_frequency_bandwidth,
        freq_delta=obs_frequency_bandwidth,
        n_channels=1,
    )
    sim.setfeed(script, )
    sim.setfield(script, pointing_centre)
    sim.setlimits(script)
    sim.setauto(script)
    ref_time = Time('2014-05-01T19:55:45', format='isot', scale='tai')
    sim.settimes(script, integration_time=10 * u.s, reference_time=ref_time)

    # Generate the visibilities
    sim.observe(script, stop_delay=10 * u.s)

    sim.predict(script, component_list_path)

    sim.set_simplenoise(script, noise_std_dev=1 * u.mJy)
    sim.corrupt(script)
    sim.close_sim(script)

    casa.run_script(script)
    return output_visibility
Exemple #17
0
from __future__ import print_function

import os

import astropy.units as u
import drivecasa
import drivecasa.commands.simulation as sim
from astropy.coordinates import SkyCoord
from astropy.time import Time
from drivecasa.utils import ensure_dir

output_dir = './simulation_output'
ensure_dir(output_dir)

commands_logfile = os.path.join(output_dir, "./casa-commands.log")
component_list_path = os.path.join(output_dir, './sources.cl')
output_visibility = os.path.join(output_dir, './foovis.ms')

if os.path.isfile(commands_logfile):
    os.unlink(commands_logfile)
casa = drivecasa.Casapy(
    commands_logfile=commands_logfile,
    echo_to_stdout=True,
)
script = []

# For VLA reference numbers, see:
# https://science.nrao.edu/facilities/vla/docs/manuals/oss/performance/fov
# https://science.nrao.edu/facilities/vla/docs/manuals/oss/performance/resolution

# Define some observation parameters:
Exemple #18
0
def simulate_vis_with_casa(pointing_centre,
                           source_list,
                           noise_std_dev,
                           vis_path,
                           overwrite=True,
                           echo=False):
    """
    Use casapy to simulate a visibility measurementset with noise.

    (This also produces an initial set of UVW data)

    Args:
        pointing_centre (:class:`astropy.coordinates.SkyCoord`)
        source_list: list of :class:`fastimgproto.skymodel.helpers.SkySource`
        noise_std_dev (astropy.units.Quantity): Standard deviation of the noise
            (units of Jy).
        vis_path (str): Path to visibilities generated.
        echo (bool): Echo the CASA output to terminal during processing.

    Returns (str): Full path to `vis.ms`.
    """

    vis_abspath = os.path.abspath(vis_path)
    commands_logfile = vis_abspath + "_casa_commands.log"
    casa_logfile = vis_abspath + "_casa_log.log"
    component_list_path = vis_abspath + "_sources.cl"

    for outdir in vis_abspath, component_list_path:
        if os.path.isdir(outdir):
            if overwrite:
                shutil.rmtree(outdir)
            else:
                raise IOError(
                    "{} already present and overwrite==False.".format(outdir))
    if os.path.isfile(commands_logfile):
        os.remove(commands_logfile)
    ensure_dir(os.path.dirname(vis_abspath))

    casa = drivecasa.Casapy(commands_logfile=commands_logfile,
                            casa_logfile=casa_logfile,
                            echo_to_stdout=echo)
    script = []
    # Add subroutine definition, for manual reproduction with CASA:
    script.append(
        drivecasa.drivecasa.commands.subroutines.def_load_antennalist)

    # Define some observation parameters...
    # For VLA reference numbers, see:
    # https://science.nrao.edu/facilities/vla/docs/manuals/oss/performance/fov
    # https://science.nrao.edu/facilities/vla/docs/manuals/oss/performance/resolution
    obs_central_frequency = 3. * u.GHz
    obs_frequency_bandwidth = 0.125 * u.GHz
    primary_beam_fwhm = (45. * u.GHz / obs_central_frequency) * u.arcmin

    # Convert the sources to a CASA 'componentlist'
    component_list_path = sim.make_componentlist(
        script,
        source_list=[(s.position, s.flux, s.frequency) for s in source_list],
        out_path=component_list_path)

    # Open the visibility file
    sim.open_sim(script, vis_abspath)

    # Configure the virtual telescope
    # sim.setpb(script,
    #           telescope_name='VLA',
    #           primary_beam_hwhm=primary_beam_fwhm * 0.5,
    #           frequency=obs_central_frequency)
    sim.setconfig(script,
                  telescope_name='VLA',
                  antennalist_path=vla_c_antennalist_path)
    sim.setspwindow(
        script,
        freq_start=obs_central_frequency - 0.5 * obs_frequency_bandwidth,
        freq_resolution=obs_frequency_bandwidth,
        freq_delta=obs_frequency_bandwidth,
        n_channels=1,
    )
    sim.setfeed(script, )
    sim.setfield(script, pointing_centre)
    sim.setlimits(script)
    sim.setauto(script)
    ref_time = Time('2014-05-01T19:55:45', format='isot', scale='tai')
    sim.settimes(script, integration_time=10 * u.s, reference_time=ref_time)

    # Generate the visibilities
    sim.observe(script, stop_delay=10 * u.s)

    sim.predict(script, component_list_path)

    sim.set_simplenoise(script, noise_std_dev=noise_std_dev)
    sim.corrupt(script)
    sim.close_sim(script)

    casa_output = casa.run_script(script)
    return casa_output