def main():
    log = Logger.get()
    gt = GlobalTimers.get()
    gt.start("toast_planck_reduce (total)")

    mpiworld, procs, rank, comm = get_comm()

    if comm.world_rank == 0:
        print("Running with {} processes at {}".format(
            procs, str(datetime.datetime.now())))

    parser = argparse.ArgumentParser(description='Simple MADAM Mapmaking',
                                     fromfile_prefix_chars='@')
    parser.add_argument('--skip_madam',
                        dest='skip_madam',
                        default=False,
                        action='store_true',
                        help='D not make maps with Madam.')
    parser.add_argument('--skip_noise',
                        dest='skip_noise',
                        default=False,
                        action='store_true',
                        help='Do not add simulated noise to the TOD.')
    parser.add_argument('--rimo', required=True, help='RIMO file')
    parser.add_argument('--freq', required=True, type=np.int, help='Frequency')
    parser.add_argument('--debug',
                        dest='debug',
                        default=False,
                        action='store_true',
                        help='Write data distribution info to file')
    parser.add_argument('--dets',
                        required=False,
                        default=None,
                        help='Detector list (comma separated)')
    parser.add_argument('--effdir',
                        required=True,
                        help='Input Exchange Format File directory')
    parser.add_argument('--effdir2',
                        required=False,
                        help='Additional input Exchange Format File directory')
    parser.add_argument('--effdir_pntg',
                        required=False,
                        help='Input Exchange Format File directory for '
                        'pointing')
    parser.add_argument('--effdir_fsl',
                        required=False,
                        help='Input Exchange Format File directory for '
                        'straylight')
    parser.add_argument('--obtmask',
                        required=False,
                        default=1,
                        type=np.int,
                        help='OBT flag mask')
    parser.add_argument('--flagmask',
                        required=False,
                        default=1,
                        type=np.int,
                        help='Quality flag mask')
    parser.add_argument('--pntflagmask',
                        required=False,
                        default=0,
                        type=np.int,
                        help='Which OBT flag bits to raise for HCM maneuvers')
    parser.add_argument('--bad_intervals',
                        required=False,
                        help='Path to bad interval file.')
    parser.add_argument('--ringdb', required=True, help='Ring DB file')
    parser.add_argument('--odfirst',
                        required=False,
                        default=None,
                        help='First OD to use')
    parser.add_argument('--odlast',
                        required=False,
                        default=None,
                        help='Last OD to use')
    parser.add_argument('--ringfirst',
                        required=False,
                        default=None,
                        help='First ring to use')
    parser.add_argument('--ringlast',
                        required=False,
                        default=None,
                        help='Last ring to use')
    parser.add_argument('--obtfirst',
                        required=False,
                        default=None,
                        help='First OBT to use')
    parser.add_argument('--obtlast',
                        required=False,
                        default=None,
                        help='Last OBT to use')
    parser.add_argument('--read_eff',
                        dest='read_eff',
                        default=False,
                        action='store_true',
                        help='Read and co-add the signal from effdir')
    parser.add_argument('--decalibrate',
                        required=False,
                        help='Path to calibration file to decalibrate with. '
                        'You can use python string formatting, assuming '
                        '.format(mc)')
    parser.add_argument('--calibrate',
                        required=False,
                        help='Path to calibration file to calibrate with. '
                        'You can use python string formatting, assuming '
                        '.format(mc)')
    parser.add_argument('--madampar',
                        required=False,
                        default=None,
                        help='Madam parameter file')
    parser.add_argument('--nside',
                        required=False,
                        default=None,
                        type=np.int,
                        help='Madam resolution')
    parser.add_argument('--out',
                        required=False,
                        default='.',
                        help='Output directory')
    parser.add_argument('--madam_prefix', required=False, help='map prefix')
    parser.add_argument('--make_rings',
                        dest='make_rings',
                        default=False,
                        action='store_true',
                        help='Compile ringsets.')
    parser.add_argument('--nside_ring',
                        required=False,
                        default=128,
                        type=np.int,
                        help='Ringset resolution')
    parser.add_argument('--ring_root',
                        required=False,
                        default='ringset',
                        help='Root filename for ringsets (setting to empty '
                        'disables ringset output).')
    parser.add_argument('--MC_start',
                        required=False,
                        default=0,
                        type=np.int,
                        help='First Monte Carlo noise realization')
    parser.add_argument('--MC_count',
                        required=False,
                        default=1,
                        type=np.int,
                        help='Number of Monte Carlo noise realizations')
    # noise parameters
    parser.add_argument('--noisefile',
                        required=False,
                        default='RIMO',
                        help='Path to noise PSD files for noise filter. '
                        'Tag DETECTOR will be replaced with detector name.')
    parser.add_argument('--noisefile_simu',
                        required=False,
                        default='RIMO',
                        help='Path to noise PSD files for noise simulation. '
                        'Tag DETECTOR will be replaced with detector name.')
    # Dipole parameters
    dipogroup = parser.add_mutually_exclusive_group()
    dipogroup.add_argument('--dipole',
                           dest='dipole',
                           required=False,
                           default=False,
                           action='store_true',
                           help='Simulate dipole')
    dipogroup.add_argument('--solsys_dipole',
                           dest='solsys_dipole',
                           required=False,
                           default=False,
                           action='store_true',
                           help='Simulate solar system dipole')
    dipogroup.add_argument('--orbital_dipole',
                           dest='orbital_dipole',
                           required=False,
                           default=False,
                           action='store_true',
                           help='Simulate orbital dipole')
    dipo_parameters_group = parser.add_argument_group('dipole_parameters')
    dipo_parameters_group.add_argument(
        '--solsys_speed',
        required=False,
        type=np.float,
        default=DEFAULT_PARAMETERS["solsys_speed"],
        help='Solar system speed wrt. CMB rest frame in km/s. Default is '
        'Planck 2015 best fit value')
    dipo_parameters_group.add_argument(
        '--solsys_glon',
        required=False,
        type=np.float,
        default=DEFAULT_PARAMETERS["solsys_glon"],
        help='Solar system velocity direction longitude in degrees')
    dipo_parameters_group.add_argument(
        '--solsys_glat',
        required=False,
        type=np.float,
        default=DEFAULT_PARAMETERS["solsys_glat"],
        help='Solar system velocity direction latitude in degrees')

    try:
        args = parser.parse_args()
    except SystemExit:
        sys.exit(0)

    if comm.world_rank == 0:
        print('All parameters:')
        print(args, flush=True)

    if args.MC_count < 1:
        raise RuntimeError('MC_count = {} < 1. Nothing done.'
                           ''.format(args.MC_count))

    timer = Timer()
    timer.start()

    nrange = 1

    odranges = None
    if args.odfirst is not None and args.odlast is not None:
        odranges = []
        firsts = [int(i) for i in str(args.odfirst).split(',')]
        lasts = [int(i) for i in str(args.odlast).split(',')]
        for odfirst, odlast in zip(firsts, lasts):
            odranges.append((odfirst, odlast))
        nrange = len(odranges)

    ringranges = None
    if args.ringfirst is not None and args.ringlast is not None:
        ringranges = []
        firsts = [int(i) for i in str(args.ringfirst).split(',')]
        lasts = [int(i) for i in str(args.ringlast).split(',')]
        for ringfirst, ringlast in zip(firsts, lasts):
            ringranges.append((ringfirst, ringlast))
        nrange = len(ringranges)

    obtranges = None
    if args.obtfirst is not None and args.obtlast is not None:
        obtranges = []
        firsts = [float(i) for i in str(args.obtfirst).split(',')]
        lasts = [float(i) for i in str(args.obtlast).split(',')]
        for obtfirst, obtlast in zip(firsts, lasts):
            obtranges.append((obtfirst, obtlast))
        nrange = len(obtranges)

    if odranges is None:
        odranges = [None] * nrange

    if ringranges is None:
        ringranges = [None] * nrange

    if obtranges is None:
        obtranges = [None] * nrange

    detectors = None
    if args.dets is not None:
        detectors = re.split(',', args.dets)

    # create the TOD for this observation

    if args.noisefile != 'RIMO' or args.noisefile_simu != 'RIMO':
        do_eff_cache = True
    else:
        do_eff_cache = False

    tods = []

    for obtrange, ringrange, odrange in zip(obtranges, ringranges, odranges):
        # create the TOD for this observation
        tods.append(
            tp.Exchange(comm=comm.comm_group,
                        detectors=detectors,
                        ringdb=args.ringdb,
                        effdir_in=args.effdir,
                        extra_effdirs=[args.effdir2, args.effdir_fsl],
                        effdir_pntg=args.effdir_pntg,
                        obt_range=obtrange,
                        ring_range=ringrange,
                        od_range=odrange,
                        freq=args.freq,
                        RIMO=args.rimo,
                        obtmask=args.obtmask,
                        flagmask=args.flagmask,
                        pntflagmask=args.pntflagmask,
                        do_eff_cache=do_eff_cache))

    # Make output directory

    if not os.path.isdir(args.out) and comm.world_rank == 0:
        os.makedirs(args.out)

    # Read in madam parameter file
    # Allow more than one entry, gather into a list
    repeated_keys = ['detset', 'detset_nopol', 'survey']
    pars = {}

    if comm.world_rank == 0:
        pars['kfirst'] = False
        pars['temperature_only'] = True
        pars['base_first'] = 60.0
        pars['nside_submap'] = 16
        pars['write_map'] = False
        pars['write_binmap'] = True
        pars['write_matrix'] = False
        pars['write_wcov'] = False
        pars['write_hits'] = True
        pars['kfilter'] = False
        pars['info'] = 3
        if args.madampar:
            pat = re.compile(r'\s*(\S+)\s*=\s*(\S+(\s+\S+)*)\s*')
            comment = re.compile(r'^#.*')
            with open(args.madampar, 'r') as f:
                for line in f:
                    if not comment.match(line):
                        result = pat.match(line)
                        if result:
                            key, value = result.group(1), result.group(2)
                            if key in repeated_keys:
                                if key not in pars:
                                    pars[key] = []
                                pars[key].append(value)
                            else:
                                pars[key] = value
        # Command line parameters override the ones in the madam parameter file
        if 'file_root' not in pars:
            pars['file_root'] = 'madam'
        if args.madam_prefix is not None:
            pars['file_root'] = args.madam_prefix
        sfreq = '{:03}'.format(args.freq)
        if sfreq not in pars['file_root']:
            pars['file_root'] += '_' + sfreq
        try:
            fsample = {30: 32.51, 44: 46.55, 70: 78.77}[args.freq]
        except Exception:
            fsample = 180.3737
        pars['fsample'] = fsample
        pars['path_output'] = args.out

    pars = comm.comm_world.bcast(pars, root=0)

    madam_mcmode = True
    if 'nsubchunk' in pars and int(pars['nsubchunk']) > 1:
        madam_mcmode = False

    if args.noisefile != 'RIMO' or args.noisefile_simu != 'RIMO':
        # We split MPI_COMM_WORLD into single process groups, each of
        # which is assigned one or more observations (rings)
        comm = toast.Comm(groupsize=1)

    # This is the distributed data, consisting of one or
    # more observations, each distributed over a communicator.
    data = toast.Data(comm)

    for iobs, tod in enumerate(tods):
        if args.noisefile != 'RIMO' or args.noisefile_simu != 'RIMO':
            # Use a toast helper method to optimally distribute rings between
            # processes.
            dist = distribute_discrete(tod.ringsizes, comm.world_size)
            my_first_ring, my_n_ring = dist[comm.world_rank]

            for my_ring in range(my_first_ring, my_first_ring + my_n_ring):
                ringtod = tp.Exchange.from_tod(
                    tod,
                    my_ring,
                    comm.comm_group,
                    noisefile=args.noisefile,
                    noisefile_simu=args.noisefile_simu)
                ob = {}
                ob['name'] = 'ring{:05}'.format(ringtod.globalfirst_ring)
                ob['id'] = ringtod.globalfirst_ring
                ob['tod'] = ringtod
                ob['intervals'] = ringtod.valid_intervals
                ob['baselines'] = None
                ob['noise'] = ringtod.noise
                ob['noise_simu'] = ringtod.noise_simu
                data.obs.append(ob)
        else:
            ob = {}
            ob['name'] = 'observation{:04}'.format(iobs)
            ob['id'] = 0
            ob['tod'] = tod
            ob['intervals'] = tod.valid_intervals
            ob['baselines'] = None
            ob['noise'] = tod.noise
            ob['noise_simu'] = tod.noise

            data.obs.append(ob)

    rimo = tods[0].rimo

    if mpiworld is not None:
        mpiworld.barrier()
    if comm.world_rank == 0:
        timer.report_clear("Metadata queries")

    # Always read the signal and flags, even if the signal is later
    # overwritten.  There is no overhead for the signal because it is
    # interlaced with the flags.

    tod_name = 'signal'
    timestamps_name = 'timestamps'
    flags_name = 'flags'
    common_flags_name = 'common_flags'
    reader = tp.OpInputPlanck(signal_name=tod_name,
                              flags_name=flags_name,
                              timestamps_name=timestamps_name,
                              commonflags_name=common_flags_name)
    if comm.world_rank == 0:
        print('Reading input signal from {}'.format(args.effdir), flush=True)
    reader.exec(data)
    if mpiworld is not None:
        mpiworld.barrier()
    if comm.world_rank == 0:
        timer.report_clear("Read")

    # Clear the signal if we don't need it

    if not args.read_eff:
        eraser = tp.OpCacheMath(in1=tod_name,
                                in2=0,
                                multiply=True,
                                out=tod_name)
        if comm.world_rank == 0:
            print('Erasing TOD', flush=True)
        eraser.exec(data)
        if mpiworld is not None:
            mpiworld.barrier()
        if comm.world_rank == 0:
            timer.report_clear("Erase")

    # Optionally flag bad intervals

    if args.bad_intervals is not None:
        flagger = tp.OpBadIntervals(path=args.bad_intervals)
        flagger.exec(data)
        if mpiworld is not None:
            mpiworld.barrier()
        if comm.world_rank == 0:
            timer.report_clear("Apply {}".format(args.bad_intervals))

    # Now read an optional second TOD to add with the first

    if args.effdir2 is not None:
        # Read the extra TOD and add it to the first one
        reader = tp.OpInputPlanck(signal_name='tod2',
                                  flags_name=None,
                                  timestamps_name=None,
                                  commonflags_name=None,
                                  effdir=args.effdir2)
        if comm.world_rank == 0:
            print('Reading extra TOD from {}'.format(args.effdir2), flush=True)
        reader.exec(data)
        if mpiworld is not None:
            mpiworld.barrier()
        if comm.world_rank == 0:
            print("Reading took {:.3f} s".format(elapsed), flush=True)

        adder = tp.OpCacheMath(in1=tod_name,
                               in2='signal2',
                               add=True,
                               out=tod_name)
        if comm.world_rank == 0:
            print('Adding TODs', flush=True)
        adder.exec(data)

        # Erase the extra cache object
        for ob in data.obs:
            tod = ob['tod']
            tod.cache.clear('signal2_.*')

    if args.effdir_fsl is not None:
        # Read the straylight signal into the tod cache under
        # "fsl_<detector>"
        reader = tp.OpInputPlanck(signal_name='fsl',
                                  flags_name=None,
                                  timestamps_name=None,
                                  commonflags_name=None,
                                  effdir=args.effdir_fsl)
        if comm.world_rank == 0:
            print('Reading straylight signal from {}'.format(args.effdir_fsl),
                  flush=True)
        reader.exec(data)
        if mpiworld is not None:
            mpiworld.barrier()
        if comm.world_rank == 0:
            timer.report_clear("Read FSL")
        do_fsl = True
    else:
        do_fsl = False

    # make a planck Healpix pointing matrix
    mode = 'IQU'
    if pars['temperature_only'] == 'T':
        mode = 'I'

    if args.nside is None:
        if 'nside_map' in pars:
            nside = int(pars['nside_map'])
        else:
            raise RuntimeError(
                'Nside must be set either in the Madam parameter file or on '
                'the command line')
    else:
        nside = args.nside
        pars['nside_map'] = nside
    if 'nside_cross' not in pars or pars['nside_cross'] > pars['nside_map']:
        pars['nside_cross'] = pars['nside_map']

    do_dipole = args.dipole or args.solsys_dipole or args.orbital_dipole

    pointing = tp.OpPointingPlanck(nside=nside,
                                   mode=mode,
                                   RIMO=rimo,
                                   margin=0,
                                   apply_flags=True,
                                   keep_vel=do_dipole,
                                   keep_pos=False,
                                   keep_phase=False,
                                   keep_quats=do_dipole)
    pointing.exec(data)
    if mpiworld is not None:
        mpiworld.barrier()
    if comm.world_rank == 0:
        timer.report_clear("Pointing Matrix")

    flags_name = 'flags'
    common_flags_name = 'common_flags'

    # for now, we pass in the noise weights from the RIMO.
    detweights = {}
    for d in tod.detectors:
        net = tod.rimo[d].net
        fsample = tod.rimo[d].fsample
        detweights[d] = 1.0 / (fsample * net * net)

    if args.debug:
        with open("debug_planck_exchange_madam.txt", "w") as f:
            data.info(f)

    if do_dipole:
        # Simulate the dipole
        if args.dipole:
            dipomode = 'total'
        elif args.solsys_dipole:
            dipomode = 'solsys'
        else:
            dipomode = 'orbital'
        dipo = tp.OpDipolePlanck(args.freq,
                                 solsys_speed=args.solsys_speed,
                                 solsys_glon=args.solsys_glon,
                                 solsys_glat=args.solsys_glat,
                                 mode=dipomode,
                                 output='dipole',
                                 keep_quats=False)
        dipo.exec(data)
        if mpiworld is not None:
            mpiworld.barrier()
        if comm.world_rank == 0:
            timer.report_clear("Dipole")

    # Loop over Monte Carlos

    madam = None

    for mc in range(args.MC_start, args.MC_start + args.MC_count):

        out = "{}/{:05d}".format(args.out, mc)
        if comm.world_rank == 0:
            if not os.path.isdir(out):
                os.makedirs(out)

        # clear all noise data from the cache, so that we can generate
        # new noise timestreams.

        for ob in data.obs:
            ob['tod'].cache.clear("noise_.*")
        tod_name = 'signal'

        if do_dipole:
            adder = tp.OpCacheMath(in1=tod_name,
                                   in2='dipole',
                                   add=True,
                                   out='noise')
            adder.exec(data)
            if mpiworld is not None:
                mpiworld.barrier()
            if comm.world_rank == 0:
                timer.report_clear("MC {}:  Add dipole".format(mc))
            tod_name = 'noise'

        # Simulate noise

        if not args.skip_noise:
            tod_name = 'noise'
            nse = toast.tod.OpSimNoise(out=tod_name,
                                       realization=mc,
                                       component=0,
                                       noise='noise_simu',
                                       rate=fsample)
            if comm.world_rank == 0:
                print('Simulating noise from {}'.format(args.noisefile_simu),
                      flush=True)
            nse.exec(data)
            if mpiworld is not None:
                mpiworld.barrier()
            if comm.world_rank == 0:
                timer.report_clear("MC {}:  Noise simulation".format(mc))

            # If we didn't add the dipole, we need to add the input
            # signal with the noise we just simulated

            if args.read_eff and not do_dipole:
                adder = tp.OpCacheMath(in1=tod_name,
                                       in2='signal',
                                       add=True,
                                       out=tod_name)
                adder.exec(data)
                if mpiworld is not None:
                    mpiworld.barrier()
                if comm.world_rank == 0:
                    timer.report_clear("MC {}:  Add input signal".format(mc))

        # Make rings

        if args.make_rings:
            ringmaker = tp.OpRingMaker(args.nside_ring,
                                       nside,
                                       signal=tod_name,
                                       fileroot=args.ring_root,
                                       out=out,
                                       commonmask=args.obtmask,
                                       detmask=args.flagmask)
            ringmaker.exec(data)
            if mpiworld is not None:
                mpiworld.barrier()
            if comm.world_rank == 0:
                timer.report_clear("MC {}:  Ringmaking".format(mc))

        # Apply calibration errors

        if args.decalibrate is not None:
            fn = args.decalibrate
            try:
                fn = fn.format(mc)
            except Exception:
                pass
            if comm.world_rank == 0:
                print('Decalibrating with {}'.format(fn), flush=True)
            decalibrator = tp.OpCalibPlanck(signal_in=tod_name,
                                            signal_out='noise',
                                            file_gain=fn,
                                            decalibrate=True)
            decalibrator.exec(data)
            if mpiworld is not None:
                mpiworld.barrier()
            if comm.world_rank == 0:
                timer.report_clear("MC {}:  Decalibrate".format(mc))
            tod_name = 'noise'

        if args.calibrate is not None:
            fn = args.calibrate
            try:
                fn = fn.format(mc)
            except Exception:
                pass
            if comm.world_rank == 0:
                print('Calibrating with {}'.format(fn), flush=True)
            calibrator = tp.OpCalibPlanck(signal_in=tod_name,
                                          signal_out='noise',
                                          file_gain=fn)
            calibrator.exec(data)
            if mpiworld is not None:
                mpiworld.barrier()
            if comm.world_rank == 0:
                timer.report_clear("MC {}:  Calibrate".format(mc))
            tod_name = 'noise'

        # Subtract the dipole and straylight

        if do_dipole:
            subtractor = tp.OpCacheMath(in1=tod_name,
                                        in2='dipole',
                                        subtract=True,
                                        out='noise')
            subtractor.exec(data)
            if mpiworld is not None:
                mpiworld.barrier()
            if comm.world_rank == 0:
                timer.report_clear("MC {}:  Subtract dipole".format(mc))
            tod_name = 'noise'

        if do_fsl:
            subtractor = tp.OpCacheMath(in1=tod_name,
                                        in2='fsl',
                                        subtract=True,
                                        out='noise')
            subtractor.exec(data)
            if mpiworld is not None:
                mpiworld.barrier()
            if comm.world_rank == 0:
                timer.report_clear("MC {}:  Subtract straylight".format(mc))
            tod_name = 'noise'

        # Make the map

        if not args.skip_madam:
            # Make maps
            if madam is None:
                try:
                    madam = toast.todmap.OpMadam(params=pars,
                                                 detweights=detweights,
                                                 purge_tod=True,
                                                 name=tod_name,
                                                 apply_flags=False,
                                                 name_out=None,
                                                 noise='noise',
                                                 mcmode=madam_mcmode,
                                                 translate_timestamps=False)
                except Exception as e:
                    raise Exception(
                        '{:4} : ERROR: failed to initialize Madam: '
                        '{}'.format(comm.world_rank, e))
            madam.params['path_output'] = out
            madam.exec(data)
            if mpiworld is not None:
                mpiworld.barrier()
            if comm.world_rank == 0:
                timer.report_clear("MC {}:  Mapmaking".format(mc))

    gt.stop_all()
    if mpiworld is not None:
        mpiworld.barrier()
    timer = Timer()
    timer.start()
    alltimers = gather_timers(comm=mpiworld)
    if comm.world_rank == 0:
        out = os.path.join(args.out, "timing")
        dump_timing(alltimers, out)
        timer.stop()
        timer.report("Gather and dump timing info")
    return
    if mpiworld is not None:
        mpiworld.barrier()
    timer = Timer()
    timer.start()
    alltimers = gather_timers(comm=mpiworld)
    if comm.world_rank == 0:
        out = os.path.join(args.out, "timing")
        dump_timing(alltimers, out)
        timer.stop()
        timer.report("Gather and dump timing info")
    return


