예제 #1
0
def above_horizon(target, observer, horizon=20.0, duration=0.0):
    """Check target visibility.
       Utility function to calculate ephem horizontal coordinates
    """

    # use local copies so you do not overwrite target time attribute
    horizon = ephem.degrees(str(horizon))

    # must be celestial target (ra, dec)
    # check that target is visible at start of track
    start_ = timestamp2datetime(time.time())
    [azim, elev] = _horizontal_coordinates(target, observer, start_)
    user_logger.trace("TRACE: target at start (az, el)= ({}, {})".format(
        azim, elev))
    if not elev > horizon:
        return False

    # check that target will be visible at end of track
    if duration:
        end_ = timestamp2datetime(time.time() + duration)
        [azim, elev] = _horizontal_coordinates(target, observer, end_)
        user_logger.trace("TRACE: target at end (az, el)= ({}, {})".format(
            azim, elev))
        return elev > horizon

    return True
예제 #2
0
def above_horizon(target, observer, horizon=20.0, duration=0.0):
    """Check target visibility."""
    # use local copies so you do not overwrite target time attribute
    horizon = ephem.degrees(str(horizon))

    if type(target) is not ephem.FixedBody:
        # anticipate katpoint special target for AzEl targets
        if 'alt' not in vars(target):
            raise RuntimeError('Unknown target type, exiting...')
        # 'StationaryBody' objects do not have RaDec coordinates
        # check pointing altitude is above minimum elevation limit
        return bool(target.alt >= horizon)

    # must be celestial target (ra, dec)
    # check that target is visible at start of track
    start_ = timestamp2datetime(time.time())
    [azim, elev] = __horizontal_coordinates__(target, observer, start_)
    user_logger.trace("TRACE: target at start (az, el)= ({}, {})".format(
        azim, elev))
    if not elev > horizon:
        return False

    # check that target will be visible at end of track
    if duration:
        end_ = timestamp2datetime(time.time() + duration)
        [azim, elev] = __horizontal_coordinates__(target, observer, end_)
        user_logger.trace("TRACE: target at end (az, el)= ({}, {})".format(
            azim, elev))
        return elev > horizon

    return True
예제 #3
0
파일: targets.py 프로젝트: ska-sa/astrokat
def read(target_items, observer=None):
    """Read targets info.

    Unpack targets target items to a katpoint compatible format
    Update all targets to have celestial (Ra, Dec) coordinates

    """
    ntargets = len(target_items)
    target_rec_array = np.recarray(ntargets, dtype=tgt_desc)
    for cnt, target_item in enumerate(target_items):
        # build astrokat target info from dict definition
        target_dict = parse_target_string(target_item, observer=observer)
        # accumulate individual target dictionaries into
        # observation ready target rec-array
        target_tuple = build_target_tuple(target_dict)
        user_logger.debug('DEBUG: target object \n{}'.format(target_tuple))
        target_rec_array[cnt] = target_tuple
    user_logger.debug('DEBUG: target parameters \n{}'.format(
        target_rec_array.dtype.names))
    user_logger.trace('TRACE: target parameters types \n{}'.format(
        target_rec_array.dtype))
    return target_rec_array
