Esempio n. 1
0
def _define_forest(ns, parent=None, **kw):
    if run_purr:
        Timba.TDL.GUI.purr(mssel.msname + ".purrlog", [mssel.msname, '.'])
    # create Purr pipe
    global purrpipe
    purrpipe = Purr.Pipe.Pipe(mssel.msname)

    # get antennas from MS
    ANTENNAS = mssel.get_antenna_set(list(range(1, 15)))
    array = Meow.IfrArray(ns, ANTENNAS, mirror_uvw=False)
    stas = array.stations()
    # get phase centre from MS, setup observation
    observation = Meow.Observation(ns,
                                   phase_centre=mssel.get_phase_dir(),
                                   linear=mssel.is_linear_pol(),
                                   circular=mssel.is_circular_pol())
    Meow.Context.set(array, observation)
    # get active correlations from MS
    Meow.Context.active_correlations = mssel.get_correlations()

    # make spigot nodes
    spigots = spigots0 = outputs = array.spigots(corr=mssel.get_corr_index())

    # ...and an inspector for them
    StdTrees.vis_inspector(ns.inspector('input'),
                           spigots,
                           bookmark="Inspect input visibilities")
    inspectors = [ns.inspector('input')]
    Bookmarks.make_node_folder("Input visibilities by baseline",
                               [spigots(p, q) for p, q in array.ifrs()],
                               sorted=True,
                               ncol=2,
                               nrow=2)

    inspect_ifrs = array.ifrs()
    if do_solve:
        # filter solvable baselines by baseline length
        solve_ifrs = []
        antpos = mssel.ms_antenna_positions
        if (min_baseline or max_baseline) and antpos is not None:
            for (ip, p), (iq, q) in array.ifr_index():
                baseline = math.sqrt(
                    ((antpos[ip, :] - antpos[iq, :])**2).sum())
                if (not min_baseline or baseline > min_baseline) and \
                   (not max_baseline or baseline < max_baseline):
                    solve_ifrs.append((p, q))
        else:
            solve_ifrs = array.ifrs()
        inspect_ifrs = solve_ifrs

    # make a predict tree using the MeqMaker
    if do_solve or do_subtract:
        predict = meqmaker.make_predict_tree(ns)
        # make a ParmGroup and solve jobs for source parameters, if we have any
        if do_solve:
            parms = {}
            for src in meqmaker.get_source_list(ns):
                parms.update([(p.name, p) for p in src.get_solvables()])
            if parms:
                pg_src = ParmGroup.ParmGroup("source",
                                             list(parms.values()),
                                             table_name="sources.fmep",
                                             individual=True,
                                             bookmark=True)
                # now make a solvejobs for the source
                ParmGroup.SolveJob("cal_source", "Calibrate source model",
                                   pg_src)

    # make nodes to compute residuals
    if do_subtract:
        residuals = ns.residuals
        for p, q in array.ifrs():
            residuals(p, q) << spigots(p, q) - predict(p, q)
        outputs = residuals

    # and now we may need to correct the outputs
    if do_correct:
        if do_correct_sky:
            srcs = meqmaker.get_source_list(ns)
            sky_correct = srcs and srcs[0]
        else:
            sky_correct = None
        outputs = meqmaker.correct_uv_data(ns,
                                           outputs,
                                           sky_correct=sky_correct,
                                           inspect_ifrs=inspect_ifrs)

    # make solve trees
    if do_solve:
        # inputs to the solver are based on calibration type
        # if calibrating visibilities, feed them to condeq directly
        if cal_type == CAL.VIS:
            observed = spigots
            model = predict
        # else take ampl/phase component
        else:
            model = ns.model
            observed = ns.observed
            if cal_type == CAL.AMPL:
                for p, q in array.ifrs():
                    observed(p, q) << Meq.Abs(spigots(p, q))
                    model(p, q) << Meq.Abs(predict(p, q))
            elif cal_type == CAL.LOGAMPL:
                for p, q in array.ifrs():
                    observed(p, q) << Meq.Log(Meq.Abs(spigots(p, q)))
                    model(p, q) << Meq.Log(Meq.Abs(predict(p, q)))
            elif cal_type == CAL.PHASE:
                for p, q in array.ifrs():
                    observed(p, q) << 0
                    model(p, q) << Meq.Abs(predict(p, q)) * Meq.FMod(
                        Meq.Arg(spigots(p, q)) - Meq.Arg(predict(p, q)),
                        2 * math.pi)
            else:
                raise ValueError("unknown cal_type setting: " + str(cal_type))
        # make a solve tree
        solve_tree = StdTrees.SolveTree(ns, model, solve_ifrs=solve_ifrs)
        # the output of the sequencer is either the residuals or the spigots,
        # according to what has been set above
        outputs = solve_tree.sequencers(inputs=observed, outputs=outputs)

    # make sinks and vdm.
    # The list of inspectors must be supplied here
    inspectors += meqmaker.get_inspectors() or []
    StdTrees.make_sinks(ns, outputs, spigots=spigots0, post=inspectors)
    Bookmarks.make_node_folder("Corrected/residual visibilities by baseline",
                               [outputs(p, q) for p, q in array.ifrs()],
                               sorted=True,
                               ncol=2,
                               nrow=2)

    if not do_solve:
        if do_subtract:
            name = "Generate residuals"
            comment = "Generated residual visibilities."
        elif do_correct:
            name = "Generate corrected data"
            comment = "Generated corrected visibilities."
        else:
            name = None
        if name:
            # make a TDL job to runsthe tree
            def run_tree(mqs, parent, **kw):
                global tile_size
                purrpipe.title("Calibrating").comment(comment)
                mqs.execute(Meow.Context.vdm.name,
                            mssel.create_io_request(tile_size),
                            wait=False)

            TDLRuntimeMenu(
                name,
                TDLOption(
                    'tile_size',
                    "Tile size, in timeslots", [10, 60, 120, 240],
                    more=int,
                    doc=
                    """Input data is sliced by time, and processed in chunks (tiles) of
                  the indicated size. Larger tiles are faster, but use more memory."""
                ), TDLRuntimeJob(run_tree, name))

    # very important -- insert meqmaker's runtime options properly
    # this should come last, since runtime options may be built up during compilation.
    TDLRuntimeOptions(*meqmaker.runtime_options(nest=False))
    # insert solvejobs
    if do_solve:
        TDLRuntimeOptions(*ParmGroup.get_solvejob_options())
    # finally, setup imaging options
    imsel = mssel.imaging_selector(npix=512,
                                   arcmin=meqmaker.estimate_image_size())
    TDLRuntimeMenu("Make an image from this MS", *imsel.option_list())

    # and close meqmaker -- this exports annotations, etc
    meqmaker.close()