if __name__ == "__main__":
    try:
        mpiworld, procs, rank, comm = get_comm()
        main()
    except Exception as e:
        print('Exception occurred: "{}"'.format(e), flush=True)
        if MPI.COMM_WORLD.size == 1:
            raise
        exc_type, exc_value, exc_traceback = sys.exc_info()
        print("*** print_tb:")
        traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
        print("*** print_exception:")
        traceback.print_exception(
            exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout
        )
        print("*** print_exc:")
        traceback.print_exc()
        print("*** format_exc, first and last line:")
Esempio n. 3
0
def main():
    log = Logger.get()
    gt = GlobalTimers.get()
    gt.start("toast_so_sim (total)")
    timer0 = Timer()
    timer0.start()

    mpiworld, procs, rank, comm = toast_tools.get_comm()

    memreport("at the beginning of the pipeline", comm.comm_world)

    args, comm = parse_arguments(comm)

    if args.use_madam:
        # Initialize madam parameters
        madampars = toast_tools.setup_madam(args)
    else:
        madampars = None

    if args.import_dir is not None:
        schedules = None
        data, telescope_data, detweights = so_tools.load_observations(
            args, comm)
        memreport("after load", comm.comm_world)
        totalname = "signal"
    else:
        # Load and broadcast the schedule file

        schedules = toast_tools.load_schedule(args, comm)

        # Load the weather and append to schedules

        toast_tools.load_weather(args, comm, schedules)

        # load or simulate the focalplane

        detweights = so_tools.load_focalplanes(args, comm, schedules)

        # Create the TOAST data object to match the schedule.  This will
        # include simulating the boresight pointing.

        data, telescope_data = so_tools.create_observations(
            args, comm, schedules)

        memreport("after creating observations", comm.comm_world)

        # Optionally rewrite the noise PSD:s in each observation to include
        # elevation-dependence
        so_tools.get_elevation_noise(args, comm, data)

        totalname = "total"

    # Split the communicator for day and season mapmaking

    time_comms = toast_tools.get_time_communicators(args, comm, data)

    # Rotate the LAT focalplane around the boresight based on co-rotator position

    so_tools.rotate_focalplane(args, data, comm)

    # Expand boresight quaternions into detector pointing weights and
    # pixel numbers

    toast_tools.expand_pointing(args, comm, data)

    # Flag Solar system objects

    so_tools.apply_flag_sso(args, comm, data)

    # Optionally, output h_n maps

    so_tools.compute_h_n(args, comm, data)

    # Optionally, output crosslinking map

    so_tools.compute_crosslinking(args, comm, data, detweights)

    # Optionally, output cadence map

    so_tools.compute_cadence_map(args, comm, data)

    # Only purge the pointing if we are NOT going to export the
    # data to a TIDAS volume
    if not (args.tidas is None) and (args.export is None):
        for ob in data.obs:
            tod = ob["tod"]
            try:
                tod.free_radec_quats()
            except AttributeError:
                # These TOD objects do not have RA/Dec quaternions
                pass

    memreport("after pointing", comm.comm_world)

    # Set up objects to take copies of the TOD at appropriate times

    if args.pysm_model:
        if schedules is not None:
            focalplanes = [
                s.telescope.focalplane.detector_data for s in schedules
            ]
        else:
            focalplanes = [telescope.focalplane.detector_data]
        signalname = so_tools.simulate_sky_signal(args, comm, data,
                                                  focalplanes)
    else:
        signalname = toast_tools.scan_sky_signal(args, comm, data)

    memreport("after PySM", comm.comm_world)

    # Loop over Monte Carlos

    firstmc = int(args.MC_start)
    nmc = int(args.MC_count)

    for mc in range(firstmc, firstmc + nmc):

        if comm.world_rank == 0:
            log.info("Processing MC = {}".format(mc))

        toast_tools.draw_weather(args, comm, data, mc)

        toast_tools.simulate_atmosphere(args, comm, data, mc, totalname)

        #so_tools.scale_atmosphere_by_bandpass(args, comm, data, totalname, mc)
        toast_tools.scale_atmosphere_by_frequency(
            args,
            comm,
            data,
            cache_name=totalname,
            mc=mc,
        )

        memreport("after atmosphere", comm.comm_world)

        so_tools.simulate_hwpss(args, comm, data, mc, totalname)

        # update_atmospheric_noise_weights(args, comm, data, freq, mc)

        toast_tools.add_signal(args,
                               comm,
                               data,
                               totalname,
                               signalname,
                               purge=(mc == firstmc + nmc - 1))

        memreport("after adding sky", comm.comm_world)

        toast_tools.simulate_sss(args, comm, data, mc, totalname)

        memreport("after simulating SSS", comm.comm_world)

        toast_tools.simulate_noise(args, comm, data, mc, totalname)

        memreport("after simulating noise", comm.comm_world)

        so_tools.apply_sim_sso(args, comm, data, mc, totalname)

        memreport("after simulating SSO", comm.comm_world)

        so_tools.convolve_time_constant(args, comm, data, totalname)

        memreport("after convolving with time constant", comm.comm_world)

        # DEBUG begin
        """
        import matplotlib.pyplot as plt
        tod = data.obs[0]['tod']
        times = tod.local_times()
        for det in tod.local_dets:
            sig = tod.local_signal(det, totalname)
            plt.plot(times, sig, label=det)
        plt.legend(loc='best')
        fnplot = 'debug_{}.png'.format(args.madam_prefix)
        plt.savefig(fnplot)
        plt.close()
        print('DEBUG plot saved in', fnplot)
        return
        """
        # DEBUG end

        toast_tools.scramble_gains(args, comm, data, mc, totalname)

        so_tools.deconvolve_time_constant(args,
                                          comm,
                                          data,
                                          totalname,
                                          realization=mc)

        memreport("after deconvolving time constant", comm.comm_world)

        if mc == firstmc:
            # For the first realization and frequency, optionally
            # export the timestream data.
            toast_tools.output_tidas(args, comm, data, totalname)
            so_tools.export_TOD(args, comm, data, totalname, schedules)

            memreport("after export", comm.comm_world)

        if args.no_maps:
            continue

        outpath = setup_output(args, comm, mc)

        # Optionally demodulate signal

        so_tools.demodulate(args, comm, data, totalname, detweights, madampars)

        # Bin and destripe maps

        if args.use_madam:
            toast_tools.apply_madam(
                args,
                comm,
                data,
                madampars,
                outpath,
                detweights,
                totalname,
                time_comms=time_comms,
                telescope_data=telescope_data,
                first_call=(mc == firstmc),
            )
        else:
            toast_tools.apply_mapmaker(
                args,
                comm,
                data,
                outpath,
                totalname,
                time_comms=time_comms,
                telescope_data=telescope_data,
                first_call=(mc == firstmc),
            )

        memreport("after destriper", comm.comm_world)

        if (args.filterbin_ground_order is not None
                or args.filterbin_poly_order is not None):
            toast_tools.apply_filterbin(
                args,
                comm,
                data,
                outpath,
                totalname,
                time_comms=time_comms,
                telescope_data=telescope_data,
                first_call=(mc == firstmc),
            )

        if args.apply_polyfilter or args.apply_groundfilter:

            # Filter signal

            toast_tools.apply_polyfilter(args, comm, data, totalname)

            memreport("after polyfilter", comm.comm_world)

            # Ground filter

            memreport("after demodulation", comm.comm_world)

            toast_tools.apply_groundfilter(args, comm, data, totalname)

            memreport("after groundfilter", comm.comm_world)

            # Bin maps

            if args.use_madam:
                toast_tools.apply_madam(
                    args,
                    comm,
                    data,
                    madampars,
                    outpath,
                    detweights,
                    totalname,
                    time_comms=time_comms,
                    telescope_data=telescope_data,
                    first_call=args.demodulate,
                    extra_prefix="filtered",
                    bin_only=True,
                )
            else:
                toast_tools.apply_mapmaker(
                    args,
                    comm,
                    data,
                    outpath,
                    totalname,
                    time_comms=time_comms,
                    telescope_data=telescope_data,
                    first_call=False,
                    extra_prefix="filtered",
                    bin_only=True,
                )

            memreport("after filter & bin", comm.comm_world)

            if args.demodulate and args.MC_count > 1:
                if comm.world_rank == 0:
                    log.info("WARNING: demodulation and MC iterations are "
                             "incompatible.  Terminating after first MC.")
                break

    if comm.comm_world is not None:
        comm.comm_world.barrier()

    memreport("at the end of the pipeline", comm.comm_world)

    gt.stop_all()
    if mpiworld is not None:
        mpiworld.barrier()
    timer = Timer()
    timer.start()
    alltimers = gather_timers(comm=mpiworld)
    if rank == 0:
        out = os.path.join(args.outdir, "timing")
        dump_timing(alltimers, out)
        timer.stop()
        timer.report("Gather and dump timing info")
    timer0.stop()
    if comm.world_rank == 0:
        timer0.report("toast_so_sim.py pipeline")
    return
Esempio n. 4
0
def main():
    log = Logger.get()
    gt = GlobalTimers.get()
    gt.start("toast_ground_sim (total)")

    mpiworld, procs, rank, comm = get_comm()

    args, comm = parse_arguments(comm)

    # Initialize madam parameters

    madampars = setup_madam(args)

    # Load and broadcast the schedule file

    schedule = load_schedule(args, comm)[0]

    # load or simulate the focalplane

    detweights = load_focalplane(args, comm, schedule)

    # Create the TOAST data object to match the schedule.  This will
    # include simulating the boresight pointing.

    data = create_observations(args, comm, schedule)

    # Expand boresight quaternions into detector pointing weights and
    # pixel numbers

    expand_pointing(args, comm, data)

    # Scan input map

    signalname = scan_sky_signal(args, comm, data, "signal")

    # Simulate noise

    if signalname is None:
        signalname = "signal"
        mc = 0
        simulate_noise(args, comm, data, mc, signalname)

    # Set up objects to take copies of the TOD at appropriate times

    signalname_madam, sigcopy_madam, sigclear = setup_sigcopy(
        args, comm, signalname)

    npp, zmap = init_binner(args, comm, data, detweights)

    output_tidas(args, comm, data, signalname)

    outpath = setup_output(args, comm)

    # Make a copy of the signal for Madam

    copy_signal_madam(args, comm, data, sigcopy_madam)

    # Bin unprocessed signal for reference

    apply_binner(args, comm, data, npp, zmap, detweights, outpath, signalname)

    if args.apply_polyfilter or args.apply_groundfilter:

        # Filter signal

        apply_polyfilter(args, comm, data, signalname)

        apply_groundfilter(args, comm, data, signalname)

        # Bin the filtered signal

        apply_binner(
            args,
            comm,
            data,
            npp,
            zmap,
            detweights,
            outpath,
            signalname,
            prefix="filtered",
        )

    data.obs[0]["tod"].cache.report()

    clear_signal(args, comm, data, sigclear)

    data.obs[0]["tod"].cache.report()

    # Now run Madam on the unprocessed copy of the signal

    if args.use_madam:
        apply_madam(args, comm, data, madampars, outpath, detweights,
                    signalname_madam)

    gt.stop_all()
    if mpiworld is not None:
        mpiworld.barrier()
    timer = Timer()
    timer.start()
    alltimers = gather_timers(comm=mpiworld)
    if comm.world_rank == 0:
        out = os.path.join(args.outdir, "timing")
        dump_timing(alltimers, out)
        timer.report_clear("Gather and dump timing info")
    return