예제 #4
0
def observe(session, ref_antenna, target_info, **kwargs):
    """Target observation functionality.

    Parameters
    ----------
    session: `CaptureSession`
    target_info:

    """
    target_visible = False

    target_name = target_info["name"]
    target = target_info["target"]
    duration = target_info["duration"]
    obs_type = target_info["obs_type"]

    # update (Ra, Dec) for horizontal coordinates @ obs time
    if ("azel" in target_info["target_str"]) and ("radec" in target.tags):
        tgt_coord = target_info["target_str"].split('=')[-1].strip()
        ra_hms, dec_dms = _get_radec_from_azel(ref_antenna.observer, tgt_coord,
                                               time.time())

        target.body._ra = ra_hms
        target.body._dec = dec_dms

    # simple way to get telescope to slew to target
    if "slewonly" in kwargs:
        return session.track(target, duration=0.0, announce=False)

    # set noise diode behaviour
    nd_setup = None
    nd_lead = None
    if kwargs.get("noise_diode"):
        nd_setup = kwargs["noise_diode"]
        # user specified lead time
        if "lead_time" in nd_setup:
            nd_lead = nd_setup['lead_time']
        # not a ND pattern
        if "cycle_len" not in nd_setup:
            nd_setup = None

    # implement target specific noise diode behaviour
    nd_period = None
    nd_restore = False
    if target_info["noise_diode"] is not None:
        if "off" in target_info["noise_diode"]:
            user_logger.info('Observation: No ND for target')
            nd_restore = True
            # disable noise diode pattern for target
            noisediode.off(session.kat, lead_time=nd_lead)
        else:
            nd_period = float(target_info["noise_diode"])

    msg = "Initialising {} {} {}".format(obs_type.capitalize(),
                                         ", ".join(target.tags[1:]),
                                         target_name)
    if not np.isnan(duration):  # scan types do not have durations
        msg += " for {} sec".format(duration)
    if np.isnan(duration) or duration > 1:
        user_logger.info(msg)

    # do the different observations depending on requested type
    session.label(obs_type.strip())
    user_logger.trace("TRACE: performing {} observation on {}".format(
        obs_type, target))
    if "drift_scan" in obs_type:
        target_visible = scans.drift_scan(session,
                                          ref_antenna,
                                          target,
                                          duration=duration,
                                          nd_period=nd_period,
                                          lead_time=nd_lead)
    elif "scan" in obs_type:  # compensating for ' and spaces around key values
        if "raster_scan" in obs_type:
            if ("raster_scan"
                    not in kwargs.keys()) or ("num_scans"
                                              not in kwargs["raster_scan"]):
                raise RuntimeError("{} needs 'num_scans' parameter".format(
                    obs_type.capitalize()))
            nscans = float(kwargs["raster_scan"]["num_scans"])
            if "scan_duration" not in kwargs["raster_scan"]:
                kwargs["raster_scan"]["scan_duration"] = duration / nscans
        else:
            if 'scan' not in kwargs.keys():
                kwargs['scan'] = {'duration': duration}
            else:
                kwargs['scan']['duration'] = duration
        # TODO: fix raster scan and remove this scan hack
        if "forwardscan" in obs_type:
            scan_func = scans.forwardscan
            obs_type = "scan"
        elif "reversescan" in obs_type:
            scan_func = scans.reversescan
            obs_type = "scan"
        elif "return_scan" in obs_type:
            scan_func = scans.return_scan
            obs_type = "scan"
        elif "raster_scan" in obs_type:
            scan_func = scans.raster_scan
        else:
            scan_func = scans.scan
        target_visible = scan_func(session,
                                   target,
                                   nd_period=nd_period,
                                   lead_time=nd_lead,
                                   **kwargs[obs_type])

    else:  # track is default
        if nd_period is not None:
            user_logger.trace("TRACE: ts before nd trigger"
                              "{} for {}".format(time.time(), nd_period))
            noisediode.trigger(session.kat,
                               duration=nd_period,
                               lead_time=nd_lead)
            user_logger.trace("TRACE: ts after nd trigger {}".format(
                time.time()))
        user_logger.debug("DEBUG: Starting {}s track on target: "
                          "{} ({})".format(duration, time.time(),
                                           time.ctime(time.time())))
        if session.track(target, duration=duration):
            target_visible = True
    user_logger.trace("TRACE: ts after {} {}".format(obs_type, time.time()))

    if (nd_setup is not None and nd_restore):
        # restore pattern if programmed at setup
        user_logger.info('Observation: Restoring ND pattern')
        noisediode.pattern(
            session.kat,
            nd_setup,
            lead_time=nd_lead,
        )

    return target_visible