def _define_forest(ns,parent=None,**kw):
  if not mssel.msname:
    raise RuntimeError,"MS not set";
  if run_purr:
    Timba.TDL.GUI.purr(mssel.msname+".purrlog",[mssel.msname,'.']);
  # create Purr pipe
  global purrpipe;
  purrpipe = Purr.Pipe.Pipe(mssel.msname);

  # setup contexts from MS
  mssel.setup_observation_context(ns);
  array = Meow.Context.array;

  # make spigot nodes for data
  mssel.enable_input_column(True);
  spigots = array.spigots(corr=mssel.get_corr_index());
  meqmaker.make_per_ifr_bookmarks(spigots,"Input visibilities");

  # data tensor
  ns.DT << Meq.Composer(dims=[0],mt_polling=True,*[ spigots(p,q) for p,q in array.ifrs() ]);

  # predict tree using the MeqMaker
  all_sources = meqmaker.get_source_list(ns);
  dg_sources = deopts.enabled and dgsel.filter(all_sources);
  if dg_sources:
    # first group all sources without a diffgain on them
    groups = [ [ src for src in all_sources if not src in dg_sources ] ];
    # group diffgain-enabled sources by grouping tag
    clusters = set([src.get_attr(diffgain_group,None) for src in dg_sources]);
    dg_groups = [ (name,[ src for src in dg_sources if src.get_attr(diffgain_group) == name ]) for name in clusters if name ];
    # add sources without a grouping tag individually, as single-source groups
    dg_groups += [ (src.name,[src]) for src in dg_sources if not src.get_attr(diffgain_group,None) ];
    # now sort by brightness
    flux_dgg = [ (sum([src.get_attr('Iapp',0) or src.get_attr('I') for src in dgg[1]]),dgg) for dgg in dg_groups ];
    flux_dgg.sort(lambda a,b:cmp(b[0],a[0]));
    diffgain_labels = [ dgg[0] for flux,dgg in flux_dgg ];
    groups += [ dgg[1] for flux,dgg in flux_dgg ];
    num_diffgains = len(flux_dgg);
    # now make predict trees
    models = [];
    for i,group in enumerate(groups):
      MT = ns.MT(i);
      predict = meqmaker.make_predict_tree(MT.Subscope(),sources=group);
      ns.MT(i) << Meq.Composer(dims=[0],mt_polling=True,*[ predict(p,q) for p,q in array.ifrs() ]);
      models.append(ns.MT(i));
    print "Number of diffgain predict groups:",len(groups);
  else:
    diffgain_labels = [];
    num_diffgains = 0;
    predict = meqmaker.make_predict_tree(ns);
    ns.MT << Meq.Composer(dims=[0],mt_polling=True,*[ predict(p,q) for p,q in array.ifrs() ]);
    models = [ ns.MT ];
    
  solve_ifrs  = array.subset(calibrate_ifrs,strict=False).ifrs();
  downsample_subtiling = [ stefcal_downsample_timeint,stefcal_downsample_freqint ] if stefcal_downsample else [1,1];

  import Calico.OMS.StefCal.StefCal
  kwopts = {}
  gopts.set_stefcal_node_options(kwopts,visualize=stefcal_visualize);
  bopts.set_stefcal_node_options(kwopts,visualize=stefcal_visualize);
  deopts.set_stefcal_node_options(kwopts,visualize=stefcal_visualize);
  ns.stefcal << Meq.PyNode(class_name="StefCalNode",module_name=Calico.OMS.StefCal.StefCal.__file__,
                           ifrs=[ "%s:%s"%(p,q) for p,q in array.ifrs() ],
                           baselines=[ array.baseline(ip,iq) for (ip,p),(iq,q) in array.ifr_index() ],
                           solve_ifrs=[ "%s:%s"%(p,q) for p,q in solve_ifrs ],
                           noise_per_chan=stefcal_noise_per_chan,
                           downsample_subtiling=downsample_subtiling,
                           num_major_loops=stefcal_nmajor,
                           regularization_factor=1e-6,#
                           rescale=stefcal_rescale,
                           init_from_previous=False,
                           critical_flag_threshold=critical_flag_threshold,
                           diffgain_labels=diffgain_labels,
                           # flagging options
                           output_flag_bit=Meow.MSUtils.FLAGMASK_OUTPUT,
                           # IFR gain solution options
                           apply_ifr_gains=stefcal_ifr_gains,
                           solve_ifr_gains=(stefcal_ifr_gain_mode != MODE_SOLVE_APPLY),
                           reset_ifr_gains=stefcal_ifr_gain_reset,
                           save_ifr_gains=(stefcal_ifr_gain_mode == MODE_SOLVE_SAVE),
                           ifr_gain_table=stefcal_ifr_gain_table,
                           per_chan_ifr_gains=stefcal_per_chan_ifr_gains,
                           diag_ifr_gains=(stefcal_diagonal_ifr_gains == DIAGONLY),
                           residuals=(do_output == CORRECTED_RESIDUALS),
                           subtract_dgsrc=(do_output == CORRECTED_DATA_SUB),
                           verbose=stefcal_verbose,
                           children=[ns.DT]+models,**kwopts);
                           
  inspectors = meqmaker.get_inspectors() or [];
  # make output bookmarks
  nv = 0;
  for p,q in array.ifrs():
    sel = ns.output_sel(p,q) << Meq.Selector(ns.stefcal,index=range(nv,nv+4),multi=True);
    ns.output(p,q) << Meq.Composer(sel,dims=[2,2]);
    nv += 4;
  meqmaker.make_per_ifr_bookmarks(ns.output,"Output visibilities");
  
  Bookmarks.Page("StefCal outputs").add(ns.stefcal,viewer="Record Browser");

  if gopts.enabled and gopts.visualize and stefcal_visualize:
    ns.stefcal_vis_G << Meq.PyNode(class_name="StefCalVisualizer",module_name=Calico.OMS.StefCal.StefCal.__file__,
      label="G",flag_unity=visualize_flag_unity,norm_offdiag=visualize_norm_offdiag,
      vells_label=Context.correlations);
    ns.stefcal_vis_G_avg << Meq.PyNode(class_name="StefCalVisualizer",module_name=Calico.OMS.StefCal.StefCal.__file__,
      label="G",freq_average=True,flag_unity=visualize_flag_unity,norm_offdiag=visualize_norm_offdiag,
      vells_label=Context.correlations);
    Bookmarks.Page("StefCal G plotter").add(ns.stefcal_vis_G,viewer="Result Plotter");
    Bookmarks.Page("StefCal G inspector").add(ns.stefcal_vis_G_avg,viewer="Collections Plotter");
    inspectors += [ ns.stefcal_vis_G,ns.stefcal_vis_G_avg ];
  if bopts.enabled and bopts.visualize and stefcal_visualize:
    ns.stefcal_vis_B << Meq.PyNode(class_name="StefCalVisualizer",module_name=Calico.OMS.StefCal.StefCal.__file__,
      label="B",flag_unity=visualize_flag_unity,norm_offdiag=visualize_norm_offdiag,
      vells_label=Context.correlations);
    ns.stefcal_vis_B_avg << Meq.PyNode(class_name="StefCalVisualizer",module_name=Calico.OMS.StefCal.StefCal.__file__,
      label="B",freq_average=True,flag_unity=visualize_flag_unity,norm_offdiag=visualize_norm_offdiag,
      vells_label=Context.correlations);
    Bookmarks.Page("StefCal B plotter").add(ns.stefcal_vis_B,viewer="Result Plotter");
    Bookmarks.Page("StefCal B inspector").add(ns.stefcal_vis_B_avg,viewer="Collections Plotter");
    inspectors += [ ns.stefcal_vis_B,ns.stefcal_vis_B_avg ];
  if deopts.enabled and deopts.visualize and stefcal_visualize:
    for i,label in enumerate(diffgain_labels):
      vde = ns.stefcal_vis_dE(label) << Meq.PyNode(class_name="StefCalVisualizer",module_name=Calico.OMS.StefCal.StefCal.__file__,
        label="dE:%s"%label,flag_unity=visualize_flag_unity,norm_offdiag=visualize_norm_offdiag,
        vells_label=Context.correlations);
      vde_avg = ns.stefcal_vis_dE_avg(label) << Meq.PyNode(class_name="StefCalVisualizer",module_name=Calico.OMS.StefCal.StefCal.__file__,
                                    label="dE:%s"%label,freq_average=True,flag_unity=visualize_flag_unity,norm_offdiag=visualize_norm_offdiag,
                                    vells_label=Context.correlations);
      Bookmarks.Page("StefCal dE:%s plotter"%label).add(vde,viewer="Result Plotter");
      Bookmarks.Page("StefCal dE:%s inspector"%label).add(vde_avg,viewer="Collections Plotter");
      inspectors += [ vde,vde_avg ];

  # make sinks
  StdTrees.make_sinks(ns,ns.output,spigots=spigots,post=inspectors,
      corr_index=mssel.get_corr_index());
  # this should come last, since runtime options may be built up during compilation.
  TDLRuntimeOptions(*meqmaker.runtime_options(nest=False));

  # finally, setup imaging options
  imsel = mssel.imaging_selector(npix=512,arcmin=meqmaker.estimate_image_size());
  TDLRuntimeMenu("Make an image from this MS",*imsel.option_list());

  # and close meqmaker -- this exports annotations, etc
  meqmaker.close();
  
  # add options to clear all solutions 
  from Calico.OMS.StefCal import StefCal
  TDLRuntimeOption("stefcal_reset_all","Remove all existing solutions",False);
  for opt in gopts,bopts,deopts:
    if opt.enabled:
      TDLRuntimeOption("reset","Remove existing %s solutions (%s)"%(opt.label,os.path.basename(opt.table)),False,namespace=opt);
  if stefcal_ifr_gains:
    TDLRuntimeOption("stefcal_reset_ifr_gains","Remove existing interferometer errors (%s)"%(
        os.path.basename(stefcal_ifr_gain_table)),False);
  TDLRuntimeJob(_run_stefcal,"Run StefCal",job_id="stefcal");
