Skip to content

Commit

Permalink
black reformatting
Browse files Browse the repository at this point in the history
  • Loading branch information
Cathyhjj committed Apr 23, 2024
1 parent b56ad7a commit eec6174
Show file tree
Hide file tree
Showing 18 changed files with 231 additions and 154 deletions.
4 changes: 1 addition & 3 deletions src/firefly/area_detector_viewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@


class AreaDetectorViewerDisplay(display.FireflyDisplay):
caqtdm_ui_file: str = (
"/APSshare/epics/synApps_6_2_1/support/areaDetector-R3-12-1/ADAravis/aravisApp/op/ui/autoconvert/ADAravis.ui"
)
caqtdm_ui_file: str = "/APSshare/epics/synApps_6_2_1/support/areaDetector-R3-12-1/ADAravis/aravisApp/op/ui/autoconvert/ADAravis.ui"
image_is_new: bool = True

def customize_device(self):
Expand Down
28 changes: 21 additions & 7 deletions src/firefly/component_selector.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@

from qasync import asyncSlot, QThreadExecutor
import qtawesome as qta
from ophyd import Device, EpicsMotor, PositionerBase, Signal, do_not_wait_for_lazy_connection
from ophyd import (
Device,
EpicsMotor,
PositionerBase,
Signal,
do_not_wait_for_lazy_connection,
)
from qtpy.QtGui import QFont, QStandardItem, QStandardItemModel
from qtpy.QtWidgets import (
QComboBox,
Expand All @@ -23,7 +29,6 @@
log = logging.getLogger(__name__)



class TreeComponent:
"""Representation of an ophyd Component/Device in a tree view."""

Expand Down Expand Up @@ -61,7 +66,6 @@ def icons():
}
)


def component_from_dotted_name(self, name):
if name == self.dotted_name:
# It's this component, so just return
Expand Down Expand Up @@ -120,7 +124,9 @@ def add_children(self):
for name in child_names:
with do_not_wait_for_lazy_connection(self.device):
child = self.__class__(
device=getattr(self.device, name), text=name, parent=self.component_item
device=getattr(self.device, name),
text=name,
parent=self.component_item,
)
self.child_components.append(child)
# Add the devices children
Expand Down Expand Up @@ -155,13 +161,19 @@ async def update_devices(self, registry):
for device in devices:
with do_not_wait_for_lazy_connection(device):
cpt = self.Component(
device=device, text=device.name, parent=parent_item, registry=registry
device=device,
text=device.name,
parent=parent_item,
registry=registry,
)
self.root_components.append(cpt)
# Add all the children for the root components in separate threads
loop = asyncio.get_running_loop()
with QThreadExecutor(len(self.root_components)) as exec:
aws = (loop.run_in_executor(exec, cpt.add_children) for cpt in self.root_components)
aws = (
loop.run_in_executor(exec, cpt.add_children)
for cpt in self.root_components
)
await asyncio.gather(*aws)


Expand All @@ -182,7 +194,9 @@ def add_children(self):
dotted_name = ".".join([self.text, name])
with do_not_wait_for_lazy_connection(self.device):
child = self.__class__(
device=getattr(self.device, name), text=dotted_name, parent=self.parent
device=getattr(self.device, name),
text=dotted_name,
parent=self.parent,
)
self.child_components.append(child)
# Add the devices children
Expand Down
8 changes: 2 additions & 6 deletions src/firefly/ion_chamber.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,8 @@ class IonChamberDisplay(display.FireflyDisplay):
"""A GUI window for changing settings in an ion chamber."""

caqtdm_scaler_ui_file: str = "/net/s25data/xorApps/ui/scaler32_full_offset.ui"
caqtdm_mcs_ui_file: str = (
"/APSshare/epics/synApps_6_2_1/support/mca-R7-9//mcaApp/op/ui/autoconvert/SIS38XX.ui"
)
caqtdm_preamp_ui_file: str = (
"/net/s25data/xorApps/epics/synApps_6_2_1/support/ip-GIT/ipApp/op/ui/autoconvert/SR570.ui"
)
caqtdm_mcs_ui_file: str = "/APSshare/epics/synApps_6_2_1/support/mca-R7-9//mcaApp/op/ui/autoconvert/SIS38XX.ui"
caqtdm_preamp_ui_file: str = "/net/s25data/xorApps/epics/synApps_6_2_1/support/ip-GIT/ipApp/op/ui/autoconvert/SR570.ui"

def customize_device(self):
self._device = registry.find(self.macros()["IC"])
Expand Down
1 change: 1 addition & 0 deletions src/firefly/kb_mirrors.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from firefly.slits import SlitsDisplay

# from haven.instrument import mirrors


Expand Down
18 changes: 10 additions & 8 deletions src/firefly/plans/line_scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def customize_ui(self):
self.ui.num_motor_spin_box.lineEdit().setReadOnly(True)
self.ui.num_motor_spin_box.valueChanged.connect(self.update_regions)