예제 #5
0
def run_observation(opts, kat):
    """Extract control and observation information provided in observation file."""
    obs_plan_params = opts.obs_plan_params
    # remove observation specific instructions housed in YAML file
    del opts.obs_plan_params

    # set up duration periods for observation control
    obs_duration = -1
    if "durations" in obs_plan_params:
        if "obs_duration" in obs_plan_params["durations"]:
            obs_duration = obs_plan_params["durations"]["obs_duration"]
    # check for nonsensical observation duration setting
    if abs(obs_duration) < 1e-5:
        user_logger.error(
            "Unexpected value: obs_duration: {}".format(obs_duration))
        return

    # TODO: the description requirement in sessions should be re-evaluated
    # since the schedule block has the description
    # Description argument in instruction_set should be retired, but is
    # needed by sessions
    # Assign proposal_description if available, else create a dummy
    if "description" not in vars(opts):
        session_opts = vars(opts)
        description = "Observation run"
        if "proposal_description" in vars(opts):
            description = opts.proposal_description
        session_opts["description"] = description

    nr_obs_loops = len(obs_plan_params["observation_loop"])
    with start_session(kat.array, **vars(opts)) as session:
        session.standard_setup(**vars(opts))

        # Each observation loop contains a number of observation cycles over LST ranges
        # For a single observation loop, only a start LST and duration is required
        # Target observation loop
        observation_timer = time.time()
        for obs_cntr, observation_cycle in enumerate(
                obs_plan_params["observation_loop"]):
            if nr_obs_loops > 1:
                user_logger.info("Observation loop {} of {}.".format(
                    obs_cntr + 1, nr_obs_loops))
                user_logger.info("Loop LST range {}.".format(
                    observation_cycle["LST"]))
            # Unpack all target information
            if not ("target_list" in observation_cycle.keys()):
                user_logger.error(
                    "No targets provided - stopping script instead of hanging around"
                )
                continue
            obs_targets = observation_cycle["target_list"]
            target_list = obs_targets["target"].tolist()
            # build katpoint catalogues for tidy handling of targets
            catalogue = collect_targets(kat.array, target_list)
            obs_tags = []
            for tgt in obs_targets:
                # catalogue names are no longer unique
                name = tgt["name"]
                # add tag evaluation to identify catalogue targets
                tags = tgt["target"].split(",")[1].strip()
                for cat_tgt in catalogue:
                    if name == cat_tgt.name:
                        if ("special" in cat_tgt.tags
                                or "xephem" in cat_tgt.tags
                                or tags == " ".join(cat_tgt.tags)):
                            tgt["target"] = cat_tgt
                            obs_tags.extend(cat_tgt.tags)
                            break
            obs_tags = list(set(obs_tags))
            cal_tags = [tag for tag in obs_tags if tag[-3:] == "cal"]

            # observer object handle to track the observation timing in a more user
            # friendly way
            #             observer = catalogue._antenna.observer
            ref_antenna = catalogue.antenna
            observer = ref_antenna.observer
            start_datetime = timestamp2datetime(time.time())
            observer.date = ephem.Date(start_datetime)
            user_logger.trace("TRACE: requested start time "
                              "({}) {}".format(
                                  datetime2timestamp(start_datetime),
                                  start_datetime))
            user_logger.trace("TRACE: observer at start\n {}".format(observer))

            # Only observe targets in valid LST range
            if nr_obs_loops > 1 and obs_cntr < nr_obs_loops - 1:
                [start_lst, end_lst] = get_lst(observation_cycle["LST"],
                                               multi_loop=True)
                if end_lst is None:
                    # for multi loop the end lst is required
                    raise RuntimeError(
                        'Multi-loop observations require end LST times')
                next_obs_plan = obs_plan_params["observation_loop"][obs_cntr +
                                                                    1]
                [next_start_lst, next_end_lst] = get_lst(next_obs_plan["LST"])
                user_logger.trace("TRACE: current LST range {}-{}".format(
                    ephem.hours(str(start_lst)), ephem.hours(str(end_lst))))
                user_logger.trace("TRACE: next LST range {}-{}".format(
                    ephem.hours(str(next_start_lst)),
                    ephem.hours(str(next_end_lst))))
            else:
                next_start_lst = None
                next_end_lst = None
                [start_lst, end_lst] = get_lst(observation_cycle["LST"])

            # Verify the observation is in a valid LST range
            # and that it is worth while continuing with the observation
            # Do not use float() values, ephem.hours does not convert as
            # expected
            local_lst = observer.sidereal_time()
            user_logger.trace("TRACE: Local LST {}".format(
                ephem.hours(local_lst)))
            # Only observe targets in current LST range
            log_msg = "Local LST outside LST range {}-{}".format(
                ephem.hours(str(start_lst)), ephem.hours(str(end_lst)))
            if float(start_lst) < end_lst:
                # lst ends before midnight
                if not _same_day(start_lst, end_lst, local_lst):
                    if obs_cntr < nr_obs_loops - 1:
                        user_logger.info(log_msg)
                    else:
                        user_logger.error(log_msg)
                    continue
            else:
                # lst ends after midnight
                if _next_day(start_lst, end_lst, local_lst):
                    if obs_cntr < nr_obs_loops - 1:
                        user_logger.info(log_msg)
                    else:
                        user_logger.error(log_msg)
                    continue

            # Verify that it is worth while continuing with the observation
            # The filter functions uses the current time as timestamps
            # and thus incorrectly set the simulation timestamp
            if not kat.array.dry_run:
                # Quit early if there are no sources to observe
                if len(catalogue.filter(el_limit_deg=opts.horizon)) == 0:
                    raise NoTargetsUpError(
                        "No targets are currently visible - "
                        "please re-run the script later")
                # Quit early if the observation requires all targets to be visible
                if opts.all_up and (len(
                        catalogue.filter(el_limit_deg=opts.horizon)) !=
                                    len(catalogue)):
                    raise NotAllTargetsUpError(
                        "Not all targets are currently visible - please re-run the script"
                        "with --visibility for information")

            # List sources and their associated functions from observation tags
            not_cals_filter_list = []
            for cal_type in cal_tags:
                not_cals_filter_list.append("~{}".format(cal_type))
                cal_array = [cal.name for cal in catalogue.filter(cal_type)]
                if len(cal_array) < 1:
                    continue  # do not display empty tags
                user_logger.info("{} calibrators are {}".format(
                    str.upper(cal_type[:-3]), cal_array))
            user_logger.info("Observation targets are [{}]".format(", ".join([
                repr(target.name)
                for target in catalogue.filter(not_cals_filter_list)
            ])))

            # TODO: setup of noise diode pattern should be moved to sessions
            #  so it happens in the line above
            if "noise_diode" in obs_plan_params:
                nd_setup = obs_plan_params["noise_diode"]
                nd_lead = nd_setup.get('lead_time')

                # Set noise diode period to multiple of correlator integration time.
                if not kat.array.dry_run:
                    cbf_corr = session.cbf.correlator
                    dump_period = cbf_corr.sensor.int_time.get_value()
                else:
                    dump_period = 0.5  # sec
                user_logger.debug(
                    'DEBUG: Correlator integration time {} [sec]'.format(
                        dump_period))

                if "cycle_len" in nd_setup:
                    if (nd_setup['cycle_len'] >= dump_period):
                        cycle_len_frac = nd_setup['cycle_len'] // dump_period
                        nd_setup['cycle_len'] = cycle_len_frac * dump_period
                        msg = ('Set noise diode period '
                               'to multiple of correlator dump period: '
                               'cycle length = {} [sec]'.format(
                                   nd_setup['cycle_len']))
                    else:
                        msg = ('Requested cycle length {}s '
                               '< correlator dump period {}s, '
                               'ND not synchronised with dump edge'.format(
                                   nd_setup['cycle_len'], dump_period))
                    user_logger.warning(msg)
                    noisediode.pattern(
                        kat.array,
                        nd_setup,
                        lead_time=nd_lead,
                    )

            # Adding explicit init after "Capture-init failed" exception was
            # encountered
            session.capture_init()
            user_logger.debug("DEBUG: Initialise capture start with timestamp "
                              "{} ({})".format(int(time.time()),
                                               timestamp2datetime(
                                                   time.time())))

            # Go to first target before starting capture
            user_logger.info("Slewing to first target")
            observe(session, ref_antenna, obs_targets[0], slewonly=True)
            # Only start capturing once we are on target
            session.capture_start()
            user_logger.trace("TRACE: capture start time after slew "
                              "({}) {}".format(time.time(),
                                               timestamp2datetime(
                                                   time.time())))
            user_logger.trace(
                "TRACE: observer after slew\n {}".format(observer))

            done = False
            sanity_cntr = 0
            while not done:
                # small errors can cause an infinite loop here
                # preventing infinite loops
                sanity_cntr += 1
                if sanity_cntr > 100000:
                    user_logger.error("While limit counter has reached {}, "
                                      "exiting".format(sanity_cntr))
                    break

                # Cycle through target list in order listed
                targets_visible = False
                time_remaining = obs_duration
                observation_timer = time.time()
                for tgt_cntr, target in enumerate(obs_targets):
                    katpt_target = target["target"]
                    user_logger.debug("DEBUG: {} {}".format(tgt_cntr, target))
                    user_logger.trace(
                        "TRACE: initial observer for target\n {}".format(
                            observer))
                    # check target visible before doing anything
                    # make sure the target would be visible for the entire duration
                    target_duration = target['duration']
                    visible = True
                    if type(katpt_target.body) is ephem.FixedBody:
                        visible = above_horizon(
                            target=katpt_target.body.copy(),
                            observer=observer.copy(),
                            horizon=opts.horizon,
                            duration=target_duration)
                    if not visible:
                        show_horizon_status = True
                        # warning for cadence targets only when they are due
                        if (target["cadence"] > 0
                                and target["last_observed"] is not None):
                            delta_time = time.time() - target["last_observed"]
                            show_horizon_status = delta_time >= target[
                                "cadence"]
                        if show_horizon_status:
                            user_logger.warn("Target {} below {} deg horizon, "
                                             "continuing".format(
                                                 target["name"], opts.horizon))
                        continue
                    user_logger.trace(
                        "TRACE: observer after horizon check\n {}".format(
                            observer))

                    # check and observe all targets with cadences
                    while_cntr = 0
                    cadence_targets = list(obs_targets)
                    while True:
                        tgt = cadence_target(cadence_targets)
                        if not tgt:
                            break
                        # check enough time remaining to continue
                        if obs_duration > 0 and time_remaining < tgt[
                                "duration"]:
                            done = True
                            break
                        # check target visible before doing anything
                        user_logger.trace("TRACE: cadence"
                                          "target\n{}\n {}".format(
                                              tgt, catalogue[tgt["name"]]))
                        user_logger.trace("TRACE: initial observer for cadence"
                                          "target\n {}".format(observer))
                        user_logger.trace(
                            "TRACE: observer before track\n {}".format(
                                observer))
                        user_logger.trace(
                            "TRACE: target observation # {} last observed "
                            "{}".format(tgt["obs_cntr"], tgt["last_observed"]))
                        cat_target = catalogue[tgt["name"]]
                        if above_horizon(
                                target=cat_target.body,
                                observer=cat_target.antenna.observer.copy(),
                                horizon=opts.horizon,
                                duration=tgt["duration"]):
                            if observe(session, ref_antenna, tgt,
                                       **obs_plan_params):
                                targets_visible += True
                                tgt["obs_cntr"] += 1
                                tgt["last_observed"] = time.time()
                            else:
                                # target not visibile to sessions anymore
                                cadence_targets.remove(tgt)
                            user_logger.trace(
                                "TRACE: observer after track\n {}".format(
                                    observer))
                            user_logger.trace(
                                "TRACE: target observation # {} last observed "
                                "{}".format(tgt["obs_cntr"],
                                            tgt["last_observed"]))
                        else:
                            cadence_targets.remove(tgt)
                        while_cntr += 1
                        if while_cntr > len(obs_targets):
                            break
                    if done:
                        break
                    user_logger.trace(
                        "TRACE: observer after cadence\n {}".format(observer))

                    # observe non cadence target
                    if target["cadence"] < 0:
                        user_logger.trace(
                            "TRACE: normal target\n {}".format(target))
                        user_logger.trace(
                            "TRACE: observer before track\n {}".format(
                                observer))
                        user_logger.trace("TRACE: ts before observe {}".format(
                            time.time()))
                        user_logger.trace("TRACE: target last "
                                          "observed {}".format(
                                              target["last_observed"]))

                        targets_visible += observe(session, ref_antenna,
                                                   target, **obs_plan_params)
                        user_logger.trace(
                            "TRACE: observer after track\n {}".format(
                                observer))
                        user_logger.trace("TRACE: ts after observe {}".format(
                            time.time()))
                        if targets_visible:
                            target["obs_cntr"] += 1
                            target["last_observed"] = time.time()
                        user_logger.trace(
                            "TRACE: target observation # {} last observed "
                            "{}".format(target["obs_cntr"],
                                        target["last_observed"]))
                        user_logger.trace(
                            "TRACE: observer after track\n {}".format(
                                observer))

                    # loop continuation checks
                    delta_time = time.time() - session.start_time
                    user_logger.trace(
                        "TRACE: time elapsed {} sec".format(delta_time))
                    user_logger.trace(
                        "TRACE: total obs duration {} sec".format(
                            obs_duration))
                    if obs_duration > 0:
                        time_remaining = obs_duration - delta_time
                        user_logger.trace(
                            "TRACE: time remaining {} sec".format(
                                time_remaining))

                        next_target = obs_targets[(tgt_cntr + 1) %
                                                  len(obs_targets)]
                        user_logger.trace("TRACE: next target before cadence "
                                          "check:\n{}".format(next_target))
                        # check if there is a cadence target that must be run
                        # instead of next target
                        for next_cadence_tgt_idx in range(
                                tgt_cntr + 1, len(obs_targets)):
                            next_cadence_target = obs_targets[
                                next_cadence_tgt_idx % len(obs_targets)]
                            if next_cadence_target["cadence"] > 0:
                                user_logger.trace(
                                    "TRACE: time needed for next obs "
                                    "{} sec".format(
                                        next_cadence_target["cadence"]))
                                next_target = obs_targets[next_cadence_tgt_idx
                                                          % len(obs_targets)]
                                continue
                        user_logger.trace("TRACE: next target after cadence "
                                          "check:\n{}".format(next_target))
                        user_logger.trace("TRACE: time needed for next obs "
                                          "{} sec".format(
                                              next_target["duration"]))
                        if (time_remaining < 1.0
                                or time_remaining < next_target["duration"]):
                            user_logger.info(
                                "Scheduled observation time lapsed - ending observation"
                            )
                            done = True
                            break

                # during dry-run when sessions exit time is reset so will be incorrect
                # outside the loop
                observation_timer = time.time()

                if obs_duration < 0:
                    user_logger.info(
                        "Observation list completed - ending observation")
                    done = True

                # for multiple loop, check start lst of next loop
                if next_start_lst is not None:
                    check_local_lst = observer.sidereal_time()
                    if (check_local_lst > next_start_lst) or (not _next_day(
                            next_start_lst, next_end_lst, check_local_lst)):
                        user_logger.info("Moving to next LST loop")
                        done = True

                # End if there is nothing to do
                if not targets_visible:
                    user_logger.warning(
                        "No more targets to observe - stopping script "
                        "instead of hanging around")
                    done = True

    user_logger.trace("TRACE: observer at end\n {}".format(observer))
    # display observation cycle statistics
    # currently only available for single LST range observations
    if nr_obs_loops < 2:
        print
        user_logger.info("Observation loop statistics")
        total_obs_time = observation_timer - session.start_time
        if obs_duration < 0:
            user_logger.info("Single run through observation target list")
        else:
            user_logger.info("Desired observation time {:.2f} sec "
                             "({:.2f} min)".format(obs_duration,
                                                   obs_duration / 60.0))
        user_logger.info("Total observation time {:.2f} sec "
                         "({:.2f} min)".format(total_obs_time,
                                               total_obs_time / 60.0))
        if len(obs_targets) > 0:
            user_logger.info("Targets observed :")
            for unique_target in np.unique(obs_targets["name"]):
                cntrs = obs_targets[obs_targets["name"] ==
                                    unique_target]["obs_cntr"]
                durations = obs_targets[obs_targets["name"] ==
                                        unique_target]["duration"]
                if np.isnan(durations).any():
                    user_logger.info("{} observed {} times".format(
                        unique_target, np.sum(cntrs)))
                else:
                    user_logger.info("{} observed for {} sec".format(
                        unique_target, np.sum(cntrs * durations)))
        print