Esempio n. 3
0
def _define_forest(ns,parent=None,**kw):
  if run_purr:
    Timba.TDL.GUI.purr(mssel.msname+".purrlog",[mssel.msname,'.']);
  # create Purr pipe
  global purrpipe;
  purrpipe = Purr.Pipe.Pipe(mssel.msname);
  
  # get antennas from MS
  ANTENNAS = mssel.get_antenna_set(list(range(1,15)));
  array = Meow.IfrArray(ns,ANTENNAS,mirror_uvw=False);
  stas = array.stations();
  # get phase centre from MS, setup observation
  observation = Meow.Observation(ns,phase_centre=mssel.get_phase_dir(),
          linear=mssel.is_linear_pol(),
          circular=mssel.is_circular_pol());
  Meow.Context.set(array,observation);
  # get active correlations from MS
  Meow.Context.active_correlations = mssel.get_correlations();
  
  # make spigot nodes
  spigots = spigots0 = outputs = array.spigots(corr=mssel.get_corr_index());

  # ...and an inspector for them
  StdTrees.vis_inspector(ns.inspector('input'),spigots,
                              bookmark="Inspect input visibilities");
  inspectors = [ ns.inspector('input') ];
  Bookmarks.make_node_folder("Input visibilities by baseline",
    [ spigots(p,q) for p,q in array.ifrs() ],sorted=True,ncol=2,nrow=2);

  inspect_ifrs = array.ifrs();
  if do_solve:
    # filter solvable baselines by baseline length
    solve_ifrs = [];
    antpos = mssel.ms_antenna_positions;
    if (min_baseline or max_baseline) and antpos is not None:
      for (ip,p),(iq,q) in array.ifr_index():
        baseline = math.sqrt(((antpos[ip,:]-antpos[iq,:])**2).sum());
        if (not min_baseline or baseline > min_baseline) and \
           (not max_baseline or baseline < max_baseline):
          solve_ifrs.append((p,q));
    else:
      solve_ifrs = array.ifrs();
    inspect_ifrs = solve_ifrs;

  # make a predict tree using the MeqMaker
  if do_solve or do_subtract:
    predict = meqmaker.make_predict_tree(ns);
    # make a ParmGroup and solve jobs for source parameters, if we have any
    if do_solve:
      parms = {};
      for src in meqmaker.get_source_list(ns):
        parms.update([(p.name,p) for p in src.get_solvables()]);
      if parms:
        pg_src = ParmGroup.ParmGroup("source",list(parms.values()),
                    table_name="sources.fmep",
                    individual=True,bookmark=True);
        # now make a solvejobs for the source
        ParmGroup.SolveJob("cal_source","Calibrate source model",pg_src);

  # make nodes to compute residuals
  if do_subtract:
    residuals = ns.residuals;
    for p,q in array.ifrs():
      residuals(p,q) << spigots(p,q) - predict(p,q);
    outputs = residuals;

  # and now we may need to correct the outputs
  if do_correct:
    if do_correct_sky:
      srcs = meqmaker.get_source_list(ns);
      sky_correct = srcs and srcs[0];
    else:
      sky_correct = None;
    outputs = meqmaker.correct_uv_data(ns,outputs,sky_correct=sky_correct,inspect_ifrs=inspect_ifrs);

  # make solve trees
  if do_solve:
    # inputs to the solver are based on calibration type
    # if calibrating visibilities, feed them to condeq directly
    if cal_type == CAL.VIS:
      observed = spigots;
      model    = predict;
    # else take ampl/phase component
    else:
      model = ns.model;
      observed = ns.observed;
      if cal_type == CAL.AMPL:
        for p,q in array.ifrs():
          observed(p,q) << Meq.Abs(spigots(p,q));
          model(p,q)  << Meq.Abs(predict(p,q));
      elif cal_type == CAL.LOGAMPL:
        for p,q in array.ifrs():
          observed(p,q) << Meq.Log(Meq.Abs(spigots(p,q)));
          model(p,q)  << Meq.Log(Meq.Abs(predict(p,q)));
      elif cal_type == CAL.PHASE:
        for p,q in array.ifrs():
          observed(p,q) << 0;
          model(p,q)  << Meq.Abs(predict(p,q))*Meq.FMod(Meq.Arg(spigots(p,q))-Meq.Arg(predict(p,q)),2*math.pi);
      else:
        raise ValueError("unknown cal_type setting: "+str(cal_type));
    # make a solve tree
    solve_tree = StdTrees.SolveTree(ns,model,solve_ifrs=solve_ifrs);
    # the output of the sequencer is either the residuals or the spigots,
    # according to what has been set above
    outputs = solve_tree.sequencers(inputs=observed,outputs=outputs);

  # make sinks and vdm.
  # The list of inspectors must be supplied here
  inspectors += meqmaker.get_inspectors() or [];
  StdTrees.make_sinks(ns,outputs,spigots=spigots0,post=inspectors);
  Bookmarks.make_node_folder("Corrected/residual visibilities by baseline",
    [ outputs(p,q) for p,q in array.ifrs() ],sorted=True,ncol=2,nrow=2);

  if not do_solve:
    if do_subtract:
      name = "Generate residuals";
      comment = "Generated residual visibilities.";
    elif do_correct:
      name = "Generate corrected data";
      comment = "Generated corrected visibilities.";
    else:
      name = None;
    if name:
      # make a TDL job to runsthe tree
      def run_tree (mqs,parent,**kw):
        global tile_size;
        purrpipe.title("Calibrating").comment(comment);
        mqs.execute(Meow.Context.vdm.name,mssel.create_io_request(tile_size),wait=False);
      TDLRuntimeMenu(name,
        TDLOption('tile_size',"Tile size, in timeslots",[10,60,120,240],more=int,
                  doc="""Input data is sliced by time, and processed in chunks (tiles) of
                  the indicated size. Larger tiles are faster, but use more memory."""),
        TDLRuntimeJob(run_tree,name)
      );

  # very important -- insert meqmaker's runtime options properly
  # this should come last, since runtime options may be built up during compilation.
  TDLRuntimeOptions(*meqmaker.runtime_options(nest=False));
  # insert solvejobs
  if do_solve:
    TDLRuntimeOptions(*ParmGroup.get_solvejob_options());
  # finally, setup imaging options
  imsel = mssel.imaging_selector(npix=512,arcmin=meqmaker.estimate_image_size());
  TDLRuntimeMenu("Make an image from this MS",*imsel.option_list());
  
  # and close meqmaker -- this exports annotations, etc
  meqmaker.close();