Esempio n. 5
0
def main():
    log = Logger.get()
    gt = GlobalTimers.get()
    gt.start("toast_ground_sim (total)")
    timer0 = Timer()
    timer0.start()

    mpiworld, procs, rank, comm = get_comm()

    args, comm = parse_arguments(comm)

    # Initialize madam parameters

    madampars = setup_madam(args)

    # Load and broadcast the schedule file

    schedules = load_schedule(args, comm)

    # Load the weather and append to schedules

    load_weather(args, comm, schedules)

    # load or simulate the focalplane

    detweights = load_focalplanes(args, comm, schedules)

    # Create the TOAST data object to match the schedule.  This will
    # include simulating the boresight pointing.

    data, telescope_data = create_observations(args, comm, schedules)

    # Split the communicator for day and season mapmaking

    time_comms = get_time_communicators(args, comm, data)

    # Expand boresight quaternions into detector pointing weights and
    # pixel numbers

    expand_pointing(args, comm, data)

    # Purge the pointing if we are NOT going to export the
    # data to a TIDAS volume
    if (args.tidas is None) and (args.spt3g is None):
        for ob in data.obs:
            tod = ob["tod"]
            tod.free_radec_quats()

    # Prepare auxiliary information for distributed map objects

    _, localsm, subnpix = get_submaps(args, comm, data)

    if args.pysm_model:
        focalplanes = [s.telescope.focalplane.detector_data for s in schedules]
        signalname = simulate_sky_signal(args, comm, data, focalplanes,
                                         subnpix, localsm, "signal")
    else:
        signalname = scan_sky_signal(args, comm, data, localsm, subnpix,
                                     "signal")

    # Set up objects to take copies of the TOD at appropriate times

    totalname, totalname_freq = setup_sigcopy(args)

    # Loop over Monte Carlos

    firstmc = args.MC_start
    nsimu = args.MC_count

    freqs = [float(freq) for freq in args.freq.split(",")]
    nfreq = len(freqs)

    for mc in range(firstmc, firstmc + nsimu):

        simulate_atmosphere(args, comm, data, mc, totalname)

        # Loop over frequencies with identical focal planes and identical
        # atmospheric noise.

        for ifreq, freq in enumerate(freqs):

            if comm.world_rank == 0:
                log.info("Processing frequency {}GHz {} / {}, MC = {}".format(
                    freq, ifreq + 1, nfreq, mc))

            # Make a copy of the atmosphere so we can scramble the gains and apply
            # frequency-dependent scaling.
            copy_signal(args, comm, data, totalname, totalname_freq)

            scale_atmosphere_by_frequency(args,
                                          comm,
                                          data,
                                          freq=freq,
                                          mc=mc,
                                          cache_name=totalname_freq)

            update_atmospheric_noise_weights(args, comm, data, freq, mc)

            # Add previously simulated sky signal to the atmospheric noise.

            add_signal(args,
                       comm,
                       data,
                       totalname_freq,
                       signalname,
                       purge=(nsimu == 1))

            mcoffset = ifreq * 1000000

            simulate_noise(args, comm, data, mc + mcoffset, totalname_freq)

            simulate_sss(args, comm, data, mc + mcoffset, totalname_freq)

            scramble_gains(args, comm, data, mc + mcoffset, totalname_freq)

            if (mc == firstmc) and (ifreq == 0):
                # For the first realization and frequency, optionally
                # export the timestream data.
                output_tidas(args, comm, data, totalname)
                output_spt3g(args, comm, data, totalname)

            outpath = setup_output(args, comm, mc + mcoffset, freq)

            # Bin and destripe maps

            apply_madam(
                args,
                comm,
                data,
                madampars,
                outpath,
                detweights,
                totalname_freq,
                freq=freq,
                time_comms=time_comms,
                telescope_data=telescope_data,
                first_call=(mc == firstmc),
            )

            if args.apply_polyfilter or args.apply_groundfilter:

                # Filter signal

                apply_polyfilter(args, comm, data, totalname_freq)

                apply_groundfilter(args, comm, data, totalname_freq)

                # Bin filtered maps

                apply_madam(
                    args,
                    comm,
                    data,
                    madampars,
                    outpath,
                    detweights,
                    totalname_freq,
                    freq=freq,
                    time_comms=time_comms,
                    telescope_data=telescope_data,
                    first_call=False,
                    extra_prefix="filtered",
                    bin_only=True,
                )

    gt.stop_all()
    if mpiworld is not None:
        mpiworld.barrier()
    timer = Timer()
    timer.start()
    alltimers = gather_timers(comm=mpiworld)
    if comm.world_rank == 0:
        out = os.path.join(args.outdir, "timing")
        dump_timing(alltimers, out)
        timer.stop()
        timer.report("Gather and dump timing info")
        timer0.report_clear("toast_ground_sim.py")
    return
Esempio n. 6
0
def main():
    log = Logger.get()
    gt = GlobalTimers.get()
    gt.start("toast_planck_reduce (total)")

    mpiworld, procs, rank, comm = get_comm()

    # This is the 2-level toast communicator.  By default,
    # there is just one group which spans MPI_COMM_WORLD.
    comm = toast.Comm()

    if comm.comm_world.rank == 0:
        print('Running with {} processes at {}'
              ''.format(procs, str(datetime.datetime.now())))

    parser = argparse.ArgumentParser(description='Planck Ringset making',
                                     fromfile_prefix_chars='@')
    parser.add_argument('--rimo', required=True, help='RIMO file')
    parser.add_argument('--freq', required=True, type=np.int, help='Frequency')
    parser.add_argument('--dets',
                        required=False,
                        default=None,
                        help='Detector list (comma separated)')
    parser.add_argument('--nosingle',
                        dest='nosingle',
                        required=False,
                        default=False,
                        action='store_true',
                        help='Do not compute single detector PSDs')
    parser.add_argument('--effdir',
                        required=True,
                        help='Input Exchange Format File directory')
    parser.add_argument('--effdir_pntg',
                        required=False,
                        help='Input Exchange Format File directory '
                        'for pointing')
    parser.add_argument('--obtmask',
                        required=False,
                        default=1,
                        type=np.int,
                        help='OBT flag mask')
    parser.add_argument('--flagmask',
                        required=False,
                        default=1,
                        type=np.int,
                        help='Quality flag mask')
    parser.add_argument('--skymask', required=False, help='Pixel mask file')
    parser.add_argument('--skymap', required=False, help='Sky estimate file')
    parser.add_argument('--skypol',
                        dest='skypol',
                        required=False,
                        default=False,
                        action='store_true',
                        help='Sky estimate is polarized')
    parser.add_argument('--no_spin_harmonics',
                        dest='no_spin_harmonics',
                        required=False,
                        default=False,
                        action='store_true',
                        help='Do not include PSD bins with spin harmonics')
    parser.add_argument('--calibrate',
                        required=False,
                        help='Path to calibration file to calibrate with.')
    parser.add_argument('--calibrate_signal_estimate',
                        dest='calibrate_signal_estimate',
                        required=False,
                        default=False,
                        action='store_true',
                        help='Calibrate '
                        'the signal estimate using linear regression.')
    parser.add_argument('--ringdb', required=True, help='Ring DB file')
    parser.add_argument('--odfirst',
                        required=False,
                        default=None,
                        type=np.int,
                        help='First OD to use')
    parser.add_argument('--odlast',
                        required=False,
                        default=None,
                        type=np.int,
                        help='Last OD to use')
    parser.add_argument('--ringfirst',
                        required=False,
                        default=None,
                        type=np.int,
                        help='First ring to use')
    parser.add_argument('--ringlast',
                        required=False,
                        default=None,
                        type=np.int,
                        help='Last ring to use')
    parser.add_argument('--obtfirst',
                        required=False,
                        default=None,
                        type=np.float,
                        help='First OBT to use')
    parser.add_argument('--obtlast',
                        required=False,
                        default=None,
                        type=np.float,
                        help='Last OBT to use')
    parser.add_argument('--out',
                        required=False,
                        default='.',
                        help='Output directory')
    parser.add_argument('--nbin_psd',
                        required=False,
                        default=1000,
                        type=np.int,
                        help='Number of logarithmically '
                        'distributed spectral bins to write.')
    parser.add_argument('--lagmax',
                        required=False,
                        default=100000,
                        type=np.int,
                        help='Maximum lag to evaluate for the '
                        'autocovariance function [samples].')
    parser.add_argument('--stationary_period',
                        required=False,
                        default=86400.,
                        type=np.float,
                        help='Length of a stationary interval [seconds].')
    # Dipole parameters
    dipogroup = parser.add_mutually_exclusive_group()
    dipogroup.add_argument('--dipole',
                           dest='dipole',
                           required=False,
                           default=False,
                           action='store_true',
                           help='Simulate dipole')
    dipogroup.add_argument('--solsys_dipole',
                           dest='solsys_dipole',
                           required=False,
                           default=False,
                           action='store_true',
                           help='Simulate solar system dipole')
    dipogroup.add_argument('--orbital_dipole',
                           dest='orbital_dipole',
                           required=False,
                           default=False,
                           action='store_true',
                           help='Simulate orbital dipole')
    # Extra filter
    parser.add_argument('--filterfile',
                        required=False,
                        help='Extra filter file.')

    try:
        args = parser.parse_args()
    except SystemExit:
        sys.exit(0)

    if comm.comm_world.rank == 0:
        print('All parameters:')
        print(args, flush=True)

    timer = Timer()
    timer.start()

    odrange = None
    if args.odfirst is not None and args.odlast is not None:
        odrange = (args.odfirst, args.odlast)

    ringrange = None
    if args.ringfirst is not None and args.ringlast is not None:
        ringrange = (args.ringfirst, args.ringlast)

    obtrange = None
    if args.obtfirst is not None and args.obtlast is not None:
        obtrange = (args.obtfirst, args.obtlast)

    detectors = None
    if args.dets is not None:
        detectors = re.split(',', args.dets)

    if args.nosingle and len(detectors) != 2:
        raise RuntimeError('You cannot skip the single detectors PSDs '
                           'without multiple detectors.')

    # This is the distributed data, consisting of one or
    # more observations, each distributed over a communicator.
    data = toast.Data(comm)

    # Make output directory

    if not os.path.isdir(args.out) and comm.comm_world.rank == 0:
        os.mkdir(args.out)

    # create the TOD for this observation

    tod = tp.Exchange(
        comm=comm.comm_group,
        detectors=detectors,
        ringdb=args.ringdb,
        effdir_in=args.effdir,
        effdir_pntg=args.effdir_pntg,
        obt_range=obtrange,
        ring_range=ringrange,
        od_range=odrange,
        freq=args.freq,
        RIMO=args.rimo,
        obtmask=args.obtmask,
        flagmask=args.flagmask,
        do_eff_cache=False,
    )

    rimo = tod.rimo

    ob = {}
    ob['name'] = 'mission'
    ob['id'] = 0
    ob['tod'] = tod
    ob['intervals'] = tod.valid_intervals
    ob['baselines'] = None
    ob['noise'] = tod.noise

    data.obs.append(ob)

    comm.comm_world.barrier()
    if comm.comm_world.rank == 0:
        timer.report_clear("Metadata queries")

    # Read the signal

    tod_name = 'signal'
    flags_name = 'flags'

    reader = tp.OpInputPlanck(signal_name=tod_name, flags_name=flags_name)
    if comm.comm_world.rank == 0:
        print('Reading input signal from {}'.format(args.effdir), flush=True)
    reader.exec(data)
    comm.comm_world.barrier()
    if comm.comm_world.rank == 0:
        timer.report_clear("Reading")

    if args.calibrate is not None:
        fn = args.calibrate
        if comm.comm_world.rank == 0:
            print('Calibrating with {}'.format(fn), flush=True)
        calibrator = tp.OpCalibPlanck(signal_in=tod_name,
                                      signal_out=tod_name,
                                      file_gain=fn)
        calibrator.exec(data)
        comm.comm_world.barrier()
        if comm.comm_world.rank == 0:
            timer.report_clear("Calibrate")

    # Optionally subtract the dipole

    do_dipole = (args.dipole or args.solsys_dipole or args.orbital_dipole)

    if do_dipole:
        if args.dipole:
            dipomode = 'total'
        elif args.solsys_dipole:
            dipomode = 'solsys'
        else:
            dipomode = 'orbital'

        dipo = tp.OpDipolePlanck(args.freq,
                                 mode=dipomode,
                                 output='dipole',
                                 keep_quats=True)
        dipo.exec(data)

        comm.comm_world.barrier()
        if comm.comm_world.rank == 0:
            timer.report_clear("Dipole")

        subtractor = tp.OpCacheMath(in1=tod_name,
                                    in2='dipole',
                                    subtract=True,
                                    out=tod_name)
        if comm.comm_world.rank == 0:
            print('Subtracting dipole', flush=True)
        subtractor.exec(data)

        comm.comm_world.barrier()
        if comm.comm_world.rank == 0:
            timer.report_clear("Dipole subtraction")

    # Optionally filter the signal

    apply_filter(args, data)
    timer.clear()

    # Estimate noise

    noise_estimator = tp.OpNoiseEstim(
        signal=tod_name,
        flags=flags_name,
        detmask=args.flagmask,
        commonmask=args.obtmask,
        maskfile=args.skymask,
        mapfile=args.skymap,
        out=args.out,
        rimo=rimo,
        pol=args.skypol,
        nbin_psd=args.nbin_psd,
        lagmax=args.lagmax,
        stationary_period=args.stationary_period,
        nosingle=args.nosingle,
        no_spin_harmonics=args.no_spin_harmonics,
        calibrate_signal_estimate=args.calibrate_signal_estimate)

    noise_estimator.exec(data)

    comm.comm_world.barrier()
    if comm.comm_world.rank == 0:
        timer.report_clear("Noise estimation")

    gt.stop_all()
    if mpiworld is not None:
        mpiworld.barrier()
    timer = Timer()
    timer.start()
    alltimers = gather_timers(comm=mpiworld)
    if comm.world_rank == 0:
        out = os.path.join(args.out, "timing")
        dump_timing(alltimers, out)
        timer.stop()
        timer.report("Gather and dump timing info")
    return
Esempio n. 7
0
def main():
    env = Environment.get()
    log = Logger.get()
    gt = GlobalTimers.get()
    gt.start("toast_satellite_sim (total)")
    timer0 = Timer()
    timer0.start()

    mpiworld, procs, rank, comm = pipeline_tools.get_comm()
    args, comm, groupsize = parse_arguments(comm, procs)

    # Parse options

    tmr = Timer()
    tmr.start()

    if comm.world_rank == 0:
        os.makedirs(args.outdir, exist_ok=True)

    focalplane, gain, detweights = load_focalplane(args, comm)
    if comm.world_rank == 0:
        tmr.report_clear("Load focalplane")

    data = create_observations(args, comm, focalplane, groupsize)
    if comm.world_rank == 0:
        tmr.report_clear("Create observations")

    pipeline_tools.expand_pointing(args, comm, data)
    if comm.world_rank == 0:
        tmr.report_clear("Expand pointing")

    signalname = None
    if args.pysm_model:
        skyname = pipeline_tools.simulate_sky_signal(args, comm, data,
                                                     [focalplane], "signal")
    else:
        skyname = pipeline_tools.scan_sky_signal(args, comm, data, "signal")
    if skyname is not None:
        signalname = skyname
    if comm.world_rank == 0:
        tmr.report_clear("Simulate sky signal")

    # NOTE: Conviqt could use different input file names for different
    # Monte Carlo indices, but the operator would need to be invoked within
    # the Monte Carlo loop.
    skyname = pipeline_tools.apply_conviqt(
        args,
        comm,
        data,
        "signal",
        mc=args.MC_start,
    )
    if skyname is not None:
        signalname = skyname
    if comm.world_rank == 0:
        tmr.report_clear("Apply beam convolution")

    diponame = pipeline_tools.simulate_dipole(args, comm, data, "signal")
    if diponame is not None:
        signalname = diponame
    if comm.world_rank == 0:
        tmr.report_clear("Simulate dipole")

    # in debug mode, print out data distribution information
    if args.debug:
        handle = None
        if comm.world_rank == 0:
            handle = open(os.path.join(args.outdir, "distdata.txt"), "w")
        data.info(handle)
        if comm.world_rank == 0:
            handle.close()
        if comm.comm_world is not None:
            comm.comm_world.barrier()
        if comm.world_rank == 0:
            tmr.report_clear("Dumping data distribution")

    # in debug mode, print out data distribution information
    if args.debug:
        handle = None
        if comm.world_rank == 0:
            handle = open(os.path.join(args.outdir, "distdata.txt"), "w")
        data.info(handle)
        if comm.world_rank == 0:
            handle.close()
        if comm.comm_world is not None:
            comm.comm_world.barrier()
        if comm.world_rank == 0:
            tmr.report_clear("Dumping data distribution")

    # Mapmaking.

    if args.use_madam:
        # Initialize madam parameters
        madampars = pipeline_tools.setup_madam(args)
        if comm.comm_world is not None:
            comm.comm_world.barrier()
        if comm.world_rank == 0:
            tmr.report_clear("Initialize madam map-making")

    # Loop over Monte Carlos

    firstmc = args.MC_start
    nmc = args.MC_count

    for mc in range(firstmc, firstmc + nmc):
        mctmr = Timer()
        mctmr.start()

        # create output directory for this realization
        outpath = os.path.join(args.outdir, "mc_{:03d}".format(mc))

        pipeline_tools.simulate_noise(args,
                                      comm,
                                      data,
                                      mc,
                                      "tot_signal",
                                      overwrite=True)
        if comm.comm_world is not None:
            comm.comm_world.barrier()
        if comm.world_rank == 0:
            tmr.report_clear("    Simulate noise {:04d}".format(mc))

        # add sky signal
        pipeline_tools.add_signal(args, comm, data, "tot_signal", signalname)
        if comm.comm_world is not None:
            comm.comm_world.barrier()
        if comm.world_rank == 0:
            tmr.report_clear("    Add sky signal {:04d}".format(mc))

        if gain is not None:
            op_apply_gain = OpApplyGain(gain, name="tot_signal")
            op_apply_gain.exec(data)
            if comm.comm_world is not None:
                comm.comm_world.barrier()
            if comm.world_rank == 0:
                tmr.report_clear("    Apply gains {:04d}".format(mc))

        if mc == firstmc:
            # For the first realization, optionally export the
            # timestream data.  If we had observation intervals defined,
            # we could pass "use_interval=True" to the export operators,
            # which would ensure breaks in the exported data at
            # acceptable places.
            pipeline_tools.output_tidas(args, comm, data, "tot_signal")
            pipeline_tools.output_spt3g(args, comm, data, "tot_signal")
            if comm.comm_world is not None:
                comm.comm_world.barrier()
            if comm.world_rank == 0:
                tmr.report_clear("    Write TOD snapshot {:04d}".format(mc))

        if args.use_madam:
            pipeline_tools.apply_madam(args, comm, data, madampars, outpath,
                                       detweights, "tot_signal")
        else:
            pipeline_tools.apply_mapmaker(args, comm, data, outpath,
                                          "tot_signal")

        if comm.comm_world is not None:
            comm.comm_world.barrier()
        if comm.world_rank == 0:
            tmr.report_clear("  Map-making {:04d}".format(mc))

        if comm.comm_world is not None:
            comm.comm_world.barrier()
        if comm.world_rank == 0:
            mctmr.report_clear("  Monte Carlo loop {:04d}".format(mc))

    gt.stop_all()
    if comm.comm_world is not None:
        comm.comm_world.barrier()
    tmr.stop()
    tmr.clear()
    tmr.start()
    alltimers = gather_timers(comm=comm.comm_world)
    if comm.world_rank == 0:
        out = os.path.join(args.outdir, "timing")
        dump_timing(alltimers, out)
        tmr.stop()
        tmr.report("Gather and dump timing info")
        timer0.report_clear("toast_satellite_sim.py")
    return
