Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • 29id/iexcode
1 result
Show changes
Commits on Source (27)
Showing
with 563 additions and 552 deletions
...@@ -49,12 +49,12 @@ ___ ...@@ -49,12 +49,12 @@ ___
### **Motor Moves and Scans** ### **Motor Moves and Scans**
------------------------------------------------------------- -------------------------------------------------------------
mprint() #prints current position mprint() #prints current position
mv_sample(position_list) #moves to position mvsample(position_list) #moves to position
------------------------------------------------------------- -------------------------------------------------------------
mvx(val) / mvy(val) / mvz(val) / mvth(val) mvx(val) / mvy(val) / mvz(val) / mvth(val)
scanx(start,stop,step) / dscanx(delta_start,delta_stop,step) ... scanx(start,stop,step) / dscanx(delta_start,delta_stop,step) ...
------------------------------------------------------------- -------------------------------------------------------------
ARPES_map_sample(y_start,y_stop,y_step,z_start,z_stop,z_step) sample_map(y_start,y_stop,y_step,z_start,z_stop,z_step)
------------------------------------------------------------- -------------------------------------------------------------
mvfocus(x_val) mvfocus(x_val)
mvy_fixed_focus(y_val) mvy_fixed_focus(y_val)
......
...@@ -21,7 +21,13 @@ from iexcode.instruments.scanRecord import mda_filepath, mda_ioc ...@@ -21,7 +21,13 @@ from iexcode.instruments.scanRecord import mda_filepath, mda_ioc
def AD_exposure_time(ADplugin,exp_time,**kwargs): def AD_exposure_time(ADplugin,exp_time,**kwargs):
""" """
sets the aquiretime and the exposure time sets the aquiretime and the exposure time
overwrites what is in kwargs
ADplugin = $(P)$(SavePlugin) (e.g. 29id_ps1:TIFF1:); only needs P with the :
exp_time: exposure time in seconds
**kwargs:
P = camera ioc (default is to split ADplugin)
R = "cam1:" by default
""" """
kwargs.setdefault("P",ADplugin.split(":")[0]+":") kwargs.setdefault("P",ADplugin.split(":")[0]+":")
kwargs.setdefault("R","cam1:") kwargs.setdefault("R","cam1:")
...@@ -36,7 +42,8 @@ def AD_filepath(ADplugin): ...@@ -36,7 +42,8 @@ def AD_filepath(ADplugin):
""" """
returns the current directory for area detector SavePlugin returns the current directory for area detector SavePlugin
handles both Winodws and linux IOCs handles both Winodws and linux IOCs
ADplugin = "29idc_ps1:TIFF1:"; $(P)$(SavePlugin)
ADplugin = $(P)$(SavePlugin) (e.g. 29id_ps1:TIFF1:)
""" """
SubDir=caget(ADplugin+"FilePath",as_string=True) SubDir=caget(ADplugin+"FilePath",as_string=True)
if SubDir[0] == 'X': if SubDir[0] == 'X':
...@@ -57,6 +64,8 @@ def AD_filepath(ADplugin): ...@@ -57,6 +64,8 @@ def AD_filepath(ADplugin):
def AD_prefix(ADplugin): def AD_prefix(ADplugin):
""" """
returns the prefix for AreaDetector plugin based on ADplugin returns the prefix for AreaDetector plugin based on ADplugin
ADplugin = $(P)$(SavePlugin) (e.g. 29id_ps1:TIFF1:)
""" """
prefix = caget(ADplugin+"FileName_RBV",as_string=True) prefix = caget(ADplugin+"FileName_RBV",as_string=True)
return prefix return prefix
...@@ -64,6 +73,7 @@ def AD_prefix(ADplugin): ...@@ -64,6 +73,7 @@ def AD_prefix(ADplugin):
def AD_EnableStats(ADplugin): def AD_EnableStats(ADplugin):
""" """
Enabling the statistics in an AreaDector Enabling the statistics in an AreaDector
ADplugin = "29idc_ps1:Stats1:"; (ADplugin=$(P)$(StatsPlugin)) ADplugin = "29idc_ps1:Stats1:"; (ADplugin=$(P)$(StatsPlugin))
""" """
caput(ADplugin+"EnableCallbacks","Enable") caput(ADplugin+"EnableCallbacks","Enable")
...@@ -73,6 +83,8 @@ def AD_EnableStats(ADplugin): ...@@ -73,6 +83,8 @@ def AD_EnableStats(ADplugin):
def AD_last_filename(ADplugin,verbose=True): def AD_last_filename(ADplugin,verbose=True):
""" """
returns the full path for the last saved image returns the full path for the last saved image
ADplugin = $(P)$(SavePlugin) (e.g. 29id_ps1:TIFF1:)
""" """
fpath = caget(ADplugin+"FullFileName_RBV",as_string=True) fpath = caget(ADplugin+"FullFileName_RBV",as_string=True)
if verbose: if verbose:
...@@ -128,6 +140,7 @@ def AD_SaveFileSetup(ADplugin,**kwargs): ...@@ -128,6 +140,7 @@ def AD_SaveFileSetup(ADplugin,**kwargs):
def AD_CurrentPrefix(ADplugin): def AD_CurrentPrefix(ADplugin):
""" """
returns the prefix (without _) for area detector SavePlugin returns the prefix (without _) for area detector SavePlugin
ADplugin = "29id_ps1:TIFF1:"; $(P)$(SavePlugin) ADplugin = "29id_ps1:TIFF1:"; $(P)$(SavePlugin)
""" """
Prefix=caget(ADplugin+'FileName',as_string=True) Prefix=caget(ADplugin+'FileName',as_string=True)
...@@ -136,6 +149,7 @@ def AD_CurrentPrefix(ADplugin): ...@@ -136,6 +149,7 @@ def AD_CurrentPrefix(ADplugin):
def AD_CurrentRun(ADplugin): def AD_CurrentRun(ADplugin):
""" """
returns the curent run specified in the filepath for area detector SavePlugin returns the curent run specified in the filepath for area detector SavePlugin
ADplugin = "29id_ps1:TIFF1:"; $(P)$(SavePlugin) ADplugin = "29id_ps1:TIFF1:"; $(P)$(SavePlugin)
""" """
fpath=caget(ADplugin+"FilePath",as_string=True) fpath=caget(ADplugin+"FilePath",as_string=True)
...@@ -145,6 +159,7 @@ def AD_CurrentRun(ADplugin): ...@@ -145,6 +159,7 @@ def AD_CurrentRun(ADplugin):
def AD_CurrentUser(ADplugin): def AD_CurrentUser(ADplugin):
""" """
returns the curent user specified in the filepath for area detector SavePlugin returns the curent user specified in the filepath for area detector SavePlugin
ADplugin = "29id_ps1:TIFF1:"; $(P)$(SavePlugin) ADplugin = "29id_ps1:TIFF1:"; $(P)$(SavePlugin)
""" """
folder_name = ADplugin.split(":")[1] folder_name = ADplugin.split(":")[1]
...@@ -165,11 +180,11 @@ def AD_DoneSingleSave(ADplugin,**kwargs): ...@@ -165,11 +180,11 @@ def AD_DoneSingleSave(ADplugin,**kwargs):
Acquire -> Done Acquire -> Done
ImageMode -> Single ImageMode -> Single
Save -> Enable Save -> Enable
e.g. ADplugin="29id_ps2:TIFF1:" e.g. ADplugin="29id_ps2:TIFF1:"; only needs ioc with :
**kwargs: **kwargs:
P=first part of ADplugin if not specified P = cam ioc, first part of ADplugin if not specified
R="cam1:"; other AD have "det1:" R = "cam1:"; other AD have "det1:"
""" """
kwargs.setdefault("P",ADplugin.split(":")[0]+":") kwargs.setdefault("P",ADplugin.split(":")[0]+":")
kwargs.setdefault("R","cam1:") kwargs.setdefault("R","cam1:")
...@@ -184,10 +199,9 @@ def AD_FreeRun(ADplugin,**kwargs): ...@@ -184,10 +199,9 @@ def AD_FreeRun(ADplugin,**kwargs):
Acquire -> Done Acquire -> Done
ImageMode -> Single ImageMode -> Single
e.g. ADplugin="29id_ps2:TIFF1:" e.g. ADplugin="29id_ps2:TIFF1:" only needs ioc with :
**kwargs: **kwargs:
P=first part of ADplugin if not specified
R="cam1:"; other AD have "det1:" R="cam1:"; other AD have "det1:"
""" """
kwargs.setdefault("P",ADplugin.split(":")[0]+":") kwargs.setdefault("P",ADplugin.split(":")[0]+":")
...@@ -200,6 +214,9 @@ def AD_FreeRun(ADplugin,**kwargs): ...@@ -200,6 +214,9 @@ def AD_FreeRun(ADplugin,**kwargs):
def AD_Done(ADplugin,**kwargs): def AD_Done(ADplugin,**kwargs):
""" """
sets acquisition to Done sets acquisition to Done
ADplugin="29id_ps2:TIFF1:" only needs ioc with :
**kwargs: **kwargs:
P=first part of ADplugin if not specified P=first part of ADplugin if not specified
R="cam1:"; other AD have "det1:" R="cam1:"; other AD have "det1:"
...@@ -254,21 +271,23 @@ def AD_snap(ADplugin,**kwargs): ...@@ -254,21 +271,23 @@ def AD_snap(ADplugin,**kwargs):
def AD_ScanTrigger(ADplugin,**kwargs): def AD_ScanTrigger(ADplugin,**kwargs):
""" """
Add Triggering of AreaDetector to scanIOC Add Triggering of AreaDetector to scanIOC
ADplugin = "29idc_ps1:TIFF1:" (ADplugin=$(P)$(SavePlugin)) ADplugin = "29idc_ps1:TIFF1:" (ADplugin=$(P)$(SavePlugin))
**kwargs **kwargs
scanIOC = "29id"+BL_ioc() if not specified scanIOC = default is mda_ioc()
scanDIM = 1 scanDIM = 1
P=first part of ADplugin if not specified P=first part of ADplugin if not specified
R="cam1:"; other AD have "det1" R="cam1:"; other AD have "det1"
detTrig = 2; detectorTrigger number detTrig = 2; detectorTrigger number
""" """
kwargs.setdefault("scanIOC",mda_ioc())
kwargs.setdefault("scanDIM",1) kwargs.setdefault("scanDIM",1)
kwargs.setdefault("P",ADplugin.split(":")[0]+":") kwargs.setdefault("P",ADplugin.split(":")[0]+":")
kwargs.setdefault("R","cam1:") kwargs.setdefault("R","cam1:")
kwargs.setdefault("detTrig",2) kwargs.setdefault("detTrig",2)
scanPV=mda_ioc()+"scan"+str(kwargs["scanDIM"]) scanPV = kwargs["scanIOC"]+"scan"+str(kwargs["scanDIM"])
trigger=".T"+str(kwargs["detTrig"])+"PV" trigger=".T"+str(kwargs["detTrig"])+"PV"
caput(scanPV+trigger,kwargs["P"]+kwargs["R"]+"Acquire",wait=True,timeout=5*60) caput(scanPV+trigger,kwargs["P"]+kwargs["R"]+"Acquire",wait=True,timeout=5*60)
...@@ -297,8 +316,11 @@ def ADplugin_ScanSetup(ADplugin, **kwargs): ...@@ -297,8 +316,11 @@ def ADplugin_ScanSetup(ADplugin, **kwargs):
""" """
#from AD_ScanTrigger #from AD_ScanTrigger
kwargs.setdefault("scanIOC",mda_ioc())
kwargs.setdefault("scanDIM",1)
kwargs.setdefault("P",ADplugin.split(":")[0]+":") kwargs.setdefault("P",ADplugin.split(":")[0]+":")
kwargs.setdefault("R","cam1:") kwargs.setdefault("R","cam1:")
kwargs.setdefault('detTrig',2)
AD_DoneSingleSave(ADplugin,**kwargs) AD_DoneSingleSave(ADplugin,**kwargs)
...@@ -306,11 +328,22 @@ def ADplugin_ScanSetup(ADplugin, **kwargs): ...@@ -306,11 +328,22 @@ def ADplugin_ScanSetup(ADplugin, **kwargs):
AD_exposure_time(ADplugin,kwargs["ExposureTime"]) AD_exposure_time(ADplugin,kwargs["ExposureTime"])
AD_SaveFileSetup(ADplugin,**kwargs) AD_SaveFileSetup(ADplugin,**kwargs)
AD_ScanTrigger(ADplugin, **kwargs) AD_ScanTrigger(ADplugin, **kwargs)
trigger = ".T"+str(kwargs["detTrig"])+"PV"
scanPV = mda_ioc()+"scan"+str(kwargs["scanDIM"])
print("WARNING: you need to need to disable saving and clear the trigger by hand after the scan") print("WARNING: you need to need to disable saving and clear the trigger by hand after the scan")
print("\tAD_FreeRun("+ADplugin+"); caput("+scanPV+trigger+",'')") print("\tAD_FreeRun("+ADplugin+"); scan_triggers_clear()")
def AD_attributes_set(ADplugin, filepath):
"""
filepath is the full path to the xml file
filepath = '/xorApps/epics/synApps_6_1/ioc/29idcScienta/iocBoot/ioc29idcScienta/HDF5Attributes.xml'
filepath = '/home/beams/29IDUSER/Documents/User_Macros/Macros_29id/AD_Attributes/DiaGon_Attributes.xml'
"""
current_xml = caget(ADplugin+"NDAttributesFile",as_string=True)
print ('Changed attributes file from ',current_xml)
caput(ADplugin+"NDAttributesFile",filepath)
sleep(1)
print('To: ',caget(ADplugin+"NDAttributesStatus",as_string=True))
def AD_ROI_setup(AD,ROInum,xcenter=500,ycenter=500,xsize=50,ysize=50,binX=1,binY=1): def AD_ROI_setup(AD,ROInum,xcenter=500,ycenter=500,xsize=50,ysize=50,binX=1,binY=1):
""" """
......
...@@ -82,6 +82,8 @@ def ARPES_init(*userName,**kwargs): ...@@ -82,6 +82,8 @@ def ARPES_init(*userName,**kwargs):
user_name = mda_user_name() user_name = mda_user_name()
else: else:
user_name = userName[0] user_name = userName[0]
#if you give a userName then you set the folder to that user
kwargs['set_folders']=True
if user_name == 'staff': if user_name == 'staff':
user_name = 'Staff' user_name = 'Staff'
kwargs['mode'] = 'staff' kwargs['mode'] = 'staff'
...@@ -580,7 +582,7 @@ def _ARPES_DefaultPosition(destination): ...@@ -580,7 +582,7 @@ def _ARPES_DefaultPosition(destination):
DefaultPosition={ DefaultPosition={
'measure':(0.0,0.0,-13.5,0.0,0.0,0.0), 'measure':(0.0,0.0,-13.5,0.0,0.0,0.0),
'LEED':(-0.0, 0.0, -141.5, 89.5, 0.0, 0.0), 'LEED':(-0.0, 0.0, -141.5, 89.5, 0.0, 0.0),
'transfer':(-0,0.0,-141.5,180.0,0.0,0.0), 'transfer':(-2.0,0.0,-141.5,180.0,0.0,0.0),
} }
if destination in DefaultPosition: if destination in DefaultPosition:
pos=DefaultPosition[destination] pos=DefaultPosition[destination]
......
...@@ -88,8 +88,8 @@ def get_all(verbose=True): ...@@ -88,8 +88,8 @@ def get_all(verbose=True):
""" """
vals={} vals={}
vals.update(iex.BL.endstation_get(verbose)) vals.update(iex.BL.endstation_get(verbose))
if 'verbose'==False:
return vals return vals
############################################################################################################## ##############################################################################################################
......
...@@ -413,7 +413,10 @@ def ID_energy_set(keV,verbose=True): ...@@ -413,7 +413,10 @@ def ID_energy_set(keV,verbose=True):
if QP_ratio[1] == None: if QP_ratio[1] == None:
#ID_off() #JM look here #ID_off() #JM look here
#ID_on() #ID_on()
print_warning_message('check QP') if ID_get() > 3.7:
message = 'ID off'
else:
print_warning_message('check QP')
eV = keV*1000.0 eV = keV*1000.0
keV = ID_calc_eV(mono_grating,ID_mode,eV,QP_ratio[0])/1000.0 keV = ID_calc_eV(mono_grating,ID_mode,eV,QP_ratio[0])/1000.0
ID_set(keV,verbose=verbose) ID_set(keV,verbose=verbose)
......
...@@ -38,6 +38,8 @@ from iexcode.instruments.spec_stuff import folders_spec ...@@ -38,6 +38,8 @@ from iexcode.instruments.spec_stuff import folders_spec
default_ioc = '29idKappa:' default_ioc = '29idKappa:'
kth_offset_pv = '29idKappa:userCalcOut1.G' kth_offset_pv = '29idKappa:userCalcOut1.G'
physical_motors = ['x','y','z','tth','kth','kap','kphi']
pseudo_motors = ['th','chi','phi']
############################################################################# #############################################################################
def kappa_init(*userName,**kwargs): def kappa_init(*userName,**kwargs):
""" """
...@@ -66,8 +68,6 @@ def kappa_init(*userName,**kwargs): ...@@ -66,8 +68,6 @@ def kappa_init(*userName,**kwargs):
#motors #motors
physical_motors = ['x','y','z','tth','kth','kap','kphi']
pseudo_motors = ['th','chi','phi']
global kappa_Motors global kappa_Motors
kappa_Motors = Motors('kappa',_kappa_motor_dictionary(),physical_motors,pseudo_motors) kappa_Motors = Motors('kappa',_kappa_motor_dictionary(),physical_motors,pseudo_motors)
...@@ -86,6 +86,8 @@ def kappa_init(*userName,**kwargs): ...@@ -86,6 +86,8 @@ def kappa_init(*userName,**kwargs):
user_name = mda_user_name() user_name = mda_user_name()
else: else:
user_name = userName[0] user_name = userName[0]
#if you give a userName then you set the folder to that user
kwargs['set_folders']=True
if user_name == 'staff': if user_name == 'staff':
user_name = 'Staff' user_name = 'Staff'
kwargs['mode'] = 'staff' kwargs['mode'] = 'staff'
...@@ -99,23 +101,22 @@ def kappa_init(*userName,**kwargs): ...@@ -99,23 +101,22 @@ def kappa_init(*userName,**kwargs):
folders_kappa(user_name,**kwargs) folders_kappa(user_name,**kwargs)
#MPA #MPA
global MPA global mpa
iex.mpa = MPA() mpa = MPA()
MPA=iex.mpa
#global detectors #global detectors
global tth_pv,tthdet global tth_pv,tthdet
tthdet = Kappa_Detector(kappa_Motors) tthdet = Kappa_Detector(kappa_Motors,tth_detector_dictionary())
tth_pv = _kappa_motor_dictionary()['tth'][3] tth_pv = _kappa_motor_dictionary()['tth'][3]
iex.tth = tthdet
#global detectors #global detectors
global tey,d3,d4,mesh global tey,d3,d4,mesh
tey = SRS("29idMZ0:scaler1.S2", '29idd:A1') tey = SRS("29idMZ0:scaler1.S2", '29idd:A1')
d3 = SRS("29idMZ0:scaler1.S3", '29idd:A2') d3 = SRS("29idMZ0:scaler1.S3", '29idd:A2')
d4 = SRS("29idMZ0:scaler1.S4", '29idd:A3') d4 = SRS("29idMZ0:scaler1.S4", '29idd:A3')
mesh = SRS("29idMZ0:scaler1.S14", '29idd:A4') mesh = SRS("29idMZ0:scaler1.S14", '29idd:A4')
tthdet
#logging (logging is dependent on global detectors) #logging (logging is dependent on global detectors)
if kwargs['set_folders']: if kwargs['set_folders']:
...@@ -124,9 +125,6 @@ def kappa_init(*userName,**kwargs): ...@@ -124,9 +125,6 @@ def kappa_init(*userName,**kwargs):
log_init('kappa',user_name,_kappa_log_dictionary,set_file=False) log_init('kappa',user_name,_kappa_log_dictionary,set_file=False)
#default scan settings #default scan settings
kappa_default_scan_settings() kappa_default_scan_settings()
...@@ -143,15 +141,15 @@ def kappa_init(*userName,**kwargs): ...@@ -143,15 +141,15 @@ def kappa_init(*userName,**kwargs):
#stores detecotrs #stores detecotrs
iex.kappa_detectors_dictionary={ kappa_global_detectors = {
'tey':tey, 'tey':tey,
'd3':d3, 'd3':d3,
'd4':d4, 'd4':d4,
'mesh':mesh, 'mesh':mesh,
'tthdet':tthdet 'tthdet':tthdet,
'mpa':mpa,
} }
iex.kappa_detectors_dictionary = kappa_global_detectors
#return any detectors or other parameters that you want access to from jupyter #return any detectors or other parameters that you want access to from jupyter
return tey,d3,d4,mesh,tth_pv,tthdet return tey,d3,d4,mesh,tth_pv,tthdet
...@@ -198,14 +196,20 @@ def kappa_motor_detectors(): ...@@ -198,14 +196,20 @@ def kappa_motor_detectors():
57:"29idKappa:Euler_PhiRBV", 57:"29idKappa:Euler_PhiRBV",
} }
return motors return motors
def tth_detector_dictionary(): def tth_detector_dictionary():
detNums={ """
'tthdet':15, Used by Kappa_det to set detectors
'd3':33, """
'd4':34, detNums = {}
'mpa':30 detNums['tth_detNum']=15
} detNums['d3']="29idMZ0:scaler1.S3" #33
detNums['d4']="29idMZ0:scaler1.S4" #34
detNums['mpa']="29iddMPA:det1:TotalRate_RBV" #30
detNums['apd']=""
detNums['yag']=""
return detNums
def _kappa_detector_dictionary(**kwargs): def _kappa_detector_dictionary(**kwargs):
""" """
...@@ -266,6 +270,7 @@ def _kappa_detector_dictionary(**kwargs): ...@@ -266,6 +270,7 @@ def _kappa_detector_dictionary(**kwargs):
det_dict.update(scalers) det_dict.update(scalers)
det_dict.update(motors) det_dict.update(motors)
det_dict.update(tthdet_detector) det_dict.update(tthdet_detector)
det_dict.update(m3r)
if kwargs['add_vortex']: if kwargs['add_vortex']:
det_dict.update(vortex) det_dict.update(vortex)
if kwargs['add_MPA']: if kwargs['add_MPA']:
...@@ -409,7 +414,7 @@ def kappa_reset(**kwargs): ...@@ -409,7 +414,7 @@ def kappa_reset(**kwargs):
#resetting the MPA ROIs #resetting the MPA ROIs
if kwargs['reset_MPA_ROIs']: if kwargs['reset_MPA_ROIs']:
MPA.mpa_ROI_reset() mpa.mpa_ROI_reset()
#resetting mono and other beamline stuff #resetting mono and other beamline stuff
if BLconfig_xrays(): if BLconfig_xrays():
...@@ -760,6 +765,13 @@ def PI_motors_sync(): ...@@ -760,6 +765,13 @@ def PI_motors_sync():
caput(val_pv,current_rbv) caput(val_pv,current_rbv)
print('PI motors VAL synced to RBV') print('PI motors VAL synced to RBV')
def PI_motor_servo(Enable_Disable='Enable'):
motor_dictionary = _kappa_motor_dictionary()
for motor in _PI_motor_list():
servo_pv = motor_dictionary[motor][3]+'.CNEN'
caput(servo_pv,Enable_Disable)
print('PI motors servos '+Enable_Disable)
def Euler_motors_sync(): def Euler_motors_sync():
""" """
Syncs the Euler motores Syncs the Euler motores
...@@ -962,18 +974,24 @@ def scanth2th_table(tth_table,th_offset, **kwargs): ...@@ -962,18 +974,24 @@ def scanth2th_table(tth_table,th_offset, **kwargs):
############################################################################################################# #############################################################################################################
############################## Preset Positions ############################## ############################## Preset Positions ##############################
############################################################################################################## ##############################################################################################################
def _kappaTransfer_StrSeq(): def _kappaTransfer_StrSeq(**kwargs):
kwargs.setdefault('seq_num',4)
seq_num=kwargs['seq_num']
ioc = mda_ioc()
#User= [ DESC, x, y, z, tth, kth, kap, kphi] #User= [ DESC, x, y, z, tth, kth, kap, kphi]
User = ["kappa Transfer",0, -2650, -650, 0, 57, 0, -88] User = ["kappa Transfer",0, -2650, -650, 0, 57, 0, -88]
n=4 pv,proc = userStringSeq_pvs(ioc, seq_num)
#_kappaPreset_StrSeq(n,User) return proc
def _kappaGrazing_StrSeq(): #Need to determine positions and then add to the kappa graphic def _kappaGrazing_StrSeq(**kwargs): #Need to determine positions and then add to the kappa graphic
kwargs.setdefault('seq_num',3)
seq_num=kwargs['seq_num']
ioc = mda_ioc()
#Dial= [ DESC, x, y, z, tth, kth, kap, kphi] #Dial= [ DESC, x, y, z, tth, kth, kap, kphi]
User = ["kappa Grazing",0, 0, 0, 0, 57.045, 134.76,57.045] User = ["kappa Grazing",0, 0, 0, 0, 57.045, 134.76,57.045]
n=3 pv,proc = userStringSeq_pvs(ioc, seq_num)
#_kappaPreset_StrSeq(n,User) return proc
def kappa_ResetPreset(): def kappa_ResetPreset():
_kappaGrazing_StrSeq() _kappaGrazing_StrSeq()
...@@ -1007,7 +1025,7 @@ def kappa_light(ON_OFF): ...@@ -1007,7 +1025,7 @@ def kappa_light(ON_OFF):
############################################################################################################## ##############################################################################################################
######################## Scan Temp and Pressure ############################## ######################## Scan Temp and Pressure ##############################
############################################################################################################## ##############################################################################################################
def kappa_temperature_pressure_scan(scan_dim=1): def kappa_temperature_pressure_scan(scan_dim=1,**kwargs):
""" """
starts scan to monitor temperature and pressure in the kappa chamber starts scan to monitor temperature and pressure in the kappa chamber
...@@ -1022,7 +1040,8 @@ def kappa_temperature_pressure_scan(scan_dim=1): ...@@ -1022,7 +1040,8 @@ def kappa_temperature_pressure_scan(scan_dim=1):
caput(pv+".D02PV","29idd:tc1:getVal_B.VAL") caput(pv+".D02PV","29idd:tc1:getVal_B.VAL")
caput(pv+".D03PV","29idb:VS11D.VAL") caput(pv+".D03PV","29idb:VS11D.VAL")
#time scan #time scan
iex.BL.mda.time_go() duration_min=10000
scan_time(duration_min,step_min=1,**kwargs)
...@@ -1043,7 +1062,7 @@ def kappa_safe_state(**kwargs): ...@@ -1043,7 +1062,7 @@ def kappa_safe_state(**kwargs):
if kwargs["mpa_off"]: if kwargs["mpa_off"]:
try: try:
MPA.HV_off() mpa.HV_off()
except: except:
print('MPA is not running') print('MPA is not running')
branch = 'd' branch = 'd'
......
...@@ -2,20 +2,14 @@ from time import sleep ...@@ -2,20 +2,14 @@ from time import sleep
from epics import caget, caput from epics import caget, caput
import iexcode.instruments.cfg as iex import iexcode.instruments.cfg as iex
#from iexcode.instruments.Kappa import tth_detector_dictionary from iexcode.instruments.scanRecord import scan_detectors_set
############################################################################################################## ##############################################################################################################
################################ Kappa detector class ############################## ################################ Kappa detector class ##############################
############################################################################################################## ##############################################################################################################
det_set_pv = '29idKappa:det:set' det_set_pv = '29idKappa:det:set'
det_list = ['d3', 'd4', 'mcp', 'apd', 'yag'] det_list = ['d3', 'd4', 'mcp', 'apd', 'yag']
def tth_detectors(name):
detNums={
'd3':33,
'd4':34,
'mpa':30
}
#JM finish here
class Kappa_Detector: class Kappa_Detector:
...@@ -23,9 +17,11 @@ class Kappa_Detector: ...@@ -23,9 +17,11 @@ class Kappa_Detector:
class for Kappa detector class for Kappa detector
""" """
def __init__(self,kappa_Motors): def __init__(self,kappa_Motors,tth_detector_dictionary):
self.motors = kappa_Motors self.motors = kappa_Motors
self.detector_dictionary = tth_detector_dictionary
self.get() self.get()
def get(self): def get(self):
""" """
...@@ -59,6 +55,16 @@ class Kappa_Detector: ...@@ -59,6 +55,16 @@ class Kappa_Detector:
caput(det_set_pv,det_name) caput(det_set_pv,det_name)
if move: if move:
self.motors.move('tth',tth_val,wait=True,verbose=False) self.motors.move('tth',tth_val,wait=True,verbose=False)
#replace det: 15 with SRS for current detector
tth_detNum = self.detector_dictionary['tth_detNum']
det_pv = self.detector_dictionary[self.name]
try:
scan_detectors_set(detector_dictionary={tth_detNum:det_pv})
except:
scan_detectors_set(detector_dictionary={tth_detNum:""})
print_warning("default tth_detNum("+str(tth_detNum)+") not set")
sleep(2)
def tth0_set(self): def tth0_set(self):
""" """
......
...@@ -10,17 +10,182 @@ from epics import caget, caput ...@@ -10,17 +10,182 @@ from epics import caget, caput
from iexcode.instruments.IEX_BL_config import * from iexcode.instruments.IEX_BL_config import *
from iexcode.instruments.utilities import read_dict from iexcode.instruments.utilities import read_dict
def Lakeshore_reset(pv,d): class Lakeshore_335:
""" """
resets the lake short to the default paramters defind in the dictionary d Lakeshore 355 data class
""" """
for key in d.keys(): def __init__(self,ioc,**kwargs):
caput(pv+key,d[key]) """
ioc = "29idARPES:"
**kwargs
Q = "TC1:"
defaults => dictionary of default parameter used by reset
"""
kwargs.setdefault('Q','TC1:')
self.pv = ioc+"LS335:"+kwargs['Q']
self.reset(**kwargs)
self.get()
pass
def reset(self,**kwargs):
"""
resets the lake short to the default paramters defind in the dictionary defaults
**kwargs
defaults = {"read.SCAN":".5 second","OUT1:Cntrl":"A","OUT2:Cntrl":"B","OUT1:Mode":"Closed Loop"}
"""
kwargs.setdefault("defaults",{"read.SCAN":".5 second","OUT1:Cntrl":"A",
"OUT2:Cntrl":"B","OUT1:Mode":"Closed Loop","P1":1,"I1":5,"D1":1,"RampR1":5,"OnRamp1":"ON"})
d=kwargs['defaults']
for key in d.keys():
caput(self.pv+key,d[key])
def heater_range_list(self):
return ["off","low","medium","high"]
def pv_dictionary(self):
d={
"INA":None,
"INB":None,
"IN1":None,
"IN2":None,
"IN1:Name_RBV":"",
"IN2:Name_RBV":"",
"OUT1:SP":None,
"OUT1:SP_RBV":None,
"HTR1":None,
"HTR1:Range":"",
"HTR1:Range_RBV":"",
"OUT1:Cntrl_RBV":"",
"P1":None,
"P1_RBV":None,
"I1":None,
"I1_RBV":None,
"D1":None,
"D1_RBV":None,
"RampR1":None,
"RampR1_RBV":None,
"OnRamp1":"",
"OnRamp1_RBV":"",
}
def get(self):
"""gets the current valuse
"""
d = self.pv_dictionary()
caput(self.pv+"read.PROC",1)
sleep(1)
caput(self.pv+"read.PROC",0)
for key in d.keys():
if d[key] != None:
caget(self.pv+key,as_string=True)
else:
caget(self.pv+key)
return d
def set(self,TA_sp,bandwidth=5,seconds=5*60,heater_range=None,out_num=1):
"""
TA_SP = temperature set point
bandwidth = the temperature range acceptable
seconds = time to wait for stablized
heater_range = "off","low","medium","high"
= None then uses current setting
out_num = control loop number (1 or 2)
"""
d = self.pv_dictionary
TA = caget(self.pv+"INA")
while True:
#sepoint with +/- current temperature
if TA - bandwidth <= TA_sp > TA + bandwidth:
#regulate off sample
self.regulate_TA(TA_sp,heater_range,out_num)
if self.TA_stable(TA_sp,bandwidth,seconds) == True:
break
else:
self.regulate_TB(TA_sp,heater_range,out_num)
caget()
def TA_stable(self,T_sp,bandwidth=5,seconds=5*60,out_num=1):
"""
returns True or False is the temperature is with in the bandwidth over a given
time interval in seconds
T_sp = temperature set point
bandwidth = +/- Temperature to be stablized
seconds = time to wait to stablize
out_num = control loop number (1 or 2)
"""
read_interval = 0.5
name_rbv = caget(self.pv+"IN"+str(out_num)+":Name_RBV", as_string=True)
for t in range(0,seconds/read_interval): #sampling every 0.5 seconds
T = caget(self.pv+"IN"+str(out_num))
if T - bandwidth <= T_sp > T + bandwidth:
return False
else:
sleep(read_interval)
return True
def regulate_TA(self,T_sp,heater_range=None,out_num=1):
"""
"""
self.Cntrl(1,'A')
self.Cntrl(2,'B')
sleep(0.5)
self.set_point(1,T_sp,heater_range)
self.set_point(2,0,heater_range='off')
def regulate_TB(self,T_sp,heater_range=None,out_num=1):
self.Cntrl(1,'B')
self.Cntrl(2,'A')
sleep(0.5)
self.set_point(1,T_sp,heater_range)
self.set_point(2,0,heater_range='off')
def Cntrl(self,out_num,sensor):
"""
out_num = control loop number (1 or 2)
sensor = 'A' or 'B'
"""
caput(self.pv+"OUT"+str(out_num)+":Cntrl",sensor)
sleep(.5)
def set_point(self,out_num,T_sp,heater_range=None):
caput(self.pv+"OUT"+str(out_num)+":SP")
self.set_heater_range(out_num,heater_range)
def set_heater_range(self,out_num,heater_range):
"""
sets the heater range
out_num = control loop number (1 or 2)
"""
if heater_range == None:
heater_range = caget(self.pv+"OUT"+str(out_num)+"HTR1:Range_RBV",as_string=True)
else:
heater_range = heater_range.upper()
if heater_range not in self.heater_range_list():
message = "heater_range = "+heater_range+" not a valid choice"
message += "\nchoose one of "+str(self.heater_range_list)
print_warning_message(message)
return
else:
caput(self.pv+"OUT"+str(out_num)+"HTR1:Range",heater_range)
sleep(.5)
return caget(self.pv+"OUT"+str(out_num)+"HTR1:Range_RBV",as_string=True)
############################################################################################################# #############################################################################################################
############################## Lakeshore 335 Diode Curves ############################## ############################## Lakeshore 335 Diode Curves ##############################
############################################################################################################## #############################################################################################################
#---Settings as of 12/04/2018--- #---Settings as of 12/04/2018---
#DiodeCurve_Write(22,"SI435") #DiodeCurve_Write(22,"SI435")
#DiodeCurve_SetInput("A",22,400) #DiodeCurve_SetInput("A",22,400)
...@@ -145,7 +310,7 @@ def DiodeCurve_SetInput(Channel,Curve,Tmax): ...@@ -145,7 +310,7 @@ def DiodeCurve_SetInput(Channel,Curve,Tmax):
caput(PV,cmd,wait=True,timeout=1800) caput(PV,cmd,wait=True,timeout=1800)
############################################################################################################## ##############################################################################################################
############################## PID Settings ############################## ############################## PID Settings for open cycle ##############################
############################################################################################################## ##############################################################################################################
...@@ -159,157 +324,7 @@ def DiodeCurve_SetInput(Channel,Curve,Tmax): ...@@ -159,157 +324,7 @@ def DiodeCurve_SetInput(Channel,Curve,Tmax):
#Lakeshore 355 I = time in seconds for one oscilation / 1000; D=50-100 for starters #Lakeshore 355 I = time in seconds for one oscilation / 1000; D=50-100 for starters
def PID_dict(which,T): #Dictionary of PID setting to try for the ARPES chamber
"""Dictionary for common PID setting for the ARPES system.
Since the PID is dependent on the cooling power, this will change with the cryogen and the flow rate:
- Flow = "LHe,LN" => LHe = needle valve = "on" and flow = 70
"""
PID={}
# PID[which,T]=[P,I,D,Range] Range=HIGH,MEDIUM,LOW,OFF
PID['RT', 378.0]=[200.0,0.0,0.0,'MEDIUM']
PID['RT', 375.0]=[200.0,0.0,0.0,'MEDIUM']
PID['RT', 338.0]=[100.0,0.0,0.0,'MEDIUM']
PID['RT', 298.0]=[20.0,0.0,0.0,'LOW']
PID['GHe', 378.0]=[210.0,0.0,0.0,'MEDIUM']
PID['GHe', 375.0]=[210.0,0.0,0.0,'MEDIUM']
PID['GHe', 338.0]=[130.0,0.0,0.0,'MEDIUM']
PID['GHe', 298.0]=[60.0,0.0,0.0,'MEDIUM']
PID['GHe', 250.0]=[10.0,0.0,0.0,'LOW']
PID['LHe',298.0]=[20.0,5.0,1.0,'HIGH'] # +/- 1.1 deg, over 10 min, heater power 53%
PID['LHe',200.0]=[10.0,5.0,1.0,'HIGH'] # +/- 1.1 deg, over 10 min, heater power 53%
PID['LHe',150.0]=[200.0,0.1,0,'HIGH'] # Stablized at 153, heater power 43%
PID['LHe',180.0]=[200.0,0.1,0,'HIGH']
PID['LHe',230.0]=[200.0,0.1,0,'HIGH']
PID['LHe',300.0]=[200.0,0.1,0,'HIGH']
PID['LHe',40.0]=[200.0,0.1,0,'HIGH'] #
PID['LN2',230]=[10.0,0.6,100,'HIGH'] #stable 237.83, needle valve=ON; flow 6 half turns from max)
PID['LN2',180]=[50.0,4,100,'MEDIUM']
return PID[which,T]
def PID_set(which,T,heater='ON'):
"""
Uses preset PID settings as defined in PID_dict()
To cool down: heater='OFF'
"""
P,I,D,Range=PID_dict(which,T)
caput("29idARPES:LS335:TC1:P1",P)
caput("29idARPES:LS335:TC1:I1",I)
caput("29idARPES:LS335:TC1:D1",D)
if heater == 'ON':
caput("29idARPES:LS335:TC1:HTR1:Range",Range)
elif heater == 'OFF':
caput("29idARPES:LS335:TC1:HTR1:Range",'OFF')
print('\nP = ',PID_dict(which,T)[0])
print('I = ',PID_dict(which,T)[1])
print('D = ',PID_dict(which,T)[2])
print('Range = ',PID_dict(which,T)[3])
def SetT_Sample(which,T,precision=5,minutes=15,offset=6):
"""
Sets PID settings for a given set point as defined in PID_dict().
Available set points:
which = 'RT' : T = 298, 338, 375
which = 'LHe': T = 150, 200
which = 'GHe': T = 250, 298, 338, 370
which = 'LN2': T = 230, 180
precision is temperature in K
"""
current_T=caget("29idARPES:LS335:TC1:IN1")
print('\nSet T to '+ str(T)+' K @ '+ dateandtime())
if T>current_T:
PID_set(which,T,'ON')
Range=PID_dict(which,T)[3]
SetT_Up(T,offset,Range,precision,minutes)
else:
PID_set(which,T,'OFF')
Range=PID_dict(which,T)[3]
SetT_Down(T,offset,Range,precision,minutes)
caput("29idARPES:LS335:TC1:OUT1:SP",T)
def SetT_Up(T,offset,Range,precision=5,minutes=15):
if Range=='LOW': Range=1
if Range=='MEDIUM': Range=2
if Range=='HIGH': Range=3
t=15
u=0
caput('29idARPES:LS335:TC1:OUT1:SP',T) # set the set point to T
while True: # while TA < T
TA=caget('29idARPES:LS335:TC1:IN1') # get current temperature at the sample
TB=caget('29idARPES:LS335:TC1:IN2') # get current temperature (B=cold finger)
if TA<T-precision: # if it hasn't reach SP
caput("29idARPES:LS335:TC1:HTR1:Range",min(Range,3)) # increase heater range to Range +1
while True: # while TB < T+offset:
TB=caget('29idARPES:LS335:TC1:IN2') # get current temperature at the cold finger
if (t%120)==0:
print('\nTA = ',TA,' TB = ',TB, ' @ ',dateandtime())
if TB<(T+offset) and t<=minutes*60: #if it hasn't reach the SP+offser
sleep(15)
t+=15
#print t, TA, TB
elif TB<(T+offset) and t>minutes*60:
heater_power=caget('29idARPES:LS335:TC1:HTR1')
heater_range=caget('29idARPES:LS335:TC1:HTR1:Range')
if heater_power > 90:
caput("29idARPES:LS335:TC1:HTR1:Range",min(heater_range+1,3))
print('Change Range to',caget('29idARPES:LS335:TC1:HTR1:Range'),' @ ',dateandtime())
elif heater_range==3 or heater_power<=90:
P=caget("29idARPES:LS335:TC1:P1")
caput("29idARPES:LS335:TC1:P1",P*1.5)
print('Change P to',caget("29idARPES:LS335:TC1:P1"),' @ ',dateandtime())
t=0
else: #else
break # break
caput("29idARPES:LS335:TC1:HTR1:Range",'OFF') # turn off the heater
elif TA>T-precision: # if it has reach the set point
break # break
print('TA = ',TA,' TB = ',TB, ' @ ',dateandtime()) # print temperatures
caput("29idARPES:LS335:TC1:HTR1:Range",Range) # set the heater range to preset value
def SetT_Down(T,offset,Range,precision=5,minutes=15):
t=0
caput('29idARPES:LS335:TC1:OUT1:SP',T) # set the set point to T
while True: # while TA < T
TA=caget('29idARPES:LS335:TC1:IN1')
TB=caget('29idARPES:LS335:TC1:IN2')
if (t%120)==0:
print('\nTA = ',TA,' TB = ',TB, ' @ ',dateandtime())
if TA>T+precision:
sleep(15)
t+=15
elif t>minutes*60:
P=caget("29idARPES:LS335:TC1:P1")
caput("29idARPES:LS335:TC1:P1",P/1.5)
t=0
else:
break
caput("29idARPES:LS335:TC1:HTR1:Range",Range)
print('TA = ',TA,' TB = ',TB, ' @ ',dateandtime())
def Get_PID(which='LHe'):
T=caget("29idARPES:LS335:TC1:IN1")
SP=caget("29idARPES:LS335:TC1:OUT1:SP")
P=caget("29idARPES:LS335:TC1:P1")
I=caget("29idARPES:LS335:TC1:I1")
D=caget("29idARPES:LS335:TC1:D1")
Range=caget("29idARPES:LS335:TC1:HTR1:Range",as_string=True)
# print SP,P,I,D,Range
print("Current T:", T,'K')
print("PID[\'"+which+"\',"+str(SP)+"]=["+str(P)+","+str(I)+","+str(D)+",\'"+Range+"\']")
#functions use from ScanFunctions_IEX import BL_ioc
def PVLakeshores(which): def PVLakeshores(which):
""" """
which = RSXS / ARPES /Hydra / DetPool which = RSXS / ARPES /Hydra / DetPool
...@@ -324,98 +339,5 @@ def PVLakeshores(which): ...@@ -324,98 +339,5 @@ def PVLakeshores(which):
} }
return d[which] return d[which]
def dateandtime():
return strftime("%a %d %b %Y %H:%M:%S",localtime())
def tempr(which=None):
"""
reads the temperature in the current branch unless otherwise specificed
"""
if which == None:
which=BL_ioc()
PVs=PVLakeshores(which)
sample=PVs[0]+PVs[1]
print(which+" Sample Temperature: {} K".format(caget(sample)))
def temps(tempset,which=None):
"""
Set sthe sample temperature set point and waits for it to stablelize for the current branch
unless specified by which = Kappa / ARPES /Hydra set by PVLakeshores
"""
if which == None:
which=BL_ioc()
P, Sample, ColdFinger, SetPoint = PVLakeshores(which)
print("Initial Sample Temperature:",caget(P+Sample)," K",dateandtime())
caput(P+SetPoint,1.0*tempset)
stop_var=0
b=0
sleep(0)
while b == 0:
delta=abs(caget(P+Sample)-1.0*tempset)
if abs(delta) < 1:
c=0
while c < 10:
sleep(1)
delta=delta+(caget(P+Sample)-1.0*tempset)
c=c+1
if abs(delta/10) < 1:
print("Stable Sample Temperature:",caget(P+Sample)," K",dateandtime())
b=1
else:
temp1=caget(P+Sample)
sleep(10)
temp2=caget(P+Sample)
if abs(temp1-temp2) < 0.1:
sleep(30)
temp2=caget(P+Sample)
if abs(temp1-temp2) < .5:
print("UNABLE TO STABLIZE TEMPERATURE! Stopped at T=:",caget(P+Sample)," K",dateandtime())
b=1
def ARPES_warming(Tmax,PowerMax=50,Tdiff=10):
"""
Ramps the temperature up for ARPES using open loop and manual power at PowerMax with
the heater on High until Tmax - Tdif is reached and then switches to
closed loop with the heater on Medium
PowerMax=50,Tdiff=10
PowerMax=55,Tdiff=25
"""
P="29idARPES:LS335:TC1:"
#Needs modified in controller changed
Tsample=P+"IN1"
Tcontrol=P+"IN2"
Tsetpoint=P+"OUT1:SP"
HeaterRange=P+"HTR1:Range"
ControlMode=P+"OUT1:Mode"
ManualPower=P+"OUT1:MOUT"
caput(Tsetpoint,Tmax)
caput(ManualPower,PowerMax)
caput(ControlMode,"Open Loop")
caput(HeaterRange,'HIGH')
print("T", caget(Tsample))
print("Started warming:", dateandtime())
while True:
TA=caget(Tsample)
TB=caget(Tsample)
if TB >= Tmax:
print ("Control is to high",TB)
break
if TA < Tmax - Tdiff:
sleep(60)
else:
break
print("T", caget(Tsample))
print("Switch to closed loop", dateandtime())
caput(HeaterRange,'MEDIUM');sleep(1)
caput(ControlMode,"Closed Loop");sleep(1)
caput(HeaterRange,'OFF');sleep(1)
caput(HeaterRange,'MEDIUM');sleep(1)
temps(Tmax,which='ARPES')
...@@ -264,6 +264,12 @@ class Motors: ...@@ -264,6 +264,12 @@ class Motors:
kwargs.setdefault('cts',0.1) kwargs.setdefault('cts',0.1)
kwargs.setdefault('mpa',False) kwargs.setdefault('mpa',False)
if kwargs['debug']:
print('kwargs:', kwargs)
print('inner_loop_list = ',inner_loop_list)
print('outer_loop_list = ',outer_loop_list)
rbv_pv,val_pv,sgm_pv,pv = self._motor_dictionary[inner_loop_list[0]] rbv_pv,val_pv,sgm_pv,pv = self._motor_dictionary[inner_loop_list[0]]
inner_loop_list.pop(0) inner_loop_list.pop(0)
inner_loop_list.insert(0,rbv_pv) inner_loop_list.insert(0,rbv_pv)
......
...@@ -80,6 +80,8 @@ def Octupole_init(*userName,**kwargs): ...@@ -80,6 +80,8 @@ def Octupole_init(*userName,**kwargs):
user_name = mda_user_name() user_name = mda_user_name()
else: else:
user_name = userName[0] user_name = userName[0]
#if you give a userName then you set the folder to that user
kwargs['set_folders']=True
if user_name == 'staff': if user_name == 'staff':
user_name = 'Staff' user_name = 'Staff'
kwargs['mode'] = 'staff' kwargs['mode'] = 'staff'
......
...@@ -436,13 +436,23 @@ class Scienta: ...@@ -436,13 +436,23 @@ class Scienta:
caput(self.PHV+"sweepStopEnergy.VAL",KEstop);time.sleep(0.25) #added 20220317 - sweep calcs need time to process or you get weird stuff caput(self.PHV+"sweepStopEnergy.VAL",KEstop);time.sleep(0.25) #added 20220317 - sweep calcs need time to process or you get weird stuff
caput(self.PHV+"sweepStepEnergy.VAL",KEstep) caput(self.PHV+"sweepStepEnergy.VAL",KEstep)
time.sleep(1) time.sleep(1)
#Re-Calc
#print('Yes Re-Calc')
#caput(self.PHV+"SweepReCalc.PROC",1)
#time.sleep(1)
#Load spectra parameters #Load spectra parameters
caput(self.PHV+"SweepLoadFanout.PROC",1) caput(self.PHV+"SweepLoadFanout.PROC",1)
time.sleep(1) time.sleep(1)
#check that there are no zeros in the KE_array
KE_array = caget(self.PHV+"KE_array")
if np.min(KE_array)<1:
print("KE_array had zeros")
caput(self.PHV+"SweepReCalc.PROC",1)
time.sleep(2)
caput(self.PHV+"SweepLoadFanout.PROC",1)
time.sleep(1)
if len(KE_array) != caget(self.PHV+"scan2.NPTS"):
print("number of scan point and KE_array miss match")
caput(self.PHV+"SweepReCalc.PROC",1)
time.sleep(2)
caput(self.PHV+"SweepLoadFanout.PROC",1)
time.sleep(1)
def _spectra_BabySwept(self, KEcenter): def _spectra_BabySwept(self, KEcenter):
...@@ -520,6 +530,9 @@ class Scienta: ...@@ -520,6 +530,9 @@ class Scienta:
# writing scan parameters # writing scan parameters
else: else:
#put the analzer at inital value so calcuations are correct
self.put(KElist[0],PassEnergy,"Angular")
time.sleep(2)
if len(EAlist)==7: #Swept Mode if len(EAlist)==7: #Swept Mode
scanType="Sweep" scanType="Sweep"
self._spectra_Swept(KElist[0],KElist[1],KElist[2],PassEnergy) self._spectra_Swept(KElist[0],KElist[1],KElist[2],PassEnergy)
......
...@@ -225,14 +225,15 @@ def mono_energy_set(hv_eV,verbose=True): ...@@ -225,14 +225,15 @@ def mono_energy_set(hv_eV,verbose=True):
caput(pv,hv_eV,wait=True,timeout=60) caput(pv,hv_eV,wait=True,timeout=60)
time.sleep(2.5) time.sleep(2.5)
mono_status = mono_status_get()
while True: while True:
if mono_status > 1: if mono_status_get() > 1:
mono_resest_pitch() mono_resest_pitch()
caput(pv,hv_eV,wait=True,timeout=60) caput(pv,hv_eV,wait=True,timeout=60)
time.sleep(2.5) time.sleep(2.5)
else: else:
break break
if verbose: if verbose:
print("Mono set to",str(round(hv_eV,3)),"eV") print("Mono set to",str(round(hv_eV,3)),"eV")
...@@ -247,8 +248,9 @@ def mono_scan_pvs(): ...@@ -247,8 +248,9 @@ def mono_scan_pvs():
def mono_status_get(): def mono_status_get():
""" """
returns the status of the mirror (GRT * MIR) returns the status of the mirror (GRT * MIR)
1 = ready 1 = positioned/ready
2 = moving 0 = somebody moving
1 > somebody not happy
Previously Mono_Status Previously Mono_Status
...@@ -256,8 +258,8 @@ def mono_status_get(): ...@@ -256,8 +258,8 @@ def mono_status_get():
pvs = _mono_pvs() pvs = _mono_pvs()
mir_P_status = int(caget(pvs['mir_P_status'])) mir_P_status = int(caget(pvs['mir_P_status']))
grt_P_status = int(caget(pvs['grt_P_status'])) grt_P_status = int(caget(pvs['grt_P_status']))
mir_X_status = int(caget(pvs['mir_P_status'])) mir_X_status = int(caget(pvs['mir_X_status']))
grt_X_status = int(caget(pvs['grt_P_status'])) grt_X_status = int(caget(pvs['grt_X_status']))
mirror_status = mir_P_status * mir_X_status mirror_status = mir_P_status * mir_X_status
grating_status = grt_P_status * grt_X_status grating_status = grt_P_status * grt_X_status
return mirror_status*grating_status return mirror_status*grating_status
...@@ -315,13 +317,15 @@ def _mono_optic_change(optic,name, verbose=True): ...@@ -315,13 +317,15 @@ def _mono_optic_change(optic,name, verbose=True):
if type_get != name: if type_get != name:
caput(type_sp,num,wait=True,timeout=18000) caput(type_sp,num,wait=True,timeout=18000)
caput(type_move,1,wait=True,timeout=18000) caput(type_move,1,wait=True,timeout=18000)
time.sleep(1) #needed
while True: while True:
if mono_status_get() > 1: if mono_status_get() != 1:
time.sleep(5) time.sleep(5)
else: else:
break break
time.sleep(1)
mono_energy_set(hv_eV) mono_energy_set(hv_eV)
time.sleep(1)
else: else:
if verbose: if verbose:
......
...@@ -32,7 +32,7 @@ class Vortex: ...@@ -32,7 +32,7 @@ class Vortex:
#set hi and low #set hi and low
caput(self._vortex_pv+'mca1.R0LO',round(center-width/2)) caput(self._vortex_pv+'mca1.R0LO',round(center-width/2))
caput(self._vortex_pv+'mca1.R0HI',round(center-width/2)) caput(self._vortex_pv+'mca1.R0HI',round(center+width/2))
#pv to store energy set point #pv to store energy set point
caput(self._calc_pv,energy) caput(self._calc_pv,energy)
......
...@@ -3,5 +3,4 @@ BL=None ...@@ -3,5 +3,4 @@ BL=None
#Kappa global stuff #Kappa global stuff
mpa=None mpa=None
det=None
kappa_detectors_dictionary={} kappa_detectors_dictionary={}
\ No newline at end of file
...@@ -686,15 +686,16 @@ def scanEA_motor(EAlist, motor,start,stop,step,mode='absolute',**kwargs): ...@@ -686,15 +686,16 @@ def scanEA_motor(EAlist, motor,start,stop,step,mode='absolute',**kwargs):
EAparms=scanEA(EAlist,**EAkwargs) EAparms=scanEA(EAlist,**EAkwargs)
#Setting up the ScanRecord for motor scans #Setting up the ScanRecord for motor scans
execute = kwargs['execute']
kwargs.update({'execute':False})
scan_dim=2 #hard coded scan_dim=2 #hard coded
kwargs.update({'scan_dim':scan_dim}) kwargs.update({'scan_dim':scan_dim})
EA.Motors.scan(motor,start,stop,step,**kwargs) EA.Motors.scan(motor,start,stop,step,**kwargs)
if kwargs['debug']: if kwargs['debug']:
print("ScanGo scan_dim = ",scan_dim) print("ScanGo scan_dim = ",scan_dim)
if kwargs["execute"]==True: if execute == True:
#Scanning #Scanning
EA.put(EAlist[1],EAparms['PassEnergy'],LensMode="Angular",Frames=EAparms['Frames'],**kwargs) EA.put(EAlist[1],EAparms['PassEnergy'],LensMode="Angular",Frames=EAparms['Frames'],**kwargs)
scan_go(**kwargs) scan_go(**kwargs)
...@@ -724,6 +725,7 @@ def scanEA_map_sample(EAlist,y_list,z_list,**kwargs): ...@@ -724,6 +725,7 @@ def scanEA_map_sample(EAlist,y_list,z_list,**kwargs):
""" """
kwargs.setdefault("execute",True) kwargs.setdefault("execute",True)
kwargs.setdefault("debug",False) kwargs.setdefault("debug",False)
kwargs.setdefault('outer_scan_dim',3)
#setting up EA #setting up EA
EAkwargs={ EAkwargs={
...@@ -733,18 +735,18 @@ def scanEA_map_sample(EAlist,y_list,z_list,**kwargs): ...@@ -733,18 +735,18 @@ def scanEA_map_sample(EAlist,y_list,z_list,**kwargs):
EAparms=scanEA(EAlist,**EAkwargs) EAparms=scanEA(EAlist,**EAkwargs)
#Setting up the ScanRecord for motor scans #Setting up the ScanRecord for motor scans
outer_scan_dim=3 #hard coded execute = kwargs['execute']
inner_loop_list = y_list.insert(0,"y") kwargs.update({'execute':False})
outer_loop_list = z_list.insert(0,"z")
EA.Motors.scan_2D(inner_loop_list,outer_loop_list,outer_scan_dim,**kwargs) EA.Motors.scan_2D(['y',y_list[0],y_list[1],y_list[2]],['z',z_list[0],z_list[1],z_list[2]],**kwargs)
if kwargs['debug']: if kwargs['debug']:
print("ScanGo scan_dim = ",outer_scan_dim) print("ScanGo scan_dim = ",kwargs['outer_scan_dim'])
if kwargs['execute']: if execute:
#Scanning #Scanning
EA.put(EAlist[1],EAparms['PassEnergy'],LensMode="Angular",Frames=EAparms['Frames'],**kwargs) EA.put(EAlist[1],EAparms['PassEnergy'],LensMode="Angular",Frames=EAparms['Frames'],**kwargs)
scan_go(scan_dim=outer_scan_dim) scan_go(scan_dim=kwargs['outer_scan_dim'])
EAlog_update() EAlog_update()
#After scan #After scan
......
...@@ -146,24 +146,25 @@ def m3r_align(target_pixel=None, precision=0.5, num_tries=10, verbose=True,debug ...@@ -146,24 +146,25 @@ def m3r_align(target_pixel=None, precision=0.5, num_tries=10, verbose=True,debug
if target_pixel == None: if target_pixel == None:
target_pixel = caget( m3r_align_pv_dictionary()['desired_pixel']) target_pixel = caget( m3r_align_pv_dictionary()['desired_pixel'])
if iex.BL.branch =='d': if hasattr(iex.BL, 'branch'):
# coarse aligment if iex.BL.branch =='d':
pixel_delta = m3r_align_stats_centroid_posx()-target_pixel # coarse aligment
m3r_align_move_pitch_piezo(pixel_delta)
try_num = 1
while True:
pixel_delta = m3r_align_stats_centroid_posx()-target_pixel pixel_delta = m3r_align_stats_centroid_posx()-target_pixel
if debug: m3r_align_move_pitch_piezo(pixel_delta)
print(try_num,pixel_delta) try_num = 1
if abs(pixel_delta) <= precision: while True:
break pixel_delta = m3r_align_stats_centroid_posx()-target_pixel
elif try_num > num_tries:
break
else:
#fine alignment
if debug: if debug:
print('Fine align') print(try_num,pixel_delta)
m3r_align_move_pitch_piezo(pixel_delta) if abs(pixel_delta) <= precision:
break
elif try_num > num_tries:
break
else:
#fine alignment
if debug:
print('Fine align')
m3r_align_move_pitch_piezo(pixel_delta)
if verbose: if verbose:
......
...@@ -56,13 +56,27 @@ def scan_positioner_after_set(**kwargs): ...@@ -56,13 +56,27 @@ def scan_positioner_after_set(**kwargs):
def scan_positioner_settling_time_set(**kwargs): def scan_positioner_settling_time_set(**kwargs):
iex.BL.mda.positioner_settling_time_set(**kwargs) iex.BL.mda.positioner_settling_time_set(**kwargs)
def scan_triggers_set(**kwargs): def scan_triggers_set(reset=False,**kwargs):
iex.BL.mda.triggers_set(**kwargs) """
sets the trigger1 to be the lower dim execute, does not change the other triggers
does nothing if scan_dim = 1
**kwargs:
scan_dim: 1 (default)
"""
iex.BL.mda.triggers_set(reset,**kwargs)
def scan_triggers_clear(**kwargs): def scan_triggers_clear(**kwargs):
"""
Clears all scan detectors triggers
**kwargs:
scan_dim: 1 (default)
"""
iex.BL.mda.triggers_clear(**kwargs) iex.BL.mda.triggers_clear(**kwargs)
def scan_detectors_set(**kwargs): def scan_detectors_set(**kwargs):
"""
detector_dictionary = {num:pv} #of detectors to change
"""
iex.BL.mda.detectors_set(**kwargs) iex.BL.mda.detectors_set(**kwargs)
def scan_reset_all(**kwargs): def scan_reset_all(**kwargs):
...@@ -516,7 +530,7 @@ class ScanRecord: ...@@ -516,7 +530,7 @@ class ScanRecord:
#detector triggers #detector triggers
self.triggers_clear(**kwargs) self.triggers_clear(**kwargs)
self.triggers_set(**kwargs) self.triggers_set(reset=True,**kwargs)
self.before_scan_set(**kwargs) self.before_scan_set(**kwargs)
self.after_scan_set(**kwargs) self.after_scan_set(**kwargs)
...@@ -781,7 +795,7 @@ class ScanRecord: ...@@ -781,7 +795,7 @@ class ScanRecord:
Clear all scan detectors triggers Clear all scan detectors triggers
**kwargs: **kwargs:
scan_dim: 1 (default) scan_dim: 1 (default)
verbose: Falase (default) verbose: False (default)
Previously: Clear_Scan_Triggers Previously: Clear_Scan_Triggers
""" """
...@@ -790,8 +804,15 @@ class ScanRecord: ...@@ -790,8 +804,15 @@ class ScanRecord:
scan_pv = self.ioc+"scan"+str(kwargs['scan_dim']) scan_pv = self.ioc+"scan"+str(kwargs['scan_dim'])
for trig_num in range(1,5): #clear trigger 2-4
caput(scan_pv+'.T'+str(trig_num)+'PV',"") for trig_num in range(2,5):
caput(scan_pv+'.T'+str(trig_num)+'PV',"")
#set trigger 1
if kwargs['scan_dim']==1:
caput(scan_pv+'.T'+str(trig_num)+'PV',"")
else:
scan_trigger = self.ioc+"scan"+str(kwargs['scan_dim']-1) + ".EXSC"
caput(scan_pv+'.T'+str(trig_num)+'PV',scan_trigger)
def triggers_get(self,**kwargs): def triggers_get(self,**kwargs):
""" """
...@@ -805,31 +826,28 @@ class ScanRecord: ...@@ -805,31 +826,28 @@ class ScanRecord:
for tigger_num in range(1,5): for tigger_num in range(1,5):
scan_trigger.update({tigger_num:caget(scan_pv+".T"+str(tigger_num)+"PV")}) scan_trigger.update({tigger_num:caget(scan_pv+".T"+str(tigger_num)+"PV")})
def triggers_set(self,**kwargs): def triggers_set(self,reset=False,**kwargs):
""" """
sets the trigger1 to be the lower dim execute, does not change the other triggers sets the trigger1 to be the lower dim execute, does not change the other triggers
does nothing if scan_dim = 1 does nothing if scan_dim = None
**kwargs: **kwargs:
scan_dim: 1 (default) scan_dim: 1 (default)
verbose: False (default) verbose: False (default)
""" """
kwargs.setdefault('scan_dim',1)
kwargs.setdefault('trigger_dictionary',self.trigger_dictionary)
kwargs.setdefault('verbose',False) kwargs.setdefault('verbose',False)
kwargs.setdefault('scan_dim',1)
scan_pv = self.ioc+"scan"+str(kwargs['scan_dim']) scan_pv = self.ioc+"scan"+str(kwargs['scan_dim'])
#clear all triggers for scan_dim
self.triggers_clear(**kwargs)
#reset scan_dim trigger
inner_scan_trigger = self.ioc+"scan"+str(kwargs['scan_dim']-1)+".EXSC" inner_scan_trigger = self.ioc+"scan"+str(kwargs['scan_dim']-1)+".EXSC"
if kwargs['scan_dim'] > 1: if reset:
caput(scan_pv+".T1PV",inner_scan_trigger) #Resets the higher dimensional scans to trigger the inner scan if kwargs['scan_dim'] == 1:
kwargs.setdefault('trigger_dictionary',self.trigger_dictionary)
else:
kwargs.setdefault('trigger_dictionary',{1:inner_scan_trigger,2:"",3:"",4:""})
else:
kwargs.setdefault('trigger_dictionary',{})
#set detector triggers to dictionary values #set detector triggers to dictionary values
trigger_dictionary = kwargs['trigger_dictionary'] trigger_dictionary = kwargs['trigger_dictionary']
if len(trigger_dictionary.keys())>0: if len(trigger_dictionary.keys())>0:
for tigger_num in trigger_dictionary.keys(): for tigger_num in trigger_dictionary.keys():
caput(scan_pv+".T"+str(tigger_num)+"PV",trigger_dictionary[tigger_num]) caput(scan_pv+".T"+str(tigger_num)+"PV",trigger_dictionary[tigger_num])
...@@ -870,7 +888,7 @@ class ScanRecord: ...@@ -870,7 +888,7 @@ class ScanRecord:
det_num=(str(i).zfill(2)) det_num=(str(i).zfill(2))
det_pv=caget(scan_pv+".D"+det_num+"PV") det_pv=caget(scan_pv+".D"+det_num+"PV")
if det_pv !='': if det_pv !='':
det=PV(det_pv); time.sleep(0.1)#smallest sleep to allow for PV traffic det=PV(det_pv); time.sleep(0.25)#sleep to allow for PV traffic
if not det.connected: if not det.connected:
print("Detector "+det_num+" has a bad PV: "+det.pvname+" not connected") print("Detector "+det_num+" has a bad PV: "+det.pvname+" not connected")
det_ok = False det_ok = False
...@@ -881,7 +899,7 @@ class ScanRecord: ...@@ -881,7 +899,7 @@ class ScanRecord:
pos_num=str(i) pos_num=str(i)
pos_pv=caget(scan_pv+".P"+pos_num+"PV") pos_pv=caget(scan_pv+".P"+pos_num+"PV")
if pos_pv != '': if pos_pv != '':
pos=PV(pos_pv); time.sleep(0.1)#smallest sleep to allow for PV traffic pos=PV(pos_pv); time.sleep(0.25)#increased from .1
if not pos.connected: if not pos.connected:
print("Positioner "+pos_num+" has a BAD PV: "+pos.pvname+" not connected") print("Positioner "+pos_num+" has a BAD PV: "+pos.pvname+" not connected")
pos_ok = False pos_ok = False
......
...@@ -294,28 +294,34 @@ def apertures_set(c_2B=1,c_1A=1,verbose=True): ...@@ -294,28 +294,34 @@ def apertures_set(c_2B=1,c_1A=1,verbose=True):
slit2B_set(Size2B[0],Size2B[1],center=(H2_center,V2_center),verbose=verbose) slit2B_set(Size2B[0],Size2B[1],center=(H2_center,V2_center),verbose=verbose)
def mvID(val): def mvID(energy_eV):
""" """
Sets the ID absolute set point (not optimized , mono & apertures stay fixed). Sets the ID absolute set point in eV
Note: flux is not optimized and mono & apertures stay fixed
to go to most flux use energy to go to most flux use energy
""" """
ID_set_eV(val) ID_set_eV(energy_eV)
def mvID_calibrated(val): def mvID_calibrated(energy_eV):
""" """
Sets the ID peak to val (calibrated). Sets the ID peak to eV (calibrated).
Note: mono & apertures stay fixed
""" """
ID_energy_set_eV(val) ID_energy_set_eV(energy_eV)
def scan_ID(ID_sp_start,ID_sp_stop,ID_sp_step,**kwargs): def scanID(ID_sp_start,ID_sp_stop,ID_sp_step,**kwargs):
""" """
scan the ID set point scan the ID set point
""" """
kwargs.setdefault('execute',True)
kwargs.setdefault('scan_dim',1)
val_pv,rbv_pv = ID_scan_pvs() val_pv,rbv_pv = ID_scan_pvs()
scan_fillin(val_pv,rbv_pv,ID_sp_start,ID_sp_stop,ID_sp_step,**kwargs) scan_fillin(val_pv,rbv_pv,ID_sp_start,ID_sp_stop,ID_sp_step,**kwargs)
#Scanning
if kwargs['execute']:
scan_go(scan_dim=kwargs['scan_dim'])
def mvmono(val): def mvmono(val):
......
from epics import caget,caput from epics import caget,caput
from ..instruments.electron_analyzer import EA from iexcode.instruments.electron_analyzer import EA
from ..instruments.shutters import main_shutter_close,branch_shutter_close from iexcode.instruments.shutters import main_shutter_close,branch_shutter_close
from ..instruments.diagnostics import diagnostics_all_out from iexcode.instruments.diagnostics import diagnostics_all_out
from iexcode.instruments.xrays import grating, mvmono
from iexcode.instruments.ARPES import ARPES_safestate
from iexcode.instruments.kappa import kappa_safestate
from iexcode.instruments.Octupole import Octupole_safestate
############################################################################################################## ##############################################################################################################
############################################ Shut down ################################################# ############################################ Shut down #################################################
...@@ -10,14 +14,20 @@ from ..instruments.diagnostics import diagnostics_all_out ...@@ -10,14 +14,20 @@ from ..instruments.diagnostics import diagnostics_all_out
def BL_Shutdown(): def BL_Shutdown():
BL_CloseAllShutters() BL_CloseAllShutters()
print('\nClosed all beamline shutters')
BL_Valve_All(state="CLOSE") BL_Valve_All(state="CLOSE")
print('\nClosed all beamline valves')
diagnostics_all_out() diagnostics_all_out()
print('\nAll diagnostics out')
try: try:
EA.off() ARPES_safestate()
kappa_safestate()
Octupole_safestate()
except: except:
print('EA is not running, visually confirm HV is off') print('Check that endstations are in a safe state')
grating('MEG')
caput("29iddau1:dau1:011:DAC_Set",0) #RSXS HV = "OFF" mvmono(500)
def BL_CloseAllShutters(): def BL_CloseAllShutters():
main_shutter_close() main_shutter_close()
......
from time import sleep from time import sleep
import iexcode.instruments.cfg as iex import iexcode.instruments.cfg as iex
from iexcode.instruments.utilities import * from iexcode.instruments.utilities import play_sound,print_warning_message,play_sound
from iexcode.instruments.Kappa import uan from iexcode.instruments.Kappa import uan
from iexcode.instruments.Motors import * from iexcode.instruments.Motors import mvz,mvtth,dscanz,dscantth,dscanth
from iexcode.instruments.scanRecord import last_mda from iexcode.instruments.scanRecord import last_mda
from iexplot.mda_quick_plot import * from iexplot.mda_quick_plot import fit_mda
try: try:
tey = iex.kappa_detectors_dictionary['tey'] detector_dictionary = iex.kappa_detectors_dictionary
d3 = iex.kappa_detectors_dictionary['d3'] tey = detector_dictionary['tey']
d4 = iex.kappa_detectors_dictionary['d4'] d3 = detector_dictionary['d3']
mesh = iex.kappa_detectors_dictionary['mesh'] d4 = detector_dictionary['d4']
tthdet = iex.kappa_detectors_dictionary['tthdet'] mesh = detector_dictionary['mesh']
tthdet = detector_dictionary['tthdet']
except: except:
print('you must kappa_init prior to importing') print('you must kappa_init prior to importing')
##### Kappa Optimization scans - 2022 versions #####
def Find_kth_zero(th_0,th_180): def Find_kth_zero(th_0,th_180):
""" """
th_0 is the motor position for specular near zero th_0 is the motor position for specular near th=zero
th_180 is motor position for spectular near 180 th_180 is motor position for spectular near th=180
""" """
Offset =0.5*(180 - th_180 - th_0) Offset =0.5*(180 - th_180 - th_0)
print("with motor at 0, the actual value is ",Offset) print("with motor at 0, the actual value is ",Offset)
def align_d4(z0,th,detNum=34,plot=False): def align_d4(th,**kwargs):
''' th = 0 or 180 """
''' sets tth.det to 'd4'; moves the sample out of the way
z= z0-1500
th = 0 or 180
scans tth around zero to set the user dial on d4
**kwargs:
detNum: default => 15
plot: True/False to show the plot (default => False)
sound: True/False (default=False)
"""
kwargs.setdefault('detNum',15)
kwargs.setdefault('plot',False)
kwargs.setdefault('sound',False)
#set the detector
tthdet.set('d4') tthdet.set('d4')
sleep(1) d4.get_all(verbose=False)
d4gain = d4.gain
d4units = d4.current_unit
#moving sample out of the way
z0=iex.BL.motors.get('z')
uan(0,th) uan(0,th)
mvz(z0-1500) mvz(z0-1500)
#setting gain for direct beam and scanning
d4.setgain(10,'uA') d4.setgain(10,'uA')
dscantth(-0.25,0.25,0.01) dscantth(-0.25,0.25,0.01)
sleep(1) sleep(1)
d4.setgain(1,'nA') #setting thing back
d4.setgain(d4gain,d4units)
mvz(z0) mvz(z0)
#fitting
scanNum=last_mda() scanNum=last_mda()
tth0 =fit_mda(scanNum,detNum,'poly',plot=plot) tth0 =fit_mda(scanNum,kwargs['detNum'],'gauss',plot=kwargs['plot'])
print('tth0 = '+str(round(tth0,3))) print('tth0 = '+str(round(tth0,3)))
play_sound() if kwargs['sound']:
play_sound()
return tth0 return tth0
def align_z0_chi0(question=True,detNum=33): def align_z0_chi0(**kwargs):
if question: """
foo=input_d('Are you at th=90/270, chi=0, phi=90 (Y or N)? >') sets tth.det to 'd3', and tth=0
if foo == 'Y'.lower() or foo == 'yes'.lower(): scanz z and fits erf
tthdet.set('d3') **kwargs:
sleep(1) detNum: default => 15
mvtth(0) plot: True/False to show the plot (default => False)
dscanz(-750,750,50) sound: True/False (default=False)
sleep(1) """
scanNum=last_mda() kwargs.setdefault('detNum',15)
z0=fit_mda(n,detNum,0,'erf',graph=False) kwargs.setdefault('plot',False)
print('z0 = '+str(round(z0,0))) kwargs.setdefault('sound',False)
play_sound()
return z0 if int(iex.BL.motors.get('th')) == 0 or int(iex.BL.motors.get('th')) == 270:
else: tthdet.set('d3',move=False)
print('Canceling')
return
else:
tthdet.set('d3')
sleep(1)
mvtth(0) mvtth(0)
#scans z
dscanz(-750,750,50) dscanz(-750,750,50)
sleep(1) sleep(1)
n=last_mda() scanNum=last_mda()
fit_mda(n,25,0,'poly',graph=False) z0=fit_mda(scanNum,kwargs['detNum'],'erf',plot=kwargs['plot'])
z0=fit_z(n)
print('z0 = '+str(round(z0,0))) print('z0 = '+str(round(z0,0)))
play_sound() if kwargs['sound']:
play_sound()
return z0 return z0
else:
print('th = ',round(iex.BL.motors.get('th'),0))
print_warning_message('th is not at 0 or 270')
def align_z0(omega_off): def align_z0(omega_off,**kwargs):
""" """
finds the correct z value finds the correct z value
omega = th_offset omega = th_offset
...@@ -87,50 +107,90 @@ def align_z0(omega_off): ...@@ -87,50 +107,90 @@ def align_z0(omega_off):
- goes to grazing incidence - goes to grazing incidence
- scans z +/- 750 of current positions - scans z +/- 750 of current positions
**kwargs:
detNum: default => 15
plot: True/False to show the plot (default => False)
sound: True/False (default=False)
""" """
tthdet.set('d3') kwargs.setdefault('detNum',15)
sleep(1) kwargs.setdefault('plot',False)
kwargs.setdefault('sound',False)
#setting the detecotr
tthdet.set('d3',move=False)
uan(0,omega_off) uan(0,omega_off)
#scanning
dscanz(-750,750,50) dscanz(-750,750,50)
sleep(1) sleep(1)
n=last_mda() scanNum = last_mda()
fit_mda(n,25,0,'poly',graph=False) z0 = fit_mda(scanNum,kwargs['detNum'],'erf',plot=kwargs['plot'])
#z0=fit_z(n) if kwargs['sound']:
#print('z0 = '+str(round(z0,0))) play_sound()
play_sound() return z0
#return z0
def align_z180(omega_off): def align_z180(omega_off,**kwargs):
tthdet.set('d3') """ finds the correct z value for tth = 180
sleep(1) omega = th_offset
Used to find the sample z0 (splitting the beam) by doing the following
- sets to d3
- goes to grazing incidence
- scans z +/- 750 of current positions
**kwargs:
detNum: default => 15
plot: True/False to show the plot (default => False)
sound: True/False (default=False)
"""
kwargs.setdefault('detNum',15)
kwargs.setdefault('plot',False)
kwargs.setdefault('sound',False)
tthdet.set('d3',move=False)
uan(0,180+omega_off) uan(0,180+omega_off)
dscanz(-750,750,50) dscanz(-750,750,50)
sleep(1) sleep(1)
n=last_mda() scanNum=last_mda()
#fit_mda(n,25,0,'poly',graph=False) z180 = fit_mda(scanNum,kwargs['detNum'],'erf',plot=kwargs['plot'])
#z180=fit_z(n) if kwargs['sound']:
#print('z180 = '+str(round(z180,0))) play_sound()
play_sound() return z180
#return z180
def align_th0(omega_off,z): def align_th0(omega_off,z,**kwargs):
"""
sets d4
goes to specular tth = 30 (default see kwargs); th = tth/2+omega_off
does rocking curve
**kwargs:
detNum: default => 15
plot: True/False to show the plot (default => False)
sound: True/False (default=False)
tth: default =>30
"""
kwargs.setdefault('detNum',15)
kwargs.setdefault('plot',False)
kwargs.setdefault('sound',False)
kwargs.setdefault('tth',30)
#set the detector
tthdet.set('d4') tthdet.set('d4')
sleep(1) d4.get_all(verbose=False)
#uan(20,10+omega) d4gain = d4.gain
uan(30,15+omega_off) d4units = d4.current_unit
#moving sample
uan(kwargs['tth'],kwargs['tth']/2+omega_off)
mvz(z) mvz(z)
sleep(30) sleep(30)
d4.setgain(1,'nA') #scanning
dscanth(-0.25,0.25,0.01) dscanth(-0.25,0.25,0.01)
n=last_mda() #fitting
fit_mda(n,25,0,'poly',graph=False) scanNum=last_mda()
th_spec=fit_d4(n) th_spec = fit_mda(scanNum,kwargs['detNum'],'gauss',plot=kwargs['plot'])
print('th specular = '+str(round(th_spec,3))) print('th specular = '+str(round(th_spec,3)))
tth=round(caget('29idKappa:m9.RBV'),3) tth=round(iex.BL.motors.get('tth'),3)
omega_off=th_spec-tth/2 omega_off=th_spec-tth/2
print('omega = th-tth/2 = '+str(round(omega_off,3))) print('omega = th-tth/2 = '+str(round(omega_off,3)))
play_sound() if kwargs['sound']:
play_sound()
return omega_off return omega_off
...@@ -143,10 +203,9 @@ def align_th180(omega_off,z): ...@@ -143,10 +203,9 @@ def align_th180(omega_off,z):
d4.setgain(1,'nA') d4.setgain(1,'nA')
dscanth(-0.25,0.25,0.01) dscanth(-0.25,0.25,0.01)
n=last_mda() n=last_mda()
fit_mda(n,25,0,'poly',graph=False) th_spec = fit_mda(n,25,0,'poly',graph=False)
th_spec=fit_d4(n)
print('th specular = '+str(round(th_spec,3))) print('th specular = '+str(round(th_spec,3)))
tth=round(caget('29idKappa:m9.RBV'),3) tth=round(iex.BL.motors.get('tth'),3)
omega180=th_spec-tth/2-180 omega180=th_spec-tth/2-180
print('omega180 = th-tth/2-180 = '+str(round(omega180,3))) print('omega180 = th-tth/2-180 = '+str(round(omega180,3)))
play_sound() play_sound()
...@@ -154,97 +213,3 @@ def align_th180(omega_off,z): ...@@ -154,97 +213,3 @@ def align_th180(omega_off,z):
##### Kappa Optimization scans - old versions #####
def Opt_d4(iteration,moveZ,graph='y',srs=None,start=-0.5,stop=0.5,step=0.04):
tth_w=0.1
if srs==None: det=21
else: det=34
z=caget('29idKappa:m4.RBV')
current_det=caget('29idKappa:userStringSeq6.STR1',as_string=True)
if current_det != 'd4':
print('Switching detector omega')
if moveZ is not None:
mvz(z-1000)
for i in range(iteration):
scantth(start,stop,step,'relative')
scannum=last_mda()
tth0=fit_mda(scannum,det,tth_w,'gauss',graph=graph)
mvtth(tth0)
mvz(z)
return tth0,scannum
def Opt_z0(iteration,movetth,movekth,det='d4',srs=None,graph='y'):
z_w=400
current_det=caget('29idKappa:userStringSeq6.STR1',as_string=True)
if current_det != det:
print('Switching detector to '+det)
tthdet.set(det)
if det=='d3' and srs==None: det=20
if det=='d3' and srs!=None: det=33
if det=='d4' and srs==None: det=21
if det=='d4' and srs!=None: det=34
if movetth is not None:
mvtth(movetth)
if movekth is not None:
mvkth(movekth)
if iteration>1:
scanz(-2000,2000,250,'relative')
scannum=last_mda()
z0=fit_mda(scannum,det,z_w,'erf',graph=graph)
mvz(z0)
scanz(-700,700,50,'relative')
scannum=last_mda()
z0=fit_mda(scannum,det,z_w,'erf',graph=graph)
mvz(z0)
return z0,scannum
def Opt_kth(kth_0,theta,det='d4',srs=None,graph='y'):
current_det=caget('29idKappa:userStringSeq6.STR1',as_string=True)
if current_det != det:
print('Switching detector to '+det)
tthdet.set(det)
if det == 'd4':
if srs==None: det=21
else: det=34
i=1
elif det == 'd3':
if srs==None: det=20
else: det=33
i=5
mvtth(theta*2)
mvkth(kth_0+theta)
scankth(-0.5*i,0.5*i,0.05*i,'relative')
new_kth=fit_mda(last_mda(),det,0.1,'gauss',graph=graph)
mvkth(new_kth)
scankth(-0.2*i,0.2*i,0.02*i,'relative')
new_kth=fit_mda(last_mda(),det,0.1,'gauss',graph=graph)
mvkth(new_kth)
scannum=last_mda()
kth0=round(new_kth-theta,3)
print('\nkth0 = ',kth0)
print('To plot use:')
print(' fit_mda('+str(scannum)+',21,0.2,"gauss",mytitle=\'theta ='+str(theta)+'\')')
print('If you are happy with that, you can set this value as kth0 using:')
print(' kth0_set('+str(kth0)+')')
return kth0,scannum
def plot_opt(opt_scan_list,energy_list,det,mytitle=''):
fig,(ax1)=plt.subplots(1,1)
fig.set_size_inches(5,4)
for i,j in zip(opt_scan_list,energy_list):
x,y,x_name,y_name=mda_1D(i,det,1,0)
xdata = np.array(x)
ydata = np.array(y)
Imax=np.max(ydata)
ax1.plot(x,y/Imax,label=str(j)+" eV")
ax1.set(ylabel='Intensity')
ax1.set(xlabel=x_name)
ax1.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
ax1.grid(color='lightgray', linestyle='-', linewidth=0.5)
ax1.legend(bbox_to_anchor=[1.2, 1],ncol=2,shadow=True, title=mytitle, fancybox=True)