Esempio n. 4
0
def _define_forest(ns, parent=None, **kw):
    if not mssel.msname:
        raise RuntimeError("MS not set")
    if run_purr:
        Timba.TDL.GUI.purr(mssel.msname + ".purrlog", [mssel.msname, '.'])
    # create Purr pipe
    global purrpipe
    purrpipe = Purr.Pipe.Pipe(mssel.msname)

    # setup contexts from MS
    mssel.setup_observation_context(ns, prefer_baseline_uvw=True)
    array = Meow.Context.array

    # make spigot nodes for data
    if do_solve or do_output not in [CORRUPTED_MODEL]:
        mssel.enable_input_column(True)
        spigots = spigots0 = outputs = array.spigots(
            corr=mssel.get_corr_index())
        if enable_inspectors:
            meqmaker.make_per_ifr_bookmarks(spigots, "Input visibilities")
        # add IFR-based errors, if any
        spigots = meqmaker.apply_visibility_processing(ns, spigots)
    else:
        mssel.enable_input_column(False)
        spigots = spigots0 = None

    # make spigot nodes for model
    corrupt_uvdata = model_spigots = None
    if read_ms_model:
        mssel.enable_model_column(True)
        model_spigots = array.spigots(column="PREDICT",
                                      corr=mssel.get_corr_index())
        if enable_inspectors:
            meqmaker.make_per_ifr_bookmarks(model_spigots,
                                            "UV-model visibilities")
        # if calibrating on (input-corrupt model), make corrupt model
        if do_solve and cal_type == CAL.DIFF:
            corrupt_uvdata = meqmaker.corrupt_uv_data(ns, model_spigots)

    # if needed, then make a predict tree using the MeqMaker
    if do_solve or do_output != CORRECTED_DATA:
        if model_spigots and not corrupt_uvdata:
            uvdata = model_spigots
        else:
            uvdata = None
        predict = meqmaker.make_predict_tree(ns, uvdata=uvdata)
    else:
        predict = None
    output_title = "Uncorrected residuals"

    # make nodes to compute residuals
    if do_output in [CORRECTED_RESIDUALS, RESIDUALS]:
        residuals = ns.residuals
        for p, q in array.ifrs():
            if corrupt_uvdata:
                residuals(p, q) << Meq.Subtract(spigots(
                    p, q), corrupt_uvdata(p, q), predict(p, q))
            else:
                residuals(p, q) << spigots(p, q) - predict(p, q)
        if enable_inspectors:
            meqmaker.make_per_ifr_bookmarks(residuals, "Uncorrected residuals")
        outputs = residuals

    # and now we may need to correct the outputs
    if do_output in [CORRECTED_DATA, CORRECTED_RESIDUALS]:
        if do_correct_sky:
            srcs = meqmaker.get_source_list(ns)
            if do_correct_sky is FIRST_SOURCE:
                sky_correct = srcs and srcs[0]
            else:
                srcs = [
                    src for src in srcs
                    if fnmatch.fnmatchcase(src.name, do_correct_sky)
                ]
                sky_correct = srcs and srcs[0]
        else:
            sky_correct = None
        outputs = meqmaker.correct_uv_data(ns,
                                           outputs,
                                           sky_correct=sky_correct,
                                           flag_jones=flag_jones)
        output_title = "Corrected data" if do_output is CORRECTED_DATA else "Corrected residuals"
    elif do_output == CORRUPTED_MODEL:
        outputs = predict
        output_title = "Predict"
    elif do_output == CORRUPTED_MODEL_ADD:
        outputs = ns.output
        for p, q in array.ifrs():
            outputs(p, q) << spigots(p, q) + predict(p, q)
        output_title = "Data+predict"

    # make flaggers
    if flag_enable and do_output in [
            CORRECTED_DATA, RESIDUALS, CORRECTED_RESIDUALS
    ]:
        flaggers = []
        if flag_res is not None or flag_mean_res is not None:
            for p, q in array.ifrs():
                ns.absres(p, q) << Meq.Abs(outputs(p, q))
        # make flagger for residuals
        if flag_res is not None:
            for p, q in array.ifrs():
                ns.flagres(p, q) << Meq.ZeroFlagger(
                    ns.absres(p, q) - flag_res,
                    oper='gt',
                    flag_bit=Meow.MSUtils.FLAGMASK_OUTPUT)
            flaggers.append(ns.flagres)
            # ...and an inspector for them
            if enable_inspectors:
                meqmaker.make_per_ifr_bookmarks(ns.flagres,
                                                "Residual amplitude flags")
        # make flagger for mean residuals
        if flag_mean_res is not None:
            ns.meanabsres << Meq.Mean(
                *[ns.absres(p, q) for p, q in array.ifrs()])
            ns.flagmeanres << Meq.ZeroFlagger(
                ns.meanabsres - flag_mean_res,
                oper='gt',
                flag_bit=Meow.MSUtils.FLAGMASK_OUTPUT)
            Meow.Bookmarks.Page("Mean residual amplitude flags").add(
                ns.flagmeanres, viewer="Result Plotter")
            flaggers.append(lambda p, q: ns.flagmeanres)

        # merge flags into output
        if flaggers:
            if enable_inspectors:
                meqmaker.make_per_ifr_bookmarks(outputs,
                                                output_title + " (unflagged)")
            for p, q in array.ifrs():
                ns.flagged(p, q) << Meq.MergeFlags(
                    outputs(p, q), *[f(p, q) for f in flaggers])
            outputs = ns.flagged

    if enable_inspectors:
        meqmaker.make_per_ifr_bookmarks(outputs, output_title)
        abs_outputs = outputs('abs')
        for p, q in array.ifrs():
            abs_outputs(p, q) << Meq.Abs(outputs(p, q))
        meqmaker.make_per_ifr_bookmarks(abs_outputs,
                                        output_title + " (mean amplitudes)")

    # make solve trees
    if do_solve:
        # parse ifr specification
        solve_ifrs = array.subset(calibrate_ifrs, strict=False).ifrs()
        if not solve_ifrs:
            raise RuntimeError(
                "No interferometers selected for calibration. Check your ifr specification (under calibration options)."
            )
        # inputs to the solver are based on calibration type
        if corrupt_uvdata:
            [
                ns.diff(p, q) << spigots(p, q) - corrupt_uvdata(p, q)
                for p, q in solve_ifrs
            ]
            rhs = ns.diff
        else:
            rhs = spigots
        lhs = predict
        weights = modulo = None
        # if calibrating visibilities, feed them to condeq directly, else take ampl/phase
        if cal_what == CAL.VIS:
            pass
        elif cal_what == CAL.AMPL:
            [
                x('ampl', p, q) << Meq.Abs(x(p, q)) for p, q in ifrs
                for x in [rhs, lhs]
            ]
            lhs = lhs('ampl')
            rhs = rhs('ampl')
        elif cal_what == CAL.LOGAMPL:
            [
                x('logampl', p, q) << Meq.Log(Meq.Abs(x(p, q)))
                for p, q in ifrs for x in [rhs, lhs]
            ]
            lhs = lhs('logampl')
            rhs = rhs('logampl')
        elif cal_what == CAL.PHASE:
            [
                x('phase', p, q) << Meq.Arg(x(p, q)) for p, q in ifrs
                for x in [rhs, lhs]
            ]
            [rhs('ampl', p, q) << Meq.Abs(rhs(p, q)) for p, q in ifrs]
            lhs = lhs('phase')
            rhs = rhs('phase')
            weights = rhs('ampl')
            modulo = 2 * math.pi
        else:
            raise ValueError("unknown cal_what setting: " + str(cal_what))
        # make a solve tree
        solve_tree = StdTrees.SolveTree(ns,
                                        lhs,
                                        solve_ifrs=solve_ifrs,
                                        weights=weights,
                                        modulo=modulo)
        # the output of the sequencer is either the residuals or the spigots,
        # according to what has been set above
        outputs = solve_tree.sequencers(inputs=rhs, outputs=outputs)

    post = ((enable_inspectors and meqmaker.get_inspectors()) or [])
    StdTrees.make_sinks(ns,
                        outputs,
                        spigots=spigots0,
                        post=post,
                        corr_index=mssel.get_corr_index())

    if not do_solve:
        name = "Generate " + output_title.lower()
        comment = "Generated " + output_title.lower()
        if name:
            # make a TDL job to run the tree
            def run_tree(mqs, parent, wait=False, **kw):
                global tile_size
                purrpipe.title("Calibrating").comment(comment)
                return mqs.execute(Meow.Context.vdm.name,
                                   mssel.create_io_request(tile_size),
                                   wait=wait)

            TDLRuntimeMenu(
                name,
                TDLOption(
                    'tile_size',
                    "Tile size, in timeslots", [10, 60, 120, 240],
                    more=int,
                    doc=
                    """Input data is sliced by time, and processed in chunks (tiles) of
                  the indicated size. Larger tiles are faster, but use more memory."""
                ), TDLJob(run_tree, name, job_id='generate_visibilities'))

    # very important -- insert meqmaker's runtime options properly
    # this should come last, since runtime options may be built up during compilation.
    TDLRuntimeOptions(*meqmaker.runtime_options(nest=False))
    # insert solvejobs
    if do_solve:
        TDLRuntimeOptions(*ParmGroup.get_solvejob_options())
    # finally, setup imaging options
    imsel = mssel.imaging_selector(npix=512,
                                   arcmin=meqmaker.estimate_image_size())
    TDLRuntimeMenu("Make an image from this MS", *imsel.option_list())

    # and close meqmaker -- this exports annotations, etc
    meqmaker.close()