Esempio n. 8
0
def main():
    # We are going to group our processes in a single group.  This is fine
    # if we have fewer processes than detectors.  Otherwise we should group
    # them in a reasonable size that is smaller than the number of detectors
    # and which divides evenly into the total number of processes.

    mpiworld, procs, rank, comm = get_comm()

    # Make a fake focalplane.  Plot it just for fun (don't waste time on this
    # for very large runs though).
    fp = fake_focalplane()
    if comm.comm_world.rank == 0:
        outfile = "custom_example_focalplane.png"
        qdets = {x: y["quat"] for x, y in fp.items()}
        beams = {x: (60.0 * y["fwhm_deg"]) for x, y in fp.items()}
        fov = 6.0
        tt.plot_focalplane(qdets, fov, fov, outfile, fwhm=beams)

    # Read in 2 boresight files
    borefiles = [
        "../data/custom_example_boresight_1.txt",
        "../data/custom_example_boresight_2.txt"
    ]

    # Set up the distributed data
    rate = 100.0
    data = create_observations(comm, rate, fp, borefiles)

    # Configure the healpix pixelization we will use for map-making and
    # also the "submap" resolution, which sets granularity of the locally
    # stored pieces of the sky.
    map_nside = 512
    map_npix = 12 * map_nside**2
    sub_nside = 4
    sub_npix = 12 * sub_nside**2

    # Compute a pointing matrix with healpix pixels and weights.
    pointing = tt.OpPointingHpix(nside=map_nside,
                                 nest=True,
                                 mode="IQU",
                                 pixels="pixels",
                                 weights="weights")
    pointing.exec(data)

    # Compute the locally hit submaps
    local_submaps = pixel_dist(data, sub_npix)

    # Sources of simulated data:  scan from a symmetric beam convolved sky
    # and then add some simulated noise.

    signalmap = tm.DistPixels(comm=comm.comm_world,
                              size=map_npix,
                              nnz=3,
                              dtype=np.float64,
                              submap=sub_npix,
                              local=local_submaps)
    signalmap.read_healpix_fits("../data/custom_example_sky.fits")

    scanmap = tt.OpSimScan(distmap=signalmap,
                           pixels='pixels',
                           weights='weights',
                           out="sim")
    scanmap.exec(data)

    nse = tt.OpSimNoise(out="sim", realization=0)
    nse.exec(data)

    # Accumulate the hits and inverse diagonal pixel covariance, as well as the
    # noise weighted map.  Here we simply use inverse noise weighting.

    detweights = {}
    for d in fp.keys():
        net = fp[d]["NET"]
        detweights[d] = 1.0 / (rate * net * net)

    invnpp = tm.DistPixels(comm=comm.comm_world,
                           size=map_npix,
                           nnz=6,
                           dtype=np.float64,
                           submap=sub_npix,
                           local=local_submaps)

    hits = tm.DistPixels(comm=comm.comm_world,
                         size=map_npix,
                         nnz=1,
                         dtype=np.int64,
                         submap=sub_npix,
                         local=local_submaps)

    zmap = tm.DistPixels(comm=comm.comm_world,
                         size=map_npix,
                         nnz=3,
                         dtype=np.float64,
                         submap=sub_npix,
                         local=local_submaps)

    invnpp.data.fill(0.0)
    hits.data.fill(0)
    zmap.data.fill(0.0)

    build_invnpp = tm.OpAccumDiag(detweights=detweights,
                                  invnpp=invnpp,
                                  hits=hits,
                                  zmap=zmap,
                                  name="sim")
    build_invnpp.exec(data)

    invnpp.allreduce()
    hits.allreduce()
    zmap.allreduce()

    # Write these products out

    hits.write_healpix_fits("custom_example_hits.fits")
    invnpp.write_healpix_fits("custom_example_invnpp.fits")
    zmap.write_healpix_fits("custom_example_zmap.fits")

    # Invert the covariance and write

    tm.covariance_invert(invnpp, 1.0e-3)
    invnpp.write_healpix_fits("custom_example_npp.fits")

    # Apply covariance to make the binned map

    tm.covariance_apply(invnpp, zmap)
    zmap.write_healpix_fits("custom_example_binned.fits")

    return
def main():
    log = Logger.get()
    gt = GlobalTimers.get()
    gt.start("toast_planck_reduce (total)")

    mpiworld, procs, rank, comm = get_comm()

    memreport("at beginning of main", mpiworld)

    # This is the 2-level toast communicator.  By default,
    # there is just one group which spans MPI_COMM_WORLD.
    comm = toast.Comm()

    if comm.world_rank == 0:
        print("Running with {} processes at {}".format(
            procs, str(datetime.datetime.now())))

    parser = argparse.ArgumentParser(description='Simple MADAM Mapmaking',
                                     fromfile_prefix_chars='@')
    parser.add_argument('--rimo', required=True, help='RIMO file')
    parser.add_argument('--freq', required=True, type=np.int, help='Frequency')
    parser.add_argument('--nside',
                        required=False,
                        type=np.int,
                        default=512,
                        help='Map resolution')
    parser.add_argument('--nside_cross',
                        required=False,
                        type=np.int,
                        default=512,
                        help='Destriping resolution')
    parser.add_argument('--debug',
                        dest='debug',
                        default=False,
                        action='store_true',
                        help='Write data distribution info to file')
    parser.add_argument('--dets',
                        required=False,
                        default=None,
                        help='Detector list (comma separated)')
    parser.add_argument('--effdir',
                        required=True,
                        help='Input Exchange Format File directory')
    parser.add_argument('--effdir_in_diode0',
                        required=False,
                        default=None,
                        help='Input Exchange Format File directory, '
                        'LFI diode 0')
    parser.add_argument('--effdir_in_diode1',
                        required=False,
                        default=None,
                        help='Input Exchange Format File directory, '
                        'LFI diode 1')
    parser.add_argument('--effdir_pntg',
                        required=False,
                        help='Input Exchange Format File directory '
                        'for pointing')
    parser.add_argument('--effdir_out',
                        required=False,
                        help='Output directory for destriped TOD')
    parser.add_argument('--effdir_out_diode0',
                        required=False,
                        help='Output directory for destriped TOD, LFI diode 0')
    parser.add_argument('--effdir_out_diode1',
                        required=False,
                        help='Output directory for destriped TOD, LFI diode 1')
    parser.add_argument('--obtmask',
                        required=False,
                        default=1,
                        type=np.int,
                        help='OBT flag mask')
    parser.add_argument('--flagmask',
                        required=False,
                        default=1,
                        type=np.int,
                        help='Quality flag mask')
    parser.add_argument('--pntflagmask',
                        required=False,
                        default=0,
                        type=np.int,
                        help='Pointing flag mask')
    parser.add_argument('--bad_intervals',
                        required=False,
                        help='Path to bad interval file.')
    parser.add_argument('--ringdb', required=True, help='Ring DB file')
    parser.add_argument('--odfirst',
                        required=False,
                        default=None,
                        type=np.int,
                        help='First OD to use')
    parser.add_argument('--odlast',
                        required=False,
                        default=None,
                        type=np.int,
                        help='Last OD to use')
    parser.add_argument('--ringfirst',
                        required=False,
                        default=None,
                        help='First ring to use (can be a list)')
    parser.add_argument('--ringlast',
                        required=False,
                        default=None,
                        help='Last ring to use (can be a list)')
    parser.add_argument('--obtfirst',
                        required=False,
                        default=None,
                        type=np.float,
                        help='First OBT to use')
    parser.add_argument('--obtlast',
                        required=False,
                        default=None,
                        type=np.float,
                        help='Last OBT to use')
    parser.add_argument('--madampar',
                        required=False,
                        default=None,
                        help='Madam parameter file')
    parser.add_argument('--out',
                        required=False,
                        default='.',
                        help='Output directory')
    parser.add_argument('--madam_prefix', required=False, help='map prefix')
    parser.add_argument('--split_mask',
                        required=False,
                        default=None,
                        help='Intensity mask, non-zero pixels are not split.')
    parser.add_argument('--save_leakage_matrices',
                        dest='save_leakage_matrices',
                        default=False,
                        action='store_true',
                        help='Compile and write out the leakage projection '
                        'matrices.')
    # noise parameters
    parser.add_argument('--noisefile',
                        required=False,
                        default='RIMO',
                        help='Path to noise PSD files for noise filter. '
                        'Tag DETECTOR will be replaced with detector name.')
    parser.add_argument('--static_noise',
                        dest='static_noise',
                        required=False,
                        default=False,
                        action='store_true',
                        help='Assume constant noise PSD')
    parser.add_argument('--filterfile',
                        required=False,
                        help='Extra filter file.')

    try:
        args = parser.parse_args()
    except SystemExit:
        sys.exit(0)

    if comm.comm_world.rank == 0:
        print('All parameters:')
        print(args, flush=True)

    timer = Timer()
    timer.start()

    nrange = 1

    odranges = None
    if args.odfirst is not None and args.odlast is not None:
        odranges = []
        firsts = [int(i) for i in str(args.odfirst).split(',')]
        lasts = [int(i) for i in str(args.odlast).split(',')]
        for odfirst, odlast in zip(firsts, lasts):
            odranges.append((odfirst, odlast))
        nrange = len(odranges)

    ringranges = None
    if args.ringfirst is not None and args.ringlast is not None:
        ringranges = []
        firsts = [int(i) for i in str(args.ringfirst).split(',')]
        lasts = [int(i) for i in str(args.ringlast).split(',')]
        for ringfirst, ringlast in zip(firsts, lasts):
            ringranges.append((ringfirst, ringlast))
        nrange = len(ringranges)

    obtranges = None
    if args.obtfirst is not None and args.obtlast is not None:
        obtranges = []
        firsts = [float(i) for i in str(args.obtfirst).split(',')]
        lasts = [float(i) for i in str(args.obtlast).split(',')]
        for obtfirst, obtlast in zip(firsts, lasts):
            obtranges.append((obtfirst, obtlast))
        nrange = len(obtranges)

    if odranges is None:
        odranges = [None] * nrange

    if ringranges is None:
        ringranges = [None] * nrange

    if obtranges is None:
        obtranges = [None] * nrange

    detectors = None
    if args.dets is not None:
        detectors = re.split(',', args.dets)

    # create the TOD for this observation

    if args.noisefile != 'RIMO' and not args.static_noise:
        do_eff_cache = True
    else:
        do_eff_cache = False

    tods = []

    if args.static_noise:
        noisefile = args.noisefile
    else:
        noisefile = 'RIMO'

    for obtrange, ringrange, odrange in zip(obtranges, ringranges, odranges):
        tods.append(
            tp.Exchange(comm=comm.comm_group,
                        detectors=detectors,
                        ringdb=args.ringdb,
                        effdir_in=args.effdir,
                        effdir_in_diode0=args.effdir_in_diode0,
                        effdir_in_diode1=args.effdir_in_diode1,
                        effdir_pntg=args.effdir_pntg,
                        obt_range=obtrange,
                        ring_range=ringrange,
                        od_range=odrange,
                        freq=args.freq,
                        RIMO=args.rimo,
                        obtmask=args.obtmask,
                        flagmask=args.flagmask,
                        pntflagmask=args.pntflagmask,
                        do_eff_cache=do_eff_cache,
                        noisefile=noisefile))

    rimo = tods[0].rimo

    # Make output directory

    if not os.path.isdir(args.out) and comm.comm_world.rank == 0:
        os.makedirs(args.out)

    # Read in madam parameter file
    # Allow more than one entry, gather into a list
    repeated_keys = ['detset', 'detset_nopol', 'survey']
    pars = {}

    if comm.comm_world.rank == 0:
        pars['kfirst'] = False
        pars['temperature_only'] = True
        pars['base_first'] = 60.0
        pars['nside_map'] = args.nside
        pars['nside_cross'] = min(args.nside, args.nside_cross)
        pars['nside_submap'] = 16
        pars['write_map'] = False
        pars['write_binmap'] = True
        pars['write_matrix'] = False
        pars['write_wcov'] = False
        pars['write_hits'] = True
        pars['kfilter'] = False
        pars['info'] = 3
        pars['pixlim_map'] = 1e-3
        pars['pixlim_cross'] = 1e-3
        if args.madampar:
            pat = re.compile(r'\s*(\S+)\s*=\s*(\S+(\s+\S+)*)\s*')
            comment = re.compile(r'^#.*')
            with open(args.madampar, 'r') as f:
                for line in f:
                    if not comment.match(line):
                        result = pat.match(line)
                        if result:
                            key, value = result.group(1), result.group(2)
                            if key in repeated_keys:
                                if key not in pars:
                                    pars[key] = []
                                pars[key].append(value)
                            else:
                                pars[key] = value
        # Command line parameters override the ones in the madam parameter file
        if 'file_root' not in pars:
            pars['file_root'] = 'madam'
        if args.madam_prefix is not None:
            pars['file_root'] = args.madam_prefix
        sfreq = '{:03}'.format(args.freq)
        if sfreq not in pars['file_root']:
            pars['file_root'] += '_' + sfreq
        try:
            fsample = {30: 32.51, 44: 46.55, 70: 78.77}[args.freq]
        except Exception:
            fsample = 180.3737
        pars['fsample'] = fsample
        pars['path_output'] = args.out

        if args.save_leakage_matrices:
            pars['write_leakmatrix'] = True

    pars = comm.comm_world.bcast(pars, root=0)

    if args.noisefile != 'RIMO':
        # We split MPI_COMM_WORLD into single process groups, each of
        # which is assigned one or more observations (rings)
        comm = toast.Comm(groupsize=1)

    # This is the distributed data, consisting of one or
    # more observations, each distributed over a communicator.
    data = toast.Data(comm)

    for iobs, tod in enumerate(tods):
        if args.noisefile != 'RIMO' and not args.static_noise:
            # Use a toast helper method to optimally distribute rings between
            # processes.
            dist = toast.distribute_discrete(tod.ringsizes, comm.world_size)
            my_first_ring, my_n_ring = dist[comm.comm_world.rank]

            for my_ring in range(my_first_ring, my_first_ring + my_n_ring):
                ringtod = tp.Exchange.from_tod(tod,
                                               my_ring,
                                               comm.comm_group,
                                               noisefile=args.noisefile)
                ob = {}
                ob['name'] = 'ring{:05}'.format(ringtod.globalfirst_ring)
                ob['id'] = ringtod.globalfirst_ring
                ob['tod'] = ringtod
                ob['intervals'] = ringtod.valid_intervals
                ob['baselines'] = None
                ob['noise'] = ringtod.noise
                data.obs.append(ob)
        else:
            ob = {}
            ob['name'] = 'observation{:04}'.format(iobs)
            ob['id'] = 0
            ob['tod'] = tod
            ob['intervals'] = tod.valid_intervals
            ob['baselines'] = None
            ob['noise'] = tod.noise

            data.obs.append(ob)

    comm.comm_world.barrier()
    timer.stop()
    if comm.comm_world.rank == 0:
        timer.report("Metadata queries")

    if args.effdir_out is not None or (args.effdir_out_diode0 is not None
                                       and args.effdir_out_diode1 is not None):
        do_output = True
    else:
        do_output = False

    # Read in the signal

    timer.clear()
    timer.start()
    reader = tp.OpInputPlanck(signal_name='signal', flags_name='flags')
    if comm.comm_world.rank == 0:
        print('Reading input signal from {}'.format(args.effdir), flush=True)
    reader.exec(data)
    comm.comm_world.barrier()
    timer.stop()
    if comm.comm_world.rank == 0:
        timer.report("Read")
    tod_name = 'signal'
    flags_name = 'flags'

    # Optionally filter the signal

    apply_filter(args, data)

    # Optionally flag bad intervals

    if args.bad_intervals is not None:
        timer = Timer()
        timer.start()
        flagger = tp.OpBadIntervals(path=args.bad_intervals)
        flagger.exec(data)
        timer.stop()
        if comm.comm_world.rank == 0:
            timer.report("Apply {}".format(args.bad_intervals))

    # make a planck Healpix pointing matrix
    timer.clear()
    timer.start()
    mode = 'IQU'
    if pars['temperature_only'] == 'T':
        mode = 'I'
    nside = int(pars['nside_map'])
    pointing = tp.OpPointingPlanck(nside=nside,
                                   mode=mode,
                                   RIMO=rimo,
                                   margin=0,
                                   apply_flags=(not do_output),
                                   keep_vel=False,
                                   keep_pos=False,
                                   keep_phase=False,
                                   keep_quats=False)

    pointing.exec(data)

    comm.comm_world.barrier()
    timer.stop()
    if comm.comm_world.rank == 0:
        timer.report("Pointing Matrix, mode = {}".format(mode))

    for obs in data.obs:
        obs['tod'].purge_eff_cache()

    # for now, we pass in the noise weights from the RIMO.
    detweights = {}
    for d in tod.detectors:
        if d[-1] in '01' and d[-2] != '-':
            det = to_radiometer(d)
        else:
            det = d
        net = tod.rimo[det].net
        fsample = tod.rimo[det].fsample
        detweights[d] = 1.0 / (fsample * net * net)

    if do_output:
        name_out = 'madam_tod'
    else:
        name_out = None

    timer.clear()
    timer.start()
    try:
        madam = toast.todmap.OpMadam(name=tod_name,
                                     flag_name=flags_name,
                                     apply_flags=do_output,
                                     params=pars,
                                     detweights=detweights,
                                     purge=True,
                                     name_out=name_out,
                                     translate_timestamps=False)
    except Exception as e:
        raise Exception('{:4} : ERROR: failed to initialize Madam: {}'.format(
            comm.comm_world.rank, e))
    madam.exec(data)

    comm.comm_world.barrier()
    timer.stop()
    if comm.comm_world.rank == 0:
        timer.report("Madam")

    if do_output:
        timer = Timer()
        timer.start()
        writer = tp.OpOutputPlanck(signal_name='madam_tod',
                                   flags_name=None,
                                   commonflags_name=None,
                                   effdir_out=args.effdir_out,
                                   effdir_out_diode0=args.effdir_out_diode0,
                                   effdir_out_diode1=args.effdir_out_diode1)

        writer.exec(data)

        comm.comm_world.barrier()
        timer.stop()
        if comm.comm_world.rank == 0:
            timer.report("Madam output")

    memreport("at end of main", mpiworld)

    gt.stop_all()
    if mpiworld is not None:
        mpiworld.barrier()
    timer = Timer()
    timer.start()
    alltimers = gather_timers(comm=mpiworld)
    if comm.world_rank == 0:
        out = os.path.join(args.out, "timing")
        dump_timing(alltimers, out)
        timer.stop()
        timer.report("Gather and dump timing info")
    return
