refactor daily and weekly setup and update PXII calibration routines
CI for pxii_bec / test (push) Successful in 1m3s

This commit is contained in:
x10sa committed 2026-10-11 12:11:44 +02:00
1 parent db244b4936
commit 6f5e45de71
14 files changed
+1914 -1107

No files matched your search

@@ -0,0 +1,605 @@
[BECDockArea]
acceptDrops=false
accessibleDescription=
accessibleIdentifier=
accessibleName=
autoFillBackground=false
baseSize=@Size(0 0)
contextMenuPolicy=@Variant(\0\0\0\x7f\0\0\0\x16Qt::ContextMenuPolicy\0\0\0\0\x1)
cursor=@Variant(\0\0\0J\0\0)
enabled=true
focusPolicy=@Variant(\0\0\0\x7f\0\0\0\x10Qt::FocusPolicy\0\0\0\0\0)
geometry=@Rect(0 23 1142 746)
inputMethodHints=@Variant(\0\0\0\x7f\0\0\0\x14Qt::InputMethodHint\0\0\0\0\0)
layoutDirection=@Variant(\0\0\0\x7f\0\0\0\x14Qt::LayoutDirection\0\0\0\0\0)
maximumSize=@Size(16777215 16777215)
minimumSize=@Size(0 0)
mode=creator
mouseTracking=false
sizeIncrement=@Size(0 0)
sizePolicy=@Variant(\0\0\0K\0\0\0U)
statusTip=
tabletTracking=false
toolTip=
toolTipDuration=-1
whatsThis=
windowFilePath=
windowModality=@Variant(\0\0\0\x7f\0\0\0\x13Qt::WindowModality\0\0\0\0\0)
windowModified=false
windowOpacity=1
windowTitle=BEC - DailySetup
workspace_is_locked=false
[BECDockArea.ads%3A%3ACDockManager.ads%3A%3ACDockSplitter.ads%3A%3ACDockAreaWidget.Info.dockWidgetScrollArea.qt_scrollarea_viewport.Info]
acceptDrops=false
accessibleDescription=
accessibleIdentifier=
accessibleName=
autoFillBackground=true
baseSize=@Size(0 0)
contextMenuPolicy=@Variant(\0\0\0\x7f\0\0\0\x16Qt::ContextMenuPolicy\0\0\0\0\x1)
cursor=@Variant(\0\0\0J\0\0)
enabled=true
focusPolicy=@Variant(\0\0\0\x7f\0\0\0\x10Qt::FocusPolicy\0\0\0\0\0)
geometry=@Rect(0 0 408 667)
html_text="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n<html><head><meta name=\"qrichtext\" content=\"1\" /><meta charset=\"utf-8\" /><style type=\"text/css\">\np, li { white-space: pre-wrap; }\nhr { height: 1px; border-width: 0; }\nli.unchecked::marker { content: \"\\2610\"; }\nli.checked::marker { content: \"\\2612\"; }\n</style></head><body style=\" font-family:'Cantarell'; font-size:11pt; font-weight:400; font-style:normal;\">\n<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p></body></html>"
inputMethodHints=@Variant(\0\0\0\x7f\0\0\0\x14Qt::InputMethodHint\0\0\0\0\0)
layoutDirection=@Variant(\0\0\0\x7f\0\0\0\x14Qt::LayoutDirection\0\0\0\0\0)
maximumSize=@Size(16777215 16777215)
minimumSize=@Size(0 0)
mouseTracking=false
plain_text=
sizeIncrement=@Size(0 0)
sizePolicy=@Variant(\0\0\0K\0\0\0U)
statusTip=
tabletTracking=false
toolTip=
toolTipDuration=-1
whatsThis=
windowFilePath=
windowModality=@Variant(\0\0\0\x7f\0\0\0\x13Qt::WindowModality\0\0\0\0\0)
windowModified=false
windowOpacity=1
windowTitle=
[BECDockArea.ads%3A%3ACDockManager.ads%3A%3ACDockSplitter.ads%3A%3ACDockAreaWidget.Progress.dockWidgetScrollArea.qt_scrollarea_viewport.Progress]
acceptDrops=false
accessibleDescription=
accessibleIdentifier=
accessibleName=
autoFillBackground=true
baseSize=@Size(0 0)
contextMenuPolicy=@Variant(\0\0\0\x7f\0\0\0\x16Qt::ContextMenuPolicy\0\0\0\0\x1)
cursor=@Variant(\0\0\0J\0\0)
enabled=true
focusPolicy=@Variant(\0\0\0\x7f\0\0\0\x10Qt::FocusPolicy\0\0\0\0\0)
geometry=@Rect(0 0 201 667)
html_text="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n<html><head><meta name=\"qrichtext\" content=\"1\" /><meta charset=\"utf-8\" /><style type=\"text/css\">\np, li { white-space: pre-wrap; }\nhr { height: 1px; border-width: 0; }\nli.unchecked::marker { content: \"\\2610\"; }\nli.checked::marker { content: \"\\2612\"; }\n</style></head><body style=\" font-family:'Cantarell'; font-size:11pt; font-weight:400; font-style:normal;\">\n<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p></body></html>"
inputMethodHints=@Variant(\0\0\0\x7f\0\0\0\x14Qt::InputMethodHint\0\0\0\0\0)
layoutDirection=@Variant(\0\0\0\x7f\0\0\0\x14Qt::LayoutDirection\0\0\0\0\0)
maximumSize=@Size(16777215 16777215)
minimumSize=@Size(0 0)
mouseTracking=false
plain_text=
sizeIncrement=@Size(0 0)
sizePolicy=@Variant(\0\0\0K\0\0\0U)
statusTip=
tabletTracking=false
toolTip=
toolTipDuration=-1
whatsThis=
windowFilePath=
windowModality=@Variant(\0\0\0\x7f\0\0\0\x13Qt::WindowModality\0\0\0\0\0)
windowModified=false
windowOpacity=1
windowTitle=
[BECDockArea.ads%3A%3ACDockManager.ads%3A%3ACDockSplitter.ads%3A%3ACDockSplitter.ads%3A%3ACDockAreaWidget.Plot_1.dockWidgetScrollArea.qt_scrollarea_viewport.Plot_1]
acceptDrops=false
accessibleDescription=
accessibleIdentifier=
accessibleName=
autoFillBackground=true
auto_range_x=true
auto_range_y=true
baseSize=@Size(0 0)
color_palette=plasma
contextMenuPolicy=@Variant(\0\0\0\x7f\0\0\0\x16Qt::ContextMenuPolicy\0\0\0\0\x1)
cursor=@Variant(\0\0\0J\0\0)
curve_json=[]
enable_fps_monitor=false
enable_popups=true
enable_side_panel=false
enable_toolbar=true
enabled=true
focusPolicy=@Variant(\0\0\0\x7f\0\0\0\x10Qt::FocusPolicy\0\0\0\0\0)
geometry=@Rect(0 0 242 194)
inner_axes=true
inputMethodHints=@Variant(\0\0\0\x7f\0\0\0\x14Qt::InputMethodHint\0\0\0\0\0)
invert_x=false
invert_y=false
layoutDirection=@Variant(\0\0\0\x7f\0\0\0\x14Qt::LayoutDirection\0\0\0\0\0)
legend_label_size=9
lock_aspect_ratio=false
max_dataset_size_mb=10
maximumSize=@Size(16777215 16777215)
minimal_crosshair_precision=3
minimumSize=@Size(0 0)
mouseTracking=false
outer_axes=false
signal_x=
sizeIncrement=@Size(0 0)
sizePolicy=@Variant(\0\0\0K\0\0\0U)
skip_large_dataset_check=false
skip_large_dataset_warning=false
statusTip=
tabletTracking=false
title=
toolTip=
toolTipDuration=-1
whatsThis=
windowFilePath=
windowModality=@Variant(\0\0\0\x7f\0\0\0\x13Qt::WindowModality\0\0\0\0\0)
windowModified=false
windowOpacity=1
windowTitle=
x_grid=false
x_label=
x_limits=@Variant(\0\0\0\x1a\0\0\0\0\0\0\0\0?\xf0\0\0\0\0\0\0)
x_log=false
x_mode=auto
y_grid=false
y_label=
y_limits=@Variant(\0\0\0\x1a\0\0\0\0\0\0\0\0?\xf0\0\0\0\0\0\0)
y_log=false
[BECDockArea.ads%3A%3ACDockManager.ads%3A%3ACDockSplitter.ads%3A%3ACDockSplitter.ads%3A%3ACDockAreaWidget.Plot_2.dockWidgetScrollArea.qt_scrollarea_viewport.Plot_2]
acceptDrops=false
accessibleDescription=
accessibleIdentifier=
accessibleName=
autoFillBackground=true
auto_range_x=true
auto_range_y=true
baseSize=@Size(0 0)
color_palette=plasma
contextMenuPolicy=@Variant(\0\0\0\x7f\0\0\0\x16Qt::ContextMenuPolicy\0\0\0\0\x1)
cursor=@Variant(\0\0\0J\0\0)
curve_json=[]
enable_fps_monitor=false
enable_popups=true
enable_side_panel=false
enable_toolbar=true
enabled=true
focusPolicy=@Variant(\0\0\0\x7f\0\0\0\x10Qt::FocusPolicy\0\0\0\0\0)
geometry=@Rect(0 0 243 194)
inner_axes=true
inputMethodHints=@Variant(\0\0\0\x7f\0\0\0\x14Qt::InputMethodHint\0\0\0\0\0)
invert_x=false
invert_y=false
layoutDirection=@Variant(\0\0\0\x7f\0\0\0\x14Qt::LayoutDirection\0\0\0\0\0)
legend_label_size=9
lock_aspect_ratio=false
max_dataset_size_mb=10
maximumSize=@Size(16777215 16777215)
minimal_crosshair_precision=3
minimumSize=@Size(0 0)
mouseTracking=false
outer_axes=false
signal_x=
sizeIncrement=@Size(0 0)
sizePolicy=@Variant(\0\0\0K\0\0\0U)
skip_large_dataset_check=false
skip_large_dataset_warning=false
statusTip=
tabletTracking=false
title=
toolTip=
toolTipDuration=-1
whatsThis=
windowFilePath=
windowModality=@Variant(\0\0\0\x7f\0\0\0\x13Qt::WindowModality\0\0\0\0\0)
windowModified=false
windowOpacity=1
windowTitle=
x_grid=false
x_label=
x_limits=@Variant(\0\0\0\x1a\0\0\0\0\0\0\0\0?\xf0\0\0\0\0\0\0)
x_log=false
x_mode=auto
y_grid=false
y_label=
y_limits=@Variant(\0\0\0\x1a\0\0\0\0\0\0\0\0?\xf0\0\0\0\0\0\0)
y_log=false
[BECDockArea.ads%3A%3ACDockManager.ads%3A%3ACDockSplitter.ads%3A%3ACDockSplitter.ads%3A%3ACDockAreaWidget.Plot_3.dockWidgetScrollArea.qt_scrollarea_viewport.Plot_3]
acceptDrops=false
accessibleDescription=
accessibleIdentifier=
accessibleName=
autoFillBackground=true
auto_range_x=true
auto_range_y=true
baseSize=@Size(0 0)
color_palette=plasma
contextMenuPolicy=@Variant(\0\0\0\x7f\0\0\0\x16Qt::ContextMenuPolicy\0\0\0\0\x1)
cursor=@Variant(\0\0\0J\0\0)
curve_json=[]
enable_fps_monitor=false
enable_popups=true
enable_side_panel=false
enable_toolbar=true
enabled=true
focusPolicy=@Variant(\0\0\0\x7f\0\0\0\x10Qt::FocusPolicy\0\0\0\0\0)
geometry=@Rect(0 0 242 193)
inner_axes=true
inputMethodHints=@Variant(\0\0\0\x7f\0\0\0\x14Qt::InputMethodHint\0\0\0\0\0)
invert_x=false
invert_y=false
layoutDirection=@Variant(\0\0\0\x7f\0\0\0\x14Qt::LayoutDirection\0\0\0\0\0)
legend_label_size=9
lock_aspect_ratio=false
max_dataset_size_mb=10
maximumSize=@Size(16777215 16777215)
minimal_crosshair_precision=3
minimumSize=@Size(0 0)
mouseTracking=false
outer_axes=false
signal_x=
sizeIncrement=@Size(0 0)
sizePolicy=@Variant(\0\0\0K\0\0\0U)
skip_large_dataset_check=false
skip_large_dataset_warning=false
statusTip=
tabletTracking=false
title=
toolTip=
toolTipDuration=-1
whatsThis=
windowFilePath=
windowModality=@Variant(\0\0\0\x7f\0\0\0\x13Qt::WindowModality\0\0\0\0\0)
windowModified=false
windowOpacity=1
windowTitle=
x_grid=false
x_label=
x_limits=@Variant(\0\0\0\x1a\0\0\0\0\0\0\0\0?\xf0\0\0\0\0\0\0)
x_log=false
x_mode=auto
y_grid=false
y_label=
y_limits=@Variant(\0\0\0\x1a\0\0\0\0\0\0\0\0?\xf0\0\0\0\0\0\0)
y_log=false
[BECDockArea.ads%3A%3ACDockManager.ads%3A%3ACDockSplitter.ads%3A%3ACDockSplitter.ads%3A%3ACDockAreaWidget.Plot_4.dockWidgetScrollArea.qt_scrollarea_viewport.Plot_4]
acceptDrops=false
accessibleDescription=
accessibleIdentifier=
accessibleName=
autoFillBackground=true
auto_range_x=true
auto_range_y=true
baseSize=@Size(0 0)
color_palette=plasma
contextMenuPolicy=@Variant(\0\0\0\x7f\0\0\0\x16Qt::ContextMenuPolicy\0\0\0\0\x1)
cursor=@Variant(\0\0\0J\0\0)
curve_json=[]
enable_fps_monitor=false
enable_popups=true
enable_side_panel=false
enable_toolbar=true
enabled=true
focusPolicy=@Variant(\0\0\0\x7f\0\0\0\x10Qt::FocusPolicy\0\0\0\0\0)
geometry=@Rect(0 0 243 193)
inner_axes=true
inputMethodHints=@Variant(\0\0\0\x7f\0\0\0\x14Qt::InputMethodHint\0\0\0\0\0)
invert_x=false
invert_y=false
layoutDirection=@Variant(\0\0\0\x7f\0\0\0\x14Qt::LayoutDirection\0\0\0\0\0)
legend_label_size=9
lock_aspect_ratio=false
max_dataset_size_mb=10
maximumSize=@Size(16777215 16777215)
minimal_crosshair_precision=3
minimumSize=@Size(0 0)
mouseTracking=false
outer_axes=false
signal_x=
sizeIncrement=@Size(0 0)
sizePolicy=@Variant(\0\0\0K\0\0\0U)
skip_large_dataset_check=false
skip_large_dataset_warning=false
statusTip=
tabletTracking=false
title=
toolTip=
toolTipDuration=-1
whatsThis=
windowFilePath=
windowModality=@Variant(\0\0\0\x7f\0\0\0\x13Qt::WindowModality\0\0\0\0\0)
windowModified=false
windowOpacity=1
windowTitle=
x_grid=false
x_label=
x_limits=@Variant(\0\0\0\x1a\0\0\0\0\0\0\0\0?\xf0\0\0\0\0\0\0)
x_log=false
x_mode=auto
y_grid=false
y_label=
y_limits=@Variant(\0\0\0\x1a\0\0\0\0\0\0\0\0?\xf0\0\0\0\0\0\0)
y_log=false
[BECDockArea.ads%3A%3ACDockManager.ads%3A%3ACDockSplitter.ads%3A%3ACDockSplitter.ads%3A%3ACDockAreaWidget.Plot_5.dockWidgetScrollArea.qt_scrollarea_viewport.Plot_5]
acceptDrops=false
accessibleDescription=
accessibleIdentifier=
accessibleName=
autoFillBackground=true
auto_range_x=true
auto_range_y=true
baseSize=@Size(0 0)
color_palette=plasma
contextMenuPolicy=@Variant(\0\0\0\x7f\0\0\0\x16Qt::ContextMenuPolicy\0\0\0\0\x1)
cursor=@Variant(\0\0\0J\0\0)
curve_json=[]
enable_fps_monitor=false
enable_popups=true
enable_side_panel=false
enable_toolbar=true
enabled=true
focusPolicy=@Variant(\0\0\0\x7f\0\0\0\x10Qt::FocusPolicy\0\0\0\0\0)
geometry=@Rect(0 0 242 194)
inner_axes=true
inputMethodHints=@Variant(\0\0\0\x7f\0\0\0\x14Qt::InputMethodHint\0\0\0\0\0)
invert_x=false
invert_y=false
layoutDirection=@Variant(\0\0\0\x7f\0\0\0\x14Qt::LayoutDirection\0\0\0\0\0)
legend_label_size=9
lock_aspect_ratio=false
max_dataset_size_mb=10
maximumSize=@Size(16777215 16777215)
minimal_crosshair_precision=3
minimumSize=@Size(0 0)
mouseTracking=false
outer_axes=false
signal_x=
sizeIncrement=@Size(0 0)
sizePolicy=@Variant(\0\0\0K\0\0\0U)
skip_large_dataset_check=false
skip_large_dataset_warning=false
statusTip=
tabletTracking=false
title=
toolTip=
toolTipDuration=-1
whatsThis=
windowFilePath=
windowModality=@Variant(\0\0\0\x7f\0\0\0\x13Qt::WindowModality\0\0\0\0\0)
windowModified=false
windowOpacity=1
windowTitle=
x_grid=false
x_label=
x_limits=@Variant(\0\0\0\x1a\0\0\0\0\0\0\0\0?\xf0\0\0\0\0\0\0)
x_log=false
x_mode=auto
y_grid=false
y_label=
y_limits=@Variant(\0\0\0\x1a\0\0\0\0\0\0\0\0?\xf0\0\0\0\0\0\0)
y_log=false
[BECDockArea.ads%3A%3ACDockManager.ads%3A%3ACDockSplitter.ads%3A%3ACDockSplitter.ads%3A%3ACDockAreaWidget.Plot_6.dockWidgetScrollArea.qt_scrollarea_viewport.Plot_6]
acceptDrops=false
accessibleDescription=
accessibleIdentifier=
accessibleName=
autoFillBackground=true
auto_range_x=true
auto_range_y=true
baseSize=@Size(0 0)
color_palette=plasma
contextMenuPolicy=@Variant(\0\0\0\x7f\0\0\0\x16Qt::ContextMenuPolicy\0\0\0\0\x1)
cursor=@Variant(\0\0\0J\0\0)
curve_json=[]
enable_fps_monitor=false
enable_popups=true
enable_side_panel=false
enable_toolbar=true
enabled=true
focusPolicy=@Variant(\0\0\0\x7f\0\0\0\x10Qt::FocusPolicy\0\0\0\0\0)
geometry=@Rect(0 0 243 194)
inner_axes=true
inputMethodHints=@Variant(\0\0\0\x7f\0\0\0\x14Qt::InputMethodHint\0\0\0\0\0)
invert_x=false
invert_y=false
layoutDirection=@Variant(\0\0\0\x7f\0\0\0\x14Qt::LayoutDirection\0\0\0\0\0)
legend_label_size=9
lock_aspect_ratio=false
max_dataset_size_mb=10
maximumSize=@Size(16777215 16777215)
minimal_crosshair_precision=3
minimumSize=@Size(0 0)
mouseTracking=false
outer_axes=false
signal_x=
sizeIncrement=@Size(0 0)
sizePolicy=@Variant(\0\0\0K\0\0\0U)
skip_large_dataset_check=false
skip_large_dataset_warning=false
statusTip=
tabletTracking=false
title=
toolTip=
toolTipDuration=-1
whatsThis=
windowFilePath=
windowModality=@Variant(\0\0\0\x7f\0\0\0\x13Qt::WindowModality\0\0\0\0\0)
windowModified=false
windowOpacity=1
windowTitle=
x_grid=false
x_label=
x_limits=@Variant(\0\0\0\x1a\0\0\0\0\0\0\0\0?\xf0\0\0\0\0\0\0)
x_log=false
x_mode=auto
y_grid=false
y_label=
y_limits=@Variant(\0\0\0\x1a\0\0\0\0\0\0\0\0?\xf0\0\0\0\0\0\0)
y_log=false
[BECDockArea.dockSettingsAction]
autoRepeat=true
checkable=false
checked=false
enabled=true
iconText=Dock settings
iconVisibleInMenu=true
menuRole=@Variant(\0\0\0\x7f\0\0\0\x12QAction::MenuRole\0\0\0\0\x1)
priority=@Variant(\0\0\0\x7f\0\0\0\x12QAction::Priority\0\0\0\0\x80)
shortcut=
shortcutContext=@Variant(\0\0\0\x7f\0\0\0\x14Qt::ShortcutContext\0\0\0\0\x1)
shortcutVisibleInContextMenu=true
statusTip=
text=Dock settings
toolTip=Dock settings
whatsThis=
[Perspectives]
1\Name=BEC - DailySetup
1\State="@ByteArray(\0\0\x3\xd3x\xda\xa5\x93_K\xc3\x30\x14\xc5\xdf\xfd\x14\x97\xbc\xcf\xaei6'\xb4\x1d\xa3\x32\xf0\xc5?l\xd3G\xa9\xed\xb5\x4\xdb\x44\x92l\xa8\xf8\xe1M\xdaQDS\xa1\xec)\xc9\xb9'\xbf{r!\xf1\xf2\xbd\xa9\xe1\x80Js)\x12\x12\x9eO\t\xa0(d\xc9\x45\x95\x90\xddv=Y\x90\x65\x1a\xdf\x9bUy\xc8\x45\x81\xe5\x95,^mm\xf3\xa1\r6\xf0\xd0_$\xb0\xd3\xa8\xfa\xb3\xc5\x64R\x98\x9c\v\xab\xb8r\x1a\xf7gX\xd7\x32\x37m\x83\xa9\xd5\x37o57\xc6\xca\xb7\x8a\xa3\xb5\x98\x16\xf0\xe5\0{a\x12\xc2\xacg\xa5\x30\x87m\xfe\xdc\xa2 \xdb+\x85\xaet\xa7\x64\xa5Pk\xebx\xe4\x65\x85\x6n\xf2\x6\x7f\xe8\x90\xd5Rc\xe9\x1a\x5i\x1c\x38\xcc \xecZ\xbc\xc8\xdf\xa0V\xf3\x42\xfc\xa9'}\xea\xe8\x9f\xd4\xb5\x34O\xe1\x9f\xcc\x9d:&q{%\xf2\x82\xa2\xf1\xa0\x99\x17\x34\x1bx>\xff\x44\x9dRz\t\x94.\xc0\xadq\xd0iv=\x8e\xe6\xf4!Qo$:\xfem\xcc\vb\xe3\x41s/h~\xd2\x90:\xd7\xf4\x2X\xc8\x80\x32\xeb\x64~g\xd0\x7f!\xbb\x1f\xf8\x92\xe9\xd9\x37,-7\xa6)"
size=1
[mainWindow]
DockingState="@ByteArray(\0\0\x3\xd3x\xda\xa5\x93_K\xc3\x30\x14\xc5\xdf\xfd\x14\x97\xbc\xcf\xaei6'\xb4\x1d\xa3\x32\xf0\xc5?l\xd3G\xa9\xed\xb5\x4\xdb\x44\x92l\xa8\xf8\xe1M\xdaQDS\xa1\xec)\xc9\xb9'\xbf{r!\xf1\xf2\xbd\xa9\xe1\x80Js)\x12\x12\x9eO\t\xa0(d\xc9\x45\x95\x90\xddv=Y\x90\x65\x1a\xdf\x9bUy\xc8\x45\x81\xe5\x95,^mm\xf3\xa1\r6\xf0\xd0_$\xb0\xd3\xa8\xfa\xb3\xc5\x64R\x98\x9c\v\xab\xb8r\x1a\xf7gX\xd7\x32\x37m\x83\xa9\xd5\x37o57\xc6\xca\xb7\x8a\xa3\xb5\x98\x16\xf0\xe5\0{a\x12\xc2\xacg\xa5\x30\x87m\xfe\xdc\xa2 \xdb+\x85\xaet\xa7\x64\xa5Pk\xebx\xe4\x65\x85\x6n\xf2\x6\x7f\xe8\x90\xd5Rc\xe9\x1a\x5i\x1c\x38\xcc \xecZ\xbc\xc8\xdf\xa0V\xf3\x42\xfc\xa9'}\xea\xe8\x9f\xd4\xb5\x34O\xe1\x9f\xcc\x9d:&q{%\xf2\x82\xa2\xf1\xa0\x99\x17\x34\x1bx>\xff\x44\x9dRz\t\x94.\xc0\xadq\xd0iv=\x8e\xe6\xf4!Qo$:\xfem\xcc\vb\xe3\x41s/h~\xd2\x90:\xd7\xf4\x2X\xc8\x80\x32\xeb\x64~g\xd0\x7f!\xbb\x1f\xf8\x92\xe9\xd9\x37,-7\xa6)"
Geometry=@ByteArray(\x1\xd9\xd0\xcb\0\x3\0\0\0\0\0\0\0\0\0\x17\0\0\x4u\0\0\x3\0\0\0\0\0\0\0\0\0\xff\xff\xff\xff\xff\xff\xff\xff\0\0\0\0\0\0\0\0\xf\0\0\0\0\0\0\0\0\x17\0\0\x4u\0\0\x3\0)
State=@Variant(\0\0\0\x7f\0\0\0\x18PySide::PyObjectWrapper\0\0\0\0\xf\x80\x4\x95\x4\0\0\0\0\0\0\0\x43\0\x94.)
[manifest]
widgets\1\closable=true
widgets\1\floatable=true
widgets\1\floating=false
widgets\1\floating_abs_h=0
widgets\1\floating_abs_w=0
widgets\1\floating_abs_x=0
widgets\1\floating_abs_y=0
widgets\1\floating_rel_h=0
widgets\1\floating_rel_w=0
widgets\1\floating_rel_x=0
widgets\1\floating_rel_y=0
widgets\1\floating_screen=
widgets\1\movable=true
widgets\1\object_name=Info
widgets\1\widget_class=TextBox
widgets\2\closable=true
widgets\2\floatable=true
widgets\2\floating=false
widgets\2\floating_abs_h=0
widgets\2\floating_abs_w=0
widgets\2\floating_abs_x=0
widgets\2\floating_abs_y=0
widgets\2\floating_rel_h=0
widgets\2\floating_rel_w=0
widgets\2\floating_rel_x=0
widgets\2\floating_rel_y=0
widgets\2\floating_screen=
widgets\2\movable=true
widgets\2\object_name=Plot_1
widgets\2\widget_class=Waveform
widgets\3\closable=true
widgets\3\floatable=true
widgets\3\floating=false
widgets\3\floating_abs_h=0
widgets\3\floating_abs_w=0
widgets\3\floating_abs_x=0
widgets\3\floating_abs_y=0
widgets\3\floating_rel_h=0
widgets\3\floating_rel_w=0
widgets\3\floating_rel_x=0
widgets\3\floating_rel_y=0
widgets\3\floating_screen=
widgets\3\movable=true
widgets\3\object_name=Plot_2
widgets\3\widget_class=Waveform
widgets\4\closable=true
widgets\4\floatable=true
widgets\4\floating=false
widgets\4\floating_abs_h=0
widgets\4\floating_abs_w=0
widgets\4\floating_abs_x=0
widgets\4\floating_abs_y=0
widgets\4\floating_rel_h=0
widgets\4\floating_rel_w=0
widgets\4\floating_rel_x=0
widgets\4\floating_rel_y=0
widgets\4\floating_screen=
widgets\4\movable=true
widgets\4\object_name=Plot_3
widgets\4\widget_class=Waveform
widgets\5\closable=true
widgets\5\floatable=true
widgets\5\floating=false
widgets\5\floating_abs_h=0
widgets\5\floating_abs_w=0
widgets\5\floating_abs_x=0
widgets\5\floating_abs_y=0
widgets\5\floating_rel_h=0
widgets\5\floating_rel_w=0
widgets\5\floating_rel_x=0
widgets\5\floating_rel_y=0
widgets\5\floating_screen=
widgets\5\movable=true
widgets\5\object_name=Plot_4
widgets\5\widget_class=Waveform
widgets\6\closable=true
widgets\6\floatable=true
widgets\6\floating=false
widgets\6\floating_abs_h=0
widgets\6\floating_abs_w=0
widgets\6\floating_abs_x=0
widgets\6\floating_abs_y=0
widgets\6\floating_rel_h=0
widgets\6\floating_rel_w=0
widgets\6\floating_rel_x=0
widgets\6\floating_rel_y=0
widgets\6\floating_screen=
widgets\6\movable=true
widgets\6\object_name=Plot_5
widgets\6\widget_class=Waveform
widgets\7\closable=true
widgets\7\floatable=true
widgets\7\floating=false
widgets\7\floating_abs_h=0
widgets\7\floating_abs_w=0
widgets\7\floating_abs_x=0
widgets\7\floating_abs_y=0
widgets\7\floating_rel_h=0
widgets\7\floating_rel_w=0
widgets\7\floating_rel_x=0
widgets\7\floating_rel_y=0
widgets\7\floating_screen=
widgets\7\movable=true
widgets\7\object_name=Plot_6
widgets\7\widget_class=Waveform
widgets\8\closable=true
widgets\8\floatable=true
widgets\8\floating=false
widgets\8\floating_abs_h=0
widgets\8\floating_abs_w=0
widgets\8\floating_abs_x=0
widgets\8\floating_abs_y=0
widgets\8\floating_rel_h=0
widgets\8\floating_rel_w=0
widgets\8\floating_rel_x=0
widgets\8\floating_rel_y=0
widgets\8\floating_screen=
widgets\8\movable=true
widgets\8\object_name=Progress
widgets\8\widget_class=TextBox
widgets\size=8
[profile]
created_at=2026-10-10T16:30:18Z
quick_select=true
screenshot="@ByteArray(\x89PNG\r\n\x1a\n\0\0\0\rIHDR\0\0\x4v\0\0\x2\xea\b\x6\0\0\0PE\xd3\x82\0\0\0\tpHYs\0\0\xe\xc4\0\0\xe\xc4\x1\x95+\xe\x1b\0\0 \0IDATx\x9c\xec\xddwT\x14W\x1b\xc0\xe1\xdfR\xa5\vbA\xb0\xb7\xa8\xd8\xc1\xde{\x8b\x5\x5{Kl\xb1\x63\x8b\xbd\xf7\xde{\x8d\r{\x8f\xc6h\xa2\x31\x89\x1a\x89\xbd\x97\xd8\xc5^@@`\xd9\xfd\xfe\xe0\x63#\xa1,e\x97\x65\xe1}\xce\xf1\x1c\x99\x99\x9d{\xe1\xce;\xe5\xdd{\xef(BB#\xd4\b!\x84\x10\x42\b!\x84\x10\x42\b\xa3\x63\x62\xe8\n\b!\x84\x10\x42\b!\x84\x10\x42\x88\xe4\x91\xc4\x8e\x10\x42\b!\x84\x10\x42\b!\x84\x91\x92\xc4\x8e\x10\x42\b!\x84\x10\x42\b!\x84\x91\x92\xc4N\x1a\xf2\xe4\xf9k\x9e<\x7fm\xe8j\b\x91hr\xcc\x1a'i\xb7\x8cK\xda^\x88\xb8Il\b!\xd2\"97\x89\xc4\x92\xc4\x8e\x10\x42\b!\x84\x10\x42\b!\x84\x91\x92\xc4\x8e\x10\x42\b!\x84\x10\x42\b!\x84\x91\x32\x33t\x5\x84\x10\x42\b!\x84\x30\x16\xc1\xc1\x9f\t\xfc\x14\x8c\x32Re\xe8\xaa\b\x91,\x16\x16\xe6\x64\xb2\xb4\xc0\xc1\xce\xda\xd0U\x11\x42\xe8\x88$v\x84\x10\x42\b!\x84H\x84\x80W\xef\xb0\xb2\x30'\xb7[V\xccL\xa5\xe3\xbb\x30Naa\x11|\f\f\xe5\xe9\xf3\x37\xb8\xe5t6tu\x84H\x91'\xcf_\x93+gVCW\xc3\xe0$\xb1#\x84\x10\x42\b!\x84\x16\xc1\xc1\x9f\xc9\x64i\x8eKvGCWE\x88\x14\xb1\xb4\x34'[VsL\xcd 8$\f\x1bkKCWI\b\x91\x42\xf2U\x83\x10\x42\b!\x84\x10Z\x4~\n&\x9b\xb3\x83\xa1\xab!2\x80;\xff\x4\xa4J9\xe\xf6\x36|\f\fN\x95\xb2\x84\x10\xfa%\x89\x1d!\x84\x10\x42\b!\xb4PF\xaa\x64\xf8\x95HW\xccLM\x89TE\x1a\xba\x1a\x42\b\x1d\x90\xab\x93\x10\x42\b!\x84\x10\x42\b\x91\xce\xa8\xd5j\xd4ju\xaa}N\x18\x8e\xcc\xb1#\x84\x10\x42\b!\x84\x10\"N~\xdbwq\xde\xff\x42\xa2\xb7\xafT\xd1\x93\xd6\xadZ\xea\xb1\x46\"1\xd4j5s\xe7-B\xadV3t\xc8@T*\x15\xc3G\x8c\xc5\xbbuK*V\xf0\x8c\xb1\xed\xd9s\xe7\xd9\xb9k/3\xa6M\xc2\xcc\xcc\x94\x99\xb3\xe6\x11\x16\x1e\xc6\xb8\x31#Q(\x14:\xad\xd3\xc2\xc5\xcby\xf2\xe4i\x8c\xe5\xb9r\xb9\x31\xb0\xffw:-+\xa3\x91\xc4\x8e\x10\x42\b!\x84\x10\x42\x88\x38\x9d\xf7\xbf\xc0\xa1\xc3G(T\xb0\x80\xd6m?}\xfa\xc4\xae\xdd{\t\r\xf9L\xa7N\xed\xf4R\x9f;\xb7\xefr\xe2\xe4)\xbe\xeb\xd5]/\xfb\xd7\xe6\xd1\xa3'l\xdf\xb1\x8b\x97\xaf^S\xbcXQ\xda\xb7\xf3&S\xa6L\x6\xa9Kb,Y\xb6\x12\xb5Z\x8d\xef\xa0\xfe\xec\xda\xbd\x17O\x8f\xb2\xb1\x12;\xf\x1f>b\xd7\xee\xbdL\x9d<\x8ey\xf3\x17\xb1|\xe5\x1a\xfa~\xd7S\xe7uY\xb4\x64\x5\xf3\x17,\xa6X\xd1\xaf\x30\x35\x35\x5@\xa5R\xb1k\xf7\xde\xa8:\xe\xec\xab\xf3\x32S\x9bR\x19\x89J\x15\x89\x85\x85\x45\xaa\x96+\x89\x1d!\x84\x10\x42\b!\x84\x10\xf1*T\xb0\0\a\xf6\xed\xe0\xed\xdb\xb7\xf1ncoo\x8f\xa9\xa9\x19\x43\x86\x8e`\xcc\xf8I\0:O\xee\xdc\xb9}\x97\x36\x1d\xba\xe2\x9c\x35\v]:u\xc0\xda\xdaJ\xa7\xfb\xd7\xe6\xda\xf5\x1b\xb4\xf2\xee@&KK\xdc\xdc\\\xd9\xb7\xff\0\xbb\xf7\xec\x63\xef\x1e?,\xcc\xcdS\xb5.\xda(\x14\n\x86\f\x1e\0\xc0\xe2\xa5+\x88P*\xb5~f\xce\xdc\x85\xac^\xbb\x81~}z1t\xc8\xc0\x14\xf5\xa0\xd9\xb5{/k\xd6m\xd4\xfc\xacV\xc3\xad[\xb7\x19\xd0\xaf\x37\x43\x6\xf\x8c\xb1\xed\xbc\xf9\x8bX\xb0p\tG~:\x86\xc9\x17\x65v\xeb\xda\x99\x36\xde^\xc9\xae\x43j\x89\x88P\xb2r\xf5Zv\xed\xda\xcb\xc3G\x8fY\xbbj\x19u\xea\xd4L\xd5:\x18l\x8e\x9d\xc7\x8f\x1f\x93'\x7fQ\x1e?~\x9c\xac\xf5\t9p\xf0 \r\x1a\x36Ni\x15\xc5\xffU\xaeR\x83\xa3G\x8f&{\xbd\xd0\x8f\x62\xee\x65\xf8\xe5\x97_\f]\x8d\x34\xc9\xd0\xc7\xac\x9c\x83\x92N\xae\tB\b!D\xda\xf6\xf6\xed[<*T\x8f\xf7\xdf\x8fG~\xc2\xcc\xcc\x94\xb9sf\xd0\xa2YS\xc6\x8c\x9f\xc4\xae\xdd{uV\xfe\xed[w\xf0i\xdf\x5\xe7\xacY\xf0\xdb\xbc>\xd5\x93:\0\xb3\xe7.$\xa7K\xe~?\xf5\x33\x87\xf\xee\x66\xcb\xa6\xf5\\\xbb~\x83\xbd\xfb\xe\xa6z]\x12\x43\xa9\x8c\xa4_\xdf^\xf4\xec\xde\x8dU\xab\xd7i\xdd~\xf5\xda\r\xf4\xec\xde\x8d\xfe\xfdz\xa3T\xa6lb\xedw\xef\xdes\xfb\xf6]J\x95p\xa7T\twJ\x97t\xc7wP\x7f\x6\xfb\xe\x88\xb5\xad\xef\xa0\xfe\xf8\xe\xeaO\x99\x92%4\xdb\xdf\xbe}7\xc1\x44\x62Z\xf1\xe8\xd1\x13Zx\xb5\x61\xdf\xbe\x3\x14(\x90\x9f\n\xe5=R=\xa9\x3:\xee\xb1\x13\x12\x12\x42Q\xf7rX\x98\x9bq\xed\x8a?\x96\x96\x96\xba\xdc\xbd\xc6\xaaU\xab\x99:c\x1e\0\x36\xd6\x99\xa8X\xbe\x1cm\xdaxS\xaf^=LLd>\xe8\xc4\xe8\xdb\xb7?\x87\x8e\x1c\xe7\xa7\x1f\xf7\xf2\xd5W_\xe9\xa5\x8cs\xe7\xce\xe1\xd3\xae\xab\xe6\xe7\x12\xc5\x8bP\xa6tI\xbc\xbcZR\xa6L\x99\x14\xef\xff\xc8\xd1\xa3l\xdb\xb6\x9d\x35\xabW\xea\xb4\xab[dd$G\x8f\xfe\xc4o\xbf\xfd\xc6\xd9s\xe7\xb1\xb3\xb3\xa3|y\xf:\xb4oG\x81\x2\xda\xbb\xa0\n\xfdH\x8d\x63v\xf1\xe2%\xdc\xbd{\x8f\x45\x8b\x16\xc4X~\xfa\xf4\xeft\xec\xd2\x83\a\xf7\xae\xc7y\x8e\t\xfd\xfc\x99o\xbe\xe9N\x8f\xee\xdfP\xbbvm\xbd\xd4\xcd\x18\xa5\xd7k\xc2\xf4\xe9\x33\xc8\x94)\x13\xbe\xbe\x83t\xbeo!\x84\xf1\xf2\x1d<\x8c-~\xfb\0\x30\x35\x35\xa1\xa2giJ\x97*\x81\x8fOk\x8a\x16M\xfcuk\xc5\x8aU\\\xb9v\x9d\xa5\x8b\x17\xa0P(\xa8\xdf\xe0k\xda\xf8x\xf1\xed\xb7\xdd\xb4~622\x92\x13'~e\xc7\xce\xdd\xf8\xff}\x99,N\x99)W\xae\x34\xadZ\xb5\xa4\x42yO\xad\x9fW\xa9T\x4\x6\x6\x62mm\x9d\xea\xc3\btI\xa9\x8c\xa4g\xaf>\xd4\xa8^\x95.]:\x19\xba:\x19Ntr\xe7\xf2\x95\xab\x9c\x39{^'\xf3\xed\xdc\xbau\x9b\xb6\x1d\xba\xf1\xfe\xfd{\x9a\x34i\xc0\xa6\xcd\xdb\x62m\x93={v\xdc\xdd\x8b\xe1^\xbc\x98\xde\xe6j\xb9{\xe7\x1eM\x1a\x37\xc0\xce\xde\xe\x80\x8a\x15<\xc9\x91=;\xf7\xee\xde\xd3Ky)5b\xd4\xb8$'\xd7V\xadY\xcf\xaa\x35\xebi\xdd\xaa%sgOKQ\xf9\x66\x66\x66\xcc\x9c\x31\x45\xebv\n\x85\x82\x41\x3\xfa\xc4X\xb6'\x8d&\xcb\xbe\x14\x11\xa1\xa4O\xbf\x41\xe4\xca\xe5Line truncated
screenshot_at=2026-10-10T20:20:15Z
+13 -11
View File
@@ -560,6 +560,8 @@ dcm_pitch:
enabled: true
onFailure: buffer
readoutPriority: baseline
userParameter:
offset: 0
dcm_x:
description: DCM Lateral
deviceClass: ophyd_devices.EpicsMotorEC
@@ -1310,6 +1312,17 @@ samcam_sigma:
onFailure: buffer
readOnly: true
readoutPriority: monitored
samcam_thresh:
description: Sample Camera Threshold
deviceClass: ophyd.EpicsSignal
deviceConfig:
auto_monitor: true
read_pv: X10SA-ES-MS:Stats5:CentroidThreshold
deviceTags:
- scam
enabled: true
onFailure: buffer
readoutPriority: baseline
samcam_x:
description: Sample Camera X
deviceClass: ophyd.EpicsSignalRO
@@ -1333,17 +1346,6 @@ samcam_xcurs:
enabled: true
onFailure: buffer
readoutPriority: baseline
samcam_thresh:
description: Sample Camera Threshold
deviceClass: ophyd.EpicsSignal
deviceConfig:
auto_monitor: true
read_pv: X10SA-ES-MS:Stats5:CentroidThreshold
deviceTags:
- scam
enabled: true
onFailure: buffer
readoutPriority: baseline
samcam_xcursprof:
description: Sample Camera X Cursor Profile
deviceClass: ophyd.EpicsSignalRO
+67 -5
View File
@@ -12,7 +12,7 @@ from pxii_bec.scripts import beamline_context as bl
def get_data(filename):
"""Open the raw DCM calibration data file."""
filename = bl.env.lut_dir / f"{filename}.csv"
filename = bl.env.lut_dir / f"{filename}"
return pd.read_csv(filename)
@@ -168,8 +168,69 @@ def lut_plot(
return fit
def pitch_analysis(filename, save=False):
"""Compare DCM pitch calibration against energy and Bragg angle."""
def pitch_analysis(filename, fit_order=3, save=False):
df = get_data(filename)
fits = {}
for xname, fit_order in [("energy", 4), ("bragg", 2)]:
x = df[xname].to_numpy()
pitch = df["pitch"].to_numpy()
fit = lut_plot(
df[[xname, "pitch"]].to_numpy(),
xname="Energy" if xname == "energy" else "Bragg angle",
yname="pitch",
title=f"DCM_Pitch_Calibration_{xname}",
fit_order=fit_order,
save=save,
)
# Calculate residuals
fitted_pitch = np.polyval(fit, x)
residuals = pitch - fitted_pitch
rms = np.sqrt(np.mean(residuals**2))
max_residual = np.max(np.abs(residuals))
print(f"\n{xname.capitalize()} fit (order {fit_order})")
print(f"RMS residual: {rms:.6g}")
print(f"Max residual: {max_residual:.6g}")
for xi, residual in zip(x, residuals):
print(f" {xi:10.3f}: {residual:+.6g}")
fits[xname] = {
"fit": fit,
"residuals": residuals,
"rms": rms,
"max_residual": max_residual,
}
return fits
def pitch_analysis_bragg(filename, fit_order=2, save=False):
"""Fit and plot the DCM pitch calibration."""
df = get_data(filename)
pitch = df[["bragg", "pitch"]]
fit = lut_plot(
pitch.to_numpy(),
xname="Bragg angle",
yname="pitch",
title="DCM_Pitch_Calibration",
fit_order=fit_order,
save=save,
)
return fit
def pitch_analysis_energy(filename, fit_order=3, save=False):
"""Fit and plot the DCM pitch calibration."""
df = get_data(filename)
@@ -328,8 +389,8 @@ def ge_edge_analysis(filename, save=False):
# ----------------------------------------------------------
if save:
signal_file = bl.env.lut_dir / f"{filename}_signal.png"
derivative_file = bl.env.lut_dir / f"{filename}_derivative.png"
signal_file = bl.env.daily_setup_dir / "Ge_edge_signal.png"
derivative_file = bl.env.daily_setup_dir / "Ge_edge_derivative.png"
fig1.savefig(signal_file, bbox_inches="tight", dpi=150)
fig2.savefig(derivative_file, bbox_inches="tight", dpi=150)
@@ -347,7 +408,8 @@ def ge_edge_analysis(filename, save=False):
"expected_edge": expected_edge,
"measured_edge": measured_edge,
"energy_offset": energy_offset,
"derivative": derivative,
"signal_png": signal_file,
"derivative_png": derivative_file,
}
def perp_analysis(filename):
+23 -7
View File
@@ -6,7 +6,7 @@ import time
import numpy as np
def compute_norm(n_readings=5):
def compute_norm_bcu(n_readings=5):
"""Average normalized BPM X/Y from repeated sets of four channels."""
xn_values = []
@@ -31,20 +31,36 @@ def compute_norm(n_readings=5):
time.sleep(0.1)
return float(np.mean(xn_values)), float(np.mean(yn_values))
return {
"bcu_Xnorm": float(np.mean(xn_values)),
"bcu_Ynorm": float(np.mean(yn_values)),
}
def get_bcu_beampos():
"""Determine beam position"""
bpm_xn, bpm_yn = compute_norm()
"""Determine beam position from BCU BPM"""
# Check that there is a reading first
if get_value(dev.bcu_bpmsum) < 1:
return {
"ok": False,
"message": "Reading too low on BCU BPM"
}
result = compute_norm_bcu()
bpm_x = dev.bcu_bpm_x.position
bpm_y = dev.bcu_bpm_y.position
beam_x = beam_offset_um(bpm_xn, bpm_x, BPM_X_Calibration)
beam_x = beam_offset_um(result["bcu_Xnorm"], bpm_x, BCU_BPM_X_Calibration)
beam_y = beam_offset_um(bpm_yn, bpm_y, BPM_Y_Calibration)
beam_y = beam_offset_um(result["bcu_Ynorm"], bpm_y, BCU_BPM_Y_Calibration)
return beam_x, beam_y
return {
"ok": True,
"bcu_Xnorm": result["bcu_Xnorm"],
"bcu_Ynorm": result["bcu_Ynorm"],
"bcu_x_um": beam_x,
"bcu_y_um": beam_y,
}
def beam_offset_um(bpm_signal, bpm_motor_position, calibration):
+9 -27
View File
@@ -11,32 +11,7 @@ import matplotlib.pyplot as plt
from pxii_bec.scripts import beamline_context as bl
from pxii_bec.macros.beamline_planner import BeamlineState
# def compute_norm(n_readings=5):
# """Average normalized BPM X/Y from repeated sets of four channels."""
# xn_values = []
# yn_values = []
# for _ in range(n_readings):
# bpm1 = dev.bcu_bpm1.read()["bcu_bpm1"]["value"]
# bpm2 = dev.bcu_bpm2.read()["bcu_bpm2"]["value"]
# bpm3 = dev.bcu_bpm3.read()["bcu_bpm3"]["value"]
# bpm4 = dev.bcu_bpm4.read()["bcu_bpm4"]["value"]
# total = bpm1 + bpm2 + bpm3 + bpm4
# if total == 0:
# continue
# xn = ((bpm1 + bpm2) - (bpm3 + bpm4)) / total
# yn = ((bpm1 + bpm3) - (bpm2 + bpm4)) / total
# xn_values.append(xn)
# yn_values.append(yn)
# time.sleep(0.1)
# return float(np.mean(xn_values)), float(np.mean(yn_values))
def compute_norm_ss(n_readings=5):
"""Average normalized BPM X/Y from repeated sets of four channels."""
@@ -62,7 +37,10 @@ def compute_norm_ss(n_readings=5):
time.sleep(0.1)
return float(np.mean(xn_values)), float(np.mean(yn_values))
return {
"ss_Xnorm": float(np.mean(xn_values)),
"ss_Ynorm": float(np.mean(yn_values)),
}
def compute_norm_lu(n_readings=5):
@@ -90,7 +68,11 @@ def compute_norm_lu(n_readings=5):
time.sleep(0.1)
return float(np.mean(xn_values)), float(np.mean(yn_values))
return {
"lu_Xnorm": float(np.mean(xn_values)),
"lu_Ynorm": float(np.mean(yn_values)),
}
def run_calibration_ss():
+29
View File
@@ -0,0 +1,29 @@
def create_daily_setup():
dock = bec.gui.new("DailySetup")
# plot1 = dock.new(widget="Waveform", object_name= "Plot_1")
# plot2 = dock.new(widget="Waveform", object_name= "Plot_2", relative_to="Plot_1", where="bottom")
# plot3 = dock.new(widget="Waveform", object_name= "Plot_3", relative_to = "Plot_2", where="bottom")
# plot4 = dock.new(widget="Waveform", object_name= "Plot_4", relative_to="Plot_1", where="right")
# plot5 = dock.new(widget="Waveform", object_name= "Plot_5", relative_to="Plot_2", where="right")
# plot6 = dock.new(widget="Waveform", object_name= "Plot_6", relative_to="Plot_3", where="right")
# log = dock.new(widget="TextBox", object_name= "Info", relative_to="Plot_1",where="left")
# progress = dock.new(widget="TextBox", object_name= "Progress", relative_to="Info", where="left")
progress = dock.new(widget="TextBox", object_name= "Progress")
log = dock.new(widget="TextBox", object_name= "Info", relative_to="Progress", where ="right")
plot1 = dock.new(widget="Waveform", object_name= "Plot_1", relative_to="Info", where ="right")
plot2 = dock.new(widget="Waveform", object_name= "Plot_2", relative_to="Plot_1", where="right")
plot3 = dock.new(widget="Waveform", object_name= "Plot_3", relative_to = "Plot_1", where="bottom")
plot4 = dock.new(widget="Waveform", object_name= "Plot_4", relative_to="Plot_2", where="bottom")
plot5 = dock.new(widget="Waveform", object_name= "Plot_5", relative_to = "Plot_3", where="bottom")
plot6 = dock.new(widget="Waveform", object_name= "Plot_6", relative_to="Plot_4", where="bottom")
dock.set_layout_ratios(
horizontal=[1,2,1.2,1.2],
vertical=[1,1,1],
)
progress.set_plain_text("")
log.set_plain_text("")
dock.save_profile()
+119 -108
View File
@@ -49,33 +49,21 @@ def daily_setup(
align_collimator=False,
measure_flux=True,
save_scilog=True,
weekly=None,
):
"""Run selected daily beamline setup tasks."""
# Check day of the week a and do the weekly and daily checks if a Wednesday
dt = datetime.now()
if dt.weekday() == 2:
scan_slits = True,
ge_scan = True,
check_xbpms = True,
# Weekly checks run automatically on Wednesday unless explicitly overridden.
# Keep this as one task: weekly.py owns the weekly sequence.
if weekly is None:
weekly = datetime.now().weekday() == 2
selected = {
"Pre checks": pre_checks,
"Scan slits": scan_slits,
"Check XBPM positions": check_xbpms,
"Ge scan": ge_scan,
"Set energy": set_energy,
"Move beam": move_beam,
"Measure flux": measure_flux,
}
# If not a Wednesday, only do the daily checks
selected = {
"Pre checks": pre_checks,
"Weekly checks": weekly,
"Set energy": set_energy,
"Move beam": move_beam,
"Align beamstop": align_beamstop,
# "Measure beam position": measure_beampos,
"Align collimator": align_collimator,
"Measure flux": measure_flux,
}
@@ -91,6 +79,10 @@ def daily_setup(
update_progress(ctx.progress, ctx.progress_state)
update_log(ctx.log, ctx.messages, "Starting daily beamline setup")
update_log(ctx.log, ctx.messages,"\nDaily setup normally takes about 1 min.")
update_log(ctx.log, ctx.messages,"\nWith Wednesday checks, allow 8-10 minutes.")
update_log(ctx.log, ctx.messages,"Good time to get a coffee.\n")
try:
# ---------------------------------------------------------
@@ -119,6 +111,15 @@ def daily_setup(
)
return results
# ---------------------------------------------------------
# Weekly checks (Wednesday by default)
# ---------------------------------------------------------
# Machine pre-checks deliberately happen first: the weekly checks move
# beamline hardware and should not bypass the normal safety gate.
if weekly:
with time_step(results, "Weekly checks"):
results["Weekly checks"] = run_weekly_checks(ctx)
# ---------------------------------------------------------
# Set energy
# ---------------------------------------------------------
@@ -130,27 +131,6 @@ def daily_setup(
ctx,
)
# ---------------------------------------------------------
# Scan slits
# ---------------------------------------------------------
if scan_slits:
with time_step(results, "Scan slits"):
results["Scan slits"] = run_weekly_scanslits(ctx)
# ---------------------------------------------------------
# Check XBPM positions
# ---------------------------------------------------------
if check_xbpms:
with time_step(results, "XBPM positions"):
results["Scan slits"] = run_weekly_check_xbpms(ctx)
# ---------------------------------------------------------
# Ge K-edge scan
# ---------------------------------------------------------
if ge_scan:
with time_step(results, "Ge scan"):
results["Scan slits"] = run_weekly_ge_scan(ctx)
# ---------------------------------------------------------
# Move beam
# ---------------------------------------------------------
@@ -244,7 +224,7 @@ def daily_setup(
def get_daily_setup_context(tasks=None):
"""Get widgets and state used by daily setup tasks."""
plot1, plot2, plot3, plot4, log, progress = select_daily_setup_gui()
plot1, plot2, plot3, plot4, plot5, plot6, log, progress = select_daily_setup_gui()
# Clear text from previous run
log.set_plain_text("")
@@ -288,7 +268,6 @@ def run_pre_checks(ctx):
task = "Pre checks"
clear_daily_plots()
set_progress(
ctx.progress,
ctx.progress_state,
@@ -575,7 +554,7 @@ def check_beamstop_position():
if i2 < cutoff:
return {
"ok": True,
"message": f"Beamstop blocking beam: I2 = {i2:.2e}",
"message": f"Beamstop blocking beam: I2 = {i2:.2e}\n",
"value": i2,
"realigned": False,
}
@@ -672,13 +651,60 @@ def check_detector_height():
# Energy
# =============================================================================
def run_weekly_checks(ctx, save_scilog=True):
"""Run weekly beamline checks and report results to Daily Setup GUI."""
task = "Weekly checks"
set_progress(ctx.progress, ctx.progress_state, task, "running")
clear_daily_plots()
try:
result = weekly_checks(save_scilog=save_scilog)
except Exception as exc:
result = {
"ok": False,
"message": f"Weekly checks failed: {exc}",
}
if not result.get("ok", True):
status = "failed"
elif result.get("warning"):
status = "warning"
else:
status = "done"
# Basic summary
lines = []
edge = result.get("edge")
if edge:
lines.append(
f"Ge edge: {edge['measured_edge']:.2f} eV "
f"(expected {edge['expected_edge']:.2f} eV, "
f"offset {edge['energy_offset']:+.2f} eV)"
)
if result.get("edge_warning"):
lines.append(f"WARNING: {result['edge_warning']}")
if result.get("edge_error"):
lines.append(f"ERROR: Ge edge scan failed: {result['edge_error']}")
update_log(ctx.log, ctx.messages, "\n".join(lines))
set_progress(ctx.progress, ctx.progress_state, task, status)
return result
def run_daily_energy(energy, mono_scan, ctx):
"""Set beamline energy and log results."""
task = "Set energy"
clear_daily_plots()
set_progress(ctx.progress, ctx.progress_state, task, "running")
try:
@@ -714,55 +740,6 @@ def run_daily_energy(energy, mono_scan, ctx):
return result
def daily_energy(energy, scan_mono, plot_widget=None):
"""Set the beamline to the required energy and correct gap"""
current_energy = get_current_energy()
if abs(energy - current_energy) > 1:
bl_energy(energy, window_name="DailySetup", plot_widget=plot_widget)
else:
gap_actual = dev.id_gap.position
gap_req = calc_gap(energy)
if abs(gap_actual - gap_req) > 0.05:
if dev.id_gap.moving():
return {
"ok": False,
"message": "Undulator gap is moving",
"energy": current_energy,
}
umv(dev.id_gap, gap_req)
if scan_mono:
mono_result = mono_pitch_scan(window_name="DailySetup", plot_widget=plot_widget)
new_energy = get_current_energy()
calib_pitch = get_dcm_motors_positions(energy)["dcm_pitch"]
pitch_offset = get_value(dev.dcm_pitch) - calib_pitch
if not mono_result["extended_scan"]:
return {
"ok": True,
"message": f"Beamline energy set to {new_energy:.0f} eV, "
f"pitch offset = {pitch_offset:.3f} mrad",
"energy": new_energy,
"pitch_offset": pitch_offset,
}
else:
return {
"ok": True,
"warning": True,
"message": (
f"Warning - DCM pitch is not within expected tolerance"
f"The DCM may need to be re-calibrated. "
f"Pitch offset = {pitch_offset:.3f} mrad"
),
"energy": new_energy,
"pitch_offset": pitch_offset,
}
@@ -797,11 +774,11 @@ def run_daily_movebeam(ctx):
"message": f"Align beam step failed: {exc}",
}
if result.get("ok"):
status = "done"
elif result.get("warning"):
if result.get("warning"):
status = "warning"
elif result.get("ok"):
status = "done"
else:
status = "failed"
@@ -848,9 +825,11 @@ def daily_movebeam(meas="scint", iterations=5):
hfm_start = get_value(hfm_mot)
# Starting BCU BPM offsets
bpm_result = get_bcu_beampos()
bpm_x_start = bpm_result["bcu_x_um"]
bpm_y_start = bpm_result["bcu_y_um"]
# Starting BCU BPM offsets
bpm_x_start, bpm_y_start, bpm_warning_start = read_bcu_beampos_safe()
# bpm_result = get_bcu_beampos()
# bpm_x_start = bpm_result["bcu_x_um"]
# bpm_y_start = bpm_result["bcu_y_um"]
print(
"Moving beam to scintillator crosshair\n"
@@ -1010,9 +989,16 @@ def daily_movebeam(meas="scint", iterations=5):
final_hfm = get_value(hfm_mot)
#Final BCU BPM offsets
bpm_result = get_bcu_beampos()
bpm_x_end = bpm_result["bcu_x_um"]
bpm_y_end = bpm_result["bcu_y_um"]
# bpm_result = get_bcu_beampos()
# bpm_x_end = bpm_result["bcu_x_um"]
# bpm_y_end = bpm_result["bcu_y_um"]
# Final BCU BPM offsets
bpm_x_end, bpm_y_end, bpm_warning_end = read_bcu_beampos_safe()
bpm_warnings = [
w for w in (bpm_warning_start, bpm_warning_end)
if w is not None
]
success = (
abs(diff_x) <= tolerance
@@ -1041,6 +1027,9 @@ def daily_movebeam(meas="scint", iterations=5):
f"{iterations} corrections."
)
warning = True
if bpm_warnings:
message += "\nWARNING: " + " | ".join(bpm_warnings)
warning = True
print(message)
@@ -1078,7 +1067,13 @@ def daily_movebeam(meas="scint", iterations=5):
def format_movebeam_for_gui(result):
"Format move beam output for Daily GUI"
icon = "✓" if result["ok"] else "✗"
if result.get("warning"):
icon = "⚠"
elif result.get("ok"):
icon = "✓"
else:
icon = "✗"
return f"\n{icon} {result['message']}"
@@ -1119,7 +1114,7 @@ def run_daily_beamstop(ctx):
def daily_beamstop():
"""Centre the beamstop against the detector cover diode, i2"""
plot1, plot2, plot3, plot4, log, progress = select_daily_setup_gui()
plot1, plot2, plot3, plot4, plot5, plot6, log, progress = select_daily_setup_gui()
result = {}
@@ -1146,7 +1141,7 @@ def daily_beamstop():
relative=True,
confirm=False,
window_name="DailySetup",
plot_widget=plot2,
plot_widget=plot6,
)
# Wait for bs_y to setlle
time.sleep(2)
@@ -1162,7 +1157,7 @@ def daily_beamstop():
relative=True,
confirm=False,
window_name="DailySetup",
plot_widget=plot1,
plot_widget=plot5,
)
result["bs_x_pos"] = x_result["centre"]
@@ -1391,6 +1386,8 @@ def run_daily_flux(ctx):
set_progress(ctx.progress, ctx.progress_state, task, "running")
try:
dev.transm.put(EnergyDefaults.default_trans)
time.sleep(3)
flux, full_flux = bpm2flux()
message = (
@@ -1427,7 +1424,16 @@ def format_flux_for_gui(result):
# =============================================================================
# Daily-setup GUI helpers
# =============================================================================
def read_bcu_beampos_safe():
"""Read calibrated BCU beam position without failing beam alignment."""
try:
result = get_bcu_beampos()
return result["bcu_x_um"], result["bcu_y_um"], None
except Exception as exc:
warning = f"BCU BPM position unavailable: {exc}"
print(f"WARNING: {warning}")
return None, None, warning
def select_daily_setup_gui():
"""Return widgets belonging to the Daily Setup GUI."""
@@ -1444,7 +1450,7 @@ def select_daily_setup_gui():
# create_empty_daily_report(filename)
# Restore the standard Daily Setup layout
gui.load_profile("daily_setup")
gui.load_profile("DailySetup")
# gui.Report.load_pdf(str(filename))
# gui.Report.fit_to_page()
@@ -1456,17 +1462,21 @@ def select_daily_setup_gui():
gui.Plot_2,
gui.Plot_3,
gui.Plot_4,
gui.Plot_5,
gui.Plot_6,
gui.Info,
gui.Progress,
)
def clear_daily_plots():
plot1, plot2, plot3, plot4, log, progress = select_daily_setup_gui()
plot1, plot2, plot3, plot4, plot5, plot6, log, progress = select_daily_setup_gui()
plot1.clear_all()
plot2.clear_all()
plot3.clear_all()
plot4.clear_all()
plot5.clear_all()
plot6.clear_all()
def update_log(log_box, messages, message):
@@ -2255,6 +2265,7 @@ def create_daily_html_report(results, total_duration=None, messages=None):
task_labels = [
("Pre checks", "Pre checks"),
("Weekly checks", "Weekly checks"),
("Set energy", "Set energy"),
("Move beam", "Move beam to crosshair"),
("Align beamstop", "Align beamstop"),
+372 -373
View File
@@ -657,14 +657,6 @@ def write_lut():
f.write(f"{energy:.0f},{gap:.5g},{pitch:.5g},{roll:.4g},{perp:.5g},{x:.4g},{y:.4g}\n")
def measure_beamsize(cam="samcam"):
a = dev.samcam_xsig.read()["samcam_xsig"]["value"]
b = dev.samcam_ysig.read()["samcam_ysig"]["value"]
zoom = dev.scam_zoom.read()["scam_zoom"]["value"]
sx = calc_scam_microns(a, zoom=zoom) * 2.35
sy = calc_scam_microns(b, zoom=zoom) * 2.35
print(f"FWHM in um : {sx, sy}")
return sx, sy
def write_beamsize():
@@ -685,106 +677,6 @@ def write_beamsize():
f.write(f"{lens_config},{sx:.4g},{sy:.4g},{i1_reading:.4g}\n")
def scan_ge(edge=11103.1, mode="coarse"):
"""
Scan across the Ge K absorption edge.
Parameters
----------
edge : float
Approximate edge energy in eV around which to centre the scan.
mode : {"coarse", "fine"}
coarse : ±100 eV, ~5 eV steps
fine : ±15 eV, ~0.5 eV steps
"""
# Scan settings
if mode == "coarse":
scan_range = 100
scanpoints = 41
elif mode == "fine":
scan_range = 15
scanpoints = 61
else:
raise ValueError(
f"Unknown scan mode '{mode}'. Use 'coarse' or 'fine'."
)
# Energy range
start_eV = edge - scan_range
end_eV = edge + scan_range
# Convert energy limits to Bragg positions
start_bragg = convert_from_energy(start_eV)["bragg_angle_mrad"]
end_bragg = convert_from_energy(end_eV)["bragg_angle_mrad"]
bragg_points = np.linspace(
start_bragg,
end_bragg,
scanpoints,
)
energy_step = (end_eV - start_eV) / (scanpoints - 1)
# Output file
filename = (
bl.env.lut_dir
/ f"{filenow(date_only=True)}_ge_edge_{mode}.csv"
)
with open(filename, "w") as f:
f.write("Energy,Bragg,ss_bpmsum,bcu_bpmsum,transmission\n")
# Move to start
print()
print(f"Ge edge {mode} scan")
print("-------------------")
print(f"Centre: {edge:.1f} eV")
print(f"Range: {start_eV:.1f} - {end_eV:.1f} eV")
print(f"Points: {scanpoints}")
print(f"Approx step: {energy_step:.2f} eV")
print(f"Results: {filename}")
print()
print(f"Moving energy to {start_eV:.1f} eV")
bl_energy(start_eV)
# Take all the filters out and then put Ge foil in
dev.transm.put(1)
time.sleep(2)
umv(dev.ss_f4_x,6.0)
time.sleep(3)
# Scan
print("Starting scan")
for bragg in bragg_points:
scans.umv(
dev.dcm_bragg,
bragg,
relative=False,
)
energy = convert_from_bragg(bragg)["energy_ev"]
ss=get_value(dev.ss_bpmsum)
inten = average_inten()
i1 = get_value(dev.i1)
transmission = inten/ss
with open(filename, "a") as f:
f.write(
f"{energy:.2f},{bragg:.2f},{ss:.2f},{inten:.2f},{transmission:.6f}\n"
)
print()
print("Scan complete")
dev.transm.put(0.1)
print(f"Results written to {filename}")
def cal_samcam_fixed_x():
@@ -1180,72 +1072,6 @@ from epics import caget, caput
import time
def auto_exposure(
cam="samcam", target=200, tol=5, gain=0.9, min_exp=0.00001, max_exp=0.2, max_iter=10
):
"""
Adjust camera exposure time to reach a target max pixel value.
Parameters
----------
target : float
Desired MaxValue (counts)
tol : float
Acceptable deviation from target
min_exp, max_exp : float
Exposure time limits (s)
max_iter : int
Maximum number of adjustment iterations
"""
if cam == "samcam":
exposure = dev.samcam_exp.read()["samcam_exp"]["value"]
else:
exposure = dev.ss_xicam_exp.read()["ss_xicam_exp"]["value"]
print(f"Starting exposure = {exposure:.4f} s")
for i in range(max_iter):
time.sleep(0.1) # allow a frame or two to update
if cam == "samcam":
maxval = dev.samcam_max.read()["samcam_max"]["value"]
if maxval is None:
print("No reading — check camera.")
break
if cam == "ss_xicam":
maxval = dev.ss_xicam_max.read()["ss_xicam_max"]["value"]
if maxval is None:
print("No reading — check camera.")
break
error = target - maxval
# print(f"Iter {i+1}: MaxValue = {maxval:.1f}, error = {error:.1f}")
# stop if within tolerance
if abs(error) <= tol:
# print(f"Target reached (MaxValue={maxval:.1f}) after {i+1} iterations.")
break
# proportional correction (simple gain control)
gain_setting = gain # moderate response
new_exp = exposure * (1 + gain_setting * error / target)
# limit exposure bounds
new_exp = max(min_exp, min(max_exp, new_exp))
# update camera perp = dev.dcm_perp.read()["dcm_perp"]["value"]
y = dev.ss_xicam_x.read()["ss_xicam_x"]["value"]
x = dev.ss_xicam_y.read()["ss_xicam_y"]["value"]
if cam == "samcam":
dev.samcam_exp.put(new_exp)
# print(f" → Adjusting exposure to {new_exp:.4f} s")
else:
dev.ss_xicam_exp.put(new_exp)
# print(f" → Adjusting exposure to {new_exp:.4f} s")
exposure = new_exp
print(f"New exposure time is {exposure:.3g}")
return exposure
# def get_new_beamsizes(mirror):
@@ -1544,14 +1370,6 @@ def vfm_yaw_check():
plt.tight_layout()
plt.show()
@dataclass
class SlitAxis:
name: str
centre_motor: object # e.g. dev.slit1_x
size_motor: object # e.g. dev.slit1_xsize
scan_range: float = 2.0
# @dataclass
# class SlitAxis:
# name: str
@@ -1563,50 +1381,6 @@ class SlitAxis:
# min_size: float = -0.4
# max_size: float = 5.0
@dataclass
class Slit:
name: str
x: SlitAxis
y: SlitAxis
def centre_axis(axis, detector, slit_size=0.5):
"""Measure the beam centre on one slit axis."""
original_size = axis.size_motor.position
start_centre = axis.centre_motor.position
try:
umv(axis.size_motor, slit_size)
go_to_peak(
axis.centre_motor,
detector,
start_centre - axis.scan_range,
start_centre + axis.scan_range,
50,
confirm=False,
)
measured_centre = get_value(axis.centre_motor)
print(
f"{axis.name}: "
f"start={start_centre:.4f}, "
f"measured={measured_centre:.4f}, "
f"shift={measured_centre - start_centre:+.4f}"
)
return {
"start": start_centre,
"centre": measured_centre,
"shift": measured_centre - start_centre,
}
finally:
umv(axis.size_motor, original_size)
# def read_intensity(detector, n=5, delay=0.1):
# values = []
# for _ in range(n):
@@ -1719,114 +1493,11 @@ def centre_axis(axis, detector, slit_size=0.5):
# centre_axis(slit.y, detector)
# print(f"=== Finished {slit.name} ===")
def centre_axis(axis, detector, slit_size=0.5, final_size=3.0):
"""Centre one slit axis using a fixed slit gap."""
print(f"\nAligning {axis.name}")
# Set a known gap for the scan
umv(axis.size_motor, slit_size)
start = axis.centre_motor.position
go_to_peak(
axis.centre_motor,
detector,
start - axis.scan_range,
start + axis.scan_range,
50,
confirm=False,
)
centre = get_value(axis.centre_motor)
print(f"{axis.name}: centre = {centre:.4f}")
# Open slit again
umv(axis.size_motor, final_size)
return centre
def centre_slit(slit, detector, slit_size=0.5, final_size=3.0):
print(f"\n=== Aligning {slit.name} ===")
x_centre = centre_axis(
slit.x,
detector,
slit_size=slit_size,
final_size=final_size,
)
y_centre = centre_axis(
slit.y,
detector,
slit_size=slit_size,
final_size=final_size,
)
print(f"=== Finished {slit.name} ===")
return {
"x": x_centre,
"y": y_centre,
}
def centre_all_slits(slits, detector):
for slit in slits:
try:
centre_slit(slit, detector)
except Exception as exc:
print(f"WARNING: failed to align {slit.name}: {exc}")
print("Continuing with next slit.")
def centre_one(name, detector):
slits = define_slits()
for slit in slits:
if slit.name == name:
centre_slit(slit, detector)
def define_slits():
return [
Slit(
name="bsf",
x=SlitAxis(
name="bsf_sl_x",
centre_motor=dev.bsf_sl_xcen,
size_motor=dev.bsf_sl_xsize,
),
y=SlitAxis(
name="bsf_sl_y",
centre_motor=dev.bsf_sl_ycen,
size_motor=dev.bsf_sl_ysize,
),
),
Slit(
name="ss",
x=SlitAxis(
name="ss_sl_x",
centre_motor=dev.ss_sl_xcen,
size_motor=dev.ss_sl_xsize,
),
y=SlitAxis(
name="ss_sl_y",
centre_motor=dev.ss_sl_ycen,
size_motor=dev.ss_sl_ysize,
),
),
Slit(
name="bcu",
x=SlitAxis(
name="bcu_sl_x",
centre_motor=dev.bcu_sl_xcen,
size_motor=dev.bcu_sl_xsize,
),
y=SlitAxis(
name="bcu_sl_y",
centre_motor=dev.bcu_sl_ycen,
size_motor=dev.bcu_sl_ysize,
),
),
]
# def define_slits():
@@ -2492,7 +2163,7 @@ def dcm_pitch_calibration():
20000, 22000, 24000, 27000, 30000]
filename = bl.env.lut_dir / f"dcm_pitch_{filenow(date_only=True)}.csv"
with open(filename, "w", encoding="utf-8") as f:
f.write("energy,pitch\n")
f.write("energy,bragg,pitch\n")
# for energy in range(start_energy, end_energy, step):
try:
for energy in energies:
@@ -2505,55 +2176,158 @@ def dcm_pitch_calibration():
# pitch_new = get_value(dev.dcm_pitch)
bl_energy(energy)
pitch_new = get_value(dev.dcm_pitch)
bragg = get_value(dev.dcm_bragg)
with open(filename, "a", encoding="utf-8") as f:
f.write(f"{energy:.0f},{pitch_new:.5g}\n")
f.write(f"{energy:.0f},{bragg:.3f},{pitch_new:.5g}\n")
finally:
bl_energy(12400)
def scan_roll(energy, start, stop, steps=9, settle=0.2, filename=None, overwrite=False):
"""Measure scintillator Y position as a function of DCM fine roll."""
# def plot_rolls():
# energies = [6000, 9000, 12000, 15000, 18000, 21000]
# for energy in energies:
# filename = bl.env.lut_dir / f"roll_{energy}.csv"
# data = np.loadtxt(filename, delimiter=",", skiprows=1)
# x = data[:, 0]
# y = data[:, 1]
scanpoints = np.linspace(start, stop, steps)
print(f"Scanning roll from {start} to {stop}")
# m, c = np.polyfit(x,y,1)
# from pathlib import Path
if filename is None:
filename = bl.env.lut_dir / f"roll_{energy:.0f}.csv"
if filename.exists() and not overwrite:
print(f"{filename.name} already exists.")
print("Use overwrite=True if you want to repeat this energy.")
return filename
bl_energy(energy)
try:
prepare_scint_measurement()
with open(filename, "w", encoding="utf-8") as f:
f.write("Roll,Y pos\n")
for roll in scanpoints:
umv(dev.dcm_froll, roll)
time.sleep(settle)
results = read_scintXY()
if not results["ok"]:
raise RuntimeError(
f"Beam position measurement failed at "
f"{energy / 1000:.1f} keV, roll={roll:.3f}: "
f"{results['message']}"
)
print(f"{energy / 1000:.1f} keV | " f"roll = {roll:.3f} | " f"Y = {results["Y_pixels"]:.2f}")
f.write(f"{roll:.6f},{results["Y_pixels"]}\n")
finally:
finish_scint_measurement()
return filename
# import numpy as np
# import pandas as pd
# import matplotlib.pyplot as plt
def analyse_roll_calibration(
energies=(6000, 9000, 12000, 15000, 18000, 21000),
):
"""
Analyse roll calibration scans at several energies.
Reads:
bl.env.lut_dir / roll_{energy}.csv
Each CSV must contain:
Roll,Y pos
Fits Y position vs roll independently for each energy and finds
the roll where the fitted Y positions have minimum spread.
"""
lut_dir = Path(bl.env.lut_dir)
fits = {}
fig, ax = plt.subplots(figsize=(10, 7))
# ------------------------------------------------------------
# Read and fit each energy
# ------------------------------------------------------------
for energy in energies:
filename = lut_dir / f"roll_{energy}.csv"
df = pd.read_csv(filename)
roll = df["Roll"].to_numpy()
y = df["Y pos"].to_numpy()
# Linear fit: y = m * roll + b
m, b = np.polyfit(roll, y, 1)
fits[energy] = (m, b)
# Plot measured points
ax.scatter(
roll,
y,
label=f"{energy / 1000:g} keV",
)
# Plot fitted line
xx = np.linspace(roll.min(), roll.max(), 100)
ax.plot(xx, m * xx + b, "--")
print(
f"{energy / 1000:4.1f} keV: "
f"Y = {m:8.3f} × roll + {b:8.3f}"
)
# ------------------------------------------------------------
# Find roll where fitted lines have minimum spread
# ------------------------------------------------------------
slopes = np.array([m for m, b in fits.values()])
intercepts = np.array([b for m, b in fits.values()])
dm = slopes - slopes.mean()
db = intercepts - intercepts.mean()
best_roll = -np.sum(dm * db) / np.sum(dm**2)
# Predicted Y position at best roll
predicted_y = np.array(
[
m * best_roll + b
for m, b in fits.values()
]
)
mean_y = predicted_y.mean()
std_y = predicted_y.std()
# ------------------------------------------------------------
# Results
# ------------------------------------------------------------
print("\nBest roll:")
print(f" {best_roll:.6f}")
print("\nPredicted Y at best roll:")
for energy, y in zip(energies, predicted_y):
print(
f" {energy / 1000:4.1f} keV : "
f"{y:8.2f} px"
)
print(
f"\nMean Y = {mean_y:.2f} px"
f"\nSpread = {std_y:.2f} px"
)
# ------------------------------------------------------------
# Plot optimum
# ------------------------------------------------------------
ax.axvline(
best_roll,
color="black",
linestyle=":",
label=f"Best roll = {best_roll:.4f}",
)
ax.axhline(
mean_y,
color="grey",
linestyle=":",
alpha=0.5,
)
ax.set_xlabel("Roll")
ax.set_ylabel("Scintillator Y position (px)")
ax.set_title("DCM roll calibration")
ax.legend()
plt.tight_layout()
plt.show()
return {
"best_roll": best_roll,
"mean_y": mean_y,
"std_y": std_y,
"fits": fits,
"predicted_y": dict(zip(energies, predicted_y)),
}
def analyse_roll(low=6000, high=25000, low_file=None, high_file=None):
"""Find the DCM fine-roll value where low/high-energy beam positions intersect."""
@@ -2612,10 +2386,64 @@ def analyse_roll(low=6000, high=25000, low_file=None, high_file=None):
return x_intersect
def scan_roll(energy, start, stop, steps=9, settle=0.2, filename=None, overwrite=False):
"""Measure scintillator Y position as a function of DCM fine roll."""
scanpoints = np.linspace(start, stop, steps)
print(f"Scanning roll from {start} to {stop}")
if filename is None:
filename = bl.env.lut_dir / f"roll_{energy:.0f}.csv"
if filename.exists() and not overwrite:
print(f"{filename.name} already exists.")
print("Use overwrite=True if you want to repeat this energy.")
return filename
bl_energy(energy)
try:
prepare_scint_measurement(zoom=800)
with open(filename, "w", encoding="utf-8") as f:
f.write("Roll,Y pos\n")
for roll in scanpoints:
umv(dev.dcm_froll, roll)
time.sleep(settle)
auto_exposure("samcam")
results = read_scintXY()
if not results["ok"]:
raise RuntimeError(
f"Beam position measurement failed at "
f"{energy / 1000:.1f} keV, roll={roll:.3f}: "
f"{results['message']}"
)
print(f"{energy / 1000:.1f} keV | " f"roll = {roll:.3f} | " f"Y = {results["Y_pixels"]:.2f}")
f.write(f"{roll:.6f},{results["Y_pixels"]}\n")
finally:
finish_scint_measurement()
return filename
def measure_rolls():
energies = [6000, 9000, 12000, 15000, 18000, 21000]
try:
for energy in energies:
scan_roll(energy, start=2, stop=5, overwrite=True)
finally:
print("done")
# bl_energy(12400)
def find_best_roll(
low=6000,
high=25000,
low_range=(3.0, 5.0),
low_range=(2.0, 4.0),
high_range=(1.0, 8.0),
steps=9,
):
@@ -3257,3 +3085,174 @@ def gap_beam():
finish_ss_xi_measurement()
finish_scint_measurement()
# bl_energy(12400)
def gap_test():
for energy in range(6000, 30001, 500):
try:
harmonic, gap = Gap.calculate_gap(energy)
print(
f"{energy:5d} eV "
f"H{harmonic:2d} "
f"{gap:.4f} mm"
)
except ValueError as exc:
print(energy, exc)
def energy_beam_position():
"""
Measure the beam trajectory as a function of energy.
At each energy:
1. Perform a normal energy change.
2. Insert the SS X-ray eye and measure beam position.
3. Remove the SS X-ray eye.
4. Prepare the sample scintillator measurement.
5. Record LU, BCU and sample-camera beam positions and flux.
No DCM perp correction or beam steering is applied.
"""
energies = [
6000,
8000,
10000,
12400,
15000,
18000,
20000,
22000,
25000,
]
filename = bl.env.lut_dir / f"energy_beam_position_{filenow()}.csv"
with open(filename, "w", encoding="utf-8") as f:
f.write(
"energy,harmonic,gap,"
"dcm_pitch,dcm_perp,dcm_roll,"
"lu_bpmsum,lu_Xnorm,lu_Ynorm,"
"xi_cam_x,xi_cam_y,"
"bcu_bpmsum,bcu_Xnorm,bcu_Ynorm,bcu_x,bcu_y,"
"samcam_x,samcam_y,"
"flux\n"
)
try:
for energy in energies:
print(f"\n{'=' * 60}")
print(f"Measuring beam position at {energy} eV")
print(f"{'=' * 60}")
# ----------------------------------------------------------
# Normal energy change
# ----------------------------------------------------------
bl_energy(energy)
# Record DCM / undulator state after energy change
dcm_pitch = get_value(dev.dcm_pitch)
dcm_perp = get_value(dev.dcm_perp)
dcm_roll = get_value(dev.dcm_froll)
harmonic, gap = Gap.calculate_gap(energy)
# ----------------------------------------------------------
# SS X-ray eye
# This blocks the downstream beam, so measure it first
# and remove it before continuing.
# ----------------------------------------------------------
try:
prepare_ss_xi_measurement()
time.sleep(0.5)
xi_read = read_ss_xicamXY()
xicam_x = xi_read["X_pixels"]
xicam_y = xi_read["Y_pixels"]
time.sleep(0.5)
finally:
finish_ss_xi_measurement()
# ----------------------------------------------------------
# Downstream measurements
# ----------------------------------------------------------
prepare_scint_measurement()
# LU BPM
lu_bpmsum = get_value(dev.lu_bpmsum)
lu = compute_norm_lu()
lu_Xnorm = lu["lu_Xnorm"]
lu_Ynorm = lu["lu_Ynorm"]
# BCU BPM
bcu_bpmsum = get_value(dev.bcu_bpmsum)
bcu_norm = compute_norm_bcu()
bcu_Xnorm = bcu_norm["bcu_Xnorm"]
bcu_Ynorm = bcu_norm["bcu_Ynorm"]
try:
bcu = get_bcu_beampos()
bcu_x = bcu["bcu_x_um"]
bcu_y = bcu["bcu_y_um"]
except ValueEror as exc:
print(f"WARNING: BCU beam position unavailable {exc}")
bcu_x = float("nan")
bcu_y = float("nan")
# Sample scintillator
scint = read_scintXY(image=False)
samcam_x = scint["X_diff_microns"]
samcam_y = scint["Y_diff_microns"]
# Flux
_,flux = bpm2flux()
# ----------------------------------------------------------
# Save immediately
# ----------------------------------------------------------
with open(filename, "a", encoding="utf-8") as f:
f.write(
f"{energy:.0f},"
f"H{harmonic},{gap:.4f},"
f"{dcm_pitch:.5f},{dcm_perp:.5f},{dcm_roll:.5f},"
f"{lu_bpmsum:.1f},{lu_Xnorm:.3f},{lu_Ynorm:.3f},"
f"{xicam_x:.1f},{xicam_y:.1f},"
f"{bcu_bpmsum:.1f},{bcu_Xnorm:.3f},{bcu_Ynorm:.3f},"
f"{bcu_x:.2f},{bcu_y:.2f},"
f"{samcam_x:.2f},{samcam_y:.2f},"
f"{flux:.3e}\n"
)
print(
f"{energy:5.0f} eV | "
f"H{harmonic} gap={gap:.4f} | "
f"XI=({xicam_x:.1f}, {xicam_y:.1f}) px | "
f"LU=({lu_Xnorm:.3f}, {lu_Ynorm:.3f}) | "
f"BCU=({bcu_x:.1f}, {bcu_y:.1f}) um | "
f"Sample=({samcam_x:.1f}, {samcam_y:.1f}) um | "
f"Flux={flux:.2e}"
)
except Exception as exc:
print(f"\nEnergy beam-position measurement FAILED at {energy} eV")
print(f"{type(exc).__name__}: {exc}")
raise
finally:
# Make sure neither screen is accidentally left in the beam
try:
finish_ss_xi_measurement()
except Exception:
pass
try:
finish_scint_measurement()
except Exception:
pass
print("\nReturning to 12400 eV")
bl_energy(12400)
print(f"\nResults saved to:\n{filename}")
+10 -10
View File
@@ -1,10 +1,10 @@
Roll, Y pos
4,802
4.375,890.3
4.75,994.2
5.125,1096
5.5,1190
5.875,1276
6.25,1359
6.625,1443
7,1524
Roll,Y pos
2.000000,333.32351717113295
2.375000,458.83075423152076
2.750000,576.4915204490983
3.125000,688.162043927042
3.500000,806.7231283084715
3.875000,925.9491968173602
4.250000,1031.01771701488
4.625000,1125.1857495953072
5.000000,1208.846194057293
1 Roll Y pos
2 4 2.000000 802 333.32351717113295
3 4.375 2.375000 890.3 458.83075423152076
4 4.75 2.750000 994.2 576.4915204490983
5 5.125 3.125000 1096 688.162043927042
6 5.5 3.500000 1190 806.7231283084715
7 5.875 3.875000 1276 925.9491968173602
8 6.25 4.250000 1359 1031.01771701488
9 6.625 4.625000 1443 1125.1857495953072
10 7 5.000000 1524 1208.846194057293
+1 -142
View File
@@ -4,135 +4,16 @@ import epics
import time
import numpy as np
import matplotlib.pyplot as plt
from pxii_bec.scripts import beamline_context as bl
# =============================================================================
# Camera utilities
# =============================================================================
def predict_scint_transmission(target_flux=None):
"""Predict transmission required for a scintillator measurement."""
if target_flux is None:
target_flux = BeamMove.scint_target_flux
_, full_flux = bpm2flux()
if not np.isfinite(full_flux) or full_flux <= 0:
raise ValueError(
f"Cannot predict scintillator transmission: "
f"invalid full flux ({full_flux:.3g} ph/s)"
)
transmission = target_flux / full_flux
# Prevent an unreasonable attenuator setting
transmission = np.clip(transmission, 0.001, 1.0)
return float(transmission)
def prepare_scint_measurement(autoexp=True, zoom=1000):
"""Prepare for taking a reading of the beam from the scintillator"""
# set transmission
transmission = predict_scint_transmission()
print(
f"Predicted scintillator transmission: "
f"{transmission:.2%}"
)
dev.transm.put(transmission)
time.sleep(3)
# set camera zoom
if get_value(dev.scam_zoom) != zoom:
umv(dev.scam_zoom, zoom)
# move to beam visualisation
if not bl.planner.is_state(BeamlineState.BEAM_VISUALISATION):
bl.planner.move_to(BeamlineState.BEAM_VISUALISATION)
# open shutter
dev.bcu_shutter.put(1)
time.sleep(0.5)
# set autoexposure and check there is a reading in the image
if autoexp:
auto_exposure(cam="samcam", max_iter=25)
return zoom
def read_scintXY(image=False, measure_size=True):
"""Get the X and Y beam positions from the sample camera at
a sepcified zoom. Default zoom is 1000"""
# Target position on sample camera
x_target = BeamMove.scint_target_x
y_target = BeamMove.scint_target_y
zoom = get_value(dev.scam_zoom)
results = {}
max_signal = get_value(dev.samcam_max)
results["max_signal"] = max_signal
thresh = get_value(dev.samcam_thresh)
if max_signal < thresh:
return {
"ok": False,
"message": (
f"Insufficient signal for centroid calculation "
f"(max signal = {max_signal:.0f}, threshold = {thresh:.0f})"
),
"max_signal": max_signal,
}
x_px = dev.samcam_x.read()["samcam_x"]["value"]
y_px = dev.samcam_y.read()["samcam_y"]["value"]
results["X_pixels"] = x_px
results["Y_pixels"] = y_px
results["ok"] = True
results["message"] = (
f"Beam detected at X={x_px:.1f}, Y ={y_px:.1f} px"
)
# Calculate difference from target position
diff_x = x_target - x_px
diff_y = y_target - y_px
results["X_diff_px"] = diff_x
results["Y diff_px"] = diff_y
# Convert to pixels
diff_x_mic = calc_scam_microns(diff_x, zoom)
diff_y_mic = calc_scam_microns(diff_y, zoom)
results["X_diff_microns"] = diff_x_mic
results["Y_diff_microns"] = diff_y_mic
# Measure beamsize
if measure_size:
x_fwhm, y_fwhm = measure_beamsize()
results["X_FWHM"] = x_fwhm
results["Y_FWHM"] = y_fwhm
print(f"Beam position: X = {results['X_pixels']:.1f} px, "
f"Y = {results['Y_pixels']:.1f} px\n"
f"Distance from crosshair: X = {results['X_diff_microns']:.1f} microns, "
f"Y = {results['Y_diff_microns']:.1f} microns\n")
if image:
imagedata = get_cam_image(Cameras.sample)
results["image"] = imagedata
return results
def finish_scint_measurement():
dev.bcu_shutter.put(0)
def get_cam_image(prefix):
@@ -322,27 +203,5 @@ def create_empty_daily_report(filename):
return filename
def test_predicted_trans():
filename = bl.env.lut_dir / f"predicted_trans.csv"
with open(filename, "w", encoding="utf-8") as f:
f.write(f"Energy,PredictedT,ExposureTime,max,auto_expT,max2\n")
energies = [8000, 10000, 12400, 16000, 18000, 20000, 24000]
for energy in energies:
bl_energy(energy)
dev.transm.put(0.1)
time.sleep(3)
exp_time =0.005
dev.samcam_exp.put(exp_time)
transmission = predict_scint_transmission()
dev.transm.put(transmission)
time.sleep(5)
max1 = get_value(dev.samcam_max)
auto_exposure()
aut_exp_time = get_value(dev.samcam_exp)
max2 = get_value(dev.samcam_max)
with open(filename, "a", encoding="utf-8") as f:
f.write(f"{energy:.0f},{transmission:.3f},{exp_time:.4f},{max1:.0f},{aut_exp_time:.4f},{max2:.0f}\n")
+131 -74
View File
@@ -88,82 +88,126 @@ def mono_pitch_scan(plot=True, window_name="Fitting", plot_widget=None):
# Set fine pitch to middle of its' travel range
scans.umv(EnergyDefaults.mono_fpitch, pos["dcm_fine_pitch"], relative=False)
# Move DCM pitch to starting value
scans.umv(EnergyDefaults.mono_pitch, pos["dcm_pitch"]-0.04, relative=False)
pitch_offset = dev.dcm_pitch.user_parameter["offset"]
scans.umv(EnergyDefaults.mono_pitch, pos["dcm_pitch"]+pitch_offset, relative=False)
# Go to peak using default parameters from EnergyDefaults
if plot:
print("Scanning monochromator pitch and moving to peak, with plotting.")
result = go_to_peak(
EnergyDefaults.mono_pitch,
EnergyDefaults.signals["sig1"],
-EnergyDefaults.pitch_scan["halfwidth"],
EnergyDefaults.pitch_scan["halfwidth"],
steps=EnergyDefaults.pitch_scan["steps"],
relative=True,
settle=0.01,
plot=plot,
confirm=False,
min_fwhm_steps=1.1,
window_name=window_name if plot else None,
plot_widget=plot_widget if plot else None,
)
extended_scan = False
if not result["success"]:
extended_scan = True
extended_range = 2 * EnergyDefaults.pitch_scan["halfwidth"]
extended_steps = 2 * EnergyDefaults.pitch_scan["steps"]
print("Scanning monochromator pitch over a broader range.")
result = go_to_peak(
EnergyDefaults.mono_pitch,
EnergyDefaults.signals["sig1"],
-EnergyDefaults.pitch_scan["halfwidth"],
EnergyDefaults.pitch_scan["halfwidth"],
steps=EnergyDefaults.pitch_scan["steps"],
-extended_range,
extended_range,
steps=extended_steps,
relative=True,
settle=0.01,
plot=True,
plot=plot,
confirm=False,
min_fwhm_steps=1.1,
window_name=window_name,
plot_widget=plot_widget,
window_name=window_name if plot else None,
plot_widget=plot_widget if plot else None,
)
result["extended_scan"] = False
if not result["success"]:
extended_range = 2 * EnergyDefaults.pitch_scan["halfwidth"]
extended_steps = 2 * EnergyDefaults.pitch_scan["steps"]
print("Scanning monochromator pitch over a broader range.")
result = go_to_peak(
EnergyDefaults.mono_pitch,
EnergyDefaults.signals["sig1"],
-extended_range,
extended_range,
steps=extended_steps,
relative=True,
settle=0.01,
plot=True,
confirm=False,
min_fwhm_steps=1.1,
window_name=window_name,
plot_widget=plot_widget,
)
result["extended_scan"] = True
else:
print("Scanning monochromator pitch and moving to peak, without plotting.")
result = go_to_peak(
EnergyDefaults.mono_pitch,
EnergyDefaults.signals["sig1"],
-EnergyDefaults.pitch_scan["halfwidth"],
EnergyDefaults.pitch_scan["halfwidth"],
steps=EnergyDefaults.pitch_scan["steps"],
relative=True,
settle=0.01,
plot=False,
min_fwhm_steps=1.1,
confirm=False,
)
result["extended_scan"] = False
if not result["success"]:
extended_range = 2 * EnergyDefaults.pitch_scan["halfwidth"]
extended_steps = 2 * EnergyDefaults.pitch_scan["steps"]
print("Scanning monochromator pitch over a broader range.")
result2 = go_to_peak(
EnergyDefaults.mono_pitch,
EnergyDefaults.signals["sig1"],
-extended_range,
extended_range,
steps=extended_steps,
relative=True,
settle=0.01,
plot=True,
confirm=False,
min_fwhm_steps=1.1,
)
result["extended_scan"] = True
result["extended_scan"] = extended_scan
return result
# if plot:
# print("Scanning monochromator pitch and moving to peak, with plotting.")
# result = go_to_peak(
# EnergyDefaults.mono_pitch,
# EnergyDefaults.signals["sig1"],
# -EnergyDefaults.pitch_scan["halfwidth"],
# EnergyDefaults.pitch_scan["halfwidth"],
# steps=EnergyDefaults.pitch_scan["steps"],
# relative=True,
# settle=0.01,
# plot=True,
# confirm=False,
# min_fwhm_steps=1.1,
# window_name=window_name,
# plot_widget=plot_widget,
# )
# result["extended_scan"] = False
# if not result["success"]:
# extended_range = 2 * EnergyDefaults.pitch_scan["halfwidth"]
# extended_steps = 2 * EnergyDefaults.pitch_scan["steps"]
# print("Scanning monochromator pitch over a broader range.")
# result = go_to_peak(
# EnergyDefaults.mono_pitch,
# EnergyDefaults.signals["sig1"],
# -extended_range,
# extended_range,
# steps=extended_steps,
# relative=True,
# settle=0.01,
# plot=True,
# confirm=False,
# min_fwhm_steps=1.1,
# window_name=window_name,
# plot_widget=plot_widget,
# )
# result["extended_scan"] = True
# else:
# print("Scanning monochromator pitch and moving to peak, without plotting.")
# result = go_to_peak(
# EnergyDefaults.mono_pitch,
# EnergyDefaults.signals["sig1"],
# -EnergyDefaults.pitch_scan["halfwidth"],
# EnergyDefaults.pitch_scan["halfwidth"],
# steps=EnergyDefaults.pitch_scan["steps"],
# relative=True,
# settle=0.01,
# plot=False,
# min_fwhm_steps=1.1,
# confirm=False,
# )
# result["extended_scan"] = False
# if not result["success"]:
# extended_range = 2 * EnergyDefaults.pitch_scan["halfwidth"]
# extended_steps = 2 * EnergyDefaults.pitch_scan["steps"]
# print("Scanning monochromator pitch over a broader range.")
# result2 = go_to_peak(
# EnergyDefaults.mono_pitch,
# EnergyDefaults.signals["sig1"],
# -extended_range,
# extended_range,
# steps=extended_steps,
# relative=True,
# settle=0.01,
# plot=True,
# confirm=False,
# min_fwhm_steps=1.1,
# )
# result["extended_scan"] = True
# return result
# Specific functions - need to be edited for each beamline
@@ -212,12 +256,13 @@ def get_dcm_motors_positions(energy_ev):
"""
# dcm_motor_values = get_value_from_lut(energy_ev)
dcm_motor_values = {}
pitch = float(np.poly1d(Calibration.pitch_calib)(energy_ev))
# pitch = float(np.poly1d(Calibration.pitch_calib)(energy_ev))
# pitch = -5.5
fpitch = 5.0
roll = EnergyDefaults.mono_roll_value
perp = calc_perp_position(energy_ev, print_result=False)
bragg_angle = convert_from_energy(energy_ev, print_result=False)["bragg_angle_mrad"]
pitch = float(np.poly1d(Calibration.pitch_calib)(bragg_angle))
dcm_motor_values.update(
{
"bragg_angle": bragg_angle,
@@ -349,24 +394,36 @@ def bl_energy(
# return gap
# def calc_gap(energy_ev, print_result=True):
# """Calculate the undulator gap for the given energy."""
# harmonic_values = Gap.get_harmonic_values(energy_ev)
# if harmonic_values is None:
# return None
# gap = np.poly1d(harmonic_values)(energy_ev)
# gap *= Gap.correction_factor
# if print_result:
# harmonic = Gap.get_harmonic_by_energy(energy_ev)
# print(f"Calculated gap is {gap:.3f} mm " f"using {harmonic}")
# return gap
def calc_gap(energy_ev, print_result=True):
"""Calculate the undulator gap for the given energy."""
harmonic_values = Gap.get_harmonic_values(energy_ev)
if harmonic_values is None:
return None
gap = np.poly1d(harmonic_values)(energy_ev)
gap *= Gap.correction_factor
harmonic, gap = Gap.calculate_gap(energy_ev)
if print_result:
harmonic = Gap.get_harmonic_by_energy(energy_ev)
print(f"Calculated gap is {gap:.3f} mm " f"using {harmonic}")
print(
f"Calculated gap is {gap:.4f} mm "
f"using H{harmonic}"
)
return gap
def set_gap(energy_ev, print_result=False):
"""Set the undulator gap."""
+60 -82
View File
@@ -20,7 +20,7 @@ class EnergyDefaults:
mono_fpitch = dev.dcm_fpitch
mono_perp = dev.dcm_perp
mono_roll = dev.dcm_froll
mono_roll_value = 4.36
mono_roll_value = 3.88
stripe_thresholds = {"silicon": 9000, "rhodium": 20000, "platinum": 40000}
pitch_scan = {"halfwidth": 0.075, "steps": 20}
@@ -29,127 +29,105 @@ class EnergyDefaults:
class Calibration:
"""Calibration parameters for PXII optics"""
pitch_calib = [-7.60082220e-19, 6.09893342e-14, -1.81702221e-09, 2.45457520e-05, -5.61275367e00]
# pitch_calib = [-7.60082220e-19, 6.09893342e-14, -1.81702221e-09, 2.45457520e-05, -5.61275367e00]
pitch_calib = [-1.84031410e-07,-6.76777668e-05, -5.59684124]
# roll = np.array([2.28291039e-03, -2.41928101e01])
@dataclass(frozen=True)
class Gap:
"""Fit parameters to calculate undulator gap from energy."""
"""PXII U19 undulator gap calibration.
Harmonic fits are from Anuschka's September 2026 calibration.
For a requested energy, use the highest odd harmonic whose
calculated gap remains >= minimum_gap.
"""
minimum_gap = 4.5
selection_min_gap = 4.505
maximum_gap = 20.0
correction_factor = 0.9994
# Anuschka's September 2026 harmonic fits.
# Energy input is in keV, gap output is in mm.
harmonics = {
"H3": np.array([9.37600000e-04, 2.98800000e-01]),
"H5": np.array([5.10102857e-04, 7.99666667e-01]),
"H7": np.array([3.58874286e-04, 8.60410476e-01]),
"H9": np.array([2.74520000e-04, 9.25540000e-01]),
"H11": np.array([2.24457143e-04, 9.25714286e-01]),
"H13": np.array([1.88834286e-04, 9.47505714e-01]),
"H15": np.array([1.63434286e-04, 9.52602857e-01]),
"H17": np.array([1.43320000e-04, 9.77500000e-01]),
"H19": np.array([1.27940000e-04, 9.85770000e-01]),
3: np.array([0.095, -0.276, 4.154]),
5: np.array([0.00269444, -0.0616905, 0.967925, -0.295405]),
7: np.array([0.00110017, -0.0369968, 0.77334, -0.688198]),
9: np.array([0.00021633, -0.00619517, 0.315392, 0.971667]),
11: np.array([0.000589549, -0.0328631, 0.837705, -2.90326]),
13: np.array([0.197702, 0.757869]),
15: np.array([0.170381, 0.783155]),
17: np.array([0.1466, 0.8906]),
19: np.array([0.128, 0.985]),
}
@classmethod
def minimum_energy(cls, harmonic):
"""
Return the lowest energy that can be reached with this harmonic
without the corrected gap going below the minimum gap.
"""
slope, intercept = cls.harmonics[harmonic]
# calc_gap() applies the correction factor afterwards,
# so account for it here as well.
raw_minimum_gap = cls.minimum_gap / cls.correction_factor
return (raw_minimum_gap - intercept) / slope
def calculate_gap_for_harmonic(cls, energy_ev, harmonic):
"""Calculate gap for a specified harmonic."""
energy_kev = energy_ev / 1000.0
return np.polyval(cls.harmonics[harmonic], energy_kev)
@classmethod
def get_harmonic_by_energy(cls, energy_ev):
"""
Return the appropriate harmonic for the requested energy.
Select the highest odd harmonic that gives a valid gap.
Switch to the next harmonic as soon as it can produce the
requested energy without requiring a gap below minimum_gap.
This selects the harmonic whose gap is closest to the
minimum allowed gap of 4.5 mm, while maintaining a small
safety margin of 0.005 mm.
"""
selected = None
valid = []
for harmonic in cls.harmonics:
if energy_ev >= cls.minimum_energy(harmonic):
selected = harmonic
else:
break
gap = cls.calculate_gap_for_harmonic(
energy_ev,
harmonic,
)
return selected
if cls.selection_min_gap <= gap <= cls.maximum_gap:
valid.append((harmonic, gap))
@classmethod
def get_harmonic_values(cls, energy_ev):
"""
Return the fit coefficients for the appropriate harmonic.
"""
harmonic = cls.get_harmonic_by_energy(energy_ev)
if harmonic is None:
if not valid:
return None
return cls.harmonics[harmonic]
# Closest valid gap to the minimum gap
harmonic, gap = min(
valid,
key=lambda x: x[1] - cls.selection_min_gap,
)
return harmonic
@classmethod
def calculate_gap(cls, energy_ev):
"""
Calculate the corrected undulator gap for the requested energy.
"""Return selected harmonic and calculated gap."""
Returns
-------
tuple
(harmonic, gap)
"""
harmonic = cls.get_harmonic_by_energy(energy_ev)
if harmonic is None:
raise ValueError(f"{energy_ev:.0f} eV is below the minimum calibrated energy.")
raise ValueError(
f"No valid harmonic found for {energy_ev:.0f} eV."
)
slope, intercept = cls.harmonics[harmonic]
gap = slope * energy_ev + intercept
gap *= cls.correction_factor
gap = cls.calculate_gap_for_harmonic(
energy_ev,
harmonic,
)
# Final check against actual motor limits
if not cls.minimum_gap <= gap <= cls.maximum_gap:
raise ValueError(
f"Calculated gap {gap:.3f} mm for {energy_ev:.0f} eV "
f"using {harmonic} is outside the allowed range "
f"using H{harmonic} is outside the allowed range "
f"{cls.minimum_gap:.1f}-{cls.maximum_gap:.1f} mm."
)
return harmonic, gap
@dataclass(frozen=True)
class Harmonics:
"""Anuschka's harmonics data for PXII U19 Undulator"""
min_gap_value = 4.5
map = {
3: np.array([1.07141725, -0.52834258]),
4: np.array([0.007111, -0.13678409, 1.52295567, -1.06882785]),
5: np.array([0.00315051, -0.0766359, 1.13107469, -0.86442062]),
6: np.array([0.00162862, -0.04452336, 0.82948259, -0.37329674]),
7: np.array([0.00080764, -0.02418882, 0.59212947, 0.15702886]),
8: np.array([1.16699242e-03, -4.68207543e-02, 9.43972396e-01, -1.94201019e00]),
9: np.array([0.00048419, -0.02010648, 0.55514114, -0.38180067]),
10: np.array([2.11583333e-04, -8.03503571e-03, 3.43141595e-01, 6.02318000e-01]),
11: np.array([0.00334392, -0.18405336, 3.58338994, -19.3640241]),
12: np.array([3.20520798e-05, 2.39253145e-03, 8.09198503e-02, 2.22897377e00]),
13: np.array([0.00278744, 0.07979874, 2.05143916]),
}
energy_ranges = {3: (0, 7), 5: (7, 10), 7: (10, 13), 9: (13, 16), 11: (16, 19), 13: (19, 22)}
high_energy = [(15, (23, 25)), (17, (25, 29)), (19, (29, float("inf")))]
@dataclass(frozen=True)
class CamConversion:
"""Convert pixels to microns for sample camera"""
@@ -164,8 +142,8 @@ class BCU_BPM_X_Calibration:
signal_limit = 0.90
# centred_position = 0.441
centred_position = -0.009 # where the bpm was during calibration
crosshair_signal = -0.00339158
crosshair_bpm_position = 0.0532
crosshair_signal = -0.0209
crosshair_bpm_position = 0.0738
# @dataclass(frozen=True)
@@ -173,8 +151,8 @@ class BCU_BPM_Y_Calibration:
coeffs = (-0.14645507, 0.010016, 0.08258468, -0.00547233, -0.02715706, -1.54419084)
signal_limit = 0.95
centred_position = -1.540 # where the bpm was during calibration
crosshair_signal = -0.00392027
crosshair_bpm_position = -1.548
crosshair_signal = 0.00156
crosshair_bpm_position = -1.5459
# @dataclass(frozen=True)
+353
View File
@@ -0,0 +1,353 @@
"""PXII-specific operational helpers used by routine daily/weekly setup.
BEC loads macro files into a shared namespace, so these functions deliberately use
the standard BEC globals (dev, umv, get_value, etc.) rather than importing other
macro files. Nothing in this module should be promoted to mxcomm_* unless it is
truly beamline-independent.
"""
import time
from dataclasses import dataclass
from datetime import datetime
import numpy as np
from pxii_bec.scripts import beamline_context as bl
from pxii_bec.macros.beamline_planner import BeamlineState
# =============================================================================
# Energy
# =============================================================================
def daily_energy(energy, scan_mono=True, plot_widget=None):
"""Set PXII energy/gap and optionally optimise DCM pitch."""
current_energy = get_current_energy()
mono_result = {"extended_scan": False}
if abs(energy - current_energy) > 1:
bl_energy(energy, window_name="DailySetup", plot_widget=plot_widget)
# bl_energy performs the normal energy move. Keep mono_result benign
# here so the result handling below is defined for both code paths.
else:
gap_actual = dev.id_gap.position
gap_req = calc_gap(energy)
if abs(gap_actual - gap_req) > 0.05:
if dev.id_gap.moving():
return {
"ok": False,
"message": "Undulator gap is moving",
"energy": current_energy,
}
umv(dev.id_gap, gap_req)
if scan_mono:
mono_result = mono_pitch_scan(
window_name="DailySetup", plot_widget=plot_widget
)
new_energy = get_current_energy()
calib_pitch = get_dcm_motors_positions(energy)["dcm_pitch"]
pitch_offset = get_value(dev.dcm_pitch) - calib_pitch
if not mono_result.get("extended_scan", False):
return {
"ok": True,
"message": (
f"Beamline energy set to {new_energy:.0f} eV, "
f"pitch offset = {pitch_offset:.3f} mrad"
),
"energy": new_energy,
"pitch_offset": pitch_offset,
}
return {
"ok": True,
"warning": True,
"message": (
"Warning - DCM pitch is not within expected tolerance. "
"The DCM may need to be re-calibrated. "
f"Pitch offset = {pitch_offset:.3f} mrad"
),
"energy": new_energy,
"pitch_offset": pitch_offset,
}
# =============================================================================
# Sample-camera scintillator measurements
# =============================================================================
def predict_scint_transmission(target_flux=None):
"""Predict PXII transmission required for a scintillator measurement."""
if target_flux is None:
target_flux = BeamMove.scint_target_flux
_, full_flux = bpm2flux()
if not np.isfinite(full_flux) or full_flux <= 0:
raise ValueError(
"Cannot predict scintillator transmission: "
f"invalid full flux ({full_flux:.3g} ph/s)"
)
return float(np.clip(target_flux / full_flux, 0.001, 1.0))
def auto_exposure(cam="samcam", target=200, tol=5, gain=0.9,
min_exp=0.00001, max_exp=0.2, max_iter=10):
"""Adjust PXII camera exposure to reach the requested maximum signal."""
if cam == "samcam":
exposure = dev.samcam_exp.read()["samcam_exp"]["value"]
else:
exposure = dev.ss_xicam_exp.read()["ss_xicam_exp"]["value"]
print(f"Starting exposure = {exposure:.4f} s")
for _ in range(max_iter):
time.sleep(0.1)
if cam == "samcam":
maxval = dev.samcam_max.read()["samcam_max"]["value"]
else:
maxval = dev.ss_xicam_max.read()["ss_xicam_max"]["value"]
if maxval is None:
print("No reading — check camera.")
break
error = target - maxval
if abs(error) <= tol:
break
new_exp = exposure * (1 + gain * error / target)
new_exp = max(min_exp, min(max_exp, new_exp))
if cam == "samcam":
dev.samcam_exp.put(new_exp)
else:
dev.ss_xicam_exp.put(new_exp)
exposure = new_exp
print(f"New exposure time is {exposure:.3g}")
return exposure
def prepare_scint_measurement(autoexp=True, zoom=1000):
"""Put PXII into the standard state for a scintillator measurement."""
transmission = predict_scint_transmission()
print(f"Predicted scintillator transmission: {transmission:.2%}")
dev.transm.put(transmission)
time.sleep(3)
if get_value(dev.scam_zoom) != zoom:
umv(dev.scam_zoom, zoom)
if not bl.planner.is_state(BeamlineState.BEAM_VISUALISATION):
bl.planner.move_to(BeamlineState.BEAM_VISUALISATION)
dev.bcu_shutter.put(1)
time.sleep(0.5)
if autoexp:
auto_exposure(cam="samcam", max_iter=25)
return zoom
def measure_beamsize(cam="samcam"):
"""Return PXII sample-camera beam FWHM in microns."""
a = dev.samcam_xsig.read()["samcam_xsig"]["value"]
b = dev.samcam_ysig.read()["samcam_ysig"]["value"]
zoom = dev.scam_zoom.read()["scam_zoom"]["value"]
sx = calc_scam_microns(a, zoom=zoom) * 2.35
sy = calc_scam_microns(b, zoom=zoom) * 2.35
print(f"FWHM in um : {(sx, sy)}")
return sx, sy
def read_scintXY(image=False, measure_size=True):
"""Read PXII beam position from the sample-camera scintillator image."""
x_target = BeamMove.scint_target_x
y_target = BeamMove.scint_target_y
zoom = get_value(dev.scam_zoom)
max_signal = get_value(dev.samcam_max)
thresh = get_value(dev.samcam_thresh)
if max_signal < thresh:
return {
"ok": False,
"message": (
"Insufficient signal for centroid calculation "
f"(max signal = {max_signal:.0f}, threshold = {thresh:.0f})"
),
"max_signal": max_signal,
}
x_px = dev.samcam_x.read()["samcam_x"]["value"]
y_px = dev.samcam_y.read()["samcam_y"]["value"]
diff_x = x_target - x_px
diff_y = y_target - y_px
results = {
"ok": True,
"message": f"Beam detected at X={x_px:.1f}, Y={y_px:.1f} px",
"max_signal": max_signal,
"X_pixels": x_px,
"Y_pixels": y_px,
"X_diff_px": diff_x,
"Y_diff_px": diff_y,
"X_diff_microns": calc_scam_microns(diff_x, zoom),
"Y_diff_microns": calc_scam_microns(diff_y, zoom),
}
if measure_size:
results["X_FWHM"], results["Y_FWHM"] = measure_beamsize()
print(
f"Beam position: X = {x_px:.1f} px, Y = {y_px:.1f} px\n"
f"Distance from crosshair: X = {results['X_diff_microns']:.1f} microns, "
f"Y = {results['Y_diff_microns']:.1f} microns\n"
)
if image:
results["image"] = get_cam_image(Cameras.sample)
return results
def finish_scint_measurement():
dev.bcu_shutter.put(0)
# =============================================================================
# Slit centring used by weekly checks
# =============================================================================
@dataclass
class SlitAxis:
name: str
centre_motor: object
size_motor: object
scan_range: float = 2.0
@dataclass
class Slit:
name: str
x: SlitAxis
y: SlitAxis
def centre_axis(axis, detector, slit_size=0.5, final_size=3.0, window_name=None, plot_widget=None):
print(f"\nAligning {axis.name}")
umv(axis.size_motor, slit_size)
start = axis.centre_motor.position
try:
go_to_peak(axis.centre_motor, detector, start-axis.scan_range,
start+axis.scan_range, 50, confirm=False, window_name=window_name,
plot_widget=plot_widget)
centre = get_value(axis.centre_motor)
print(f"{axis.name}: centre = {centre:.4f}")
return centre
finally:
umv(axis.size_motor, final_size)
def centre_slit(slit, detector, slit_size=0.5, final_size=3.0, window_name=None, x_plot_widget=None, y_plot_widget=None):
print(f"\n=== Aligning {slit.name} ===")
x = centre_axis(slit.x, detector, slit_size, final_size,window_name=window_name,plot_widget=x_plot_widget)
y = centre_axis(slit.y, detector, slit_size, final_size, window_name=window_name,plot_widget=y_plot_widget)
print(f"=== Finished {slit.name} ===")
return {"x": x, "y": y}
def define_slits():
def axis(prefix, direction):
return SlitAxis(
name=f"{prefix}_sl_{direction}",
centre_motor=getattr(dev, f"{prefix}_sl_{direction}cen"),
size_motor=getattr(dev, f"{prefix}_sl_{direction}size"),
)
return [Slit(name, axis(name, "x"), axis(name, "y"))
for name in ("bsf", "ss", "bcu")]
def centre_one(name, detector, window_name=None, x_plot_widget=None, y_plot_widget=None):
for slit in define_slits():
if slit.name == name:
return centre_slit(slit, detector,window_name=window_name,x_plot_widget=x_plot_widget,y_plot_widget=y_plot_widget)
raise ValueError(f"Unknown PXII slit set: {name}")
# =============================================================================
# Ge energy calibration diagnostic
# =============================================================================
def scan_ge(edge=11103.1, mode="coarse"):
"""Scan the PXII Ge K edge and return the generated CSV filename."""
if mode == "coarse":
scan_range, scanpoints = 100, 41
if mode == "medium":
scan_range, scanpoints = 40, 41
elif mode == "fine":
scan_range, scanpoints = 15, 61
else:
raise ValueError(f"Unknown scan mode '{mode}'. Use 'coarse', 'medium' or 'fine'.")
start_eV, end_eV = edge-scan_range, edge+scan_range
start_bragg = convert_from_energy(start_eV)["bragg_angle_mrad"]
end_bragg = convert_from_energy(end_eV)["bragg_angle_mrad"]
bragg_points = np.linspace(start_bragg, end_bragg, scanpoints)
filename = bl.env.lut_dir / f"{datetime.now():%Y%m%d}_ge_edge_{mode}.csv"
with open(filename, "w") as f:
f.write("Energy,Bragg,ss_bpmsum,bcu_bpmsum,transmission\n")
print(f"\nGe edge {mode} scan: {start_eV:.1f}-{end_eV:.1f} eV")
bl_energy(start_eV)
dev.transm.put(1)
time.sleep(2)
umv(dev.ss_f4_x, 6.0)
time.sleep(3)
try:
for bragg in bragg_points:
scans.umv(dev.dcm_bragg, bragg, relative=False)
energy = convert_from_bragg(bragg)["energy_ev"]
ss = get_value(dev.ss_bpmsum)
vals = []
for _ in range(5):
vals.append(dev.bcu_bpmsum.read()["bcu_bpmsum"]["value"])
time.sleep(0.1)
inten = float(np.mean(vals))
transmission = inten / ss
with open(filename, "a") as f:
f.write(f"{energy:.2f},{bragg:.2f},{ss:.2f},{inten:.2f},{transmission:.6f}\n")
finally:
bl_energy(12400)
dev.transm.put(0.1)
time.sleep(2)
print(f"Scan complete. Results written to {filename}")
return filename
def prepare_ss_xi_measurement(autoexp=True):
"""Prepare for taking a reading of the beam from the SS Xray eye"""
# move to x-ray eye into the beam
umv(dev.ss_xi_x, 7.0)
# set autoexposure and check there is a reading in the image
if autoexp:
auto_exposure(cam="ss_xicam", max_iter=25)
def finish_ss_xi_measurement():
'''Move the SS xray eye out of the beam'''
umv(dev.ss_xi_x, -7)
def read_ss_xicamXY():
"""Read the beam position at the SS xray eye camera"""
results = {}
max_signal = get_value(dev.ss_xicam_max)
results["max_signal"] = max_signal
# thresh = get_value(dev.samcam_thresh)
thresh = 150
if max_signal < thresh:
return {
"ok": False,
"message": (
f"Insufficient signal for centroid calculation "
f"(max signal = {max_signal:.0f}, threshold = {thresh:.0f})"
),
"max_signal": max_signal,
}
x_px = dev.ss_xicam_x.read()["ss_xicam_x"]["value"]
y_px = dev.ss_xicam_y.read()["ss_xicam_y"]["value"]
results["X_pixels"] = x_px
results["Y_pixels"] = y_px
results["ok"] = True
results["message"] = (
f"Beam detected at X={x_px:.1f}, Y ={y_px:.1f} px"
)
print(f"Beam position: X = {results['X_pixels']:.1f} px, "
f"Y = {results['Y_pixels']:.1f} px\n")
return results
+122 -268
View File
@@ -1,347 +1,201 @@
# """Weekly beamline checks"""
"""Weekly beamline checks."""
"""PXII weekly beamline checks.
"""
import csv
from dataclasses import dataclass
from datetime import datetime
from pxii_bec.scripts import beamline_context as bl
from pxii_bec.macros.beamline_planner import BeamlineState
# =============================================================================
# Setup
# =============================================================================
def setup_weekly():
"""Put the beamline into standard conditions for weekly checks."""
"""Put PXII into the standard conditions used for weekly checks."""
print("\nSetting up standard weekly-check conditions...")
# Set standard energy and run mono pitch scan
energy_result = daily_energy(
BLSetup.energy,
scan_mono=True,
plot_widget="Plot_1"
)
energy_result = daily_energy(BLSetup.energy, scan_mono=True, plot_widget="Plot_1")
return {
"ok": True,
"ok": energy_result.get("ok", True),
"energy": BLSetup.energy,
"gap": get_value(dev.id_gap),
"energy_result": energy_result,
}
# =============================================================================
# Slit scans
# =============================================================================
def weekly_fe_scan(window_name="DailySetup"):
"""Scan the FE slits to find the centre values."""
print("\nScanning FE slits...")
try:
results = scan_fe(window_name)
return {
"ok": True,
"x": results["fe_xcen"],
"y": results["fe_ycen"],
}
except Exception as exc:
reason = str(exc)
print(f"FE slit scan failed: {reason}")
return {
"ok": False,
"error": reason,
}
def scan_fe(window_name="Fitting", plot_widget=None):
"""Scan the FE slits in X and Y"""
"""Scan PXII FE slits in X and Y and restore the standard gaps."""
try:
print("Scanning FE slits in X")
umv(dev.fe_sl_xsize, 0.05, dev.fe_sl_ysize, 0.6)
go_to_peak(dev.fe_sl_xcen, dev.lu_bpmsum, -1, 1, 25, confirm=False, relative=True, window_name=window_name, plot_widget=1)
go_to_peak(dev.fe_sl_xcen, dev.lu_bpmsum, -1, 1, 25,
confirm=False, relative=True, window_name=window_name, plot_widget="Plot_1")
xcen = get_value(dev.fe_sl_xcen)
print("Scanning FE slits in Y")
umv(dev.fe_sl_xsize, 0.6, dev.fe_sl_ysize, 0.05)
go_to_peak(dev.fe_sl_ycen, dev.lu_bpmsum, -1, 1, 25, confirm=False, relative=True, window_name=window_name, plot_widget=2)
go_to_peak(dev.fe_sl_ycen, dev.lu_bpmsum, -1, 1, 25,
confirm=False, relative=True, window_name=window_name, plot_widget="Plot_2")
ycen = get_value(dev.fe_sl_ycen)
return {
"fe_xcen": xcen,
"fe_ycen": ycen,
}
return {"fe_xcen": xcen, "fe_ycen": ycen}
finally:
umv(dev.fe_sl_xsize, WeeklySetup.fe_xsize)
umv(dev.fe_sl_ysize, WeeklySetup.fe_ysize)
umv(dev.fe_sl_xsize, BLSetup.fe_xsize)
umv(dev.fe_sl_ysize, BLSetup.fe_ysize)
def weekly_fe_scan(window_name="DailySetup"):
try:
result = scan_fe(window_name)
return {"ok": True, "x": result["fe_xcen"], "y": result["fe_ycen"]}
except Exception as exc:
print(f"FE slit scan failed: {exc}")
return {"ok": False, "error": str(exc)}
def weekly_bsf_slits_scan():
"""Scan the BSF slits to find the centre values."""
print("\nScanning BSF slits...")
try:
results = centre_one("bsf", dev.lu_bpmsum)
return {
"ok": True,
"x": get_value(dev.bsf_sl_xcen),
"y": get_value(dev.bsf_sl_ycen),
# "result": results,
}
result = centre_one("bsf", dev.lu_bpmsum, window_name="DailySetup", x_plot_widget="Plot_3", y_plot_widget="Plot_4")
return {"ok": True, "x": result["x"], "y": result["y"]}
except Exception as exc:
reason = str(exc)
print(f"BSF slit scan failed: {reason}")
return {
"ok": False,
"error": reason,
}
print(f"BSF slit scan failed: {exc}")
return {"ok": False, "error": str(exc)}
def weekly_ss_slits_scan():
"""Scan the secondary slits to find the centre values."""
print("\nScanning secondary slits...")
try:
results = centre_one("ss", dev.bcu_bpmsum)
return {
"ok": True,
"x": get_value(dev.ss_sl_xcen),
"y": get_value(dev.ss_sl_ycen),
# "result": results,
}
result = centre_one("ss", dev.bcu_bpmsum, window_name="DailySetup", x_plot_widget="Plot_5", y_plot_widget="Plot_6")
return {"ok": True, "x": result["x"], "y": result["y"]}
except Exception as exc:
reason = str(exc)
print(f"SS slit scan failed: {reason}")
print(f"SS slit scan failed: {exc}")
return {"ok": False, "error": str(exc)}
return {
"ok": False,
"error": reason,
}
# =============================================================================
# BPM readings
# =============================================================================
def measure_bpm_positions():
lubpm = compute_norm_lu()
ssbpm = compute_norm_ss()
bcubpm = get_bcu_beampos()
"""Read all three PXII BPM systems into one structured result."""
return {
"lu": compute_norm_lu(),
"ss": compute_norm_ss(),
"bcu": get_bcu_beampos(),
}
results = {}
results["lu"]["X norm"] = lubpm["lu_Xnorm"]
results["lu"]["Y norm"] = lubpm["lu_Ynorm"]
results["ss"]["X norm"] = ssbpm["ss_Xnorm"]
results["ss"]["Y norm"] = ssbpm["ss_Ynorm"]
results["bcu"]["BCU Xnorm"] = bcubpm["bcu_Xnorm"]
results["bcu"]["Ynorm"] = bcubpm["bcu_Xnorm"]
results["bcu"]["bcu_x_um"] = bcubpm["bcu_x_um"]
results["bcu"]["bcu_y_um"] = bcubpm["bcu_y_um"]
return results
# =============================================================================
# Save results
# =============================================================================
def save_weekly_results(results):
"""Append weekly beamline diagnostics to the history CSV."""
"""Append weekly PXII diagnostics to the history CSV."""
filename = bl.env.daily_setup_dir / "weekly_beamline_health.csv"
setup = results.get("setup", {})
energy_result = setup.get("energy_result", {})
fe = results.get("FE", {})
bsf = results.get("BSF", {})
ss = results.get("SS", {})
lubpm = results.get("lubpm", {})
ssbpm = results.get("ssbpm", {})
bcubpm = results.get("bcubpm", {})
fe, bsf, ss = results.get("FE", {}), results.get("BSF", {}), results.get("SS", {})
lubpm, ssbpm, bcubpm = results.get("lubpm", {}), results.get("ssbpm", {}), results.get("bcubpm", {})
edge_result = results.get("edge", {})
row = {
"timestamp": datetime.now().isoformat(timespec="seconds"),
# Energy / machine settings
"energy_eV": format_value(
energy_result.get("energy"), ".0f"
),
"id_gap_mm": format_value(
setup.get("gap"), ".3f"
),
"pitch_offset_mrad": format_value(
energy_result.get("pitch_offset"), ".4f"
),
# Slit centres
"fe_x": format_value(
fe.get("x"), ".3f"
),
"fe_y": format_value(
fe.get("y"), ".3f"
),
"bsf_x": format_value(
bsf.get("x"),".3f"
),
"bsf_y": format_value(
bsf.get("y"), ".3f"
),
"ss_x": format_value(
ss.get("x"), ".3f"
),
"ss_y": format_value(
ss.get("y"),".3f"
),
"lu_Xnorm": format_value(
lubpm.get("lu_Xnorm"), ".4f"
),
"lu_Ynorm": format_value(
lubpm.get("lu_Ynorm"), ".4f"
),
"ss_Xnorm": format_value(
ssbpm.get("ss_Xnorm"), ".4f"
),
"ss_Ynorm": format_value(
ssbpm.get("ss_Ynorm"), ".4f"
),
"bcu_Xnorm": format_value(
bcubpm.get("bcu_Xnorm"), ".4f"
),
"bcu_Ynorm": format_value(
bcubpm.get("bcu_Ynorm"), ".4f"
),
"bcu_beamX": format_value(
bcubpm.get("bcu_x_um"), ".1f"
),
"bcu_beamY": format_value(
bcubpm.get("bcu_y_um"), ".1f"
),
"energy_eV": format_value(energy_result.get("energy"), ".0f"),
"id_gap_mm": format_value(setup.get("gap"), ".3f"),
"pitch_offset_mrad": format_value(energy_result.get("pitch_offset"), ".4f"),
"fe_x": format_value(fe.get("x"), ".3f"),
"fe_y": format_value(fe.get("y"), ".3f"),
"bsf_x": format_value(bsf.get("x"), ".3f"),
"bsf_y": format_value(bsf.get("y"), ".3f"),
"ss_x": format_value(ss.get("x"), ".3f"),
"ss_y": format_value(ss.get("y"), ".3f"),
"lu_Xnorm": format_value(lubpm.get("lu_Xnorm"), ".4f"),
"lu_Ynorm": format_value(lubpm.get("lu_Ynorm"), ".4f"),
"ss_Xnorm": format_value(ssbpm.get("ss_Xnorm"), ".4f"),
"ss_Ynorm": format_value(ssbpm.get("ss_Ynorm"), ".4f"),
"bcu_Xnorm": format_value(bcubpm.get("bcu_Xnorm"), ".4f"),
"bcu_Ynorm": format_value(bcubpm.get("bcu_Ynorm"), ".4f"),
"bcu_beamX": format_value(bcubpm.get("bcu_x_um"), ".1f"),
"bcu_beamY": format_value(bcubpm.get("bcu_y_um"), ".1f"),
"energy_offset_eV": format_value(edge_result.get("energy_offset"), ".2f")
}
fieldnames = list(row.keys())
file_exists = filename.exists()
exists = filename.exists()
with open(filename, "a", newline="") as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if not file_exists:
writer = csv.DictWriter(csvfile, fieldnames=list(row))
if not exists:
writer.writeheader()
writer.writerow(row)
print(f"\nWeekly results saved to:")
print(filename)
print(f"\nWeekly results saved to:\n{filename}")
return filename
# =============================================================================
# SciLog results
# =============================================================================
def send_week_to_scilog():
filename = bl.env.daily_setup_dir / "weekly_beamline_health.csv"
def send_week_to_scilog(filename=None):
if filename is None:
filename = bl.env.daily_setup_dir / "weekly_beamline_health.csv"
msg = bec.messaging.scilog.new()
msg.add_text("Weekly PXII checks")
msg.add_attachment(filename)
msg.add_tags("weekly-check", "PXII")
msg.add_tags(["weekly-check", "PXII"])
msg.send()
# =============================================================================
# Main weekly check
# =============================================================================
def weekly_checks():
"""Run standard weekly beamline checks."""
def weekly_checks(save_scilog=True):
"""Run the complete PXII weekly sequence.
This remains independently callable, while daily_setup() invokes it
automatically on Wednesdays after the normal machine pre-checks.
"""
print("\n========================================")
print("PXII WEEKLY CHECKS")
print("========================================")
results = {}
# ------------------------------------------------------------------
# Standard conditions
# ----------------------------------SS--------------------------------
results = {"ok": True}
try:
results["setup"] = setup_weekly()
if not results["setup"].get("ok", False):
results["ok"] = False
results["error"] = "Weekly setup failed"
results["filename"] = save_weekly_results(results)
return results
except Exception as exc:
reason = str(exc)
print(f"Weekly setup failed: {reason}")
results["setup"] = {
"ok": False,
"error": reason,
}
# Don't continue with slit scans if we couldn't establish
# the standard starting conditions.
save_weekly_results(results)
results.update(ok=False, error=f"Weekly setup failed: {exc}")
results["setup"] = {"ok": False, "error": str(exc)}
results["filename"] = save_weekly_results(results)
return results
# ------------------------------------------------------------------
# BPM positions
# ------------------------------------------------------------------
results["lubpm"] = compute_norm_lu()
results["ssbpm"] = compute_norm_ss()
results["bcubpm"] = get_bcu_beampos()
# Record BPM positions before moving slit centres.
try:
bpm = measure_bpm_positions()
results["lubpm"], results["ssbpm"], results["bcubpm"] = bpm["lu"], bpm["ss"], bpm["bcu"]
except Exception as exc:
results["ok"] = False
results["bpm_error"] = str(exc)
print(f"BPM readings failed: {exc}")
# ------------------------------------------------------------------
# Slit scans
# ------------------------------------------------------------------
results["FE"] = weekly_fe_scan()
results["BSF"] = weekly_bsf_slits_scan()
results["SS"] = weekly_ss_slits_scan()
if not all(results[k].get("ok", False) for k in ("FE", "BSF", "SS")):
results["ok"] = False
# ------------------------------------------------------------------
# Save results
# ------------------------------------------------------------------
# Run the Ge edge scan.
try:
filename = scan_ge(11103, mode="medium")
edge = ge_edge_analysis(filename, save=True)
results["edge"] = edge
# Weekly-check acceptance criterion
if abs(edge["energy_offset"]) > 1.2:
results["warning"] = True
results["edge_warning"] = (
f"Energy calibration is {edge['energy_offset']:+.2f} eV off "
f"(measured {edge['measured_edge']:.2f} eV, "
f"expected {edge['expected_edge']:.2f} eV)"
)
print(f"WARNING: {results['edge_warning']}")
except Exception as exc:
results["ok"] = False
results["edge_error"] = str(exc)
print(f"Ge edge scan failed: {exc}")
results["filename"] = save_weekly_results(results)
# ------------------------------------------------------------------
# Edge scan
# ------------------------------------------------------------------
results["edge"] = scan_ge(11103, mode="coarse")
# ------------------------------------------------------------------
# Save results to SciLog
# ------------------------------------------------------------------
if save_scilog:
try:
send_week_to_scilog(results["filename"])
except Exception as exc:
print(f"WARNING: could not send weekly results to SciLog: {exc}")
print("\nWeekly checks complete.")
return results