Esempio n. 5
0
def _define_forest(ns, parent=None, **kw):
    if not mssel.msname:
        raise RuntimeError("MS not set")
    if run_purr:
        Timba.TDL.GUI.purr(mssel.msname + ".purrlog", [mssel.msname, '.'])
    # create Purr pipe
    global purrpipe
    purrpipe = Purr.Pipe.Pipe(mssel.msname)

    # setup contexts from MS
    mssel.setup_observation_context(ns)
    array = Meow.Context.array

    # make spigot nodes for data
    mssel.enable_input_column(True)
    spigots = array.spigots(corr=mssel.get_corr_index())
    meqmaker.make_per_ifr_bookmarks(spigots, "Input visibilities")

    # data tensor
    ns.DT << Meq.Composer(
        dims=[0], mt_polling=True, *[spigots(p, q) for p, q in array.ifrs()])
    # list of model tensors
    models = []

    if read_ms_model:
        mssel.enable_model_column(True)
        model_spigots = array.spigots(column="PREDICT",
                                      corr=mssel.get_corr_index())
        meqmaker.make_per_ifr_bookmarks(model_spigots, "UV-model visibilities")
        mtuv = ns.MT("uv") << Meq.Composer(
            dims=[0],
            mt_polling=True,
            *[model_spigots(p, q) for p, q in array.ifrs()])

    # predict tree using the MeqMaker
    all_sources = meqmaker.get_source_list(ns)
    dg_sources = deopts.enabled and dgsel.filter(all_sources)
    if dg_sources:
        # first group all sources without a diffgain on them
        groups = [[src for src in all_sources if not src in dg_sources]]
        # group diffgain-enabled sources by grouping tag
        clusters = set(
            [src.get_attr(diffgain_group, None) for src in dg_sources])
        dg_groups = [(name, [
            src for src in dg_sources if src.get_attr(diffgain_group) == name
        ]) for name in clusters if name]
        # add sources without a grouping tag individually, as single-source groups
        dg_groups += [(src.name, [src]) for src in dg_sources
                      if not src.get_attr(diffgain_group, None)]
        # now sort by brightness
        flux_dgg = [(sum(
            [src.get_attr('Iapp', 0) or src.get_attr('I')
             for src in dgg[1]]), dgg) for dgg in dg_groups]
        from past.builtins import cmp
        from functools import cmp_to_key
        flux_dgg.sort(key=cmp_to_key(lambda a, b: cmp(b[0], a[0])))
        diffgain_labels = [dgg[0] for flux, dgg in flux_dgg]
        groups += [dgg[1] for flux, dgg in flux_dgg]
        num_diffgains = len(flux_dgg)
        # now make predict trees
        for i, group in enumerate(groups):
            MT = ns.MT(group[0].name if i else "all")
            # first tensor is "MT", rest qualified by source names
            predict = meqmaker.make_predict_tree(MT.Subscope(), sources=group)
            MT << Meq.Composer(dims=[0],
                               mt_polling=True,
                               *[predict(p, q) for p, q in array.ifrs()])
            # if reading an extra uv-model, add to first term
            if not i and read_ms_model:
                MT = ns.MT << Meq.Add(MT, mtuv)
            models.append(MT)
        print("Number of diffgain predict groups:", len(groups))
    else:
        diffgain_labels = []
        num_diffgains = 0
        predict = meqmaker.make_predict_tree(ns)
        MT = ns.MT("all") << Meq.Composer(
            dims=[0],
            mt_polling=True,
            *[predict(p, q) for p, q in array.ifrs()])
        if read_ms_model:
            MT = ns.MT << Meq.Add(MT, mtuv)
        models.append(MT)

    solve_ifrs = array.subset(calibrate_ifrs, strict=False).ifrs()
    downsample_subtiling = [
        stefcal_downsample_timeint, stefcal_downsample_freqint
    ] if stefcal_downsample else [1, 1]

    import Calico.OMS.StefCal.StefCal
    kwopts = {}
    gopts.set_stefcal_node_options(kwopts, visualize=stefcal_visualize)
    bopts.set_stefcal_node_options(kwopts, visualize=stefcal_visualize)
    deopts.set_stefcal_node_options(kwopts, visualize=stefcal_visualize)
    ns.stefcal << Meq.PyNode(
        class_name="StefCalNode",
        module_name=Calico.OMS.StefCal.StefCal.__file__,
        ifrs=["%s:%s" % (p, q) for p, q in array.ifrs()],
        baselines=[
            array.baseline(ip, iq) for (ip, p), (iq, q) in array.ifr_index()
        ],
        solve_ifrs=["%s:%s" % (p, q) for p, q in solve_ifrs],
        noise_per_chan=stefcal_noise_per_chan,
        downsample_subtiling=downsample_subtiling,
        num_major_loops=stefcal_nmajor,
        regularization_factor=1e-6,  #
        rescale=stefcal_rescale,
        init_from_previous=False,
        critical_flag_threshold=critical_flag_threshold,
        diffgain_labels=diffgain_labels,
        # flagging options
        output_flag_bit=Meow.MSUtils.FLAGMASK_OUTPUT,
        # IFR gain solution options
        apply_ifr_gains=stefcal_ifr_gains,
        solve_ifr_gains=(stefcal_ifr_gain_mode != MODE_SOLVE_APPLY),
        reset_ifr_gains=stefcal_ifr_gain_reset,
        save_ifr_gains=(stefcal_ifr_gain_mode == MODE_SOLVE_SAVE),
        ifr_gain_table=stefcal_ifr_gain_table,
        per_chan_ifr_gains=stefcal_per_chan_ifr_gains,
        diag_ifr_gains=(stefcal_diagonal_ifr_gains == DIAGONLY),
        residuals=(do_output == CORRECTED_RESIDUALS),
        subtract_dgsrc=(do_output == CORRECTED_DATA_SUB),
        verbose=stefcal_verbose,
        children=[ns.DT] + models,
        **kwopts)

    inspectors = meqmaker.get_inspectors() or []
    # make output bookmarks
    nv = 0
    for p, q in array.ifrs():
        sel = ns.output_sel(p, q) << Meq.Selector(
            ns.stefcal, index=list(range(nv, nv + 4)), multi=True)
        ns.output(p, q) << Meq.Composer(sel, dims=[2, 2])
        nv += 4
    meqmaker.make_per_ifr_bookmarks(ns.output, "Output visibilities")

    Bookmarks.Page("StefCal outputs").add(ns.stefcal, viewer="Record Browser")

    if gopts.enabled and gopts.visualize and stefcal_visualize:
        ns.stefcal_vis_G << Meq.PyNode(
            class_name="StefCalVisualizer",
            module_name=Calico.OMS.StefCal.StefCal.__file__,
            label="G",
            flag_unity=visualize_flag_unity,
            norm_offdiag=visualize_norm_offdiag,
            vells_label=Context.correlations)
        ns.stefcal_vis_G_avg << Meq.PyNode(
            class_name="StefCalVisualizer",
            module_name=Calico.OMS.StefCal.StefCal.__file__,
            label="G",
            freq_average=True,
            flag_unity=visualize_flag_unity,
            norm_offdiag=visualize_norm_offdiag,
            vells_label=Context.correlations)
        Bookmarks.Page("StefCal G plotter").add(ns.stefcal_vis_G,
                                                viewer="Result Plotter")
        Bookmarks.Page("StefCal G inspector").add(ns.stefcal_vis_G_avg,
                                                  viewer="Collections Plotter")
        inspectors += [ns.stefcal_vis_G, ns.stefcal_vis_G_avg]
    if bopts.enabled and bopts.visualize and stefcal_visualize:
        ns.stefcal_vis_B << Meq.PyNode(
            class_name="StefCalVisualizer",
            module_name=Calico.OMS.StefCal.StefCal.__file__,
            label="B",
            flag_unity=visualize_flag_unity,
            norm_offdiag=visualize_norm_offdiag,
            vells_label=Context.correlations)
        ns.stefcal_vis_B_avg << Meq.PyNode(
            class_name="StefCalVisualizer",
            module_name=Calico.OMS.StefCal.StefCal.__file__,
            label="B",
            freq_average=True,
            flag_unity=visualize_flag_unity,
            norm_offdiag=visualize_norm_offdiag,
            vells_label=Context.correlations)
        Bookmarks.Page("StefCal B plotter").add(ns.stefcal_vis_B,
                                                viewer="Result Plotter")
        Bookmarks.Page("StefCal B inspector").add(ns.stefcal_vis_B_avg,
                                                  viewer="Collections Plotter")
        inspectors += [ns.stefcal_vis_B, ns.stefcal_vis_B_avg]
    if deopts.enabled and deopts.visualize and stefcal_visualize:
        for i, label in enumerate(diffgain_labels):
            vde = ns.stefcal_vis_dE(label) << Meq.PyNode(
                class_name="StefCalVisualizer",
                module_name=Calico.OMS.StefCal.StefCal.__file__,
                label="dE:%s" % label,
                flag_unity=visualize_flag_unity,
                norm_offdiag=visualize_norm_offdiag,
                vells_label=Context.correlations)
            vde_avg = ns.stefcal_vis_dE_avg(label) << Meq.PyNode(
                class_name="StefCalVisualizer",
                module_name=Calico.OMS.StefCal.StefCal.__file__,
                label="dE:%s" % label,
                freq_average=True,
                flag_unity=visualize_flag_unity,
                norm_offdiag=visualize_norm_offdiag,
                vells_label=Context.correlations)
            Bookmarks.Page("StefCal dE:%s plotter" % label).add(
                vde, viewer="Result Plotter")
            Bookmarks.Page("StefCal dE:%s inspector" % label).add(
                vde_avg, viewer="Collections Plotter")
            inspectors += [vde, vde_avg]

    # make sinks
    StdTrees.make_sinks(ns,
                        ns.output,
                        spigots=spigots,
                        post=inspectors,
                        corr_index=mssel.get_corr_index())
    # this should come last, since runtime options may be built up during compilation.
    TDLRuntimeOptions(*meqmaker.runtime_options(nest=False))

    # finally, setup imaging options
    imsel = mssel.imaging_selector(npix=512,
                                   arcmin=meqmaker.estimate_image_size())
    TDLRuntimeMenu("Make an image from this MS", *imsel.option_list())

    # and close meqmaker -- this exports annotations, etc
    meqmaker.close()

    # add options to clear all solutions
    from Calico.OMS.StefCal import StefCal
    TDLRuntimeOption("stefcal_reset_all", "Remove all existing solutions",
                     False)
    for opt in gopts, bopts, deopts:
        if opt.enabled:
            TDLRuntimeOption("reset",
                             "Remove existing %s solutions (%s)" %
                             (opt.label, os.path.basename(opt.table)),
                             False,
                             namespace=opt)
    if stefcal_ifr_gains:
        TDLRuntimeOption(
            "stefcal_reset_ifr_gains",
            "Remove existing interferometer errors (%s)" %
            (os.path.basename(stefcal_ifr_gain_table)), False)
    TDLRuntimeJob(_run_stefcal, "Run StefCal", job_id="stefcal")
