Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
d8bc6bc
first draft of applying cookie template
jennmald Jul 31, 2025
1f7f822
remove dependency on my fork
jennmald Aug 19, 2025
5023304
pre-commit changes
jennmald Aug 19, 2025
e71dae8
more formatting work
jennmald Aug 19, 2025
a948807
ruff fixes for versioneer
jennmald Aug 22, 2025
d0a2ba9
fix ruff for setup.py
jennmald Aug 22, 2025
0935a26
fix transforms with ruff
jennmald Aug 22, 2025
d50684d
ruff fixes for xspress3 tests
jennmald Aug 22, 2025
d6388df
ruff formatting
jennmald Aug 22, 2025
78fc010
more ruff formatting for tests
jennmald Aug 25, 2025
c42382d
ruff formatting finished for tests and started temp controllers
jennmald Aug 25, 2025
edd4a04
add ruff formatting to ophyd async and plans
jennmald Aug 25, 2025
13e9679
ruff formatting for common, detectors, and iocs
jennmald Aug 27, 2025
bd74263
finished ruff fixes for nslsii
jennmald Aug 29, 2025
25eede6
fix ruff format with pre-commit
jennmald Aug 29, 2025
2a3fcfd
fix test file names
jennmald Sep 3, 2025
50d23b2
fix rst-backticks
jennmald Sep 3, 2025
090ec27
fix codespell
jennmald Sep 3, 2025
f22755f
remove mypy
jennmald Sep 4, 2025
42dcd92
add versioneer
jennmald Sep 4, 2025
51c2914
satisfy pylint
jennmald Sep 4, 2025
ccf86ef
add versioneer to dev dependencies
jennmald Sep 4, 2025
f8e1532
build versioneer:
jennmald Sep 4, 2025
9e06067
fix setup.py
jennmald Sep 4, 2025
a5093c1
fix joinpath
jennmald Sep 4, 2025
fbaa7ce
fix path dirname
jennmald Sep 4, 2025
11b54ba
fix a few Path errors:
jennmald Sep 4, 2025
8584c0c
fix ophyd async version
jennmald Sep 4, 2025
b2c8f94
typo for ophyd async version
jennmald Sep 4, 2025
f37f532
remove kafka tests
jennmald Sep 4, 2025
0d46396
move nslsii to src
jennmald Sep 9, 2025
7c7a985
pre-commit for new files
jennmald Sep 9, 2025
a0b27a9
add src path
jennmald Sep 9, 2025
d4bfe03
try to fix path for contest
jennmald Sep 9, 2025
0ac5807
fix versioneer
jennmald Sep 10, 2025
22bb24f
move tests and fix versioneer
jennmald Sep 10, 2025
dc22b16
fix version
jennmald Sep 10, 2025
0b96179
rename version.py
jennmald Sep 10, 2025
70f4ba8
fix get versions
jennmald Sep 10, 2025
023615c
change None to Close
jennmald Sep 10, 2025
79f668e
fix none to close tyep
jennmald Sep 10, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
ruff formatting for common, detectors, and iocs
  • Loading branch information
jennmald committed Sep 9, 2025
commit 13e96797d0002b160a0b69a8a0e92107eb267dbe
4 changes: 2 additions & 2 deletions nslsii/common/ipynb/logutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,14 @@ def log_exception(ipyshell, etype, evalue, tb, tb_offset=None):

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

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

return tb_lines
3 changes: 2 additions & 1 deletion nslsii/common/touchbl.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ def if_touch_beamline(envvar="TOUCHBEAMLINE"):
return False
if value in ("y", "yes", "t", "true", "on", "1"):
return True
raise ValueError(f"Unknown value: {value}")
msg = f"Unknown value: {value}"
raise ValueError(msg)
6 changes: 3 additions & 3 deletions nslsii/detectors/QEPro.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ def __init__(self, *args, tolerance=1, **kwargs):
super().__init__(*args, **kwargs)

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

Expand Down Expand Up @@ -142,7 +142,7 @@ def setup_collection(
self,
integration_time,
num_spectra_to_average,
correction_type="reference",
correction_type="reference", # noqa : ARG002
electric_dark_correction=True,
):
self.integration_time.put(integration_time)
Expand Down
7 changes: 4 additions & 3 deletions nslsii/detectors/maia.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import time as ttime
from collections import OrderedDict
from typing import ClassVar

from ophyd import Component as Cpt
from ophyd import Device, EpicsSignal, EpicsSignalRO
Expand Down Expand Up @@ -816,7 +817,7 @@ class Encoder(Device):


