Ejemplo n.º 1
0
 def test_crosssubtract_datamodel(self):
     self.actualSetUp(zerow=True)
     
     future_vis = rsexecute.scatter(self.vis_list[0])
     future_skymodel_list = rsexecute.scatter(self.skymodel_list)
     skymodel_vislist = predict_skymodel_list_rsexecute_workflow(future_vis, future_skymodel_list,
                                                                 context='2d', docal=True)
     skymodel_vislist = rsexecute.compute(skymodel_vislist, sync=True)
     vobs = sum_predict_results(skymodel_vislist)
     
     future_vobs = rsexecute.scatter(vobs)
     skymodel_vislist = crosssubtract_datamodels_skymodel_list_rsexecute_workflow(future_vobs, skymodel_vislist)
     
     skymodel_vislist = rsexecute.compute(skymodel_vislist, sync=True)
     
     result_skymodel = [SkyModel(components=None, image=self.skymodel_list[-1].image)
                        for v in skymodel_vislist]
     
     self.vis_list = rsexecute.scatter(self.vis_list)
     result_skymodel = invert_skymodel_list_rsexecute_workflow(skymodel_vislist, result_skymodel,
                                                                context='2d', docal=True)
     results = rsexecute.compute(result_skymodel, sync=True)
     assert numpy.max(numpy.abs(results[0][0].data)) > 0.0
     assert numpy.max(numpy.abs(results[0][1])) > 0.0
     if self.plot:
         import matplotlib.pyplot as plt
         from rascil.processing_components.image.operations import show_image
         show_image(results[0][0], title='Dirty image after cross-subtraction', vmax=0.1, vmin=-0.01)
         plt.show()
Ejemplo n.º 2
0
    def test_mpccal_ICAL_onesource(self):

        self.actualSetup(nsources=1, nvoronoi=1)

        model = create_empty_image_like(self.theta_list[0].image)

        if rsexecute.using_dask:
            progress = None
        else:
            progress = self.progress

        future_vis = rsexecute.scatter(self.all_skymodel_noniso_vis)
        future_model = rsexecute.scatter(model)
        future_theta_list = rsexecute.scatter(self.theta_list)
        result = mpccal_skymodel_list_rsexecute_workflow(future_vis, future_model, future_theta_list,
                                                         mpccal_progress=progress,
                                                         nmajor=5,
                                                         context='2d',
                                                         algorithm='hogbom',
                                                         scales=[0, 3, 10],
                                                         fractional_threshold=0.15, threshold=0.05,
                                                         gain=0.1, niter=1000, psf_support=256,
                                                         deconvolve_facets=8, deconvolve_overlap=16,
                                                         deconvolve_taper='tukey')

        (self.theta_list, residual) = rsexecute.compute(result, sync=True)

        combined_model = calculate_skymodel_equivalent_image(self.theta_list)

        psf_obs = invert_list_rsexecute_workflow([self.all_skymodel_noniso_vis], [model], context='2d', dopsf=True)
        result = restore_list_rsexecute_workflow([combined_model], psf_obs, [(residual, 0.0)])
        result = rsexecute.compute(result, sync=True)

        if self.persist: export_image_to_fits(residual,
                                              rascil_path('test_results/test_mpccal_ical_onesource_residual.fits'))
        if self.persist: export_image_to_fits(result[0],
                                              rascil_path('test_results/test_mpccal_ical_onesource_restored.fits'))
        if self.persist: export_image_to_fits(combined_model,
                                              rascil_path('test_results/test_mpccal_ical_onesource_deconvolved.fits'))

        recovered_mpccal_components = find_skycomponents(result[0], fwhm=2, threshold=0.32, npixels=12)

        def max_flux(elem):
            return numpy.max(elem.flux)

        recovered_mpccal_components = sorted(recovered_mpccal_components, key=max_flux, reverse=True)

        assert recovered_mpccal_components[0].name == 'Segment 0', recovered_mpccal_components[0].name
        assert numpy.abs(recovered_mpccal_components[0].flux[0, 0] - 1.138095494391862) < 1e-6, \
            recovered_mpccal_components[0].flux[0, 0]

        newscreen = create_empty_image_like(self.screen)
        gaintables = [th.gaintable for th in self.theta_list]
        newscreen, weights = grid_gaintable_to_screen(self.all_skymodel_noniso_blockvis, gaintables, newscreen)
        if self.persist: export_image_to_fits(newscreen,
                                              rascil_path('test_results/test_mpccal_ical_onesource_screen.fits'))
        if self.persist: export_image_to_fits(weights,
                                              rascil_path('test_results/test_mpccal_ical_onesource_screenweights.fits'))

        rsexecute.close()
Ejemplo n.º 3
0
    def test_predict(self):
        self.actualSetUp(zerow=True)

        self.skymodel_list = [
            rsexecute.execute(create_low_test_skymodel_from_gleam)(
                npixel=self.npixel,
                cellsize=self.cellsize,
                frequency=[self.frequency[f]],
                phasecentre=self.phasecentre,
                polarisation_frame=PolarisationFrame("stokesI"),
                flux_limit=0.3,
                flux_threshold=1.0,
                flux_max=5.0) for f, freq in enumerate(self.frequency)
        ]

        self.skymodel_list = rsexecute.compute(self.skymodel_list, sync=True)
        assert isinstance(self.skymodel_list[0].image,
                          Image), self.skymodel_list[0].image
        assert isinstance(self.skymodel_list[0].components[0],
                          Skycomponent), self.skymodel_list[0].components[0]
        assert len(self.skymodel_list[0].components) == 25, len(
            self.skymodel_list[0].components)
        assert numpy.max(numpy.abs(
            self.skymodel_list[0].image.data)) > 0.0, "Image is empty"

        self.skymodel_list = rsexecute.scatter(self.skymodel_list)
        skymodel_vislist = predict_skymodel_list_rsexecute_workflow(
            self.vis_list[0], self.skymodel_list, context='2d')
        skymodel_vislist = rsexecute.compute(skymodel_vislist, sync=True)
        assert numpy.max(numpy.abs(skymodel_vislist[0].vis)) > 0.0
