From c2c2b9c775b7d29919feea5bdd2411627c4554e8 Mon Sep 17 00:00:00 2001 From: Tom Aldcroft Date: Sun, 19 Nov 2023 06:20:22 -0500 Subject: [PATCH] Apply numpydoc style to docstrings --- docs/conf.py | 7 +- kadi/__init__.py | 4 +- kadi/commands/command_sets.py | 20 +- kadi/commands/commands.py | 19 +- kadi/commands/commands_v1.py | 22 +- kadi/commands/commands_v2.py | 185 +++++++++++----- kadi/commands/core.py | 135 ++++++++---- kadi/commands/observations.py | 154 +++++++++---- kadi/commands/states.py | 385 +++++++++++++++++++++++---------- kadi/commands/utils.py | 19 +- kadi/commands/validate.py | 67 ++++-- kadi/events/models.py | 27 ++- kadi/events/query.py | 20 +- kadi/occweb.py | 18 +- kadi/scripts/update_cmds_v1.py | 39 +++- 15 files changed, 801 insertions(+), 320 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index 42db102f..e8ff857d 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -26,12 +26,17 @@ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' +# Don't show summaries of the members in each class along with the +# class' docstring +numpydoc_show_class_members = False + # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.imgmath', - 'sphinx.ext.viewcode'] + 'sphinx.ext.viewcode', + 'numpydoc'] try: import matplotlib.sphinxext.plot_directive diff --git a/kadi/__init__.py b/kadi/__init__.py index 83942bfe..997e8080 100644 --- a/kadi/__init__.py +++ b/kadi/__init__.py @@ -36,7 +36,9 @@ def test(*args, **kwargs): def create_config_file(overwrite=False): """Create the configuration file for the kadi package. - :param overwrite: bool + Parameters + ---------- + overwrite : bool Force updating the file if it already exists. """ from astropy import config diff --git a/kadi/commands/command_sets.py b/kadi/commands/command_sets.py index cc87e364..a837bff2 100644 --- a/kadi/commands/command_sets.py +++ b/kadi/commands/command_sets.py @@ -23,8 +23,14 @@ def cmd_set_rts(*args, date=None): def cmd_set_obsid(obs_id, date=None): """Return a command set that updates the commanded ObsID. - :param obsid: obsid - :returns: list of command defs suitable for generate_cmds() + Parameters + ---------- + obsid + obsid + + Returns + ------- + list of command defs suitable for generate_cmds() """ return (dict(type="MP_OBSID", tlmsid="COAOSQID", params=dict(ID=obs_id)),) @@ -32,8 +38,14 @@ def cmd_set_obsid(obs_id, date=None): def cmd_set_maneuver(*args, date=None): """Return a command set that initiates a maneuver to the given attitude ``att``. - :param att: attitude compatible with Quat() initializer - :returns: list of command defs suitable for generate_cmds() + Parameters + ---------- + att + attitude compatible with Quat() initializer + + Returns + ------- + list of command defs suitable for generate_cmds() """ att = Quat(args) return ( diff --git a/kadi/commands/commands.py b/kadi/commands/commands.py index e5352973..27b19095 100644 --- a/kadi/commands/commands.py +++ b/kadi/commands/commands.py @@ -32,16 +32,23 @@ def get_cmds(start=None, stop=None, inclusive_stop=False, scenario=None, **kwarg >>> tlmsid='wsvidalldn') cmds = commands.get_cmds(msid='aflcrset') >>> print(cmds) - :param start: DateTime format (optional) Start time, defaults to beginning + Parameters + ---------- + start : DateTime format (optional) Start time, defaults to beginning of available commands (2002:001) - :param stop: DateTime format (optional) Stop time, defaults to end of available + stop : DateTime format (optional) Stop time, defaults to end of available commands - :param inclusive_stop: bool, include commands at exactly ``stop`` if True. - :param scenario: str, None + inclusive_stop + bool, include commands at exactly ``stop`` if True. + scenario : str, None Commands scenario (applicable only for V2 commands) - :param kwargs: key=val keyword argument pairs for filtering + kwargs + key=val keyword argument pairs for filtering - :returns: :class:`~kadi.commands.commands.CommandTable` of commands + Returns + ------- + CommandTable + Commands in the interval and matching the filter criteria. """ commands_version = os.environ.get("KADI_COMMANDS_VERSION", conf.commands_version) if commands_version == "2": diff --git a/kadi/commands/commands_v1.py b/kadi/commands/commands_v1.py index 0b0b3781..aa055bae 100644 --- a/kadi/commands/commands_v1.py +++ b/kadi/commands/commands_v1.py @@ -44,14 +44,20 @@ def get_cmds(start=None, stop=None, inclusive_stop=False, **kwargs): >>> tlmsid='wsvidalldn') cmds = commands.get_cmds(msid='aflcrset') >>> print(cmds) - :param start: DateTime format (optional) Start time, defaults to beginning - of available commands (2002:001) - :param stop: DateTime format (optional) Stop time, defaults to end of available - commands - :param inclusive_stop: bool, include commands at exactly ``stop`` if True. - :param kwargs: key=val keyword argument pairs for filtering - - :returns: :class:`~kadi.commands.commands.CommandTable` of commands + Parameters + ---------- + start : DateTime format (optional) + Start time, defaults to beginning of available commands (2002:001) + stop : DateTime format (optional) + Stop time, defaults to end of available commands + inclusive_stop : bool + Include commands at exactly ``stop`` if True. + **kwargs : dict + key=val keyword argument pairs for filtering + + Returns + ------- + :class:`~kadi.commands.commands.CommandTable` of commands """ out = _find(start, stop, inclusive_stop, IDX_CMDS, PARS_DICT, **kwargs) out.rev_pars_dict = weakref.ref(REV_PARS_DICT) diff --git a/kadi/commands/commands_v2.py b/kadi/commands/commands_v2.py index 18505134..d56d9ee1 100644 --- a/kadi/commands/commands_v2.py +++ b/kadi/commands/commands_v2.py @@ -97,11 +97,16 @@ def _merge_cmds_archive_recent(start, scenario): - CMDS_RECENT cache has been set with that scenario. - Recent commands overlap the cmds archive - :parameter start: CxoTime-like, + Parameters + ---------- + start : CxoTime-like Start time for returned commands - :parameter scenario: str + scenario : str Scenario name - :returns: CommandTable + + Returns + ------- + CommandTable Commands from cmds archive and all recent commands """ cmds_recent = CMDS_RECENT[scenario] @@ -184,21 +189,25 @@ def get_cmds( ) -> CommandTable: """Get commands using loads table, relying entirely on RLTT. - :param start: CxoTime-like + Parameters + ---------- + start : CxoTime-like Start time for cmds - :param stop: CxoTime-like + stop : CxoTime-like Stop time for cmds - :param scenario: str, None + scenario : str, None Scenario name - :param inclusive_stop: bool + inclusive_stop : bool Include commands at exactly ``stop`` if True. - :param loads_stop: CxoTime-like, None + loads_stop : CxoTime-like, None Stop time for loads table (default is all available loads, but useful for development/testing work) - :param **kwargs: dict + **kwargs : dict key=val keyword argument pairs for filtering - :returns: CommandTable + Returns + ------- + CommandTable """ logger.info( f"Getting commands from {CxoTime(start).date} to {CxoTime(stop).date} for {scenario=}" @@ -315,17 +324,21 @@ def update_archive_and_get_cmds_recent( This relies entirely on RLTT and load_events to assemble the commands. - :param scenario: str, None + Parameters + ---------- + scenario : str, None Scenario name - :param lookback: int, Quantity, None + lookback : int, Quantity, None Lookback time from ``stop`` for recent loads. If None, use conf.default_lookback. - :param stop: CxoTime-like, None + stop : CxoTime-like, None Stop time for loads table (default is now + 21 days) - :param cache: bool + cache : bool Cache the result in CMDS_RECENT dict. - :returns: CommandTable + Returns + ------- + CommandTable """ # List of CommandTable objects from loads and cmd_events cmds_list: List[CommandTable] = [] @@ -473,14 +486,21 @@ def add_obs_cmds(cmds, pars_dict, rev_pars_dict, prev_att=None): - obsid: observation ID - starcat_idx: index of starcat in reversed params dict - :param cmds_recent: CommandTable - :param pars_dict: dict + Parameters + ---------- + cmds_recent + CommandTable + pars_dict : dict Dictionary of parameters from the command table. - :param rev_pars_dict: dict + rev_pars_dict : dict Dictionary of parameters from the command table, with keys reversed. - :param prev_att: tuple + prev_att : tuple Continuity attitude. If not supplied the first obs is dropped. - :returns: CommandTable with added OBS commands + + Returns + ------- + CommandTable + Command table with added OBS commands """ # Last command in cmds is the schedule stop time (i.e. obs_stop for the # last observation). @@ -512,8 +532,14 @@ def add_obs_cmds(cmds, pars_dict, rev_pars_dict, prev_att=None): def get_state_cmds(cmds): """Get the state-changing commands need to create LOAD_EVENT OBS commands. - :param cmds: CommandTable of input commands. - :returns: CommandTable of state-changing commands. + Parameters + ---------- + cmds + CommandTable of input commands. + + Returns + ------- + CommandTable of state-changing commands. """ state_tlmsids = [ "AOSTRCAT", @@ -560,10 +586,17 @@ def get_cmds_obs_from_manvrs(cmds, prev_att=None): of the maneuver END for the second pass, where at the point in time of the maneuver end (obs start), all the state-changing commands have occurred. - :param cmds: CommandTable of state-changing commands. - :param prev_att: tuple + Parameters + ---------- + cmds : CommandTable + CommandTable of state-changing commands. + prev_att : tuple Previous attitude (q1, q2, q3, q4) - :returns: CommandTable of OBS commands. + + Returns + ------- + CommandTable + OBS commands. """ targ_att = None npnt_enab = False @@ -666,12 +699,19 @@ def get_cmds_obs_from_manvrs(cmds, prev_att=None): def manvr_duration(q1, q2): """Calculate the duration of a maneuver from two quaternions - This is basically the same as the function in Chandra.Maneuver but + This is basically the same as the function in chandra_maneuver but optimized to work on a single 4-vector quaterion. - :param q1: list of 4 quaternion elements - :param q2: list of 4 quaternion elements - :returns: duration of maneuver in seconds + Parameters + ---------- + q1 + list of 4 quaternion elements + q2 + list of 4 quaternion elements + + Returns + ------- + duration of maneuver in seconds """ # Compute 4th element of delta quaternion q_manvr = q2 / q1 q_manvr_3 = abs(-q2[0] * q1[0] - q2[1] * q1[1] - q2[2] * q1[2] + q2[3] * -q1[3]) @@ -707,12 +747,21 @@ def get_cmds_obs_final(cmds, pars_dict, rev_pars_dict, schedule_stop_time): The observation state is completed by encountering the next transition to NMM or NSM. - :param cmds: CommandTable of state-changing + OBS commands. - :param pars_dict: dict of parameters for commands - :param rev_pars_dict: reversed dict of parameters for commands - :param schedule_stop_time: date of last command - - :returns: CommandTable of OBS commands with all parameters filled in. + Parameters + ---------- + cmds + CommandTable of state-changing + OBS commands. + pars_dict + dict of parameters for commands + rev_pars_dict + reversed dict of parameters for commands + schedule_stop_time + date of last command + + Returns + ------- + CommandTable + OBS commands with all parameters filled in. """ # Initialize state variables. Note that the first OBS command may end up # with bogus values for some of these, but this is OK because of the command @@ -835,19 +884,30 @@ def log_context_obs(cmds, cmd, before=3600, after=3600, log_level="warning"): def is_google_id(scenario): """Return True if scenario appears to be a Google ID. - :param scenario: str, None - :returns: bool + Parameters + ---------- + scenario + str, None + + Returns + ------- + bool """ # Something better?? return scenario is not None and len(scenario) > 35 -def update_cmd_events(scenario=None): +def update_cmd_events(scenario=None) -> Table: """Update local cmd_events.csv from Google Sheets for ``scenario``. - :param scenario: str, None + Parameters + ---------- + scenario : str, None Scenario name - :returns: Table + + Returns + ------- + Table Command events table """ # Named scenarios with a name that isn't "flight" and does not look like a @@ -886,9 +946,15 @@ def update_cmd_events(scenario=None): def get_cmd_events(scenario=None): """Get local cmd_events.csv for ``scenario``. - :param scenario: str, None + Parameters + ---------- + scenario : str, None Scenario name - :returns: Table + + Returns + ------- + out + Table Command events table """ cmd_events_path = paths.CMD_EVENTS_PATH(scenario) @@ -1015,11 +1081,16 @@ def get_load_cmds_from_occweb_or_local( file is downloaded from OCCweb and is then parsed and saved as a gzipped pickle file of the corresponding CommandTable object. - :param dir_year_month: Path + Parameters + ---------- + dir_year_month : Path Path to the directory containing the ``load_name`` directory. - :param load_name: str + load_name : str Load name in the usual format e.g. JAN0521A. - :returns: CommandTable + + Returns + ------- + CommandTable Backstop commands for the load. """ # Determine output file name and make directory if necessary. @@ -1097,18 +1168,20 @@ def update_cmds_archive( This updates the archive though ``stop`` date, where is required that the ``stop`` date is within ``lookback`` days of existing data in the archive. - :param lookback: int, None + Parameters + ---------- + lookback : int, None Number of days to look back to get recent load commands from OCCweb. Default is ``conf.default_lookback`` (currently 30). - :param stop: CxoTime-like, None + stop : CxoTime-like, None Stop date to update the archive to. Default is NOW + 21 days. - :param log_level: int + log_level : int Logging level. Default is ``logging.INFO``. - :param scenario: str, None + scenario : str, None Scenario name for loads and command events - :param data_root: str, Path + data_root : str, Path Root directory where cmds2.h5 and cmds2.pkl are stored. Default is '.'. - :param match_prev_cmds: bool + match_prev_cmds : bool One-time use flag set to True to update the cmds archive near the v1/v2 transition of APR1420B. See ``utils/migrate_cmds_to_cmds2.py`` for details. @@ -1280,8 +1353,14 @@ def convert_aostrcat_to_acatable(params): MINMAG = min mag MAXMAG = max mag - :param params: dict of AOSTRCAT parameters - :returns: ACATable + Parameters + ---------- + params + dict of AOSTRCAT parameters + + Returns + ------- + ACATable """ from proseco.catalog import ACATable diff --git a/kadi/commands/core.py b/kadi/commands/core.py index 48aef0ad..72115b78 100644 --- a/kadi/commands/core.py +++ b/kadi/commands/core.py @@ -106,8 +106,15 @@ def load_name_to_cxotime(name): def vstack_exact(tables): """Stack tables known to have identical types and columns and no metadata. - :param tables: list of tables - :returns: stacked table with same type as first table + Parameters + ---------- + tables : list + List of tables + + Returns + ------- + Table + Stacked table with same type as first table """ new_cols = [] table0 = tables[0] @@ -134,8 +141,14 @@ def read_backstop(backstop): This function is a wrapper around ``get_cmds_from_backstop`` but follows a more typical naming convention. - :param backstop: str or Table - :returns: :class:`~kadi.commands.commands.CommandTable` of commands + Parameters + ---------- + backstop + str or Table + + Returns + ------- + :class:`~kadi.commands.commands.CommandTable` of commands """ return get_cmds_from_backstop(backstop) @@ -147,9 +160,16 @@ def get_cmds_from_backstop(backstop, remove_starcat=False): ``backstop`` can either be a string file name or a backstop table from ``parse_cm.read_backstop``. - :param backstop: str or Table - :param remove_starcat: remove star catalog command parameters (default=False) - :returns: :class:`~kadi.commands.commands.CommandTable` of commands + Parameters + ---------- + backstop + str or Table + remove_starcat + remove star catalog command parameters (default=False) + + Returns + ------- + :class:`~kadi.commands.commands.CommandTable` of commands """ if isinstance(backstop, Path): backstop = str(backstop) @@ -225,23 +245,27 @@ def _find( >>> cmds = commands._find(type='acispkt', tlmsid='wsvidalldn') >>> cmds = commands._find(msid='aflcrset') - :param start: CxoTime format (optional) + Parameters + ---------- + start : CxoTime format (optional) Start time, defaults to beginning of available commands (2002:001) - :param stop: CxoTime format (optional) + stop : CxoTime format (optional) Stop time, defaults to end of available commands - :param include_stop: bool (optional) + include_stop : bool (optional) If True, find commands with ``date <= stop``, otherwise ``date < stop``. - :param idx_cmds: CommandTable-like + idx_cmds : CommandTable-like Table of commands from the commands archive HDF5 file (e.g. ``cmds2.h5``). In reality this is a ``LazyVal`` which encapsulates a ``CommandTable``. - :param pars_dict: dict-like + pars_dict : dict-like Dict mapping a command parameters tuple to the index in the commands archive params pickle file. This is a ``LazyVal`` which encapsulates a dict. - :param **kwargs: dict + **kwargs : dict Additional key=val keyword argument pairs to filter the results. - :returns: ``CommandTable`` of commands + Returns + ------- + CommandTable """ ok = np.ones(len(idx_cmds), dtype=bool) par_ok = np.zeros(len(idx_cmds), dtype=bool) @@ -493,13 +517,18 @@ def find_date(self, date, side="left"): the ``date`` column is a byte string and the astropy unicode machinery ends up getting called a lot in a way that impacts performance badly. - :param date: str, sequence of str + Parameters + ---------- + date : str, sequence of str Date(s) to search for. - :param side: {'left', 'right'}, optional + side : {'left', 'right'}, optional If 'left', the index of the first suitable location found is given. If 'right', return the last such index. If there is no suitable index, return either 0 or N (where N is the length of `a`). - :returns: int + + Returns + ------- + int Index of row(s) corresponding to ``date``. """ if isinstance(date, CxoTime): @@ -548,10 +577,16 @@ def add_cmds(self, cmds, rltt=None): The commands table is maintained in order (date, step, scs). - :param cmds: :class:`~kadi.commands.commands.CommandTable` of commands - :param apply_rltt: bool, optional + Parameters + ---------- + cmds : CommandTable + Commands to add. + apply_rltt : bool, optional Clip existing commands to the RLTT of the new commands. - :returns: :class:`~kadi.commands.commands.CommandTable` of commands + + Returns + ------- + CommandTable """ if rltt is not None: remove_idxs = np.where(self["date"] > rltt)[0] @@ -613,8 +648,14 @@ def as_list_of_dict(self, ska_parsecm=False): - Add ``cmd`` key which is set to the ``type`` key - Make ``params`` keys uppercase. - :param ska_parsecm: bool, make output more Ska.ParseCM compatible - :return: list of dict + Parameters + ---------- + ska_parsecm : bool + Make output more Ska.ParseCM compatible + + Returns + ------- + list of dict """ self.fetch_params() @@ -641,16 +682,22 @@ def pformat_like_backstop( ): """Format the table in a human-readable format that is similar to backstop. - :param show_source: bool, optional + Parameters + ---------- + show_source : bool, optional Show the source (load name) of each command (default=True) - :param show_nonload_meta: bool, optional + show_nonload_meta : bool, optional Show event and event_date for non-load commands (default=True) - :param sort_orbit_events: bool, optional + sort_orbit_events : bool, optional Sort orbit events at same date by event_type (default=False, mostly for testing) - :param max_params_width: int, optional + max_params_width : int, optional Maximum width of parameter values string (default=80) - :returns: list of lines + + Returns + ------- + list + List of lines. """ lines = [] has_params = "params" in self.colnames @@ -726,18 +773,24 @@ def pformat_like_backstop( def pprint_like_backstop(self, *, logger_func=None, logger_text="", **kwargs): """Format the table in a human-readable format that is similar to backstop. - :param logger_func: function, optional + Parameters + ---------- + logger_func : function, optional Function to call with the formatted lines (default is print) - :param show_source: bool, optional + show_source : bool, optional Show the source (load name) of each command (default=True) - :param show_nonload_meta: bool, optional + show_nonload_meta : bool, optional Show event and event_date for non-load commands (default=True) - :param sort_orbit_events: bool, optional + sort_orbit_events : bool, optional Sort orbit events at same date by event_type (default=False, mostly for testing) - :param max_params_width: int, optional + max_params_width : int, optional Maximum width of parameter values string (default=80) - :returns: list of lines + + Returns + ------- + list + List of formatted lines. """ lines = self.pformat_like_backstop(**kwargs) if logger_func is None: @@ -814,14 +867,20 @@ def get_par_idx_update_pars_dict(pars_dict, cmd, params=None, rev_pars_dict=None This code was factored out verbatim from kadi.update_cmds.py. - :param pars_dict: dict of pars tuples - :param cmd: dict or CommandRow + Parameters + ---------- + pars_dict + dict of pars tuples + cmd : dict or CommandRow Command for updated par_idx - :param pars: dict, optional + pars : dict, optional If provided, this is used instead of cmd['params'] - :param rev_pars_dict: dict, optional + rev_pars_dict : dict, optional If provided, also update the reverse dict. - :returns: int + + Returns + ------- + int Params index (value of corresponding pars tuple dict key) """ # Define a consistently ordered tuple that has all command parameter information diff --git a/kadi/commands/observations.py b/kadi/commands/observations.py index 71241e6a..2ccac76a 100644 --- a/kadi/commands/observations.py +++ b/kadi/commands/observations.py @@ -63,9 +63,19 @@ def get_detector_and_sim_offset(simpos): Finds the detector with nominal SIM position closest to ``simpos``. Taken from fot_matlab_tools/MissionScheduling/axafutil/getSIFromPosition.m. - :param aca: ACATable + Parameters + ---------- + aca : ACATable Input star catalog - :param simpos: int, SIM position (steps) + simpos + int, SIM position (steps) + + Returns + ------- + detector : str + Detector name + sim_offset : int + SIM offset (steps) """ from proseco import characteristics_fid as FID @@ -116,7 +126,9 @@ def set_star_ids(aca): This set the ID in-place to the brightest star within 1.5 arcsec of the commanded position. - :param aca: ACATable + Parameters + ---------- + aca : ACATable Input star catalog """ from chandra_aca.transform import radec_to_yagzag @@ -156,8 +168,14 @@ def set_star_ids(aca): def convert_starcat_dict_to_acatable(starcat_dict: dict): """Convert star catalog dict to an ACATable, including obs metadata. - :param starcat_dict: dict of list with starcat values - :returns: ACATable + Parameters + ---------- + starcat_dict + dict of list with starcat values + + Returns + ------- + ACATable """ from proseco.acq import AcqTable from proseco.catalog import ACATable @@ -182,7 +200,7 @@ def convert_starcat_dict_to_acatable(starcat_dict: dict): def convert_aostrcat_to_starcat_dict(params): - """Convert dict of AOSTRCAT parameters to an dict of list for each attribute. + """Convert dict of AOSTRCAT parameters to a dict of list for each attribute. The dict looks like:: @@ -201,9 +219,17 @@ def convert_aostrcat_to_starcat_dict(params): MINMAG = min mag MAXMAG = max mag - :param obs: dict of observation (OBS command) parameters - :param params: dict of AOSTRCAT parameters - :returns: dict of list for each catalog attribute + Parameters + ---------- + obs + dict of observation (OBS command) parameters + params + dict of AOSTRCAT parameters + + Returns + ------- + dict of list + Dict of list keyed on each catalog attribute """ for idx in range(1, 17): if params[f"minmag{idx}"] == params[f"maxmag{idx}"] == 0: @@ -261,17 +287,27 @@ def get_starcats_as_table( >>> obss = obss[~obss['starcat_date'].mask] # keep only obs with starcat >>> guides = table.join(guides, obss, keys=['starcat_date', 'obsid']) - :param start: CxoTime-like, None Start time (default=beginning of commands) - :param stop: CxoTime-like, None Stop time (default=end of commands) - :param obsid: int, None ObsID - :param unique: bool, if True return remove duplicate entries - :param scenario: str, None Scenario - :param cmds: CommandTable, None Use this command table instead of querying - the archive. - :param starcat_date: CxoTime-like, None + Parameters + ---------- + start : CxoTime-like, None + Start time (default=beginning of commands) + stop : CxoTime-like, None + Stop time (default=end of commands) + obsid : int, None + ObsID + unique : bool + If True return remove duplicate entries + scenario : str, None + Scenario + cmds : CommandTable, None + Use this command table instead of querying the archive. + starcat_date : CxoTime-like, None Date of the observation's star catalog - :returns: astropy ``Table`` star catalog entries for matching observations. + Returns + ------- + Table + Star catalog entries for matching observations. """ starcats = get_starcats( obsid=obsid, @@ -367,19 +403,29 @@ def get_starcats( 1 10 31982136 ACQ 6x6 10.19 11.70 562.06 -186.39 20 1 2 11 32375384 ACQ 6x6 9.79 11.30 1612.28 -428.24 20 1] - :param start: CxoTime-like, None Start time (default=beginning of commands) - :param stop: CxoTime-like, None Stop time (default=end of commands) - :param obsid: int, None ObsID - :param scenario: str, None Scenario - :param cmds: CommandTable, None Use this command table instead of querying - the archive. - :param as_dict: bool, False Return a list of dict instead of a list - of ACATable objects. - :param starcat_date: CxoTime-like, None + Parameters + ---------- + start : CxoTime-like, None + Start time (default=beginning of commands) + stop : CxoTime-like, None + Stop time (default=end of commands) + obsid : int, None + ObsID + scenario : str, None + Scenario + cmds : CommandTable, None + Use this command table instead of querying the archive. + as_dict : bool, False + Return a list of dict instead of a list of ACATable objects. + starcat_date : CxoTime-like, None Date of the observation's star catalog - :param show_progress: bool, + show_progress : bool Show progress bar for long queries (default=False) - :returns: list of star catalogs (ACATable or dict) for matching observations. + + Returns + ------- + list + List of star catalogs (ACATable or dict) for matching observations. """ import shelve from contextlib import ExitStack @@ -515,15 +561,25 @@ def get_observations( 'starcat_idx': 171677, 'source': 'DEC3021A'}] - :param start: CxoTime-like, None Start time (default=beginning of commands) - :param stop: CxoTime-like, None Stop time (default=end of commands) - :param obsid: int, None ObsID - :param scenario: str, None Scenario - :param cmds: CommandTable, None Use this command table instead of querying - the archive. - :param starcat_date: CxoTime-like, None Date of the observation's star - catalog - :returns: list of dict Observation parameters for matching observations. + Parameters + ---------- + start : CxoTime-like, None + Start time (default=beginning of commands) + stop : CxoTime-like, None + Stop time (default=end of commands) + obsid : int, None + ObsID + scenario : str, None + Scenario + cmds : CommandTable, None + Use this command table instead of querying the archive + starcat_date : CxoTime-like, None + Date of the observation's star catalog + + Returns + ------- + list of dict + Observation parameters for matching observations. """ from kadi.commands.commands_v2 import get_cmds @@ -593,13 +649,21 @@ def get_agasc_cone_fast(ra, dec, radius=1.5, date=None, matlab_pm_bug=False): This is a fast version of agasc.get_agasc_cone() that keeps the key columns in memory instead of accessing the H5 file each time. - :param dec: Declination (deg) - :param radius: Cone search radius (deg) - :param date: Date for proper motion (default=Now) - :param matlab_pm_bug: bool Apply MATLAB proper motion bug prior to - the MAY2118A loads (default=False) - - :returns: astropy Table of AGASC entries + Parameters + ---------- + dec : float + Declination (deg) + radius : float + Cone search radius (deg) + date : CxoTime-like, None + Date for proper motion (default=Now) + matlab_pm_bug : bool + Apply MATLAB proper motion bug prior to the MAY2118A loads (default=False) + + Returns + ------- + Table + Table of AGASC entries """ global STARS_AGASC diff --git a/kadi/commands/states.py b/kadi/commands/states.py index 977211da..7e512cfd 100644 --- a/kadi/commands/states.py +++ b/kadi/commands/states.py @@ -174,9 +174,15 @@ def get_state_changing_commands(cls, cmds): available command parameters, and ``match_value`` is either the required value or a list of required values (where at least one must match). - :param cmds: commands (:class:`~kadi.commands.commands.CommandTable`) - - :returns: subset of ``cmds`` relevant for this Transition class (CmdList) + Parameters + ---------- + cmds : CommandTable + Input commands + + Returns + ------- + CommandTable + Subset of ``cmds`` relevant for this Transition class """ # First filter on command attributes. These ok = np.ones(len(cmds), dtype=bool) @@ -274,12 +280,20 @@ def set_transitions(cls, transitions_dict, cmds, start, stop): """ Set transitions for a Table of commands ``cmds``. - :param transitions_dict: global dict of transitions (updated in-place) - :param cmds: commands (CmdList) - :param start: start time for states - :param stop: stop time for states - - :returns: None + Parameters + ---------- + transitions_dict + global dict of transitions (updated in-place) + cmds + commands (CmdList) + start + start time for states + stop + stop time for states + + Returns + ------- + None """ state_cmds = cls.get_state_changing_commands(cmds) vals = cls.transition_val @@ -313,12 +327,20 @@ def set_transitions(cls, transitions_dict, cmds, start, stop): """ Set transitions for a Table of commands ``cmds``. - :param transitions_dict: global dict of transitions (updated in-place) - :param cmds: commands (CmdList) - :param start: start time for states - :param stop: stop time for states - - :returns: None + Parameters + ---------- + transitions_dict + global dict of transitions (updated in-place) + cmds + commands (CmdList) + start + start time for states + stop + stop time for states + + Returns + ------- + None """ # cmds.rev_pars_dict is either None or a weakref to a dict rev_pars_dict = rpd() if (rpd := cmds.rev_pars_dict) else None @@ -470,12 +492,20 @@ def set_transitions(cls, transitions_dict, cmds, start, stop): """ Set transitions for a Table of commands ``cmds``. - :param transitions_dict: global dict of transitions (updated in-place) - :param cmds: commands (CmdList) - :param start: start time for states - :param stop: stop time for states - - :returns: None + Parameters + ---------- + transitions_dict + global dict of transitions (updated in-place) + cmds + commands (CmdList) + start + start time for states + stop + stop time for states + + Returns + ------- + None """ state_cmds = cls.get_state_changing_commands(cmds) vals = cls.transition_val @@ -756,12 +786,20 @@ def set_transitions(cls, transitions_dict, cmds, start, stop): """ Set transitions for a Table of commands ``cmds``. - :param transitions_dict: global dict of transitions (updated in-place) - :param cmds: commands (CmdList) - :param start: start time for states - :param stop: stop time for states - - :returns: None + Parameters + ---------- + transitions_dict + global dict of transitions (updated in-place) + cmds + commands (CmdList) + start + start time for states + stop + stop time for states + + Returns + ------- + None """ # Preselect only commands that might have an impact here. state_cmds = cls.get_state_changing_commands(cmds) @@ -797,12 +835,20 @@ def set_transitions(cls, transitions_dict, cmds, start, stop): """ Set transitions for a Table of commands ``cmds``. - :param transitions_dict: global dict of transitions (updated in-place) - :param cmds: commands (CmdList) - :param start: start time for states - :param stop: stop time for states - - :returns: None + Parameters + ---------- + transitions_dict + global dict of transitions (updated in-place) + cmds + commands (CmdList) + start + start time for states + stop + stop time for states + + Returns + ------- + None """ # Preselect only commands that might have an impact here. state_cmds = cls.get_state_changing_commands(cmds) @@ -837,12 +883,20 @@ def set_transitions(cls, transitions, cmds, start, stop): """ Set transitions for a Table of commands ``cmds``. - :param transitions_dict: global dict of transitions (updated in-place) - :param cmds: commands (CmdList) - :param start: start time for states - :param stop: stop time for states - - :returns: None + Parameters + ---------- + transitions_dict + global dict of transitions (updated in-place) + cmds + commands (CmdList) + start + start time for states + stop + stop time for states + + Returns + ------- + None """ state_cmds = cls.get_state_changing_commands(cmds) @@ -958,12 +1012,20 @@ def set_transitions(cls, transitions_dict, cmds, start, stop): """ Set transitions for a Table of commands ``cmds``. - :param transitions_dict: global dict of transitions (updated in-place) - :param cmds: commands (CmdList) - :param start: start time for states - :param stop: stop time for states - - :returns: None + Parameters + ---------- + transitions_dict + global dict of transitions (updated in-place) + cmds + commands (CmdList) + start + start time for states + stop + stop time for states + + Returns + ------- + None """ state_cmds = cls.get_state_changing_commands(cmds) @@ -991,12 +1053,20 @@ def set_transitions(cls, transitions_dict, cmds, start, stop): """ Set transitions for a Table of commands ``cmds``. - :param transitions_dict: global dict of transitions (updated in-place) - :param cmds: commands (CmdList) - :param start: start time for states - :param stop: stop time for states - - :returns: None + Parameters + ---------- + transitions_dict + global dict of transitions (updated in-place) + cmds + commands (CmdList) + start + start time for states + stop + stop time for states + + Returns + ------- + None """ # np.ceil is used here to get 'times' between start/stop at even # increments of "sample_time" so that the commands will be at the same @@ -1020,10 +1090,16 @@ def update_sun_vector_state(cls, date, transitions, state, idx): This will potentially update the ``pitch`` and ``off_nominal`` states if pcad_mode is NPNT. - :param date: date (str) - :param transitions: global list of transitions - :param state: current state (dict) - :param idx: current index into transitions + Parameters + ---------- + date + date (str) + transitions + global list of transitions + state + current state (dict) + idx + current index into transitions """ if state["pcad_mode"] == "NPNT": q_att = Quat([state[qc] for qc in QUAT_COMPS]) @@ -1067,12 +1143,20 @@ def set_transitions(cls, transitions_dict, cmds, start, stop): """ Set transitions for a Table of commands ``cmds``. - :param transitions_dict: global dict of transitions (updated in-place) - :param cmds: commands (CmdList) - :param start: start time for states - :param stop: stop time for states - - :returns: None + Parameters + ---------- + transitions_dict + global dict of transitions (updated in-place) + cmds + commands (CmdList) + start + start time for states + stop + stop time for states + + Returns + ------- + None """ state_cmds = cls.get_state_changing_commands(cmds) @@ -1135,12 +1219,20 @@ def set_transitions(cls, transitions, cmds, start, stop): """ Set transitions for a Table of commands ``cmds``. - :param transitions_dict: global dict of transitions (updated in-place) - :param cmds: commands (CmdList) - :param start: start time for states - :param stop: stop time for states - - :returns: None + Parameters + ---------- + transitions_dict + global dict of transitions (updated in-place) + cmds + commands (CmdList) + start + start time for states + stop + stop time for states + + Returns + ------- + None """ state_cmds = cls.get_state_changing_commands(cmds) @@ -1315,8 +1407,10 @@ def decode_power(mnem): 'feps': '1 2 3 4 5 ', 'vid_board': 1} - :param mnem: power command string - + Parameters + ---------- + mnem + power command string """ fep_info = { "fep_count": 0, @@ -1380,12 +1474,20 @@ def set_transitions(cls, transitions, cmds, start, stop): """ Set transitions for a Table of commands ``cmds``. - :param transitions_dict: global dict of transitions (updated in-place) - :param cmds: commands (CmdList) - :param start: start time for states - :param stop: stop time for states - - :returns: None + Parameters + ---------- + transitions_dict + global dict of transitions (updated in-place) + cmds + commands (CmdList) + start + start time for states + stop + stop time for states + + Returns + ------- + None """ state_cmds = cls.get_state_changing_commands(cmds) for cmd in state_cmds: @@ -1446,12 +1548,20 @@ def set_transitions(cls, transitions, cmds, start, stop): """ Set transitions for a Table of commands ``cmds``. - :param transitions_dict: global dict of transitions (updated in-place) - :param cmds: commands (CmdList) - :param start: start time for states - :param stop: stop time for states - - :returns: None + Parameters + ---------- + transitions_dict + global dict of transitions (updated in-place) + cmds + commands (CmdList) + start + start time for states + stop + stop time for states + + Returns + ------- + None """ state_cmds = cls.get_state_changing_commands(cmds) for cmd in state_cmds: @@ -1500,10 +1610,16 @@ def get_transitions_list(cmds, state_keys, start, stop, continuity=None): If ``state_keys`` is None then all known state keys are included. - :param cmds: CmdList with spacecraft commands - :param state_keys: desired state keys (None, str, or list) + Parameters + ---------- + cmds + CmdList with spacecraft commands + state_keys + desired state keys (None, str, or list) - :returns: list of dict (transitions), set of transition classes + Returns + ------- + list of dict (transitions), set of transition classes """ # To start, collect transitions in a dict keyed by date. This auto-initializes # a dict whenever a new date is used, allowing (e.g.) a single step of:: @@ -1549,11 +1665,18 @@ def add_transition(transitions, idx, transition): function to generate downstream transitions. The ManeuverTransition class is the canonical example. - :param transitions: global list of transition dicts - :param idx: current index into transitions in state processing - :param transition: transition to add (dict) - - :returns: None + Parameters + ---------- + transitions + global list of transition dicts + idx + current index into transitions in state processing + transition + transition to add (dict) + + Returns + ------- + None """ # Prevent adding command before current command since the command # interpreter is a one-pass process. @@ -1609,16 +1732,28 @@ def get_states( ``reduce_states()`` function separately to reduce to only the desired state keys. - :param start: start of states (optional, DateTime compatible) - :param stop: stop of states (optional, DateTime compatible) - :param state_keys: state keys of interest (optional, list or str or None) - :param cmds: input commands (optional, CmdList, CommandTable) - :param continuity: initial state (optional, dict) - :param reduce: call reduce_states() on output - :param merge_identical: merge identical states (see reduce_states() docs) - :param scenario: commands archive scenario to use - - :returns: astropy Table of states + Parameters + ---------- + start + start of states (optional, DateTime compatible) + stop + stop of states (optional, DateTime compatible) + state_keys + state keys of interest (optional, list or str or None) + cmds + input commands (optional, CmdList, CommandTable) + continuity + initial state (optional, dict) + reduce + call reduce_states() on output + merge_identical + merge identical states (see reduce_states() docs) + scenario + commands archive scenario to use + + Returns + ------- + astropy Table of states """ # Define complete list of column names for output table corresponding to # each state key. Maintain original order and uniqueness of keys. @@ -1768,12 +1903,20 @@ def reduce_states(states, state_keys, merge_identical=False, all_keys=False) -> However, if ``merge_identical`` is True then adacent states with identical values will be merged. - :param states: table of states - :param state_keys: notice transitions in this list of state keys - :param merge_identical: merge adjacent identical states - :param all_keys: if True, then all state keys are included in the output - - :returns: Table of reduced states + Parameters + ---------- + states + table of states + state_keys + notice transitions in this list of state keys + merge_identical + merge adjacent identical states + all_keys + if True, then all state keys are included in the output + + Returns + ------- + Table of reduced states """ if not isinstance(states, Table): states = Table(states) @@ -1850,12 +1993,20 @@ def get_continuity( is used. This corresponds to the "classic" Chandra commanded states (obsid, ACIS, PCAD, and mechanisms). - :param date: date (DateTime compatible, default=NOW) - :param state_keys: list of state keys or str (one state key) or None - :param lookbacks: list of lookback times in days (default=[7, 30, 180, 1000]) - :param scenario: commands archive scenario (default=None) - - :returns: dict of state values + Parameters + ---------- + date + date (DateTime compatible, default=NOW) + state_keys + list of state keys or str (one state key) or None + lookbacks + list of lookback times in days (default=[7, 30, 180, 1000]) + scenario + commands archive scenario (default=None) + + Returns + ------- + dict of state values """ if isinstance(state_keys, str): state_keys = [state_keys] @@ -1965,10 +2116,16 @@ def get_continuity( def interpolate_states(states, times): """Interpolate ``states`` table at given times. - :param states: states (astropy states Table) - :param times: times (np.array or any DateTime compatible input) + Parameters + ---------- + states + states (astropy states Table) + times + times (np.array or any DateTime compatible input) - :returns: ``states`` view at ``times`` + Returns + ------- + ``states`` view at ``times`` """ from astropy.table import Column diff --git a/kadi/commands/utils.py b/kadi/commands/utils.py index 1708446c..6fe4a0d7 100644 --- a/kadi/commands/utils.py +++ b/kadi/commands/utils.py @@ -226,11 +226,20 @@ def fill_gaps_with_nan(times: list, vals: list, max_gap: float, dt: float = 0.00 times = [1, 2, 20, 21, 22] => [1, 2, 2.001, 19.999, 20, 21, 22] vals = [1, 2, 3, 4, 5] => [1.0, 2.0, NaN, NaN, 3.0, 4.0, 5.0] - :param times: times - :param vals: values - :param max_gap: maximum gap in seconds - :param dt: time delta to use for filling gaps - :returns: times, vals with gaps filled with NaNs + Parameters + ---------- + times + times + vals + values + max_gap + maximum gap in seconds + dt + time delta to use for filling gaps + + Returns + ------- + times, vals with gaps filled with NaNs """ times = np.asarray(times, dtype=float) vals = np.asarray(vals, dtype=float) diff --git a/kadi/commands/validate.py b/kadi/commands/validate.py index 2d772762..0656445a 100644 --- a/kadi/commands/validate.py +++ b/kadi/commands/validate.py @@ -119,9 +119,14 @@ class Validate(ABC): def __init__(self, stop=None, days: float = 14, no_exclude: bool = False): """Base class for validation. - :param stop: stop time for validation - :param days: number of days for validation - :param no_exclude: if True then do not exclude any data (for testing) + Parameters + ---------- + stop + stop time for validation + days + number of days for validation + no_exclude + if True then do not exclude any data (for testing) """ self.stop = CxoTime(stop) self.days = days @@ -435,7 +440,9 @@ def get_plot_html(self, show=False) -> str: def get_context(self) -> dict: """Get the standard context for a jinja2 template. - :returns: dict + Returns + ------- + dict """ title = f"{self.plot_attrs.title} (state name = {self.state_name!r})" context = {} @@ -451,9 +458,17 @@ def get_html( ) -> str: """Get HTML for validator including section header, violations, and plot - :param context: optional dict of context for jinja2 template - :param template_text: optional Jinja2 template text - :returns: HTML string + Parameters + ---------- + context + optional dict of context for jinja2 template + template_text + optional Jinja2 template text + + Returns + ------- + str + HTML string """ if context is None: context = self.get_context() @@ -739,10 +754,19 @@ def get_states(start: CxoTimeLike, stop: CxoTimeLike, state_keys: list) -> Table This is a thin wrapper around kadi.commands.states.get_states() that reduces the output time span slightly to ensure telemetry interpolation works. - :param start: start date (CxoTime-like) - :param stop: stop date (CxoTime-like) - :param state_keys: list of state keys to get - :returns: Table of states + Parameters + ---------- + start + start date (CxoTime-like) + stop + stop date (CxoTime-like) + state_keys + list of state keys to get + + Returns + ------- + Table + States in the interval """ from kadi.commands.states import get_states as get_states_kadi @@ -776,12 +800,21 @@ def get_index_page_html( ): """Make a simple HTML page with all the validation plots and information. - :param stop: stop time for validation interval (CxoTime-like, default=now) - :param days: length of validation interval (days) - :param states: list of states to validate (default=all) - :param no_exclude: if True then do not exclude intervals (default=False) - - :returns: HTML string + Parameters + ---------- + stop + stop time for validation interval (CxoTime-like, default=now) + days + length of validation interval (days) + states + list of states to validate (default=all) + no_exclude + if True then do not exclude intervals (default=False) + + Returns + ------- + str + HTML string """ validators = [] violations = [] diff --git a/kadi/events/models.py b/kadi/events/models.py index 13c66597..ca62f2ba 100644 --- a/kadi/events/models.py +++ b/kadi/events/models.py @@ -126,7 +126,9 @@ def get_event_models(baseclass=None): Get all Event models that represent actual events (and are not base or meta classes). - :returns: dict of {model_name:ModelClass, ...} + Returns + ------- + dict of {model_name:ModelClass, ...} """ import inspect @@ -148,9 +150,12 @@ def fuzz_states(states, t_fuzz): other. Logical intervals are just the subset of states with 'val' equal to a particular value. - :param states: table of states or intervals - :param t_fuzz: fuzz time in seconds - :returns fuzzed_states: table + Parameters + ---------- + states + table of states or intervals + t_fuzz : fuzz time in seconds + :returns fuzzed_states: table """ done = False state_has_val = "val" in states.dtype.names @@ -505,7 +510,9 @@ def get_obsid(self): Typically this is the obsid at the start of the event, but for maneuvers it is the obsid at the end of the maneuver. - :returns: obsid + Returns + ------- + obsid """ from . import query @@ -641,8 +648,14 @@ def get_state_times_bools(cls, event_msidset): desired state for this event type. The default is when ``event_msid == cls.event_val``, but subclasses may override this method. - :param event_msid: fetch.MSID object - :returns: boolean ndarray + Parameters + ---------- + event_msid + fetch.MSID object + + Returns + ------- + boolean ndarray """ event_msid = event_msidset[cls.event_msids[0]] bools = event_msid.vals == cls.event_val diff --git a/kadi/events/query.py b/kadi/events/query.py index 1093069c..05882a54 100644 --- a/kadi/events/query.py +++ b/kadi/events/query.py @@ -289,12 +289,20 @@ def filter(self, start=None, stop=None, obsid=None, subset=None, **kwargs): [1]: https://docs.djangoproject.com/en/3.1/topics/db/queries/ [2]: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#field-lookups - :param start: start time (DateTime compatible format) - :param stop: stop time (DateTime compatible format) - :param obsid: obsid for event - :param subset: subset of matching events that are output - - :returns: Django query set with matching events + Parameters + ---------- + start + start time (DateTime compatible format) + stop + stop time (DateTime compatible format) + obsid + obsid for event + subset + subset of matching events that are output + + Returns + ------- + Django query set with matching events """ cls = self.cls objs = cls.objects.all() diff --git a/kadi/occweb.py b/kadi/occweb.py index 164c5961..19e284a6 100644 --- a/kadi/occweb.py +++ b/kadi/occweb.py @@ -310,17 +310,23 @@ def get_occweb_dir(path, timeout=30, cache=False, user=None, password=None): credentials are stored in the file ``~/.netrc``. See the ``Ska.ftp`` package for details. - :param path: str, Path + Parameters + ---------- + path : str, Path Relative path on OCCweb - :param timeout: int + timeout : int Timeout in seconds for the request - :param cache: bool + cache : bool If True, cache the result and check cache for subsequent calls - :param user: str, optional + user : str, optional Username for OCCweb authentication - :param password: str, optional + password : str, optional Password for OCCweb authentication - :returns: astropy Table + + Returns + ------- + out + astropy Table Table of directory entries """ html = get_occweb_page(path, timeout=timeout, cache=cache) diff --git a/kadi/scripts/update_cmds_v1.py b/kadi/scripts/update_cmds_v1.py index 00d9fb98..e4f422ff 100644 --- a/kadi/scripts/update_cmds_v1.py +++ b/kadi/scripts/update_cmds_v1.py @@ -132,11 +132,18 @@ def _tl_to_bs_cmds(tl_cmds, tl_id, db): Ska.ParseCM.read_backstop(). This includes reading parameter values from the ``db``. - :param tl_cmds: numpy recarray of commands from timeline load segment - :param tl_id: timeline id - :param db: Ska.DBI db object - - :returns: list of command dicts + Parameters + ---------- + tl_cmds + numpy recarray of commands from timeline load segment + tl_id + timeline id + db + Ska.DBI db object + + Returns + ------- + list of command dicts """ bs_cmds = [dict((col, row[col]) for col in tl_cmds.dtype.names) for row in tl_cmds] cmd_index = dict((x["id"], x) for x in bs_cmds) @@ -535,8 +542,15 @@ def parse_params(paramstr): Parameter values are cast to the first type (int, float, or str) that succeeds. - :param paramstr: Comma separated string of key=val pairs - :rtype: dict of key=val pairs + Parameters + ---------- + paramstr + Comma separated string of key=val pairs + + Returns + ------- + dict + Dict of key=val pairs """ params = {} for opt in paramstr.split(","): @@ -557,8 +571,15 @@ def read_backstop(filename): actual string with comma-separated parameters and ``params`` is the corresponding dict of key=val pairs. - :param filename: Backstop file name - :returns: list of dict for each command + Parameters + ---------- + filename + Backstop file name + + Returns + ------- + list of dict + List of dict for each command """ bs = [] for bs_line in open(filename):