Skip to content

Commit

Permalink
Merge pull request #863 from BCDA-APS/860-code-style-black
Browse files Browse the repository at this point in the history
apply black code style
  • Loading branch information
prjemian authored May 20, 2023
2 parents 2841ce8 + 7436a52 commit 691060f
Show file tree
Hide file tree
Showing 72 changed files with 248 additions and 433 deletions.
5 changes: 5 additions & 0 deletions .github/workflows/unit_tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ jobs:
run: |
flake8
- name: Run black
uses: rickstaa/action-black@v1
with:
black_args: ". --check"

install-catalogs:
name: Install & cache databroker catalogs
runs-on: ubuntu-latest
Expand Down
1 change: 1 addition & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ Maintenance
------------

* Add unit tests for shutters.
* Apply consistent code style (black) throughout.
* Set ``kind`` attribute to add plugin to ad.read_attrs list.
* Clear ``PVPositionerSoftDone``'s setpoint & readback subscriptions at exit.

Expand Down
15 changes: 4 additions & 11 deletions apstools/callbacks/callback_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,10 +185,7 @@ def trim(value, length=60):
tbl.labels = "stream num_vars num_values".split()
for k, v in sorted(self.streams.items()):
if len(v) != 1:
print(
f"expecting only one descriptor in stream {k},"
f" found {len(v)}"
)
print(f"expecting only one descriptor in stream {k}, found {len(v)}")
else:
data = self.acquisitions[v[0]]["data"]
num_vars = len(data)
Expand Down Expand Up @@ -287,10 +284,7 @@ def event(self, doc):
for k, v in doc["data"].items():
data = descriptor["data"].get(k)
if data is None:
print(
f"entry key {k} not found in"
f" descriptor of {descriptor['stream']}"
)
print(f"entry key {k} not found in descriptor of {descriptor['stream']}")
else:
data["data"].append(v)
data["time"].append(doc["timestamps"][k])
Expand All @@ -316,9 +310,7 @@ def start(self, doc):
self.start_time = doc["time"]
self.uid = doc["uid"]
self.detectors = doc.get("detectors", [])
self.positioners = (
doc.get("positioners") or doc.get("motors") or []
)
self.positioners = doc.get("positioners") or doc.get("motors") or []

# gather the metadata
for k, v in doc.items():
Expand All @@ -339,6 +331,7 @@ def stop(self, doc):

self.writer()


# -----------------------------------------------------------------------------
# :author: Pete R. Jemian
# :email: [email protected]
Expand Down
5 changes: 2 additions & 3 deletions apstools/callbacks/doc_collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,7 @@ class DocumentCollectorCallback(object):
"""

data_event_names = (
"descriptor event resource datum bulk_events".split()
)
data_event_names = "descriptor event resource datum bulk_events".split()

def __init__(self):
self.documents = {} # key: name, value: document
Expand Down Expand Up @@ -79,6 +77,7 @@ def receiver(self, key, document):
self.documents[key].append(document)
return


# -----------------------------------------------------------------------------
# :author: Pete R. Jemian
# :email: [email protected]
Expand Down
2 changes: 1 addition & 1 deletion apstools/callbacks/nexus_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -661,7 +661,7 @@ def copy_image_from_IOC_file(fname):
fname,
self._external_file_read_retry_delay,
self._external_file_read_timeout - t_elapsed,
exinfo
exinfo,
)
time.sleep(self._external_file_read_retry_delay)

Expand Down
1 change: 0 additions & 1 deletion apstools/callbacks/tests/test_nxwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ class MySimDetectorCam(CamMixin, SimDetectorCam):


class MyDetector(SingleTrigger, DetectorBase):

cam = Component(MySimDetectorCam, "cam1:")

hdf1 = Component(
Expand Down
17 changes: 7 additions & 10 deletions apstools/devices/aps_cycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from ophyd.sim import SynSignalRO

_PATH = pathlib.Path(__file__).parent
YAML_CYCLE_FILE = (_PATH / "aps_cycle_info.yml")
YAML_CYCLE_FILE = _PATH / "aps_cycle_info.yml"


class _ApsCycleDB:
Expand Down Expand Up @@ -62,14 +62,10 @@ def _read_cycle_data(self):
_cycles = yaml.load(_cycles_yml, Loader=yaml.BaseLoader)

def iso2ts(isodatetime):
return datetime.datetime.timestamp(
datetime.datetime.fromisoformat(isodatetime)
)
return datetime.datetime.timestamp(datetime.datetime.fromisoformat(isodatetime))

db = {
run_name: dict(
start=iso2ts(span["begin"]), end=iso2ts(span["end"])
)
run_name: dict(start=iso2ts(span["begin"]), end=iso2ts(span["end"]))
for run_name, span in _cycles.items()
}
return db
Expand Down Expand Up @@ -133,11 +129,12 @@ class ApsCycleDM(SynSignalRO):
def get(self):
self._cycle_name = cycle_db.get_cycle_name()
if datetime.datetime.now().isoformat(sep=" ") >= self._cycle_ends:
self._cycle_ends = datetime.datetime.fromtimestamp(
cycle_db.db[self._cycle_name]["end"]
).isoformat(sep=" ")
self._cycle_ends = datetime.datetime.fromtimestamp(cycle_db.db[self._cycle_name]["end"]).isoformat(
sep=" "
)
return self._cycle_name


# -----------------------------------------------------------------------------
# :author: Pete R. Jemian
# :email: [email protected]
Expand Down
1 change: 1 addition & 0 deletions apstools/devices/aps_machine.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ def inUserOperations(self):
)
# fmt: on


# -----------------------------------------------------------------------------
# :author: Pete R. Jemian
# :email: [email protected]
Expand Down
16 changes: 11 additions & 5 deletions apstools/devices/aps_undulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,20 @@ class ApsUndulator(Device):
"""

