Skip to content

Commit

Permalink
Merge pull request #268 from sot/ruff
Browse files Browse the repository at this point in the history
Use ruff for linting and formatting
  • Loading branch information
taldcroft authored Nov 11, 2023
2 parents 11b8177 + d923425 commit 44a63c6
Show file tree
Hide file tree
Showing 24 changed files with 522 additions and 358 deletions.
21 changes: 0 additions & 21 deletions .github/workflows/flake8.yml

This file was deleted.

10 changes: 10 additions & 0 deletions .github/workflows/python-formatting.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
name: check format using ruff
on: [push]
jobs:
ruff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: chartboost/ruff-action@v1
with:
args: format --check
8 changes: 8 additions & 0 deletions .github/workflows/python-linting.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
name: lint code using ruff
on: [push]
jobs:
ruff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: chartboost/ruff-action@v1
19 changes: 8 additions & 11 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
repos:
- repo: https://github.com/psf/black
rev: 23.1.0
hooks:
- id: black
language_version: python3.10

- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
name: isort (python)
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.1.5
hooks:
# Run the linter.
- id: ruff
# Run the formatter.
- id: ruff-format
4 changes: 2 additions & 2 deletions kadi/commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,5 +71,5 @@ class Conf(ConfigNamespace):
conf = Conf()


from .commands import * # noqa
from .core import * # noqa
from .commands import *
from .core import *
5 changes: 2 additions & 3 deletions kadi/commands/command_sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

import astropy.units as u
from cxotime import CxoTime
from ska_helpers.utils import convert_to_int_float_str
from Quaternion import Quat
from ska_helpers.utils import convert_to_int_float_str

from kadi.commands.core import CommandTable