def main():
    timer0 = Timer()
    timer0.start()

    log = Logger.get()
    gt = GlobalTimers.get()
    gt.start("toast_planck_reduce (total)")

    mpiworld, procs, rank, comm = get_comm()
    memreport("At start of pipeline", mpiworld)

    if comm.world_rank == 0:
        print("Running with {} processes at {}".format(
            procs, str(datetime.datetime.now())))

    parser = argparse.ArgumentParser(description='Simple MADAM Mapmaking',
                                     fromfile_prefix_chars='@')
    parser.add_argument('--rimo', required=True, help='RIMO file')
    parser.add_argument('--freq', required=True, type=np.int, help='Frequency')
    parser.add_argument('--debug',
                        dest='debug',
                        default=False,
                        action='store_true',
                        help='Write data distribution info to file')
    parser.add_argument('--dets',
                        required=False,
                        default=None,
                        help='Detector list (comma separated)')
    parser.add_argument('--effdir',
                        required=True,
                        help='Input Exchange Format File directory')
    parser.add_argument('--effdir_pntg',
                        required=False,
                        help='Input Exchange Format File directory '
                        'for pointing')
    parser.add_argument('--coord',
                        default='G',
                        help='Coordinate system, "G", "E" or "C"')
    parser.add_argument('--obtmask',
                        required=False,
                        default=1,
                        type=np.int,
                        help='OBT flag mask')
    parser.add_argument('--flagmask',
                        required=False,
                        default=1,
                        type=np.int,
                        help='Quality flag mask')
    parser.add_argument('--pntflagmask',
                        required=False,
                        default=0,
                        type=np.int,
                        help='Pointing flag mask')
    parser.add_argument('--bad_intervals',
                        required=False,
                        help='Path to bad interval file.')
    parser.add_argument('--ringdb', required=True, help='Ring DB file')
    parser.add_argument('--odfirst',
                        required=False,
                        default=None,
                        type=np.int,
                        help='First OD to use')
    parser.add_argument('--odlast',
                        required=False,
                        default=None,
                        type=np.int,
                        help='Last OD to use')
    parser.add_argument('--ringfirst',
                        required=False,
                        default=None,
                        help='First ring to use (can be a list)')
    parser.add_argument('--ringlast',
                        required=False,
                        default=None,
                        help='Last ring to use (can be a list)')
    parser.add_argument('--obtfirst',
                        required=False,
                        default=None,
                        type=np.float,
                        help='First OBT to use')
    parser.add_argument('--obtlast',
                        required=False,
                        default=None,
                        type=np.float,
                        help='Last OBT to use')
    parser.add_argument('--out',
                        required=False,
                        default='.',
                        help='Output directory')
    parser.add_argument('--catalog', required=True, help='Target catalog file')
    parser.add_argument('--radius',
                        required=True,
                        type=np.float,
                        help='Search radius about the source [arc min]')
    parser.add_argument('--mask',
                        required=False,
                        help='Mask defining region of the sky to accept')
    parser.add_argument('--bg',
                        required=False,
                        help='Background map to subtract')
    parser.add_argument('--recalib_bg',
                        dest='recalib_bg',
                        default=False,
                        action='store_true',
                        help='Recalibrate bg map for each ring.')
    parser.add_argument('--full_rings',
                        dest='full_rings',
                        default=False,
                        action='store_true',
                        help='Extract impacted rings entirely.')
    # noise parameters
    parser.add_argument('--noisefile',
                        required=False,
                        default='RIMO',
                        help='Path to noise PSD files for noise filter. '
                        'Tag DETECTOR will be replaced with detector name.')
    # Dipole parameters
    dipogroup = parser.add_mutually_exclusive_group()
    dipogroup.add_argument('--dipole',
                           dest='dipole',
                           required=False,
                           default=False,
                           action='store_true',
                           help='Simulate dipole')
    dipogroup.add_argument('--solsys_dipole',
                           dest='solsys_dipole',
                           required=False,
                           default=False,
                           action='store_true',
                           help='Simulate solar system dipole')
    dipogroup.add_argument('--orbital_dipole',
                           dest='orbital_dipole',
                           required=False,
                           default=False,
                           action='store_true',
                           help='Simulate orbital dipole')

    try:
        args = parser.parse_args()
    except SystemExit:
        sys.exit(0)

    if comm.world_rank == 0:
        print('All parameters:')
        print(args, flush=True)

    data = create_observations(args, comm)
    rimo = data.obs[0]["tod"].rimo

    memreport("After create observations", mpiworld)

    # Read in the signal

    timer = Timer()
    timer.start()

    reader = tp.OpInputPlanck(signal_name='signal', flags_name='flags')
    if comm.world_rank == 0:
        print('Reading input signal from {}'.format(args.effdir), flush=True)
    reader.exec(data)
    if mpiworld is not None:
        mpiworld.barrier()
    if comm.world_rank == 0:
        timer.report_clear("Reading")
    tod_name = 'signal'
    flags_name = 'flags'

    memreport("After read", mpiworld)

    # Optionally flag bad intervals

    if args.bad_intervals is not None:
        flagger = tp.OpBadIntervals(path=args.bad_intervals)
        flagger.exec(data)
        if comm.world_rank == 0:
            timer.report_clear("Applying {}".format(args.bad_intervals))

    do_dipole = (args.dipole or args.solsys_dipole or args.orbital_dipole)

    # make a planck Healpix pointing matrix
    pointing = tp.OpPointingPlanck(nside=1024,
                                   mode='IQU',
                                   RIMO=rimo,
                                   margin=0,
                                   apply_flags=False,
                                   keep_vel=do_dipole,
                                   keep_pos=False,
                                   keep_phase=True,
                                   keep_quats=True)

    pointing.exec(data)

    memreport("After pointing", mpiworld)

    if mpiworld is not None:
        mpiworld.barrier()
    if comm.world_rank == 0:
        timer.report_clear("Pointing Matrix")

    # Optionally subtract the dipole

    if do_dipole:
        if args.dipole:
            dipomode = 'total'
        elif args.solsys_dipole:
            dipomode = 'solsys'
        else:
            dipomode = 'orbital'
        dipo = tp.OpDipolePlanck(args.freq,
                                 mode=dipomode,
                                 output='dipole',
                                 keep_quats=True)
        dipo.exec(data)
        if mpiworld is not None:
            mpiworld.barrier()
        if comm.world_rank == 0:
            timer.report_clear("Dipole")
        subtractor = tp.OpCacheMath(in1=tod_name,
                                    in2='dipole',
                                    subtract=True,
                                    out=tod_name)
        if comm.comm_world.rank == 0:
            print('Subtracting dipole', flush=True)
        subtractor.exec(data)
        if mpiworld is not None:
            mpiworld.barrier()
        if comm.world_rank == 0:
            timer.report_clear("Dipole subtraction")

        memreport("After dipole", mpiworld)

    extract = tp.OpExtractPlanck(rimo,
                                 args.catalog,
                                 args.radius,
                                 mpiworld,
                                 common_flag_mask=args.obtmask,
                                 flag_mask=args.flagmask,
                                 maskfile=args.mask,
                                 bg=args.bg,
                                 full_rings=args.full_rings,
                                 recalibrate_bg=args.recalib_bg,
                                 out=args.out)
    extract.exec(data)

    memreport("After extract", mpiworld)

    if mpiworld is not None:
        mpiworld.barrier()
    if comm.world_rank == 0:
        timer.report_clear("Extraction")

    gt.stop_all()
    if mpiworld is not None:
        mpiworld.barrier()
    timer = Timer()
    timer.start()
    alltimers = gather_timers(comm=mpiworld)
    if comm.world_rank == 0:
        out = os.path.join(args.out, "timing")
        dump_timing(alltimers, out)
        timer.report_clear("Gather and dump timing info")
        timer0.report_clear("Full pipeline")
    return
Esempio n. 11
0
def main():
    log = Logger.get()
    gt = GlobalTimers.get()
    gt.start("toast_s4_sim (total)")
    timer0 = Timer()
    timer0.start()

    mpiworld, procs, rank, comm = toast_tools.get_comm()

    memreport("at the beginning of the pipeline", comm.comm_world)

    args, comm = parse_arguments(comm)

    # Initialize madam parameters

    madampars = toast_tools.setup_madam(args)

    # Load and broadcast the schedule file

    schedules = toast_tools.load_schedule(args, comm)

    # Load the weather and append to schedules

    toast_tools.load_weather(args, comm, schedules)

    # load or simulate the focalplane

    detweights = s4_tools.load_focalplanes(args, comm, schedules)

    # Create the TOAST data object to match the schedule.  This will
    # include simulating the boresight pointing.

    data, telescope_data = s4_tools.create_observations(args, comm, schedules)

    memreport("after creating observations", comm.comm_world)

    # Optionally rewrite the noise PSD:s in each observation to include
    # elevation-dependence
    s4_tools.get_elevation_noise(args, comm, data)

    totalname = "total"

    # Split the communicator for day and season mapmaking

    time_comms = toast_tools.get_time_communicators(args, comm, data)

    # Expand boresight quaternions into detector pointing weights and
    # pixel numbers

    toast_tools.expand_pointing(args, comm, data)

    # Only purge the pointing if we are NOT going to export the
    # data to a TIDAS volume
    if args.tidas is None:
        for ob in data.obs:
            tod = ob["tod"]
            try:
                tod.free_radec_quats()
            except AttributeError:
                # These TOD objects do not have RA/Dec quaternions
                pass

    memreport("after pointing", comm.comm_world)

    # Prepare auxiliary information for distributed map objects

    memreport("after submaps", comm.comm_world)

    # Set up objects to take copies of the TOD at appropriate times

    if args.pysm_model:
        if schedules is not None:
            focalplanes = [
                s.telescope.focalplane.detector_data for s in schedules
            ]
        else:
            focalplanes = [telescope.focalplane.detector_data]
        signalname = s4_tools.simulate_sky_signal(args, comm, data,
                                                  focalplanes)
    else:
        signalname = toast_tools.scan_sky_signal(args, comm, data)

    memreport("after PySM", comm.comm_world)

    # Loop over Monte Carlos

    firstmc = int(args.MC_start)
    nmc = int(args.MC_count)

    for mc in range(firstmc, firstmc + nmc):

        if comm.world_rank == 0:
            log.info("Processing MC = {}".format(mc))

        # Uncomment to run with new TOAST
        #toast_tools.draw_weather(args, comm, data, mc)

        outpath = setup_output(args, comm, mc)

        if outputs_exist(args, comm, outpath):
            if comm.world_rank == 0:
                log.info("Outputs already exist, skipping.")
            continue

        toast.tod.OpCacheClear(totalname).exec(data)

        toast_tools.simulate_atmosphere(args, comm, data, mc, totalname)

        s4_tools.scale_atmosphere_by_bandpass(args, comm, data, totalname, mc)

        memreport("after atmosphere", comm.comm_world)

        # update_atmospheric_noise_weights(args, comm, data, freq, mc)

        toast_tools.add_signal(args,
                               comm,
                               data,
                               totalname,
                               signalname,
                               purge=(mc == firstmc + nmc - 1))

        memreport("after adding sky", comm.comm_world)

        toast_tools.simulate_noise(args, comm, data, mc, totalname)

        memreport("after simulating noise", comm.comm_world)

        toast_tools.simulate_sss(args, comm, data, mc, totalname)

        memreport("after simulating SSS", comm.comm_world)

        toast_tools.scramble_gains(args, comm, data, mc, totalname)

        if mc == firstmc:
            # For the first realization and frequency, optionally
            # export the timestream data.
            toast_tools.output_tidas(args, comm, data, totalname)

            memreport("after export", comm.comm_world)

        if args.no_maps:
            continue

        # Bin and destripe maps

        pairdiff(data, args, comm, totalname, mc == firstmc)

        if not args.skip_madam:
            toast_tools.apply_madam(
                args,
                comm,
                data,
                madampars,
                outpath,
                detweights,
                totalname,
                time_comms=time_comms,
                telescope_data=telescope_data,
                first_call=(mc == firstmc),
            )
            memreport("after madam", comm.comm_world)

        if (args.filterbin_ground_order is not None
                or args.filterbin_poly_order is not None):
            toast_tools.apply_filterbin(
                args,
                comm,
                data,
                outpath,
                totalname,
                time_comms=time_comms,
                telescope_data=telescope_data,
                first_call=(mc == firstmc),
            )

        if (args.apply_polyfilter or args.apply_polyfilter2D
                or args.apply_common_mode_filter or args.apply_groundfilter):

            # Filter signal

            toast_tools.apply_common_mode_filter(args, comm, data, totalname)

            toast_tools.apply_polyfilter2D(args, comm, data, totalname)

            toast_tools.apply_polyfilter(args, comm, data, totalname)

            toast_tools.apply_groundfilter(args, comm, data, totalname)

            memreport("after filter", comm.comm_world)

            # Bin maps

            toast_tools.apply_madam(
                args,
                comm,
                data,
                madampars,
                outpath,
                detweights,
                totalname,
                time_comms=time_comms,
                telescope_data=telescope_data,
                first_call=(args.skip_madam and mc == firstmc),
                extra_prefix="filtered",
                bin_only=(not args.skip_madam),
            )

            memreport("after filter & bin", comm.comm_world)

    if comm.comm_world is not None:
        comm.comm_world.barrier()

    memreport("at the end of the pipeline", comm.comm_world)

    gt.stop_all()
    if mpiworld is not None:
        mpiworld.barrier()
    timer = Timer()
    timer.start()
    alltimers = gather_timers(comm=mpiworld)
    if rank == 0:
        out = os.path.join(args.outdir, "timing")
        dump_timing(alltimers, out)
        timer.stop()
        timer.report("Gather and dump timing info")
    timer0.stop()
    if comm.world_rank == 0:
        timer0.report("toast_s4_sim.py pipeline")
    return