예제 #6
0
    def subarray_setup(self, instrument):
        """Set up the array for observing.

        Include current sensor list in instrument.

        Parameters
        ----------
        instrument: dict
            An object specifying the configuration of the correlator and frontend
            resources to set up telescope for observing
            e.g {pool_resources, product, dump_rate, band}. Where

                pool_resources = ptuse or specific antennas
                product = correlator product
                dump_rate = correlator data dumprate
                band = observing frequency band (l, s, u, x)

        """
        user_logger.trace(self.opts.obs_plan_params["instrument"])
        if self.opts.obs_plan_params["instrument"] is None:
            return

        approved_sb_sensor = self.array.sched.sensor.get("approved_schedule")
        if not approved_sb_sensor:
            user_logger.info(
                "Skipping instrument checks - approved_schedule does not exist"
            )
            return
        approved_sb_sensor_value = approved_sb_sensor.get_value()
        if self.array.sb_id_code not in approved_sb_sensor_value:
            user_logger.info("Skipping instrument checks - {} "
                             "not in approved_schedule".format(
                                 self.array.sb_id_code))
            return

        for key in instrument.keys():
            conf_param = instrument[key]
            user_logger.trace("{}: {}".format(key, conf_param))
            sensor_name = "sub_{}".format(key)
            user_logger.trace("{}".format(sensor_name))
            sub_sensor = self.array.sensor.get(sensor_name).get_value()
            if isinstance(conf_param, list):
                conf_param = set(conf_param)
            if isinstance(sub_sensor, list):
                sub_sensor = set(sub_sensor)
            if key == "product" and conf_param in sub_sensor:
                continue
            elif key == "pool_resources":
                if conf_param == "available":
                    continue
                pool_params = [str_.strip() for str_ in conf_param.split(",")]
                for param in pool_params:
                    if param not in sub_sensor:
                        raise RuntimeError(
                            "Subarray configuration {} error, {} required, "
                            "{} found".format(sensor_name, param, sub_sensor))
            elif key == "dump_rate":
                delta = abs(conf_param - sub_sensor)
                if delta > DUMP_RATE_TOLERANCE:
                    raise RuntimeError(
                        "Subarray configuration {} error, {} required, "
                        "{} found, delta > tolerance ({} > {})".format(
                            sensor_name, conf_param, sub_sensor, delta,
                            DUMP_RATE_TOLERANCE))
            elif conf_param != sub_sensor:
                raise RuntimeError(
                    "Subarray configuration {} error, {} required, "
                    "{} found".format(sensor_name, conf_param, sub_sensor))
