def setUp(self):

        client = get_dask_Client(memory_limit=4 * 1024 * 1024 * 1024)
        arlexecute.set_client(client)

        from data_models.parameters import arl_path
        self.dir = arl_path('test_results')
    def setUp(self):

        from data_models.parameters import arl_path
        self.dir = arl_path('test_results')

        arlexecute.set_client(use_dask=False)

        numpy.random.seed(180555)
예제 #3
0
    def test_useFunction(self):
        def square(x):
            return x**2

        arlexecute.set_client(use_dask=False)
        graph = arlexecute.execute(square)(numpy.arange(10))
        assert (arlexecute.compute(graph) == numpy.array(
            [0, 1, 4, 9, 16, 25, 36, 49, 64, 81])).all()
        arlexecute.close()
 def setUp(self):
 
     from data_models.parameters import arl_path
     self.dir = arl_path('test_results')
     
     self.frequency = numpy.linspace(1e8, 1.5e8, 3)
     self.channel_bandwidth = numpy.array([2.5e7, 2.5e7, 2.5e7])
     self.phasecentre = SkyCoord(ra=+15.0 * u.deg, dec=-60.0 * u.deg, frame='icrs', equinox='J2000')
     self.times = numpy.linspace(-300.0, 300.0, 3) * numpy.pi / 43200.0
     arlexecute.set_client(use_dask=False)
예제 #5
0
    def test_useDaskSync(self):
        def square(x):
            return x**2

        arlexecute.set_client(use_dask=True)
        graph = arlexecute.execute(square)(numpy.arange(10))
        result = arlexecute.compute(graph, sync=True)
        assert (result == numpy.array([0, 1, 4, 9, 16, 25, 36, 49, 64,
                                       81])).all()
        arlexecute.close()
예제 #6
0
 def setUp(self):
     super(ARLExecuteTestCase, self).setUp()
     
     import os
     from wrappers.arlexecute.execution_support.arlexecute import arlexecute
     use_dlg = os.environ.get('ARL_TESTS_USE_DLG', '0') == '1'
     use_dask = os.environ.get('ARL_TESTS_USE_DASK', '1') == '1'
     arlexecute.set_client(use_dask=use_dask, use_dlg=use_dlg)
     
     # Start a daliuge node manager for these tests; make sure it can see
     # the arl modules. The node manager will be shut down at tearDown
     if use_dlg:
         from dlg import tool
         arl_root = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
         self.nm_proc = tool.start_process('nm', ['--dlg-path', arl_root])