Ejemplo n.º 4
0
 def test_predictcal(self):
     
     self.actualSetUp(zerow=True)
     
     future_vis = rsexecute.scatter(self.vis_list[0])
     future_skymodel = rsexecute.scatter(self.skymodel_list)
     skymodel_vislist = predict_skymodel_list_rsexecute_workflow(future_vis, future_skymodel,
                                                                  context='2d', docal=True)
     skymodel_vislist = rsexecute.compute(skymodel_vislist, sync=True)
     vobs = sum_predict_results(skymodel_vislist)
     
     if self.plot:
         def plotvis(i, v):
             import matplotlib.pyplot as plt
             uvr = numpy.hypot(v.u, v.v)
             amp = numpy.abs(v.vis[:, 0])
             plt.plot(uvr, amp, '.')
             plt.title(str(i))
             plt.show()
         
         plotvis(0, vobs)
    def actualSetUp(self,
                    add_errors=False,
                    nfreqwin=7,
                    dospectral=True,
                    dopol=False,
                    zerow=True):

        self.npixel = 512
        self.low = create_named_configuration('LOWBD2', rmax=750.0)
        self.freqwin = nfreqwin
        self.vis_list = list()
        self.ntimes = 5
        self.times = numpy.linspace(-3.0, +3.0, self.ntimes) * numpy.pi / 12.0
        self.frequency = numpy.linspace(0.8e8, 1.2e8, self.freqwin)

        if self.freqwin > 1:
            self.channelwidth = numpy.array(
                self.freqwin * [self.frequency[1] - self.frequency[0]])
        else:
            self.channelwidth = numpy.array([1e6])

        if dopol:
            self.vis_pol = PolarisationFrame('linear')
            self.image_pol = PolarisationFrame('stokesIQUV')
            f = numpy.array([100.0, 20.0, 0.0, 0.0])
        else:
            self.vis_pol = PolarisationFrame('stokesI')
            self.image_pol = PolarisationFrame('stokesI')
            f = numpy.array([100.0])

        if dospectral:
            flux = numpy.array(
                [f * numpy.power(freq / 1e8, -0.7) for freq in self.frequency])
        else:
            flux = numpy.array([f])

        self.phasecentre = SkyCoord(ra=+180.0 * u.deg,
                                    dec=-60.0 * u.deg,
                                    frame='icrs',
                                    equinox='J2000')
        self.blockvis_list = \
            [rsexecute.execute(ingest_unittest_visibility, nout=1)(self.low,
                                                                   [self.frequency[i]],
                                                                   [self.channelwidth[i]],
                                                                   self.times,
                                                                   self.vis_pol,
                                                                   self.phasecentre, block=True,
                                                                   zerow=zerow)
             for i in range(nfreqwin)]
        self.blockvis_list = rsexecute.compute(self.blockvis_list, sync=True)
        self.blockvis_list = rsexecute.scatter(self.blockvis_list)

        self.vis_list = [
            rsexecute.execute(convert_blockvisibility_to_visibility,
                              nout=1)(bv) for bv in self.blockvis_list
        ]
        self.vis_list = rsexecute.compute(self.vis_list, sync=True)
        self.vis_list = rsexecute.scatter(self.vis_list)

        self.model_imagelist = [
            rsexecute.execute(create_unittest_model,
                              nout=1)(self.vis_list[i],
                                      self.image_pol,
                                      npixel=self.npixel,
                                      cellsize=0.0005) for i in range(nfreqwin)
        ]
        self.model_imagelist = rsexecute.compute(self.model_imagelist,
                                                 sync=True)
        self.model_imagelist = rsexecute.scatter(self.model_imagelist)

        self.components_list = [
            rsexecute.execute(create_unittest_components)(
                self.model_imagelist[freqwin],
                flux[freqwin, :][numpy.newaxis, :])
            for freqwin, m in enumerate(self.model_imagelist)
        ]
        self.components_list = rsexecute.compute(self.components_list,
                                                 sync=True)
        self.components_list = rsexecute.scatter(self.components_list)

        self.blockvis_list = [
            rsexecute.execute(dft_skycomponent_visibility)(
                self.blockvis_list[freqwin], self.components_list[freqwin])
            for freqwin, _ in enumerate(self.blockvis_list)
        ]
        self.blockvis_list = rsexecute.compute(self.blockvis_list, sync=True)
        self.vis = self.blockvis_list[0]
        self.blockvis_list = rsexecute.scatter(self.blockvis_list)

        self.model_imagelist = [
            rsexecute.execute(insert_skycomponent,
                              nout=1)(self.model_imagelist[freqwin],
                                      self.components_list[freqwin])
            for freqwin in range(nfreqwin)
        ]
        self.model_imagelist = rsexecute.compute(self.model_imagelist,
                                                 sync=True)
        model = self.model_imagelist[0]
        self.cmodel = smooth_image(model)
        if self.persist:
            export_image_to_fits(
                model, '%s/test_pipelines_rsexecute_model.fits' % self.dir)
            export_image_to_fits(
                self.cmodel,
                '%s/test_pipelines_rsexecute_cmodel.fits' % self.dir)

        if add_errors:
            gt = create_gaintable_from_blockvisibility(self.vis)
            gt = simulate_gaintable(gt,
                                    phase_error=0.1,
                                    amplitude_error=0.0,
                                    smooth_channels=1,
                                    leakage=0.0)
            self.blockvis_list = [
                rsexecute.execute(apply_gaintable,
                                  nout=1)(self.blockvis_list[i], gt)
                for i in range(self.freqwin)
            ]
            self.blockvis_list = rsexecute.compute(self.blockvis_list,
                                                   sync=True)
            self.blockvis_list = rsexecute.scatter(self.blockvis_list)

        self.vis_list = [
            rsexecute.execute(convert_blockvisibility_to_visibility)(bv)
            for bv in self.blockvis_list
        ]
        self.vis_list = rsexecute.compute(self.vis_list, sync=True)
        self.vis_list = rsexecute.scatter(self.vis_list)

        self.model_imagelist = [
            rsexecute.execute(create_unittest_model,
                              nout=1)(self.vis_list[i],
                                      self.image_pol,
                                      npixel=self.npixel,
                                      cellsize=0.0005) for i in range(nfreqwin)
        ]
        self.model_imagelist = rsexecute.compute(self.model_imagelist,
                                                 sync=True)
        self.model_imagelist = rsexecute.scatter(self.model_imagelist)