예제 #7
0
def pattern(kat,
            nd_setup,
            lead_time=_DEFAULT_LEAD_TIME,
            ):
    """Start background noise diode pattern controlled by digitiser hardware.

    Parameters
    ----------
    kat : session kat container-like object
        Container for accessing KATCP resources allocated to schedule block.
    nd_setup : dict
        Noise diode pattern setup, with keys:
            'antennas':  options are 'all', or 'm062', or ....,
            'cycle_len': the cycle length [sec],
                           - must be less than 20 sec for L-band,
            etc., etc.
    lead_time : float, optional (default = system default lead time)
        Lead time before digitisers pattern is set [sec]

    Returns
    -------
    timestamp : float
        Linux timestamp reported by digitiser
    """

    # nd pattern length [sec]
    max_cycle_len = _get_max_cycle_len(kat)
    if float(nd_setup['cycle_len']) > max_cycle_len:
        msg = 'Maximum cycle length is {} seconds'.format(max_cycle_len)
        raise RuntimeError(msg)

    user_logger.trace('TRACE: max cycle len {}'
                      .format(max_cycle_len))

    # Try to trigger noise diodes on specified antennas in array simultaneously.
    # - add a default lead time to ensure enough time for all digitisers
    #   to be set up
    if lead_time >= max_cycle_len:
        user_logger.error('Nonstandard ND usage: lead time > max cycle len')
        raise RuntimeError('ND pattern setting cannot be achieved')

    start_time = _get_nd_timestamp_(lead_time)
    user_logger.trace('TRACE: desired start_time {} ({})'
                      .format(start_time,
                              time.ctime(start_time)))
    msg = ('Request: Set noise diode pattern to activate at {} '
           '(includes {} sec lead time)'
           .format(start_time,
                   lead_time))
    user_logger.warning(msg)

    nd_antennas = nd_setup['antennas']
    sb_ants = ",".join(str(ant.name) for ant in kat.ants)
    nd_setup['antennas'] = sb_ants
    if nd_antennas == 'all':
        cycle = False
    elif nd_antennas == 'cycle':
        cycle = True
    else:
        cycle = False
        nd_setup['antennas'] = ",".join(
            ant.strip() for ant in nd_antennas.split(",") if ant.strip() in sb_ants
        )
    user_logger.info('Antennas found in subarray, setting ND: {}'
                     .format(nd_setup['antennas']))

    # Noise Diodes are triggered simultaneously
    # on specified antennas in the array
    timestamp = _set_dig_nd_(kat,
                             start_time,
                             nd_setup=nd_setup,
                             cycle=cycle)
    user_logger.trace('TRACE: now {} ({})'
                      .format(time.time(),
                              time.ctime(time.time())))
    user_logger.trace('TRACE: timestamp {} ({})'
                      .format(timestamp,
                              time.ctime(timestamp)))
    wait_time = timestamp - time.time()
    user_logger.trace('TRACE: delta {}'
                      .format(wait_time))
    time.sleep(wait_time)
    user_logger.trace('TRACE: set nd pattern at {}, slept {}'
                      .format(time.time(),
                              wait_time))
    msg = ('Report: Switch noise-diode pattern on at {}'
           .format(timestamp))
    user_logger.info(msg)
    return timestamp
