Skip to content

Commit b1beec1

Browse files
committed
ruff formatting for common, detectors, and iocs
1 parent ebe2c89 commit b1beec1

21 files changed

Lines changed: 167 additions & 185 deletions

nslsii/common/ipynb/logutils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,14 +47,14 @@ def log_exception(ipyshell, etype, evalue, tb, tb_offset=None):
4747

4848
# display the exception in the console
4949
if ipyshell.InteractiveTB.mode == "Minimal":
50-
print(
50+
print( # noqa : T201
5151
"An exception has occurred, use '%tb verbose' to see the full traceback.",
5252
file=sys.stderr,
5353
)
5454
ipyshell.showtraceback((etype, evalue, tb), tb_offset=tb_offset)
5555

5656
# send the traceback to the nslsii.ipython logger
5757
logging.getLogger("nslsii.ipython").exception(evalue)
58-
print(f"See {bluesky_log_file_path} for the full traceback.", file=sys.stderr)
58+
print(f"See {bluesky_log_file_path} for the full traceback.", file=sys.stderr) # noqa : T201
5959

6060
return tb_lines

nslsii/common/touchbl.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,5 @@ def if_touch_beamline(envvar="TOUCHBEAMLINE"):
1010
return False
1111
if value in ("y", "yes", "t", "true", "on", "1"):
1212
return True
13-
raise ValueError(f"Unknown value: {value}")
13+
msg = f"Unknown value: {value}"
14+
raise ValueError(msg)

nslsii/detectors/QEPro.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@ def __init__(self, *args, tolerance=1, **kwargs):
1717
super().__init__(*args, **kwargs)
1818

1919
def set(self, value):
20-
def check_setpoint(value, old_value, **kwargs):
20+
def check_setpoint(value, old_value, **kwargs): # noqa : ARG001
2121
if abs(value - self.tec_temp.get()) < self.tolerance:
22-
print(f"Reached setpoint {self.tec_temp.get()}.")
22+
print(f"Reached setpoint {self.tec_temp.get()}.") # noqa : T201
2323
return True
2424
return False
2525

@@ -142,7 +142,7 @@ def setup_collection(
142142
self,
143143
integration_time,
144144
num_spectra_to_average,
145-
correction_type="reference",
145+
correction_type="reference", # noqa : ARG002
146146
electric_dark_correction=True,
147147
):
148148
self.integration_time.put(integration_time)

nslsii/detectors/maia.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import time as ttime
44
from collections import OrderedDict
5+
from typing import ClassVar
56

67
from ophyd import Component as Cpt
78
from ophyd import Device, EpicsSignal, EpicsSignalRO
@@ -816,7 +817,7 @@ class Encoder(Device):
816817

817818

818819
class MAIA(Kandinskivars):
819-
fly_keys = [
820+
fly_keys: ClassVar[list[str]] = [
820821
"blog.info.blogd_data_path",
821822
"blog.info.blogd_working_directory",
822823
"blog.info.run_number",
@@ -833,7 +834,7 @@ def kickoff(self):
833834

834835
st = DeviceStatus(self)
835836

836-
def _cb_discard(value, **kwargs):
837+
def _cb_discard(value, **kwargs): # noqa : ARG001
837838
if value == 0:
838839
st._finished()
839840
self.blog_discard_mon.value.clear_sub(_cb_discard)
@@ -845,7 +846,7 @@ def _cb_discard(value, **kwargs):
845846
def complete(self):
846847
st = DeviceStatus(self)
847848

848-
def _cb_discard(value, **kwargs):
849+
def _cb_discard(value, **kwargs): # noqa : ARG001
849850
if value == 1:
850851
st._finished()
851852
self.blog_discard_mon.value.clear_sub(_cb_discard)

nslsii/detectors/trigger_mixins.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -130,10 +130,11 @@ def unstage(self):
130130

131131
def trigger_internal(self):
132132
if self._staged != Staged.yes:
133-
raise RuntimeError(
133+
msg = (
134134
"This detector is not ready to trigger."
135135
"Call the stage() method before triggering."
136136
)
137+
raise RuntimeError(msg)
137138

138139
self._status = DeviceStatus(self)
139140
self._acquisition_signal.put(1, wait=False)
@@ -142,10 +143,11 @@ def trigger_internal(self):
142143

143144
def trigger_external(self):
144145
if self._staged != Staged.yes:
145-
raise RuntimeError(
146+
msg = (
146147
"This detector is not ready to trigger."
147148
"Call the stage() method before triggering."
148149
)
150+
raise RuntimeError(msg)
149151

150152
self._status = DeviceStatus(self)
151153
self._status._finished()
@@ -159,7 +161,7 @@ def trigger(self):
159161
mode_trigger = getattr(self, f"trigger_{self.mode}")
160162
return mode_trigger()
161163

162-
def _acquire_changed(self, value=None, old_value=None, **kwargs):
164+
def _acquire_changed(self, value=None, old_value=None, **kwargs): # noqa : ARG002
163165
"""This is called when the 'acquire' signal changes."""
164166
if self._status is None:
165167
return

nslsii/detectors/utils.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,24 @@
11
from __future__ import annotations
22

3-
import os
3+
from pathlib import Path
44

55

66
def makedirs(path, mode=0o777):
77
"""Recursively make directories and set permissions"""
88
# Permissions not working with os.makedirs -
99
# See: http://stackoverflow.com/questions/5231901
10-
if not path or os.path.exists(path):
10+
if not path or Path.exists(path):
1111
return []
1212

13-
head, tail = os.path.split(path)
13+
head, _ = Path.split(path)
1414
ret = makedirs(head, mode)
1515
try:
16-
os.mkdir(path)
16+
Path.mkdir(path)
1717
except OSError as ex:
1818
if "File exists" not in str(ex):
1919
raise
2020

21-
os.chmod(path, mode)
21+
Path.chmod(path, mode)
2222
ret.append(path)
2323
return ret
2424

@@ -28,7 +28,7 @@ def ordered_dict_move_to_beginning(od, key):
2828
return
2929

3030
value = od[key]
31-
items = list((k, v) for k, v in od.items() if k != key)
31+
items = [(k, v) for k, v in od.items() if k != key]
3232
od.clear()
3333
od[key] = value
3434
od.update(items)
@@ -55,8 +55,8 @@ def make_filename_add_subdirectory(
5555
Number of characters to use from the hash
5656
"""
5757
hash_portion = fn[:hash_characters]
58-
read_path = os.path.join(read_path, hash_portion, "")
59-
write_path = os.path.join(write_path, hash_portion, "")
58+
read_path = Path.join(read_path, hash_portion, "")
59+
write_path = Path.join(write_path, hash_portion, "")
6060

6161
if make_directories:
6262
makedirs(read_path)

nslsii/detectors/webcam.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import datetime
44
import itertools
55
import logging
6+
import sys
67
import time as ttime
78
import warnings
89
from collections import deque
@@ -36,7 +37,7 @@ def __init__(
3637
**kwargs,
3738
):
3839
warnings.warn(
39-
f"This class {self.__class__.__name__} will be removed in the future."
40+
f"This class {self.__class__.__name__} will be removed in the future.", stacklevel=2
4041
)
4142

4243
super().__init__(*args, **kwargs)
@@ -74,7 +75,7 @@ def stage(self):
7475
self._resource_document.pop("run_start")
7576
self._asset_docs_cache.append(("resource", self._resource_document))
7677

77-
logger.debug(f"{self._data_file = }")
78+
logger.debug("%r", self._data_file)
7879

7980
self._h5file_desc = h5py.File(self._data_file, "x")
8081
group = self._h5file_desc.create_group("/entry")
@@ -98,29 +99,29 @@ def trigger(self, *args, **kwargs):
9899
i = 0
99100
cap = cv2.VideoCapture(self._video_stream_url)
100101
while True:
101-
logger.debug(f"Iteration: {i}")
102+
logger.debug("Iteration: %r", i)
102103
i += 1
103104
ret, frame = cap.read()
104105
frames.append(frame)
105106
times.append(ttime.time())
106107

107108
# cv2.imshow('Video', frame)
108-
logger.debug(f"shape: {frame.shape}")
109+
logger.debug("shape: %r", frame.shape)
109110

110111
if ttime.monotonic() - start >= self.exposure_time.get():
111112
break
112113

113114
if cv2.waitKey(1) == 27:
114-
exit(0)
115+
sys.exit(0)
115116

116117
frames = np.array(frames)
117-
logger.debug(f"original shape: {frames.shape}")
118+
logger.debug("original shape: %r", frames.shape)
118119
# Averaging over all frames and summing 3 RGB channels
119120
averaged = frames.mean(axis=0).sum(axis=-1)
120121

121122
current_frame = next(self._counter)
122123
self._dataset.resize((current_frame + 1, *self._frame_shape))
123-
logger.debug(f"{self._dataset = }\n{self._dataset.shape = }")
124+
logger.debug("%r\nshape=%r", self._dataset, self._dataset.shape)
124125
self._dataset[current_frame, :, :] = averaged
125126

126127
datum_document = self._datum_factory(datum_kwargs={"frame": current_frame})
@@ -133,7 +134,7 @@ def trigger(self, *args, **kwargs):
133134

134135
def describe(self):
135136
res = super().describe()
136-
res[self.image.name].update(dict(shape=self._frame_shape))
137+
res[self.image.name].update({"shape": self._frame_shape})
137138
return res
138139

139140
def unstage(self):
@@ -146,5 +147,5 @@ def unstage(self):
146147
def collect_asset_docs(self):
147148
items = list(self._asset_docs_cache)
148149
self._asset_docs_cache.clear()
149-
for item in items:
150+
for item in items: # noqa : UP028
150151
yield item

nslsii/detectors/xspress3.py

Lines changed: 24 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -137,8 +137,8 @@ def unstage(self):
137137
logger.warning("Still capturing data .... giving up.")
138138
logger.warning(
139139
"Check that the xspress3 is configured to take the right "
140-
"number of frames "
141-
f"(it is trying to take {self.parent.settings.num_images.get()})"
140+
"number of frames (it is trying to take %s)",
141+
self.parent.settings.num_images.get()
142142
)
143143
self.capture.put(0)
144144
break
@@ -171,7 +171,8 @@ def stage(self):
171171

172172
total_points = self.parent.total_points.get()
173173
if total_points < 1:
174-
raise RuntimeError("You must set the total points")
174+
msg = "You must set the total points"
175+
raise RuntimeError(msg)
175176
spec_per_point = self.parent.spectra_per_point.get()
176177
total_capture = total_points * spec_per_point
177178

@@ -223,9 +224,8 @@ def stage(self):
223224
)
224225

225226
if not self.file_path_exists.get():
226-
raise OSError(
227-
f"Path {self.file_path.get()} does not exits on IOC!! Please Check"
228-
)
227+
msg = f"Path {self.file_path.get()} does not exits on IOC!! Please Check"
228+
raise OSError(msg)
229229

230230
logger.debug("Inserting the filestore resource: %s", self._fn)
231231
self._generate_resource({})
@@ -365,10 +365,7 @@ def __init__(
365365
**kwargs,
366366
):
367367
if read_attrs is None:
368-
if use_sum:
369-
read_attrs = ["value_sum"]
370-
else:
371-
read_attrs = ["value", "value_sum"]
368+
read_attrs = ["value_sum"] if use_sum else ["value", "value_sum"]
372369

373370
if configuration_attrs is None:
374371
configuration_attrs = ["ev_low", "ev_high", "enable"]
@@ -464,18 +461,18 @@ def make_rois(rois):
464461
for roi in rois:
465462
attr = f"roi{roi:02d}"
466463
# cls prefix kwargs
467-
defn[attr] = (Xspress3ROI, f"ROI{roi}:", dict(roi_num=roi))
464+
defn[attr] = (Xspress3ROI, f"ROI{roi}:", {"roi_num": roi})
468465
# e.g., device.rois.roi01 = Xspress3ROI('ROI1:', roi_num=1)
469466

470467
# AreaDetector NDPluginAttribute information
471468
attr = f"ad_attr{roi:02d}"
472-
defn[attr] = (Xspress3ROISettings, f"ROI{roi}:", dict(read_attrs=[]))
469+
defn[attr] = (Xspress3ROISettings, f"ROI{roi}:", {"read_attrs": []})
473470
# e.g., device.rois.roi01 = Xspress3ROI('ROI1:', roi_num=1)
474471

475472
# TODO: 'roi01' and 'ad_attr_01' have the same prefix and could
476473
# technically be combined. Is this desirable?
477474

478-
defn["num_rois"] = (Signal, None, dict(value=len(rois)))
475+
defn["num_rois"] = (Signal, None, {"value": len(rois)})
479476
# e.g., device.rois.num_rois.get() => 16
480477
return defn
481478

@@ -518,7 +515,8 @@ def set_roi(self, index, ev_low, ev_high, *, name=None):
518515
roi = index
519516
else:
520517
if index <= 0:
521-
raise ValueError("ROI index starts from 1")
518+
msg = "ROI index starts from 1"
519+
raise ValueError(msg)
522520
roi = list(self.all_rois)[index - 1]
523521

524522
roi.configure(ev_low, ev_high)
@@ -563,11 +561,11 @@ def __init__(
563561
name=None,
564562
parent=None,
565563
# to remove?
566-
file_path="",
567-
ioc_file_path="",
568-
default_channels=None,
569-
channel_prefix=None,
570-
roi_sums=False,
564+
file_path="", # noqa : ARG002
565+
ioc_file_path="", # noqa : ARG002
566+
default_channels=None, # noqa : ARG002
567+
channel_prefix=None, # noqa : ARG002
568+
roi_sums=False, # noqa : ARG002
571569
# to remove?
572570
**kwargs,
573571
):
@@ -607,8 +605,8 @@ def channels(self):
607605

608606
@property
609607
def all_rois(self):
610-
for ch_num, channel in self._channels.items():
611-
for roi in channel.all_rois:
608+
for _, channel in self._channels.items():
609+
for roi in channel.all_rois: # noqa : UP028
612610
yield roi
613611

614612
@property
@@ -617,7 +615,7 @@ def enabled_rois(self):
617615
if roi.enable.get():
618616
yield roi
619617

620-
def read_hdf5(self, fn, *, rois=None, max_retries=2):
618+
def read_hdf5(self, fn, *, rois=None, max_retries=2): # noqa : ARG002
621619
"""Read ROI data from an HDF5 file using the current ROI configuration
622620
623621
Parameters
@@ -631,10 +629,7 @@ def read_hdf5(self, fn, *, rois=None, max_retries=2):
631629
rois = self.enabled_rois
632630

633631
num_points = self.settings.num_images.get()
634-
if isinstance(fn, h5py.File):
635-
hdf = fn
636-
else:
637-
hdf = h5py.File(fn, "r")
632+
hdf = fn if isinstance(fn, h5py.File) else h5py.File(fn, "r")
638633

639634
RoiTuple = Xspress3ROI.get_device_tuple()
640635

@@ -689,7 +684,7 @@ def unstage(self):
689684
self._status = None
690685
return ret
691686

692-
def _acquire_changed(self, value=None, old_value=None, **kwargs):
687+
def _acquire_changed(self, value=None, old_value=None, **kwargs): # noqa : ARG002
693688
"This is called when the 'acquire' signal changes."
694689
if self._status is None:
695690
return
@@ -699,7 +694,8 @@ def _acquire_changed(self, value=None, old_value=None, **kwargs):
699694

700695
def trigger(self):
701696
if self._staged != Staged.yes:
702-
raise RuntimeError("not staged")
697+
msg = "not staged"
698+
raise RuntimeError(msg)
703699

704700
self._status = DeviceStatus(self)
705701
self._acquisition_signal.put(1, wait=False)

0 commit comments

Comments
 (0)