def _define_forest(ns,parent=None,**kw):
  if not mssel.msname:
    raise RuntimeError,"MS not set";
  if run_purr:
    Timba.TDL.GUI.purr(mssel.msname+".purrlog",[mssel.msname,'.']);
  # create Purr pipe
  global purrpipe;
  purrpipe = Purr.Pipe.Pipe(mssel.msname);

  # setup contexts from MS
  mssel.setup_observation_context(ns,prefer_baseline_uvw=True);
  array = Meow.Context.array;

  # make spigot nodes for data
  if do_solve or do_output not in [CORRUPTED_MODEL]:
    mssel.enable_input_column(True);
    spigots = spigots0 = outputs = array.spigots(corr=mssel.get_corr_index());
    if enable_inspectors:
      meqmaker.make_per_ifr_bookmarks(spigots,"Input visibilities");
    # add IFR-based errors, if any
    spigots = meqmaker.apply_visibility_processing(ns,spigots);
  else:
    mssel.enable_input_column(False);
    spigots = spigots0 = None;

  # make spigot nodes for model
  corrupt_uvdata = model_spigots = None;
  if read_ms_model:
    mssel.enable_model_column(True);
    model_spigots = array.spigots(column="PREDICT",corr=mssel.get_corr_index());
    if enable_inspectors:
      meqmaker.make_per_ifr_bookmarks(model_spigots,"UV-model visibilities");
    # if calibrating on (input-corrupt model), make corrupt model
    if do_solve and cal_type == CAL.DIFF:
      corrupt_uvdata = meqmaker.corrupt_uv_data(ns,model_spigots);

  # if needed, then make a predict tree using the MeqMaker
  if do_solve or do_output != CORRECTED_DATA:
    if model_spigots and not corrupt_uvdata:
      uvdata = model_spigots;
    else:
      uvdata = None;
    predict = meqmaker.make_predict_tree(ns,uvdata=uvdata);
  else:
    predict = None;
  output_title = "Uncorrected residuals";

  # make nodes to compute residuals
  if do_output in [CORRECTED_RESIDUALS,RESIDUALS]:
    residuals = ns.residuals;
    for p,q in array.ifrs():
      if corrupt_uvdata:
        residuals(p,q) << Meq.Subtract(spigots(p,q),corrupt_uvdata(p,q),predict(p,q));
      else:
        residuals(p,q) << spigots(p,q) - predict(p,q);
    if enable_inspectors:
      meqmaker.make_per_ifr_bookmarks(residuals,"Uncorrected residuals");
    outputs = residuals;

  # and now we may need to correct the outputs
  if do_output in [CORRECTED_DATA,CORRECTED_RESIDUALS]:
    if do_correct_sky:
      srcs = meqmaker.get_source_list(ns);
      if do_correct_sky is FIRST_SOURCE:
        sky_correct = srcs and srcs[0];
      else:
        srcs = [ src for src in srcs if fnmatch.fnmatchcase(src.name,do_correct_sky) ];
        sky_correct = srcs and srcs[0];
    else:
      sky_correct = None;
    outputs = meqmaker.correct_uv_data(ns,outputs,sky_correct=sky_correct,
                                      flag_jones=flag_jones);
    output_title = "Corrected data" if do_output is CORRECTED_DATA else "Corrected residuals";
  elif do_output == CORRUPTED_MODEL:
    outputs = predict;
    output_title = "Predict";
  elif do_output == CORRUPTED_MODEL_ADD:
    outputs = ns.output;
    for p,q in array.ifrs():
      outputs(p,q) << spigots(p,q) + predict(p,q);
    output_title = "Data+predict";

  # make flaggers
  if flag_enable and do_output in [ CORRECTED_DATA,RESIDUALS,CORRECTED_RESIDUALS ]:
    flaggers = [];
    if flag_res is not None or flag_mean_res is not None:
      for p,q in array.ifrs():
        ns.absres(p,q) << Meq.Abs(outputs(p,q));
    # make flagger for residuals
    if flag_res is not None:
      for p,q in array.ifrs():
        ns.flagres(p,q) << Meq.ZeroFlagger(ns.absres(p,q)-flag_res,oper='gt',flag_bit=Meow.MSUtils.FLAGMASK_OUTPUT);
      flaggers.append(ns.flagres);
      # ...and an inspector for them
      if enable_inspectors:
        meqmaker.make_per_ifr_bookmarks(ns.flagres,"Residual amplitude flags");
    # make flagger for mean residuals
    if flag_mean_res is not None:
      ns.meanabsres << Meq.Mean(*[ns.absres(p,q) for p,q in array.ifrs()]);
      ns.flagmeanres << Meq.ZeroFlagger(ns.meanabsres-flag_mean_res,oper='gt',flag_bit=Meow.MSUtils.FLAGMASK_OUTPUT);
      Meow.Bookmarks.Page("Mean residual amplitude flags").add(ns.flagmeanres,viewer="Result Plotter");
      flaggers.append(lambda p,q:ns.flagmeanres);

    # merge flags into output
    if flaggers:
      if enable_inspectors:
        meqmaker.make_per_ifr_bookmarks(outputs,output_title+" (unflagged)");
      for p,q in array.ifrs():
        ns.flagged(p,q) << Meq.MergeFlags(outputs(p,q),*[f(p,q) for f in flaggers]);
      outputs = ns.flagged;

  if enable_inspectors:
    meqmaker.make_per_ifr_bookmarks(outputs,output_title);
    abs_outputs = outputs('abs');
    for p,q in array.ifrs():
      abs_outputs(p,q) << Meq.Abs(outputs(p,q));
    meqmaker.make_per_ifr_bookmarks(abs_outputs,output_title+" (mean amplitudes)");

  # make solve trees
  if do_solve:
    # parse ifr specification
    solve_ifrs  = array.subset(calibrate_ifrs,strict=False).ifrs();
    if not solve_ifrs:
      raise RuntimeError,"No interferometers selected for calibration. Check your ifr specification (under calibration options).";
    # inputs to the solver are based on calibration type
    if corrupt_uvdata:
      [ ns.diff(p,q) << spigots(p,q) - corrupt_uvdata(p,q) for p,q in solve_ifrs ];
      rhs = ns.diff;
    else:
      rhs = spigots;
    lhs = predict;
    weights = modulo = None;
    # if calibrating visibilities, feed them to condeq directly, else take ampl/phase
    if cal_what == CAL.VIS:
      pass;
    elif cal_what == CAL.AMPL:
      [ x('ampl',p,q) << Meq.Abs(x(p,q)) for p,q in ifrs for x in rhs,lhs ];
      lhs = lhs('ampl');
      rhs = rhs('ampl');
    elif cal_what == CAL.LOGAMPL:
      [ x('logampl',p,q) << Meq.Log(Meq.Abs(x(p,q))) for p,q in ifrs for x in rhs,lhs ];
      lhs = lhs('logampl');
      rhs = rhs('logampl');
    elif cal_what == CAL.PHASE:
      [ x('phase',p,q) << Meq.Arg(x(p,q)) for p,q in ifrs for x in rhs,lhs ];
      [ rhs('ampl',p,q) << Meq.Abs(rhs(p,q)) for p,q in ifrs  ];
      lhs = lhs('phase');
      rhs = rhs('phase');
      weights = rhs('ampl');
      modulo = 2*math.pi;
    else:
      raise ValueError,"unknown cal_what setting: "+str(cal_what);
    # make a solve tree
    solve_tree = StdTrees.SolveTree(ns,lhs,solve_ifrs=solve_ifrs,weights=weights,modulo=modulo);
    # the output of the sequencer is either the residuals or the spigots,
    # according to what has been set above
    outputs = solve_tree.sequencers(inputs=rhs,outputs=outputs);

  post = ( ( enable_inspectors and meqmaker.get_inspectors() ) or [] );
  StdTrees.make_sinks(ns,outputs,spigots=spigots0,post=post,corr_index=mssel.get_corr_index());

  if not do_solve:
    name = "Generate "+output_title.lower();
    comment = "Generated "+output_title.lower();
    if name:
      # make a TDL job to run the tree
      def run_tree (mqs,parent,wait=False,**kw):
        global tile_size;
        purrpipe.title("Calibrating").comment(comment);
        return mqs.execute(Meow.Context.vdm.name,mssel.create_io_request(tile_size),wait=wait);
      TDLRuntimeMenu(name,
        TDLOption('tile_size',"Tile size, in timeslots",[10,60,120,240],more=int,
                  doc="""Input data is sliced by time, and processed in chunks (tiles) of
                  the indicated size. Larger tiles are faster, but use more memory."""),
        TDLJob(run_tree,name,job_id='generate_visibilities')
      );

  # very important -- insert meqmaker's runtime options properly
  # this should come last, since runtime options may be built up during compilation.
  TDLRuntimeOptions(*meqmaker.runtime_options(nest=False));
  # insert solvejobs
  if do_solve:
    TDLRuntimeOptions(*ParmGroup.get_solvejob_options());
  # finally, setup imaging options
  imsel = mssel.imaging_selector(npix=512,arcmin=meqmaker.estimate_image_size());
  TDLRuntimeMenu("Make an image from this MS",*imsel.option_list());

  # and close meqmaker -- this exports annotations, etc
  meqmaker.close();