self.ui.run_button.setEnabled(True) #for testing
self.ui.run_button.setEnabled(True) # for testing
self.ui.run_button.clicked.connect(self.queue_plan)

def clearLayout(self, layout):
Expand Down Expand Up @@ -115,17 +115,19 @@ def queue_plan(self, *args, **kwargs):

if self.ui.relative_scan_checkbox.isChecked():
if self.ui.log_scan_checkbox.isChecked():
scan_type = 'rel_log_scan'
scan_type = "rel_log_scan"
else:
scan_type = 'rel_scan'
scan_type = "rel_scan"
else:
if self.ui.log_scan_checkbox.isChecked():
scan_type = 'log_scan'
scan_type = "log_scan"
else:
scan_type = 'scan'

md={'sample': self.ui.lineEdit_sample.text(),
'purpose':self.ui.lineEdit_purpose.text()}
scan_type = "scan"

md = {
"sample": self.ui.lineEdit_sample.text(),
"purpose": self.ui.lineEdit_purpose.text(),
}

# # Build the queue item
item = BPlan(
Expand Down
83 changes: 50 additions & 33 deletions src/firefly/plans/xafs_scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,52 +18,56 @@
merge_ranges,
wavenumber_to_energy,
)

log = logging.getLogger(__name__)

#TODO solve Python decimal
# TODO solve Python decimal
float_accuracy = 4


# the energy resolution will not be better than 0.01 eV at S25, e.g., 0.01 eV /4000 eV -> 10-6 level, Si(311) is 10-5 level
def wavenumber_to_energy_round(wavenumber):
return round(wavenumber_to_energy(wavenumber), 2)


def k_step_to_E_step_round(k_start, k_step):
return round(k_step_to_E_step(k_start, k_step), 2)


class TitleRegion:
def __init__(self):
self.setup_ui()

def setup_ui(self):
self.layout = QtWidgets.QHBoxLayout()

# Enable checkbox
self.regions_all_checkbox = QtWidgets.QCheckBox()
self.regions_all_checkbox.setChecked(True)
self.regions_all_checkbox.setFixedWidth(15)

self.layout.addWidget(self.regions_all_checkbox)

labels = ['Start', 'Stop', 'Step', 'Weight', '', 'Exposure [s]']
labels = ["Start", "Stop", "Step", "Weight", "", "Exposure [s]"]
Qlabels_all = {}
for label_i in labels:
Qlabel_i = QtWidgets.QLabel(label_i)
self.layout.addWidget(Qlabel_i)
Qlabels_all[label_i] = Qlabel_i

# fix widths so the labels are aligned with XafsRegions
Qlabels_all['Weight'].setFixedWidth(57)
Qlabels_all[''].setFixedWidth(57)
Qlabels_all['Exposure [s]'].setFixedWidth(68)
Qlabels_all["Weight"].setFixedWidth(57)
Qlabels_all[""].setFixedWidth(57)
Qlabels_all["Exposure [s]"].setFixedWidth(68)


class XafsScanRegion:
def __init__(self):
self.setup_ui()

def setup_ui(self):
self.layout = QtWidgets.QHBoxLayout()

# Enable checkbox
self.region_checkbox = QtWidgets.QCheckBox()
self.region_checkbox.setChecked(True)
Expand All @@ -83,7 +87,9 @@ def setup_ui(self):

# Energy step box
self.step_line_edit = QtWidgets.QLineEdit()
self.step_line_edit.setValidator(QDoubleValidator(0.0, float('inf'), 2)) # only takes positive floats
self.step_line_edit.setValidator(
QDoubleValidator(0.0, float("inf"), 2)
) # only takes positive floats
self.step_line_edit.setPlaceholderText("Step…")
self.layout.addWidget(self.step_line_edit)

Expand All @@ -97,7 +103,7 @@ def setup_ui(self):
self.k_space_checkbox.setText("k-space")
self.k_space_checkbox.setEnabled(True)
self.layout.addWidget(self.k_space_checkbox)

# Exposure time double spin box
self.exposure_time_spinbox = QtWidgets.QDoubleSpinBox()
self.exposure_time_spinbox.setValue(1)
Expand All @@ -120,11 +126,9 @@ def update_wavenumber_energy(self):
self.step_line_edit: E_step_to_k_step
if is_k_checked
else lambda x, y: k_step_to_E_step_round(x, y),

self.start_line_edit: energy_to_wavenumber
if is_k_checked
else wavenumber_to_energy_round,

self.stop_line_edit: energy_to_wavenumber
if is_k_checked
else wavenumber_to_energy_round,
Expand All @@ -138,7 +142,9 @@ def update_wavenumber_energy(self):
if start_text and line_edit.text():
start = float(start_text)
step = float(line_edit.text())
new_values = func(start, step) if is_k_checked else func(start, step)
new_values = (
func(start, step) if is_k_checked else func(start, step)
)
line_edit.setText(f"{new_values:.4g}")
else:
self.update_line_edit_value(line_edit, func)
Expand Down Expand Up @@ -174,7 +180,7 @@ def customize_ui(self):
combo_box.addItems(["Select edge…", *items])

