diff --git a/build/lib/iexcode/__init__.py b/build/lib/iexcode/__init__.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/build/lib/iexcode/instruments/AD_utilities.py b/build/lib/iexcode/instruments/AD_utilities.py deleted file mode 100644 index d1e324da81e3a4c3629f1f568b0e3d7ba9ed31f9..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/AD_utilities.py +++ /dev/null @@ -1,379 +0,0 @@ -""" -General functions for dealing with Area Detectors and Cameras at 29ID - -work in progress need to redo -""" -############################################################################################################## -############################## General Area Detector ############################## -############################################################################################################## -import os -import datetime -import re - -from time import sleep - -from epics import caget, caput - -import iexcode.instruments.cfg as iex -from iexcode.instruments.files_and_folders import get_next_fileNumber - -def AD_exposure_time(ADplugin,exp_time,**kwargs): - """ - sets the aquiretime and the exposure time - overwrites what is in kwargs - """ - kwargs.setdefault("P",ADplugin.split(":")[0]+":") - kwargs.setdefault("R","cam1:") - kwargs.setdefault("P",ADplugin.split(":")[0]+":") - kwargs.setdefault("R","cam1:") - - caput(kwargs["P"]+kwargs["R"]+"AcquireTime",exp_time) - caput(kwargs["P"]+kwargs["R"]+"AcquireTime",exp_time+.01) - - -def AD_CurrentDirectory(ADplugin): - """ - returns the current directory for area detector SavePlugin - handles both Winodws and linux IOCs - ADplugin = "29idc_ps1:TIFF1:"; $(P)$(SavePlugin) - """ - SubDir=caget(ADplugin+"FilePath",as_string=True) - if SubDir[0] == 'X': - Dir='/net/s29data/export/data_29idb/' - SubDir=SubDir.split('\\')[1:] - elif SubDir[0] == 'Y': - Dir='/net/s29data/export/data_29idc/' - SubDir=SubDir.split('\\')[1:] - elif SubDir[0] == 'Z': - Dir='/net/s29data/export/data_29idd/' - SubDir=SubDir.split('\\')[1:] - else: - Dir = SubDir - SubDir=[] - FilePath=os.path.join(Dir,*SubDir,'') - return FilePath - -def AD_prefix(ADplugin): - """ - returns the prefix for AreaDetector plugin based on ADplugin - """ - prefix = caget(ADplugin+"FileName_RBV",as_string=True) - return prefix - -def AD_EnableStats(ADplugin): - """ - Enabling the statistics in an AreaDector - ADplugin = "29idc_ps1:Stats1:"; (ADplugin=$(P)$(StatsPlugin)) - """ - caput(ADplugin+"EnableCallbacks","Enable") - caput(ADplugin+"ComputeStatistics","Yes") - caput(ADplugin+"ComputeCentroid","Yes") - -def AD_last_filename(ADplugin,verbose=True): - """ - returns the full path for the last saved image - """ - fpath = caget(ADplugin+"FullFileName_RBV",as_string=True) - if verbose: - print(ADplugin," => ",fpath) - return fpath - -def AD_SaveFileSetup(ADplugin,**kwargs): - """ - ADplugin = "29id_ps1:TIFF1:" which IOC and which filesaving plugin - (ADplugin=$(P)$(SavePlugin)) - - **kwargs (defaults) - scanIOC = BL_ioc() - userpath = extracted from ScanRecord unless specified - subfolder = taken from ADplugin unless specified - filepath = userpath/subfolder - - prefix = default same as subfolder - ext = file extension is extracted for ADplugin unless specified - (TIFF -> tif, HDF -> h5, ...) - FileTemplate="%s%s_%4.4d."+ext; format for filename first %s = filepath, second %s = prefix - - """ - kwargs.setdefault("userpath",os.path.dirname(iex.BL.mda.filepath())) - kwargs.setdefault("subfolder",ADplugin.split(":")[-2][:-1]) - - kwargs.setdefault("prefix",ADplugin.split(":")[-2][:-1]) - kwargs.setdefault("ext",ADplugin.split(":")[-2][:-1]) - kwargs.setdefault("FileTemplate","%s%s_%4.4d."+kwargs["ext"]) - - kwargs.setdefault("debug",False) - - if kwargs['debug']: - print("kwargs: ",kwargs) - - fpath=os.path.join(kwargs['userpath'],kwargs['subfolder'],'') - print("\nFolder: " + fpath) - if not (os.path.exists(fpath)): - fileNumber=1 - else: - fileNumber=get_next_fileNumber(fpath,kwargs["prefix"]) - print("NextFile: "+str(fileNumber)) - caput(ADplugin+"CreateDirectory",-1) #allows IOC to create directories - caput(ADplugin+"FilePath",fpath) - caput(ADplugin+"FileName",kwargs["prefix"]) - caput(ADplugin+"FileNumber",fileNumber) - - #setup AD - caput(ADplugin+"FileTemplate",kwargs["FileTemplate"]) - caput(ADplugin+"AutoIncrement","Yes") - caput(ADplugin+"AutoSave","Yes") - -def AD_CurrentPrefix(ADplugin): - """ - returns the prefix (without _) for area detector SavePlugin - ADplugin = "29id_ps1:TIFF1:"; $(P)$(SavePlugin) - """ - Prefix=caget(ADplugin+'FileName',as_string=True) - return Prefix - -def AD_CurrentRun(ADplugin): - """ - returns the curent run specified in the filepath for area detector SavePlugin - ADplugin = "29id_ps1:TIFF1:"; $(P)$(SavePlugin) - """ - fpath=caget(ADplugin+"FilePath",as_string=True) - current_run=re.findall("\d\d\d\d_\d", fpath)[0] - return current_run - -def AD_CurrentUser(ADplugin): - """ - returns the curent user specified in the filepath for area detector SavePlugin - ADplugin = "29id_ps1:TIFF1:"; $(P)$(SavePlugin) - """ - folder_name = ADplugin.split(":")[1] - folder_name[:-1] - SubDir=caget(ADplugin+":FilePath",as_string=True) - if SubDir[0] == 'X': - current_user='Staff' - elif SubDir[0] == 'Y': - m=SubDir.find(AD_CurrentRun(ADplugin)) - n=SubDir.find(folder_name) - current_user=SubDir[m+7:n] - else: current_user=None - return current_user - -def AD_DoneSingleSave(ADplugin,**kwargs): - """ - sets and AD up ready to save images - Acquire -> Done - ImageMode -> Single - Save -> Enable - e.g. ADplugin="29id_ps2:TIFF1:" - - **kwargs: - P=first part of ADplugin if not specified - R="cam1:"; other AD have "det1:" - """ - kwargs.setdefault("P",ADplugin.split(":")[0]+":") - kwargs.setdefault("R","cam1:") - AD_Done(ADplugin,**kwargs) - caput(kwargs["P"]+kwargs["R"]+"ImageMode","Single");sleep(.5) - caput(ADplugin+"EnableCallbacks","Enable");sleep(.1) - -def AD_FreeRun(ADplugin,**kwargs): - """ - sets and AD to disable saving and free run - Saving -> Disable - Acquire -> Done - ImageMode -> Single - - e.g. ADplugin="29id_ps2:TIFF1:" - - **kwargs: - P=first part of ADplugin if not specified - R="cam1:"; other AD have "det1:" - """ - kwargs.setdefault("P",ADplugin.split(":")[0]+":") - kwargs.setdefault("R","cam1:") - AD_Done(ADplugin,**kwargs) - caput(ADplugin+"EnableCallbacks","Disable");sleep(.1) - caput(kwargs["P"]+kwargs["R"]+"ImageMode","Continuous");sleep(.1) - caput(kwargs["P"]+kwargs["R"]+"Acquire","Acquire");sleep(.1) - -def AD_Done(ADplugin,**kwargs): - """ - sets acquisition to Done - **kwargs: - P=first part of ADplugin if not specified - R="cam1:"; other AD have "det1:" - """ - kwargs.setdefault("P",ADplugin.split(":")[0]+":") - kwargs.setdefault("R","cam1:") - caput(kwargs["P"]+kwargs["R"]+"Acquire","Done",wait=True,timeout=5*60) - sleep(0.1) - -def AD_snap(ADplugin,**kwargs): - """ - takes an image and save the image for ADplugin - e.g. ADplugin="29id_ps2:TIFF1:" - - use AD_SaveFileSetup to set filepath, prefix etc. - use AD_CurrentDirectory to see current directory - use AD_prefix to see current prefix - - **kwargs: - P=first part of ADplugin if not specified - R="cam1:"; other AD have "det1:" - - ExposureTime: changes both the exposure time and the acquire time for the snapshot - resets after acquisition - FreeRun: True => disable setting and go back to continuous acquision - False => leave saving enabled and camera in single acquision - """ - kwargs.setdefault("P",ADplugin.split(":")[0]+":") - kwargs.setdefault("R","cam1:") - kwargs.setdefault("FreeRun",True) - - expT=caget(kwargs["P"]+kwargs["R"]+"AcquireTime_RBV") - acqT=caget(kwargs["P"]+kwargs["R"]+"AcquirePeriod_RBV") - - AD_DoneSingleSave(ADplugin,**kwargs) - - if "ExposureTime" in kwargs: - AD_exposure_time(ADplugin,kwargs["ExposureTime"]) - - caput(kwargs["P"]+kwargs["R"]+"Acquire","Acquire",wait=True,timeout=5*60) - - if "ExposureTime" in kwargs: - caput(kwargs["P"]+kwargs["R"]+"AcquireTime",expT) - caput(kwargs["P"]+kwargs["R"]+"AcquireTime",acqT) - - if kwargs["FreeRun"]: - sleep(.1) - AD_FreeRun(ADplugin,**kwargs) - - - -def AD_ScanTrigger(ADplugin,**kwargs): - """ - Add Triggering of AreaDetector to scanIOC - ADplugin = "29idc_ps1:TIFF1:" (ADplugin=$(P)$(SavePlugin)) - - **kwargs - scanIOC = "29id"+BL_ioc() if not specified - scanDIM = 1 - P=first part of ADplugin if not specified - R="cam1:"; other AD have "det1" - detTrig = 2; detectorTrigger number - """ - kwargs.setdefault("scanDIM",1) - kwargs.setdefault("P",ADplugin.split(":")[0]+":") - kwargs.setdefault("R","cam1:") - kwargs.setdefault("detTrig",2) - - scanPV=iex.BL.mda.ioc+"scan"+str(kwargs["scanDIM"]) - trigger=".T"+str(kwargs["detTrig"])+"PV" - caput(scanPV+trigger,kwargs["P"]+kwargs["R"]+"Acquire",wait=True,timeout=5*60) - -def ADplugin_ScanSetup(ADplugin, **kwargs): - """ - stop the acquisition, puts in ImageMode=Single - enables saving - add to detector trigger - Does not press go - - ADplugin = "29idc_ps1:TIFF1:"; (ADplugin=$(P)$(SavePlugin)) - **kwargs - # AD_ScanTrigger - scanIOC = "29id"+BL_ioc() if not specified - scanDIM = 1 - P=first part of ADplugin if not specified - R="cam1:"; other AD have "det1:" - detTrig = 2; detectorTrigger number - - # AD_SaveFileSetup - filepath=userpath (from BL_ioc scanRecord)+"/dtype" - (e.g. filepath="/net/s29data/export/data_29id"+folder+"/"+run+"/"+userName+"/"+df) - dtype = taken from ADplugin - FileTemplate="%s%s_%4.4d."+dtype; format for filename first %s = filepath, second %s = prefix - prefix = dtype by default - - """ - #from AD_ScanTrigger - kwargs.setdefault("P",ADplugin.split(":")[0]+":") - kwargs.setdefault("R","cam1:") - - AD_DoneSingleSave(ADplugin,**kwargs) - - if "ExposureTime" in kwargs: - AD_exposure_time(ADplugin,kwargs["ExposureTime"]) - - AD_SaveFileSetup(ADplugin,**kwargs) - AD_ScanTrigger(ADplugin, **kwargs) - trigger=".T"+str(kwargs["detTrig"])+"PV" - scanPV=iex.BL.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("\tAD_FreeRun("+ADplugin+"); caput("+scanPV+trigger+",'')") - -def AD_ROI_setup(AD,ROInum,xcenter=500,ycenter=500,xsize=50,ysize=50,binX=1,binY=1): - """ - AD = "29id_ps4" - AD = "29iddMPA" - """ - # roiNUM=1 MPA_ROI_SetUp(535,539,50,50) center of MCP - - ADplugin=AD+':ROI'+str(ROInum)+':' - xstart=xcenter-xsize/2.0 - ystart=ycenter-ysize/2.0 - caput(ADplugin+'MinX',xstart) - caput(ADplugin+'MinY',ystart) - caput(ADplugin+'SizeX',xsize) - caput(ADplugin+'SizeY',ysize) - caput(ADplugin+'BinX',binX) - caput(ADplugin+'BinY',binY) - caput(ADplugin+'EnableCallbacks','Enable') - print(ADplugin+' - '+caget(ADplugin+'EnableCallbacks_RBV',as_string=True)) - #MPA_ROI_Stats(roiNUM) - -def AD_OVER_SetUp(AD,ROInum,OVERnum,linewidth=5,shape='Rectangle'): - """ - AD = "29id_ps4" - AD = "29iddMPA" - shape= 'Cross', 'Rectangle', 'Ellipse','Text' - """ - OVER1=AD+":Over1:"+str(OVERnum)+":" - ROI=AD+":ROI"+str(ROInum)+":" - - caput(ROI+'EnableCallbacks','Enable') - caput(OVER1+"Name","ROI"+str(ROInum)) - caput(OVER1+"Shape",shape) - caput(OVER1+"Red",0) - caput(OVER1+"Green",255) - caput(OVER1+"Blue",0) - caput(OVER1+'WidthX',linewidth) - caput(OVER1+'WidthY',linewidth) - - caput(OVER1+"PositionXLink.DOL",ROI+"MinX_RBV CP") - caput(OVER1+"SizeXLink.DOL",ROI+"SizeX_RBV CP") - caput(OVER1+"PositionYLink.DOL",ROI+"MinY_RBV CP") - caput(OVER1+"SizeYLink.DOL",ROI+"SizeY_RBV CP") - - caput(OVER1+"Use","Yes") - - -def AD_OverLayCenter(x,y,AD,OverLay=1,Num=1): - """ - Sets CenterX and CenterY for AD:Over(OverLay):Num: - eg. 29id_ps2:Over1:1: AD='29id_ps2',Overlay=1, Num=1 - """ - caput(AD+":Over"+str(OverLay)+":"+str(Num)+":CenterX",x) - caput(AD+":Over"+str(OverLay)+":"+str(Num)+":CenterY",y) - -def AD_OverLayCenter_get(AD,OverLay=1,Num=1): - """ - Sets CenterX and CenterY for AD:Over(OverLay):Num: - eg. 29id_ps2:Over1:1: AD='29id_ps2',Overlay=1, Num=1 - """ - print('x = '+str(caget(AD+":Over"+str(OverLay)+":"+str(Num)+":CenterX"))) - print('y = '+str(caget(AD+":Over"+str(OverLay)+":"+str(Num)+":CenterY"))) - - - - - diff --git a/build/lib/iexcode/instruments/ARPES.py b/build/lib/iexcode/instruments/ARPES.py deleted file mode 100644 index ba46b7430a5cdb360ea9a65791f156cbd4765c82..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/ARPES.py +++ /dev/null @@ -1,799 +0,0 @@ -import os -from re import A -from time import sleep -import numpy as np -from epics import caget,caput,PV - -import iexcode.instruments.cfg as iex -from iexcode.instruments.IEX_BL_config import Beamline_Config -from iexcode.instruments.IEX_cameras import _enable_endstation_cameras - -from iexcode.instruments.files_and_folders import check_run,make_user_folders,folder_mda,path_dserv -from iexcode.instruments.Logfile import Logfile -from iexcode.instruments.staff import staff_detector_dictionary -from iexcode.instruments.xrays import xrays_detector_dictionary, _xrays_reset, xrays_get_all, xrays_log_dictionary - -from iexcode.instruments.conversions_constants import * -from iexcode.instruments.utilities import * -from iexcode.instruments.userCalcs import * - -from iexcode.instruments.Motors import Motors -from iexcode.instruments.SRS_current_amplifiers import Keithley, _Keithley_pv, ca_reset_all, _ca_live_sequence - -from iexcode.instruments.valves import branch_valve_close -from iexcode.instruments.shutters import branch_shutter_close - -#branch specific -from iexcode.instruments.slits import slit3C_get -#endstation specific -from iexcode.instruments.Lakeshore_335 import Lakeshore_reset -from iexcode.instruments.electron_analyzer import _EA_init_Motors,folders_EA,EA - -default_ioc = '29idARPES:' -############################################################################# -def ARPES_init(*userName,**kwargs): - """ - used to intialize the Endstation class which carries scanRecord, logging ... parameters - returns global detectors relavent to this endstation (tey,ca15) - - *userName is an optional parameter, will be prompted if set_folders=True - - **kwargs: - set_folders: sets the mda and EA folders (default => True) - reset: to reset the detectors in the IOC, sets the logfile name, etc (default => False) - xrays: sets global variable and detectors for x-ray (default => True) - mode: used sets the detectors 'user ' / 'staff' (default => 'user' ) - - usage: - tey,ca15 = ARPES_init('user_name') - tey,ca15 = ARPES_init(mode='staff') - """ - kwargs.setdefault('scan_ioc',default_ioc) - kwargs.setdefault('xrays',True) - kwargs.setdefault('mode','user') - kwargs.setdefault('set_folders',True) - kwargs.setdefault('reset',False) - - #motors - physical_motors = ['x','y','z','th','chi','phi'] - pseudo_motors = ['focus'] - global ARPES_Motors - ARPES_Motors = Motors('ARPES',_ARPES_motor_dictionary(),physical_motors,pseudo_motors) - - #endstation - iex.BL = Beamline_Config('ARPES',kwargs['scan_ioc'],kwargs['xrays'],kwargs['mode'],ARPES_Motors) - iex.BL.safe_state = ARPES_safe_state - iex.BL.endstation_get = ARPES_get_all - - #setting folders - if kwargs['set_folders']: - if iex.BL.mode == 'staff': - user_name = 'Staff' - else: - if len(userName)==0: - user_name = input('user name: ') - else: - user_name = userName[0] - print(user_name) - folders_ARPES(user_name,**kwargs) - else: - user_name = iex.BL.mda.user_name() - - #update for default scanRecord advanced parameters - iex.BL.mda.log=Logfile('ARPES',user_name,_ARPES_log_dictionary,set_file=False) - - #EA - if EA.connected: - sleep(1) - EA.get() - _EA_init_Motors(ARPES_Motors) - if kwargs['set_folders']: - userPath = os.path.dirname(iex.BL.mda.filepath()) - folders_EA(userPath,filePrefix="EA",**kwargs) - - else: - print("NOTE: Scienta IOC is not running") - - #global detectors - global tey, ca15 - tey = Keithley('c',1) - ca15 = Keithley('b',15) - - #default scan settings - ARPES_default_scan_setting() - - #resetting everything - if kwargs['reset']: - ARPES_reset() - - #enable cameras - _enable_endstation_cameras() - - print ('\nARPES initalized') - print('\tpath = "'+iex.BL.mda.filepath()+'"') - print('\tprefix = "'+iex.BL.mda.prefix()+'"') - #return any detectors or other parameters that you want access to from jupyter - return tey,ca15 - -############################################################################################################## -############################## ARPES detectors and motors ############################## -############################################################################################################## -def _ARPES_ca_list(): - """ - list of detectors to trigger - - Previously: part of Detector_List - """ - ca_list=[["c",1],["b",15],["b",4],["b",13]] - return ca_list - -def _ARPES_detector_dictionary(): - """ - returns a dictionary of the default detectors for the scan record - - Previously: Detector_Default - """ - det_dict={ - 14:"29idc:ca2:read", - 16:"29idc:ca1:read", - 17:"", - 18:"29idARPES:LS335:TC1:IN1", - 19:"29idARPES:LS335:TC1:IN2", - } - - #add Scienta if ioc is on - if EA.connected: - det_dict.update({17:EA._statsPlugin+"Total_RBV"}) - - #add detectors related to beamline - if iex.BL.xrays: - det_dict.update(xrays_detector_dictionary()) - - return det_dict - -def _ARPES_motor_dictionary(): - """ - returns a dictionary with {name:[rbv,val,spmg,pv]} - """ - p = '29idc:m' - motor_nums = {'x': 1, - 'y':2, - 'z':3, - 'th':4, - 'chi':5, - 'phi':6, - } - - motor_dictionary={} - for name in motor_nums.keys(): - pv = '29idc:m'+str(motor_nums[name]) - motor_dictionary.update({name:[pv+'.RBV',pv+'.VAL',pv+'.SPMG',pv]}) - - return motor_dictionary - -def ARPES_extra_pvs(): - """ - used to get the PV associated with a given pnuemonic - - """ - d={ - "SES_slit":"29idc:m8.RBV", - "TA":"29idARPES:LS335:TC1:IN1", - "TB":"29idARPES:LS335:TC1:IN2", - "tey1":"29idc:ca1:read", - "tey2":"29idc:ca2:read", - } - return d - -############################################################################################################## -############################## setting folder ############################## -############################################################################################################## -def folders_ARPES(user_name,**kwargs): - """ - Create and sets (if create_only=False) all the folders the current run and ARPES user - Sets the FileName for logging to be "UserName/YYYYMMDD_log.txt using logname_Set()" - - **kwargs: - set_folders = True (default); set the mda and EA scanRecords - = False; only makes the folders (was create_only) - run: run cycle e.g. 2022_1 (default => check_run() ) - ftp = True / False (default); print what needs to be added to the ftps crontab and create additional ftp folders - mda_ioc: will overwrite the default ioc for mda scans - debug - - """ - kwargs.setdefault('set_folders',True) - kwargs.setdefault('run',check_run()) - kwargs.setdefault('scan_ioc',default_ioc) - kwargs.setdefault('ftp',False) - kwargs.setdefault('debug',False) - - run = kwargs['run'] - - if kwargs['debug']: - print("run,folder,user_name,ioc,ftp: ",run,iex.BL.folder,user_name,kwargs['scan_ioc'],kwargs['ftp']) - - # Create User Folder: - make_user_folders(run,iex.BL.folder,user_name,iex.BL.endstation_name,ftp=kwargs['ftp']) - sleep(5) - - if kwargs["set_folders"]: - # Set up MDA folder: - folder_mda(run,iex.BL.folder,user_name,iex.BL.prefix,iex.BL.ioc) - - #Set up Scienta folders: - if EA.connected: - userPath = path_dserv(iex.BL.folder,run,user_name) - try: - folders_EA(userPath,filePrefix="EA") - except: - print("EA folder not set; need to be 29id to create folder on the dserv") - else: - print_warning_message("EA ioc is not running, h5 folder not set") - -def ARPES_default_scan_setting(): - """ - default setting for scan record - Note: only get set if ARPES_reset is run - """ - #writing default parameters to iex.BL.mda - - iex.BL.mda.detector_dictionary = _ARPES_detector_dictionary() - if iex.BL.mode=='staff': - iex.BL.mda.detector_dictionary.update(staff_detector_dictionary()) - - iex.BL.mda.trigger_dictionary = _ARPES_trigger_dictionary() - iex.BL.mda.before_scan_pv = _ARPES_scan_before_sequence() - iex.BL.mda.after_scan_pv = _ARPES_scan_after_sequence() - iex.BL.mda.snake_set = ARPES_snake_set #sending the function, no parenthesis - - #set the logfile name - iex.BL.mda.log.name_set() - -def ARPES_reset(): - """ - resets scanRecord, current amplifiers, mono limits and lakeshore - """ - #resetting the scanRecord - print("resetting the scanRecord - "+iex.BL.ioc) - iex.BL.mda.reset_all() - - #resetting the current amplifiers - print("resetting the current amplifiers") - if iex.BL.xrays: - ca_reset_all() - else: - tey.reset() - - #resetting mono and other beamline stuff - if iex.BL.xrays: - _xrays_reset() - - #reseting the ARPES Lakeshore - pv = "29idARPES:LS335:" - LS_355_defaults = { - "TC1:read.SCAN":".5 second", - "TC1:OUT1:Cntrl":"A", - "TC1:OUT2:Cntrl":"B", - "TC1:OUT1:Mode":"Closed Loop" - } - print("resetting ARPES Lakeshore") - Lakeshore_reset(pv,LS_355_defaults) - - - -############################################################################################################## -############################## get all ############################## -############################################################################################################## -def ARPES_get_all(verbose=True): - """ - returns a dictionary with the current status of the ARPES endstation and exit slit - """ - vals={} - if verbose: - print("\n===========================================================") - #sample position - motor_dictionary = _ARPES_motor_dictionary() - for motor in motor_dictionary.keys(): - vals[motor]=ARPES_Motors.get(motor,verbose=False) - #endstation/branch pvs - extra_pvs = ARPES_extra_pvs() - for key in extra_pvs.keys(): - vals.update(key,caget(extra_pvs[key])) - if iex.BL.xrays: - vals.update('exit_slit',slit3C_get()) - if verbose: - for key in vals: - print(key+" = "+vals[key]) - - #beamline info - if iex.BL.xray: - beamline_info = xrays_get_all() - vals.update(beamline_info) - if verbose: - print("-----------------------------------------------------------") - for key in beamline_info: - print(key+" = "+beamline_info[key]) - print("-----------------------------------------------------------") - - if verbose: - print("\n===========================================================") - - return vals - - - -############################################################################################################## -############################## logging ############################## -############################################################################################################## -def _ARPES_log_header(): - header_list={ - 'EA': "scan,x,y,z,th,chi,phi,T,scan_mode,E1,E2,step,i,f,PE,lens_mode,SES slit #,hv,exit_slit,GRT,ID_SP,ID_RBV,ID_Mode,ID_QP,TEY1,TEY2,time,comment", - 'ARPES':"scan,motor,start,stop,step,x,y,z,th,chi,phi,T,hv,exit_slit,GRT,ID_SP,ID_RBV,ID_Mode,ID_QP,TEY_1,TEY_2,time,comment" - } - return header_list - -def _ARPES_log_dictionary(): - """ - endstation info for log file - - Previously: scanlog - """ - #header: pv, format - d={ - "x":(ARPES_Motors.get('x'),".2f"), - "y":(ARPES_Motors.get('y'),".2f"), - "z":(ARPES_Motors.get('z'),".2f"), - "th":(ARPES_Motors.get('th'),".2f"), - "chi":(ARPES_Motors.get('chi'),".2f"), - "phi":(ARPES_Motors.get('phi'),".2f"), - "TA":(caget(ARPES_extra_pvs()['TA']),".2f"), - "TB":(caget(ARPES_extra_pvs()['TB']),".2f"), - "tey1":(caget(ARPES_extra_pvs()['tey1']),"1.2e"), - "tey2":(caget(ARPES_extra_pvs()['tey2']),"1.2e") - } - - if iex.BL.xrays == True: - d.update(xrays_log_dictionary()) - - return d - -############################################################################################################## -############################## ARPES scanRecord ############################## -############################################################################################################## -def _ARPES_scan_before_sequence(**kwargs): - """ - writes the user string sequence to happen at the beginning of a scan - returns before_scan_pv = pv for userStringSeq for before scan - - **kwargs - seq_num: userStringSeq number in ioc => 9 (default) - - Previously: BeforeScan_StrSeq - """ - kwargs.setdefault('seq_num',9) - seq_num=kwargs['seq_num'] - - scan_ioc = iex.BL.ioc - - before_scan_pv,before_scan_proc = userStringSeq_pvs(scan_ioc,seq_num) - - #clear and write the before scan user sequence - userStringSeq_clear(scan_ioc,seq_num) - caput(before_scan_pv+".DESC","Before Scan") - - #sequence put CAs in passive - ca_list = _ARPES_ca_list() - for (i,ca) in enumerate(ca_list): - ca_pv = _Keithley_pv(ca[0], ca[1])+'read.SCAN PP NMS' - caput(before_scan_pv+".LNK" +str(i+1),ca_pv) - caput(before_scan_pv+".STR" +str(i+1),"Passive") - - return before_scan_proc - -def _ARPES_ca_live_sequence(**kwargs): - """ - """ - kwargs.setdefault('seq_num',7) - - ca_live_sequence_proc = _ca_live_sequence(iex.BL.ioc,kwargs['seq_num'],_ARPES_ca_list()) - return ca_live_sequence_proc - -def _ARPES_scan_after_pvs(clear=False,**kwargs): - """ - _ARPES_scan_after_sequence pv - - """ - kwargs.setdefault('seq_num',10) - seq_num = kwargs['seq_num'] - - scan_ioc = iex.BL.ioc - - after_scan_pv,after_scan_proc = userStringSeq_pvs(scan_ioc, seq_num) - - if clear: - userStringSeq_clear(scan_ioc,seq_num) - return after_scan_pv,after_scan_proc - -def _ARPES_scan_after_sequence(**kwargs): - """ - writes the user string sequence to happen at the end of a scan - returns after_scan_pv = pv for userStringSeq for after scan - - **kwargs - seq_num: userStringSeq number in ioc => 10 (default) - snake: for snake scanning => False (default) - Previously: AfterScan_StrSeq - """ - - kwargs.setdefault('scan_dim',1) - scan_dim = kwargs['scan_dim'] - - #clear and write the after scan user sequence - after_scan_pv,after_scan_proc = _ARPES_scan_after_pvs(clear=True,**kwargs) - - caput(after_scan_pv+".DESC","After Scan") - - ## Put All relevant CA back in live mode - ca_live_sequence_proc = _ARPES_ca_live_sequence(**kwargs) - caput(after_scan_pv+".LNK1",ca_live_sequence_proc+" NP NMS") - caput(after_scan_pv+".DO1",1) - - scan_pv = iex.BL.ioc+"scan"+str(scan_dim) - ## Put scan record back in absolute mode - caput(after_scan_pv+".LNK2",scan_pv+".P1AR") - caput(after_scan_pv+".STR2","ABSOLUTE") - - ## Put Positionner Settling time to 0.1s - caput(after_scan_pv+".LNK3",scan_pv+".PDLY NPP NMS") - caput(after_scan_pv+".DO3",0.1) - - ## Clear DetTriggers 2: - caput(after_scan_pv+".LNK4",scan_pv+".T2PV NPP NMS") #remove trigger 2 (used for EA) after scan - caput(after_scan_pv+".STR4","") - - ##Snake goes in LNKA (10) - - return after_scan_proc - - -def _ARPES_detector_triggers_sequence(**kwargs): - """ - """ - kwargs.setdefault('seq_num',8) - seq_num=kwargs['seq_num'] - - scan_ioc = iex.BL.ioc - detector_triggers_pv,detector_triggers_proc = userStringSeq_pvs(scan_ioc, seq_num) - - #clear the userStringSeq - userStringSeq_clear(scan_ioc, seq_num) - caput(detector_triggers_pv+".DESC","ARPES_Trigger1") - - ca_list = _ARPES_ca_list() - last = len(ca_list) - for i,ca in enumerate(ca_list): - ca_pv = _Keithley_pv(ca[0], ca[1])+':read.PROC CA NMS' - caput(detector_triggers_pv+".LNK" +str(i+1),ca_pv) - caput(detector_triggers_pv+".WAIT"+str(i+1),"After"+str(last)) - - return detector_triggers_proc - -def _ARPES_trigger_dictionary(**kwargs): - """ - need to do something - """ - trigger_dictionary = { - 1:_ARPES_detector_triggers_sequence(**kwargs), - } - return trigger_dictionary - -def _ARPES_snake_userCalc(**kwargs): - """ - used to flip the sign of the step after a scan - snake scans as opposed to typewriter scans - """ - kwargs.setdefault('seq_num',10) - kwargs.setdefault('scan_dim',1) - - seq_num=kwargs['seq_num'] - scan_ioc = iex.BL.ioc - - userCalc_clear(scan_ioc,seq_num) - snake_userCalc_pv,snake_userCalc_proc = userCalcs_pvs(scan_ioc, seq_num) - - scan_step_pv = scan_ioc+'scan'+str(kwargs['scan_dim'])+'.P1SI NP NMS' - - caput(snake_userCalc_pv+'.DESC','snake_calc'), - caput(snake_userCalc_pv+'.SCAN','I/O Intr'), - caput(snake_userCalc_pv+'.INAN',scan_step_pv) - caput(snake_userCalc_pv+'.B',"-1") - caput(snake_userCalc_pv+'.CALC$',"A*B") - - return snake_userCalc_pv+'.VAL' - -def ARPES_snake_set(snake,**kwargs): - """ - used for snake scanning - """ - kwargs.setdefault('scan_dim',1) - scan_ioc = iex.BL.mda.ioc - after_scan_pv,after_scan_proc = _ARPES_scan_after_pvs() - - scan_step_pv = scan_ioc+'scan'+str(kwargs['scan_dim'])+'.P1SI NP NMS' - - if snake: - caput(after_scan_pv+".LNKA",scan_step_pv) - caput(after_scan_pv+".DOLA",_ARPES_snake_userCalc()+" NP") - else: - caput(after_scan_pv+".LNKA","") - caput(after_scan_pv+".DOA","") -############################################################################################################## -############################## ARPES Motor Endcoders ############################## -############################################################################################################## -def ARPES_motor_encoder_sync(): - ioc = "29idc:" - for motor in [1,2,3,4]: - pv = ioc+"m"+str(motor)+".SYNC" - caput(pv,1) - print("synch encoder: "+pv) - - - - -#################################################################################################### -################ ARPES Positions (LEED,transfer, measure) ##################################### -##################################################################################################### -def _ARPES_DefaultPosition(destination): - """ - Default ARPES positions in DIAL units - """ - DefaultPosition={ - '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), - 'transfer':(-0,0.0,-141.5,180.0,0.0,0.0), - } - if destination in DefaultPosition: - pos=DefaultPosition[destination] - else: - pos=(None,None,None,None,None,None) - return pos - -def _ARPES_MoveSequence(destination): - """ - Moves the ARPES manipulator x,y,z,th to a given destination (does not change chi or phi) - Resets the limits to help protect from crashes - such as: phi/chi motor body into the strong back, manipulator into the LEED, manipulator into the wobble stick - - DO NOT MAKE BIG MOVE WITH OUT WATCHING THE MANIPULATOR!!!! - if the theta encoder stops reading the manipulator will CRASH!!!! - """ - (x,y,z,th,chi,phi)=_ARPES_DefaultPosition(destination) - motor_dictionary = _ARPES_motor_dictionary() - if x is None: - print("Not a valid destination") - else: - #reset limits to default values - _ARPES_limits_set(None) - #print destination - print(("Moving to "+destination+": "+str(round(x,1))+","+str(round(y,1))+","+str(round(z,1))+","+str(round(th,1)))+' Time:'+time.strftime("%H:%M")) - # move x and y to zero for all moves (helps protect the motors from crashing into the strong back) - caput(motor_dictionary['x'][3]+".DVAL",0,wait=True,timeout=18000) - caput(motor_dictionary['y'][3]+".DVAL",0,wait=True,timeout=18000) - # moves z and th simultaneously and monitors the .DMOV - caput(motor_dictionary['z'][3]+".DVAL",z,wait=False,timeout=18000) - caput(motor_dictionary['th'][3]+".DVAL",th,wait=False,timeout=18000) - while True: - sleep(5) - Test=caget(motor_dictionary['z'][3]+".DMOV")*caget(motor_dictionary['th'][3]+".DMOV") - if(Test==1): - break - # move x and y to final position - caput(motor_dictionary['x'][3]+".DVAL",x,wait=True,timeout=18000) - caput(motor_dictionary['y'][3]+".DVAL",y,wait=True,timeout=18000) - print(("Arrived at "+destination+": "+str(round(x,1))+","+str(round(y,1))+","+str(round(z,1))+","+str(round(th,1)))+' Time:'+time.strftime("%H:%M")) - #set the limits for this position - _ARPES_limits_set(destination) - -def _ARPES_limits_set(destination): - """ - Resets the ARPES motor limits in Dial cooridinates(remember that z is negative) - destination: 'measures' or 'LEED', - else: sets to the full range - ARPES_MoveSequence(destination) minimizes that chance of a crash and sets limits - - Previously: ARPES_LimitsSet - """ - motor_dictionary = _ARPES_motor_dictionary() - if destination == 'measure': - (x,y,z,th,chi,phi)=_ARPES_DefaultPosition("measure") - limits={'x':[5.5,-7],'y':[7,-5],'z':[-6,-310],'th':[th+35,th-25],'chi':[45,-15],'phi':[120,-120]} - elif destination == 'LEED': - (x,y,z,th,chi,phi)=_ARPES_DefaultPosition("LEED") - limits={'x':[5.5,-7],'y':[6,-1],'z':[z+5,z-5],'th':[th+2,th-2],'chi':[45,-15],'phi':[120,-120]} - else: - limits={'x':[5.5,-7],'y':[7,-5],'z':[-6,-310],'th':[240,-70],'chi':[45,-15],'phi':[120,-120]} - #setting the limits for each motor in Dial - for m in limits: - caput(motor_dictionary[m][3]+'.DHLM',limits[m][0]) - caput(motor_dictionary[m][3]+'.DLLM',limits[m][1]) - if destination is not None: - print("Limits have been reset for "+destination+" position") - else: - print("Limits have been reset for full range") -#################################################################################################### -def ARPES_transfer(chi=0,phi=0,**kwargs): - """ - Moves the ARPES manipulator to the default transfer position - kwargs: - EA_off = True (default); Turns off the EA HV - shutter_close = True (default); closes the C-shutter and the C-valve (main chamber to BL) - valve_close = True (default) - """ - _ARPESgo2("transfer",**kwargs) - -def ARPES_measure(**kwargs): - """ - Moves to ARPES motors x,y,z,th to the default measurement position - kwargs - - kwargs: - EA_off = True (default); Turns off the EA HV - shutter_close = True (default); closes the C-shutter and the C-valve (main chamber to BL) - valve_close = True (default) - - chi = None (default, no change); specify a value to move chi - phi=None (default, no change; specifiy a value to move phi - """ - _ARPESgo2("measure",**kwargs) - -def ARPES_LEED(**kwargs): - """ - Moves to ARPES motors x,y,z,th to the default LEED position - kwargs: - EA_off = True (default); Turns off the EA HV - shutter_close = True (default); closes the C-shutter and the C-valve (main chamber to BL) - valve_close = True (default) - - chi = None (default, no change); specify a value to move chi - phi=None (default, no change; specifiy a value to move phi - """ - _ARPESgo2("LEED",**kwargs) -#################################################################################################### -def _ARPESgo2(destination,**kwargs): - """ - Moves the ARPES manipulator to the default position: - destination: "transfer", "measure", "LEED" - - kwargs: - EA_off = True; turns off EA HV - shutter_close = True; closes the C-shutter - valve_close = True; closes the C-valve - - chi=None => doesn't move, otherwise specify a value to move chi - phi=None => doesn't move, otherwise specifiy a value to move phi - - """ - - - kwargs.setdefault("EA_off",True) - kwargs.setdefault("shutter_close",True) - kwargs.setdefault("valve_close",True) - - kwargs.setdefault("chi",None) - kwargs.setdefault("phi",None) - - ARPES_safe_state(**kwargs) - - #Move x,y,z,th - _ARPES_MoveSequence(destination) - #Move chi and phi back to 0 - motor_dictionary = _ARPES_motor_dictionary() - if kwargs["chi"] is not None: - caput(motor_dictionary['chi'][1],kwargs["chi"]) - if kwargs["phi"] is not None: - caput(motor_dictionary['phi'][1],kwargs["phi"]) - - -############################################################################################################## -############################## ARPES pvs for GUIs (caQtDM) ############################## -############################################################################################################## -def _ARPES_StringCalc_trigger2_active(): - """ - setup a string calc to be used by caQtDM to indicate that the trigger 2 is filled - """ - ioc="29idARPES:" - pv=ioc+"userStringCalc2" - caput(pv+".DESC","scan1 trigger2 calc") - caput(pv+".INAA",ioc+"scan1.T2PV CP NMS") - caput(pv+".CALC$","AA") - - caput(ioc+"userStringCalcEnable.VAL","Enable") - - - -############################################################################################################## -############################## ARPES safestate ############################## -############################################################################################################## -def ARPES_safe_state(**kwargs): - """ - puts the C-branch in a safe state, - **kwargs - EA_off = True; turns off EA HV - shutter_close = True; closes the C-shutter - valve_close = True; closes the C-valve - """ - kwargs.setdefault("EA_off",True) - kwargs.setdefault("shutter_close",True) - kwargs.setdefault("valve_close",True) - - global EA - - if kwargs["EA_off"]: - if EA.connected: - EA.off(quiet=False) - else: - print('EA is not running, visually confirm HV is off') - - if kwargs['shutter_close']: - branch_shutter_close() - - if kwargs['valve_close']: - branch_valve_close() - - - -############################################################################################################## -############################## ARPES motors ############################## -############################################################################################################## -def mvfocus(x_val): - """ - Moves APPES x and compensates y motor so that the beam stays in the same sample position but the focus is moved - """ - x_delta = x_val - ARPES_Motors.get('x') - y_delta = x_delta * np.tan(55/180*np.pi) - y_val = ARPES_Motors.get('y') + y_delta - - ARPES_Motors.move("x",x_val) - ARPES_Motors.move("y",y_val) - - return x_val,y_val - -def mvy_fixed_focus(y_val): - """ - Moves APPES x and compensates y motor so that the beam stays in the same sample position but the focus is moved - """ - y_delta = y_val - ARPES_Motors.get('y') - x_delta = y_delta / np.tan(55/180*np.pi) - x_val = ARPES_Motors.get('x') + x_delta - - ARPES_Motors.move("x",x_val) - ARPES_Motors.move("y",y_val) - return x_val,y_val - -def scanfocus(x_start,x_stop,x_step,**kwargs): - """ - Scans APPES x and compensates y motor so that the beam stays in the same sample position - y=x*tan(55) - - kwargs: - execute: True/False to start the scan => True (default) - """ - kwargs.setdefault('execute',True) - - - -def ARPES_map_sample(y_start=-2,y_stop=2,y_step=0.5,z_start=12,z_stop=16,z_step=0.5,**kwargs): - """ - 2D map of sample area in ARPES chamber - - *kwargs - snake: True (default); otherwise a typewriter scan - comment: to add a comment to the end of the meta data in the logfile - relative: True to scan relatively from current position - - Previously: Map_ARPES_Sample - """ - kwargs.setdefault('snake',True) - ARPES_Motors.scan_2D(["y",y_start,y_stop,y_step],["z",z_start,z_stop,z_step],**kwargs) - diff --git a/build/lib/iexcode/instruments/FMB_mirrors.py b/build/lib/iexcode/instruments/FMB_mirrors.py deleted file mode 100644 index 5af10702dc9fc621863cb0b57556b199f8c3f8b6..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/FMB_mirrors.py +++ /dev/null @@ -1,171 +0,0 @@ -from time import sleep - -from epics import caget, caput - -import iexcode.instruments.cfg as iex -from iexcode.instruments.utilities import read_dict, print_warning_message - -M0M1_fpath="/home/beams22/29IDUSER/Documents/User_Macros/Macros_29id/IEX_Dictionaries/Dict_IDCal.txt" - -def _FMB_mirror_ioc(mirror_num): - """ - returns the ioc name for the given mirror number: - miror_num = 0 / 1 / 3 for M0 / M1 /M3R respectively - """ - ioc = '29id_'+['m0','m1','','m3r'][mirror_num]+":" - return ioc - -def FMB_mirror_status(mirror_num): - """ - returns the ioc name for the given mirror number: - miror_num = 0 / 1 / 3 for M0 / M1 /M3R respectively - - status =1 when positioned - """ - ioc = '29id_'+['m0','m1','','m3r'][mirror_num]+":" - pv = _FMB_mirror_ioc(mirror_num) - status=caget(pv+'SYSTEM_STS') - - return status - -def FMB_mirror_axis_position(mirror_num,axis, verbose=True): - """ - returns the readback and set point of an FMB mirror - """ - pv = _FMB_mirror_ioc(mirror_num) - - rbv = round(caget(pv+axis+"_MON"),3) - sp = round(caget(pv+axis+"_POS_SP"),3) - - if verbose: - print (pv+axis+": "+str(rbv)) - - return rbv,sp - -def FMB_mirror_get(mirror_num,verbose=True): - """ - get and returns the current mirror position - """ - axis_labels=['TX','TY','TX','RX','RY','RZ'] - vals=[] - message = "\nM"+str(mirror_num)+" @ " - for axis in axis_labels: - rbv,sp = FMB_mirror_axis_position(mirror_num,axis, verbose=False) - vals.append(round(rbv,3)) - message = message + str(round(rbv,3))+"/" - if verbose: - print(message[0:-1]) # to not have the last / - return vals - -def FMB_mirror_move(mirror_num,axis,val,verbose=True): - """ - miror_num = 0 / 1 / 3 for M0 / M1 /M3R respectively - and axis: - TX = lateral RX = Roll - TY = vertical RY = Pitch - TZ = longitudinal RZ = Yaw - - "Previously: Move_M0M1 - """ - pv = _FMB_mirror_ioc(mirror_num) - axes = ['TX','TY','TZ','RX','RY','RZ'] - if axis in axes: - caput(pv+axis+"_SP.PREC",3) - caput(pv+axis+"_POS_SP",val) - caput(pv+"MOVE_CMD.PROC",1,wait=True,timeout=18000) - while True: - if FMB_mirror_status(mirror_num) != 1: - sleep(.5) - else: - break - FMB_mirror_axis_position(mirror_num,axis,verbose=verbose) - - else: - print_warning_message(axis+' is not a valid axis chose '+axes) - -def FMB_mirror_move_all(mirror_num,position_list,verbose=True,execute=True): - """ - miror_num = 0 / 1 / 3 for M0 / M1 /M3R respectively - position_list = [TX,TY,TZ,RX,RY,RZ] - - "Previously: Move_M0M1 - """ - pv = _FMB_mirror_ioc(mirror_num) - for i, axis in enumerate(['TX','TY','TZ','RX','RY','RZ']): - caput(pv+axis+"_SP.PREC",3) - caput(pv+axis+"_POS_SP",position_list[i]) - sleep(.5) - if execute: - caput(pv+"MOVE_CMD.PROC",1,wait=True,timeout=18000) - while True: - if FMB_mirror_status(mirror_num) != 1: - sleep(.5) - else: - break - FMB_mirror_axis_position(mirror_num,axis,verbose=verbose) - - -def FMB_mirror_tweak(mirror_num,axis,val,verbose=False): - """ - miror_num = 0 / 1 / 3 for M0 / M1 /M3R respectively - and axis: - TX = lateral RX = Roll - TY = vertical RY = Pitch - TZ = longitudinal RZ = Yaw - - "Previously: Move_M0M1 - """ - pv = _FMB_mirror_ioc(mirror_num) - previous_position = FMB_mirror_axis_position(mirror_num,axis,verbose=False) - new_position = previous_position[0] + val - FMB_mirror_move(mirror_num,axis,new_position,verbose=False) - - if verbose: - print(pv+" "+str(previous_position[0])+" -> "+str(new_position[0])) - - -def FMB_mirror_scan(mirror_num,start,stop,step): - """ - e.g. Scan_FMB_mirror("m1:TX",-5,5,.25) - - TX = lateral RX = Yaw - TY = vertical RY = Pitch - TZ = longitudinal RZ = Roll - """ - pv = _FMB_mirror_ioc(mirror_num) - - # database sets .PREC==0. We want more digits than that. - caput(pv+"_SP.PREC",3) - iex.BL.mda.fillin(pv+"_SP",pv+"_MON",start,stop,step) - - - - -def M0M1_table(run,mirror): - """ - Prints the positions TX / TY / TZ / RX / RY / RZ for either Mirror = 0 or 1 (M0 or M1) for the specified Run - Run='default' give a reasonable starting position after homing - M0M1_SP() will put those values as the set points, you will need to push the Move button - """ - M0M1_Pos=read_dict(M0M1_fpath) - return M0M1_Pos[run][mirror[-1]] - -def M0M1_SP(run,mirror,Go=False): - """ - Gets the values from the mirror position from a previous run and - put values as defined by M0M1_Table as the set points - Go = True / False (default); True to moves to that position - """ - mirror_pos=M0M1_table(run,mirror).split('/') - motor=['TX','TY','TZ','RX','RY','RZ'] - mirror=mirror[-1] - for i in range(len(motor)): - PV="29id_m"+str(mirror)+":"+motor[i]+"_POS_SP" - Val=mirror_pos[i] #float(MirrorPos[i]) - print(PV+" = "+Val) - caput(PV,Val) - sleep(0.5) - if Go: - caput('29id_m'+str(mirror)+':MOVE_CMD.PROC',0,wait=True,timeout=18000) - else: - print(" caput(\'29id_m"+str(mirror)+":MOVE_CMD.PROC\',0)") diff --git a/build/lib/iexcode/instruments/IEX_VPU.py b/build/lib/iexcode/instruments/IEX_VPU.py deleted file mode 100644 index 9f850fdf9c2647375a9d8b690e180a2e7ae350fb..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/IEX_VPU.py +++ /dev/null @@ -1,605 +0,0 @@ -from os import path -from math import * -from time import sleep -import numpy.polynomial.polynomial as poly - -from epics import caget, caput - -import iexcode.instruments.cfg as iex -from iexcode.instruments.userCalcs import userCalcOut_clear -from iexcode.instruments.utilities import dateandtime, print_warning_message, read_dict -from iexcode.instruments.VLS_PGM import mono_grating_get -from iexcode.instruments.shutters import shutter_check - -IDcal_path="/home/beams22/29IDUSER/Documents/User_Macros/Macros_29id/IEX_Dictionaries" - -############################################################################################################## -################################ ID limits and calibration ############################## -############################################################################################################## -def ID_pvs(): - """ - dictionary of ID pvs - """ - pv = 'ID29:' - pvs={'AccessSecurity':pv+'AccessSecurity.VAL', - 'mode_rbv':pv+'ActualMode', - 'mode_val':pv+'DesiredMode.VAL', - 'check_ready':pv+'feedback.VAL', - 'check_busy':pv+'BusyRecord', - 'busy_reset':pv+'Busy.VAL', - 'main_power':pv+'Main_on_off.VAL', - 'energy_rbv':pv+'Energy.VAL', - 'energy_sp':pv+'EnergySet.VAL', - 'start_ramp':pv+'StartRamp.VAL', - 'energy_eV_rbv':pv+'EnergyRBV', - 'energy_eV_sp':pv+'EnergyScanSeteV', - 'scan_val':pv+'EnergyScanSet.VAL', - 'scan_val_eV':pv+'EnergyScanSeteV', - 'table_dir':pv+'TableDirection', - 'By_q':pv+'ByqRdbk', - 'Bx_q':pv+'BxqRdbk', - 'Vcoil':pv+'ByRdbk.VAL', - 'Hcoil':pv+'BxRdbk.VAL', - 'QP_ratio':pv+'QuasiRatio.RVAL',} - return pvs - - -def ID_calc_eV(mono_grating,ID_mode,hv_eV,QP_ratio): # Mode = state (0=RCP,1=LCP,2=V,3=H) - """Calculate the ID SP for a given polarization mode and energy; - with Mode = 0 (RCP),1 (LCP), 2 (V), 3 (H) - - Previously: ID_Calc - """ - if type(ID_mode)== str: - ID_state=ID_state_mode(ID_mode) - try: - K=ID_coef(mono_grating,ID_state,hv_eV,QP_ratio) - ID=poly.polyval(hv_eV,K) - except KeyError: - message_string='Not a valid ID mode!'+"\nValid Modes: "+str(ID_mode_list()) - print_warning_message(message_string) - ID=caget(ID_pvs()['energy_rbv']) - return round(ID,1) - -############################################################################################################## -################################ ID Functions ############################## -############################################################################################################## - - -def ID_wait_for_permission(verbose=True): - """ - Monitors the ID permissions and waits for the ID to be in User Mode and then breaks - Checks the status every 30 seconds - - Previously: WaitForPermission - """ - while True: - ID_Access=caget(ID_pvs()['AccessSecurity']) - if (ID_Access!=0): - print("Checking ID permission, please wait..."+dateandtime()) - sleep(30) - else: - if verbose: - print("ID now in user mode -"+dateandtime()) - break - -############################################################################################################## -def ID_get_all(verbose=False): - """ - returns dictionary with: ID_Mode, ID_QP_ratio, ID_SP, ID_RBV - - Previously: Get_energy - """ - vals={ - "ID_mode":ID_mode_get(verbose=False), - "ID_QP_ratio":ID_QP_ratio_get(verbose=False), - "ID_sp":ID_get_sp(verbose=False), - "ID_rbv":ID_get_rbv_eV(verbose=False) - } - - if verbose: - print(" ID SP : "+"%.2f" % vals["ID_sp"] , "eV ID mode : "+vals["ID_mode"]) - print(" ID RBV : "+"%.2f" % vals['ID_rbv'], "eV QP mode : "+str(vals['ID_QP_ratio']) +" %") - return vals - -def ID_energy_range(ID_mode=None): - """ - Returns the ID_min_SP, ID_max_SP in keV for a given ID mode - - Previously: ID_Range - """ - if ID_mode == None: - ID_state=caget(ID_pvs()['mode_rbv']) - else: - ID_state = ID_state_mode(ID_mode) - # RCP,LCP, V , H , HN - ID_min_SP = [.400,.400,.440,.250,.250] - ID_max_SP = 3.800 - return ID_min_SP[ID_state],ID_max_SP - -def ID_energy_range_eV(ID_mode=None): - """ - Returns the ID_min_SP, ID_max_SP in eV for a given ID mode - - Previously: ID_Range - """ - ID_min_keV, ID_max_keV = ID_energy_range(ID_mode) - return ID_min_keV*1000.0, ID_max_keV*1000.0 - -def ID_mode_list(): - """ - returns the ID_mode_List - current mode = - """ - return ["RCP", "LCP", "V", "H", "HN"] - - -def ID_state_mode(ID_mode): - """ - Returns the state number if mode is a string - Returns the mode string if mode is an int or float - - Previously: ID_State2Mode(which,mode) - """ - try: - ID_mode = ID_mode.upper() - ID_state =ID_mode_list().index(ID_mode) - return ID_state - - except: - message_string='Not a valid ID mode!'+"\nValid Modes: "+str(ID_mode_list()) - print_warning_message(message_string) - -def ID_state_get(): - """ - Returns the current ID state - """ - ID_state = caget(ID_pvs()['mode_rbv']) - return ID_state - -def ID_mode_get(verbose=True): - """ - Returns the current ID mode - """ - ID_state =ID_state_get() - ID_mode = ID_mode_list()[ID_state] - - if verbose: - print('ID mode: '+ID_mode) - return ID_mode - -def ID_mode_set(ID_mode): - """ - writes the desired mode to the correct ID pv - """ - if ID_mode in ID_mode_list(): - ID_state = ID_mode_list().index(ID_mode) - caput(ID_pvs()['mode_val'],ID_state,wait=True,timeout=18000) - sleep(1) - else: - print_warning_message('ID_mode not in '+str(ID_mode_list())) - - -def ID_ready(verbose=False): - """ - check both the read and busy pv every 2 seconds - - Previously: ID_Ready - """ - while True: - RBV = caget(ID_pvs()['energy_rbv']) - checkready = caget(ID_pvs()['check_ready']) - checkbusy = caget(ID_pvs()['check_busy'],as_string=True) - if (checkready!="Ready"): - #print('checkready',checkready) - sleep(2) - if checkbusy=="Busy": - sleep(2) - #print('checkbusy',checkbusy) - else: - if RBV > 3.7: - #thinks its done but isn't, need to reset busy - caput(ID_pvs()['busy_reset'],0) - sleep(2) - if verbose: - print('resetting ID busy record') - else: - if verbose: - print("ID Ready") - return True - -def ID_power_status(): - """ - gets if the ID power supplies are On or Off - """ - ID_OnOff=caget(ID_pvs()['main_power'],as_string=True) - return ID_OnOff - -def ID_off(verbose=True): - """ - waits for permission then turns on the main coils OFF - """ - ID_wait_for_permission(verbose=False) - ID_ready() - - caput(ID_pvs()['main_power'],'Off',wait=True,timeout=18000) - sleep(5) - if verbose: - print("ID is now off") - - -def ID_on(verbose=True): - print("Starting ID - "+dateandtime()) - - #caput(ID_pvs()['energy_sp'],3.8) - caput(ID_pvs()['main_power'],'On',wait=True,timeout=18000) - sleep(5) - -def ID_start(ID_mode='RCP',QP_ratio=None, verbose=True): - """ - waits for ID permission and then - starts ID with a specific polarization - mode = \"H\", \"V\", \"RCP\" or \"LCP\" - QP ratio if specified - """ - #turns on if ID is off - if ID_power_status =='Off': - ID_on() - #set QP - if ID_ready(): - ID_QP_mode_set(QP_ratio,verbose) - #set ID mode - if ID_ready(): - ID_mode_set(ID_mode, verbose) - #opens the main shutter - if ID_ready(): - shutter_check(verbose) - - if verbose: - print('ID is now on, please set your energy') - -def ID_switch_mode(ID_mode): - """ - Change ID polarization; which = 'H', 'V', 'RCP' or 'LCP' - if ID_mode = current mode then does nothing - - WARNING: Does not set the energy - - Previously Switch_IDMode - """ - ID_wait_for_permission(verbose=False) - shutter_check(verbose=False) - ID_state = ID_state_get() - - if ID_state_mode(ID_mode) != ID_state: - print("Turning ID off...") - ID_off(verbose=True) - ID_ready() - - print("Switching ID mode, please wait...") - ID_on(verbose=True) - ID_mode_set(ID_mode) - ID_ready() - - if ID_mode_get() != ID_mode: - print_warning_message("ID mode switch had an error, please try again") - else: - print("ID Mode:",ID_mode_get()) - - -def ID_get(verbose=False): - """ - returns the readback value for the ID in keV - """ - ID_RBV = caget(ID_pvs()['energy_rbv']) - if verbose: - print("ID_RBV: ", ID_RBV) - return ID_RBV - -def ID_get_sp(verbose=False): - """ - returns the readback value for the ID in keV - """ - ID_SP = caget(ID_pvs()['energy_sp']) - if verbose: - print("ID_SP: ", ID_SP) - return ID_SP - -def ID_get_rbv_eV(verbose=False): - """ - returns the readback value for the - """ - ID_RBV = ID_get(verbose=False)*1000 - if verbose: - print("ID_RBV: ", ID_RBV) - return ID_RBV - -def ID_get_sp_eV(verbose=False): - """ - returns the setpoint value for the ID in eV - """ - ID_SP = ID_get_sp(verbose=False)*1000 - if verbose: - print("ID_SP: ", ID_SP) - return ID_SP - -def _ID_write_SP_proc(keV): - # pressing ramp button doesn't work - # ramp_delay=5 - # caput(ID_pvs()['energy_sp'],keV,wait=True,timeout=18000) - # sleep(ramp_delay) - # caput(ID_pvs()['start_ramp'],1,wait=True,timeout=18000) - caput(ID_pvs()['scan_val'],keV,wait=True,timeout=18000) - #caput(ID_pvs()['energy_sp'],keV,wait=True,timeout=18000) # just for bookkeeping - sleep(1) - - -def ID_set(keV,verbose=True): - """ - "Sets the ID set point to a specific value (hv(eV)) which will not likely be optimum" - - Previously: SetID_Raw - """ - - #check if I'm already there - ID_SP = round(ID_get_sp(verbose=False),3) - if round(keV,3) == ID_SP: - if verbose: - print("ID already at "+str(ID_SP)) - else: - - #checking permissions and opening the main shutter - ID_wait_for_permission(verbose=False) - shutter_check(verbose=False) - - #checking if desired is with allowed range, if not printing the nearest allowed value - ID_min,ID_max = ID_energy_range() - if keV < ID_min or keV > ID_max: - message_string="Set point out of BL energy range \nPlease select a different energy." - message_string+="\nClosest allowed value is "+str(min(max(keV,ID_min),ID_max)) - print_warning_message(message_string) - else: - #set energy sp and ramp - _ID_write_SP_proc(keV) - - ID_ready(verbose=False) - #run twice to make sure ready (sometime busy is weird and instantaneously give ready) - ID_ready(verbose=False) - - #check if ID within some bandwidth - # if _ID_bw_ok(keV): - # if verbose: - # ID_SP = ID_get_sp(verbose=False) - # ID_RBV = ID_get() - # print("ID SET : "+"%.1f" % ID_SP, "eV") - # print("ID RBV : "+"%.1f" % ID_RBV, "eV") - # print(caget(ID_pvs()['table_dir'],as_string=True)) - # else: - # print_warning_message("ID not within energy bandwidth") - # ID_QP_ratio_get(verbose) - -def ID_energy_set(keV,verbose=True): - """ - Sets optimum ID set point for hv(eV) (max intensity) - and opens the main shutter - - Note that QP is generally not calibrated - - Previously: SetID - """ - ID_mode = ID_mode_get(verbose=False) - mono_grating = mono_grating_get() - QP_ratio = ID_QP_ratio_get(verbose=False)[0] - eV = keV*1000.0 - keV = ID_calc_eV(mono_grating,ID_mode,eV,QP_ratio)/1000.0 - ID_set(keV,verbose=verbose) - -def ID_energy_set_eV(eV,verbose=True): - """ - Sets optimum ID set point for hv(eV) (max intensity) - and opens the main shutter - - Note that QP is generally not calibrated - - Previously: SetID - """ - keV = eV/1000.0 - print("setting ID = "+str(eV)+" ("+str(keV)+" keV)") - ID_energy_set(keV,verbose=verbose) - -def ID_set_eV(eV,verbose=True): - """ - Set the ID setpoint - """ - keV=eV/1000.0 - ID_set(keV,verbose=verbose) - -def ID_QP_ratio_get(verbose=True): - """ - gets the read back for the QP ratio - calculate the QP ratio - - """ - Byq=caget(ID_pvs()['By_q']) - Vcoil=caget(ID_pvs()['Vcoil']) - ratio_calc=round(Byq/Vcoil,3)*100 - ratio_RBV=caget(ID_pvs()['QP_ratio']) - if verbose: - print("QP RBV =", ratio_RBV,"%") - print("QP calculated ratio =", ratio_calc ,"%") - - - if abs(ratio_RBV-ratio_calc)>1: - message_string="QP RBV and QP calc do not agree \nCheck Interlocks" - print_warning_message(message_string) - return ratio_RBV, ratio_calc - -def ID_QP_mode_set(QP_ratio=None,verbose=True): - """ - switched to QP mode, if not currently in - sets the QP ratio (QP ratio min is 70) and polarization (ID mode) - - WARNING: you will need to set the polarization and mode afterward - - Previously: Switch_IDQP - """ - - #checking if above the minimum allowed value - QP_min = 70 - if QP_ratio < QP_min: - message_string="QP ratio is too small, setting it to minimum allowed value ("+str(QP_min)+")" - print_warning_message(message_string) - QP_ratio=min(100,max(70,QP_ratio)) - - if QP_ratio != None: - #checking to see if already in specified QP - ratio_RBV, ratio_calc = ID_QP_ratio_get() - #not the same ratio - if ratio_RBV != QP_ratio: - ID_off() - caput("ID29:QuasiRatioIn.C",QP_ratio) - sleep(1) - - ID_on() - sleep(15) - - -def ID_coef(grt,ID_state,hv_eV,QP_ratio): # Mode = state (0=RCP,1=LCP,2=V,3=H); - - """Return the ID coeff for a given polarization mode and energy; - with Mode = 0 (RCP),1 (LCP), 2 (V), 3 (H). - Current coefficient dictionary: - /home/beams22/29IDUSER/Documents/User_Macros/Macros_29id/IEX_Dictionaries/Dict_IDCal.txt - - Previously: ID_Coef - """ - - def ListRange(grt,ID_state,IDdict): # extract the list of break pts for a given mode/grt - tmp_list=[] - for item in (IDdict[grt][ID_state]): - tmp_list.append(item[0]) - return tmp_list - - - def FindRange(hv_eV,range_list): # returns the index for the corresponding range - B = [x - hv_eV for x in range_list] - #print(B) - index = [i for (i, x) in enumerate(B) if x > 0] - #print(index) - return(index[0]) - - if QP_ratio < 100.0: - if isinstance(QP_ratio,float) or isinstance(QP_ratio,int): - QP_ratio=str(floor(QP_ratio)) - dictfile='Dict_IDCal_QP'+QP_ratio+'.txt' - error_msg="calibration curve might not exist for this QP value" - else: - print('invalid QP value') - return - else: - dictfile='Dict_IDCal.txt' - error_msg="" - try: - IDcal_fpath = path.join(IDcal_path,dictfile) - ID_function=read_dict(IDcal_fpath) - - except KeyError: - print("Unable to read dictionary "+dictfile+" ; "+error_msg) - - try: - Lrange = ListRange(grt,ID_state,ID_function) - Erange = FindRange(hv_eV,Lrange) - K = ID_function[grt][ID_state][Erange][1] - return K - - except KeyError: - print("WARNING: PLease select one of the following: "+str(ID_mode_list())) - - -def ID_scan_pvs(): - """ - returns the rbv and val for scanning - """ - val_pv=ID_pvs()['scan_val_eV'] - rbv_pv="" - return val_pv, rbv_pv - -def ID_scan_fillin(start,stop,step,**kwargs): - """ - fills in the scanRecord for scanning the ID set point - - **kwargs => scanRecord.fillin kwargs - """ - #Setting up the ScanRecord for ID in Table mode - val_pv, rbv_pv = ID_scan_pvs() - iex.BL.mda.fillin(val_pv,rbv_pv,start,stop,step,**kwargs) - - -def ID_scan_fillin_table(ID_array,**kwargs): - """ - fills in the scanRecord for scanning the ID set point - - **kwargs => scanRecord.fillin kwargs - """ - #Setting up the ScanRecord for ID in Table mode - val_pv, rbv_pv = ID_scan_pvs() - iex.BL.mda.fillin_table(val_pv,rbv_pv,ID_array,**kwargs) - -############################################################################################################## -############################## ID direction table ############################## -############################################################################################################## - -def ID_Table(): - """ - - Previously: ID_Table - """ - table = caget("ID29:TableDirection") # up = 1 , down = 0 - By = caget("ID29:ByPolaritySet") # pos = 1, neg = 0 - - mode = ID_mode_get() - - if By > 0: - print("\nBy > 0") - if table == 1: # By=1, table = 1 => -1 => A=B - print("table = up") - ID_direction = -1 - elif table == 0: # By=1, table = 0 => +1 => A#B - print("table = down") - ID_direction = 1 - elif By <= 0: - print("\nBy < 0") - if table == 1: # By=0, table = 1 => +1 => A=B - print("table = up") - ID_direction = 1 - elif table == 0: # By=0, table = 0 => -1 => A#B - print("table = down") - ID_direction = -1 - - - if mode == "H" and mode == "RCP": - if By > 0 and table == 0: - print_warning_message("will do a long hysteresis if decreasing energy !!!") -# if Mode == "HN" and Mode == "LCP": -# if By = 0 and table == 1: -# print "WARNING: will do a long hysteresis if decreasing energy !!!" - print("ID direction", ID_direction) - return ID_direction - -def ID_table_userCalcOut(): - """ - # Work in progress - - Previously:ID_Table_CalcOut - """ - n=4 - userCalcOut_clear("b",n) - pvstr="29idb:userCalcOut"+str(n) - caput(pvstr+".DESC","ID_Table") - table="ID29:TableDirection" # up = 1 , down = 0 - By="ID29:ByPolaritySet" # pos = 1, neg = 0 - caput(pvstr+".INPA",table+" CP NMS") - caput(pvstr+".INPB",By+" CP NMS") - caput(pvstr+".CALC$","A#B") - caput(pvstr+".OOPT","On Change") - caput(pvstr+".DOPT","Use CALC") \ No newline at end of file diff --git a/build/lib/iexcode/instruments/Kappa.py b/build/lib/iexcode/instruments/Kappa.py deleted file mode 100644 index cb565d1633d08e3922fbd990af567de242f27d5d..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/Kappa.py +++ /dev/null @@ -1,929 +0,0 @@ -from json import detect_encoding -import numpy as np -from time import sleep -from math import floor - -from epics import caget, caput,PV - -import iexcode.instruments.cfg as iex -from iexcode.instruments.IEX_BL_config import Beamline_Config -from iexcode.instruments.IEX_cameras import _enable_endstation_cameras - -from iexcode.instruments.files_and_folders import check_run,make_user_folders,folder_mda,path_dserv -from iexcode.instruments.Logfile import Logfile -from iexcode.instruments.staff import staff_detector_dictionary -from iexcode.instruments.xrays import xrays_detector_dictionary, _xrays_reset, xrays_get_all - -from iexcode.instruments.conversions_constants import * -from iexcode.instruments.utilities import * -from iexcode.instruments.userCalcs import userStringSeq_clear, userStringSeq_pvs - -from iexcode.instruments.Motors import Motors -from iexcode.instruments.SRS_current_amplifiers import Keithley, _Keithley_pv, ca_reset_all, _ca_live_sequence -from iexcode.instruments.SRS_current_amplifiers import SRS - -from iexcode.instruments.valves import branch_valve_close -from iexcode.instruments.shutters import branch_shutter_close - -#branch specific -from iexcode.instruments.slits import slit3D_get - -#endstation specific -from iexcode.instruments.kappa_det import Kappa_Detector -from iexcode.instruments.scalers import scaler_cts -from iexcode.instruments.MPA import MPA, mpa_ROI_reset -from iexcode.instruments.spec_stuff import folders_spec - -default_ioc = '29idKappa:' - -global tey,d3,d4,mesh,kappa_scaler_pv,tth_pv,tthdet - -############################################################################# -def kappa_init(*userName,**kwargs): - """ - used to intialize the Endstation class which carries scanRecord, logging ... parameters - returns global detectors relavent to this endstation (tey,d3,d4,mesh,kappa_scaler_pv,tth_pv,tthdet) - - *userName is an optional parameter, will be prompted if set_folders=True - - **kwargs: - set_folders: sets the mda and EA folders (default => True) - reset: to reset the detectors in the IOC, etc (default => True) - xrays: sets global variable and detectors for x-ray (default => True) - mode: used sets the detectors 'user ' / 'staff' (default => 'user' ) - """ - kwargs.setdefault('scan_ioc',default_ioc) - kwargs.setdefault('xrays',True) - kwargs.setdefault('mode','user') - kwargs.setdefault('set_folders',True) - kwargs.setdefault('reset',True) - - #motors - physical_motors = ['x','y','z','tth','kth','kap','kphi'] - pseudo_motors = ['th','chi','phi'] - global kappa_Motors - kappa_Motors = Motors('kappa',_kappa_motor_dictionary(),physical_motors,pseudo_motors) - - #endstation - iex.BL = Beamline_Config('kappa',kwargs['scan_ioc'],kwargs['xrays'],kwargs['mode'],kappa_Motors) - - #setting folders - if kwargs['set_folders']: - if iex.BL.mode == 'staff': - user_name = 'staff' - else: - if len(userName)==0: - user_name = input('user name: ') - else: - user_name = userName[0] - print(user_name) - folders_kappa(user_name,**kwargs) - - #update for default scanRecord advanced parameters - iex.BL.mda.log('kappa',user_name,_kappa_log_header(),_kappa_log_entries) - - #global detectors - tey = SRS("29idMZ0:scaler1.S2", '29idd:A1') - d3 = SRS("29idMZ0:scaler1.S3", '29idd:A2') - d4 = SRS("29idMZ0:scaler1.S4", '29idd:A3') - mesh = SRS("29idMZ0:scaler1.S14", '29idd:A4') - kappa_scaler_pv = '29idMZ0:scaler1.CNT' - tth_pv = _kappa_motor_dictionary('tth')[3] - iex.mpa = MPA() - tthdet = Kappa_Detector(kappa_Motors) - - #resetting everything - if kwargs['reset']: - kappa_reset(**kwargs) - - #enable cameras - _enable_endstation_cameras() - - print ('kappa initalized') - #return any detectors or other parameters that you want access to from jupyter - return tey,d3,d4,mesh,kappa_scaler_pv,tth_pv,tthdet -############################################################################################################## -############################## detectors and motors ############################## -############################################################################################################## -def _kappa_ca_list(): - """ - list of detectors to trigger - - Previously: part of Detector_List - """ - ca_list=[] - return ca_list - - -def _kappa_detector_dictionary(**kwargs): - """ - returns a dictionary of the default detectors - - **kwargs - add_vortex: to specifiy to add the vortex detectors to the dictionary (True/False) - - Previously: Detector_Default - """ - kwargs.setdefault('add_vortex',False) - det_dict={} - vortex={ - 16:"", - 17:"", - 49:"", - 50:"", - - } - sample_temp={ - 23:"29idd:LS331:TC1:SampleA", - 24:"29idd:LS331:TC1:SampleB", - } - m3r={ - 25:"29id_ps6:Stats1:CentroidX_RBV", - 26:"29id_ps6:Stats1:SigmaX_RBV", - 27:"29id_ps6:Stats1:CentroidTotal_RBV", - } - scalers={ - 31:"29idMZ0:scaler1.S14", - 32:"29idMZ0:scaler1.S2", - 33:"29idMZ0:scaler1.S3", - 34:"29idMZ0:scaler1.S4", - 35:"29idMZ0:scaler1.S5", - 36:"29idMZ0:scaler1_calc1.B", - 37:"29idMZ0:scaler1_calc1.C", - 38:"29idMZ0:scaler1_calc1.D", - 39:"29idMZ0:scaler1_calc1.E", - } - mpa_dets={ - 30:"29iddMPA:det1:TotalRate_RBV", - 41:"29iddMPA:Stats1:Total_RBV", - 42:"29iddMPA:Stats2:Total_RBV", - 43:"29iddMPA:Stats3:Total_RBV", - 44:"29iddMPA:Stats4:Total_RBV", - 45:"29iddMPA:Stats5:Total_RBV", - } - hkl={ - 46:'<H>', - 47:'<K>', - 48:'<L>' - } - motors={ - 51:"29idKappa:m8.RBV", - 52:"29idKappa:m7.RBV", - 53:"29idKappa:m1.RBV", - 54:"29idKappa:m9.RBV", - 55:"29idKappa:Euler_ThetaRBV", - 56:"29idKappa:Euler_ChiRBV", - 57:"29idKappa:Euler_PhiRBV", - } - #hkl are listed just a place holders, they are filled in by thier scanning functions - det_dict.update(sample_temp) - det_dict.update(scalers) - det_dict.update(mpa_dets) - det_dict.update(motors) - if kwargs['add_vortex']: - det_dict.update(vortex) - - #add detectors related to beamline - if iex.BL.xrays: - det_dict.update(xrays_detector_dictionary()) - - return det_dict - - -def _kappa_motor_dictionary(name): - """ - motor_dictionary = {name:[rbv,val,spmg,pv]} for physical and psuedo/Euler motors - usage: - kappa_PVmotor('x') => ['29idKappa:m2.RBV', '29idKappa:m2.VAL', '29idKapp:m2.SPMG','29idKappa:m2'] - """ - motor_nums={ - 'x':2, - 'y':3, - 'z':4, - 'tth':9, - 'kth':8, - 'kap':7, - 'kphi':1, - } - Euler_motors={ - 'th':'29idKappa:Euler_Theta', - 'chi':'29idKappa:Euler_Chi', - 'phi':'29idKappa:Euler_Phi' - } - motor_dictionary = {} - for name in motor_nums.keys(): - pv = '29idKappa:m'+str(motor_nums[name]) - motor_dictionary.update({name:[pv+'.VAL',pv+'.SPMG',pv]}) - - for name in Euler_motors.keys(): - pv = Euler_motors[name] - motor_dictionary.update({name:[pv+'RBV',pv,'',pv]}) - - return motor_dictionary - -def kappa_extra_pvs(): - """ - used to get the PV associated with a given pnuemonic - - """ - d={ - "TA":"29idd:LS331:TC1:Control", - "TB":"29idd:LS331:TC1:SampleB", - "det_nam":'29idKappa:userStringSeq6.STR1', - "HV":'29idKappa:userCalcOut10.OVAL', - "centroid":'29id_ps6:Stats1:CentroidX_RBV' - } - return d - -def kappa_kth_offset_get(): - caget("29idKappa:userCalcOut1.G") - -def kappa_kth_offset_set(val): - caput("29idKappa:userCalcOut1.G",val) - - -############################################################################################################# -############################## setting folder ############################## -############################################################################################################## -def folders_kappa(user_name,**kwargs): - """ - Create and sets (if create_only=False) all the folders the current run and ARPES user - Sets the FileName for logging to be "UserName/YYYYMMDD_log.txt using logname_Set()" - - **kwargs: - set_folders = True (default); set the mda and EA scanRecords - = False; only makes the folders (was create_only) - run: run cycle e.g. 2022_1 (default => check_run() ) - ftp = True / False (default); print what needs to be added to the ftps crontab and create additional ftp folders - mda_ioc: will overwrite the default ioc for mda scans - debug - """ - kwargs.setdefault('set_folders',False) - kwargs.setdefault('run',check_run()) - kwargs.setdefault('ftp',False) - kwargs.setdefault('debug',False) - - run = kwargs['run'] - - if kwargs['debug']: - print("run,folder,user_name,ioc,ftp: ",run,iex.BL.folder,user_name,iex.BL.ioc,kwargs['ftp']) - - # Create User Folder: - make_user_folders(run,iex.BL.folder,user_name,iex.BL.endstation,ftp=kwargs['ftp']) - sleep(5) - - if kwargs["set_folders"]: - # Set up MDA folder: - folder_mda(run,iex.BL.folder,user_name,iex.BL.prefix,iex.BL.ioc) - #logfile_name_set(iex.BL.endstation) - #logfile_header(iex.BL.endstation,iex.BL.ioc,kappa_log_header()) - - - # Set up SPEC folder: - folders_spec(run,iex.BL.folder,user_name) - - # Set up MPA folder: - #Folder_MPA(run,iex.BL.folder,user_name) - - #resetting - if 'reset': - kappa_reset() - -def kappa_reset(): - """ - resets scanRecord, current amplifiers, mono limits and lakeshore - """ - #writing default parameters to iex.BL.mda - if iex.BL.mode=='staff': - iex.BL.mda.detector_dictionary = staff_detector_dictionary() - else: - iex.BL.mda.detector_dictionary = _kappa_detector_dictionary() - iex.BL.mda.trigger_dictionary = _kappa_trigger_dictionary() - iex.BL.mda.scan_before_sequence = _kappa_scan_before_sequence() - iex.BL.mda.scan_after_sequence = _kappa_scan_after_sequence() - - #resetting the scanRecord - print("resetting the scanRecord - "+iex.BL.ioc) - iex.BL.mda.reset_all() - - #resetting the MPA ROIs - if iex.BL.xray: - mpa_ROI_reset() - - - #resetting mono and anyother beamline stuff - if iex.BL.xrays: - _xrays_reset() - - #resetting mono and other beamline stuff - if iex.BL.xrays: - _xrays_reset() - - #motors home and sync - _SmarAct_motors_home() - _PI_motors_sync() - Euler_motors_sync() - - -############################################################################################################## -############################## get all ############################## -############################################################################################################## -def kappa_get_all(verbose=True): - """ - returns a dictionary with the current status of the kappa endstation and exit slit - """ - vals = {} - - if verbose: - print("\n===========================================================") - #sample postion - motor_dictionary = _kappa_motor_dictionary() - for motor in motor_dictionary.keys(): - vals[motor]=kappa_Motors.get(motor,verbose=False) - #endstation/branch pvs - extra_pvs = kappa_extra_pvs() - for key in extra_pvs.keys(): - vals.update(key,caget(extra_pvs[key])) - if iex.BL.xrays: - vals.update('exit_slit',slit3D_get()) - vals.update({'mesh':mesh.current_Amp}) - if verbose: - for key in vals: - print(key+" = "+vals[key]) - - #beamline info - if iex.BL.xray: - beamline_info = xrays_get_all() - vals.update(beamline_info) - if verbose: - print("-----------------------------------------------------------") - for key in beamline_info: - print(key+" = "+vals[key]) - print("-----------------------------------------------------------") - if verbose: - print("\n===========================================================") - return vals - -############################################################################################################## -############################## logging ############################## -############################################################################################################## -def _kappa_log_header(): - """ - header for the log file - """ - h = "scan,motor,start,stop,step,x,y,z,tth,kth,kap,kphi,TA,TB," - h += "hv,exit_slit,GRT,ID_SP,ID_RBV,ID_Mode,ID_QP,TEY,mesh,det_name,mpa_HV,m3r_centroid,time,comment" - header_list = {'kappa':h} - return header_list - -def _kappa_log_entries(): - """ - enstation info for log file - - Previously: scanlog - """ - vals = kappa_get_all(verbose=False) - x = vals['x'] - y = vals['y'] - z = vals['z'] - tth = vals['tth'] - kth = vals['kth'] - kap = vals['kap'] - kphi = vals['kphi'] - - TA = vals['TA'] - TB = vals['TB'] - mesh.get() - tey_current = tey.current_Amp - mesh_current = mesh.current_Amp - det_name = tthdet.name - mpa_HV = iex.mpa.HV_get() - m3r_cent = m3r_centroid() - - entry_list = ["x","y","z","tth","kth","kap","kphi","TA","TB","TEY","mesh","det_name","mpa_HV","m3r_centroid"] - pv_list = [ x, y, z, tth, kth, kap,kphi, TA, TB,tey_current,mesh_current,det_name,mpa_HV,m3r_centroid] - format_list = [".2f",".2f",".2f",".2f",".2f",".2f",".2f",".2f",".2f","1.2e","1.2e","s",".0f",".0f"] - - return entry_list,pv_list,format_list - -############################################################################################################## -############################## kappa scanRecord ############################## -############################################################################################################## -def _kappa_scan_before_sequence(scan_ioc,scan_dim,**kwargs): - """ - writes the user string sequence to happen at the beginning of a scan - returns before_scan_pv = pv for userStringSeq for before scan - - **kwargs - seq_num: userStringSeq number in ioc => 9 (default) - - Previously: BeforeScan_StrSeq - """ - kwargs.setdefault('seq_num',9) - seq_num=kwargs['seq_num'] - - before_scan_pv,before_scan_proc = userStringSeq_pvs(scan_ioc, seq_num) - - #clear and write the before scan user sequence - userStringSeq_clear(scan_ioc,seq_num) - caput(before_scan_pv+".DESC","Before Scan") - - #This is where you'd do something if need (CA -> 'Passive', etc) - pv='' - cmd='' - caput(before_scan_pv+".LNK" +str(1),pv) - caput(before_scan_pv+".STR" +str(1),cmd) - - return before_scan_proc - -def _kappa_scan_after_sequence(scan_ioc,scan_dim,**kwargs): - """ - writes the user string sequence to happen at the end of a scan - returns after_scan_pv = pv for userStringSeq for after scan - - **kwargs - seq_num: userStringSeq number in ioc => 10 (default) - snake: for snake scanning => False (default) - - Previously: AfterScan_StrSeq - """ - kwargs.setdefault('seq_num',10) - kwargs.setdefault('snake',False) - seq_num=kwargs['seq_num'] - - if 'scan_ioc' in kwargs: - scan_ioc = kwargs['scan_ioc'] - try: - iex.BL.ioc = kwargs['scan_ioc'] - except: - error = 'undefined' - else: - scan_ioc = iex.BL.ioc - - after_scan_pv,after_scan_proc = userStringSeq_pvs(scan_ioc, seq_num) - - #clear and write the after scan user sequence - userStringSeq_clear(scan_ioc,seq_num) - caput(after_scan_pv+".DESC","After Scan") - - scan_pv = iex.BL.ioc+"scan"+str(scan_dim) - ## Put scan record back in absolute mode - caput(after_scan_pv+".LNK2",scan_pv+".P1AR") - caput(after_scan_pv+".STR2","ABSOLUTE") - - ## Put Positionner Settling time to 0.1s - caput(after_scan_pv+".LNK3",scan_pv+".PDLY NPP NMS") - caput(after_scan_pv+".DO3",0.1) - - ## Clear DetTriggers 2 to 4: - caput(after_scan_pv+".LNK4",scan_pv+".T2PV NPP NMS") #remove trigger 2 (used for EA) after scan - - if kwargs['snake']: - snake_dim = scan_dim - 1 - #snake_proc= kappa_snake_pv(snake_dim,enable=True) - #caput(after_scan_pv+".LNK10",kappa_snake_pv()+"PP NMS") - #caput(after_scan_pv+".D10",1) - - return after_scan_proc - -def _kappa_detector_triggers_sequence(scan_ioc,scan_dim,**kwargs): # do we need to add 29idb:ca5 ??? - """ - """ - kwargs.setdefault(seq_num,8) - seq_num=kwargs['seq_num'] - - detector_triggers_pv,detector_triggers_proc = userStringSeq_pvs(iex.BL.ioc, seq_num) - - #clear the userStringSeq - userStringSeq_clear(scan_ioc,seq_num=kwargs['seq_num']) - caput(detector_triggers_pv+".DESC","kappa_Trigger1") - - scaler_pv = kappa_scaler_pv - - caput(detector_triggers_pv+".LNK" +str(1),scaler_pv) - caput(detector_triggers_pv+".WAIT"+str(1),"After"+str(last)) - - ca_list = _kappa_ca_list() - last = len(ca_list) - for i,ca in enumerate(ca_list): - ca_pv = _Keithley_pv(ca[0], ca[1])+':read.PROC CA NMS' - caput(detector_triggers_pv+".LNK" +str(i+2),ca_pv) - caput(detector_triggers_pv+".WAIT"+str(i+2),"After"+str(last)) - - return detector_triggers_proc - -def _kappa_trigger_dictionary(scan_ioc,scan_dim,**kwargs): - """ - need to do something - """ - trigger_dictionary = { - 1:_kappa_detector_triggers_sequence(scan_ioc,scan_dim,**kwargs), - } - return trigger_dictionary - - - - -############################################################################################################## -############################## kappa Motor Scan Set Up ############################## -############################################################################################################## - -def kappa_sample_Euler_list(): - """ - returns list of motor names used by mvsample - """ - motor_list = ['th','chi','phi'] - return motor_list - -def kappa_4c_mprint(): - """ - returns the dictionary of the current sample position in 4c units - - motors=['th','chi','phi'] - - Previously: diffracto? - """ - positions={} - motors=kappa_sample_Euler_list() - for motor in motors: - positions.update(motor,_kappa_motor_dictionary()(motor)[0]) - return positions - -def kappa_4c_move(th_chi_phi_list): - """ - moves the sample in 4c (Euler) units - Previously: mv4C - """ - motor_list=kappa_sample_Euler_list() - for motor,i in enumerate(motor_list): - kappa_Motors.move(motor,motor_list[i],wait=True,verbose=False) - - for motor,i in enumerate(motor_list): - kappa_Motors.get(motor,verbose=True) - -def _SmarAct_motor_list(): - """ - returns a list of the motor names for the SmarAct motors in the kappa - """ - return ['x','y','z'] - -def _SmarAct_motors_home(): - """ - Homes the piezo (x,y,z). Home position is middle of travel - - Previously: Home_SmarAct_Motor - """ - motor_dictionary = _kappa_motor_dictionary() - for motor in _SmarAct_motor_list(): - pv = motor_dictionary[motor][3] - caput(pv+'.HOMF',1) - sleep(10) - print('SamrAct motors VAL homed') - -def _SmarAct_enable(): - motor_dictionary = _kappa_motor_dictionary() - for motor in _SmarAct_motor_list(): - spmg = motor_dictionary[motor][2] - caput(spmg,3) # 3=Go - -def _SmarAct_disable(): - motor_dictionary = _kappa_motor_dictionary() - for motor in _SmarAct_motor_list(): - spmg = motor_dictionary[motor][2] - caput(spmg,0) # 1=Stop - -def _PI_motor_list(): - """ - returns a list of the motor names for the SmarAct motors in the kappa - """ - return ['kap','kth','tth'] - -def _PI_motors_sync(): - motor_dictionary = _kappa_motor_dictionary() - for motor in _PI_motor_list(): - val_pv = motor_dictionary[motor][1] - rbv_pv = motor_dictionary[motor][0] - current_rbv=caget(rbv_pv) - caput(val_pv,current_rbv) - print('PI motors VAL synced to RBV') - -def Euler_motors_sync(): - """ - Syncs the Euler motores - - Previously: Sync_Euler_Motor - """ - caput('29idKappa:Kappa_sync.PROC',1) - sleep(1) - caput('29idKappa:Kappa_sync.PROC',1) - print('Euler motors VAL/RBV synced to physical motors') - -def kappa_kphi_reset_zero(val): - """ - resets the zero for the kphi motor - - """ - kphi_pv = _kappa_motor_dictionary()['kphi'][3] - caput(kphi_pv+".SET",1) # 1 = Set - sleep(0.5) - caput("kphi_pv.VAL",val) - sleep(0.5) - caput(kphi_pv+".SET",0) # 0 = Use - print("\nkphi has been reset to " +str(val)) - -def kappa_tth_reset_zero(): - """ - resets the zero for the tth motor - """ - tthdet.tth0_set() - -def th2th_scan_sensitivity(th_table,gain_num_table,gain_unit_table,**kwargs): - """ - Scans th2th with variable gain on SRS# (srs_num). - Gain is specified for a given th2th range by building tables as follow: - - th_table = np.array([]) - gain_num_table = np.array([]) - gain_unit_table = np.array([]) - - Example: - for i in RangeUp(10,20,0.5): - th_table = np.append(th_table, i) - gn_table = np.append(gn_table, gain_dict(2)) - gu_table = np.append(gu_table, unit_dict('mA')) - for i in RangeUp(20.5,40,0.5): - th_table = np.append(th_table, i) - gn_table = np.append(gn_table, gain_dict(1)) - gu_table = np.append(gu_table, unit_dict('uA')) - for i in RangeUp(40.5,60,0.5): - th_table = np.append(th_table, i) - gn_table = np.append(gn_table, gain_dict(10)) - gu_table = np.append(gu_table, unit_dict('pA')) - - kwargs: - detector (default tey) - scan_dim: 1 (default) - cts: integration time for scalers and mpa/mcp => 0.1 (default) - execute: True/False to start the scan => True (default) - - Previoulsy: Scan_th2th_sensitivity - """ - kwargs.setdefault('cts',0.1) - kwargs.setdefault('execute',True) - - if 'detector' not in kwargs: - detector = tey - else: - detector = kwargs['detector'] - - kth_offset = kappa_kth_offset_get() - - motor_dictionary = _kappa_motor_dictionary() - kth_val,kth_rbv,kth_spmg,kth_pv = motor_dictionary['kth'] - tth_val,tth_rbv,tth_spmg,tth_pv = motor_dictionary['tth'] - - detector_pv = detector._srs_pv - gain_num_pv = detector_pv + "sens_num.VAL" - gain_unit_pv= detector_pv + "sens_unit.VAL" - - kth_table = th_table + kth_offset - tth_table = 2*th_table - - kwargs.update("positioner_num",1) - iex.BL.mda.fillin_table(kth_val,kth_rbv,kth_table,**kwargs) - - kwargs.update("positioner_num",2) - iex.BL.mda.fillin_table(tth_val,tth_rbv,tth_table,**kwargs) - - kwargs.update("positioner_num",3) - iex.BL.mda.fillin_table(gain_num_pv,"",gain_num_table,**kwargs) - - kwargs.update("positioner_num",4) - iex.BL.mda.fillin_table(gain_unit_pv,"",gain_unit_table,**kwargs) - - print("\nDon't forget to clear extra positionners at the end of the scan if you were to abort the script using the function:") - print(" Clear_Scan_Positioners('kappa',1)") - - scaler_cts(kwargs['cts'],verbose=False) - if kwargs['execute']: - iex.BL.mda.go(**kwargs) - - #clean up after scan - iex.BL.mda.table_reset_after(**kwargs) - scaler_cts(verbose=False) - -def scanth2th(tth_start,tth_stop,tth_step,th_offset,**kwargs): - """ - Used for a linear (not table) scan where th = tth /2 + th_offset - **kwargs - scan_dim: 1 (default) - cts: integration time for scalers and mpa/mcp => 0.1 (default) - execute: True/False to start the scan => True (default) - - Previously: scanth2th - """ - kwargs.setdefault('scan_dim',1) - kwargs.setdefault('cts',0.1) - kwargs.setdefault('execute',True) - - th_start = (tth_start)/2+th_offset - th_stop = (tth_stop)/2+th_offset - th_step = int(tth_step/2) - - print('tth: '+str(tth_start)+"/"+str(tth_stop)+"/"+str(tth_step)) - print('th: '+str(th_start)+"/"+str(th_stop)+"/"+str(tth_step/2.0)) - - #write to the scanRecord - th_val,th_rbv,th_spmg,th_pv = _kappa_motor_dictionary['th'] - tth_val,tth_rbv,tth_spmg,tth_pv = _kappa_motor_dictionary['tth'] - - - kwargs.update("positioner_num",2) - iex.BL.mda.fillin(th_val,th_rbv,th_start,th_stop,th_step,**kwargs) - - kwargs.update("positioner_num",1) - iex.BL.mda.fillin(tth_val,tth_rbv,tth_start,tth_stop,tth_step,**kwargs) - - scaler_cts(kwargs['cts'],verbose=False) - if kwargs['execute']: - iex.BL.mda.go(**kwargs) - - #clean up after scan - scaler_cts(verbose=False) - -def dscanth2th(tth_start_rel,tth_stop_rel,tth_step,th_offset,**kwargs): - """ - relative (about current tth position) linear (not table) scan where th = tth /2 + th_offset - **kwargs - scan_dim: 1 (default) - cts: integration time for scalers and mpa/mcp => 0.1 (default) - execute: True/False to start the scan => True (default) - - Previously: scanth2th - """ - tth_rbv= kappa_Motors.get('tth',verbose=False) - tth_start = tth_rbv+tth_start_rel - tth_stop = tth_rbv+tth_stop_rel - - scanth2th(tth_start,tth_stop,tth_step,th_offset,**kwargs) - - -def scanth2th_table(tth_table,th_offset, **kwargs): - """ - Used for constant q scans (tth is none linear) - **kwargs - scan_dim: 1 (default) - cts: integration time for scalers and mpa/mcp => 0.1 (default) - execute: True/False to start the scan => True (default) - - Previously: scanth2th - """ - kwargs.setdefault('scan_dim',1) - kwargs.setdefault('cts',0.1) - kwargs.setdefault('execute',True) - - tth_table = np.asarray(tth_table) - th_table = tth_table/2.0 + th_offset - - #write to the scanRecord - th_val,th_rbv,th_spmg,th_pv = _kappa_motor_dictionary['th'] - tth_val,tth_rbv,tth_spmg,tth_pv = _kappa_motor_dictionary['tth'] - - kwargs.update("positioner_num",1) - iex.BL.mda.fillin_table(tth_val,tth_rbv,tth_table,**kwargs) - - kwargs.update("positioner_num",2) - iex.BL.mda.fillin_table(th_val,th_rbv,th_table,**kwargs) - iex.BL.mda.positioner_after_scan(after="STAY") - - - scaler_cts(kwargs['cts'],verbose=False,**kwargs) - if kwargs['execute']: - iex.BL.mda.go(**kwargs) - - #clean up after scan - iex.BL.mda.table_reset_after() - scaler_cts(verbose=False) - iex.BL.mda.positioner_after_scan(after="PRIOR POS",**kwargs) - - - - -############################################################################################################# -############################## Preset Positions ############################## -############################################################################################################## -def _kappaTransfer_StrSeq(): - #User= [ DESC, x, y, z, tth, kth, kap, kphi] - User = ["kappa Transfer",0, -2650, -650, 0, 57, 0, -88] - n=4 - _kappaPreset_StrSeq(n,User) - - -def _kappaGrazing_StrSeq(): #Need to determine positions and then add to the kappa graphic - #Dial= [ DESC, x, y, z, tth, kth, kap, kphi] - User = ["kappa Grazing",0, 0, 0, 0, 57.045, 134.76,57.045] - n=3 - _kappaPreset_StrSeq(n,User) - -def kappa_ResetPreset(): - _kappaGrazing_StrSeq() - _kappaTransfer_StrSeq() - - - - - - - - - - -############################################################################################################## -############################## Kappa light ############################## -############################################################################################################## -def kappa_light(ON_OFF): - """ - Previously:light - """ - light_pv = '29idd:Unidig1Bo0' - if ON_OFF.lower() == 'on': - light=0 - elif ON_OFF.lower() == 'off': - light=1 - caput(light_pv,light) - print(("Turning light "+ON_OFF+".")) - - -############################################################################################################## -######################## Scan Temp and Pressure ############################## -############################################################################################################## -def kappa_temperature_pressure_scan(scan_dim=1): - """ - starts scan to monitor temperature and pressure in the kappa chamber - - Previously: kappa_ScanTempPres - """ - - pv="29id"+iex.BL.mda.ioc+":scan"+str(scan_dim) - #Clear all scan pvs - caput(pv+".CMND",6) - #Set detectors - caput(pv+".D01PV","29idd:tc1:getVal_A.VAL") - caput(pv+".D02PV","29idd:tc1:getVal_B.VAL") - caput(pv+".D03PV","29idb:VS11D.VAL") - #time scan - iex.BL.mda.time_go() - - - -############################################################################################################## -############################## kappa safestate ############################## -############################################################################################################## -def kappa_safe_state(**kwargs): - """ - puts the C-branch in a safe state, - **kwargs - MPA_off = True; turns off EA HV - shutter_close = True; closes the D-shutter - valve_close = True; closes the D-valve - """ - kwargs.setdefault("MPA_off",True) - kwargs.setdefault("shutter_close",True) - kwargs.setdefault("valve_close",True) - - if kwargs["mpa_off"]: - try: - iex.mpa.HV_off() - except: - print('MPA is not running') - - if kwargs['shutter_close']: - branch_shutter_close() - - if kwargs['valve_close']: - branch_valve_close() - - -### uan moves tth and th simultaneously -def uan(tth,th): - """ Moves tth and th motors simultaneously in the in the kappa chamber - """ - - #move tth and th - kappa_Motors.move('th',th,wait=False) - kappa_Motors.move('tth',tth,wait=False) - time.sleep(0.2) - - while True: - status = kappa_Motors.status() - if status == 0: - time.sleep(0.2) - else: - tth_RBV=round(kappa_Motors.get('tth',verbose=False),3) - th_RBV=round(kappa_Motors.get('th',verbose=False),3) - print('tth='+str(tth_RBV)+' th='+str(th_RBV)) - break - - #double check both moved to the correct position - kappa_Motors.move('th',th) - kappa_Motors.move('tfh',tth) diff --git a/build/lib/iexcode/instruments/Kappa_det.py b/build/lib/iexcode/instruments/Kappa_det.py deleted file mode 100644 index 5ea9e9e8f9f10625ad1cb901a8f28125d8688b9c..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/Kappa_det.py +++ /dev/null @@ -1,77 +0,0 @@ -from time import sleep -from epics import caget, caput - - - -############################################################################################################## -################################ Kappa detector class ############################## -############################################################################################################## -det_set_pv = '29idKappa:det:set' -det_list = ['d3', 'd4', 'mcp', 'apd', 'yag'] - -class Kappa_Detector: - """ - class for Kappa detector - """ - - def __init__(self,kappa_Motors): - self.motors = kappa_Motors - self.get() - - def get(self): - """ - gets the current det_name and position - - det_name, tth_val - """ - #det_name = caget('29idKappa:userStringSeq6.STR1') - det_name = caget(det_set_pv) - self.name = det_name - tth_val = self.motors.get('tth') - return self.name, tth_val - - def set(self,det_name,move=True): - """ - sets the tth detector - and moves the motor to tth value for the new detecotr - - det_names - d3: large diode - d4: small diode - mcp: for the mpa - apd: avalanche photodiode (not currently installed) - yag: yag 'fluorescence screen' - """ - #get current value for tth - tth_val = self.motors.get('tth') - - #change det - if det_name in det_list: - caput(det_set_pv,det_name) - if move: - self.motors.move('tth',tth_val,wait=True,verbose=False) - - def tth0_set(self,move): - """ - resetting the tth motor zero to correspond to direct beam - - only works with d4 - """ - current_det=caget(det_set_pv,as_string=True) - tth_pv = self.motors._motor_dictionary['th'][3] - - if current_det != 'd4': - print('tth0 can only be redefined with d4') - else: - foo=input('Are you sure you want to reset tth0 (y or n)? >') - if foo == 'Y' or foo == 'y' or foo == 'yes'or foo == 'YES': - caput(tth_pv+'.SET','Set') - sleep(0.5) - caput(tth_pv+'.VAL',0) - caput(tth_pv+'.DVAL',0) - sleep(0.5) - caput(tth_pv+'.SET','Use') - print("tth position reset to 0") - else: - print("That's ok, everybody can get cold feet in tough situation...") - diff --git a/build/lib/iexcode/instruments/Lakeshore_335.py b/build/lib/iexcode/instruments/Lakeshore_335.py deleted file mode 100644 index 3c2784d571404a2ce8f1cb692b6ca77291bac749..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/Lakeshore_335.py +++ /dev/null @@ -1,448 +0,0 @@ -""" -work in progress need to redo -""" -from time import sleep, strftime, localtime - -import numpy as np -from epics import caget, caput - - -from iexcode.instruments.IEX_BL_config import * -from iexcode.instruments.utilities import read_dict - -def Lakeshore_reset(pv,d): - """ - resets the lake short to the default paramters defind in the dictionary d - """ - for key in d.keys(): - caput(pv+key,d[key]) - - -############################################################################################################# -############################## Lakeshore 335 Diode Curves ############################## -############################################################################################################## -#---Settings as of 12/04/2018--- -#DiodeCurve_Write(22,"SI435") -#DiodeCurve_SetInput("A",22,400) -#DiodeCurve_Write(23,"SI410") -#DiodeCurve_SetInput("B",23,450) - - - -# ============================================================================= -# def DiodeCurves(DiodeModel): -# DiodeCalibration={} -# DiodeCalibration["SI435"]=[0.00000,1.66751,1.64531,1.61210,1.57373,1.53247,1.49094,1.45196,1.41723,1.38705,1.36089,1.33785,1.31699,1.29756,1.27912,1.26154,1.24489,1.22917,1.21406,1.19855,1.18193,1.16246,1.13841,1.12425,1.11828,1.11480,1.11217,1.10996,1.10828,1.10643,1.10465,1.10295,1.10124,1.09952,1.09791,1.09629,1.09468,1.09306,1.09145,1.08983,1.08821,1.08659,1.08497,1.08334,1.08171,1.08008,1.07844,1.07681,1.07517,1.07353,1.07188,1.07023,1.06858,1.06693,1.06528,1.06362,1.06196,1.06029,1.05863,1.05696,1.05528,1.05360,1.05192,1.05024,1.04856,1.04687,1.04518,1.04349,1.04179,1.04010,1.03839,1.03669,1.03498,1.03327,1.03156,1.02985,1.02814,1.02642,1.02471,1.02299,1.02127,1.01957,1.01785,1.01612,1.01439,1.01267,1.01093,1.00918,1.00744,1.00569,1.00393,1.00218,1.00042,0.99865,0.99687,0.99510,0.99332,0.99153,0.98975,0.98795,0.98615,0.98434,0.98254,0.98073,0.97891,0.97710,0.97527,0.97344,0.97161,0.96978,0.96794,0.96609,0.96424,0.96239,0.96053,0.95867,0.95680,0.95492,0.95304,0.95116,0.94927,0.94738,0.94549,0.94358,0.94167,0.93976,0.93785,0.93592,0.93398,0.93203,0.93008,0.92812,0.92616,0.92418,0.92221,0.92022,0.91823,0.91623,0.91423,0.91222,0.91021,0.90819,0.90617,0.90414,0.90212,0.90008,0.89805,0.89601,0.89397,0.89293,0.88988,0.88783,0.88578,0.88372,0.88166,0.87959,0.87752,0.87545,0.87337,0.87129,0.86921,0.86712,0.86503,0.86294,0.86084,0.85874,0.85664,0.85453,0.85242,0.85030,0.84818,0.84606,0.84393,0.84180,0.83967,0.83754,0.83540,0.83325,0.83111,0.82896,0.82680,0.82465,0.82249,0.82032,0.81816,0.81599,0.81381,0.81163,0.80945,0.80727,0.80508,0.80290,0.80071,0.79851,0.79632,0.79412,0.79192,0.78972,0.78752,0.78532,0.78311,0.78090,0.77869,0.77648,0.77426,0.77205,0.76983,0.76761,0.76539,0.76317,0.76094,0.75871,0.75648,0.75425,0.75202,0.74978,0.74755,0.74532,0.74308,0.74085,0.73861,0.73638,0.73414,0.73191,0.72967,0.72743,0.72520,0.72296,0.72072,0.71848,0.71624,0.71400,0.71176,0.70951,0.70727,0.70503,0.70278,0.70054,0.69829,0.69604,0.69379,0.69154,0.68929,0.68704,0.68479,0.68253,0.68028,0.67802,0.67576,0.67351,0.67124,0.66898,0.66672,0.66445,0.66219,0.65992,0.65765,0.65538,0.65310,0.65083,0.64855,0.64628,0.64400,0.64172,0.63944,0.63716,0.63487,0.63259,0.63030,0.62802,0.62573,0.62344,0.62115,0.61885,0.61656,0.61427,0.61197,0.60968,0.60738,0.60509,0.60279,0.60050,0.59820,0.59590,0.59360,0.59131,0.58901,0.58671,0.58441,0.58211,0.57980,0.57750,0.57520,0.57289,0.57059,0.56828,0.56598,0.56367,0.56136,0.55905,0.55674,0.55443,0.55211,0.54980,0.54748,0.54516,0.54285,0.54053,0.53820,0.53588,0.53356,0.53123,0.52891,0.52658,0.52425,0.52192,0.51958,0.51725,0.51492,0.51258,0.51024,0.50790,0.50556,0.50322,0.50088,0.49854,0.49620,0.49385,0.49151,0.48916,0.48681,0.48446,0.48212,0.47977,0.47741,0.47506,0.47271,0.47036,0.46801,0.46565,0.46330,0.46095,0.45860,0.45624,0.45389,0.45154,0.44918,0.44683,0.44447,0.44212,0.43976,0.43741,0.43505,0.43270,0.43034,0.42799,0.42563,0.42327,0.42092,0.41856,0.41620,0.41384,0.41149,0.40913,0.40677,0.40442,0.40206,0.39970,0.39735,0.39499,0.39263,0.39027,0.38792,0.38556,0.38320,0.38085,0.37849,0.37613,0.37378,0.37142,0.36906,0.36670,0.36435,0.36199,0.35963,0.35728,0.35492,0.35256,0.35021,0.34785,0.34549,0.34313,0.34078,0.33842,0.33606,0.33371,0.33135,0.32899,0.32667,0.32428,0.32192] -# DiodeCalibration["SI410"]=[0.0000,1.7191,1.7086,1.6852,1.6530,1.6124,1.5659,1.5179,1.4723,1.4309,1.3956,1.3656,1.3385,1.3142,1.2918,1.2712,1.2517,1.2333,1.2151,1.1963,1.1759,1.1524,1.1293,1.1192,1.1146,1.1114,1.1090,1.1069,1.1049,1.1031,1.1014,1.0997,1.0980,1.0964,1.0949,1.0933,1.0917,1.0902,1.0886,1.0871,1.0855,1.0839,1.0824,1.0808,1.0792,1.0776,1.0760,1.0744,1.0728,1.0712,1.0696,1.0679,1.0663,1.0646,1.0630,1.0613,1.0597,1.0580,1.0563,1.0547,1.0530,1.0513,1.0497,1.0480,1.0463,1.0446,1.0429,1.0412,1.0395,1.0378,1.0361,1.0344,1.0327,1.0310,1.0293,1.0276,1.0259,1.0242,1.0224,1.0207,1.0190,1.0172,1.0155,1.0137,1.0120,1.0102,1.0085,1.0067,1.0049,1.0032,1.0014,0.9996,0.9978,0.9960,0.9942,0.9924,0.9905,0.9887,0.9869,0.9851,0.9832,0.9814,0.9795,0.9777,0.9758,0.9740,0.9721,0.9703,0.9684,0.9665,0.9646,0.9628,0.9609,0.9590,0.9571,0.9552,0.9533,0.9514,0.9495,0.9476,0.9457,0.9437,0.9418,0.9398,0.9379,0.9359,0.9340,0.9320,0.9300,0.9281,0.9261,0.9241,0.9222,0.9202,0.9182,0.9162,0.9142,0.9122,0.9102,0.9082,0.9062,0.9042,0.9022,0.9002,0.8982,0.8962,0.8942,0.8921,0.8901,0.8881,0.8860,0.8840,0.8820,0.8799,0.8779,0.8758,0.8738,0.8717,0.8696,0.8676,0.8655,0.8634,0.8613,0.8593,0.8572,0.8551,0.8530,0.8509,0.8488,0.8467,0.8446,0.8425,0.8404,0.8383,0.8362,0.8341,0.8320,0.8299,0.8278,0.8257,0.8235,0.8214,0.8193,0.8171,0.8150,0.8129,0.8107,0.8086,0.8064,0.8043,0.8021,0.8000,0.7979,0.7957,0.7935,0.7914,0.7892,0.7871,0.7849,0.7828,0.7806,0.7784,0.7763,0.7741,0.7719,0.7698,0.7676,0.7654,0.7632,0.7610,0.7589,0.7567,0.7545,0.7523,0.7501,0.7479,0.7457,0.7435,0.7413,0.7391,0.7369,0.7347,0.7325,0.7303,0.7281,0.7259,0.7237,0.7215,0.7193,0.7170,0.7148,0.7126,0.7104,0.7082,0.7060,0.7037,0.7015,0.6993,0.6971,0.6948,0.6926,0.6904,0.6881,0.6859,0.6837,0.6814,0.6792,0.6770,0.6747,0.6725,0.6702,0.6680,0.6657,0.6635,0.6612,0.6590,0.6567,0.6545,0.6522,0.6500,0.6477,0.6455,0.6432,0.6410,0.6387,0.6365,0.6342,0.6319,0.6297,0.6274,0.6251,0.6229,0.6206,0.6183,0.6161,0.6138,0.6115,0.6092,0.6070,0.6047,0.6024,0.6001,0.5979,0.5956,0.5933,0.5910,0.5887,0.5865,0.5842,0.5819,0.5796,0.5773,0.5750,0.5727,0.5705,0.5682,0.5659,0.5636,0.5613,0.5590,0.5567,0.5544,0.5521,0.5498,0.5475,0.5452,0.5429,0.5406,0.5383,0.5360,0.5337,0.5314,0.5291,0.5268,0.5245,0.5222,0.5199,0.5176,0.5153,0.5130,0.5107,0.5084,0.5061,0.5038,0.5015,0.4992,0.4968,0.4945,0.4922,0.4899,0.4876,0.4853,0.4830,0.4806,0.4783,0.4760,0.4737,0.4714,0.4690,0.4667,0.4644,0.4621,0.4597,0.4574,0.4551,0.4528,0.4504,0.4481,0.4458,0.4435,0.4411,0.4388,0.4365,0.4341,0.4318,0.4295,0.4271,0.4248,0.4225,0.4201,0.4178,0.4154,0.4131,0.4108,0.4084,0.4061,0.4037,0.4014,0.3991,0.3967,0.3944,0.4154,0.4131,0.4108,0.4084,0.4061,0.4037,0.4014,0.3991,0.3967,0.3709,0.3685,0.3662,0.3638,0.3615,0.3591,0.3567,0.3544,0.3520,0.3497,0.3473,0.3449,0.3426,0.3402,0.3379,0.3355,0.3331,0.3308,0.3284,0.3260,0.3237,0.3213,0.3189,0.3165,0.3142,0.3118,0.3094,0.3071,0.3047,0.3023,0.2999,0.2976,0.2952,0.2928,0.2904,0.2880,0.2857,0.2833,0.2809,0.2785,0.2761,0.2738,0.2714,0.2690,0.2666,0.2642,0.2618,0.2594,0.2570,0.2547,0.2523,0.2499,0.2475,0.2451,0.2427,0.2403,0.2379,0.2355,0.2331,0.2307,0.2283,0.2259,0.2235,0.2211,0.2187,0.2163,0.2139,0.2115,0.2091,0.2067,0.2043] -# return DiodeModel,DiodeCalibration[DiodeModel] -# ============================================================================= - -def DiodeCurve_Write_backup(CRVNum,DiodeModel): - """ - Writes a Diode curve to the Lakeshore 335 temperature controller - Diode curves are saved in the fname=Dict_TempDiode.txt - usage: DiodeCurve_Write(22,"SI435") to write to curve 22 the dictionary entry "SI435" - DiodeCurve_SetInput("A",22,400) - """ - fname="Dict_TempDiode.txt" - PV="29idARPES:LS335:TC1:serial.AOUT" - - t=1 - index=1 - #Curve Header - DiodeDict=read_dict(fname) - CRVHDR,CRVList=DiodeModel,DiodeDict[DiodeModel] - - cmd="CRVHDR "+str(CRVNum)+","+CRVHDR+",SN,2,"+str(len(CRVList)-1)+",1" - print(cmd) - caput(PV,cmd,wait=True,timeout=1800) - while t <len(CRVList): - if(t>=0 and t<30): - countby=1 - elif(t>=30 and t<230): - countby=2 - elif(t>=230): - countby=5 - cmd="CRVPT "+str(CRVNum)+","+str(index)+","+str(CRVList[t])+","+str(t) - #print cmd - caput(PV,cmd,wait=True,timeout=1800) - #sleep(1) - t=t+countby - index+=1 - #write 0,0 to indicate list is done - cmd="CRVPT "+str(CRVNum)+","+str(index)+","+str(CRVList[0])+","+str(0) - caput(PV,cmd,wait=True,timeout=1800) - print("last point = "+str(index)) - -def DiodeCurve_Write(CRVNum,DiodeModel,run=True): #reversing order since it seems that the curve needs to go from high to low based on the built-in - """ - Writes a Diode curve to the Lakeshore 335 temperature controller - Diode curves are saved in the fname=Dict_TempDiode.txt - - run=True to write to the Lakeshoe - run=False to print only - - usage: DiodeCurve_Write(22,"SI435") to write to curve 22 the dictionary entry "SI435" - DiodeCurve_SetInput("A",22,400) - """ - fname="Dict_TempDiode.txt" - PV="29idARPES:LS335:TC1:serial.AOUT" - - - #Curve Header - CRVList=read_dict(fname)[DiodeModel] - cmd="CRVHDR "+str(CRVNum)+","+DiodeModel+",SN,2,"+str(len(CRVList)-1)+",1" - if run == True: - caput(PV,cmd,wait=True,timeout=1800) - else: - print(cmd) - - #Writing the individual terms (model 335 only supports index:1-200) - T1=50 - T2=230 - T3=len(CRVList) - - T=np.arange(0,T1,1) - V=np.array(CRVList[0:T1]) - - T=np.append(T,np.arange(T1,T2,2)) - V=np.append(V,np.array(CRVList[T1:T2:2])) - - T=np.append(T,np.arange(T2,T3,5)) - V=np.append(V,np.array(CRVList[T2:T3:5])) - - #reverse order - T=T[::-1] - V=V[::-1] - - for i,t in enumerate(T): - cmd="CRVPT "+str(CRVNum)+","+str(i+1)+","+str(V[i])+","+str(t) - #cmd="index,v,t"+str(i+1)#+","+str(V[i])+","+str(t) - if run == True: - caput(PV,cmd,wait=True,timeout=1800) - else: - print(cmd) - -def DiodeCurve_SetInput(Channel,Curve,Tmax): - """ - Sets the diode curve for a given channel on the Lakeshore 335 temperature controller - DiodeCurve_SetInput("A",22,400) - Channel: A or B - Curve: set by DiodeCurve_Write(22,"SI435") - Tmax: max temperature for that diode - (pg 118 of manual) - """ - - PV="29idARPES:LS335:TC1:serial.AOUT" - #Set curve info - cmd="INTYPE "+Channel+","+"1,0,0,0,1" - caput(PV,cmd,wait=True,timeout=1800) - #Select curve - cmd="INCRV "+Channel+","+str(Curve) - caput(PV,cmd,wait=True,timeout=1800) - #Set temperature Limit - cmd="TLIMIT "+Channel+","+str(Tmax) - caput(PV,cmd,wait=True,timeout=1800) - -############################################################################################################## -############################## PID Settings ############################## -############################################################################################################## - - -#Setting the PID -# Set P=10, I=0, D=0; Set T and range, -# if T oscilate above setpoint, P/=2 -# if T doesn't reach setpoint, P*=2 -# if T swings above setpoint but then settle below use this P -# Set I=10; smaller I, more reactive (approximately time(sec) for one full oscillation period -# Set D=I/4 -#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+"\']") - - - -############################################################################################################## -############################## SI9700 Kludge ############################## - -############################################################################################################## -def ResetPID(): - caput('29idd:tc1:SetPID_1.INPA','') - caput('29idd:tc1:SetPID_1.INPB','') - caput('29idd:tc1:SetPID_1.INPC','') - -def GetCurrentPID(): - T=caget('29idd:tc1:getVal_A.VAL') - P=caget('29idd:tc1:SetPID_1.A') - I=caget('29idd:tc1:SetPID_1.B') - D=caget('29idd:tc1:SetPID_1.C') - return T,P,I,D - -def SetTempSetting(T,P,I,D): - #Change the sample temperature T with the specified PID values - caput('29idd:tc1:getVal_A.VAL',T) - caput('29idd:tc1:SetPID_1.A',P) - caput('29idd:tc1:SetPID_1.B',I) - caput('29idd:tc1:SetPID_1.C',D) - -# GetCurrentPID => (60.0121, 8.0, 50.0, 12.0) ## Temperature overshoots no more than 5.5 degrees -#it takes about 3 min to stablize at any temp -#cooling is about 10 degrees/min - - -#functions use from ScanFunctions_IEX import BL_ioc -def PVLakeshores(which): - """ - which = RSXS / ARPES /Hydra / DetPool - usage: P, Sample, ColdFinger, SetPoint = PVLakeshores[which] - """ - # key: - - d={"Kappa":("29idd:LS331:TC1:","SampleA","SampleB","wr_SP"), - "ARPES":("29idARPES:LS335:TC1:","IN1","IN2","OUT1:SP"), - "Hydra":("29idc:LS340:TC2:","Sample","Control","wr_SP1"), - "DetPool":("29idc:LS340:TC1:","Sample","Control","wr_SP1") - } - 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') diff --git a/build/lib/iexcode/instruments/Motors.py b/build/lib/iexcode/instruments/Motors.py deleted file mode 100644 index 475e3627837c70aed74aa8d24d72576e1904e1eb..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/Motors.py +++ /dev/null @@ -1,465 +0,0 @@ -import time - -from epics import caget, caput - -import iexcode.instruments.cfg as iex - -from iexcode.instruments.utilities import print_warning_message -from iexcode.instruments.scalers import scaler_cts - - -############################################################################################################## -############################## Motor Class ############################## -############################################################################################################## -class Motors: - """ - short hand to move motors in endstation - usage motors = Motor('ARPES','ARPES_motor_dictionary') - """ - - def __init__(self,endstation_name,motor_dictionary,physical_motors, - psuedo_motors): - self.endstation_name = endstation_name - self._motor_dictionary = motor_dictionary - self.physical_motors = physical_motors - self.pseudo_motors = psuedo_motors - - def info(self): - print("physical motors:",self.physical_motors) - print("pseudo motors:",self.pseudo_motors) - - def get(self,name,verbose=False): - """ - get current position of motor name = "x","y"... - """ - - try: - rbv = caget(self._motor_dictionary[name][0]) - if verbose: - print('current position: '+name+" = "+str(rbv)) - return rbv - except: - print("Not a valid motor name") - - def reset(self,name): - """ - Reset motor if stuck in 'moving' - """ - pv=self._motor_dictionary[name][2] - caput(pv,'Stop') - time.sleep(1) - caput(pv,'Go') - - def status(self): - """ - if status == 0 then moving - """ - status = 0 - for motor in self._motor_dictionary.keys(): - status *= caget(self._motor_dictionary[motor][3]+".DMOV") - return status - - def move(self,name,val,**kwargs): - """ - Moves a motor in the endstation based on common name, not PV name - - name: motor name => 'x','y','z','th','chi','phi' ... - val: absolute position if relative=False, delta if relative=True - - **kwargs: - relative: move mode => True/False; default = False (absolute) - wait: wait for move completion before moving on => True/False; default=True - verbose: print old and new motor position => True/False; default=False - - - Previously: Move_ARPES_Motor or Move_ARPES_Motor or motor_move_vs_Branch - """ - kwargs.setdefault('relative',False) - kwargs.setdefault('wait',True) - kwargs.setdefault('verbose',False) - - try: - rbv_pv,val_pv,sgm_pv,pv = self._motor_dictionary[name] - old_position = caget(rbv_pv) - if kwargs['relative']: - val = old_position + val - - caput(val_pv,val,wait=kwargs['wait'],timeout=18000) - - new_position = caget(rbv_pv) - if kwargs['verbose']: - print('old: '+name+" = "+str(old_position)) - print('new: '+name+" = "+str(new_position)) - except: - print(name+" is not a valid motor name") - - - - def dmove(self,name,val,**kwargs): - """ - relative move of a motor in the endstation based on common name, not PV name - name = x,y,z,th,chi,phi ... - - **kwargs: - wait: wait for move completion before moving on => True/False; default=True - verbose: print old and new motor position => True/False; default=False - - Previously: motor_umove_vs_Branch - """ - kwargs.setdefault('wait',True) - kwargs.setdefault('verbose',False) - - self.move(name,val,relative=True,wait=kwargs['wait'],verbose=kwargs['verbose']) - - def mprint(self,name=''): - """ - prints current position of the physical motors - """ - position_list = [name] - for motor in self.physical_motors: - position_list.append(self.get(motor)) - return position_list - - def mvsample(self,position_list,verbose=True): - """ - moves the sample to the position sepcified by position_list - position_list = ['description',x,y,z,th,chi,phi] - - Previously: sample - """ - if not isinstance(position_list[0],str): - sample_name = '' - else: - sample_name = position_list[0] - position_list = position_list[1:] - - motor_list = self.physical_motors - #debug - print('motor_list=',motor_list) - print('position_list=',position_list) - for i,motor in enumerate(motor_list): - self.move(motor,position_list[i]) - - if verbose: - print("Sample now @ "+sample_name) - - def scan(self,name,start,stop,step,**kwargs): - """ - scans a motor - - **kwargs: - relative: move mode => True/False; default = False (absolute) - scan_dim: 1 (default) - execute: True/False to start the scan => True (default) - - for Kappa only: - cts: scaler integration time in seconds (default = 0.1 s) - mpa: True/False to sum mpa acquisitions - - Previously Scan_ARPES_motor / Scan_Kappa_motor - """ - kwargs.setdefault('relative',False) - kwargs.setdefault('scan_dim',1) - kwargs.setdefault('execute',True) - - #for kappa only - kwargs.setdefault('cts',0.1) - kwargs.setdefault('mpa',False) - - motor_pvs = self._motor_dictionary.get(name) - if motor_pvs: - rbv_pv,val_pv,sgm_pv,pv = motor_pvs - else:#here - print_warning_message('motor = "'+str(name)+'" is not defined for '+iex.BL.endstation_name) - return - - if kwargs['relative']: - current_value = caget(rbv_pv) - abs_start = round(current_value + start,3) - abs_stop = round(current_value + stop,3) - print("start, stop, step = "+str(abs_start)+", "+str(abs_stop) - +", "+str(step)) - else: - abs_start = start - abs_stop = stop - - scaler_cts(kwargs['cts'],verbose=True) - iex.BL.mda.fillin(val_pv,rbv_pv,abs_start,abs_stop,step,**kwargs) - - if kwargs['execute']: - iex.BL.mda.go(**kwargs) - - - def scan_2D(self,inner_loop_list,outer_loop_list,**kwargs): - """ - Fills in a the Scan Record for a 2D scan (Mesh), does NOT press go - InnerMotorList=[name1,start1,stop1,step1] #scanDIM=2 - OuterMotorList=[name2,start2,stop2,step2] #scanDIM=3 - name = 'x'/'y'/'z'/'th'... - - **kwargs: - relative: scab => True/False; default = False (absolute) - outer_scan_dim: 2 (default) - execute: True/False to start the scan => True (default) - snake; testing - - - for Kappa only: - cts: scaler integration time in seconds (default = 0.1 s) - mpa: True/False to sum mpa acquisitions - - """ - kwargs.setdefault('mode','absolute') - kwargs.setdefault('outer_scan_dim',2) - kwargs.setdefault('snake',False) - kwargs.setdefault('execute',True) - kwargs.setdefault('debug',False) - - #for kappa only - kwargs.setdefault('cts',0.1) - kwargs.setdefault('mpa',False) - - rbv_pv,val_pv,sgm_pv,pv = self._motor_dictionary[inner_loop_list[0]] - inner_loop_list.pop(0) - inner_loop_list.insert(0,rbv_pv) - inner_loop_list.insert(0,val_pv) - - rbv_pv,val_pv,sgm_pv,pv = self._motor_dictionary[outer_loop_list[0]] - outer_loop_list.pop(0) - outer_loop_list.insert(0,rbv_pv) - outer_loop_list.insert(0,val_pv) - - if kwargs['debug']: - print('inner_loop_list = ',inner_loop_list) - print('outer_loop_list = ',outer_loop_list) - - if kwargs["mode"] == "relative": - current_value1 = caget(inner_loop_list[1]) - inner_loop_list[2]=round(current_value1+inner_loop_list[2],3) - inner_loop_list[3]=round(current_value1+inner_loop_list[3],3) - - current_value2 = caget(outer_loop_list[1]) - outer_loop_list[2]=round(current_value1+outer_loop_list[2],3) - outer_loop_list[3]=round(current_value1+outer_loop_list[3],3) - - scaler_cts(kwargs['cts'],verbose=True) - iex.BL.mda.fillin_2D(inner_loop_list,outer_loop_list,**kwargs) - - if kwargs['execute']: - kwargs.update({'scan_dim':kwargs['outer_scan_dim']}) - iex.BL.mda.go(**kwargs) - - - - -############################################################################################################## -############################## Motor Short Names ############################## -############################################################################################################## -### x ### -def mvx(val,**kwargs): - """ moves x motor in the endstation""" - iex.BL.motors.move('x',val,**kwargs) - -def dmvx(delta): - """ relative x motor in the endstation""" - iex.BL.motors.move('x',delta,relative=True) - -def scanx(start,stop,step,**kwargs): - """ scans the x motor in the endstation""" - iex.BL.motors.scan("x",start,stop,step,**kwargs) - -def dscanx(start,stop,step,**kwargs): - """relative scans of the x motor in the endstation """ - kwargs.update({'relative':True}) - iex.BL.motors.scan("x",start,stop,step,**kwargs) - -### y ### -def mvy(val,**kwargs): - """ moves y motor in the endstation""" - iex.BL.motors.move('y',val,**kwargs) - -def dmvy(delta): - """ relative y motor in the endstation""" - iex.BL.motors.move('y',delta,relative=True) - -def scany(start,stop,step,**kwargs): - """ scans the y motor in the endstation""" - iex.BL.motors.scan("y",start,stop,step,**kwargs) - -def dscany(start,stop,step,**kwargs): - """relative scans of the y motor in the endstation """ - kwargs.update({'relative':True}) - iex.BL.motors.scan("y",start,stop,step,**kwargs) - -### z ### -def mvz(val,**kwargs): - """ moves z motor in the endstation""" - iex.BL.motors.move('z',val,**kwargs) - -def dmvz(delta): - """ relative z motor in the endstation""" - iex.BL.motors.move('z',delta,relative=True) - -def scanz(start,stop,step,**kwargs): - """ scans the z motor in the endstation""" - iex.BL.motors.scan("z",start,stop,step,**kwargs) - -def dscanz(start,stop,step,**kwargs): - """relative scans of the z motor in the endstation """ - kwargs.update({'relative':True}) - iex.BL.motors.scan("z",start,stop,step,**kwargs) - -### kth ### -def mvkth(val,**kwargs): - """ moves kth motor in the endstation""" - iex.BL.motors.move('kth',val,**kwargs) - -def dmvkth(delta): - """ relative kth motor in the endstation""" - iex.BL.motors.move('kth',delta,relative=True) - -def scankth(start,stop,step,**kwargs): - """ scans the kth motor in the endstation""" - iex.BL.motors.scan("kth",start,stop,step,**kwargs) - -def dscankth(start,stop,step,**kwargs): - """relative scans of the kth motor in the endstation """ - kwargs.update({'relative':True}) - iex.BL.motors.scan("kth",start,stop,step,**kwargs) - -### kphi ### -def mvkphi(val,**kwargs): - """ moves kphi motor in the endstation""" - iex.BL.motors.move('kphi',val,**kwargs) - -def dmvkphi(val): - """ relative kphi motor in the endstation""" - iex.BL.motors.move('kphi',val,relative=True) - -def scankphi(start,stop,step,**kwargs): - """ scans the kphi motor in the endstation""" - iex.BL.motors.scan("kphi",start,stop,step,**kwargs) - -def dscankphi(start,stop,step,**kwargs): - """relative scans of the kphi motor in the endstation """ - kwargs.update({'relative':True}) - iex.BL.motors.scan("kphi",start,stop,step,**kwargs) - -### kap ### -def mvkap(val,**kwargs): - """ moves kap motor in the endstation""" - iex.BL.motors.move('kap',val,**kwargs) - -def dmvkap(delta): - """ relative kap motor in the endstation""" - iex.BL.motors.move('kap',delta,relative=True) - -def scankap(start,stop,step,**kwargs): - """ scans the kap motor in the endstation""" - iex.BL.motors.scan("kap",start,stop,step,**kwargs) - -def dscankap(start,stop,step,**kwargs): - """relative scans of the kap motor in the endstation """ - kwargs.update({'relative':True}) - iex.BL.motors.scan("kap",start,stop,step,**kwargs) - -### tth ### -def mvtth(val,**kwargs): - """ moves tth motor in the endstation""" - iex.BL.motors.move('tth',val,**kwargs) - -def dmvtth(delta): - """ relative tth motor in the endstation""" - iex.BL.motors.move('tth',delta,relative=True) - -def scantth(start,stop,step,**kwargs): - """ scans the tth motor in the endstation""" - iex.BL.motors.scan("tth",start,stop,step,**kwargs) - -def dscantth(start,stop,step,**kwargs): - """relative scans of the tth motor in the endstation """ - kwargs.update({'relative':True}) - iex.BL.motors.scan("tth",start,stop,step,**kwargs) - -### th ### -def mvth(val,**kwargs): - """ moves th motor in the endstation""" - iex.BL.motors.move('th',val,**kwargs) - -def dmvth(delta): - """ relative th motor in the endstation""" - iex.BL.motors.move('th',delta,relative=True) - -def scanth(start,stop,step,**kwargs): - """ scans the th motor in the endstation""" - iex.BL.motors.scan("th",start,stop,step,**kwargs) - -def dscanth(start,stop,step,**kwargs): - """relative scans of the th motor in the endstation """ - kwargs.update({'relative':True}) - iex.BL.motors.scan("th",start,stop,step,**kwargs) - -### chi ### -def mvchi(val,**kwargs): - """ moves chi motor in the endstation""" - iex.BL.motors.move('chi',val,**kwargs) - -def dmvchi(val): - """ relative chi motor in the endstation""" - iex.BL.motors.move('chi',val,relative=True) - -def scanchi(start,stop,step,**kwargs): - """ scans the chi motor in the endstation""" - iex.BL.motors.scan("chi",start,stop,step,**kwargs) - -def dscanchi(start,stop,step,**kwargs): - """relative scans of the chi motor in the endstation """ - kwargs.update({'relative':True}) - iex.BL.motors.scan("chi",start,stop,step,**kwargs) - -### phi ### -def mvphi(val,**kwargs): - """ moves phi motor in the endstation""" - iex.BL.motors.move('phi',val,**kwargs) - -def dmvphi(delta): - """ relative phi motor in the endstation""" - iex.BL.motors.move('phi',delta,relative=True) - -def scanphi(start,stop,step,**kwargs): - """ scans the phi motor in the endstation""" - iex.BL.motors.scan("phi",start,stop,step,**kwargs) - -def dscanphi(start,stop,step,**kwargs): - """relative scans of the phi motor in the endstation """ - kwargs.update({'relative':True}) - iex.BL.motors.scan("phi",start,stop,step,**kwargs) - - -def scan_motors_2D(inner_loop_list,outer_loop_list,**kwargs): - """ - 2D motor scans - - usage: - scan_motors_2D(["x",-5,5,.25],["z",141.5-5,141.5+5,.25]) - """ - iex.BL.motors.scan_2D(inner_loop_list,outer_loop_list,**kwargs) - -######## mprint and mvsample ################### -def mprint(name=''): - """ - prints current position of the physical motors - """ - vals = iex.BL.motors.mprint(name) - print(vals) - - return vals - -def mvsample(position_list): - """ - moves the sample to the position sepcified by position_list - position_list = ['description',x,y,z,th,chi,phi] - - Previously: sample - """ - iex.BL.motors.mvsample(position_list) \ No newline at end of file diff --git a/build/lib/iexcode/instruments/Scienta.py b/build/lib/iexcode/instruments/Scienta.py deleted file mode 100644 index 66ebb4e92b9938b4dd98348afcd250ff28df690c..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/Scienta.py +++ /dev/null @@ -1,588 +0,0 @@ -import time -import numpy as np -from epics import caget,caput, PV - - -#----------------------------------------------- -#--- Beamline dependent PVs and definitions --- -#----------------------------------------------- -P="29idcScienta:" -PHV=P+'HV:' -Pcam =P+'basler:cam1:' -savePlugin = P+"HDF1:" -statsPlugin = P+"Stats4:" -dtype = "h5" -#energy scaling -KEpix=0.0000845#*PE -KEwidth=0.1085#*PE - - -def AllowedEnergyRange(*args): - """ - KEmin, KEmax for a given PassEnergy, LensMode combination - *args - = PassEnergy, LensMode => returns KEmin,KEmax - = empty => returns entire table - - """ - Table={} - Table['Transmission']={1:(0,76),2:(0,107),5:(1,237),10:(1,453),20:(3,968),50:(7,6041),100:(21,6000),200:(30,6206),500:(283,6504)} - Table['Angular']={1:(None,None),2:(1,52),5:(2,131),10:(2,262),20:(10,523),50:(24,1309),100:(34,6105),200:(230,6206),500:(None,None)} - Table['Angular_01']={1:(None,None),2:(None,None),5:(None,None),10:(None,None),20:(None,None),50:(126,2947),100:(252,1401),200:(844,1261),500:(None,None)} - Table['Angular_05']={1:(None,None),2:(None,None),5:(None,None),10:(None,None),20:(None,None),50:(None,None),100:(252,1323),200:(1043,1270),500:(None,None)} - - if len(args)<1: - return Table - - if len(args)==2: - try: - PassEnergy,LensMode=args - KEmin,KEmax=Table[LensMode][PassEnergy] - return KEmin,KEmax - except: - return None - else: - print('Not a valid argument') - -############################################################# -########### Scienta python control functions ################ -############################################################# - -class Scienta: - """ - Scienta only talks in 'KE' anything related to the binding energy happens outside of these - controls - Usage: - EA=Scienta() - EA.get(); cagets all Scienta parameters and returns vars(EA); dictionary of variables - EA.PE(),EA.KE(),EA.LensMode() - """ - - def __init__(self): - #High Voltage Setting - self.PHV = PHV - self._Pcam=Pcam - self._savePlugin=savePlugin - self._statsPlugin=statsPlugin - - self.dtype=dtype - self.wk = None - - self.ElementSet = None #HV for XPS, LV for UPS - - self.LensMode = None - self.PassEnergy = None - self.KineticEnergy = None - self.SpectraMode = None - - self.connected = None - - #Camera Settings - self.Frames = None - - #external variables - self.Motors = None - - pv = PV(self.PHV+"WorkFunction") - time.sleep(1) - if pv.connected: - self.get() - self.connected = True - else: - self.connected = False - print("Scienta is not connected") - return - - def get(self,q=1): - """ - Gets the current Scienta parameters - returns the dictionary for q!=1 - """ - - for key in vars(self): - if key not in ["PHV","_Pcam","_savePlugin","_statsPlugin","wk","Frames","dtype","connected","Motors"]: - vars(self)[key]=caget(self.PHV+key+".VAL") - if key in ["LensMode","SpectraMode"]: - vars(self)[key]=caget(self.PHV+key+".VAL",as_string=True) - if key == "Frames": - vars(self)[key]=caget(self.PHV.split(':')[0]+':'+"ExpFrames.VAL") - if key == "wk": - vars(self)[key]=caget(self.PHV+"WorkFunction") - if q !=1: - for key in vars(self): - print(key+" = "+str(vars(self)[key])) - return vars(self) - - def counts(self): - """ - returns the current intensity on the Scienta using EA. - """ - return caget(self._savePlugin+"Total_RBV") - - def _errorCheck(self,KineticEnergy,PassEnergy,LensMode,Frames,**kwargs): - """ - check the parameters to see if they are allowed - - returns list of errors - **kwargs: - debug=False - """ - kwargs.setdefault('debug',False) - if kwargs['debug']: - print("\n _errorCheck") - error=[] - - if LensMode not in AllowedEnergyRange().keys(): - error.append("LensMode = "+LensMode+" is not a valid") - elif PassEnergy not in AllowedEnergyRange()[LensMode]: - error.append("PassEnergy = "+str(PassEnergy)+" is not a valid") - try: - KEmin,KEmax=AllowedEnergyRange(PassEnergy,LensMode) - if KEmin>KineticEnergy or KineticEnergy>KEmax: - error.append("Kinetic Energy: "+str(KineticEnergy)+" is outside allowed range for this Lens Mode,Pass Energy combination") - except: - error.append("Undefined PassEnergy/LensMode Combination "+str(PassEnergy - )+"/"+LensMode) - if Frames < 1: - error.append("Frames must be 1 or greater") - return error - - def put(self, KE=None, PE=None, LensMode="Angular",Frames=1,**kwargs): - """ - Used to set all the SES parameters at once - KE = kinetic energy (None keeps the current KE) - PE = pass energy (None keeps the current PE) - LensMode = "Angular"/"Transmission" - - **kwargs - debug - """ - - kwargs.setdefault('debug',False) - parms=self.get(q=1) - if kwargs['debug']: - print("\n EA.put") - print('KE,PE,LensMode,Frames = ',KE,PE,LensMode,Frames) - time.sleep(.1) - if KE != None: - parms.update({"KineticEnergy":KE}) - else: - parms.update({"KineticEnergy":self.KineticEnergy}) - if PE != None: - parms.update({"PassEnergy":PE}) - else: - parms.update({"PassEnergy":self.PassEnergy}) - parms.update({"LensMode":LensMode}) - parms.update({"Frames":Frames}) - - if kwargs['debug']: - print("parms:",parms) - - time.sleep(.5) - self._setHV(parms) - - def _setHV(self,parms,**kwargs): - """ - Error checks and sets the Scienta high voltage supplies - parms={'LensMode':LensMode, - 'PassEnergy':PassEnergy - 'KineticEnergy':KineticEnergy, - 'Frames':Frames} - - kwargs: - q: quiet (default = 1); to print the dictionary q!=1 - """ - kwargs.setdefault('q',1) - kwargs.setdefault('debug',False) - - if kwargs['debug']: - print('\n _setHV') - print(parms) - - #checking for errors - error=self._errorCheck(parms['KineticEnergy'],parms['PassEnergy'],parms['LensMode'],parms['Frames']) - if kwargs['debug']: - print(error) - - #setting Frames - self._frames(parms['Frames']) - - if len(error) == 0: - caput(self.PHV+"LensMode",parms["LensMode"]) - time.sleep(.25) - caput(self.PHV+"PassEnergy_Set",str(int(parms["PassEnergy"]))) - time.sleep(0.25) - caput(self.PHV.split(':')[0]+':'+"ExpFrames",parms["Frames"]) - time.sleep(.25) - caput(self.PHV+"KineticEnergy",parms["KineticEnergy"]+0.01) - time.sleep(1) - caput(self.PHV+"KineticEnergy",parms["KineticEnergy"]) - time.sleep(1) - - self.get() - if kwargs['q'] !=1: - for key in vars(self):print(key+" = "+str(vars(self)[key])) - - else: - for e in error: - #print(e) #JM need to modify - x=5 - return - - def off(self,quiet=True): - """ - Zeros the high voltage supplies - """ - self.zeroSupplies() - if quiet == False: - print ("EA HV is zeroed, visually confirm") - - def zeroSupplies(self): - """ - Zeros the Scienta HV supplies (safe-state) - """ - caput(self.PHV+"ZeroSupplies.RVAL",1) - caput(self.PHV+"ZeroSuppliesSeq.PROC",1) - - - def KE(self,val): - """ - Sets the kinetic energy of the Scienta - KE should be grearter than the PassEnergy - """ - self.put(KE=val) - - - def _setwk(self,val): - """ - Sets the wk to the value specified - """ - caput(self.PHV+"WorkFunction",val) - - def PE(self,val): - """ - Sets the pass energy of the Scienta - PassEnergy: 1, 2, 5, 10, 20, 50, 100, 200, 500 - """ - self.put(PE=val) - - def lensMode(self,val): - """ - Sets the pass energy of the Scienta - LensMode: 'Transmission','Angular','Angular_01','Angular_05' - """ - self.put(LensMode=val) - - def _frames(self,val,q=1): - """ - Sets the number of frames - Frames >=1 - """ - caput(self.PHV.split(':')[0]+':'+"ExpFrames.VAL",val) - - - def _ElementSet(self,mode,q=1): - """ - Used to switch between - 0: High Energy (XPS) and 1:Low Energy (UPS) mode - Must be done in conjunction with changing the cabling on the front of the HV supply - mode = 0 or 1 - """ - caput(self.PHV+"ElementSet",mode) - self.get() - if q !=1: - for key in vars(self):print(key+" = "+str(vars(self)[key])) - return - - - def _BurstSupplies(self,val): - """ - BurstSupplies:'Fast','Slow' - """ - caput(self.PHV+"BurstSupplies",val,as_string=True) - - def _AcqCalc(self,val): - """ - AcqCalc:'Off','Live','Scan' - """ - caput(self.PHV+"AcqCalc",val,as_string=True) - - def _AcquisitionMode(self,val): - """ - AcquisitionMode: 'Off','Scan','Spectra' - """ - caput(self.PHV+"AcquisitionMode",val) - - def _ScientaMode(self,val): - """ - ScientaMode: 'BetaScan','XYScan','Fixed','BabySweep','SweepOverlapping','SweepNo' - """ - caput(self.PHV+"ScientaMode",val,as_string=True) - - - def _babySweepSteps(self,val): - """ - sets the number of steps in baby sweep - """ - caput(self.PHV+"babySweepSteps.VAL",val) - - def _spectraStatus(self): - """ - checking the spectra status - returns 1=busy or 0=idle - """ - status=caget(self.PHV+'ScanTrigger') - return status - - def _spectraProgress(self): - """ - Monitors the spectra status every 30 seconds - returns 0 when the spectra scan is idle - """ - while True: - status=self._spectraStatus() - if (status==1): - time.sleep(30) - else: - break - return 0 - - def _SpectraMode(self,Mode): - """ - Checks that Mode exists and sets the mode - - """ - DefinedModes=["Fixed","Baby-Sweep","Sweep"] - if Mode in DefinedModes: - caput(self.PHV+"SpectraMode", "Mode") - else: - print("Not a defined SpectraMode") - - def _spectraInfo(self): - """ - returns the pertainent information for a given spectra type - modeNum=2; Swept=[start,stop,step] - """ - modeNum=caget(self.PHV+"SpectraMode") - scanType=caget(self.PHV+"SpectraMode",as_string=True) - info=[] - if modeNum==2: #swept - info.append(caget(self.PHV+"sweepStartEnergy")) - info.append(caget(self.PHV+"sweepStopEnergy")) - info.append(caget(self.PHV+"sweepStepEnergy")) - elif modeNum==1: #baby-swept - info.append(caget(self.PHV+"babySweepCenter.VAL")) - elif modeNum==0: #fixed - info.append(caget(self.PHV+"fixedEnergy.VAL")) - return scanType,info - - def live(self,KE=None,PE=None,LensMode="Angular"): - """ - puts the Scienta back in live mode (no savinga and Fixed Mode) with PE and KE - if PE or KE is None then uses the current value - """ - if self.spectraProgress() != 1: - parms=self.get() - caput('29idcScienta:HV:LiveSeq',1) - self.put(KE,PE,LensMode) - else: - print("Scienta spectra in progress") - - def _updateAttributes(self,filepath=None): - """ - filepath is the full path to the xml file - filepath = None; to update after making changes - filepath='/xorApps/epics/synApps_6_1/ioc/29idcScienta/iocBoot/ioc29idcScienta/HDF5Attributes.xml' - - from 29idcScienta:HDF1: screen - More (under process plugin) - NDPluginBase Full - """ - if filepath is None: - print(caget(self._savePlugin+"NDAttributesFile",as_string=True)) - else: - caput(self._savePlugin+"NDAttributesFile",filepath) - time.sleep(1) - print(caget(self._savePlugin+"NDAttributesStatus",as_string=True)) - - - def _spectraErrorCheck(self,KElist,PassEnergy,Frames,LensMode,**kwargs): - """ - error checking to see if parameters are allowed - """ - error=[] - parms={} - for KE in list(KElist[0:-1]): - error=self._errorCheck(KE,PassEnergy,LensMode,Frames,**kwargs) - - if len(error) > 0: - print(error) - return error - - def _spectra_Swept(self,KEstart,KEstop,KEstep,PE): - """ - setting up for a swept spectra, does not set the LensMode, PassEnergy or Frames - """ - print("setting SpectraMode") - caput(self.PHV+"SpectraMode", "Sweep") - time.sleep(1) - #input pass energy setpoint (doesn't change util KE is changed but needed for calcs) - caput(self.PHV+"PassEnergy_Set",PE) - time.sleep(0.25) - #input spectra parameters - caput(self.PHV+"sweepStartEnergy.VAL",KEstart);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) - time.sleep(1) - #Re-Calc - #print('Yes Re-Calc') - #caput(self.PHV+"SweepReCalc.PROC",1) - #time.sleep(1) - #Load spectra parameters - caput(self.PHV+"SweepLoadFanout.PROC",1) - time.sleep(1) - - - def _spectra_BabySwept(self, KEcenter): - """ - setting up for a Baby-Swept - """ - #setting SpectraMode - caput(self.PHV+"SpectraMode", "Baby-Sweep") - time.sleep(1) - #input spectra parameters - caput(self.PHV+"babySweepCenter.VAL",KEcenter) - time.sleep(1) - #Load spectra parameters - caput(self.PHV+"SweepLoadFanout.PROC",1) - time.sleep(1) - #settling time - #caput(self.PHV+"scan2.PDLY",0.25) - #caput(self.PHV+"scan2.DDLY",0.1) - - def _spectra_Fixed(self,KEcenter): - """ - setting up for Fixed - """ - #setting SpectraMode - caput(self.PHV+"SpectraMode", "Fixed") - caput("29idcScienta:HV:SpectraMode", "Fixed") - time.sleep(1) - #input spectra parameters - caput(self.PHV+"fixedEnergy.VAL",KEcenter) - time.sleep(1) - - def _spectraSetup(self,EAlist,**kwargs): - """ - Writes EAlist to the appropriate PVs and does error checking - and return scanType, scanPV, KElist, parms - **kwargs - run = True; will write the PVs (False just does error checking) - LensMode = "Angular" - debug = False - - """ - kwargs.setdefault("debug",False) - kwargs.setdefault("run",True) - kwargs.setdefault("LensMode","Angular") - - if kwargs['debug']: - print("\n\n _spectraSetup") - print("EAlist",EAlist) - - scanType="spectra" - if EAlist[-1] == "BS": - BS=True - EAlist=EAlist[0:-1] - else: - BS=False - Sweeps=EAlist[-1] - Frames=EAlist[-2] - PassEnergy=EAlist[-3] - EnergyMode=EAlist[0] - KElist=np.array(EAlist[1:-3]) - LensMode=kwargs['LensMode'] - - - if kwargs['debug']: - print("KElist: ",KElist) - - parms={'LensMode':LensMode,'PassEnergy':PassEnergy,'KineticEnergy':KElist[0],'Frames':Frames} - - #checking parameters are valid - error=self._spectraErrorCheck(KElist,PassEnergy,Frames,LensMode) - if len(error) == 0: #passed check - #Checking Progress - if self._spectraStatus() == 1: - print("Spectra in Progess") - - # writing scan parameters - else: - if len(EAlist)==7: #Swept Mode - scanType="Sweep" - self._spectra_Swept(KElist[0],KElist[1],KElist[2],PassEnergy) - parms={'LensMode':LensMode,'PassEnergy':PassEnergy,'KineticEnergy':KElist[0]-.01,'Frames':Frames} - elif len(EAlist)==5: #fixed or baby sweep - if BS is True: - scanType="Baby-Sweep" - self._spectra_BabySwept(KElist[0]) - parms={'LensMode':LensMode,'PassEnergy':PassEnergy,'KineticEnergy':KElist[0]-.01,'Frames':Frames} - else: - scanType="Fixed" - self._spectra_Fixed(KElist[0]) - parms={'LensMode':LensMode,'PassEnergy':PassEnergy,'KineticEnergy':KElist[0]-.01,'Frames':Frames} - else: - print("not a valid number of parameters") - #PV to initate scan" - scanPV=self.PHV+"ScanTrigger" - return scanType, scanPV, KElist, parms - - def _spectraMessage(self,scanType, scanPV, KElist): - """ - prints KE range for spectra - """ - message=str(scanType)+" scan KE: " - for KE in KElist: - message+=str(KE)+" | " - return message[0:-2] - - - - def spectra(self,EAlist,**kwargs): - """ - takes a Scienta spectra based on the number or parameters in EAlist - Sweeps are handled by scanRecord outside of this modual (see scanEA) - - Fixed Mode:["KE",CenterEnergy,PassEnergy,Frames,Sweeps] (5) - Swept Mode:["KE",StartEnergy,StopEnergy,StepEnergy,PassEnergy,Frames,Sweeps] (7) - Baby Sweep (dither):["KE",CenterEnergy,PassEnergy,Frames,Sweeps,"BS"] (6) - - **kwargs: - debug=False - run=True (executes the scan); False for error checking only - LensMode = Angular (default) - """ - kwargs.setdefault("debug",False) - kwargs.setdefault("run",True) - - #Sending Parmeters to _spectraSetup - scanType, scanPV, KElist, parms =self._spectraSetup(EAlist,**kwargs) - - if kwargs['debug']: - print(scanType,scanPV, KElist) - else: - print(scanType, "KE: ", KElist) - #Getting Filename info - fpath=caget(self._savePlugin+"FileName_RBV",as_string=True)+"_ " - fnum=caget(self._savePlugin+"FileNumber",as_string=True) - - - if kwargs['run'] is True: - dateandtime=time.strftime("%a %d %b %Y %H:%M:%S",time.localtime()) - print("\t"+fpath+fnum+" started at ",dateandtime,"\r") - self.put(parms['KineticEnergy'],parms['PassEnergy'],LensMode=parms['LensMode'],Frames=parms['Frames']) - caput(scanPV,1,wait=True,timeout=129600)#timeout=36 hours - dateandtime=time.strftime("%a %d %b %Y %H:%M:%S",time.localtime()) - print("\t"+fpath+fnum+" finished at ",dateandtime,"\r") - - diff --git a/build/lib/iexcode/instruments/VLS_PGM.py b/build/lib/iexcode/instruments/VLS_PGM.py deleted file mode 100644 index 095ac21879db6c91ab89c2ac39bf9d7fd684420a..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/VLS_PGM.py +++ /dev/null @@ -1,810 +0,0 @@ -""" -functions used for the mono -""" - -import time -import numpy as np - - -from epics import caget,caput - -import iexcode.instruments.cfg as iex -from iexcode.instruments.IEX_BL_config import * -from iexcode.instruments.utilities import print_warning_message,read_dict -from iexcode.instruments.scanRecord import * - -############################################################################################################## -################################ mono ############################## -############################################################################################################## -def mono_grating_names(): - """ - List of grating names - - """ - ext = ['C', 'D', 'E', 'F', 'G', 'H', 'I', "J", "K", "L" ] - GRT_names = ["MEG_Imp","HEG","MEG","Dummy", "not used", "not used", "not used","not used","not used","not used"] - GRT_names=GRT_names[0:3] # only use the first 3 slots - return GRT_names - -def mono_mirror_names(): - """ - List of grating names - - """ - ext = ['C', 'D', 'E', 'F', 'G', 'H', 'I', "J", "K", "L" ] - MIR_names = ["Au", "Silicon", "Carbon","not used","not used","not used","not used","not used","not used","not used"] - MIR_names=MIR_names[0:3] # only use the first 3 slots - return MIR_names - -def _mono_extensions(): - """ - extension used for the mono mirror and grating locations - """ - ext = ['C', 'D', 'E', 'F', 'G', 'H', 'I', "J", "K", "L" ] - return ext - -def mono_energy_range(GRT=None): - """ - returns hv_min,hv_max, the minimum and maxium energy achievable the the specified grating - """ - if GRT == None: - GRT = mono_grating_get() - - if GRT == 'HEG': - hv_min=120 - hv_max=2200 - else: - hv_min=120 - hv_max=3000 - return hv_min,hv_max - -def mono_get_all(verbose=False): - """ - gets hv, hv_sp,grating,mirror - - Previously: Mono_Optics - """ - d = mono_get_all_extended(verbose=False) - vals = { - 'hv':d['energy'], - 'hv_sp':d['energy_sp'], - 'grating':d['grt'], - 'mirror':d['mir'], - } - if verbose: - print(" hv: "+"%.2f" % vals['hv'], "eV, hv_sp: "+"% .2f" % vals['hv_sp']) - print(" grating : "+vals['grating'],", mirror : "+vals['mirror']) - return vals - -def _mono_grating_num(): - """returns the current grating num""" - return caget('29idmonoGRT_TYPE_MON') - -def _mono_mirror_num(): - """returns the current mirror num""" - return caget('29idmonoMIR_TYPE_MON') - -def _mono_pvs(grt_num=None,mir_num=None): - """ - returns a dictionary with all the mono pvs - """ - if grt_num is None: - grt_num = _mono_grating_num() - if mir_num is None: - mir_num = _mono_mirror_num() - - ext=_mono_extensions() - - d={ - 'energy':"29idmono:ENERGY_MON", - 'energy_sp':"29idmono:ENERGY_SP", - 'grt_density':"29idmono:GRT_DENSITY", - 'grt_offset':'29idmonoGRT:P_OFFSETS.'+ext[grt_num], - 'grt_b2':'29idmonoGRT:B2_CALC.'+ext[grt_num], - 'grt_pos':'29idmonoGRT:X_DEF_POS.'+ext[grt_num], - 'grt_LD':'29idmonoGRT:TYPE_CALC.'+ext[grt_num], - 'grt_tun0':'29idmonoGRT:TUN0_CALC.'+ext[grt_num], - 'grt_tun1':'29idmonoGRT:TUN1_CALC.'+ext[grt_num], - 'grt_tun2':'29idmonoGRT:TUN2_CALC.'+ext[grt_num], - 'grt_tun3':'29idmonoGRT:TUN3_CALC.'+ext[grt_num], - 'grt_type_sp':"29idmonoGRT_TYPE_SP", - 'grt_type_move':"29idmonoGRT:X_DCPL_CALC.PROC", - 'mir_type_sp':"29idmonoMIR_TYPE_SP", - 'mir_type_move':"29idmonoMIR:X_DCPL_CALC.PROC", - 'mono_pitch_state':'29idmono:ERDY_STS', - 'grt_P_sp':"29idmonoGRT:P_SP", - 'grt_P_status':"29idmonoGRT:P_AXIS_STS", - 'grt_P_stop':"29idmonoGRT:P.STOP", - 'grt_P_kill':"29idmonoGRT:P_KILL_CMD.PROC", - 'grt_P_enable':"29idmonoGRT:P_ENA_CMD.PROC", - 'mir_P_sp':"29idmonoMIR:P_SP", - 'mir_P_status':"29idmonoMIR:P_AXIS_STS", - 'mir_P_stop':"29idmonoMIR:P.STOP", - 'mir_P_kill':"29idmonoMIR:P_KILL_CMD.PROC", - 'mir_P_enable':"29idmonoMIR:P_ENA_CMD.PROC", - 'grt_X_sp':"29idmonoGRT:X_SP", - 'grt_X_status':"29idmonoGRT:X_AXIS_STS", - 'grt_X_stop':"29idmonoGRT:X.STOP", - 'grt_X_kill':"29idmonoGRT:X_KILL_CMD.PROC", - 'grt_X_enable':"29idmonoGRT:X_ENA_CMD.PROC", - 'mir_X_sp':"29idmonoMIR:X_SP", - 'mir_X_status':"29idmonoMIR:X_AXIS_STS", - 'mir_X_stop':"29idmonoMIR:X.STOP", - 'mir_X_kill':"29idmonoMIR:X_KILL_CMD.PROC", - 'mir_X_enable':"29idmonoMIR:X_ENA_CMD.PROC", - 'mir_offset':'29idmonoMIR:P_OFFSETS.'+ext[mir_num], - 'mir_pos':'29idmonoMIR:X_DEF_POS.'+ext[mir_num], - 'mono_stop':"29idmono:STOP_CMD.PROC", - 'cff':'29idmono:CC_MON', - 'arm':'29idmono:PARAMETER.G' - - - } - return d - -def mono_get_all_extended(verbose=False): - """ - gets the mono parameters for the current grating and mirror - returns a dictionary with those values - - Previously: Mono_Optics - """ - grt_num = _mono_grating_num() - mir_num = _mono_mirror_num() - grt_names = mono_grating_names() - mir_names = mono_mirror_names() - - ext=_mono_extensions() - - pvs = _mono_pvs() - vals={ - 'grt_num':grt_num, - 'mir_num':mir_num, - 'grt':grt_names[grt_num-1], - 'mir':mir_names[mir_num-1], - 'energy':caget(pvs['energy']), - 'energy_sp':caget(pvs['energy_sp']), - 'grt_density':caget(pvs['grt_density']), - 'grt_offset':caget(pvs['grt_offset']), - 'grt_b2':caget(pvs['grt_b2']), - 'grt_pos':caget(pvs['grt_pos']), - 'grt_LD':caget(pvs['grt_LD']), - 'grt_tun0':caget(pvs['grt_tun0']), - 'grt_tun1':caget(pvs['grt_tun1']), - 'grt_tun2':caget(pvs['grt_tun2']), - 'grt_tun3':caget(pvs['grt_tun3']), - 'grt_P_status':caget(pvs['grt_P_status']), - 'mir_P_status':caget(pvs['mir_P_status']), - 'grt_X_status':caget(pvs['grt_X_status']), - 'mir_X_status':caget(pvs['mir_X_status']), - 'mir_offset':caget(pvs['mir_offset']), - 'mir_pos':caget(pvs['mir_pos']), - 'cff':caget('29idmono:CC_MON'), - 'arm':caget('29idmono:PARAMETER.G') - } - - if verbose: - for key in vals.keys(): - print(key," = ",vals[key]) - - return vals - -def mono_grating_get(): - """ - returns the grating density and the string name for the grating - """ - return mono_get_all_extended()['grt'] - -def mono_mirror_get(): - """ - returns the grating density and the string name for the grating - """ - return mono_get_all_extended()['mir'] - -def mono_energy_get(): - """ - returns the grating density and the string name for the grating - """ - return mono_get_all_extended()['energy'] - -def mono_grating_density_get(): - """ - returns the grating density and the string name for the grating - """ - return mono_get_all_extended()['grt_density'] - -def mono_energy_set(hv_eV,verbose=True): - """ - sets the mono energy - - Previously: SetMono - """ - hv_min, hv_max = mono_energy_range() - pv = _mono_pvs()['energy_sp'] - if hv_min <= hv_eV <= hv_max: - caput(pv,hv_eV,wait=True,timeout=60) - time.sleep(2.5) - - mono_status = mono_status_get() - while True: - if mono_status > 1: - mono_resest_pitch() - caput(pv,hv_eV,wait=True,timeout=60) - time.sleep(2.5) - else: - break - if verbose: - print("Mono set to",str(round(hv_eV,3)),"eV") - -def mono_scan_pvs(): - """ - returns the pvs to be used in scanning - """ - val_pv = _mono_pvs()['energy_sp'] - rbv_pv = _mono_pvs()['energy'] - return val_pv, rbv_pv - -def mono_status_get(): - """ - returns the status of the mirror (GRT * MIR) - 1 = ready - 2 = moving - - - Previously Mono_Status - """ - pvs = _mono_pvs() - mir_P_status = int(caget(pvs['mir_P_status'])) - grt_P_status = int(caget(pvs['grt_P_status'])) - mir_X_status = int(caget(pvs['mir_P_status'])) - grt_X_status = int(caget(pvs['grt_P_status'])) - mirror_status = mir_P_status * mir_X_status - grating_status = grt_P_status * grt_X_status - return mirror_status*grating_status - -def mono_grating_set(grating_name,verbose=True): - """ - Translate between the different grating positions - list grating_name: mono_grating_names() - - Warning: this does not close the shutters use xrays:mirror - - Previously: Move_GRT - """ - _mono_optic_change('grating',grating_name, verbose) - -def mono_mirror_set(mirror_name,verbose=True): - """ - Translate between the different mirror positions - list mirror_name: mono_mirror_names() - - Warning: this does not close the shutters - - """ - _mono_optic_change('mirror',mirror_name, verbose) - -def _mono_optic_change(optic,name, verbose=True): - """ - optic = 'mirror','grating' - """ - - hv_eV = mono_energy_get() - - try: - if optic == 'grating': - num = mono_grating_names().index(name)+1 - elif optic == 'mirror': - num = mono_mirror_names().index(name)+1 - except: - print_warning_message(name+' not a valid '+optic) - return - - pvs = _mono_pvs () - if optic == 'grating': - type_get = mono_grating_get() - type_sp = pvs['grt_type_sp'] - type_move = pvs['grt_type_move'] - elif optic == 'mirror': - type_get = mono_mirror_get() - type_sp = pvs['mir_type_sp'] - type_move = pvs['mir_type_move'] - else: - print('Error: optic = ',optic,' not a valid choice') - return - - if type_get != name: - caput(type_sp,num,wait=True,timeout=18000) - caput(type_move,1,wait=True,timeout=18000) - - while True: - if mono_status_get() > 1: - time.sleep(5) - else: - break - mono_energy_set(hv_eV) - - else: - if verbose: - print(optic+" is already "+name) - - if verbose: - print("Mono "+optic+":",name) - -def mono_resest_pitch(): - """ - resets the MIR and GRT pitch interlocks after a following error or limit - Previoulsy part of SetMono - """ - pv=_mono_pvs() - caput(pv['grt_P_stop'],1) - time.sleep(1) - caput(pv['mir_P_stop'],1) - time.sleep(1) - print('Mono pitch was reset') - -def mono_kill(): - """ - kills the mono pitch motors - - Previously: Kill_Mono - """ - pv=_mono_pvs() - caput(pv['grt_P_kill'],1) - caput(pv['mir_P_kill'],1) - caput(pv['grt_X_kill'],1) - caput(pv['mir_X_kill'],1) - time.sleep(5) - mono_stop() - - - -def mono_stop(): - """ - presses the stop button on the mono motors - - Previously: Stop_Mono - """ - pv=_mono_pvs() - caput(pv['mono_stop'],1) - time.sleep(5) - -def mono_enable(): - """ - re-enable the mono motors - - Previously: Enable_Mono - """ - pv=_mono_pvs() - caput(pv['grt_P_enable'],1) - caput(pv['mir_P_enable'],1) - caput(pv['grt_X_enable'],1) - caput(pv['mir_X_enable'],1) - -def mono_limits_reset(): - """ - resest the mono low limit to 200 - was changed in the pmac to the wrong value so we need to do this - - Previously: Reset_Mono_Limits - """ - - pv=_mono_pvs()['energy_sp'] - caput(pv+".DRVL",200) - caput(pv+".LOW",200) - caput(pv+".LOLO",200) - caput(pv+".LOPR",200) - print("Mono limits have been reset.") - - -def mono_parameters_pv(grt_num=None,mir_num=None): - """ - returns dictionary with mono_parameter for current grating/mirror - """ - pvs=_mono_pvs(grt_num,mir_num) - - - d={ - 'mir_offset':pvs['mir_offset'], - 'mir_pos':pvs['mir_pos'], - 'grt_offset':pvs['grt_offset'], - 'grt_pos':pvs['grt_pos'], - 'grt_density':pvs['grt_density'], - 'grt_b2':pvs['grt_b2'] - } - return d - - -def mono_parameters_get(): - """ - Gets the mono parameters and prints them for the History - - Previously: Mono_Parameters_Get - """ - date=time.strftime("%Y%m%d",time.localtime()) - mirList = mono_mirror_names() - grtList = mono_grating_names() - pvList = _mono_extensions() - - #MIR - txt="MonoParm[\'"+date+"\']= {\n\t" - for i in range(0,len(mirList)): - d = mono_parameters_pv(mir_num=i) - mir = mirList[i] - offset = caget(d['mir_offset']) - position = caget(d['mir_pos']) - txt+="\'"+mir+"\':["+str(offset)+","+str(position)+"]," - - #GRT - txt+="\n\t" - for i in range(0,len(grtList)): - d = mono_parameters_pv(grt_num=i) - grt = grtList[i] - offset = caget(d['grt_offset']) - position = caget(d['grt_pos']) - density = caget(d['grt_density']) - b2 = caget(d['grt_b2']) - txt+="\'"+grt+"\':["+str(offset)+","+str(position)+","+str(density)+","+str(b2)+"]," - - txt+="}" - print(txt) - -def mono_parameters_history_read(date): - """ - Dictionary of Mono parameters used in Mono_Parameters(date) which sets the parameters - #MonoParm['date']={'Au':[],Si:[],'Carbon':[],'MEG_Imp':[],'HEG_JY':[],'MEG_JY':[]} - Mono_Parameters_Set(date) writes the parameters from the Dictionary - - Previously: Mono_Parameters_History - """ - #MonoParm['date']={'Au':[],Si:[],'Carbon':[],'MEG_Imp':[],'HEG_JY':[],'MEG_JY':[]} - - MonoParm=read_dict('mono_parameters.txt') - return MonoParm[date] - - -def mono_parameters_history_write(date): - """ - - Previously: Mono_Parameters_Set - """ - hv_eV=caget("29idmono:ENERGY_SP") - MonoParm=mono_parameters_history_read(date) - pvList=['C','D','E'] - mirList=["Au","Si","Carbon"] - for i in range(0,len(mirList)): - mir=mirList[i] - caput("29idmonoMIR:P_OFFSETS."+pvList[i],MonoParm[mir][0]) - caput("29idmonoMIR:X_DEF_POS."+pvList[i],MonoParm[mir][1]) - grtList=["MEG_Imp", "HEG_JY", "MEG_JY"] - for i in range(0,len(grtList)): - grt=grtList[i] - caput("29idmonoGRT:P_OFFSETS."+pvList[i],MonoParm[grt][0]) - caput("29idmonoGRT:X_DEF_POS."+pvList[i],MonoParm[grt][1]) - caput("29idmonoGRT:TYPE_CALC."+pvList[i],MonoParm[grt][2]) - caput("29idmonoGRT:B2_CALC."+pvList[i],MonoParm[grt][3]) - time.sleep (1) - mono_energy_set(hv_eV,verbose=True) - - - -def mono_temperature_interlock(): - """ - userCalcOut to monitor the temperatures on the Mono if the temperature gets too high then it closes the main shutter - #29idb:userCalcOut10.VAL =0 => OK; =1 => Too hot - - Previously: Mono_TemperatureInterlock - """ - pv='29idb:userCalcOut10' - caput(pv+'.DESC', 'Mono Temperature Interlock') - caput(pv+'.INPA','29idmono:TC1_MON CP NMS') - caput(pv+'.INPB','29idmono:TC2_MON CP NMS') - caput(pv+'.INPC','29idmono:TC3_MON CP NMS') - caput(pv+'.INPD','29idmono:TC4_MON CP NMS') - caput(pv+'.INPE','29idmono:TC5_MON CP NMS') - caput(pv+'.INPF','29idmono:TC6_MON CP NMS') - - caput(pv+'.H','31') - - caput(pv+'.CALC','A>H | B>H | C>H |D>H') - caput(pv+'OOPT','Transition To Non-zero') - caput(pv+'.OUT','PC:29ID:FES_CLOSE_REQUEST.VAL PP NMS') - - - -def mono_scan(hv_start,hv_stop,hv_step,**kwargs): - """ - fills in the scanRecord for scanning the mono - - puts the positioner in stay after scan - - **kwargs => scanRecord.fillin kwargs - positioner_settling_time: increased because busy record is too fast => 0.2 (default) - """ - kwargs.setdefault('positioner_settling_time',0.2) - - - #Setting up the ScanRecord for Mono in Table mode - val_pv, rbv_pv = mono_scan_pvs() - iex.BL.mda.fillin(val_pv,rbv_pv,hv_start,hv_stop,hv_step,**kwargs) - - #mono needs to stay and have a longer settling time - iex.BL.mda.positioner_after_scan("STAY") - - -def mono_scan_table(hv_array,**kwargs): - """ - fills in the scanRecord for scanning the mono - - puts the positioner in stay after scan - - **kwargs => scanRecord.fillin kwargs - positioner_settling_time: increased because busy record is too fast => 0.2 (default) - - """ - kwargs.setdefault('positioner_settling_time',0.2) - - #Setting up the ScanRecord for Mono in Table mode - val_pv, rbv_pv = mono_scan_pvs() - scan_fillin_table(val_pv,rbv_pv,hv_array,**kwargs) - - #mono needs to stay and have a longer settling time - iex.BL.mda.positioner_settling_time(**kwargs) - iex.BL.mda.positioner_after_scan("STAY") - -def mono_scan_after(**kwargs): - """ - resets mda after scanning the mono - """ - after_scan_pv = iex.BL.mda.default_after_scan_seq() - caput(after_scan_pv+".PROC",1) - iex.BL.mda.positioner_after_scan("PRIOR POS",**kwargs) - - -############################################################################################################## -################################ aligmnent and commissioning ############################## -############################################################################################################## -def mono_motor_move(motor,value,wait=True,timeout=18000): - """ - for pitch motor => MIR:P or GRT:P - for translation motor => MIR:X or GRT:X - - Previously: Move_FMBMono - """ - val_pv,rbv_pv = mono_motor_scan_pvs(motor) - caput(val_pv+".PREC",3) - caput(val_pv,value,wait=wait,timeout=timeout) - -def mono_motor_scan_pvs(motor): - """ - returns the rbv and val for scanning - """ - val_pv = "29idmono"+motor+"_SP" - rbv_pv = "29idmono"+motor+"_MON" - return val_pv,rbv_pv - -def mono_motor_scan(motor,start,stop,step,**kwargs): - """ - for pitch motor => MIR:P or GRT:P - for translation motor => MIR:X or GRT:X - - Previously: Scan_FMBMono - """ - val_pv,rbv_pv = mono_motor_scan_pvs(motor) - caput(val_pv+".PREC",3) # database sets .PREC==0. We want more digits than that. - - iex.BL.mda.fillin(val_pv,rbv_pv,start,stop,step,**kwargs) - -def mono_zero_order(angle): - """ - puts the beam in zero order => grating/mirror are parallel - range ~1 - 5 degrees - - Previously: Mono_zero - """ - mono_angles_set(angle,angle) - print("Mono set to zero order:") - -def mono_angles_set(alpha,beta): #JM modified to monitor the ready, moving sequentialy ended up in crash sometimes - """ - Sets the mirror pitch (alpha) and grating pitch (beta) angles - - Previously: Mono_angle - """ - alpha=alpha*1.0 - beta=beta*1.0 - pvs = _mono_pvs() - - #don't wait during move so they move in parallel (less likely to crash) - caput(pvs['mir_P_sp'],alpha) - caput(pvs['grt_P_sp'],beta) - time.sleep(0.5) #need sleep before things start moving - - while caget(pvs['mono_pitch_state']) != 1: - time.sleep(0.5) - print("MIR_pitch = "+str(alpha)+", GRT_pitch = "+str(beta)) - -def mono_pink_beam(): - """ - moves grating and mirror out of beam - x-rays will hit the pink beamstop - - Previously: Mono_pinkbeam - """ - mono_angles_set(0,0) - pvs=_mono_pvs() - mono_motor_move('MIR:X',-52,wait=False) - mono_motor_move('GRT:X',210,wait=True) - -def mono_CC(): - """ - ##used for commissioning - - Previously: Mono_CC - """ - caput("29idmonoMIR_TYPE_SP",3) - caput("29idmonoMIR:X_DCPL_CALC.PROC",0) - caput("29idmonoGRT_TYPE_SP", 10) - caput("29idmonoGRT:X_DCPL_CALC.PROC",0) - - caput("29idmono:ENERGY_SP", 440) - -def mono_grating_offset_get(grt_num=None): - pvs=_mono_pvs(grt_num,None) - return caget(pvs['grt_offset']) - -def mono_grating_offset_set(val,grt_num=None): - """ - sets the grating offset for the grating - - Previously: Mono_Set_GRT0 - """ - pvs=_mono_pvs(None,None) - caput(pvs['grt_offset'],val) - mono_get_all_extended(verbose=True) - -def mono_mirror_offset_get(mir_num=None): - pvs=_mono_pvs(None,mir_num) - return caget(pvs['mir_offset']) - -def mono_mirror_offset_set(val,mir_num=None): - """ - sets the mirror offset for the grating - - Previously: Mono_Set_MIR0 - """ - pvs=_mono_pvs(None,mir_num) - caput(pvs['mir_offset'],val) - mono_get_all_extended(verbose=True) - -def mono_grating_mirror_offsets_set(mirror_offset): - """ - changes the mirror and grating offsets to maintain parallelism - After determining parallelism (zero order a=b) - Get the correct take-off angle delta, equivalent to scan ExitSlit_Vcenter - - Previously: Mono_Set_MIR0_GRT0,MIR_GRT_Offset,Mono_Set_MIR0_GRT0_all - """ - current_vals = mono_get_all_extended(verbose=False) - energy_sp = current_vals['energy_sp'] - mirror_offset_old = current_vals['mir_offset'] - - #get current grating offsets - grating_offsets=[] - for grt_num in range(0,3): - grating_offsets.append(mono_parameters_pv(grt_num=grt_num,mir_num=None)['grt_offset']) - - #calc mirror_offset - grating_grating - mir_grt_offsets = mirror_offset_old-np.array(grating_offsets) # list of MIR-GRT for all 3 gratings - - #set mirror_offset - mono_mirror_offset_set(mirror_offset) - - #set grating_offsets - for grt_num in range(0,3): - mono_grating_offset_set(mirror_offset - mir_grt_offsets[grt_num],grt_num) - - time.sleep (1) - mono_energy_set(energy_sp) - mono_get_all_extended(verbose=True) - -def mono_grating_b2_get(grt_num=None): - pvs = _mono_pvs(grt_num,None) - return caget(pvs['grt_b2']) - -def mono_grating_b2_set(val,grt_num=None): - """ - sets the grating offset for the grating - Previously: Mono_Set_b2 - """ - hv = mono_energy_get() - pvs = _mono_pvs(grt_num,None) - caput(pvs['grt_b2t'],val) - time.sleep(1) - - mono_energy_set(hv) - mono_get_all_extended(verbose=True) - -def mono_cff_get(): - """ - print the cff tuning parameters and arm for the current grating - - Previously: Get_CFF - """ - d = mono_get_all_extended() - cff = d['cff'] - tun0 = d['grt_tun0'] - tun1 = d['grt_tun1'] - tun2 = d['grt_tun2'] - tun3 = d['grt_tun3'] - arm = d['arm'] - print(" cff : "+"%.4f" % cff , " exit arm: "+"%.1f" % arm,"mm") - print(" tun0 : "+"%.4e" % tun0 , " tun1: "+"%.4e" % tun1) - print(" tun2 : "+"%.4e" % tun2 , " tun3: "+"%.4e" % tun3) - - -def mono_cff_set(val,tune_num): - """ - sets the tuning parameters for the cff calculation - tune_num = order - - Previously: Mono_Set_cff - """ - hv = mono_energy_get() - pvs = _mono_pvs() - - #get current info - current_vals = mono_get_all_extended(verbose=False) - grt_pitch = current_vals['grt_pitch'] - mir_pitch = current_vals['mir_pitch'] - print ('Pitch grating, mirror: ',grt_pitch,mir_pitch) - - #set the tuning coeffient - tun='tun'+str(tune_num) - caput(pvs[tun],val) - time.sleep(1) - - #set then energy - mono_energy_set(hv) - - #print differences in pitch - mono_get_all_extended(verbose=False) - grt_dif = grt_pitch-current_vals['grt_pitch'] - mir_dif = mir_pitch-current_vals['mir_pitch'] - - print('Pitch grating, mirror: ',current_vals['grt_pitch'],current_vals['mir_pitch']) - print('Differences : ',grt_dif,mir_dif) - -def mono_arm_get(): - pvs = _mono_pvs() - return caget(pvs(['arm'])) - -def mono_arm_set(distance_mm): - """ - sets the exit arm for the grating - - Previously: Mono_Set_ExitArm - """ - hv = mono_energy_get() - pvs = _mono_pvs() - - #get current info - current_vals = mono_get_all_extended(verbose=False) - grt_pitch = current_vals['grt_pitch'] - mir_pitch = current_vals['mir_pitch'] - print ('Pitch grating, mirror: ',grt_pitch,mir_pitch) - - #set the exit arm - - caput(pvs(['arm']),distance_mm) - time.sleep(1) - - #set then energy - mono_energy_set(hv) - - #print differences in pitch - mono_get_all_extended(verbose=False) - grt_dif = grt_pitch-current_vals['grt_pitch'] - mir_dif = mir_pitch-current_vals['mir_pitch'] - - print('Pitch grating, mirror: ',current_vals['grt_pitch'],current_vals['mir_pitch']) - print('Differences : ',grt_dif,mir_dif) \ No newline at end of file diff --git a/build/lib/iexcode/instruments/__init__.py b/build/lib/iexcode/instruments/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/build/lib/iexcode/instruments/bakeout.py b/build/lib/iexcode/instruments/bakeout.py deleted file mode 100644 index f232c19053db8dd22a40aef771f8dc59b6469ea6..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/bakeout.py +++ /dev/null @@ -1,193 +0,0 @@ -from time import sleep -from os import mkdir -from os.path import exists - -from epics import caget,caput - -from iexcode.instruments.files_and_folders import get_next_fileNumber, check_run -from iexcode.instruments.scanRecord import * - -############################################################################################################## -############################## Scan Bakeout ############################## -############################################################################################################## - -def bakout_scan(scan_ioc_name,chamber): - """ - sets up the scan record to record temperature and pressures - - scan_ioc_name = 'ARPES', 'Kappa','Test' - chamber = "Beamline"; Yokawgawa + all beamline ion pumps and vacuum gauges - chamber = "Mono"; Beamline + mono thermocouples - chamber = "ARPES"; Beamline + ARPES pressures and temperatures - chamber = "Kappa"; Beamline + Kappa pressures and temperatures - chamber = "Stinger"; Stinger temperatures + ARPES and Kappa temperatures and pressures - - Previously: Scan_Bakeout - """ - #setting the folders and save datat - run = check_run() - folder='/net/s29data/export/data_29idb/Bakeout/' - subfolder='/'+chamber+'/'+run - prefix='mda_' - - scan_ioc = '29id'+scan_ioc_name+":" - - caput(scan_ioc+'saveData_fileSystem',folder) - caput(scan_ioc+'saveData_subDir',subfolder) - caput(scan_ioc+'saveData_baseName',prefix) - - MyPath="/net/s29data/export/data_29idb/Bakeout/"+chamber+"/"+run - print("\nBakeout folder: " + MyPath) - if not (exists(MyPath)): - mkdir(MyPath) - sleep(1) - FileNumber=1 - else: - FileNumber=get_next_fileNumber(MyPath,prefix[:-1]) - caput(scan_ioc+'saveData_scanNumber',FileNumber) - - sleep(5) - SaveStatus=caget(scan_ioc+'saveData_status',as_string=True) - SaveMessage=caget(scan_ioc+'saveData_message',as_string=True) - print("\nSave Status "+scan_ioc+" "+SaveStatus+" - "+SaveMessage) - - #setting up scan record - detector_dictionary = _bakeout_detector_dictionary(chamber) - - #caput("29idb:ca1:read.SCAN",0) - #trigger_dictionary = {1:"29idb:ca1:read"} - trigger_dictionary = {1:""} - - before_scan_pv = "" - after_scan_pv = "" - - mda_scan = ScanRecord(scan_ioc,detector_dictionary,trigger_dictionary,before_scan_pv,after_scan_pv) - - mda_scan.time_scan(99999,60) - - - -def _bakeout_detector_dictionary(chamber): - """ - returns a dictionary of the default detectors - - """ - thermocouples={ - 1:"29iddau1:dau1:001:ADC", - 2:"29iddau1:dau1:002:ADC", - 3:"29iddau1:dau1:003:ADC", - 4:"29iddau1:dau1:004:ADC", - 6:"29iddau1:dau1:006:ADC", - 7:"29iddau1:dau1:007:ADC", - 8:"29iddau1:dau1:008:ADC", - 9:"29iddau1:dau1:009:ADC", - 10:"29iddau1:dau1:010:ADC", - } - ion_gauges={ - 21:"29idb:VS1A.VAL", - 22:"29idb:VS2A.VAL", - 23:"29idb:VS3AB.VAL", - 24:"29idb:VS4B.VAL", - 25:"29idb:VS5B.VAL", - 26:"29idb:VS6B.VAL", - 27:"29idb:VS7B.VAL", - 28:"29idb:VS8C.VAL", - 29:"29idb:VS8CSP.VAL", - 30:"29idb:VS9C.VAL", - 31:"29idb:VS10C.VAL", - 32:"29idb:VS8D.VAL", - 33:"29idb:VS9D.VAL", - 34:"29idb:VS10D.VAL", - } - ion_pumps={ - 41:"29idb:IP1A.VAL", - 42:"29idb:IP2A.VAL", - 43:"29idb:IP3A.VAL", - 44:"29idb:IP3B.VAL", - 45:"29idb:IP4B.VAL", - 46:"29idb:IP5B.VAL", - 47:"29idb:IP6B.VAL", - 48:"29idb:IP7B.VAL", - 49:"29idb:IP7C.VAL", - 51:"29idb:IP8C1.VAL", - 52:"29idb:IP8C2.VAL", - 53:"29idb:IP9C.VAL", - 54:"29idb:IP10C1.VAL", - 55:"29idb:IP10C2.VAL", - 56:"29idb:IP7D.VAL", - 57:"29idb:IP8D1.VAL", - 58:"29idb:IP8D2.VAL", - 59:"29idb:IP9D.VAL", - 60:"29idb:IP10D1.VAL", - 61:"29idb:IP10D2.VAL", - } - - mono = { - 11:"29idmono:TC1_MON", - 12:"29idmono:TC2_MON", - 13:"29idmono:TC3_MON", - 14:"29idmono:TC4_MON", - 15:"29idmono:TC5_MON", - 16:"29idmono:TC6_MON", - } - - ARPES = { - 11:"29idc:VS11C.VAL", - 12:"29idc:VSCUBE.VAL", - 13:"29idc:IP11C1.VAL", - 14:"29idc:IP11C2.VAL", - 15:"29idc:IPCUBE.VAL", - 16:"29idARPES:LS335:TC1:IN1", - 17:"29idARPES:LS335:TC1:IN2", - } - - Kappa = { - 11:"29idb:VS11D.VAL", - 12:"29idb:VS12D.VAL", - 13:"29idd:LS331:TC1:SampleA", - 14:"29idd:LS331:TC1:SampleB", - } - - Stinger = { - 1:"29idc:LS340:TC2:Control", - 2:"29idc:LS340:TC2:Sample", - - 3:"29idARPES:LS335:TC1:IN1", - 4:"29idARPES:LS335:TC1:IN2", - - 5:"29idd:LS331:TC1:SampleA", - 6:"29idd:LS331:TC1:SampleB", - - 7:"29idc:VS11C.VAL", - 8:"29idc:IP11C1.VAL", - 9:"29idc:IP11C2.VAL", - - 10:"29idb:VS11D.VAL", - } - d={} - if chamber.lower() == "Beamline".lower(): - d.update(thermocouples) - d.update(ion_gauges) - d.update(ion_pumps) - print("ScanRecord ready") - - if chamber.lower() == "Mono".lower(): - d.update(thermocouples) - d.update(ion_gauges) - d.update(ion_pumps) - d.update(mono) - print('Setting up Mono temperatures') - - if chamber.lower() == "ARPES".lower(): - d.update(ARPES) - print('Setting up ARPES temperatures') - - if chamber.lower() == "Kappa".lower(): - d.update(Kappa) - print('Setting up Kappa temperatures') - - if chamber.lower() == "Stinger".lower(): - d.update(Stinger) - print('Setting up Stinger temperatures') - - return d diff --git a/build/lib/iexcode/instruments/conversions_constants.py b/build/lib/iexcode/instruments/conversions_constants.py deleted file mode 100644 index 44f84907c589a4d7965bde87e823d3fee4fc5c1a..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/conversions_constants.py +++ /dev/null @@ -1,33 +0,0 @@ -import numpy as np - -############################################################################################################## -############################## conversions ############################## -############################################################################################################## -#Plank's constant eV/s -h=4.135667516e-15 -#speed of ligh m/s -c=299792458 - -def deg2rad(angle_deg): - angle_rad=angle_deg*np.pi/180 - return angle_rad - -def rad2deg(angle_rad): - angle_deg=angle_rad*180/np.pi - return angle_deg - -def eV2Lambda(eV): - """ - Converts energy (eV) into wavelenght (Angstrom) - """ - Angstrom = h*c/eV*1e10 - return Angstrom - -def Lambda2eV(Angstrom): - """ - Converts wavelenghth (Angstrom) into energy (eV) - """ - - eV = h*c/Angstrom*1e10 - return eV - diff --git a/build/lib/iexcode/instruments/current_amplifiers.py b/build/lib/iexcode/instruments/current_amplifiers.py deleted file mode 100644 index 47327a8acac2ee40b338b0da252ab2cb8c0f729e..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/current_amplifiers.py +++ /dev/null @@ -1,441 +0,0 @@ -import numpy as np -from time import sleep - -from epics import caget, caput - -import iexcode.instruments.cfg as iex -from iexcode.instruments.userCalcs import userStringSeq_pvs, userStringSeq_clear -from iexcode.instruments.VLS_PGM import mono_energy_get - - -def ca_detector_list(branch): - """ - returns the list of keithley current amplifiers based on key - key: 'ARPES' / 'Staff' - """ - ca_list = iex.ca_list - - return ca_list - -def _ca_dictionary(): - """ - dictionary of connected Keithley and thier names - - Previously: CA_Name - """ - #For new endstation modify here: - ca={} - ca["b"] = { - 1: 'W-mesh', - 2: 'H-wire', - 3: 'V-wire', - 4: 'Slit1A', - 5: 'Slit1A', - 9: 'D2B', - 10: 'B-branch', - 12: '', - 13: 'Slit3C', - 14: 'MeshD', - 15: 'DiodeC', - } - - ca["c"] = { - 1:'TEY', - } - return ca - -############################################################################################################## -################################ Keithley ############################## -############################################################################################################## -def _Keithley_pv(ca_crate, ca_num): - """ - ca_crate = 'b' / 'c' ... - """ - return "29id"+ca_crate+":ca"+str(ca_num)+":" - -class Keithley: - """ - class for Keithley current amplifiers - """ - def __init__(self,ca_crate, ca_num): - """ - ca_crate = 'b' / 'c' ... - - """ - self._pv = _Keithley_pv(ca_crate, ca_num) - try: - self.name = _ca_dictionary()[ca_crate][ca_num] - except: - self.name = 'CA'+ca_crate+str(ca_num) - - self.current = None - self.rate = None - self.filter_num = None - self.range = None - - self.get_all(verbose=False) - - def get_all(self,verbose=False): - """ - reads the current SRS and corresponding scaler values - verbose: prints current values True/False - """ - self.current = caget(self._pv+"read") - self.range = 'Autoscale' if caget(self._pv+"rangeAuto",as_string=True)=='On' else caget(self._pv+"range",as_string=True) - self.rate = caget(self._pv+"rate") - digital_filter = caget(self._pv+'digitalFilter',as_string=True) - self.filter_num = 1 if digital_filter == 'On' else caget(self._pv+'digitalFilterCount') - - if verbose: - for key, value in vars(self).items(): - if key[0] != '_': - print(key, ' = ', value) - - def get(self,verbose=True): - """ - returns the current in Amps - """ - self.get_all(verbose=False) - current = self.current - if verbose: - print(format(current,'.3E')) - return current - - def reset(self,rate="Slow"): - """ - - Previously: Reset_CA - """ - - pv = self._pv - caput(pv+"reset.PROC",1) - sleep(.1) - caput(pv+"digitalFilterSet","Off") - caput(pv+"medianFilterSet","Off") - caput(pv+"zeroCheckSet",0) - caput(pv+"rangeAuto",1) - caput(pv+"rateSet",rate) - caput(pv+"rangeAutoUlimit","20mA") - caput(pv+"read.SCAN",".5 second") - - def autoscale(self,On_Off='On',gain=7): - """ - ca_crate = 'b' / 'c' - ca_num = 2 - - On_Off= 'On' => Turns On the Autoscale; gain is irrelevant. - On_Off= 'Off' => Turns Off the Autoscale with gain below: - 0 = 2nA - 1 = 20nA - 2 = 200nA - 3 = 2uA - 4 = 20uA - 5 = 200uA - 6 = 2mA - 7 = 20mA - - Previously: CA_Autoscale - """ - pv = self._pv - caput(pv+"rangeAutoSet",On_Off) - sleep(0.5) - caput(pv+"rangeSet",gain) - print(pv,"Autoscale",On_Off) - - if On_Off == 'Off': - sleep(1) - print("Gain set to:",caget(pv+"range",as_string=True)) - - - - def avg(self,num_averages,rate='Slow',verbose=True): - """ - Turns on the filtering for the Keithlys for average during a scan - - rate: Keithley sampling rate - 'Slow' / 'Medium' / 'Fast' - - num_averages: number of points to average - - returns the settling_time - - Previously: CA_Filter - """ - - pv = self._pv - name=self.name - t=0.1 - if rate == "Slow": - t=6/60.0 - elif rate == "Medium": - t=1/60.0 - elif rate == "Fast": - t=0.1/60.0 - - settling_time=round(max(0.15,num_averages*t+0.1),2) - - if num_averages <= 1: # no averaging - self.reset(rate) - settling_time = None - if verbose: - print("Average disabled: "+name+" - "+pv) - - else: - caput(pv+"read.SCAN","Passive",wait=True,timeout=500) - caput(pv+"rateSet",rate) - sleep(1) - caput(pv+"digitalFilterCountSet",num_averages,wait=True,timeout=500) - caput(pv+"digitalFilterControlSet","Repeat",wait=True,timeout=500) - caput(pv+"digitalFilterSet","On",wait=True,timeout=500) - - if verbose: - print("Average enabled: "+name+" - "+pv) - print("Detector settling time: "+str(settling_time)+"s") - - return settling_time - - - -def ca_reset_all(rate="Slow"): - """" - - Previously: Reset_CA_all - """ - ca_dict = _ca_dictionary() - for ca_crate in ca_dict.keys(): - for ca_num in ca_dict[ca_crate].keys(): - CA = Keithley(ca_crate,ca_num) - CA.reset() - - caput("29idb:ca5:read.SCAN","Passive") # CA5 in passive - print("\nAll the current amplifiers have been reset; ca5 set to passive.") - -def _ca_live_sequence(ioc,seq_num,detector_list): - """ - creates a string sequence to put keithleys back in live mode - - ca_list = list of ca to go in live - - Previously: CA_Live_StrSeq - """ - userStringSeq_pv, userStringSeq_proc = userStringSeq_pvs(ioc, seq_num) # do we need to add 29idb:ca5 ??? - - userStringSeq_clear(ioc,seq_num) - - caput(userStringSeq_pv+".DESC","CA Live "+ioc) - - for (i,ca) in enumerate(detector_list): - pv = "29id"+ca[0]+":ca"+str(ca[1])+":" - ca_read_pv = pv+'read.SCAN CA NMS' - ca_avg_pv = pv+'digitalFilterSet PP NMS' - - caput(userStringSeq_pv+".LNK"+str(i+1),ca_avg_pv) - caput(userStringSeq_pv+".STR" +str(i+1),"Off") - - n=len(detector_list) - if n+1+i < 10: - caput(userStringSeq_pv+".LNK" +str(n+1+i),ca_read_pv) - caput(userStringSeq_pv+".STR" +str(n+1+i),".5 second") - caput(userStringSeq_pv+".WAIT"+str(n+1+i),"After"+str(n)) - elif n+1+i == 10: - caput(userStringSeq_pv+".LNKA",ca_read_pv) - caput(userStringSeq_pv+".STRA",".5 second") - caput(userStringSeq_pv+".WAITA","After"+str(n)) - - return userStringSeq_proc - -def ca_average(avg_pts,**kwargs): - """ - Average reading of the relevant current amplifiers for the current scanIOC/branch. - ** kwargs: - - Previously: CA_average - """ - kwargs.setdefault('ca_list',ca_detector_list(iex.BL.branch)), - kwargs.setdefault('rate',"Slow") - kwargs.setdefault('verbose',True) - ca_list = kwargs['ca_list'] - - for i in range(0,len(ca_list)): - ca = Keithley(ca_list[i][0],ca_list[i][1]) - ca.avg(avg_pts,rate=kwargs['rate'],verbose=kwargs['verbose']) - - -def _load_responsivity_curve(): - """ - Loads the responsivity curve for the AUX100 photo diode, used to convert - current to flux at a given photon energy - - Previously: loadResponsivityCurve - """ - FilePath='/home/beams/29IDUSER/Documents/User_Macros/Macros_29id/IEX_Dictionaries/' - FileName="DiodeResponsivityCurve" - data = np.loadtxt(FilePath+FileName, delimiter=' ', skiprows=1) - return data - -def current2flux(current,hv=None,verbose=True): - """ - Converts the current to flux for of an AUX 100 diode using the responisity curves - - hv = None; gets the current mono energy; otherwise you will need to specify - - Previously CA2flux - """ - try: - curve=_load_responsivity_curve() - except: - print('responsivity curve not loaded') - return - responsivity=curve[:,0] - energy=curve[:,1] - charge = 1.602e-19 - if hv is None: - try: - hv = mono_energy_get() - except: - print('specify hv') - return - eff=np.interp(hv,energy,responsivity) - flux = current/(eff*hv*charge) - if verbose: - print("\nCalculating flux for:") - print(" hv = %.1f eV" % hv) - print(" current = %.3e Amp" % current) - print("Flux = %.3e ph/s\n" % flux) - return flux - - -def flux2current(flux,hv=None,verbose=True): - """ - Converts the specified flux to a current for of an AUX 100 diode using the responisity curves - - hv = None; gets the current mono energy; otherwise you will need to specify - """ - try: - curve=_load_responsivity_curve() - except: - print('responsivity curve not loaded') - return - responsivity=curve[:,0] - energy=curve[:,1] - charge = 1.602e-19 - if hv is None: - try: - hv = mono_energy_get() - except: - print('specify hv') - return - eff=np.interp(hv,energy,responsivity) - current = flux*(eff*hv*charge) - if verbose: - print("\nCalculating current for:") - print(" hv = %.1f eV" % hv) - print(" flux = %.3e ph/s" % flux) - print("Current = %.3e Amp/n" % current) - return current - - - -############################################################################################################## -################################ SRS ############################## -############################################################################################################## -class SRS: - """ - SRS current amplifier and corresponding scalers - """ - - def __init__(self,scaler_pv,srs_pv): - self._scaler_pv = scaler_pv - self._srs_pv = srs_pv - - self.scaler_value = None - self.gain = None - self.current_Amp = None - self.current_unit = None - self.invert = None - self.offset_value = None - self.offset_unit = None - self.offset_sign = None - self.offset_factor = None - self.set_all() - self.get_all(verbose=False) - - def set_all(self): - """ - set all PV to current SP values (what the screen shows in not necessarely what the PV are set to) - """ - pv=self._srs_pv+"init.PROC" - caput(pv,1) - - - def get_all(self,verbose): - """ - reads the current SRS and corresponding scaler values - """ - self.scaler_value = caget(self._scaler_pv) - self.gain = float(caget(self._srs_pv+'sens_num.VAL',as_string=True)) - self.current_unit = caget(self._srs_pv+'sens_unit.VAL',as_string=True) - self.invert = caget(self._srs_pv+'invert_on.VAL',as_string=True) - unit_sciNote = {'pA':1e-12, 'nA':1e-9, 'uA':1e-6, 'mA':1e-3} - - self.offset_value=float(caget(self._srs_pv+"offset_num.VAL",as_string=True)) - self.offset_unit=caget(self._srs_pv+"offset_unit.VAL",as_string=True) - self.offset_sign=caget(self._srs_pv+"offset_sign.VAL",as_string=True) - self.offset_factor=float(caget(self._srs_pv+"off_u_put.VAL",as_string=True)) - - - current_Amp = self.scaler_value * self.gain * unit_sciNote[self.current_unit[:-2]] - baseline = self.offset_value * self.offset_factor * unit_sciNote[self.offset_unit] - - if self.invert == 1: - current_Amp *= -1 - if self.offset_sign == '+': - self.current_Amp = current_Amp + baseline - elif self.offset_sign == '-': - self.current_Amp = current_Amp - baseline - - self.filter_type=caget(self._srs_pv+'filter_type.VAL',as_string=True) - self.filter_low=caget(self._srs_pv+'low_freq.VAL',as_string=True) - self.filter_high=caget(self._srs_pv+'high_freq.VAL',as_string=True) - self.blank=caget(self._srs_pv+'blank_on.VAL',as_string=True) - self.bias_OnOff=caget(self._srs_pv+'bias_on.VAL',as_string=True) - self.bias_value=caget(self._srs_pv+'bias_put.VAL',as_string=True) - - if verbose: - self.print_all(extended=True) - - def get(self,verbose=True): - """ - returns the current in Amps with offset removed - """ - current = self.current_Amp - if verbose: - print(format(current,'.3E')) - return current - - def setgain(self,gain,unit): - """ - gain = 1,2,5,10,20,50,100,200,500 - unit = 'pA, 'nA', 'uA', 'mA' - """ - caput(self._srs_pv+'sens_num.VAL',str(gain)) - caput(self._srs_pv+'sens_unit.VAL',str(unit)) - - - def srs_print_all(self, extended=False): - """ - prints SRS setting - """ - print('Gain: '+str(self.scaler_value)+' '+str(self.current_unit)+' (invert '+str(self.invert)+')') - print('Baseline: '+str(self.offset_sign)+' '+str(self.offset_factor)+' x '+str(self.offset_value)+" "+str(self.offset_unit)) - if extended: - filterType = str(self.filter_type) - filterLow = str(self.filter_low) - filterHigh = str(self.filter_high) - blank = str(self.blank) - biasOnOff = str(self.bias_OnOff) - biasValue = str(self.bias_value) - print('Filter: '+filterType+' - Low/High: '+filterLow+' -'+filterHigh) - print('Bias: '+biasOnOff+'- '+biasValue) - print('Blank: '+blank) - diff --git a/build/lib/iexcode/instruments/diagnostics.py b/build/lib/iexcode/instruments/diagnostics.py deleted file mode 100644 index 93705290fa35267786c94df0a14361ca4289dd8a..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/diagnostics.py +++ /dev/null @@ -1,285 +0,0 @@ -from numpy import nan - -from epics import caput, caget - -import iexcode.instruments.cfg as iex -from iexcode.instruments.SRS_current_amplifiers import Keithley,SRS -from iexcode.instruments.utilities import print_warning_message -############################################################################################################## -################################ default positions ############################## -############################################################################################################## -#For new endstation modify here: -def diagnostics_presets(): - presets={ - 'H-wire':(['OUT','Start'],'29id:m1'), - 'V-wire':(['OUT','Start'],'29id:m2'), - 'H-Diagon':(['OUT','Si-2800','ML-400','ML-460'],'29id:m3'), - 'V-Diagon':(['OUT','Si-2800','ML-400','ML-460'],'29id:m4'), - 'D1A':(['OUT','Mesh'],'29id:m5'), - 'D2B':(['OUT','Mesh','YAG'],'29id:m6'), - 'D3B':(['OUT','YAG'],'29id:m7'), - 'D4C':(['OUT','Mesh','YAG'],'29id:m17'), - 'gas-cell':(['OUT','Diode1','Diode2'],'29id:m20'), - 'D4D':(['OUT','Mesh','YAG'],'29id:m25'), - 'D5D':(['OUT','Mesh','YAG','Diode'],'29id:m6') - } - return presets - -#For new endstation modify here: -def _diagnostics_inout_dict(): - """ - dictionary to convert quick_name to preset_names - """ - #quick_name: (diag_name, preset_in,preset_out) - d={ - 'mesh_W':('D1A','Mesh','OUT'), - 'mesh_c':('D4C','Mesh','OUT'), - 'mesh_d':('D4D','Mesh','OUT'), - 'diode_c':('gas-cell','Diode1','OUT'), - 'diode_d':('gas-D4D','Diode','OUT'), - } - - return d - -#For new endstation modify here: -def _diagnostic_read_dict(): - read_dict={ - 'diode_c':Keithley('b',15), - 'mesh_d':SRS("29idMZ0:scaler1.S14", '29idd:A4'), - 'diode_d':Keithley('b',14), - } - return read_dict - -############################################################################################################## -################################ access presets ############################## -############################################################################################################## -def _diagnostics_preset_pv(diag_name,preset_name): - """ - dictionary of the motor pvs for the beamline diagnostics - """ - ioc = '29idb:' - d = diagnostics_presets() - pv=None - - if diag_name.casefold() in (key.casefold() for key in list(d.keys())): - idx = [item.lower() for item in list(d.keys())].index(diag_name.lower()) - diag_name=list(d.keys())[idx] - if preset_name.casefold() in (preset.casefold() for preset in d[diag_name][0]): - idx = [item.lower() for item in d[diag_name][0]].index(preset_name.lower()) - preset_name = d[diag_name][0][idx] - pv = ioc+diag_name+'_'+preset_name - else: - message ='preset_name = '+preset_name+' not a valid name' - message +='\npreset_names:'+str(d[diag_name][0]) - print_warning_message(message) - - else: - message = 'diag_name = '+diag_name+' not a valid name' - message +='\npreset_names:'+str(list(d.keys())) - print_warning_message(message) - - return pv - -def diagnostics_presets_go(diag_name,preset_name,wait=False): - pv = _diagnostics_preset_pv(diag_name,preset_name) - caput(pv+'_Trigger.PROC',1,wait=wait,timeout=180) - -def diagnostics_sp_read(diag_name,preset_name): - pv = _diagnostics_preset_pv(diag_name,preset_name) - caget(pv+'_Setpoint.VAL') - -def _diagnostics_sp_write(diag_name,preset_name): - pv = _diagnostics_preset_pv(diag_name,preset_name) - caget(pv+'_Setpoint.VAL') - - -############################################################################################################## -################################ quick names ############################## -############################################################################################################## -def diagnostic_name_list(verbose=True): - """ - lists all diagnostics - """ - d = _diagnostics_inout_dict() - if verbose: - for key in d.keys(): - print(key) - return list(d.keys()) - -def diagnostic(name,in_out): - """ - inserts/removes a diagnostic - use - """ - ''' - Inserts/retracts a diagnostic either = "In" or "Out" - => diagnostic_name_list: to list diagnostics - ''' - d_quick = _diagnostics_inout_dict() - if name in d_quick.keys(): - diag_name, preset_in,preset_out = d_quick[name] - if in_out.lower() == "in": - preset_name = preset_in - elif in_out.lower() == "out": - preset_name = preset_in - diagnostics_presets_go(diag_name,preset_name) - print("\n"+name+": "+ in_out) - else: - message = 'name = '+name+' is not a valid diagnostic name' - message +='\n valid names are '+str(d_quick.keys()) - print_warning_message(message) - -def diagnostics_all_out(diode_stay_in=False,mesh_stay_in=False): - """ - Retracts all diagnostic unless - diode_stay_in = True => leaves diode_c/diode_d In - mesh_stay_in = True => leaves mesh_c/mesh_d In - - Previously: AllDiagOut - """ - message = "All diagnostics out" - d_names = _diagnostics_inout_dict() - - diag_list = list(diagnostics_presets().keys()) - - #if staying remove diag_name from list - if diode_stay_in: - branch = iex.BL.branch - if branch == 'c': - diode_stay_name = d_names['diode_c'][0] - message += '\ndiode_c => In' - elif branch == 'd': - diode_stay_name = d_names['diode_d'][0] - message += '\ndiode_d => In' - diag_list.pop(diode_stay_name) - - if mesh_stay_in: - branch = iex.BL.branch - if branch == 'c': - mesh_stay_name = d_names['mesh_c'][0] - message += '\nmesh_c => In' - elif branch == 'd': - mesh_stay_name = d_names['mesh_d'][0] - message += '\nmesh_d => In' - diag_list.pop(mesh_stay_name) - - #moving the diagnostics in list - for diag_name in diag_list: - diagnostics_presets_go(diag_name,'OUT') - - #putting stays in if not already in - if diode_stay_in: - diagnostics_presets_go(diode_stay_name,'Diode') - if mesh_stay_name: - diagnostics_presets_go(mesh_stay_name,'Mesh') - - print("\n",message) - -def diagnostics_all_in(): - print("The follow diagnostics are in ") - d_names = _diagnostics_inout_dict() - for i,name in enumerate(d_names.keys()): - diag_name,preset_in,preset_out = d_names[name] - if i == len(d_names.keys())-1: - diagnostics_presets_go(diag_name,preset_in,wait=True) - else: - diagnostics_presets_go(diag_name,preset_in,wait=False) - print("\t"+name) - -def diagnostic_InOut(name,In_Out): - d_names = _diagnostics_inout_dict() - try: - diag_name,preset_in,preset_out = d_names[name] - if In_Out.lower() == 'in': - preset = preset_in - elif In_Out.lower() == 'out': - preset = preset_out - else: - print('\nIn_Out = '+In_Out+' not a valid option, must be "in" or "out"') - return - - diagnostics_presets_go(diag_name,preset_in,wait=True) - print("\n"+diag_name+" = "+preset) - except: - message = name+"not a valid diagnostic \n choose one of: " - message += list(d_names.keys()) - -def mesh_W(In_Out): - """ - Inserts/retracts the mesh in the A-hutch - - Previously MeshW - """ - diagnostic_InOut('mesh_W',In_Out) - - -def diode_c(In_Out): - """ - Inserts/retracts ARPES (gas-cell) diode - - Previously: DiodeC - """ - diagnostic_InOut('diode_c',In_Out) - - -def diode_d(In_Out): - """ - Inserts/retracts RSXS diode just before the endstation - - Previously:DiodeD - """ - diagnostic_InOut('diode_d',In_Out) - - -def mesh_d(In_Out): - """ - Inserts/retracts RSXS mesh (post-slit) - - Previoulsy: MeshD - """ - diagnostic_InOut('mesh_d',In_Out) - -def diagnostic_read(name, verbose=True): - """ - reads the current amplifier and returns the value - """ - try: - det = _diagnostic_read_dict()[name] - val=det.get(verbose) - except: - print_warning_message(name+" not in "+str(list(_diagnostic_read_dict().keys()))) - return - return val - -def diode_c_read(verbose=True): - """ - reads the current amplifier and returns the value - quiet = False to pring - """ - val = diagnostic_read('diode_c',verbose) - return val - -def mesh_d_read(verbose=True): - """ - reads the current amplifier and returns the value - quiet = False to pring - """ - val = diagnostic_read('mesh_d',verbose) - return val - -def diode_d_read(verbose=True): - """ - reads the current amplifier and returns the value - quiet = False to pring - """ - val = diagnostic_read('diode_d',verbose) - return val - - -############################################################################################### -####################################### FLUX CONVERSION ####################################### -############################################################################################### - - - - diff --git a/build/lib/iexcode/instruments/electron_analyzer.py b/build/lib/iexcode/instruments/electron_analyzer.py deleted file mode 100644 index d7c92a143556e4c24c99ee9eeb70bc25c03f71be..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/electron_analyzer.py +++ /dev/null @@ -1,804 +0,0 @@ -############################################################# -###################### Imports ############################## -############################################################# - -from os.path import join, isfile, exists, dirname -from os import mkdir -from operator import itemgetter -import time -from datetime import timedelta -from math import ceil,floor,modf - -import numpy as np -from scipy.interpolate import interp1d - -from epics import caput,caget -from iexcode.instruments.IEX_BL_config import * - -from iexcode.instruments.scanRecord import * -from iexcode.instruments.conversions_constants import * -from iexcode.instruments.xrays import energy, scanXAS, BL_energy_tables -from iexcode.instruments.shutters import branch_shutter_close -from iexcode.instruments.VLS_PGM import mono_energy_get -from iexcode.instruments.files_and_folders import get_next_fileNumber -from iexcode.instruments.Logfile import log_print -from iexcode.instruments.Scienta import * - -global EA -try: - print('connecting to Scienta') - EA = Scienta() -except: - print("EA is not connected") - -########################################################################### -def _EA_init_Motors(Motors): - """ - Adds Motors to EA object to be used in scanning - """ - EA.Motors = Motors - -def EA_ioc_init(**kwargs): - """ - run after restarting the 29idcScienta IOC - kwargs: - Close_CShutter="Close" default, if something else then it doesn't close the shutter - """ - kwargs.setdefault("close_shutter",True) - if kwargs['close_shutter']==True: - branch_shutter_close('c') - #Addding HDF5 atttributes - filepath='/xorApps/epics/synApps_6_1/ioc/29idcScienta/iocBoot/ioc29idcScienta/HDF5Attributes.xml' - EA._updateAttributes(filepath) - #Allow EA to make directories - caput('29idcScienta:HDF1:CreateDirectory',-1) - #Enabling User CalcOut, needed for BE - caput("29idcScienta:userCalcOutEnable.VAL","Enable") - #Enabling User StringCalc for caQtDM - ioc="29idcScienta:" - pv=ioc+"userStringCalc2" - caput(pv+".DESC","scan1 trigger2 calc") - caput(pv+".INAA",ioc+"scan1.T2PV CP NMS") - caput(pv+".BB",ioc+"HV:ScanTrigger") - caput(pv+".CALC$","AA==BB") - caput(ioc+"userStringCalcEnable.VAL","Enable") - - #clipping and other processing - caput("29idcScienta:Proc1:EnableLowClip","Enable") - caput("29idcScienta:Proc1:LowClip",1) - caput("29idcScienta:Proc1:EnableHighClip",'Disable') - caput("29idcScienta:Proc1:EnableOffsetScale","Enable") - caput("29idcScienta:Proc1:Scale",10) - caput("29idcScienta:Proc1:Offset",-1) - - #Global Detector Setting - caput('29idcScienta:HV:AngularROImin.VAL',290) - caput('29idcScienta:HV:AngularROImax.VAL',830) - caput('29idcScienta:HV:AngularBinning','Off') - - ### Add here - #Setting ExpFrames - caput("29idcScienta:ExpFrames.VAL",1) - #setting save default lens values - EA._AcquisitionMode('Spectra') - time.sleep(0.25) - try: - KE = mono_energy_get() - except: - KE = 2000 - EA.put(KE, PE=50, LensMode="Angular") - caput(EA.PHV+"KineticEnergy:TWV.VAL",1) - caput(EA._Pcam+"Acquire","Acquire") - - print("C-Shutter is closed for initialization ") - - -def folders_EA(userPath,filePrefix="EA",**kwargs): - """ - For Staff: folder='b', userName='Staff' - For ARPES: folder ='c' - - setFolders = True; creates the data folder and sets scanRecords/AreaDetectors - = False: only creates the data folders; does NOT set - """ - kwargs.setdefault('set_folders',True) - kwargs.setdefault('debug',False) - try: - ADplugin=EA._savePlugin - dtype=EA.dtype - if dtype == "nc": - df="netCDF" - else: - df=EA.dtype - except: - df="h5" - - fpath=join(userPath,df) - print("\nFolder: " + fpath) - - if exists(fpath): - if kwargs['debug']==True: - print("exists") - try: - fileNumber=get_next_fileNumber(fpath,filePrefix, debug=False) - except: - kwargs['create_only']=True - print("fileNumber not set, EA not connected, create_only=True") - else: - if kwargs['debug']==True: - print("making") - mkdir(fpath) - fileNumber=1 - try: - if kwargs['set_folders']: - caput(ADplugin+"FilePath",fpath) - caput(ADplugin+"FileName",filePrefix) - caput(ADplugin+"FileNumber",fileNumber) - - #setup AD - caput(ADplugin+"FileTemplate","%s%s_%4.4d."+dtype) - caput(ADplugin+"AutoIncrement","Yes") - caput(ADplugin+"AutoSave","Yes") - - print("EA path: "+fpath) - print("Next "+filePrefix+" file: "+str(fileNumber)) - except: - df='h5' - fpath=join(userPath,df) - -def EA_log_dictionary(): - """ - dictionary for writing spectra to logfile - """ - d = { - "spectra_mode":[EA.SpectraMode,"s"], - 'lens_mode':[EA.LensMode,"s"], - 'PE':[EA.PassEnergy,".0f"], - "KE":[EA.KineticEnergy,".0f"], - "sweeps":[caget(iex.BL.mda.ioc+'scan1.NPTS'),".0f"], - "frames":[EA.Frames,".0f"] - } - return d - -def EAlog_update(): - """ - spectra entries for the log file - """ - d=EA_log_dictionary() - try: - log_update(d) - except: - print("EAlog did not write to file, check for errors.") - -def EAlog_header(): - d=EA_log_dictionary() - try: - header_list,data_list,format_list = iex.BL.mda.log.log_entries(d) - iex.BL.mda.log.write_entry(header_list,label="EA Header: ") - except: - print("EAlog did not write header") - -def EA_sweptTime_estimate(EAlist,overhead=[60,.22]): - """ - estimates the time for spectra with the current analyzer settings - overhead[0] = intiating scan (seconds) - overhead[1] = per point (seconds) - """ - E=1392#image width - HVscanDIM=2 - - B=EAlist[4]*0.000078# PixelEnergy=PassEnergy*0.000078 - - C=EAlist[1]# Estart - A=ceil(EAlist[3]/B)*B # Estep - D=C+ceil((EAlist[2]-C)/A)*A # Estop - - E0=ceil((D-C)/(ceil(A/B)*B)) - E1=E/min(floor(ceil(A/B)+0.001),E) - E2=(E/min(floor(ceil(A/B)+0.001),E))%2 - numPnts=E0+E1-E2+1 - print(numPnts) - - PDLY=caget(EA.PHV+"scan"+str(HVscanDIM)+".PDLY") - DDLY=caget(EA.PHV+"scan"+str(HVscanDIM)+".PDLY") - time_seconds=overhead[0]+numPnts*(1/17+PDLY+DDLY+overhead[1]) - print(C,D,B, EAlist[4]) - return str(timedelta(seconds=time_seconds)*EAlist[-1]) - - -def _scanEATrigger(EAlist,before_after,**kwargs): - """ - before_after="before" sets up scanIOC scanRecord for EA scan and sets prefix to "MDAscan0000" - before_after="after" clears up scanIOC scanRecord of EA scan and resets prefix to "EA" - Trigger EA - Det20 = EA scanNum - - set the EA._savePlugin Prefix to be 'MDAscan0045_' - **kwargs: - scan_dim=1 - detTrig=2 - """ - kwargs.setdefault("scan_dim",1) - kwargs.setdefault("detTrig",2) - kwargs.setdefault("dtype",EA.dtype) - kwargs.setdefault("detNum",20) - kwargs.setdefault("prefix","EA")# if not None then over rides the auto - kwargs.setdefault("debug",False) - - if kwargs["debug"]: - print("before_after: "+before_after) - - #setting EA._savePlugin FilePath, FileName,FileNumber - if before_after == "before": - _scanEAPrefix("mda",**kwargs) - scantype, HVscanPV, KElist, parms =EA._spectraSetup(EAlist,**kwargs) - iex.BL.mda.trigger_dictionary.update({kwargs['detTrig']:HVscanPV}) - - if before_after == "after": - _scanEAPrefix(kwargs["prefix"],**kwargs) - iex.BL.mda.trigger_dictionary.update({kwargs['detTrig']:""}) - - if kwargs["debug"]: - print("trigger_dictionary",iex.BL.mda.trigger_dictionary) - return - - -def _scanEAPrefix(ptype,**kwargs): - """ - sets the EA file prefix based on - ptype = "mda" -> for "MDAscan"+current MDA file - else prefix = ptype - kwargs: - debug = False (default) - prefix - """ - kwargs.setdefault("debug",False) - kwargs.setdefault("nzeros",4) - kwargs.setdefault("debug",False) - - prefix="" - if kwargs["debug"]: - print(ptype) - - if ptype == "mda": - fpath = iex.BL.mda.filepath()[0:-3]+EA.dtype - nextMDA = iex.BL.mda.fileNum() - prefix = "MDAscan"+str.zfill(str(nextMDA),kwargs["nzeros"]) - else: - prefix = ptype - - if kwargs["debug"]==kwargs["debug"]: - print("_scanEAPrefix prefix: ",prefix) - - - #setting the file path for the EA saving - fpath=caget(EA._savePlugin +"FilePath",as_string=True) - caput(EA._savePlugin+"FileName",prefix) - nextNum=get_next_fileNumber(fpath,prefix,**kwargs) - caput(EA._savePlugin+"FileNumber",nextNum) - time.sleep(.5) - if kwargs["debug"]: - print("FilePath: ",caget(EA._savePlugin +"FilePath", as_string=True)) - print("FileName: ",caget(EA._savePlugin +"FileName", as_string=True)) - print("FileNumber: ",caget(EA._savePlugin +"FileNumber", as_string=True)) - -def _BE2KE_setupCalc(BE,DESC,CalcOutNum,OutputPV): - """ - used by scanEA for talking in BE - """ - pvCalcOut="29idcScienta:userCalcOut"+str(CalcOutNum) - if len(OutputPV)==0: - caput(pvCalcOut+"Enable","D") - else: - caput(pvCalcOut+"Enable","E") - caput(pvCalcOut+".DESC", DESC) - caput(pvCalcOut+".A",BE) - caput(pvCalcOut+".INPB","29idmono:ENERGY_MON CP NMS") - caput(pvCalcOut+".INPC","29idcScienta:HV:WorkFunction CP NMS") - caput(pvCalcOut+".CALC$","B-A-C") - caput(pvCalcOut+".OUT",OutputPV+" PP") - return pvCalcOut - -def scanEA_reset(**kwargs): - """resets the IOC after a forced stop - """ - kwargs.setdefault("scan_dim",1) - - _scanEATrigger([],"after",**kwargs) - iex.BL.mda.positioners_clear(kwargs["scan_dim"]) - -def scanEA(EAlist,**kwargs): - """ - Uses the scanRecord (mda) to take multiple Scienta spectra - EAlist= - Fixed Mode:["KE"/"BE",CenterEnergy,PassEnergy,Frames,Sweeps] (5) - Swept Mode:["KE"/"BE",StartEnergy,StopEnergy,StepEnergy,PassEnergy,Frames,Sweeps] (7) - Baby Sweep (dither):["KE"/"BE",CenterEnergy,PassEnergy,Frames,Sweeps,"BS"] (6) - - (+) BE is positive below Ef - (-) BE is negative above Ef - - **kwargs - scanIOC=BL_ioc() - scan_dim=1 - execute: True/False to start the scan => True (default) - debug=False - - """ - - kwargs.setdefault('scanIOC',iex.BL.ioc) - kwargs.setdefault('scan_dim',1) - kwargs.setdefault('execute',True) - kwargs.setdefault("debug",False) - - if EAlist[0]=="KE" or EAlist[0]=="BE": - pass - else: - print("need to specify BE or KE") - - if EAlist[-1]=='BS': - sweeps=EAlist[-2] - else: - sweeps=EAlist[-1] - - if kwargs['debug']: - print("sweeps: "+str(sweeps)) - - if EAlist[0]=="BE": - if len(EAlist)==5: #Fixed - pvCalcOut1=_BE2KE_setupCalc(EAlist[1],"BE_center",10,"29idcScienta:HV:fixedEnergy.VAL") - EAlist[1]=caget(pvCalcOut1+'.VAL') - arrayP1=list(np.full(sweeps, EAlist[1])) - iex.BL.mda.fillin_table(pvCalcOut1+'.PROC',"",kwargs["scanIOC"],kwargs["scan_dim"],arrayP1,1) - EAlist[1]=arrayP1[0] - if kwargs['debug']: - print('\npvCalcOut1: ',pvCalcOut1) - print('Pos1 table:',arrayP1) - elif len(EAlist)==6: #Baby-Swept - pvCalcOut1=_BE2KE_setupCalc(EAlist[1],"BE_center",10,"29idcScienta:HV:babySweepCenter.VAL") - EAlist[1]=caget(pvCalcOut1+'.VAL') - arrayP1=list(np.full(sweeps, EAlist[1])) - iex.BL.mda.fillin_table(pvCalcOut1+'PROC',"",kwargs["scanIOC"],kwargs["scan_dim"],arrayP1,1) - print('\npvCalcOut1: ',pvCalcOut1) - print('Pos1 table:',arrayP1) - elif len(EAlist)==7: #Sweep - pvCalcOut1=_BE2KE_setupCalc(EAlist[1],"BE_start",9,"29idcScienta:HV:sweepStartEnergy.VAL") - pvCalcOut2=_BE2KE_setupCalc(EAlist[2],"BE_stop",10,"29idcScienta:HV:sweepStopEnergy.VAL") - EAlist[1]=caget(pvCalcOut1+'.VAL') - EAlist[2]=caget(pvCalcOut2+'.VAL') - arrayP1=list(np.full(sweeps, EAlist[1])) - arrayP2=list(np.full(sweeps, EAlist[2])) - iex.BL.mda.fillin_table(pvCalcOut1+'.PROC',"",kwargs["scanIOC"],kwargs["scan_dim"],arrayP1,1) - iex.BL.mda.fillin_table(pvCalcOut2+'.PROC',"",kwargs["scanIOC"],kwargs["scan_dim"],arrayP2,2) - if kwargs['debug']: - print("\npvCalcOut1",pvCalcOut1) - print("\npvCalcOut2",pvCalcOut2) - print('Pos1 table:',arrayP1) - print('Pos2 table:',arrayP2) - EAlist[0]=='KE' - else: - _BE2KE_setupCalc(0,"",9,"") - _BE2KE_setupCalc(0,"",10,"") - - if kwargs['debug']: - print('/n EAlist => ',EAlist) - - #set up name and add HV trigger and FileNum as det scan1 (sweeps) - _scanEATrigger(EAlist,"before",**kwargs) - - if kwargs['debug']: - print("Clearing scan positioners and filling in sweeps") - #Fill in Sweeps scan - iex.BL.mda.positioners_clear(**kwargs) - VAL="" - RBV="" - iex.BL.mda.fillin(VAL,RBV,1,sweeps,1,**kwargs) - if kwargs['debug']: - scanPV="29id"+kwargs["scanIOC"]+":scan"+str(kwargs["scan_dim"]) - print("scanPV: "+scanPV) - - - - #Writing EA parameters - EAscanType, EAscanPV, KElist, EAparms =EA._spectraSetup(EAlist,**kwargs) - - if kwargs['debug']: - print("EA._spectraSetup: ") - print(EAscanType,EAscanPV, KElist) - - print(EA._spectraMessage(EAscanType, EAscanPV, KElist)) - #print(EA._EAspectraTime()) - - #executing the scan - if kwargs['execute']: - EA.put(EAparms['KineticEnergy'],EAparms['PassEnergy'],LensMode="Angular",Frames=EAparms['Frames'],**kwargs) - time.sleep(10) - EA.put(EAlist[1]-.05,EAlist[-3],LensMode="Angular") - time.sleep(2) - iex.BL.mda.go(**kwargs) - #After scan - EAlog_update() - scanEA_reset(**kwargs) - iex.BL.mda.table_reset_after(**kwargs) - else: - return EAparms - - - -def scanFM(RoughPositions,thList,EAlist,**kwargs): - """ - New FermiMap using ScanRecord table scans to move motors - RoughPositions is a List rough positions from which to interpolate (use RoughPositions_Find()) - thList=[th_start,th_stop,th_step] - EAlist to be finish only one scan at the moment[can be a single list if you are only taking a single scan or a list of lists to take multiple scans] - **kwargs - scanIOC = BL_ioc() - scan_dim = 1 - - logfile(**kwargs) - """ - kwargs.setdefault("scan_dim",2) - kwargs.setdefault("debug",False) - kwargs.setdefault('execute',True) - - # Making Tables and Filling positioners - x,y,z,th,chi,phi=interpRoughPositions(RoughPositions,thList[0],thList[1],thList[2]) - if kwargs['debug']: - print(x,y,z,th,chi,phi) - - iex.BL.mda.fillin_table(EA.Motors._motor_dictionary["th"][1],EA.Motors._motor_dictionary["th"][0],th,positioner_num=1) - iex.BL.mda.fillin_table(EA.Motors._motor_dictionary["x"][1],EA.Motors._motor_dictionary["x"][0],x,positioner_num=2) - iex.BL.mda.fillin_table(EA.Motors._motor_dictionary["y"][1],EA.Motors._motor_dictionary["y"][0],y,positioner_num=3) - iex.BL.mda.fillin_table(EA.Motors._motor_dictionary["z"][1],EA.Motors._motor_dictionary["z"][0],z,positioner_num=4) - - #setting up EA - EAkwargs={ - 'execute':False, - 'scan_dim':1 - } - EAparms=scanEA(EAlist,**EAkwargs) - - #executing the scan - if kwargs["execute"]==True: - print(EAparms) - EA.put(EAparms['KineticEnergy'],EAparms['PassEnergy'],LensMode="Angular",Frames=EAparms['Frames'],**kwargs) - iex.BL.mda.go(**kwargs) - EAlog_update() - scanEA_reset(**kwargs) - - -def interpRoughPositions(RoughPositions,thStart,thStop,thStep,**kwargs): - """ - Interpolate sample position as a function of theta, based on RoughPosition, - a list of motor position lists and returns x,y,z,th,chi,phi - - **kwargs: - kind="cubic" by default, interpolation type ("linear","cubic","quadratic") - - Usage: - x,y,z,th,chi,phi=interpRoughPositions(RoughPositions,3,-8,0.5) - - (direction to minimize backlash) - RoughPositions=[ - [x,y,z,th,chi,phi], - [x,y,z,th,chi,phi] - ] - """ - kwargs.setdefault('kind','cubic') - kwargs.setdefault('debug',False) - - #Puts Rough Position in increasing theta order - RoughPositions=sorted(RoughPositions, key=itemgetter(3))[::-1] - RoughPositions=np.array(RoughPositions) - if kwargs['debug']: - print('RoughPositions: ',RoughPositions) - - #thlist - if kwargs['debug']: - print('ths: ',thStart,thStop,thStep) - th=np.arange(np.max([thStart,thStop]),np.min([thStart,thStop])-1.0*abs(thStep),-1.0*abs(thStep),dtype=float) - if kwargs['debug']: - print('th: ',th) - - #interpolating - def func(th,th_col,m_col,**kwargs): - f=interp1d(th_col,m_col) - m=f(th) - return m - x=func(th,RoughPositions[:,3], RoughPositions[:,0]) - y=func(th,RoughPositions[:,3], RoughPositions[:,1]) - z=func(th,RoughPositions[:,3], RoughPositions[:,2]) - chi=func(th,RoughPositions[:,3], RoughPositions[:,4]) - phi=func(th,RoughPositions[:,3], RoughPositions[:,5]) - - return x,y,z,th,chi,phi - -def mvth_interp(RoughPositions, thVal,**kwargs): - """ - Moves to the interpolated position for a give theta and RoughPosition list - uses interpRoughPositions - """ - x,y,z,th,chi,phi=interpRoughPositions(RoughPositions,thVal,thVal-.1,1,**kwargs) - Pos=[x[0],y[0],z[0],th[0],chi[0],phi[0]] - #print("Pos = ",Pos) - EA.Motors.mvsample(Pos) - -def scanEA_hv(hv_start_stop_step_lists,EAlist=[],**kwargs): - """ - triggers and EAscan for each photon energy in *hvs - - hv_start_stop_step_lists, listoflist ... see scanXAS for more info - - EAlist = - Fixed Mode: EAlist=["KE/BE",CenterEnergy,PassEnergy,Frames,Sweeps] (5) - Swept Mode: EAlist=["KE/BE",StartEnergy,StopEnergy,StepEnergy,PassEnergy,Frames,Sweeps] (7) - Baby Sweep (dither): EAlist=["KE"/"BE",CenterEnergy,PassEnergy,Frames,Sweeps,"BS"] (6) - KE => Auger - BE => Core levels - (+) BE is positive below Ef - (-) BE is negative above Ef - - usage: - scanEA_hv([400,500,1200],EAlist=["BE",-5,200,17*60,1]) - NOTE that EAlist = needs to be written explicitly - - **kwargs - execute: True/False to start the scan => True (default) - debug: default => False - QP_ratio: if other than fully periodic - - (Note: scan_dim=2 is hardcoded for photon energy) - - """ - kwargs.setdefault("average",None) - kwargs.setdefault("execute",True) - kwargs.setdefault("debug",False) - - if(kwargs['debug']): - print('EAlist: ',EAlist) - - #setting up EA - EAkwargs={ - 'execute':False, - 'scan_dim':1 - } - EAparms=scanEA(EAlist,**EAkwargs) - - scanGo = kwargs['execute'] - #Setting up the ScanRecord for Mono and ID in Table mode - kwargs["scan_dim"]=2 - kwargs["execute"]=False - mono_array,ID_array = BL_energy_tables(hv_start_stop_step_lists,**kwargs) - kwargs.update({"ID_tracking":True}) - scanXAS(hv_start_stop_step_lists,**kwargs) - - if scanGo == True: - #Setting the beamline energy to the first point, and EA at first KE - energy(mono_array[0]) - #Scanning - EA.put(mono_array[0]-EAlist[1],EAparms['PassEnergy'],LensMode="Angular",Frames=EAparms['Frames'],**kwargs) - iex.BL.mda.go(**kwargs) - #After scan - scanEA_reset(**kwargs) - iex.BL.mda.table_reset_after(**kwargs) - -def scanEA_y(EAlist, start,stop,step,mode='absolute',**kwargs): - scanEA_motor(EAlist,'y',start,stop,step,mode=mode,**kwargs) - -def scanEA_z(EAlist, start,stop,step,mode='absolute',**kwargs): - scanEA_motor(EAlist,'z',start,stop,step,mode=mode,**kwargs) - - -def scanEA_motor(EAlist, motor,start,stop,step,mode='absolute',**kwargs): - """ - scans an ARPES motor (scan_dim=2) while triggering the EA (scan_dim=1) - - EAlist = - Fixed Mode:["BE",CenterEnergy,PassEnergy,Frames,Sweeps] (5) - Swept Mode:["BE",StartEnergy,StopEnergy,StepEnergy,PassEnergy,Frames,Sweeps] (7) - Baby Sweep (dither):["KE"/"BE",CenterEnergy,PassEnergy,Frames,Sweeps,"BS"] (6) - - (+) BE is positive below Ef - (-) BE is negative above Ef - - **kwargs - execute: True/False to start the scan => True (default) - debug=False - (Note: scan_dim=2 is hardcoded) - """ - kwargs.setdefault("execute",True) - kwargs.setdefault("debug",False) - - #setting up EA - EAkwargs={ - 'execute':False, - 'scan_dim':1 - } - EAparms=scanEA(EAlist,**EAkwargs) - - #Setting up the ScanRecord for motor scans - scan_dim=2 #hard coded - kwargs.update({'scan_dim':scan_dim}) - - EA.Motors.scan(motor,start,stop,step,**kwargs) - - if kwargs['debug']: - print("ScanGo scan_dim = ",scan_dim) - - if kwargs["execute"]==True: - #Scanning - EA.put(EAlist[1],EAparms['PassEnergy'],LensMode="Angular",Frames=EAparms['Frames'],**kwargs) - iex.BL.mda.go(kwargs["scanIOC"],scan_dim) - EAlog_update() - #After scan - scanEA_reset(**kwargs) - -def scanEA_Mesh(EAlist,y_start_stop_step,z_start_stop_step,**kwargs): - """ - 2D scan mesh (y/z) while triggering the EA: scan_dim=1 - y_start_stop_step=[start1,stop1,step1] #y: scan_dim=2 - z_start_stop_step=[start2,stop2,step2] #z: scan_dim=3 - - - EAlist = - Fixed Mode:["BE",CenterEnergy,PassEnergy,Frames,Sweeps] (5) - Swept Mode:["BE",StartEnergy,StopEnergy,StepEnergy,PassEnergy,Frames,Sweeps] (7) - Baby Sweep (dither):["KE"/"BE",CenterEnergy,PassEnergy,Frames,Sweeps,"BS"] (6) -1205 - (+) BE is positive below Ef - (-) BE is negative above Ef - - **kwargs - execute: True/False to start the scan => True (default) - debug=False - (Note: scan_dims are hardcoded) - """ - kwargs.setdefault("execute",True) - kwargs.setdefault("debug",False) - - #setting up EA - EAkwargs={ - 'execute':False, - 'scan_dim':1 - } - EAparms=scanEA(EAlist,**EAkwargs) - - #Setting up the ScanRecord for motor scans - outer_scan_dim=3 #hard coded - inner_loop_list = y_start_stop_step.insert(0,"y") - outer_loop_list = z_start_stop_step.insert(0,"z") - EA.Motors.scan_2D(inner_loop_list,outer_loop_list,outer_scan_dim,**kwargs) - - if kwargs['debug']: - print("ScanGo scan_dim = ",outer_scan_dim) - - if kwargs['execute']: - #Scanning - EA.put(EAlist[1],EAparms['PassEnergy'],LensMode="Angular",Frames=EAparms['Frames'],**kwargs) - iex.BL.mda.go(scan_dim=outer_scan_dim) - EAlog_update() - - #After scan - scanEA_reset(**kwargs) - - - - - -def hv2kz(lattice,V0,hv): - """ - Converts a hv value for the nth zone had returns corresponding kz values - [0]for zone boundary and [1] for zone center in inverse angstroms - lattice = c; assuming kz orthoganal to a-b plane (i.e. 2np.pi/c = GZ distance) - and at zone center (kx,ky)=0 /cos(th=0)=1 - V0 = the inner potential - """ - work_fct=EA.wk - Ek=hv-work_fct - k_z=0.5124*np.sqrt(Ek+V0) # Kz at (kx,ky)=0 i.e. cos(th)=1 - c_star=2*np.pi/lattice # 2pi/c = GZ distance - GZ_n=round((k_z/c_star*2),2) - G_n=round((k_z/c_star),2) - print(" kz = "+str(round(k_z,2))+" A^(-1) = " +str(GZ_n)+" * pi/c = " +str(G_n)+" * 2pi/c") - return GZ_n,G_n - -def kz2hv(lattice,V0,n): - """ - Converts a kz value for the nth zone had returns corresponding hv - lattice = c; assuming kz orthoganal to a-b plane (i.e. 2pi/c = GZ distance) - and at zone center (kx,ky)=0 /cos(th=0)=1 - V0 = the inner potential - """ - work_fct=EA.wk - c_star=2*np.pi/lattice # 2pi/c = GZ distance - Ek=(n*c_star/0.5124)**2-V0 # Ek at (kx,ky)=0 i.e. cos(th)=1 - hv=Ek+work_fct - mono=round(hv,1) - print("\n") - print(" hv = Ek + Phi = "+str(round(hv,2))+" eV") - print(" kz = n*2pi/c with n = "+str(n)) - return mono - - -def Print_Gamma_n(lattice,V0,n1,n2): - work_fct=EA.wk - c_star=2*np.pi/lattice # 2pi/c = GZ distance - for n in range(n1,n2+1,1): - Ek_Gn=(n*c_star/0.5124)**2-V0 # Ek at G - Ek_Zn=((n+0.5)*c_star/0.5124)**2-V0 # Ek at Z - hv_Gn=round(Ek_Gn+work_fct,2) - hv_Zn=round(Ek_Zn+work_fct,2) - print("\n G["+str(n)+"]: hv = Ek + Phi = "+str(round(hv_Gn,2))+" eV ") - print(" Z["+str(n)+"]: hv = Ek + Phi = "+str(round(hv_Zn,2))+" eV") - -def Print_Gamma_hv(lattice,V0,hv1,hv2): - work_fct=EA.wk - c_star=2*np.pi/lattice # 2pi/c = GZ distance - Ek1=hv1-work_fct - Ek2=hv2-work_fct - k_z1=0.5124*np.sqrt(Ek1+V0) # Kz at (kx,ky)=0 i.e. cos(th)=1 - k_z2=0.5124*np.sqrt(Ek2+V0) # Kz at (kx,ky)=0 i.e. cos(th)=1 - GZ_n1=round((k_z1/c_star*2),1) - G_n1=round((k_z1/c_star),1) - GZ_n2=round((k_z2/c_star*2),1) - G_n2=round((k_z2/c_star),1) - if modf(G_n1)[0]>=0.5: - n1=modf(G_n1)[1]+1,0 - else: - n1=modf(G_n1)[1] - n2=modf(G_n2)[1] - print("\n hv1 = "+str(hv1)+" eV: " +str(GZ_n1)+" * pi/c = " +str(G_n1)+" * 2pi/c") - if type(n1) == tuple: n1 = n1[0] - if type(n2) == tuple: n2 = n2[0] - Print_Gamma_n(lattice,V0,n1,n2) - print("\n hv2 = "+str(hv2)+" eV: " +str(GZ_n2)+" * pi/c = " +str(G_n2)+" * 2pi/c") - return n1,n2 - -def kx2deg(lattice,hv): - a=np.pi/lattice - b=0.5124*np.sqrt(hv) - c=a/b - theta_rad=np.asin(c) - theta_deg=rad2deg(theta_rad) - print(" 1/2-BZ (GX) = "+str(round(theta_deg,1))+" deg") - -def resolution_EA(PE,slit_SES): # updated 10/30/17: straight slits scaled to slit width not area - SES_Table={} - SES_Table[2] = {1: 1.6, 2:2, 3:2, 4:4, 5:4, 6:6, 7:12, 8:20, 9:32} - SES_Table[5] = {1: 2.7, 2:4, 3:4, 4:7, 5:7, 6:11, 7:20, 8:34, 9:54} - SES_Table[10] = {1: 5.7, 2:9, 3:9, 4:14, 5:14, 6:23, 7:43, 8:71, 9:114} - SES_Table[20] = {1:10.8, 2:16, 3:16, 4:27, 5:27, 6:43, 7:81, 8:135, 9:216} - SES_Table[50] = {1:34.6, 2:52, 3:52, 4:87, 5:87, 6:138, 7:260, 8:433, 9:692} - SES_Table[100] = {1:49.5, 2:74, 3:74, 4:124, 5:124, 6:198, 7:371, 8:619, 9:990} - SES_Table[200] = {1:88.9, 2:133, 3:133, 4:222, 5:222, 6:356, 7:667, 8:1111, 9:1778} - SES_Table[500] = {1:250, 2:375, 3:375, 4:625, 5:625, 6:1000, 7:1875, 8:3125, 9:5000} - try: - SES=SES_Table[PE][slit_SES] - except KeyError: - print("WARNING: Not a valid PE/Slit combination") - SES=0 - return SES - - -def SES_slit_set(val): - """ - Set the Scienta Slit - val w_mm l_mm Shape - 1 0.2 25 Curved - 2 0.3 30 Straight - 3 0.3 25 Curved - 4 0.5 30 Straight - 5 0.5 25 Curved - 6 0.8 25 Curved - 7 1.5 30 Straight - 8 2.5 30 Straight - 8.5 open apperture - 9 4.0 30 Straight - """ - caput("29idc:m8.VAL",val,wait=True,timeout=18000) - - -def SES_slit_get(): - SES=caget("29idc:m8.RBV") - return SES - diff --git a/build/lib/iexcode/instruments/encoders.py b/build/lib/iexcode/instruments/encoders.py deleted file mode 100644 index 308ea53b1ddb7596f5d29ded6f7e916f10494f12..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/encoders.py +++ /dev/null @@ -1,67 +0,0 @@ -from epics import caput,caget - -def _encoder_dictionary(): - """ - returns a dictionary with the encoder pvs - encoder_dictionary_entry(name) = encoder_ioc, motor_ioc, encoder_list - - """ - d={ - 'slit2B':("29idMini1:","29idb:",[13,14,15,16]), - 'slit3D':("29idMini2:","29idb:",[26,27]), - 'ARPES':("29idARPES:","29idARPES:",[1,2,3,4]), - } - return d - -def encoder_name_list(): - d = _encoder_dictionary() - for key in d.keys(): - print(key) - -def encoder_sync(name): - """ - sync all the encoders for name - """ - encoder_ioc, motor_ioc, encoder_list = _encoder_dictionary()[name] - for encoder_num in encoder_list: - pv = motor_ioc+"m"+str(encoder_num)+".SYNC" - caput(pv,1) - -def encoders_reset_zero(name): - """ - Resetting Slit 2B encoders to 0 for the current position. - Slit size need to be set to 0. - - Previously: Reset_Slit2B_Encoders - """ - encoder_sync(name) - encoder_ioc, motor_ioc, encoder_list = _encoder_dictionary()[name] - - print('\nCurrent Position:') - for e_num in encoder_list: - pv = encoder_ioc+'e'+(e_num)+'Pos' - print('e'+(e_num)+' = '+str(caget(pv))) - - print('\nSetting all Offsets to 0:') - for e_num in encoder_list: - pv = encoder_ioc+'e'+(e_num)+'Pos.EOFF' - caput(pv,0) - - print('\nCurrent Position:') - for e_num in encoder_list: - pv = encoder_ioc+'e'+(e_num)+'Pos' - print('e'+(e_num)+' = '+str(caget(pv))) - - print('\nSetting back Offsets:') - for e_num in encoder_list: - pos_pv = encoder_ioc+'e'+(e_num)+'Pos' - offset_pv = encoder_ioc+'e'+(e_num)+'Pos.EOFF' - caput(offset_pv,-caget(pos_pv)) - - print('\nCurrent Position:') - for e_num in encoder_list: - pv = encoder_ioc+'e'+(e_num)+'Pos' - print('e'+(e_num)+' = '+str(caget(pv))) - - encoder_sync(name) - print('sync '+name) diff --git a/build/lib/iexcode/instruments/files_and_folders.py b/build/lib/iexcode/instruments/files_and_folders.py deleted file mode 100644 index 8bb38a7326a3775f6c1046990995ed37bf5b592d..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/files_and_folders.py +++ /dev/null @@ -1,241 +0,0 @@ -from os import listdir,mkdir,chmod -from os.path import join, isfile, exists -import datetime -from time import sleep -import re - -from epics import caget, caput - - -############################################################################################################## -################################ Standard Paths ############################## -############################################################################################################## - - -path_User_Folders='/home/beams/29IDUSER/Documents/User_Folders/' - -def path_dserv(folder,run,user_name): - """ - Returns the path to a user folder - dataFolder='/net/s29data/export/data_29id'+folder+'/'+run+'/'+user_name - - previously: _userDataFolder - """ - - dataFolder='/net/s29data/export/data_29id'+folder+'/'+run+'/'+user_name - return dataFolder - - -############################################################################################################## -################################ Folders ############################## -############################################################################################################## -def check_run(): - """ - gets the current date and determines the run number from that - run = year_cycle - cycle 1 => Jan - April - cycle 2 => May - September - cycle 1 => October - December - - previously: Check_run - """ - todays_date = datetime.date.today() - - date1 = ( 1, 1) # start date run_1 - date2 = ( 5, 1) # start date run_2 - date3 = (10, 1) # start date run_3 - - datex = (todays_date.month,todays_date.day) - - if date1 <= datex < date2: - run=str(todays_date.year)+'_1' - elif date2 <= datex < date3: - run=str(todays_date.year)+'_2' - else: - run=str(todays_date.year)+'_3' - - return(run) - -def make_ftp(folder,run,user_name): - """ - Creates the folders on kip (ftp server) and prints what is needed for the cronjob - - folder = 'c' /'d' - - Previously: was part of Make_DataFolder - """ - crontime={ - 'mda2ascii':'0,30 * * * * ', - 'chmod':'1,31 * * * * ', - 'data_other':'2,32 * * * * ', - 'notebook':'*/3 * * * * ', - } - - #making the crontab text - print('-------------------------------------------------------------') - #mda2ascii - MyPath_kip_run='/net/kip/sftp/pub/29id'+folder+'ftp/files/'+run+'/' - MyPath_kip='/net/kip/sftp/pub/29id'+folder+'ftp/files/'+run+'/'+user_name+'/' - cmd_mda2ascii=crontime['mda2ascii']+' /net/s29dserv/APSshare/bin/mda2ascii -d '+MyPath_kip+'ascii '+MyPath_kip+'mda/*.mda' - print(cmd_mda2ascii) - #chmode - cmd_chmod=crontime['chmod']+' chmod 664 '+MyPath_kip+'ascii/*.asc' - print(cmd_chmod) - #notebooks - cmd_notebook=crontime['notebook']+' /usr/bin/rsync -av --exclude=core /home/beams22/29IDUSER/Documents/User_Folders/'+user_name+'/* kip:'+MyPath_kip+'notebook > /home/beams22/29ID/cronfiles/cptoftp-currrun-d-User.log 2>&1' - print(cmd_notebook) - print('-------------------------------------------------------------\n\n') - - #making folders - print("\n\n") - print(MyPath_kip) - print(MyPath_kip+"ascii") - if not (exists(MyPath_kip_run)): - mkdir(MyPath_kip_run) - chmod(MyPath_kip_run, 0o775) - if not (exists(MyPath_kip)): - mkdir(MyPath_kip) - chmod(MyPath_kip, 0o775) - if not (exists(MyPath_kip+"ascii")): - mkdir(MyPath_kip+'ascii') - chmod(MyPath_kip+'ascii', 0o775) - if not (exists(MyPath_kip+"notebook")): - mkdir(MyPath_kip+"notebook") - chmod(MyPath_kip+"notebook", 0o775) - -def make_user_folders(run,folder,user_name,endstation_name,ftp=False): - """ - if user_name is not a folder in path_User_Folders, then it creates a new folder - - if ftp = True / False (default) creates the folders on kip (ftp server) and modifies the cronjob - - previously: Make_DataFolder - """ - - if (folder == 'c'or folder == 'd'): - if ftp: - make_ftp(folder,run,user_name) - else: - print("To create ftp folders & update contrab, you need to run the following as 29id:") - print("\tFolder_"+str(endstation_name)+"('"+str(run)+"','"+str(user_name)+"',ftp=True)") - - #create user folder for saving log files - path_user=join(path_User_Folders,user_name) - user_name = "/"+user_name - if not (exists(path_user)): - mkdir(path_user) - - -def folder_mda(run,folder,user_name,file_prefix,ioc,verbose=True): - """ - sets the folder, prefix and file number for the scan record - ioc is the full ioc, e.g. '29idb', or '29idARPES' - - For Staff: folder='b', user_name='' - For ARPES: folder ='c' - For Kappa: folder = 'd' - - mda_path="/net/s29data/export/data_29id"+folder+"/"+run+"/"+user_name+"mda" - """ - - if user_name == 'Staff': - user_name="" - else: - user_name=user_name+'/' - - mda_path="/net/s29data/export/data_29id"+folder+"/"+run+"/"+user_name+"mda" - print("\nMDA folder: " + mda_path) - if not (exists(mda_path)): - mkdir(mda_path) - FileNumber=1 - else: - FileNumber=get_next_fileNumber(mda_path,file_prefix) - - if ioc in ['29idb','29idc','29idd']: #VME iocs - caput(ioc+"saveData_fileSystem","//s29data/export/data_29id"+folder+"/"+run) - sleep(0.25) - caput(ioc+"saveData_subDir",user_name+"mda") - - else: #soft iocs - caput(ioc+"saveData_fileSystem","/net/s29data/export/data_29id"+folder+"/"+run) - sleep(0.25) #needed so that it has time to write - caput(ioc+"saveData_subDir","/"+user_name+"mda") - - caput(ioc+"saveData_baseName",file_prefix) - caput(ioc+"saveData_scanNumber",FileNumber) - - print("\nioc set to:", ioc) - sleep(5) - - if verbose: - SaveStatus=caget(ioc+'saveData_status',as_string=True) - SaveMessage=caget(ioc+'saveData_message',as_string=True) - print("\nSave Status "+ioc+": "+SaveStatus+" - "+SaveMessage) - - -def folder_SPEC(run,folder,user_name): - if folder == "b": - user_name = "Staff" - else: - user_name = user_name+"/" - MyPath="/home/beams22/29IDUSER/spec/data/"+run+"/"+user_name - print("\nSPEC folder: " + MyPath) - print("You will need to create folder and set up the path manually in SPEC:") - print(" cd "+MyPath) - print(" newfile FileName") - print("To start SPEC fresh: ./bin/kappa29ID -f") - #if not (exists(MyPath)): - # mkdir(MyPath) - - - - -def _filename_key(filename): - return (len(filename), filename) - -def get_next_fileNumber(data_dir, file_prefix,**kwargs): - """ - gets the next file number for the pattern - data_dir/file_prefix_filenum - - kwargs: - verbose = False (default); if True then prints next file number - debug = False (default) - Previously: getNextFileNumber - """ - kwargs.setdefault("verbose",False) - kwargs.setdefault("debug",False) - - - onlyfiles = [f for f in listdir(data_dir) if isfile(join(data_dir, f)) and f[:len(file_prefix)] == file_prefix] - sortedfiles = sorted(onlyfiles, key=_filename_key) - pattern = re.compile('(.*)_(.*)\.(.*)') - try: - lastFile = sortedfiles[-1] - except IndexError as errObj: - nextFileNumber = 1 - if kwargs["debug"]: - print("Data directory = ", data_dir) - print("File prefix =", file_prefix) - print("File number =", None) - print("File extension =", "TBD") - print("Next File number =", nextFileNumber) - else: - matchObj = pattern.match(lastFile) - nextFileNumber = int(matchObj.group(2)) + 1 - if kwargs["debug"]: - print("Data directory = ", data_dir) - print("File prefix =", matchObj.group(1)) - print("File number =", matchObj.group(2)) - print("File extension =", matchObj.group(3)) - print("Next File number =", nextFileNumber) - if kwargs["verbose"] == True: - print("Next File Number: ",nextFileNumber) - return nextFileNumber - - - - - - - diff --git a/build/lib/iexcode/instruments/hxp_mirrors.py b/build/lib/iexcode/instruments/hxp_mirrors.py deleted file mode 100644 index 72df87b817ebd017c75325e360759cd3cc5663b5..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/hxp_mirrors.py +++ /dev/null @@ -1,67 +0,0 @@ -from re import M -from epics import caput, caget -from iexcode.instruments.utilities import print_warning_message -from iexcode.instruments.m3r import m3r_branch - -def _hxp_ioc(mirror_name): - """ - returns the ioc for a given - mirror_name: 'm3a' / 'm4a' / 'm4r' - """ - hxp_namelist={ - 'm4r':'hxp2', - 'm3a':'hxp1', - 'm4a':'hxp3', - } - if mirror_name not in hxp_namelist: - print("not a valid mirror name ("+list(hxp_namelist.keys())+")") - else: - ioc = '29idHXP:'+hxp_namelist[mirror_name]+":" - return ioc - - -def hxp_sync(mirror_name): - """ - synchs the rbv and sp for all axes - - mirror_name: 'm3a' / 'm4a' / 'm4r' - - Previously: Sync_m4r - """ - pv = _hxp_ioc(mirror_name) - try: - for m in range(1,7): - caput(pv+'m'+str(m)+'.SYNC',1) - except: - print_warning_message("Check if ioc is running") - - -def hxp_get_all(mirror_name,verbose=True): - """ - - Previously: Get_HXP - """ - pv = _hxp_ioc(mirror_name) - - Tx=caget(pv+"m1.RBV") - Ty=caget(pv+"m2.RBV") - Tz=caget(pv+"m3.RBV") - Rx=caget(pv+"m4.RBV") - Ry=caget(pv+"m5.RBV") - Rz=caget(pv+"m6.RBV") - - if verbose: - print("\n"+mirror_name+" @ "+"%.3f" % Tx, "/","%.3f" % Ty, "/","%.3f" % Tz, "/","%.3f" % Rx, "/","%.3f" % Ry, "/","%.3f" % Rz) - return Tx,Ty,Tz,Rx,Ry,Rz - -def hxp_get_all(): - """ - - Previously: Get_HXP - """ - branch = m3r_branch() - if branch == 'c': - hxp_get_all('m3a',verbose=True) - hxp_get_all('m4a',verbose=True) - else: - hxp_get_all('m4r',verbose=True) \ No newline at end of file diff --git a/build/lib/iexcode/instruments/m3r.py b/build/lib/iexcode/instruments/m3r.py deleted file mode 100644 index 04aef80dfdf60c9b02794b78a0cf99afec6f1975..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/m3r.py +++ /dev/null @@ -1,156 +0,0 @@ -from cgi import print_arguments -from iexcode.instruments.VLS_PGM import mono_energy_get - -from epics import caget, caput - -from iexcode.instruments.utilities import print_warning_message -from iexcode.instruments.FMB_mirrors import * - -############################################################################################################## -################################ M3R ############################## -############################################################################################################## -M3R_RY_POS_SP_initial = -16.52 -M3R_camera = '29id_ps6:' -M3R_cam1 = M3R_camera+"cam1:" -M3R_stats = M3R_camera+"Stats1:" -M3R_pitch = "29id_m3r:RY_MON" -M3R_align_pv = "29idKappa:align_m3r:" - -############################################################################################################## -################################ M3R default positions ############################## -############################################################################################################## -def m3r_position_dictionary(): - """ - dictionary for the default positions for a given branch - """ - positions={ - "c":[10,0,0,0,0,0], - "d":[-2.5,0,0,-13.955,-16.322,-8.5], - "e":[-2.000,0,0,-13.960,-16.614,-7.500] - } - - - # d => optimized for MEG @ 500 eV on 2/29/def start - # e => 2018_3-- JM changed for RSoXS alignment max diode current - return positions - -def m3r_get(verbose=True): - position = FMB_mirror_get(3,verbose) - return position - -def m3r_RY_pos_sp(): - return M3R_RY_POS_SP_initial - -def m3r_RY_pos_sp_get(): - RY_SP = caget('29id_m3r:RY_POS_SP') - return RY_SP - -def m3r_tweak (axis,val): - """ - \"TX\" = lateral \"RX\" = Yaw - \"TY\" = vertical \"RY\" = Pitch - \"TZ\" = longitudinal \"RZ\" = Roll - - Previously: Tweak_M3R - """ - mirror_num = 3 - FMB_mirror_tweak(mirror_num,axis,val,verbose=True) - -def m3r_tweak_pitch(sign,val=0.005): - """ - Previously: Tweak_M3R_Pitch - """ - axis="RY" - if sign == "+": - m3r_tweak(axis,val) - elif sign == "-": - m3r_tweak(axis,-val) - - - -def m3r_table(branch): - """ - Defines the positions used by switch_branch() form M3R - WARNING: branch_pv uses: D => (Tx <= 0) and (Ry < 0) - Make sure this remains true or change it - """ - positions = m3r_position_dictionary() - - try: - position = positions[branch] - except KeyError: - print_warning_message("not a valid branch") - print(list(positions.keys())) - position = FMB_mirror_get(3,verbose=False) - return position - -def m3r_branch(): - """ - get which branch based on the mirror position and returns the branch - """ - PV="29id_m3r:" - TX=caget(PV+"TX_MON") - if TX > 6: - branch = 'c' - elif TX < -1: - branch = 'd' - else: - print('M3R is not in a default position') - return branch - -def m3r_switch_branch(branch,verbose=True): - """ - switches the mirror to the position defined in m3r_table - """ - position = m3r_table(branch) - if verbose: - print("Moving M3R to the "+branch+"branch: "+str(position)) - FMB_mirror_move_all(3,position,verbose=False) - # Relax bellows by doing large Z translation: - FMB_mirror_move(3,"TY",5,verbose=False) - sleep(.1) - FMB_mirror_move(3,"TY",0,verbose=False) - sleep(.1) - FMB_mirror_get(3,verbose=True) - -############################################################################################################## -################################ M3R alignment ############################## -############################################################################################################## - -def m3r_centroid(t=None,q=1): - ''' - Return position of centroid, sigma, m3r:RY (mirror pitch) - Optional argument t to set camera intergration time. - ''' - if t is not None: - caput(M3R_cam1+'AcquireTime',t) - else: - t=caget(M3R_cam1+'AcquireTime') - position = round(caget(M3R_stats+'CentroidX_RBV'),2) - sigma = round(caget(M3R_stats+'SigmaX_RBV'),2) - intensity = round(caget(M3R_stats+'CentroidTotal_RBV'),2) - m3rRY = round(caget(M3R_pitch),4) - if q != None: - print('(position, sigma, total intensity, integration time (s), mirror pitch):') - return position,sigma,intensity,t,m3rRY - -def _m3r_align_start(pxl=None): - if pxl == None: - pxl = caget(M3R_align_pv+'desired_pixel') - caput(M3R_align_pv+'desired_pixel',pxl) - caput(M3R_align_pv+'startAlign',1,wait=True,timeout=180) - -def m3r_align(pxl=None): - if iex.BL.branch == 'd': - print('\nalign_m3r()') - try: - _m3r_align_start() - sleep(1) - if mono_energy_get()>2100: - _m3r_align_start() - sleep(1) - sleep(1) - min_m3r=caget(M3R_align_pv+'motor_min') - if m3r_RY_pos_sp_get() == min_m3r: - align_m3r_epics() - except: - print('Unable to align; check camera settings.') \ No newline at end of file diff --git a/build/lib/iexcode/instruments/remote_controlers.py b/build/lib/iexcode/instruments/remote_controlers.py deleted file mode 100644 index 2c65239be40dcfcbbbc0a218203d49a0a2a08562..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/remote_controlers.py +++ /dev/null @@ -1,356 +0,0 @@ -from epics import caget,caput - -############################################################################################################## -############################## RSXS Remote control ############################## -############################################################################################################## - -# To start ioc for ARPES(RSXS) Surly(Sneezy) -# cd /net/s29dserv/xorApps/epics/synApps_5_8/ioc/29idSurlySoft/iocboot/iocLinux -# 29idSurlySoft start - -# to bring up epics screen -# cd /net/s29dserv/xorApps/epics/synApps_5_8/ioc/29idSurlySoft/ -# start_epics_29idSurlySoft - -def ARPES_Controller(): - """ - Button={} with Button[][0]=PV name and Button[][1]=value (for tweaks or other procs value=1) - ".TWF -> (+)tweak" - ".TWR -> (-)tweak" - """ - Controller="29idSurlySoft" - ioc="29idc:" - - Triggers={} #['LTSeq','RTSeq','LBSeq','RBSeq'] - Triggers[0]=ioc+"allstop.VAL",1 - Triggers[1]=ioc+"allstop.VAL",1 - Triggers[2]=ioc+"allstop.VAL",1 - Triggers[3]=ioc+"allstop.VAL",1 - - DPad={} #['UpSeq','DownSeq','LeftSeq','RightSeq'] - DPad[0]=ioc+"m1.TWF",1 #x - DPad[1]=ioc+"m1.TWR",1 - DPad[2]=ioc+"m4.TWR",1 #th - DPad[3]=ioc+"m4.TWF",1 - - Buttons={} #['YSeq','ASeq','XSeq','BSeq'] - Buttons[0]=ioc+"m3.TWF",1 #z - Buttons[1]=ioc+"m3.TWR",1 - Buttons[2]=ioc+"m2.TWR",1 #y - Buttons[3]=ioc+"m2.TWF",1 - - Ljoy={} #['LSUpSeq','LSDownSeq','LSLeftSeq','LSRightSeq'] - Ljoy[0]="",0 - Ljoy[1]="",0 - Ljoy[2]=ioc+"m6.TWR",1 #phi - Ljoy[3]=ioc+"m6.TWF",1 #phi - Lclick={} #['L3Seq'] - Lclick[0]=ioc+"m1.TWV",.25 #x - Lclick[1]=ioc+"m2.TWV",.25 #y - Lclick[2]=ioc+"m3.TWV",.25 #z - Lclick[3]=ioc+"m4.TWV",1 #th - Lclick[4]=ioc+"m5.TWV",1 #chi - Lclick[5]=ioc+"m6.TWV",1 #phi - Lclick[6]="",0 - Lclick[7]="",0 - Lclick[8]="",0 - - Rjoy={} #['RSUpSeq','RSDownSeq','RSLeftSeq','RSRightSeq'] - Rjoy[0]="",0 - Rjoy[1]="",0 - Rjoy[2]=ioc+"m5.TWR",1 #chi - Rjoy[3]=ioc+"m5.TWF",1 #chi - Rclick={} #['R3Seq'] - Rclick[0]=ioc+"m1.TWV",.5 #x - Rclick[1]=ioc+"m2.TWV",.5 #y - Rclick[2]=ioc+"m3.TWV",.5 #z - Rclick[3]=ioc+"m4.TWV",5 #th - Rclick[4]=ioc+"m5.TWV",5 #chi - Rclick[5]=ioc+"m6.TWV",5 #phi - Rclick[6]="",0 - Rclick[7]="",0 - Rclick[8]="",0 - - Controller_setup(Controller,Triggers,DPad,Buttons,Ljoy,Lclick,Rjoy,Rclick) - - -def RSXS_Kappa_Controller_backup(): #Keep JM modified below when kth broke - """ - Button={} with Button[][0]=PV name and Button[][1]=value (for tweaks or other procs value=1) - ".TWF -> (+)tweak" - ".TWR -> (-)tweak" - """ - Controller="29idSneezySoft" - ioc="29idKappa:" - - Triggers={} #['LTSeq','RTSeq','LBSeq','RBSeq'] - Triggers[0]=ioc+"m9.TWR",1 #tth - Triggers[1]=ioc+"m9.TWF",1 - Triggers[2]=ioc+"allstop.VAL",1 - Triggers[3]=ioc+"allstop.VAL",1 - - DPad={} #['UpSeq','DownSeq','LeftSeq','RightSeq'] - DPad[0]=ioc+"m4.TWF",1 #z - DPad[1]=ioc+"m4.TWR",1 - DPad[2]=ioc+"m1.TWR",1 #phi - DPad[3]=ioc+"m1.TWF",1 - - Buttons={} #['YSeq','ASeq','XSeq','BSeq'] - Buttons[0]=ioc+"m3.TWF",1 #y - Buttons[1]=ioc+"m3.TWR",1 - Buttons[2]=ioc+"m2.TWR",1 #x - Buttons[3]=ioc+"m2.TWF",1 - - Ljoy={} #['LSUpSeq','LSDownSeq','LSLeftSeq','LSRightSeq'] - Ljoy[0]="",0 - Ljoy[1]="",0 - Ljoy[2]=ioc+"m8.TWR",1 #th - Ljoy[3]=ioc+"m8.TWF",1 - Lclick={} #['L3Seq'] - Lclick[0]=ioc+"m2.TWV",50 #x - Lclick[1]=ioc+"m3.TWV",50 #y - Lclick[2]=ioc+"m4.TWV",50 #z - Lclick[3]=ioc+"m1.TWV",0.5 #phi (0.5 deg) - Lclick[4]=ioc+"m7.TWV",0.5 #kappa - Lclick[5]=ioc+"m8.TWV",0.5 #th - Lclick[6]=ioc+"m9.TWV",0.5 #tth - Lclick[7]="",0 - Lclick[8]="",0 - - Rjoy={} #['RSUpSeq','RSDownSeq','RSLeftSeq','RSRightSeq'] - Rjoy[0]="",0 - Rjoy[1]="",0 - Rjoy[2]=ioc+"m7.TWR",1 #kappa - Rjoy[3]=ioc+"m7.TWF",1 - Rclick={} #['R3Seq'] - Rclick[0]=ioc+"m2.TWV",250 #x - Rclick[1]=ioc+"m3.TWV",250 #y - Rclick[2]=ioc+"m4.TWV",250 #z - Rclick[3]=ioc+"m1.TWV",5 #phi (45 deg) - Rclick[4]=ioc+"m7.TWV",5 #kappa - Rclick[5]=ioc+"m8.TWV",5 #th - Rclick[6]=ioc+"m9.TWV",5 #tth - Rclick[7]="",0 - Rclick[8]="",0 - - Controller_setup(Controller,Triggers,DPad,Buttons,Ljoy,Lclick,Rjoy,Rclick) - -def RSXS_Kappa_Controller(): - """ - Button={} with Button[][0]=PV name and Button[][1]=value (for tweaks or other procs value=1) - ".TWF -> (+)tweak" - ".TWR -> (-)tweak" - """ - Controller="29idSneezySoft" - ioc="29idKappa:" - - Triggers={} #['LTSeq','RTSeq','LBSeq','RBSeq'] - Triggers[0]=ioc+"m9.TWR",1 #tth - Triggers[1]=ioc+"m9.TWF",1 - Triggers[2]=ioc+"allstop.VAL",1 - Triggers[3]=ioc+"allstop.VAL",1 - - DPad={} #['UpSeq','DownSeq','LeftSeq','RightSeq'] - DPad[0]=ioc+"m4.TWF",1 #z - DPad[1]=ioc+"m4.TWR",1 - DPad[2]=ioc+"m1.TWR",1 #phi - DPad[3]=ioc+"m1.TWF",1 - - Buttons={} #['YSeq','ASeq','XSeq','BSeq'] - Buttons[0]=ioc+"m3.TWF",1 #y - Buttons[1]=ioc+"m3.TWR",1 - Buttons[2]=ioc+"m2.TWR",1 #x - Buttons[3]=ioc+"m2.TWF",1 - - Ljoy={} #['LSUpSeq','LSDownSeq','LSLeftSeq','LSRightSeq'] - Ljoy[0]="29idd:Unidig1Bo0",0 #light on - Ljoy[1]="29idd:Unidig1Bo0",1 #light off - Ljoy[2]=ioc+"",0 #th - Ljoy[3]=ioc+"",0 - Lclick={} #['L3Seq'] - Lclick[0]=ioc+"m2.TWV",250 #x - Lclick[1]=ioc+"m3.TWV",250 #y - Lclick[2]=ioc+"m4.TWV",250 #z - Lclick[3]=ioc+"m1.TWV",0.5 #phi (0.5 deg) - Lclick[4]=ioc+"m7.TWV",0.5 #kappa - Lclick[5]=ioc+"m8.TWV",0.5 #th - Lclick[6]=ioc+"m9.TWV",0.5 #tth - Lclick[7]="",0 - Lclick[8]="",0 - - Rjoy={} #['RSUpSeq','RSDownSeq','RSLeftSeq','RSRightSeq'] - Rjoy[0]="",0 - Rjoy[1]="",0 - Rjoy[2]=ioc+"",0 #kappa - Rjoy[3]=ioc+"",0 - Rclick={} #['R3Seq'] - Rclick[0]=ioc+"m2.TWV",500 #x - Rclick[1]=ioc+"m3.TWV",500 #y - Rclick[2]=ioc+"m4.TWV",500 #z - Rclick[3]=ioc+"m1.TWV",5 #phi (45 deg) - Rclick[4]=ioc+"m7.TWV",5 #kappa - Rclick[5]=ioc+"m8.TWV",5 #th - Rclick[6]=ioc+"m9.TWV",5 #tth - Rclick[7]="",0 - Rclick[8]="",0 - - Controller_setup(Controller,Triggers,DPad,Buttons,Ljoy,Lclick,Rjoy,Rclick) - - -def RSoXS_Controller(): - """ - Button={} with Button[][0]=PV name and Button[][1]=value (for tweaks or other procs value=1) - ".TWF -> (+)tweak" - ".TWR -> (-)tweak" - """ - Controller="29idSneezySoft" - ioc="29idRSoXS:" - - Triggers={} #['LTSeq','RTSeq','LBSeq','RBSeq'] - Triggers[0]=ioc+"allstop.VAL",1 - Triggers[1]=ioc+"allstop.VAL",1 - Triggers[2]=ioc+"allstop.VAL",1 - Triggers[3]=ioc+"allstop.VAL",1 - - DPad={} #D-Pad:['UpSeq','DownSeq','LeftSeq','RightSeq'] - DPad[0]=ioc+"m10.TWF",1 #Det-V - DPad[1]=ioc+"m10.TWR",1 - DPad[2]=ioc+"m11.TWR",1 #Det-Q - DPad[3]=ioc+"m11.TWF",1 - - Buttons={} #Buttons:['YSeq','ASeq','XSeq','BSeq'] - Buttons[0]=ioc+"m2.TWF",1 #y - Buttons[1]=ioc+"m2.TWR",1 - Buttons[2]=ioc+"m1.TWR",1 #x - Buttons[3]=ioc+"m1.TWF",1 - - Ljoy={} #Left Joystick:['LSUpSeq','LSDownSeq','LSLeftSeq','LSRightSeq'] - Ljoy[0]=ioc+"m5.TWF",1 #phi - Ljoy[1]=ioc+"m5.TWR",1 - Ljoy[2]=ioc+"m9.TWR",1 #tth - Ljoy[3]=ioc+"m9.TWF",1 - Lclick={} #['L3Seq'] - Lclick[0]="",0 - Lclick[1]="",0 - Lclick[2]="",0 - Lclick[3]="",0 - Lclick[4]="",0 - Lclick[5]="",0 - Lclick[6]="",0 - Lclick[7]="",0 - Lclick[8]="",0 - - Rjoy={} #Right Joystick:['RSUpSeq','RSDownSeq','RSLeftSeq','RSRightSeq'] - Rjoy[0]=ioc+"m3.TWF",1 #z - Rjoy[1]=ioc+"m3.TWF",1 - Rjoy[2]=ioc+"m8.TWR",1 #th - Rjoy[3]=ioc+"m8.TWF",1 - Rclick={} #['R3Seq'] - Rclick[0]=ioc+"m2.TWV",1 #x - Rclick[1]=ioc+"m3.TWV",1 #y - Rclick[2]=ioc+"m4.TWV",1 #z - Rclick[3]=ioc+"m1.TWV",1 #th - Rclick[4]=ioc+"m7.TWV",1 #phi - Rclick[5]=ioc+"m8.TWV",1 #tth - Rclick[6]=ioc+"m9.TWV",1 #Det-V - Rclick[7]=ioc+"m9.TWV",1 #Det-Q - Rclick[8]="",0 - - Controller_setup(Controller,Triggers,DPad,Buttons,Ljoy,Lclick,Rjoy,Rclick) - -def Controller_setup(Controller,Triggers,DPad,Buttons,Ljoy,Lclick,Rjoy,Rclick): - """ -------- Standard set up for the Logitech controllers -------------- - Controller -> controller ioc name - - Button={} - Button[][0]=PV name - Button[][1]=value (for tweaks or other procs value=1) - ".TWF -> (+)tweak" - ".TWR -> (-)tweak" - - Trigger[0,3] -> PVs for link 1 of the 4 buttons (bottoms are typically the allstop) - DPad[0,3] -> PVs for link 1 of the 4 buttons (order: Top/Bottom/Left/Right) - Buttons[0,3] -> PVs for link 1 of the 4 buttons (order: Top/Bottom/Left/Right) - Ljoy[0,3] -> PVs for link 1 of the 4 buttons (order: Top/Bottom/Left/Right) - Lclick[0,8] -> PVs for Link 1-9 of the center click (typically coarse tweak values) - RJoy[0,3] -> PVs for link 1 of the 4 buttons (order: Top/Bottom/Left/Right) - Rclick[0,8] -> PVs for Link 1-9 of the center click (typically fine tweak values) - """ - - #Triggers - Ctrl_button(Controller,"LTSeq",1,Triggers[0][0],Triggers[0][1]) - Ctrl_button(Controller,"RTSeq",1,Triggers[1][0],Triggers[1][1]) - Ctrl_button(Controller,"LBSeq",1,Triggers[2][0],Triggers[2][1])#All Stop - Ctrl_button(Controller,"RBSeq",1,Triggers[3][0],Triggers[3][1])#All Stop - - # D-Pad - Ctrl_button(Controller,"UpSeq",1, DPad[0][0],DPad[0][1]) - Ctrl_button(Controller,"DownSeq",1, DPad[1][0],DPad[1][1]) - Ctrl_button(Controller,"LeftSeq",1, DPad[2][0],DPad[2][1]) - Ctrl_button(Controller,"RightSeq",1,DPad[3][0],DPad[3][1]) - - - #Buttons - Ctrl_button(Controller,"YSeq",1,Buttons[0][0],Buttons[0][1]) - Ctrl_button(Controller,"ASeq",1,Buttons[1][0],Buttons[1][1]) - Ctrl_button(Controller,"XSeq",1,Buttons[2][0],Buttons[2][1]) - Ctrl_button(Controller,"BSeq",1,Buttons[3][0],Buttons[3][1]) - - - #Left Joystick - Ctrl_button(Controller,"LSUpSeq",1, Ljoy[0][0],Ljoy[0][1]) - Ctrl_button(Controller,"LSDownSeq",1, Ljoy[1][0],Ljoy[1][1]) - Ctrl_button(Controller,"LSLeftSeq",1, Ljoy[2][0],Ljoy[2][1]) - Ctrl_button(Controller,"LSRightSeq",1,Ljoy[3][0],Ljoy[3][1]) - #Left Click Coarse Tweak Values - Ctrl_button(Controller,"L3Seq",1,Lclick[0][0],Lclick[0][1]) - Ctrl_button(Controller,"L3Seq",2,Lclick[1][0],Lclick[1][1]) - Ctrl_button(Controller,"L3Seq",3,Lclick[2][0],Lclick[2][1]) - Ctrl_button(Controller,"L3Seq",4,Lclick[3][0],Lclick[3][1]) - Ctrl_button(Controller,"L3Seq",5,Lclick[4][0],Lclick[4][1]) - Ctrl_button(Controller,"L3Seq",6,Lclick[5][0],Lclick[5][1]) - Ctrl_button(Controller,"L3Seq",7,Lclick[6][0],Lclick[6][1]) - Ctrl_button(Controller,"L3Seq",8,Lclick[7][0],Lclick[7][1]) - Ctrl_button(Controller,"L3Seq",9,Lclick[8][0],Lclick[8][1]) - - #Right Joystick - Ctrl_button(Controller,"RSUpSeq",1, Rjoy[0][0],Rjoy[0][1]) - Ctrl_button(Controller,"RSDownSeq",1, Rjoy[1][0],Rjoy[1][1]) - Ctrl_button(Controller,"RSLeftSeq",1, Rjoy[2][0],Rjoy[2][1]) - Ctrl_button(Controller,"RSRightSeq",1,Rjoy[3][0],Rjoy[3][1]) - #Right Click Fine Tweak Values - Ctrl_button(Controller,"R3Seq",1,Rclick[0][0],Rclick[0][1]) - Ctrl_button(Controller,"R3Seq",2,Rclick[1][0],Rclick[1][1]) - Ctrl_button(Controller,"R3Seq",3,Rclick[2][0],Rclick[2][1]) - Ctrl_button(Controller,"R3Seq",4,Rclick[3][0],Rclick[3][1]) - Ctrl_button(Controller,"R3Seq",5,Rclick[4][0],Rclick[4][1]) - Ctrl_button(Controller,"R3Seq",6,Rclick[5][0],Rclick[5][1]) - Ctrl_button(Controller,"R3Seq",7,Rclick[6][0],Rclick[6][1]) - Ctrl_button(Controller,"R3Seq",8,Rclick[7][0],Rclick[7][1]) - Ctrl_button(Controller,"R3Seq",9,Rclick[8][0],Rclick[8][1]) - - -def Ctrl_reset(Controller): - PV="" - val=0 - CtrlButtonList = ['LTSeq','RTSeq','LBSeq','RBSeq','UpSeq','DownSeq','LeftSeq','RightSeq','YSeq','ASeq','XSeq','BSeq'] - CtrlButtonList.extend(['LSUpSeq','LSDownSeq','LSLeftSeq','LSRightSeq','L3Seq','RSUpSeq','RSDownSeq','RSLeftSeq','RSRightSeq','R3Seq']) - for button in CtrlButtonList: - for link in range(1,10): - Ctrl_button(Controller,button,link,PV,val) - -def Ctrl_button(Controller,button,link,PV,val):#writes to specified link (controller has 1 to 9) - ctlpv=Controller+":ctl1:"+button - caput(ctlpv+".LNK"+str(link),PV+" NPP NMS") - caput(ctlpv+".DO"+str(link),val) - -def Ctrl_print(Controller): - CtrlButtonList = ['LTSeq','RTSeq','LBSeq','RBSeq','UpSeq','DownSeq','LeftSeq','RightSeq','YSeq','ASeq','XSeq','BSeq'] - CtrlButtonList.extend(['LSUpSeq','LSDownSeq','LSLeftSeq','LSRightSeq','L3Seq','RSUpSeq','RSDownSeq','RSLeftSeq','RSRightSeq','R3Seq']) - for button in CtrlButtonList: - print("---"+button+"---") - for link in range(1,10): - ctlpv=Controller+":ctl1:"+button - PV=caget(ctlpv+".LNK"+str(link)) - val=caget(ctlpv+".DO"+str(link)) - print(" "+PV+", "+str(val)) diff --git a/build/lib/iexcode/instruments/resolution.py b/build/lib/iexcode/instruments/resolution.py deleted file mode 100644 index c6f5a73169e11f831e562c9b6ec8555b3ed52f7e..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/resolution.py +++ /dev/null @@ -1,136 +0,0 @@ -import numpy as np - -from epics import caget - -import iexcode.instruments.cfg as iex -from iexcode.instruments.utilities import take_closest_value -from iexcode.instruments.xrays import getE, slit_get -from iexcode.instruments.VLS_PGM import mono_grating_get -from iexcode.instruments.electron_analyzer import EA, resolution_EA, SES_slit_get -from iexcode.instruments.ARPES import ARPES_extra_pvs -############################################################################################################# -############################## Resolution ############################## -############################################################################################################# -def resolution(): - """ - Calculate the theoretical resolution for the current beamline settings: - ARPES: total resolution i.e. sqrt(kbT^2 + analyzer^2 + BL^2); default SES slit = 5. - Kappa: beamline contribution only - """ - branch = iex.BL.branch - grt = mono_grating_get() - hv_eV = getE() - slit_size = take_closest_value([10,20,50,100,200],round(slit_get(),0)) - - if branch == "c": - slit_SES = SES_slit_get() - PE = int(EA.PassEnergy) - Tsample = caget(ARPES_extra_pvs['TA']) - resolution_ARPES(grt,hv_eV,slit_size,PE,slit_SES,Tsample,verbose=True) - print("Calculate: resolution_ARPES(grt,hv_eV,slit_size,PE,slit_SES,Tsample)") - else: - resolution_beamline(grt,hv_eV,slit_size,verbose=True) - print("Calculate: resolution_beamline(grt,hv_eV,slit_size)") - - - -def resolution_calculate_beamline(grt,hv_eV,slit_size): - """ - - Previously: Calc_BL_Resolution - """ - res_function={} - res_function[10] = {"MEG":(-0.000800494,2.56761e-05,1.83724e-08,-1.69223e-12,0), "HEG":(-0.000414482,1.07456e-05,8.79034e-09,-8.42361e-13,0)} - res_function[20] = {"MEG":(-0.00156643, 3.16894e-05,2.72121e-08,-2.63642e-12,0), "HEG":(-0.00054591, 1.35647e-05,2.01775e-08,-4.30789e-12,5.70112e-16)} - res_function[50] = {"MEG":(-0.00251543, 4.89022e-05,7.70055e-08,-1.66358e-11,2.21272e-15),"HEG":(-0.00173081, 2.97625e-05,4.90646e-08,-1.0706e-11, 1.43011e-15)} - res_function[100] = {"MEG":(-0.00545563, 9.14928e-05,1.51335e-07,-3.30332e-11,4.41314e-15),"HEG":(-0.00360316, 5.83265e-05,9.76881e-08,-2.13767e-11,2.85877e-15)} - res_function[200] = {"MEG":(-0.0111658, 0.000179785,3.01277e-07,-6.59309e-11,8.81755e-15),"HEG":(-0.00728107, 0.000116055,1.95149e-07,-4.27331e-11,5.71638e-15)} - try: - a,b,c,d,e = res_function[slit_size][grt] - resolution = a + b*hv_eV + c*hv_eV**2 + d*hv_eV**3 + e*hv_eV**4 - - except KeyError: - print("WARNING: Slit size not listed, please choose one of the following:") - print(" 10, 20, 50, 100, 200 um.") - resolution=0 - - return resolution*1000 - - -def resolution_mono_noise(grt,hv_eV): - """ - jitter/noise in the mono contribution to the resolution - - Previoulsy: Resolution_Mono - """ - if grt == "MEG": - K0=-2.3836 - K1=0.02083 - K2=7.8886e-06 - if grt == "HEG": - K0=-2.0984 - K1=0.011938 - K2=3.6397e-06 - noise = K0 + K1*hv_eV + K2*hv_eV**2 - return noise - - -def resolution_beamline(grt,hv_eV,slit_size,verbose=True): - """ - resolution of the beamline optics - - Resolution_BL - """ - mono_noise = resolution_mono_noise(grt,hv_eV) - theortical = resolution_calculate_beamline(grt,hv_eV,slit_size) - resolution=np.sqrt(theortical**2 + mono_noise**2) - if verbose: - print("BL : "+"%.0f" % theortical, "meV") - print("Mono : "+"%.0f" % mono_noise, "meV") - print("Total: "+"%.0f" % resolution, "meV") - return resolution - - -def resolution_ARPES(grt,hv_eV,slit_size,PE,slit_SES,T,verbose=True): - """ - resolution of the ARPES - """ - bl = resolution_beamline(grt,hv_eV,slit_size,verbose=False) - KbT = T*25/300 - SES = resolution_EA(PE,slit_SES) - - resolution = np.sqrt(bl**2 + KbT**2 + SES**2) - - if verbose: - print("BL + mono : "+"%.0f" % bl, "meV") - print("SES : "+"%.0f" % SES, "meV") - print("KbT : "+"%.0f" % KbT, "meV") - print("Total: "+"%.0f" % resolution, "meV") - - return resolution - -def resolution_BL_eff(grating,hv,slit_3C,PE,slit_SES,T,Ef): - M = resolution_mono_noise(grating,hv) - KbT = T*25/300 - BL = resolution_calculate_beamline(grating,hv,slit_3C) - SES = resolution_EA(PE,slit_SES) - resolution = np.sqrt(BL**2+SES**2+KbT**2+M**2) - effective = np.sqrt(Ef**2-SES**2-KbT**2-M**2) - print("BL_th : "+"%.0f" % BL, "meV SES : "+"%.0f" % SES, "meV") - print("Mono : "+"%.0f" % M, "meV KbT : "+"%.0f" % KbT, "meV") - print("Total : "+"%.0f" % resolution, "meV Fermi : "+"%.0f" % Ef, "meV") - print("BL_eff: "+"%.0f" % effective, "meV") - - -def resolution_BL_eff2(grating,hv,slit_3C,PE,slit_SES,T,Ef,Dirty_Au): - M = resolution_mono_noise(grating,hv) - KbT = T*25/300 - BL = resolution_calculate_beamline(grating,hv,slit_3C) - SES = resolution_EA(PE,slit_SES) - resolution = np.sqrt(BL**2+SES**2+KbT**2+M**2+Dirty_Au**2) - effective = np.sqrt(Ef**2-SES**2-KbT**2-M**2-Dirty_Au**2) - print("BL_th : "+"%.0f" % BL, "meV SES : "+"%.0f" % SES, "meV") - print("Mono : "+"%.0f" % M, "meV KbT : "+"%.0f" % KbT, "meV") - print("Total : "+"%.0f" % resolution, "meV Fermi : "+"%.0f" % Ef, "meV") - print("BL_eff: "+"%.0f" % effective, "meV Sample : "+"%.0f" % Dirty_Au, "meV") - diff --git a/build/lib/iexcode/instruments/s29_temp_cntl.py b/build/lib/iexcode/instruments/s29_temp_cntl.py deleted file mode 100644 index 4bffcdae02016ef54eeb3e51bff3f8d9b26c390d..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/s29_temp_cntl.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env python - -from epics import caget, caput -from time import sleep, gmtime, strftime, localtime - -#Define caput with wait function -def caputw(PVname,PVinput): - return caput(PVname,PVinput,wait=True, timeout = 100000) - -def dateandtime(): - return strftime("%a %d %b %Y %H:%M:%S",localtime()) - -def tempr(): - print("RSXS Sample Temperature: {} K".format(caget("29idd:LS331:TC1:SampleA"))) - -def temps(tempset): - print("Initial Sample Temperature:",caget("29idd:LS331:TC1:SampleA")," K",dateandtime()) - caput("29idd:LS331:TC1:wr_SP",1.0*tempset) - stop_var=0 - b=0 - sleep(10) - while b == 0: - delta=abs(caget("29idd:LS331:TC1:SampleA")-1.0*tempset) - if abs(delta) < 1: - c=0 - while c < 10: - sleep(1) - delta=delta+(caget("29idd:LS331:TC1:SampleA")-1.0*tempset) - c=c+1 - if abs(delta/10) < 1: - print("Stable Sample Temperature:",caget("29idd:LS331:TC1:SampleA")," K",dateandtime()) - b=1 - else: - temp1=caget("29idd:LS331:TC1:SampleA") - sleep(10) - temp2=caget("29idd:LS331:TC1:SampleA") - if abs(temp1-temp2) < 0.1: - sleep(30) - temp2=caget("29idd:LS331:TC1:SampleA") - if abs(temp1-temp2) < .5: - print("UNABLE TO STABLIZE TEMPERATURE! Stopped at T=:",caget("29idd:LS331:TC1:SampleA")," K",dateandtime()) - b=1 - - diff --git a/build/lib/iexcode/instruments/scalers.py b/build/lib/iexcode/instruments/scalers.py deleted file mode 100644 index 705710f3bce187e746b4e09743c83870d4b1512b..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/scalers.py +++ /dev/null @@ -1,66 +0,0 @@ -from math import floor -from epics import caput,PV - -import iexcode.instruments.cfg as iex - -def scaler_cts(time_seconds=0.1,verbose=True): - """ - sets the scalers counting for the endstation defined in BL - """ - 'For new endstation modify here:' - if iex.BL.endstation_name == 'kappa': - Kappa_scaler(time_seconds,verbose=verbose) - elif iex.BL.endstation_name == 'Octupole': - Octupole_scaler(time_seconds,verbose) - else: - pass - -def Kappa_scaler(time_seconds,verbose): - """ - Sets the integration time for the scalers in the Kappa chamber - and mpa filter num if mpa is running - """ - scaler_pv="29idMZ0:scaler1.TP" - mpa_NumFilter = '29iddMPA:Proc1:NumFilter' - - caput(pv,time_seconds) - - pv=PV(mpa_NumFilter) - if pv.connected(): - caput(mpa_NumFilter,max(floor(time_seconds),1)) - - if verbose: - print("Integration time set to:", str(time_seconds)) - - -def Octupole_scaler(time_seconds,verbose): - """ - Sets the integration time for the scalers in the Kappa chamber - and mpa filter num if mpa is running - """ - scaler_pv="29ide:scaler1.TP" #JM fix here - - caput(scaler_pv,time_seconds) - - if verbose: - print("Integration time set to:", str(time_seconds)) - - -class Scaler: - def __init__(self, pv): - """ - to access scaler pvs - usage: - tfy = Scaler('29ide:scaler1.S5') - tfy.get() => to caget the current value - """ - self.pv = pv - - def get(self,verbose=True): - """ - returns the current value - """ - val = caget(self.pv) - if verbose: - print(val) - return val diff --git a/build/lib/iexcode/instruments/scanRecord.py b/build/lib/iexcode/instruments/scanRecord.py deleted file mode 100644 index d0537a2db0d1643cb064429a838ea48a242e62c2..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/scanRecord.py +++ /dev/null @@ -1,916 +0,0 @@ - -from os.path import join -import time - -from epics import caget, caput, PV - -import iexcode.instruments.cfg as iex -from iexcode.instruments.utilities import dateandtime, print_warning_message -from iexcode.instruments.userCalcs import userStringSeq_pvs,userStringSeq_clear -from iexcode.instruments.shutters import shutter_check -from iexcode.instruments.Logfile import log_update - -def scan_fillin(VAL,RBV,start,stop,steps_points,**kwargs): - """ - fills in the scan record for the curretn beamline ioc - """ - try: - iex.BL.mda.fillin(VAL,RBV,start,stop,steps_points,**kwargs) - except: - print("IEX_endstations has not been initialized") - -def scan_fillin_table(VAL,RBV,my_table,**kwargs): - """ - fills in the scan record for the curretn beamline ioc - """ - try: - iex.BL.mda.fillin_table(VAL,RBV,my_table,**kwargs) - except: - print("IEX_endstations has not been initialized") - -def scan_go(**kwargs): - """ - Starts a scan - by default: scanDIM=1 - Logging is automatic: use **kwargs or the optional logging arguments see scanlog() for details - kwargs: - X-ray = True (default), does shutter checks - = False no shutter checks - """ - try: - iex.BL.mda.go(verbose=True,**kwargs) - except: - print("IEX_endstations has not been initialized") - - -def last_mda(): - """ - returns the last mda file number in the ioc defined by BL_ioc - Previously: LastMDA - """ - try: - filenum = iex.BL.mda.lastFileNum() - return filenum - except: - print("IEX_endstations has not been initialized") - -def user_path(): - """ - returns to the user directory as found in the mda scanRecord - """ - return iex.BL.mda.filepath() - -def saveData_get_all(ioc_pv): - """ - returns saveData info: - """ - try: - saveData_info = { - 'fileSystem':caget(ioc_pv+"saveData_fileSystem",as_string=True), - 'subDir':caget(ioc_pv+"saveData_subDir",as_string=True), - 'scanNumber':caget(ioc_pv+"saveData_scanNumber"), - 'baseName':caget(ioc_pv+"saveData_baseName",as_string=True), - } - #take care of subDir starting with '/' - f1 = saveData_info['fileSystem'] - f2 = saveData_info['subDir'][1:] if saveData_info['subDir'][0] =='/' else saveData_info['subDir'] - filepath = join(f1,f2) - #take care f filesystem starting with '//' (VME only) - filepath=filepath.replace('//','/') - saveData_info['filepath'] = filepath - return saveData_info - except: - print(ioc_pv+"not connected") - return {} - - - - -############################################################################################################## -########################### Scan class ###################### -############################################################################################################## -default_positioner_settling_time = 0.05 -default_detector_settling_time = 0.1 - -class ScanRecord: - """ - used for short hand scanning and to get info related to a scanRecord - """ - - def __init__(self,scan_ioc,**kwargs): - """ - mda = scanRecord('29idTest:') - mda.scan_ioc: full pv for the ioc, "29idARPES:", "29idc:" - mda.detector_dictionary: dictionary corresponding to detector num and pv to proc => {det_num:'det_pv'} - mda.trigger_dictionary: dictionary corresponding to trigger num and trigger pv => {trigger_num:'trigger_pv'} - mda.before_scan_pv: pv to be proc'ed be for the start of a scan - mda.after_scan_pv: pv to be proc'ed be for the start of a scan - mda.snake_set: function which adds/removes sign of step to the after_scan - mda.log - - **kwargs: - if a kwargs is not specified then it will not modify that field of the scanRecord - empty = True - kwargs = { - 'detector_dictionary':'{}', - 'trigger_dictionary':'{}', - 'before_scan_pv':"", - 'after_scan_pv':"" - } - """ - - self.ioc = scan_ioc - - if 'empty' in kwargs: - if kwargs['empty']: - kwargs = { - 'detector_dictionary':'{}', - 'trigger_dictionary':'{}', - 'before_scan_pv':"", - 'after_scan_pv':"" - } - if 'detector_dictionary' in kwargs: - self.detector_dictionary = kwargs['detector_dictionary'] - else: - self.detector_dictionary = {} - - if 'trigger_dictionary' in kwargs: - self.trigger_dictionary = kwargs['trigger_dictionary'] - else: - self.trigger_dictionary = {} - - if 'before_scan_pv' in kwargs: - self.before_scan_pv = kwargs['before_scan_pv'] - else: - self.before_scan_pv = None - - if 'after_scan_pv' in kwargs: - self.after_scan_pv = kwargs['after_scan_pv'] - else: - self.after_scan_pv = None - - if 'default_detector_settling_time' in kwargs: - self.default_detector_settling_time = kwargs['default_detector_settling_time'] - else: - self.default_detector_settling_time = default_detector_settling_time - - if 'default_positioner_settling_time' in kwargs: - self.default_positioner_settling_time = kwargs['default_positioner_settling_time'] - else: - self.default_positioner_settling_time = default_positioner_settling_time - - if 'logging' in kwargs: - self.log = kwargs['logging'] - else: - self.log = None - - if 'snake_set' in kwargs: - self.snake_set = kwargs['snake_set'] - else: - self.snake_set = None - pass - - - - - -############################################################################################################## -################################ MDA (ScanRecord) files and folders ############################## -############################################################################################################## - - def fileNum(self): - """ - returns the current fileNum in the SaveData of ioc is scanning - or next if idle - - """ - - return saveData_get_all(self.ioc)['scanNumber'] - - def lastFileNum(self): - """ - returns the last saved fileNum in the SaveData of ioc - - previously: MDA_GetLastFileNum - """ - - fileNum = self.fileNum() - return fileNum - 1 - - - def filepath(self): - """ - returns the full filepath for the SaveData of ioc - - previously: MDA_CurrentDirectory - """ - return saveData_get_all(self.ioc)['filepath'] - - def prefix(self): - """ - returns the prefix for the SaveData of ioc - - previously: MDA_CurrentPrefix - """ - return saveData_get_all(self.ioc)['baseName'] - - def current_run(self): - """ - returns the current run by parsing the filepath in the SaveData for ioc - - previously: MDA_CurrentRun - """ - filepath = self.filepath() - m=filepath.find('data_29id')+len('data_29id')+2 - current_run=filepath[m:m+6] - return current_run - - def user_name(self): - """ - returns the current user by parsing the filepath in the SaveData for ioc - - previously: MDA_CurrentUser - """ - subdir=saveData_get_all(self.ioc)['subDir'] - m=subdir.find('/mda') - if m == 0 : - current_user='staff' - elif m > 0: - current_user=subdir[1:m] - else: - current_user="" - print_warning_message("mda_user is empty string") - return current_user - - -############################################################################################################## -############################# filling in the scan record ############################## -############################################################################################################## - - - ### before and after scans - def _before_after_scan_set(self,scan_dim,**kwargs): - """ - Clears the before_scan and after_scan in all dims - Fills in the before_scan and after_after pv for kwargs['scan_dim'] only - **kwargs - before_scan_pv - after_scan_pv - """ - - scan_pv = self.ioc+"scan"+str(scan_dim) - - if 'before_scan_pv' in kwargs: - self.before_scan_pv = kwargs['before_scan_pv'] - caput(scan_pv+".BSPV",self.before_scan_pv) - caput(scan_pv+".BSCD",1) - caput(scan_pv+".BSWAIT","Wait") - - if 'after_scan_pv' in kwargs: - self.before_scan_pv = kwargs['after_scan_pv'] - caput(scan_pv+".ASPV",self.after_scan_pv) - caput(scan_pv+".ASCD",1) - caput(scan_pv+".ASWAIT","Wait") - - - - def default_after_scan_seq(self,**kwargs): - """ - writes the user string sequence to happen at the end of a scan - returns after_scan_pv = pv for userStringSeq for after scan - - uses links 1-4, link 10 is reserved for snake scans - - **kwargs - seq_num: userStringSeq number in ioc => 10 (default) - positioner_settling_time - detector_settling_time - - Previously: AfterScan_StrSeq - """ - kwargs.setdefault('seq_num',10) - kwargs.setdefault('positioner_settling_time',default_positioner_settling_time) - kwargs.setdefault('detector_settling_time',default_detector_settling_time) - - scan_dim = 1 - scan_pv = self.ioc+"scan"+str(scan_dim) - - seq_num=kwargs['seq_num'] - after_scan_pv = userStringSeq_pvs(self.ioc, seq_num)[0] - self.after_scan_pv = after_scan_pv - - #clear and write the after scan user sequence - userStringSeq_clear(self.ioc,seq_num) - caput(after_scan_pv+".DESC","After Scan") - - #link 1 - clears positioners - caput(after_scan_pv+".LNK1",scan_pv+'.P1AR'+" PP NMS") - caput(after_scan_pv+".STR1","Clear pos&rdbk PV's, etc") - - #link 2 - sets positioner mode to to abosolute - caput(after_scan_pv+".LNK2",scan_pv+'.CMND'+" PP NMS") - caput(after_scan_pv+".STR2","ABSOLUTE") - - #link 3 - sets positioner delay time to default - settling_time = kwargs['positioner_settling_time'] - caput(after_scan_pv+".LNK3",scan_pv+'.PDLY'+" PP NMS") - caput(after_scan_pv+".DO3",settling_time) - - #link 4 - sets detector delay time to default - settling_time = kwargs['detector_settling_time'] - caput(after_scan_pv+".LNK4",scan_pv+'.DDLY'+" PP NMS") - caput(after_scan_pv+".DO4",settling_time) - - return after_scan_pv+".PROC" - - ### Resetting: - def reset_scan_dim(self,scan_dim,**kwargs): - """ - Resets all the scanRecords (scanDIM=1,2,3,4) for a given IOC - **kwargs: - detector_dictionary - trigger_dictionary - before_scan_pv - after_scan_pv - - Previously: Reset_ScanAll - """ - - #clearing - self.detectors_clear(scan_dim,{}) - self.triggers_clear(scan_dim,{}) - self.positioners_clear({scan_dim:scan_dim}) - - #resetting - if 'detector_dictionary' in kwargs: - self.detectors_set(scan_dim,kwargs['detector_dictionary']) - if 'trigger_dictionary' in kwargs: - self.triggers_set(scan_dim,kwargs['trigger_dictionary']) - - self._before_after_scan_set(scan_dim,**kwargs) - - #settling time - kwargs.setdefault('scan_dim',scan_dim) - self.detector_settling_time(**kwargs) - self.positioner_settling_time(**kwargs) - - def reset_all(self,**kwargs): - """ - Resets all the scanRecords (scanDIM=1,2,3,4) for a given IOC - - - **kwargs - detector_dictionary - trigger_dictionary - before_scan_pv - after_scan_pv - - Note that for scan_dim = 1; default values are those that were set to attributes - - Previously: Reset_ScanAll - """ - kwargs.setdefault('detector_dictionary',self.detector_dictionary) - kwargs.setdefault('trigger_dictionary',self.trigger_dictionary) - if self.before_scan_pv != None: - kwargs.setdefault('before_scan_pv',self.before_scan_pv) - if self.after_scan_pv != None: - kwargs.setdefault('after_scan_pv',self.after_scan_pv) - - #clearing all - for scan_dim in range(4,1): - self.reset_scan_dim(scan_dim,{},{},'','') - - #setting to defaults - self.reset_scan_dim(1,**kwargs) - - ### default setting - def settings_defaults(self,scan_dim,verbose=True,**kwargs): - """ - Reset scan settings to default: ABSOLUTE, STAY, 0.05/0.1 positioner/detector settling time - - Previous: Reset_Scan - """ - kwargs.setdefault('scan_dim',scan_dim) - scan_pv = self.ioc+"scan"+str(kwargs['scan_dim']) - self.positioner_absolute_mode(absolute=True,**kwargs) # Absolute position - self.positioner_after_scan(after="PRIOR POS",**kwargs) # After scan: prior position - self.positioner_settling_time(**kwargs)# Positioner Settling time => default - self.detector_settling_time(**kwargs)# Detector Settling time => default - self.triggers_reset(verbose=False,**kwargs) - - if verbose: - print("Scan record "+self.ioc+" reset to default settings.") - - ### positioners - def positioners_clear(self,verbose=True,**kwargs): - """ - Clear all extra scan positioners - - Previously: Clear_Scan_Positioners - """ - kwargs.setdefault('scan_dim',1) - - scan_pv = self.ioc+"scan"+str(kwargs['scan_dim']) - caput(scan_pv+".CMND",4) # Clear all Positioners,etc - - if verbose: - print("\nAll extra positionners cleared") - - def positioner_settling_time(self,**kwargs): - """ - sets the positioner settling time - """ - kwargs.setdefault('scan_dim',1) - kwargs.setdefault('positioner_settling_time',self.default_positioner_settling_time) - - scan_pv = self.ioc+"scan"+str(kwargs['scan_dim']) - - caput(scan_pv+".PDLY",kwargs['positioner_settling_time']) # Positioner Settling time - return scan_pv+".PDLY",kwargs['positioner_settling_time'] - - def positioner_after_scan(self,after="PRIOR POS",**kwargs): - """ - sets the positioner after scan - after = "PRIOR POS" - "STAY" - - """ - kwargs.setdefault('scan_dim',1) - scan_pv = self.ioc+"scan"+str(kwargs['scan_dim']) - caput(scan_pv+".PASM",after) - - def positioner_absolute_mode(self,absolute=True,**kwargs): - """ - absolute = True - = False => relative - - """ - kwargs.setdefault('scan_dim',1) - - scan_pv = self.ioc+"scan"+str(kwargs['scan_dim']) - if absolute: - ab_state = 0 - else: - ab_state = 1 - - caput(scan_pv+".P1AR",ab_state) # Absolute position - - def fillin(self,val_pv,rbv_pv,start,stop,steps_points,**kwargs): - """ - Fills in the scanRecord for the positionner - dim: scan dim - val_pv: drive pv - rbv_pv: readback pv - start: first point - stop: last point - step: step size (only used for positioner_num = 1, otherwise ignored) - kwargs: - num_points: False (default) => steps_points is the step size - True => steps_points is the number of points - positioner_num: default => 1 - positioner_settling_time: default => 0.1 - detector_settling_time: default => 0.1 - - Previously: Scan_FillIn - """ - kwargs.setdefault('scan_dim',1) - kwargs.setdefault("positioner_num",1) - kwargs.setdefault('detector_settling_time',default_detector_settling_time) - kwargs.setdefault('positioner_settling_time',default_positioner_settling_time) - kwargs.setdefault('debug',False) - - self.progress(kwargs['scan_dim']) - - scan_pv = self.ioc+"scan"+str(kwargs['scan_dim']) - posNum = kwargs['positioner_num'] - - if kwargs['debug']: - print('fillin: ',val_pv,rbv_pv,start,stop,steps_points) - - caput(scan_pv+".P"+str(posNum)+"PV",val_pv) - caput(scan_pv+".R"+str(posNum)+"PV",rbv_pv) - caput(scan_pv+".P"+str(posNum)+"SP",start*1.0) - caput(scan_pv+".P"+str(posNum)+"EP",stop*1.0) - - if posNum == 1: - if 'num_points' in kwargs: - if kwargs['num_points'] : - caput(scan_pv+".NPTS",steps_points) - else: - caput(scan_pv+".P1SI",steps_points*1.0) - - self.detector_settling_time(**kwargs) - self.positioner_settling_time(**kwargs) - - if 'trigger_dictionary' in kwargs: - self.trigger_dictionary = kwargs['trigger_dictionary'] - self.triggers_set(kwargs['scan_dim'],self.trigger_dictionary) - - #checking that PVs and positioner limits are good - self.check(kwargs['scan_dim']) - - - ### detectors and detector settling time - def detectors_clear(self,scan_dim,verbose=True): - """ - Clear all scan detectors - - Previously: Clear_Scan_Detectors - """ - scan_pv = self.ioc+"scan"+str(scan_dim) - for i in range(1,10): - caput(scan_pv+".D0"+str(i)+"PV","") - for i in range(10,71): - caput(scan_pv+".D"+str(i)+"PV","") - if verbose: - print("\nAll detectors cleared") - - def detectors_set(self,scan_dim,detector_dictionary): - """ - sets the detectors - detector_dictionary = {detNum:pv} - """ - scan_pv = self.ioc+"scan"+str(scan_dim) - for det_num in detector_dictionary.keys(): - det_pv=scan_pv+".D"+str(det_num).zfill(2)+"PV" - caput(det_pv,detector_dictionary[det_num]) - - def detector_settling_time(self,**kwargs): - """ - set the detector settling time - """ - kwargs.setdefault('detector_settling_time',self.default_detector_settling_time) - - scan_pv = self.ioc+"scan"+str(kwargs['scan_dim']) - - caput(scan_pv+".DDLY",kwargs['detector_settling_time']) - return scan_pv+".DDLY",kwargs['detector_settling_time'] - - ### triggers - def triggers_set(self,scan_dim,trigger_dictionary): - """ - Clear all scan detectors triggers - - trigger_dictionary = {trigger_num:pv} - """ - scan_pv = self.ioc+"scan"+str(scan_dim) - if len(trigger_dictionary.keys())>0: - for tigger_num in trigger_dictionary.keys(): - caput(scan_pv+".T"+str(tigger_num)+"PV",trigger_dictionary[tigger_num]) - - def triggers_get(self,scan_dim): - """ - returns a dictionary of the current scan striggers for scan_dim - """ - scan_pv = self.ioc+"scan"+str(scan_dim) - scan_trigger = {} - for tigger_num in range(1,5): - scan_trigger.update({tigger_num:caget(scan_pv+".T"+str(tigger_num)+"PV")}) - - - def triggers_clear(self,scan_dim,trigger_dictionary,verbose=True): - """ - Clear all scan detectors triggers - - Previously: Clear_Scan_Triggers - """ - scan_pv = self.ioc+"scan"+str(scan_dim) - inner_scan_trigger = self.ioc+"scan"+str(scan_dim-1)+".EXSC" - - if len(trigger_dictionary.keys())>0: - for dim in range(1,5): - if dim==1 and scan_dim>1: - caput(scan_pv+".T1PV",inner_scan_trigger) - else: - caput(scan_pv+'.T'+str(dim)+'PV',"") - - def triggers_reset(self,verbose=True,**kwargs): - """ - sets the trigger1 to be the lower dim execute, does not change the other triggers - does nothing if scan_dim = 1 - """ - kwargs.setdefault('scan_dim',1) - scan_pv = self.ioc+"scan"+str(kwargs['scan_dim']) - - inner_scan_trigger = self.ioc+"scan"+str(kwargs['scan_dim']-1)+".EXSC" - if kwargs['scan_dim'] > 1: - caput(scan_pv+".T1PV",inner_scan_trigger) #Resets the higher dimensional scans to trigger the inner scan - - if verbose: - print("Scan record "+self.ioc+"Trigger 1 is reset") - - - ### checks - def check(self,scan_dim): - """ - checks pvs connects and that positioners are within limits - - returns scan_ok = True/False - """ - pv_ok = self._check_pvs(scan_dim) - limits_ok = self._check_limits(scan_dim) - - scan_ok = bool(pv_ok * limits_ok) - return scan_ok - - def _check_pvs(self,scan_dim,verbose=False): - """ - Check if any of the detectors or positions pvs are not connected - - returns connected = True/False - - Previously: Scan_Check - """ - if verbose: - print('Checking if all detectors & positioners are connected...') - - scan_pv = self.ioc+"scan"+str(scan_dim) - - #Detectors - det_ok = True - for i in range(1,71): - det_num=(str(i).zfill(2)) - det_pv=caget(scan_pv+".D"+det_num+"PV") - if det_pv !='': - det=PV(det_pv); time.sleep(0.1)#smallest sleep to allow for PV traffic - if not det.connected: - print("Detector "+det_num+" has a bad PV: "+det.pvname+" not connected") - det_ok = False - - #Positioners - pos_ok = True - for i in range(1,5): - pos_num=str(i) - pos_pv=caget(scan_pv+".P"+pos_num+"PV") - if pos_pv != '': - pos=PV(pos_pv); time.sleep(0.1)#smallest sleep to allow for PV traffic - if not pos.connected: - print("Positioner "+pos_num+" has a BAD PV: "+pos.pvname+" not connected") - pos_ok = False - if verbose: - print('Connected') - - return bool(pos_ok * det_ok) - - def _check_limits(self,scan_dim,verbose=False): - """ - checks if the scan parameters are within the limits - returns limits_ok (True / False) - """ - scan_pv = self.ioc+"scan"+str(scan_dim) - caput(scan_pv+'.CMND',1) - time.sleep(.5) - SMSG = caget(scan_pv+'.SMSG',as_string=True) - if verbose: - print(SMSG) - - if SMSG != 'SCAN Values within limits': - print_warning_message('Positioner out of limits \n '+SMSG) - limits_ok = False - else: - limits_ok = True - - return limits_ok - - - ############################################################################################################## - ############################# table scans ############################## - ############################################################################################################## - def fillin_table(self,val_pv,rbv_pv,myarray,**kwargs): - """ - Fills in the scan record for table scans given positioner=posNum - myarray can be generated by myarray=Scan_MakeTable(StartStopStepLists) - - kwargs: - positioner_num: default => 1 - scan_dim: default =>1 - detector_settling_time: - positioner_settling_time - - Previously: Scan_FillIn_Table - """ - kwargs.setdefault("scan_dim",1) - kwargs.setdefault("positioner_num",1) - kwargs.setdefault('detector_settling_time',default_detector_settling_time) - kwargs.setdefault('positioner_settling_time',default_positioner_settling_time) - - scan_dim = kwargs['scan_dim'] - - self.progress(scan_dim) - - scan_pv = self.ioc+"scan"+str(scan_dim) - posNum = kwargs['positioner_num'] - - caput(scan_pv+".P"+str(posNum)+"SM","TABLE") - caput(scan_pv+".P"+str(posNum)+"PV",val_pv) #Drive - caput(scan_pv+".R"+str(posNum)+"PV",rbv_pv) #Read - caput(scan_pv+".P"+str(posNum)+"PA",myarray) - caput(scan_pv+'.NPTS',len(myarray)) - - self.detector_settling_time(**kwargs) - self.positioner_settling_time(**kwargs) - - #checking that PVs and positioner limits are good - self.check(scan_dim) - - def table_reset_after(self,**kwargs): - """ - resets positioner settling time 0.1 - sets all positionitonser to linear - clears positioners - - Previously: Scan_Reset_AfterTable - """ - kwargs.setdefault('scan_dim',1) - #Setting everything back - scan_pv = self.ioc+"scan"+str(kwargs['scan_dim']) - - self.detector_settling_time(**kwargs) - - for i in range(1,5): - caput(scan_pv+".P"+str(i)+"SM","LINEAR") - - self.positioners_clear(**kwargs) - - ############################################################################################################## - ############################# progress, go and abort ############################## - ############################################################################################################## - def progress(self,scan_dim,verbose=True): - """ - Checks if a scan is in progress, and sleeps until it is done - - pv now includes the full 29idARPES: - Previously: Scan_Progress - """ - pv = self.ioc+"scan"+str(scan_dim) - check=caget(pv+".FAZE") - while (check!=0): - if verbose: - print(pv+" in progress - please wait...") - time.sleep(30) - check=caget(pv+".FAZE") - - def abort(self): - """ - aborts a scan for the command line - - Previously: Scan_Abort - """ - caput(self.ioc+"AbortScans.PROC",1) - - def go(self,verbose=True,**kwargs): - """ - checks limits and then starts a scan for a given ioc and scan_dim - - Previously: part of Scan_Go - """ - kwargs.setdefault('scan_dim',1) - kwargs.setdefault('snake',False) - scan_dim = kwargs['scan_dim'] - - self.progress(scan_dim) - - if verbose: - for i in range(1,scan_dim+1): - drive = caget(self.ioc+"scan"+str(i)+".P1PV") - start = caget(self.ioc+"scan"+str(i)+".P1SP") - stop = caget(self.ioc+"scan"+str(i)+".P1EP") - step = caget(self.ioc+"scan"+str(i)+".P1SI") - print('Scan'+str(i)+': '+drive+'= '+str(start)+' / '+str(stop)+' / '+str(step)) - try: - if iex.BL.xrays: - shutter_check(verbose=True) - except: - print_warning_message('no shutter check') - - try: - self.snake_set(kwargs['snake']) - except: - error = 'snake scanning not configured for this BL_config' - if verbose: - print(error) - - if self.check(scan_dim): - filename = self.prefix() - fileNum = self.fileNum() - print(filename+str(fileNum)+" started at ", dateandtime()) - scan_pv = self.ioc+"scan"+str(scan_dim) - caput(scan_pv+".EXSC",1,wait=True,timeout=900000) #pushes scan button - if self.log != None: - log_update(**kwargs) # writes the log file - print(filename+str(fileNum)+" finished at ", dateandtime()) - print('\n') - - - - ############################################################################################################## - ############################# empty and time scans ############################## - ############################################################################################################## - - - def empty_scan(self,npts=1,**kwargs): - """ - starts a scan with out a drive - npts = number of points - - **kwargs: - execute = True/False (default=True) - see scanRecord.fillin for more options - - Previously: Scan_Empty_Go - """ - kwargs.setdefault('execute',True) - kwargs.setdefault('num_points',True) - self.fillin("","",0,npts-1,npts,**kwargs) - time.sleep(.1) - - if kwargs['execute']: - self.go(**kwargs) - - def time_scan(self,duration_min,step_min=1,**kwargs): - """ - starts a scan with the readback as time in seconds - duration: total time for the scan in minutes - step_min: steps per minute (sets the detector setting time for this) - - **kwargs - execute True/False (default = True) - - trigger_dictionary = {1:'29idb:ca5:read'} - - - Previously: Scan_Time_Go - """ - kwargs.setdefault('execute',True) - - kwargs.update({'detector_settling_time':60.0/step_min}) - - stop = duration_min - #num_pnts = duration_min * step_min - dwell = 60/step_min - self.fillin("","time",dwell/60,stop,dwell/60,**kwargs) - - print("Time scan - Settling time : "+str(step_min)) - if kwargs['execute']: - self.go(**kwargs) - - ############################################################################################################## - ############################# 2D scans typewriter/snake scans ############################## - ############################################################################################################## - def fillin_2D(self,inner_loop_list,outer_loop_list,**kwargs): - """ - Fills in a the Scan Record for a 2D scan (Mesh), - InnerMotorList=[val_pv1,rbv_pv1,start1,stop1,step1] #scanDIM=1 - OuterMotorList=[val_pv2,rbv_pv2,start2,stop2,step2] #scanDIM=2 - kwargs: - num_points: False (default) => steps_points is the step size - True => steps_points is the number of points - positioner_num: default => 1 - detector_settling_time: default => 0.1 - snake: coming soon - """ - kwargs.setdefault("snake",False) - kwargs.setdefault("outer_scan_dim",2) - - outer_scan_dim = kwargs['outer_scan_dim'] - - #fillin inner loop - kwargs.update({'scan_dim':outer_scan_dim-1}) - self.fillin(inner_loop_list[0],inner_loop_list[1],inner_loop_list[2],inner_loop_list[3],inner_loop_list[4],**kwargs) - #fillin outer loop - kwargs.update({'scan_dim':outer_scan_dim}) - self.fillin(outer_loop_list[0],outer_loop_list[1],outer_loop_list[2],outer_loop_list[3],outer_loop_list[4],**kwargs) - - - - def snake_pv(self,snake_dim,enable=True): - """ - used for snake scans (as opposed to typewriter scans) - """ - snake_proc = self.snake_scan_userCalcOut(self.ioc,snake_dim=snake_dim,calc_num=1,enable=enable) - return snake_proc - - - def snake_scan_userCalcOut(self,snake_dim=1,calc_num=1,enable=False): - """ - for snake scans you need to add this userCalcOut to the after scan - it multiplies the step of the inner scan by -1 - - return the userCalcOut.PROC pv - """ - snake_calc_pv = self.ioc+"userCalcOut"+str(calc_num) #Snake userCalc - caput(self.ioc+"userCalcOutEnable.VAL",1) #global enable for userCalcs - - step_pv = self.ioc+"scan"+str(snake_dim)+".P1SI" - ### Setting up the user - caput(snake_calc_pv+".DESC","Snake Calc") - caput(snake_calc_pv+".INPA",step_pv+" NPP NMS") - caput(snake_calc_pv+".CALC$","A*-1*B") - caput(snake_calc_pv+".OUT",step_pv+" PP NMS") - - if enable: - caput(snake_calc_pv+".B",1) - else: - caput(snake_calc_pv+".B",0) - - return snake_calc_pv+".PROC" \ No newline at end of file diff --git a/build/lib/iexcode/instruments/shutters.py b/build/lib/iexcode/instruments/shutters.py deleted file mode 100644 index 01e5a9de1723f63d4200d2e1618d5a832c35f8dd..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/shutters.py +++ /dev/null @@ -1,128 +0,0 @@ -""" -main shutter and branch shutter functions -""" -from time import sleep -from epics import caget, caput - -import iexcode.instruments.cfg as iex -from iexcode.instruments.utilities import dateandtime - - -def shutter_check(verbose=True): - """ - Checks main shutter is open, if not opens it" - Checks brancg shutter is open, if not opens it" - - Previously: Check_MainShutter - """ - while True: - shutter_open = main_shutter_status() - if shutter_open == False: - print("MAIN SHUTTER CLOSED !!!" , dateandtime()) - main_shutter_open() - sleep(10) - else: - if verbose: - print("Shutter is now open" , dateandtime()) - break - shutter_open = branch_shutter_status() - - if shutter_open == False: - branch_shutter_open() - -############################################################################################################## -################################ main shutter ############################## -############################################################################################################## - -def main_shutter_open(verbose=True): - """ - opens the main shutter - - Previously: Open_MainShutter - """ - caput("PC:29ID:FES_OPEN_REQUEST.VAL",1, wait=True,timeout=180000) - if verbose: - print("Opening Main Shutter...") - -def main_shutter_close(verbose=True): - """ - closes the main shutter - - Previously: Close_MainShutter - """ - caput("PC:29ID:FES_CLOSE_REQUEST.VAL",1,wait=True,timeout=18000) - if verbose: - print("Closing Main Shutter...") - -def main_shutter_status(): - """ - checks on the status of the main shutter - and returns shutter_open = True / False - - """ - SS1=caget("EPS:29:ID:SS1:POSITION") - SS2=caget("EPS:29:ID:SS2:POSITION") - PS2=caget("EPS:29:ID:PS2:POSITION") - check=SS1*SS2*PS2 - - if check == 8: - shutter_open = True - else: - shutter_open = False - - return shutter_open - - -############################################################################################################## -################################ branch shutters ############################## -############################################################################################################## - -def branch_shutter_status(branch=None,verbose=False): - """ - checks on the status of the main shutter - and returns shutter_open = True / False - """ - if branch == None: - branch = iex.BL.branch - pvA = "PA:29ID:S"+branch.upper()+"S_BLOCKING_BEAM.VAL" - pvB = "PB:29ID:S"+branch.upper()+"S_BLOCKING_BEAM.VAL" - #"ON" = 1 => shutter blocking - status=caget(pvA)+caget(pvB) - if status == 0: - shutter_open=True - else: - shutter_open=False - - if verbose: - status = 'Open' if shutter_open else 'Closed' - print(branch+"-shutter is "+status) - return shutter_open - -def branch_shutter_close(branch=None,verbose=False): - """ - closes current branch shutter - - Previously: Close_BranchShutter - """ - if branch == None: - branch = iex.BL.branch - caput("PC:29ID:S"+branch.upper()+"S_CLOSE_REQUEST.VAL",1,wait=True,timeout=18000) - print("Closing "+branch.upper()+"-Shutter...") - - -def branch_shutter_open(branch=None,verbose=False): - """ - Opens current branch shutter - - Previoulsy: Open_BranchShutter - - """ - if branch == None: - branch = iex.BL.branch - shutter_status = branch_shutter_status() - if shutter_status: - print(branch+"-Shutter already open...") - else: - caput("PC:29ID:S"+branch.upper()+"S_OPEN_REQUEST.VAL",1,wait=True,timeout=18000) - print("Opening "+branch.upper()+"-Shutter...") - diff --git a/build/lib/iexcode/instruments/slits.py b/build/lib/iexcode/instruments/slits.py deleted file mode 100644 index 1b8da8715131f6cc714346eff7d888302865bdaf..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/slits.py +++ /dev/null @@ -1,506 +0,0 @@ -from numpy import inf,nan - -from epics import caget, caput - -import iexcode.instruments.cfg as iex -from iexcode.instruments.shutters import main_shutter_close -from iexcode.instruments.utilities import print_warning_message -from iexcode.instruments.encoders import encoders_reset_zero, _encoder_dictionary,encoder_sync - - -slit_ioc="29idb:" - -def _slits_dictionary(): - """ - dictionary of slit pv names for two and four blade slit assemblies - key = slit_name - val - slitHV - """ - #'slit3C' : (None, "uses a flexure stage so is different"), - - d = { - 'slit1A' : ('29idb:Slit1H','29idb:Slit1V'), - 'slit2B' : ('29idb:Slit2H','29idb:Slit2V'), - 'slit3C' : ('29idb:Slit3C',), - 'slit3D' : ('29idd:Slit4V',), - } - return d - -def slit_name_list(): - d=_slits_dictionary() - message = "slit_list = " - for i, key in enumerate(d.keys()): - if i==0: - message += key - else: - message = message+", "+key - print(message) - -def _slits_wide_open_dictionary(): - """ - wide open size for the slits - These are not the epics limits, but the physical extent of the beam - """ - d = { - 'slit1A' : (4.5,4.5), - 'slit2B' : (6,8), - 'slit3C' : (300,), - 'slit3D' : (2000,), - } - return d - -def slits_pvs(slit_name): - """ - returns the rbv and drive for the size,center - (rbv_size,val_size),(rvb_center,val_center) - """ - - d = _slits_dictionary() - size = []#H,V - center = []#H,V - if slit_name in d.keys(): - if slit_name == 'slit3C': - size_val = d[slit_name][0]+'Fit.A' - size_rbv = d[slit_name][0]+'RBV' - center_val = None - center_rbv = None - size.append((size_rbv,size_val)) - center.append((center_rbv,center_val)) - else: - for slit_HV in d[slit_name]: - size_rbv = slit_HV +'size.VAL' - size_val = slit_HV +'t2.C' - center_rbv = slit_HV +'center.VAL' - center_val = slit_HV +'t2.D' - size.append((size_val,size_rbv)) - center.append((center_val,center_rbv)) - else: - print_warning_message('slit_name = '+slit_name+' not a valid slit') - slit_name_list() - return size,center - -def slits_synch(slit_name): - """ - synch the motor position and the slit table for all the beamline slits - """ - d = _slits_dictionary() - if slit_name in _encoder_dictionary().keys(): - encoder_sync(slit_name) - if slit_name in d.keys(): - if slit_name != 'slit3C': - for slit_HV in d[slit_name]: - slit_pv = slit_HV+'sync.PROC' - caput(slit_pv,1) - else: - print_warning_message('slit_name = '+slit_name+' not a valid slit') - slit_name_list() - -def slits_sync_all(): - """ - synch the motor position and the slit table for all the beamline slits - Slit-1A, slit-2B, slit-3C, slit-3D - - Previously: SyncAllSlits - """ - slit_list = _slits_dictionary() - for slit_name in slit_list.keys(): - slits_synch(slit_name) - - -def slits_get_all(verbose=True): - """ - returns a dictionary with the current slit status - """ - vals = {} - for slit_name in ['slit1A','slit2B','slit3C','slit3D']: - vals[slit_name+'_size'], vals[slit_name+'_center'] = slits_get(slit_name,verbose=verbose) - return vals - -def slits_set(slit_name,size,center,verbose=True,wait=True): - """ - synchs the slit motors and the slit table and then sets the center and size - - slit_name is key in slits_dictionary - size = (H_size, V_size) #inf in direction specified => all the way open - center = (H_center, V_center) - None=> use current value - - Previously: SetSlit - """ - d = _slits_dictionary() - - #syncing - slits_synch(slit_name) - - maxsize=_slits_wide_open_dictionary()[slit_name] - size=list(size) - center=list(center) - for i,s in enumerate(size): - if size[i] == inf: - size[i]=maxsize - #get pvnames - size_pvs,center_pvs = slits_pvs(slit_name) - size_rbv, size_val, = size_pvs[i] - center_rbv,center_val = center_pvs[i] - - #check if there is a pv - if center_rbv != None: - #check if specified value - if center[i] != None: - caput(center_val, center[i],wait=wait,timeout=180) - #check if there is a pv - if size_rbv != None: - #check if specified value - if size[i] != None: - caput(size_val, size[i],wait=wait,timeout=180) - - if verbose: - slits_get(slit_name,verbose=True) - - return tuple(size),tuple(center) - - -def slits_get(slit_name,verbose=True): - """ - returns the current H_size,V_size,H_center,V_center - - """ - d=_slits_dictionary() - size = [] - center = [] - - #syncing - slits_synch(slit_name) - - size_pvs,center_pvs = slits_pvs(slit_name) - for i in range(0,len(size_pvs)): - size_rbv, size_val, = size_pvs[i] - center_rbv,center_val = center_pvs[i] - if center_rbv != None: - center.append(caget(center_rbv)) - else: - center.append(0) - if size_rbv != None: - size.append(caget(size_rbv)) - - - - if verbose: - if len(d[slit_name])>1: - print(slit_name + " = ("+str(round(size[0],3))+" x "+str(round(size[1],3))+") @ ("+str(round(center[0],3))+","+str(round(center[1],3))+")") - else: - print(slit_name + " = ("+str(round(size[0],3))+") @ ("+str(round(center[0],3))+")") - - return tuple(size),tuple(center) - -def slits_set_size(slit_name,size): - """ - sets the slit size with the current slit center - - size = (H,V) for slit1A, slit2B - size = V for slit3D - """ - size_current,center = slits_get(slit_name,verbose=False) - slits_set(slit_name, size=size,center=center) - -def slits_set_center(slit_name,center): - """ - sets the slit size with the current slit center - - center = (H,V) for slit1A, slit2B - center = V for slit3D - """ - size,center_current = slits_get(slit_name,verbose=False) - slits_set(slit_name,size=size,center=center) - -def slits_scan_size(slit_name,direction,start,stop,step,**kwargs): - """ - slit_name = 'slit1A','slit2B','slit3D' - direction = 'H', 'V' - **kwargs - center: slits center, if not specified then uses current center position - """ - kwargs.setdefault('center',slits_get(slit_name,verbose=False)[1]) - kwargs.setdefault('execute',True) - - size,center = slits_pvs(slit_name) - if direction == 'H': - size_rbv,size_val = size[0] - center_rbv,center_val = center[0] - if direction == 'V': - size_rbv,size_val = size[1] - center_rbv,center_val = center[1] - - #set slit center - slits_set_center(slit_name,kwargs['center']) - #scan - iex.BL.mda.fillin(size_rbv,size_val,start,stop,step,**kwargs) - if kwargs['execute']: - iex.BL.mda.go(**kwargs) - -def slits_scan_center(slit_name,direction,start,stop,step,**kwargs): - """ - slit_name = 'slit1A','slit2B','slit3D' - direction = 'H', 'V' - **kwargs - size: slits size, if not specified then uses current size - - Previously: Scan_NarrowSlit_Go - """ - kwargs.setdefault('size',slits_get(slit_name,verbose=False)[0]) - kwargs.setdefault('execute',True) - - size,center = slits_pvs(slit_name) - if direction == 'H': - size_rbv,size_val = size[0] - center_rbv,center_val = center[0] - if direction == 'V': - size_rbv,size_val = size[1] - center_rbv,center_val = center[1] - - #set slit center - slits_set_size(slit_name,kwargs['size']) - #scan - iex.BL.mda.fillin(center_rbv,center_val,start,stop,step,**kwargs) - if kwargs['execute']: - iex.BL.mda.go(**kwargs) - - -def slit1A_scribe_marks(): - """ - moves slit1A to the position which corresponds to the scribe marks - used to check if we have lost steps - - Dial values should be 0 on when on the scribe marks - User values are set to correspond to the center of the beam - - Previously: GoToSlit1AScribe - """ - main_shutter_close() - for m in range(9,13): - caput('29idb:m'+str(m)+'.DVAL',0,wait=True) - - print('At slit1A scribe marks') - -def slit1A_set(H_size,V_size,verbose=True,**kwargs): - """ - sets the first aperture / slit to the specificed size - if Hsize / Vsize = inf then goes to maximim 4.5 / 4.5 - **kwargs - center = slit center, by default => (0,0) - - Previously: SetSlit1A - """ - kwargs.setdefault('center',(None,None)) - slit_name = 'slit1A' - - size = (H_size,V_size) - center = kwargs['center'] - slits_set(slit_name,size,center, verbose=verbose) - -def slit1A_get(verbose=True): - """ - returns the current (H_size,V_size),(H_center,V_center) - """ - slit_name = 'slit1A' - return slits_get(slit_name,verbose=verbose) - -def slit2B_set(H_size,V_size,verbose=True,**kwargs): - """ - sets the clean up aperture / slit downstream of the mono to the specificed size - if Hsize / Vsize = inf then goes to maximim 6 / 8 - - **kwargs - center = slit center, by default => (0,0) - - Previously: SetSlit2B - """ - kwargs.setdefault('center',(None,None)) - slit_name = "slit2B" - - size = (H_size,V_size) - center = kwargs['center'] - slits_set(slit_name,size,center,verbose=verbose) - -def slit2B_get(verbose=True): - """ - returns the current (H_size,V_size),(H_center,V_center) - """ - slit_name = "slit2B" - return slits_get(slit_name,verbose=verbose) - -def slit2B_encoders_reset(Hcenter,Vcenter): - """ - Resetting Slit 2B encoders to 0 for a given position (Hcenter,Vcenter). - Slit size need to be set to 0. - - Previously: Reset_Slit2B_Encoders - """ - slit_name = 'slit2B' - slits_set(slit_name,(0,0),(Hcenter,Vcenter), verbose=True) - encoders_reset_zero(slit_name) - slits_synch(slit_name) - - -def slit3C_set(size,verbose=True): - """ - sets slit-3C (ARPES resolution defining slit) - - Previously SetSlit3C - """ - slit_name = 'slit3C' - center = (None,) - slits_set(slit_name,(size,),center, verbose=verbose) - -def slit3C_get(verbose=True): - """ - gets slit-3C (ARPES resolution defining slit) - returns size, position - """ - slit_name = "slit3C" - return slits_get(slit_name,verbose=verbose) - -def slit3D_set(V_size,center=None,verbose=True): - """ - set the exit slit for the D-branch - - Previously: SetSlit3D - """ - slit_name = "slit3D" - - if V_size in [inf,nan,None]: - V_size=2000 - - size = (V_size) - if center == None: - center = slit3D_get()[1] - else: - center = (center,) - - slits_set(slit_name,size,center,verbose=False) - - - if center == None: - size,center = slit3D_get() - print("Slit-3D = "+str(size)+"um") - else: - print("Slit-3D = "+str(size)+'@ '+str(center)+"um") - - -def slit3D_get(verbose=True): - """ - returns the current V_size,V_center - """ - slit_name = "slit3D" - (V_size),(V_center) = slits_get(slit_name,verbose) - V_size = round(V_size[0],3) - V_center = round(V_center[0],3) - - return V_size,V_center - -def slit3D_encoders_reset(Vcenter): - """ - Resetting Slit 2B encoders to 0 for a given position (Hcenter,Vcenter). - Slit size need to be set to 0. - - Previously: Reset_Slit2B_Encoders - """ - - slit_name = 'slit3D' - slits_set(slit_name,(0),(Vcenter), verbose=True) - encoders_reset_zero(slit_name) - slits_synch(slit_name) - -def exit_slit_set(branch, size, verbose=True): - """ - sets the size for the iex.BL.branch exit slit - - Previously: SetExitSlit - """ - if branch == "c": - slit3C_set(size, verbose) - elif branch == "d": - slit3D_set(size, verbose) - -def exit_slit_get(branch, verbose=True): - """ - gets the size for the iex.BL.branch exit slit - """ - if branch == "c": - slit_size,slit_center = slit3C_get(verbose=False) - elif branch == "d": - slit_size,slit_center = slit3D_get(verbose=False) - - return slit_size,slit_center - - -############################################################################################################## -################################ slit fits ############################## -############################################################################################################## - - - -def slit_coef(slit_num): - """ - 3rd order polynomials coeffients for closing slit1A / slit2B to minimize heat bump effects - slit_num = 1 / 2 for slit1A / slit2B - """ - if slit_num == 1: - pv='29id:k_slit1A' - #Redshifted x (H): - H0=2.3325 - H1=-.000936 - H2=2.4e-7 - #Redshifted z (V): - V0=2.3935 - V1=-.0013442 - V2=3.18e-7 - if slit_num == 2: - pv='29id:k_slit2B' - #Redshifted x (H): - H0=3.61 - H1=-0.00186 - H2=5.2e-7 - #Redshifted z (V): - V0=6.8075 - V1=-0.003929 - V2=9.5e-7 - K=H0,H1,H2,V0,V1,V2 - return pv,K - - -def slit_3C_fit_calc_position(size): - """ - used to convert slit size to motor position for slit 3C - flexure stage - empirically determine offline with a camera, coeffients used by epics - - Previously: Slit3C_Fit - """ - K0=-36.383 - K1=0.16473 - K2=-0.00070276 - K3=8.4346e-06 - K4=-5.6215e-08 - K5=1.8223e-10 - K6=-2.2635e-13 - motor=K0+K1*size+K2*size**2+K3*size**3+K4*size**4+K5*size**5+K6*size**6 - return motor - -def slit_3C_fit_calc_size(position): - """ - used to convert slit size to motor position for slit 3C - flexure stage - empirically determine offline with a camera, coeffients used by epics - - Previously: Slit3C_RBV - """ - K0=299.66 - K1=16.404 - K2=1.5572 - K3=0.14102 - K4=0.0064767 - K5=0.00014501 - K6=1.2617e-06 - size=round(K0+K1*position+K2*position**2+K3*position**3+K4*position**4+K5*position**5+K6*position**6,0) - return size - - diff --git a/build/lib/iexcode/instruments/spec_stuff.py b/build/lib/iexcode/instruments/spec_stuff.py deleted file mode 100644 index 61cc85925755a39d9b1fa2395e72d18b22c30cf8..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/spec_stuff.py +++ /dev/null @@ -1,14 +0,0 @@ - -def folders_spec(run,folder,UserName): - if folder == "b": - UserName = "Staff" - else: - UserName = UserName+"/" - MyPath="/home/beams22/29IDUSER/spec/data/"+run+"/"+UserName - print("\nSPEC folder: " + MyPath) - print("You will need to create folder and set up the path manually in SPEC:") - print(" cd "+MyPath) - print(" newfile FileName") - print("To start SPEC fresh: ./bin/kappa29ID -f") - #if not (exists(MyPath)): - # mkdir(MyPath) diff --git a/build/lib/iexcode/instruments/staff.py b/build/lib/iexcode/instruments/staff.py deleted file mode 100644 index dfca99fdd25c07ea7fd5e109bd40413c88014bac..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/staff.py +++ /dev/null @@ -1,49 +0,0 @@ -import iexcode.instruments.cfg as iex - -############################################################################################################## -############################## staff detectors ############################## -############################################################################################################## - - -def staff_detector_dictionary(): - """ - returns a dictionary of the default detectors - - Previously: Detector_Default - """ - det_dict={} - diodes={ - 15:"29idb:ca15:read" - } - slits_apertures={ - 58:"29idb:Slit1Ht2.C", - 59:"29idb:Slit1Ht2.D", - 60:"29idb:Slit1Vt2.C", - 61:"29idb:Slit1Vt2.D", - 62:"29idb:Slit2Ht2.C", - 63:"29idb:Slit2Ht2.D", - 64:"29idb:Slit2Vt2.C", - 65:"29idb:Slit2Vt2.D", - 66:"29idb:Slit3CRBV", - 67:"29idb:Slit4Vt2.C" - } - vacuum_shutters={ - 61:"29idb:VS1A.VAL", - 62:"29idb:VS2A.VAL", - 63:"29idb:VS3AB.VAL", - 64:"29idb:VS4B.VAL", - 65:"29idb:IP4B.VAL", - 66:"PA:29ID:SCS_BLOCKING_BEAM.VAL", - 67:"PA:29ID:SDS_BLOCKING_BEAM.VAL" - } - mono_details={ - 68:"29idmono:ENERGY_SP", - 69:"29idmonoMIR:P.RBV", - 70:"29idmonoGRT:P.RBV" - } - det_dict.update(diodes) - det_dict.update(slits_apertures) - det_dict.update(mono_details) - return det_dict - - diff --git a/build/lib/iexcode/instruments/storage_ring.py b/build/lib/iexcode/instruments/storage_ring.py deleted file mode 100644 index de3e7fb1e1099d1cdd978e43db6db4456042f1e5..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/storage_ring.py +++ /dev/null @@ -1,23 +0,0 @@ - - -""" -Functions dealing with the storage ring pvs - -""" -from epics import caget -from time import sleep - -from iexcode.instruments.utilities import dateandtime - -def wait_for_beam(ring_current=80): - """ - Monitors the storage ring current and breaks when the ring current is above 60 mA - Checks the status every 30 seconds - """ - while True: - SR=caget("S:SRcurrentAI.VAL") - if (SR<ring_current): - sleep(30) - else: - print("Beam is back -"+dateandtime()) - break \ No newline at end of file diff --git a/build/lib/iexcode/instruments/userCalcs.py b/build/lib/iexcode/instruments/userCalcs.py deleted file mode 100644 index de49f369eae6c80a7ced00c059780061b49a6fca..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/userCalcs.py +++ /dev/null @@ -1,210 +0,0 @@ -from epics import caget, caput -############################################################################################################## -########################### String Sequences ###################### -############################################################################################################## -def userStringSeq_pvs(ioc, seq_num): - """ - returns the proc pv for a given userStringSeq - userStringSeq, proc_pv - - Previously: BeforeScan_StrSeq, AfterScan_StrSeq - """ - userStringSeq_pv = ioc+"userStringSeq"+str(seq_num) - userStringSeq_proc = userStringSeq_pv+".PROC" - return userStringSeq_pv, userStringSeq_proc - - -def userStringSeq_clear(ioc,seq_num): - """ - clears the nth suserStringSeq in the specified ioc - - Previously: ClearStringSeq - """ - pv=ioc+"userStringSeq"+str(seq_num) - caput(pv+".DESC","") - for i in range(1,10): - caput(pv+".STR"+str(i),"") - caput(pv+".LNK"+str(i),"") - caput(pv+".DOL"+str(i),"") - caput(pv+".DO"+str(i),0.0) - caput(pv+".DLY"+str(i),0.0) - caput(pv+".WAIT"+str(i),"NoWait") - caput(pv+".STRA","") - caput(pv+".LNKA","") - caput(pv+".DOLA","") - caput(pv+".DOA",0.0) - caput(pv+".DLYA",0.0) - caput(pv+".WAITA","NoWait") - caput(pv+".FLNK","") - return pv - -############################################################################################################## -########################### userCalcs ###################### -############################################################################################################## -def userCalcs_pvs(ioc, seq_num): - """ - returns the proc pv for a given userStringSeq - userStringSeq, proc_pv - - Previously: BeforeScan_StrSeq, AfterScan_StrSeq - """ - userCalc_pv = ioc+"userCalc"+str(seq_num) - userCalc_proc = userCalc_pv+".PROC" - return userCalc_pv, userCalc_proc - -def userCalc_clear(ioc,calcOut_num): - """ - clears the nth userCalc in the specified ioc - - Previously:ClearCalc - """ - pv=ioc+"userCalc"+str(calcOut_num) - caput(pv+".DESC","") - - for i in ["A","B","C","D","E","F","G","H","I","J","K","L"]: - caput(pv+'.IN'+i+'P',"Yes") - caput(pv+'.IN'+i+'N',"") - caput(pv+"."+i,0) - - caput(pv+".CALC$","") - caput(pv+".DOLN","") - caput(pv+".OUTN","") - caput(pv+".OOPT","Every Time") - return pv -############################################################################################################## -########################### userCalcsOut ###################### -############################################################################################################## - -def userCalcOut_clear(ioc,calcOut_num): - """ - clears the nth userCalcOut in the specified ioc - - Previously:ClearCalcOut - """ - pv=ioc+"userCalcOut"+str(calcOut_num) - caput(pv+".DESC","") - - for i in ["A","B","C","D","E","F","G","H","I","J","K","L"]: - caput(pv+".INP"+i,"") - caput(pv+"."+i,0) - - caput(pv+".CALC$","A") - caput(pv+".OCAL$","A") - caput(pv+".OUT","") - caput(pv+".OOPT","On Change") - return pv - -############################################################################################################## -########################### User Average User Average ###################### -############################################################################################################## -def userAvg_clear(ioc,userAvg_num): - """ - clears the nth userAvg in the specified ioc - - Previously: ClearUserAvg - """ - pv = ioc+"userAve"+str(userAvg_num) - caput(pv+".DESC","") - caput(pv+".INPB","") - return pv - -def userAvg_pvs(ioc, userAve_num): - """ - returns the proc pv for a given userStringSeq - userStringSeq, proc_pv - - """ - userAve_pv = ioc+"userAve"+str(userAve_num) - userAve_proc = userAve_pv+".PROC" - return userAve_pv, userAve_proc - - -def userAvg_trigger_strSeq(ioc,num,userAvg_num=8): - """ - num = number of userAvg - """ - userAvg_num = 8 - userAvg_clear(ioc,userAvg_num) - str_pv="29id"+ioc+":userStringSeq"+str(userAvg_num) - caput(str_pv+".DESC","Average Triggers_"+ioc) - if num < 10: - str_num = str(num) - else: - str_num = "A" - for userAve_num in range(1,userAve_num+1,1): - if userAve_num < 10: - userAve_num = str(userAve_num) - else: - userAve_num = "A" - userAve_pv, userAve_proc = userAvg_pvs(ioc, userAve_num) - caput(str_pv+".LNK"+userAve_num,userAve_proc+" CA NMS") - caput(str_pv+".WAIT"+userAve_num,"After"+str_num) - - -def UserAvg_setup(ioc,userAvg_num,det_num,average_pts,UserAvg_trigger_strSeq_pv,scan_dim=1): - """ - kappa - userAv_num 1->10 - det_num 61 -> 70 - Previously:UserAvg - """ - userAvg_pv = ioc+"userAve"+str(userAvg_num) - scan_pv = ioc+"scan"+str(scan_dim) - det_pv = scan_pv+".D"+str(det_num)+"PV" - - trigger_strSeq_pv,trigger_strSeq_proc = userAvg_trigger_strSeq(ioc) - - if average_pts > 0: - caput(scan_pv+".T2PV",trigger_strSeq_proc) #set all Avg as Det - caput(userAvg_pv+".A",average_pts) - caput(det_pv,userAvg_pv+".VAL") - print("User Average enabled") - elif average_pts == 0: - caput(scan_pv+".T2PV","") - caput(det_pv,"") - print("User Average disabled") - - -def userAvg_setup(ioc,pv,userAvg_num,name,average_pts=10,mode="ONE-SHOT"): - """ - - Previously: UserAvg_PV - """ - trigger_strSeq_pv,trigger_strSeq_proc = userAvg_trigger_strSeq(ioc) - - # Fill User Average: - userAvg_clear(ioc,userAvg_num) - userAve_pv, userAve_proc = userAvg_pvs(ioc, userAvg_num) - - caput(userAve_pv+".SCAN","Passive") - caput(userAve_pv+".INPB",trigger_strSeq_pv+" CP NMS") - caput(userAve_pv+".A",average_pts) - caput(userAve_pv+".PREC",9) - caput(userAve_pv+"_mode.VAL",mode) - caput(userAve_pv+"_algorithm.VAL","AVERAGE") - caput(userAve_pv+".DESC",name) - - -def userAvg_trigger_strSeq(ioc,num, seq_num=8): - """ - - Previously: UserAvg_Trigger_StrSeq - """ - userStringSeq_clear(ioc,seq_num) - trigger_strSeq_pv,trigger_strSeq_proc = userStringSeq_pvs(ioc, seq_num) - caput(trigger_strSeq_pv+".DESC",ioc+" Average Triggers") - - if num < 10: - str_num=str(num) - else: - str_num="A" - for i in range(1,num+1,1): - if i < 10: - i=str(i) - else: - i="A" - avg_pv="29id"+ioc+":userAve"+i - caput(trigger_strSeq_pv+".LNK"+i,avg_pv+"_acquire.PROC CA NMS") - caput(trigger_strSeq_pv+".WAIT"+i,"After"+str_num) - - return trigger_strSeq_pv,trigger_strSeq_proc \ No newline at end of file diff --git a/build/lib/iexcode/instruments/utilities.py b/build/lib/iexcode/instruments/utilities.py deleted file mode 100644 index da2072668d9717e178117a4166d98865f473a5ba..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/utilities.py +++ /dev/null @@ -1,238 +0,0 @@ -""" -useful functions - -""" -import time -import datetime -import select -import sys -import ast -import os -import numpy as np - -from epics import caget, caput - -def dateandtime(): - return time.strftime("%a %d %b %Y %H:%M:%S",time.localtime()) - -def today(which='default'): - dt=datetime.date.today() - today_year = dt.year - today_month = dt.month - today_day = dt.day - if which == 'slash': - today_str=("{:02d}/{:02d}/{:04d}".format(today_month,today_day,today_year)) - elif which == 'int': - today_str=int(("{:04d}{:02d}{:02d}".format(today_year,today_month,today_day))) - else: # 'default': - today_str=("{:04d}{:02d}{:02d}".format(today_year,today_month,today_day)) - return today_str - - -def print_warning_message(message_string): - print('\n==================================') - print("WARNING: " +message_string+ " !!!!! ") - print('==================================\n') - - -def wait_for_it(D,H,M): - """ - D = how many days from now - H,M = what time that day in 24h clock - - e.g.: if today is Wed Nov 21 at 14:00 - WaitForIt(2,9,0) => Fri Nov 23 at 9:00 - """ - t = datetime.datetime.now()() - day = datetime.timedelta(days=D) - future = t + day - returnTime = datetime.datetime(future.year, future.month, future.day, int(H), int(M)) - timeToWait = returnTime - t - s=round(timeToWait.total_seconds(),1) - m=round(timeToWait.total_seconds()/60.0,1) - h=round(timeToWait.total_seconds()/3600.0,1) - print("Now is: "+str(t)) - print("Target date: "+str(returnTime)) - print("Sleeping for "+str(s)+" s = "+str(m)+" m = "+str(h)+" h") - print("Waaaaaaaait for it...") - time.sleep(timeToWait.total_seconds()) - print(dateandtime()) - - -def input_timeout(question,t): - print("You have "+str(t)+" seconds to answer!") - i, o, e = select.select( [sys.stdin], [], [], t ) - if (i): - print("You said", sys.stdin.readline().strip()) - else: - print("You said nothing!") - -def playsound(sound='FF'): - """ - plays a sound when run - 'FF' Final Fantasy victory sound - 'ding' a subtle ding noise - 'hallelujah' hallelujah chorus - """ - if sound == 'FF': - sounds = '/home/beams/29IDUSER/Documents/User_Macros/Macros_29id/Sound_Files/VictoryFF.wav' - elif sound == 'ding': - sounds = '/home/beams/29IDUSER/Documents/User_Macros/Macros_29id/Sound_Files/ding.wav' - elif sound == 'hallelujah': - sounds = '/home/beams/29IDUSER/Documents/User_Macros/Macros_29id/Sound_Files/hallelujah.wav' - os.system('aplay ' + sounds) - -def range_up(start,end,step): - while start <= end: - yield start - start += abs(step) - -def range_down(start,end,step): - while start >= end: - yield start - start -= abs(step) - -def EgForLoop(): - for hv in range_down(2000,500,-500): - print(hv) - for hv in range_up(500,2000,500): - print(hv) - -def take_closest_value(my_list,my_number): - """ - Given a list of integers, I want to find which number is the closest to a number x. - - Previously: TakeClosest - """ - return min(my_list, key=lambda x:abs(x-my_number)) - -def read_dict(filename,**kwargs): - """ - filename = name with extension of dictionary to read - **kwargs: - path = path to folder containing dictionary file (default: .IEX_dictionaries) - """ - if 'path' in kwargs: - path = kwargs['path'] - else: - path = os.path.join(os.path.dirname(os.path.dirname(__file__)),'IEX_dictionaries') - fpath = os.path.join(path,filename) - with open(fpath) as f: - for c,line in enumerate(f.readlines()): - if line[0] == '=': - lastdate=line[8:16] - lastline=line - mydict=ast.literal_eval(lastline) - return mydict - - -def make_table(start_stop_step_lists): - """ - Creates and returns a np.array with values based on StartStopStepList - StartStopStepList is a list of lists defining regions for a table array - StartStopStepList[[start1,stop1,step1],[start1,stop1,step1],...] - Automatically removes duplicates and sorts into ascending order - if you want descending - myarray=XAS_Table(StartStopStepLists)[::-1] - - Previously: Scan_MakeTable - """ - table_array=np.array([]) - if type(start_stop_step_lists[0]) is not list: - start = start_stop_step_lists[0] - stop = start_stop_step_lists[1] - step = start_stop_step_lists[2] - j = start - while j<=stop: - table_array=np.append(table_array, j) - j+=step - else: - for i in range(0,len(start_stop_step_lists)): - if type(start_stop_step_lists[i]) != list: - print_warning_message("start_stop_step_lists must be a list of list") - start=start_stop_step_lists[i][0] - stop=start_stop_step_lists[i][1] - step=start_stop_step_lists[i][2] - if stop <= start: - print_warning_message('start_stop_step_lists needs to be in assending order') - j=start - while j<=stop: - table_array=np.append(table_array, j) - j+=step - table_array=np.unique(table_array)#removing duplicate - table_array=np.sort(table_array) #sort into ascending order - return table_array - - - -def SendText(msg,which='user'): - """ - - which = 'user' or 'staff' - - Edit the following file with the correct email/phone number: - [sleepy /home/beams22/29ID/bin] pvMailSomething # for staff - [sleepy /home/beams22/29IDUSER/bin] pvMailUser # for user - - Use the following website to figure out carriers email: - https://20somethingfinance.com/how-to-send-text-messages-sms-via-email-for-free/ - - In a terminal, run the screen session: - pvMailUser (or pvMailSomething) - - To kill the screen session: - screen -ls #show list of screen session - screen -r screen# #reattached to a given screen session - screen -XS screen# kill #kill a given screen session - - - """ - if which == 'staff':n='6' - elif which == 'user':n='7' - caput('29idb:userCalcOut'+n+'.DESC',msg) - caput('29idb:userCalcOut'+n+'.A',0) - time.sleep(1) - caput('29idb:userCalcOut'+n+'.A',1) - print('Sending text/email') - - -def AbortScript(): - """ - Example: - while True: - try: - print 'do something' - sleep(5) - except KeyboardInterrupt: - if AbortScript() == 'y': - break - """ - try: - print('\n\nWARNING: Do you want to abort?') - print('Type y to ABORT, anything else to CONTINUE >') - foo = input() - return foo - except KeyboardInterrupt as e: - raise e - -def input_timeout(question,t): - print("You have "+str(t)+" seconds to answer!") - i, o, e = select.select( [sys.stdin], [], [], t ) - if (i): - print("You said", sys.stdin.readline().strip()) - else: - print("You said nothing!") - -def input_d(question): - """ - ask a question (e.g 'Are you sure you want to reset tth0 (y or n)? >') - return the answer - """ - try: - print(question) - foo = input() - return foo - except KeyboardInterrupt as e: - raise e - except: - return \ No newline at end of file diff --git a/build/lib/iexcode/instruments/xrays.py b/build/lib/iexcode/instruments/xrays.py deleted file mode 100644 index 5d57f2d078d82647a80cb9218ea7393dba9844a8..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/xrays.py +++ /dev/null @@ -1,564 +0,0 @@ -""" -functions related to using x-rays - -""" -import numpy as np -#import math -from time import sleep - -from epics import caget,caput - -import iexcode.instruments.cfg as iex -from iexcode.instruments.SRS_current_amplifiers import ca_average, ca_detector_list -from iexcode.instruments.diagnostics import * -from iexcode.instruments.FMB_mirrors import FMB_mirror_get -from iexcode.instruments.IEX_VPU import * -from iexcode.instruments.m3r import m3r_align,m3r_branch,m3r_switch_branch,m3r_position_dictionary -from iexcode.instruments.shutters import * -from iexcode.instruments.slits import * -from iexcode.instruments.utilities import print_warning_message,make_table -from iexcode.instruments.valves import * -from iexcode.instruments.VLS_PGM import * - -mpa = iex.mpa - -def safe_state(): - iex.BL.safe_state() - -############################################################################################################## -############################## resets and detector lists ############################## -############################################################################################################## -def _xrays_reset(verbose=True): - if verbose: - print("resetting the mono limits") - - mono_limits_reset() - - if verbose: - print("resetting beamline encoders") - - xray_motor_encoder_sync() - - -def _xrays_detector_list(): - """ - defualt detectors for the APRES endstation - used by: - CA_Live_StrSeq() - Detector_Triggers_StrSeq() - BeforeScan_StrSeq() => puts everybody in passive - CA_Average() - WARNING: can't have more than 5 otherwise CA_Live_StrSeq gets angry. - - Previously: part of Detector_List - """ - ca_list=[["b",4],["b",13]] - - return ca_list - - -def _xrays_detector_dictionary(): - """ - returns a dictionary of the default detectors - - Previously: Detector_Default - """ - det_dict={} - sr_main_shutter={ - 1:"S:SRcurrentAI.VAL", - 2:"EPS:29:ID:SS1:POSITION" - } - bl_energy={ - 3:"29idmono:ENERGY_MON", - 4:"ID29:EnergySet.VAL", - 5:"ID29:Energy.VAL" - } - bl_keithleys={ - 6:"29idb:ca1:read", - 7:"29idb:ca2:read", - 8:"29idb:ca3:read", - 9:"29idb:ca4:read", - 10:"29idb:ca5:read", - 11:"29idb:ca9:read", - 12:"29idb:ca12:read", - 13:"29idb:ca13:read" - } - det_dict.update(sr_main_shutter) - det_dict.update(bl_energy) - det_dict.update(bl_keithleys) - return det_dict - -############################################################################################################## -############################## get beamline info ############################## -############################################################################################################## - -def xrays_get_all(verbose=True): - """ - gets info about current beamline setting - returns a dictionary - - """ - vals={} - - if verbose: - print("-----------------------------------------------------------") - vals.update(ID_get_all(verbose=verbose)) - vals.update(mono_get_all(verbose=verbose)) - - if verbose: - print("-----------------------------------------------------------") - vals.update(slits_get_all(verbose=verbose)) - vals.update({"M0":FMB_mirror_get(0,verbose=verbose)}) - vals.update({"M1":FMB_mirror_get(1,verbose=verbose)}) - vals.update({"M3":FMB_mirror_get(3,verbose=verbose)}) - if verbose: - print("-----------------------------------------------------------") - - return vals - -def xrays_log_dictionary(**kwargs): - """ - Writes CSV file for the MDA scans with the following default parameters: - FilePath='/home/beams/29IDUSER/Documents/User_Folders/UserName/' - Filename is set by logname_set(FileName=None), default:YYYYMMDD_log.txt, where YYYYMMDD is when folders were set - (FileName=None,FileSuffix=None) is they are specified then it will use those values instead - - comment="Additional comments, last column" - - Previously: scanlog - """ - d={ - 'ID_mode':(ID_mode_get(verbose=False),"s"), - 'ID_QP_ratio':(ID_QP_ratio_get(verbose=False)[0],".0f"), - 'ID_sp':(ID_get_sp_eV(verbose=False),".2f"), - 'ID_rbv':(ID_get_rbv_eV(verbose=False),".2f"), - 'mono':(mono_energy_get(),".2f"), - 'grating':(mono_grating_get(),"s"), - 'slit_size':(slit_get(verbose=False)[0][0],".0f"), - } - - return d - -############################################################################################################## -############################## beamline encoders ############################## -############################################################################################################## - -def xray_motor_encoder_sync(): - ioc = "29idb:" - for motor in [13,14,15,16,26,27]: - pv = ioc+"m"+str(motor)+".SYNC" - caput(pv,1) - print("synch encoder: "+pv) - -############################################################################################################## -############################## energy : ID + mono ############################## -############################################################################################################## -def energy_get_all(verbose=True): - """ - returns ID_mode,ID_QP_ratio,ID_sp,ID_rbv,hv,grt - - """ - d = ID_get_all(verbose=False) - d.update(mono_get_all(verbose=False)) - keylist = ['ID_mode', 'ID_QP_ratio', 'ID_sp', 'ID_rbv','hv','grating'] - values = [] - for key in keylist: - values.append(d[key]) - if verbose: - print(key,d[key]) - - return tuple(values) - -def energy_get(): - """ - return the mono energy readback - """ - hv = mono_energy_get() - return hv - -def energy(hv_eV,slit_coeff=1,m3r=True,verbose=True): - """ - sets the ID for optimal flux based on calibration - sets the mono - sets the beamline aperture/slits - - slit_coeff < 1 is used to kill flux by closing the aperature after the mono (slit-2B) - - m3r => if True optimizes the mirror for the d-branch only - Previously: Set_BL, energy - """ - if hv_eV != _energy_range_check(hv_eV): - message_string = 'Requested photon energy '+str(hv_eV)+' not with the allowed range' - message_string = '\n closest allowed energy is '+str(_energy_range_check(hv_eV)) - print_warning_message(message_string) - - ID_energy_set_eV(hv_eV,verbose=verbose) - mono_energy_set(hv_eV,verbose=verbose) - apertures_set(c_2B=slit_coeff,c_1A=1,verbose=verbose) - - if m3r == True: - m3r_align() - -def _energy_range_min_max(): - """ - returns the min,max energies for the current grating/ID setting - """ - ID_min, ID_max = ID_energy_range_eV() - mono_min, mono_max = mono_energy_range() - hv_max = min(ID_max, mono_max) - hv_min = max(ID_min, mono_min) - return hv_min,hv_max - -def _energy_range_check(hv): - """ - checks if the energy is within the allowed range for both the mono - and the ID. If outside the ranges set it to the closest allowed value - - Previously: SetRange() - """ - hv_min,hv_max = _energy_range_min_max() - hv = min(hv_max,hv) - hv = max(hv_min,hv) - return hv - -def qp(QP_ratio): - """ - Used to set the QP (quasiperiodicity) of the ID for harmonic rejection - QP_ratio => - 100 fully periodic; max flux - 70 minimum allowed value, most quasiperiodic - - After changing QP, you will need to set - polarization - energy - """ - ID_QP_mode_set(QP_ratio) -############################################################################################################## -################################ beamline slits = apertures ############################## -############################################################################################################## -def aperture_fit(hv,slit_num): - """ - used close the beamline apertures/slits to only take the center of the beam, - i.e. no heat bump (determined emperically by looking at the the shift in energy vs slit position) - - Previously Aperture_Fit - """ - K=slit_coef(slit_num)[1] - sizeH=K[0]+K[1]*hv+K[2]*hv*hv - sizeV=K[3]+K[4]*hv+K[5]*hv*hv - return [round(sizeH,3),round(sizeV,3)] - -def apertures_set(c_2B=1,c_1A=1,verbose=True): - """ - Sets slit-1A and slit-2B for the current - grating and photon energy to remove the heat bump - - c_1A and c_2B are used to take a different ratio of the beam - (1 = normal ops, < 1 to reduce flux) - - Previously: SetSlit_BL - """ - hv_rbv = mono_energy_get() - grt = mono_grating_get() - - # slit were defined for the range: 500 - 2000 - hv = max(hv_rbv,500) - hv = min(hv_rbv,2000) - c = 4.2/2.2 # to account for the magnification difference between gratings - - if grt == 'MEG': - V=0.65 # set to 65% of RR calculation for both grt => cf 2016_2_summary - elif grt=='HEG': - V=0.65*c # set to 65% of RR calculation (no longer 80%) => cf 2016_2_summary - - try: - slit_position = read_dict('Dict_Slit.txt') - except KeyError: - print_warning_message("Unable to read dictionary") - return - - V2_center= slit_position[grt]['S2V'] - H2_center= slit_position[grt]['S2H'] - V1_center= slit_position[grt]['S1V'] - H1_center= slit_position[grt]['S1H'] - - Size1A=( aperture_fit(hv,1)[0]*c_1A, aperture_fit(hv,1)[1]*c_1A ) - Size2B=( aperture_fit(hv,2)[0]*c_2B, round(aperture_fit(hv,2)[1]*c_2B*V,3)) - - slit1A_set(Size1A[0],Size1A[1],center=(H1_center,V1_center),verbose=verbose) # standard operating - slit2B_set(Size2B[0],Size2B[1],center=(H2_center,V2_center),verbose=verbose) - - -def mvID(val): - """ - Sets the ID absolute set point (not optimized , mono & apertures stay fixed). - - to go to most flux use energy - """ - ID_set_eV(val) - -def mvID_calibrated(val): - """ - Sets the ID peak to val (calibrated). - - """ - ID_energy_set_eV(val) - - -def scan_ID(ID_sp_start,ID_sp_stop,ID_sp_step,**kwargs): - """ - scan the ID set point - """ - val_pv,rbv_pv = ID_scan_pvs() - iex.BL.mda.fillin(val_pv,rbv_pv,ID_sp_start,ID_sp_stop,ID_sp_step,**kwargs) - - -def mvmono(val): - """ - Sets the mono energy (insertion device & apertures stay fixed). - """ - mono_energy_set(val) - -def getE(): - """ - Returns current mono set point. - """ - return energy_get() - -def grating(grating_name): - """ - used to switch between gratings - grating = 'HEG' / 'MEG' - - check current grating - closes the main shutter - sets the mono energy - - Previously: Switch_Grating - """ - current_grt = mono_grating_get() - if grating != current_grt: - shutter_open = main_shutter_status() - main_shutter_close() - print("Switching grating, please wait...") - mono_grating_set(grating_name,verbose=False) - apertures_set() - - if shutter_open: - main_shutter_open() - - print(dateandtime()) - else: - print("grating: "+grating) - -def grating_get(): - """ - returns the current grating - """ - grating_name = mono_grating_get() - return grating_name - - -def polarization(ID_mode): - """ - Change beam polarization: ID_mode = 'H', 'V', 'RCP' or 'LCP' - """ - ID_switch_mode(ID_mode) - -def polarization_get(): - """ - gets the current polarization - """ - ID_mode_get() - -def scanmono(start,stop,step,average_pnts=1,**kwargs): - """ - scans the mono at the current ID value - - """ - ca_average(average_pnts) - - mono_scan(start,stop,step,**kwargs) - - - -def scanXAS(start_stop_step_lists,ID_eV=None,ID_tracking=False, **kwargs): - """ - scans the beamline energy: - ID_eV = None => the ID stays at the current value (default) - ID_eV = value => set the ID - ID_track = True => ID will follow with the mono (SLOW but required in ARPES) - - start_stop_step_lists is a list of lists for the different scan ranges - start_stop_step_lists = [[start1,stop1,step1], [start1,stop1,step1],...] - Note duplicates are removed and the resulting array is sorted in ascending order - - **kwargs: - scan_dim = 1 (default) - average_pnts: if using Keithlys this set the averaging; None for no averaging - m3r: if True the mirror is optimized before the start of the scan - mcp - execute: True/False to start the scan => True (default) - QP_ratio: if other than fully periodic - - Normalization: - - If in the D-branch the Mesh is put in but is not removed - - If in the C-branch we use the slit blades for normalization (ca13) - """ - kwargs.setdefault("scan_dim",1) - kwargs.setdefault("average_pnts",1) - kwargs.setdefault("m3r",True) - kwargs.setdefault("mcp",True) - kwargs.setdefault('execute',True) - - scan_dim=kwargs['scan_dim'] - - #Setting up the ScanRecord for Mono and ID in Table mode - mono_array,ID_array = BL_energy_tables(start_stop_step_lists,**kwargs) - #break is mono_array has no points - if len(list(mono_array)) == 0: - return - kwargs.update({'positioner_num':1}) - mono_scan_table(mono_array,execute=False) - if ID_tracking == True: - kwargs.update({'positioner_num':2}) - ID_scan_fillin_table(ID_array,**kwargs) - energy(ID_array[0],m3r=kwargs["m3r"]) - elif ID_eV != None: - #Setting the beamline energy - energy(ID_eV,m3r=kwargs["m3r"]) - - #Averaging and Normalization - ca_average(kwargs['average_pnts']) - if iex.BL.branch=="d": - mesh_d("In") - print_warning_message('MeshD is not automatically removed') - - #mpa - if iex.BL.endstation_name == "Kappa" and kwargs["mcp"]: - mpa.HV_on() - - #Scanning - if kwargs['execute']: - mono_energy_set(mono_array[0]) - iex.BL.mda.go(scan_dim) - - #Setting everything back - mono_scan_after() - iex.BL.mda.table_reset_after() - - if iex.BL.endstation_name == "Kappa": - if kwargs["mcp"]: - mpa.HV_off() - print("WARNING: Mesh"+iex.BL.branch+" is still In") - - -def BL_energy_tables(start_stop_step_lists,**kwargs): - """ - returns mono_array and ID_array for BL energy scans - *energies: - start,stop,step - ListofLists, e.g.{[400,420,1],[420,425,0.25]...} - **kwargs: - QP_ratio = 100; completely periodic, normal operations - Previously: Tables_BLenergy - """ - kwargs.setdefault('QP_ratio', 100) - mono_array = make_table(start_stop_step_lists) - if len(list(mono_array)) == 0: - print_warning_message('mono_array is length 0, check start_stop_step_lists') - ID_array=np.array([]) - ID_mode,ID_QP_ratio,ID_sp,ID_rbv,hv,grt = energy_get_all(verbose=False) - for hv_eV in mono_array: - ID_array=np.append(ID_array,ID_calc_eV(grt,ID_mode,hv_eV,kwargs['QP_ratio'])) - return mono_array,ID_array - - -############################################################################################################## -########################### switch branch ###################### -############################################################################################################## - - -def switch_branch(branch, force=False, shutter=True,enable_cams=True): - """Switch beam into which = \"c\" or \"d\" branch (by retracting/inserting deflecting mirror) - Optionnal keyword argument: - force: change m3r even if the beamline think it is already there (default=False) - shutter: open the branch shutter, does not open the valve (default=False) - reset: resets the scanRecord and the global BL for the selected branch - enable_cams: to turn on/off branch camera - - Previously: Switch_Branch - """ - branch = branch.lower() - # Check current branch: - d = m3r_position_dictionary() - if branch in d.keys(): - if m3r_branch() == branch and not force: - m3r_position = FMB_mirror_get(3,verbose=False) - if np.sum(np.array(m3r_position)): - print("\nMirror homed...") - print("...Try again using: Switch_Branch(which, forced=True)") - else: - print("\nWell, looks like the beam is already in this branch...") - print("...if you want to force the mirror motion, use the argument: forced=True") - else: - # Close both shutters: - print("\n") - print("Switching branch, please wait...") - if shutter: - branch_shutter_close('c') - branch_shutter_close('d') - - #Move M3R: - m3r_switch_branch(branch) - print(dateandtime()," - In "+branch+"-Branch") - sleep(2) - - # Open branch shutters: - if shutter: - branch_shutter_open(branch) - - - print("Need to intialize endstation") - - else: - print_warning_message(branch+' is not a valid branch selection') -# if not nocam: - -############################################################################################################## -########################### mirrors ###################### -############################################################################################################## -def get_mirrors(): - for mirror_num in [0,1,3]: - FMB_mirror_get(mirror_num,verbose=True) - - -############################################################################################################## -########################### slits and resolution ###################### -############################################################################################################## -def slit(size,verbose=True): - """ - sets the exit slit based on iex.BL.endstation_name - - ARPES = 0 < x < 300 um - Kappa = 0 < x < 1000 um - """ - branch = iex.BL.branch - exit_slit_set(branch,size,verbose=verbose) - - -def slit_get(verbose=True): - """ - sets the exit slit based on iex.BL.endstation_name - - ARPES = 0 < x < 300 um - Kappa = 0 < x < 1000 um - """ - branch = iex.BL.branch - slit_size,slit_center = exit_slit_get(branch,verbose=verbose) - return slit_size,slit_center - - - - - diff --git a/build/lib/iexcode/macros/ARPES_macros.py b/build/lib/iexcode/macros/ARPES_macros.py deleted file mode 100644 index d62a31ac3cb21abb590e726696658c5794354757..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/macros/ARPES_macros.py +++ /dev/null @@ -1,96 +0,0 @@ -import numpy as np - -from epics import caget,caput - -from .quick_plot import mda_1D,fit_gauss - -from ..instruments.electron_analyzer import scanEA -from ..instruments.slits import slit3C_set -from ..instruments.xrays import energy -from ..instruments.ARPES import mvth,scanx,mvx,mprint - - -############################################################################################################## -############################## SES Work Function ############################## -############################################################################################################## - -def WorkFunction_Measure(PE,KE=409,**kwargs): - ''' - Takes data with 1st and 2nd order light of core level with KE at @ hv=500eV - **kwargs - - ''' - frames=round(17*60*200/PE,0) - energy(500) - - #Fermi Level - slit3C_set(150) - kwargs.update({'comment': 'EF1'}) - EAlist=['KE',495,PE,frames,1] - scanEA(EAlist,**kwargs) - - #Core level first order - slit3C_set(50) - kwargs.update({'comment': 'KE1'}) - EAlist=['KE',KE,PE,frames/10,1] - scanEA(EAlist,**kwargs) - - #Core level second order - slit3C_set(150) - kwargs.update({'comment': 'KE2'}) - EAlist=['KE',KE+500,PE,frames*10,1] - scanEA(EAlist,**kwargs) - print("""Fit the data : - - EF1 = EF in first order light (scan #1) - - KE1 = Au_3/2 in first order light (scan #2) - - KE2 = Au_3/2 for 2nd order light (scan #3) - => wk = KE2-2*KE1-(EF1-KE1)` - Details of the math is page 16 of commissionning book IV - Now if you know what you are doing you can: - caput('29idcEA:det1:ENERGY_OFFSET',new_wk_value)""") - -def WorkFunction_Calc(EF1,KE1,KE2): - """Fit the data : - - EF1 = EF in first order light (scan #1) - - KE1 = Au_3/2 in first order light (scan #2) - - KE2 = Au_3/2 for 2nd order light (scan #3) - => wk = KE2-2*KE1-(EF1-KE1)` - Details of the math is page 16 of commissionning book IV""" - wk = KE2-2*KE1-(EF1-KE1) - print("wk = KE2-2*KE1-(EF1-KE1) = ",wk) - print("Now if you know what you are doing you can:") - print("EA._setwk("+str(round(wk,2))+")") - -def WorkFunction(KE1,KE2,Ef): - Phi=round(KE2-2*KE1-(Ef-KE1),3) - print(('Phi = '+str(Phi)+' eV')) - return Phi - -def RoughPositions_Find(th_start,th_stop, th_step,**kwargs): - """automatically scans and creates the RoughPosition list used in FermiMap for - relatively uniform samples by: - 1) scanx(-0.5,0.5,.05,mode='relative') - 2) does a gaussian fits the mda EAV intesnity to determine center of the fit x_center - 3) mv(x_center) - 4) mprint() and appends current position to list - 5) moves to the next theta value and repeats - - Note: before starting move to the first theta position and adjust the focus leaving the EA is Live Mode - - **kwargs - scanDet=17 - """ - kwargs.setdefault("scanDet",17) - if caget("29idcEA:det1:Acquire") !=1: - print("Turn on the EA!!! EALive(PE,KE,Lens=\'Transmission\')") - else: - RefinedPositions=[] - for th in (th_start,th_stop+th_step,th_step): - mvth(th) - scanx(-0.5,0.5,.05,mode='relative') - scanNum=caget("29idARPES:saveData_scanNumber")-1 - x,y,x_name,y_name=mda_1D(scanNum,kwargs["scanDet"]) - results=fit_gauss(np.array(x),np.array(y)) - mvx(results[2][1]) - RefinedPositions.append(mprint()) - print("RefinedPositions=",RefinedPositions) diff --git a/build/lib/iexcode/macros/BL_shutdown.py b/build/lib/iexcode/macros/BL_shutdown.py deleted file mode 100644 index 800bf0c93902b720273eb0e63ef5d15fba729d02..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/macros/BL_shutdown.py +++ /dev/null @@ -1,47 +0,0 @@ -from epics import caget,caput - -from ..instruments.electron_analyzer import EA -from ..instruments.shutters import main_shutter_close,branch_shutter_close -from ..instruments.diagnostics import diagnostics_all_out - -############################################################################################################## -############################################ Shut down ################################################# -############################################################################################################## - -def BL_Shutdown(): - BL_CloseAllShutters() - BL_Valve_All(state="CLOSE") - diagnostics_all_out() - try: - EA.off() - except: - print('EA is not running, visually confirm HV is off') - - caput("29iddau1:dau1:011:DAC_Set",0) #RSXS HV = "OFF" - -def BL_CloseAllShutters(): - main_shutter_close() - branch_shutter_close('c') - branch_shutter_close('d') - -def BL_Valve_All(state="CLOSE"): - ValveList=["V1A","V2A","V3B","V4B","V5B","V6B","V7C","V8C","V9C","V10C","V7D","V8D","V9D","V10D"] - for Vname in ValveList: - pv=BL_Valve2pv(Vname)+state+".VAL" - caput(pv,1) - -def BL_Valve(Vname,state="CLOSE"): - pv=BL_Valve2pv(Vname)+state+".VAL" - caput(pv,1) - -def BL_Valve2pv(Vname): - Valve={ - "V1A":"GV01","V2A":"GV02", #A-Hutch - "V3B":"GV03","V4B":"GV04","V5B":"GV05","V6B":"GV15", #B-Branch - "V7C":"GV06","V8C":"GV08","V9C":"GV09","V10C":"GV10", #C-Branch - "C-Turbo":"GV16", #ARPES - "V7D":"GV11","V8D":"GV12","V9D":"GV13","V10D":"GV14", #D-Branch - "D-Turbo":"GV17","D-TES":"GV18" #RSXS - } - pv="29id:BLEPS:"+Valve[Vname]+":" - return pv \ No newline at end of file diff --git a/build/lib/iexcode/macros/Kappa_optimization.py b/build/lib/iexcode/macros/Kappa_optimization.py deleted file mode 100644 index fac115060aea63fae449105471ca0ad925a43b6e..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/macros/Kappa_optimization.py +++ /dev/null @@ -1,237 +0,0 @@ -from time import sleep - -from iexcode.instruments.utilities import * -from iexcode.instruments.kappa import uan -from iexcode.instruments.kappa import tey,d3,d4,mesh,kappa_scaler_pv,tth_pv,tthdet -from iexcode.instruments.Motors import * -from iexcode.instruments.scanRecord import last_mda -from iexcode.macros.quick_plot import * - - -##### Kappa Optimization scans - 2022 versions ##### - -def Find_kth_zero(th_0,th_180): - """ - th_0 is the motor position for specular near zero - th_180 is motor position for spectular near 180 - """ - - Offset =0.5*(180 - th_180 - th_0) - - print("with motor at 0, the actual value is ",Offset) - - -def align_d4(z0,th): - ''' th = 0 or 180 - ''' - tthdet.set('d4') - sleep(1) - uan(0,th) - mvz(z0-1500) - d4.setgain(10,'uA') - dscantth(-0.25,0.25,0.01) - sleep(1) - d4.setgain(1,'nA') - mvz(z0) - n=last_mda() - fit_mda(n,25,0,'poly',graph=False) - tth0=fit_d4(n) - print('tth0 = '+str(round(tth0,3))) - playsound() - return tth0 - - -def align_z0_chi0(question=True): - if question: - foo=input_d('Are you at th=90/270, chi=0, phi=90 (Y or N)? >') - if foo == 'Y'.lower() or foo == 'yes'.lower(): - tthdet.set('d3') - sleep(1) - mvtth(0) - dscanz(-750,750,50) - sleep(1) - n=last_mda() - fit_mda(n,25,0,'poly',graph=False) - z0=fit_z(n) - print('z0 = '+str(round(z0,0))) - playsound() - return z0 - else: - print('Canceling') - return - else: - tthdet.set('d3') - sleep(1) - mvtth(0) - dscanz(-750,750,50) - sleep(1) - n=last_mda() - fit_mda(n,25,0,'poly',graph=False) - z0=fit_z(n) - print('z0 = '+str(round(z0,0))) - playsound() - return z0 - -def align_z0(omega): - tthdet.set('d3') - sleep(1) - uan(0,omega) - dscanz(-750,750,50) - sleep(1) - n=last_mda() - #fit_mda(n,25,0,'poly',graph=False) - #z0=fit_z(n) - #print('z0 = '+str(round(z0,0))) - playsound() - #return z0 - - -def align_z180(omega): - tthdet.set('d3') - sleep(1) - uan(0,180+omega) - dscanz(-750,750,50) - sleep(1) - n=last_mda() - #fit_mda(n,25,0,'poly',graph=False) - #z180=fit_z(n) - #print('z180 = '+str(round(z180,0))) - playsound() - #return z180 - -def align_th0(omega,z): - tthdet.set('d4') - sleep(1) - #uan(20,10+omega) - uan(30,15+omega) - mvz(z) - sleep(30) - d4.setgain(1,'nA') - dscanth(-0.25,0.25,0.01) - n=last_mda() - fit_mda(n,25,0,'poly',graph=False) - th_spec=fit_d4(n) - print('th specular = '+str(round(th_spec,3))) - tth=round(caget('29idKappa:m9.RBV'),3) - omega=th_spec-tth/2 - print('omega = th-tth/2 = '+str(round(omega,3))) - playsound() - return omega - - -def align_th180(omega,z): - tthdet.set('d4') - sleep(1) - uan(-30,180+omega-15) - #uan(-20,180+omega-10) - mvz(z) - d4.setgain(1,'nA') - dscanth(-0.25,0.25,0.01) - n=last_mda() - fit_mda(n,25,0,'poly',graph=False) - th_spec=fit_d4(n) - print('th specular = '+str(round(th_spec,3))) - tth=round(caget('29idKappa:m9.RBV'),3) - omega180=th_spec-tth/2-180 - print('omega180 = th-tth/2-180 = '+str(round(omega180,3))) - playsound() - return omega180 - - - - -##### 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 to d4') - tthdet.set('d4') - mvtth(0) - 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) diff --git a/build/lib/iexcode/macros/__init__.py b/build/lib/iexcode/macros/__init__.py deleted file mode 100644 index f7f0f356b6d6e4721ab6e6fc6477e17d3860073a..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/macros/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -import iexcode.instruments.cfg as iex - -from iexcode.instruments.ARPES import * -from iexcode.instruments.bakeout import * #not tested -from iexcode.instruments.conversions_constants import * -from iexcode.instruments.SRS_current_amplifiers import * #need to test SRS -from iexcode.instruments.diagnostics import * -from iexcode.instruments.electron_analyzer import * #didn't test, but not much changed -from iexcode.instruments.encoders import * #didn't test encoder reset -from iexcode.instruments.files_and_folders import * -from iexcode.instruments.FMB_mirrors import * -#from iexcode.instruments.hxp_mirrors import * -from iexcode.instruments.IEX_cameras import * -from iexcode.instruments.IEX_VPU import * #need to test with ID -#from iexcode.instruments.kappa_angle_calcs import * -#from iexcode.instruments.Kappa_det import * -#from iexcode.instruments.Kappa import * -from iexcode.instruments.Lakeshore_335 import *#didnt' test mostly hardcoded -from iexcode.instruments.Logfile import * # -from iexcode.instruments.m3r import * -from iexcode.instruments.Motors import * -#from iexcode.instruments.MPA import * -from iexcode.instruments.Octupole import * -#from iexcode.instruments.remote_controlers import * -#from iexcode.instruments.resolution import * -#from iexcode.instruments.s29_temp_cntl import * -from iexcode.instruments.scalers import * -from iexcode.instruments.scanRecord import * -from iexcode.instruments.Scienta import * -from iexcode.instruments.shutters import * #didn't do main shutter -from iexcode.instruments.slits import * -#from iexcode.instruments.spec_stuff import * -from iexcode.instruments.staff import * -from iexcode.instruments.storage_ring import * -from iexcode.instruments.userCalcs import * -from iexcode.instruments.utilities import * -from iexcode.instruments.valves import * -from iexcode.instruments.VLS_PGM import * -from iexcode.instruments.utilities import * -#from iexcode.instruments.vortex import * -from iexcode.instruments.xrays import * - diff --git a/build/lib/iexcode/macros/commissioning.py b/build/lib/iexcode/macros/commissioning.py deleted file mode 100644 index 3e627f0e8889e65e60d0514d58615a2e9fa34322..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/macros/commissioning.py +++ /dev/null @@ -1,890 +0,0 @@ -from os.path import join, isfile, exists, dirname -from time import sleep -import matplotlib.pyplot as plt - -from epics import caget, caput - -import iexcode.instruments.cfg as iex - -from iexcode.instruments.xrays import * -from iexcode.instruments.VLS_PGM import * -from iexcode.instruments.IEX_VPU import * - -from iexcode.instruments.SRS_current_amplifiers import * -from iexcode.instruments.diagnostics import diagnostics_all_out, diagnostics_all_in,diode_c,diode_d -from iexcode.instruments.m3r import * -from iexcode.instruments.slits import _slits_wide_open_dictionary -from iexcode.instruments.slits import * -from iexcode.instruments.utilities import * -from iexcode.instruments.electron_analyzer import scanEA -from iexcode.macros.cam_macros import * - -from .quick_plot import fit_mda, mda_1D - -############################################################################################################## -################################ checking alignment ############################## -############################################################################################################## - -def check_flux_scan(hv=500,stay=False,**kwargs): - """ - puts the diode in and scans the mono - stay: - True => leaves the diode in - False => takes the diode out - """ - kwargs.setdefault('sound',True) - diagnostics_all_out(diode_stay_in=True) - slit(50) - energy(hv) - hv_start = hv*.95 - hv_stop = hv*1.05 - hv_step = round(1.0*hv/500,0) - scanmono(hv_start,hv_stop,hv_step,comment='Mono Scan @ '+str(hv)+' eV') - if kwargs['sound']: - playsound() - -def check_flux_read(hv=500,ID_mode='RCP',stay=False): - """ - puts the diode in in the branch defined my position of m3r - measures flux at energy ID_mode specified - stay = True => leaves the diode in - - Previously: CheckFlux - """ - current_slit = exit_slit_get(verbose=True) - ID_switch_mode(ID_mode) - energy(hv) - - ring_current=round(caget("S:SRcurrentAI.VAL"),2) - - diagnostics_all_out(diode_stay_in=True) - exit_slit_get(50) - sleep(10) - - if m3r_branch() == "c": - diode=diode_c_read() - elif m3r_branch() == "d": - diode=diode_d_read() - - flux=current2flux(diode) - print("\n----- Current on diode : %.3e" % diode, "A") - print("----- Corresponding flux: %.3e" % flux, "ph/s \n") - print("----- Storage ring current: %.2f" % ring_current, "mA") - print("\nFlux at hv=500 as off Feb 2019 for RCP and HEG: ~3.3e-06 A = ~1.5e+11 ph/s") - - if not stay: - diagnostics_all_out() - exit_slit_set(current_slit) - - -def scan_wire(direction,all_diag=True,**kwargs): - """ - Scans the wires located just downstream of M0/M1, - which = 'H' for the horizontal, typically CA2 - which = 'V' for the vertical, typically CA3 - all_diag =True -> AllDiagIn(), otherwise you have to put any diagnostics in by hand - Logging is automatic: use **kwargs or the optional logging arguments see scanlog() for details - **kwargs: - execute - - Previously: WireScan - """ - kwargs.setdefault('execute',True) - if all_diag: - diagnostics_all_in() - - - if direction == 'H': - name = "H-wire" - - elif direction == 'V': - name = "V-wire" - - diagnostics_presets_go(name,'Start') - pv = diagnostics_presets()[name][1] - print("\n================== "+name+" scan (29idb:ca2):") - iex.BL.mda.fillin(pv+".VAL",pv+".RBV",1,-17,-30,-0.25,**kwargs) - - if kwargs['execute']: - iex.BL.mda.go(**kwargs) - - if all_diag: - diagnostics_all_out() - - -############################################################################################################## -########################### Beam Profile ###################### -############################################################################################################## -def scan_narrow_slit(slit='2V',slit_parameters=[0.25,-2,2,0.5],**kwargs): - """ - slit = '1V','1H','2V','2H' - slit_parameters = [SlitSize,start,stop,step] - - Typical slit sizes/start/stop/step are (for full range): - 1H/1V : [0.50, -4.5, 4.5, 0.2] - 2H : [0.25, -3.0, 3.0, 0.2] - 2V-MEG: [0.25, -4.0, 4.0, 0.2] - 2V-HEG: [0.50, -8.0, 8.0, 0.2] - - **kwargs: - scan_dim = 1 - execute = True - - Previously: Scan_NarrowSlit - """ - kwargs.setdefault('scan_dim',1) - kwargs.setdefault('execute',True) - - size,start,stop,step = slit_parameters - - direction = slit[1] - if direction == "V": - size = (inf, size) - center = (0, 0) - elif direction == "H": - size = (size, inf) - center = (0, 0) - - if slit[0] == '1': - slit_name = "slit1A" - slit1A_set(size,center) - slit2B_set((inf,inf),(0,0)) - - elif slit[0] == '2': - slit_name = "slit2B" - slit1A_set((3,3),(0,0)) - slit2B_set(size,center) - - slits_scan_center(slit_name,direction,start,stop,step,**kwargs) - if kwargs['execute']: - iex.BL.mda.go(kwargs['scan_dim']) - - -def scan_mono_vs_slit(slit='2V',slit_parameters=[0.25,-2,2,0.5],energy_parameters=[470,530,2],**kwargs): - """ - This can be used to find the center of the resonant beam i.e. the slit value for the most blue shifted curve: - slit='1V','1H','2V','2H' - slit_parameters = [SlitSize,start,stop,step] - energy_parameters = [eVstart,eVstop,eVstep]= [470,530,2] - - Typical slit sizes/start/stop/step are (for full range): - 1H/1V : [0.50, -4.5, 4.5, 0.2] - 2H : [0.25, -3.0, 3.0, 0.2] - 2V-MEG: [0.25, -4.0, 4.0, 0.2] - 2V-HEG: [0.50, -8.0, 8.0, 0.2] - - Previously: Scan_MonoVsSlit - """ - hv_start,hv_stop,hv_step = energy_parameters - # Filling Scans: - mono_scan(hv_start,hv_stop,hv_step) - scan_narrow_slit(slit='2V',slit_parameters=[0.25,-2,2,0.5],**kwargs) - - # Resetting everybody to normal: - mono_energy_set((hv_start+hv_stop)/2.0) - apertures_set() - - -############################################################################################################## -################################ mono alignment ############################## -############################################################################################################## -def mono_MIR_GRT_find_offset(grt,slit_list,**kwargs): - """ - Find MIR-GRT offset by scanning 0 order through exit slit - **kwargs: - detNum = 15 - - Previously: MIR_GRT_Offset - """ - kwargs.setdefault("detNum",15) - - grating(grt) - exit_slit_set(50) - diode_c('In') - slit2B_set(2,0.5,0,0) - - #set zero order, scan grating pitch - for ang in range_up(1.5,5,0.5): - print("\r") - mono_zero_order(ang) - print("Mirror pitch: "+str(ang)+"\r") - for s in slit_list: - exit_slit_set(s) - print("\r") - mono_motor_scan("GRT:P",ang-0.0005*s, ang+0.0005*s ,0.00002*s) - - sleep(1) - print("\r") - grating_ang = fit_mda(iex.BL.mda.fileNum(),kwargs['detNum'],.1,'gauss') - print("Peak: ",grating_ang) - print("\r") - print("-------------------------") - -##################### mono slit scans => Energy calibration ##################### -def exit_slit_vs_hv(hv,c=3): - ''' - Adjust slit size to keep reasonable count vs hv - c=3 for nominal slit2B size - c=10 for apertured slit2B (e.g 0.25 or 0.5) - - Previously: Mono_Set_Slitvshv - ''' - slit(hv/100.0*c) - - -def scan_energy_along_grating(hv,peakBE=84,pts=11,r=0.75,i=1,**kwargs): - """ - Takes a Slit-2V map for a range of photon energies - peakBE=84; fixed mode - pts = number of pts in slit positions, default: 11 - r = % of range in slit size, default: 0.75 - i = scanEA time in minute (default:1 for MEG, 2 for HEG?) - Takes 2.5h with default parameters (i=1) - - Previously: Mono_Scan_Slit2BV - """ - grt_density = mono_grating_density_get() - c=grt_density/1200 # c = 1 for MEG, 2 for HEG - - # Getting EA parameters vs hv: - PE=200 - - #Getting Slit-2B parameters - Vsize=0.25*c - n=(4.5-hv/500) - Vstart=-((floor((2*n)/Vsize/2)+1)*Vsize*c)*r - Vstep=-round(Vstart*2/pts,2) - - #Setting energy: - energy(hv) - exit_slit_vs_hv(hv,c=10) - - #Aperturing slit 2V (note that we have the nominal size horizontally) - (size_rbv,size_val),(center_rbv,center_val) = slits_pvs('slit2B') - caput(size_val,Vsize) - - print("\n--------------- Starting core level vs Slit-2B(V) map ---------------") - - #Take XPS for each Slit-2V position - for V_center in range_up(Vstart,-Vstart,Vstep): - caput(center_val,V_center,wait=True,timeout=18000) - kwargs.update({'comment': "2-V center ="+str(V_center)[0:6]}) - EAlist=["BE",peakBE,PE,17*60*i,1] - scanEA(EAlist,**kwargs) - - #reset the slits - apertures_set() - - - -def scan_mono_energy_drift(start,stop,step,peakBE=84,EF=None,**kwargs): - ''' - Measure core level (by default Au 4f) in fixed mode vs energy while maintaining resonable count rate - If EF='y' (by default None) takes the Fermi edge as well. - kwargs: - c=3 is the default slit2B size - - Used for grating calibration (changing grating_offset and b2 effects this - use grating_offset since b2 was measured) - - Previously: Mono_Scan_hv_drift - ''' - kwargs.setdefault('c','3') - - for hv in range_up(start,stop,step): - energy(hv) - c=int(kwargs['c']) - exit_slit_vs_hv(hv,c) - kwargs.update({'comment': "Core level @ hv = "+str(hv)}) - scanEA(["BE",peakBE,200,17*60*1,1],**kwargs) - if EF is not None: - kwargs.update({'comment': "EF @ hv = "+str(hv)}) - scanEA(["BE",0,200,17*60*10,1],**kwargs) - - - -############################################################################################################## -########################### Pinhole Scripts ###################### -############################################################################################################## -def scan_pinhole_full(): - """ - Does a pinhole with .1 mm step with AllDiagIn and then with only branch diode in - - Previously: FullPinhole - """ - diagnostics_all_in() - scan_pinhole([-3, 3, .5, .1], [-3, 3, .1, .5]) - diagnostics_all_out(diode_stay_in=True) - scan_pinhole([-3, 3, .5, .1], [-3, 3, .1, .5]) - - -def scan_pinhole(H_list,V_list,**kwargs): - """ - Sets up the pinhole scan for slit1A - Make sure that you have the appropriate Diagnostics in can use AllDiagIn() - - H_list = [Hstart, Hstop, Hstep, Hsize] => [-3, 3, .1, .5] - V_list = [Vstart, Vstop, Vstep, Vsize] => [-3, 3, .1, .5] - - *kwargs: - H_scan_dim => 1 - V_scan_dim => 2 - execute => True - - Previously: Scan_Pinhole_Go, Scan_Pinhole - """ - kwargs.setdefault('H_scan_dim',1) - kwargs.setdefault('V_scan_dim',2) - kwargs.setdefault('execute',True) - - #Synching slits - slits_synch("slit1A") - - #Getting initial slit size - (Hsize0,Vsize0),(Hcenter0,Vcenter0) = slit1A_get(verbose=False) - - #Filling in the ScanRecord - slits_scan_center("slit1A","H",H_list[0],H_list[1],H_list[2],scan_dim=kwargs['H_scan_dim'],execute=False) - slits_scan_center("slit1A","V",V_list[0],V_list[1],V_list[2],scan_dim=kwargs['V_scan_dim'],execute=False) - - #Set the slit size - slit1A_set((H_list[2],V_list[2]),(0,0),verbose=True) - - if kwargs['execute']: - print("\rPinhole scan: ("+str(kwargs['H_scan_dim'])+","+str(kwargs['V_scan_dim'])+") " - +str(H_list[0])+"/"+str(H_list[1])+"/"+str(H_list[2])+"/"+str(H_list[3])+"/" - +str(V_list[0])+"/"+str(V_list[1])+"/"+str(V_list[2])+"/"+str(V_list[3])) - - iex.BL.mda.go(max(kwargs['H_scan_dim'],kwargs['V_scan_dim'])) - print("\rNow setting the slits back to:") - apertures_set() - - print("\r") - print_warning_message("Don't forget to pull all of the diagnostics out.") - - - -############################################################################################################## -################## Slit Calibration & Beam Steering scripts ################## -############################################################################################################## -FMB_mirror_move - -def notes_20191212(): - print(""" looking at diode 3 in scattering chamber, open 3D all the way (2000) - WARNING: 10% energy detune is enough to see the 2 lobes with 2B but not for 1A => 20% - Red shifted (485eV) = edges give center of the grating - Blue shifted (510eV) = gaussian center gives center of the beam - => we want the slit centered on the grating center and the beam centered on the slits/grating - => 5 urad down = 1 mm negative motion on 2B-V with HEG""") - - -def procedure_align_m1(): - print("""\n-Start with a very red shifted line cut to localize the edges of the grating: - Set_IDraw(510) - mono(485) - scan_narrow_slit('2V',[0.25,-8,8,0.5]) - scan_narrow_slit('2H',[0.25,-4,4,0.5]) - => Verticaly: The edges/center of the grating define the center of 2V - => Horizontaly: The edges are defined by the aperture upstream. - As long as the beam makes it through the pipe to the next mirror, we are good. - Each M1 pitch will have its own slit-2H zero - It can be a good idea to check that GRT or M2 translation does not change anything. -\n-Once the slits are centered on the grating, center resonant beam on the grating (zero slit): - FMB_mirror_get(1) # to get current values - for roll_value in RangeUp(3,4,0.2): - print('\\nRZ = '+str(roll_value)) - FMB_mirror_move(1,'RZ',roll_value) - sleep(5) - scan_mono_vs_slit('2V',[0.25,-0.5,0.5,0.25],[490,530,2]) - for pitch_value in RangeUp(8.5,8.7,0.05): - print('\\nRY = '+str(pitch_value)) - FMB_mirror_move(1,'RY',pitch_value) - sleep(5) - scan_mono_vs_slit('2H',[0.25,-0.5,0.5,0.25],[490,530,2]) - => The resonant beam is the slit value for the most blue shifted curve. - - WARNING: It is more accurate (and easier) to compare the leading edge of the ID peak - than trying to look at the perpendicular direction (slit line cut) because of the - asymetry in the beam intensity (uneven carbon strip along the grating?) -""") - - - # 2017_3 - HEG after opitmization: mba_b_0241-0244 - # 2018_1 - HEG before opitmization: mba_b_0005-0008 - -def iex_steering(h_position,v_position): - """ - prints the required steering to compensate for the current - """ - print('\nBeam position:') - print(' - horizontal: '+str(h_position)) - print(' - vertical: '+str(v_position)) - h_steering,v_steering=beamsteering_1A(h_position,v_position) - print('\nBeam steering:') - print(' - horizontal: '+h_steering) - print(' - vertical: '+v_steering) - print('\n') - return h_steering,v_steering - -def beamsteering_1A(h_position,v_position,FE_center_h=0,FE_center_v=0): - h_correction=FE_center_h-h_position - v_correction=FE_center_v-v_position - hrad=round(abs(h_correction)*10/0.25,0) - vrad=round(abs(v_correction)*10/0.25,0) - if h_correction<0: h_direction=' urad outboard' - else: h_direction=' urad inboard' - if v_correction<0: v_direction=' urad up' - else: v_direction=' urad down' - h_steering=str(hrad)+h_direction - v_steering=str(vrad)+v_direction - return h_steering,v_steering - -def M0M1_steering(H2,V2): - """ - M1 steering: (monoVslit-2V and 2H) - Roll: Rz more positive => 2V more positive (0.25 => .25 mm) - Pitch: Ry more positive => 2H more positive (0.03 => .5 mm - """ - print('\nBeam position:') - print(f" - vertical: V2 = {round(V2,3)}") - print(f" - horizontal: H2 = {round(H2,3)}") - v_steering=beamsteering_2B(V2) - m1_roll=beamsteering_2B(V2)[1] - print('\nCurrent position:') - current_roll=FMB_mirror_get(1)[5] - new_roll=current_roll+m1_roll - print('\nREMEMBER: 2V slit should always be centered at zero by steering M1 roll!') - print(" - vertical: "+str(current_roll)+str(v_steering[1])+" => Move_M1('RZ',"+str(new_roll)+")") - print(' - horizontal: reset slit 2BH center to ',str(H2)) - - print("\n\nM1 roll vs energy calibration/flux:") - print(" - 1.0 mm @ slit2V ~ 1.0 mrad on M1 roll") - print(" - 1.0 mm @ slit2V = 0.4 eV shift in energy") - print(" - 0.8 mm @ slit2V = 25% loss in intensity on Au 4f\n") - - -def beamsteering_2B(v_position): - vroll=round(v_position*0.05/0.04,3) - if v_position<0: v_direction=' +' - else: v_direction=' -' - v_steering=v_direction+str(abs(vroll))+' urad' - return v_steering,float(v_steering.split(" ")[1]) - - - - - -def ID_steering_scans(**kwargs): - """ - slit1 - Scanning front-end slit center - cutoffs are defined by the fixed aperature midpoint is slit center - beam should be center at slit center, steer ID until the coincide - - **kwargs: - verbose: default => True - sound: playsound, default => True - extended_range True/False - False: default range = -3,3,0.1 - True: -5,5,0.1 - - Note: Does not set the ID, mvID = 2.0 gives a nice gaussian - """ - kwargs.setdefault('sound',True) - - if 'extended_range' in kwargs: - start,stop = (-5,5) - else: - start,stop = (-3,3) - - size,center = slit1A_get(verbose=False) - - slits_scan_center('slit1A','H',start,stop,0.1,size=(0.25,inf),comment='Slit center - 1H') - slits_scan_center('slit1A','V',start,stop,0.1,size=(inf,0.25),comment='Slit center - 1V') - - slit1A_set(size,center,verbose=False) - - - if kwargs['sound']: - playsound() - - if kwargs['verbose']: - print('\nsteering out => move beam more positive (10 urad ~ 0.25 mm)') - print('steering up => move beam more positive (10 urad ~ 0.25 mm)\n') - -def ID_steering_plots(scanNum,det_num,xrange=[-1,1]): - """ - plots data from ID_steering_scans and returns the positions - """ - - position=fit_mda(scanNum,det_num,1,'gauss',xrange=xrange) - plt.show() - - return position - -def wire_scans(**kwargs): - """ - Checks for large misaligment or clipping by M0/M1 - - Note: Does not set the ID, mvID = 2.0 gives a nice gaussian - """ - kwargs.setdefault('sound',True) - - slits_set_size('slit1A',(4.5,4.5)) - scan_wire('H',comment='Wire scan - H',all_diag=False) # by default puts all meshes in + DiodeC - scan_wire('V',comment='Wire scan - V',all_diag=False) - - if kwargs['sound']: - playsound() - -def monoVslit_quick_scan(slit_name, **kwargs): - """ - sets the slit to be narrow and scans along and across the grating - at 500 eV to see if M0/M1 are steering the beam to the center of the grating - - """ - kwargs.setdefault('sound',True) - - energy(500) - mvmono(505) - - H,V = _slits_wide_open_dictionary()[slit_name] - - c = mono_grating_density_get()/1200.0 - - slits_scan_center(slit_name,'V',-V,V,0.25,size=(inf,0.25*c)) - sleep(1) - - slits_scan_center(slit_name,'H',-H,H,0.25,size=(0.25,inf)) - sleep(1) - - if kwargs['sound']: - playsound() - - -def monoVslit_quick_plot(scanNum,detDiode,c,xrange=None): - position = fit_mda(scanNum,detDiode,c,'gauss',xrange) - plt.show() - return position - - -##################################################################################### -### Slit-1A Procedures -##################################################################################### - -def check_slit1A(step=0.1): - """ - Checks that Slit1A is centered on the fixed aperature/theoretical optic axis - top='m9' -> CA5 - inboard='m10' -> CA4 - - Scans the top blade - CA4 sees an step function - top_center = midpoint of motor position for zero current and when current saturates - Scans the inner blade - CA4 sees box fuction convoluted with gaussian beam position - inner_center - midpoint bewteen box edges - - SetSlit1A(0,0,inner_center,top_center) - for m in range(9,13): - Reset_Motor_User(m,'b',0) - SyncAllSlits() - - If data makes no sense then Reset_Slit1A_Procedure() - - """ - #scanning top-blade - slit1A_set(8,8,0,0) # aperture wide open - caput('29idb:m10.VAL',0) # Inboard blade centered-ish in the beam - m=9 - VAL='29idb:m'+str(m)+'.VAL' - RBV='29idb:m'+str(m)+'.RBV' - iex.BL.mda.fillin(VAL,RBV,-4,4.0,step) - FileNum1 = iex.BL.mda.lastFileNum() - - #scanning inboard-blade - slit1A_set(8,8,0,0) # aperture wide open - caput('29idb:m9.VAL',0) # top blade centered-ish in the beam - m=10 - VAL='29idb:m'+str(m)+'.VAL' - RBV='29idb:m'+str(m)+'.RBV' - iex.BL.mda.fillin(VAL,RBV,-4,4.0,step) - FileNum2 = iex.BL.mda.lastFileNum() - - return FileNum1, FileNum2 - - -def procedure_reset_slit1A(): - """ - Prints the procedure for Resetting Slit1A - """ - print("\n#------- Checking and Resetting the Dial -------") - print(" GoToSlit1AScribe()") - print("# if not on the scribe marks tweek the position until the scribe marks are aligned") - print(" for m in [9,10,11,12]: Reset_Motor_Dial(m,\'b\',0);SyncAllSlits()") - print("\n#------- Resetting the User -------") - print("# SetSlit1A by hand such that you have some beam coming through") - print(" Scan_SlitSize(\"1H\",start,stop,step) #looking at CA4") - print(" Scan_SlitSize(\"1V\",start,stop,step) #looking at CA4") - print("# Then SetSlit1A(1Hsize,1Vsize,0,0); where 1Hsize and 1Vsize are the size where CA4 = 0") - print(" for m in [9,10,11,12]: Reset_Motor_User(m,'b',0);SyncAllSlits()") - - -def check_ID_steering(hv=2000): - """ - Scans Slit1A center (set to a (0.25,0.25) pinhole) while looking at the back blade: - - slit center vs fixed aperture: given by the position of the edges - - beam center vs fixed aperture: given by the position of the bump in the middle - """ - slit1A_set(0.25,0.25,0,0) - ID_set(hv) - scan_slit_center('1H',-3,3,0.1) - scan_slit_center('1V',-3,3,0.1) - -def scan_slit_center(slit,start,stop,step,size=0.25): - """ - slit = '1H','1V','2H' or '2V' - - Previously: Scan_SlitCenter - """ - if slit[0] == '1': - slit_name = "slit1A" - elif slit[0] == '2': - slit_name = "slit2B" - direction = slit[1] - slits_scan_center(slit_name,direction,start,stop,step,size=size) - - -def scan_slit_size(slit,start,stop,step,center=(0,0)): - """ - slit = '1H','1V','2H' or '2V' - - Previously: Scan_SlitSize - """ - if slit[0] == '1': - slit_name = "slit1A" - elif slit[0] == '2': - slit_name = "slit2B" - direction = slit[1] - slits_scan_center(slit_name,direction,start,stop,step,center=center) - - - -##################################################################################### -# Checking the beam steering uses the gas-cell to see if the beam is centered on the grating -# and that the slits are centered -##################################################################################### - -def beam_profile(grt,slit_list): - """ - Makes a nice 2D image of the energy distribution of the beam across the grating at ID=500 - SlitList=["2H","2V","1H","1V"] - - Note: Does NOT put the diagnostics into the beam - - Previously BeamProfile - """ - grating(grt) - c = mono_grating_density_get()/1200 - - mvID(500) - apertures_set() - - eVstart = 460 - eVstop = 540 - eVstep = 4 - - for slit in slit_list: - if slit=="1H": - #Hsize,Vsize,Hstart,Hstop,Hstep = 0.50,2,-2,2,0.25*c_slit # => 35 min - scan_mono_vs_slit('1H',[0.5,-2,2,0.25*c],[eVstart,eVstop,eVstep],comment='Mono/Slit - 1H') - elif slit == "1V": - #Hsize,Vsize,Vstart,Vstop,Vstep = 2,0.50,-2,2,0.25*c_slit - scan_mono_vs_slit('1V',[0.5,-2,2,0.25*c],[eVstart,eVstop,eVstep],comment='Mono/Slit - 1V') - elif slit =="2H": - #Hsize,Vsize,Hstart,Hstop,Hstep = 0.50,8,-3,3,0.5*c_slit - scan_mono_vs_slit('2H',[0.5,-3,3,0.5*c],[eVstart,eVstop,eVstep],comment='Mono/Slit - 2H') - elif slit =="2V": - #Hsize,Vsize,Vstart,Vstop,Vstep = 6,0.25*c,-4*c,4*c,0.5*c_slit - scan_mono_vs_slit('2V',[0.5,-4,4,0.5*c],[eVstart,eVstop,eVstep],comment='Mono/Slit - 2V') - - -def CheckAllSlits_long(hv_list=[500],slit_list=["1H","1V","2H","2V"],**kwargs): - """ - For each photon energy in hvList, takes 3 slit curves @ mono below / resonance / above - For given SlitList - For both gratings - """ - for grt in ["HEG","MEG"]: # One full loop for a given grating and 3 energies takes 5h for average 20 - grating(grt) - for hv in hv_list: - apertures_set(hv) - step=hv/100.0 - start=hv-step - stop=hv+step - for slit in slit_list: - for hv in range(start,stop,step): - print("\r") - mono_energy_set(hv) - check_ID_beam_steering(slit) - - -def CheckSlitCalibration(slit_list,BL=500,hvList=[485,510],scanIOC=None,**kwargs): - """ - Slit scan for red shifted and blue shifted mono values - used to determine in the beam is centered on the grating (gaussian) - and if the slits are centered on the grating (humped) - hv=500; hvList=[485,510] - hv=1500;hvList=[hv*0.97,hv*1.01] - Note: sets the exit slit to 50 - """ - if scanIOC is None: - scanIOC=BL_ioc() - exit_slit_set(50) - apertures_set(BL) - for hv in hvList: - mono_energy_set(hv) - for slit in slit_list: - check_ID_beam_steering(slit) - print("\n") - -def check_ID_beam_steering(slit): #here - """ - checks the ID beam steering by scanning the slit with the ID detuned - if there is carbon on the mirror you might need to do the full ID_beam_profile to - find the red shifted beam - - slit = '1V','1H','2V','2H' - - Previously: CheckBeamPosition - """ - - grt_density = mono_grating_density_get() # can be plotted directly on dview using the buffer. That should - c=grt_density/1200 # be fairly quick and not require any data loading/analysis - - slit1A_set((3.5,3.5),(0,0),verbose=False) - slit2B_set((6.0,8.0),(0,0),verbose=False) # Open up all the slits to make sure we scan the full beam - - if slit == "1H": - size,start,stop,step = 0.50,-4.5,4.5,0.2 - elif slit == "1V": - size,start,stop,step = 0.50,-4.5,4.5,0.2 - elif slit == "2H": - size,start,stop,step = 0.25,-8.0,8.0,0.2 - elif slit == "2V": - size,start,stop,step = 0.25*c,-4*c,4*c,0.2*c - - scan_slit_center(slit,start,stop,step,size=size) - apertures_set() - - -############################################################################################################## -################## Commissioning paper curves ################## -############################################################################################################## -def FermiEdges(Energy,Slit): - EF_Table={} - EF_Table[500] = {10:20, 20:20, 50:20, 100:20, 200:20} - EF_Table[1000] = {10:50, 20:50, 50:50, 100:50, 200:50} - EF_Table[1500] = {10:100, 20:100, 50:100, 100:100, 200:100} - PE = EF_Table[Energy][Slit] - return PE - - - - -def QP_curves(ID_energy,ID_mode_list,hv_start,hv_stop,hv_step): - """ - Sets the ID to setpoint and scans the mono for a list of polarizations - - Does not set the QP_ratio first use, ID_QP_mode_set(QP_ratio) - """ - exit_slit_set(200) - - for ID_mode in ID_mode_list: - polarization(ID_mode) - ID_set_eV(ID_energy) - apertures_set() - mono_scan(hv_start,hv_stop,hv_step) - - - - - -############################################################################################################## -############################## Beam Motion ############################## -############################################################################################################## -def scan_cam_motor(motor_name,start,stop,step,cam_num,ExposureTime): - """ - motor_name = 'x','y','z'... - cam_num = 1,2,3... uses cam_pv to get the pv - - Previously: Pixel_Calibration - """ - - cam_scan_setup(cam_num,ADtype='TIFF',) - - iex.BL.motors.scan(motor_name,start,stop,step) - cam_live() - - - -def scan_cam_hv(start,stop,step,cam_num,**kwargs): - """ - takes and image as a function of photon energy - **kwargs: - ExposureTime - Previously: BeamMotion_Vs_BL_Go - """ - cam_scan_setup(cam_num,ADtype='TIFF') - scanmono(start,stop,step,**kwargs) - - cam_live() - - - -def scan_cam_mono_zero_order(start,stop,step,cam_num,iterations=1,**kwargs): - """ - Previously: BeamMotion_Vs_MonoZero_Go - """ - i = 0 - while i < iterations: - for angle in range(start,stop+step,step): - mono_zero_order(angle) - sleep(5) - cam_snap(cam_num,ADtype='TIFF',**kwargs) - i+=1 - - cam_live() - -def scan_cam_mono_pitch(motor,angle,delta,cam_num,iterations=1,**kwargs): - """ - takes image at zero order (alpha = beta = angle) - takes image at zeror order with delta - - motor = 'grating' or 'mirror - if 'grating': - alpha = angle - beta = angle + delta - if 'mirror': - alpha = angle + delta - beta = angle - - Previously:BeamMotion_Vs_MirPitch_Go - """ - if motor == 'grating': - alpha = angle - beta = angle + delta - if motor == 'mirror': - alpha = angle + delta - beta = angle - i=0 - while i<iterations: - mono_angles_set(angle,angle) - sleep(5) - cam_snap(cam_num,ADtype='TIFF',**kwargs) - - mono_angles_set(alpha,beta) - sleep(5) - cam_snap(cam_num,ADtype='TIFF',**kwargs) - i+=1 - - cam_live() - - - diff --git a/build/lib/iexcode/macros/start_of_the_week.py b/build/lib/iexcode/macros/start_of_the_week.py deleted file mode 100644 index f76be91f9dc479f15f7d900fc8429d7604ae93fd..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/macros/start_of_the_week.py +++ /dev/null @@ -1,503 +0,0 @@ -import datetime -from re import A -import matplotlib.pyplot as plt - -import iexcode.instruments.cfg as iex -from iexcode.instruments.ARPES import ARPES_init -from iexcode.instruments.Kappa import kappa_init - -from iexcode.instruments.scanRecord import * -from iexcode.instruments.diagnostics import _diagnostics_dict, diagnostics_all_out, diagnostics_all_in,diode_c,diode_d -from iexcode.instruments.SRS_current_amplifiers import * -from iexcode.instruments.xrays import * -from iexcode.instruments.VLS_PGM import * -from iexcode.instruments.Logfile import log_name_set,log_print -from iexcode.instruments.shutters import branch_shutter_open, branch_shutter_status -from iexcode.instruments.utilities import * -from iexcode.macros.commissioning import * -from iexcode.macros.quick_plot import * - - -def StartOfTheWeek_detectors(branch): - """ - returns detCA4,detH,detV,detDiode - """ - DetDict={'c':(9,7,8,15),'d':(9,7,8,14)} - return DetDict[branch] - -def interactive_fct(mirror=False): - options='0,1,2,3' - if not mirror: - print('''\nDo you want to: - \t (0) write comment - \t (1) continue - \t (2) repeat scan - \t (3) adjust xrange for fit - ''') - else: - print('''\nDo you want to: - \t (0) write comment - \t (1) continue - \t (2) repeat scan - \t (3) adjust xrange for fit - \t (4) move M1 roll - ''') - options=options+',4' - flag=input('\nType ('+options+'), or press enter to abort script >') - if flag not in options.split(","): - print('\ninvalid input; please try again...\n') - flag=input('\nType ('+options+') >') - if flag == '0': - cmt=input('\nType comment >') - print('\n================================') - log_print(cmt) - print('================================\n') - flag=input('\nType ('+options+'), or press enter to abort script >') - if flag == '1': print('\nresuming script...\n'); flag=1 - if flag == '2': print('\nrepeating scan...\n'); flag=2 - if flag == '3': flag=3 - if mirror: - if flag == '4': flag=4 - - return flag - - -def StartOfTheWeek(GRT,branch,wait=False,**kwargs): - """ - This should be run every at the start of every week; 50 min total. - Switch to C-branch,. - If wait=True, wait for next day a 8:05. - - **kwargs: - mode: polarization, default => RCP - repeat: True/False - True => doesn't do any initialization - False => resets everything (switches branch and grating) - scanType = ['slit1','wire','monoVslit','flux',] - sound: plays sound when a scantype is completed, default => True - # for individiual scantypes - slit1A_extended: to take a larger range, default => False - monoVslit_quick: - True => takes a single line cut (defaule) - False => - - """ - kwargs.setdefault('mode','RCP') - kwargs.setdefault('repeat',False) - kwargs.setdefault('scanType',['slit1','wire','flux','monoVslit']) - kwargs.setdefault('sound',True) - - kwargs.setdefault('slit1A_extended',False) - kwargs.setdefault('monoVslit_quick',True) - - - detCA4,detH,detV,detDiode = StartOfTheWeek_detectors() - - branch=branch.lower() - if iex.BL == None: - if branch == 'c': - BL_init=ARPES_init - else: - BL_init=kappa_init - - if kwargs['repeat']==False: #reset folders/detectors/... - BL_init('staff') - else: - BL_init('staff',reset=False,set_folders=False) - switch_branch(branch) - log_name_set('StartOfTheWeek_log.txt') - log_print("\n\n================== Start Of The Week @ "+today('slash')+':\n') - - for scan in kwargs['scanType']: - if scan not in ['slit1','wire','flux','monoVslit']: - print(scan+" is not a valid scan scanType=['slit1','wire','flux','monoVslit']") - return - - ### checking diode settings: - if branch == 'c': - ca15 = Keithley('b',15) - ca15.autoscale('Off') - - else: - foo=input('Do you have a diode in direct beam (y or n)? >') - if foo.lower() == 'y' or foo.lower() == 'yes': - print('Resuming...') - - print("\n\n================== Sets Beamline & Scans:") - grating(GRT) - - ########################################################################### - ### stuff that requires beam - ########################################################################### - - ### checking branch shutter: - shutter_open = branch_shutter_status() - if shutter_open == False: - foo=input_d('Shutter '+branch.upper()+' is closed, do you want to open it (y or n)? >') - if foo.lower() == 'y' or foo.lower() == 'yes': - branch_shutter_open() - else: - print('Aborting...') - return - - ### checking QP ratio: - QP=caget('ID29:QuasiRatio.RVAL') - if QP != 100: - foo=input('QP on!!! Continue (y or n)? >') - if foo.lower() == 'y' or foo.lower() == 'yes': - print('Resuming...') - - ### Wait for next 8AM: - if wait: - t = datetime.today() - if 0 <= t.hour <= 8: - wait_for_it(0,8,5) - else: - wait_for_it(1,8,5) - - ### checking ID: - polarization(kwargs['mode']) - - ### Ready to start: - FirstScan=iex.BL.mda.filenum() - - ########################################################################### - if 'slit1' in kwargs['scanType']: - print("\n\n================== Slit 1A scans:") - mvID(2000) - flag=2 - while flag==2: - #scanning - slit1A_kwargs = { - 'sound':kwargs['sound'], - 'extended_range':kwargs['slit1A_extended'] - } - ID_steering_scans(**slit1A_kwargs) - - #plotting - try: - scanNum_h = last_mda()-1 - scanNum_v = last_mda() - h_position = ID_steering_plots(scanNum_h,detCA4,xrange=[-1,1]) - v_position = ID_steering_plots(scanNum_v,detCA4,xrange=[-1,1]) - iex_steering(h_position,v_position) - except: - print('\nUnable to fit position; try to adjust xrange.\n') - - flag=interactive_fct() - - #want to refit - while flag == 3: - try: - fitH=input('do you want to fit mda #'+str(scanNum_h)+' ie horizontal (y or n)? >') - if fitH.lower() == 'y' or fitH.lower() == 'yes': - x1=input('x1 >') - x2=input('x2 >') - h_position = ID_steering_plots(scanNum_h,detCA4,xrange=[float(x1),float(x2)]) - - fitV=input('do you want to fit mda #'+str(scanNum_v)+' ie vertical (y or n)? >') - if fitV.lower() == 'y' or fitV.lower() == 'yes': - x1=input('x1 >') - x2=input('x2 >') - v_position = ID_steering_plots(scanNum_v,detCA4,xrange=[float(x1),float(x2)]) - - iex_steering(h_position,v_position) - foo=input('\nare you happy with the fit (y or n)? >') - if foo.lower() == 'y' or foo.lower() == 'yes': - flag=interactive_fct() - - except: - print('\nUnable to fit position; try to tweak xrange again\n') - flag=interactive_fct() - if flag == '': - return - - ###### Wire scans: - if 'wire' in kwargs['scanType']: - #scanning - mvID(2000) - wire_scans(**kwargs) - - #plotting - try: - scanNum_h = last_mda()-1 - scanNum_v = last_mda() - plot_mda(scanNum_h,detH,scanNum_v,detV,title='wire-H (blue) & wire-V (orange)');plt.show() - except: - print('Unable to plot. Try:') - print("plot_mda("+str(scanNum_h)+","+str(detH)+","+str(scanNum_v)+","+str(detV)+",title='wire-H (blue) & wire-V (orange)');plt.show()") - - - ###### Mono/slit scans: - if 'monoVslit' in kwargs['scanType']: - list_position=[GRT,'S1H','S1V','S2H','S2v'] - if mono_grating_get('HEG'): - slit(300) - c=2 - else: - slit(200) - c=1 - - diagnostics_all_out(diode_stay_in=True) - print("\n\n================== Mono/slit scans:") - if kwargs['monoVslit_quick']: - for i,slit_name in enumerate(['slit2B','slit1A']): - print('\n---------- Scanning '+slit_name+':\n') - flag=2 - while flag==2: - #scanning - monoVslit_quick_scan(slit_name,**kwargs) - - #plotting - try: - scanNum_v = last_mda()-1 - scanNum_h = last_mda() - V2 = monoVslit_quick_plot(scanNum_v,detDiode,c) - H2 = monoVslit_quick_plot(scanNum_h,detDiode,1) - - except: - print('Unable to fit position; try to adjust xrange.') - - flag=interactive_fct(mirror=True) - #want to refit - while flag == 3: - fitV2=input('do you want to FIT mda #'+str(scanNum_v)+' ie slit2-V (y or n)? >') - if fitV2.lower() == 'y' or fitV2.lower() == 'yes': - x1=input('x1 >') - x2=input('x2 >') - xrange=[float(x1),float(x2)] - V2 = monoVslit_quick_plot(scanNum_v,detDiode,c,xrange=xrange) - foo=input('do you want to replace '+slit_name+'-V value in list_position (y or n)? >') - if foo.lower() == 'y' or foo.lower() == 'yes': - list_position[1]=V2 - - fitH2=input('do you want to FIT mda #'+str(scanNum_h)+' ie slit2-H (y or n)? >') - if fitH2.lower() == 'y' or fitH2.lower() == 'yes': - x1=input('x1 >') - x2=input('x2 >') - xrange=[float(x1),float(x2)] - H2 = monoVslit_quick_plot(scanNum_h,detDiode,1,xrange=xrange) - foo=input('do you want to REPLACE '+slit_name+'-H value in list_position (y or n)? >') - if foo.lower() == 'y' or foo.lower() == 'yes': - list_position[1]=H2 - - if slit_name == 'slit2B': - M0M1_steering(H2,V2) - list_position[4] = V2 - list_position[3] = H2 - mirror = True - elif slit_name == 'slit1A': - list_position[2] = V2 - list_position[1] = H2 - mirror = False - - foo=input('\nare you happy with the fit (y or n)? >') - if foo.lower() == 'y' or foo.lower() == 'yes': - flag=interactive_fct(mirror=mirror) - - #happy with fitting but want to adjust roll - if flag == 4: - x=input('New M1 roll value >') - x=float(x) - try: - FMB_mirror_move(1,'RZ',x) - sleep(2); - FMB_mirror_get(1) - print('\nrepeating scan...\n') - flag=2 - except: - print('\ninvalid input; unable to move M1...\n') - flag=interactive_fct(mirror=True) - - print('\nBeam center fit @ '+str(list_position)) - foo=input('do you want to update the slit dictionary (y or n)? >') - if foo.lower() == 'y' or foo.lower() == 'yes': - slit_list=input('do you want to use '+str(list_position)+' (y or n)? >') - if foo.lower() == 'y' or foo.lower() == 'yes': - update_slit_dict(list_position) - else: - update_slit_dict() - - else: # 2D map - mvID(500) - flag=2 - while flag==2: - beam_profile(GRT,["2V","2H","1V","1H"]) - - #interactive - flag=interactive_fct() - if flag == '': - return - - ###### Check flux: - if 'flux' in kwargs['scanType']: - diode_c('In') - print("\n\n================== Check Flux:") - flag=2 - while flag==2: - check_flux_scan(stay=True) - - scanNum = last_mda() - try: - plot_mda(scanNum,detDiode,Flux=3);plt.show() - except: - print('Unable to plot. Try:') - print("plot_mda("+str(scanNum)+","+str(detDiode)+",flux=3);plt.show()") - flag=interactive_fct() - if flag == '': - return - - diagnostics_all_out() - - print("\n\n================== All done:") - print("\nDon't forget to put back the user folder !!!!") - - - ###### The end: - if list_position: - print('\nBeam center fit @ ['+GRT+',2V,2H,1V,1H]:',list_position) - if kwargs['sound']: - playsound() - - return list_position - - - - -def update_slit_dict(mylist=None,**kwargs): - """ - Interactive function to update the slit position dictionary (Dict_Slit.txt) - mylist=['GRT',2V,2H,1V,1H] - **kwargs - readOnly == False, if true just pring the current slit dictionary - """ - filepath = "/home/beams22/29IDUSER/Documents/User_Macros/Macros_29id/IEX_Dictionaries/" - filename ='Dict_Slit.txt' - - kwargs.setdefault("readOnly",False) - - # print('\n\nWARNING: 2V slit should always be centered at zero ie steer M1 center beam on the grating') - # print('Increasing the roll moves the beam more positive: +0.05 pitch => ~ +0.04 slit position; Use:\n') - # print("Get_Mirror(1);Move_M1('RZ',x)") - # print("energy(500);mono(505);slit(200)") - # print("Scan_NarrowSlit_Go(which='2V',slit_parameters=[0.25, -2, 2, 0.25]) #for MEG; slit_parameters=[0.5, -2, 2, 0.25] for HEG") - # print("Scan_NarrowSlit_Go(which='2V',slit_parameters=[0.50, -2, 2, 0.25]) #for HEG") - # print('Once steering is completed, check 2H position:') - # print("Scan_NarrowSlit_Go(which='2H',slit_parameters=[0.25, -6, 6, 0.25]) ") - - - try: - slit_position=read_dict(filename) - print('\nCurrent dictionary:\n') - print(slit_position) - - except KeyError: - print("Unable to read dictionary") - return - - if kwargs['readOnly']== True: - return slit_position - - else: - if mylist: - if len(mylist) == 5: - grt,s2v,s2h,s1v,s1h=mylist - else: - print('\nInvalid list. No changes made in file.') - return - - else: - grt=input('\nWhich grating do you want to update (HEG or MEG) >') - s2v=input('New Slit 2B-V center >') - s2h=input('New Slit 2B-H center >') - s1v=input('New Slit 1A-V center >') - s1h=input('New Slit 1A-H center >') - - if grt == '' or s1h == '' or s1v == '' or s2h == '' or s2v == '': - print('\nMissing input. No changes made in file.') - return - - if grt[0] == '"' or grt[0]=="'": grt = grt[1:4] - - # new_slit_position={grt.upper():{'S1H':float(s1h),'S1V':float(s1v),'S2H':float(s2h),'S2V':float(s2v)}} # change order to match scan/fit order - if grt.upper() == 'MEG' or grt.upper() == 'HEG': - new_slit_position={grt.upper():{'S2V':float(s2v),'S2H':float(s2h),'S1V':float(s1v),'S1H':float(s1h)}} - else: - print('\nInvalid grating name. No changes made in file.') - return - - - slit_position.update(new_slit_position) - - - with open(join(filepath, filename), "a+") as f: - f.write('\n======= '+today()+': \n') - f.write(str(slit_position)) - f.write('\n') - print('\nWriting dictionary to:',join(filepath, filename)) - sleep(2) - apertures_set() - return slit_position - - - -def update_slit_dict(**kwargs): - """ - Interactive function to update the slit position dictionary (Dict_Slit.txt) - - **kwargs - readOnly == False, if true just pring the current slit dictionary - """ - filepath = "/home/beams22/29IDUSER/Documents/User_Macros/Macros_29id/IEX_Dictionaries/" - filename ='Dict_Slit.txt' - - kwargs.setdefault("readOnly",False) - - print('\n\nWARNING: 2V slit should always be centered at zero ie steer M1 center beam on the grating') - print('Increasing the roll moves the beam more positive: +0.05 pitch => ~ +0.04 slit position; Use:\n') - print("Get_Mirror(1);Move_M1('RZ',x)") - print("energy(500);mono(505);slit(200)") - print("Scan_NarrowSlit_Go(which='2V',slit_parameters=[0.25, -2, 2, 0.25]) #for MEG; slit_parameters=[0.5, -2, 2, 0.25] for HEG") - print("Scan_NarrowSlit_Go(which='2V',slit_parameters=[0.50, -2, 2, 0.25]) #for HEG") - print('Once steering is completed, check 2H position:') - print("Scan_NarrowSlit_Go(which='2H',slit_parameters=[0.25, -6, 6, 0.25]) ") - - try: - slit_position=read_dict(filename) - print('\nCurrent dictionary:\n') - print(slit_position) - - except KeyError: - print("Unable to read previous dictionary") - return - - if kwargs['readOnly']== True: - return slit_position - - else: - grt=input('\nWhich grating do you want to update (HEG or MEG) >') - s2v=input('New Slit 2B-V center >') - s2h=input('New Slit 2B-H center >') - s1v=input('New Slit 1A-V center >') - s1h=input('New Slit 1A-H center >') - - if grt == '' or s1h == '' or s1v == '' or s2h == '' or s2v == '': - print('\nMissing input. No changes made in file.') - return - - if grt[0] == '"' or grt[0]=="'": grt = grt[1:4] - - # new_slit_position={grt.upper():{'S1H':float(s1h),'S1V':float(s1v),'S2H':float(s2h),'S2V':float(s2v)}} # change order to match scan/fit order - new_slit_position={grt.upper():{'S2V':float(s2v),'S2H':float(s2h),'S1V':float(s1v),'S1H':float(s1h)}} - slit_position.update(new_slit_position) - - - with open(join(filepath, filename), "a+") as f: - f.write('\n======= '+today()+': \n') - f.write(str(slit_position)) - f.write('\n') - print('\nWriting dictionary to:',join(filepath, filename)) - - apertures_set() - return slit_position - diff --git a/iexcode.egg-info/PKG-INFO b/iexcode.egg-info/PKG-INFO deleted file mode 100644 index 5719aabcdbf6587bd55979d8a0f179457b4c05d9..0000000000000000000000000000000000000000 --- a/iexcode.egg-info/PKG-INFO +++ /dev/null @@ -1,7 +0,0 @@ -Metadata-Version: 2.1 -Name: iexcode -Version: 0.0.1 -Summary: python scripts to run 29id of the APS -Home-page: https://github.com/xxx -Maintainer: Jessica McChesney -Maintainer-email: jmcchesn@anl.gov diff --git a/iexcode.egg-info/SOURCES.txt b/iexcode.egg-info/SOURCES.txt deleted file mode 100644 index 01565edb3e8e2ef75a2ff3c06005678e708f801a..0000000000000000000000000000000000000000 --- a/iexcode.egg-info/SOURCES.txt +++ /dev/null @@ -1,75 +0,0 @@ -README.md -setup.py -iexcode/__init__.py -iexcode.egg-info/PKG-INFO -iexcode.egg-info/SOURCES.txt -iexcode.egg-info/dependency_links.txt -iexcode.egg-info/requires.txt -iexcode.egg-info/top_level.txt -iexcode/IEX_dictionaries/Dict_IDCal.txt -iexcode/IEX_dictionaries/Dict_IDCal_QP70.txt -iexcode/IEX_dictionaries/Dict_M0.txt -iexcode/IEX_dictionaries/Dict_M1.txt -iexcode/IEX_dictionaries/Dict_M3.txt -iexcode/IEX_dictionaries/Dict_Slit.txt -iexcode/IEX_dictionaries/Dict_TempDiode.txt -iexcode/IEX_dictionaries/DiodeResponsivityCurve -iexcode/IEX_dictionaries/DiodeResponsivityCurve_2 -iexcode/IEX_dictionaries/Flux_Curves.txt -iexcode/IEX_dictionaries/Flux_Curves_QP70.txt -iexcode/IEX_dictionaries/M0M1_positions.py -iexcode/IEX_dictionaries/calibrationToFix.txt -iexcode/IEX_dictionaries/mono_parameters.txt -iexcode/instruments/AD_utilities.py -iexcode/instruments/ARPES.py -iexcode/instruments/FMB_mirrors.py -iexcode/instruments/IEX_BL_config.py -iexcode/instruments/IEX_VPU.py -iexcode/instruments/IEX_VPU_backup.py -iexcode/instruments/IEX_cameras.py -iexcode/instruments/Kappa.py -iexcode/instruments/Kappa_det.py -iexcode/instruments/Lakeshore_335.py -iexcode/instruments/Logfile.py -iexcode/instruments/MPA.py -iexcode/instruments/Motors.py -iexcode/instruments/Octupole.py -iexcode/instruments/Scienta.py -iexcode/instruments/VLS_PGM.py -iexcode/instruments/__init__.py -iexcode/instruments/bakeout.py -iexcode/instruments/cfg.py -iexcode/instruments/conversions_constants.py -iexcode/instruments/current_amplifiers.py -iexcode/instruments/diagnostics.py -iexcode/instruments/electron_analyzer.py -iexcode/instruments/encoders.py -iexcode/instruments/files_and_folders.py -iexcode/instruments/hxp_mirrors.py -iexcode/instruments/kappa_angle_calcs.py -iexcode/instruments/m3r.py -iexcode/instruments/remote_controlers.py -iexcode/instruments/resolution.py -iexcode/instruments/s29_temp_cntl.py -iexcode/instruments/scalers.py -iexcode/instruments/scanRecord.py -iexcode/instruments/shutters.py -iexcode/instruments/slits.py -iexcode/instruments/spec_stuff.py -iexcode/instruments/staff.py -iexcode/instruments/storage_ring.py -iexcode/instruments/userCalcs.py -iexcode/instruments/utilities.py -iexcode/instruments/valves.py -iexcode/instruments/vortex.py -iexcode/instruments/xrays.py -iexcode/macros/ARPES_macros.py -iexcode/macros/BL_shutdown.py -iexcode/macros/ID_energy_calibration.py -iexcode/macros/Kappa_optimization.py -iexcode/macros/__init__.py -iexcode/macros/cam_macros.py -iexcode/macros/commissioning.py -iexcode/macros/quick_plot.py -iexcode/macros/start_of_the_week.py -iexcode/macros/start_up.py \ No newline at end of file diff --git a/iexcode.egg-info/dependency_links.txt b/iexcode.egg-info/dependency_links.txt deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/iexcode.egg-info/dependency_links.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/iexcode.egg-info/requires.txt b/iexcode.egg-info/requires.txt deleted file mode 100644 index d085ec32a16b7618473a4be6496a8ea5cd476dad..0000000000000000000000000000000000000000 --- a/iexcode.egg-info/requires.txt +++ /dev/null @@ -1,6 +0,0 @@ -matplotlib -numpy -scipy -h5py -netCDF4 -pyepics diff --git a/iexcode.egg-info/top_level.txt b/iexcode.egg-info/top_level.txt deleted file mode 100644 index 3dc2072e0b7c51426134239fbc2e3afd8f41a12f..0000000000000000000000000000000000000000 --- a/iexcode.egg-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -iexcode