Esempio n. 7
0
def _define_forest(ns, parent=None, **kw):
    if not mssel.msname:
        raise RuntimeError('MS name not set')

    mssel.setup_observation_context(ns)
    array = Context.array

    # Data and model input

    if do_solve or output_type.need_data:
        mssel.enable_input_column(True)
        spigots = array.spigots(corr=mssel.get_corr_index())
        meqmaker.make_per_ifr_bookmarks(spigots, 'Input visibilities')
    else:
        mssel.enable_input_column(False)
        spigots = None

    if do_solve or output_type.need_model:
        predict = meqmaker.make_predict_tree(ns, uvdata=None)
    else:
        predict = None

    # Data output

    outputs = output_type.apply(ns, meqmaker, array.ifrs(), spigots, predict)

    # Flagging

    if flag_enable and output_type.flag_data:
        flaggers = []

        if flag_res is not None or flag_mean_res is not None:
            for p, q in array.ifrs():
                ns.absres(p, q) << Meq.Abs(outputs(p, q))

        if flag_res is not None:
            for p, q in array.ifrs():
                ns.flagres(p, q) << Meq.ZeroFlagger(
                    ns.absres(p, q) - flag_res,
                    oper='gt',
                    flag_bit=MSUtils.FLAGMASK_OUTPUT)
            flaggers.append(ns.flagres)
            meqmaker.make_per_ifr_bookmarks(ns.flagres,
                                            'Residual amplitude flags')

        if flag_mean_res is not None:
            ns.meanabsres << Meq.Mean(
                *[ns.absres(p, q) for p, q in array.ifrs()])
            ns.flagmeanres << Meq.ZeroFlagger(ns.meanabsres - flag_mean_res,
                                              oper='gt',
                                              flag_bit=MSUtils.FLAGMASK_OUTPUT)
            Bookmarks.Page('Mean residual amplitude flags').add(
                ns.flagmeanres, viewer='Result Plotter')
            flaggers.append(lambda p, q: ns.flagmeanres)

        if flaggers:
            meqmaker.make_per_ifr_bookmarks(outputs,
                                            output_type.desc + ' (unflagged)')
            for p, q in array.ifrs():
                ns.flagged(p, q) << Meq.MergeFlags(
                    outputs(p, q), *[f(p, q) for f in flaggers])
            outputs = ns.flagged

    meqmaker.make_per_ifr_bookmarks(outputs, output_type.desc)

    # Solve trees

    if do_solve:
        # parse ifr specification
        solve_ifrs = array.subset(calibrate_ifrs, strict=False).ifrs()

        if not solve_ifrs:
            raise RuntimeError(
                'No interferometers selected for calibration. '
                'Check your ifr specification (under calibration options).')

        lhs, rhs, weights, modulo = cal_quant.apply(solve_ifrs, predict,
                                                    spigots)
        solve_tree = StdTrees.SolveTree(ns,
                                        lhs,
                                        solve_ifrs=solve_ifrs,
                                        weights=weights,
                                        modulo=modulo)
        outputs = solve_tree.sequencers(inputs=rhs, outputs=outputs)

    StdTrees.make_sinks(ns,
                        outputs,
                        spigots=spigots,
                        post=meqmaker.get_inspectors() or [],
                        corr_index=mssel.get_corr_index())

    if not do_solve:
        name = 'Generate ' + output_type.desc.lower()
        comment = 'Generated ' + output_type.desc.lower()

        def run_tree(mqs, parent, wait=False, **kw):
            return mqs.execute(Context.vdm.name,
                               mssel.create_io_request(tile_size),
                               wait=wait)

        doc = """Input data are sliced by time, and processed in chunks (tiles) of
the indicated size. Larger tiles are faster, but use more memory."""

        TDLRuntimeMenu(
            name,
            TDLOption('tile_size',
                      'Tile size, in timeslots', [10, 60, 120, 240],
                      more=int,
                      doc=doc),
            TDLJob(run_tree, name, job_id='generate_visibilities'))

    # very important -- insert meqmaker's runtime options properly
    # this should come last, since runtime options may be built up
    # during compilation.

    TDLRuntimeOptions(*meqmaker.runtime_options(nest=False))

    if do_solve:
        TDLRuntimeOptions(*ParmGroup.get_solvejob_options())

    imsel = mssel.imaging_selector(npix=512,
                                   arcmin=meqmaker.estimate_image_size())
    TDLRuntimeMenu('Make an image', *imsel.option_list())
    meqmaker.close()