def main():
    log = Logger.get()
    gt = GlobalTimers.get()
    gt.start("toast_planck_reduce (total)")

    mpiworld, procs, rank, comm = get_comm()

    if comm.comm_world.rank == 0:
        print("Running with {} processes at {}".format(
            procs, str(datetime.datetime.now())))

    parser = argparse.ArgumentParser(description='Planck Ringset making',
                                     fromfile_prefix_chars='@')
    parser.add_argument('--rimo', required=True, help='RIMO file')
    parser.add_argument('--freq', required=True, type=np.int, help='Frequency')
    parser.add_argument('--dets',
                        required=False,
                        default=None,
                        help='Detector list (comma separated)')
    parser.add_argument('--effdir',
                        required=True,
                        help='Input Exchange Format File directory')
    parser.add_argument('--read_eff',
                        dest='read_eff',
                        default=False,
                        action='store_true',
                        help='Read and co-add the signal from effdir')
    parser.add_argument('--effdir_pntg',
                        required=False,
                        help='Input Exchange Format File directory for '
                        'pointing')
    parser.add_argument('--obtmask',
                        required=False,
                        default=1,
                        type=np.int,
                        help='OBT flag mask')
    parser.add_argument('--flagmask',
                        required=False,
                        default=1,
                        type=np.int,
                        help='Quality flag mask')
    parser.add_argument('--ringdb', required=True, help='Ring DB file')
    parser.add_argument('--odfirst',
                        required=False,
                        default=None,
                        help='First OD to use')
    parser.add_argument('--odlast',
                        required=False,
                        default=None,
                        help='Last OD to use')
    parser.add_argument('--ringfirst',
                        required=False,
                        default=None,
                        help='First ring to use')
    parser.add_argument('--ringlast',
                        required=False,
                        default=None,
                        help='Last ring to use')
    parser.add_argument('--obtfirst',
                        required=False,
                        default=None,
                        help='First OBT to use')
    parser.add_argument('--obtlast',
                        required=False,
                        default=None,
                        help='Last OBT to use')
    parser.add_argument('--out',
                        required=False,
                        default='.',
                        help='Output directory')
    dipogroup = parser.add_mutually_exclusive_group()
    dipogroup.add_argument('--dipole',
                           dest='dipole',
                           required=False,
                           default=False,
                           action='store_true',
                           help='Simulate dipole')
    dipogroup.add_argument('--solsys_dipole',
                           dest='solsys_dipole',
                           required=False,
                           default=False,
                           action='store_true',
                           help='Simulate solar system dipole')
    dipogroup.add_argument('--orbital_dipole',
                           dest='orbital_dipole',
                           required=False,
                           default=False,
                           action='store_true',
                           help='Simulate orbital dipole')
    # dipole parameters
    dipo_parameters_group = parser.add_argument_group('dipole_parameters')
    dipo_parameters_group.add_argument(
        '--solsys_speed',
        dest='solsys_speed',
        required=False,
        type=np.float,
        default=DEFAULT_PARAMETERS["solsys_speed"],
        help='Solar system speed wrt. CMB rest frame in km/s. '
        'Default is Planck 2015 best fit value')
    dipo_parameters_group.add_argument(
        '--solsys_glon',
        dest='solsys_glon',
        required=False,
        type=np.float,
        default=DEFAULT_PARAMETERS["solsys_glon"],
        help='Solar system velocity direction longitude in degrees')
    dipo_parameters_group.add_argument(
        '--solsys_glat',
        dest='solsys_glat',
        required=False,
        type=np.float,
        default=DEFAULT_PARAMETERS["solsys_glat"],
        help='Solar system velocity direction latitude in degrees')

    # libconviqt parameters
    parser.add_argument('--lmax',
                        required=False,
                        default=1024,
                        type=np.int,
                        help='Simulation lmax')
    parser.add_argument('--fwhm',
                        required=False,
                        default=0.0,
                        type=np.float,
                        help='Sky fwhm [arcmin] to deconvolve')
    parser.add_argument('--beammmax',
                        required=False,
                        default=None,
                        type=np.int,
                        help='Beam mmax')
    parser.add_argument('--order',
                        required=False,
                        default=11,
                        type=np.int,
                        help='Iteration order')
    parser.add_argument('--pxx',
                        required=False,
                        default=False,
                        action='store_true',
                        help='Beams are in Pxx frame, not Dxx')
    parser.add_argument('--skyfile',
                        required=False,
                        default=None,
                        help='Path to sky alm files. Tag DETECTOR will be '
                        'replaced with detector name.')
    parser.add_argument('--beamfile',
                        required=False,
                        default=None,
                        help='Path to beam alm files. Tag DETECTOR will be '
                        'replaced with detector name.')
    parser.add_argument('--nopol',
                        dest='nopol',
                        default=False,
                        action='store_true',
                        help='Sky and beam should be treated unpolarized')
    # noise simulation parameters
    parser.add_argument('--add_noise',
                        dest='add_noise',
                        default=False,
                        action='store_true',
                        help='Simulate noise')
    parser.add_argument('--noisefile',
                        required=False,
                        default='RIMO',
                        help='Path to noise PSD files for noise filter. '
                        'Tag DETECTOR will be replaced with detector name.')
    parser.add_argument('--noisefile_simu',
                        required=False,
                        default='RIMO',
                        help='Path to noise PSD files for noise simulation. '
                        'Tag DETECTOR will be replaced with detector name.')
    parser.add_argument('--mc',
                        required=False,
                        default=0,
                        type=np.int,
                        help='Noise realization')
    # ringset parameters
    parser.add_argument('--nside_ring',
                        required=False,
                        default=128,
                        type=np.int,
                        help='Ringset resolution')
    parser.add_argument('--ring_root',
                        required=False,
                        default='ringset',
                        help='Root filename for ringsets (setting to empty '
                        'disables ringset output).')

    args = parser.parse_args()

    if comm.world_rank == 0:
        print('All parameters:')
        print(args, flush=True)

    timer = Timer()
    timer.start()

    nrange = 1

    odranges = None
    if args.odfirst is not None and args.odlast is not None:
        odranges = []
        firsts = [int(i) for i in str(args.odfirst).split(',')]
        lasts = [int(i) for i in str(args.odlast).split(',')]
        for odfirst, odlast in zip(firsts, lasts):
            odranges.append((odfirst, odlast))
        nrange = len(odranges)

    ringranges = None
    if args.ringfirst is not None and args.ringlast is not None:
        ringranges = []
        firsts = [int(i) for i in str(args.ringfirst).split(',')]
        lasts = [int(i) for i in str(args.ringlast).split(',')]
        for ringfirst, ringlast in zip(firsts, lasts):
            ringranges.append((ringfirst, ringlast))
        nrange = len(ringranges)

    obtranges = None
    if args.obtfirst is not None and args.obtlast is not None:
        obtranges = []
        firsts = [float(i) for i in str(args.obtfirst).split(',')]
        lasts = [float(i) for i in str(args.obtlast).split(',')]
        for obtfirst, obtlast in zip(firsts, lasts):
            obtranges.append((obtfirst, obtlast))
        nrange = len(obtranges)

    if odranges is None:
        odranges = [None] * nrange

    if ringranges is None:
        ringranges = [None] * nrange

    if obtranges is None:
        obtranges = [None] * nrange

    detectors = None
    if args.dets is not None:
        detectors = re.split(',', args.dets)

    # Make output directory

    if comm.world_rank == 0:
        os.makedirs(args.out, exist_ok=True)

    do_dipole = args.dipole or args.solsys_dipole or args.orbital_dipole
    do_convolve = args.skyfile is not None and args.beamfile is not None
    do_noise = args.add_noise
    if not do_noise and args.noisefile_simu != 'RIMO':
        raise RuntimeError('Did you mean to simulate noise? add_noise = {} '
                           'but noisefile_simu = {}'.format(
                               args.add_noise, args.noisefile_simu))

    if comm.world_rank == 0:
        print('read_eff = {}'.format(args.read_eff))
        print('do_dipole = {}'.format(do_dipole))
        print('solsys_speed = {}'.format(args.solsys_speed))
        print('solsys_glon = {}'.format(args.solsys_glon))
        print('solsys_glat = {}'.format(args.solsys_glat))
        print('do_convolve = {}'.format(do_convolve))
        print('do_noise = {}'.format(do_noise), flush=True)

    # create the TOD for the whole data span (loads ring database and caches
    # directory contents)

    if do_noise and args.noisefile_simu != 'RIMO':
        do_eff_cache = True
    else:
        do_eff_cache = False

    tods = []

    for obtrange, ringrange, odrange in zip(obtranges, ringranges, odranges):
        tods.append(
            tp.Exchange(comm=comm.comm_group,
                        detectors=detectors,
                        ringdb=args.ringdb,
                        effdir_in=args.effdir,
                        effdir_pntg=args.effdir_pntg,
                        obt_range=obtrange,
                        ring_range=ringrange,
                        od_range=odrange,
                        freq=args.freq,
                        RIMO=args.rimo,
                        obtmask=args.obtmask,
                        flagmask=args.flagmask,
                        do_eff_cache=do_eff_cache))

    if mpiworld is not None:
        mpiworld.barrier()
    if comm.world_rank == 0:
        timer.report_clear("Metadata queries")

    if args.noisefile != 'RIMO' or args.noisefile_simu != 'RIMO':
        # We split MPI_COMM_WORLD into single process groups, each of
        # which is assigned one or more observations (rings)
        comm = Comm(groupsize=1)

    # This is the distributed data, consisting of one or
    # more observations, each distributed over a communicator.
    data = Data(comm)

    for tod in tods:
        if args.noisefile != 'RIMO' or args.noisefile_simu != 'RIMO':
            # Use a toast helper method to optimally distribute rings between
            # processes.
            dist = distribute_discrete(tod.ringsizes, procs)
            my_first_ring, my_n_ring = dist[comm.world_rank]

            for my_ring in range(my_first_ring, my_first_ring + my_n_ring):
                ringtod = tp.Exchange.from_tod(
                    tod,
                    my_ring,
                    comm.comm_group,
                    noisefile=args.noisefile,
                    noisefile_simu=args.noisefile_simu)
                ob = {}
                ob['name'] = 'ring{:05}'.format(ringtod.globalfirst_ring)
                ob['id'] = ringtod.globalfirst_ring
                ob['tod'] = ringtod
                ob['intervals'] = ringtod.valid_intervals
                ob['baselines'] = None
                ob['noise'] = ringtod.noise
                ob['noise_simu'] = ringtod.noise_simu
                data.obs.append(ob)
        else:
            # This is the distributed data, consisting of one or
            # more observations, each distributed over a communicator.
            ob = {}
            ob['name'] = 'mission'
            ob['id'] = 0
            ob['tod'] = tod
            ob['intervals'] = tod.valid_intervals
            ob['baselines'] = None
            ob['noise'] = tod.noise

            data.obs.append(ob)

    rimo = tods[0].rimo
    fsample = rimo[detectors[0]].fsample

    if mpiworld is not None:
        mpiworld.barrier()
    if comm.world_rank == 0:
        timer.report_clear("Create observations")

    # make a planck Healpix pointing matrix
    mode = 'IQU'

    pointing = tp.OpPointingPlanck(nside=args.nside_ring,
                                   mode=mode,
                                   RIMO=rimo,
                                   margin=0,
                                   apply_flags=False,
                                   keep_vel=do_dipole,
                                   keep_pos=False,
                                   keep_phase=False,
                                   keep_quats=(do_dipole or do_convolve))

    pointing.exec(data)

    if mpiworld is not None:
        mpiworld.barrier()
    if comm.world_rank == 0:
        timer.report_clear("Pointing Matrix")

    # Always read the signal because we always need the flags

    reader = tp.OpInputPlanck(signal_name='tod')
    if comm.world_rank == 0:
        print('Reading input signal from {}'.format(args.effdir), flush=True)
    reader.exec(data)
    comm.comm_world.barrier()
    if comm.world_rank == 0:
        timer.report_clear("Read")
    tod_name = 'tod'

    # Clear the signal if we don't need it

    if not args.read_eff:
        eraser = tp.OpCacheMath(in1='tod', in2=0, multiply=True, out='tod')
        if comm.comm_world.rank == 0:
            print('Erasing TOD', flush=True)
        eraser.exec(data)
        comm.comm_world.barrier()
        if comm.world_rank == 0:
            timer.report_clear("Erase")

    if do_convolve:
        # simulate the TOD by convolving the sky with the beams
        detectordata = []
        for det in tod.detectors:
            skyfile = args.skyfile.replace('DETECTOR', det)
            beamfile = args.beamfile.replace('DETECTOR', det)
            epsilon = rimo[det].epsilon
            # Getting the right polarization angle can be a sensitive matter.
            # Dxx beams are always defined without psi_uv or psi_pol rotation
            # but some Pxx beams may require psi_pol to be removed and psi_uv
            # left in.
            if args.pxx:
                # Beam is in the polarization basis.
                # No extra rotations are needed
                psipol = np.radians(rimo[det].psi_pol)
            else:
                # Beam is in the detector basis. Convolver needs to remove
                # the last rotation into the polarization sensitive frame.
                psipol = np.radians(rimo[det].psi_uv + rimo[det].psi_pol)
            detectordata.append((det, skyfile, beamfile, epsilon, psipol))

        # always construct conviqt with dxx=True and modify the psipol
        # to produce the desired rotation.

        conviqt = tt.OpSimConviqt(args.lmax,
                                  args.beammmax,
                                  detectordata,
                                  pol=(not args.nopol),
                                  fwhm=args.fwhm,
                                  order=args.order,
                                  calibrate=True,
                                  dxx=True,
                                  out='tod',
                                  quat_name='quats',
                                  apply_flags=False)
        conviqt.exec(data)
        if mpiworld is not None:
            mpiworld.barrier()
        if comm.world_rank == 0:
            timer.report_clear("Convolution")
        tod_name = 'tod'

    if do_dipole:
        # Simulate the dipole
        if args.dipole:
            dipomode = 'total'
        elif args.solsys_dipole:
            dipomode = 'solsys'
        else:
            dipomode = 'orbital'
        dipo = tp.OpDipolePlanck(args.freq,
                                 solsys_speed=args.solsys_speed,
                                 solsys_glon=args.solsys_glon,
                                 solsys_glat=args.solsys_glat,
                                 mode=dipomode,
                                 output='tod',
                                 add_to_existing=args.read_eff)
        dipo.exec(data)
        if mpiworld is not None:
            mpiworld.barrier()
        if comm.world_rank == 0:
            timer.report_clear("Dipole")
        tod_name = 'tod'

    if do_noise:
        nse = tt.OpSimNoise(out='tod',
                            realization=args.mc,
                            component=0,
                            noise='noise_simu',
                            rate=fsample)
        nse.exec(data)
        if mpiworld is not None:
            mpiworld.barrier()
        if comm.world_rank == 0:
            timer.report_clear("Noise simulation")
        tod_name = 'tod'

    # for now, we pass in the noise weights from the RIMO.
    detweights = {}
    for d in tod.detectors:
        net = tod.rimo[d].net
        fsample = tod.rimo[d].fsample
        detweights[d] = 1.0 / (fsample * net * net)

    # Make rings

    ringmaker = tp.OpRingMaker(args.nside_ring,
                               args.nside_ring,
                               signal=tod_name,
                               fileroot=args.ring_root,
                               out=args.out,
                               detmask=args.flagmask,
                               commonmask=args.obtmask)
    ringmaker.exec(data)
    if mpiworld is not None:
        mpiworld.barrier()
    if comm.world_rank == 0:
        timer.report_clear("Ringmaking")

    gt.stop_all()
    if mpiworld is not None:
        mpiworld.barrier()
    timer = Timer()
    timer.start()
    alltimers = gather_timers(comm=mpiworld)
    if comm.world_rank == 0:
        out = os.path.join(args.out, "timing")
        dump_timing(alltimers, out)
        timer.stop()
        timer.report("Gather and dump timing info")
    return
Esempio n. 13
0
def main():
    log = Logger.get()
    gt = GlobalTimers.get()
    gt.start("toast_so_sim (total)")
    timer0 = Timer()
    timer0.start()

    mpiworld, procs, rank, comm = toast_tools.get_comm()

    memreport("at the beginning of the pipeline", comm.comm_world)

    args, comm = parse_arguments(comm)

    # Load and broadcast the schedule file

    schedules = toast_tools.load_schedule(args, comm)

    # Load the weather and append to schedules

    toast_tools.load_weather(args, comm, schedules)

    # load or simulate the focalplane

    detweights = so_tools.load_focalplanes(args, comm, schedules)

    # Create the TOAST data object to match the schedule.  This will
    # include simulating the boresight pointing.

    data, telescope_data = so_tools.create_observations(args, comm, schedules)

    memreport("after creating observations", comm.comm_world)

    # Optionally rewrite the noise PSD:s in each observation to include
    # elevation-dependence
    so_tools.get_elevation_noise(args, comm, data)

    totalname = "total"

    # Split the communicator for day and season mapmaking

    time_comms = toast_tools.get_time_communicators(args, comm, data)

    # Expand boresight quaternions into detector pointing weights and
    # pixel numbers

    toast_tools.expand_pointing(args, comm, data)

    memreport("after pointing", comm.comm_world)

    # Loop over Monte Carlos

    firstmc = int(args.MC_start)
    nmc = int(args.MC_count)

    madam = None

    for mc in range(firstmc, firstmc + nmc):

        timer_mc = Timer()
        timer_mc.start()

        outpath = setup_output(args, comm, mc)
        outprefix = args.map_prefix + "_filtered"
        if args.madam:
            outmap = os.path.join(outpath, outprefix + "_bmap.fits")
        else:
            outmap = os.path.join(outpath, outprefix + "_binned.fits")

        if os.path.isfile(outmap):
            if comm.world_rank == 0:
                log.info("{} exists, skipping".format(outmap))
            continue

        if comm.world_rank == 0:
            log.info("Processing MC = {} into {}".format(mc, outmap))

        # Ensure there is no stale signal in the cache

        toast.tod.OpCacheClear(totalname).exec(data)

        if args.pysm_model:
            if schedules is not None:
                focalplanes = [
                    s.telescope.focalplane.detector_data for s in schedules
                ]
            else:
                focalplanes = [telescope.focalplane.detector_data]
            so_tools.simulate_sky_signal(args,
                                         comm,
                                         data,
                                         focalplanes,
                                         totalname,
                                         mc=mc)
        else:
            toast_tools.scan_sky_signal(args, comm, data, totalname, mc=mc)

        memreport("after PySM", comm.comm_world)

        if args.apply_polyfilter or args.apply_groundfilter:

            # Filter signal

            toast_tools.apply_polyfilter(args, comm, data, totalname)

            toast_tools.apply_groundfilter(args, comm, data, totalname)

            memreport("after filter", comm.comm_world)

            # Bin maps

            timer_map = Timer()
            timer_map.start()

            if args.madam:
                if madam is None:
                    madampars = {}
                    madampars["temperature_only"] = False
                    for name in [
                            "kfirst", "write_map", "write_matrix",
                            "write_wcov", "write_hits"
                    ]:
                        madampars[name] = False
                    madampars["write_binmap"] = True
                    madampars["concatenate_messages"] = True
                    madampars["allreduce"] = True
                    madampars["nside_submap"] = args.nside_submap
                    madampars["reassign_submaps"] = True
                    madampars["pixlim_map"] = 1e-2
                    madampars["pixmode_map"] = 2
                    # Instead of fixed detector weights, we'll want to use scaled noise
                    # PSD:s that include the atmospheric noise
                    madampars["radiometers"] = True
                    madampars["noise_weights_from_psd"] = True
                    madampars["nside_map"] = args.nside
                    madampars["fsample"] = args.sample_rate
                    madampars["path_output"] = outpath
                    madampars["file_root"] = outprefix
                    if args.madam_concatenate_messages:
                        # Collective communication is fast but requires memory
                        madampars["concatenate_messages"] = True
                        if args.madam_allreduce:
                            # Every process will allocate a copy of every observed submap.
                            madampars["allreduce"] = True
                        else:
                            # Every process will allocate complete send and receive buffers
                            madampars["allreduce"] = False
                    else:
                        # Slow but memory-efficient point-to-point communication.  Allocate
                        # only enough memory to communicate with one process at a time.
                        madampars["concatenate_messages"] = False
                        madampars["allreduce"] = False
                    madam = toast.todmap.OpMadam(
                        params=madampars,
                        detweights=detweights,
                        name=totalname,
                        common_flag_mask=args.common_flag_mask,
                        purge_tod=True,
                        mcmode=False,
                        conserve_memory=args.madam_conserve_memory,
                    )
                else:
                    madam.params["path_output"] = outpath
                madam.exec(data)
                del madam
                madam = None
            else:
                mapmaker = toast.todmap.OpMapMaker(
                    nside=args.nside,
                    nnz=3,
                    name=totalname,
                    outdir=outpath,
                    outprefix=outprefix + "_",
                    write_hits=False,
                    zip_maps=False,
                    write_wcov_inv=False,
                    write_wcov=False,
                    write_binned=True,
                    write_destriped=False,
                    write_rcond=False,
                    rcond_limit=1e-3,
                    baseline_length=None,
                    common_flag_mask=args.common_flag_mask,
                )
                mapmaker.exec(data)

            if comm.world_rank == 0:
                timer_map.report_clear("Bin map")

            memreport("after filter & bin", comm.comm_world)

            if comm.world_rank == 0:
                timer_mc.report_clear(
                    "Monte Carlo iteration # {:05}".format(mc))

    if comm.comm_world is not None:
        comm.comm_world.barrier()

    memreport("at the end of the pipeline", comm.comm_world)

    gt.stop_all()
    if mpiworld is not None:
        mpiworld.barrier()
    timer = Timer()
    timer.start()
    alltimers = gather_timers(comm=mpiworld)
    if rank == 0:
        out = os.path.join(args.outdir, "timing")
        dump_timing(alltimers, out)
        timer.report_clear("Gather and dump timing info")

    if comm.world_rank == 0:
        timer0.report_clear("toast_so_tf.py pipeline")

    return