예제 #8
0
def trigger(kat,
            duration=None,
            lead_time=_DEFAULT_LEAD_TIME):
    """Fire the noise diode before track.

    Parameters
    ----------
    kat : session kat container-like object
        Container for accessing KATCP resources allocated to schedule block.
    duration : float, optional (default = None)
        Duration that the noisediode will be active [sec]
    lead_time : float, optional (default = system default lead time)
        Lead time before the noisediode is switched on [sec]
    """

    if duration is None:
        return True  # nothing to do

    msg = ('Firing noise diode for {}s before target observation'
           .format(duration))
    user_logger.info(msg)
    user_logger.info('Add lead time of {}s'
                     .format(lead_time))
    user_logger.debug('DEBUG: issue command to switch ND on @ {}'
                      .format(time.time()))
    if duration > lead_time:
        user_logger.trace('TRACE: Trigger duration > lead_time')
        # allow lead time for all to switch on simultaneously
        # timestamp on = now + lead
        on_time = on(kat, lead_time=lead_time)
        user_logger.debug('DEBUG: on {} ({})'
                          .format(on_time,
                                  time.ctime(on_time)))
        user_logger.debug('DEBUG: fire nd for {}'
                          .format(duration))
        sleeptime = min(duration - lead_time, lead_time)
        user_logger.trace('TRACE: sleep {}'
                          .format(sleeptime))
        off_time = on_time + duration
        user_logger.trace('TRACE: desired off_time {} ({})'
                          .format(off_time,
                                  time.ctime(off_time)))
        user_logger.trace('TRACE: delta {}'
                          .format(off_time - on_time))
        user_logger.debug('DEBUG: sleeping for {} [sec]'
                          .format(sleeptime))
        time.sleep(sleeptime)
        user_logger.trace('TRACE: ts after sleep {} ({})'
                          .format(time.time(),
                                  time.ctime(time.time())))
    else:
        user_logger.trace('TRACE: Trigger duration <= lead_time')
        cycle_len = _get_max_cycle_len(kat)
        nd_setup = {'antennas': 'all',
                    'cycle_len': cycle_len,
                    'on_frac': float(duration) / cycle_len,
                    }
        user_logger.debug('DEBUG: fire nd for {} using pattern'
                          .format(duration))
        on_time = pattern(kat, nd_setup, lead_time=lead_time)
        user_logger.debug('DEBUG: pattern set {} ({})'
                          .format(on_time,
                                  time.ctime(on_time)))
        off_time = _get_nd_timestamp_(lead_time)
        user_logger.trace('TRACE: desired off_time {} ({})'
                          .format(off_time,
                                  time.ctime(off_time)))

    user_logger.debug('DEBUG: off {} ({})'
                      .format(off_time,
                              time.ctime(off_time)))
    off_time = off(kat, timestamp=off_time)
    sleeptime = off_time - time.time()
    user_logger.debug('DEBUG: now {}, sleep {}'
                      .format(time.time(),
                              sleeptime))
    time.sleep(sleeptime)  # default sleep to see for signal to get through
    user_logger.debug('DEBUG: now {}, slept {}'
                      .format(time.time(),
                              sleeptime))
