attenuator adjustable, dummy adjustable, scans can now acquire

This commit is contained in:
2020-01-29 19:20:29 +01:00
parent 69ed54f7aa
commit 7309897d5d
34 changed files with 799 additions and 450 deletions
+31 -22
View File
@@ -14,8 +14,16 @@ def set_prefs(prefs):
# '.svn': matches 'pkg/.svn' and all of its children
# 'build/*.o': matches 'build/lib.o' but not 'build/sub/lib.o'
# 'build//*.o': matches 'build/lib.o' and 'build/sub/lib.o'
prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject',
'.hg', '.svn', '_svn', '.git', '.tox']
prefs["ignored_resources"] = [
"*.pyc",
"*~",
".ropeproject",
".hg",
".svn",
"_svn",
".git",
".tox",
]
# Specifies which files should be considered python files. It is
# useful when you have scripts inside your project. Only files
@@ -37,66 +45,66 @@ def set_prefs(prefs):
# prefs.add('python_path', '~/python/')
# Should rope save object information or not.
prefs['save_objectdb'] = True
prefs['compress_objectdb'] = False
prefs["save_objectdb"] = True
prefs["compress_objectdb"] = False
# If `True`, rope analyzes each module when it is being saved.
prefs['automatic_soa'] = True
prefs["automatic_soa"] = True
# The depth of calls to follow in static object analysis
prefs['soa_followed_calls'] = 0
prefs["soa_followed_calls"] = 0
# If `False` when running modules or unit tests "dynamic object
# analysis" is turned off. This makes them much faster.
prefs['perform_doa'] = True
prefs["perform_doa"] = True
# Rope can check the validity of its object DB when running.
prefs['validate_objectdb'] = True
prefs["validate_objectdb"] = True
# How many undos to hold?
prefs['max_history_items'] = 32
prefs["max_history_items"] = 32
# Shows whether to save history across sessions.
prefs['save_history'] = True
prefs['compress_history'] = False
prefs["save_history"] = True
prefs["compress_history"] = False
# Set the number spaces used for indenting. According to
# :PEP:`8`, it is best to use 4 spaces. Since most of rope's
# unit-tests use 4 spaces it is more reliable, too.
prefs['indent_size'] = 4
prefs["indent_size"] = 4
# Builtin and c-extension modules that are allowed to be imported
# and inspected by rope.
prefs['extension_modules'] = []
prefs["extension_modules"] = []
# Add all standard c-extensions to extension_modules list.
prefs['import_dynload_stdmods'] = True
prefs["import_dynload_stdmods"] = True
# If `True` modules with syntax errors are considered to be empty.
# The default value is `False`; When `False` syntax errors raise
# `rope.base.exceptions.ModuleSyntaxError` exception.
prefs['ignore_syntax_errors'] = False
prefs["ignore_syntax_errors"] = False
# If `True`, rope ignores unresolvable imports. Otherwise, they
# appear in the importing namespace.
prefs['ignore_bad_imports'] = False
prefs["ignore_bad_imports"] = False
# If `True`, rope will insert new module imports as
# `from <package> import <module>` by default.
prefs['prefer_module_from_imports'] = False
prefs["prefer_module_from_imports"] = False
# If `True`, rope will transform a comma list of imports into
# multiple separate import statements when organizing
# imports.
prefs['split_imports'] = False
prefs["split_imports"] = False
# If `True`, rope will remove all top-level import statements and
# reinsert them at the top of the module when making changes.
prefs['pull_imports_to_top'] = True
prefs["pull_imports_to_top"] = True
# If `True`, rope will sort imports alphabetically by module name instead
# of alphabetically by import statement, with from imports after normal
# imports.
prefs['sort_imports_alphabetically'] = False
prefs["sort_imports_alphabetically"] = False
# Location of implementation of
# rope.base.oi.type_hinting.interfaces.ITypeHintingFactory In general
@@ -105,8 +113,9 @@ def set_prefs(prefs):
# listed in module rope.base.oi.type_hinting.providers.interfaces
# For example, you can add you own providers for Django Models, or disable
# the search type-hinting in a class hierarchy, etc.
prefs['type_hinting_factory'] = (
'rope.base.oi.type_hinting.factory.default_type_hinting_factory')
prefs[
"type_hinting_factory"
] = "rope.base.oi.type_hinting.factory.default_type_hinting_factory"
def project_opened(project):
+3 -3
View File
@@ -68,8 +68,8 @@ class BStools:
queue_size=100,
compact_format=False,
):
N_pulses *=1
N_pulses+=200
N_pulses *= 1
N_pulses += 200
if os.path.isfile(fina):
print("!!! File %s already exists, would you like to delete it?" % fina)
if input("(y/n)") == "y":
@@ -163,7 +163,7 @@ class BStools:
def acquire(self, file_name=None, Npulses=100):
file_name += ".h5"
Npulses +=100
Npulses += 100
if self._default_file_path:
file_name = self._default_file_path % file_name
+24 -13
View File
@@ -168,7 +168,13 @@ class DIAClient:
sleep(time_interval)
def take_pedestal(
self, n_frames=1000, analyze=True, analyze_locally=False, n_bad_modules=0, freq=25):
self,
n_frames=1000,
analyze=True,
analyze_locally=False,
n_bad_modules=0,
freq=25,
):
from jungfrau_utils.scripts.jungfrau_run_pedestals import (
run as jungfrau_utils_run,
)
@@ -181,7 +187,7 @@ class DIAClient:
os.makedirs(res_dir)
os.chmod(res_dir, 0o775)
filename = "pedestal_%s" % datetime.now().strftime("%Y%m%d_%H%M")
period = 1/freq
period = 1 / freq
jungfrau_utils_run(
self._api_address,
filename,
@@ -282,8 +288,8 @@ class DIAClient:
if file_name is None:
# FIXME /dev/null crashes the data taking (h5py can't close /dev/null and crashes)
print("Not saving any data, as file_name is not set")
#file_name_JF = file_rootdir + "DelMe"
#file_name_bsread = file_rootdir + "DelMe"
# file_name_JF = file_rootdir + "DelMe"
# file_name_bsread = file_rootdir + "DelMe"
file_name_JF = "/dev/null"
file_name_bsread = "/dev/null"
else:
@@ -305,8 +311,7 @@ class DIAClient:
# 'n_messages': n_frames
}
)
self.backend_config.update({
'run_name': file_name_JF})
self.backend_config.update({"run_name": file_name_JF})
# 'n_frames': n_frames})
self.bsread_config.update(
{
@@ -318,7 +323,7 @@ class DIAClient:
self.reset()
self.set_config()
# print(self.get_config())
self.wait_for_status('IntegrationStatus.CONFIGURED')
self.wait_for_status("IntegrationStatus.CONFIGURED")
self.client.start()
done = False
@@ -327,19 +332,20 @@ class DIAClient:
if stat["status"] == "IntegrationStatus.FINISHED":
done = True
# if stat["status"] == "IntegrationStatus.BSREAD_STILL_RUNNING":
# done = True
# done = True
# if stat["status"] == "IntegrationStatus.INITIALIZED":
# done = True
# done = True
# if stat["status"] == "IntegrationStatus.DETECTOR_STOPPED":
# done = True
# done = True
sleep(0.1)
self.client.stop()
self.client.stop()
outputfilenames = [
f"{file_name_JF}.{tcli.upper()}.h5" for tcli in self.active_clients #+['BSREAD.h5_SARES20-CAMS142-M4','BSREAD.h5_SARES20-CAMS142-M5'] # DIRTY HACK
f"{file_name_JF}.{tcli.upper()}.h5"
for tcli in self.active_clients # +['BSREAD.h5_SARES20-CAMS142-M4','BSREAD.h5_SARES20-CAMS142-M5'] # DIRTY HACK
]
return Acquisition(
acquire=acquire,
acquisition_kwargs={"file_names": outputfilenames, "Npulses": Npulses},
@@ -349,3 +355,8 @@ class DIAClient:
def wait_done(self):
self.check_running()
self.check_still_running()
def reset_server(self, *args):
if not args:
args = ["all"]
os.system("ssh jf@sf-daq-3 -i ~/.ssh/daq3.key " + " ".join(args))
+48 -5
View File
@@ -1,10 +1,11 @@
import os
import json
import numpy as np
from time import sleep,time
from time import sleep, time
import traceback
from pathlib import Path
import colorama
from ..devices_general.adjustable import DummyAdjustable
class Scan:
@@ -36,7 +37,7 @@ class Scan:
self.scan_info = {
"scan_parameters": {
"name": [ta.name for ta in adjustables],
"Id": [ta.Id for ta in adjustables],
"Id": [ta.Id if hasattr(ta, "Id") else "noId" for ta in adjustables],
},
"scan_values_all": values,
"scan_values": [],
@@ -69,11 +70,20 @@ class Scan:
first_check = time()
checker_unhappy = False
while not self.checker.check_now():
print(colorama.Fore.RED+f"Condition checker is not happy, waiting for OK conditions since {time()-first_check:5.1f} seconds."+colorama.Fore.RESET,end="\r")
print(
colorama.Fore.RED
+ f"Condition checker is not happy, waiting for OK conditions since {time()-first_check:5.1f} seconds."
+ colorama.Fore.RESET,
end="\r",
)
sleep(self._checker_sleep_time)
checker_unhappy = True
if checker_unhappy:
print(colorama.Fore.RED+f"Condition checker was not happy and waiting for {time()-first_check:5.1f} seconds."+colorama.Fore.RESET)
print(
colorama.Fore.RED
+ f"Condition checker was not happy and waiting for {time()-first_check:5.1f} seconds."
+ colorama.Fore.RESET
)
self.checker.clear_and_start_counting()
if not len(self.values_todo) > 0:
@@ -145,7 +155,7 @@ class Scan:
tb = "Ended all steps without interruption."
finally:
print(tb)
if input("Move back to initial values? (y/n)")[0]=='y':
if input("Move back to initial values? (y/n)")[0] == "y":
self.changeToInitialValues()
def changeToInitialValues(self):
@@ -228,6 +238,38 @@ class Scans:
s.scanAll(step_info=step_info)
return s
def acquire(
self,
N_pulses,
N_repetitions=1,
file_name="",
counters=[],
start_immediately=True,
step_info=None,
):
adjustable = DummyAdjustable()
positions = list(range(N_repetitions))
values = [[tp] for tp in positions]
file_name = self.filename_generator.get_nextrun_filename(file_name)
if not counters:
counters = self._default_counters
s = Scan(
[adjustable],
values,
counters,
file_name,
Npulses=N_pulses,
basepath=self.data_base_dir,
scan_info_dir=self.scan_info_dir,
checker=self.checker,
scan_directories=self._scan_directories,
)
if start_immediately:
s.scanAll(step_info=step_info)
return s
def ascan(
self,
adjustable,
@@ -364,6 +406,7 @@ class Scans:
s.scanAll(step_info=step_info)
return s
class RunFilenameGenerator:
def __init__(self, path, prefix="run", Ndigits=4, separator="_", suffix="json"):
self.separator = separator
+8 -2
View File
@@ -5,10 +5,16 @@ from asyncio import Future
class Acquisition:
def __init__(
self, parent=None, acquire=lambda:None, acquisition_kwargs={}, hold=True, stopper=None, get_result=lambda:None
self,
parent=None,
acquire=lambda: None,
acquisition_kwargs={},
hold=True,
stopper=None,
get_result=lambda: None,
):
self.acquisition_kwargs = acquisition_kwargs
for key,val in acquisition_kwargs.items():
for key, val in acquisition_kwargs.items():
self.__dict__[key] = val
self._acquire = acquire
self._stopper = stopper
+6 -4
View File
@@ -2,6 +2,7 @@ import os
from pathlib import Path
import json
import logging
logger = logging.getLogger(__name__)
@@ -23,7 +24,9 @@ class Alias:
subalias.parent = self
else:
print(subalias.parent)
logger.warning(f'parent of alias {subalias.alias} has been defined already {subalias.parent.alias}.')
logger.warning(
f"parent of alias {subalias.alias} has been defined already {subalias.parent.alias}."
)
def get_all(self, joiner="."):
aa = []
@@ -47,19 +50,18 @@ class Alias:
)
return aa
def get_full_name(self,joiner="."):
def get_full_name(self, joiner="."):
name = [self.alias]
parent = self.parent
while not parent == None:
name.append(parent.alias)
parent = parent.__dict__.get('parent',None)
parent = parent.__dict__.get("parent", None)
if joiner:
return joiner.join(reversed(name))
else:
return name
# def add_children(self, *args):
# self.children.append(find_aliases(*args))
File diff suppressed because one or more lines are too long
+6 -6
View File
@@ -16,27 +16,27 @@ _scope_name = "bernina"
alias_namespaces = NamespaceCollection()
def init(*args,lazy=None):
def init(*args, lazy=None):
if args:
allnames = [tc['name'] for tc in components]
allnames = [tc["name"] for tc in components]
comp_toinit = []
for arg in args:
if not arg in allnames:
raise Exception(f'The component {arg} has no configuration defined!')
raise Exception(f"The component {arg} has no configuration defined!")
else:
comp_toinit.append(components[allnames.index(arg)])
else:
comp_toinit = components
if lazy is None:
lazy=ecocnf.startup_lazy
lazy = ecocnf.startup_lazy
op = {}
for key, value in initFromConfigList(comp_toinit, components, lazy=lazy).items():
# _namespace[key] = value
_mod.__dict__[key] = value
op[key]= value
op[key] = value
if not ecocnf.startup_lazy:
try:
-2
View File
@@ -1,3 +1 @@
# init()
+82 -38
View File
@@ -61,11 +61,27 @@ components = [
"kwargs": {},
"desc": "Slit after Undulator",
},
{
"name": "pshut_und",
"type": "eco.xoptics.shutters:PhotonShutter",
"args": ["SARFE10-OPSH044:REQUEST"],
"kwargs": {},
"z_und": 44,
"desc": "First shutter after Undulators",
},
{
"name": "sshut_opt",
"type": "eco.xoptics.shutters:SafetyShutter",
"args": ["SGE01-EPKT822:BST1_oeffnen"],
"kwargs": {},
"z_und": 115,
"desc": "Bernina safety shutter",
},
{
"name": "att_fe",
"type": "eco.xoptics.attenuator_aramis:AttenuatorAramis",
"args": ["SARFE10-OATT053"],
"kwargs": {},
"kwargs": {"shutter": Component("pshut_und")},
"z_und": 53,
"desc": "Attenuator in Front End",
},
@@ -94,12 +110,12 @@ components = [
"type": "eco.xdiagnostics.profile_monitors:Pprm",
},
# {
# "name": "slitSwitch",
# "z_und": 92,
# "desc": "Slit in Optics hutch after Photon switchyard and before Bernina optics",
# "type": "eco.xoptics.slits:SlitBlades_old",
# "args": ["SAROP21-OAPU092"],
# "kwargs": {},
# "name": "slitSwitch",
# "z_und": 92,
# "desc": "Slit in Optics hutch after Photon switchyard and before Bernina optics",
# "type": "eco.xoptics.slits:SlitBlades_old",
# "args": ["SAROP21-OAPU092"],
# "kwargs": {},
# },
{
"name": "slit_switch",
@@ -178,7 +194,21 @@ components = [
"desc": "Intensity/position monitor after Optics hutch",
"type": "eco.xdiagnostics.intensity_monitors:SolidTargetDetectorPBPS_new",
"args": ["SAROP21-PBPS133"],
"kwargs": {"VME_crate": "SAROP21-CVME-PBPS1", "link": 9, 'channels':{'up':'SLAAR21-LSCP1-FNS:CH6:VAL_GET','down':'SLAAR21-LSCP1-FNS:CH7:VAL_GET','left':'SLAAR21-LSCP1-FNS:CH4:VAL_GET','right':'SLAAR21-LSCP1-FNS:CH5:VAL_GET'},'calc':{'itot':'SLAAR21-LTIM01-EVR0:CALCI','xpos':'SLAAR21-LTIM01-EVR0:CALCX','ypos':'SLAAR21-LTIM01-EVR0:CALCY'}},
"kwargs": {
"VME_crate": "SAROP21-CVME-PBPS1",
"link": 9,
"channels": {
"up": "SLAAR21-LSCP1-FNS:CH6:VAL_GET",
"down": "SLAAR21-LSCP1-FNS:CH7:VAL_GET",
"left": "SLAAR21-LSCP1-FNS:CH4:VAL_GET",
"right": "SLAAR21-LSCP1-FNS:CH5:VAL_GET",
},
"calc": {
"itot": "SLAAR21-LTIM01-EVR0:CALCI",
"xpos": "SLAAR21-LTIM01-EVR0:CALCX",
"ypos": "SLAAR21-LTIM01-EVR0:CALCY",
},
},
},
{
"name": "prof_opt",
@@ -191,16 +221,16 @@ components = [
{
"name": "spect_tt",
"args": ["SAROP21-PSEN135"],
"kwargs": {"reduction_client_address":"http://sf-daqsync-02:12002/"},
"kwargs": {"reduction_client_address": "http://sf-daqsync-01:8889/"},
"z_und": 135,
"desc": "Spectral encoding timing diagnostics before Attenuator.",
"type": "eco.xdiagnostics.timetools:SpectralEncoder",
"lazy":False,
"lazy": False,
},
{
"name": "att",
"args": ["SAROP21-OATT135"],
"kwargs": {'pulse_picker':Component('xp')},
"kwargs": {"shutter": Component("xp")},
"z_und": 135,
"desc": "Attenuator Bernina",
"type": "eco.xoptics.attenuator_aramis:AttenuatorAramis",
@@ -223,12 +253,12 @@ components = [
"lazy": True,
},
# {
# "name": "slitAtt",
# "args": ["SAROP21-OAPU136"],
# "kwargs": {},
# "z_und": 136,
# "desc": "Slits behind attenuator",
# "type": "eco.xoptics.slits:SlitPosWidth_old",
# "name": "slitAtt",
# "args": ["SAROP21-OAPU136"],
# "kwargs": {},
# "z_und": 136,
# "desc": "Slits behind attenuator",
# "type": "eco.xoptics.slits:SlitPosWidth_old",
# },
{
"name": "mon_att",
@@ -273,21 +303,21 @@ components = [
{
"name": "spatial_tt",
"args": [],
"kwargs": {"reduction_client_address":"http://sf-daqsync-02:12003/"},
"kwargs": {"reduction_client_address": "http://sf-daqsync-02:12003/"},
"z_und": 141,
"desc": "spatial encoding timing diagnostics before sample.",
"type": "eco.xdiagnostics.timetools:SpatialEncoder",
"lazy":False,
"lazy": False,
},
{
"name": "slit_kb",
"args": [],
"kwargs": {"pvname": "SARES20-MF1"},
"z_und": 141,
"desc": "Slits behind Kb",
"type": "eco.xoptics.slits:SlitBlades_JJ",
# "type": "eco.xoptics.slits:SlitBladesJJ_old",
},
{
"name": "slit_kb",
"args": [],
"kwargs": {"pvname": "SARES20-MF1"},
"z_und": 141,
"desc": "Slits behind Kb",
"type": "eco.xoptics.slits:SlitBlades_JJ",
#"type": "eco.xoptics.slits:SlitBladesJJ_old",
},
{
"args": [],
"name": "gps",
@@ -304,7 +334,6 @@ components = [
"type": "eco.endstations.bernina_diffractometers:XRD",
"kwargs": {"Id": "SARES21-XRD", "configuration": config["xrd_config"]},
},
{
"args": [],
"name": "vonHamos",
@@ -313,7 +342,8 @@ components = [
"type": "eco.devices_general.micos_stage:stage",
"kwargs": {
"vonHamos_horiz_pv": config["Kern"]["vonHamos_horiz"],
"vonHamos_vert_pv": config["Kern"]["vonHamos_vert"],}
"vonHamos_vert_pv": config["Kern"]["vonHamos_vert"],
},
},
{
"args": [],
@@ -321,7 +351,7 @@ components = [
"z_und": 142,
"desc": "ToF comm. gasjet",
"type": "tof:jet",
"kwargs": {}
"kwargs": {},
},
{
"args": [],
@@ -335,7 +365,6 @@ components = [
"bshost": "sf-daqsync-01.psi.ch",
"bsport": 11151,
},
},
{
"args": [],
@@ -392,7 +421,9 @@ components = [
"name": "epics_channel_list",
"desc": "epics channel list",
"type": "eco.utilities.config:ChannelList",
"kwargs": {"file_name":"/sf/bernina/config/channel_lists/default_channel_list_epics"},
"kwargs": {
"file_name": "/sf/bernina/config/channel_lists/default_channel_list_epics"
},
},
{
"args": [],
@@ -492,7 +523,9 @@ components = [
"name": "default_channel_list",
"desc": "Bernina default channels, used in daq",
"type": "eco.utilities.config:ChannelList",
"kwargs": {"file_name":"/sf/bernina/config/channel_lists/default_channel_list"},
"kwargs": {
"file_name": "/sf/bernina/config/channel_lists/default_channel_list"
},
"lazy": False,
},
{
@@ -500,7 +533,9 @@ components = [
"name": "default_channel_list_bs",
"desc": "Bernina default bs channels, used by bs_daq",
"type": "eco.utilities.config:ChannelList",
"kwargs": {"file_name":"/sf/bernina/config/channel_lists/default_channel_list_bs"},
"kwargs": {
"file_name": "/sf/bernina/config/channel_lists/default_channel_list_bs"
},
"lazy": False,
},
{
@@ -508,7 +543,9 @@ components = [
"name": "channels_spectrometer_projection",
"desc": "",
"type": "eco.utilities.config:ChannelList",
"kwargs": {"file_name":"/sf/bernina/config/channel_lists/channel_list_PSSS_projection"},
"kwargs": {
"file_name": "/sf/bernina/config/channel_lists/channel_list_PSSS_projection"
},
"lazy": False,
},
{
@@ -518,14 +555,21 @@ components = [
"type": "eco.acquisition.bs_data:BStools",
"kwargs": {
"default_channel_list": {
"bernina_default_channels_bs": Component("default_channel_list_bs")
"bernina_default_channels_bs": Component("default_channel_list")
},
"default_file_path": f"/sf/bernina/data/{config['pgroup']}/res/%s",
},
"lazy": False,
},
{
"args": [[Component('slit_und'),Component('slit_switch'),Component('slit_att'),Component('slit_kb')]],
"args": [
[
Component("slit_und"),
Component("slit_switch"),
Component("slit_att"),
Component("slit_kb"),
]
],
"name": "slits",
"desc": "collection of all slits",
"type": "eco.utilities.beamline:Slits",
+25 -1
View File
@@ -29,7 +29,7 @@ def default_representation(Obj):
return Obj.Id
def get_repr(Obj):
s = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')+': '
s = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") + ": "
s += f"{colorama.Style.BRIGHT}{Obj._get_name()}{colorama.Style.RESET_ALL} at {colorama.Style.BRIGHT}{Obj.get_current_value():g}{colorama.Style.RESET_ALL}"
return s
@@ -195,6 +195,30 @@ def update_changes(Adj):
# wrappers for adjustables <<<<<<<<<<<
@spec_convenience
class DummyAdjustable:
def __init__(self, name="no_adjustable"):
self.name = name
self.current_value = 0
def get_current_value(self):
return self.current_value
def set_target_value(self, value, hold=False):
def changer(value):
self.current_value = value
return Changer(
target=value, parent=self, changer=changer, hold=hold, stopper=None
)
def __repr__(self):
name = self.name
cv = self.get_current_value()
s = f"{name} at value: {cv}" + "\n"
return s
def _keywordChecker(kw_key_list_tups):
for tkw, tkey, tlist in kw_key_list_tups:
assert tkey in tlist, "Keyword %s should be one of %s" % (tkw, tlist)
+45 -27
View File
@@ -1,33 +1,51 @@
from ..aliases import Alias, append_object_to_object
from .adjustable import PvRecord, PvEnum
from ..aliases import Alias,append_object_to_object
from .adjustable import PvRecord,PvEnum
class CameraBasler:
def __init__(self,pvname,name=None):
def __init__(self, pvname, name=None):
self.pvname = pvname
self.name = name
self.alias = Alias(name)
append_object_to_object(self,PvEnum,self.pvname+':INIT',name='initialize')
append_object_to_object(self,PvEnum,self.pvname+':CAMERA',name='running')
append_object_to_object(self,PvRecord,self.pvname+':BOARD',name='board_no')
append_object_to_object(self,PvRecord,self.pvname+':SERIALNR',name='serial_no')
append_object_to_object(self,PvRecord,self.pvname+':EXPOSURE',name='_exposure_time')
append_object_to_object(self,PvEnum,self.pvname+':ACQMODE',name='_acq_mode')
append_object_to_object(self,PvEnum,self.pvname+':RECMODE',name='_req_mode')
append_object_to_object(self,PvEnum,self.pvname+':STOREMODE',name='_store_mode')
append_object_to_object(self,PvRecord,self.pvname+':BINY',name='_binx')
append_object_to_object(self,PvRecord,self.pvname+':BINY',name='_biny')
append_object_to_object(self,PvRecord,self.pvname+':REGIONX_START',name='_roixmin')
append_object_to_object(self,PvRecord,self.pvname+':REGIONX_END',name='_roixmax')
append_object_to_object(self,PvRecord,self.pvname+':REGIONY_START',name='_roiymin')
append_object_to_object(self,PvRecord,self.pvname+':REGIONY_END',name='_roiymax')
append_object_to_object(self,PvEnum,self.pvname+':SET_PARAM',name='_set_parameters')
append_object_to_object(self,PvEnum,self.pvname+':TRIGGER',name='trigger_on')
append_object_to_object(self,PvEnum,self.pvname+':TRIGGERSOURCE',name='trigger_source')
#append_object_to_object(self,PvEnum,self.pvname+':TRIGGEREDGE',name='trigger_edge')
append_object_to_object(self, PvEnum, self.pvname + ":INIT", name="initialize")
append_object_to_object(self, PvEnum, self.pvname + ":CAMERA", name="running")
append_object_to_object(self, PvRecord, self.pvname + ":BOARD", name="board_no")
append_object_to_object(
self, PvRecord, self.pvname + ":SERIALNR", name="serial_no"
)
append_object_to_object(
self, PvRecord, self.pvname + ":EXPOSURE", name="_exposure_time"
)
append_object_to_object(
self, PvEnum, self.pvname + ":ACQMODE", name="_acq_mode"
)
append_object_to_object(
self, PvEnum, self.pvname + ":RECMODE", name="_req_mode"
)
append_object_to_object(
self, PvEnum, self.pvname + ":STOREMODE", name="_store_mode"
)
append_object_to_object(self, PvRecord, self.pvname + ":BINY", name="_binx")
append_object_to_object(self, PvRecord, self.pvname + ":BINY", name="_biny")
append_object_to_object(
self, PvRecord, self.pvname + ":REGIONX_START", name="_roixmin"
)
append_object_to_object(
self, PvRecord, self.pvname + ":REGIONX_END", name="_roixmax"
)
append_object_to_object(
self, PvRecord, self.pvname + ":REGIONY_START", name="_roiymin"
)
append_object_to_object(
self, PvRecord, self.pvname + ":REGIONY_END", name="_roiymax"
)
append_object_to_object(
self, PvEnum, self.pvname + ":SET_PARAM", name="_set_parameters"
)
append_object_to_object(
self, PvEnum, self.pvname + ":TRIGGER", name="trigger_on"
)
append_object_to_object(
self, PvEnum, self.pvname + ":TRIGGERSOURCE", name="trigger_source"
)
# append_object_to_object(self,PvEnum,self.pvname+':TRIGGEREDGE',name='trigger_edge')
+41 -28
View File
@@ -3,12 +3,12 @@ from epics import caget
from epics import PV
from ..eco_epics.utilities_epics import EnumWrapper
# from cam_server import PipelineClient
# from cam_server.utils import get_host_port_from_stream_address
# from bsread import source, SUB
from cam_server import PipelineClient
from cam_server.utils import get_host_port_from_stream_address
from bsread import source, SUB
import subprocess
import h5py
from time import sleep,time
from time import sleep, time
from threading import Thread
from datetime import datetime
@@ -23,48 +23,61 @@ class PvDataStream:
self.name = name
self.alias = Alias(self.name, channel=self.Id, channeltype="CA")
def collect(self,seconds=None,samples=None):
def collect(self, seconds=None, samples=None):
if (not seconds) and (not samples):
raise Exception('Either a time interval or number of samples need to be defined.')
raise Exception(
"Either a time interval or number of samples need to be defined."
)
try:
self._pv.callbacks.pop(self._collection['ix_cb'])
self._pv.callbacks.pop(self._collection["ix_cb"])
except:
pass
self._collection = {'done':False}
self._collection = {"done": False}
self.data_collected = []
if seconds:
self._collection['start_time']= time()
self._collection['seconds']= seconds
stopcond = lambda: (time() - self._collection['start_time']) > self._collection['seconds']
self._collection["start_time"] = time()
self._collection["seconds"] = seconds
stopcond = (
lambda: (time() - self._collection["start_time"])
> self._collection["seconds"]
)
def addData(**kw):
if not stopcond():
self.data_collected.append(kw['value'])
self.data_collected.append(kw["value"])
else:
self._pv.callbacks.pop(self._collection['ix_cb'])
self._collection['done'] = True
self._pv.callbacks.pop(self._collection["ix_cb"])
self._collection["done"] = True
elif samples:
self._collection['samples'] = samples
stopcond = lambda: len(self.data_collected) >= self._collection['samples']
self._collection["samples"] = samples
stopcond = lambda: len(self.data_collected) >= self._collection["samples"]
def addData(**kw):
self.data_collected.append(kw['value'])
self.data_collected.append(kw["value"])
if stopcond():
self._pv.callbacks.pop(self._collection['ix_cb'])
self._collection['done'] = True
self._collection['ix_cb'] = self._pv.add_callback(addData)
while not self._collection['done']:
sleep(.005)
self._pv.callbacks.pop(self._collection["ix_cb"])
self._collection["done"] = True
self._collection["ix_cb"] = self._pv.add_callback(addData)
while not self._collection["done"]:
sleep(0.005)
return self.data_collected
def acquire(self,hold=False,**kwargs):
return Acquisition(acquire=lambda:self.collect(**kwargs), hold=hold, stopper=None, get_result=lambda:self.data_collected)
def acquire(self, hold=False, **kwargs):
return Acquisition(
acquire=lambda: self.collect(**kwargs),
hold=hold,
stopper=None,
get_result=lambda: self.data_collected,
)
def accumulate(self, n_buffer):
if not hasattr(self,'_accumulate'):
if not hasattr(self, "_accumulate"):
self._accumulate = {"n_buffer": n_buffer, "ix": 0, "n_cb": -1}
else:
self._accumulate['n_buffer'] = n_buffer
self._accumulate['ix'] = 0
self._accumulate["n_buffer"] = n_buffer
self._accumulate["ix"] = 0
self._pv.callbacks.pop(self._accumulate["n_cb"], None)
self._data = np.squeeze(np.zeros([n_buffer * 2, self._pv.count])) * np.nan
+5 -11
View File
@@ -1,32 +1,26 @@
from ..devices_general.motors import MotorRecord
from ..aliases import Alias, append_object_to_object
def addMotorRecordToSelf(self, name=None, Id=None):
try:
self.__dict__[name] = MotorRecord(Id, name=name)
self.alias.append(self.__dict__[name].alias)
except:
print(f"Warning! Could not find motor {name} (Id:{Id})")
self.Id = Id
self.name = name
self.alias = Alias(name)
self.alias = Alias(name)
class stage:
def __init__( self, name=None,vonHamos_horiz_pv=None,vonHamos_vert_pv = None ):
def __init__(self, name=None, vonHamos_horiz_pv=None, vonHamos_vert_pv=None):
self.name = name
self.alias = Alias(name)
addMotorRecordToSelf(self, Id=vonHamos_horiz_pv, name="horiz")
addMotorRecordToSelf(self, Id=vonHamos_vert_pv, name="vert")
def get_adjustable_positions_str(self):
ostr = "***** VonHamos motor positions******\n"
+1 -1
View File
@@ -55,7 +55,7 @@ class MotorRecord:
Alias(an, channel=".".join([pvname, af]), channeltype="CA")
)
self._currentChange = None
self.description = EpicsString(pvname+'.DESC')
self.description = EpicsString(pvname + ".DESC")
# Conventional methods and properties for all Adjustable objects
def set_target_value(self, value, hold=False, check=True):
-2
View File
@@ -1,9 +1,7 @@
from .devices_general.adjustable import PvEnum
class PowerSocket:
def __init__(self, pvname, name=None):
self.alias = Alias(name)
self.name = name
+2 -2
View File
@@ -135,13 +135,13 @@ class Device(object):
if attrs is not None:
for attr in attrs:
#self.PV(attr, connect=False, connection_timeout=timeout)
# self.PV(attr, connect=False, connection_timeout=timeout)
self.PV(attr, connect=False, timeout=timeout)
if aliases:
for attr in aliases.values():
if attrs is None or attr not in attrs:
#self.PV(attr, connect=False, connection_timeout=timeout)
# self.PV(attr, connect=False, connection_timeout=timeout)
self.PV(attr, connect=False, timeout=timeout)
if with_poll:
+6 -8
View File
@@ -63,24 +63,22 @@ class Positioner:
tname = "v" + tname
self.__dict__[tname] = func
class EpicsString:
def __init__(self,pvname,name=None,elog=None):
def __init__(self, pvname, name=None, elog=None):
self.name = name
self.pvname = pvname
self._pv = PV(pvname)
self._elog = elog
def get(self):
return self._pv.get()
def set(self,string):
self._pv.put(bytes(string,'utf8'))
def set(self, string):
self._pv.put(bytes(string, "utf8"))
def __repr__(self):
return self.get()
def __call__(self,string):
def __call__(self, string):
self.set(string)
+110 -24
View File
@@ -5,7 +5,7 @@ from ..devices_general.motors import MotorRecord
from ..devices_general.adjustable import PvRecord
from epics import PV
from ..aliases import Alias,append_object_to_object
from ..aliases import Alias, append_object_to_object
def addMotorRecordToSelf(self, name=None, Id=None):
@@ -42,12 +42,48 @@ class GPS:
if "phi_hex" in self.configuration:
### motors PI hexapod ###
append_object_to_object(self,PvRecord,"SARES20-HEX_PI:SET-POSI-X",pvreadbackname="SARES20-HEX_PI:POSI-X",name='xhex')
append_object_to_object(self,PvRecord,"SARES20-HEX_PI:SET-POSI-Y",pvreadbackname="SARES20-HEX_PI:POSI-Y",name='yhex')
append_object_to_object(self,PvRecord,"SARES20-HEX_PI:SET-POSI-Z",pvreadbackname="SARES20-HEX_PI:POSI-Z",name='zhex')
append_object_to_object(self,PvRecord,"SARES20-HEX_PI:SET-POSI-U",pvreadbackname="SARES20-HEX_PI:POSI-U",name='uhex')
append_object_to_object(self,PvRecord,"SARES20-HEX_PI:SET-POSI-V",pvreadbackname="SARES20-HEX_PI:POSI-V",name='vhex')
append_object_to_object(self,PvRecord,"SARES20-HEX_PI:SET-POSI-W",pvreadbackname="SARES20-HEX_PI:POSI-W",name='whex')
append_object_to_object(
self,
PvRecord,
"SARES20-HEX_PI:SET-POSI-X",
pvreadbackname="SARES20-HEX_PI:POSI-X",
name="xhex",
)
append_object_to_object(
self,
PvRecord,
"SARES20-HEX_PI:SET-POSI-Y",
pvreadbackname="SARES20-HEX_PI:POSI-Y",
name="yhex",
)
append_object_to_object(
self,
PvRecord,
"SARES20-HEX_PI:SET-POSI-Z",
pvreadbackname="SARES20-HEX_PI:POSI-Z",
name="zhex",
)
append_object_to_object(
self,
PvRecord,
"SARES20-HEX_PI:SET-POSI-U",
pvreadbackname="SARES20-HEX_PI:POSI-U",
name="uhex",
)
append_object_to_object(
self,
PvRecord,
"SARES20-HEX_PI:SET-POSI-V",
pvreadbackname="SARES20-HEX_PI:POSI-V",
name="vhex",
)
append_object_to_object(
self,
PvRecord,
"SARES20-HEX_PI:SET-POSI-W",
pvreadbackname="SARES20-HEX_PI:POSI-W",
name="whex",
)
# self.hex_x = PV("SARES20-HEX_PI:POSI-X")
# self.hex_y = PV("SARES20-HEX_PI:POSI-Y")
# self.hex_z = PV("SARES20-HEX_PI:POSI-Z")
@@ -66,7 +102,6 @@ class GPS:
if "hlrxrz" in self.configuration:
addMotorRecordToSelf(self, Id=Id + ":MOT_TBL_RX", name="rxhl")
addMotorRecordToSelf(self, Id=Id + ":MOT_TBL_RZ", name="rzhl")
def get_adjustable_positions_str(self):
ostr = "*****GPS motor positions******\n"
@@ -136,23 +171,74 @@ class XRD:
if "phi_hex" in self.configuration:
### motors PI hexapod ###
append_object_to_object(self,PvRecord,"SARES20-HEX_PI:SET-POSI-X",pvreadbackname="SARES20-HEX_PI:POSI-X",name='xhex')
append_object_to_object(self,PvRecord,"SARES20-HEX_PI:SET-POSI-Y",pvreadbackname="SARES20-HEX_PI:POSI-Y",name='yhex')
append_object_to_object(self,PvRecord,"SARES20-HEX_PI:SET-POSI-Z",pvreadbackname="SARES20-HEX_PI:POSI-Z",name='zhex')
append_object_to_object(self,PvRecord,"SARES20-HEX_PI:SET-POSI-U",pvreadbackname="SARES20-HEX_PI:POSI-U",name='uhex')
append_object_to_object(self,PvRecord,"SARES20-HEX_PI:SET-POSI-V",pvreadbackname="SARES20-HEX_PI:POSI-V",name='vhex')
append_object_to_object(self,PvRecord,"SARES20-HEX_PI:SET-POSI-W",pvreadbackname="SARES20-HEX_PI:POSI-W",name='whex')
append_object_to_object(
self,
PvRecord,
"SARES20-HEX_PI:SET-POSI-X",
pvreadbackname="SARES20-HEX_PI:POSI-X",
name="xhex",
)
append_object_to_object(
self,
PvRecord,
"SARES20-HEX_PI:SET-POSI-Y",
pvreadbackname="SARES20-HEX_PI:POSI-Y",
name="yhex",
)
append_object_to_object(
self,
PvRecord,
"SARES20-HEX_PI:SET-POSI-Z",
pvreadbackname="SARES20-HEX_PI:POSI-Z",
name="zhex",
)
append_object_to_object(
self,
PvRecord,
"SARES20-HEX_PI:SET-POSI-U",
pvreadbackname="SARES20-HEX_PI:POSI-U",
name="uhex",
)
append_object_to_object(
self,
PvRecord,
"SARES20-HEX_PI:SET-POSI-V",
pvreadbackname="SARES20-HEX_PI:POSI-V",
name="vhex",
)
append_object_to_object(
self,
PvRecord,
"SARES20-HEX_PI:SET-POSI-W",
pvreadbackname="SARES20-HEX_PI:POSI-W",
name="whex",
)
if "kappa" in self.configuration:
append_object_to_object(self,MotorRecord,"SARES21-XRD:MOT_KAP_KRX",name='eta')
append_object_to_object(self,MotorRecord,"SARES21-XRD:MOT_KAP_KAP",name='kappa')
append_object_to_object(self,MotorRecord,"SARES21-XRD:MOT_KAP_KPH",name='phi')
append_object_to_object(self,MotorRecord,"SARES21-XRD:MOT_KAP_DTY",name='zkap')
append_object_to_object(self,MotorRecord,"SARES21-XRD:MOT_KAP_DTX",name='xkap')
append_object_to_object(self,MotorRecord,"SARES21-XRD:MOT_KAP_DTZ",name='ykap')
append_object_to_object(self,MotorRecord,"SARES21-XRD:MOT_KAP_DRX",name='rxkap')
append_object_to_object(self,MotorRecord,"SARES21-XRD:MOT_KAP_DRZ",name='rykap')
append_object_to_object(
self, MotorRecord, "SARES21-XRD:MOT_KAP_KRX", name="eta"
)
append_object_to_object(
self, MotorRecord, "SARES21-XRD:MOT_KAP_KAP", name="kappa"
)
append_object_to_object(
self, MotorRecord, "SARES21-XRD:MOT_KAP_KPH", name="phi"
)
append_object_to_object(
self, MotorRecord, "SARES21-XRD:MOT_KAP_DTY", name="zkap"
)
append_object_to_object(
self, MotorRecord, "SARES21-XRD:MOT_KAP_DTX", name="xkap"
)
append_object_to_object(
self, MotorRecord, "SARES21-XRD:MOT_KAP_DTZ", name="ykap"
)
append_object_to_object(
self, MotorRecord, "SARES21-XRD:MOT_KAP_DRX", name="rxkap"
)
append_object_to_object(
self, MotorRecord, "SARES21-XRD:MOT_KAP_DRZ", name="rykap"
)
def get_adjustable_positions_str(self):
ostr = "*****XRD motor positions******\n"
+41 -38
View File
@@ -6,8 +6,9 @@ from epics import PV
from ..devices_general.delay_stage import DelayStage
from ..devices_general.adjustable import AdjustableVirtual
import colorama,datetime
import colorama, datetime
from pint import UnitRegistry
ureg = UnitRegistry()
@@ -27,7 +28,9 @@ def addDelayStageToSelf(self, stage=None, name=None):
class DelayTime(AdjustableVirtual):
def __init__(self, stage, direction=1, passes=2, reset_current_value_to=True, name=None):
def __init__(
self, stage, direction=1, passes=2, reset_current_value_to=True, name=None
):
self._direction = direction
self._group_velo = 299798458 # m/s
self._passes = passes
@@ -49,26 +52,26 @@ class DelayTime(AdjustableVirtual):
return s * self._group_velo * 1e3 / self._passes * self._direction
def __repr__(self):
s = ''
s = ""
s += f"{colorama.Style.DIM}"
s += datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')+': '
s += datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") + ": "
s += f"{colorama.Style.RESET_ALL}"
s += f"{colorama.Style.BRIGHT}{self._get_name()}{colorama.Style.RESET_ALL} at "
s += f'{(self.get_current_value()*ureg.second).to_compact():P~6.3f}'
s += f"{(self.get_current_value()*ureg.second).to_compact():P~6.3f}"
s += f"{colorama.Style.RESET_ALL}"
return s
def get_limits(self):
return [self._mm_to_s(tl) for tl in self._stage.get_limits()]
def set_limits(self,low_limit,high_limit):
lims_stage = [self._s_to_mm(tl) for tl in [low_limit,high_limit]]
def set_limits(self, low_limit, high_limit):
lims_stage = [self._s_to_mm(tl) for tl in [low_limit, high_limit]]
lims_stage.sort()
self._stage.set_limits(*lims_stage)
return [self._mm_to_s(tl) for tl in self._stage.get_limits()]
class DelayCompensation(AdjustableVirtual):
"""Simple virtual adjustable for compensating delay adjustables. It assumes the first adjustable is the master for
getting the current value."""
@@ -81,7 +84,7 @@ class DelayCompensation(AdjustableVirtual):
adjustables,
self._from_values,
self._calc_values,
set_current_value = set_current_value,
set_current_value=set_current_value,
name=name,
)
@@ -93,14 +96,14 @@ class DelayCompensation(AdjustableVirtual):
return positions[0]
tuple(tdir * value for tdir in self._directions)
def __repr__(self):
s = ''
s = ""
s += f"{colorama.Style.DIM}"
s += datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')+': '
s += datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") + ": "
s += f"{colorama.Style.RESET_ALL}"
s += f"{colorama.Style.BRIGHT}{self._get_name()}{colorama.Style.RESET_ALL} at "
s += f'{(self.get_current_value()*ureg.second).to_compact():P~6.3f}'
s += f"{(self.get_current_value()*ureg.second).to_compact():P~6.3f}"
s += f"{colorama.Style.RESET_ALL}"
return s
@@ -136,7 +139,7 @@ class Laser_Exp:
addMotorRecordToSelf(self, Id=self.Id + "-M521:MOTOR_1", name="delay_eos_stg")
self.delay_eos = DelayTime(self.delay_eos_stg, name="delay_eos")
self.alias.append(self.delay_eos.alias)
self.lxt_eos = DelayTime(self.delay_eos_stg, direction=-1,name="lxt_eos")
self.lxt_eos = DelayTime(self.delay_eos_stg, direction=-1, name="lxt_eos")
self.alias.append(self.lxt_eos.alias)
# except Exception as expt:
# print("Problems initializing eos delay stage")
@@ -156,7 +159,9 @@ class Laser_Exp:
)
self.delay_glob = DelayTime(self.delay_glob_stg, name="delay_glob")
self.alias.append(self.delay_glob.alias)
self.lxt_glob = DelayTime(self.delay_glob_stg, direction=-1, name="lxt_glob")
self.lxt_glob = DelayTime(
self.delay_glob_stg, direction=-1, name="lxt_glob"
)
self.alias.append(self.lxt_glob.alias)
except:
print("Problems initializing global delay stage")
@@ -167,21 +172,23 @@ class Laser_Exp:
[self.delay_glob, self.delay_tt], [-1, 1], name="delay_lxtt"
)
self.alias.append(self.delay_lxtt.alias)
except:
print('Problems initializing virtual pump delay stage')
except:
print("Problems initializing virtual pump delay stage")
# compressor
addMotorRecordToSelf(self, Id=self.Id + "-M532:MOT", name="compressor")
# self.compressor = MotorRecord(Id+'-M532:MOT')
# LAM delay stages
#addSmarActRecordToSelf(self, Id="SLAAR21-LMTS-LAM11", name="_lam_delay_smarstg")
#addDelayStageToSelf(self, self.__dict__["_lam_delay_smarstg"], name="lam_delay_smar")
# addSmarActRecordToSelf(self, Id="SLAAR21-LMTS-LAM11", name="_lam_delay_smarstg")
# addDelayStageToSelf(self, self.__dict__["_lam_delay_smarstg"], name="lam_delay_smar")
# self._lam_delayStg_Smar = SmarActRecord('SLAAR21-LMTS-LAM11')
# self.lam_delay_Smar = DelayStage(self._lam_delayStg_Smar)
try:
addMotorRecordToSelf(self, Id=self.Id + "-M548:MOT", name="_lam_delaystg")
addDelayStageToSelf(self, self.__dict__["_lam_delaystg"], name="lam_delay") #this try except does not work
except:
print('Problems initializing LAM delay stage')
addDelayStageToSelf(
self, self.__dict__["_lam_delaystg"], name="lam_delay"
) # this try except does not work
except:
print("Problems initializing LAM delay stage")
# self._lam_delayStg = MotorRecord(self.Id+'-M548:MOT')
# self.lam_delay = DelayStage(self._lam_delayStg)
@@ -195,9 +202,7 @@ class Laser_Exp:
# self._psen_delayStg = MotorRecord(self.Id+'')
# self.psen_delay = DelayStage(self._pump_delayStg)
try:
addMotorRecordToSelf(
self, Id=self.Id + "-M561:MOT", name="_psen_delaystg"
)
addMotorRecordToSelf(self, Id=self.Id + "-M561:MOT", name="_psen_delaystg")
addDelayStageToSelf(
self, stage=self.__dict__["_psen_delaystg"], name="psen_delay"
)
@@ -210,11 +215,9 @@ class Laser_Exp:
for smar_name, smar_address in self.smar_config.items():
#try:
addSmarActRecordToSelf(
self, Id=(self.IdSA + smar_address), name=smar_name
)
#except:
# try:
addSmarActRecordToSelf(self, Id=(self.IdSA + smar_address), name=smar_name)
# except:
# print("Loading %s SmarAct motor in bernina laser conifg failed") % (
# smar_name
# )
@@ -226,10 +229,10 @@ class Laser_Exp:
for tkey, item in sorted(self.__dict__.items()):
if hasattr(item, "get_current_value"):
pos = item.get_current_value()
posdialstr = ''
posdialstr = ""
try:
posdial = item.get_current_value(postype = 'dial')
posdialstr = ' dial: % 14g\n' % posdial
posdial = item.get_current_value(postype="dial")
posdialstr = " dial: % 14g\n" % posdial
except:
pass
ostr += " " + tkey.ljust(18) + " : % 14g\n" % pos + posdialstr
@@ -291,8 +294,8 @@ class Laser_Exp_old:
addDelayStageToSelf(
self, self.__dict__["_lam_delay_smarstg"], name="lam_delay_smar"
)
#self._lam_delayStg_Smar = SmarActRecord('SLAAR21-LMTS-LAM11')
#self.lam_delay_Smar = DelayStage(self._lam_delayStg_Smar)
# self._lam_delayStg_Smar = SmarActRecord('SLAAR21-LMTS-LAM11')
# self.lam_delay_Smar = DelayStage(self._lam_delayStg_Smar)
addMotorRecordToSelf(self, Id=self.Id + "-M548:MOT", name="_lam_delaystg")
addDelayStageToSelf(self, self.__dict__["_lam_delaystg"], name="lam_delay")
@@ -329,10 +332,10 @@ class Laser_Exp_old:
for tkey, item in sorted(self.__dict__.items()):
if hasattr(item, "get_current_value"):
pos = item.get_current_value()
posdialstr = ''
posdialstr = ""
try:
posdial = item.get_current_value(postype = 'dial')
posdialstr = ' dial: % 14g\n' % posdial
posdial = item.get_current_value(postype="dial")
posdialstr = " dial: % 14g\n" % posdial
except:
pass
ostr += " " + tkey.ljust(18) + " : % 14g\n" % pos + posdialstr
+2 -5
View File
@@ -26,7 +26,7 @@ parser.add_argument(
"-l", "--lazy", action="store_true", default=False, help="lazy initialisation"
)
parser.add_argument(
"--shell", action="store_true" , default=False, help="open eco in ipython shell"
"--shell", action="store_true", default=False, help="open eco in ipython shell"
)
parser.add_argument(
"--pylab", type=bool, default=True, help="open ipython shell in pylab mode"
@@ -41,9 +41,7 @@ if arguments.scopes_available:
print("{:<15s}{:<15s}{:<15s}".format("module", "name", "facility"))
for ts in ecocnf.scopes:
print(
" {:<14s} {:<14s} {:<14s}".format(
ts["module"], ts["name"], ts["facility"]
)
" {:<14s} {:<14s} {:<14s}".format(ts["module"], ts["name"], ts["facility"])
)
return
@@ -75,4 +73,3 @@ if scope:
term.set_title()
print(arguments)
+7 -7
View File
@@ -187,20 +187,20 @@ class MasterEventSystem:
Id = self._get_evtcode_Id(evtcode)
return self._get_Id_period(Id) / 1000
def get_evt_code_status(self,codes=None):
def get_evt_code_status(self, codes=None):
if not codes:
codes = sorted(eventcodes)
if isinstance(codes,Number):
if isinstance(codes, Number):
codes = [codes]
s = []
for c in codes:
s.append(f'{c:3d}: delay = {self.get_evtcode_delay(c)*1e6:9.3f} us; frequency: {self.get_evtcode_frequency(c):5.1f} Hz; Desc.: {self.get_evtcode_description(c)}')
s.append(
f"{c:3d}: delay = {self.get_evtcode_delay(c)*1e6:9.3f} us; frequency: {self.get_evtcode_frequency(c):5.1f} Hz; Desc.: {self.get_evtcode_description(c)}"
)
return s
def status(self,codes=None):
print('\n'.join(self.get_evt_code_status(codes)))
def status(self, codes=None):
print("\n".join(self.get_evt_code_status(codes)))
class EvrPulser:
+43 -15
View File
@@ -1,5 +1,5 @@
from epics import PV
from ..aliases import Alias,append_object_to_object
from ..aliases import Alias, append_object_to_object
from ..utilities.lazy_proxy import Proxy
from ..devices_general.adjustable import PvEnum, PvRecord
from ..eco_epics.utilities_epics import EpicsString
@@ -194,15 +194,34 @@ class EvrPulser:
self.name = name
self.alias = Alias(name)
self._pvs = {}
append_object_to_object(self,PvEnum,f"{self.pv_base}-Polarity-Sel", name="polarity")
append_object_to_object(self,PvEnum,f"{self.pv_base}-Ena-Sel", name="enable")
append_object_to_object(self,PvRecord,f"{self.pv_base}-Evt-Trig0-SP", name="eventcode")
append_object_to_object(self,PvRecord,f"{self.pv_base}-Evt-Set0-SP", name="event_set")
append_object_to_object(self,PvRecord,f"{self.pv_base}-Evt-Reset0-SP", name="event_reset")
append_object_to_object(self,PvRecord,f"{self.pv_base}-Delay-SP", pvreadbackname=f'{self.pv_base}-Delay-RB', name="delay")
append_object_to_object(self,PvRecord,f"{self.pv_base}-Width-SP", pvreadbackname=f'{self.pv_base}-Width-RB', name="width")
self.description = EpicsString(pv_base+'-Name-I')
append_object_to_object(
self, PvEnum, f"{self.pv_base}-Polarity-Sel", name="polarity"
)
append_object_to_object(self, PvEnum, f"{self.pv_base}-Ena-Sel", name="enable")
append_object_to_object(
self, PvRecord, f"{self.pv_base}-Evt-Trig0-SP", name="eventcode"
)
append_object_to_object(
self, PvRecord, f"{self.pv_base}-Evt-Set0-SP", name="event_set"
)
append_object_to_object(
self, PvRecord, f"{self.pv_base}-Evt-Reset0-SP", name="event_reset"
)
append_object_to_object(
self,
PvRecord,
f"{self.pv_base}-Delay-SP",
pvreadbackname=f"{self.pv_base}-Delay-RB",
name="delay",
)
append_object_to_object(
self,
PvRecord,
f"{self.pv_base}-Width-SP",
pvreadbackname=f"{self.pv_base}-Width-RB",
name="width",
)
self.description = EpicsString(pv_base + "-Name-I")
class EvrOutput:
@@ -212,12 +231,12 @@ class EvrOutput:
self.alias = Alias(name)
self._pulsers = None
# self._update_connected_pulsers()
append_object_to_object(self,PvEnum,f"{self.pv_base}-Ena-SP", name="enable")
append_object_to_object(self, PvEnum, f"{self.pv_base}-Ena-SP", name="enable")
self.pulsers_numbers = (
PvEnum(f"{self.pv_base}-Src-Pulse-SP", name="pulserA"),
PvEnum(f"{self.pv_base}-Src2-Pulse-SP", name="pulserB"),
)
self.description = EpicsString(pv_base+'-Name-I')
self.description = EpicsString(pv_base + "-Name-I")
def _get_pulserA(self):
return self._pulsers[self.pulsers_numbers[0].get_current_value()]
@@ -252,15 +271,24 @@ class EventReceiver:
self.pvname = pvname
pulsers = []
for n in range(n_pulsers):
append_object_to_object(self,EvrPulser,f"{self.pvname}:Pul{n}", name=f"pulser{n}")
append_object_to_object(
self, EvrPulser, f"{self.pvname}:Pul{n}", name=f"pulser{n}"
)
pulsers.append(self.__dict__[f"pulser{n}"])
self.pulsers = tuple(pulsers)
outputs = []
for n in range(n_output_front):
append_object_to_object(self,EvrOutput,f"{self.pvname}:FrontUnivOut{n}", name=f"output_front{n}")
append_object_to_object(
self,
EvrOutput,
f"{self.pvname}:FrontUnivOut{n}",
name=f"output_front{n}",
)
outputs.append(self.__dict__[f"output_front{n}"])
for n in range(n_output_rear):
append_object_to_object(self,EvrOutput,f"{self.pvname}:RearUniv{n}", name=f"output_rear{n}")
append_object_to_object(
self, EvrOutput, f"{self.pvname}:RearUniv{n}", name=f"output_rear{n}"
)
outputs.append(self.__dict__[f"output_rear{n}"])
for to in outputs:
to._pulsers = self.pulsers
+8 -2
View File
@@ -129,8 +129,14 @@ _OSCILLATOR_PERIOD = 1 / 71.368704e6
class LaserDelay:
def __init__(self, pv_set='SLAAR02-LTIM-PDLY:DELAY', pv_get='SLAAR-LGEN:DLY_OFFS2', name="xlt_edwin", dial_max=14.0056e-9, precision=100e-15):
def __init__(
self,
pv_set="SLAAR02-LTIM-PDLY:DELAY",
pv_get="SLAAR-LGEN:DLY_OFFS2",
name="xlt_edwin",
dial_max=14.0056e-9,
precision=100e-15,
):
self.pvnname = pv_basename
self._filename = os.path.join(_basefolder, pv_basename)
self._pv_setvalue = PV(pv_set)
+10 -16
View File
@@ -1,43 +1,37 @@
from functools import partial
class BeamlineSwissfel:
def __init__(self,components=['slits'],name=None):
def __init__(self, components=["slits"], name=None):
self.name = name
for comp_type in components:
self.__dict__[f'_{comp_type}'] = []
self.__dict__[comp] = partial(self._print_component_status,comp_type)
self.__dict__[f"_{comp_type}"] = []
self.__dict__[comp] = partial(self._print_component_status, comp_type)
def append_component(self,comp_type,item):
def append_component(self, comp_type, item):
self.__dict__[comp_type].append(item)
def _get_component_status(self,comp_type):
def _get_component_status(self, comp_type):
s = []
for comp in self.__dict__[comp_type]:
s.append(comp.__repr__())
return s
def _print_component_status(self,comp_type,linker='\n'):
def _print_component_status(self, comp_type, linker="\n"):
s = self._get_component_status()
print(linker.join(s))
class Slits:
def __init__(self, slits):
self.slits = slits
def __repr__(self):
o = []
for s in self.slits:
o.append(s.name)
tr = s.__repr__()
for line in tr.splitlines():
o.append(' '+line)
return '\n'.join(o)
o.append(" " + line)
return "\n".join(o)
+19 -12
View File
@@ -74,10 +74,14 @@ def replaceComponent(inp, dict_all, config_all, lazy=False):
if ta.name in dict_all.keys():
outp.append(dict_all[ta.name])
else:
ind = [ta.name==tca['name'] for tca in config_all].index(True)
outp.append(initFromConfigList(config_list[ind:ind+1],config_all,lazy=lazy))
ind = [ta.name == tca["name"] for tca in config_all].index(True)
outp.append(
initFromConfigList(
config_list[ind : ind + 1], config_all, lazy=lazy
)
)
elif isinstance(ta, dict) or isinstance(ta, list):
outp.append(replaceComponent(ta, dict_all,config_all, lazy=lazy))
outp.append(replaceComponent(ta, dict_all, config_all, lazy=lazy))
else:
outp.append(ta)
elif isinstance(inp, dict):
@@ -87,8 +91,10 @@ def replaceComponent(inp, dict_all, config_all, lazy=False):
if ta.name in dict_all.keys():
outp[tk] = dict_all[ta.name]
else:
ind = [tk.name==tca['name'] for tca in config_all].index(True)
outp[tk] = initFromConfigList(config_list[ind:ind+1],config_all,lazy=lazy)
ind = [tk.name == tca["name"] for tca in config_all].index(True)
outp[tk] = initFromConfigList(
config_list[ind : ind + 1], config_all, lazy=lazy
)
elif isinstance(ta, dict) or isinstance(ta, list):
outp[tk] = replaceComponent(ta, dict_all, config_all, lazy=lazy)
else:
@@ -178,7 +184,7 @@ def writeConfig(fina, obj):
class ChannelList(list):
def __init__(self,*args,**kwargs):
def __init__(self, *args, **kwargs):
self.file_name = kwargs.pop("file_name")
# list.__init__(*args,**kwargs)
self.load()
@@ -212,8 +218,9 @@ def prepend_to_path(*args):
for targ in args:
sys.path.insert(0, targ)
class Terminal:
def __init__(self,title='eco',scope=None):
def __init__(self, title="eco", scope=None):
self.title = title
self.scope = scope
@@ -230,11 +237,11 @@ class Terminal:
return getpass.getuser()
def get_string(self):
s = f'{self.title}'
s = f"{self.title}"
if self.scope:
s +=f'-{self.scope}'
s += f' ({self.user}@{self.host})'
s += f"-{self.scope}"
s += f" ({self.user}@{self.host})"
return s
def set_title(self,extension=''):
print(colorama.ansi.set_title("♻️ "+self.get_string()+extension))
def set_title(self, extension=""):
print(colorama.ansi.set_title("♻️ " + self.get_string() + extension))
+85 -60
View File
@@ -1,8 +1,8 @@
from ..devices_general.motors import MotorRecord
from ..eco_epics.utilities_epics import EnumWrapper
from ..devices_general.detectors import FeDigitizer,PvDataStream
from ..devices_general.detectors import FeDigitizer, PvDataStream
from ..devices_general.adjustable import PvEnum
from ..aliases import Alias,append_object_to_object
from ..aliases import Alias, append_object_to_object
from epics import PV
import numpy as np
@@ -12,14 +12,13 @@ class GasDetector:
pass
class SolidTargetDetectorPBPS_new:
def __init__(
self,
pvname,
VME_crate=None,
link=None,
channels = {},
channels={},
ch_up=12,
ch_down=13,
ch_left=15,
@@ -28,34 +27,46 @@ class SolidTargetDetectorPBPS_new:
name=None,
calc=None,
calc_calib={},
):
self.name = name
self.pvname = pvname
self.alias = Alias(name)
append_object_to_object(self,MotorRecord,pvname + ":MOTOR_X1", name="x_diodes")
append_object_to_object(self,MotorRecord,pvname + ":MOTOR_Y1", name="y_diodes")
append_object_to_object(self,MotorRecord,pvname + ":MOTOR_PROBE", name="target_y")
append_object_to_object(self,PvEnum,pvname + ":PROBE_SP", name="target")
append_object_to_object(
self, MotorRecord, pvname + ":MOTOR_X1", name="x_diodes"
)
append_object_to_object(
self, MotorRecord, pvname + ":MOTOR_Y1", name="y_diodes"
)
append_object_to_object(
self, MotorRecord, pvname + ":MOTOR_PROBE", name="target_y"
)
append_object_to_object(self, PvEnum, pvname + ":PROBE_SP", name="target")
if VME_crate:
self.diode_up = FeDigitizer("%s:Lnk%dCh%d" % (VME_crate, link, ch_up))
self.diode_down = FeDigitizer("%s:Lnk%dCh%d" % (VME_crate, link, ch_down))
self.diode_left = FeDigitizer("%s:Lnk%dCh%d" % (VME_crate, link, ch_left))
self.diode_right = FeDigitizer("%s:Lnk%dCh%d" % (VME_crate, link, ch_right))
if channels:
append_object_to_object(self,PvDataStream,channels['up'], name="signal_up")
append_object_to_object(self,PvDataStream,channels['down'], name="signal_down")
append_object_to_object(self,PvDataStream,channels['left'], name="signal_left")
append_object_to_object(self,PvDataStream,channels['right'], name="signal_right")
append_object_to_object(
self, PvDataStream, channels["up"], name="signal_up"
)
append_object_to_object(
self, PvDataStream, channels["down"], name="signal_down"
)
append_object_to_object(
self, PvDataStream, channels["left"], name="signal_left"
)
append_object_to_object(
self, PvDataStream, channels["right"], name="signal_right"
)
if calc:
append_object_to_object(self,PvDataStream,calc['itot'], name="intensity")
append_object_to_object(self,PvDataStream,calc['xpos'], name="xpos")
append_object_to_object(self,PvDataStream,calc['ypos'], name="ypos")
append_object_to_object(self, PvDataStream, calc["itot"], name="intensity")
append_object_to_object(self, PvDataStream, calc["xpos"], name="xpos")
append_object_to_object(self, PvDataStream, calc["ypos"], name="ypos")
def get_calibration_values(self,seconds=5):
def get_calibration_values(self, seconds=5):
self.x_diodes.set_target_value(0).wait()
self.y_diodes.set_target_value(0).wait()
ds = [self.signal_up, self.signal_down, self.signal_left, self.signal_right]
@@ -63,68 +74,80 @@ class SolidTargetDetectorPBPS_new:
data = [aq.wait() for aq in aqs]
mean = [np.mean(td) for td in data]
std = [np.std(td) for td in data]
norm_diodes = [1/tm/4 for tm in mean]
norm_diodes = [1 / tm / 4 for tm in mean]
return norm_diodes
def set_calibration_values(self,norm_diodes):
#this is now only for bernina when using the ioxos from sla
channels = ['SLAAR21-LTIM01-EVR0:CALCI.INPG','SLAAR21-LTIM01-EVR0:CALCI.INPH','SLAAR21-LTIM01-EVR0:CALCI.INPF','SLAAR21-LTIM01-EVR0:CALCI.INPE']
for tc,tv in zip(channels,norm_diodes):
PV(tc).put(bytes(str(tv),'utf8'))
channels = ['SLAAR21-LTIM01-EVR0:CALCX.INPE','SLAAR21-LTIM01-EVR0:CALCX.INPF']
for tc,tv in zip(channels,norm_diodes[2:4]):
PV(tc).put(bytes(str(tv),'utf8'))
channels = ['SLAAR21-LTIM01-EVR0:CALCY.INPE','SLAAR21-LTIM01-EVR0:CALCY.INPF']
for tc,tv in zip(channels,norm_diodes[0:2]):
PV(tc).put(bytes(str(tv),'utf8'))
def set_calibration_values(self, norm_diodes):
# this is now only for bernina when using the ioxos from sla
channels = [
"SLAAR21-LTIM01-EVR0:CALCI.INPG",
"SLAAR21-LTIM01-EVR0:CALCI.INPH",
"SLAAR21-LTIM01-EVR0:CALCI.INPF",
"SLAAR21-LTIM01-EVR0:CALCI.INPE",
]
for tc, tv in zip(channels, norm_diodes):
PV(tc).put(bytes(str(tv), "utf8"))
channels = ["SLAAR21-LTIM01-EVR0:CALCX.INPE", "SLAAR21-LTIM01-EVR0:CALCX.INPF"]
for tc, tv in zip(channels, norm_diodes[2:4]):
PV(tc).put(bytes(str(tv), "utf8"))
channels = ["SLAAR21-LTIM01-EVR0:CALCY.INPE", "SLAAR21-LTIM01-EVR0:CALCY.INPF"]
for tc, tv in zip(channels, norm_diodes[0:2]):
PV(tc).put(bytes(str(tv), "utf8"))
def get_calibration_values_position(self,calib_intensities,seconds=5,motion_range=.2):
self.x_diodes.set_limits(-motion_range/2-.1,+motion_range/2+.1)
self.y_diodes.set_limits(-motion_range/2-.1,+motion_range/2+.1)
def get_calibration_values_position(
self, calib_intensities, seconds=5, motion_range=0.2
):
self.x_diodes.set_limits(-motion_range / 2 - 0.1, +motion_range / 2 + 0.1)
self.y_diodes.set_limits(-motion_range / 2 - 0.1, +motion_range / 2 + 0.1)
self.x_diodes.set_target_value(0).wait()
self.y_diodes.set_target_value(0).wait()
raw = []
for pos in [motion_range/2, -motion_range/2]:
for pos in [motion_range / 2, -motion_range / 2]:
self.x_diodes.set_target_value(pos).wait()
aqs = [ts.acquire(seconds=seconds) for ts in [self.signal_left, self.signal_right]]
vals = [np.mean(aq.wait())*calib for aq,calib in zip(aqs,calib_intensities[0:2])]
raw.append((vals[0]-vals[1])/(vals[0]+vals[1]))
grad = motion_range/np.diff(raw)[0]
aqs = [
ts.acquire(seconds=seconds)
for ts in [self.signal_left, self.signal_right]
]
vals = [
np.mean(aq.wait()) * calib
for aq, calib in zip(aqs, calib_intensities[0:2])
]
raw.append((vals[0] - vals[1]) / (vals[0] + vals[1]))
grad = motion_range / np.diff(raw)[0]
# xcalib = [np.diff(calib_intensities[0:2])[0]/np.sum(calib_intensities[0:2]), grad]
xcalib = [0, grad]
self.x_diodes.set_target_value(0).wait()
raw = []
for pos in [motion_range/2, -motion_range/2]:
for pos in [motion_range / 2, -motion_range / 2]:
self.y_diodes.set_target_value(pos).wait()
aqs = [ts.acquire(seconds=seconds) for ts in [self.signal_up, self.signal_down]]
vals = [np.mean(aq.wait())*calib for aq,calib in zip(aqs,calib_intensities[2:4])]
raw.append((vals[0]-vals[1])/(vals[0]+vals[1]))
grad = motion_range/np.diff(raw)[0]
aqs = [
ts.acquire(seconds=seconds) for ts in [self.signal_up, self.signal_down]
]
vals = [
np.mean(aq.wait()) * calib
for aq, calib in zip(aqs, calib_intensities[2:4])
]
raw.append((vals[0] - vals[1]) / (vals[0] + vals[1]))
grad = motion_range / np.diff(raw)[0]
# ycalib = [np.diff(calib_intensities[2:4])[0]/np.sum(calib_intensities[2:4]), grad]
ycalib = [0, grad]
self.y_diodes.set_target_value(0).wait()
return xcalib,ycalib
return xcalib, ycalib
def set_calibration_values_position(self,xcalib,ycalib):
channels = ['SLAAR21-LTIM01-EVR0:CALCX.INPJ','SLAAR21-LTIM01-EVR0:CALCX.INPI']
def set_calibration_values_position(self, xcalib, ycalib):
channels = ["SLAAR21-LTIM01-EVR0:CALCX.INPJ", "SLAAR21-LTIM01-EVR0:CALCX.INPI"]
# txcalib = [-1*xcalib[0],-1*xcalib[1]]
for tc,tv in zip(channels,xcalib):
PV(tc).put(bytes(str(tv),'utf8'))
channels = ['SLAAR21-LTIM01-EVR0:CALCY.INPJ','SLAAR21-LTIM01-EVR0:CALCY.INPI']
for tc,tv in zip(channels,ycalib):
PV(tc).put(bytes(str(tv),'utf8'))
for tc, tv in zip(channels, xcalib):
PV(tc).put(bytes(str(tv), "utf8"))
channels = ["SLAAR21-LTIM01-EVR0:CALCY.INPJ", "SLAAR21-LTIM01-EVR0:CALCY.INPI"]
for tc, tv in zip(channels, ycalib):
PV(tc).put(bytes(str(tv), "utf8"))
def calibrate(self,seconds=5):
def calibrate(self, seconds=5):
c = self.get_calibration_values(seconds=seconds)
self.set_calibration_values(c)
xc,yc = self.get_calibration_values_position(c,seconds=seconds)
self.set_calibration_values_position(xc,yc)
xc, yc = self.get_calibration_values_position(c, seconds=seconds)
self.set_calibration_values_position(xc, yc)
def __repr__(self):
s = f"**Intensity monitor {self.name}**\n\n"
@@ -191,6 +214,8 @@ class SolidTargetDetectorPBPS_new:
print("No diodes configured, can not change any gain!")
# SAROP21-CVME-PBPS:Lnk10Ch15-WD-gain
class SolidTargetDetectorPBPS:
def __init__(
self,
+74 -39
View File
@@ -1,45 +1,64 @@
from ..devices_general.motors import MotorRecord
# from ..devices_general.smaract import SmarActRecord
# from epics import PV
from ..devices_general.delay_stage import DelayStage
# from ..devices_general.adjustable import
from ..aliases import Alias,append_object_to_object
# from ..devices_general.adjustable import
from ..aliases import Alias, append_object_to_object
from psen_processing import PsenProcessingClient
from ..loptics.bernina_experiment import DelayTime
from cam_server import PipelineClient
class SpectralEncoder:
def __init__(self, pvname, name=None, reduction_client_address="http://sf-daqsync-02:12002/",delay_stages={'spect_tt':"SLAAR21-LMOT-M553:MOT","retroreflector":"SLAAR21-LMOT-M561:MOT"}):
def __init__(
self,
pvname,
name=None,
reduction_client_address="http://sf-daqsync-01:8889/",
delay_stages={
"spect_tt": "SLAAR21-LMOT-M553:MOT",
"retroreflector": "SLAAR21-LMOT-M561:MOT",
},
):
self.pvname = pvname
self.name=name
self.name = name
self.alias = Alias(name)
append_object_to_object(self,MotorRecord,pvname+":MOTOR_X1",name='x_target')
append_object_to_object(self,MotorRecord,pvname+":MOTOR_Y1",name='y_target')
append_object_to_object(
self, MotorRecord, pvname + ":MOTOR_X1", name="x_target"
)
append_object_to_object(
self, MotorRecord, pvname + ":MOTOR_Y1", name="y_target"
)
if delay_stages:
for key,pv in delay_stages.items():
tname = 'delay_'+key+'_stg'
append_object_to_object(self,MotorRecord,pv,name=tname)
append_object_to_object(self,DelayTime,self.__dict__[tname],name='delay_'+key)
for key, pv in delay_stages.items():
tname = "delay_" + key + "_stg"
append_object_to_object(self, MotorRecord, pv, name=tname)
append_object_to_object(
self, DelayTime, self.__dict__[tname], name="delay_" + key
)
# self.delay = MotorRecord(self.Id + "-M424:MOT")
# self.delayTime = DelayStage(self.delay)
self.data_reduction_client = PsenProcessingClient(address=reduction_client_address)
self.data_reduction_client = PsenProcessingClient(
address=reduction_client_address
)
@property
def roi(self):
return self.data_reduction_client.get_roi_signal()
@roi.setter
def roi(self,values):
def roi(self, values):
self.data_reduction_client.set_roi_signal(values)
@property
def roi_background(self):
return self.data_reduction_client.get_roi_background()
@roi_background.setter
def roi_background(self,values):
def roi_background(self, values):
self.data_reduction_client.set_roi_background(values)
def __repr__(self):
@@ -49,19 +68,28 @@ class SpectralEncoder:
s.append(f"Data reduction is on")
s.append(f" roi {self.roi}")
s.append(f" roi_background {self.roi_background}")
return '\n'.join(s)
return "\n".join(s)
class SpatialEncoder:
def __init__(self, name=None, reduction_client_address="http://sf-daqsync-02:12003/",delay_stages={'spatial_tt':"SLAAR21-LMOT-M522:MOTOR_1"},pipeline_id='SARES20-CAMS142-M4_psen_db1'):
self.name=name
def __init__(
self,
name=None,
reduction_client_address="http://sf-daqsync-02:12003/",
delay_stages={"spatial_tt": "SLAAR21-LMOT-M522:MOTOR_1"},
pipeline_id="SARES20-CAMS142-M4_psen_db1",
):
self.name = name
self.alias = Alias(name)
# append_object_to_object(self,MotorRecord,pvname+":MOTOR_X1",name='x_target')
# append_object_to_object(self,MotorRecord,pvname+":MOTOR_Y1",name='y_target')
if delay_stages:
for key,pv in delay_stages.items():
tname = 'delay_'+key+'_stg'
append_object_to_object(self,MotorRecord,pv,name=tname)
append_object_to_object(self,DelayTime,self.__dict__[tname],name='delay_'+key)
for key, pv in delay_stages.items():
tname = "delay_" + key + "_stg"
append_object_to_object(self, MotorRecord, pv, name=tname)
append_object_to_object(
self, DelayTime, self.__dict__[tname], name="delay_" + key
)
# self.delay = MotorRecord(self.Id + "-M424:MOT")
# self.delayTime = DelayStage(self.delay)
@@ -69,36 +97,43 @@ class SpatialEncoder:
self._camera_server_client = PipelineClient()
self._camera_server_pipeline_id = pipeline_id
# @property
# def roi(self):
# return self.data_reduction_client.get_roi_signal()
# return self.data_reduction_client.get_roi_signal()
# @roi.setter
# def roi(self,values):
# self.data_reduction_client.set_roi_signal(values)
# self.data_reduction_client.set_roi_signal(values)
# @property
# def roi_background(self):
# return self.data_reduction_client.get_roi_background()
# return self.data_reduction_client.get_roi_background()
# @roi_background.setter
# def roi_background(self,values):
# self.data_reduction_client.set_roi_background(values)
# self.data_reduction_client.set_roi_background(values)
@property
def roi(self):
return self._camera_server_client.get_instance_config(self._camera_server_pipeline_id)['roi_signal']
return self._camera_server_client.get_instance_config(
self._camera_server_pipeline_id
)["roi_signal"]
@roi.setter
def roi(self,values):
self._camera_server_client.set_instance_config(self._camera_server_pipeline_id,{'roi_signal':values})
def roi(self, values):
self._camera_server_client.set_instance_config(
self._camera_server_pipeline_id, {"roi_signal": values}
)
@property
def roi_background(self):
return self._camera_server_client.get_instance_config(self._camera_server_pipeline_id)['roi_background']
@roi_background.setter
def roi_background(self,values):
self._camera_server_client.set_instance_config(self._camera_server_pipeline_id,{'roi_background':values})
return self._camera_server_client.get_instance_config(
self._camera_server_pipeline_id
)["roi_background"]
@roi_background.setter
def roi_background(self, values):
self._camera_server_client.set_instance_config(
self._camera_server_pipeline_id, {"roi_background": values}
)
def __repr__(self):
s = [f"Status {self.name}"]
@@ -107,4 +142,4 @@ class SpatialEncoder:
s.append(f"Data reduction is on")
s.append(f" roi {self.roi}")
s.append(f" roi_background {self.roi_background}")
return '\n'.join(s)
return "\n".join(s)
+12 -11
View File
@@ -7,7 +7,9 @@ from ..devices_general.adjustable import PvEnum
class AttenuatorAramis:
def __init__(self, Id, E_min=1500, sleeptime=1, name=None, set_limits=[-52, 2],pulse_picker=None):
def __init__(
self, Id, E_min=1500, sleeptime=1, name=None, set_limits=[-52, 2], shutter=None
):
self.Id = Id
self.E_min = E_min
self._pv_status_str = PV(self.Id + ":MOT2TRANS.VALD")
@@ -15,10 +17,9 @@ class AttenuatorAramis:
self._sleeptime = sleeptime
self.name = name
self.alias = Alias(name)
self.pulse_picker = pulse_picker
self.shutter = shutter
self.motors = [
MotorRecord(f"{self.Id}:MOTOR_{n+1}", name=f"motor{n+1}")
for n in range(6)
MotorRecord(f"{self.Id}:MOTOR_{n+1}", name=f"motor{n+1}") for n in range(6)
]
for n, mot in enumerate(self.motors):
self.__dict__[f"motor_{n+1}"] = mot
@@ -59,24 +60,24 @@ class AttenuatorAramis:
def setE(self):
pass
def get_transmission(self,verbose=True):
def get_transmission(self, verbose=True):
tFun = PV(self.Id + ":TRANS_RB").value
tTHG = PV(self.Id + ":TRANS3EDHARM_RB").value
if verbose:
print("Transmission Fundamental: %s THG: %s" % (tFun, tTHG))
return tFun, tTHG
def get_current_value(self,*args,**kwargs):
return self.get_transmission(*args,verbose=False,**kwargs)[0]
def get_current_value(self, *args, **kwargs):
return self.get_transmission(*args, verbose=False, **kwargs)[0]
def set_target_value(self,value,sleeptime=10,hold=False):
def set_target_value(self, value, sleeptime=10, hold=False):
def changer(value):
self.set_transmission(value)
sleep(sleeptime)
if self.pulse_picker:
self.pulse_picker.open()
return Changer(target=value, parent=self, changer=changer, hold=hold)
if self.shutter:
self.shutter.open()
return Changer(target=value, parent=self, changer=changer, hold=hold)
def get_status(self):
s_str = self._pv_status_str.get(as_string=True)
+4 -1
View File
@@ -137,7 +137,10 @@ class MonoEcolEnergy:
return self.dcm.get_current_value()
def move_and_wait(self, value):
ch = [self.dcm.set_target_value(value), self.ecol.set_target_value(self.calcEcol(value))]
ch = [
self.dcm.set_target_value(value),
self.ecol.set_target_value(self.calcEcol(value)),
]
for tc in ch:
tc.wait()
+6 -9
View File
@@ -53,15 +53,12 @@ class Pulsepick:
def get_status(self):
stat = self._evrsrc.get()
if stat==62 and self._openclose.get()==1:
return 'open'
if self._openclose.get()==0:
return 'closed'
if stat == 62 and self._openclose.get() == 1:
return "open"
if self._openclose.get() == 0:
return "closed"
else:
return 'unknown'
return "unknown"
def __repr__(self):
return f'FEL pulse picker state {self.get_status()}.'
return f"FEL pulse picker state {self.get_status()}."
+35 -25
View File
@@ -8,9 +8,11 @@ def addSlitRepr(Slitobj):
def repr(self):
s = f"pos ({self.hpos.get_current_value():6.3f},{self.vpos.get_current_value():6.3f}), gap ({self.hgap.get_current_value():6.3f},{self.vgap.get_current_value():6.3f})"
return s
Slitobj.__repr__ = repr
Slitobj.__repr__ = repr
return Slitobj
@addSlitRepr
class SlitBlades:
def __init__(self, pvname, name=None, elog=None):
@@ -21,10 +23,18 @@ class SlitBlades:
append_object_to_object(self, MotorRecord, pvname + ":MOTOR_X2", name="left")
append_object_to_object(self, MotorRecord, pvname + ":MOTOR_Y1", name="down")
append_object_to_object(self, MotorRecord, pvname + ":MOTOR_Y2", name="up")
append_object_to_object(self, MotorRecord, pvname + ":MOTOR_X", name="hpos_virt_mrec")
append_object_to_object(self, MotorRecord, pvname + ":MOTOR_W", name="hgap_virt_mrec")
append_object_to_object(self, MotorRecord, pvname + ":MOTOR_Y", name="vpos_virt_mrec")
append_object_to_object(self, MotorRecord, pvname + ":MOTOR_H", name="vgap_virt_mrec")
append_object_to_object(
self, MotorRecord, pvname + ":MOTOR_X", name="hpos_virt_mrec"
)
append_object_to_object(
self, MotorRecord, pvname + ":MOTOR_W", name="hgap_virt_mrec"
)
append_object_to_object(
self, MotorRecord, pvname + ":MOTOR_Y", name="vpos_virt_mrec"
)
append_object_to_object(
self, MotorRecord, pvname + ":MOTOR_H", name="vgap_virt_mrec"
)
def getgap(xn, xp):
return xp - xn
@@ -103,6 +113,7 @@ class SlitBlades:
else:
raise Exception("wrong number of input arguments!")
@addSlitRepr
class SlitPosWidth:
def __init__(self, pvname, name=None, elog=None):
@@ -114,14 +125,14 @@ class SlitPosWidth:
append_object_to_object(self, MotorRecord, pvname + ":MOTOR_W", name="hgap")
append_object_to_object(self, MotorRecord, pvname + ":MOTOR_H", name="vgap")
def getblade(pos,gap,direction=1):
return pos + direction*gap/2
def getblade(pos, gap, direction=1):
return pos + direction * gap / 2
def setblade(bde,pos,gap,direction=1):
delta = bde-getblade(pos,gap,direction=direction)
ngap = gap + direction*delta
npos = pos + direction*delta/2
return npos,ngap
def setblade(bde, pos, gap, direction=1):
delta = bde - getblade(pos, gap, direction=direction)
ngap = gap + direction * delta
npos = pos + direction * delta / 2
return npos, ngap
def getpos(xn, xp):
return (xn + xp) / 2
@@ -142,37 +153,37 @@ class SlitPosWidth:
self,
AdjustableVirtual,
[self.vpos, self.vgap],
partial(getblade,direction=1),
partial(setblade,direction=1),
partial(getblade, direction=1),
partial(setblade, direction=1),
reset_current_value_to=True,
name="up"
name="up",
)
append_object_to_object(
self,
AdjustableVirtual,
[self.vpos, self.vgap],
partial(getblade,direction=-1),
partial(setblade,direction=-1),
partial(getblade, direction=-1),
partial(setblade, direction=-1),
reset_current_value_to=True,
name="down"
name="down",
)
append_object_to_object(
self,
AdjustableVirtual,
[self.hpos, self.hgap],
partial(getblade,direction=1),
partial(setblade,direction=1),
partial(getblade, direction=1),
partial(setblade, direction=1),
reset_current_value_to=True,
name="left"
name="left",
)
append_object_to_object(
self,
AdjustableVirtual,
[self.hpos, self.hgap],
partial(getblade,direction=-1),
partial(setblade,direction=-1),
partial(getblade, direction=-1),
partial(setblade, direction=-1),
reset_current_value_to=True,
name="right"
name="right",
)
def __call__(self, *args):
@@ -198,7 +209,6 @@ class SlitPosWidth:
raise Exception("wrong number of input arguments!")
@addSlitRepr
class SlitBlades_JJ:
def __init__(self, pvname, name=None, elog=None):
+4 -2
View File
@@ -27,7 +27,7 @@ def main():
"-l", "--lazy", action="store_true", default=False, help="lazy initialisation"
)
parser.add_argument(
"--shell", action="store_true" , default=False, help="open eco in ipython shell"
"--shell", action="store_true", default=False, help="open eco in ipython shell"
)
parser.add_argument(
"--pylab", type=bool, default=True, help="open ipython shell in pylab mode"
@@ -78,12 +78,14 @@ def main():
print(arguments)
if arguments.shell:
if arguments.pylab:
print('start pylab with %pylab')
print("start pylab with %pylab")
from IPython import embed
embed()
else:
from IPython import embed
embed()
+5 -8
View File
@@ -2,7 +2,7 @@
from eco import ecocnf
from eco.utilities.config import Terminal
import sys
import sys
import argparse
@@ -27,7 +27,7 @@ parser.add_argument(
"-l", "--lazy", action="store_true", default=False, help="lazy initialisation"
)
parser.add_argument(
"--shell", action="store_true" , default=False, help="open eco in ipython shell"
"--shell", action="store_true", default=False, help="open eco in ipython shell"
)
parser.add_argument(
"--pylab", type=bool, default=True, help="open ipython shell in pylab mode"
@@ -42,9 +42,7 @@ if arguments.scopes_available:
print("{:<15s}{:<15s}{:<15s}".format("module", "name", "facility"))
for ts in ecocnf.scopes:
print(
" {:<14s} {:<14s} {:<14s}".format(
ts["module"], ts["name"], ts["facility"]
)
" {:<14s} {:<14s} {:<14s}".format(ts["module"], ts["name"], ts["facility"])
)
@@ -63,8 +61,8 @@ if scope:
ecocnf.startup_lazy = True
exec(f"import eco.{scope} as {scope}")
exec(f"op = {scope}.init()")
for tk,tv in op.items():
sys.modules['__main__'].__dict__[tk] = tv
for tk, tv in op.items():
sys.modules["__main__"].__dict__[tk] = tv
# exec(f'{scope}.init(lazy=ecocnf.startup_lazy)')
# exec(f"from eco.{scope} import *")
# is there an __all__? if so respect it
@@ -78,4 +76,3 @@ if scope:
term.set_title()
print(arguments)