# Connect the E0 checkbox to the E0 combobox
self.ui.use_edge_checkbox.stateChanged.connect(self.use_edge)
self.ui.use_edge_checkbox.stateChanged.connect(self.use_edge)

# disable the line edits in spin box
self.ui.regions_spin_box.lineEdit().setReadOnly(True)
Expand All @@ -187,12 +193,14 @@ def customize_ui(self):
self.ui.pushButton.clicked.connect(self.reset_default_regions)

# for testing
#TODO remove the following after testing
# TODO remove the following after testing
self.ui.run_button.setEnabled(True)
self.ui.run_button.clicked.connect(self.queue_plan)
self.ui.run_button.clicked.connect(self.queue_plan)

# connect checkboxes with all regions' check box
self.title_region.regions_all_checkbox.stateChanged.connect(self.on_regions_all_checkbox)
self.title_region.regions_all_checkbox.stateChanged.connect(
self.on_regions_all_checkbox
)

def on_region_checkbox(self):
for region_i in self.regions:
Expand All @@ -207,20 +215,23 @@ def on_region_checkbox(self):
else:
region_i.k_space_checkbox.setEnabled(is_region_i_checked)


def on_regions_all_checkbox(self, is_checked):
for region_i in self.regions:
region_i.region_checkbox.setChecked(is_checked)

def use_edge(self, is_checked):
self.edge_combo_box.setEnabled(is_checked)

# extract edge values
match = re.findall(r"\d+\.?\d*", self.edge_combo_box.currentText())
self.edge_value = round(float(match[-1]), float_accuracy) if match else 0

# iterate through selected regions
checked_regions = [region_i for region_i in self.regions if region_i.region_checkbox.isChecked()]
checked_regions = [
region_i
for region_i in self.regions
if region_i.region_checkbox.isChecked()
]
for region_i in checked_regions:
# Adjust checkbox based on use_edge_checkbox state
region_i.k_space_checkbox.setEnabled(is_checked)
Expand Down Expand Up @@ -264,7 +275,6 @@ def reset_default_regions(self):
region_i.stop_line_edit.setText(str(default_regions[i][1]))
region_i.step_line_edit.setText(str(default_regions[i][2]))


def add_regions(self, num=1):
for i in range(num):
region = XafsScanRegion()
Expand Down Expand Up @@ -293,14 +303,17 @@ def update_regions(self):
elif diff_region_num > 0:
self.add_regions(diff_region_num)


def queue_plan(self, *args, **kwargs):
"""Execute this plan on the queueserver."""
# get paramters from each rows of line regions:
energy_ranges_all = []

# iterate through only selected regions
checked_regions = [region_i for region_i in self.regions if region_i.region_checkbox.isChecked()]
checked_regions = [
region_i
for region_i in self.regions
if region_i.region_checkbox.isChecked()
]
for region_i in checked_regions:
try:
start = round(float(region_i.start_line_edit.text()), float_accuracy)
Expand All @@ -309,7 +322,9 @@ def queue_plan(self, *args, **kwargs):
weight = region_i.weight_spinbox.value()
exposure_time = region_i.exposure_time_spinbox.value()
except ValueError:
QtWidgets.QMessageBox.warning(self, "Value Error", "Invalid value detected!")
QtWidgets.QMessageBox.warning(
self, "Value Error", "Invalid value detected!"
)
return None
if region_i.k_space_checkbox.isChecked():
energy_ranges_all.append(
Expand Down Expand Up @@ -338,8 +353,10 @@ def queue_plan(self, *args, **kwargs):
energies = list(np.round(energies, float_accuracy))
exposures = list(np.round(exposures, float_accuracy))
detectors = self.ui.detectors_list.selected_detectors()
md={'sample': self.ui.lineEdit_sample.text(),
'purpose':self.ui.lineEdit_purpose.text()}
md = {
"sample": self.ui.lineEdit_sample.text(),
"purpose": self.ui.lineEdit_purpose.text(),
}

# Check that an absorption edge was selected
if self.use_edge_checkbox.isChecked():
Expand All @@ -348,29 +365,29 @@ def queue_plan(self, *args, **kwargs):
self.edge_value = round(float(match[-1]), float_accuracy)

except:
QtWidgets.QMessageBox.warning(self, "Error", "Please select an absorption edge.")
QtWidgets.QMessageBox.warning(
self, "Error", "Please select an absorption edge."
)
return None
else:
self.edge_value = 0
# Build the queue item
item = BPlan(
'energy_scan',
"energy_scan",
energies=energies,
exposure=exposures,
E0=self.edge_value,
detectors=detectors,
md=md,
)
)

print(item)
print(energies, exposures, self.edge_value, detectors, md)


# Submit the item to the queueserver
app = FireflyApplication.instance()
log.info("Add ``scan()`` plan to queue.")
app.add_queue_item(item)


def ui_filename(self):
return "plans/xafs_scan.ui"
Expand Down
Loading

0 comments on commit eec6174

Please sign in to comment.