Expand All @@ -30,8 +30,7 @@ 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``.
"""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()
Expand Down
16 changes: 9 additions & 7 deletions kadi/commands/commands_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ def get_matching_block_idx_simple(cmds_recent, cmds_arch, min_match):


def get_cmds(
start=None, stop=None, inclusive_stop=False, scenario=None, **kwargs
start=None, stop=None, *, inclusive_stop=False, scenario=None, **kwargs
) -> CommandTable:
"""Get commands using loads table, relying entirely on RLTT.
Expand All @@ -201,7 +201,8 @@ def get_cmds(
:returns: CommandTable
"""
logger.info(
f"Getting commands from {CxoTime(start).date} to {CxoTime(stop).date} for {scenario=}")
f"Getting commands from {CxoTime(start).date} to {CxoTime(stop).date} for {scenario=}"
)
scenario = os.environ.get("KADI_SCENARIO", scenario)
start = CxoTime("1999:001" if start is None else start)
stop = (CxoTime.now() + 1 * u.year) if stop is None else CxoTime(stop)
Expand Down Expand Up @@ -286,7 +287,8 @@ def get_cmds(
# 4 weeks of weekly loads)?". Imagine these inputs:
#
# start = Apr-02-2022
# Loads = APR0122 (Never run due to anomaly), APR0622 (replan), APR0822, APR1522, APR2222
# Loads = APR0122 (Never run due to anomaly), APR0622 (replan), APR0822, APR1522,
# APR2222
# cmds_recent.meta["loads_start"] = Apr-01-2022 (first command in APR0122 approx)
#
# So what we care about is the first command in the applicable loads in the time
Expand Down Expand Up @@ -427,7 +429,7 @@ def update_archive_and_get_cmds_recent(
# Apply end SCS from these commands to the current running loads.
# Remove commands with date greater than end SCS date. In most
# cases this does not cut anything.
for jj in range(0, ii):
for jj in range(ii):
prev_cmds = cmds_list[jj]
# First check for any overlap since prev_cmds is sorted by date.
if len(prev_cmds) > 0 and prev_cmds["date"][-1] > date_end:
Expand Down Expand Up @@ -692,8 +694,8 @@ def manvr_duration(q1, q2):
if eps < 0:
eps = 0

Tm = 4 * MANVR_DELTA + 2 * eps + tau
return Tm
tm = 4 * MANVR_DELTA + 2 * eps + tau
return tm


def get_cmds_obs_final(cmds, pars_dict, rev_pars_dict, schedule_stop_time):
Expand Down Expand Up @@ -1005,7 +1007,7 @@ def clean_loads_dir(loads):


def get_load_cmds_from_occweb_or_local(
dir_year_month=None, load_name=None, use_ska_dir=False
dir_year_month=None, load_name=None, *, use_ska_dir=False
) -> CommandTable:
"""Get the load cmds (backstop) for ``load_name`` within ``dir_year_month``
Expand Down
65 changes: 30 additions & 35 deletions kadi/commands/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
logger = logging.getLogger(__name__)


class LazyVal(object):
class LazyVal:
def __init__(self, load_func):
self._load_func = load_func

Expand Down Expand Up @@ -87,7 +87,7 @@ def load_pars_dict(version=None, file=None):
return pars_dict


@functools.lru_cache()
@functools.lru_cache
def load_name_to_cxotime(name):
"""Convert load name to date"""
mon = name[:3].capitalize()
Expand Down Expand Up @@ -142,8 +142,10 @@ def read_backstop(backstop):

def get_cmds_from_backstop(backstop, remove_starcat=False):
"""
Initialize a ``CommandTable`` from ``backstop``, which can either
be a string file name or a backstop table from ``parse_cm.read_backstop``.
Initialize a ``CommandTable`` from ``backstop``.
``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)
Expand All @@ -159,9 +161,7 @@ def get_cmds_from_backstop(backstop, remove_starcat=False):
elif isinstance(backstop, Table):
bs = backstop
else:
raise ValueError(
f"`backstop` arg must be a string filename or " f"a backstop Table"
)
raise ValueError("`backstop` arg must be a string filename or a backstop Table")

n_bs = len(bs)
out = {}
Expand Down Expand Up @@ -355,7 +355,7 @@ def keys(self):
return out + params

def values(self):
return [self[key] for key in self.keys()]
return [self[key] for key in self.keys()] # noqa: SIM118

def items(self):
return [(key, value) for key, value in zip(self.keys(), self.values())]
Expand Down Expand Up @@ -384,8 +384,10 @@ def __sstr__(self):

class CommandTable(Table):
"""
Astropy Table subclass that is specialized to handle commands via a
``params`` column that is expected to be ``None`` or a dict of params.
Astropy Table subclass that is specialized to handle commands.
This uses a ``params`` column that is expected to be ``None`` or a dict of
params.
"""

rev_pars_dict = TableAttribute()
Expand Down Expand Up @@ -431,12 +433,8 @@ def __getitem__(self, item):
)
return out

elif (
isinstance(item, slice)
or isinstance(item, np.ndarray)
or isinstance(item, list)
or isinstance(item, tuple)
and all(isinstance(x, np.ndarray) for x in item)
elif isinstance(item, (slice, np.ndarray, list)) or (
isinstance(item, tuple) and all(isinstance(x, np.ndarray) for x in item)
):
# here for the many ways to give a slice; a tuple of ndarray
# is produced by np.where, as in t[np.where(t['a'] > 2)]
Expand Down Expand Up @@ -514,7 +512,8 @@ def fetch_params(self):
"""
Fetch all ``params`` for every row and force resolution of actual values.
This is handy for printing a command table and seeing all the parameters at once.
This is handy for printing a command table and seeing all the parameters
at once.
"""
if "params" not in self.colnames:
self["params"] = None
Expand All @@ -529,8 +528,8 @@ def get_rltt(self):
and cmd["params"]["event_type"] == "RUNNING_LOAD_TERMINATION_TIME"
):
return cmd["date"]
else:
return None

return None

def get_scheduled_stop_time(self):
for idx in range(len(self), 0, -1):
Expand All @@ -540,13 +539,14 @@ def get_scheduled_stop_time(self):
and cmd["params"]["event_type"] == "SCHEDULED_STOP_TIME"
):
return cmd["date"]
else:
return None

return None

def add_cmds(self, cmds, rltt=None):
"""
Add CommandTable ``cmds`` to self and return the new CommandTable. The
commands table is maintained in order (date, step, scs).
Add CommandTable ``cmds`` to self and return the new CommandTable.
The commands table is maintained in order (date, step, scs).
:param cmds: :class:`~kadi.commands.commands.CommandTable` of commands
:param apply_rltt: bool, optional
Expand Down Expand Up @@ -585,15 +585,16 @@ def sort_in_backstop_order(self):
indexes = self.argsort(["date"], kind="stable")

with self.index_mode("freeze"):
for name, col in self.columns.items():
for col in self.columns.values():
# Make a new sorted column. This requires that take() also copies
# relevant info attributes for mixin columns.
new_col = col.take(indexes, axis=0)

# First statement in try: will succeed if the column supports an in-place
# update, and matches the legacy behavior of astropy Table. However,
# some mixin classes may not support this, so in that case just drop
# in the entire new column. See #9553 and #9536 for discussion.
# First statement in try: will succeed if the column supports an
# in-place update, and matches the legacy behavior of astropy
# Table. However, some mixin classes may not support this, so
# in that case just drop in the entire new column. See #9553 and
# #9536 for discussion.
try:
col[:] = new_col
except Exception:
Expand Down Expand Up @@ -691,13 +692,7 @@ def pformat_like_backstop(
fmt = "{}={:.8e}"
elif key == "packet(40)":
continue
elif (
key.startswith("aopcads")
or key.startswith("co")
or key.startswith("afl")
or key.startswith("2s1s")
or key.startswith("2s2s")
):
elif key.startswith(("aopcads", "co", "afl", "2s1s", "2s2s")):
fmt = "{}={:d} "
else:
fmt = "{}={}"
Expand Down
Loading

0 comments on commit 44a63c6

Please sign in to comment.