예제 #9
0
def observe(session, target_info, **kwargs):
    """Target observation functionality.

    Parameters
    ----------
    session: `CaptureSession`
    target_info:

    """
    target_visible = False

    target_name = target_info["name"]
    target = target_info["target"]
    duration = target_info["duration"]
    obs_type = target_info["obs_type"]

    # simple way to get telescope to slew to target
    if "slewonly" in kwargs:
        return session.track(target, duration=0.0, announce=False)

    # set noise diode behaviour
    nd_setup = None
    nd_lead = _DEFAULT_LEAD_TIME
    if kwargs.get("noise_diode"):
        nd_setup = kwargs["noise_diode"]
        # user specified lead time
        if "lead_time" in nd_setup:
            nd_lead = nd_setup['lead_time']
        # not a ND pattern
        if "cycle_len" not in nd_setup:
            nd_setup = None

    # implement target specific noise diode behaviour
    nd_period = None
    nd_restore = False
    if target_info["noise_diode"] is not None:
        if "off" in target_info["noise_diode"]:
            user_logger.info('Observation: No ND for target')
            nd_restore = True
            # disable noise diode pattern for target
            noisediode.off(session.kat, lead_time=nd_lead)
        else:
            nd_period = float(target_info["noise_diode"])

    msg = "Initialising {} {} {}".format(obs_type.capitalize(),
                                         ", ".join(target.tags[1:]),
                                         target_name)
    if not np.isnan(duration):  # scan types do not have durations
        msg += " for {} sec".format(duration)
    if np.isnan(duration) or duration > 1:
        user_logger.info(msg)

    # do the different observations depending on requested type
    session.label(obs_type.strip())
    user_logger.trace("TRACE: performing {} observation on {}".format(
        obs_type, target))
    if "scan" in obs_type:  # compensating for ' and spaces around key values
        if "drift_scan" in obs_type:
            scan_func = scans.drift_scan
        # TODO: fix raster scan and remove this scan hack
        elif "forwardscan" in obs_type:
            scan_func = scans.forwardscan
            obs_type = "scan"
        elif "reversescan" in obs_type:
            scan_func = scans.reversescan
            obs_type = "scan"
        elif "return_scan" in obs_type:
            scan_func = scans.return_scan
            obs_type = "scan"
        elif "raster_scan" in obs_type:
            scan_func = scans.raster_scan
        else:
            scan_func = scans.scan
        if obs_type in kwargs:  # user settings other than defaults
            target_visible = scan_func(session,
                                       target,
                                       nd_period=nd_period,
                                       **kwargs[obs_type])
        else:
            target_visible = scan_func(session, target, nd_period=nd_period)
    else:  # track is default
        if nd_period is not None:
            user_logger.trace("TRACE: ts before nd trigger"
                              "{} for {}".format(time.time(), nd_period))
            noisediode.trigger(session.kat,
                               duration=nd_period,
                               lead_time=nd_lead)
            user_logger.trace("TRACE: ts after nd trigger {}".format(
                time.time()))
        user_logger.debug("DEBUG: Starting {}s track on target: "
                          "{} ({})".format(duration, time.time(),
                                           time.ctime(time.time())))
        if session.track(target, duration=duration):
            target_visible = True
    user_logger.trace("TRACE: ts after {} {}".format(obs_type, time.time()))

    if (nd_setup is not None and nd_restore):
        # restore pattern if programmed at setup
        user_logger.info('Observation: Restoring ND pattern')
        noisediode.pattern(
            session.kat,
            nd_setup,
            lead_time=nd_lead,
        )

    return target_visible