energy = Component(
EpicsSignal, "Energy", write_pv="EnergySet", put_complete=True, kind="hinted",
EpicsSignal,
"Energy",
write_pv="EnergySet",
put_complete=True,
kind="hinted",
)
energy_taper = Component(
EpicsSignal, "TaperEnergy", write_pv="TaperEnergySet", kind="config",
EpicsSignal,
"TaperEnergy",
write_pv="TaperEnergySet",
kind="config",
)
gap = Component(EpicsSignal, "Gap", write_pv="GapSet")
gap_taper = Component(
EpicsSignal, "TaperGap", write_pv="TaperGapSet", kind="config"
)
gap_taper = Component(EpicsSignal, "TaperGap", write_pv="TaperGapSet", kind="config")
start_button = Component(EpicsSignal, "Start", put_complete=True, kind="omitted")
stop_button = Component(EpicsSignal, "Stop", kind="omitted")
harmonic_value = Component(EpicsSignal, "HarmonicValue", kind="config")
Expand Down Expand Up @@ -79,6 +84,7 @@ class ApsUndulatorDual(Device):
upstream = Component(ApsUndulator, "us:")
downstream = Component(ApsUndulator, "ds:")


# -----------------------------------------------------------------------------
# :author: Pete R. Jemian
# :email: [email protected]
Expand Down
11 changes: 3 additions & 8 deletions apstools/devices/axis_tuner.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,18 +76,12 @@ def __init__(self, *args, **kwargs):

def _default_pre_tune_method(self):
"""called before `tune()`"""
logger.info(
"{} position before tuning: {}".format(
self.name, self.position
)
)
logger.info("{} position before tuning: {}".format(self.name, self.position))
yield from bps.null()

def _default_post_tune_method(self):
"""called after `tune()`"""
logger.info(
"{} position after tuning: {}".format(self.name, self.position)
)
logger.info("{} position after tuning: {}".format(self.name, self.position))
yield from bps.null()

def tune(self, md=None, **kwargs):
Expand All @@ -114,6 +108,7 @@ def tune(self, md=None, **kwargs):
if self.post_tune_method is not None:
yield from self.post_tune_method()