def main():
    log = Logger.get()
    gt = GlobalTimers.get()
    gt.start("toast_planck_reduce (total)")

    mpiworld, procs, rank, comm = get_comm()

    # This is the 2-level toast communicator.  By default,
    # there is just one group which spans MPI_COMM_WORLD.
    comm = toast.Comm()

    if comm.comm_world.rank == 0:
        print(
            "Running with {} processes at {}".format(
                procs, str(datetime.datetime.now())
            )
        )

    parser = argparse.ArgumentParser(
        description="Simple on-the-fly signal convolution + MADAM Mapmaking",
        fromfile_prefix_chars="@",
    )
    parser.add_argument("--lmax", required=True, type=np.int, help="Simulation lmax")
    parser.add_argument(
        "--fwhm", required=True, type=np.float, help="Sky fwhm [arcmin] to deconvolve"
    )
    parser.add_argument("--beammmax", required=True, type=np.int, help="Beam mmax")
    parser.add_argument("--order", default=11, type=np.int, help="Iteration order")
    parser.add_argument(
        "--pxx",
        required=False,
        default=False,
        action="store_true",
        help="Beams are in Pxx frame, not Dxx",
    )
    parser.add_argument(
        "--normalize",
        required=False,
        default=False,
        action="store_true",
        help="Normalize the beams",
    )
    parser.add_argument(
        "--skyfile",
        required=True,
        help="Path to sky alm files. Tag DETECTOR will be "
        "replaced with detector name.",
    )
    parser.add_argument(
        "--remove_monopole",
        required=False,
        default=False,
        action="store_true",
        help="Remove the sky monopole before convolution",
    )
    parser.add_argument(
        "--remove_dipole",
        required=False,
        default=False,
        action="store_true",
        help="Remove the sky dipole before convolution",
    )
    parser.add_argument(
        "--beamfile",
        required=True,
        help="Path to beam alm files. Tag DETECTOR will be "
        "replaced with detector name.",
    )
    parser.add_argument("--rimo", required=True, help="RIMO file")
    parser.add_argument("--freq", required=True, type=np.int, help="Frequency")
    parser.add_argument(
        "--dets", required=False, default=None, help="Detector list (comma separated)"
    )
    parser.add_argument(
        "--effdir", required=True, help="Input Exchange Format File directory"
    )
    parser.add_argument(
        "--effdir_pntg",
        required=False,
        help="Input Exchange Format File directory " "for pointing",
    )
    parser.add_argument(
        "--effdir_out", required=False, help="Output directory for convolved TOD"
    )
    parser.add_argument(
        "--obtmask", required=False, default=1, type=np.int, help="OBT flag mask"
    )
    parser.add_argument(
        "--flagmask", required=False, default=1, type=np.int, help="Quality flag mask"
    )
    parser.add_argument("--ringdb", required=True, help="Ring DB file")
    parser.add_argument(
        "--odfirst", required=False, default=None, type=np.int, help="First OD to use"
    )
    parser.add_argument(
        "--odlast", required=False, default=None, type=np.int, help="Last OD to use"
    )
    parser.add_argument(
        "--ringfirst",
        required=False,
        default=None,
        type=np.int,
        help="First ring to use",
    )
    parser.add_argument(
        "--ringlast", required=False, default=None, type=np.int, help="Last ring to use"
    )
    parser.add_argument(
        "--obtfirst",
        required=False,
        default=None,
        type=np.float,
        help="First OBT to use",
    )
    parser.add_argument(
        "--obtlast", required=False, default=None, type=np.float, help="Last OBT to use"
    )
    parser.add_argument("--madam_prefix", required=False, help="map prefix")
    parser.add_argument(
        "--madampar", required=False, default=None, help="Madam parameter file"
    )
    parser.add_argument(
        "--obtmask_madam", required=False, type=np.int, help="OBT flag mask for Madam"
    )
    parser.add_argument(
        "--flagmask_madam",
        required=False,
        type=np.int,
        help="Quality flag mask for Madam",
    )
    parser.add_argument(
        "--skip_madam",
        required=False,
        default=False,
        action="store_true",
        help="Do not run Madam on the convolved timelines",
    )
    parser.add_argument("--out", required=False, default=".", help="Output directory")

    try:
        args = parser.parse_args()
    except SystemExit:
        sys.exit(0)

    timer = Timer()
    timer.start()

    odrange = None
    if args.odfirst is not None and args.odlast is not None:
        odrange = (args.odfirst, args.odlast)

    ringrange = None
    if args.ringfirst is not None and args.ringlast is not None:
        ringrange = (args.ringfirst, args.ringlast)

    obtrange = None
    if args.obtfirst is not None and args.obtlast is not None:
        obtrange = (args.obtfirst, args.obtlast)

    detectors = None
    if args.dets is not None:
        detectors = re.split(",", args.dets)

    # This is the distributed data, consisting of one or
    # more observations, each distributed over a communicator.
    data = toast.Data(comm)

    # Ensure output directory exists

    if not os.path.isdir(args.out) and comm.comm_world.rank == 0:
        os.makedirs(args.out)

    # Read in madam parameter file

    # Allow more than one entry, gather into a list
    repeated_keys = ["detset", "detset_nopol", "survey"]
    pars = {}

    if comm.comm_world.rank == 0:
        pars["kfirst"] = False
        pars["temperature_only"] = True
        pars["base_first"] = 60.0
        pars["nside_map"] = 512
        pars["nside_cross"] = 512
        pars["nside_submap"] = 16
        pars["write_map"] = False
        pars["write_binmap"] = True
        pars["write_matrix"] = False
        pars["write_wcov"] = False
        pars["write_hits"] = True
        pars["kfilter"] = False
        pars["info"] = 3
        if args.madampar:
            pat = re.compile(r"\s*(\S+)\s*=\s*(\S+(\s+\S+)*)\s*")
            comment = re.compile(r"^#.*")
            with open(args.madampar, "r") as f:
                for line in f:
                    if not comment.match(line):
                        result = pat.match(line)
                        if result:
                            key, value = result.group(1), result.group(2)
                            if key in repeated_keys:
                                if key not in pars:
                                    pars[key] = []
                                pars[key].append(value)
                            else:
                                pars[key] = value
        # Command line parameters override the ones in the madam parameter file
        if "file_root" not in pars:
            pars["file_root"] = "madam"
        if args.madam_prefix is not None:
            pars["file_root"] = args.madam_prefix
        sfreq = "{:03}".format(args.freq)
        if sfreq not in pars["file_root"]:
            pars["file_root"] += "_" + sfreq
        try:
            fsample = {30: 32.51, 44: 46.55, 70: 78.77}[args.freq]
        except Exception:
            fsample = 180.3737
        pars["fsample"] = fsample
        pars["path_output"] = args.out

        print("All parameters:")
        print(args, flush=True)

    pars = comm.comm_world.bcast(pars, root=0)

    memreport("after parameters", MPI.COMM_WORLD)

    # madam only supports a single observation.  Normally
    # we would have multiple observations with some subset
    # assigned to each process group.

    # create the TOD for this observation

    tod = tp.Exchange(
        comm=comm.comm_group,
        detectors=detectors,
        ringdb=args.ringdb,
        effdir_in=args.effdir,
        effdir_pntg=args.effdir_pntg,
        obt_range=obtrange,
        ring_range=ringrange,
        od_range=odrange,
        freq=args.freq,
        RIMO=args.rimo,
        obtmask=args.obtmask,
        flagmask=args.flagmask,
        do_eff_cache=False,
    )

    # normally we would get the intervals from somewhere else, but since
    # the Exchange TOD already had to get that information, we can
    # get it from there.

    ob = {}
    ob["name"] = "mission"
    ob["id"] = 0
    ob["tod"] = tod
    ob["intervals"] = tod.valid_intervals
    ob["baselines"] = None
    ob["noise"] = tod.noise

    # Add the bare minimum focal plane information for the conviqt operator
    focalplane = {}
    for det in tod.detectors:
        if args.pxx:
            # Beam is in the polarization basis.
            # No extra rotations are needed
            psipol = tod.rimo[det].psi_pol
        else:
            # Beam is in the detector basis. Convolver needs to remove
            # the last rotation into the polarization sensitive frame.
            psipol = tod.rimo[det].psi_uv + tod.rimo[det].psi_pol
        focalplane[det] = {
            "pol_leakage" : tod.rimo[det].epsilon,
            "pol_angle_deg" : psipol,
        }
    ob["focalplane"] = focalplane

    data.obs.append(ob)

    comm.comm_world.barrier()
    if comm.comm_world.rank == 0:
        timer.report_clear("Metadata queries")

    loader = tp.OpInputPlanck(
        commonflags_name="common_flags", flags_name="flags", margin=0
    )

    loader.exec(data)

    comm.comm_world.barrier()
    if comm.comm_world.rank == 0:
        timer.report_clear("Data read and cache")
        tod.cache.report()

    memreport("after loading", mpiworld)

    # make a planck Healpix pointing matrix
    mode = "IQU"
    if pars["temperature_only"] == "T":
        mode = "I"
    nside = int(pars["nside_map"])
    pointing = tp.OpPointingPlanck(
        nside=nside,
        mode=mode,
        RIMO=tod.RIMO,
        margin=0,
        apply_flags=False,
        keep_vel=False,
        keep_pos=False,
        keep_phase=False,
        keep_quats=True,
    )
    pointing.exec(data)

    comm.comm_world.barrier()
    if comm.comm_world.rank == 0:
        timer.report_clear("Pointing Matrix took, mode = {}".format(mode))

    memreport("after pointing", mpiworld)

    # simulate the TOD by convolving the sky with the beams

    if comm.comm_world.rank == 0:
        print("Convolving TOD", flush=True)

    for pattern in args.beamfile.split(","):
        skyfiles = {}
        beamfiles = {}
        for det in tod.detectors:
            freq = "{:03}".format(tp.utilities.det2freq(det))
            if "LFI" in det:
                psmdet = "{}_{}".format(freq, det[3:])
                if det.endswith("M"):
                    arm = "y"
                else:
                    arm = "x"
                graspdet = "{}_{}_{}".format(freq[1:], det[3:5], arm)
            else:
                psmdet = det.replace("-", "_")
                graspdet = det
            skyfile = (
                args.skyfile.replace("FREQ", freq)
                .replace("PSMDETECTOR", psmdet)
                .replace("DETECTOR", det)
            )
            skyfiles[det] = skyfile
            beamfile = pattern.replace("GRASPDETECTOR", graspdet).replace(
                "DETECTOR", det
            )
            beamfiles[det] = beamfile
            if comm.comm_world.rank == 0:
                print("Convolving {} with {}".format(skyfile, beamfile), flush=True)

        conviqt = OpSimConviqt(
            comm.comm_world,
            skyfiles,
            beamfiles,
            lmax=args.lmax,
            beammmax=args.beammmax,
            pol=True,
            fwhm=args.fwhm,
            order=args.order,
            calibrate=True,
            dxx=True,
            out="conviqt_tod",
            apply_flags=False,
            remove_monopole=args.remove_monopole,
            remove_dipole=args.remove_dipole,
            verbosity=1,
            normalize_beam=args.normalize,
        )
        conviqt.exec(data)

    comm.comm_world.barrier()
    if comm.comm_world.rank == 0:
        timer.report_clear("Convolution")

    memreport("after conviqt", mpiworld)

    if args.effdir_out is not None:
        if comm.comm_world.rank == 0:
            print("Writing TOD", flush=True)

        tod.set_effdir_out(args.effdir_out, None)
        writer = tp.OpOutputPlanck(
            signal_name="conviqt_tod",
            flags_name="flags",
            commonflags_name="common_flags",
        )
        writer.exec(data)

        comm.comm_world.barrier()
        if comm.comm_world.rank == 0:
            timer.report_clear("Conviqt output")

        memreport("after writing", mpiworld)

    # for now, we pass in the noise weights from the RIMO.
    detweights = {}
    for d in tod.detectors:
        net = tod.rimo[d].net
        fsample = tod.rimo[d].fsample
        detweights[d] = 1.0 / (fsample * net * net)

    if not args.skip_madam:
        if comm.comm_world.rank == 0:
            print("Calling Madam", flush=True)

        try:
            if args.obtmask_madam is None:
                obtmask = args.obtmask
            else:
                obtmask = args.obtmask_madam
            if args.flagmask_madam is None:
                flagmask = args.flagmask
            else:
                flagmask = args.flagmask_madam
            madam = OpMadam(
                params=pars,
                detweights=detweights,
                name="conviqt_tod",
                flag_name="flags",
                purge=True,
                name_out="madam_tod",
                common_flag_mask=obtmask,
                flag_mask=flagmask,
            )
        except Exception as e:
            raise Exception(
                "{:4} : ERROR: failed to initialize Madam: {}".format(
                    comm.comm_world.rank, e
                )
            )
        madam.exec(data)

        comm.comm_world.barrier()
        if comm.comm_world.rank == 0:
            timer.report_clear("Madam took {:.3f} s")

        memreport("after madam", mpiworld)

    gt.stop_all()
    if mpiworld is not None:
        mpiworld.barrier()
    timer = Timer()
    timer.start()
    alltimers = gather_timers(comm=mpiworld)
    if comm.world_rank == 0:
        out = os.path.join(args.out, "timing")
        dump_timing(alltimers, out)
        timer.stop()
        timer.report("Gather and dump timing info")
    return
Esempio n. 15
0
def main():
    log = Logger.get()
    gt = GlobalTimers.get()
    gt.start("toast_planck_reduce (total)")

    mpiworld, procs, rank, comm = get_comm()

    # This is the 2-level toast communicator.  By default,
    # there is just one group which spans MPI_COMM_WORLD.
    comm = toast.Comm()

    if comm.world_rank == 0:
        print("Running with {} processes at {}".format(
            procs, str(datetime.datetime.now())))

    parser = argparse.ArgumentParser(
        description='Accumulate polarization moments',
        fromfile_prefix_chars='@')
    parser.add_argument('--rimo', required=True, help='RIMO file')
    parser.add_argument('--freq', required=True, type=np.int, help='Frequency')
    parser.add_argument('--nside',
                        required=False,
                        type=np.int,
                        default=512,
                        help='Map resolution')
    parser.add_argument('--smax',
                        required=False,
                        type=np.int,
                        default=6,
                        help='Highest moment')
    parser.add_argument('--debug',
                        dest='debug',
                        default=False,
                        action='store_true',
                        help='Write data distribution info to file')
    parser.add_argument('--dets',
                        required=False,
                        default=None,
                        help='Detector list (comma separated)')
    parser.add_argument('--effdir',
                        required=True,
                        help='Input Exchange Format File directory')
    parser.add_argument('--effdir_in_diode0',
                        required=False,
                        default=None,
                        help='Input Exchange Format File directory, '
                        'LFI diode 0')
    parser.add_argument('--effdir_in_diode1',
                        required=False,
                        default=None,
                        help='Input Exchange Format File directory, '
                        'LFI diode 1')
    parser.add_argument('--effdir_pntg',
                        required=False,
                        help='Input Exchange Format File directory '
                        'for pointing')
    parser.add_argument('--obtmask',
                        required=False,
                        default=1,
                        type=np.int,
                        help='OBT flag mask')
    parser.add_argument('--flagmask',
                        required=False,
                        default=1,
                        type=np.int,
                        help='Quality flag mask')
    parser.add_argument('--pntflagmask',
                        required=False,
                        default=0,
                        type=np.int,
                        help='Pointing flag mask')
    parser.add_argument('--ringdb', required=True, help='Ring DB file')
    parser.add_argument('--odfirst',
                        required=False,
                        default=None,
                        type=np.int,
                        help='First OD to use')
    parser.add_argument('--odlast',
                        required=False,
                        default=None,
                        type=np.int,
                        help='Last OD to use')
    parser.add_argument('--ringfirst',
                        required=False,
                        default=None,
                        help='First ring to use (can be a list)')
    parser.add_argument('--ringlast',
                        required=False,
                        default=None,
                        help='Last ring to use (can be a list)')
    parser.add_argument('--obtfirst',
                        required=False,
                        default=None,
                        type=np.float,
                        help='First OBT to use')
    parser.add_argument('--obtlast',
                        required=False,
                        default=None,
                        type=np.float,
                        help='Last OBT to use')
    parser.add_argument('--out',
                        required=False,
                        default='.',
                        help='Output directory')
    parser.add_argument('--prefix',
                        required=False,
                        default='spins',
                        help='map prefix')

    try:
        args = parser.parse_args()
    except SystemExit:
        sys.exit(0)

    if comm.world_rank == 0:
        print('All parameters:')
        print(args, flush=True)

    timer = Timer()
    timer.start()

    nrange = 1

    odranges = None
    if args.odfirst is not None and args.odlast is not None:
        odranges = []
        firsts = [int(i) for i in str(args.odfirst).split(',')]
        lasts = [int(i) for i in str(args.odlast).split(',')]
        for odfirst, odlast in zip(firsts, lasts):
            odranges.append((odfirst, odlast))
        nrange = len(odranges)

    ringranges = None
    if args.ringfirst is not None and args.ringlast is not None:
        ringranges = []
        firsts = [int(i) for i in str(args.ringfirst).split(',')]
        lasts = [int(i) for i in str(args.ringlast).split(',')]
        for ringfirst, ringlast in zip(firsts, lasts):
            ringranges.append((ringfirst, ringlast))
        nrange = len(ringranges)

    obtranges = None
    if args.obtfirst is not None and args.obtlast is not None:
        obtranges = []
        firsts = [float(i) for i in str(args.obtfirst).split(',')]
        lasts = [float(i) for i in str(args.obtlast).split(',')]
        for obtfirst, obtlast in zip(firsts, lasts):
            obtranges.append((obtfirst, obtlast))
        nrange = len(obtranges)

    if odranges is None:
        odranges = [None] * nrange

    if ringranges is None:
        ringranges = [None] * nrange

    if obtranges is None:
        obtranges = [None] * nrange

    detectors = None
    if args.dets is not None:
        detectors = re.split(',', args.dets)

    # create the TOD for this observation

    tods = []

    for obtrange, ringrange, odrange in zip(obtranges, ringranges, odranges):
        tods.append(
            tp.Exchange(comm=comm.comm_group,
                        detectors=detectors,
                        ringdb=args.ringdb,
                        effdir_in=args.effdir,
                        effdir_in_diode0=args.effdir_in_diode0,
                        effdir_in_diode1=args.effdir_in_diode1,
                        effdir_pntg=args.effdir_pntg,
                        obt_range=obtrange,
                        ring_range=ringrange,
                        od_range=odrange,
                        freq=args.freq,
                        RIMO=args.rimo,
                        obtmask=args.obtmask,
                        flagmask=args.flagmask,
                        pntflagmask=args.pntflagmask,
                        do_eff_cache=False,
                        noisefile='RIMO'))

    rimo = tods[0].rimo

    # Make output directory

    if not os.path.isdir(args.out) and comm.comm_world.rank == 0:
        os.makedirs(args.out)

    # This is the distributed data, consisting of one or
    # more observations, each distributed over a communicator.
    data = toast.Data(comm)

    for iobs, tod in enumerate(tods):
        ob = {}
        ob['name'] = 'observation{:04}'.format(iobs)
        ob['id'] = 0
        ob['tod'] = tod
        ob['intervals'] = tod.valid_intervals
        ob['baselines'] = None
        ob['noise'] = tod.noise

        data.obs.append(ob)

    if mpiworld is not None:
        mpiworld.barrier()
    if comm.comm_world.rank == 0:
        timer.report_clear("Metadata queries")

    # Accumulate and save the moment maps
    polmoments = tp.OpPolMomentsPlanck(nside=args.nside,
                                       RIMO=rimo,
                                       margin=0,
                                       keep_vel=False,
                                       keep_pos=False,
                                       keep_phase=False,
                                       keep_quats=False,
                                       smax=args.smax,
                                       prefix=os.path.join(
                                           args.out, args.prefix))

    polmoments.exec(data)

    if mpiworld is not None:
        mpiworld.barrier()
    if comm.comm_world.rank == 0:
        timer.report_clear("Accumulate moment maps")

    gt.stop_all()
    if mpiworld is not None:
        mpiworld.barrier()
    timer = Timer()
    timer.start()
    alltimers = gather_timers(comm=mpiworld)
    if comm.world_rank == 0:
        out = os.path.join(args.out, "timing")
        dump_timing(alltimers, out)
        timer.stop()
        timer.report("Gather and dump timing info")
    return