Esempio n. 8
0
File: pkgw.py Progetto: aimran/pwpy
def _define_forest (ns, parent=None, **kw):
    if not mssel.msname:
        raise RuntimeError ('MS name not set')

    mssel.setup_observation_context (ns)
    array = Context.array

    # Data and model input

    if do_solve or output_type.need_data:
        mssel.enable_input_column (True)
        spigots = array.spigots (corr=mssel.get_corr_index ())
        meqmaker.make_per_ifr_bookmarks (spigots, 'Input visibilities')
    else:
        mssel.enable_input_column (False)
        spigots = None

    if do_solve or output_type.need_model:
        predict = meqmaker.make_predict_tree (ns, uvdata=None)
    else:
        predict = None

    # Data output

    outputs = output_type.apply (ns, meqmaker, array.ifrs (), spigots, predict)

    # Flagging

    if flag_enable and output_type.flag_data:
        flaggers = []

        if flag_res is not None or flag_mean_res is not None:
            for p, q in array.ifrs ():
                ns.absres(p,q) << Meq.Abs (outputs(p,q))

        if flag_res is not None:
            for p, q in array.ifrs ():
                ns.flagres(p,q) << Meq.ZeroFlagger (ns.absres(p,q) - flag_res,
                                                    oper='gt',
                                                    flag_bit=MSUtils.FLAGMASK_OUTPUT)
            flaggers.append (ns.flagres)
            meqmaker.make_per_ifr_bookmarks (ns.flagres, 'Residual amplitude flags')

        if flag_mean_res is not None:
            ns.meanabsres << Meq.Mean (*[ns.absres(p,q) for p, q in array.ifrs()])
            ns.flagmeanres << Meq.ZeroFlagger (ns.meanabsres - flag_mean_res,
                                               oper='gt', flag_bit=MSUtils.FLAGMASK_OUTPUT)
            Bookmarks.Page ('Mean residual amplitude flags').add (ns.flagmeanres,
                                                                  viewer='Result Plotter')
            flaggers.append (lambda p, q: ns.flagmeanres)

        if flaggers:
            meqmaker.make_per_ifr_bookmarks (outputs, output_type.desc + ' (unflagged)')
            for p, q in array.ifrs ():
                ns.flagged(p,q) << Meq.MergeFlags (outputs(p,q), *[f(p,q) for f in flaggers])
            outputs = ns.flagged

    meqmaker.make_per_ifr_bookmarks (outputs, output_type.desc)

    # Solve trees

    if do_solve:
        # parse ifr specification
        solve_ifrs = array.subset (calibrate_ifrs, strict=False).ifrs()

        if not solve_ifrs:
            raise RuntimeError ('No interferometers selected for calibration. '
                                'Check your ifr specification (under calibration options).')

        lhs, rhs, weights, modulo = cal_quant.apply (solve_ifrs, predict, spigots)
        solve_tree = StdTrees.SolveTree (ns, lhs, solve_ifrs=solve_ifrs,
                                         weights=weights, modulo=modulo)
        outputs = solve_tree.sequencers (inputs=rhs, outputs=outputs)

    StdTrees.make_sinks (ns, outputs, spigots=spigots,
                         post=meqmaker.get_inspectors () or [],
                         corr_index=mssel.get_corr_index ())

    if not do_solve:
        name = 'Generate ' + output_type.desc.lower ()
        comment = 'Generated ' + output_type.desc.lower ()

        def run_tree (mqs, parent, wait=False, **kw):
            return mqs.execute (Context.vdm.name, mssel.create_io_request (tile_size),
                                wait=wait)

        doc = """Input data are sliced by time, and processed in chunks (tiles) of
the indicated size. Larger tiles are faster, but use more memory."""

        TDLRuntimeMenu(name, TDLOption ('tile_size', 'Tile size, in timeslots',
                                        [10, 60, 120, 240], more=int, doc=doc),
                       TDLJob (run_tree, name, job_id='generate_visibilities'))

    # very important -- insert meqmaker's runtime options properly
    # this should come last, since runtime options may be built up
    # during compilation.

    TDLRuntimeOptions (*meqmaker.runtime_options (nest=False))

    if do_solve:
        TDLRuntimeOptions (*ParmGroup.get_solvejob_options ())

    imsel = mssel.imaging_selector (npix=512, arcmin=meqmaker.estimate_image_size ())
    TDLRuntimeMenu ('Make an image', *imsel.option_list ())
    meqmaker.close()