# -----------------------------------------------------------------------------
# :author: Pete R. Jemian
# :email: [email protected]
Expand Down
1 change: 1 addition & 0 deletions apstools/devices/description_mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ class EpicsMotorWithMore(

desc = Component(EpicsSignal, ".DESC")


# -----------------------------------------------------------------------------
# :author: Pete R. Jemian
# :email: [email protected]
Expand Down
1 change: 1 addition & 0 deletions apstools/devices/dict_device_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ def make_dict_device(obj, name="ddev"):
New in release 1.6.4.
"""

def standardize(obj):
"""Make obj look like .read()"""
d_new = {}
Expand Down
1 change: 1 addition & 0 deletions apstools/devices/epics_scan_id_signal.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def cb_scan_id_source(self, *args, **kwargs):
self.put(new_scan_id)
return new_scan_id


# -----------------------------------------------------------------------------
# :author: Pete R. Jemian
# :email: [email protected]
Expand Down
3 changes: 2 additions & 1 deletion apstools/devices/eurotherm_2216e.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,11 @@ def __init__(self, prefix="", *, tolerance=1, **kwargs):
setpoint_pv="ignore",
tolerance=tolerance,
update_target=False,
**kwargs
**kwargs,
)
self.sensor.subscribe(self.cb_sensor)


# -----------------------------------------------------------------------------
# :author: Pete R. Jemian
# :email: [email protected]
Expand Down
33 changes: 8 additions & 25 deletions apstools/devices/flyer_motor_scaler.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,10 +261,7 @@ def example_fly_scan():
self.status_taxi.wait()

# arrived to within motor's precision?
if round(
self._motor.position - self._pos_start,
self._motor.precision
) != 0:
if round(self._motor.position - self._pos_start, self._motor.precision) != 0:
raise RuntimeError(
"Not in requested taxi position:"
f" requested={self.pos_start}"
Expand All @@ -291,10 +288,7 @@ def motor(self):
@motor.setter
def motor(self, obj):
if not isinstance(obj, EpicsMotor):
raise TypeError(
"Expected instance of 'ophyd.EpicsMotor'."
f" Received: {type(obj)}"
)
raise TypeError("Expected instance of 'ophyd.EpicsMotor'. Received: {type(obj)}")
self._motor = obj

@property
Expand Down Expand Up @@ -398,14 +392,9 @@ def _action_taxi(self):
self.status_taxi.wait()

# arrived to within motor's precision?
if round(
self._motor.position - self._pos_start,
self._motor.precision
) != 0:
if round(self._motor.position - self._pos_start, self._motor.precision) != 0:
raise RuntimeError(
"Not in requested taxi position:"
f" requested={self.pos_start}"
f" position={self.motor.position}"
"Not in requested taxi position: requested={self.pos_start} position={self.motor.position}"
)

def _action_fly(self):
Expand Down Expand Up @@ -494,10 +483,7 @@ def scaler(self):
@scaler.setter
def scaler(self, obj):
if not isinstance(obj, ScalerCH):
raise TypeError(
"Expected instance of 'ophyd.scaler.ScalerCH'."
f" Received: {type(obj)}"
)
raise TypeError("Expected instance of 'ophyd.scaler.ScalerCH'. Received: {type(obj)}")
self._scaler = obj

@property
Expand Down Expand Up @@ -564,9 +550,7 @@ class ScalerMotorFlyer(_SMFlyer_Step_3):
def __init__(self, *args, period=None, **kwargs):
period = period or 0.1
if period <= 0:
raise ValueError(
f"Sampling period must be a POSITIVE number: {period=}"
)
raise ValueError(f"Sampling period must be a POSITIVE number: {period=}")

self.period = period
self._readings = []
Expand Down Expand Up @@ -613,9 +597,7 @@ def _action_setup(self):
expected_period = round(self.period, 5)
self._original_values.remember(self.scaler.update_rate)
self.scaler.update_rate.put(1 / self.period)
received_period = round(
1 / self.scaler.update_rate.get(use_monitor=False), 5
)
received_period = round(1 / self.scaler.update_rate.get(use_monitor=False), 5)
if received_period != expected_period:
raise ValueError(
"Could not get requested scaler sample period:"
Expand Down Expand Up @@ -732,6 +714,7 @@ def period(self, value):
raise ValueError(f"Value must be greater than zero. Received: {value}")
self._period = value


# -----------------------------------------------------------------------------
# :author: Pete R. Jemian
# :email: [email protected]
Expand Down
6 changes: 3 additions & 3 deletions apstools/devices/kohzu_monochromator.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ def inposition(self):

def move(self, *args, **kwargs):
"""Reposition, with optional wait for completion."""

@run_in_thread
def push_the_move_button_soon(delay_s=0.01):
time.sleep(delay_s) # wait a short time
Expand Down Expand Up @@ -102,9 +103,7 @@ class KohzuSeqCtl_Monochromator(Device):
operator_acknowledge = Component(EpicsSignal, "KohzuOperAckBO", kind="omitted")
use_set = Component(EpicsSignal, "KohzuUseSetBO", kind="omitted")
mode = Component(EpicsSignal, "KohzuModeBO", kind="config", string=True)
move_button = Component(
EpicsSignal, "KohzuPutBO", put_complete=True, kind="omitted"
)
move_button = Component(EpicsSignal, "KohzuPutBO", put_complete=True, kind="omitted")
moving = Component(EpicsSignal, "KohzuMoving", kind="omitted")
y_offset = Component(EpicsSignal, "Kohzu_yOffsetAO", kind="config")
allstop_button = Component(EpicsSignal, "allstop", string=True, kind="omitted")
Expand All @@ -129,6 +128,7 @@ def calibrate_energy(self, value):
self.energy.put(value)
self.use_set.put("Use")


# -----------------------------------------------------------------------------
# :author: Pete R. Jemian
# :email: [email protected]
Expand Down
Loading

0 comments on commit 691060f

Please sign in to comment.