class MAIA(Kandinskivars):
fly_keys = [
fly_keys: ClassVar[list[str]] = [
"blog.info.blogd_data_path",
"blog.info.blogd_working_directory",
"blog.info.run_number",
Expand All @@ -833,7 +834,7 @@ def kickoff(self):

st = DeviceStatus(self)

def _cb_discard(value, **kwargs):
def _cb_discard(value, **kwargs): # noqa : ARG001
if value == 0:
st._finished()
self.blog_discard_mon.value.clear_sub(_cb_discard)
Expand All @@ -845,7 +846,7 @@ def _cb_discard(value, **kwargs):
def complete(self):
st = DeviceStatus(self)

def _cb_discard(value, **kwargs):
def _cb_discard(value, **kwargs): # noqa : ARG001
if value == 1:
st._finished()
self.blog_discard_mon.value.clear_sub(_cb_discard)
Expand Down
8 changes: 5 additions & 3 deletions nslsii/detectors/trigger_mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,11 @@ def unstage(self):

def trigger_internal(self):
if self._staged != Staged.yes:
raise RuntimeError(
msg = (
"This detector is not ready to trigger."
"Call the stage() method before triggering."
)
raise RuntimeError(msg)

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

def trigger_external(self):
if self._staged != Staged.yes:
raise RuntimeError(
msg = (
"This detector is not ready to trigger."
"Call the stage() method before triggering."
)
raise RuntimeError(msg)

self._status = DeviceStatus(self)
self._status._finished()
Expand All @@ -159,7 +161,7 @@ def trigger(self):
mode_trigger = getattr(self, f"trigger_{self.mode}")
return mode_trigger()

def _acquire_changed(self, value=None, old_value=None, **kwargs):
def _acquire_changed(self, value=None, old_value=None, **kwargs): # noqa : ARG002
"""This is called when the 'acquire' signal changes."""
if self._status is None:
return
Expand Down
16 changes: 8 additions & 8 deletions nslsii/detectors/utils.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
from __future__ import annotations

import os
from pathlib import Path


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

head, tail = os.path.split(path)
head, _ = Path.split(path)
ret = makedirs(head, mode)
try:
os.mkdir(path)
Path.mkdir(path)
except OSError as ex:
if "File exists" not in str(ex):
raise

os.chmod(path, mode)
Path.chmod(path, mode)
ret.append(path)
return ret

Expand All @@ -28,7 +28,7 @@ def ordered_dict_move_to_beginning(od, key):
return

value = od[key]
items = list((k, v) for k, v in od.items() if k != key)
items = [(k, v) for k, v in od.items() if k != key]
od.clear()
od[key] = value
od.update(items)
Expand All @@ -55,8 +55,8 @@ def make_filename_add_subdirectory(
Number of characters to use from the hash
"""
hash_portion = fn[:hash_characters]
read_path = os.path.join(read_path, hash_portion, "")
write_path = os.path.join(write_path, hash_portion, "")
read_path = Path.join(read_path, hash_portion, "")
write_path = Path.join(write_path, hash_portion, "")

if make_directories:
makedirs(read_path)
Expand Down
19 changes: 10 additions & 9 deletions nslsii/detectors/webcam.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import datetime
import itertools
import logging
import sys
import time as ttime
import warnings
from collections import deque
Expand Down Expand Up @@ -36,7 +37,7 @@ def __init__(
**kwargs,
):
warnings.warn(
f"This class {self.__class__.__name__} will be removed in the future."
f"This class {self.__class__.__name__} will be removed in the future.", stacklevel=2
)

super().__init__(*args, **kwargs)
Expand Down Expand Up @@ -74,7 +75,7 @@ def stage(self):
self._resource_document.pop("run_start")
self._asset_docs_cache.append(("resource", self._resource_document))

logger.debug(f"{self._data_file = }")
logger.debug("%r", self._data_file)

self._h5file_desc = h5py.File(self._data_file, "x")
group = self._h5file_desc.create_group("/entry")
Expand All @@ -98,29 +99,29 @@ def trigger(self, *args, **kwargs):
i = 0
cap = cv2.VideoCapture(self._video_stream_url)
while True:
logger.debug(f"Iteration: {i}")
logger.debug("Iteration: %r", i)
i += 1
ret, frame = cap.read()
frames.append(frame)
times.append(ttime.time())

# cv2.imshow('Video', frame)
logger.debug(f"shape: {frame.shape}")
logger.debug("shape: %r", frame.shape)

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

if cv2.waitKey(1) == 27:
exit(0)
sys.exit(0)

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

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

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

def describe(self):
res = super().describe()
res[self.image.name].update(dict(shape=self._frame_shape))
res[self.image.name].update({"shape": self._frame_shape})
return res

def unstage(self):
Expand All @@ -146,5 +147,5 @@ def unstage(self):
def collect_asset_docs(self):
items = list(self._asset_docs_cache)
self._asset_docs_cache.clear()
for item in items:
for item in items: # noqa : UP028
yield item
52 changes: 24 additions & 28 deletions nslsii/detectors/xspress3.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,8 @@ def unstage(self):
logger.warning("Still capturing data .... giving up.")
logger.warning(
"Check that the xspress3 is configured to take the right "
"number of frames "
f"(it is trying to take {self.parent.settings.num_images.get()})"
"number of frames (it is trying to take %s)",
self.parent.settings.num_images.get()
)
self.capture.put(0)
break
Expand Down Expand Up @@ -171,7 +171,8 @@ def stage(self):

total_points = self.parent.total_points.get()
if total_points < 1:
raise RuntimeError("You must set the total points")
msg = "You must set the total points"
raise RuntimeError(msg)
spec_per_point = self.parent.spectra_per_point.get()
total_capture = total_points * spec_per_point

Expand Down Expand Up @@ -223,9 +224,8 @@ def stage(self):
)

if not self.file_path_exists.get():
raise OSError(
f"Path {self.file_path.get()} does not exits on IOC!! Please Check"
)
msg = f"Path {self.file_path.get()} does not exits on IOC!! Please Check"
raise OSError(msg)

logger.debug("Inserting the filestore resource: %s", self._fn)
self._generate_resource({})
Expand Down Expand Up @@ -365,10 +365,7 @@ def __init__(
**kwargs,
):
if read_attrs is None:
if use_sum:
read_attrs = ["value_sum"]
else:
read_attrs = ["value", "value_sum"]
read_attrs = ["value_sum"] if use_sum else ["value", "value_sum"]

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

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

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

defn["num_rois"] = (Signal, None, dict(value=len(rois)))
defn["num_rois"] = (Signal, None, {"value": len(rois)})
# e.g., device.rois.num_rois.get() => 16
return defn

Expand Down Expand Up @@ -518,7 +515,8 @@ def set_roi(self, index, ev_low, ev_high, *, name=None):
roi = index
else:
if index <= 0:
raise ValueError("ROI index starts from 1")
msg = "ROI index starts from 1"
raise ValueError(msg)
roi = list(self.all_rois)[index - 1]

roi.configure(ev_low, ev_high)
Expand Down Expand Up @@ -563,11 +561,11 @@ def __init__(
name=None,
parent=None,
# to remove?
file_path="",
ioc_file_path="",
default_channels=None,
channel_prefix=None,
roi_sums=False,
file_path="", # noqa : ARG002
ioc_file_path="", # noqa : ARG002
default_channels=None, # noqa : ARG002
channel_prefix=None, # noqa : ARG002
roi_sums=False, # noqa : ARG002
# to remove?
**kwargs,
):
Expand Down Expand Up @@ -607,8 +605,8 @@ def channels(self):

@property
def all_rois(self):
for ch_num, channel in self._channels.items():
for roi in channel.all_rois:
for _, channel in self._channels.items():
for roi in channel.all_rois: # noqa : UP028
yield roi

@property
Expand All @@ -617,7 +615,7 @@ def enabled_rois(self):
if roi.enable.get():
yield roi

def read_hdf5(self, fn, *, rois=None, max_retries=2):
def read_hdf5(self, fn, *, rois=None, max_retries=2): # noqa : ARG002
"""Read ROI data from an HDF5 file using the current ROI configuration

Parameters
Expand All @@ -631,10 +629,7 @@ def read_hdf5(self, fn, *, rois=None, max_retries=2):
rois = self.enabled_rois

num_points = self.settings.num_images.get()
if isinstance(fn, h5py.File):
hdf = fn
else:
hdf = h5py.File(fn, "r")
hdf = fn if isinstance(fn, h5py.File) else h5py.File(fn, "r")

RoiTuple = Xspress3ROI.get_device_tuple()

Expand Down Expand Up @@ -689,7 +684,7 @@ def unstage(self):
self._status = None
return ret

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

def trigger(self):
if self._staged != Staged.yes:
raise RuntimeError("not staged")
msg = "not staged"
raise RuntimeError(msg)

self._status = DeviceStatus(self)
self._acquisition_signal.put(1, wait=False)
Expand Down
Loading