Esempio n. 16
0
def main():
    env = Environment.get()
    log = Logger.get()
    gt = GlobalTimers.get()
    gt.start("toast_satellite_sim (total)")
    timer0 = Timer()
    timer0.start()

    mpiworld, procs, rank, comm = get_comm()
    args, comm, groupsize = parse_arguments(comm, procs)

    # Parse options

    tmr = Timer()
    tmr.start()

    if comm.world_rank == 0:
        os.makedirs(args.outdir, exist_ok=True)

    focalplane, gain, detweights = load_focalplane(args, comm)

    data = create_observations(args, comm, focalplane, groupsize)

    expand_pointing(args, comm, data)

    localpix, localsm, subnpix = get_submaps(args, comm, data)

    signalname = None
    skyname = simulate_sky_signal(args, comm, data, [focalplane], subnpix,
                                  localsm, "signal")
    if skyname is not None:
        signalname = skyname

    diponame = simulate_dipole(args, comm, data, "signal")
    if diponame is not None:
        signalname = diponame

    # Mapmaking.

    if not args.use_madam:
        if comm.world_rank == 0:
            log.info("Not using Madam, will only make a binned map")

        npp, zmap = init_binner(args,
                                comm,
                                data,
                                detweights,
                                subnpix=subnpix,
                                localsm=localsm)

        # Loop over Monte Carlos

        firstmc = args.MC_start
        nmc = args.MC_count

        for mc in range(firstmc, firstmc + nmc):
            mctmr = Timer()
            mctmr.start()

            outpath = os.path.join(args.outdir, "mc_{:03d}".format(mc))

            simulate_noise(args, comm, data, mc, "tot_signal", overwrite=True)

            # add sky signal
            add_signal(args, comm, data, "tot_signal", signalname)

            if gain is not None:
                timer = Timer()
                timer.start()
                op_apply_gain = OpApplyGain(gain, name="tot_signal")
                op_apply_gain.exec(data)
                if comm.world_rank == 0:
                    timer.report_clear("  Apply gains {:04d}".format(mc))

            if mc == firstmc:
                # For the first realization, optionally export the
                # timestream data.  If we had observation intervals defined,
                # we could pass "use_interval=True" to the export operators,
                # which would ensure breaks in the exported data at
                # acceptable places.
                output_tidas(args, comm, data, "tot_signal")
                output_spt3g(args, comm, data, "tot_signal")

            apply_binner(args, comm, data, npp, zmap, detweights, outpath,
                         "tot_signal")

            if comm.world_rank == 0:
                mctmr.report_clear("  Map-making {:04d}".format(mc))
    else:

        # Initialize madam parameters

        madampars = setup_madam(args)

        # in debug mode, print out data distribution information
        if args.debug:
            handle = None
            if comm.world_rank == 0:
                handle = open(os.path.join(args.outdir, "distdata.txt"), "w")
            data.info(handle)
            if comm.world_rank == 0:
                handle.close()
            if comm.comm_world is not None:
                comm.comm_world.barrier()
            if comm.world_rank == 0:
                tmr.report_clear("Dumping data distribution")

        # Loop over Monte Carlos

        firstmc = args.MC_start
        nmc = args.MC_count

        for mc in range(firstmc, firstmc + nmc):
            mctmr = Timer()
            mctmr.start()

            # create output directory for this realization
            outpath = os.path.join(args.outdir, "mc_{:03d}".format(mc))

            simulate_noise(args, comm, data, mc, "tot_signal", overwrite=True)

            # add sky signal
            add_signal(args, comm, data, "tot_signal", signalname)

            if gain is not None:
                op_apply_gain = OpApplyGain(gain, name="tot_signal")
                op_apply_gain.exec(data)

            if comm.comm_world is not None:
                comm.comm_world.barrier()
            if comm.world_rank == 0:
                tmr.report_clear("  Apply gains {:04d}".format(mc))

            apply_madam(args, comm, data, madampars, outpath, detweights,
                        "tot_signal")

            if comm.comm_world is not None:
                comm.comm_world.barrier()
            if comm.world_rank == 0:
                mctmr.report_clear("  Map-making {:04d}".format(mc))

    gt.stop_all()
    if comm.comm_world is not None:
        comm.comm_world.barrier()
    tmr.stop()
    tmr.clear()
    tmr.start()
    alltimers = gather_timers(comm=comm.comm_world)
    if comm.world_rank == 0:
        out = os.path.join(args.outdir, "timing")
        dump_timing(alltimers, out)
        tmr.stop()
        tmr.report("Gather and dump timing info")
        timer0.report_clear("toast_satellite_sim.py")
    return
def main():
    log = Logger.get()
    gt = GlobalTimers.get()
    gt.start("toast_planck_reduce (total)")

    mpiworld, procs, rank, comm = get_comm()

    if comm.world_rank == 0:
        print("Running with {} processes at {}".format(
            procs, str(datetime.datetime.now())))

    parser = argparse.ArgumentParser(description='Simple dipole pipeline',
                                     fromfile_prefix_chars='@')
    parser.add_argument('--rimo', required=True, help='RIMO file')
    parser.add_argument('--freq', required=True, type=np.int, help='Frequency')
    parser.add_argument('--dets',
                        required=False,
                        default=None,
                        help='Detector list (comma separated)')
    parser.add_argument('--effdir',
                        required=True,
                        help='Input Exchange Format File directory')
    parser.add_argument('--effdir_pntg',
                        required=False,
                        help='Input Exchange Format File directory for '
                        'pointing')
    parser.add_argument('--obtmask',
                        required=False,
                        default=1,
                        type=np.int,
                        help='OBT flag mask')
    parser.add_argument('--flagmask',
                        required=False,
                        default=1,
                        type=np.int,
                        help='Quality flag mask')
    parser.add_argument('--pntflagmask',
                        required=False,
                        default=0,
                        type=np.int,
                        help='Which OBT flag bits to raise for HCM maneuvers')
    parser.add_argument('--ringdb', required=True, help='Ring DB file')
    parser.add_argument('--odfirst',
                        required=False,
                        default=None,
                        help='First OD to use')
    parser.add_argument('--odlast',
                        required=False,
                        default=None,
                        help='Last OD to use')
    parser.add_argument('--ringfirst',
                        required=False,
                        default=None,
                        help='First ring to use')
    parser.add_argument('--ringlast',
                        required=False,
                        default=None,
                        help='Last ring to use')
    parser.add_argument('--obtfirst',
                        required=False,
                        default=None,
                        help='First OBT to use')
    parser.add_argument('--obtlast',
                        required=False,
                        default=None,
                        help='Last OBT to use')
    parser.add_argument('--out',
                        required=False,
                        default='.',
                        help='Output directory')
    # Dipole parameters
    dipogroup = parser.add_mutually_exclusive_group()
    dipogroup.add_argument('--dipole',
                           dest='dipole',
                           required=False,
                           default=False,
                           action='store_true',
                           help='Simulate dipole')
    dipogroup.add_argument('--solsys-dipole',
                           required=False,
                           default=False,
                           action='store_true',
                           help='Simulate solar system dipole')
    dipogroup.add_argument('--orbital-dipole',
                           required=False,
                           default=False,
                           action='store_true',
                           help='Simulate orbital dipole')
    dipo_parameters_group = parser.add_argument_group('dipole_parameters')
    dipo_parameters_group.add_argument(
        '--solsys_speed',
        required=False,
        type=np.float,
        default=DEFAULT_PARAMETERS["solsys_speed"],
        help='Solar system speed wrt. CMB rest frame in km/s. Default is '
        'Planck 2015 best fit value')
    dipo_parameters_group.add_argument(
        '--solsys-glon',
        required=False,
        type=np.float,
        default=DEFAULT_PARAMETERS["solsys_glon"],
        help='Solar system velocity direction longitude in degrees')
    dipo_parameters_group.add_argument(
        '--solsys-glat',
        required=False,
        type=np.float,
        default=DEFAULT_PARAMETERS["solsys_glat"],
        help='Solar system velocity direction latitude in degrees')

    try:
        args = parser.parse_args()
    except SystemExit:
        sys.exit(0)

    if comm.world_rank == 0:
        print('All parameters:')
        print(args, flush=True)

    timer = Timer()
    timer.start()

    do_dipole = args.dipole or args.solsys_dipole or args.orbital_dipole
    if not do_dipole:
        raise RuntimeError(
            "You have to set dipole, solsys-dipole or orbital-dipole")

    nrange = 1

    odranges = None
    if args.odfirst is not None and args.odlast is not None:
        odranges = []
        firsts = [int(i) for i in str(args.odfirst).split(',')]
        lasts = [int(i) for i in str(args.odlast).split(',')]
        for odfirst, odlast in zip(firsts, lasts):
            odranges.append((odfirst, odlast))
        nrange = len(odranges)

    ringranges = None
    if args.ringfirst is not None and args.ringlast is not None:
        ringranges = []
        firsts = [int(i) for i in str(args.ringfirst).split(',')]
        lasts = [int(i) for i in str(args.ringlast).split(',')]
        for ringfirst, ringlast in zip(firsts, lasts):
            ringranges.append((ringfirst, ringlast))
        nrange = len(ringranges)

    obtranges = None
    if args.obtfirst is not None and args.obtlast is not None:
        obtranges = []
        firsts = [float(i) for i in str(args.obtfirst).split(',')]
        lasts = [float(i) for i in str(args.obtlast).split(',')]
        for obtfirst, obtlast in zip(firsts, lasts):
            obtranges.append((obtfirst, obtlast))
        nrange = len(obtranges)

    if odranges is None:
        odranges = [None] * nrange

    if ringranges is None:
        ringranges = [None] * nrange

    if obtranges is None:
        obtranges = [None] * nrange

    detectors = None
    if args.dets is not None:
        detectors = re.split(',', args.dets)

    # create the TOD for this observation

    tods = []

    for obtrange, ringrange, odrange in zip(obtranges, ringranges, odranges):
        # create the TOD for this observation
        tods.append(
            tp.Exchange(comm=comm.comm_group,
                        detectors=detectors,
                        ringdb=args.ringdb,
                        effdir_in=args.effdir,
                        effdir_pntg=args.effdir_pntg,
                        obt_range=obtrange,
                        ring_range=ringrange,
                        od_range=odrange,
                        freq=args.freq,
                        RIMO=args.rimo,
                        obtmask=args.obtmask,
                        flagmask=args.flagmask,
                        pntflagmask=args.pntflagmask,
                        do_eff_cache=False))

    # Make output directory

    if not os.path.isdir(args.out) and comm.world_rank == 0:
        os.makedirs(args.out)

    # This is the distributed data, consisting of one or
    # more observations, each distributed over a communicator.
    data = toast.Data(comm)

    for iobs, tod in enumerate(tods):
        ob = {}
        ob['name'] = 'observation{:04}'.format(iobs)
        ob['id'] = 0
        ob['tod'] = tod
        ob['intervals'] = tod.valid_intervals
        ob['baselines'] = None
        ob['noise'] = tod.noise
        ob['noise_simu'] = tod.noise

        data.obs.append(ob)

    rimo = tods[0].rimo

    if mpiworld is not None:
        mpiworld.barrier()
    if comm.world_rank == 0:
        timer.report_clear("Metadata queries")

    # Always read the signal and flags, even if the signal is later
    # overwritten.  There is no overhead for the signal because it is
    # interlaced with the flags.

    tod_name = 'signal'
    timestamps_name = 'timestamps'
    flags_name = 'flags'
    common_flags_name = 'common_flags'
    reader = tp.OpInputPlanck(signal_name=tod_name,
                              flags_name=flags_name,
                              timestamps_name=timestamps_name,
                              commonflags_name=common_flags_name)
    if comm.world_rank == 0:
        print('Reading input signal from {}'.format(args.effdir), flush=True)
    reader.exec(data)
    if mpiworld is not None:
        mpiworld.barrier()
    if comm.world_rank == 0:
        timer.report_clear("Read")
    """
    # Clear the signal

    eraser = tp.OpCacheMath(in1=tod_name, in2=0, multiply=True,
                            out=tod_name)
    if comm.world_rank == 0:
        print('Erasing TOD', flush=True)
    eraser.exec(data)
    if mpiworld is not None:
        mpiworld.barrier()
    if comm.world_rank == 0:
        timer.report_clear("Erase")
    """

    # make a planck Healpix pointing matrix

    mode = 'IQU'
    nside = 512

    pointing = tp.OpPointingPlanck(nside=nside,
                                   mode=mode,
                                   RIMO=rimo,
                                   margin=0,
                                   apply_flags=True,
                                   keep_vel=do_dipole,
                                   keep_pos=False,
                                   keep_phase=False,
                                   keep_quats=do_dipole)
    pointing.exec(data)
    if mpiworld is not None:
        mpiworld.barrier()
    if comm.world_rank == 0:
        timer.report_clear("Pointing Matrix")

    flags_name = 'flags'
    common_flags_name = 'common_flags'

    # Simulate the dipole
    if args.dipole:
        dipomode = 'total'
    elif args.solsys_dipole:
        dipomode = 'solsys'
    else:
        dipomode = 'orbital'
    dipo = tp.OpDipolePlanck(args.freq,
                             solsys_speed=args.solsys_speed,
                             solsys_glon=args.solsys_glon,
                             solsys_glat=args.solsys_glat,
                             mode=dipomode,
                             output='dipole',
                             keep_quats=False,
                             npipe_mode=True)
    dipo.exec(data)
    dipo = tp.OpDipolePlanck(args.freq,
                             solsys_speed=args.solsys_speed,
                             solsys_glon=args.solsys_glon,
                             solsys_glat=args.solsys_glat,
                             mode=dipomode,
                             output='dipole4pi',
                             keep_quats=False,
                             npipe_mode=False,
                             lfi_mode=False)
    dipo.exec(data)
    if mpiworld is not None:
        mpiworld.barrier()
    if comm.world_rank == 0:
        timer.report_clear("Dipole")

    # Write out the values in ASCII
    for iobs, obs in enumerate(data.obs):
        tod = obs["tod"]
        times = tod.local_times()
        velocity = tod.local_velocity()
        for det in tod.local_dets:
            quat = tod.local_pointing(det)
            angles = np.vstack(qarray.to_angles(quat)).T
            signal = tod.local_signal(det)
            dipole = tod.local_signal(det, "dipole")
            dipole4pi = tod.local_signal(det, "dipole4pi")
            fname_out = os.path.join(
                args.out,
                "{}_dipole.{}.{}.{}.txt".format(dipomode, comm.world_rank,
                                                iobs, det))
            with open(fname_out, "w") as fout:
                for t, ang, vel, sig, dipo, dipo4pi in zip(
                        times, angles, velocity, signal, dipole, dipole4pi):
                    fout.write(
                        (10 * " {}" + "\n").format(t, *ang, *vel, sig, dipo,
                                                   dipo4pi))
            print("{} : Wrote {}".format(comm.world_rank, fname_out))

    if comm.world_rank == 0:
        timer.report_clear("Write dipole")

    gt.stop_all()
    if mpiworld is not None:
        mpiworld.barrier()
    timer = Timer()
    timer.start()
    alltimers = gather_timers(comm=mpiworld)
    if comm.world_rank == 0:
        out = os.path.join(args.out, "timing")
        dump_timing(alltimers, out)
        timer.stop()
        timer.report("Gather and dump timing info")
    return