Ejemplo n.º 6
0
        print("    Using %s Dask workers" % nworkers)

    # Uniform weighting
    psf_list = [
        rsexecute.execute(create_image_from_visibility)(
            v,
            npixel=npixel,
            frequency=frequency,
            nchan=nfreqwin,
            cellsize=cellsize,
            phasecentre=phasecentre,
            polarisation_frame=PolarisationFrame("stokesI"))
        for v in future_bvis_list
    ]
    psf_list = rsexecute.compute(psf_list, sync=True)
    future_psf_list = rsexecute.scatter(psf_list)
    del psf_list

    if use_natural:
        print("Using natural weighting")
    else:
        print("Using uniform weighting")

        vis_list = [
            rsexecute.execute(convert_blockvisibility_to_visibility)(bvis)
            for bvis in future_bvis_list
        ]
        vis_list = weight_list_rsexecute_workflow(vis_list, future_psf_list)
        bvis_list = [
            rsexecute.execute(convert_visibility_to_blockvisibility)(vis)
            for vis in vis_list
Ejemplo n.º 7
0
    def actualSetup(self, nsources=None, nvoronoi=None):

        # Set up the observation: 10 minutes at transit, with 10s integration.
        # Skip 5/6 points to avoid outstation redundancy

        nfreqwin = 1
        ntimes = 3
        self.rmax = 2500.0
        dec = -40.0 * u.deg
        frequency = [1e8]
        channel_bandwidth = [0.1e8]
        times = numpy.linspace(-10.0, 10.0, ntimes) * numpy.pi / (3600.0 * 12.0)

        phasecentre = SkyCoord(ra=+0.0 * u.deg, dec=dec, frame='icrs', equinox='J2000')
        low = create_named_configuration('LOWBD2', rmax=self.rmax)

        centre = numpy.mean(low.xyz, axis=0)
        distance = numpy.hypot(low.xyz[:, 0] - centre[0],
                               low.xyz[:, 1] - centre[1],
                               low.xyz[:, 2] - centre[2])
        lowouter = low.data[distance > 1000.0][::6]
        lowcore = low.data[distance < 1000.0][::3]
        low.data = numpy.hstack((lowcore, lowouter))

        blockvis = create_blockvisibility(low, times, frequency=frequency, channel_bandwidth=channel_bandwidth,
                                          weight=1.0, phasecentre=phasecentre,
                                          polarisation_frame=PolarisationFrame("stokesI"), zerow=True)

        vis = convert_blockvisibility_to_visibility(blockvis)
        advice = advise_wide_field(vis, guard_band_image=2.0, delA=0.02)

        cellsize = advice['cellsize']
        npixel = 512

        small_model = create_image_from_visibility(
            blockvis,
            npixel=512,
            frequency=frequency,
            nchan=nfreqwin,
            cellsize=cellsize,
            phasecentre=phasecentre)

        vis.data['imaging_weight'][...] = vis.data['weight'][...]
        vis = weight_list_serial_workflow([vis], [small_model])[0]
        vis = taper_list_serial_workflow([vis], 3 * cellsize)[0]

        blockvis = convert_visibility_to_blockvisibility(vis)

        # ### Generate the model from the GLEAM catalog, including application of the primary beam.

        beam = create_image_from_visibility(blockvis, npixel=npixel, frequency=frequency,
                                            nchan=nfreqwin, cellsize=cellsize, phasecentre=phasecentre)
        beam = create_low_test_beam(beam, use_local=False)

        flux_limit = 0.5
        original_gleam_components = create_low_test_skycomponents_from_gleam(flux_limit=flux_limit,
                                                                             phasecentre=phasecentre,
                                                                             frequency=frequency,
                                                                             polarisation_frame=PolarisationFrame(
                                                                                 'stokesI'),
                                                                             radius=0.15)

        all_components = apply_beam_to_skycomponent(original_gleam_components, beam)
        all_components = filter_skycomponents_by_flux(all_components, flux_min=flux_limit)
        voronoi_components = filter_skycomponents_by_flux(all_components, flux_min=1.5)

        def max_flux(elem):
            return numpy.max(elem.flux)

        voronoi_components = sorted(voronoi_components, key=max_flux, reverse=True)

        if nsources is not None:
            all_components = [all_components[0]]

        if nvoronoi is not None:
            voronoi_components = [voronoi_components[0]]

        self.screen = import_image_from_fits(rascil_data_path('models/test_mpc_screen.fits'))
        all_gaintables = create_gaintable_from_screen(blockvis, all_components,
                                                      self.screen)

        gleam_skymodel_noniso = [SkyModel(components=[all_components[i]], gaintable=all_gaintables[i])
                                 for i, sm in enumerate(all_components)]

        # ### Now predict the visibility for each skymodel and apply the gaintable for that skymodel,
        # returning a list of visibilities, one for each skymodel. We then sum these to obtain
        # the total predicted visibility. All images and skycomponents in the same skymodel
        # get the same gaintable applied which means that in this case each skycomponent has a separate gaintable.

        self.all_skymodel_noniso_vis = convert_blockvisibility_to_visibility(blockvis)

        ngroup = 8
        future_vis = rsexecute.scatter(self.all_skymodel_noniso_vis)
        chunks = [gleam_skymodel_noniso[i:i + ngroup] for i in range(0, len(gleam_skymodel_noniso), ngroup)]
        for chunk in chunks:
            result = predict_skymodel_list_rsexecute_workflow(future_vis, chunk, context='2d', docal=True)
            work_vis = rsexecute.compute(result, sync=True)
            for w in work_vis:
                self.all_skymodel_noniso_vis.data['vis'] += w.data['vis']
            assert numpy.max(numpy.abs(self.all_skymodel_noniso_vis.data['vis'])) > 0.0

        self.all_skymodel_noniso_blockvis = convert_visibility_to_blockvisibility(self.all_skymodel_noniso_vis)

        # ### Remove weaker of components that are too close (0.02 rad)
        idx, voronoi_components = remove_neighbouring_components(voronoi_components, 0.02)

        model = create_image_from_visibility(blockvis, npixel=npixel, frequency=frequency,
                                             nchan=nfreqwin, cellsize=cellsize, phasecentre=phasecentre)

        # Use the gaintable for the brightest component as the starting gaintable
        all_gaintables[0].gain[...] = numpy.conjugate(all_gaintables[0].gain[...])
        all_gaintables[0].gain[...] = 1.0 + 0.0j
        self.theta_list = initialize_skymodel_voronoi(model, voronoi_components, all_gaintables[0])
Ejemplo n.º 8
0
 def actualSetUp(self, add_errors=False, freqwin=7, block=False, dospectral=True, dopol=False,
                 zerow=True):
     
     self.npixel = 256
     self.low = create_named_configuration('LOWBD2', rmax=750.0)
     self.freqwin = freqwin
     self.vis_list = list()
     self.ntimes = 5
     cellsize = 0.001
     self.times = numpy.linspace(-3.0, +3.0, self.ntimes) * numpy.pi / 12.0
     self.frequency = numpy.linspace(0.8e8, 1.2e8, self.freqwin)
     
     if freqwin > 1:
         self.channelwidth = numpy.array(freqwin * [self.frequency[1] - self.frequency[0]])
     else:
         self.channelwidth = numpy.array([1e6])
     
     if dopol:
         self.vis_pol = PolarisationFrame('linear')
         self.image_pol = PolarisationFrame('stokesIQUV')
         f = numpy.array([100.0, 20.0, -10.0, 1.0])
     else:
         self.vis_pol = PolarisationFrame('stokesI')
         self.image_pol = PolarisationFrame('stokesI')
         f = numpy.array([100.0])
     
     if dospectral:
         flux = numpy.array([f * numpy.power(freq / 1e8, -0.7) for freq in self.frequency])
     else:
         flux = numpy.array([f])
     
     self.phasecentre = SkyCoord(ra=+180.0 * u.deg, dec=-60.0 * u.deg, frame='icrs', equinox='J2000')
     self.vis_list = [rsexecute.execute(ingest_unittest_visibility)(self.low,
                                                                     [self.frequency[freqwin]],
                                                                     [self.channelwidth[freqwin]],
                                                                     self.times,
                                                                     self.vis_pol,
                                                                     self.phasecentre, block=block,
                                                                     zerow=zerow)
                      for freqwin, _ in enumerate(self.frequency)]
     
     self.model_imagelist = [rsexecute.execute(create_unittest_model, nout=freqwin)(self.vis_list[freqwin],
                                                                                     self.image_pol,
                                                                                     cellsize=cellsize,
                                                                                     npixel=self.npixel)
                             for freqwin, _ in enumerate(self.frequency)]
     
     self.componentlist = [rsexecute.execute(create_unittest_components)(self.model_imagelist[freqwin],
                                                                          flux[freqwin, :][numpy.newaxis, :])
                           for freqwin, _ in enumerate(self.frequency)]
     
     self.model_imagelist = [rsexecute.execute(insert_skycomponent, nout=1)(self.model_imagelist[freqwin],
                                                                             self.componentlist[freqwin])
                             for freqwin, _ in enumerate(self.frequency)]
     
     self.vis_list = [rsexecute.execute(predict_skycomponent_visibility)(self.vis_list[freqwin],
                                                                          self.componentlist[freqwin])
                      for freqwin, _ in enumerate(self.frequency)]
     
     # Calculate the model convolved with a Gaussian.
     
     self.model_imagelist = rsexecute.compute(self.model_imagelist, sync=True)
     model = self.model_imagelist[0]
     
     self.cmodel = smooth_image(model)
     if self.persist: export_image_to_fits(model, '%s/test_imaging_rsexecute_deconvolved_model.fits' % self.dir)
     if self.persist: export_image_to_fits(self.cmodel, '%s/test_imaging_rsexecute_deconvolved_cmodel.fits' % self.dir)
     
     if add_errors and block:
         self.vis_list = [rsexecute.execute(insert_unittest_errors)(self.vis_list[i])
                          for i, _ in enumerate(self.frequency)]
     
     #        self.vis_list = rsexecute.compute(self.vis_list, sync=True)
     self.vis_list = rsexecute.persist(self.vis_list)
     self.model_imagelist = rsexecute.scatter(self.model_imagelist)
def trial_case(results,
               seed=180555,
               context='wstack',
               nworkers=8,
               threads_per_worker=1,
               memory=8,
               processes=True,
               order='frequency',
               nfreqwin=7,
               ntimes=3,
               rmax=750.0,
               facets=1,
               wprojection_planes=1,
               use_dask=True,
               use_serial_imaging=True,
               flux_limit=0.3,
               nmajor=5,
               dft_threshold=1.0,
               use_serial_clean=True,
               write_fits=False):
    """ Single trial for performance-timings
    
    Simulates visibilities from GLEAM including phase errors
    Makes dirty image and PSF
    Runs ICAL pipeline
    
    The results are in a dictionary:
    
    'context': input - a string describing concisely the purpose of the test
    'time overall',  overall execution time (s)
    'time predict', time to execute GLEAM prediction graph
    'time invert', time to make dirty image
    'time invert graph', time to make dirty image graph
    'time ICAL graph', time to create ICAL graph
    'time ICAL', time to execute ICAL graph
    'context', type of imaging e.g. 'wstack'
    'nworkers', number of workers to create
    'threads_per_worker',
    'nnodes', Number of nodes,
    'processes', 'order', Ordering of data_models
    'nfreqwin', Number of frequency windows in simulation
    'ntimes', Number of hour angles in simulation
    'rmax', Maximum radius of stations used in simulation (m)
    'facets', Number of facets in deconvolution and imaging
    'wprojection_planes', Number of wprojection planes
    'vis_slices', Number of visibility slices (per Visibbility)
    'npixel', Number of pixels in image
    'cellsize', Cellsize in radians
    'seed', Random number seed
    'dirty_max', Maximum in dirty image
    'dirty_min', Minimum in dirty image
    'restored_max',
    'restored_min',
    'deconvolved_max',
    'deconvolved_min',
    'residual_max',
    'residual_min',
    'git_info', GIT hash (not definitive since local mods are possible)
    
    :param results: Initial state
    :param seed: Random number seed (used in gain simulations)
    :param context: imaging context
    :param context: Type of context: '2d'|'timeslice'|'wstack'
    :param nworkers: Number of dask workers to use
    :param threads_per_worker: Number of threads per worker
    :param processes: Use processes instead of threads 'processes'|'threads'
    :param order: See simulate_list_list_rsexecute_workflow_workflowkflow
    :param nfreqwin: See simulate_list_list_rsexecute_workflow_workflowkflow
    :param ntimes: See simulate_list_list_rsexecute_workflow_workflowkflow
    :param rmax: See simulate_list_list_rsexecute_workflow_workflowkflow
    :param facets: Number of facets to use
    :param wprojection_planes: Number of wprojection planes to use
    :param use_dask: Use dask or immediate evaluation
    :return: results dictionary
    """
    if use_dask:
        scheduler = os.getenv('RASCIL_DASK_SCHEDULER', None)
        if scheduler is not None:
            client = get_dask_client(n_workers=nworkers,
                                     memory_limit=memory * 1024 * 1024 * 1024,
                                     threads_per_worker=threads_per_worker)
            rsexecute.set_client(client=client)
        else:
            rsexecute.set_client(threads_per_worker=threads_per_worker,
                                 processes=threads_per_worker == 1,
                                 memory_limit=memory * 1024 * 1024 * 1024,
                                 n_workers=nworkers)
        print("Defined %d workers" % (nworkers))
    else:
        rsexecute.set_client(use_dask=use_dask)
        results['nnodes'] = 1

    def init_logging():
        logging.basicConfig(
            filename='pipelines_rsexecute_timings.log',
            filemode='w',
            format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
            datefmt='%H:%M:%S',
            level=logging.INFO)

    init_logging()
    log = logging.getLogger()

    # Initialise logging on the workers. This appears to only work using the process scheduler.
    rsexecute.run(init_logging)

    def lprint(*args):
        log.info(*args)
        print(*args)

    lprint("Starting pipelines_rsexecute_timings")

    numpy.random.seed(seed)
    results['seed'] = seed

    start_all = time.time()

    results['context'] = context
    results['hostname'] = socket.gethostname()
    results['git_hash'] = git_hash()
    results['epoch'] = time.strftime("%Y-%m-%d %H:%M:%S")

    lprint("Context is %s" % context)

    results['nworkers'] = nworkers
    results['threads_per_worker'] = threads_per_worker
    results['processes'] = processes
    results['memory'] = memory
    results['order'] = order
    results['nfreqwin'] = nfreqwin
    results['ntimes'] = ntimes
    results['rmax'] = rmax
    results['facets'] = facets
    results['wprojection_planes'] = wprojection_planes
    results['dft threshold'] = dft_threshold

    results['use_dask'] = use_dask

    lprint("At start, configuration is:")
    lprint(sort_dict(results))

    # Parameters determining scale of simulation.
    frequency = numpy.linspace(1.0e8, 1.2e8, nfreqwin)
    centre = nfreqwin // 2
    if nfreqwin > 1:
        channel_bandwidth = numpy.array(nfreqwin *
                                        [frequency[1] - frequency[0]])
    else:
        channel_bandwidth = numpy.array([1e6])

    times = numpy.linspace(-numpy.pi / 4.0, numpy.pi / 4.0, ntimes)
    phasecentre = SkyCoord(ra=+0.0 * u.deg,
                           dec=-40.0 * u.deg,
                           frame='icrs',
                           equinox='J2000')

    lprint("****** Visibility creation ******")
    # Create the empty BlockVisibility's and persist these on the cluster
    tmp_bvis_list = simulate_list_rsexecute_workflow(
        'LOWBD2',
        frequency=frequency,
        channel_bandwidth=channel_bandwidth,
        times=times,
        phasecentre=phasecentre,
        order=order,
        format='blockvis',
        rmax=rmax)
    tmp_vis_list = [
        rsexecute.execute(convert_blockvisibility_to_visibility)(bv)
        for bv in tmp_bvis_list
    ]
    tmp_vis_list = rsexecute.client.compute(tmp_vis_list, sync=True)
    vis_list = rsexecute.gather(tmp_vis_list)

    import matplotlib.pyplot as plt
    plt.clf()
    plt.hist(vis_list[0].w, bins=100)
    plt.title('Histogram of w samples: rms=%.1f (wavelengths)' %
              numpy.std(vis_list[0].w))
    plt.xlabel('W (wavelengths)')
    #plt.show()
    plt.clf()
    plt.hist(vis_list[0].uvdist, bins=100)
    plt.title('Histogram of uvdistance samples')
    plt.xlabel('UV Distance (wavelengths)')
    #plt.show()

    rsexecute.client.cancel(tmp_vis_list)
    future_vis_list = rsexecute.scatter(vis_list)

    # Find the best imaging parameters but don't bring the vis_list back here
    print("****** Finding wide field parameters ******")
    future_advice = [
        rsexecute.execute(advise_wide_field)(
            v,
            guard_band_image=6.0,
            delA=0.1,
            facets=facets,
            wprojection_planes=wprojection_planes,
            oversampling_synthesised_beam=4.0) for v in future_vis_list
    ]

    future_advice = rsexecute.compute(future_advice)
    advice = rsexecute.client.gather(future_advice)[-1]
    rsexecute.client.cancel(future_advice)

    # Deconvolution via sub-images requires 2^n
    npixel = advice['npixels2']
    results['npixel'] = npixel
    cellsize = advice['cellsize']
    results['cellsize'] = cellsize
    lprint("Image will have %d by %d pixels, cellsize = %.6f rad" %
           (npixel, npixel, cellsize))

    # Create an empty model image
    tmp_model_list = [
        rsexecute.execute(create_image)(
            npixel=npixel,
            cellsize=cellsize,
            frequency=[frequency[f]],
            channel_bandwidth=[channel_bandwidth[f]],
            phasecentre=phasecentre,
            polarisation_frame=PolarisationFrame("stokesI"))
        for f, freq in enumerate(frequency)
    ]
    model_list = rsexecute.compute(tmp_model_list, sync=True)
    future_model_list = rsexecute.scatter(model_list)

    lprint("****** Setting up imaging parameters ******")
    # Now set up the imaging parameters
    template_model = create_image(
        npixel=npixel,
        cellsize=cellsize,
        frequency=[frequency[centre]],
        phasecentre=phasecentre,
        channel_bandwidth=[channel_bandwidth[centre]],
        polarisation_frame=PolarisationFrame("stokesI"))
    gcfcf = [create_pswf_convolutionfunction(template_model)]

    if context == 'timeslice':
        vis_slices = ntimes
        lprint("Using timeslice with %d slices" % vis_slices)
    elif context == '2d':
        vis_slices = 1
    elif context == "wprojection":
        wstep = advice['wstep']
        nw = advice['wprojection_planes']
        vis_slices = 1
        support = advice['nwpixels']
        results['wprojection_planes'] = nw

        lprint("****** Starting W projection kernel creation ******")
        lprint("Using wprojection with %d planes with wstep %.1f wavelengths" %
               (nw, wstep))
        lprint("Support of wprojection = %d pixels" % support)
        gcfcf = [
            create_awterm_convolutionfunction(template_model,
                                              nw=nw,
                                              wstep=wstep,
                                              oversampling=4,
                                              support=support,
                                              use_aaf=True)
        ]
        lprint("Size of W projection gcf, cf = %.2E bytes" % get_size(gcfcf))
    else:
        context = 'wstack'
        vis_slices = advice['vis_slices']
        lprint("Using wstack with %d slices" % vis_slices)

    gcfcf = rsexecute.scatter(gcfcf, broadcast=True)

    results['vis_slices'] = vis_slices

    # Make a skymodel from gleam, with bright sources as components and weak sources in an image
    lprint("****** Starting GLEAM skymodel creation ******")
    future_skymodel_list = [
        rsexecute.execute(create_low_test_skymodel_from_gleam)(
            npixel=npixel,
            cellsize=cellsize,
            frequency=[frequency[f]],
            phasecentre=phasecentre,
            polarisation_frame=PolarisationFrame("stokesI"),
            flux_limit=flux_limit,
            flux_threshold=dft_threshold,
            flux_max=5.0) for f, freq in enumerate(frequency)
    ]

    # We use predict_skymodel so that we can use skycomponents as well as images
    lprint("****** Starting GLEAM skymodel prediction ******")
    predicted_vis_list = [
        predict_skymodel_list_rsexecute_workflow(future_vis_list[f],
                                                 [future_skymodel_list[f]],
                                                 context=context,
                                                 vis_slices=vis_slices,
                                                 facets=facets,
                                                 gcfcf=gcfcf)[0]
        for f, freq in enumerate(frequency)
    ]

    # Corrupt the visibility for the GLEAM model
    lprint("****** Visibility corruption ******")
    tmp_corrupted_vis_list = corrupt_list_rsexecute_workflow(
        predicted_vis_list, phase_error=1.0, seed=seed)
    lprint("****** Weighting and tapering ******")
    tmp_corrupted_vis_list = weight_list_rsexecute_workflow(
        tmp_corrupted_vis_list, future_model_list)
    tmp_corrupted_vis_list = taper_list_rsexecute_workflow(
        tmp_corrupted_vis_list, 0.003 * 750.0 / rmax)
    tmp_corrupted_vis_list = rsexecute.compute(tmp_corrupted_vis_list,
                                               sync=True)

    corrupted_vis_list = rsexecute.gather(tmp_corrupted_vis_list)
    # rsexecute.client.cancel(predicted_vis_list)
    rsexecute.client.cancel(tmp_corrupted_vis_list)
    future_corrupted_vis_list = rsexecute.scatter(corrupted_vis_list)

    # At this point the only futures are of scatter'ed data so no repeated calculations should be
    # incurred.
    lprint("****** Starting dirty image calculation ******")
    start = time.time()
    dirty_list = invert_list_rsexecute_workflow(
        future_corrupted_vis_list,
        future_model_list,
        vis_slices=vis_slices,
        context=context,
        facets=facets,
        use_serial_invert=use_serial_imaging,
        gcfcf=gcfcf)
    results['size invert graph'] = get_size(dirty_list)
    lprint('Size of dirty graph is %.3E bytes' %
           (results['size invert graph']))
    end = time.time()
    results['time invert graph'] = end - start
    lprint("Construction of invert graph took %.3f seconds" % (end - start))

    start = time.time()
    dirty, sumwt = rsexecute.compute(dirty_list, sync=True)[centre]
    end = time.time()
    results['time invert'] = end - start
    lprint("Dirty image invert took %.3f seconds" % (end - start))
    lprint("Maximum in dirty image is %f, sumwt is %s" %
           (numpy.max(numpy.abs(dirty.data)), str(sumwt)))
    qa = qa_image(dirty)
    results['dirty_max'] = qa.data['max']
    results['dirty_min'] = qa.data['min']
    if write_fits:
        export_image_to_fits(
            dirty, "pipelines_rsexecute_timings-%s-dirty.fits" % context)

    lprint("****** Starting prediction ******")
    start = time.time()
    tmp_vis_list = predict_list_rsexecute_workflow(
        future_corrupted_vis_list,
        future_model_list,
        vis_slices=vis_slices,
        context=context,
        facets=facets,
        use_serial_predict=use_serial_imaging,
        gcfcf=gcfcf)
    result = rsexecute.compute(tmp_vis_list, sync=True)
    # rsexecute.client.cancel(tmp_vis_list)
    end = time.time()
    results['time predict'] = end - start
    lprint("Predict took %.3f seconds" % (end - start))

    # Create the ICAL pipeline to run major cycles, starting selfcal at cycle 1. A global solution across all
    # frequencies (i.e. Visibilities) is performed.

    print("Using subimage clean")
    deconvolve_facets = 8
    deconvolve_overlap = 16
    deconvolve_taper = 'tukey'

    lprint("****** Starting ICAL graph creation ******")

    controls = create_calibration_controls()

    controls['T']['first_selfcal'] = 1
    controls['T']['timeslice'] = 'auto'

    start = time.time()
    ical_list = ical_list_rsexecute_workflow(
        future_corrupted_vis_list,
        model_imagelist=future_model_list,
        context=context,
        vis_slices=vis_slices,
        scales=[0, 3, 10],
        algorithm='mmclean',
        nmoment=3,
        niter=1000,
        fractional_threshold=0.1,
        threshold=0.01,
        nmajor=nmajor,
        gain=0.25,
        psf_support=64,
        deconvolve_facets=deconvolve_facets,
        deconvolve_overlap=deconvolve_overlap,
        deconvolve_taper=deconvolve_taper,
        timeslice='auto',
        global_solution=True,
        do_selfcal=True,
        calibration_context='T',
        controls=controls,
        use_serial_predict=use_serial_imaging,
        use_serial_invert=use_serial_imaging,
        use_serial_clean=use_serial_clean,
        gcfcf=gcfcf)

    results['size ICAL graph'] = get_size(ical_list)
    lprint('Size of ICAL graph is %.3E bytes' % results['size ICAL graph'])
    end = time.time()
    results['time ICAL graph'] = end - start
    lprint("Construction of ICAL graph took %.3f seconds" % (end - start))

    print("Current objects on cluster: ")
    pp.pprint(rsexecute.client.who_has())
    #
    # Execute the graph
    lprint("****** Executing ICAL graph ******")
    start = time.time()
    deconvolved, residual, restored, gaintables = rsexecute.compute(ical_list,
                                                                    sync=True)
    end = time.time()

    results['time ICAL'] = end - start
    lprint("ICAL graph execution took %.3f seconds" % (end - start))
    qa = qa_image(deconvolved[centre])
    results['deconvolved_max'] = qa.data['max']
    results['deconvolved_min'] = qa.data['min']
    deconvolved_cube = image_gather_channels(deconvolved)
    if write_fits:
        export_image_to_fits(
            deconvolved_cube,
            "pipelines_rsexecute_timings-%s-ical_deconvolved.fits" % context)

    qa = qa_image(residual[centre][0])
    results['residual_max'] = qa.data['max']
    results['residual_min'] = qa.data['min']
    residual_cube = remove_sumwt(residual)
    residual_cube = image_gather_channels(residual_cube)
    if write_fits:
        export_image_to_fits(
            residual_cube,
            "pipelines_rsexecute_timings-%s-ical_residual.fits" % context)

    qa = qa_image(restored[centre])
    results['restored_max'] = qa.data['max']
    results['restored_min'] = qa.data['min']
    restored_cube = image_gather_channels(restored)
    if write_fits:
        export_image_to_fits(
            restored_cube,
            "pipelines_rsexecute_timings-%s-ical_restored.fits" % context)
    #
    rsexecute.close()

    end_all = time.time()
    results['time overall'] = end_all - start_all

    lprint("At end, results are:")
    results = sort_dict(results)
    lprint(results)

    return results
Ejemplo n.º 10
0
    def test_apply_voltage_pattern_image_pointsource(self):
        self.createVis(rmax=1e3)
        telescope = 'MID_FEKO_B2'
        vpol = PolarisationFrame("linear")
        self.times = numpy.linspace(-4, +4, 8) * numpy.pi / 12.0
        bvis = create_blockvisibility(self.config,
                                      self.times,
                                      self.frequency,
                                      channel_bandwidth=self.channel_bandwidth,
                                      phasecentre=self.phasecentre,
                                      weight=1.0,
                                      polarisation_frame=vpol,
                                      zerow=True)
        cellsize = advise_wide_field(bvis)['cellsize']

        pbmodel = create_image_from_visibility(
            bvis,
            cellsize=self.cellsize,
            npixel=self.npixel,
            override_cellsize=False,
            polarisation_frame=PolarisationFrame("stokesIQUV"))
        vpbeam = create_vp(pbmodel, telescope=telescope, use_local=False)
        vpbeam.wcs.wcs.ctype[0] = 'RA---SIN'
        vpbeam.wcs.wcs.ctype[1] = 'DEC--SIN'
        vpbeam.wcs.wcs.crval[0] = pbmodel.wcs.wcs.crval[0]
        vpbeam.wcs.wcs.crval[1] = pbmodel.wcs.wcs.crval[1]

        s3_components = create_test_skycomponents_from_s3(
            flux_limit=0.1,
            phasecentre=self.phasecentre,
            frequency=self.frequency,
            polarisation_frame=PolarisationFrame('stokesI'),
            radius=1.5 * numpy.pi / 180.0)

        for comp in s3_components:
            comp.polarisation_frame = PolarisationFrame('stokesIQUV')
            comp.flux = numpy.array([[comp.flux[0, 0], 0.0, 0.0, 0.0]])

        s3_components = filter_skycomponents_by_flux(s3_components, 0.0, 10.0)

        from rascil.processing_components.image import show_image
        import matplotlib.pyplot as plt
        plt.clf()
        show_image(vpbeam, components=s3_components)
        plt.show(block=False)

        vpcomp = apply_voltage_pattern_to_skycomponent(s3_components, vpbeam)
        bvis.data['vis'][...] = 0.0 + 0.0j
        bvis = dft_skycomponent_visibility(bvis, vpcomp)

        rec_comp = idft_visibility_skycomponent(bvis, vpcomp)[0]

        stokes_comp = list()
        for comp in rec_comp:
            stokes_comp.append(
                convert_pol_frame(comp.flux[0], PolarisationFrame("linear"),
                                  PolarisationFrame("stokesIQUV")))

        stokesI = numpy.abs(
            numpy.array([comp_flux[0] for comp_flux in stokes_comp]).real)
        stokesQ = numpy.abs(
            numpy.array([comp_flux[1] for comp_flux in stokes_comp]).real)
        stokesU = numpy.abs(
            numpy.array([comp_flux[2] for comp_flux in stokes_comp]).real)
        stokesV = numpy.abs(
            numpy.array([comp_flux[3] for comp_flux in stokes_comp]).real)
        plt.clf()
        plt.loglog(stokesI, stokesQ, '.', label='Q')
        plt.loglog(stokesI, stokesU, '.', label='U')
        plt.loglog(stokesI, stokesV, '.', label='V')
        plt.xlabel("Stokes Flux I (Jy)")
        plt.ylabel("Flux (Jy)")
        plt.legend()
        plt.savefig('%s/test_primary_beams_pol_rsexecute_stokes_errors.png' %
                    self.dir)
        plt.show(block=False)

        split_times = False
        if split_times:
            bvis_list = list()
            for rows in vis_timeslice_iter(bvis, vis_slices=8):
                bvis_list.append(create_visibility_from_rows(bvis, rows))
        else:
            bvis_list = [bvis]

        bvis_list = rsexecute.scatter(bvis_list)

        model_list = \
            [rsexecute.execute(create_image_from_visibility, nout=1)(bv, cellsize=cellsize, npixel=4096,
                                                                     phasecentre=self.phasecentre,
                                                                     override_cellsize=False,
                                                                     polarisation_frame=PolarisationFrame("stokesIQUV"))
             for bv in bvis_list]

        model_list = rsexecute.persist(model_list)
        bvis_list = weight_list_rsexecute_workflow(bvis_list, model_list)

        continuum_imaging_list = \
            continuum_imaging_list_rsexecute_workflow(bvis_list, model_list,
                                                      context='2d',
                                                      algorithm='hogbom',
                                                      facets=1,
                                                      niter=1000,
                                                      fractional_threshold=0.1,
                                                      threshold=1e-4,
                                                      nmajor=5, gain=0.1,
                                                      deconvolve_facets=4,
                                                      deconvolve_overlap=32,
                                                      deconvolve_taper='tukey',
                                                      psf_support=64,
                                                      restore_facets=4, psfwidth=1.0)
        clean, residual, restored = rsexecute.compute(continuum_imaging_list,
                                                      sync=True)
        centre = 0
        if self.persist:
            export_image_to_fits(
                clean[centre],
                '%s/test_primary_beams_pol_rsexecute_clean.fits' % self.dir)
            export_image_to_fits(
                residual[centre][0],
                '%s/test_primary_beams_pol_rsexecute_residual.fits' % self.dir)
            export_image_to_fits(
                restored[centre],
                '%s/test_primary_beams_pol_rsexecute_restored.fits' % self.dir)

        plt.clf()
        show_image(restored[centre])
        plt.show(block=False)

        qa = qa_image(restored[centre])
        assert numpy.abs(qa.data['max'] - 0.9953017707113947) < 1.0e-7, str(qa)
        assert numpy.abs(qa.data['min'] +
                         0.0036396480874570846) < 1.0e-7, str(qa)
Ejemplo n.º 11
0
    cellsize = 0.001
    npixel = 1024
    pol_frame = PolarisationFrame("stokesI")

    model_list = [
        rsexecute.execute(create_image_from_visibility)(
            v, npixel=npixel, cellsize=cellsize, polarisation_frame=pol_frame)
        for v in vis_list
    ]

    print('Creating model images')
    model_list = rsexecute.compute(model_list, sync=True)

    print('Creating graph')
    future_vis_list = rsexecute.scatter(vis_list)
    future_model_list = rsexecute.scatter(model_list)

    controls = create_calibration_controls()

    controls['T']['first_selfcal'] = 1
    controls['T']['phase_only'] = True
    controls['T']['timeslice'] = 'auto'

    controls['G']['first_selfcal'] = 3
    controls['G']['timeslice'] = 'auto'

    controls['B']['first_selfcal'] = 4
    controls['B']['timeslice'] = 1e5

    ical_list = ical_list_rsexecute_workflow(future_vis_list,