예제 #7
0
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=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 create gleam', time to create GLEAM prediction graph
    'time predict', time to execute GLEAM prediction graph
    'time corrupt', time to corrupt data_models
    'time invert', time to make dirty image
    'time psf invert', time to make PSF
    '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
    'psf_max',
    'psf_min',
    '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_arlexecute_workflow_workflowkflow
    :param nfreqwin: See simulate_list_list_arlexecute_workflow_workflowkflow
    :param ntimes: See simulate_list_list_arlexecute_workflow_workflowkflow
    :param rmax: See simulate_list_list_arlexecute_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
    :param kwargs:
    :return: results dictionary
    """

    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")

    zerow = False
    print("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['use_dask'] = use_dask

    print("At start, configuration is {0!r}".format(results))

    # Parameters determining scale
    frequency = numpy.linspace(0.8e8, 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 / 3.0, numpy.pi / 3.0, ntimes)

    phasecentre = SkyCoord(ra=+30.0 * u.deg,
                           dec=-60.0 * u.deg,
                           frame='icrs',
                           equinox='J2000')

    if use_dask:
        client = get_dask_Client(threads_per_worker=threads_per_worker,
                                 memory_limit=memory * 1024 * 1024 * 1024,
                                 n_workers=nworkers)
        arlexecute.set_client(client)
        nodes = findNodes(arlexecute.client)
        unodes = list(numpy.unique(nodes))
        results['nnodes'] = len(unodes)
        print("Defined %d workers on %d nodes" % (nworkers, results['nnodes']))
        print("Workers are: %s" % str(nodes))
    else:
        arlexecute.set_client(use_dask=use_dask)
        results['nnodes'] = 1
        unodes = None

    vis_list = simulate_list_arlexecute_workflow(
        'LOWBD2',
        frequency=frequency,
        channel_bandwidth=channel_bandwidth,
        times=times,
        phasecentre=phasecentre,
        order=order,
        format='blockvis',
        rmax=rmax)

    print("****** Visibility creation ******")
    vis_list = arlexecute.persist(vis_list)

    # Find the best imaging parameters but don't bring the vis_list back here
    def get_wf(bv):
        v = convert_blockvisibility_to_visibility(bv)
        return advise_wide_field(v,
                                 guard_band_image=6.0,
                                 delA=0.02,
                                 facets=facets,
                                 wprojection_planes=wprojection_planes,
                                 oversampling_synthesised_beam=4.0)

    wprojection_planes = 1
    advice = arlexecute.compute(arlexecute.execute(get_wf)(vis_list[0]),
                                sync=True)

    npixel = advice['npixels2']
    cellsize = advice['cellsize']

    if context == 'timeslice':
        vis_slices = ntimes
        print("Using timeslice with %d slices" % vis_slices)
    elif context == '2d':
        vis_slices = 1
    else:
        context = 'wstack'
        vis_slices = 5 * advice['vis_slices']
        print("Using wstack with %d slices" % vis_slices)

    results['vis_slices'] = vis_slices
    results['cellsize'] = cellsize
    results['npixel'] = npixel

    gleam_model_list = [
        arlexecute.execute(create_low_test_image_from_gleam)(
            npixel=npixel,
            frequency=[frequency[f]],
            channel_bandwidth=[channel_bandwidth[f]],
            cellsize=cellsize,
            phasecentre=phasecentre,
            polarisation_frame=PolarisationFrame("stokesI"),
            flux_limit=0.3,
            applybeam=True) for f, freq in enumerate(frequency)
    ]

    start = time.time()
    print("****** Starting GLEAM model creation ******")
    gleam_model_list = arlexecute.compute(gleam_model_list, sync=True)
    cmodel = smooth_image(gleam_model_list[centre])
    export_image_to_fits(cmodel,
                         "pipelines-timings-arlexecute-gleam_cmodel.fits")
    end = time.time()
    results['time create gleam'] = end - start
    print("Creating GLEAM model took %.2f seconds" % (end - start))

    gleam_model_list = arlexecute.scatter(gleam_model_list)
    vis_list = predict_list_arlexecute_workflow(vis_list,
                                                gleam_model_list,
                                                vis_slices=vis_slices,
                                                context=context)
    start = time.time()
    print("****** Starting GLEAM model visibility prediction ******")
    vis_list = arlexecute.compute(vis_list, sync=True)

    end = time.time()
    results['time predict'] = end - start
    print("GLEAM model Visibility prediction took %.2f seconds" %
          (end - start))

    # Corrupt the visibility for the GLEAM model
    print("****** Visibility corruption ******")
    vis_list = corrupt_list_arlexecute_workflow(vis_list, phase_error=1.0)
    start = time.time()
    vis_list = arlexecute.compute(vis_list, sync=True)

    vis_list = arlexecute.scatter(vis_list)

    end = time.time()
    results['time corrupt'] = end - start
    print("Visibility corruption took %.2f seconds" % (end - start))

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

    psf_list = invert_list_arlexecute_workflow(vis_list,
                                               model_list,
                                               vis_slices=vis_slices,
                                               context=context,
                                               facets=facets,
                                               dopsf=True)
    start = time.time()
    print("****** Starting PSF calculation ******")
    psf, sumwt = arlexecute.compute(psf_list, sync=True)[centre]
    end = time.time()
    results['time psf invert'] = end - start
    print("PSF invert took %.2f seconds" % (end - start))

    results['psf_max'] = qa_image(psf).data['max']
    results['psf_min'] = qa_image(psf).data['min']

    dirty_list = invert_list_arlexecute_workflow(vis_list,
                                                 model_list,
                                                 vis_slices=vis_slices,
                                                 context=context,
                                                 facets=facets)
    start = time.time()
    print("****** Starting dirty image calculation ******")
    dirty, sumwt = arlexecute.compute(dirty_list, sync=True)[centre]
    end = time.time()
    results['time invert'] = end - start
    print("Dirty image invert took %.2f seconds" % (end - start))
    print("Maximum in dirty image is ", numpy.max(numpy.abs(dirty.data)),
          ", sumwt is ", sumwt)
    qa = qa_image(dirty)
    results['dirty_max'] = qa.data['max']
    results['dirty_min'] = qa.data['min']

    # Create the ICAL pipeline to run 5 major cycles, starting selfcal at cycle 1. A global solution across all
    # frequencies (i.e. Visibilities) is performed.
    start = time.time()
    print("****** Starting ICAL ******")

    controls = create_calibration_controls()

    controls['T']['first_selfcal'] = 1
    controls['G']['first_selfcal'] = 3
    controls['B']['first_selfcal'] = 4

    controls['T']['timescale'] = 'auto'
    controls['G']['timescale'] = 'auto'
    controls['B']['timescale'] = 1e5

    if nfreqwin > 6:
        nmoment = 3
        algorithm = 'mmclean'
    elif nfreqwin > 2:
        nmoment = 2
        algorithm = 'mmclean'
    else:
        nmoment = 1
        algorithm = 'msclean'

    start = time.time()
    ical_list = ical_list_arlexecute_workflow(vis_list,
                                              model_imagelist=model_list,
                                              context='wstack',
                                              calibration_context='TG',
                                              controls=controls,
                                              scales=[0, 3, 10],
                                              algorithm=algorithm,
                                              nmoment=nmoment,
                                              niter=1000,
                                              fractional_threshold=0.1,
                                              threshold=0.1,
                                              nmajor=5,
                                              gain=0.25,
                                              vis_slices=vis_slices,
                                              timeslice='auto',
                                              global_solution=False,
                                              psf_support=64,
                                              do_selfcal=True)

    end = time.time()
    results['time ICAL graph'] = end - start
    print("Construction of ICAL graph took %.2f seconds" % (end - start))

    # Execute the graph
    start = time.time()
    result = arlexecute.compute(ical_list, sync=True)
    deconvolved, residual, restored = result
    end = time.time()

    results['time ICAL'] = end - start
    print("ICAL graph execution took %.2f seconds" % (end - start))
    qa = qa_image(deconvolved[centre])
    results['deconvolved_max'] = qa.data['max']
    results['deconvolved_min'] = qa.data['min']
    export_image_to_fits(deconvolved[centre],
                         "pipelines-timings-arlexecute-ical_deconvolved.fits")

    qa = qa_image(residual[centre][0])
    results['residual_max'] = qa.data['max']
    results['residual_min'] = qa.data['min']
    export_image_to_fits(residual[centre][0],
                         "pipelines-timings-arlexecute-ical_residual.fits")

    qa = qa_image(restored[centre])
    results['restored_max'] = qa.data['max']
    results['restored_min'] = qa.data['min']
    export_image_to_fits(restored[centre],
                         "pipelines-timings-arlexecute-ical_restored.fits")
    #
    arlexecute.close()

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

    print("At end, results are {0!r}".format(results))

    return results
예제 #8
0
pp = pprint.PrettyPrinter()


def init_logging():
    logging.basicConfig(filename='%s/gleam-pipeline.log' % results_dir,
                        filemode='a',
                        format='%(thread)s %(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                        datefmt='%H:%M:%S',
                        level=logging.INFO)


if __name__ == '__main__':
    log = logging.getLogger()
    print("Starting gleam_simulate_list_arlexecute_pipeline")
    
    arlexecute.set_client(use_dask=True)
    arlexecute.run(init_logging)
    
    # We create a graph to make the visibility. The parameter rmax determines the distance of the furthest antenna/stations used. All over parameters are determined from this number.
    
    nfreqwin = 7
    ntimes = 11
    rmax = 300.0
    frequency = numpy.linspace(0.9e8, 1.1e8, nfreqwin)
    channel_bandwidth = numpy.array(nfreqwin * [frequency[1] - frequency[0]])
    times = numpy.linspace(-numpy.pi / 3.0, numpy.pi / 3.0, ntimes)
    phasecentre = SkyCoord(ra=+30.0 * u.deg, dec=-60.0 * u.deg, frame='icrs', equinox='J2000')
    
    vis_list = simulate_list_arlexecute_workflow('LOWBD2',
                                                 rmax=rmax,
                                                 frequency=frequency,
    logging.basicConfig(
        filename='%s/gleam-pipeline.log' % results_dir,
        filemode='a',
        format=
        '%(thread)s %(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
        datefmt='%H:%M:%S',
        level=logging.INFO)


if __name__ == '__main__':
    pp = pprint.PrettyPrinter()

    log = logging.getLogger()
    logging.info("Starting ical_list_arlexecute_workflow-pipeline")

    arlexecute.set_client(get_dask_Client())
    arlexecute.run(init_logging)

    # Load data from previous simulation
    vislist = import_blockvisibility_from_hdf5('gleam_simulation_vislist.hdf')

    print(vislist[0])

    cellsize = 0.001
    npixel = 1024
    pol_frame = PolarisationFrame("stokesI")

    model_list = [
        arlexecute.execute(create_image_from_visibility)(
            v, npixel=1024, cellsize=cellsize, polarisation_frame=pol_frame)
        for v in vislist
예제 #10
0
def init_logging():
    logging.basicConfig(
        filename='%s/ska-pipeline.log' % results_dir,
        filemode='a',
        format='%%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
        datefmt='%H:%M:%S',
        level=logging.INFO)


if __name__ == '__main__':
    log = logging.getLogger()
    print("Starting ska-pipelines pipeline")

    arlexecute.set_client(use_dask=True,
                          threads_per_worker=1,
                          memory_limit=4e9,
                          local_dir=dask_dir)
    print(arlexecute.client)
    arlexecute.run(init_logging)

    # We create a graph to make the visibility. The parameter rmax determines the distance of the
    # furthest antenna/stations used. All over parameters are determined from this number.

    nfreqwin = 41
    ntimes = 5
    rmax = 750.0
    centre = nfreqwin // 2

    frequency = numpy.linspace(0.9e8, 1.1e8, nfreqwin)
    channel_bandwidth = numpy.array(nfreqwin * [frequency[1] - frequency[0]])
    times = numpy.linspace(-numpy.pi / 3.0, numpy.pi / 3.0, ntimes)
예제 #11
0
                        help='Context: 2d|timeslice|wstack')
    parser.add_argument('--nchan',
                        type=int,
                        default=40,
                        help='Number of channels to process')

    args = parser.parse_args()
    print(args)

    log = logging.getLogger()
    logging.info("Starting Imaging pipeline")

    use_dask = args.use_dask == 'True'
    arlexecute.set_client(use_dask=use_dask,
                          threads_per_worker=args.threads,
                          memory_limit=args.memory * 1024 * 1024 * 1024,
                          n_workers=args.nworkers,
                          local_dir=dask_dir)
    arlexecute.run(init_logging)

    nchan = args.nchan
    uvmax = 450.0
    nfreqwin = 2
    centre = 0
    cellsize = 0.0004
    npixel = args.npixel
    psfwidth = (((8.0 / 2.35482004503) / 60.0) * numpy.pi / 180.0) / cellsize

    context = args.context
    if context == 'wstack':
        vis_slices = 45
 def actualSetUp(self, add_errors=False, freqwin=1, block=False, dospectral=True, dopol=False, zerow=False):
     
     arlexecute.set_client(use_dask=False)
     
     self.npixel = 256
     self.low = create_named_configuration('LOWBD2', rmax=750.0)
     self.freqwin = freqwin
     self.vis_list = list()
     self.ntimes = 5
     self.times = numpy.linspace(-3.0, +3.0, self.ntimes) * numpy.pi / 12.0
     
     if freqwin > 1:
         self.frequency = numpy.linspace(0.8e8, 1.2e8, self.freqwin)
         self.channelwidth = numpy.array(freqwin * [self.frequency[1] - self.frequency[0]])
     else:
         self.frequency = numpy.array([0.8e8])
         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 = [arlexecute.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_list = [arlexecute.execute(create_unittest_model, nout=freqwin)(self.vis_list[freqwin],
                                                                                 self.image_pol,
                                                                                 npixel=self.npixel)
                         for freqwin, _ in enumerate(self.frequency)]
     
     self.components_list = [arlexecute.execute(create_unittest_components)(self.model_list[freqwin],
                                                                             flux[freqwin, :][numpy.newaxis, :])
                              for freqwin, _ in enumerate(self.frequency)]
     
     self.model_list = [arlexecute.execute(insert_skycomponent, nout=1)(self.model_list[freqwin],
                                                                         self.components_list[freqwin])
                         for freqwin, _ in enumerate(self.frequency)]
     
     self.vis_list = [arlexecute.execute(predict_skycomponent_visibility)(self.vis_list[freqwin],
                                                                          self.components_list[freqwin])
                      for freqwin, _ in enumerate(self.frequency)]
     
     # Calculate the model convolved with a Gaussian.
     self.model = arlexecute.compute(self.model_list[0], sync=True)
     
     self.cmodel = smooth_image(self.model)
     export_image_to_fits(self.model, '%s/test_imaging_model.fits' % self.dir)
     export_image_to_fits(self.cmodel, '%s/test_imaging_cmodel.fits' % self.dir)
     
     if add_errors and block:
         self.vis_list = [arlexecute.execute(insert_unittest_errors)(self.vis_list[i])
                          for i, _ in enumerate(self.frequency)]
     
     self.vis = arlexecute.compute(self.vis_list[0], sync=True)
     
     self.components = arlexecute.compute(self.components_list[0], sync=True)
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_arlexecute_workflow_workflowkflow
    :param nfreqwin: See simulate_list_list_arlexecute_workflow_workflowkflow
    :param ntimes: See simulate_list_list_arlexecute_workflow_workflowkflow
    :param rmax: See simulate_list_list_arlexecute_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:
        client = get_dask_Client(threads_per_worker=threads_per_worker,
                                 processes=threads_per_worker == 1,
                                 memory_limit=memory * 1024 * 1024 * 1024,
                                 n_workers=nworkers)
        arlexecute.set_client(client)
        nodes = findNodes(arlexecute.client)
        print("Defined %d workers on %d nodes" % (nworkers, len(nodes)))
        print("Workers are: %s" % str(nodes))
    else:
        arlexecute.set_client(use_dask=use_dask)
        results['nnodes'] = 1

    def init_logging():
        logging.basicConfig(
            filename='pipelines_arlexecute_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.
    arlexecute.run(init_logging)

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

    lprint("Starting pipelines_arlexecute_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_arlexecute_workflow(
        'LOWBD2',
        frequency=frequency,
        channel_bandwidth=channel_bandwidth,
        times=times,
        phasecentre=phasecentre,
        order=order,
        format='blockvis',
        rmax=rmax)
    tmp_vis_list = [
        arlexecute.execute(convert_blockvisibility_to_visibility)(bv)
        for bv in tmp_bvis_list
    ]
    tmp_vis_list = arlexecute.client.compute(tmp_vis_list, sync=True)
    vis_list = arlexecute.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()

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

    # Find the best imaging parameters but don't bring the vis_list back here
    print("****** Finding wide field parameters ******")
    future_advice = [
        arlexecute.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 = arlexecute.compute(future_advice)
    advice = arlexecute.client.gather(future_advice)[-1]
    arlexecute.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 = [
        arlexecute.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 = arlexecute.compute(tmp_model_list, sync=True)
    future_model_list = arlexecute.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 = arlexecute.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 = [
        arlexecute.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_arlexecute_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_arlexecute_workflow(
        predicted_vis_list, phase_error=1.0, seed=seed)
    lprint("****** Weighting and tapering ******")
    tmp_corrupted_vis_list = weight_list_arlexecute_workflow(
        tmp_corrupted_vis_list, future_model_list)
    tmp_corrupted_vis_list = taper_list_arlexecute_workflow(
        tmp_corrupted_vis_list, 0.003 * 750.0 / rmax)
    tmp_corrupted_vis_list = arlexecute.compute(tmp_corrupted_vis_list,
                                                sync=True)

    corrupted_vis_list = arlexecute.gather(tmp_corrupted_vis_list)
    # arlexecute.client.cancel(predicted_vis_list)
    arlexecute.client.cancel(tmp_corrupted_vis_list)
    future_corrupted_vis_list = arlexecute.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_arlexecute_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 = arlexecute.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_arlexecute_timings-%s-dirty.fits" % context)

    lprint("****** Starting prediction ******")
    start = time.time()
    tmp_vis_list = predict_list_arlexecute_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 = arlexecute.compute(tmp_vis_list, sync=True)
    # arlexecute.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']['timescale'] = 'auto'

    start = time.time()
    ical_list = ical_list_arlexecute_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(arlexecute.client.who_has())
    #
    # Execute the graph
    lprint("****** Executing ICAL graph ******")
    start = time.time()
    deconvolved, residual, restored, gaintables = arlexecute.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_arlexecute_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_arlexecute_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_arlexecute_timings-%s-ical_restored.fits" % context)
    #
    arlexecute.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
예제 #14
0
 def test_setup_errors(self):
     with self.assertRaises(AssertionError):
         arlexecute.set_client(client=1)
예제 #15
0
# We will use dask

# In[2]:

threads_per_worker = 16
memory = 384
nworkers = 1
filename = args.schedulerfile
client = get_dask_Client(threads_per_worker=threads_per_worker,
                         processes=threads_per_worker == 1,
                         memory_limit=memory * 1024 * 1024 * 1024,
                         n_workers=nworkers,
                         with_file=True,
                         scheduler_file=filename)
arlexecute.set_client(client)
nodes = findNodes(arlexecute.client)
print("Defined %d workers on %d nodes" % (nworkers, len(nodes)))
print("Workers are: %s" % str(nodes))
#arlexecute.set_client(use_dask=True)

init_logging()
log = logging.getLogger()
logging.info("Starting imaging-pipeline")

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

# In[3]:
예제 #16
0
    args = parser.parse_args()
    print("Starting LOW low level RFI simulation")

    pp.pprint(vars(args))

    write_ms = args.write_ms == "True"

    numpy.random.seed(args.seed)

    if args.use_dask == "True":
        client = get_dask_Client(threads_per_worker=1,
                                 processes=True,
                                 memory_limit=32 * 1024 * 1024 * 1024,
                                 n_workers=8)
        arlexecute.set_client(client=client)
        print(arlexecute.client)
    else:
        print("Running in serial mode")
        arlexecute.set_client(use_dask=False)

    emitter_location = EarthLocation(lon=args.emitter_longitude,
                                     lat=args.emitter_latitude,
                                     height=0.0)
    emitter_power = args.emitter_power
    print("Emitter is %.1f kW at location %s" %
          (1e-3 * emitter_power, emitter_location.geodetic))

    if args.waterfall == "True":
        waterfall = True
    else:
예제 #17
0
    def simulation(self,
                   args,
                   time_series='wind',
                   band='B2',
                   context='singlesource',
                   vp_directory=''):

        ra = args.ra
        declination = args.declination
        use_radec = args.use_radec == "True"
        integration_time = args.integration_time
        time_range = args.time_range
        time_chunk = args.time_chunk
        offset_dir = args.offset_dir
        pbtype = args.pbtype
        pbradius = args.pbradius
        rmax = args.rmax
        flux_limit = args.flux_limit
        npixel = args.npixel
        shared_directory = args.shared_directory
        vp_directory = args.vp_directory

        # Simulation specific parameters
        global_pe = numpy.array(args.global_pe)
        static_pe = numpy.array(args.static_pe)
        dynamic_pe = args.dynamic_pe

        seed = args.seed
        basename = os.path.basename(os.getcwd())

        # client = get_dask_Client()
        use_dask = False
        arlexecute.set_client(use_dask=use_dask)

        # Set up details of simulated observation
        nfreqwin = 1
        if band == 'B1':
            frequency = [0.765e9]
        elif band == 'B2':
            frequency = [1.36e9]
        elif band == 'Ku':
            frequency = [12.179e9]
        else:
            raise ValueError("Unknown band %s" % band)

        phasecentre = SkyCoord(ra=ra * u.deg,
                               dec=declination * u.deg,
                               frame='icrs',
                               equinox='J2000')

        bvis_graph = create_standard_mid_simulation_arlexecute_workflow(
            band, rmax, phasecentre, time_range, time_chunk, integration_time,
            shared_directory)
        future_bvis_list = arlexecute.persist(bvis_graph)
        vis_graph = [
            arlexecute.execute(convert_blockvisibility_to_visibility)(bv)
            for bv in future_bvis_list
        ]
        future_vis_list = arlexecute.persist(vis_graph, sync=True)

        # We need the HWHM of the primary beam, and the location of the nulls
        HWHM_deg, null_az_deg, null_el_deg = find_pb_width_null(
            pbtype, frequency)

        HWHM = HWHM_deg * numpy.pi / 180.0

        FOV_deg = 8.0 * 1.36e9 / frequency[0]

        advice_list = arlexecute.execute(advise_wide_field)(
            future_vis_list[0], guard_band_image=1.0, delA=0.02, verbose=False)
        advice = arlexecute.compute(advice_list, sync=True)
        pb_npixel = 1024
        d2r = numpy.pi / 180.0
        pb_cellsize = d2r * FOV_deg / pb_npixel
        cellsize = advice['cellsize']

        # Now construct the components
        original_components, offset_direction = create_simulation_components(
            context, phasecentre, frequency, pbtype, offset_dir, flux_limit,
            pbradius * HWHM, pb_npixel, pb_cellsize)

        vp_list = [
            arlexecute.execute(create_image_from_visibility)(
                bv,
                npixel=pb_npixel,
                frequency=frequency,
                nchan=nfreqwin,
                cellsize=pb_cellsize,
                phasecentre=phasecentre,
                override_cellsize=False) for bv in future_bvis_list
        ]
        vp_list = [
            arlexecute.execute(create_vp)(vp,
                                          pbtype,
                                          pointingcentre=phasecentre,
                                          use_local=not use_radec)
            for vp in vp_list
        ]
        future_vp_list = arlexecute.persist(vp_list)

        # Make one image per component
        future_model_list = [
            arlexecute.execute(create_image_from_visibility)(
                future_vis_list[0],
                npixel=npixel,
                frequency=frequency,
                nchan=nfreqwin,
                cellsize=cellsize,
                phasecentre=offset_direction,
                polarisation_frame=PolarisationFrame("stokesI"))
            for i, _ in enumerate(original_components)
        ]

        a2r = numpy.pi / (3600.0 * 1800)

        no_error_gtl = None
        error_gtl = None
        if time_series == '':
            global_pointing_error = global_pe
            static_pointing_error = static_pe
            pointing_error = dynamic_pe

            no_error_gtl, error_gtl = \
                create_pointing_errors_gaintable_arlexecute_workflow(future_bvis_list, original_components,
                                                                     sub_vp_list=future_vp_list,
                                                                     use_radec=use_radec,
                                                                     pointing_error=a2r * pointing_error,
                                                                     static_pointing_error=a2r * static_pointing_error,
                                                                     global_pointing_error=a2r * global_pointing_error,
                                                                     seed=seed,
                                                                     show=False, basename=basename)

        elif time_series == 'wind':

            no_error_gtl, error_gtl = \
                create_pointing_errors_gaintable_arlexecute_workflow(future_bvis_list, original_components,
                                                                     sub_vp_list=future_vp_list,
                                                                     use_radec=use_radec,
                                                                     time_series=time_series,
                                                                     time_series_type='precision',
                                                                     seed=seed,
                                                                     show=False, basename=basename)
        elif time_series == 'gravity':
            no_error_gtl, error_gtl = \
                create_surface_errors_gaintable_arlexecute_workflow(band, future_bvis_list, original_components,
                                                                    vp_directory=vp_directory, use_radec=use_radec,
                                                                    show=False, basename=basename)
        else:
            raise ValueError("Unknown type of error %s" % time_series)

        # Now make all the residual images
        vis_comp_chunk_dirty_list = \
            calculate_residual_from_gaintables_arlexecute_workflow(future_bvis_list, original_components,
                                                                   future_model_list,
                                                                   no_error_gtl, error_gtl)

        # Add the resulting images
        error_dirty_list = sum_invert_results_arlexecute(
            vis_comp_chunk_dirty_list)

        # Actually compute the graph assembled above
        error_dirty, sumwt = arlexecute.compute(error_dirty_list, sync=True)

        return error_dirty, sumwt
예제 #18
0
    return lowcore

if __name__ == '__main__':

    log = logging.getLogger()
    log.setLevel(logging.DEBUG)
    log.addHandler(logging.StreamHandler(sys.stdout))

    pylab.rcParams['figure.figsize'] = (12.0, 12.0)
    pylab.rcParams['image.cmap'] = 'rainbow'


    lowcore = create_configuration('MUSER')
    # lowcore = create_named_configuration('MUSER')
    # arlexecute.set_client(use_dask=True)
    arlexecute.set_client(use_dask=True, threads_per_worker=1, memory_limit=32 * 1024 * 1024 * 1024, n_workers=8,
                          local_dir=dask_dir)
    times = numpy.array([-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0]) * (numpy.pi / 12.0)
    frequency = numpy.array([4e8])
    channel_bandwidth = numpy.array([25e6])
    reffrequency = numpy.max(frequency)
    phasecentre = SkyCoord(ra=+5 * u.deg, dec=20 * u.deg, frame='icrs', equinox='J2000')
    vt = create_visibility(lowcore, times, frequency, channel_bandwidth=channel_bandwidth,
                        weight=1.0, phasecentre=phasecentre,
                        polarisation_frame=PolarisationFrame('stokesI'))

    advice = advise_wide_field(vt, wprojection_planes=1)

    vt.data['vis'] *= 0.0
    npixel=256

    model = create_image_from_visibility(vt, npixel=npixel, cellsize=6.8e-5, nchan=1,
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=False,
               flux_limit=0.3, nmajor=5, dft_threshold=1.0):
    """ 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 create gleam', time to create GLEAM prediction graph
    'time predict', time to execute GLEAM prediction graph
    'time corrupt', time to corrupt data_models
    'time invert', time to make dirty image
    'time psf invert', time to make PSF
    '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
    'psf_max',
    'psf_min',
    '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_arlexecute_workflow_workflowkflow
    :param nfreqwin: See simulate_list_list_arlexecute_workflow_workflowkflow
    :param ntimes: See simulate_list_list_arlexecute_workflow_workflowkflow
    :param rmax: See simulate_list_list_arlexecute_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:
        client = get_dask_Client(threads_per_worker=threads_per_worker,
                                 processes = threads_per_worker == 1,
                                 memory_limit=memory * 1024 * 1024 * 1024,
                                 n_workers=nworkers)
        arlexecute.set_client(client)
        nodes = findNodes(arlexecute.client)
        print("Defined %d workers on %d nodes" % (nworkers, len(nodes)))
        print("Workers are: %s" % str(nodes))
    else:
        arlexecute.set_client(use_dask=use_dask)
        results['nnodes'] = 1

    def init_logging():
        logging.basicConfig(filename='pipelines-arlexecute-timings.log',
                            filemode='a',
                            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.
    arlexecute.run(init_logging)

    
    def lprint(s):
        log.info(s)
        print(s)
    
    lprint("Starting pipelines-arlexecute-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(results)
    
    # Parameters determining scale
    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=+30.0 * u.deg, dec=-60.0 * u.deg, frame='icrs', equinox='J2000')
    
    bvis_list = simulate_list_arlexecute_workflow('LOWBD2',
                                                  frequency=frequency,
                                                  channel_bandwidth=channel_bandwidth,
                                                  times=times,
                                                  phasecentre=phasecentre,
                                                  order=order,
                                                  format='blockvis',
                                                  rmax=rmax)
    
    lprint("****** Visibility creation ******")
    bvis_list = arlexecute.compute(bvis_list, sync=True)
    
    vis_list = [arlexecute.execute(convert_blockvisibility_to_visibility(bv)) for bv in bvis_list]
    vis_list = arlexecute.compute(vis_list, sync=True)
    
    # Find the best imaging parameters but don't bring the vis_list back here
    def get_wf(v):
        return advise_wide_field(v, guard_band_image=6.0,
                                 delA=0.1,
                                 facets=facets,
                                 wprojection_planes=wprojection_planes,
                                 oversampling_synthesised_beam=4.0)
    
    advice = arlexecute.compute(arlexecute.execute(get_wf)(vis_list[-1]), sync=True)
    
    # 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
    model_list = [arlexecute.execute(create_image_from_visibility)
                  (vis_list[f],
                   npixel=npixel, cellsize=cellsize,
                   frequency=[frequency[f]],
                   channel_bandwidth=[channel_bandwidth[f]],
                   polarisation_frame=PolarisationFrame("stokesI"))
                  for f, freq in enumerate(frequency)]
    model_list = arlexecute.compute(model_list, sync=True)
    model_list = arlexecute.scatter(model_list)
    
    start = time.time()
    vis_list = weight_list_arlexecute_workflow(vis_list, model_list)
    vis_list = taper_list_arlexecute_workflow(vis_list, 0.003 * 750.0 / rmax)
    print("****** Starting weighting and tapering ******")
    vis_list = arlexecute.compute(vis_list, sync=True)
    end = time.time()
    results['time weight'] = end - start
    print("Weighting took %.3f seconds" % (end - start))
    vis_list = arlexecute.scatter(vis_list)
    
    # Now set up the imaging parameters
    gcfcf_list = [None for i in range(nfreqwin)]
    
    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("Using wprojection with %d planes with wstep %.1f wavelengths" % (nw, wstep))
        
        start = time.time()
        lprint("****** Starting W projection kernel creation ******")
        gcfcf_list = [arlexecute.execute(create_awterm_convolutionfunction, nout=1)
                      (m, nw=nw, wstep=wstep, oversampling=8, support=support, use_aaf=True)
                      for m in model_list]
        gcfcf_list = arlexecute.compute(gcfcf_list, sync=True)
        end = time.time()
        results['time create wprojection'] = end - start
        lprint("Creating W projection kernel took %.3f seconds" % (end - start))
        cf_image = convert_convolutionfunction_to_image(gcfcf_list[centre][1])
        cf_image.data = numpy.real(cf_image.data)
        export_image_to_fits(cf_image, "pipelines-arlexecute-timings-wterm-cf.fits")
        gcfcf_list = arlexecute.scatter(gcfcf_list)
    
    else:
        context = 'wstack'
        vis_slices = advice['vis_slices']
        lprint("Using wstack with %d slices" % vis_slices)
    
    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 ******")
    start = time.time()
    skymodel_list = [arlexecute.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)]
    skymodel_list = arlexecute.compute(skymodel_list, sync=True)
    end = time.time()
    lprint("GLEAM skymodel creation took %.3f seconds" % (end - start))
    results['time create gleam'] = end - start
    
    lprint("****** Starting GLEAM skymodel prediction ******")
    start = time.time()
    predicted_vis_list = [predict_skymodel_list_arlexecute_workflow(vis_list[f], [skymodel_list[f]], context=context,
                                                                   vis_slices=vis_slices, facets=facets,
                                                                   gcfcf=[gcfcf_list[f]])[0]
                          for f, freq in enumerate(frequency)]
    predicted_vis_list = arlexecute.compute(predicted_vis_list, sync=True)
    end = time.time()
    lprint("GLEAM skymodel prediction took %.3f seconds" % (end - start))
    results['time predict gleam'] = end - start
    
    lprint("****** Starting psf image calculation ******")
    start = time.time()
    predicted_vis_list = arlexecute.scatter(predicted_vis_list)
    psf_list = invert_list_arlexecute_workflow(predicted_vis_list, model_list, vis_slices=vis_slices,
                                               dopsf=True, context=context, facets=facets,
                                               use_serial_invert=use_serial_imaging, gcfcf=gcfcf_list)
    psf, sumwt = arlexecute.compute(psf_list, sync=True)[centre]
    end = time.time()
    results['time psf invert'] = end - start
    lprint("PSF invert took %.3f seconds" % (end - start))
    lprint("Maximum in psf image is %f, sumwt is %s" % (numpy.max(numpy.abs(psf.data)), str(sumwt)))
    qa = qa_image(psf)
    results['psf_max'] = qa.data['max']
    results['psf_min'] = qa.data['min']
    export_image_to_fits(psf, "pipelines-arlexecute-timings-%s-psf.fits" % context)
    
    # Make a smoothed model image for comparison
    
    # smoothed_model_list = restore_list_arlexecute_workflow(gleam_model_list, psf_list)
    # smoothed_model_list = arlexecute.compute(smoothed_model_list, sync=True)
    # smoothed_cube = image_gather_channels(smoothed_model_list)
    # export_image_to_fits(smoothed_cube, "pipelines-arlexecute-timings-cmodel.fits")
    
    # Create an empty model image
    model_list = [arlexecute.execute(create_image_from_visibility)
                  (predicted_vis_list[f],
                   npixel=npixel, cellsize=cellsize,
                   frequency=[frequency[f]],
                   channel_bandwidth=[channel_bandwidth[f]],
                   polarisation_frame=PolarisationFrame("stokesI"))
                  for f, freq in enumerate(frequency)]
    model_list = arlexecute.compute(model_list, sync=True)
    model_list = arlexecute.scatter(model_list)
    
    lprint("****** Starting dirty image calculation ******")
    start = time.time()
    dirty_list = invert_list_arlexecute_workflow(predicted_vis_list, model_list, vis_slices=vis_slices,
                                                 context=context, facets=facets,
                                                 use_serial_invert=use_serial_imaging, gcfcf=gcfcf_list)
    dirty, sumwt = arlexecute.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']
    export_image_to_fits(dirty, "pipelines-arlexecute-timings-%s-dirty.fits" % context)
    
    # Corrupt the visibility for the GLEAM model
    lprint("****** Visibility corruption ******")
    start = time.time()
    corrupted_vis_list = corrupt_list_arlexecute_workflow(predicted_vis_list, phase_error=1.0, seed=seed)
    corrupted_vis_list = arlexecute.compute(corrupted_vis_list, sync=True)
    end = time.time()
    results['time corrupt'] = end - start
    lprint("Visibility corruption 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.
    lprint("****** Starting ICAL ******")
    
    controls = create_calibration_controls()
    
    controls['T']['first_selfcal'] = 1
    controls['T']['timescale'] = 'auto'
    
    start = time.time()
    ical_list = ical_list_arlexecute_workflow(corrupted_vis_list,
                                              model_imagelist=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=8,
                                              deconvolve_overlap=32,
                                              deconvolve_taper='tukey',
                                              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,
                                              gcfcf=gcfcf_list)
    end = time.time()
    results['time ICAL graph'] = end - start
    lprint("Construction of ICAL graph took %.3f seconds" % (end - start))
    
    # Execute the graph
    start = time.time()
    result = arlexecute.compute(ical_list, sync=True)
    deconvolved, residual, restored, gaintables = result
    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)
    export_image_to_fits(deconvolved_cube, "pipelines-arlexecute-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)
    export_image_to_fits(residual_cube, "pipelines-arlexecute-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)
    export_image_to_fits(restored_cube, "pipelines-arlexecute-timings-%s-ical_restored.fits" % context)
    #
    arlexecute.close()
    
    end_all = time.time()
    results['time overall'] = end_all - start_all
    
    lprint("At end, results are:")
    lprint(results)
    
    return results