diff --git a/build/lib/iexcode/init_Kapp.py b/build/lib/iexcode/init_Kapp.py deleted file mode 100644 index d0b32195c0745aa89403f7fcf0f0c09141342f8d..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/init_Kapp.py +++ /dev/null @@ -1,11 +0,0 @@ - -from iexcode.instruments.kappa import * -from iexcode.instruments.kappa_det import * -from iexcode.instruments.Kappa_Euler import * - -from iexcode.instruments.current_amplifiers import * -from iexcode.instruments.MPA import * -from iexcode.instruments.vortexs import * - - -from iexcode.instruments.spec_stuff import * diff --git a/build/lib/iexcode/init_staff.py b/build/lib/iexcode/init_staff.py deleted file mode 100644 index 7ea17bb7dde161ba943a77873cc9e1078ace74f1..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/init_staff.py +++ /dev/null @@ -1 +0,0 @@ -from iexcode.instruments.staff import * diff --git a/build/lib/iexcode/init_xrays.py b/build/lib/iexcode/init_xrays.py deleted file mode 100644 index 98461ccfd83b38d43373123ffd108cb0fe80cd60..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/init_xrays.py +++ /dev/null @@ -1,12 +0,0 @@ -from iexcode.instruments.get_all import * -from iexcode.instruments.diagnostics import * -from iexcode.instruments.FMB_mirrors import * -from iexcode.instruments.gate_valves import * -from iexcode.instruments.hxp_mirrors import * -from iexcode.instruments.IEX_VPU import * -from iexcode.instruments.m3r import * -from iexcode.instruments.slits import * -from iexcode.instruments.resolution import * -from iexcode.instruments.storage_ring import * -from iexcode.instruments.VLS_PGM import * -from iexcode.instruments.xrays import * \ No newline at end of file diff --git a/build/lib/iexcode/instruments/AD_utilites.py b/build/lib/iexcode/instruments/AD_utilites.py deleted file mode 100644 index 9828834bfa96f6d2cc63625a048394df22e343f8..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/AD_utilites.py +++ /dev/null @@ -1,347 +0,0 @@ -""" -General functions for dealing with Area Detectors and Cameras at 29ID - -work in progress need to redo -""" -############################################################################################################## -############################## General Area Detector ############################## -############################################################################################################## -import datetime -import re -from os import listdir,mkdir,chown,system,chmod -from os.path import join, isfile, exists, dirname -from time import sleep - -from epics import caget, caput -from iexcode.instruments.IEX_BL_config import * -from iexcode.instruments.files_and_folders import get_next_fileNumber - - -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=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_SaveFileSetup(ADplugin,mda,**kwargs): - """ - ADplugin = "29id_ps1:TIFF1:" which IOC and which filesaving plugin - (ADplugin=$(P)$(SavePlugin)) - uses to get the current MDA directory and then set the path to one up + /dtype - MDA_CurrentDirectory(scanIOC=None) - - **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",dirname(dirname(mda.filepath))) - kwargs.setdefault("subfolder",ADplugin.split(":")[-2][:-1]) - - kwargs.setdefault("prefix",ADplugin.split(":")[-2][:-1]) - extDict={"TIFF":".tif","HDF":"h5"} - 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=join(kwargs['userpath'],kwargs['subfolder'],'') - print("\nFolder: " + fpath) - if not (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:") - caput(kwargs["P"]+kwargs["R"]+"Acquire","Done",wait=True,timeout=5*60);sleep(.1) - 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:") - caput(kwargs["P"]+kwargs["R"]+"Acquire","Done",wait=True,timeout=5*60) - 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_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: - caput(kwargs["P"]+kwargs["R"]+"AcquireTime",kwargs["ExposureTime"]) - caput(kwargs["P"]+kwargs["R"]+"AcquireTime",kwargs["ExposureTime"]+.01) - - 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,mda,**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=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,mda, **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) - - AD_SaveFileSetup(ADplugin,**kwargs) - AD_ScanTrigger(ADplugin, **kwargs) - trigger=".T"+str(kwargs["detTrig"])+"PV" - scanPV=mda.ioc+"scan"+str(kwargs["scanDIM"]) - print("WARNING: you need to need to disable saving and clear the trigger by hand after the scan") - print("\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/AD_utilities.py b/build/lib/iexcode/instruments/AD_utilities.py index cfe1930890eddd5dc2bde59f1782aea8caa3d855..dde214f254b2fc7d5441fa50814a9ebd2f5a8a38 100644 --- a/build/lib/iexcode/instruments/AD_utilities.py +++ b/build/lib/iexcode/instruments/AD_utilities.py @@ -6,13 +6,15 @@ work in progress need to redo ############################################################################################################## ############################## General Area Detector ############################## ############################################################################################################## +import os import datetime import re -from os import listdir,mkdir,chown,system,chmod -from os.path import join, isfile, exists, dirname + 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 @@ -35,7 +37,7 @@ def AD_CurrentDirectory(ADplugin): else: Dir = SubDir SubDir=[] - FilePath=join(Dir,*SubDir,'') + FilePath=os.path.join(Dir,*SubDir,'') return FilePath def AD_prefix(ADplugin): @@ -55,12 +57,10 @@ def AD_EnableStats(ADplugin): caput(ADplugin+"ComputeCentroid","Yes") -def AD_SaveFileSetup(ADplugin,mda,**kwargs): +def AD_SaveFileSetup(ADplugin,**kwargs): """ ADplugin = "29id_ps1:TIFF1:" which IOC and which filesaving plugin (ADplugin=$(P)$(SavePlugin)) - uses to get the current MDA directory and then set the path to one up + /dtype - MDA_CurrentDirectory(scanIOC=None) **kwargs (defaults) scanIOC = BL_ioc() @@ -74,11 +74,10 @@ def AD_SaveFileSetup(ADplugin,mda,**kwargs): FileTemplate="%s%s_%4.4d."+ext; format for filename first %s = filepath, second %s = prefix """ - kwargs.setdefault("userpath",dirname(dirname(mda.filepath))) + kwargs.setdefault("userpath",os.path.dirname(iex.BL.mda.filepath())) kwargs.setdefault("subfolder",ADplugin.split(":")[-2][:-1]) kwargs.setdefault("prefix",ADplugin.split(":")[-2][:-1]) - extDict={"TIFF":".tif","HDF":"h5"} kwargs.setdefault("ext",ADplugin.split(":")[-2][:-1]) kwargs.setdefault("FileTemplate","%s%s_%4.4d."+kwargs["ext"]) @@ -87,9 +86,9 @@ def AD_SaveFileSetup(ADplugin,mda,**kwargs): if kwargs['debug']: print("kwargs: ",kwargs) - fpath=join(kwargs['userpath'],kwargs['subfolder'],'') + fpath=os.path.join(kwargs['userpath'],kwargs['subfolder'],'') print("\nFolder: " + fpath) - if not (exists(fpath)): + if not (os.path.exists(fpath)): fileNumber=1 else: fileNumber=get_next_fileNumber(fpath,kwargs["prefix"]) @@ -146,13 +145,13 @@ def AD_DoneSingleSave(ADplugin,**kwargs): Save -> Enable e.g. ADplugin="29id_ps2:TIFF1:" - **kwargs: + **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(.1) + AD_Done(ADplugin,**kwargs) caput(kwargs["P"]+kwargs["R"]+"ImageMode","Single");sleep(.5) caput(ADplugin+"EnableCallbacks","Enable");sleep(.1) @@ -165,17 +164,28 @@ def AD_FreeRun(ADplugin,**kwargs): e.g. ADplugin="29id_ps2:TIFF1:" - **kwargs: + **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) + 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): """ @@ -220,7 +230,7 @@ def AD_snap(ADplugin,**kwargs): -def AD_ScanTrigger(ADplugin,mda,**kwargs): +def AD_ScanTrigger(ADplugin,**kwargs): """ Add Triggering of AreaDetector to scanIOC ADplugin = "29idc_ps1:TIFF1:" (ADplugin=$(P)$(SavePlugin)) @@ -237,11 +247,11 @@ def AD_ScanTrigger(ADplugin,mda,**kwargs): kwargs.setdefault("R","cam1:") kwargs.setdefault("detTrig",2) - scanPV=mda.ioc+"scan"+str(kwargs["scanDIM"]) + 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,mda, **kwargs): +def ADplugin_ScanSetup(ADplugin, **kwargs): """ stop the acquisition, puts in ImageMode=Single enables saving @@ -274,7 +284,7 @@ def ADplugin_ScanSetup(ADplugin,mda, **kwargs): AD_SaveFileSetup(ADplugin,**kwargs) AD_ScanTrigger(ADplugin, **kwargs) trigger=".T"+str(kwargs["detTrig"])+"PV" - scanPV=mda.ioc+"scan"+str(kwargs["scanDIM"]) + 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+",'')") diff --git a/build/lib/iexcode/instruments/ARPES.py b/build/lib/iexcode/instruments/ARPES.py index 81517b4342da01fdff2c0ab7720bd2bcf545541b..ad8520546027f66b8f8505028761c9ebe115fc1c 100644 --- a/build/lib/iexcode/instruments/ARPES.py +++ b/build/lib/iexcode/instruments/ARPES.py @@ -1,13 +1,13 @@ -import numpy as np +import os 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.cameras import _enable_endstation_cameras -from iexcode.instruments.files_and_folders import check_run,make_user_folders,folder_mda +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 @@ -17,7 +17,8 @@ from iexcode.instruments.utilities import * from iexcode.instruments.userCalcs import userStringSeq_clear, userStringSeq_pvs from iexcode.instruments.Motors import Motors -from iexcode.instruments.current_amplifiers import * +from iexcode.instruments.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 @@ -44,18 +45,18 @@ def ARPES_init(*userName,**kwargs): """ kwargs.setdefault('scan_ioc',default_ioc) kwargs.setdefault('xrays',True) - kwargs.setdefault('BL_mode','user') + kwargs.setdefault('mode','user') kwargs.setdefault('set_folders',True) kwargs.setdefault('reset',True) #motors physical_motors = ['x','y','z','th','chi','phi'] - psuedo_motors = ['focus'] + pseudo_motors = ['focus'] global ARPES_Motors - ARPES_Motors = Motors('ARPES',_ARPES_motor_dictionary(),physical_motors,psuedo_motors) + ARPES_Motors = Motors('ARPES',_ARPES_motor_dictionary(),physical_motors,pseudo_motors) #endstation - iex.BL = Beamline_Config('ARPES',kwargs['scan_ioc'],kwargs['xrays'],kwargs['BL_mode'],ARPES_Motors) + 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 @@ -78,6 +79,10 @@ def ARPES_init(*userName,**kwargs): if EA.connected: 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") @@ -137,7 +142,7 @@ def _ARPES_motor_dictionary(): """ returns a dictionary with {name:[rbv,val,spmg,pv]} """ - + p = '29idc:m' motor_nums = {'x': 1, 'y':2, 'z':3, @@ -205,7 +210,7 @@ def folders_ARPES(user_name,**kwargs): #Set up Scienta folders: if EA.connected: - userPath = "/net/s29data/export/data_29id"+iex.BL.folder+"/"+run+"/"+user_name+"/" + userPath = path_dserv(iex.BL.folder,run,user_name) folders_EA(userPath,filePrefix="EA") else: print_warning_message("EA ioc is not running, h5 folder not set") @@ -257,29 +262,34 @@ 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 vals: - print(key+" = "+vals[key]) - print("-----------------------------------------------------------") + if verbose: + print("-----------------------------------------------------------") + for key in beamline_info: + print(key+" = "+beamline_info[key]) + print("-----------------------------------------------------------") + + if verbose: + print("\n===========================================================") return vals diff --git a/build/lib/iexcode/instruments/FMB_mirrors.py b/build/lib/iexcode/instruments/FMB_mirrors.py index d389584e9fa5f77bf7c8ba7ed5239158fc0d0cdf..1c92a07a48cf017e916e88b9ac1a7f0790747b5c 100644 --- a/build/lib/iexcode/instruments/FMB_mirrors.py +++ b/build/lib/iexcode/instruments/FMB_mirrors.py @@ -2,13 +2,12 @@ from time import sleep from epics import caget, caput -from iexcode.instruments.IEX_BL_config import * +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): +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 @@ -24,7 +23,7 @@ def FMB_mirror_status(mirror_num): status =1 when positioned """ ioc = '29id_'+['M0','M1','','M3R'][mirror_num]+":" - pv = FMB_mirror_ioc(mirror_num) + pv = _FMB_mirror_ioc(mirror_num) status=caget(pv+'SYSTEM_STS') return status @@ -33,7 +32,7 @@ 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) + pv = _FMB_mirror_ioc(mirror_num) rbv = round(caget(pv+axis+"_MON"),3) sp = round(caget(pv+axis+"_POS_SP"),3) @@ -47,12 +46,12 @@ def FMB_mirror_get(mirror_num,verbose=True): """ get and returns the current mirror position """ - axis_labels=['Tx','Ty','Tz','Rx','Ry','Rz'] + 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(rbv) + vals.append(round(rbv,3)) message =+ "%.3f"+"/" % rbv if verbose: print(message) @@ -68,7 +67,7 @@ def FMB_mirror_move(mirror_num,axis,val,verbose=True): "Previously: Move_M0M1 """ - pv = FMB_mirror_ioc(mirror_num) + pv = _FMB_mirror_ioc(mirror_num) axes = ['TX','TY','TZ','RX','RY','RZ'] if axis in axes: caput(pv+axis+"_SP.PREC",3) @@ -91,7 +90,7 @@ def FMB_mirror_move_all(mirror_num,position_list,verbose=True): "Previously: Move_M0M1 """ - pv = FMB_mirror_ioc(mirror_num) + pv = _FMB_mirror_ioc(mirror_num) for axis in ['TX','TY','TZ','RX','RY','RZ']: caput(pv+axis+"_SP.PREC",3) caput(pv+axis+"_POS_SP") @@ -114,7 +113,7 @@ def FMB_mirror_tweak(mirror_num,axis,val,verbose=False): "Previously: Move_M0M1 """ - pv = FMB_mirror_ioc(mirror_num) + 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) @@ -131,11 +130,11 @@ def FMB_mirror_scan(mirror_num,start,stop,step): TY = vertical RY = Pitch TZ = longitudinal RZ = Roll """ - pv = FMB_mirror_ioc(mirror_num) + pv = _FMB_mirror_ioc(mirror_num) # database sets .PREC==0. We want more digits than that. caput(pv+"_SP.PREC",3) - mda.fillin(pv+"_SP",pv+"_MON",start,stop,step) + iex.BL.mda.fillin(pv+"_SP",pv+"_MON",start,stop,step) diff --git a/build/lib/iexcode/instruments/IEX_VPU.py b/build/lib/iexcode/instruments/IEX_VPU.py index a408465c818289227dde89a14b50c71a33060379..45ddf3a2fceb35a290deafa7bfd69d96d9a1225e 100644 --- a/build/lib/iexcode/instruments/IEX_VPU.py +++ b/build/lib/iexcode/instruments/IEX_VPU.py @@ -1,23 +1,22 @@ - - +from os import path from math import * from time import sleep import numpy.polynomial.polynomial as poly from epics import caget, caput +from iexcode.instruments.userCalcs import userCalcOut_clear from iexcode.instruments.utilities import dateandtime, print_warning_message, read_dict -from iexcode.instruments.shutters import main_shutter_check_open from iexcode.instruments.VLS_PGM import mono_grating_get -from iexcode.instruments.userCalcs import userCalcOut_clear +from iexcode.instruments.shutters import main_shutter_open -IDcal_fpath="/home/beams22/29IDUSER/Documents/User_Macros/Macros_29id/IEX_Dictionaries/Dict_IDCal.txt" +IDcal_path="/home/beams22/29IDUSER/Documents/User_Macros/Macros_29id/IEX_Dictionaries" ############################################################################################################## ################################ ID limits and calibration ############################## ############################################################################################################## -def ID_calc_SP(mono_grating,ID_mode,hv_eV): # Mode = state (0=RCP,1=LCP,2=V,3=H) +def ID_calc_SP(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) @@ -28,7 +27,7 @@ def ID_calc_SP(mono_grating,ID_mode,hv_eV): # Mode = state (0=RCP,1=LCP,2=V,3 if type(ID_mode)== str: ID_state=ID_state_mode(ID_mode) try: - K=ID_coef(mono_grating,ID_state,hv_eV) + 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()) @@ -60,7 +59,7 @@ def ID_wait_for_permission(): ############################################################################################################## def ID_get_all(verbose=False): """ - returns dictionart with: ID_Mode, ID_QP_ratio, ID_SP, ID_RBV + returns dictionary with: ID_Mode, ID_QP_ratio, ID_SP, ID_RBV Previously: Get_energy """ @@ -157,51 +156,64 @@ def ID_ready(verbose=True): elif ((checkready=="Ready") and (RBV > 3.7)) and (checkbusy=="Busy"): caput("ID29:Busy.VAL",0) else: - break - if verbose: - print("ID Ready") + if verbose: + print("ID Ready") + return True -def ID_stop(verbose=True): +def ID_power_status(): """ - waits for the ID to be in user mode and then turns it off + gets if the ID power supplies are On or Off + """ + ID_OnOff=caget('ID29:Main_on_off.VAL') + if ID_OnOff == 1: + return 'Off' + elif ID_OnOff == 0: + return 'On' - Previously: ID_Stop +def ID_off(verbose=True): + """ + waits for permission then turns on the main coils OFF """ ID_wait_for_permission() caput("ID29:Main_on_off.VAL",1,wait=True,timeout=18000) - sleep(5) if verbose: print("ID is now off") -def ID_off(): +def ID_on(verbose=True): """ - calls ID_stop + waits for permission then turns on the main coils On """ - ID_stop() - + ID_wait_for_permission() + if verbose: + print("Starting ID - "+dateandtime()) + + caput("ID29:EnergySet.VAL",3.8) + caput("ID29:Main_on_off.VAL",0,wait=True,timeout=18000) -def ID_start(ID_mode='RCP'): +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(): + main_shutter_open() - """ - - ID_wait_for_permission() - #turning on the ID; default mode = RCP - print("Starting ID - "+dateandtime()) - caput("ID29:EnergySet.VAL",3.8) - caput("ID29:Main_on_off.VAL",0,wait=True,timeout=18000) - ID_ready() - ID_mode_set(ID_mode) - - ID_wait_for_permission() - main_shutter_check_open() - - print('ID is now on, please set your energy') + if verbose: + print('ID is now on, please set your energy') def ID_switch_mode(ID_mode): """ @@ -213,13 +225,13 @@ def ID_switch_mode(ID_mode): Previously Switch_IDMode """ ID_wait_for_permission() - main_shutter_check_open() + main_shutter_open() ID_state = ID_state_get() try: if ID_state_mode(ID_mode) != ID_state: print("Turning ID off...") - ID_stop(verbose=True) + ID_off(verbose=True) sleep(10) print("Switching ID mode, please wait...") @@ -265,24 +277,6 @@ def ID_rbv_get_eV(verbose=False): print("ID_RBV: ", ID_RBV) return ID_RBV -def ID_restart(): - """ - turns off the ID and turns it back on with the same set point - - Previously: ID_Restart - """ - ID_state = ID_state_get() - ID_mode = ID_mode_list()[ID_state] - hv = ID_SP_get_eV(verbose=False) - - print("Restarting ID", dateandtime()) - ID_stop(verbose=False) - ID_ready(verbose=False) - - ID_start(verbose=False) - - print("ID is back ON", dateandtime()) - ID_SP_set(hv) def ID_SP_set(hv_eV,verbose=True): """ @@ -290,48 +284,78 @@ def ID_SP_set(hv_eV,verbose=True): Previously: SetID_Raw """ + def _ID_write_SP_proc(keV): + caput("ID29:EnergyScanSet.VAL",keV,wait=True,timeout=18000) + sleep(0.5) + caput("ID29:EnergyScanSet.VAL",(keV+0.001),wait=True,timeout=18000) + caput('ID29:StartRamp.VAL',1) + + def _ID_bw_ok(ID_SP): + ID_bw = ID_SP*0.095 + ID_diff = abs(ID_rbv_get()-ID_SP) + if ID_diff > ID_bw: + return False + else: + return True + + #checking permissions and opening the main shutter ID_wait_for_permission() - main_shutter_check_open() + main_shutter_open() + #checking if desired is with allowed range, if not printing the nearest allowed value ID_max,ID_min = ID_energy_range() ID_SP=min(max(hv_eV,ID_min),ID_max)*1.0 - if hv_eV < ID_min or hv_eV > ID_max: message_string="Set point out of BL energy range \nPlease select a different energy." + message_string+="\nClosest allowed value is "+str(ID_SP) print_warning_message(message_string) else: + #desired energy is within range ID_SP_RBV=round(caget("ID29:EnergySet.VAL"),3)*1000 - if ID_SP == ID_SP_RBV: # checks if ID is already at the SP energy - ID_RBV=caget("ID29:EnergyRBV") + ID_RBV=caget("ID29:EnergyRBV") + if ID_SP == ID_SP_RBV: + #ID is already at the SP energy if verbose: print("ID SET : "+"%.1f" % ID_SP, "eV") print("ID RBV : "+"%.1f" % ID_RBV, "eV") print(caget('ID29:TableDirection',as_string=True)) + else: - caput("ID29:EnergyScanSet.VAL",ID_SP/1000,wait=True,timeout=18000) - sleep(0.5) - caput("ID29:EnergyScanSet.VAL",(ID_SP+0.001)/1000,wait=True,timeout=18000) - caput('ID29:StartRamp.VAL',1) - - sleep(5) - ID_ready(verbose=False) - - ID_RBV=caget("ID29:EnergyRBV") - print("\nID SET : "+"%.1f" % ID_SP, "eV") - print("ID RBV : "+"%.1f" % ID_RBV, "eV") - print(caget('ID29:TableDirection',as_string=True)) - - ID_diff = abs(ID_RBV-ID_SP) - ID_bw = ID_SP*0.095 - if ID_diff > ID_bw: - sleep(20) - ID_RBV=caget("ID29:EnergyRBV") - ID_diff = abs(ID_RBV-ID_SP) - print("\nID RBV : "+"%.1f" % ID_RBV, "eV") - if ID_diff > ID_bw: - ID_restart - -def ID_energy_set(hv_eV): + # ID not at energy + ready = ID_ready(verbose=False) + if ready: + #set the energy + _ID_write_SP_proc(ID_SP/1000) + + while not ID_ready(verbose=False): + sleep(20) + + #is ID within some bandwidth + if _ID_bw_ok(ID_SP) == False: + sleep(20) + if _ID_bw_ok(ID_SP) == False: + print("\nID RBV : "+"%.1f" % ID_RBV, "eV") + ID_start(ID_mode_get()) + if ID_ready(verbose=False): + #set the energy + _ID_write_SP_proc(ID_SP/1000) + + if verbose: + print("\nID SET : "+"%.1f" % ID_SP, "eV") + print("ID RBV : "+"%.1f" % ID_RBV, "eV") + print(caget('ID29:TableDirection',as_string=True)) + + if ID_QP_ratio_get()[0] < 100: + #check ratio + Byq=caget("ID29:ByqRdbk") + Vcoil=caget("ID29:ByRdbk.VAL") + ratio=Byq/Vcoil + ratio_RBV=caget("ID29:QuasiRatio.RVAL") + if verbose: + print("QP ratio =", round(ratio,3)*100,"%") + print("QP RBV =", ratio_RBV,"%") + +def ID_energy_set(hv_eV,QP_ratio=None): """ Sets optimum ID set point for hv(eV) (max intensity) and opens the main shutter @@ -342,9 +366,8 @@ def ID_energy_set(hv_eV): """ ID_mode = ID_mode_list()[ID_state_get()] mono_grating = mono_grating_get() - ID_SP = ID_calc_SP(mono_grating,ID_mode,hv_eV) - - ID_SP(hv_eV) + ID_SP = ID_calc_SP(mono_grating,ID_mode,hv_eV,QP_ratio) + ID_SP_set(ID_SP) def ID_QP_ratio_get(verbose=True): @@ -352,7 +375,6 @@ def ID_QP_ratio_get(verbose=True): gets the read back for the QP ratio calculate the QP ratio - """ Byq=caget("ID29:ByqRdbk") Vcoil=caget("ID29:ByRdbk.VAL") @@ -367,38 +389,36 @@ def ID_QP_ratio_get(verbose=True): print_warning_message(message_string) return ratio_RBV, ratio_calc -def ID_QP_mode_set(ID_mode,QP_ratio): +def ID_QP_mode_set(QP_ratio=None,verbose=True): """ switched to QP mode, if not currently in - sets the QP ratio (QP ration min is 70) and polarization (ID mode) + sets the QP ratio (QP ratio min is 70) and polarization (ID mode) - does not set the energy, need to use ID_SP + 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=max(70,QP_ratio) - - ratio_RBV, ratio_calc=ID_QP_ratio_get() - if ratio_RBV != QP_ratio: - ID_stop() - caput("ID29:QuasiRatioIn.C",QP_ratio) - - ID_start(ID_mode) - sleep(15) - Byq=caget("ID29:ByqRdbk") - Vcoil=caget("ID29:ByRdbk.VAL") - ratio=Byq/Vcoil - ratio_RBV=caget("ID29:QuasiRatio.RVAL") - print("QP ratio =", round(ratio,3)*100,"%") - print("QP RBV =", ratio_RBV,"%") - sleep(15) + 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) + + ID_on() + sleep(15) -def ID_coef(grt,ID_state,hv_eV): # Mode = state (0=RCP,1=LCP,2=V,3=H); + +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). @@ -408,6 +428,9 @@ def ID_coef(grt,ID_state,hv_eV): # Mode = state (0=RCP,1=LCP,2=V,3=H); Previously: ID_Coef """ + if QP_ratio == None: + QP_ratio = ID_QP_ratio_get()[0] + 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]): @@ -421,12 +444,26 @@ def ID_coef(grt,ID_state,hv_eV): # Mode = state (0=RCP,1=LCP,2=V,3=H); index = [i for (i, x) in enumerate(B) if x > 0] #print(index) return(index[0]) + + + if QP_ratio < 100: + 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") + print("Unable to read dictionary "+dictfile+" ; "+error_msg) try: Lrange = ListRange(grt,ID_state,ID_function) @@ -435,11 +472,8 @@ def ID_coef(grt,ID_state,hv_eV): # Mode = state (0=RCP,1=LCP,2=V,3=H); return K except KeyError: - print("WARNING: PLease select one of the following:") - print(" mode 0 = RCP") - print(" mode 1 = LCP") - print(" mode 2 = V") - print(" mode 3 = H") + print("WARNING: PLease select one of the following: "+str(ID_mode_list())) + def ID_scan_pvs(): """ diff --git a/build/lib/iexcode/instruments/IEX_endstations.py b/build/lib/iexcode/instruments/IEX_endstations.py deleted file mode 100644 index d937acd2c0cb91391b64a2167ff90bfad4772649..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/IEX_endstations.py +++ /dev/null @@ -1,154 +0,0 @@ -from iexcode.instruments.scanRecord import ScanRecord -from iexcode.instruments.utilities import print_warning_message - -import iexcode.instruments.cfg as iex - -""" -Endstation class is used to contain information about ioc, branch, mode - -it makes the default stuff work - -this will prompt for the endstation and will set the default parameters, look at the -init kwargs to see which defaults you can change. -""" -#For new endstation modify here: -endstations_list = ['ARPES','Kappa'] - -class Endstation: - """ - used for defining which endstation in which you are running - for short names and ioc info - - BL = Endstation('ARPES') - BL.endstaton: name of endstation ("ARPES" / "Kappa" / "Octupole") - - BL.ioc: string of scan ioc ('29idb:', '29idTest:') - BL.mda: scanRecord object of ioc specified by .ioc - - BL.xrays: True/False, used for detectors and shutter check - BL.mode: 'user' / 'staff', used for detectors and to specifiy folder - - BL.folder: shorthand for where data is save and used for saveData structure ('b','c','d') - BL.prefix: mda prefix (set by endstation) - - BL.log: object of log class which holds logging info - - """ - - def __init__(self,endstation_name,scan_ioc,xrays,BL_mode,Motors=None,**kwargs): - """ - intializes the several beamline variables - - endstation_name = 'ARPES' / 'Kappa' - - BL = Endstation() - BL.endstation => endstation_name - BL.branch => BL branch 'c' or 'd' only (used for shutter checks) - BL.xrays => True/False - BL.mode => 'user'/'staff' previously: BL_Mode_Set - BL.folder => 'b','c','d' - BL.prefix => 'ARPES_','Kappa_' - BL.ioc => previously: BL_ioc() - BL.Motors => motor calls - BL.safe_state => function to put endstation in a 'safe state' - BL.endstation_get => function to return endstation status - - Note intialization does not set default detectors and logging for .mda - - """ - - self.endstation = None - self.branch = None - self.ioc = scan_ioc - self.folder = None - self.prefix = None - - self.mode = None - self.xrays = xrays - - self.mda = ScanRecord(scan_ioc) - self.Motors = Motors - - self.safe_state = None - self.endstation_get = None - - BL_mode_list = ['user','staff'] - - if endstation_name in endstations_list: - self.endstation=endstation_name - else: - print('Not a valid Endstation choice') - print('Endstations: '+endstations_list) - return - - - if BL_mode in BL_mode_list: - - self.mode = BL_mode - if BL_mode == 'user': - #For new endstation modify here: - if endstation_name == 'ARPES': - self.folder = 'c' - self.prefix = 'ARPES_' - self.branch = 'c' - elif endstation_name == 'Kappa': - self.folder = 'd' - self.prefix = 'Kappa_' - self.branch = 'd' - #elif endstation_name == 'Octupole': - #self.folder = 'e' - self.branch = 'd' - else: - print('folder and prefix not set') - - elif BL_mode == 'staff': - #overwrite folder for staff mode - self.folder = 'b' - self.prefix = endstation_name+"_" - else: - message = 'Not a valid BL_mode choice\n' - message += 'BL_modes: '+BL_mode_list - print_warning_message(message) - return - - if 'safe_state' in kwargs: - self.safe_state = kwargs['safe_state'] - if 'endstation_get' in kwargs: - self.endstation_get = kwargs['endstation_get'] - - -############################################################################################################## -############################## BL commands ############################## -############################################################################################################## -def BL_ioc(): - """ - returns the ioc from the Endstation instance - """ - return iex.BL.ioc - -def BL_branch(): - """ - returns the branch from the Endstation instance - """ - return iex.BL.branch - -def BL_mode(): - """ - returns the beamline mode, User / Staff / No_Xray - """ - return iex.BL.mode - -def BL_mda_prefix(): - """ - returns the mda file prefix - """ - return iex.BL.prefix - -def BL_mda_filepath(): - """ - returns the mda file prefix - """ - return iex.BL.filepath - -############################################################################################################## - diff --git a/build/lib/iexcode/instruments/Kappa.py b/build/lib/iexcode/instruments/Kappa.py index 1789225b713f8f1dfea19bff493f862f819a2711..86a4a841af608eb0a9cedfbf4e6f16f6aac2a2bb 100644 --- a/build/lib/iexcode/instruments/Kappa.py +++ b/build/lib/iexcode/instruments/Kappa.py @@ -1,3 +1,4 @@ +from json import detect_encoding import numpy as np from time import sleep from math import floor @@ -27,15 +28,18 @@ 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 +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): +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) + 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 @@ -47,18 +51,18 @@ def Kappa_init(*userName,**kwargs): """ kwargs.setdefault('scan_ioc',default_ioc) kwargs.setdefault('xrays',True) - kwargs.setdefault('BL_mode','user') + kwargs.setdefault('mode','user') kwargs.setdefault('set_folders',True) kwargs.setdefault('reset',True) #motors physical_motors = ['x','y','z','tth','kth','kap','kphi'] - psuedo_motors = ['th','chi','phi'] - global Kappa_Motors - Kappa_Motors = Motors('Kappa',_Kappa_motor_dictionary(),physical_motors,psuedo_motors) + 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['BL_mode'],Kappa_Motors) + iex.BL = Beamline_Config('kappa',kwargs['scan_ioc'],kwargs['xrays'],kwargs['mode'],kappa_Motors) #setting folders if kwargs['set_folders']: @@ -70,36 +74,36 @@ def Kappa_init(*userName,**kwargs): else: user_name = userName[0] print(user_name) - folders_Kappa(user_name,**kwargs) + folders_kappa(user_name,**kwargs) #update for default scanRecord advanced parameters - iex.BL.mda.log('Kappa',user_name,_Kappa_log_header(),_Kappa_log_entries) + iex.BL.mda.log('kappa',user_name,_kappa_log_header(),_kappa_log_entries) #global detectors - global tey,d3,d4,mesh,Kappa_scaler_pv,tth_pv,tthdet + 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] + kappa_scaler_pv = '29idMZ0:scaler1.CNT' + tth_pv = _kappa_motor_dictionary('tth')[3] iex.mpa = MPA() - tthdet = Kappa_Detector(Kappa_Motors) + tthdet = Kappa_Detector(kappa_Motors) #resetting everything if kwargs['reset']: - Kappa_reset(**kwargs) + kappa_reset(**kwargs) #enable cameras _enable_endstation_cameras() - print ('Kappa initalized') + 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 + return tey,d3,d4,mesh,kappa_scaler_pv,tth_pv,tthdet ############################################################################################################## ############################## detectors and motors ############################## ############################################################################################################## -def _Kappa_detector_list(): +def _kappa_detector_list(): """ list of detectors to trigger @@ -109,7 +113,7 @@ def _Kappa_detector_list(): return ca_list -def _Kappa_detector_dictionary(**kwargs): +def _kappa_detector_dictionary(**kwargs): """ returns a dictionary of the default detectors @@ -121,9 +125,11 @@ def _Kappa_detector_dictionary(**kwargs): kwargs.setdefault('add_vortex',False) det_dict={} vortex={ - 15:"", 16:"", 17:"", + 49:"", + 50:"", + } sample_temp={ 23:"29idd:LS331:TC1:SampleA", @@ -182,11 +188,11 @@ def _Kappa_detector_dictionary(**kwargs): return det_dict -def _Kappa_motor_dictionary(name): +def _kappa_motor_dictionary(name): """ motor_dictionary = {name:[rbv,val,spmg,pv]} for physical and psuedo/Euler motors usage: - KappaS_PVmotor('x') => ['29idKappa:m2.RBV', '29idKappa:m2.VAL', '29idKapp:m2.SPMG','29idKappa:m2'] + kappa_PVmotor('x') => ['29idKappa:m2.RBV', '29idKappa:m2.VAL', '29idKapp:m2.SPMG','29idKappa:m2'] """ motor_nums={ 'x':2, @@ -213,7 +219,7 @@ def _Kappa_motor_dictionary(name): return motor_dictionary -def Kappa_extra_pvs(): +def kappa_extra_pvs(): """ used to get the PV associated with a given pnuemonic @@ -227,17 +233,17 @@ def Kappa_extra_pvs(): } return d -def Kappa_kth_offset_get(): +def kappa_kth_offset_get(): caget("29idKappa:userCalcOut1.G") -def Kappa_kth_offset_set(val): +def kappa_kth_offset_set(val): caput("29idKappa:userCalcOut1.G",val) ############################################################################################################# ############################## setting folder ############################## ############################################################################################################## -def folders_Kappa(user_name,**kwargs): +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()" @@ -268,7 +274,7 @@ def folders_Kappa(user_name,**kwargs): # 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()) + #logfile_header(iex.BL.endstation,iex.BL.ioc,kappa_log_header()) # Set up SPEC folder: @@ -279,9 +285,9 @@ def folders_Kappa(user_name,**kwargs): #resetting if 'reset': - Kappa_reset() + kappa_reset() -def Kappa_reset(): +def kappa_reset(): """ resets scanRecord, current amplifiers, mono limits and lakeshore """ @@ -289,18 +295,19 @@ def Kappa_reset(): 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() + 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 current amplifiers + #resetting the MPA ROIs if iex.BL.xray: - ca_reset_all() + mpa_ROI_reset() + #resetting mono and anyother beamline stuff if iex.BL.xrays: @@ -319,58 +326,61 @@ def Kappa_reset(): ############################################################################################################## ############################## get all ############################## ############################################################################################################## -def Kappa_get_all(verbose=True): +def kappa_get_all(verbose=True): """ - returns a dictionary with the current status of the Kappa endstation and exit slit + 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() + motor_dictionary = _kappa_motor_dictionary() for motor in motor_dictionary.keys(): - vals[motor]=Kappa_Motors.get(motor,verbose=False) - + vals[motor]=kappa_Motors.get(motor,verbose=False) #endstation/branch pvs - extra_pvs = Kappa_extra_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) - - mesh.get() - vals.update({'mesh':mesh.current_Amp}) - - if verbose: - print("-----------------------------------------------------------") - for key in vals: - print(key+" = "+vals[key]) - print("-----------------------------------------------------------") + if verbose: + print("-----------------------------------------------------------") + for key in beamline_info: + print(key+" = "+vals[key]) + print("-----------------------------------------------------------") + if verbose: + print("\n===========================================================") return vals ############################################################################################################## ############################## logging ############################## ############################################################################################################## -def _Kappa_log_header(): +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} + header_list = {'kappa':h} return header_list -def _Kappa_log_entries(): +def _kappa_log_entries(): """ enstation info for log file Previously: scanlog """ - vals = Kappa_get_all(verbose=False) + vals = kappa_get_all(verbose=False) x = vals['x'] y = vals['y'] z = vals['z'] @@ -395,9 +405,9 @@ def _Kappa_log_entries(): return entry_list,pv_list,format_list ############################################################################################################## -############################## Kappa scanRecord ############################## +############################## kappa scanRecord ############################## ############################################################################################################## -def _Kappa_scan_before_sequence(scan_ioc,scan_dim,**kwargs): +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 @@ -424,7 +434,7 @@ def _Kappa_scan_before_sequence(scan_ioc,scan_dim,**kwargs): return before_scan_proc -def _Kappa_scan_after_sequence(scan_ioc,scan_dim,**kwargs): +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 @@ -468,13 +478,13 @@ def _Kappa_scan_after_sequence(scan_ioc,scan_dim,**kwargs): 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") + #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 ??? +def _kappa_detector_triggers_sequence(scan_ioc,scan_dim,**kwargs): # do we need to add 29idb:ca5 ??? """ """ kwargs.setdefault(seq_num,8) @@ -484,14 +494,14 @@ def _Kappa_detector_triggers_sequence(scan_ioc,scan_dim,**kwargs): # do we ne #clear the userStringSeq userStringSeq_clear(scan_ioc,seq_num=kwargs['seq_num']) - caput(detector_triggers_pv+".DESC","Kappa_Trigger1") + caput(detector_triggers_pv+".DESC","kappa_Trigger1") - scaler_pv = Kappa_scaler_pv() + 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_detector_list() + ca_list = _kappa_detector_list() last = len(ca_list) for i,ca in enumerate(ca_list): ca_pv = _Keithley_pv(ca[0], ca[1])+':read.PROC CA NMS' @@ -500,12 +510,12 @@ def _Kappa_detector_triggers_sequence(scan_ioc,scan_dim,**kwargs): # do we ne return detector_triggers_proc -def _Kappa_trigger_dictionary(scan_ioc,scan_dim,**kwargs): +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), + 1:_kappa_detector_triggers_sequence(scan_ioc,scan_dim,**kwargs), } return trigger_dictionary @@ -513,17 +523,17 @@ def _Kappa_trigger_dictionary(scan_ioc,scan_dim,**kwargs): ############################################################################################################## -############################## Kappa Motor Scan Set Up ############################## +############################## kappa Motor Scan Set Up ############################## ############################################################################################################## -def Kappa_sample_Euler_list(): +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(): +def kappa_4c_mprint(): """ returns the dictionary of the current sample position in 4c units @@ -532,26 +542,26 @@ def Kappa_4c_mprint(): Previously: diffracto? """ positions={} - motors=Kappa_sample_Euler_list() + motors=kappa_sample_Euler_list() for motor in motors: - positions.update(motor,_Kappa_motor_dictionary()(motor)[0]) + positions.update(motor,_kappa_motor_dictionary()(motor)[0]) return positions -def Kappa_4c_move(th_chi_phi_list): +def kappa_4c_move(th_chi_phi_list): """ moves the sample in 4c (Euler) units Previously: mv4C """ - motor_list=Kappa_sample_Euler_list() + motor_list=kappa_sample_Euler_list() for motor,i in enumerate(motor_list): - Kappa_Motors.move(motor,motor_list[i],wait=True,verbose=False) + kappa_Motors.move(motor,motor_list[i],wait=True,verbose=False) for motor,i in enumerate(motor_list): - Kappa_Motors.get(motor,verbose=True) + kappa_Motors.get(motor,verbose=True) def _SmarAct_motor_list(): """ - returns a list of the motor names for the SmarAct motors in the Kappa + returns a list of the motor names for the SmarAct motors in the kappa """ return ['x','y','z'] @@ -561,7 +571,7 @@ def _SmarAct_motors_home(): Previously: Home_SmarAct_Motor """ - motor_dictionary = _Kappa_motor_dictionary() + motor_dictionary = _kappa_motor_dictionary() for motor in _SmarAct_motor_list(): pv = motor_dictionary[motor][3] caput(pv+'.HOMF',1) @@ -569,25 +579,25 @@ def _SmarAct_motors_home(): print('SamrAct motors VAL homed') def _SmarAct_enable(): - motor_dictionary = _Kappa_motor_dictionary() + 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() + 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 + 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() + motor_dictionary = _kappa_motor_dictionary() for motor in _PI_motor_list(): val_pv = motor_dictionary[motor][1] rbv_pv = motor_dictionary[motor][0] @@ -606,12 +616,12 @@ def Euler_motors_sync(): caput('29idKappa:Kappa_sync.PROC',1) print('Euler motors VAL/RBV synced to physical motors') -def Kappa_kphi_reset_zero(val): +def kappa_kphi_reset_zero(val): """ resets the zero for the kphi motor """ - kphi_pv = _Kappa_motor_dictionary()['kphi'][3] + kphi_pv = _kappa_motor_dictionary()['kphi'][3] caput(kphi_pv+".SET",1) # 1 = Set sleep(0.5) caput("kphi_pv.VAL",val) @@ -619,7 +629,7 @@ def Kappa_kphi_reset_zero(val): caput(kphi_pv+".SET",0) # 0 = Use print("\nkphi has been reset to " +str(val)) -def Kappa_tth_reset_zero(): +def kappa_tth_reset_zero(): """ resets the zero for the tth motor """ @@ -664,9 +674,9 @@ def th2th_scan_sensitivity(th_table,gain_num_table,gain_unit_table,**kwargs): else: detector = kwargs['detector'] - kth_offset = Kappa_kth_offset_get() + kth_offset = kappa_kth_offset_get() - motor_dictionary = _Kappa_motor_dictionary() + 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'] @@ -690,7 +700,7 @@ def th2th_scan_sensitivity(th_table,gain_num_table,gain_unit_table,**kwargs): 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)") + print(" Clear_Scan_Positioners('kappa',1)") scaler_cts(kwargs['cts'],verbose=False) if kwargs['execute']: @@ -700,7 +710,7 @@ def th2th_scan_sensitivity(th_table,gain_num_table,gain_unit_table,**kwargs): iex.BL.mda.table_reset_after(**kwargs) scaler_cts(verbose=False) -def scan_th2th(tth_start,tth_stop,tth_step,th_offset,**kwargs): +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 @@ -722,9 +732,10 @@ def scan_th2th(tth_start,tth_stop,tth_step,th_offset,**kwargs): 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'] + 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) @@ -738,36 +749,44 @@ def scan_th2th(tth_start,tth_stop,tth_step,th_offset,**kwargs): #clean up after scan scaler_cts(verbose=False) - -def th2th_table(tth_table,th0,**kwargs): +def dscanth2th(tth_start_rel,tth_stop_rel,tth_step,th_offset,**kwargs): """ - Create a table for tth, e.g.: - mytable_tth=[] - for q in range(2,41,1): - mytable_tth.append(q) - print(mytable_tth) - - th0 = th value at grazing incidence - cts = counting time (default is 1s) - + 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_table + 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+th0 - - th_val,th_rbv,th_spmg,th_pv = _Kappa_motor_dictionary['th'] - tth_val,tth_rbv,tth_spmg,tth_pv = _Kappa_motor_dictionary['tth'] + + 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) @@ -791,22 +810,22 @@ def th2th_table(tth_table,th0,**kwargs): ############################################################################################################# ############################## Preset Positions ############################## ############################################################################################################## -def _KappaTransfer_StrSeq(): +def _kappaTransfer_StrSeq(): #User= [ DESC, x, y, z, tth, kth, kap, kphi] - User = ["Kappa Transfer",0, -2650, -650, 0, 57, 0, -88] + User = ["kappa Transfer",0, -2650, -650, 0, 57, 0, -88] n=4 - _KappaPreset_StrSeq(n,User) + _kappaPreset_StrSeq(n,User) -def _KappaGrazing_StrSeq(): #Need to determine positions and then add to the Kappa graphic +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] + User = ["kappa Grazing",0, 0, 0, 0, 57.045, 134.76,57.045] n=3 - _KappaPreset_StrSeq(n,User) + _kappaPreset_StrSeq(n,User) -def Kappa_ResetPreset(): - _KappaGrazing_StrSeq() - _KappaTransfer_StrSeq() +def kappa_ResetPreset(): + _kappaGrazing_StrSeq() + _kappaTransfer_StrSeq() @@ -820,7 +839,7 @@ def Kappa_ResetPreset(): ############################################################################################################## ############################## Kappa light ############################## ############################################################################################################## -def Kappa_light(ON_OFF): +def kappa_light(ON_OFF): """ Previously:light """ @@ -836,11 +855,11 @@ def Kappa_light(ON_OFF): ############################################################################################################## ######################## Scan Temp and Pressure ############################## ############################################################################################################## -def Kappa_temperature_pressure_scan(scan_dim=1): +def kappa_temperature_pressure_scan(scan_dim=1): """ starts scan to monitor temperature and pressure in the kappa chamber - Previously: Kappa_ScanTempPres + Previously: kappa_ScanTempPres """ pv="29id"+iex.BL.mda.ioc+":scan"+str(scan_dim) @@ -856,9 +875,9 @@ def Kappa_temperature_pressure_scan(scan_dim=1): ############################################################################################################## -############################## Kappa safestate ############################## +############################## kappa safestate ############################## ############################################################################################################## -def Kappa_safe_state(**kwargs): +def kappa_safe_state(**kwargs): """ puts the C-branch in a safe state, **kwargs @@ -883,4 +902,26 @@ def Kappa_safe_state(**kwargs): branch_valve_close() - \ No newline at end of file +### 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_Euler.py b/build/lib/iexcode/instruments/Kappa_Euler.py deleted file mode 100644 index 20d6047e8ba685bb504e3b5aa26981029a7cdeda..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/Kappa_Euler.py +++ /dev/null @@ -1,120 +0,0 @@ -import numpy as np -from epics import caget, caput - -from iexcode.instruments.userCalcs import userCalcOut_clear -from iexcode.instruments.IEX_BL_config import * -from iexcode.instruments.userCalcs import userCalcOut_clear - -#### Obsolete? - -def Bragg_Index_CalcOut(d,eV,th): - n=8 - userCalcOut_pv = userCalcOut_clear(mda,n) - - h=4.135667516e-15 - c=299792458 - f=h*c*1e9*10 - - caput(userCalcOut_pv+".DESC","Bragg_Index") - caput(userCalcOut_pv+".A",d) - caput(userCalcOut_pv+".B",th) - caput(userCalcOut_pv+".C",eV) - caput(userCalcOut_pv+".D",np.pi) - caput(userCalcOut_pv+".E",f) - caput(userCalcOut_pv+".CALC$","SIN(B*D/"+str(180)+")*"+str(2)+"*A*C/E") - - - -def KtoE_th_CalcOut(): - n=1 - userCalcOut_pv = userCalcOut_clear(mda,n) - - caput(userCalcOut_pv+".DESC","KtoE_th") - caput(userCalcOut_pv+".INPA","29idKappa:m8.RBV CP NMS") #A=kth - caput(userCalcOut_pv+".INPB","29idKappa:m7.RBV CP NMS") #B=kap - caput(userCalcOut_pv+".INPC","29idKappa:m1.RBV CP NMS") #C=kphi - caput(userCalcOut_pv+".D",3.141592653589793) - caput(userCalcOut_pv+".E",180) - caput(userCalcOut_pv+".F",50) - caput(userCalcOut_pv+".H",57.045) - caput(userCalcOut_pv+".CALC$","((A-(G-H))*D/E-ATAN(TAN(B*D/E/2.0)*COS(F*D/E)))*E/D") - caput(userCalcOut_pv+".DOPT",0) # Use CAL - -def KtoE_chi_CalcOut(): - n=2 - userCalcOut_pv = userCalcOut_clear(mda,n) - - caput(userCalcOut_pv+".DESC","KtoE_chi") - caput(userCalcOut_pv+".INPA","29idKappa:m8.RBV CP NMS") #A=kth - caput(userCalcOut_pv+".INPB","29idKappa:m7.RBV CP NMS") #B=kap - caput(userCalcOut_pv+".INPC","29idKappa:m1.RBV CP NMS") #C=kphi - caput(userCalcOut_pv+".D",3.141592653589793) - caput(userCalcOut_pv+".E",180) - caput(userCalcOut_pv+".F",50) - caput(userCalcOut_pv+".CALC$","(2*ASIN(SIN(B*D/E/2.0) * SIN(F*D/E)))*E/D") - caput(userCalcOut_pv+".DOPT",0) # Use CAL - -def KtoE_phi_CalcOut(): - n=3 - userCalcOut_pv = userCalcOut_clear(mda,n) - - caput(userCalcOut_pv+".DESC","KtoE_phi") - caput(userCalcOut_pv+".INPA","29idKappa:m8.RBV CP NMS") #A=kth - caput(userCalcOut_pv+".INPB","29idKappa:m7.RBV CP NMS") #B=kap - caput(userCalcOut_pv+".INPC","29idKappa:m1.RBV CP NMS") #C=kphi - caput(userCalcOut_pv+".D",3.141592653589793) - caput(userCalcOut_pv+".E",180) - caput(userCalcOut_pv+".F",50) - caput(userCalcOut_pv+".CALC$","(C*D/E-ATAN(TAN(B*D/E/2.0)*COS(F*D/E)))*E/D") - caput(userCalcOut_pv+".DOPT",0) # Use CAL - - - - -def EtoK_kth_CalcOut(): - n=4 - userCalcOut_pv = userCalcOut_clear(mda,n) - - caput(userCalcOut_pv+".DESC","EtoK_kth") - caput(userCalcOut_pv+".INPA","29idKappa:userCalcOut1.VAL CP NMS") #A=th - caput(userCalcOut_pv+".INPB","29idKappa:userCalcOut2.VAL CP NMS") #B=chi - caput(userCalcOut_pv+".INPC","29idKappa:userCalcOut3.VAL CP NMS") #C=phi - caput(userCalcOut_pv+".D",3.141592653589793) - caput(userCalcOut_pv+".E",180) - caput(userCalcOut_pv+".F",50) - caput(userCalcOut_pv+".CALC$","(A*D/E-ASIN(-TAN(B*D/E/2.0)/TAN(F*D/E)))*E/D") - caput(userCalcOut_pv+".DOPT",0) # Use CAL - -def EtoK_kap_CalcOut(): - n=5 - userCalcOut_pv = userCalcOut_clear(mda,n) - - caput(userCalcOut_pv+".DESC","EtoK_kap") - caput(userCalcOut_pv+".INPA","29idKappa:userCalcOut1.VAL CP NMS") #A=th - caput(userCalcOut_pv+".INPB","29idKappa:userCalcOut2.VAL CP NMS") #B=chi - caput(userCalcOut_pv+".INPC","29idKappa:userCalcOut3.VAL CP NMS") #C=phi - caput(userCalcOut_pv+".D",3.141592653589793) - caput(userCalcOut_pv+".E",180) - caput(userCalcOut_pv+".F",50) - caput(userCalcOut_pv+".CALC$","((2*ASIN(SIN(B*D/E/2.0) / SIN(F*D/E))))*E/D") - caput(userCalcOut_pv+".DOPT",0) # Use CAL - -def EtoK_kphi_CalcOut(): - n=6 - userCalcOut_pv = userCalcOut_clear(mda,n) - - caput(userCalcOut_pv+".DESC","EtoK_kphi") - caput(userCalcOut_pv+".INPA","29idKappa:userCalcOut1.VAL CP NMS") #A=th - caput(userCalcOut_pv+".INPB","29idKappa:userCalcOut2.VAL CP NMS") #B=chi - caput(userCalcOut_pv+".INPC","29idKappa:userCalcOut3.VAL CP NMS") #C=phi - caput(userCalcOut_pv+".D",3.141592653589793) - caput(userCalcOut_pv+".E",180) - caput(userCalcOut_pv+".F",50) - caput(userCalcOut_pv+".CALC$","(C*D/E-ASIN(-TAN(B*D/E/2.0)/TAN(F*D/E)))*E/D") - caput(userCalcOut_pv+".DOPT",0) # Use CAL - - - - - - diff --git a/build/lib/iexcode/instruments/Kappa_det.py b/build/lib/iexcode/instruments/Kappa_det.py index 5c3e502e2c64d05d6b78c457c187c29a1eddc9e6..5ea9e9e8f9f10625ad1cb901a8f28125d8688b9c 100644 --- a/build/lib/iexcode/instruments/Kappa_det.py +++ b/build/lib/iexcode/instruments/Kappa_det.py @@ -7,14 +7,15 @@ from epics import caget, caput ################################ Kappa detector class ############################## ############################################################################################################## det_set_pv = '29idKappa:det:set' -det_list = 'd3', 'd4', 'mcp', 'apd', 'yag' +det_list = ['d3', 'd4', 'mcp', 'apd', 'yag'] class Kappa_Detector: """ class for Kappa detector """ - def __init__(self,Kappa_Motors): + def __init__(self,kappa_Motors): + self.motors = kappa_Motors self.get() def get(self): @@ -26,7 +27,7 @@ class Kappa_Detector: #det_name = caget('29idKappa:userStringSeq6.STR1') det_name = caget(det_set_pv) self.name = det_name - tth_val = Kappa_Motors.get('tth') + tth_val = self.motors.get('tth') return self.name, tth_val def set(self,det_name,move=True): @@ -42,22 +43,22 @@ class Kappa_Detector: yag: yag 'fluorescence screen' """ #get current value for tth - tth_val = Kappa_Motors.get('tth') + tth_val = self.motors.get('tth') #change det if det_name in det_list: caput(det_set_pv,det_name) if move: - Kappa_Motors.move('tth',tth_val,wait=True,verbose=False) + self.motors.move('tth',tth_val,wait=True,verbose=False) - def tth0_set(move): + 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 = Kappa_Motors._motor_dictionary['th'][3] + tth_pv = self.motors._motor_dictionary['th'][3] if current_det != 'd4': print('tth0 can only be redefined with d4') diff --git a/build/lib/iexcode/instruments/Motors.py b/build/lib/iexcode/instruments/Motors.py index 3db6923f1ff73c1209de69c47cae9798572171b3..5e7756b15fce0ec439ffa87ad051f1ca99152664 100644 --- a/build/lib/iexcode/instruments/Motors.py +++ b/build/lib/iexcode/instruments/Motors.py @@ -1,5 +1,4 @@ import time -from math import floor from epics import caget, caput @@ -112,13 +111,14 @@ class Motors: self.move(name,val,relative=True,wait=kwargs['wait'],verbose=kwargs['verbose']) - def mprint(self): + def mprint(self,name=''): """ prints current position of the physical motors """ - position_list = [] + position_list = [name] for motor in self.physical_motors: position_list.append(self.get(motor,verbose=False)) + return position_list def mvsample(self,position_list,verbose=True): @@ -166,6 +166,7 @@ class Motors: #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 @@ -254,9 +255,9 @@ def mvx(val,**kwargs): """ moves x motor in the endstation""" iex.BL.Motors.move('x',val,**kwargs) -def dmvx(val): +def dmvx(delta): """ relative x motor in the endstation""" - iex.BL.Motors.move('x',val,relative=True) + iex.BL.Motors.move('x',delta,relative=True) def scanx(start,stop,step,**kwargs): """ scans the x motor in the endstation""" @@ -271,9 +272,9 @@ def mvy(val,**kwargs): """ moves y motor in the endstation""" iex.BL.Motors.move('y',val,**kwargs) -def dmvy(val): +def dmvy(delta): """ relative y motor in the endstation""" - iex.BL.Motors.move('y',val,relative=True) + iex.BL.Motors.move('y',delta,relative=True) def scany(start,stop,step,**kwargs): """ scans the y motor in the endstation""" @@ -288,9 +289,9 @@ def mvz(val,**kwargs): """ moves z motor in the endstation""" iex.BL.Motors.move('z',val,**kwargs) -def dmvz(val): +def dmvz(delta): """ relative z motor in the endstation""" - iex.BL.Motors.move('z',val,relative=True) + iex.BL.Motors.move('z',delta,relative=True) def scanz(start,stop,step,**kwargs): """ scans the z motor in the endstation""" @@ -305,9 +306,9 @@ def mvkth(val,**kwargs): """ moves kth motor in the endstation""" iex.BL.Motors.move('kth',val,**kwargs) -def dmvkth(val): +def dmvkth(delta): """ relative kth motor in the endstation""" - iex.BL.Motors.move('kth',val,relative=True) + iex.BL.Motors.move('kth',delta,relative=True) def scankth(start,stop,step,**kwargs): """ scans the kth motor in the endstation""" @@ -339,9 +340,9 @@ def mvkap(val,**kwargs): """ moves kap motor in the endstation""" iex.BL.Motors.move('kap',val,**kwargs) -def dmvkap(val): +def dmvkap(delta): """ relative kap motor in the endstation""" - iex.BL.Motors.move('kap',val,relative=True) + iex.BL.Motors.move('kap',delta,relative=True) def scankap(start,stop,step,**kwargs): """ scans the kap motor in the endstation""" @@ -356,9 +357,9 @@ def mvtth(val,**kwargs): """ moves tth motor in the endstation""" iex.BL.Motors.move('tth',val,**kwargs) -def dmvtth(val): +def dmvtth(delta): """ relative tth motor in the endstation""" - iex.BL.Motors.move('tth',val,relative=True) + iex.BL.Motors.move('tth',delta,relative=True) def scantth(start,stop,step,**kwargs): """ scans the tth motor in the endstation""" @@ -373,9 +374,9 @@ def mvth(val,**kwargs): """ moves th motor in the endstation""" iex.BL.Motors.move('th',val,**kwargs) -def dmvth(val): +def dmvth(delta): """ relative th motor in the endstation""" - iex.BL.Motors.move('th',val,relative=True) + iex.BL.Motors.move('th',delta,relative=True) def scanth(start,stop,step,**kwargs): """ scans the th motor in the endstation""" @@ -407,9 +408,9 @@ def mvphi(val,**kwargs): """ moves phi motor in the endstation""" iex.BL.Motors.move('phi',val,**kwargs) -def dmvphi(val): +def dmvphi(delta): """ relative phi motor in the endstation""" - iex.BL.Motors.move('phi',val,relative=True) + iex.BL.Motors.move('phi',delta,relative=True) def scanphi(start,stop,step,**kwargs): """ scans the phi motor in the endstation""" @@ -419,27 +420,7 @@ def dscanphi(start,stop,step): """relative scans of the phi motor in the endstation """ iex.BL.Motors.scan("phi",start,stop,step,relative=True) -### uan moves tth and th simultaneously -def uan(tth,th): - """ Moves tth and th motors simultaneously in the in the Kappa chamber - """ - if iex.BL.endstation == 'Kappa': - #move tth and th - mvth(th,wait=False) - mvtth(tth,wait=False) - sleep(0.2) - - while True: - status = iex.BL.Motors.status() - if status == 0: - sleep(0.2) - else: - tth_RBV=round(iex.BL.Motors.get('tth',verbose=False),3) - th_RBV=round(iex.BL.Motors.get('th',verbose=False),3) - print('tth='+str(tth_RBV)+' th='+str(th_RBV)) - break - else: - print("not a defined move") + ######## mprint and mvsample ################### def mprint(): """ diff --git a/build/lib/iexcode/instruments/VLS_PGM.py b/build/lib/iexcode/instruments/VLS_PGM.py index c4bb2d114bdf9eb2eb0fbd30d7c4038ad2d0f055..4a40674b807b46f8211d99ea5cc563832cf9c509 100644 --- a/build/lib/iexcode/instruments/VLS_PGM.py +++ b/build/lib/iexcode/instruments/VLS_PGM.py @@ -14,7 +14,7 @@ from iexcode.instruments.utilities import print_warning_message,read_dict ############################################################################################################## ################################ mono ############################## ############################################################################################################## -def mono_grating_names(): +def _mono_grating_names(): """ List of grating names @@ -24,7 +24,7 @@ def mono_grating_names(): GRT_names=GRT_names[0:2] # only use the first 3 slots return GRT_names -def mono_mirror_names(): +def _mono_mirror_names(): """ List of grating names @@ -34,7 +34,7 @@ def mono_mirror_names(): MIR_names=MIR_names[0:2] # only use the first 3 slots return MIR_names -def mono_extensions(): +def _mono_extensions(): """ extension used for the mono mirror and grating locations """ @@ -74,24 +74,24 @@ def mono_get_all(verbose=False): print(" grating : "+vals['grating']," mirror : "+vals['mirror']) return vals -def mono_grating_num(): +def _mono_grating_num(): """returns the current grating num""" return caget('29idmonoGRT_TYPE_MON') -def mono_mirror_num(): +def _mono_mirror_num(): """returns the current mirror num""" return caget('29idmonoMIR_TYPE_MON') -def mono_pvs(grt_num=None,mir_num=None): +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() + grt_num = _mono_grating_num() if mir_num is None: - mir_num = mono_mirror_num() + mir_num = _mono_mirror_num() - ext=mono_extensions() + ext=_mono_extensions() d={ 'energy':"29idmono:ENERGY_MON", @@ -125,14 +125,14 @@ def mono_get_all_extended(verbose=False): Previously: Mono_Optics """ - grt_num = mono_grating_num() - mir_num = mono_mirror_num() - grt_names = mono_grating_names() - mir_names = mono_mirror_names() + grt_num = _mono_grating_num() + mir_num = _mono_mirror_num() + grt_names = _mono_grating_names() + mir_names = _mono_mirror_names() - ext=mono_extensions() + ext=_mono_extensions() - pvs = mono_pvs(grt_num=None,mir_num=None) + pvs = _mono_pvs(grt_num=None,mir_num=None) vals={ 'grt_num':grt_num, 'mir_num':mir_num, @@ -190,7 +190,7 @@ def mono_energy_set(hv_eV,verbose=True): Previously: SetMono """ hv_min, hv_max = mono_energy_range() - pv = mono_pvs()['energy_sp'] + pv = _mono_pvs()['energy_sp'] if hv_min <= hv_eV <= hv_max: caput(pv,hv_eV,wait=True,timeout=60) time.sleep(2.5) @@ -210,19 +210,20 @@ def mono_scan_pvs(): """ returns the pvs to be used in scanning """ - val_pv = mono_pvs()['energy_sp'] - rbv_pv = mono_pvs()['energy'] + 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()['energy'] + pvs = _mono_pvs()['energy'] mir_P_status = caget(pvs['mir_P_status']) grt_P_status = caget(pvs['grt_P_status']) mir_X_status = caget(pvs['mir_P_status']) @@ -244,13 +245,13 @@ def mono_grating_translate(grating,verbose=True): hv_eV = mono_energy_get() try: - grating_state = mono_grating_names().index(grating) + grating_state = _mono_grating_names().index(grating) except: print_warning_message(grating+' not a valid grating') if current_grating != grating: - pvs=mono_pvs() + pvs=_mono_pvs() caput(pvs['grt_type_sp'],grating_state,wait=True,timeout=18000) caput(pvs['grt_move'],1,wait=True,timeout=18000) while True: @@ -351,11 +352,11 @@ def mono_parameters_pv(grt_num=None,mir_num=None): returns dictionary with mono_parameter for current grating/mirror """ if grt_num is None: - grt_num = mono_grating_num()() + grt_num = _mono_grating_num()() if mir_num is None: - mir_num = mono_mirror_num()() + mir_num = _mono_mirror_num()() - ext = mono_extensions() + ext = _mono_extensions() d={ 'mir_offset':"29idmonoMIR:P_OFFSETS."+ext[mir_num], @@ -375,9 +376,9 @@ def mono_parameters_get(): Previously: Mono_Parameters_Get """ date=time.strftime("%Y%m%d",time.localtime()) - mirList = mono_mirror_names() - grtList = mono_grating_names() - pvList = mono_extensions() + mirList = _mono_mirror_names() + grtList = _mono_grating_names() + pvList = _mono_extensions() #MIR txt="MonoParm[\'"+date+"\']= {\n\t" @@ -479,10 +480,10 @@ def mono_scan_fillin(hv_start,hv_stop,hv_step,**kwargs): #Setting up the ScanRecord for Mono in Table mode val_pv, rbv_pv = mono_scan_pvs() - BL.mda.fillin(val_pv,rbv_pv,hv_start,hv_stop,hv_step,**kwargs) + 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 - BL.mda.positioner_after_scan("STAY") + iex.BL.mda.positioner_after_scan("STAY") def mono_scan_fillin_table(hv_array,**kwargs): @@ -499,19 +500,19 @@ def mono_scan_fillin_table(hv_array,**kwargs): #Setting up the ScanRecord for Mono in Table mode val_pv, rbv_pv = mono_scan_pvs() - BL.mda.fillin.table(val_pv,rbv_pv,hv_array,**kwargs) + iex.BL.mda.fillin.table(val_pv,rbv_pv,hv_array,**kwargs) #mono needs to stay and have a longer settling time - BL.mda.positioner_settling_time(kwargs['positioner_settling_time']) - BL.mda.positioner_after_scan("STAY") + iex.BL.mda.positioner_settling_time(kwargs['positioner_settling_time']) + iex.BL.mda.positioner_after_scan("STAY") def mono_scan_after(**kwargs): """ resets mda after scanning the mono """ - after_scan_pv = BL.mda.default_after_scan_seq + after_scan_pv = iex.BL.mda.default_after_scan_seq caput(after_scan_pv+".PROC",1) - BL.mda.positioner_after_scan("PRIOR POS") + iex.BL.mda.positioner_after_scan("PRIOR POS") ############################################################################################################## @@ -546,7 +547,7 @@ def mono_motor_scan_fillin(motor,start,stop,step,**kwargs): val_pv,rbv_pv = mono_motor_scan_pvs(motor) caput(val_pv+".PREC",3) # database sets .PREC==0. We want more digits than that. - BL.mda.fillin(val_pv,rbv_pv,start,stop,step,**kwargs) + iex.BL.mda.fillin(val_pv,rbv_pv,start,stop,step,**kwargs) def mono_zero_order(angle): """ @@ -617,7 +618,7 @@ def mono_grating_offset_set(val,grt_num=None): Previously: Mono_Set_GRT0 """ - pvs=mono_pvs(grt_num,None) + pvs=_mono_pvs(grt_num,None) caput(pvs['grt_offset'],val) mono_get_all_extended(verbose=True) @@ -627,7 +628,7 @@ def mono_mirror_offset_set(val,mir_num=None): Previously: Mono_Set_MIR0 """ - pvs=mono_pvs(None,mir_num) + pvs=_mono_pvs(None,mir_num) caput(pvs['mir_offset'],val) mono_get_all_extended(verbose=True) @@ -669,7 +670,7 @@ def mono_grating_b2_set(val,grt_num=None): Previously: Mono_Set_b2 """ hv = mono_energy_get() - pvs = mono_pvs(grt_num,None) + pvs = _mono_pvs(grt_num,None) caput(pvs['grt_b2t'],val) time.sleep(1) @@ -684,7 +685,7 @@ def mono_cff_set(val,tune_num): Previously: Mono_Set_cff """ hv = mono_energy_get() - pvs = mono_pvs() + pvs = _mono_pvs() #get current info current_vals = mono_get_all_extended(verbose=False) @@ -715,7 +716,7 @@ def mono_arm_set(distance_mm): Previously: Mono_Set_ExitArm """ hv = mono_energy_get() - pvs = mono_pvs() + pvs = _mono_pvs() #get current info current_vals = mono_get_all_extended(verbose=False) diff --git a/build/lib/iexcode/instruments/bakeout.py b/build/lib/iexcode/instruments/bakeout.py index 94dfd1a00e1173fabb280bf94cd6090258599878..f232c19053db8dd22a40aef771f8dc59b6469ea6 100644 --- a/build/lib/iexcode/instruments/bakeout.py +++ b/build/lib/iexcode/instruments/bakeout.py @@ -52,7 +52,7 @@ def bakout_scan(scan_ioc_name,chamber): print("\nSave Status "+scan_ioc+" "+SaveStatus+" - "+SaveMessage) #setting up scan record - detector_dictionary = bakeout_detector_dictionary(chamber) + detector_dictionary = _bakeout_detector_dictionary(chamber) #caput("29idb:ca1:read.SCAN",0) #trigger_dictionary = {1:"29idb:ca1:read"} @@ -67,7 +67,7 @@ def bakout_scan(scan_ioc_name,chamber): -def bakeout_detector_dictionary(chamber): +def _bakeout_detector_dictionary(chamber): """ returns a dictionary of the default detectors diff --git a/build/lib/iexcode/instruments/beamline.py b/build/lib/iexcode/instruments/beamline.py deleted file mode 100644 index f8de3a0d8204d785696cb58ba3d3841e32b3cb10..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/beamline.py +++ /dev/null @@ -1,50 +0,0 @@ - -""" -short name for functions used with or without x-rays - -""" - -import numpy as np -from time import sleep - -from epics import PV - -import iexcode.instruments.cfg as iex - - - - - - -############################################################################################################## -############################## Beeper ############################## -############################################################################################################## - - -def endstation_cams_enable(): - """ - should live in cameras - """ - endstation=iex.BLendstation - - cam_dict={'ARPES':[0,1,2],'Kappa':[3,4,6]} # index of cam_list - pvcam1=PV("29id_ps1:cam1:Acquire") - pvcam2=PV("29id_ps2:cam1:Acquire") - pvcam3=PV("29id_ps3:cam1:Acquire") - pvcam4=PV("29id_ps4:cam1:Acquire") - pvcam6=PV("29id_ps6:cam1:Acquire") - pvcam7=PV("29id_ps7:cam1:Acquire") - cam_list=[pvcam1,pvcam2,pvcam3,pvcam4,pvcam6,pvcam7] - sleep(0.1) - for pvcam in cam_list: # turn OFF all cam - try: - if pvcam.connected: pvcam.put(0) - except: - pass - for i in cam_dict[endstation]: # turn ON relevant cam - try: - if cam_list[i].connected: cam_list[i].put(1) - else: print(cam_list[i].pvname+' not connected') - except: - pass - diff --git a/build/lib/iexcode/instruments/cameras.py b/build/lib/iexcode/instruments/cameras.py index e91f8d39fb1efcde73b3b41a0be7ec0128bafab1..977490ced8d54c937769a98757e361a724faf9c6 100644 --- a/build/lib/iexcode/instruments/cameras.py +++ b/build/lib/iexcode/instruments/cameras.py @@ -20,6 +20,7 @@ def _pv_dictionary(): 4:"29id_ps4:", 5:"29idarv5:", 6:"29id_ps6:", + 7:"29id_ps7:", } return d @@ -33,7 +34,7 @@ def _enable_endstation_cameras(unused_off=True): unused_off=True turns off other cameras """ - endstation=iex.BL.endstation + endstation=iex.BL.endstation_name #For new endstation modify here: cam_dict={'ARPES':[0,1,2],'Kappa':[3,4,6]} # index of cam_list @@ -72,8 +73,7 @@ def cam_snap(cam_num,ADtype='TIFF',**kwargs): False => leave saving enabled and camera in single acquision """ - ADplugin = _pv_dictionary()[cam_num]+ADtype+":" - AD_SaveFileSetup(ADplugin,iex.BL.mda,**kwargs) + ADplugin = _pv_dictionary()[cam_num]+ADtype+"1:" AD_snap(ADplugin,**kwargs) @@ -84,16 +84,43 @@ def cam_snap(cam_num,ADtype='TIFF',**kwargs): ############################################################################################################## def cam_scan_setup(cam_num,ADtype='TIFF',**kwargs): """ - sets up the BL scanRecord to trigger the camera (trigger - 2) + sets up the BL scanRecord for scanning at every point + **kwargs + scanDIM = 1 + 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 """ - ADplugin = _pv_dictionary()[cam_num]+ADtype+":" + ADplugin = _pv_dictionary()[cam_num]+ADtype+"1:" ADplugin_ScanSetup(ADplugin,iex.BL.mda, **kwargs) -def cam_live(cam_num,ADtype='TIFF',**kwargs): +def cam_live(cam_num): """ puts camera in no save and continuous a.k.a free run """ - ADplugin = _pv_dictionary()[cam_num]+ADtype+":" - AD_FreeRun(ADplugin,**kwargs) \ No newline at end of file + ADplugin = _pv_dictionary()[cam_num] + AD_FreeRun(ADplugin) + +def cam_done(cam_num,**kwargs): + """ + stops camera acquisition (not will stop after current acquisition) + """ + ADplugin = _pv_dictionary()[cam_num] + AD_Done(ADplugin,**kwargs) + +def cam_save_setup(cam_num,ADtype='TIFF',**kwargs): + """ + sets up the save paths using iex.BL.mda.current_user + **kwargs + prefix: beginning of filename + """ + ADplugin = _pv_dictionary()[cam_num]+ADtype+"1:" + AD_SaveFileSetup(ADplugin,**kwargs) + diff --git a/build/lib/iexcode/instruments/conversions_constants.py b/build/lib/iexcode/instruments/conversions_constants.py index 45f1aea59c570ce29108135e34ade471f665f24b..44f84907c589a4d7965bde87e823d3fee4fc5c1a 100644 --- a/build/lib/iexcode/instruments/conversions_constants.py +++ b/build/lib/iexcode/instruments/conversions_constants.py @@ -1,12 +1,12 @@ import numpy as np -from epics import caget - ############################################################################################################## ############################## conversions ############################## ############################################################################################################## +#Plank's constant eV/s h=4.135667516e-15 -c=299792458 +#speed of ligh m/s +c=299792458 def deg2rad(angle_deg): angle_rad=angle_deg*np.pi/180 @@ -20,8 +20,7 @@ def eV2Lambda(eV): """ Converts energy (eV) into wavelenght (Angstrom) """ - - Angstrom = h*c/eV*1e9*10 + Angstrom = h*c/eV*1e10 return Angstrom def Lambda2eV(Angstrom): @@ -29,81 +28,6 @@ def Lambda2eV(Angstrom): Converts wavelenghth (Angstrom) into energy (eV) """ - eV = h*c/Angstrom*1e9*10 + eV = h*c/Angstrom*1e10 return eV -############################################################################################################## -############################## Kappa to Euler Conversion ############################## -############################################################################################################## -def Kappa2Fourc(ang1,ang2,ang3,conversion,k_arm=50): - - a,b,c=0,0,0 - if conversion=='Kappa': - a,b,c=EtoK(ang1,ang2,ang3,k_arm) - print(("\n"+"th = "+str(ang1))) - print(("chi = "+str(ang2))) - print(("phi = "+str(ang3))) - print("~~~~~~~~") - print(("kth = "+str(a))) - print(("kap = "+str(b))) - print(("kphi = "+str(c)+"\n")) - elif conversion=='fourc': - a,b,c=KtoE(ang1,ang2,ang3,k_arm) - print(("\n"+"kth = "+str(ang1))) - print(("kap = "+str(ang2))) - print(("kphi = "+str(ang3))) - print("~~~~~~~~") - print(("th = "+str(a))) - print(("chi = "+str(b))) - print(("phi = "+str(c)+"\n")) - else: - print('2nd argument invalid; please choose one of the following:') - print('"Kappa" or "fourc"') - return a,b,c - - - -def EtoK(e_theta,e_chi,e_phi,k_arm=50): - conv = np.pi/180.0 - kth_offset=caget('29idKappa:userCalcOut1.G') - if(abs(e_chi)> 2.0*k_arm): - print("Chi should be no more than twice the Kappa arm offset angle.") - kth,kap,kphi=0,0,0 - else: - print(("Calculating Kappa angles using kth0 = "+str(kth_offset))) - k_ang = k_arm*conv - delta = np.asin( - np.tan(e_chi*conv/2.0) / np.tan(k_ang) ) - k_theta = e_theta*conv - delta - k_kappa = 2.0 * np.asin( np.sin(e_chi*conv/2.0) / np.sin(k_ang)) - k_phi = e_phi*conv - delta - #print k_theta, k_kappa,k_phi - kth = rounder(k_theta)-(57.045-kth_offset) - kap = rounder(k_kappa) - kphi = rounder(k_phi) - #print delta - return (kth,kap,kphi) - - - - -def KtoE(k_theta,k_kappa,k_phi,k_arm=50): - conv = np.pi/180.0 - kth_offset=caget('29idKappa:userCalcOut1.G') - print(("Calculating Euler angles using kth0 = "+str(kth_offset))) - k_ang = k_arm*conv - delta = np.atan( np.tan(k_kappa*conv/2.0) * np.cos(k_ang) ) - e_theta = k_theta*conv - delta - e_chi = 2.0 * np.asin( np.sin(k_kappa*conv/2.0) * np.sin(k_ang) ) - e_phi = k_phi*conv - delta - #print round(e_theta,1),round(e_phi,1),round(e_chi,1) - theta = rounder(e_theta)+(57.045-kth_offset) - chi = rounder(e_chi) # convert from rad to deg - phi = rounder(e_phi) - #print round(delta,1) - return (theta,chi,phi) - - -def rounder(val): # convert from rad to deg - conv = np.pi/180.0 - roundVal=round(1000.0*val/conv)/1000.0 - return roundVal diff --git a/build/lib/iexcode/instruments/current_amplifiers.py b/build/lib/iexcode/instruments/current_amplifiers.py index 88268a27cc8c0a7f7ff27565234289265a682a1a..cb6a1b778a92facd0dbcb22c3a4e22fcc3cca7fe 100644 --- a/build/lib/iexcode/instruments/current_amplifiers.py +++ b/build/lib/iexcode/instruments/current_amplifiers.py @@ -11,16 +11,17 @@ def ca_detector_list(branch): returns the list of keithley current amplifiers based on key key: 'ARPES' / 'Staff' """ - ca_list = list(ca_dictionary()[branch].keys()) + ca_list = list(_ca_dictionary()[branch].keys()) return ca_list -def ca_dictionary(): +def _ca_dictionary(): """ - dictionary of connected Kiethlys and thier names + dictionary of connected Keithley and thier names Previously: CA_Name """ + #For new endstation modify here: ca={} ca["b"] = { 1: 'W-mesh', @@ -44,7 +45,7 @@ def ca_dictionary(): ############################################################################################################## ################################ Keithley ############################## ############################################################################################################## -def Keithley_pv(ca_crate, ca_num): +def _Keithley_pv(ca_crate, ca_num): """ ca_crate = 'b' / 'c' ... """ @@ -59,9 +60,9 @@ class Keithley: ca_crate = 'b' / 'c' ... """ - self._pv = Keithley_pv(ca_crate, ca_num) + self._pv = _Keithley_pv(ca_crate, ca_num) try: - self.name = ca_dictionary()[ca_crate][ca_num] + self.name = _ca_dictionary()[ca_crate][ca_num] except: self.name = 'CA'+ca_crate+str(ca_num) @@ -189,7 +190,7 @@ def ca_reset_all(rate="Slow"): Previously: Reset_CA_all """ - ca_dict = ca_dictionary() + 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) @@ -198,7 +199,7 @@ def ca_reset_all(rate="Slow"): 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): +def _ca_live_sequence(ioc,seq_num,detector_list): """ creates a string sequence to put keithleys back in live mode @@ -244,7 +245,7 @@ def ca_average(avg_pts,ca_list,rate="Slow",verbose=True): ca.avg(avg_pts,rate=rate,verbose=verbose) -def load_responsivity_curve(): +def _load_responsivity_curve(): """ Loads the responsivity curve for the AUX100 photo diode, used to convert current to flux at a given photon energy @@ -265,7 +266,7 @@ def current2flux(current,hv=None,verbose=True): Previously CA2flux """ try: - curve=load_responsivity_curve() + curve=_load_responsivity_curve() except: print('responsivity curve not loaded') return @@ -295,7 +296,7 @@ def flux2current(flux,hv=None,verbose=True): hv = None; gets the current mono energy; otherwise you will need to specify """ try: - curve=load_responsivity_curve() + curve=_load_responsivity_curve() except: print('responsivity curve not loaded') return @@ -333,8 +334,14 @@ class SRS: self.scaler_value self.gain - self.unit - self.current + self.current_Amp + self.current_unit + self.invert + self.baseline + self.offset_value + self.offset_unit + self.offset_sign + self.offset_factor self.get(verbose=False) def get(self): @@ -343,10 +350,25 @@ class SRS: """ self.scaler_value = caget(self._scaler_pv) self.gain = float(caget(self._scaler_pv+'sens_num.VAL',as_string=True)) - self.unit = caget(self._scaler_pv+'sens_unit.VAL',as_string=True) - CA = {'pA':1e-12, 'nA':1e-9, 'uA':1e-6, 'mA':1e-3} - self.current = self.scaler_value * self.gain * CA[self.unit] - + self.current_unit = caget(self._scaler_pv+'sens_unit.VAL',as_string=True) + self.invert = caget(self._scaler_pv+'invert_on.VAL',as_string=True) + unit_sciNote = {'pA':1e-12, 'nA':1e-9, 'uA':1e-6, 'mA':1e-3} + self.current_Amp = self.scaler_value * self.gain * unit_sciNote[self.current_unit] + + self.offset_value=caget(self._scaler_pv+"offset_num.VAL",as_string=True) + self.offset_unit=caget(self._scaler_pv+"offset_unit.VAL",as_string=True) + self.offset_sign=caget(self._scaler_pv+"offset_sign.VAL",as_string=True) + self.offset_factor=caget(self._scaler_pv+"off_u_put.VAL",as_string=True) + self.baseline = self.offset_factor * self.offset_value * unit_sciNote[self.offset_unit] + + self.filter_type=caget(self._scaler_pv+'filter_type.VAL',as_string=True) + self.filter_low=caget(self._scaler_pv+'low_freq.VAL',as_string=True) + self.filter_high=caget(self._scaler_pv+'high_freq.VAL',as_string=True) + self.blank=caget(self._scaler_pv+'blank_on.VAL',as_string=True) + self.bias_OnOff=caget(self._scaler_pv+'bias_on.VAL',as_string=True) + self.bias_value=caget(self._scaler_pv+'bias_put.VAL',as_string=True) + + def setgain(self,gain,unit): """ gain = 1,2,5,10,20,50,100,200,500 @@ -360,23 +382,17 @@ class SRS: """ prints SRS setting """ + self.get() - invert=caget(self._srs_pv+'invert_on.VAL',as_string=True) - currentUnit=caget(self._srs_pv+'sens_unit.VAL',as_string=True) - currentValue=caget(self._srs_pv+'sens_num.VAL',as_string=True) - offsetValue=caget(self._srs_pv+"offset_num.VAL",as_string=True) - offsetUnit=caget(self._srs_pv+"offset_unit.VAL",as_string=True) - offsetSign=caget(self._srs_pv+"offset_sign.VAL",as_string=True) - offsetFactor=caget(self._srs_pv+"off_u_put.VAL",as_string=True) - print('Gain: '+currentValue+' '+currentUnit+' (invert '+invert+')') - print('Baseline: '+offsetSign+' '+offsetFactor+' x '+offsetValue+" "+offsetUnit) + print('Gain: '+self.scaler_value+' '+self.current_unit+' (invert '+self.invert+')') + print('Baseline: '+self.offset_sign+' '+self.offset_factor+' x '+self.offset_value+" "+self.offset_unit) if long: - filterType=caget(self._srs_pv+'filter_type.VAL',as_string=True) - filterLow=caget(self._srs_pv+'low_freq.VAL',as_string=True) - filterHigh=caget(self._srs_pv+'high_freq.VAL',as_string=True) - blank=caget(self._srs_pv+'blank_on.VAL',as_string=True) - biasOnOff=caget(self._srs_pv+'bias_on.VAL',as_string=True) - biasValue=caget(self._srs_pv+'bias_put.VAL',as_string=True) + filterType = self.filter_type + filterLow = self.filter_low + filterHigh = self.filter_high + blank = self.blank + biasOnOff = self.bias_OnOff + biasValue = 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 index 0127d98e6c9939e0ac311ea549fd99226f09f0ba..e062b81e0cd6496867ce78bf16316549ad3c67e7 100644 --- a/build/lib/iexcode/instruments/diagnostics.py +++ b/build/lib/iexcode/instruments/diagnostics.py @@ -1,14 +1,16 @@ +from iexcode.instruments.current_amplifiers import Keithley,SRS from numpy import nan from epics import caput, caget -#from iexcode.instruments.IEX_endstations import * + +import iexcode.instruments.cfg as iex ############################################################################################################## ################################ default positions ############################## ############################################################################################################## ###### We should make pvs in the 29idb ioc to hold these values: -def diagnostics_dict(): +def _diagnostics_dict(): """ Dictionary of Diagnostic positions In and Out by either motor number or name WARNING: When updating motor values, also update the following screens: @@ -37,16 +39,24 @@ def diagnostics_dict(): "D2B":6, "D3B":7, "D4C":17, "gas-cell":20,"D4D":25,"D5D":28} return diag -def diagnostic_CA_dict(): +def _diagnostic_CA_dict(): CA_dict={ - 'diode_c':'29idb:ca15:' + 'diode_c':Keithley('b',15), + 'mesh_d':SRS("29idMZ0:scaler1.S14", '29idd:A4'), } return CA_dict +def diagnostics_list_all(): + """ + lists all diagnostics + """ + d = _diagnostics_dict() + for key in d.keys(): + print(key) def diagnostic(diagnostic_name,in_out): "Inserts/retracts a diagnostic(motor number or name) either = \"In\" or \"Out\"" - diag=diagnostics_dict() + diag=_diagnostics_dict() if type(diagnostic_name) is int: motor=diagnostic_name name=diag['name'][motor] @@ -65,12 +75,12 @@ def diagnostics_all_out(diode_stay_in=False): Previously: AllDiagOut """ - diag=diagnostics_dict() + diag=_diagnostics_dict() text="" #which motor is Diode of interest if diode_stay_in: - branch = BL.branch + branch = iex.BL.branch if branch == 'c': diode_motor=diag["motor"]["gas-cell"] @@ -82,7 +92,7 @@ def diagnostics_all_out(diode_stay_in=False): #Taking out the diagnostic for motor in list(diag["Out"].keys()): if motor is diode_motor: - text=' except Diode-'+BL.branch + text=' except Diode-'+iex.BL.branch #putting Diode In if not already in -JM position=diag["In"][motor] caput("29idb:m"+str(motor)+".VAL",position,wait=True,timeout=18000) @@ -98,7 +108,7 @@ def diagnostics_all_in(): Previously: AllDiagIn and AllMeshIn() """ - diag=diagnostics_dict() + diag=_diagnostics_dict() for motor in list(diag["In"].keys()): position=diag["In"][motor] if type(position) == list: @@ -113,31 +123,31 @@ def mesh_W(In_Out): Previously MeshW """ - diag=diagnostics_dict() + diag=_diagnostics_dict() motor=5; position=diag[In_Out][motor] caput("29idb:m"+str(motor)+".VAL",position,wait=True,timeout=18000) print("\nD1A mesh_W: "+ In_Out) -def diodeC(In_Out): +def diode_c(In_Out): """ Inserts/retracts ARPES (gas-cell) diode; arg = \"In\" or \"Out\" Previously: DiodeC """ - diag=diagnostics_dict() + diag=_diagnostics_dict() motor=20; position=diag[In_Out][motor] caput("29idb:m"+str(motor)+".VAL",position,wait=True,timeout=18000) print("\nARPES Diode: "+ In_Out) -def diodeD(In_Out): +def diode_d(In_Out): """ Inserts/retracts RSXS diode; arg = \"In\" or \"Out\" Previously:DiodeD """ - diag=diagnostics_dict() + diag=_diagnostics_dict() motor=28; position=position=diag[In_Out][motor] if type(position) == list: position=position[1] @@ -145,53 +155,36 @@ def diodeD(In_Out): print("\nRSXS Diode: "+ In_Out) - -def meshC(In_Out,which="postSlit"): - """ - Inserts/retracts ARPES mesh (preSlit or postSlit); arg = \"In\" or \"Out\" - - Previously: MeshC - """ - diag=diagnostics_dict() - if which == "postSlit": - motor=20; position=-31 - elif which == "preSlit": - motor=17; position=diag[In_Out][motor] - - caput("29idb:m"+str(motor)+".VAL",position,wait=True,timeout=18000) - print("\nD4C Au-Mesh: "+ In_Out) - -def meshD(In_Out): +def mesh_d(In_Out): """ Inserts/retracts RSXS mesh (post-slit); arg = \"In\" or \"Out\" Previoulsy: MeshD """ - diag=diagnostics_dict() + diag=_diagnostics_dict() motor=28; position=position=diag[In_Out][motor] if type(position) == list: position=position[0] caput("29idb:m"+str(motor)+".VAL",position,wait=True,timeout=18000) print("\nD5D Au-Mesh: "+ In_Out) -def diagnostic_read(diode_d, quiet=True): +def diagnostic_read(diode_name, verbose=True): """ reads the current amplifier and returns the value - quiet = False to pring """ try: - diode_pv = diagnostic_CA_dict['diode_d'] - val=caget(diode_pv+'read') + det = _diagnostic_CA_dict[diode_name] + val=det.get(verbose) except: diode_pv="not connected" val = nan print('pv not defined') - if not quiet: - print('Diode-D ',val, "(pv = "+diode_pv+")") + if verbose: + print(diode_name,val, "(pv = "+diode_pv+")") return val -def diodeC_read(quiet=True): +def diode_c_read(quiet=True): """ reads the current amplifier and returns the value quiet = False to pring @@ -199,7 +192,7 @@ def diodeC_read(quiet=True): val = diagnostic_read('diode_d',quiet) return val -def diodeD_read(quiet=True): +def diode_d_read(quiet=True): """ reads the current amplifier and returns the value quiet = False to pring @@ -207,7 +200,7 @@ def diodeD_read(quiet=True): val = diagnostic_read('diode_d',quiet) return val -def meshD_read(quiet=True): +def mesh_d_read(quiet=True): """ reads the current amplifier and returns the value quiet = False to pring diff --git a/build/lib/iexcode/instruments/electron_analyzer.py b/build/lib/iexcode/instruments/electron_analyzer.py index 557b1a1301eb647fe50048f9e00a980a1ac27c28..52fd4ffb375fac9030c1818b10b11f30b422387e 100644 --- a/build/lib/iexcode/instruments/electron_analyzer.py +++ b/build/lib/iexcode/instruments/electron_analyzer.py @@ -17,11 +17,11 @@ 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, BL_energy_tables +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 * +from iexcode.instruments.Logfile import log_print from iexcode.instruments.Scienta import * global EA @@ -32,7 +32,7 @@ except: print("EA is not connected") ########################################################################### -def EA_init_Motors(Motors): +def _EA_init_Motors(Motors): """ Adds Motors to EA object to be used in scanning """ @@ -92,9 +92,6 @@ def EA_ioc_init(**kwargs): print("C-Shutter is closed for initialization ") -def getSESslit(): - SES=caget("29idc:m8.RBV") - return SES def folders_EA(userPath,filePrefix="EA",**kwargs): """ @@ -170,14 +167,13 @@ def EA_log_update(): entry_list.append(key) pv_list.append(spectra_info[key][0]) format_list.append(spectra_info[key][1]) - logfile_update("ARPES",BL.ioc,entry_list,pv_list,format_list) + iex.BL.mda.log.update(entry_list,pv_list,format_list) except: print("EAlog did not write to file, check for errors.") def log_headerEA():##JM - need to update so that we get the keys from log_EA s="\nscan x y z th chi phi T scan_mode E1 E2 step i f PE lens_mode SES slit # ID_mode hv exit_slit GRT TEY1 TEY2 time\n" - kwargs={'comment': s} - logfile_print("ARPES",BL.ioc,comment='') + log_print(s) def EAsweptTime_estimate(EAlist,overhead=[60,.22]): """ @@ -226,7 +222,7 @@ def _scanEATrigger(EAlist,before_after,**kwargs): kwargs.setdefault("prefix","EA")# if not None then over rides the auto kwargs.setdefault("debug",False) - scanPV=BL.ioc+"scan"+str(kwargs["scan_dim"]) + scanPV=iex.BL.ioc+"scan"+str(kwargs["scan_dim"]) triggerPV=scanPV+".T"+str(kwargs["detTrig"])+"PV" if kwargs["debug"]: @@ -266,8 +262,8 @@ def _scanEAPrefix(ptype,**kwargs): print(ptype) if ptype == "mda": - fpath = BL.mda.filepath[0:-3]+EA.dtype - nextMDA = BL.mda.fileNum + 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 @@ -310,7 +306,7 @@ def scanEA_reset(**kwargs): kwargs.setdefault("scan_dim",1) _scanEATrigger([],"after",**kwargs) - BL.mda.positioners_clear(kwargs["scan_dim"]) + iex.BL.mda.positioners_clear(kwargs["scan_dim"]) def scanEA(EAlist,**kwargs): """ @@ -331,7 +327,7 @@ def scanEA(EAlist,**kwargs): """ - kwargs.setdefault('scanIOC',BL.ioc()) + kwargs.setdefault('scanIOC',iex.BL.ioc()) kwargs.setdefault('scan_dim',1) kwargs.setdefault('execute',True) kwargs.setdefault("debug",False) @@ -354,7 +350,7 @@ def scanEA(EAlist,**kwargs): pvCalcOut1=_BE2KE_setupCalc(EAlist[1],"BE_center",10,"29idcScienta:HV:fixedEnergy.VAL") EAlist[1]=caget(pvCalcOut1+'.VAL') arrayP1=list(np.full(sweeps, EAlist[1])) - BL.mda.fillin_table(pvCalcOut1+'.PROC',"",kwargs["scanIOC"],kwargs["scan_dim"],arrayP1,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) @@ -363,7 +359,7 @@ def scanEA(EAlist,**kwargs): pvCalcOut1=_BE2KE_setupCalc(EAlist[1],"BE_center",10,"29idcScienta:HV:babySweepCenter.VAL") EAlist[1]=caget(pvCalcOut1+'.VAL') arrayP1=list(np.full(sweeps, EAlist[1])) - BL.mda.fillin_table(pvCalcOut1+'PROC',"",kwargs["scanIOC"],kwargs["scan_dim"],arrayP1,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 @@ -373,8 +369,8 @@ def scanEA(EAlist,**kwargs): EAlist[2]=caget(pvCalcOut2+'.VAL') arrayP1=list(np.full(sweeps, EAlist[1])) arrayP2=list(np.full(sweeps, EAlist[2])) - BL.mda.fillin_table(pvCalcOut1+'.PROC',"",kwargs["scanIOC"],kwargs["scan_dim"],arrayP1,1) - BL.mda.fillin_table(pvCalcOut2+'.PROC',"",kwargs["scanIOC"],kwargs["scan_dim"],arrayP2,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) @@ -394,10 +390,10 @@ def scanEA(EAlist,**kwargs): if kwargs['debug']: print("Clearing scan positioners and filling in sweeps") #Fill in Sweeps scan - BL.mda.positioners_clear(**kwargs) + iex.BL.mda.positioners_clear(**kwargs) VAL="" RBV="" - BL.mda.fillin(VAL,RBV,1,sweeps,1,**kwargs) + 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) @@ -420,11 +416,11 @@ def scanEA(EAlist,**kwargs): time.sleep(10) EA.put(EAlist[1]-.05,EAlist[-3],LensMode="Angular") time.sleep(2) - BL.mda.go(**kwargs) + iex.BL.mda.go(**kwargs) #After scan EA_log_update() scanEA_reset(**kwargs) - BL.mda.table_reset_after(**kwargs) + iex.BL.mda.table_reset_after(**kwargs) else: return EAparms @@ -451,10 +447,10 @@ def scanFM(RoughPositions,thList,EAlist,**kwargs): if kwargs['debug']: print(x,y,z,th,chi,phi) - BL.mda.fillin_table(EA.Motors._motor_dictionary("th")[1],EA.Motors._motor_dictionary("th")[0],th,positioner_num=1) - BL.mda.fillin_table(EA.Motors._motor_dictionary("x")[1],EA.Motors._motor_dictionary("x")[0],x,positioner_num=2) - BL.mda.fillin_table(EA.Motors._motor_dictionary("y")[1],EA.Motors._motor_dictionary("y")[0],y,positioner_num=3) - BL.mda.fillin_table(EA.Motors._motor_dictionary("z")[1],EA.Motors._motor_dictionary("z")[0],z,positioner_num=4) + 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={ @@ -467,7 +463,7 @@ def scanFM(RoughPositions,thList,EAlist,**kwargs): if kwargs["execute"]==True: print(EAparms) EA.put(EAparms['KineticEnergy'],EAparms['PassEnergy'],LensMode="Angular",Frames=EAparms['Frames'],**kwargs) - BL.mda.go(**kwargs) + iex.BL.mda.go(**kwargs) EA_log_update() scanEA_reset(**kwargs) @@ -550,6 +546,7 @@ def scanEA_hv(hv_start_stop_step_lists,EAlist=[],**kwargs): **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) @@ -572,18 +569,19 @@ def scanEA_hv(hv_start_stop_step_lists,EAlist=[],**kwargs): #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) - scanXAS_BL(hv_start_stop_step_lists,**kwargs) + 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) - BL.mda.go(**kwargs) + iex.BL.mda.go(**kwargs) #After scan scanEA_reset(**kwargs) - BL.mda.table_reset_after(**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) @@ -631,7 +629,7 @@ def scanEA_motor(EAlist, motor,start,stop,step,mode='absolute',**kwargs): if kwargs["execute"]==True: #Scanning EA.put(EAlist[1],EAparms['PassEnergy'],LensMode="Angular",Frames=EAparms['Frames'],**kwargs) - BL.mda.go(kwargs["scanIOC"],scan_dim) + iex.BL.mda.go(kwargs["scanIOC"],scan_dim) EA_log_update() #After scan scanEA_reset(**kwargs) @@ -678,7 +676,7 @@ def scanEA_Mesh(EAlist,y_start_stop_step,z_start_stop_step,**kwargs): if kwargs['execute']: #Scanning EA.put(EAlist[1],EAparms['PassEnergy'],LensMode="Angular",Frames=EAparms['Frames'],**kwargs) - BL.mda.go(scan_dim=outer_scan_dim) + iex.BL.mda.go(scan_dim=outer_scan_dim) EA_log_update() #After scan @@ -783,7 +781,7 @@ def resolution_EA(PE,slit_SES): # updated 10/30/17: straight slits scaled to return SES -def SES_slit(val): +def SES_slit_set(val): """ Set the Scienta Slit val w_mm l_mm Shape @@ -801,3 +799,6 @@ def SES_slit(val): 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 index e3eb8c75061323d44edc985e0eeb0df5c3ef1aac..308ea53b1ddb7596f5d29ded6f7e916f10494f12 100644 --- a/build/lib/iexcode/instruments/encoders.py +++ b/build/lib/iexcode/instruments/encoders.py @@ -1,6 +1,6 @@ from epics import caput,caget -def encoder_dictionary_entry(name): +def _encoder_dictionary(): """ returns a dictionary with the encoder pvs encoder_dictionary_entry(name) = encoder_ioc, motor_ioc, encoder_list @@ -11,26 +11,31 @@ def encoder_dictionary_entry(name): 'slit3D':("29idMini2:","29idb:",[26,27]), 'ARPES':("29idARPES:","29idARPES:",[1,2,3,4]), } - return d[name] + 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_entry(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(name,Hcenter,Vcenter): +def encoders_reset_zero(name): """ - Resetting Slit 2B encoders to 0 for a given position (Hcenter,Vcenter). + 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_entry(name) + encoder_sync(name) + encoder_ioc, motor_ioc, encoder_list = _encoder_dictionary()[name] print('\nCurrent Position:') for e_num in encoder_list: diff --git a/build/lib/iexcode/instruments/files_and_folders.py b/build/lib/iexcode/instruments/files_and_folders.py index 1f85d5bc8ec66cfe0552bc5e9f744c89c63e4797..8bb38a7326a3775f6c1046990995ed37bf5b592d 100644 --- a/build/lib/iexcode/instruments/files_and_folders.py +++ b/build/lib/iexcode/instruments/files_and_folders.py @@ -26,11 +26,6 @@ def path_dserv(folder,run,user_name): return dataFolder - - - - - ############################################################################################################## ################################ Folders ############################## ############################################################################################################## @@ -193,29 +188,7 @@ def folder_SPEC(run,folder,user_name): # mkdir(MyPath) -def folder_MPA(run,folder,user_name,file_prefix="mpa"): - if folder == "b": - windows_ioc = "X" - user_name = "" - windows_path = windows_ioc+':\\'+run+"\\mpa" - else: - windowsIOC = "Z" - user_name = user_name+"/" - windows_path=windows_ioc+':\\'+run+"\\"+user_name[:-1]+"\\mpa" - mpa_path="/net/s29data/export/data_29id"+folder+"/"+run+"/"+user_name+"mpa" - print("\nMPA folder: " + mpa_path) - if not (exists(mpa_path)): - mkdir(mpa_path) - FileNumber=1 - else: - FileNumber=get_next_fileNumber(mpa_path,file_prefix) - caput("29iddMPA:det1:MPAFilename",windows_ioc+":/"+run+"/"+user_name+"mpa/mpa_") - - save_plugin='TIFF1' - caput("29iddMPA:"+save_plugin+":FilePath",windows_path) - print("\nMPA folder on Crabby: "+windows_path) - caput("29iddMPA:"+save_plugin+":FileName",file_prefix) - caput("29iddMPA:"+save_plugin+":FileNumber",FileNumber) + def _filename_key(filename): return (len(filename), filename) diff --git a/build/lib/iexcode/instruments/gate_valves.py b/build/lib/iexcode/instruments/gate_valves.py deleted file mode 100644 index 1e122c526975534f743216fa16ae2f089094db2d..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/gate_valves.py +++ /dev/null @@ -1,35 +0,0 @@ -from epics import caget, caput - -def branch_valves(): - """ - returns a dictionary of the gate valves for a given branch - - used by close_valve and safe_state - """ - - GVs={ - 'c':('GV10'), - 'd':('GV14'), - 'e':() - } - return GVs - -def valve_close(GV, verbose=True): - """ - closes the gate valve ('GV10', 'GV14'), EPS nomenclature - - Previously: Close_DValve,Close_DValve - """ - caput("29id:BLEPS:"+GV+":CLOSE.VAL",1,wait=True,timeout=18000) - if verbose: - print("Closing gate valve: "+GV+"...") - -def valve_open(GV, verbose=True): - """ - closes the gate valve ('GV10', 'GV14'), EPS nomenclature - - Previously: Close_DValve,Close_DValve - """ - caput("29id:BLEPS:"+GV+":OPEN.VAL",1,wait=True,timeout=18000) - if verbose: - print("Opening gate valve: "+GV+"...") \ No newline at end of file diff --git a/build/lib/iexcode/instruments/hxp_mirrors.py b/build/lib/iexcode/instruments/hxp_mirrors.py index 0eb90509f2784ff042fbcb4ef78235ec102d02fd..72df87b817ebd017c75325e360759cd3cc5663b5 100644 --- a/build/lib/iexcode/instruments/hxp_mirrors.py +++ b/build/lib/iexcode/instruments/hxp_mirrors.py @@ -3,7 +3,7 @@ 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): +def _hxp_ioc(mirror_name): """ returns the ioc for a given mirror_name: 'm3a' / 'm4a' / 'm4r' @@ -20,7 +20,7 @@ def hxp_ioc(mirror_name): return ioc -def HXP_synch(mirror_name): +def hxp_sync(mirror_name): """ synchs the rbv and sp for all axes @@ -28,7 +28,7 @@ def HXP_synch(mirror_name): Previously: Sync_m4r """ - pv = hxp_ioc(mirror_name) + pv = _hxp_ioc(mirror_name) try: for m in range(1,7): caput(pv+'m'+str(m)+'.SYNC',1) @@ -36,12 +36,12 @@ def HXP_synch(mirror_name): print_warning_message("Check if ioc is running") -def hxp_print(mirror_name): +def hxp_get_all(mirror_name,verbose=True): """ Previously: Get_HXP """ - pv = hxp_ioc(mirror_name) + pv = _hxp_ioc(mirror_name) Tx=caget(pv+"m1.RBV") Ty=caget(pv+"m2.RBV") @@ -49,16 +49,19 @@ def hxp_print(mirror_name): Rx=caget(pv+"m4.RBV") Ry=caget(pv+"m5.RBV") Rz=caget(pv+"m6.RBV") - print("\n"+mirror_name+" @ "+"%.3f" % Tx, "/","%.3f" % Ty, "/","%.3f" % Tz, "/","%.3f" % Rx, "/","%.3f" % Ry, "/","%.3f" % Rz) + + 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(): +def hxp_get_all(): """ Previously: Get_HXP """ branch = m3r_branch() if branch == 'c': - hxp_print('m3a') - hxp_print('m4a') + hxp_get_all('m3a',verbose=True) + hxp_get_all('m4a',verbose=True) else: - hxp_print('m4r') \ No newline at end of file + hxp_get_all('m4r',verbose=True) \ No newline at end of file diff --git a/build/lib/iexcode/instruments/logfile.py b/build/lib/iexcode/instruments/logfile.py deleted file mode 100644 index f4a1a97ed69286222365fe5e4f9fefee6dfcdcf2..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/logfile.py +++ /dev/null @@ -1,158 +0,0 @@ -from os.path import join,isfile - -from epics import caget, caput - -from iexcode.instruments.utilities import today - -## To do: make this work if User Folder doesn't already exist - -############################################################################################################## -############################## general logfile functions ############################## -############################################################################################################## -class Logfile: - def __init__(self,endstation_name,user_name,headerlist,entries_function): - """ - endstation: used for filename pv ('ARPES' / 'Kappa' / 'Octupole' / 'Test') - user_name: used for filepath - headerlist: header info - - """ - self.endstation_name = endstation_name - self.pv = self._name_pv() - self.userName = user_name - self.filepath = self._fpath() - self.headerlist = headerlist - self.entries_function = entries_function - - self.name_set() - - def _name_pv(self): - """ - Dictionary to get the PV in which the FileName for logging is stored - - endstation: 'ARPES' / 'Kappa' / 'Test - - Previously: logname_pv - """ - pv_dict={ - 'Test':'29idb:userStringSeq10.STR1', - 'ARPES':'29idb:userStringSeq10.STR2', - 'Kappa':'29idb:userStringSeq10.STR3', - 'Octupole':'29idb:userStringSeq10.STR4', - } - if self.endstation_name in pv_dict.keys(): - pv=pv_dict[self.endstation_name] - else: - pv='29idb:userStringSeq10.STR10' - return pv - - def name_set(self,**kwargs): - """ - Sets the string used for the FileName in scanlog and EAlog - uses logname_PV to reference PV associated with a particular ioc - **kwargs: - filename = to set a specific filename, default => YYYYMMDD_log.txt - - Previously: logname_set - """ - kwargs.setdefault('filename_suffix','_log') - kwargs.setdefault('filename',today()+kwargs['filename_suffix']+'.txt') - - filename = kwargs['filename'] - - try: - caput(self._name_pv(),filename) - print("\nLog filename = \'"+filename+"\' @ "+self._name_pv()) - print('To change filename, use logname_set(endstation_name,new_name)') - except: - print("Error: was not able to set the filename, check that 29idb ioc is running") - - - def name_get(self): - """ - Gets the string used for the FileName in scanlog and EAlog for the given scanIOC. - - Previously: logname - """ - - return caget(self._name_pv()) - - def _fpath(self): - """ - returns the full path to the logfile based on the current user in the mda scanRecord - - - Previously: logname, logname_generate - """ - try: - filename = self.name_get() - user_name = self.userName - fpath_with_subfolder = join(user_name,filename) - except: - fpath_with_subfolder = "logfile.txt" - self.name_get() - print("Couldn't read log file path, using: "+fpath_with_subfolder) - - return fpath_with_subfolder - - - def print(self, comment=''): - """ - Writes comments to the logfile on a new line - comment is a string of what you want to add to the file - e.g. comment = "------- New Sample--------" - - Previously: logprint - """ - - try: - if not isfile(self.filepath): - self.write_header() - with open(self.filepath,'a') as myfile: - myfile.write(comment) - myfile.write('\n') - - except: - print("Logprint failed") - - - def write_header(self): - """ - file path = path to where file_name lives - file_name = name of the logfile - entry is a list - - Previously: SaveFile_Header - """ - version = '1.4' - - with open(self.filepath, "w+") as f: - f.write('@Log version: '+ version+'\n\n') - f.write('FilePath '+self.endstation_name+': '+self.filepath+'\n') - - for key in self.headerlist.keys(): - f.write(key+' Header: '+ self.headerlist[key]+'\n\n') - - - - def update(self,entry_list,pv_list,format_list): - """ - To be used for scanlog and scanEA functions. - Update SaveFile_Header version number when changing the structure of the file (indexing). - - Previously: SaveFile - """ - #entry_list is the human readable portion - - if not isfile(self.filepath): - self.write_header() - - with open(self.filepath, "a+") as f: - for i in range(len(format_list)): - pv_format = "{0:"+format_list[i]+"}," - f.write(pv_format.format(pv_list[i])) - last_entry=len(format_list)-1 - pv_format="{0:"+format_list[last_entry]+"}\n" - f.write(pv_format.format(pv_list[last_entry])) - - diff --git a/build/lib/iexcode/instruments/m3r.py b/build/lib/iexcode/instruments/m3r.py index 54bb5ec77693a6857ce71dd5b87d6b4aeffd3386..fe8d151fd14b930d65df4b8c7c442ce418045d62 100644 --- a/build/lib/iexcode/instruments/m3r.py +++ b/build/lib/iexcode/instruments/m3r.py @@ -1,4 +1,5 @@ from cgi import print_arguments +from iexcode.instruments.VLS_PGM import mono_energy_get from epics import caget, caput @@ -18,6 +19,21 @@ 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 @@ -29,7 +45,7 @@ def m3r_RY_pos_sp_get(): RY_SP = caget('29id_m3r:RY_POS_SP') return RY_SP -def m3R_tweak (axis,val): +def m3r_tweak (axis,val): """ \"TX\" = lateral \"RX\" = Yaw \"TY\" = vertical \"RY\" = Pitch @@ -46,29 +62,24 @@ def m3r_tweak_pitch(sign,val=0.005): """ axis="RY" if sign == "+": - m3R_tweak(axis,val) + m3r_tweak(axis,val) elif sign == "-": - m3R_tweak(axis,-val) + 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 """ - branch = branch.lower() - positions={ - "c":[10,0,0,0,0,0], - "d":[-2.5,0,0,-13.955,-16.450,-5.15], - "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 + 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 @@ -102,7 +113,7 @@ def m3r_switch_branch(branch): ################################ M3R alignment ############################## ############################################################################################################## -def centroid(t=None,q=1): +def m3r_centroid(t=None,q=1): ''' Return position of centroid, sigma, m3r:RY (mirror pitch) Optional argument t to set camera intergration time. @@ -119,8 +130,24 @@ def centroid(t=None,q=1): print('(position, sigma, total intensity, integration time (s), mirror pitch):') return position,sigma,intensity,t,m3rRY -def m3r_align(pxl=None): +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/mpa.py b/build/lib/iexcode/instruments/mpa.py deleted file mode 100644 index 034396dbd695f609f0e5910e19ff35cec8afb499..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/mpa.py +++ /dev/null @@ -1,450 +0,0 @@ -from time import sleep -from os.path import dirname, join -import socket - -from epics import caget, caput -from iexcode.instruments.userCalcs import userCalcOut_clear,userStringSeq_clear -from iexcode.instruments.scalers import Kappa_scaler -from iexcode.instruments.AD_utilities import AD_ROI_setup -from iexcode.instruments.scanRecord import ScanRecord -from iexcode.instruments.IEX_BL_config import BL - - -""" -To do, get busy record in the mpa ioc, get user calcs in the mpa ioc - - -""" -############################################################################################################## -############################## PVs ############################## -############################################################################################################## -mpa_pv = "29iddMPA:" -mpa_busy = "29idcScienta:mybusy2" -userCalc_ioc = "29idTest:" -DAC_pv = '29iddau1:dau1:011:DAC' -HV_val_pv = "29idKappa:userCalcOut9.A" -HV_rbv_pv = "29idKappa:userCalcOut10.OVAL" -class MPA: - """ - class for the MPA detector - """ - - def __init__(self,tth_pv, max_HV = 2990,ratio = 500,tth_dLLM=13.73,tth_dHLM=23.73): - self.pv = mpa_pv - self._reset_pv = mpa_pv+'C1O' - self._det_pv = mpa_pv + "det1:" - self._busy = mpa_busy - self._DAC_pv = DAC_pv - - self.max_HV = max_HV - self.ratio = ratio - self.tth_dLLM = tth_dLLM - self.tth_dHLM = tth_dHLM - - self._tth_pv = tth_pv - self._reset_pv = mpa_pv+'C1O' #"writing a 1 resets" - self._off_on_pv = mpa_pv+'C0O' #off/on = 0/1 - - pass - - - - def HV_pvs(self): - """ - returns the pvs for the userCalcout which hold the pvs for the mpa high voltage - """ - val_pv = HV_val_pv - rbv_pv =HV_rbv_pv - return val_pv, rbv_pv - - ############################################################################################################## - ############################## HV Control ############################## - ############################################################################################################## - - def HV_set(self,volt,verbose=True): - """ - sets the high voltage for the mpa - - Previously: MPA_HV_Set - """ - val_pv, rbv_pv = self.HV_pvs() - volt=min(volt,2990) - - caput(val_pv,volt,wait=True,timeout=18000) - sleep(1) - HV_rbv=caget(rbv_pv) - - if verbose: - print("HV = "+str(HV_rbv)+" V") - - - def HV_get(self): - """ - sets the high voltage for the mpa - """ - val_pv, rbv_pv = self.HV_pvs() - - return caget(rbv_pv) - - - def HV_on(self): - """ - turns the mpa high voltage on - - Previously: MPA_HV_ON - """ - try: - n_on=1 - tth_dial = caget(self._tth_pv+'.DRBV') - - if self.tth_dLLM <= tth_dial <= self.tth_dHLM: - print('MPA OFF: detector in direct beam (-5 < tth for mcp < 5); move away before turning HV ON.') - else: - caput(self._reset_pv,1,wait=True,timeout=18000) - caput(self._reset_pv,0,wait=True,timeout=18000) - caput(self._off_on_pv,n_on,wait=True,timeout=18000) - print("MPA - HV On") - except: - print('mpa not running') - - def HV_off(self): - """ - turns the mpa high voltage off - - Previously: MPA_HV_OFF - """ - try: - n_off=0 - caput(self._off_on_pv,n_off,wait=True,timeout=18000) - print("MPA - HV Off") - except: - print('MPA not running') - - - def HV_reset(self): - """ - resets the mpa high voltage - - Previously: MPA_HV_Reset - """ - caput(self._reset_pv,1) - print("MPA - Reset") - - - def HV_scan(self,start=2400,stop=2990,step=10,**kwargs): - """ - - Previously: MPA_HV_scan - """ - kwargs.setdefault('positioner_settling_time',1) - Kappa_scaler(1) - val_pv, rbv_pv = self._HV_pvs() - BL.mda.fillin(val_pv, rbv_pv,start,stop,step,**kwargs) - BL.mda.go(**kwargs) - - ############################################################################################################## - ############################## MCP Scripts ############################## - ############################################################################################################## - def ROI_setup(self,ROI_num=1,xcenter=535,ycenter=539,xsize=50,ysize=50,binX=1,binY=1): - """ - usage: - center of MCP, roiNum = 1 => MPA_ROI_SetUp(1,535,539,50,50) - to set up all use: mpa_ROI_setup_all(xcenter,ycenter) - """ - AD_ROI_setup('29iddMPA',ROI_num,xcenter,ycenter,xsize,ysize,binX,binY) - self._ROI_stats(ROI_num) - - def ROI_setup_all(self,xcenter=535,ycenter=539): - """ - setup up ROI - 1 => size = 50 x 50 - 2 => size = 100 x 100 - 3 => size = 150 x 150 - 4 => size = 200 x 200 - - """ - self._ROI_setup(1,xcenter,ycenter,xsize=50,ysize=50) - self._ROI_setup(2,xcenter,ycenter,xsize=100,ysize=100) - self._ROI_setup(3,xcenter,ycenter,xsize=150,ysize=150) - self._ROI_setup(4,xcenter,ycenter,xsize=200,ysize=200) - - - def ROI_stats(self,ROI_num): - """ - sequence to enable stats for mpa ROI - """ - ROI_pv=self.pv+"ROI"+str(ROI_num)+':' - stats_pv=self.pv+"Stats"+str(ROI_num)+':' - caput(stats_pv+'NDArrayPort','ROI'+str(ROI_num)) - caput(stats_pv+'EnableCallbacks','Enable') - caput(stats_pv+'ArrayCallbacks','Enable') - caput(stats_pv+'ComputeStatistics','Yes') - caput(stats_pv+'ComputeCentroid','Yes') - caput(stats_pv+'ComputeProfiles','Yes') - - def _trigger_calcOut(self,**kwargs): - """ - writes strSeq and calcOut for MPA this should go into the IOC - - **kwargs: - ADplugin = 'TIFF1:' (default) - """ - - kwargs.setdefault("ADplugin","TIFF1:") - kwargs.setdefault("save_image",False) - - ADplugin = self.pv + kwargs["ADplugin"] - Proc1 = self.pv + "Proc1:" - - #All this should moved into the MPA IOC - Calcs_mda = ScanRecord(userCalc_ioc) - - desc = "MPA busy" - n=9 - busy_CalcOut = userCalcOut_clear(Calcs_mda,n) - caput(busy_CalcOut+".DESC",desc) - caput(busy_CalcOut+".INPA",mpa_busy+" CP") - caput(busy_CalcOut+".OOPT",'Transition to non-zero') - caput(busy_CalcOut+".OUT",start_strSeq+".PROC PP") - - desc = "MPA start" - n=1 - start_strSeq = userStringSeq_clear(Calcs_mda,n) - caput(start_strSeq+".DESC",desc) - caput(start_strSeq+".LNK1", Proc1+"ResetFilter PP") - caput(start_strSeq+".STR1","Yes") - - desc = "MPA wait" - n=10 - wait_CalcOut = userCalcOut_clear(Calcs_mda,n) - caput(wait_CalcOut+".DESC",desc) - caput(wait_CalcOut+".INPA",Proc1+"NumFilter_RBV") - caput(wait_CalcOut+".INPB",Proc1+"NumFiltered_RBV") - caput(wait_CalcOut+".OOPT",'Transition to non-zero') - caput(wait_CalcOut+".OUT",done_strSeq+".PROC PP") - - desc = "MPA writeDone" - n=1 - done_strSeq = userStringSeq_clear(Calcs_mda,n) - caput(done_strSeq+".DESC","MPA writeDone") - caput(done_strSeq+".LNK1", ADplugin+"WriteFile PP") - caput(done_strSeq+".STR1","Write") - caput(done_strSeq+".LNK1", mpa_busy+" PP") - caput(done_strSeq+".STR1","Done") - - - - def self_trigger_callback(self,trigger,saveImg=False,**kwargs): - """ - used for triggering the MPA in the scanRecord, reset Proc1 and waits for finish - - trigger: adds/removes trigger to mda (True/False) - - **kwargs: - save_image = False used for appropriate trigger of ROIs - = True also saves an image based on ADplugin type - ADplugin = 'TIFF1:' (default - - by default ADplugin = 29iddMPA:TIFF1: - can use 29iddMPA:HDF1: - """ - - kwargs.setdefault("ADplugin","TIFF1:") - kwargs.setdefault("save_image",False) - - ADplugin = self.pv + kwargs['ADplugin'] - - self._trigger_calcOut(**kwargs) - - if trigger==True: - caput(ADplugin+"AutoResetFilter","Yes") - if saveImg: - caput(ADplugin+"AutoSave", "No") - caput(ADplugin+"EnableCallbacks", "Enable") - - if trigger==False: - caput(ADplugin+"AutoResetFilter","No") - if saveImg: - caput(ADplugin+"EnableCallbacks", "Disable") - caput(ADplugin+"AutoSave", "Yes") - - return mpa_busy - - def _mpa_prefix(self,**kwargs): - """ - """ - kwargs.setdefault("debug",False) - - fpath=join(dirname(dirname(BL.mda.filepath)),"mpa",'') - nextMDA = BL.mda.fileNum - prefix="mda"+str.zfill(str(nextMDA),4)+"_mpa" - return prefix - - def _trigger(self,trigger, **kwargs): - """ - Sets up / Cleans up the ScanRecord to trigger the MPA - - trigger: adds/removes trigger to mda (True/False) - - - **kwargs: - save_image = False used for appropriate trigger of ROIs - = True also saves an image based on ADplugin type - detTrigNum = 2 (default) - scan_dim = 1 (default) - ADplugin = "TIFF1" / "HDF1" - - Previously: MPA_Trigger - """ - kwargs.setdefault("detTrigNum",2) - kwargs.setdefault("save_image",False) - kwargs.setdefault('scan_dim',1) - kwargs.setdefault("ADplugin","TIFF1:") - - mpa_busy = self._mpa_trigger_callback(trigger, **kwargs) - - #adding the MPA to the scanRecord trigger - if trigger == True: - self._mpa_prefix(**kwargs) - BL.mda.triggers_set(kwargs['scan_dim'],{2:mpa_busy}) - - if trigger == False: - BL.mda.triggers_set(kwargs['scan_dim'],{2:''}) - - - - def _save_strSeq(self,**kwargs): - """ - **kwargs: - ADplugin: "TIFF1:" - """ - kwargs.setdefault("ADplugin","TIFF1:") - - ADplugin = self.pv + kwargs["ADplugin"] - - desc = "MCP datamode" - n=2 - strSeq_pv = userStringSeq_clear(BL.mda,n) - caput(strSeq_pv+".DESC",desc) - caput(strSeq_pv+".LNK1",self._det_pv+"Acquire CA NMS") - caput(strSeq_pv+".STR1","Done") - caput(strSeq_pv+".WAIT1","Wait") - caput(strSeq_pv+".LNK2",self._det_pv+"RunTimeEnable PP NMS") - caput(strSeq_pv+".STR2","1") - caput(strSeq_pv+".WAIT2","Wait") - caput(strSeq_pv+".LNK3",ADplugin+"EnableCallbacks PP NMS") - caput(strSeq_pv+".STR3","1") - - def _freerun_strSeq(self): - """ - """ - desc = "MCP freerun" - n=1 - strSeq_pv = userStringSeq_clear(BL.mda,n) - caput(strSeq_pv+".DESC",desc) - caput(strSeq_pv+".LNK1",self._det_pv+"Acquire PP NMS") - caput(strSeq_pv+".WAIT1","Wait") - caput(strSeq_pv+".STR1","Done") - caput(strSeq_pv+".LNK2","29iddMPA:TIFF1:EnableCallbacks PP NMS") - caput(strSeq_pv+".STR2","0") - caput(strSeq_pv+".WAIT2","Wait") - caput(strSeq_pv+".LNK3",self._det_pv+"RunTimeEnable PP NMS") - caput(strSeq_pv+".STR3","0") - caput(strSeq_pv+".WAIT3","Wait") - caput(strSeq_pv+".LNK4",self._det_pv+"Acquire PP NMS") - caput(strSeq_pv+".STR4","Acquire") - - - def _HV_sp_calcOut(self): - """ - """ - - desc = "MPA HV SP" - n=9 - calcOut_pv = userCalcOut_clear(BL.mda,n) - - caput(calcOut_pv+".DESC",desc) - caput(calcOut_pv+".A",0) - caput(calcOut_pv+".B",self.ratio) - caput(calcOut_pv+".C",self.max_HV) - caput(calcOut_pv+".CALC$","A") - caput(calcOut_pv+".OCAL$","MIN(A/B,C/B)") - caput(calcOut_pv+".OOPT",1) # On Change - caput(calcOut_pv+".DOPT",1) # Use 0CALC - caput(calcOut_pv+".IVOA",0) # Continue Normally - caput(calcOut_pv+".OUT",self._DAC_pv+" PP NMS") - - def _HV_rbv_calcOut(self): - """ - """ - desc = "MPA HV RBV" - n=10 - calcOut_pv = userCalcOut_clear(BL.mda,n) - - caput(calcOut_pv+".DESC",desc) - caput(calcOut_pv+".INPA",DAC_pv+' CP NMS') - caput(calcOut_pv+".B",self.ratio) - caput(calcOut_pv+".CALC$","A*B") - - def _interlock_mpa(self): - """ - """ - desc = "MPA Interlock mpa" - n=7 - calcOut_pv = userCalcOut_clear(BL.mda,n) - - caput(calcOut_pv+".DESC",desc) - tth_pv = self._tth_pv - caput(calcOut_pv+".INPA",tth_pv+".DRBV CP NMS") - caput(calcOut_pv+".B",1) - caput(calcOut_pv+".CALC$","ABS((("+str(self.tth_dLLM)+"<A && A<"+str(self.tth_dHLM)+") && (B>0))-1)") - caput(calcOut_pv+".OCAL$",'A') - caput(calcOut_pv+".OOPT",2) # When zero - caput(calcOut_pv+".DOPT",0) # Use CALC - caput(calcOut_pv+".IVOA",0) # Continue Normally - caput(calcOut_pv+".OUT",self._off_on_pv()+"PP NMS") - - - def _interlock_DAC(self): - """ - """ - desc = "MPA Interlock DAC" - n=8 - calcOut_pv = userCalcOut_clear(BL.mda,n) - - caput(calcOut_pv+".DESC",desc) - tth_pv = self._tth_pv - caput(calcOut_pv+".INPA",tth_pv+".DRBV CP NMS") - caput(calcOut_pv+".B",1) - caput(calcOut_pv+".CALC$","ABS((("+str(self.tth_dLLM)+"<A && A<"+str(self.tth_dHLM)+") && (B>0))-1)") - caput(calcOut_pv+".OCAL$",'A') - caput(calcOut_pv+".OOPT",2) # When zero - caput(calcOut_pv+".DOPT",0) # Use CALC - caput(calcOut_pv+".IVOA",0) # Continue Normally - caput(calcOut_pv+".OUT",self._DAC_pv+"_Se PP NMS") - -def reset_mpa_HV(): - """ - resetting the SRS which controls the MPA HV - Model: SRS PS350 - ip = "164.54.118.57" - """ - ip = "164.54.118.57" - # Open TCP connect to poet 1234 of GPIB-ETHERNET - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) - sock.settimeout(0.1) - sock.connect((ip, 1234)) - - # Set mode as CONTROLLER - sock.send(b'++mode 1\n') - - # specify GPIB address of device being controlled - addr = "14" - str1="++addr"+addr+'\n' - sock.send(bytes(str1,'utf-8')) - - # reset SRS PS350 - #sock.send("*RST\n") - - # turn the high voltage on, clearing any current or voltage trips - sock.send(b"HVON\n") \ No newline at end of file diff --git a/build/lib/iexcode/instruments/resolution.py b/build/lib/iexcode/instruments/resolution.py index cd8c8367cf08540c76971236c93793493377778d..7cdbf8fee6456c02f55f31c95e1fab5400d932ac 100644 --- a/build/lib/iexcode/instruments/resolution.py +++ b/build/lib/iexcode/instruments/resolution.py @@ -2,8 +2,9 @@ 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 get_branch, getE, slit_get +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, getSESslit from iexcode.instruments.ARPES import ARPES_extra_pvs @@ -16,7 +17,7 @@ def resolution(): ARPES: total resolution i.e. sqrt(kbT^2 + analyzer^2 + BL^2); default SES slit = 5. Kappa: beamline contribution only """ - branch = get_branch() + 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)) @@ -24,10 +25,13 @@ def resolution(): if branch == "c": slit_SES = getSESslit() PE = int(EA.PassEnergy) - T = caget(ARPES_extra_pvs['TA']) - resolution_ARPES(grt,hv_eV,slit_size,PE,slit_SES,T,verbose=True) + 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): @@ -105,7 +109,7 @@ def resolution_ARPES(grt,hv_eV,slit_size,PE,slit_SES,T,verbose=True): return resolution -def Resolution_BL_eff(grating,hv,slit_3C,PE,slit_SES,T,Ef): +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) @@ -118,7 +122,7 @@ def Resolution_BL_eff(grating,hv,slit_3C,PE,slit_SES,T,Ef): print("BL_eff: "+"%.0f" % effective, "meV") -def Resolution_BL_eff2(grating,hv,slit_3C,PE,slit_SES,T,Ef,Dirty_Au): +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) diff --git a/build/lib/iexcode/instruments/scalers.py b/build/lib/iexcode/instruments/scalers.py index 9f608be1cc6a6ea3b5e85645363753e556cfa12a..c3cef3bf48a9f7ac23ac76f28811f5e2e99f4ab5 100644 --- a/build/lib/iexcode/instruments/scalers.py +++ b/build/lib/iexcode/instruments/scalers.py @@ -1,5 +1,4 @@ from math import floor - from epics import caput,PV import iexcode.instruments.cfg as iex @@ -8,7 +7,8 @@ def scaler_cts(time_seconds=0.1,verbose=True): """ sets the scalers counting for the endstation defined in BL """ - if iex.BL.ioc == 'Kappa': + 'For new endstation modify here:' + if iex.BL.endstation_name == 'kappa': Kappa_scaler(time_seconds,verbose=verbose) else: pass @@ -25,8 +25,26 @@ def Kappa_scaler(time_seconds=0.1,verbose=True): pv=PV(mpa_NumFilter) if pv.connected(): - caput(mpa_NumFilter,floor(time_seconds)) + caput(mpa_NumFilter,max(floor(time_seconds),1)) if verbose: print("Integration time set to:", str(time_seconds)) +class Scaler: + def __inti__(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 index 566a82d173ee791436f0253c1e1ff4187d3a8299..2fc7d396b6bc9a886699195dbb43da3a976527af 100644 --- a/build/lib/iexcode/instruments/scanRecord.py +++ b/build/lib/iexcode/instruments/scanRecord.py @@ -5,10 +5,9 @@ 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 def scan_fillin(VAL,RBV,start,stop,steps_points,**kwargs): """ @@ -207,7 +206,7 @@ class ScanRecord: """ return saveData_get_all(self.ioc)['baseName'] - def scanRecord_run(self): + def current_run(self): """ returns the current run by parsing the filepath in the SaveData for ioc @@ -218,7 +217,7 @@ class ScanRecord: current_run=filepath[m:m+6] return current_run - def scanRecord_user(self): + def user_name(self): """ returns the current user by parsing the filepath in the SaveData for ioc @@ -227,7 +226,7 @@ class ScanRecord: subdir=saveData_get_all(self.ioc)['subDir'] m=subdir.find('/mda') if m == 0 : - current_user='Staff' + current_user='staff' elif m > 0: current_user=subdir[1:m] else: @@ -320,7 +319,6 @@ class ScanRecord: def reset_scan_dim(self,scan_dim,**kwargs): """ Resets all the scanRecords (scanDIM=1,2,3,4) for a given IOC - uses Reset_Scan() **kwargs: detector_dictionary trigger_dictionary @@ -536,13 +534,22 @@ class ScanRecord: Clear all scan detectors triggers trigger_dictionary = {trigger_num:pv} - Previously: Clear_Scan_Triggers """ 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 @@ -651,22 +658,26 @@ class ScanRecord: ############################################################################################################## ############################# table scans ############################## ############################################################################################################## - def fillin_table(self,scan_dim,val_pv,rbv_pv,myarray,**kwargs): + 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) @@ -746,7 +757,11 @@ class ScanRecord: 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') if self.check(scan_dim): filename = self.prefix() fileNum = self.fileNum() diff --git a/build/lib/iexcode/instruments/scratch.py b/build/lib/iexcode/instruments/scratch.py deleted file mode 100644 index ded5e799532a9f085e7e81f233ff0d2a7e4267a8..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/scratch.py +++ /dev/null @@ -1,44 +0,0 @@ -############################################################################################################## -############################## setting folder from ARPES ############################## -############################################################################################################## -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('ftp',False) - kwargs.setdefault('debug',False) - - run = kwargs['run'] - - if kwargs['debug']: - print("run,folder,user_name,ioc,ftp: ",run,BL.folder,user_name,BL.ioc,kwargs['ftp']) - - # Create User Folder: - make_user_folders(run,BL.folder,user_name,BL.endstation,ftp=kwargs['ftp']) - sleep(5) - - if kwargs["set_folders"]: - # Set up MDA folder: - folder_mda(run,BL.folder,user_name,BL.prefix,BL.ioc) - logfile_name_set(BL.endstation) - logfile_header(BL.endstation,BL.ioc,ARPES_log_header()) - - - #Set up Scienta folders: - try: - userPath = "/net/s29data/export/data_29id"+BL.folder+"/"+run+"/"+user_name+"/" - folders_EA(userPath,filePrefix="EA") - except: - print_warning_message("EA ioc is not running, cannot set folder") \ No newline at end of file diff --git a/build/lib/iexcode/instruments/shutters.py b/build/lib/iexcode/instruments/shutters.py index 39eb4da5630d605bd2eeece1d42095bcf94b64dc..8279908e4238c86e583d37f4efc55646a6bdc78d 100644 --- a/build/lib/iexcode/instruments/shutters.py +++ b/build/lib/iexcode/instruments/shutters.py @@ -8,27 +8,49 @@ import iexcode.instruments.cfg as iex from iexcode.instruments.utilities import dateandtime +def shutter_check(): + """ + 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: + 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(): +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) - print("Opening Main Shutter...") + if verbose: + print("Opening Main Shutter...") -def main_shutter_close(): +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) - print("Closing Main Shutter...") + if verbose: + print("Closing Main Shutter...") def main_shutter_status(): """ @@ -49,34 +71,21 @@ def main_shutter_status(): return shutter_open -def main_shutter_check_open(): - """ - Checks main 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: - print("Shutter is now open" , dateandtime()) - break ############################################################################################################## ################################ branch shutters ############################## ############################################################################################################## -def branch_shutter_status(verbose=False): +def branch_shutter_status(branch=None,verbose=False): """ checks on the status of the main shutter and returns shutter_open = True / False """ - pvA="PA:29ID:S"+iex.BL.branch+"S_BLOCKING_BEAM.VAL" - pvB="PB:29ID:S"+iex.BL.branch+"S_BLOCKING_BEAM.VAL" + if branch == None: + branch = iex.BL.branch + pvA="PA:29ID:S"+branch+"S_BLOCKING_BEAM.VAL" + pvB="PB:29ID:S"+branch+"S_BLOCKING_BEAM.VAL" #"ON" = 1 => shutter open - status=caget(pvA)+caget(pvA) + status=caget(pvA)+caget(pvB) if status == 2: shutter_open=True else: @@ -84,30 +93,34 @@ def branch_shutter_status(verbose=False): if verbose: status = 'Open' if shutter_open else 'Closed' - print(iex.BL.branch+"-shutter is "+status) + print(branch+"-shutter is "+status) return shutter_open -def branch_shutter_close(): +def branch_shutter_close(branch=None,verbose=False): """ closes current branch shutter Previously: Close_BranchShutter """ - caput("PC:29ID:S"+iex.BL.branch+"S_CLOSE_REQUEST.VAL",1,wait=True,timeout=18000) - print("Closing "+iex.BL.branch+"-Shutter...") + if branch == None: + branch = iex.BL.branch + caput("PC:29ID:S"+branch+"S_CLOSE_REQUEST.VAL",1,wait=True,timeout=18000) + print("Closing "+branch+"-Shutter...") -def branch_shutter_open(): +def branch_shutter_open(branch=None,verbose=False): """ Opens current branch shutter Previoulsy: Open_BranchShutter """ - shutter_status = branch_shutter_status + if branch == None: + branch = iex.BL.branch + shutter_status = branch_shutter_status() if shutter_status: - print(iex.BL.branch+"-Shutter already open...") + print(branch+"-Shutter already open...") else: - caput("PC:29ID:S"+iex.BL.branch+"S_OPEN_REQUEST.VAL",1,wait=True,timeout=18000) - print("Opening "+iex.BL.branch+"-Shutter...") - \ No newline at end of file + caput("PC:29ID:S"+branch+"S_OPEN_REQUEST.VAL",1,wait=True,timeout=18000) + print("Opening "+branch+"-Shutter...") + diff --git a/build/lib/iexcode/instruments/slits.py b/build/lib/iexcode/instruments/slits.py index e843bac8ca53de7f353422325a9a23ba63c8e625..42448064d4693a4a3902a348579651c12c21805a 100644 --- a/build/lib/iexcode/instruments/slits.py +++ b/build/lib/iexcode/instruments/slits.py @@ -1,17 +1,16 @@ from numpy import inf,nan from epics import caget, caput -from .IEX_endstations import * - +import iexcode.instruments.cfg as iex from iexcode.instruments.shutters import main_shutter_close -from iexcode.instruments.utilities import print_warning_message, read_dict -from iexcode.instruments.VLS_PGM import mono_get_all +from iexcode.instruments.utilities import print_warning_message from iexcode.instruments.encoders import encoders_reset_zero + slit_ioc="29idb:" -def slits_dictionary(): +def _slits_dictionary(): """ dictionary of slit pv names for two and four blade slit assemblies @@ -22,7 +21,28 @@ def slits_dictionary(): d = { 'slit1A' : ('Slit1H','Slit1V'), 'slit2B' : ('Slit2H','Slit2V'), + 'slit3C' : None, 'slit3D' : ('Slit4V') + + } + return d + +def slit_name_list(): + d=_slits_dictionary + for key in d.keys(): + print(key) + +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 @@ -31,11 +51,19 @@ def slits_pvs(slit_name): returns the rbv and drive for the size,center (rbv_size,val_size),(rvb_center,val_center) """ - slit_pv = slit_ioc + slit_name - size_rbv = slit_pv +'t2.D' - size_val = slit_pv +'center.VAL' - center_rbv = slit_pv +'t2.C' - center_val = slit_pv +'center.VAL' + d = _slits_dictionary() + if slit_name in d.keys(): + if slit_name == 'slit3C': + size_rbv = '29idb:Slit3CRBV' + size_val = '29idb:Slit3CFit.A' + center_rbv = None + center_val = None + else: + slit_pv = slit_ioc + slit_name + size_rbv = slit_pv +'t2.D' + size_val = slit_pv +'center.VAL' + center_rbv = slit_pv +'t2.C' + center_val = slit_pv +'center.VAL' return (size_rbv,size_val),(center_rbv,center_val) @@ -43,8 +71,11 @@ def slits_synch(slit_name): """ synch the motor position and the slit table for all the beamline slits """ - slit_pv = slit_ioc + slit_name+'sync.PROC' - caput(slit_pv,1) + d = _slits_dictionary() + if slit_name in d.keys(): + if slit_name != 'slit3C': + slit_pv = slit_ioc + slit_name+'sync.PROC' + caput(slit_pv,1) def slits_sync_all(): """ @@ -53,62 +84,46 @@ def slits_sync_all(): Previously: SyncAllSlits """ - slit_list = slits_dictionary() + slit_list = _slits_dictionary() for slit_name in slit_list.keys(): slits_synch(slit_name) -def slits_print_all(): - """ - gets the current position of slit-1A, slit-2B, slit-3C, slit-3D - - Previously Get_Slits - """ - slits_sync_all() - slit1A_get(verbose=True) - slit2B_get(verbose=True) - - slit3C_get(verbose=True) - slit3D_get(verbose=True) -def slits_get_all(verbose=False): +def slits_get_all(verbose=True): """ returns a dictionary with the current slit status """ vals = {} - vals['slit1A_size'], vals['slit1A_center'] = slit1A_get(verbose=False) - vals['slit2B_size'], vals['slit2B_center'] = slit2B_get(verbose=False) - vals['slit3C_size'] = slit3C_get(verbose=False) - vals['slit3D_size'],vals['slit3D_center'] = slit3D_get(verbose=False) - - if verbose: - slits_print_all() - return vals + vals['slit1A_size'], vals['slit1A_center'] = slit1A_get(verbose=verbose) + vals['slit2B_size'], vals['slit2B_center'] = slit2B_get(verbose=verbose) + vals['slit3C_size'] = slit3C_get(verbose=verbose) + vals['slit3D_size'],vals['slit3D_center'] = slit3D_get(verbose=verbose) def slits_set(slit_name,size,center,verbose=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) + size = (H_size, V_size) #inf => all the way open center = (H_center, V_center) Previously: SetSlit """ - d = slits_dictionary() + d = _slits_dictionary() #syncing slits_synch(slit_name) - for i,slit_HV in enumerate(d[slit_name]): #H and V - (size_rbv,size_val),(center_rbv,center_val) = slits_pvs(slit_HV) - caput(size_val, size[i],timeout=180) - caput(center_val, center[i],timeout=180) - - if verbose: - if (d[slit_name])>1: - print(slit_name + " = ("+str(round(size[0],3))+"x"+str(round(size[1],3))+") @ ("+str(center[0])+","+str(center[1])+")") - else: - print(slit_name + " = ("+str(round(size[0],3))+") @ ("+str(center[0])+")") - + if inf in size: + size = _slits_wide_open_dictionary()[slit_name] + if d[slit_name] != None: + for i,slit_HV in enumerate(d[slit_name]): #H and V + (size_rbv,size_val),(center_rbv,center_val) = slits_pvs(slit_HV) + if center_rbv != None: + caput(center_val, center[i],timeout=180) + if size_rbv != None: + caput(size_val, size[i],timeout=180) + else: + print_warning_message("Not a valid slit_name") return size,center @@ -117,7 +132,7 @@ def slits_get(slit_name,verbose=True): returns the current H_size,V_size,H_center,V_center """ - d=slits_dictionary() + d=_slits_dictionary() size = [] center = [] @@ -126,8 +141,12 @@ def slits_get(slit_name,verbose=True): for slit_HV in d[slit_name]: #H and V (size_rbv,size_val),(center_rbv,center_val) = slits_pvs(slit_HV) - size.append(caget(size_rbv)) - center.append(caget(center_rbv)) + if size_rbv != None: + size.append(caget(size_rbv)) + if center_rbv != None: + center.append(caget(center_rbv)) + else: + center.append(0) if verbose: if (d[slit_name])>1: @@ -167,7 +186,7 @@ def slits_scan_size(slit_name,direction,start,stop,step,**kwargs): kwargs.setdefault('center',slits_get(slit_name,verbose=False)[1]) kwargs.setdefault('execute',True) - slit_H,slit_V = slits_dictionary()[slit_name] + slit_H,slit_V = _slits_dictionary()[slit_name] if direction == 'H': (size_rbv,size_val),(center_rbv,center_val) = slits_pvs(slit_H) @@ -177,9 +196,9 @@ def slits_scan_size(slit_name,direction,start,stop,step,**kwargs): #set slit center slits_set_center(slit_name,kwargs['center']) #scan - BL.mda.fillin(size_rbv,size_val,start,stop,step,**kwargs) + iex.BL.mda.fillin(size_rbv,size_val,start,stop,step,**kwargs) if kwargs['execute']: - BL.mda.go(**kwargs) + iex.BL.mda.go(**kwargs) def slits_scan_center(slit_name,direction,start,stop,step,**kwargs): """ @@ -187,11 +206,13 @@ def slits_scan_center(slit_name,direction,start,stop,step,**kwargs): 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) - slit_H,slit_V = slits_dictionary()[slit_name] + slit_H,slit_V = _slits_dictionary()[slit_name] if direction == 'H': (size_rbv,size_val),(center_rbv,center_val) = slits_pvs(slit_H) @@ -201,9 +222,10 @@ def slits_scan_center(slit_name,direction,start,stop,step,**kwargs): #set slit center slits_set_size(slit_name,kwargs['size']) #scan - BL.mda.fillin(center_rbv,center_val,start,stop,step,**kwargs) + iex.BL.mda.fillin(center_rbv,center_val,start,stop,step,**kwargs) if kwargs['execute']: - BL.mda.go(**kwargs) + iex.BL.mda.go(**kwargs) + def slit1A_scribe_marks(): """ @@ -231,11 +253,6 @@ def slit1A_set(H_size,V_size,verbose=True,**kwargs): kwargs.setdefault('center',(0,0)) slit_name = 'slit1A' - if H_size in [inf,nan,None]: - H_size=4.5 - if V_size in [inf,nan,None]: - V_size=4.5 - size = (H_size,V_size) center = kwargs['center'] slits_set(slit_name,size,center, verbose=verbose) @@ -244,8 +261,7 @@ def slit1A_get(verbose=True): """ returns the current (H_size,V_size),(H_center,V_center) """ - slit_name = "slit1A" - + slit_name = 'slit1A' return slits_get(slit_name,verbose=verbose) def slit2B_set(H_size,V_size,verbose=True,**kwargs): @@ -261,26 +277,10 @@ def slit2B_set(H_size,V_size,verbose=True,**kwargs): kwargs.setdefault('center',(0,0)) slit_name = "slit2B" - if H_size in [inf,nan,None]: - H_size=6 - if V_size in [inf,nan,None]: - V_size=8 - size = (H_size,V_size) center = kwargs['center'] slits_set(slit_name,size,center, verbose=verbose) -def slit2B_set_small(Hsize,Vsize,coef,verbose=True,**kwargs): - """ - Used to scale the aperature size by coef - Hsize = Hsize * coef - Vsize = Vsize * coef - """ - Hsize = Hsize * coef - Vsize = Vsize * coef - print_warning_message("closing Slit-2B down by a factor of", coef, "!!!") - slit2B_set(Hsize,Vsize,verbose=True,**kwargs) - def slit2B_get(verbose=True): """ returns the current (H_size,V_size),(H_center,V_center) @@ -295,8 +295,10 @@ def slit2B_encoders_reset(Hcenter,Vcenter): Previously: Reset_Slit2B_Encoders """ - encoders_reset_zero('slit2B',Hcenter,Vcenter) - slits_synch('slit2B') + 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): @@ -305,80 +307,80 @@ def slit3C_set(size,verbose=True): Previously SetSlit3C """ - position=round(slit_3C_fit(size),1) - caput("29idb:Slit3CFit.A",size,wait=True,timeout=18000) - - if verbose: - print("Slit-3C =",size,"um - ( m24 =",position,")") + slit_name = 'slit3C' + center = None + slits_set(slit_name,size,center, verbose=verbose) def slit3C_get(size,verbose=True): """ gets slit-3C (ARPES resolution defining slit) returns size, position """ - size, position = slit_3C_rbv() - - if verbose: - print("Slit-3C =",size,"um - ( m24 =",position,")") - - return size, position + slit_name = "slit3C" + return slits_get(slit_name,verbose=verbose) -def slit3D_set(V_size,verbose=True,**kwargs): +def slit3D_set(V_size,position=None,verbose=True): """ - 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 => current value + set the exit slit for the D-branch Previously: SetSlit3D """ - kwargs.setdefault('center',slit3D_get(verbose=False)[1]) slit_name = "slit3D" if V_size in [inf,nan,None]: V_size=2000 size = (V_size) - center = kwargs['center'] - slits_set(slit_name,size,center,verbose=verbose) + if position == None: + center = slit3D_get()[1] + else: + center = (position) + + slits_set(slit_name,size,center,verbose=False) + + if position == 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 = "slit1A" - (V_size),(V_center) = slits_get(slit_name) + slit_name = "slit3D" + (V_size),(V_center) = slits_get(slit_name,verbose) V_size = round(V_size,3) V_center = round(V_center,3) return V_size,V_center -def slit3D_encoders_reset(Hcenter,Vcenter): +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 """ - encoders_reset_zero('slit3D',Hcenter,Vcenter) - slits_synch('slit3D') -def exit_slit(branch, size, verbose=True): + slit_name = 'slit3D' + slits_set(slit_name,(0),(Vcenter), verbose=True) + encoders_reset_zero(slit_name) + slits_synch(slit_name) + +def exit_slit(size, verbose=True): """ verbose used to supress printing Previously: SetExitSlit """ + branch=iex.BL.mda.branch if branch == "c": slit3C_set(size, verbose) elif branch == "d": slit3D_set(size, verbose) - elif branch == "e": - slit3D_set(size, verbose) - - @@ -386,7 +388,6 @@ def exit_slit(branch, size, verbose=True): ################################ slit fits ############################## ############################################################################################################## - def aperture_fit(hv,slit_num): """ used close the beamline apertures/slits to only take the center of the beam, @@ -394,12 +395,12 @@ def aperture_fit(hv,slit_num): Previously Aperture_Fit """ - K=slit_Coef(slit_num)[1] + 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 slit_Coef(slit_num): +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 @@ -428,11 +429,10 @@ def slit_Coef(slit_num): return pv,K -def slit_3C_fit(size): +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 + empirically determine offline with a camera, coeffients used by epics Previously: Slit3C_Fit """ @@ -446,13 +446,13 @@ def slit_3C_fit(size): motor=K0+K1*size+K2*size**2+K3*size**3+K4*size**4+K5*size**5+K6*size**6 return motor -def slit_3C_rbv(): +def slit_3C_fit_calc_size(position): """ - used to convert slit motor position to 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_RBV """ - position=caget("29idb:m24.RBV") K0=299.66 K1=16.404 K2=1.5572 @@ -461,49 +461,6 @@ def slit_3C_rbv(): 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, position - -############################################################################################################## -################################ beamline slits ############################## -############################################################################################################## - -def slits_set_BL(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) + return size - Previously: SetSlit_BL - """ - mono_vals=mono_get_all() - hv_rbv = mono_vals['ENERGY_MON'] - grt = mono_vals['GRT'] - - # 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(FileName='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],H1_center,V1_center,verbose) # standard operating - slit1A_set(Size2B[0],Size2B[1],H2_center,V2_center,verbose) diff --git a/build/lib/iexcode/instruments/staff.py b/build/lib/iexcode/instruments/staff.py index ba5648b20ddbb97055a2626f03afbdec84e006b3..dfca99fdd25c07ea7fd5e109bd40413c88014bac 100644 --- a/build/lib/iexcode/instruments/staff.py +++ b/build/lib/iexcode/instruments/staff.py @@ -1,42 +1,11 @@ -from os import listdir,mkdir,chmod -from os.path import join, isfile, exists - -def folders_startup(run): - """ - Creates the run directories for the following: - data_29idb - data_29idc - data_29idd - - calls folder_ARPES('Staff');folder_Kappa('Staff') - - print text required to modify the rsynch crontab - - previously: Folders_Startup - """ - data_directories=['data_29idb','data_29idc','data_29idd'] - dserv="/net/s29data/export/" - for dataDir in data_directories: - path=join(dserv,dataDir,run) - print(path) - if not (exists(path)): - mkdir(path) - - #folders_ARPES('Staff',create_only=True) - #folders_Kappa('Staff',create_only=True) - - txt="\n\n\nupdate the rsync portion the 29id@nerdy crontab\n" - txt+="*/1 * * * * /usr/bin/rsync -av --exclude=core /net/s29data/export/data_29idd/"+run+" kip:/net/kip/sftp/pub/29iddftp/files > /home/beams22/29ID/cronfiles/cptoftp-currrun-d.log 2>&1" - txt+=("\n") - txt+="*/1 * * * * /usr/bin/rsync -av --exclude=core /net/s29data/export/data_29idd/"+run+" kip:/net/kip/sftp/pub/29iddftp/files > /home/beams22/29ID/cronfiles/cptoftp-currrun-d.log 2>&1" - print(txt) +import iexcode.instruments.cfg as iex ############################################################################################################## ############################## staff detectors ############################## ############################################################################################################## -def staff_detector_dictionary(xrays=True): +def staff_detector_dictionary(): """ returns a dictionary of the default detectors @@ -75,4 +44,6 @@ def staff_detector_dictionary(xrays=True): det_dict.update(diodes) det_dict.update(slits_apertures) det_dict.update(mono_details) - return det_dict \ No newline at end of file + return det_dict + + diff --git a/build/lib/iexcode/instruments/storage_ring.py b/build/lib/iexcode/instruments/storage_ring.py index a2269b8e853b181f4efacb0c0be43d4316c028e8..de3e7fb1e1099d1cdd978e43db6db4456042f1e5 100644 --- a/build/lib/iexcode/instruments/storage_ring.py +++ b/build/lib/iexcode/instruments/storage_ring.py @@ -9,14 +9,14 @@ from time import sleep from iexcode.instruments.utilities import dateandtime -def wait_for_beam(): +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<80): + if (SR<ring_current): sleep(30) else: print("Beam is back -"+dateandtime()) diff --git a/build/lib/iexcode/instruments/utilities.py b/build/lib/iexcode/instruments/utilities.py index 3e4b739171c309dee52bff4b64bcfba7f6fedf8d..fb052f8e1087624849bcdaf1e13303f4246976ea 100644 --- a/build/lib/iexcode/instruments/utilities.py +++ b/build/lib/iexcode/instruments/utilities.py @@ -9,7 +9,6 @@ import sys import ast import os import numpy as np -from numpy import inf from epics import caget, caput @@ -83,20 +82,20 @@ def playsound(sound='FF'): sounds = '/home/beams/29IDUSER/Documents/User_Macros/Macros_29id/Sound_Files/hallelujah.wav' os.system('aplay ' + sounds) -def RangeUp(start,end,step): +def range_up(start,end,step): while start <= end: yield start start += abs(step) -def RangeDown(start,end,step): +def range_down(start,end,step): while start >= end: yield start start -= abs(step) def EgForLoop(): - for hv in RangeDown(2000,500,-500): + for hv in range_down(2000,500,-500): print(hv) - for hv in RangeUp(500,2000,500): + for hv in range_up(500,2000,500): print(hv) def take_closest_value(my_list,my_number): @@ -211,3 +210,25 @@ def AbortScript(): 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/vortexs29.py b/build/lib/iexcode/instruments/vortexs29.py deleted file mode 100644 index 81deb7330942fbeaeb31d6e092c9fbceeb878a78..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/instruments/vortexs29.py +++ /dev/null @@ -1,91 +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 vortex(energy,time=1): - cen, wid = vortex_Ecal(energy) - set_roi1(cen,wid) - -def set_roi1(cen,wid): - caput('29idVORTEX:mca1.R0LO',round(cen-wid/2)) - caput('29idVORTEX:mca1.R0HI',round(cen+wid/2)) - -def set_roi2(cen,wid): - caput('29idVORTEX:mca1.R1LO',round(cen-wid/2)) - caput('29idVORTEX:mca1.R1HI',round(cen+wid/2)) - -def vortex_Ecal(energy): - cen = 12.8 + 0.72*energy - wid = 120 - return cen, wid - -def mcacounttime(time): - caput('29idVORTEX:mca1.PRTM',time) - -def runmca(time): - caput('29idVORTEX:mca1.PRTM',time) - sleep(0.1) - caputw('29idVORTEX:mca1EraseStart',1) - -def mcaoff(): - caput('29idd:Unidig1Bo1',1) - -def mcaon(): - caput('29idd:Unidig1Bo1',0) - -def savemca(): - caput('29idKappa:scan1.T2PV','29idVORTEX:scanH.EXSC') - caput('29idKappa:scan1.D16PV','29idVORTEX:mca1.R0') - caput('29idKappa:scan1.D17PV','29idVORTEX:mca1.R1') - caput('29idKappa:scan1.D49PV','29idd:userTran1.D') - caput('29idKappa:scan1.D50PV','29idd:userTran1.E') - sleep(1) - -def nosavemca(): - caput('29idKappa:scan1.T2PV','29idVORTEX:mca1EraseStart') - caput('29idKappa:scan1.D16PV','29idVORTEX:mca1.R0') - caput('29idKappa:scan1.D17PV','29idVORTEX:mca1.R1') - caput('29idKappa:scan1.D49PV','29idd:userTran1.D') - caput('29idKappa:scan1.D50PV','29idd:userTran1.E') - sleep(1) - -def nomca(): - caput('29idKappa:scan1.T2PV','') - caput('29idKappa:scan1.D16PV','') - caput('29idKappa:scan1.D17PV','') - caput('29idKappa:scan1.D49PV','') - caput('29idKappa:scan1.D50PV','') - sleep(1) - - -def scan_num(): - scan = caget('29idKappa:saveData_message') - loc = scan.find('.') - if (loc==-1): - scannum=0 - else: - scannum =int(scan[loc-4:loc]) - return scannum - -def mcafileinit(): - # mainpath = '/net/s4data/export/sector4/4idc/mda' - scanrecpath = caget('29idKappa:saveData_subDir') - scan = scan_num()+1 - caput('4idcVORTEX:saveData_subDir', '/'+ scanrecpath+'/S'+str(scan)) - caput('4idcVORTEX:saveData_scanNumber',1) - - -def chkmcasave(): - if (caget('29idKappa:scan1.T2PV')=='29idVORTEX:scanH.EXSC'): - print('Saving mca files') - mcafileinit() - - diff --git a/build/lib/iexcode/instruments/xrays.py b/build/lib/iexcode/instruments/xrays.py index a86cc09a41fb7ac1b40b556361dd536aa75a9a2f..0dd844574642d4f26a294ea1e7a15a4821ba0e73 100644 --- a/build/lib/iexcode/instruments/xrays.py +++ b/build/lib/iexcode/instruments/xrays.py @@ -8,18 +8,18 @@ from time import sleep from epics import caget,caput import iexcode.instruments.cfg as iex - +from iexcode.instruments.cameras import _enable_endstation_cameras +from iexcode.instruments.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.VLS_PGM import * -from iexcode.instruments.slits import * +from iexcode.instruments.Logfile import log_update +from iexcode.instruments.m3r import m3r_align,m3r_branch,m3r_switch_branch,m3r_position_dictionary from iexcode.instruments.shutters import * -from iexcode.instruments.gate_valves import * -from iexcode.instruments.diagnostics import * -from iexcode.instruments.m3r import * -from iexcode.instruments.cameras import _enable_endstation_cameras +from iexcode.instruments.slits import * from iexcode.instruments.utilities import print_warning_message,make_table -from iexcode.instruments.current_amplifiers import ca_average -from iexcode.instruments.Logfile import log_update +from iexcode.instruments.valves import * +from iexcode.instruments.VLS_PGM import * mpa = iex.mpa @@ -206,7 +206,7 @@ def energy_get_all(verbose=True): """ 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'] + keylist = ['ID_mode', 'ID_QP_ratio', 'ID_sp', 'ID_rbv','hv','grating'] values = [] for key in keylist: values.append(d[key]) @@ -216,10 +216,13 @@ def energy_get_all(verbose=True): return tuple(values) def energy_get(): - hv = getE() + """ + return the mono energy readback + """ + hv = mono_energy_get() return hv -def energy(hv_eV,slit_coeff=1,m3r=True,verbose=True): +def energy(hv_eV,slit_coeff=1,m3r=True,QP_ratio=100,verbose=True): """ sets the ID for optimal flux based on calibration sets the mono @@ -230,31 +233,19 @@ def energy(hv_eV,slit_coeff=1,m3r=True,verbose=True): m3r => if True optimizes the mirror for the d-branch only Previously: Set_BL, energy """ - if iex.BL.xrays: - if hv_eV != _energy_range_check(hv_eV): - message_string = 'request 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(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: - if iex.BL.branch() == 'd': - print('\nalign_m3r()') - try: - m3r_align() - sleep(1) - if m3r_RY_pos_sp_get() == m3r_RY_pos_sp(): - m3r_align() - except: - print('Unable to align; check camera settings.') - else: - message_string = 'iex.BL.xrays = False, energy is not set' + if hv_eV != _energy_range_check(hv_eV): + message_string = 'request 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(hv_eV,QP_ratio,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 @@ -277,24 +268,80 @@ def _energy_range_check(hv): hv = np.max(hv_min,hv) return hv -def mvid_SP(val): +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 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 + """ + mono_vals=mono_get_all() + hv_rbv = mono_vals['ENERGY_MON'] + grt = mono_vals['GRT'] + + # 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(FileName='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],H1_center,V1_center,verbose) # standard operating + slit1A_set(Size2B[0],Size2B[1],H2_center,V2_center,verbose) + + +def mvID(val,QP_ratio=100): """ Sets the ID absolute set point (not optimized , mono & apertures stay fixed). to go to most flux use energy """ - ID_energy_set(val) - ID_SP_set(val) + ID_SP_set(val,QP_ratio=100) -def mvid(val): +def mvID_calibrated(val,QP_ratio=100): """ Sets the ID peak to val (calibrated). """ - ID_energy_set(val) + ID_energy_set(val,QP_ratio) -def _scan_ID(ID_sp_start,ID_sp_stop,ID_sp_step,**kwargs): +def scan_ID(ID_sp_start,ID_sp_stop,ID_sp_step,**kwargs): """ scan the ID set point """ @@ -312,9 +359,9 @@ def getE(): """ Returns current mono set point. """ - return mono_energy_get() + return energy_get() -def switch_gratings(grating): +def grating(grating): """ used to switch between gratings grating = 'HEG' / 'MEG' @@ -340,13 +387,12 @@ def switch_gratings(grating): else: print("grating: "+grating) -def mvgrating(grating): +def grating_get(): """ - Change mono grating: - HEG = high resolution, low flux - MEG = medium resolution, high flux + returns the current grating """ - switch_gratings(grating) + grt = mono_grating_get() + return grt def polarization(ID_mode): """ @@ -360,13 +406,12 @@ def polarization_get(): """ ID_mode_get() -def scanhv(start,stop,step,average_pnts=1,**kwargs): +def scanmono(start,stop,step,average_pnts=1,**kwargs): """ scans the mono at the current ID value """ - #global BL - ca_average(average_pnts) + ca_average(average_pnts,ca_detector_list(iex.BL.branch)) mono_scan_fillin(iex.BL.mda,start,stop,step,**kwargs) @@ -376,43 +421,14 @@ def scanhv(start,stop,step,average_pnts=1,**kwargs): mono_scan_after(iex.BL.mda) -def scanE(start,stop,step,ID_offset=0,mesh='stay',average_pnts=1,scan_dim=1,**kwargs): - """ - sets the ID and then scans the mono - - hv_start,hv_stop,hv_step: are the mono start, stop, step energies - ID_offset: used to position the ID - None => the ID does not move - otherwise ID_energy_set = (stop-start)/2 + ID_offset - mesh: used to specifiy mesh status (for normalization) - => mesh='y': drops in the mesh for normalization (D branch only); retracts it at the end. - => mesh='stay': to leave the mesh in after the scan is finished - => mesh='n': no mesh. - **kwargs - scan_dim - positioner_settling_time = 0.2 - """ - - mda = iex.BL.mda - ca_average(average_pnts) - - if ID_offset != None: - ID_energy_set = (start+stop)/2.0 + ID_offset - - apertures_set() - - mono_scan_fillin(mda,scan_dim,start,stop,step,**kwargs) - - mono_energy_set(start) - iex.BL.mda.go(scan_dim) - - mono_scan_after(mda,scan_dim) - -def scanXAS(ID_eV,start_stop_step_lists,**kwargs): +def scanXAS(start_stop_step_lists,ID_eV=None,ID_tracking=False, **kwargs): """ - Sets the beamline to ID_eV and then scans the mono for XAS scans - + 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 @@ -423,6 +439,7 @@ def scanXAS(ID_eV,start_stop_step_lists,**kwargs): 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 @@ -436,17 +453,23 @@ def scanXAS(ID_eV,start_stop_step_lists,**kwargs): scan_dim=kwargs['scan_dim'] - #Setting up the ScanRecord for Mono in Table mode - hv_array = make_table(start_stop_step_lists) - mono_scan_fillin_table(iex.BL.mda,scan_dim,hv_array,**kwargs) + #Setting up the ScanRecord for Mono and ID in Table mode + mono_array,ID_array = BL_energy_tables(start_stop_step_lists,**kwargs) + kwargs.update('positioner_num',1) + mono_scan_fillin_table(iex.BL.mda,scan_dim,mono_array,**kwargs) + if ID_tracking == True: + kwargs.update('positioner_num',2) + ID_scan_fillin_table(iex.BL.mda,scan_dim,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']) + ca_average(kwargs['average_pnts'],ca_detector_list(iex.BL.branch)) if iex.BL.branch=="d": mesh_d("In") - - #Setting the beamline energy - energy(ID_eV,m3r=kwargs["m3r"]) + print_warning_message('MeshD is not automatically removed') #mpa if iex.BL.endstation == "Kappa" and kwargs["mcp"]: @@ -454,93 +477,31 @@ def scanXAS(ID_eV,start_stop_step_lists,**kwargs): #Scanning if kwargs['execute']: - mono_energy_set(hv_array[0]) - BL.mda.go(scan_dim) + mono_energy_set(mono_array[0]) + iex.BL.mda.go(scan_dim) #Setting everything back mono_energy_set(ID_eV) - mono_scan_after(BL.mda,scan_dim) - BL.mda.table_reset_after(scan_dim) + mono_scan_after(iex.BL.mda,scan_dim) + iex.BL.mda.table_reset_after(scan_dim) - if BL.endstation == "Kappa": + if iex.BL.endstation == "Kappa": if kwargs["mcp"]: mpa.HV_off() - print("WARNING: Mesh"+BL.branch+" is still In") + print("WARNING: Mesh"+iex.BL.branch+" is still In") -def scanXAS_BL(start_stop_step_lists,**kwargs): - """ - scans the mono and the ID for XAS scans - Note: this is slow, but required in if the c-branch - - 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) - - 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.update('positioner_num',1) - mono_scan_fillin_table(BL.mda,scan_dim,mono_array,**kwargs) - - kwargs.update('positioner_num',2) - ID_scan_fillin_table(BL.mda,scan_dim,ID_array,**kwargs) - - #Averaging and Normalization - ca_average(kwargs['average_pnts']) - if BL.branch=="d": - mesh_d("In") - - #Setting the beamline energy - apertures_set(mono_array[0],m3r=kwargs["m3r"]) - - #mpa - if BL.endstation == "Kappa" and kwargs["mcp"]: - mpa.HV_on() - - #Scanning - if kwargs['execute']: - mono_energy_set(mono_array[0]) - ID_SP_set(ID_array[0]) - BL.mda.go(scan_dim) - - #Setting everything back - mono_energy_set(mono_array[0]) - mono_scan_after(BL.mda,scan_dim) - BL.mda.table_reset_after(scan_dim) - - if BL.endstation == "Kappa": - if kwargs["mcp"]: - mpa.HV_off() - print("WARNING: Mesh"+BL.branch+" is still In") - -def BL_energy_tables(start_stop_step_lists): +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) ID_array=np.array([]) ID_mode,ID_QP_ratio,ID_sp,ID_rbv,hv,grt = energy_get_all(verbose=False) @@ -550,50 +511,43 @@ def BL_energy_tables(start_stop_step_lists): ############################################################################################################## -########################### branch shutter, valves, safe_state ###################### +########################### shutter check ###################### ############################################################################################################## -def get_branch(verbose=True): - """ - gets the branch based on the position of m3r - """ - branch = m3r_branch(verbose) - return branch - -def open_branch(branch=None,valve=False): +def shutter_check(verbose=True): """ - Opens the branch shutter, if branch is none, then uses the position of m3r to determine branch + Opens the shutter in the branch determined from the position of m3r Previously: Check_BranchShutter """ - branch = get_branch(verbose=False) - + #main shutter + if main_shutter_status: + if verbose: + print("Main shutter already open") + else: + main_shutter_open() + + #branch shutter + branch = m3r_branch(verbose) if branch_shutter_status(branch): - print(dateandtime(), +branch+" shutter already open..." ,) + if verbose: + print(dateandtime(), +branch+" shutter already open..." ,) else: while True: if branch_shutter_status(branch) == False : - print(dateandtime(), "Opening "+branch+" shutter ..." ,) + if verbose: + print(dateandtime(), "Opening "+branch+" shutter ..." ,) branch_shutter_open(branch,verbose=False) sleep(30) else: print(dateandtime(), +branch+" shutter is now open..." ,) break - if valve: - GVs = branch_valves() - for GV in GVs: - valve_open(GV) -def close_shutter(branch=None): - """ - Closes the branch shutter, if branch is none, then uses the position of m3r to determine branch - - Previously: Close_CShutter,Close_DShutter - """ - if branch is None: - branch = get_branch() - caput("PC:29ID:S"+branch+"S_CLOSE_REQUEST.VAL",1,wait=True,timeout=18000) - print("Closing "+branch+"-Shutter...") + +############################################################################################################## +########################### switch branch ###################### +############################################################################################################## + def switch_branch(branch, force=False, shutter=True,scan_reset=True,enable_cams=True): """Switch beam into which = \"c\" or \"d\" branch (by retracting/inserting deflecting mirror) @@ -606,10 +560,10 @@ def switch_branch(branch, force=False, shutter=True,scan_reset=True,enable_cams= Previously: Switch_Branch """ branch = branch.lower() - if branch in ["c","d","e"]: - # Check current branch: - if get_branch() == branch and not force: + 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...") @@ -632,10 +586,10 @@ def switch_branch(branch, force=False, shutter=True,scan_reset=True,enable_cams= # Open branch shutters: if shutter: - open_branch(branch,valve=False) + branch_shutter_open(branch,valve=False) if scan_reset: - BL.mda.reset() + iex.BL.mda.reset() if enable_cams: _enable_endstation_cameras(branch) @@ -657,28 +611,22 @@ def get_mirrors(): ############################################################################################################## def slit(size): """ - sets the exit slit based on BL.endstation + sets the exit slit based on iex.BL.endstation ARPES = 0 < x < 300 um Kappa = 0 < x < 1000 um """ - global BL - branch = BL.branch - if branch == "c": - slit3C_set(size, quiet=False) - elif branch == "d": - slit3D_set(size, quiet=False) + exit_slit(size) def slit_get(verbose=True): """ - sets the exit slit based on BL.endstation + sets the exit slit based on iex.BL.endstation ARPES = 0 < x < 300 um Kappa = 0 < x < 1000 um """ - global BL - branch = BL.branch + branch = iex.BL.branch if branch == "c": slit_size = slit3C_get(verbose=False) slit_center = np.nan @@ -686,8 +634,8 @@ def slit_get(verbose=True): slit_size,slit_center = slit3D_get(verbose=False) if verbose: - message = BL.branch+' exit slit: '+str(slit_size) - message += ", @ "+str(slit_center) if BL.branch is not 'c' else '' + message = iex.BL.branch+' exit slit: '+str(slit_size) + message += ", @ "+str(slit_center) if iex.BL.branch is not 'c' else '' print(message) return slit_size,slit_center diff --git a/build/lib/iexcode/macros/ARPES_macros.py b/build/lib/iexcode/macros/ARPES_macros.py index 240e6d80e466ef7ca34fc6bff6eae7cd8d249a51..d62a31ac3cb21abb590e726696658c5794354757 100644 --- a/build/lib/iexcode/macros/ARPES_macros.py +++ b/build/lib/iexcode/macros/ARPES_macros.py @@ -2,7 +2,7 @@ import numpy as np from epics import caget,caput -from .ScanFunctions_plot import mda_1D,fit_gauss +from .quick_plot import mda_1D,fit_gauss from ..instruments.electron_analyzer import scanEA from ..instruments.slits import slit3C_set diff --git a/build/lib/iexcode/macros/Kappa_optimization.py b/build/lib/iexcode/macros/Kappa_optimization.py index 378f9c598983c35739c1894748dbd5275e9b1b80..fac115060aea63fae449105471ca0ad925a43b6e 100644 --- a/build/lib/iexcode/macros/Kappa_optimization.py +++ b/build/lib/iexcode/macros/Kappa_optimization.py @@ -1,12 +1,149 @@ -import matplotlib.pyplot as plt +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 ##### -from epics import caget,caput -from ..instruments.Kappa import * -from ..instruments.Motors import * -from .ScanFunctions_plot import fit_mda, mda_1D -##### Kappa Optimization scans ##### 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 @@ -15,13 +152,13 @@ def Opt_d4(iteration,moveZ,graph='y',srs=None,start=-0.5,stop=0.5,step=0.04): current_det=caget('29idKappa:userStringSeq6.STR1',as_string=True) if current_det != 'd4': print('Switching detector to d4') - tthdet.set('d4',move=False) - mvtth(0) + tthdet.set('d4') + mvtth(0) if moveZ is not None: mvz(z-1000) for i in range(iteration): scantth(start,stop,step,'relative') - scannum = mda.lastFileNum() + scannum=last_mda() tth0=fit_mda(scannum,det,tth_w,'gauss',graph=graph) mvtth(tth0) mvz(z) @@ -32,7 +169,7 @@ def Opt_z0(iteration,movetth,movekth,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,move=False) + 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 @@ -43,11 +180,11 @@ def Opt_z0(iteration,movetth,movekth,det='d4',srs=None,graph='y'): mvkth(movekth) if iteration>1: scanz(-2000,2000,250,'relative') - scannum=mda.fileNum() + scannum=last_mda() z0=fit_mda(scannum,det,z_w,'erf',graph=graph) mvz(z0) scanz(-700,700,50,'relative') - scannum = mda.lastFileNum() + scannum=last_mda() z0=fit_mda(scannum,det,z_w,'erf',graph=graph) mvz(z0) return z0,scannum @@ -56,7 +193,7 @@ 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,move=False) + tthdet.set(det) if det == 'd4': if srs==None: det=21 else: det=34 @@ -68,12 +205,12 @@ def Opt_kth(kth_0,theta,det='d4',srs=None,graph='y'): mvtth(theta*2) mvkth(kth_0+theta) scankth(-0.5*i,0.5*i,0.05*i,'relative') - new_kth=fit_mda(mda.lastFileNum(),det,0.1,'gauss',graph=graph) + 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(mda.lastFileNum(),det,0.1,'gauss',graph=graph) + new_kth=fit_mda(last_mda(),det,0.1,'gauss',graph=graph) mvkth(new_kth) - scannum=mda.lastFileNum + scannum=last_mda() kth0=round(new_kth-theta,3) print('\nkth0 = ',kth0) print('To plot use:') diff --git a/build/lib/iexcode/macros/ScanFunctions_plot.py b/build/lib/iexcode/macros/ScanFunctions_plot.py deleted file mode 100644 index c4ca21637d4ca36a0b2bec68618036e5544fd27d..0000000000000000000000000000000000000000 --- a/build/lib/iexcode/macros/ScanFunctions_plot.py +++ /dev/null @@ -1,2787 +0,0 @@ -""" -#ScanFunctions_plot.py -how to copy tabs in stabs and not spaces jupyter - -For Fanny: Converting spaces to tabs from the terminal -cp ScanFunctions_IEX.py ScanFunctions_IEXbackup.py -sed -e 's/ /\t/g' ScanFunctions_IEXbackup.py > ScanFunctions_IEX.py -""" - -#### Other utilities: -import csv -from os import listdir -from os.path import join, isfile, dirname -from scipy.optimize import curve_fit -from scipy.special import erf -import numpy.polynomial.polynomial as poly -import ast - -### Data analysis: -from inspect import CO_ASYNC_GENERATOR -from sre_constants import CATEGORY_DIGIT -import matplotlib.pyplot as plt -import matplotlib.image as mpimg -import numpy as np -from math import * - -from netCDF4 import Dataset - - -##### APS / 29ID-IEX: -from IEX_plotting_and_analysis.mda import readMDA,scanDim -from IEX_plotting_and_analysis.IEX_nData import * - -try: - from epics import caget - from ..instruments.IEX_endstations import BL - from ..instruments.utilities import read_dict,today - from ..instruments.slits import slits_set_BL - from IEXcode.iexcode.current_amplifiers import current2flux -except: - print("EPICS package and dependent functions are not installed") - - - -############################################################################################################## -############################## JM Curves and Curve Fitting ############################## -############################################################################################################## - -def gauss(x, *p): - """ - Function for a guassian where p=[A,x0,sigma] - f(x)=A*numpy.exp(-(x-x0)**2/(2.*sigma**2) - fwhm=2.355*sigma - """ - A, x0, sigma = p - return A*np.exp(-(x-x0)**2/(2.*sigma**2)) - -def gauss_p0(y,x): - """ - Inital guesses for guassian fit - x and y are np.arrays - returns p0=[A,x0,sigma] - """ - A=max(y) - x0=x[np.where(y == max(y))][0] - sigma=0.2 - return [A,x0,sigma] - -def fit_gauss(x,y,xrange=None): - """ - x,y=EA_Spectrum(ScanNum, EnergyAxis,FilePath,Prefix) - x,y,x_name,y_name=mda_1D(ScanNum,DetectorNum) - - xrange = None to fit the full range - = [x1,x2] to fit a subrange - returns input_x,fit_y,coeff,var_matrix - where input_x and fit_y are the sub range x and the fitted data respectivley - coeff=[A,x0,sigma] - var_matrix is the fit variance - """ - if xrange is None: - input_y=y - input_x=x - else: - index1=np.where(x == x.flat[np.abs(x - xrange[0]).argmin()])[0][0] - index2=np.where(x == x.flat[np.abs(x - xrange[1]).argmin()])[0][0] - input_x=x[index1:index2] - input_y=y[index1:index2] - coeff, var_matrix = curve_fit(gauss, input_x, input_y, p0=gauss_p0(input_y,input_x)) - fit_y= gauss(input_x, *coeff) - return input_x,fit_y,coeff,var_matrix - - -############################################################################################################## -############################## Plot Tiff,JPEG,PNG ############################## -############################################################################################################## - -# filepath='/home/beams/29IDUSER/Documents/User_Folders/Topp/S089.tif' -def plot_image(filepath,h=20,v=10,**kwargs): - """ - filepath = '/home/beams/29IDUSER/Documents/User_Folders/UserName/TifFile.tif' - ** kwargs are imshow kwargs: - cmap = colormap; examples => 'gray','BuPu','Inferno' - vmin,vmax, adjust max and min of colormap - """ - - image = mpimg.imread(filepath) - plt.figure(figsize=(h,v)) - plt.imshow(image,**kwargs) - plt.axis('off') - plt.show() - - - -def plot_image2(Filepath1,Filepath2,h=20,v=10): - """ - filepath = '/home/beams/29IDUSER/Documents/User_Folders/UserName/TifFile.tif' - """ - print(Filepath1) - print(Filepath2) - image1 = mpimg.imread(Filepath1) - image2 = mpimg.imread(Filepath2) - plt.figure(figsize=(h,v)) - plt.subplot(1,2,1), plt.imshow(image1,cmap='gray') - plt.axis('off') - plt.subplot(1,2,2), plt.imshow(image2,cmap='gray') - plt.axis('off') -# fig.subplots_adjust(wspace=0.5,hspace=0.5,left=0.125,right=0.9,top=0.85,bottom=0.15) - plt.tight_layout() - plt.show() - - -############################################################################################################## -############################## Extract mda Data ############################## -############################################################################################################## - -## mda_1D(1691,44,1,0,'/net/s29data/export/data_29idb/2018_1/mda_b')??? - -def mda_unpack(ScanNum,filepath=None,prefix=None): - """ Return data file + dictionary D##:("pv",index##) - filepath: by default plot scans for the current data folder (as defined in BL_ioc() ScanRecord SaveData) - or specified folder path: - e.g. filepath='/net/s29data/export/data_29idb/2018_1/mda_b/' - prefix: by default, uses prefix as defined in ScanRecord - "mda_" for users, "Kappa_" or "ARPES_" for staff (sometimes) - """ - try: - if filepath is None: - filepath = BL.mda.filepath - if prefix is None: - prefix = BL.mda.prefix - except: - print('Please specify filepath and prefix, BL is not defined') - - mdaFile=filepath + prefix+'{:04}.mda'.format(ScanNum) - data_file = readMDA(mdaFile) - try: - D={} - n=len(data_file)-1 - for i in range(0,data_file[n].nd): - detector=data_file[n].d[i].fieldName - D[int(detector[1:])]=(data_file[n].d[i].name,i) - return (data_file,D) - except: - pass - -def mda_1D(ScanNum,DetectorNum,coeff=1,bckg=0,filepath=None,prefix=None): - """ Return x=positionner and y=detector(DetectorNum) - for a given detector number DYY (as shown in dview). """ - try: - (data_file,det)=mda_unpack(ScanNum,filepath,prefix) - index=det[DetectorNum][1] - x = data_file[1].p[0].data - y = data_file[1].d[index].data - x_name = data_file[1].p[0].name - y_name = data_file[1].d[index].name - if type(x_name) == bytes: - x_name=x_name.decode("utf-8") - if type(y_name) == bytes: - y_name=y_name.decode("utf-8") - n=list(zip(x,y)) - d=[n[i] for i, e in enumerate(n) if e != (0.0,0.0)] - if len(d)<len(n): - x=x[:len(d)] - y=y[:len(d)] - y=[(y[i]+bckg)*coeff for i, e in enumerate(y)] - #y=[(y[i]*coeff)+bckg for i, e in enumerate(y)] - return x,y,x_name,y_name - except: - print('error') - pass - - -def mda_1D_unscaled(ScanNum,DetectorNum,filepath=None,prefix=None): - """ Return x=positionner and y=detector(DetectorNum) - for a given detector number DYY (as shown in dview). """ - try: - (data_file,det)=mda_unpack(ScanNum,filepath,prefix) - if (data_file,det) == (None,None): - return(None) - else: - index=det[DetectorNum][1] - x = data_file[1].p[0].data - y = data_file[1].d[index].data - x_name = data_file[1].p[0].name - y_name = data_file[1].d[index].name - if type(x_name) == bytes: - x_name=x_name.decode("utf-8") - if type(y_name) == bytes: - y_name=y_name.decode("utf-8") - n=list(zip(x,y)) - d=[n[i] for i, e in enumerate(n) if e != (0.0,0.0)] - if len(d)<len(n): - x=x[:len(d)] - y=y[:len(d)] - bckg=min(y) - coeff=max(y)-min(y) - y=[(y[i]-bckg)/coeff for i, e in enumerate(y)] - return x,y,x_name,y_name - except: - pass - -def mda_1D_Xindex(ScanNum,DetectorNum,coeff=1,bckg=0,filepath=None,prefix=None): - """ Return x=index and y=detector(DetectorNum) - for a given detector number DYY (as shown in dview). """ - try: - (data_file,det)=mda_unpack(ScanNum,filepath,prefix) - index=det[DetectorNum][1] - x = data_file[1].d[0].data - y = data_file[1].d[index].data - x_name = data_file[1].d[0].name - y_name = data_file[1].d[index].name - if type(x_name) == bytes: - x_name=x_name.decode("utf-8") - if type(y_name) == bytes: - y_name=y_name.decode("utf-8") - n=list(zip(x,y)) - d=[n[i] for i, e in enumerate(n) if e != (0.0,0.0)] - if len(d)<len(n): - y=y[:len(d)] - x=list(range(1,len(y)+1)) - y=[(y[i]*coeff)+bckg for i, e in enumerate(y)] - return x,y,x_name,y_name - except: - pass - -def mda_1D_vsDet(ScanNum,DetectorNum,DetectorNum2,coeff=1,bckg=0,filepath=None,prefix=None): - """ Return x=index and y=detector(DetectorNum) - for a given detector number DYY (as shown in dview). """ - try: - #print(ScanNum,filepath,prefix,scanIOC) - (data_file,det)=mda_unpack(ScanNum,filepath,prefix) - index=det[DetectorNum][1] - index2=det[DetectorNum2][1] - x = data_file[1].d[0].data - x2 = data_file[1].d[index2].data - y = data_file[1].d[index].data - x_name = data_file[1].d[0].name - x2_name = data_file[1].d[index2].name - y_name = data_file[1].d[index].name - x = data_file[1].p[0].data - x2= data_file[1].d[index2].data - y= data_file[1].d[index].data - if type(x_name) == bytes: - x_name=x_name.decode("utf-8") - if type(y_name) == bytes: - y_name=y_name.decode("utf-8") - if type(x2_name) == bytes: - x2_name=x2_name.decode("utf-8") - n=list(zip(x,y)) - d=[n[i] for i, e in enumerate(n) if e != (0.0,0.0)] - if len(d)<len(n): - y=y[:len(d)] - x2=x2[:len(d)] - y=[(y[i]*coeff)+bckg for i, e in enumerate(y)] - return x2,y,x2_name,y_name - except: - pass - -def mda_Flux(ScanNum,DetectorNum,EnergyNum,filepath=None,prefix=None): - """ Return x=positionner and y=Flux(DetectorNum) - for a given diode recorded as detector number DYY (see ## in dview). - EnergyNum is the detector number for the mono RBV. - - """ - try: - (data_file,det)=mda_unpack(ScanNum,filepath,prefix) - index=det[DetectorNum][1] - Eindex=det[EnergyNum][1] - x = data_file[1].p[0].data - y = data_file[1].d[index].data - energy = data_file[1].d[Eindex].data - x_name = data_file[1].p[0].name - y_name = data_file[1].d[index].name - if type(x_name) == bytes: - x_name=x_name.decode("utf-8") - if type(y_name) == bytes: - y_name=y_name.decode("utf-8") - n=list(zip(x,y)) - d=[n[i] for i, e in enumerate(n) if e != (0.0,0.0)] - if len(d)<len(n): - x=x[:len(d)] - y=y[:len(d)] - y=[current2flux(y[i],energy[i],p=None) for (i, e) in enumerate(y)] - return x,y,x_name,y_name - except: - pass - - - -def mda_NormDet(ScanNum,DetectorNum,NormNum,coeff=1,bckg=0,filepath=None,prefix=None): - """ Return x=positionner and y=detector(DetectorNum) - for a given detector number DYY (as shown in dview). """ - try: - (data_file,det)=mda_unpack(ScanNum,filepath,prefix) - index=det[DetectorNum][1] - index_Norm=det[NormNum][1] - x = data_file[1].p[0].data - y= data_file[1].d[index].data - y_Norm=data_file[1].d[index_Norm].data - x_name = data_file[1].p[0].name - y_name = data_file[1].d[index].name#+"_norm:"+str(NormNum) - if type(x_name) == bytes: - x_name=x_name.decode("utf-8") - if type(y_name) == bytes: - y_name=y_name.decode("utf-8") - - n=list(zip(x,y)) - d=[n[i] for i, e in enumerate(n) if e != (0.0,0.0)] - if len(d)<len(n): - x=x[:len(d)] - y=y[:len(d)] - y=[y[i]/y_Norm[i] for i, e in enumerate(y)] - return x,y,x_name,y_name - except: - pass - -def mda_DivScan(ScanNum1,DetectorNum1,ScanNum2,DetectorNum2,coeff=1,bckg=0,filepath=None,prefix=None): - """ Return x=positionner and y=detector(DetectorNum) - for a given detector number DYY (as shown in dview). """ - try: - (data_file1,det1)=mda_unpack(ScanNum1,filepath,prefix) - index1=det1[DetectorNum1][1] - (data_file2,det2)=mda_unpack(ScanNum2,filepath,prefix) - index2=det2[DetectorNum2][1] - x1 = data_file1[1].p[0].data - y1= data_file1[1].d[index1].data - y2= data_file2[1].d[index2].data - x_name = data_file1[1].p[0].name - y_name = data_file1[1].d[index1].name+"_norm:"+str(ScanNum2) - if type(x_name) == bytes: - x_name=x_name.decode("utf-8") - if type(y_name) == bytes: - y_name=y_name.decode("utf-8") - - n=list(zip(x1,y1)) - d=[n[i] for i, e in enumerate(n) if e != (0.0,0.0)] - if len(d)<len(n): - x1=x1[:len(d)] - y1=y1[:len(d)] - y=[y1[i]/y2[i] for i, e in enumerate(y1)] - return x1,y,x_name,y_name - except: - pass - - - -def mda_2D(ScanNum,DetectorNum,filepath=None,prefix=None): - """ Return x=positionner and y=detector(DetectorNum) - for a given detector number DYY (as shown in dview). """ - try: - (data_file,det)=mda_unpack(ScanNum,filepath,prefix) - index=det[DetectorNum][1] - x_temp = data_file[2].p[0].data - y_temp = data_file[1].p[0].data - z_temp = data_file[2].d[index].data - x_name = data_file[2].p[0].name - y_name = data_file[1].p[0].name - z_name = data_file[2].d[index].name - if type(x_name) == bytes: - x_name=x_name.decode("utf-8") - if type(y_name) == bytes: - y_name=y_name.decode("utf-8") - if type(z_name) == bytes: - z_name=z_name.decode("utf-8") - - n=list(zip(x_temp,y_temp,z_temp)) - d=[n[i] for i, e in enumerate(n) if e != (0.0,0.0,0.0)] - if len(d)<len(n): - x_temp=x_temp[:len(d)] - y_temp=y_temp[:len(d)] - z_temp=z_temp[:len(d)] - x = x_temp[0] - y = y_temp - z = np.asarray(z_temp) #2-D array - return x,y,z,x_name,y_name,z_name - except: - pass - - -############################################################################################### -#################################### PLOT MDA ################################### -############################################################################################### - - - - -def plot_mda2D(ScanNum,DetectorNum,title=None,color=None,filepath=None,prefix=None): - try: - x,y,z,xName,yName,zName=mda_2D(ScanNum,DetectorNum,filepath,prefix) - fig, ax0 = plt.subplots() - if color is None: - color='gnuplot' - img = ax0.imshow(z, cmap=color, interpolation = 'nearest', extent = [min(x), max(x), max(y), min(y)], aspect = 'auto') - fig.colorbar(img) - if title is None: - plt.title(zName) - else: - plt.title(title) - ax0.set_xlabel(xName) - ax0.set_ylabel(yName) - # ax0.set_ylim(y.max(),y.min()) - plt.show() - except: - pass - - - -def plot_mda_series(*ScanDet,**kwArg): - """plot_mda_series(1217, 1226, 1, 39 ,0.025, **kwArg) - (first,last,countby,det,offset,**kwArg) - Optional data analysis keywords arguments: - Flux conversion (for diode only): flux= 3(User) or 25(Staff). - Norm option: norm = 'yes' normalizes all the scans to 1 (default: None) - NormDet= 1 for SR current, 14 for Mesh (D-branch); Normalize by the mesh does not work with norm='yes' - Optional graphical keywords arguments: - sizeH = 1,1.5,... increase horizontal figure size - sizeV = 1,1.5,... increase vertical figure size - marker = 'x','+','o','v','^','D',... (default:None) - markersize = 1,2,3,... (default: 5) - linewidth = 0.5,1,2... (default: 1) - linestyle = '-','--','-.',':' (default: solid '-') - color = 'r','b','m','c','g','y'... (default: jupyter colors series) - legend = 'best',Supper left', 'lower right'... (default: None) - log = 'log' (default: None = linear) - xrange = [x1,x2] (default: None = Autoscale) - yrange = [y1,y2] (default: None = Autoscale) - xlabel = 'mxLabel' (default: pv name) - ylabel = 'myLabel' (default: pv name) - ytickstyle = 'sci' for y axes (default: 'plain') - xtickstyle = 'sci' for y axes (default: 'plain') - filepath: by default plot scans for the current data folder (as defined in BL_ioc() ScanRecord SaveData) - or specified folder path: - e.g. user : filepath='/net/s29data/export/data_29idc/2018_2/UserName/mda/' - e.g. staff: filepath='/net/s29data/export/data_29idb/2018_2/mda/' - prefix: by default, uses prefix as defined in ScanRecord ("mda_") - scanIOC: by default, uses the IOC for the current branch as define in BL_IOC() - """ - - if type(ScanDet[0]) is not tuple: - ScanDet=(tuple(ScanDet),) - m=1 - else: m= len(ScanDet) - - scanlist="" - j=0 - offset=0 - for n in range(m): - print(n) - print(m) - print(ScanDet) - det=ScanDet[n][3] - if len(ScanDet)>4 and isinstance(ScanDet[n][3],str)== False: - offset=ScanDet[n][4] - for scanNum in range(ScanDet[n][0],ScanDet[n][1]+ScanDet[n][2],ScanDet[n][2]): - scanlist+=str(scanNum)+',(det,1,'+str(offset)+'),' - j+=offset - cmd="plot_mda("+scanlist - if kwArg is not None: - for key, value in list(kwArg.items()): - if type(value) == str: - cmd=cmd+(key+'=\"'+value+'\",') - else: - cmd=cmd+(key+'='+str(value)+',') - if cmd[-1]==",": - cmd=cmd[:-1] - cmd=cmd+")" - if kwArg is not None: - for key, value in list(kwArg.items()): - if key=='q': - print('det=',det) - print(cmd) - exec(cmd) - - - -def plot_mda(*ScanDet,**kwArg): - - """ - Plot mda scans: *ScanDet = (scan,det,scan,det...),(scan,det,scan,det...),title=(subplot_title1,subplot_title2) - = subplot1, subplot2 - Optional data analysis keywords arguments: - Flux conversion (for diode only): flux= 3(D## for mono rbv, typically 3). - Norm option: norm = 'yes' normalizes all the scans to 1 (default: None) - NormDet = 1 for SR current, 14 for Mesh (D-branch); Normalize by the mesh does not work with norm='yes' - DivScan = ? - Optional graphical keywords arguments: - sizeH = 1,1.5,... increase horizontal figure size - sizeV = 1,1.5,... increase vertical figure size - marker = 'x','+','o','v','^','D',... (default:None) - markersize = 1,2,3,... (default: 5) - linewidth = 0.5,1,2... (default: 1) - linestyle = '-','--','-.',':' (default: solid '-') - color = 'r','b','m','c','g','y'... (default: jupyter colors series) - legend = 'best',Supper left', 'lower right'... (default: None) - log = 'log' (default: None = linear) - xrange = [x1,x2] (default: None = Autoscale) - yrange = [y1,y2] (default: None = Autoscale) - xlabel = 'mxLabel' (default: pv name) - ylabel = 'myLabel' (default: pv name) - ytickstyle = 'sci' for y axes (default: 'plain') - xtickstyle = 'sci' for y axes (default: 'plain') - filepath: by default plot scans for the current data folder (as defined in BL_ioc() ScanRecord SaveData) - or specified folder path: - e.g. user : filepath='/net/s29data/export/data_29idc/2018_2/UserName/mda/' - e.g. staff: filepath='/net/s29data/export/data_29idb/2018_2/mda/' - prefix: by default, uses prefix as defined in ScanRecord ("mda_") - scanIOC: by default, uses the IOC for the current branch as define in BL_IOC() - """ - - args={ - 'marker':None, - 'markersize':5, - 'linewidth':1, - 'linestyle':'-', - 'color':None, - 'nticks':None, - 'sizeH':1, - 'sizeV':1, - 'title':'', - 'filepath':None, - 'prefix':None, - 'norm':None, - 'flux':None, - 'NormDet':None, - 'scanIOC':None, - 'legend':None, - 'vs_index':None, - 'vs_det':None, - 'xrange':[None,None], - 'yrange':[None,None], - 'save':True - } - - args.update(kwArg) - - mkr=args['marker'] - ms=args['markersize'] - lw=args['linewidth'] - ls=args['linestyle'] - c=args['color'] - path=args['filepath'] - prefix=args['prefix'] - scanIOC=args['scanIOC'] - save=args['save'] - - if 'legend' in args: - if args['legend'] == 'center left': - hsize=7 - - if type(ScanDet[0]) is not tuple: - ScanDet=(tuple(ScanDet),) - m=1 - else: m= len(ScanDet) - - def SubplotsLayout(m): - if m >1: - ncols=2 - else: - ncols=1 - nrows=max(sum(divmod(m,2)),1) - hsize=ncols*5*args['sizeH'] - vsize=nrows*4*args['sizeV'] - if nrows==1: vsize=nrows*3.5*args['sizeV'] - return nrows,ncols,hsize,vsize - - try: - nrows,ncols,hsize,vsize=SubplotsLayout(m) - - fig, axes = plt.subplots(nrows,ncols,figsize=(hsize,vsize)) # HxV - axes=np.array(axes) - - for (n,ax) in zip(list(range(m)),axes.flat): - for (i,j) in zip(ScanDet[n][0::2],ScanDet[n][1::2]): - if type(j) is tuple: - p,k,l=j - x,y,x_name,y_name=mda_1D(i,p,k,l,path,prefix) - elif args['flux'] is not None: - x,y,x_name,y_name=mda_Flux(i,j,args['flux'],path,prefix,scanIOC) - elif args['norm'] is not None: - x,y,x_name,y_name=mda_1D_unscaled(i,j,path,prefix,scanIOC) - elif args['NormDet'] is not None: - x,y,x_name,y_name=mda_NormDet(i,j,args['NormDet'],1,0,path,prefix,scanIOC) - elif args['vs_index'] is not None: - x,y,x_name,y_name=mda_1D_Xindex(i,j,1,0,path,prefix) - elif args['vs_det'] is not None: - x,y,x_name,y_name=mda_1D_vsDet(i,j,args['vs_det'],1,0,path,prefix) - #elif DivScan is not None: - # x,y,x_name,y_name=mda_DivScan(i,j,DivScan,DivDet,1,0,path,prefix,scanIOC) - else: - x,y,x_name,y_name=mda_1D(i,j,1,0,path,prefix,scanIOC) - ax.plot(x,y,label="mda_"+str(i),color=c,marker=mkr,markersize=ms,linewidth=lw,linestyle=ls) - ax.grid(color='lightgray', linestyle='-', linewidth=0.5) - - #modifying graph - if args['legend'] != None: - if args['legend'] == 'center left': - box = ax.get_position() - ax.set_position([box.x0, box.y0, box.width * 0.6, box.height]) - ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) - myleft=0.1 - myright=0.55 - else: - ax.legend(args['legend'], frameon=True) - if 'ytickstyle' in args: - ax.ticklabel_format(style=args['ytickstyle'], axis='y', scilimits=(0,0)) - if 'xtickstyle' in args: - ax.ticklabel_format(style=args['xtickstyle'], axis='x', scilimits=(0,0)) - if 'log' in args: - ax.set_yscale('log') - if args['xrange'] != [None,None]: - ax.set_xlim(args['xrange'][0],args['xrange'][1]) - if args['yrange'] != [None,None]: - ax.set_ylim(args['yrange'][0],args['yrange'][1]) - if 'xlabel' in args: - x_name=args['xlabel'] - if 'ylabel' in args: - y_name=args['ylabel'] - if args['nticks'] != None: - tck=args['nticks']-1 - ax.locator_params(tight=None,nbins=tck) - - - if 'title' in args: - mytitle=args['title'] - if type(mytitle) is not tuple: - ax.set(xlabel=x_name,ylabel=y_name,title=mytitle) - else: - p=len(mytitle) - if n == p: - ax.set(xlabel=x_name,ylabel=y_name,title='') - else: - ax.set(xlabel=x_name,ylabel=y_name,title=mytitle[n]) - # ax.text(0.5, 1.025,mytitle,horizontalalignment='center',fontsize=14,transform = ax.transAxes) - ax.grid(color='lightgray', linestyle='-', linewidth=0.5) - - if ncols==1 and nrows==1 and kwArg.get('legend')!='center left': - fig.subplots_adjust(wspace=0.5,hspace=0.5,left=0.25,right=0.88,top=0.85,bottom=0.22) - elif ncols==1 and kwArg.get('legend')=='center left': - fig.subplots_adjust(wspace=0.5,hspace=0.5,left=myleft,right=myright,top=0.85,bottom=0.22) - else: - fig.subplots_adjust(wspace=0.5,hspace=0.5,left=0.125,right=0.9,top=0.85,bottom=0.15) - - plt.tight_layout() - if save: - try: - fname=join('/home/beams/29IDUSER/Documents/User_Folders/','lastfigure.png') - print(fname) - plt.savefig(fname) - except: - pass - plt.show() - except: - pass - - - -def plot_mda_lists(*ScanDet,**kwArg): - """ - Plot mda scans: *ScanDet = (scanNum_list,detNum_list),(scanNum_list,detNum_list) - = subplot1, subplot2 - Optional data analysis keywords arguments: - Flux conversion (for diode only): flux= 3(User) or 25(Staff). - Norm option: norm = 'yes' normalizes all the scans to 1 (default: None) - NormDet= 1 for SR current, 14 for Mesh (D-branch); Normalize by the mesh does not work with norm='yes' - Optional graphical keywords argudef plot_mdaments: - sizeH = 1,1.5,... increase horizontal figure size - sizeV = 1,1.5,... increase vertical figure size - marker = 'x','+','o','v','^','D',... (default:None) - markersize = 1,2,3,... (default: 5) - linewidth = 0.5,1,2... (default: 1) - linestyle = '-','--','-.',':' (default: solid '-') - color = 'r','b','m','c','g','y'... (default: jupyter colors F) - legend = 'best',Supper left', 'lower right'... (default: None) - log = 'log' (default: None = linear) - xrange = [x1,x2] (default: None = Autoscale) - yrange = [y1,y2] (default: None = Autoscale) - xlabel = 'mxLabel' (default: pv name) - ylabel = 'myLabel' (default: pv name) - ytickstyle = 'sci' for y axes (default: 'plain') - xtickstyle = 'sci' for y axes (default: 'plain') - filepath: by default plot scans for the current data folder (as defined in BL_ioc() ScanRecord SaveData) - or specified folder path: - e.g. user : filepath='/net/s29data/export/data_29idc/2018_2/UserName/mda/' - e.g. staff: filepath='/net/s29data/export/data_29idb/2018_2/mda/' - prefix: by default, uses prefix as defined in ScanRecord ("mda_") - scanIOC: by default, uses the IOC for the current branch as define in BL_IOC() - """ - - args={ - 'marker':None, - 'markersize':5, - 'linewidth':1, - 'linestyle':'-', - 'color':None, - 'nticks':None, - 'sizeH':1, - 'sizeV':1, - 'title':'', - 'filepath':None, - 'prefix':None, - 'norm':None, - 'flux':None, - 'NormDet':None, - 'scanIOC':None, - 'legend':None, - 'vs_index':None, - 'xrange':[None,None], - 'yrange':[None,None] - } - - args.update(kwArg) - - mkr=args['marker'] - ms=args['markersize'] - lw=args['linewidth'] - ls=args['linestyle'] - c=args['color'] - path=args['filepath'] - prefix=args['prefix'] - scanIOC=args['scanIOC'] - - - - if 'legend' in args: - if args['legend'] == 'center left': - hsize=7 - - #setting up the subplot - if type(ScanDet[0]) is not tuple: - ScanDet=(tuple(ScanDet),) - m=1 - else: m= len(ScanDet) - - def SubplotsLayout(m): - if m >1: - ncols=2 - else: - ncols=1 - nrows=max(sum(divmod(m,2)),1) - hsize=ncols*5*args['sizeH'] - vsize=nrows*4*args['sizeV'] - if nrows==1: vsize=nrows*3.5*args['sizeV'] - return nrows,ncols,hsize,vsize - - try: - nrows,ncols,hsize,vsize=SubplotsLayout(m) - fig, axes = plt.subplots(nrows,ncols,figsize=(hsize,vsize)) # HxV - axes=np.array(axes) - - - for (n,ax) in zip(list(range(m)),axes.flat): #n=subplot tuple - scanNum_list=ScanDet[n][0] - detNum_list=ScanDet[n][1] - - if type(scanNum_list) is int: - scanNum_list=[scanNum_list] - if type(detNum_list) is int: - detNum_list=[detNum_list] - for i in range(1,len(scanNum_list)): - detNum_list.append(detNum_list[0]) - if type(args['filepath']) is not list: - filepath_list=[args['filepath']] - for i in range(1,len(scanNum_list)): - filepath_list.append(filepath_list[0]) - else: filepath_list=args['filepath'] - if type(args['prefix']) is not list: - prefix_list=[args['prefix']] - for i in range(1,len(scanNum_list)): - prefix_list.append(prefix_list[0]) - else: prefix_list=args['prefix'] - if type(args['scanIOC']) is not list: - scanIOC_list=[args['scanIOC']] - for i in range(1,len(scanNum_list)): - scanIOC_list.append(scanIOC_list[0]) - else: scanIOC_list=args['scanIOC'] - #loading the data - for index in range(0,len(scanNum_list)): - i=scanNum_list[index] - j=detNum_list[index] - path=filepath_list[index] - prefix=prefix_list[index] - scanIOC=scanIOC_list[index] - #print(i) - if type(j) is tuple: - p,k,l=j - x,y,x_name,y_name=mda_1D(i,p,k,l,path,prefix) - elif args['flux'] is not None: - x,y,x_name,y_name=mda_Flux(i,j,args['flux'],path,prefix,scanIOC) - elif args['norm'] is not None: - x,y,x_name,y_name=mda_1D_unscaled(i,j,path,prefix,scanIOC) - elif args['NormDet'] is not None: - x,y,x_name,y_name=mda_NormDet(i,j, args['NormDet'],1,0,path,prefix,scanIOC) - else: - x,y,x_name,y_name=mda_1D(i,j,1,0,path,prefix,scanIOC) - #adding to graph - ax.grid(color='lightgray', linestyle='-', linewidth=0.5) - ax.plot(x,y,label="mda_"+str(i),color=c,marker=mkr,markersize=ms,linewidth=lw,linestyle=ls) - - #modifying graph - if args['legend'] != None: - if args['legend'] == 'center left': - box = ax.get_position() - ax.set_position([box.x0, box.y0, box.width * 0.6, box.height]) - ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) - myleft=0.1 - myright=0.55 - else: - ax.legend(args['legend'], frameon=True) - if 'ytickstyle' in args: - ax.ticklabel_format(style=args['ytickstyle'], axis='y', scilimits=(0,0)) - if 'xtickstyle' in args: - ax.ticklabel_format(style=args['xtickstyle'], axis='x', scilimits=(0,0)) - if 'log' in args: - ax.set_yscale('log') - if args['xrange'] != [None,None]: - ax.set_xlim(args['xrange'][0],args['xrange'][1]) - if args['yrange'] != [None,None]: - ax.set_ylim(args['yrange'][0],args['yrange'][1]) - if 'xlabel' in args: - x_name=args['xlabel'] - if 'ylabel' in args: - y_name=args['ylabel'] - if args['nticks'] != None: - tck=args['nticks']-1 - ax.locator_params(tight=None,nbins=tck) - - if 'title' in args: - if type(args['title']) is not str: - mytitle=args['title'][n] - else: - mytitle=args['title'] - ax.set(xlabel=x_name,ylabel=y_name,title=mytitle) - #adjusting subplots - if ncols==1 and nrows==1 and kwArg.get('legend')!='center left': - fig.subplots_adjust(wspace=0.5,hspace=0.5,left=0.25,right=0.88,top=0.85,bottom=0.22) - elif ncols==1 and kwArg.get('legend')=='center left': - fig.subplots_adjust(wspace=0.5,hspace=0.5,left=myleft,right=myright,top=0.85,bottom=0.22) - else: - fig.subplots_adjust(wspace=0.5,hspace=0.5,left=0.125,right=0.9,top=0.85,bottom=0.15) - #show plot - plt.tight_layout() - plt.show() - - except: - pass - - - - -############################################################################################### -#################################### PLOT netCDF ################################### -############################################################################################### - - - - -def nc_unpack(ScanNum,FilePath=None,Prefix=None): - """ - Returns the full netCDF data file - meta data (Attributes/Exta PVs) - c.variables['Attr_EnergyStep_Swept'][:][0] - data array is accessed - nc.variables['array_data'][:][0] - - FilePath: by default plot scans for the current data folder (as shown on detector panel) - or specified folder path ending with '/': - e.g. user : FilePath='/net/s29data/export/data_29idc/2018_2/UserName/netCDF/' - e.g. staff: FilePath='/net/s29data/export/data_29idb/2018_2/netCDF/' - Prefix: by default, uses prefix as shown on detector panel ("EA_") - """ - def GetFileName(): - SubFolder= caget('29idcEA:netCDF1:FilePath',as_string=True) - if SubFolder[0]=='X': drive='b' - elif SubFolder[0]=='Y': drive='c' - FilePath='/net/s29data/export/data_29id'+drive+SubFolder[2:]+'/' - Prefix = caget("29idcEA:netCDF1:FileName_RBV",as_string=True) - return FilePath, Prefix - - if FilePath is None: - FilePath=GetFileName()[0] - if Prefix is None: - Prefix= GetFileName()[1] - myFile=FilePath+Prefix+'{:04}.nc'.format(ScanNum) - nc = Dataset(myFile,mode='r') - return nc - -def EA_data(nc): - """ Returns: x,xname,ycrop,yname,img,ActualPhotonEnergy,WorkFunction,PE - """ - - LowEnergy=nc.variables['Attr_LowEnergy'][:][0] - HighEnergy=nc.variables['Attr_HighEnergy'][:][0] - ActualPhotonEnergy=nc.variables['Attr_ActualPhotonEnergy'][:][0] - EnergyStep_Swept=nc.variables['Attr_EnergyStep_Swept'][:][0] - EnergyStep_Swept_RBV=nc.variables['Attr_EnergyStep_Swept_RBV'][:][0] - EperChannel=nc.variables['Attr_EnergyStep_Fixed_RBV'][:][0] - GratingPitch=nc.variables['Attr_GratingPitch'][:][0] - MirrorPitch=nc.variables['Attr_MirrorPitch'][:][0] - - WorkFunction=nc.variables['Attr_Energy Offset'][:][0] - - DetMode=nc.variables['Attr_DetectorMode'][:][0] # BE=0,KE=1 - AcqMode= nc.variables['Attr_AcquisitionMode'][:][0] # Swept=0, Fixed=1, BS=2 - LensMode=nc.variables['Attr_LensMode'][:][0] - - PassEnergyMode=nc.variables['Attr_PassEnergy'][:][0] - PEdict={0:1,1:2,2:5,3:10,4:20,5:50,6:100,7:200,8:500} - PE=PassEnergyMode - - #ActualPhotonEnergy,WorkFunction,PE=EA_metadata(nc)[0:3] - data = nc.variables['array_data'][:][0] - - def SelectValue(which,x1,x2): - if which == 0: value=x1 - if which == 1: value=x2 - return value - - ### Energy Scaling: - Edelta = SelectValue(DetMode,-EnergyStep_Swept,EnergyStep_Swept) - if AcqMode == 0: # Swept - Ehv=ActualPhotonEnergy - Estart = SelectValue(DetMode, Ehv-LowEnergy, LowEnergy) - #Estop = SelectValue(DetMode, Ehv-HighEnergy, HighEnergy) - if AcqMode >= 1: # Fixed or Baby Swept - Ecenter=nc.variables['Attr_CentreEnergy_RBV'][:][0] - #print nc.variables#JM was here - #print Ecenter,Edelta#JM was here - Estart=Ecenter-(data.shape[1]/2.0)*Edelta - Eunits=SelectValue(DetMode,"Binding Energy (eV)","Kinetic Energy (eV)") - - x=[Estart+Edelta*i for i,e in enumerate(data[0,:])] - xname=Eunits - - ### Angular Scaling: - if LensMode>-1: # Angular Modes RE changed from >0 (Angular) to >-1 (all mode) - CenterChannel=571 - FirstChannel=0 - Ddelta =0.0292717 - Dstart = (FirstChannel-CenterChannel)*Ddelta - y=[Dstart+Ddelta*i for i,e in enumerate(data[:,0])] - #getting rid of edges with no data - data=nc.variables['array_data'] - #x1=338;x2=819 #old - x1=338-100;x2=819-10 - datacrop=data[:,x1:x2] - ycrop=y[x1:x2] - yname='Degrees' - else: - ycrop,yname=None,'mm' - return x,xname,ycrop,yname,datacrop,ActualPhotonEnergy,WorkFunction,PE - - - - -def EA_Image(ScanNum,EnergyAxis='KE',FilePath=None,Prefix=None): - """ - Returns - x = KE or BE energy scale; BE is calculated based on the wk in the SES and the mono energy - y = Integrated intensity - - FilePath: by default plot scans for the current data folder (as shown on detector panel) - or specified folder path ending with '/': - e.g. user : FilePath='/net/s29data/export/data_29idc/2018_2/UserName/netCDF/' - e.g. staff: FilePath='/net/s29data/export/data_29idb/2018_2/netCDF/' - Prefix: by default, uses prefix as shown on detector panel ("EA_") - - x,y,img=EA_Image(1) - plt.imshow(img,extent = [min(x), max(x), min(y), max(y)], aspect = 'auto') - plt.show()) - """ - nc=nc_unpack(ScanNum,FilePath,Prefix) - x,xname,y,yname,img,hv,wk,PE=EA_data(nc) - y=np.array(y) - img=img[0] - if EnergyAxis == 'KE': - x=np.array(x) - else: - x=hv-wk-np.array(x) - return x, y, img - -def EA_Spectrum(ScanNum,EnergyAxis='KE',FilePath=None,Prefix=None): - """ - Returns - x = KE or BE energy scale; BE is calculated based on the wk in the SES and the mono energy - y = Integrated intensity - FilePath: by default plot scans for the current data folder (as shown on detector panel) - or specified folder path ending with '/': - e.g. user : FilePath='/net/s29data/export/data_29idc/2018_2/UserName/netCDF/' - e.g. staff: FilePath='/net/s29data/export/data_29idb/2018_2/netCDF/' - Prefix: by default, uses prefix as shown on detector panel ("EA_") - - Simple plot: x,y=EA_Spectrum(ScanNum);plt.plot(x,y);plt.xlim(min(x),xmax(x));plt.show() -""" - x, ang, img = EA_Image(ScanNum, EnergyAxis,FilePath,Prefix) - y = np.asarray([sum(img[:,i]) for i in range(img.shape[1])]) - return x, y - -def EA_metadata(ScanNum,FilePath=None,Prefix=None): - """ Returns: ActualPhotonEnergy,WorkFunction,GratingPitch,MirrorPitch - """ - nc=nc_unpack(ScanNum,FilePath,Prefix) - # SES parameters - LowEnergy=nc.variables['Attr_LowEnergy'][:][0] - HighEnergy=nc.variables['Attr_HighEnergy'][:][0] - EnergyStep_Swept=nc.variables['Attr_EnergyStep_Swept'][:][0] - EnergyStep_Swept_RBV=nc.variables['Attr_EnergyStep_Swept_RBV'][:][0] - EperChannel=nc.variables['Attr_EnergyStep_Fixed_RBV'][:][0] - WorkFunction=nc.variables['Attr_Energy Offset'][:][0] - DetMode=nc.variables['Attr_DetectorMode'][:][0] # BE=0,KE=1 - AcqMode= nc.variables['Attr_AcquisitionMode'][:][0] # Swept=0, Fixed=1, BS=2 - LensMode=nc.variables['Attr_LensMode'][:][0] - PassEnergyMode=nc.variables['Attr_PassEnergy'][:][0] - PEdict={0:1,1:2,2:5,3:10,4:20,5:50,6:100,7:200,8:500} - PE=PassEnergyMode - - TEY=nc.variables['Attr_TEY'][:][0] - - # Mono parameters - ActualPhotonEnergy=nc.variables['Attr_ActualPhotonEnergy'][:][0] - GratingPitch=nc.variables['Attr_GratingPitch'][:][0] - MirrorPitch=nc.variables['Attr_MirrorPitch'][:][0] - Grating_Density=nc.variables['Attr_Grating_Density'][:][0] - Grating_Slot=nc.variables['Attr_Grating_Slot'][:][0] - GRT_Offset_1=nc.variables['Attr_GRT_Offset_1'][:][0] - GRT_Offset_2=nc.variables['Attr_GRT_Offset_2'][:][0] - GRT_Offset_3=nc.variables['Attr_GRT_Offset_3'][:][0] - MIR_Offset_1=nc.variables['Attr_MIR_Offset_1'][:][0] - b2_GRT1=nc.variables['Attr_b2-GRT1'][:][0] - b2_GRT2=nc.variables['Attr_b2-GRT2'][:][0] - b2_GRT3=nc.variables['Attr_b2-GRT3'][:][0] - - offset=[MIR_Offset_1,GRT_Offset_1,GRT_Offset_2,GRT_Offset_3] - b2=[0,b2_GRT1,b2_GRT2,b2_GRT3] - - return WorkFunction,ActualPhotonEnergy,MirrorPitch,GratingPitch,Grating_Density,Grating_Slot,offset,b2 - - -def Get_EDCmax(ScanNum,EnergyAxis='KE',FilePath=None,Prefix=None): - x,y=EA_Spectrum(ScanNum, EnergyAxis,FilePath,Prefix) - maxY= max(y) - maxX=round(x[np.where(y == max(y))][0],3) - return maxX,maxY # energy position, intensity of the peak - - - -def EDC_Series(first,last,countby, EnergyAxis='BE',title="",norm=None,FilePath=None,Prefix=None): - """ - Plots a seriew of EA_Spectrum - """ - if title == "": - title="Scans: "+str(first)+"/"+str(last)+"/"+str(countby) - fig = plt.figure(figsize=(6,6)) - a1 = fig.add_axes([0,0,1,1]) - for ScanNum in range(first,last+countby,countby): - x,y=EA_Spectrum(ScanNum, EnergyAxis,FilePath,Prefix) - if norm is not None: maxvalue=max(y) - else: maxvalue=1 - plt.plot(x,y/maxvalue,label='#'+str(ScanNum)) - plt.legend(ncol=2, shadow=True, title=title, fancybox=True) - plt.grid(color='lightgray', linestyle='-', linewidth=0.5) - a1.plot - if EnergyAxis == 'BE': - a1.set_xlim(max(x),min(x)) - plt.show() - - - - -def plot_nc(*ScanNum,**kwgraph): - """ - ScanNum = Scan number to be plotted: single scan, or range (first,last,countby) to average. - kwgraph = EDC / FilePath / Prefix - - Transmission mode: angle integrated EDC. - - Angular mode: - default: band map only - EDC = 'y' : angle integrated EDC only - EDC = 'both': angle integrated EDC + band map - EnergyAxis = KE (default) or BE (BE uses work function from SES) - FilePath: by default plot scans for the current data folder (as shown on detector panel) - or specified folder path ending with '/': - e.g. user : FilePath='/net/s29data/export/data_29idc/2018_2/UserName/netCDF/' - e.g. staff: FilePath='/net/s29data/export/data_29idb/2018_2/netCDF/' - Prefix: by default, uses prefix as shown on detector panel ("EA_") - - """ - FilePath,Prefix,EDC,EnergyAxis,avg=None,None,None,'KE',None - if kwgraph is not None: - for key, value in list(kwgraph.items()): - if key=='FilePath': FilePath=value - if key=='Prefix': Prefix=value - if key=='EDC': EDC=value - if key=='EnergyAxis': EnergyAxis=value - if key=='avg': avg=1 - #Get lens mode - nc=nc_unpack(ScanNum[0],FilePath,Prefix) - LensMode=nc.variables['Attr_LensMode'][:][0] - #Loading Scans () - first=ScanNum[0] - if len(ScanNum)==1: - last =ScanNum[0] - countby=1 - else: - last=ScanNum[1] - countby=ScanNum[2] - for n in range(first,last+countby,countby): - x,intensity=EA_Spectrum(n,EnergyAxis,FilePath,Prefix) - x,y,img =EA_Image(n,EnergyAxis,FilePath,Prefix) - if n == first: - Spectra=intensity - Img=img - else: - if avg == 1: #Summing the Scans - print('averaging') - Spectra=np.add(Spectra, intensity) - Img=np.add(Img,img) - - #Getting plot size - if LensMode == 0 or EDC != None and EDC != 'both': #Integrated Angle only - hsize,vsize=6,3.5 - elif LensMode >0 and EDC == None: - hsize,vsize=6,4 - elif LensMode >0 and EDC == 'both': - hsize,vsize=6,8 - if kwgraph is not None: - for key, value in list(kwgraph.items()): - if key=='hsize': hsize=value - if key=='vsize': vsize=value - #plotting\ - if LensMode == 0 or EDC != None and EDC != 'both': #Integrated Angle only - #print('p-DOS only') - fig, ax = plt.subplots(figsize=(hsize,vsize)) # HxV - ax.plot(x,Spectra) - if EnergyAxis == "BE": - ax.set_xlim(max(x),min(x)) - else: - ax.set_xlim(min(x),max(x)) - ax.set(xlabel=EnergyAxis,ylabel='Intensity') - ax.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) - ax.grid(color='lightgray', linestyle='-', linewidth=0.5) - elif LensMode >0 and EDC is None: #Imgage Only - #print('Image Only') - fig, ax = plt.subplots(figsize=(hsize,vsize)) # HxV - if EnergyAxis == 'BE': - fig=ax.imshow(Img,extent = [max(x), min(x), min(y), max(y)], aspect = 'auto') - else: - fig=ax.imshow(Img,extent = [min(x), max(x), min(y), max(y)], aspect = 'auto') - ax.set(xlabel=EnergyAxis,ylabel="Angle") - elif LensMode >0 and EDC == 'both': - #print('both') - fig, axes = plt.subplots(2,1,figsize=(hsize,vsize)) # HxV - axes=np.array(axes) - for (n,ax) in zip(list(range(2)),axes.flat): - if n == 0: - ax.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) - ax.grid(color='lightgray', linestyle='-', linewidth=0.5) - ax.plot(x,Spectra) - if EnergyAxis == "BE": - ax.set_xlim(max(x),min(x)) - else: - ax.set_xlim(min(x),max(x)) - ax.set(xlabel=EnergyAxis,ylabel='Intensity') - if n == 1: - if EnergyAxis == 'BE': - ax.imshow(Img,extent = [max(x), min(x), min(y), max(y)], aspect = 'auto') - else: - ax.imshow(Img,extent = [min(x), max(x), min(y), max(y)], aspect = 'auto') - ax.set(xlabel=EnergyAxis,ylabel='Angle') - plt.tight_layout() - plt.show() - - -def plot_nc_Sum(first,last,**kwgraph): - - FilePath,Prefix=None,None - if kwgraph is not None: - for key, value in list(kwgraph.items()): - if key=='FilePath': FilePath=value - if key=='Prefix': Prefix=value - for n in range(first,last+1): - print(n) - nc=nc_unpack(n,FilePath,Prefix) - x,xname,ycrop,yname,img,hv,wk,PE=EA_data(nc) - LensMode=nc.variables['Attr_LensMode'][:][0] - if n == first: - datasum = nc.variables['array_data'] - x,xname,ycrop,yname,img,hv,wk,PE=EA_data(nc) - else: - data = nc.variables['array_data'] - tmp=datasum - datasum=np.add(tmp,data) - crop_data=data[:,338:819] - fig, ax = plt.subplots(figsize=(6,4)) # HxV - fig=ax.imshow(crop_data.squeeze(),extent = [min(x), max(x), min(ycrop), max(ycrop)], aspect = 'auto') - plt.show() - - - - - - - - - - - -############################################################################################### -##################################### FR curves fitting ####################################### -############################################################################################### - - -def fit_mda(scannum,det,FWHM_or_PolyOrder,fct,hkl_positionner=False,xrange=None,title='',marker='x',graph=True, filepath=None,prefix=None): - """ - fct= 'gauss','lorz','erf','poly','box' - hkl_positionner = 'H','K','L','tth','th','chi','phi' - """ - - if hkl_positionner == False: - x,y,x_name,y_name=mda_1D(scannum,det,1,0,filepath,prefix) - if hkl_positionner: - d={'h':46,'k':47,'l':48,'tth':54,'th':55,'chi':56,'phi':57} - x,y,x_name,y_name=mda_1D_vsDet(scannum,det,d[hkl_positionner.lower()],1,0,filepath,prefix) - - - - if BL.endstation == 'Kappa' and fct != 'poly': - try: - title=title + ' centroid = '+str(centroid_avg(scannum)) - except: - pass - - def closest(lst, K): - return lst[min(range(len(lst)), key = lambda i: abs(lst[i]-K))] - - def gaussian(x,*p): - amp, cen, wid, bkgd = p - return bkgd+amp*np.exp(-np.power(x - cen, 2.) / (2 * np.power(wid, 2.))) - - def lorentzian( x, *p): - amp, x0, gam, bkgd =p - return bkgd+amp * gam**2 / ( gam**2 + ( x - x0 )**2) - - def step(z,amp=1,bkgd=0,z0=0,width=1): - return (amp*erf((z-z0)/width))+bkgd - - def box(x, *p): - height, center, width ,bkgd = p - return bkgd+height*(center-width/2 < x)*(x < center+width/2) - - - - if xrange is not None: - x1=closest(x,xrange[0]) - x2=closest(x,xrange[1]) - xrange=[x.index(x1),x.index(x2)] - xmin=min(xrange) - xmax=max(xrange) - xcrop=x[xmin:xmax] - ycrop=y[xmin:xmax] - xdata = np.array(xcrop) - ydata = np.array(ycrop) - else: - xdata = np.array(x) - ydata = np.array(y) - - - Imax=np.max(ydata) - #print(xdata) - #print(ydata) - x0=xdata[np.where(ydata==Imax)][0] - A0=xdata[0] - - nPt_fit=200 - xfit = np.linspace(min(x),max(x), nPt_fit) - - - if fct == 'gauss': - FWHM=FWHM_or_PolyOrder - best_vals, covar = curve_fit(gaussian, xdata, ydata, p0=[Imax, x0, FWHM, A0]) #5 p0=[amp,cen,wid] - yfit=gaussian(xfit,*best_vals) - FWHM=2.355*best_vals[2] - center=best_vals[1] - print('Amplitude: ',best_vals[0]) - elif fct == 'lorz': - FWHM=FWHM_or_PolyOrder - best_vals, covar = curve_fit(lorentzian, xdata, ydata, p0=[Imax, x0, FWHM, A0]) #5 p0=[amp,cen,wid] - yfit=lorentzian(xfit,*best_vals) - FWHM=2.355*best_vals[2] - center=best_vals[1] - print('Amplitude: ',best_vals[0]) - elif fct == 'erf' or fct == 'box': - FWHM=FWHM_or_PolyOrder - xmax=np.max(xdata) - xmin=np.min(xdata) - amp=np.mean(ydata) - x0=np.mean(xdata) - ymin=np.min(ydata) - if fct == 'erf': - yfirst=ydata[np.where(xdata == xmin)][0] - ylast =ydata[np.where(xdata == xmax)][0] - if yfirst-ylast >0: amp=-abs(amp) #amp <0 step down - else: amp = abs(amp) #amp >0 step up - p0=[amp, ymin, x0, FWHM] - popt,pcor = curve_fit(step, xdata, ydata, p0=p0) - yfit=step(xfit,*popt) - FWHM=popt[3] - center=popt[2] - elif fct == 'box': - p0=[amp, x0, FWHM, A0] - popt,pcor = curve_fit(box, xdata, ydata, p0=p0) - yfit=box(xfit,*popt) - FWHM=popt[2] - center=popt[1] - elif fct == 'poly': - PolyRank=FWHM_or_PolyOrder - coefs = poly.polyfit(xdata, ydata, PolyRank) - yfit = poly.polyval(xfit, coefs) - result='' - for i in list(range(len(coefs))): - result=result+'a'+str(i)+' = '+str(round(coefs[i],3))+'\n' - print(result) - center=coefs - - if fct != 'poly': - print('Center: ',center) - print('FWHM: ',FWHM) - print('\n') - - - if graph == True: - center=round(center,4) - fig,(ax1)=plt.subplots(1,1) - fig.set_size_inches(5,4) - ax1.plot(xdata,ydata,label='mda #'+str(scannum),marker=marker) - ax1.plot(xfit,yfit,label='fit @ '+str(center)[0:6]) - ax1.set(ylabel=y_name) - 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(shadow=True, title=title, fancybox=True) - - return center - - -def fit_centroid(n): - fit_mda(n,25,0,'poly',graph=False) - -def centroid_avg(scannum,det=25): # det = detector number for centroid position - avg=round(fit_mda_poly(scannum,det,0,graph=None)[0],2) - return avg - - -def fit_mda_gauss(scannum,det,FWHM,xrange=None,title='',marker='x',graph=1, filepath=None,prefix=None,scanIOC=None): - fct='gauss' - fit_mda(scannum,det,FWHM,fct,xrange,title,marker,graph, filepath,prefix,scanIOC) - - -def fit_mda_lorz(scannum,det,FWHM,xrange=None,title='',marker='x',graph=1, filepath=None,prefix=None,scanIOC=None): - fct='lorz' - fit_mda(scannum,det,FWHM,fct,xrange,title,marker,graph, filepath,prefix,scanIOC) - - -def fit_mda_erf(scannum,det,FWHM,xrange=None,title='',marker='x',graph=1, filepath=None,prefix=None,scanIOC=None): - fct='erf' - fit_mda(scannum,det,FWHM,fct,xrange,title,marker,graph, filepath,prefix,scanIOC) - -def fit_mda_poly(scannum,det,PolyRank,xrange=None,title='',marker='x',graph=1, filepath=None,prefix=None,scanIOC=None): - fct='poly' - fit_mda(scannum,det,PolyRank,fct,xrange,title,marker,graph, filepath,prefix,scanIOC) - - -def fit_mda_box(scannum,det,FWHM,xrange=None,title='',marker='x',graph=1, filepath=None,prefix=None,scanIOC=None): - fct='box' - fit_mda(scannum,det,FWHM,fct,xrange,title,marker,graph, filepath,prefix,scanIOC) - - - - - - - - -############################################################################################### -######################################### hkl ################################### -############################################################################################### - - - -def plot_hkl(mydata,n,x,y,title='',nlabel=''): - """mydata = instance of mdaFile object - n = scan number or [scan number1, ..., scan number N] - x = h, k or l index (D##) - d = detector index (D##) - """ - if type(n) == int: - maxpts=mydata.dim1[n].curr_pt - x_index=mydata.dim1[n].kappaDet()[x][0] - y_index=mydata.dim1[n].kappaDet()[y][0] - x_name =mydata.dim1[n].d[x_index].desc - y_name =mydata.dim1[n].kappaDet()[y][2] - plt.plot(mydata.dim1[n].d[x_index].data[:maxpts],mydata.dim1[n].d[y_index].data[:maxpts],label='scan #'+str(n)+' '+nlabel) - elif type(n) == list: - for i,j in enumerate(n): - maxpts=mydata.dim1[j].curr_pt - x_index=mydata.dim1[j].kappaDet()[x][0] - y_index=mydata.dim1[j].kappaDet()[y][0] - x_name =mydata.dim1[j].d[x_index].desc - y_name =mydata.dim1[j].kappaDet()[y][2] - try: - curve_label='scan #'+str(j)+' '+nlabel[i] - except: - curve_label='scan #'+str(j) - plt.plot(mydata.dim1[j].d[x_index].data[:maxpts],mydata.dim1[j].d[y_index].data[:maxpts],label=curve_label) - else: - print('n must be a single scan (int) or a list of scan') - return - plt.xlabel(x_name) - plt.ylabel(y_name) - plt.locator_params(tight=None,nbins=5,axis='x') - plt.legend(ncol=1, shadow=True, title=title, fancybox=True,loc='center left', bbox_to_anchor=(1, 0.5)) - plt.grid(color='lightgray', linestyle='-', linewidth=0.5) - plt.show() - - -def fit_hkl(mydata,n,pos,det,FWHM,fct='gauss',xrange=None,title='',marker='x',graph=1): - """ - mydata = instance of the class mdaFile - n = scan number - pos = D## for positioner - det = D## for detector - FWHM = width estimate - fct = 'gauss' or 'lorz' - xrange = [x1,x2] subrange for fit - """ - - - x_index=mydata.dim1[n].kappaDet()[pos][0] - y_index=mydata.dim1[n].kappaDet()[det][0] - x_name =mydata.dim1[n].d[x_index].desc - y_name =mydata.dim1[n].kappaDet()[det][2] - - x=mydata.dim1[n].d[x_index].data - y=mydata.dim1[n].d[y_index].data - - def closest(lst, K): - return lst[min(range(len(lst)), key = lambda i: abs(lst[i]-K))] - - if xrange is not None: - x1=closest(x,xrange[0]) - x2=closest(x,xrange[1]) - xrange=[np.where(x==x1),np.where(x==x2)] - xmin=min(xrange) - xmax=max(xrange) - xmin=min(xrange[0][0]) - xmax=max(xrange[1][0]) - xcrop=x[xmin:xmax] - ycrop=y[xmin:xmax] - xdata = np.array(xcrop) - ydata = np.array(ycrop) - else: - xdata = np.array(x) - ydata = np.array(y) - - Imax=np.max(ydata) - x0=xdata[np.where(ydata==Imax)][0] - - nPt_gaus=200 - xfit = np.linspace(min(x),max(x), nPt_gaus) - - - def lorentzian( x, amp, x0, gam ): - return amp * gam**2 / ( gam**2 + ( x - x0 )**2) - - def gaussian(x, amp, cen, wid): - return amp*np.exp(-np.power(x - cen, 2.) / (2 * np.power(wid, 2.))) - - if fct == 'gauss': - best_vals, covar = curve_fit(gaussian, xdata, ydata, p0=[Imax, x0, FWHM]) #5 p0=[amp,cen,wid] - yfit=gaussian(xfit,*best_vals) - elif fct == 'lorz': - best_vals, covar = curve_fit(lorentzian, xdata, ydata, p0=[Imax, x0, FWHM]) #5 p0=[amp,cen,wid] - yfit=lorentzian(xfit,*best_vals) - else: - print('Not a valid function: fct = "gauss" or fct = "lorz"') - return - - FWHM=2.355*best_vals[2] - center=best_vals[1] - print('Amplitude: ',best_vals[0]) - print('Center: ',center) - print('FWHM: ',FWHM) - - if graph is not None: - fig,(ax1)=plt.subplots(1,1) - fig.set_size_inches(5,4) - ax1.plot(xdata,ydata,label='data',marker=marker) - ax1.plot(xfit,yfit,label='fit @ '+str(center)[0:6]) - ax1.set(ylabel=y_name) - ax1.set(xlabel=x_name) - ax1.locator_params(tight=None,nbins=5,axis='x') - ax1.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) - ax1.grid(color='lightgray', linestyle='-', linewidth=0.5) - ax1.legend(shadow=True, title=title, fancybox=True) - - return center - - -def fit_d4(n=BL.mda.lastFileNum()): - d4=fit_mda(n,34,0.1,'gauss',title='mda_'+str(n).zfill(4)) - return round(d4,3) - -def fit_d3(n=BL.mda.lastFileNum()): - d3=fit_mda(n,33,3,'gauss',title='mda_'+str(n).zfill(4)) - return round(d3,3) - -def fit_z(n=BL.mda.lastFileNum(),d=33): - z=fit_mda(n,d,500,'erf',title='mda_'+str(n).zfill(4)) - return round(z,0) - -def plotd(): - dets=[34,33,35] - n=BL.mda.lastFileNum() - d=dets[caget('29idKappa:det:set')] - plot_mda(n,d,title='mda_'+str(n).zfill(4)) - - - -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 read_hkl_old(n,user=None,run=None): -# h=[] -# k=[] -# l=[] -# if user is None: user=MDA_CurrentUser() -# if run is None: run=MDA_CurrentRun() -# with open('/home/beams/29IDUSER/Documents/User_Folders/'+user+'/hkl/scan_'+str(n)+'.txt') as csv_file: -# csv_f=csv.reader(csv_file,delimiter=',') -# for row in csv_f: -# if not row[0]=='h': -# h.append(float(row[0])) -# k.append(float(row[1])) -# l.append(float(row[2])) -# return np.array(h), np.array(k), np.array(l) - -# def plot_hkl_old(mydata,n1,n2=None,which='h',det=39,cropMin=None,cropMax=None,title=''): -# D=mydata.kappaDet(n1) -# d=D[det][1] -# if which == 'h': -# m = 0 -# if which == 'k': -# m = 1 -# if which == 'l': -# m = 2 - -# plt.figure(num=None, figsize=(6, 6), dpi=80, facecolor='w', edgecolor='k') -# if n2 == None: -# n=n1 -# #dif=len(read_hkl(n)[m])-mydata.dim1[n].curr_pt -# if cropMax is not None: -# x=read_hkl(n)[m][cropMin:-cropMax] -# else: -# x=read_hkl(n)[m][cropMin:] - -# plt.plot(x,mydata.dim1[n].d[d].data,label='scan #'+str(n),marker='+') -# else: -# for n in range(n1,n2+1): -# #dif=len(read_hkl(n)[m])-mydata.dim1[n].curr_pt -# if cropMax is not None: -# x=read_hkl(n)[m][cropMin:-cropMax] -# else: -# x=read_hkl(n)[m][cropMin:] - -# plt.plot(x,mydata.dim1[n].d[d].data,label='scan #'+str(n),marker='+') -# plt.xlabel(which) -# plt.ylabel(D[det][-1]) -# plt.legend(ncol=1, shadow=True, title=title, fancybox=True,loc='center left', bbox_to_anchor=(1, 0.5)) -# #plt.title(title) -# plt.grid(color='lightgray', linestyle='-', linewidth=0.5) -# plt.show() - - - -# def fit_hkl_gauss_old(scannum,det,FWHM,which='l',cropMin=None,cropMax=None,xrange=None,title='',marker='x',graph=1): -# motor,y,motor_name,y_name=mda_1D(scannum,det,1,0) -# if which == 'h': -# m = 0 -# if which == 'k': -# m = 1 -# if which == 'l': -# m = 2 -# if cropMax is not None: -# x=read_hkl(scannum)[m][cropMin:-cropMax] -# else: -# x=read_hkl(scannum)[m][cropMin:] -# def closest(lst, K): -# return lst[min(range(len(lst)), key = lambda i: abs(lst[i]-K))] - -# if xrange is not None: -# x1=closest(x,xrange[0]) -# x2=closest(x,xrange[1]) -# xrange=[np.where(x==x1),np.where(x==x2)] -# xmin=min(xrange) -# xmax=max(xrange) -# xmin=min(xrange[0][0]) -# xmax=max(xrange[1][0]) -# xcrop=x[xmin:xmax] -# ycrop=y[xmin:xmax] -# xdata = np.array(xcrop) -# ydata = np.array(ycrop) -# else: -# xdata = np.array(x) -# ydata = np.array(y) - -# Imax=np.max(ydata) -# x0=xdata[np.where(ydata==Imax)][0] - -# nPt_gaus=200 -# xfit = np.linspace(min(x),max(x), nPt_gaus) - -# def gaussian(x, amp, cen, wid): -# return amp*np.exp(-np.power(x - cen, 2.) / (2 * np.power(wid, 2.))) - -# best_vals, covar = curve_fit(gaussian, xdata, ydata, p0=[Imax, x0, FWHM]) #5 p0=[amp,cen,wid] -# yfit=gaussian(xfit,*best_vals) -# FWHM=2.355*best_vals[2] -# center=best_vals[1] -# print('Amplitude: ',best_vals[0]) -# print('Center: ',center) -# print('FWHM: ',FWHM) - -# if graph is not None: -# fig,(ax1)=plt.subplots(1,1) -# fig.set_size_inches(5,4) -# ax1.plot(xdata,ydata,label='data',marker=marker) -# ax1.plot(xfit,yfit,label='fit @ '+str(center)[0:6]) -# ax1.set(ylabel=y_name) -# ax1.set(xlabel=which) -# ax1.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) -# ax1.grid(color='lightgray', linestyle='-', linewidth=0.5) -# ax1.legend(shadow=True, title=title, fancybox=True) - -# return center - - -############################################################################################### -######################################### Start Of The Week ################################### -############################################################################################### - -def plot_StartOfTheWeek_DetDict(branch): - """ - returns the detectors for a given branch - - """ - DetDict={'c':(9,7,8,15),'d':(9,7,8,14)} - return DetDict[branch] - -def StartOfTheWeek_plot(branch,FirstScanNum,**kwargs): - """ - Plots the data from StartOfTheWeek - - branch is used to set the detectors - detCA4,detH,detV,detDiode=plot_StartOfTheWeek_Det(branch) - - FirstScanNum is based on slit1A - slit1A-H = FirstScanNum - slit1A-V = FirstScanNum + 1 - wire1-H = FirstScanNum + 2 - wire1-V = FirstScanNum + 3 - monoVslit = FirstScanNum + 4/5/6/7 - flux = FirstScanNum + 8 - - Slit 1A and Wire scans: determine ID steering and Slit1A position - Scan_MonoVsSlit: determine the steering from M0/M1 - by default the full range is plotted (pnt_first=0, pnt_last=inf) - refine the plot via - plot_StartOfTheWeek_mono(branch,FirstScanNum,pnt_first,pnt_last) - - kwargs: - filepath = None, uses current mda filepath unless specified - e.g. user : filepath='/net/s29data/export/data_29idc/2018_2/UserName/mda/' - e.g. staff: filepath='/net/s29data/export/data_29idb/2018_2/mda/' - prefix = None, uses current mda prefix unless specified - scanIOC = None, uses BL_ioc() unless specified - - scanType = ['slit1','wire','flux','monoVslit'], full set by default - - ref_firstScanNum to plot reference spectra - ref_branch = branch, unless specified - ref_filepath = filepath, unless specified - ref_prefix = prefix, unless specified - - steering out => moves beam more positive (20 urad ~ 0.5 mm) - steering up => moves beam more positive (20 urad ~ 0.5 mm) - -figure, axes = plt.subplots(nrows=2, ncols=2) -axes[0, 0].plot(x, y) - """ - - kwargs.setdefault('filepath',BL.mda.filepath()) - kwargs.setdefault('prefix',BL.mda.prefix()) - - kwargs.setdefault('scanType',['slit1','wire','flux','monoVslit']) - - kwargs.setdefault('ref_firstScanNum',None) - kwargs.setdefault('ref_fpath',None) - kwargs.setdefault('ref_branch',branch) - kwargs.setdefault('ref_filepath',BL.mda.filepath()) - kwargs.setdefault('ref_prefix',BL.mda.prefix()) - - kwargs.setdefault('debug',False) - - - scanNum=FirstScanNum - ref_firstScanNum=kwargs['ref_firstScanNum'] - detCA4,detH,detV,detDiode=plot_StartOfTheWeek_DetDict(branch) - - - if 'slit1' in kwargs['scanType']: - if kwargs['debug']: - print('slit1') - plot_StartOfTheWeek_slit1A(branch,scanNum,**kwargs) - scanNum+=2 - if kwargs['ref_firstScanNum'] is not None: - kwargs.update({'ref_firstScanNum':ref_firstScanNum+2}) - - - if 'wire' in kwargs['scanType']: - if kwargs['debug']: - print('wire') - plot_StartOfTheWeek_wire(branch,scanNum,**kwargs) - scanNum+=2 - if kwargs['ref_firstScanNum'] is not None: - ref_firstScanNum+=2 - kwargs.update({'ref_firstScanNum':ref_firstScanNum+2}) - - if 'monoVslit' in kwargs['scanType']: - d=IEXdata(scanNum,path=kwargs['filepath'],prefix=kwargs['prefix'],q=1) - if d.mda[scanNum].header.all['rank']<2: #quick - print(scanNum, detDiode) - V2=fit_mda(scanNum,detDiode,1,'gauss',filepath=kwargs['filepath'],prefix=kwargs['prefix'],scanIOC=kwargs['scanIOC'],title='2V - mda_'+str(scanNum)) - H2=fit_mda(scanNum+1,detDiode,1,'gauss',filepath=kwargs['filepath'],prefix=kwargs['prefix'],scanIOC=kwargs['scanIOC'],title='2H - mda_'+str(scanNum+1)) - V1=fit_mda(scanNum+2,detDiode,1,'gauss',filepath=kwargs['filepath'],prefix=kwargs['prefix'],scanIOC=kwargs['scanIOC'],title='1V - mda_'+str(scanNum+2)) - H1=fit_mda(scanNum+3,detDiode,1,'gauss',filepath=kwargs['filepath'],prefix=kwargs['prefix'],scanIOC=kwargs['scanIOC'],title='1H - mda_'+str(scanNum+3)) - plt.show() - print('\nFit positions:') - print(f"V2={round(V2,3)}") - print(f"H2={round(H2,3)}") - print(f"V1={round(V1,3)}") - print(f"H1={round(H1,3)}") - - else: #MonoVsSlit - print('\n# To plot the Mono vs Slit data use:\n') - print('\tplot_MonoVsSlit(\"'+branch+'\",'+str(scanNum)+','+str(detDiode)+',0,inf)'+'\t#2V') - print('\tplot_MonoVsSlit(\"'+branch+'\",'+str(scanNum+1)+','+str(detDiode)+',0,inf)'+'\t#2H') - print('\tplot_MonoVsSlit(\"'+branch+'\",'+str(scanNum+2)+','+str(detDiode)+',0,inf)'+'\t#1V') - print('\tplot_MonoVsSlit(\"'+branch+'\",'+str(scanNum+3)+','+str(detDiode)+',0,inf)'+'\t#1H') - print('\n# (pnt_first,pnt_last0=(0,inf) => plots all') - print('# select specific first/last to refine.') - - print('\nREMEMBER to update slit center using: \tupdate_slit_dict()' ) - scanNum+=4 - if kwargs['ref_firstScanNum'] is not None: - kwargs.update({'ref_firstScanNum':ref_firstScanNum+4}) - - if 'flux' in kwargs['scanType']: - if kwargs['debug']: - print('flux') - plot_StartOfTheWeek_flux(branch,scanNum,**kwargs) - -def plot_StartOfTheWeek_slit1A(branch,scanNum,**kwargs): - """ - plots the slit1A scans - scanNum = slit1A-H scanNum - """ - kwargs.setdefault('filepath',BL.mda.filepath()) - kwargs.setdefault('prefix',BL.mda.prefix()) - kwargs.setdefault('plotType',['slit1','wire','flux','monoVslit']) - kwargs.setdefault('ref_firstScanNum',None) - kwargs.setdefault('ref_fpath',None) - kwargs.setdefault('ref_branch',branch) - kwargs.setdefault('ref_filepath',BL.mda.filepath()) - kwargs.setdefault('ref_prefix',BL.mda.prefix()) - kwargs.setdefault('debug',False) - - detCA4,detH,detV,detDiode=plot_StartOfTheWeek_DetDict(branch) - ref_detCA4,ref_detH,ref_detV,ref_detDiode=plot_StartOfTheWeek_DetDict(kwargs['ref_branch']) - - figure, axes = plt.subplots(nrows=1, ncols=2,figsize=(10,3)) - for i,t in enumerate(['1H center scan','1V center scan']): - d=IEXdata(scanNum,path=kwargs['filepath'],prefix=kwargs['prefix'],q=1) - axes[i].plot(d.mda[scanNum].det[detCA4].scale['x'], d.mda[scanNum].det[detCA4].data,marker='x',label=str(scanNum)) - scanNum+=1 - if kwargs['ref_firstScanNum'] is not None: - ref_scanNum=kwargs['ref_firstScanNum']+i - ref_d=IEXdata(ref_scanNum,path=kwargs['ref_filepath'],prefix=kwargs['ref_prefix'],q=1) - axes[i].plot(ref_d.mda[ref_scanNum].det[ref_detCA4].scale['x'], ref_d.mda[ref_scanNum].det[ref_detCA4].data,marker='x',label=str(ref_scanNum)) - axes[i].grid(color='lightgray', linestyle='-', linewidth=0.5) - axes[i].title.set_text(t) - axes[i].legend() - plt.show() - print("\nsteering out => move beam more positive (10 urad ~ 0.25 mm)") - print("steering up => move beam more positive (10 urad ~ 0.25 mm)") - print("\nTo fit beam position use:\n") - print("detCA4,detH,detV,detDiode=plot_StartOfTheWeek_DetDict('"+kwargs['ref_branch']+"')") - print("fit_mda("+str(scanNum-2)+",detCA4,1,'gauss',xrange=(-1,1))") - print("fit_mda("+str(scanNum-1)+",detCA4,1,'gauss',xrange=(-1,1))\n") - - -def plot_StartOfTheWeek_wire(branch,scanNum,**kwargs): - """ - plots the wire scans - scanNum = wire-H scanNum - """ - kwargs.setdefault('filepath',BL.mda.filepath()) - kwargs.setdefault('prefix',BL.mda.prefix()) - kwargs.setdefault('plotType',['slit1','wire','flux','monoVslit']) - kwargs.setdefault('ref_firstScanNum',None) - kwargs.setdefault('ref_fpath',None) - kwargs.setdefault('ref_branch',branch) - kwargs.setdefault('ref_filepath',BL.mda.filepath()) - kwargs.setdefault('ref_prefix',BL.mda.prefix()) - kwargs.setdefault('debug',False) - - detCA4,detH,detV,detDiode=plot_StartOfTheWeek_DetDict(branch) - ref_detCA4,ref_detH,ref_detV,ref_detDiode=plot_StartOfTheWeek_DetDict(kwargs['ref_branch']) - - figure, axes = plt.subplots(nrows=1, ncols=2,figsize=(10,3)) - for i,t in enumerate(['H-wire','V-wire']): - d=IEXdata(scanNum,path=kwargs['filepath'],prefix=kwargs['prefix'],q=1) - #niceplot(d.mda[scanNum].det[DetDict[branch][1+i]],marker='x',label=str(scanNum)) - detNum=plot_StartOfTheWeek_DetDict(branch)[1+i] - axes[i].plot(d.mda[scanNum].det[detNum].scale['x'], d.mda[scanNum].det[detNum].data,marker='x',label=str(scanNum)) - scanNum+=1 - if kwargs['ref_firstScanNum'] is not None: - ref_scanNum=kwargs['ref_firstScanNum']+i - ref_d=IEXdata(ref_scanNum,path=kwargs['ref_filepath'],prefix=kwargs['ref_prefix'],q=1) - #niceplot(ref_d.mda[ref_scanNum].det[DetDict[kwargs["ref_branch"]][1+i]],marker='x',label=str(ref_scanNum)) - detNum=plot_StartOfTheWeek_DetDict(kwargs["ref_branch"])[1+i] - axes[i].plot(ref_d.mda[ref_scanNum].det[detNum].scale['x'], ref_d.mda[ref_scanNum].det[detNum].data,marker='x',label=str(ref_scanNum)) - axes[i].grid(color='lightgray', linestyle='-', linewidth=0.5) - axes[i].title.set_text(t) - axes[i].legend() - plt.show() - -def plot_StartOfTheWeek_flux(branch,scanNum,**kwargs): - """ - plots the wire scans - scanNum = wire-H scanNum - """ - kwargs.setdefault('filepath',BL.mda.filepath()) - kwargs.setdefault('prefix',BL.mda.prefix()) - kwargs.setdefault('plotType',['slit1','wire','flux','monoVslit']) - kwargs.setdefault('ref_firstScanNum',None) - kwargs.setdefault('ref_fpath',None) - kwargs.setdefault('ref_branch',branch) - kwargs.setdefault('ref_filepath',BL.mda.filepath()) - kwargs.setdefault('ref_prefix',BL.mda.prefix()) - kwargs.setdefault('debug',False) - - detCA4,detH,detV,detDiode=plot_StartOfTheWeek_DetDict(branch) - ref_detCA4,ref_detH,ref_detV,ref_detDiode=plot_StartOfTheWeek_DetDict(kwargs['ref_branch']) - - for t in ['ID peak @ 500eV']: - d=IEXdata(scanNum,path=kwargs['filepath'],prefix=kwargs['prefix'],q=1) - niceplot(d.mda[scanNum].det[detDiode],marker='x',label=str(scanNum)) - scanNum+=1 - if kwargs['ref_firstScanNum'] is not None: - ref_scanNum=kwargs['ref_firstScanNum']+2 - ref_d=IEXdata(ref_scanNum,path=kwargs['ref_filepath'],prefix=kwargs['ref_prefix'],q=1) - niceplot(ref_d.mda[ref_scanNum].det[ref_detDiode],marker='x',label=str(ref_scanNum)) - ref_scanNum+=1 - plt.grid(color='lightgray', linestyle='-', linewidth=0.5) - plt.title(t) - plt.legend() - plt.show() - -def plot_MonoVsSlit(branch,ScanNum,detDiode,pnt_first,pnt_last,norm=True,filepath=None,prefix=None,scanIOC=None): - """ - Plots Scan_MonoVsSlit to determine the steering from M0/M1 - To plot the full range (pnt_first=0, pnt_last=inf) - plot_StartofWeek_mono(branch,FirstScanNum+4,pnt_first,pnt_last) - - filepath: by default plot scans for the current data folder (as defined in BL_ioc() ScanRecord SaveData) - or specified folder path ending with '/': - e.g. user : filepath='/net/s29data/export/data_29idc/2018_2/UserName/mda/' - e.g. staff: filepath='/net/s29data/export/data_29idb/2018_2/mda/' - prefix: by default, uses prefix as defined in ScanRecord ("mda_") - """ - x,y,z,x_name,y_name,z_name=mda_2D(ScanNum,detDiode,filepath,prefix,scanIOC) - Which=str(y_name)[10:12] - if pnt_last is inf: - pnt_last=len(z)-1 - for i in range(pnt_first,pnt_last+1): - maxvalue=max(z[i]) - if norm == True: - plt.plot(x,z[i]/maxvalue,label='#'+str(i)+': '+str(round(y[i],2))) - else: - plt.plot(x,z[i],label='#'+str(i)+': '+str(round(y[i],2))) - plt.legend(bbox_to_anchor=(1, 0), loc='lower left', ncol=2,shadow=True, title="ScanNum: "+str(ScanNum)+"\nSlit-"+Which+" position", fancybox=True) - #plt.legend(loc='lower left',ncol=2, shadow=True, title="ScanNum: "+str(ScanNum)+"\nSlit-"+Which+" position", fancybox=True) - plt.grid(color='lightgray', linestyle='-', linewidth=0.5) - plt.show() - - -############################################################################################### -######################################### IDCalibration New ################################### -############################################################################################### - - - -def id_calibration_fit(first_scan,last_scan,det,PolyRank,**kwargs): - - - #id_calibration_fit(FirstLast[0],FirstLast[1],det,poly_order,mytitle=mytitle,countby=countby,plotMin=plt_min,plotMax=plt_max,plotType=plotType,filepath=filepath,prefix=prefix) - """ - Fits calibration curves fpr each GRTs and modes included in the data set. Creates 3 dictionnaries: - - coefs={[GRT][mode][[breakpoint1,[coefs]],[breakpoint2,[coefs]...} - xdata= {[GRT][mode][[breakpoint1,[flux curve x axis]],[breakpoint2,[flux curve x axis]...} - fdata= {[GRT][mode][[breakpoint1,[flux curve y axis]],[breakpoint2,[flux curve y axis]...} - - kwargs: - countby = 1 by default - mytitle = '' by default - plotMin = min x range for plotting (default 250) - plotMax = max x range for plotting (default 3000) - plotType = ['dif,'fit,'flux'], full set by default - filepath = None, uses current mda filepath unless specified - e.g. user : filepath='/net/s29data/export/data_29idc/2018_2/UserName/mda/' - e.g. staff: filepath='/net/s29data/export/data_29idb/2018_2/mda/' - prefix = None, uses current mda prefix unless specified - scanIOC = None, uses BL_ioc() unless specified - """ - - kwargs.setdefault('countby',1) - kwargs.setdefault('mytitle','') - #kwargs.setdefault('plotMin',2000) - kwargs.setdefault('plotMin',225) - kwargs.setdefault('plotMax',3000) - kwargs.setdefault('plotType',['fit','dif','flux']) - kwargs.setdefault('filepath',BL.mda.filepath()) - kwargs.setdefault('prefix',BL.mda.prefix()) - - countby=kwargs['countby'] - mytitle=kwargs['mytitle'] - plotMin=kwargs['plotMin'] - plotMax=kwargs['plotMax'] - filepath=kwargs['filepath'] - prefix=kwargs['prefix'] - - - def calibration_curve(first,last,det,countby,filepath,prefix): - mono_list=[] - ID_list=[] - max_list=[] - flux_list=[] - print("filepath = ",filepath) - print("prefix = ",prefix) - print("First scan = ",first) - print("Last scan = ",last) - for i in range(first,last,countby): - x,y,x_name,y_name=mda_1D(i,det,1,0,filepath,prefix) #mda_1D(ScanNum,DetectorNum,coeff=1,bckg=0,filepath=None,prefix=None,scanIOC=None): - v,w,v_name,w_name=mda_1D(i, 4 ,1,0,filepath,prefix) - if y != []: - n=y.index(max(y)) # finds the peak max intensity index - e=round(x[n],2) # finds the corresponding mono energy - sp=round(w[2]*1000,0) # reads the ID set point - mono_list.append(e) - max_list.append(max(y)) - ID_list.append(sp) - flux_list.append(current2flux(max(y),e,p=None)) - return mono_list,ID_list,max_list,flux_list - - Mono_max,ID_SP,int_max,flux=calibration_curve(first_scan,last_scan+1,det,countby,filepath,prefix) - nPt_gaus=200 - x_HR = np.linspace(Mono_max[0], Mono_max[-1], nPt_gaus) - - # Data - xdata = np.array(Mono_max) - ydata = np.array(ID_SP) - zdata = np.array(int_max) - fdata = np.array(flux) - # Fitting - coefs = poly.polyfit(xdata, ydata, PolyRank) - ffit_HR = poly.polyval(x_HR, coefs) - ffit_Coarse = poly.polyval(xdata, coefs) - # Residual - Dif=np.array(ID_SP)-np.array(ffit_Coarse) - ratio=(np.array(ID_SP)-np.array(ffit_Coarse))/(np.array(ID_SP)/100) - # Plot differences - #print('plotMin = ',str(plotMin)) - if 'dif' in kwargs['plotType']: - fig = plt.figure(figsize=(12,6)) - plt.plot(Mono_max,ID_SP,marker='x',markersize=5,color='g',linewidth=0,label='data') - plt.plot(x_HR,ffit_HR,color='b',label='SP-fit') - plt.plot(xdata,Dif*100,marker='x',color='r',label='Dif x100') - plt.plot(xdata,ratio*1000,marker='x',color='g',label='Difx1000/ID') - plt.ylabel('ID SP') - plt.xlabel('Mono') - plt.xlim(plotMin,plotMax) - plt.legend(ncol=2, shadow=True, title=mytitle, fancybox=True) - plt.grid(linestyle='-', linewidth='0.5', color='grey') - plt.show() - # Plot raw data + fit - if 'fit' in kwargs['plotType']: - fig = plt.figure(figsize=(12,6)) - a1 = fig.add_axes([0,0,1,1]) - a1.plot(xdata+Dif,zdata,marker='*',markersize=10,color='r',linewidth=0,label='Interpolated ID SP') - for i in range(first_scan,last_scan+1): - x,y,x_name,y_name=mda_1D(i,det,1,0,filepath,prefix) - a1.plot(x,y,color='b') - a1.set_xlim(plotMin,plotMax) - a1.set(xlabel='Mono') - a1.set(ylabel='ID SP') - a1.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) - a1.grid(linestyle='-', linewidth='0.5', color='grey') - plt.legend(ncol=2, shadow=True, title=mytitle, fancybox=True) - plt.show() - # Plot flux curves: - fdata_x=xdata+Dif - if 'flux' in kwargs['plotType']: - fig = plt.figure(figsize=(12,6)) - a1 = fig.add_axes([0,0,1,1]) - a1.plot(fdata_x,fdata,color='r',linewidth=1,label='Flux curves') - a1.set_xlim(plotMin,plotMax) - a1.set(xlabel='Mono') - a1.set(ylabel='ID SP') - a1.set_yscale('log') - #a1.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) - a1.grid(linestyle='-', linewidth='0.5', color='grey') - plt.legend(ncol=2, shadow=True, title=mytitle, fancybox=True) - plt.show() - return coefs, fdata_x,fdata - - - - - - -def read_id_files(first,last,filepath=None,prefix=None,q=True): - """ - Reads extra PVs - Return a list of [[ScanNum,ID_SP,grt,mode],...] for mda files between first and last. - """ - if filepath == None: - filepath=BL.mda.filepath() - if prefix == None: - prefix=BL.mda.prefix()[:-1] - elif prefix[-1] == "_": - prefix=prefix[:-1] - mydata=mdaFile(first,last,filepath=filepath,prefix=prefix,q=q) - value=[] - modeDict={'CW, RCP':'RCP','CCW, LCP':'LCP','H':'H','V':'V'} - grtDict={1200:'MEG',2400:'HEG'} - for mdaNum in mydata.scanList: - if first<=mdaNum<=last: - extraPVs=mydata.header[mdaNum].all - try: - ID=round(extraPVs['ID29:EnergySet.VAL'][2][0]*1000,2) - mode=modeDict[extraPVs['ID29:ActualMode'][2]] # extraPVs return 'CW, RCP' - grt=grtDict[extraPVs['29idmono:GRT_DENSITY'][2][0]] # extraPVs return 1200 - except KeyError: - ID=round(extraPVs[b'ID29:EnergySet.VAL'][2][0]*1000,2) - mode=modeDict[str(extraPVs[b'ID29:ActualMode'][2])[2:-1]] - grt=grtDict[extraPVs[b'29idmono:GRT_DENSITY'][2][0]] # extraPVs return 1200 - if len(value)>0 and value[-1][1:] == [ID,grt,mode]: - pass - else: - value.append([mdaNum,ID,grt,mode]) - return value - - - -def id2num(ID,grt,mode,first=0,last=inf,ignore=[],filepath=None,prefix=None,q=True): # Not efficient - requires to read all 600 files everytime - """ - Return ScanNum corresponding to a given ID_SP from ExtraPVs (using mdaFile) - """ - if filepath == None: - filepath=BL.mda.filepath() - if prefix == None: - prefix=BL.mda.prefix()[:-1] - elif prefix[-1] == "_": - prefix=prefix[:-1] - ScanNum = 0 - data_list = read_id_files(first,last,filepath,prefix,q) - data_short=[x for x in data_list if x[2:]==[grt,mode] and x[0] not in ignore] - step=data_short[1][1]-data_short[0][1] - precision=int(step/2) - ID1=ID-precision - ID2=ID+precision - ScanNum=[x[0] for x in data_short if ID1<= x[1]<= ID2] - if len(ScanNum)==0: result=None - else: result=ScanNum[0] - return result - - - -def num2id(ScanNum,grt,mode,first=0,last=inf,ignore=[],filepath=None,prefix=None,q=True): # Not efficient - requires to read all 600 files everytime - """ - Return ID SP corresponding to a given ScanNum from ExtraPVs (using mdaFile) - """ - if filepath == None: - filepath=BL.mda.filepath() - if prefix == None: - prefix=BL.mda.prefix()[:-1] - elif prefix[-1] == "_": - prefix=prefix[:-1] - ID = 0 - data_short=[] - data_list = read_id_files(first,last,filepath,prefix,q) - data_short=[x for x in data_list if x[2:]==[grt,mode] and x[0] not in ignore] - ID=[x[1] for x in data_short if x[0] == ScanNum] - return ID[0] - - - -def extract_id(first,last,ignore=[],breakpts={'RCP':[600],'H':[400,600],'V':[600],'LCP':[600],'HEG':[],'MEG':[2200,2475]},filepath=None,prefix=None,q=True): - """ - Breaksdown the info from a calibration files into grt & mode with the corresponding breakpoints (hardcoded): - [[first, last, 'HEG', 'RCP', [600]], - [first, last, 'HEG', 'H', [400, 600]]...] - """ - if filepath == None: - filepath=BL.mda.filepath() - if prefix == None: - prefix=BL.mda.prefix()[:-1] - elif prefix[-1] == "_": - prefix=prefix[:-1] - IDlog=read_id_files(first,last,filepath,prefix,q) - #breakpts={'RCP':[600],'H':[400,600],'V':[600],'LCP':[600],'HEG':[],'MEG':[2200]} - #breakpts={'RCP':[600],'H':[400,600],'V':[600],'LCP':[600],'HEG':[],'MEG':[2200]} - #breakpts={'RCP':[600],'H':[600],'V':[600],'LCP':[600],'HEG':[],'MEG':[2200,2475]} # FR changed H breakpoints, missing low energy scans 06/14/2021 - data=[] - for grt in ['HEG','MEG']: - for mode in ['RCP','H','V','LCP']: - tmp=[x for x in IDlog if x[2:]==[grt,mode] and x[0] not in ignore] - #print(tmp) - if len(tmp)>0: - tmp=[tmp[0][0],tmp[-1][0],grt,mode,breakpts[mode]+breakpts[grt]] - data.append(tmp) - return data - - - -def update_id_dict(first,last,det,update_file,ignore,**kwargs): - - - - """ - Calculate new calibration curve for a full set of data.' - But what if the set is not complete? To be addressed by Future Me - If update_file == True (ONLY): - \tupdate the ID dictionary '/home/beams22/29IDUSER/Documents/User_Macros/Macros_29id/IEX_Dictionaries/Dict_IDCal.txt' - """ - - if update_file == True: - foo=input('\nAre you sure you want to update the ID calibration dictionary?\n>') - if foo == 'Y' or foo == 'y' or foo == 'yes'or foo == 'YES' or foo == 'Yes': - foo = 'yes' - print('\nWill save new dictionary to: \'/home/beams22/29IDUSER/Documents/User_Macros/Macros_29id/IEX_Dictionaries/Dict_IDCal.txt\'\n') - else: - print('\nCalibration curves will not be saved.\n') - else: - print('\nCalibration curves will not be saved.\n') - - kwargs.setdefault('countby',1) - kwargs.setdefault('mytitle','') - kwargs.setdefault('plotMin',225) - kwargs.setdefault('plotMax',3000) - kwargs.setdefault('plotType',['fit','dif','flux']) - kwargs.setdefault('filepath',BL.mda.filepath()) - kwargs.setdefault('prefix',BL.mda.prefix()) - kwargs.setdefault('q',True) - kwargs.setdefault('breakpts',{'RCP':[600],'H':[400,600],'V':[600],'LCP':[600],'HEG':[],'MEG':[2200,2475]}) - - - breakpts=kwargs['breakpts'] - plotType=kwargs['plotType'] - filepath=kwargs['filepath'] - prefix=kwargs['prefix'] - q=kwargs['q'] - - ID_data=extract_id(first,last,ignore,breakpts,filepath,prefix,q) - - ##### Extract parameters: - - mode_dict ={'RCP':0,'LCP':1,'V':2,'H':3} - id_coef={} - new_id_function={} - id_flux={} - flux_dict={} - id_energy={} - energy_dict={} - for mylist in ID_data: - if len(mylist) > 0: # in case of incomplete data set - tmp0,tmp1,tmp2=[],[],[] - first_scan=mylist[0] - last_scan=mylist[1] - scan_list=[[first_scan,last_scan]] - countby=1 - #det=15 - #det=33 - poly_order=4 - grt=mylist[2] - mode=mylist[3] - breakpts_energy=mylist[4] - breakpts_scan=[] - mytitle=mode+' - '+grt - - ## generating list of scans depending on breakpoints: - if breakpts_energy != []: - scan_list=[] - for x in breakpts_energy: - breakpts_scan.append(id2num(x,grt,mode,first,last,ignore,filepath,prefix,q)) - breakpts_scan = [i for i in breakpts_scan if i] - print(breakpts_scan) - for c,x in enumerate(breakpts_scan): # can get the number by extracting step size then /2 - if c == 0: - if x == first_scan: pass - else: scan_list.append([first_scan,x]) - if 0 < c < len(breakpts_scan)-1: - scan_list.append([breakpts_scan[c-1],x]) - scan_list.append([x,breakpts_scan[c+1]]) - if c == len(breakpts_scan)-1 and (c-1) == 0: - scan_list.append([breakpts_scan[c-1],x]) - if c == len(breakpts_scan)-1: - scan_list.append([x,last_scan]) - final_list = [i for n, i in enumerate(scan_list) if i not in scan_list[:n]] # remove doubles - energy_list=[] - for x in final_list: - ID1=num2id(x[0],grt,mode,first,last,ignore,filepath,prefix,q) - ID2=num2id(x[1],grt,mode,first,last,ignore,filepath,prefix,q) - energy_list.append([ID1,ID2]) - energy_list_2=energy_list # we need the final value for plot purposes (max value) - if grt == 'HEG': - energy_list_2[-1][-1]=2500 # but we don't want it to be a cutoff for ID_Calc in dict - for (FirstLast,ID,cutoff) in zip(final_list,energy_list,energy_list_2): - plt_min=ID[0]-200 - plt_max=ID[1]+100 - if grt=='MEG' and ID[1]>2900: - poly_order=5 - plt_min=ID[0]-200 - print('det =',det) - print('poly_order =',poly_order) - - subkwargs=kwargs # kwargs contains plotType, filepath, prefix and q - newkwargs={'mytitle':mytitle,'countby':countby,"plotMin":plt_min,'plotMax':plt_max} - subkwargs.update(newkwargs) - #print(newkwargs) - #print(FirstLast[0],FirstLast[1]) - #result,energy_data,flux_data=id_calibration_fit(FirstLast[0],FirstLast[1],det,poly_order,subkwargs) - result,energy_data,flux_data=id_calibration_fit(FirstLast[0],FirstLast[1],det,poly_order,mytitle=mytitle,countby=countby,plotMin=plt_min,plotMax=plt_max,plotType=['fit','dif'],filepath=filepath,prefix=prefix) - tmp0.append([cutoff[1],result.tolist()]) - tmp1.append([cutoff[1],energy_data]) - tmp2.append([cutoff[1],flux_data]) - - if 2900<tmp0[-1][0]<3000: tmp0[-1][0]=3000 - id_coef[mode_dict[mode]]=tmp0 # dictionary that - new_id_function[grt]=id_coef # dictionary containing all the calibration curves forthe data set - id_energy[mode_dict[mode]]=tmp1 # dictionary that - energy_dict[grt]=id_energy - id_flux[mode_dict[mode]]=tmp2 # dictionary that - flux_dict[grt]=id_flux - - ##### Read & update old dictionary: - - try: - id_function=read_dict('Dict_IDCal.txt') - print(id_function) - id_function.update(new_id_function) - - except KeyError: - print("Unable to read previous dictionary") - - - if update_file == True and foo == 'yes': - filepath = "/home/beams22/29IDUSER/Documents/User_Macros/Macros_29id/IEX_Dictionaries/" - filename = 'Dict_IDCal.txt' - - with open(join(filepath, filename), "a+") as f: - f.write('\n======= '+today()+': \n') - f.write(str(id_function)) - f.write('\n') - print('\nWriting dictionary to:',join(filepath, filename)) - - if update_file == True and foo == 'yes': - filepath = "/home/beams22/29IDUSER/Documents/User_Macros/Macros_29id/IEX_Dictionaries/" - filename = 'Flux_Curves.txt' - - with open(join(filepath, filename), "a+") as f: - f.write('\n======= '+today()+': \n') - f.write('\n----- flux_x:\n') - f.write(str(energy_dict)) - f.write('\n----- flux_y:\n') - f.write(str(flux_dict)) - f.write('\n') - print('\nWriting flux curves to:',join(filepath, filename)) - - return id_function,energy_dict,flux_dict - - -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)) - - slits_set_BL() - return slit_position - - - - - - -def read_flux(FileName='Flux_Curves.txt',FilePath="/home/beams22/29IDUSER/Documents/User_Macros/Macros_29id/IEX_Dictionaries/"): - print('test') - with open(join(FilePath, FileName)) as f: - for c,line in enumerate(f.readlines()): - if line[0] == '=': - lastdate=line[8:16] - print(lastdate) - if line[0] == '-' and line[-2] == 'x': - axis='x' - print(axis) - line_x=line - if line[0] == '-' and line[-2] == 'y': - axis='y' - print(axis) - line_y=line - mydict_x=ast.literal_eval(line_x) - mydict_y=ast.literal_eval(line_y) - return mydict_x,mydict_y - - - - - - -############################################################################################### -######################################### Object Oriented ##################################### -############################################################################################### - -class _mdaData(scanDim): - - def __init__(self): - scanDim.__init__(self) - self.poslist = None - self.detlist = None - - - def _getDetIndex(self,d): - """ - d = det Num - """ - D=self.detlist - if D==[]: - print('Data contains no detectors. Try higher dimensions: mydata.dim2[n]') - index=[None] - else: - index=[x for x, y in enumerate(D) if y[1] == 'D'+str(d).zfill(2)] - if index == []: - print('Detector '+str(d)+' not found.') - index=[None] - return index[0] - - - - def plt(self,d): - d=self._getDetIndex(d) - if d== None: - return - x=self.p[0] - y=self.d[d] - if self.dim == 2: - print('This is a 2D scan; use method mydata.img(n,d)') - for i in range(len(y.data)): - plt.plot(x.data[i], y.data[i],label=y.fieldName,marker='+') # crop aborted scans (curr_pt<npts) - else: plt.plot(x.data[:self.curr_pt], y.data[:self.curr_pt],label=y.fieldName,marker='+') # crop aborted scans (curr_pt<npts) - plt.xlabel(x.name) - plt.ylabel(y.name) - plt.legend() - plt.grid(color='lightgray', linestyle='-', linewidth=0.5) - - - - def kappaDet(self,q=None): - if q is not None: - print('\nUse detIndex for plot: mydata.dim1[n].d[detIndex].data\nIf D=mydata.dim1[n].kappaDet => detIndex=D[detNum][1]\n') - print('key = (detIndex, detNum, description, pv)') - det={} - D=self.detlist - for (i,j) in zip([32,33,34,35,31,36,37,38,39,41,42,43,44,45,46,47,48,54,55,56,57],['TEY','D3','D4','MCP','mesh','TEY / mesh','D3 / mesh','D4 / mesh','MCP / mesh','ROI1','ROI2','ROI3','ROI4','ROI5','<H>','<K>','<L>','tth','th','chi','phi']): - d=self._getDetIndex(i) - if d != None: - det[i]=(d,D[d][1],j,D[d][2]) - else: - det[i]=None - return det - - - - - -class _mdaHeader: - def __init__(self): - self.all = None - self.sample = None - self.mono = None - self.ID = None - self.energy = None - self.det = None - self.motor = None - self.mirror = None - self.centroid = None - self.slit=None - self.comment=None - - - - -class mdaFile: - - - '''mydata=mdaFile(first=0,last=None,name=datasetName,filepath=None,prefix=None) - - /net/s29data/export/data_29idb/2020_3/mda/Kappa_0107.mda is a 1-D file; 1 dimensions read in. - - mydata.header[n] = dictionary of 163 scan-environment PVs - - usage: mydata.header[n]['sampleEntry'] -> ('description', 'unit string', 'value', 'EPICS_type', 'count') - - mydata.dim1[n] = 1D data from '29idKappa:scan1' acquired on Oct 20, 2020 19:06:23: - 33/33 pts; 1 positioners, 65 detectors - - usage: mydata.dim1[n].p[2].data -> 1D array of positioner 1 data - - Each scan dimension (i.e., dim1, dim2, ...) has the following fields: - time - date & time at which scan was started: Oct 20, 2020 19:06:23 - name - name of scan record that acquired this dimension: 29idKappa:scan1 - curr_pt - number of data points actually acquired: 33 - npts - number of data points requested: 33 - nd - number of detectors for this scan dimension: 65 - d[] - list of detector-data structures - np - number of positioners for this scan dimension: 1 - p[] - list of positioner-data structures - nt - number of detector triggers for this scan dimension: 1 - t[] - list of trigger-info structures - - Each detector-data structure (e.g., dim[1].d[0]) has the following fields: - desc - description of this detector - data - data list - unit - engineering units associated with this detector - fieldName - scan-record field (e.g., 'D01') - - Each positioner-data structure (e.g., dim[1].p[0]) has the following fields: - desc - description of this positioner - data - data list - step_mode - scan mode (e.g., Linear, Table, On-The-Fly) - unit - engineering units associated with this positioner - fieldName - scan-record field (e.g., 'P1') - name - name of EPICS PV (e.g., 'xxx:m1.VAL') - readback_desc - description of this positioner - readback_unit - engineering units associated with this positioner - readback_name - name of EPICS PV (e.g., 'xxx:m1.VAL') - ''' - - def __init__(self,first=1,last=None,name='mydata',filepath=None,prefix=None,q=False): - if filepath == None: - filepath = BL.mda.filepath() - self.path = filepath - self._name = name - self._first = first - self._last = last - if prefix != None and prefix[-1]=='_': - self._prefix= prefix[:-1] - else: - self._prefix= prefix - - self._allFiles = None - self._allPrefix = None - self.loadedFiles = None - self.scanList = None - self.dim1 = None - self.dim2 = None - self.dim3 = None - self.header = None - - self._extractFiles() - self._extractData(q) - - - #def __str__(self): - - - - def _extractFiles(self): - allFiles = [f for f in listdir(self.path) if isfile(join(self.path, f))] - loadedFiles= [x for (i,x) in enumerate(allFiles) if allFiles[i].split('.')[-1]=='mda'] - allPrefix = [loadedFiles[i][:loadedFiles[i].find('_')] for (i,x) in enumerate(loadedFiles)] - scanList = [int(loadedFiles[i][loadedFiles[i].find('_')+1:loadedFiles[i].find('_')+5]) for (i,x) in enumerate(loadedFiles)] - if self._prefix != None: - allPrefix=[s for s in allPrefix if s == self._prefix] - scanList = [int(loadedFiles[i][loadedFiles[i].find('_')+1:loadedFiles[i].find('_')+5]) for (i,x) in enumerate(loadedFiles) if loadedFiles[i][:loadedFiles[i].find('_')] == self._prefix] - loadedFiles = [s for s in loadedFiles if s[:s.find('_')] == self._prefix] - else: - self._prefix=allPrefix[-1] - if allPrefix[0]!=allPrefix[-1]: - print('\nWARNING: Found more than one file prefix: {}, {}.\n\nData with the same scan number will be overwriten in the order they are loaded. \nPlease specify the one you want to load with arg prefix="which".\n\n'.format(allPrefix[0],allPrefix[-1])) - if self._last == None: - self._last = self._first - shortlist = [i for (i,x) in enumerate(scanList) if self._first<=x<=self._last] - self._allFiles = allFiles - self.loadedFiles = [loadedFiles[i] for i in shortlist] - self.scanList = [scanList[i] for i in shortlist] - self._allPrefix=[allPrefix[i] for i in shortlist] - - - def _extractData(self,q): - - allheader = {} - alldata1 = {} - alldata2 = {} - alldata3 = {} - - for (i,mda) in enumerate(self.loadedFiles): - - ##### File info: - - filename=mda - filepath=self.path - #print(filepath) - num=self.scanList[i] - #print(num) - fullpath=join(filepath,filename) - #print(fullpath) - data=readMDA(fullpath,useNumpy=True) # data = scanDim object of mda module - - ###### Extract header: - - D0 = _mdaHeader() # initiate D0 = mdaHeader object - D1 = _mdaData() - D2 = _mdaData() - D3 = _mdaData() - - D=[] - - for d in range(0,4): - if d in range(0,len(data)): D.append(data[d]) - else: D.append(None) - - # D[0]=data[0] - # D[1]=data[1] - # D[2]=None if 1D data, data[2] if 2D data - # D[3]=None if 2D data, data[3] if 3D data - - - D0.all=D[0] - - - if filename[:5] == 'Kappa': - try: - D0.sample={**{key:value[:3] for key, value in D[0].items() if '29idKappa:m' in key},**{key:value[:3] for key, value in D[0].items() if '29idKappa:Euler' in key},**{key:value[:3] for key, value in D[0].items() if 'LS331' in key}} - D0.mirror = {key:value[:3] for key, value in D[0].items() if '29id_m3r' in key} - D0.centroid={key:value[:3] for key, value in D[0].items() if 'ps6' in key.lower()} - D0.det = {key:value[:3] for key, value in D[0].items() if '29idd:A' in key} - detkeys=['29idMZ0:scaler1.TP','29idKappa:m9.RBV','29idKappa:userCalcOut10.OVAL','29iddMPA:C0O','29idKappa:userStringSeq6.STR1','29idd:Unidig1Bo0'] - for k in detkeys: - if k in D[0]: D0.det[k]=D[0][k][:3] - D0.ID={key:value[:3] for key, value in D[0].items() if 'ID29' in key} - D0.UB={key:value[:3] for key, value in D[0].items() if 'UB' in key} - D0.mono={key:value[:3] for key, value in D[0].items() if 'mono' in key} - D0.energy={key:value[:3] for key, value in D[0].items() if 'energy' in key.lower()} - D0.motor = {key:value[:3] for key, value in D[0].items() if '29idb:m' in key} - D0.slit={key:value[:3] for key, value in D[0].items() if 'slit3d' in key.lower()} - except: - pass - if filename[:5] == 'ARPES': - try: - #D0.sample={**{key:value[:3] for key, value in D[0].items() if '29idKappa:m' in key},**{key:value[:3] for key, value in D[0].items() if '29idKappa:Euler' in key},**{key:value[:3] for key, value in D[0].items() if 'LS331' in key}} - #D0.mirror = {key:value[:3] for key, value in D[0].items() if '29id_m3r' in key} - #D0.centroid={key:value[:3] for key, value in D[0].items() if 'ps6' in key.lower()} - #D0.det = {key:value[:3] for key, value in D[0].items() if '29idd:A' in key} - #detkeys=['29idMZ0:scaler1.TP','29idKappa:m9.RBV','29idKappa:userCalcOut10.OVAL','29iddMPA:C0O','29idKappa:userStringSeq6.STR1','29idd:Unidig1Bo0'] - #for k in detkeys: - # if k in D[0]: D0.det[k]=D[0][k][:3] - D0.ID={key:value[:3] for key, value in D[0].items() if 'ID29' in key} - #D0.UB={key:value[:3] for key, value in D[0].items() if 'UB' in key} - D0.mono={key:value[:3] for key, value in D[0].items() if 'mono' in key} - D0.energy={key:value[:3] for key, value in D[0].items() if 'energy' in key.lower()} - D0.motor = {key:value[:3] for key, value in D[0].items() if '29idb:m' in key} - D0.slit={key:value[:3] for key, value in D[0].items() if 'slit3c' in key.lower()} - except: - pass - - try: - cmt1=D[0]['29id'+self._prefix+':saveData_comment1'][2] - cmt2=D[0]['29id'+self._prefix+':saveData_comment2'][2] - if cmt2 != '': D0.comment = cmt1+' - '+cmt2 - else: D0.comment = cmt1 - except: - D0.comment = '' - - - ###### Extract data: - - DIMS=[D1,D2,D3] - - for counter, value in enumerate(DIMS): - c=counter+1 - if D[c] is not None: - value.rank=D[c].rank - value.dim=D[c].dim - value.npts=D[c].npts - value.curr_pt=D[c].curr_pt - value.plower_scans=D[c].plower_scans - value.name=D[c].name # - value.time=D[c].time - value.np=D[c].np - value.p=D[c].p - value.nd=D[c].nd - value.d=D[c].d - value.nt=D[c].nt - value.t=D[c].t - value.detlist=[(i,D[c].d[i].fieldName,D[c].d[i].name,D[c].d[i].desc) for i in range(0,D[c].nd)] - value.poslist=[(i,D[c].p[i].fieldName,D[c].p[i].name,D[c].p[i].desc) for i in range(0,D[c].np)] - else: - value=None - - allheader[num] = D0 - alldata1[num] = D1 - alldata2[num] = D2 - alldata3[num] = D3 - - d=D.index(None)-1 - if q is False: - print('Loading {} as {}.dim{}[{}]:\n\t\t...{}D data, {}/{} pts; {} positioners, {} detectors'.format( - filename,self._name,d,self.scanList[i],D[d].dim,D[d].curr_pt, D[d].npts, D[d].np, D[d].nd)) - - self.header=allheader - self.dim1=alldata1 - self.dim2=alldata2 - self.dim3=alldata3 - - - - - - def updateFiles(self,first=0,last=inf,name=None,filepath=None,prefix=None): - new=mdaFile(first,last,name,filepath,prefix) - self.loadedFiles=list(dict.fromkeys(self.loadedFiles+new.loadedFiles)) - self._allFiles=list(dict.fromkeys(self._allFiles+new._allFiles)) # merging the 2 list and removing duplicates - self.scanList=list(dict.fromkeys(self.scanList+new.scanList)) - self._allPrefix=list(dict.fromkeys(self._allPrefix+new._allPrefix)) - self.dim1.update(new.dim1) - self.dim2.update(new.dim2) - self.dim3.update(new.dim3) - self.header.update(new.header) - return self - - - - def plt(self,*argv): - if self.dim2[argv[0]].dim == 0: #1D scan - for index,arg in enumerate(argv): - if index %2 !=0: - pass - else: - n=arg - d=argv[index+1] - d=self.dim1[n]._getDetIndex(d) - x=self.dim1[n].p[0] - y=self.dim1[n].d[d] - plt.plot(x.data[:self.dim1[n].curr_pt], y.data[:self.dim1[n].curr_pt],label='mda #'+str(n)+' - '+y.fieldName,marker='+') - plt.xlabel(x.name) - plt.ylabel(y.name+' - ('+y.fieldName+')') - plt.legend() - plt.grid(color='lightgray', linestyle='-', linewidth=0.5) - plt.show() - elif self.dim2[argv[0]].dim == 2: # 2D scan - for index,arg in enumerate(argv): - if index %2 !=0: - pass - else: - n=arg - d=argv[index+1] - d=self.dim2[n]._getDetIndex(d) - if d == None: - return - x=self.dim2[n].p[0] - y=self.dim1[n].p[0] - z=self.dim2[n].d[d] - zlim=self.dim2[n].curr_pt - fig, ax0 = plt.subplots() - img = ax0.imshow(z.data[:zlim],cmap='gnuplot', interpolation = 'nearest', extent = [min(x.data[0]), max(x.data[0]), min(y.data),max(y.data)], aspect = 'auto') - fig.colorbar(img) - plt.title(z.name+' - ('+z.fieldName+')') - ax0.set_xlabel(x.name) - ax0.set_ylabel(y.name) - plt.show() - - - - - - - diff --git a/build/lib/iexcode/macros/commissioning.py b/build/lib/iexcode/macros/commissioning.py index 60f7b983b224def32c6e68d20b36751d0ee18ed6..5400079031c1089d51d62c1de2825190c97ff783 100644 --- a/build/lib/iexcode/macros/commissioning.py +++ b/build/lib/iexcode/macros/commissioning.py @@ -1,94 +1,32 @@ -""" -Functions for commissioning, alignment and start of the week - -""" from os.path import join, isfile, exists, dirname from time import sleep from epics import caget, caput +import iexcode.instruments.cfg as iex -from ..instruments.files_and_folders import check_run, folder_mda -from ..instruments.scanRecord import scanRecord_run,scanRecord_filepath -from ..instruments.xrays import energy -from ..instruments.m3r import M3R_branch - -from ..instruments.IEX_VPU import ID_switch_mode -from ..instruments.diagnostics import diagnostics_all_out, diagnostics_all_in,diodeC,diodeD -from ..instruments.current_amplifiers import current2flux -from ..instruments.slits import set_exit_slit -from ..instruments.Logfile import * -from ..instruments.cameras import * - -from ..instruments.ARPES import * -from ..instruments.electron_analyzer import * -from ..instruments.Kappa import * +from iexcode.instruments.ARPES import ARPES_init +from iexcode.instruments.kappa import kappa_init +from iexcode.instruments.xrays import * +from iexcode.instruments.xrays import _energy_range_min_max +from iexcode.instruments.current_amplifiers import current2flux +from iexcode.instruments.diagnostics import _diagnostics_dict, diagnostics_all_out, diagnostics_all_in,diode_c,diode_d +from iexcode.instruments.m3r import * +from iexcode.instruments.slits import * +from iexcode.instruments.utilities import * +from iexcode.instruments.electron_analyzer import scanEA +from iexcode.instruments.Logfile import log_name_set,log_print +from iexcode.instruments.cameras import * -from .ScanFunctions_plot import fit_mda, mda_1D - -############################################################################################################## -################################ setting the mda folder ############################## -############################################################################################################## - -def staff_init(endstation_name=None,set_folders=True,reset=True): - """ - endstation_name : sets the scan record and BL - set_folders: sets the mda and EA folders; default => False - reset: resets the scanRecord (detectors,triggers...) - **kwargs: - xrays: sets global variable; default => True - BL_mode: 'user' / 'staff' => used for saving, detectors - Previously: folders_staff - """ - if endstation_name is None: - endstation_name = BL.endstation - - if endstation_name == 'ARPES': - ARPES_init(set_folders,reset,BL_mode='staff') - if endstation_name == 'Kappa': - Kappa_init(set_folders,reset,BL_mode='staff') -def check_staff_directory(BL, **kwargs): - """ - Switchs to the staff directory - **kwargs for folder_ARPES +from .quick_plot import fit_mda, mda_1D - Previously: Check_Staff_Directory - """ - - ioc = BL.ioc() - run = check_run() - - directory = scanRecord_filepath(ioc) - current_run = scanRecord_run(ioc) - - if directory.find('data_29idb') < 1 or current_run != run: - print('You are not currently saving in the Staff directory and/or the desired run.') - # foo=input('\nAre you ready to switch to the '+run+' Staff directory (y or n)? >') - # if foo.lower() == 'y' or foo.lower() == 'yes': - if not (exists(directory)): - print('Staff directory does not exist for this run.') - print('Open ipython as 29id to create a new run directory using:\n\tFolder_'+ioc+'(run,"Staff")') - foo=input('\nPress enter when done >') - if foo == '': pass - print('Switching directory...') - if ioc=='ARPES': - folders_ARPES('Staff',mdaOnly=True,**kwargs) - elif ioc=='Kappa': - folders_Kappa('Staff',create_only=False) - else: - print('\nFolder not set.') - else: - print('Staff directory OK.') - directory = scanRecord_filepath(ioc) - print('\nCurrent directory: '+directory) - ############################################################################################################## @@ -109,16 +47,16 @@ def check_flux(hv=500,ID_mode='RCP',stay=False): SR=round(caget("S:SRcurrentAI.VAL"),2) if m3r_branch() == "c": current_slit=caget('29idb:Slit3CFit.A') - diodeC('In') - set_exit_slit(50) + diode_c('In') + exit_slit(50) sleep(10) - diode=diodeC_read() + diode=diode_c_read() elif m3r_branch() == "d": current_slit=caget('29idb:Slit4Vsize.VAL') sleep(10) - diodeD("In") - set_exit_slit(50) - diode=caget('29idb:ca14:read') + diode_d("In") + exit_slit(50) + diode=diode_d_read() flux=current2flux(diode) print("\n----- Current on diode : %.3e" % diode, "A") print("----- Corresponding flux: %.3e" % flux, "ph/s \n") @@ -127,7 +65,7 @@ def check_flux(hv=500,ID_mode='RCP',stay=False): if not stay: diagnostics_all_out() - set_exit_slit(current_slit) + exit_slit(current_slit) def check_m0m1(hv=500,stay=True,wire=True,**kwargs): """ @@ -140,7 +78,7 @@ def check_m0m1(hv=500,stay=True,wire=True,**kwargs): """ switch_branch('c') - switch_gratings('HEG') + grating('HEG') print("\nFlux at hv=500 as off Feb 2019: ~3.3e-06 A = ~1.5e+11 ph/s") branch_shutter_open() check_flux(hv=hv,stay=stay) @@ -171,13 +109,13 @@ def scan_wire(direction,all_diag=True,**kwargs): elif direction == 'V': name = "V-wire" - diag = diagnostics_dict() + diag = _diagnostics_dict() pv = "29idb:m"+str(diag["motor"][name]) print("\n================== "+name+" scan (29idb:ca2):") - BL.mda.fillin(pv+".VAL",pv+".RBV",1,-17,-30,-0.25,**kwargs) + iex.BL.mda.fillin(pv+".VAL",pv+".RBV",1,-17,-30,-0.25,**kwargs) if kwargs['execute']: - BL.mda.go(**kwargs) + iex.BL.mda.go(**kwargs) if all_diag: diagnostics_all_out() @@ -228,7 +166,7 @@ def scan_narrow_slit(slit='2V',slit_parameters=[0.25,-2,2,0.5],**kwargs): slits_scan_center(slit_name,direction,start,stop,step,**kwargs) if kwargs['execute']: - BL.mda.go(kwargs['scan_dim']) + 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): @@ -253,13 +191,13 @@ def scan_mono_vs_slit(slit='2V',slit_parameters=[0.25,-2,2,0.5],energy_parameter # Resetting everybody to normal: mono_energy_set((hv_start+hv_stop)/2.0) - slits_set_BL() + apertures_set() ############################################################################################################## ################################ mono alignment ############################## ############################################################################################################## -def mono_MIR_GRT_find_offset(grating,slit_list,**kwargs): +def mono_MIR_GRT_find_offset(grt,slit_list,**kwargs): """ Find MIR-GRT offset by scanning 0 order through exit slit **kwargs: @@ -269,9 +207,9 @@ def mono_MIR_GRT_find_offset(grating,slit_list,**kwargs): """ kwargs.setdefault("detNum",15) - switch_gratings(grating) + grating(grt) exit_slit(50) - diodeC('In') + diode_c('In') slit2B_set(2,0.5,0,0) #set zero order, scan grating pitch @@ -284,11 +222,11 @@ def mono_MIR_GRT_find_offset(grating,slit_list,**kwargs): print("\r") mono_motor_scan_fillin("GRT:P",ang-0.0005*s, ang+0.0005*s ,0.00002*s) - BL.mda.go(**kwargs) + iex.BL.mda.go(**kwargs) sleep(1) print("\r") - grating_ang = fit_mda(mda.fileNum(),kwargs['detNum'],.1,'gauss') + grating_ang = fit_mda(iex.BL.mda.fileNum(),kwargs['detNum'],.1,'gauss') print("Peak: ",grating_ang) print("\r") print("-------------------------") @@ -346,7 +284,7 @@ def scan_energy_along_grating(hv,peakBE=84,pts=11,r=0.75,i=1,**kwargs): scanEA(EAlist,**kwargs) #reset the slits - slits_set_BL() + apertures_set() @@ -427,9 +365,9 @@ def scan_pinhole(H_list,V_list,**kwargs): +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])) - BL.mda.go(max(kwargs['H_scan_dim'],kwargs['V_scan_dim'])) + iex.BL.mda.go(max(kwargs['H_scan_dim'],kwargs['V_scan_dim'])) print("\rNow setting the slits back to:") - slits_set_BL() + apertures_set() print("\r") print_warning_message("Don't forget to pull all of the diagnostics out.") @@ -439,9 +377,9 @@ def scan_pinhole(H_list,V_list,**kwargs): ############################################################################################################## ################## Slit Calibration & Beam Steering scripts ################## ############################################################################################################## +FMB_mirror_move - -def Notes_from_20191212(): +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 @@ -450,27 +388,27 @@ def Notes_from_20191212(): => 5 urad down = 1 mm negative motion on 2B-V with HEG""") -def procedure_alignment_M1(): +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_NarrowSlit('2V',[0.25,-8,8,0.5]) - Scan_NarrowSlit('2H',[0.25,-4,4,0.5]) + 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): - Get_Mirror(1) # to get current values - for roll in RangeUp(3,4,0.2): - print('\\n') - Move_M1('RZ',roll) + 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 in RangeUp(8.5,8.7,0.05): - print('\\nMove_M1('RY',pitch)') - Move_M1('RY',pitch) + 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. @@ -489,15 +427,17 @@ 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(vroll)+' urad' - return v_steering - -def beamsteering_1A(h_position,v_position): - hrad=round(h_position*10/0.25,0) - vrad=round(v_position*10/0.25,0) - if h_position<0: h_direction=' urad outboard' + v_steering=v_direction+str(abs(vroll))+' urad' + return v_steering,float(v_steering.split(" ")[1]) + +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_position<0: v_direction=' urad up' + 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 @@ -536,9 +476,9 @@ def check_slit1A(step=0.1): m=9 VAL='29idb:m'+str(m)+'.VAL' RBV='29idb:m'+str(m)+'.RBV' - BL.mda.fillin(VAL,RBV,-4,4.0,step) - BL.mda.go() - FileNum1 = BL.mda.lastFileNum() + iex.BL.mda.fillin(VAL,RBV,-4,4.0,step) + iex.BL.mda.go() + FileNum1 = iex.BL.mda.lastFileNum() #scanning inboard-blade slit1A_set(8,8,0,0) # aperture wide open @@ -546,9 +486,9 @@ def check_slit1A(step=0.1): m=10 VAL='29idb:m'+str(m)+'.VAL' RBV='29idb:m'+str(m)+'.RBV' - BL.mda.fillin(VAL,RBV,-4,4.0,step) - BL.mda.go() - FileNum2 = BL.mda.lastFileNum() + iex.BL.mda.fillin(VAL,RBV,-4,4.0,step) + iex.BL.mda.go() + FileNum2 = iex.BL.mda.lastFileNum() return FileNum1, FileNum2 @@ -625,7 +565,7 @@ def ID_beam_profile(grt,slit_list,c_slit=1,c_energy=1,**kwargs): Previously """ - switch_gratings(grt) + grating(grt) grt_density = mono_grating_density_get() c=grt_density/1200 ID=500 @@ -656,9 +596,9 @@ def CheckAllSlits_long(hv_list=[500],slit_list=["1H","1V","2H","2V"],**kwargs): For both gratings """ for grt in ["HEG","MEG"]: # One full loop for a given grating and 3 energies takes 5h for average 20 - switch_gratings(grt) + grating(grt) for hv in hv_list: - slits_set_BL(hv) + apertures_set(hv) step=hv/100.0 start=hv-step stop=hv+step @@ -681,7 +621,7 @@ def CheckSlitCalibration(slit_list,BL=500,hvList=[485,510],scanIOC=None,**kwargs if scanIOC is None: scanIOC=BL_ioc() exit_slit(50) - slits_set_BL(BL) + apertures_set(BL) for hv in hvList: mono_energy_set(hv) for slit in slit_list: @@ -715,7 +655,7 @@ def check_ID_beam_steering(slit): #here size,start,stop,step = 0.25*c,-4*c,4*c,0.2*c scan_slit_center(slit,start,stop,step,size=size) - slits_set_BL() + apertures_set() ############################################################################################################## @@ -752,109 +692,15 @@ def QP_curves(ID_energy,ID_mode_list,hv_start,hv_stop,hv_step): for ID_mode in ID_mode_list: polarization(ID_mode) ID_SP_set(ID_energy) - slits_set_BL()() + apertures_set()() mono_energy_set(250) mono_scan_fillin(hv_start,hv_stop,hv_step) - BL.mda.go() + iex.BL.mda.go() #Switch_IDQP("off") #Switch_Grating("HEG") #Switch_IDMode("RCP") -############################################################################################################## -################################ ID calibration scripts ############################## -############################################################################################################## - -###### Energy range follows ID ######## - -def ID_calibration_scan(ID_start,ID_stop,ID_step,bandwidth=10,QP=None,Harm=1,scanIOC=None): - """ - Sets the ID_SP and scans the mono: - start,stop,step are for ID - if QP is not None adjusts the mono range to offset accordingly - !!! DOES NOT CHANGE QP VALUE !!!! - !!! Doesn't put diodes in !!! - """ - - print(""" - !!! DOES NOT CHANGE QP VALUE !!!! - !!! Doesn't put diodes in !!!""") - - logfile_name_set(BL.endstation,filename_suffix='IDCalibration') - - #Getting mono max range based on grating - grt_density = mono_grating_density_get() - c=grt_density/1200 # c = 1 for MEG, 2 for HEG - if c == 1: - maxhv = 3000 - elif c == 2: - maxhv = 2000 - - log_print(comment="====== Starting Mono Scan vs ID ======") - - for ID_energy in range_up(ID_start,ID_stop,ID_step): - print("\n------------------ ID-SP @ "+str(ID_energy)+" ------------------") - mono_energy_set(ID_energy) - ID_SP_set(ID_energy) - slits_set_BL() - branch = m3r_branch() - if branch == 'd': - m3r_align() - if QP is None: - start_hv=min(ID_energy-ID_energy/(bandwidth*1.0)*Harm,maxhv) # FR update range 11/20/2019 - stop_hv=min(ID_energy+ID_energy/(bandwidth*2.0)*Harm,maxhv) - step_hv=round(ID_energy/300.0,1) -# start_hv=min(ID_energy-ID_energy/(bandwidth*2.0)*Harm,maxhv) # shift the window by doing -BW*2/+BW*1 instead of -BW*1'/'+BW*2 -# stop_hv=min(ID_energy+ID_energy/(bandwidth*1.0)*Harm,maxhv) -# step_hv=round(ID_energy/500.0,1) - else: - start_hv=min(ID_energy-ID_energy/(bandwidth*2.5)*Harm,maxhv) - stop_hv=min(ID_energy+ID_energy/(bandwidth*0.7)*Harm,maxhv) - step_hv=round(ID_energy/300.0,1) - - mono_scan_fillin(start_hv,stop_hv,step_hv) - BL.mda.go() - sleep(1) - - FileNum = BL.mda.lastFileNum - if ID_energy == ID_start: - FirstFileNum = FileNum # Record First Scan Number - - LastFileNum = FileNum # Record Last Scan Number - - print("Use: update_id_dict("+str(FirstFileNum)+","+str(LastFileNum)+"ignore=[] ,update_file,path=None,prefix='ARPES',q=True)") - - - - -def ID_calibration_mode(ID_mode,start=None,stop=None,step=25,Harm=1): - ''' - Runs full calibration with a 25 eV step (by default) for a given mode: - which = 'RCP','LCP', 'V','H' - Better to run each mode in a separated cell (print statement at the end helps with calibration) - ''' - branch = m3r_branch() - diagnostics_all_out(diode_stay_in=True) - - polarization(ID_mode) - - grt = mono_grating_get() - - QP_ratio = ID_QP_ratio_get() - - hv_min,hv_max = energy_range_min_max() - if start == None: - start = hv_min - if stop == None: - stop=hv_max-50 - - if QP_ratio <100: - stop=min(stop,1500) - QP_ratio=1 - else: - QP_ratio=None - - ID_calibration_scan(start,stop,step,QP=QP_ratio,Harm=Harm) ############################################################################################################## @@ -869,11 +715,7 @@ def scan_cam_motor(motor_name,start,stop,step,cam_num,ExposureTime): """ cam_scan_setup(cam_num,ADtype='TIFF') - if BL.branch == 'ARPES': - ARPES_Motors.scan(motor_name,start,stop,step) - if BL.branch == 'Kappa': - Kappa_Motors.scan(motor_name,start,stop,step) - + iex.BL.motors.scan(motor_name,start,stop,step) cam_live() @@ -886,7 +728,7 @@ def scan_cam_hv(start,stop,step,cam_num,**kwargs): Previously: BeamMotion_Vs_BL_Go """ cam_scan_setup(cam_num,ADtype='TIFF') - scanhv(start,stop,step,**kwargs) + scanmono(start,stop,step,**kwargs) cam_live() diff --git a/build/lib/iexcode/macros/start_of_the_week.py b/build/lib/iexcode/macros/start_of_the_week.py index d2be15d2e4f2f32d8e55f8c0bc9c3094f60abee5..ec9555c03621a7efc94162f1303632567070602e 100644 --- a/build/lib/iexcode/macros/start_of_the_week.py +++ b/build/lib/iexcode/macros/start_of_the_week.py @@ -1,29 +1,28 @@ +import datetime import matplotlib.pyplot as plt -from ..instruments.diagnostics import diodeC -from ..instruments.files_and_folders import check_run -from ..instruments.utilities import wait_for_it -from ..instruments.current_amplifiers import Keithley -from ..instruments.IEX_VPU import * -from ..instruments.VLS_PGM import * -from ..instruments.xrays import * -from ..instruments.shutters import * -from ..instruments.slits import * +import iexcode.instruments.cfg as iex +from iexcode.instruments.staff import staff_init -from ..instruments.Kappa import * -from ..instruments.ARPES import * +from iexcode.instruments.diagnostics import _diagnostics_dict, diagnostics_all_out, diagnostics_all_in,diode_c,diode_d +from iexcode.instruments.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 * -from .commissioning import * -from .ScanFunctions_plot import * - -def start_of_the_week(grt,branch,wait=False,**kwargs): +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 defaults: - run = None: used today's date to set run appropriatetly + mode = polarization + run = None: used today's date to set run appropriately repeat = False: sets everything: switches branch, sets BL_Mode to Staff, resets scan/CAs/mono scanType = ['slit1','wire','flux','monoVslit'] sound = False; no sounds @@ -36,61 +35,61 @@ def start_of_the_week(grt,branch,wait=False,**kwargs): 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 - - Previously: StartOfTheWeek """ + kwargs.setdefault('mode','RCP') kwargs.setdefault('repeat',False) - kwargs.setdefault('run',check_run()) kwargs.setdefault('quick',True) - kwargs.setdefault('interactive',True) kwargs.setdefault('scanType',['slit1','wire','flux','monoVslit']) kwargs.setdefault('sound',True) kwargs.setdefault('extended_range',False) - + + branch=branch.lower() + if iex.BL == None or kwargs['repeat']==False: + if branch == 'c': + staff_init('ARPES') + switch_branch(branch) + else: + staff_init('kappa') + switch_branch(branch) + FileName='StartOfTheWeek_log.txt' + log_name_set(FileName) + 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': - diode = Keithley('b',15) - diode.autoscale() + ca15 = Keithley('b',15) + ca15.autoscale('Off') diode_c('In') else: foo=input('Do you have a diode in direct beam (y or n)? >') if foo.lower() == 'y' or foo.lower() == 'yes': print('Resuming...') - - ### checking QP ratio: - QP_ratio = ID_QP_ratio_get()[] - if QP_ratio != 100: - foo=input('QP on!!! Continue (y or n)? >') - if foo.lower() == 'y' or foo.lower() == 'yes': - print('Resuming...') - ### Stuff that doesn't need beam & does not need to be run if repeating SoTW: print("\n\n================== Sets Beamline & Scans:") - switch_gratings(grt) - - if not kwargs['repeat']: - switch_branch(branch) + grating(GRT) - print("\n\n================== Sets Directory:") - - if branch=='c': - ARPES_init(BL_mode='staff') - - fname='StartOfTheWeek_log.txt' - logfile_name_set(BL.endstation,filename=fname) - - ### checking branch shutter: - if branch_shutter_status() == False: - branch_shutter_open() + 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: @@ -101,159 +100,281 @@ def start_of_the_week(grt,branch,wait=False,**kwargs): wait_for_it(1,8,5) ### checking ID: - print("\n\n================== Start ID:") - polarization('RCP') - - + polarization(kwargs['mode']) + ### Ready to start: - FirstScan=BL.mda.fileNum+1 - + FirstScan=iex.BL.mda.filenum() if not kwargs['repeat']: - log_print("\n\n================== Start Of The Week @ "+today('slash')+':\n') + log_print("\n\n================== Start Of The Week @ "+today('slash')+':\n',FileName=FileName) - def interactive_fct(comment='scans'): - foo=input('\nRepeat '+comment+' (y or n)? >') - if foo.lower() == 'y' or foo.lower() == 'yes': - print('\nRepeating...\n');flag=True - - else: - print('\nResuming...\n'); flag=False + + 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+') >') + 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+') >') + 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 + + + + # if foo.lower() == 'y' or foo.lower() == 'yes': + # print('\nType any comments here - you have 30s! >') + # i, o, e = select.select( [sys.stdin], [], [], 5 ) + # if (i): + # print ('\n==============\n'+sys.stdin.readline().strip()+'\n==============\n') + # else: + # print('\nTimeout...'); + # print('\nRepeating scan...\n');flag=2 + + # else: + # print('\nResuming script...\n'); flag=3 + # return flag + + + + def iex_steering(h_position,v_position): + 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 DetDict={'c':(9,7,8,15),'d':(9,7,8,14)} detCA4,detH,detV,detDiode=DetDict[branch] + list_position=[GRT,0,0,0,0] ###### Scan front-end slit center: if 'slit1' in kwargs['scanType']: print("\n\n================== Slit 1A scans:") - ID_SP_set(2000) - flag=True - while flag: - - #Scan_SlitCenter('1H',-3,3,0.1,comment='Slit center - 1H') - #Scan_SlitCenter('1V',-3,3,0.1,comment='Slit center - 1V') - scan_narrow_slit('1H',[0.25,-3,3,0.1],comment='Slit center - 1H') - scan_narrow_slit('1V',[0.25,-3,3,0.1],comment='Slit center - 1V') - #SetSlit1A(4.5,4.5,0,0) - slit1A_set((4.5,4.5),(0,0)) - m=BL.mda.lastFileNum() + mvID(2000) + flag=2 + while flag==2: + slits_scan_center('slit1A','H',-3,3,0.1,size=(0.25,inf),comment='Slit center - 1H') + slits_scan_center('slit1A','V',-3,3,0.1,size=(inf,0.25),comment='Slit center - 1V') + slit1A_set(4.5,4.5,0,0) + m=iex.BL.mda.last_mda() print('\nsteering out => move beam more positive (10 urad ~ 0.25 mm)') - print('steering up => move beam more positive (10 urad ~ 0.25 mm)') + print('steering up => move beam more positive (10 urad ~ 0.25 mm)\n') try: h_position=fit_mda(m-1,detCA4,1,'gauss',xrange=[-1,1]);plt.show() v_position=fit_mda(m ,detCA4,1,'gauss',xrange=[-1,1]);plt.show() - 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') + iex_steering(h_position,v_position) except: - print('Unable to fit position; try to tweak xrange or FWHM:') - print('fit_mda('+str(m)+','+str(detCA4)+',1,"gauss",xrange=[-1,1])') - print('fit_mda('+str(m+1)+','+str(detCA4)+',1,"gauss",xrange=[-1,1])') - print('\n') + print('\nUnable to fit position; try to adjust xrange.\n') + # print('h_position=fit_mda('+str(m-1)+','+str(detCA4)+',1,"gauss",xrange=[-1,1])') + # print('v_position=fit_mda('+str(m)+','+str(detCA4)+',1,"gauss",xrange=[-1,1])') + # print('\nThen use:') + # print('\tbeamsteering_1A(h_position,v_position)') if kwargs['sound']:playsound() - if kwargs['interactive']: flag=interactive_fct() - else: break + flag=interactive_fct() + while flag == 3: + try: + fitH=input('do you want to fit mda #'+str(m-1)+' ie horizontal (y or n)? >') + if fitH.lower() == 'y' or fitH.lower() == 'yes': + x1=input('x1 >') + x2=input('x2 >') + h_position=fit_mda(m-1,detCA4,1,'gauss',xrange=[float(x1),float(x2)]);plt.show() + fitV=input('do you want to fit mda #'+str(m)+' ie vertical (y or n)? >') + if fitV.lower() == 'y' or fitV.lower() == 'yes': + x1=input('x1 >') + x2=input('x2 >') + v_position=fit_mda(m ,detCA4,1,'gauss',xrange=[float(x1),float(x2)]);plt.show() + 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() ###### Wire scans: if 'wire' in kwargs['scanType']: - ID_SP_set(2000) + mvID(2000) slit1A_set(4.5,4.5,0,0) 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) - m=BL.mda.lastFileNum() + m=iex.BL.mda.last_mda() try: plot_mda(m-1,detH,m,detV,title='wire-H (blue) & wire-V (orange)');plt.show() except: - print('Unable to plot.') + print('Unable to plot. Try:') + print("plot_mda("+str(m-1)+","+str(detH)+","+str(m)+","+str(detV)+",title='wire-H (blue) & wire-V (orange)');plt.show()") if kwargs['sound']:playsound() - + ###### Mono/slit scans: - list_position=[] - if 'monoVslit' in kwargs['scanType']: - if grt=="HEG": + if 'monoVslit' in kwargs['scanType']: + c=mono_grating_density_get()/1200 + if c==2: slit(300) - c=2 - else: + else: slit(200) - c=1 print("\n\n================== Mono/slit scans:") if 'quick' in kwargs: energy(500) - mono_energy_set(505) + mvmono(505) print('\n---------- Scanning slit 2B:\n') - flag=True - while flag: - scan_narrow_slit('2V',[0.25*c, -8, 8, 0.25]) - sleep(1) - scan_narrow_slit('2H',[0.25, -6, 6, 0.25]) - sleep(1) - m=BL.mda.lastFileNum() + flag=2 + while flag==2: + slits_scan_center('slit2B','V',-8,8,0.25,size=(inf,0.25*c));sleep(1) + slits_scan_center('slit2B','H',-6,6,0.25,size=(0.25,inf));sleep(1) + m=iex.BL.mda.last_mda() try: - V2=fit_mda(m-1,detDiode,1*c,'gauss') - plt.show() - H2=fit_mda(m ,detDiode,1,'gauss') - plt.show() - list_position.append(V2) - list_position.append(H2) + V2=fit_mda(m-1,detDiode,1*c,'gauss');plt.show() + H2=fit_mda(m ,detDiode,1,'gauss');plt.show() + list_position[1]=V2 + list_position[2]=H2 #print(f"V2 = {round(V2,3)}") #print(f"H2 = {round(H2,3)}") print('\nBeam position:') - print(f" - vertical: V1 = {round(V2,3)}") - print(f" - horizontal: H1 = {round(H2,3)}") + print(f" - vertical: V2 = {round(V2,3)}") + print(f" - horizontal: H2 = {round(H2,3)}") v_steering=beamsteering_2B(V2) - print('\nM1 roll (RZ) steering:') - print(' - vertical: ~ '+v_steering) - print(' - horizontal: reset slit 2BH center to ',str(H2)) - print('\n') - - print('\n\nWARNING: 2V slit should always be centered at zero') - print('Increasing M1 roll moves the beam more positive on 2V:') - print('\t+0.05 pitch => ~ +0.04 slit position') - print('To steer M1, use:') - print("\tGet_Mirror(1);Move_M1('RZ',x)") + 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)) + except: - print('Unable to fit position.') + print('Unable to fit position; try to adjust xrange.') + # print('c='+str(c)) + # print('V2=fit_mda('+str(m-1)+','+str(detDiode)+',1*c+,"gauss")') + # print('H2=fit_mda('+str(m)+','+str(detDiode)+',1,"gauss")') + # print('\nThen use:') + # print('\tbeamsteering_2B(V2)') + # list_position.append(np.nan) + # list_position.append(np.nan) + flag=interactive_fct(mirror=True) + if kwargs['sound']:playsound() - if kwargs['interactive']: flag=interactive_fct('slit 2B') - else: break + flag=interactive_fct(mirror=True) + while flag == 3: + fitV2=input('do you want to FIT mda #'+str(m-1)+' ie slit2-V (y or n)? >') + if fitV2.lower() == 'y' or fitV2.lower() == 'yes': + x1=input('x1 >') + x2=input('x2 >') + V2=fit_mda(m-1,detDiode,1,'gauss',xrange=[float(x1),float(x2)]);plt.show() + foo=input('do you want to replace slit2-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(m)+' ie slit2-H (y or n)? >') + if fitH2.lower() == 'y' or fitH2.lower() == 'yes': + x1=input('x1 >') + x2=input('x2 >') + H2=fit_mda(m ,detDiode,1,'gauss',xrange=[float(x1),float(x2)]);plt.show() + foo=input('do you want to REPLACE slit2-H value in list_position (y or n)? >') + if foo.lower() == 'y' or foo.lower() == 'yes': + list_position[1]=H2 + foo=input('\nare you happy with the fit (y or n)? >') + if foo.lower() == 'y' or foo.lower() == 'yes': + flag=interactive_fct(mirror=True) + 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('\n---------- Scanning slit 1A:\n') - flag=True - while flag: - scan_narrow_slit('1V',[0.25, -4, 4, 0.1]) - sleep(1) - scan_narrow_slit('1H',[0.25, -3, 3, 0.1]) - sleep(1) + flag=2 + while flag==2: + slits_scan_center('slit1A','V',-4, 4, 0.1,size=(inf,0.25)) + slits_scan_center('slit1A','H',-3, 3, 0.1,size=(0.25,inf)) apertures_set() - m=BL.mda.lastFileNum() + m=iex.BL.mda.last_mda() try: V1=fit_mda(m-1,detDiode,1,'gauss');plt.show() H1=fit_mda(m ,detDiode,1,'gauss');plt.show() - list_position.append(V1) - list_position.append(H1) + list_position[3]=V1 + list_position[4]=H1 print('\nBeam position:') print(f" - vertical: V1 = {round(V1,3)}") print(f" - horizontal: H1 = {round(H1,3)}") except: - print('Unable to fit position.') + print('\nUnable to fit position; try to adjust xrange.') + # print('V1=fit_mda('+str(m-1)+','+str(detDiode)+',1,"gauss")') + # print('H1=fit_mda('+str(m)+','+str(detDiode)+',1,"gauss")') + # list_position.append(np.nan) + # list_position.append(np.nan) if kwargs['sound']:playsound() - if kwargs['interactive']: flag=interactive_fct('slit 1A') - else: break - print('\nBeam center fit @ [2V,2H,1V,1H]:',list_position) - print('\nTo update slit center using: update_slit_dict()\n') + flag=interactive_fct() #interactive_fct('slit 1A') + while flag == 3: + fitV1=input('do you want to fit mda #'+str(m-1)+' ie slit1-V (y or n)? >') + if fitV1.lower() == 'y' or fitV1.lower() == 'yes': + x1=input('x1 >') + x2=input('x2 >') + V1=fit_mda(m-1,detDiode,1,'gauss',xrange=[float(x1),float(x2)]);plt.show() + foo=input('do you want to replace slit1-V value in list_position (y or n)? >') + if foo.lower() == 'y' or foo.lower() == 'yes': + list_position[3]=V1 + fitH1=input('do you want to fit mda #'+str(m)+' ie slit1-H (y or n)? >') + if fitH1.lower() == 'y' or fitH1.lower() == 'yes': + x1=input('x1 >') + x2=input('x2 >') + H1=fit_mda(m ,detDiode,1,'gauss',xrange=[float(x1),float(x2)]);plt.show() + foo=input('do you want to replace slit1-H value in list_position (y or n)? >') + if foo.lower() == 'y' or foo.lower() == 'yes': + list_position[4]=H1 + foo=input('\nare you happy with the fit (y or n)? >') + if foo.lower() == 'y' or foo.lower() == 'yes': + flag=interactive_fct() + print('\nBeam center fit @ ['+GRT+',2V,2H,1V,1H]:',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: # longer full slit scans - ID_SP_set(500) - flag=True - while flag: - mono_energy_set(500) + mvID(500) + flag=2 + while flag==2: + mvmono(500) apertures_set() n=2 if 'extended_range' in kwargs else 1 scan_mono_vs_slit('2V',[0.25*c,-2*c*n,2*c*n,0.5],[475,515,2],comment='Mono/Slit - 2V') #10/20 min for MEG/HEG @@ -261,43 +382,457 @@ def start_of_the_week(grt,branch,wait=False,**kwargs): scan_mono_vs_slit('1V',[0.5,-0.75*n,0.75*n,0.25*c],[475,515,2],comment='Mono/Slit - 1V') #10min scan_mono_vs_slit('1H',[0.5,-0.75*n,0.75*n,0.25],[475,515,2],comment='Mono/Slit - 1H') #10min #interactive - if kwargs['interactive']: flag=interactive_fct() - else: break + flag=interactive_fct() ###### Check flux: if 'flux' in kwargs['scanType']: - if m3r_branch == 'c': - diode_c('In') + diode_c('In') print("\n\n================== Check Flux:") - flag=True - while flag: - check_flux(stay=True) - exit_slit(50) + flag=2 + while flag==2: + check_flux(stay='y') + slit(50) energy(500) - scanhv(475,525,1,comment='Mono Scan @ 500eV') + scanmono(475,525,1,comment='Mono Scan @ 500eV') + m=iex.BL.mda.last_mda() try: - m=BL.mda.lastFileNum() - plot_mda(m,detDiode,flux=3);plt.show() + plot_mda(m,detDiode,Flux=3);plt.show() except: - print('Unable to fit position.') - ### interactive - if kwargs['interactive']: flag=interactive_fct() - else: break + print('Unable to plot. Try:') + print("plot_mda("+str(m)+","+str(detDiode)+",flux=3);plt.show()") + flag=interactive_fct() diagnostics_all_out() print("\n\n================== All done:") print("\nDon't forget to put back the user folder !!!!") - ###### Plotting instructions and return first scan number - if FirstScan is not None: - log_print(comment="\nFirstScan = "+str(FirstScan)) - print('StartOfTheWeek_plot("'+branch+'",'+str(FirstScan)+')' ) - print('Beam center fit @ [2V,2H,1V,1H]:',list_position) - print('\nREMEMBER to update slit center using: update_slit_dict()') - + + ###### 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 + +############################################################################################### +######################################### Start Of The Week plotting -- old!!!! ################################### +############################################################################################### + +def plot_StartOfTheWeek_DetDict(branch): + """ + returns the detectors for a given branch + + """ + DetDict={'c':(9,7,8,15),'d':(9,7,8,14)} + return DetDict[branch] + +def StartOfTheWeek_plot(branch,FirstScanNum,**kwargs): + """ + Plots the data from StartOfTheWeek + + branch is used to set the detectors + detCA4,detH,detV,detDiode=plot_StartOfTheWeek_Det(branch) + + FirstScanNum is based on slit1A + slit1A-H = FirstScanNum + slit1A-V = FirstScanNum + 1 + wire1-H = FirstScanNum + 2 + wire1-V = FirstScanNum + 3 + monoVslit = FirstScanNum + 4/5/6/7 + flux = FirstScanNum + 8 + + Slit 1A and Wire scans: determine ID steering and Slit1A position + Scan_MonoVsSlit: determine the steering from M0/M1 + by default the full range is plotted (pnt_first=0, pnt_last=inf) + refine the plot via + plot_StartOfTheWeek_mono(branch,FirstScanNum,pnt_first,pnt_last) + + kwargs: + filepath = None, uses current mda filepath unless specified + e.g. user : filepath='/net/s29data/export/data_29idc/2018_2/UserName/mda/' + e.g. staff: filepath='/net/s29data/export/data_29idb/2018_2/mda/' + prefix = None, uses current mda prefix unless specified + scanIOC = None, uses BL_ioc() unless specified + + scanType = ['slit1','wire','flux','monoVslit'], full set by default + + ref_firstScanNum to plot reference spectra + ref_branch = branch, unless specified + ref_filepath = filepath, unless specified + ref_prefix = prefix, unless specified + + steering out => moves beam more positive (20 urad ~ 0.5 mm) + steering up => moves beam more positive (20 urad ~ 0.5 mm) + +figure, axes = plt.subplots(nrows=2, ncols=2) +axes[0, 0].plot(x, y) + """ + + kwargs.setdefault('filepath',BL.mda.filepath()) + kwargs.setdefault('prefix',BL.mda.prefix()) + + kwargs.setdefault('scanType',['slit1','wire','flux','monoVslit']) + + kwargs.setdefault('ref_firstScanNum',None) + kwargs.setdefault('ref_fpath',None) + kwargs.setdefault('ref_branch',branch) + kwargs.setdefault('ref_filepath',BL.mda.filepath()) + kwargs.setdefault('ref_prefix',BL.mda.prefix()) + + kwargs.setdefault('debug',False) + + + scanNum=FirstScanNum + ref_firstScanNum=kwargs['ref_firstScanNum'] + detCA4,detH,detV,detDiode=plot_StartOfTheWeek_DetDict(branch) + + + if 'slit1' in kwargs['scanType']: + if kwargs['debug']: + print('slit1') + plot_StartOfTheWeek_slit1A(branch,scanNum,**kwargs) + scanNum+=2 + if kwargs['ref_firstScanNum'] is not None: + kwargs.update({'ref_firstScanNum':ref_firstScanNum+2}) + + + if 'wire' in kwargs['scanType']: + if kwargs['debug']: + print('wire') + plot_StartOfTheWeek_wire(branch,scanNum,**kwargs) + scanNum+=2 + if kwargs['ref_firstScanNum'] is not None: + ref_firstScanNum+=2 + kwargs.update({'ref_firstScanNum':ref_firstScanNum+2}) + + if 'monoVslit' in kwargs['scanType']: + d=IEXdata(scanNum,path=kwargs['filepath'],prefix=kwargs['prefix'],q=1) + if d.mda[scanNum].header.all['rank']<2: #quick + print(scanNum, detDiode) + V2=fit_mda(scanNum,detDiode,1,'gauss',filepath=kwargs['filepath'],prefix=kwargs['prefix'],scanIOC=kwargs['scanIOC'],title='2V - mda_'+str(scanNum)) + H2=fit_mda(scanNum+1,detDiode,1,'gauss',filepath=kwargs['filepath'],prefix=kwargs['prefix'],scanIOC=kwargs['scanIOC'],title='2H - mda_'+str(scanNum+1)) + V1=fit_mda(scanNum+2,detDiode,1,'gauss',filepath=kwargs['filepath'],prefix=kwargs['prefix'],scanIOC=kwargs['scanIOC'],title='1V - mda_'+str(scanNum+2)) + H1=fit_mda(scanNum+3,detDiode,1,'gauss',filepath=kwargs['filepath'],prefix=kwargs['prefix'],scanIOC=kwargs['scanIOC'],title='1H - mda_'+str(scanNum+3)) + plt.show() + print('\nFit positions:') + print(f"V2={round(V2,3)}") + print(f"H2={round(H2,3)}") + print(f"V1={round(V1,3)}") + print(f"H1={round(H1,3)}") + + else: #MonoVsSlit + print('\n# To plot the Mono vs Slit data use:\n') + print('\tplot_MonoVsSlit(\"'+branch+'\",'+str(scanNum)+','+str(detDiode)+',0,inf)'+'\t#2V') + print('\tplot_MonoVsSlit(\"'+branch+'\",'+str(scanNum+1)+','+str(detDiode)+',0,inf)'+'\t#2H') + print('\tplot_MonoVsSlit(\"'+branch+'\",'+str(scanNum+2)+','+str(detDiode)+',0,inf)'+'\t#1V') + print('\tplot_MonoVsSlit(\"'+branch+'\",'+str(scanNum+3)+','+str(detDiode)+',0,inf)'+'\t#1H') + print('\n# (pnt_first,pnt_last0=(0,inf) => plots all') + print('# select specific first/last to refine.') + + print('\nREMEMBER to update slit center using: \tupdate_slit_dict()' ) + scanNum+=4 + if kwargs['ref_firstScanNum'] is not None: + kwargs.update({'ref_firstScanNum':ref_firstScanNum+4}) + + if 'flux' in kwargs['scanType']: + if kwargs['debug']: + print('flux') + plot_StartOfTheWeek_flux(branch,scanNum,**kwargs) + +def plot_StartOfTheWeek_slit1A(branch,scanNum,**kwargs): + """ + plots the slit1A scans + scanNum = slit1A-H scanNum + """ + kwargs.setdefault('filepath',BL.mda.filepath()) + kwargs.setdefault('prefix',BL.mda.prefix()) + kwargs.setdefault('plotType',['slit1','wire','flux','monoVslit']) + kwargs.setdefault('ref_firstScanNum',None) + kwargs.setdefault('ref_fpath',None) + kwargs.setdefault('ref_branch',branch) + kwargs.setdefault('ref_filepath',BL.mda.filepath()) + kwargs.setdefault('ref_prefix',BL.mda.prefix()) + kwargs.setdefault('debug',False) + + detCA4,detH,detV,detDiode=plot_StartOfTheWeek_DetDict(branch) + ref_detCA4,ref_detH,ref_detV,ref_detDiode=plot_StartOfTheWeek_DetDict(kwargs['ref_branch']) + + figure, axes = plt.subplots(nrows=1, ncols=2,figsize=(10,3)) + for i,t in enumerate(['1H center scan','1V center scan']): + d=IEXdata(scanNum,path=kwargs['filepath'],prefix=kwargs['prefix'],q=1) + axes[i].plot(d.mda[scanNum].det[detCA4].scale['x'], d.mda[scanNum].det[detCA4].data,marker='x',label=str(scanNum)) + scanNum+=1 + if kwargs['ref_firstScanNum'] is not None: + ref_scanNum=kwargs['ref_firstScanNum']+i + ref_d=IEXdata(ref_scanNum,path=kwargs['ref_filepath'],prefix=kwargs['ref_prefix'],q=1) + axes[i].plot(ref_d.mda[ref_scanNum].det[ref_detCA4].scale['x'], ref_d.mda[ref_scanNum].det[ref_detCA4].data,marker='x',label=str(ref_scanNum)) + axes[i].grid(color='lightgray', linestyle='-', linewidth=0.5) + axes[i].title.set_text(t) + axes[i].legend() + plt.show() + print("\nsteering out => move beam more positive (10 urad ~ 0.25 mm)") + print("steering up => move beam more positive (10 urad ~ 0.25 mm)") + print("\nTo fit beam position use:\n") + print("detCA4,detH,detV,detDiode=plot_StartOfTheWeek_DetDict('"+kwargs['ref_branch']+"')") + print("fit_mda("+str(scanNum-2)+",detCA4,1,'gauss',xrange=(-1,1))") + print("fit_mda("+str(scanNum-1)+",detCA4,1,'gauss',xrange=(-1,1))\n") + + +def plot_StartOfTheWeek_wire(branch,scanNum,**kwargs): + """ + plots the wire scans + scanNum = wire-H scanNum + """ + kwargs.setdefault('filepath',BL.mda.filepath()) + kwargs.setdefault('prefix',BL.mda.prefix()) + kwargs.setdefault('plotType',['slit1','wire','flux','monoVslit']) + kwargs.setdefault('ref_firstScanNum',None) + kwargs.setdefault('ref_fpath',None) + kwargs.setdefault('ref_branch',branch) + kwargs.setdefault('ref_filepath',BL.mda.filepath()) + kwargs.setdefault('ref_prefix',BL.mda.prefix()) + kwargs.setdefault('debug',False) + + detCA4,detH,detV,detDiode=plot_StartOfTheWeek_DetDict(branch) + ref_detCA4,ref_detH,ref_detV,ref_detDiode=plot_StartOfTheWeek_DetDict(kwargs['ref_branch']) + + figure, axes = plt.subplots(nrows=1, ncols=2,figsize=(10,3)) + for i,t in enumerate(['H-wire','V-wire']): + d=IEXdata(scanNum,path=kwargs['filepath'],prefix=kwargs['prefix'],q=1) + #niceplot(d.mda[scanNum].det[DetDict[branch][1+i]],marker='x',label=str(scanNum)) + detNum=plot_StartOfTheWeek_DetDict(branch)[1+i] + axes[i].plot(d.mda[scanNum].det[detNum].scale['x'], d.mda[scanNum].det[detNum].data,marker='x',label=str(scanNum)) + scanNum+=1 + if kwargs['ref_firstScanNum'] is not None: + ref_scanNum=kwargs['ref_firstScanNum']+i + ref_d=IEXdata(ref_scanNum,path=kwargs['ref_filepath'],prefix=kwargs['ref_prefix'],q=1) + #niceplot(ref_d.mda[ref_scanNum].det[DetDict[kwargs["ref_branch"]][1+i]],marker='x',label=str(ref_scanNum)) + detNum=plot_StartOfTheWeek_DetDict(kwargs["ref_branch"])[1+i] + axes[i].plot(ref_d.mda[ref_scanNum].det[detNum].scale['x'], ref_d.mda[ref_scanNum].det[detNum].data,marker='x',label=str(ref_scanNum)) + axes[i].grid(color='lightgray', linestyle='-', linewidth=0.5) + axes[i].title.set_text(t) + axes[i].legend() + plt.show() + +def plot_StartOfTheWeek_flux(branch,scanNum,**kwargs): + """ + plots the wire scans + scanNum = wire-H scanNum + """ + kwargs.setdefault('filepath',BL.mda.filepath()) + kwargs.setdefault('prefix',BL.mda.prefix()) + kwargs.setdefault('plotType',['slit1','wire','flux','monoVslit']) + kwargs.setdefault('ref_firstScanNum',None) + kwargs.setdefault('ref_fpath',None) + kwargs.setdefault('ref_branch',branch) + kwargs.setdefault('ref_filepath',BL.mda.filepath()) + kwargs.setdefault('ref_prefix',BL.mda.prefix()) + kwargs.setdefault('debug',False) + + detCA4,detH,detV,detDiode=plot_StartOfTheWeek_DetDict(branch) + ref_detCA4,ref_detH,ref_detV,ref_detDiode=plot_StartOfTheWeek_DetDict(kwargs['ref_branch']) + + for t in ['ID peak @ 500eV']: + d=IEXdata(scanNum,path=kwargs['filepath'],prefix=kwargs['prefix'],q=1) + niceplot(d.mda[scanNum].det[detDiode],marker='x',label=str(scanNum)) + scanNum+=1 + if kwargs['ref_firstScanNum'] is not None: + ref_scanNum=kwargs['ref_firstScanNum']+2 + ref_d=IEXdata(ref_scanNum,path=kwargs['ref_filepath'],prefix=kwargs['ref_prefix'],q=1) + niceplot(ref_d.mda[ref_scanNum].det[ref_detDiode],marker='x',label=str(ref_scanNum)) + ref_scanNum+=1 + plt.grid(color='lightgray', linestyle='-', linewidth=0.5) + plt.title(t) + plt.legend() + plt.show() + +def plot_MonoVsSlit(branch,ScanNum,detDiode,pnt_first,pnt_last,norm=True,filepath=None,prefix=None,scanIOC=None): + """ + Plots Scan_MonoVsSlit to determine the steering from M0/M1 + To plot the full range (pnt_first=0, pnt_last=inf) + plot_StartofWeek_mono(branch,FirstScanNum+4,pnt_first,pnt_last) + + filepath: by default plot scans for the current data folder (as defined in BL_ioc() ScanRecord SaveData) + or specified folder path ending with '/': + e.g. user : filepath='/net/s29data/export/data_29idc/2018_2/UserName/mda/' + e.g. staff: filepath='/net/s29data/export/data_29idb/2018_2/mda/' + prefix: by default, uses prefix as defined in ScanRecord ("mda_") + """ + x,y,z,x_name,y_name,z_name=mda_2D(ScanNum,detDiode,filepath,prefix,scanIOC) + Which=str(y_name)[10:12] + if pnt_last is inf: + pnt_last=len(z)-1 + for i in range(pnt_first,pnt_last+1): + maxvalue=max(z[i]) + if norm == True: + plt.plot(x,z[i]/maxvalue,label='#'+str(i)+': '+str(round(y[i],2))) + else: + plt.plot(x,z[i],label='#'+str(i)+': '+str(round(y[i],2))) + plt.legend(bbox_to_anchor=(1, 0), loc='lower left', ncol=2,shadow=True, title="ScanNum: "+str(ScanNum)+"\nSlit-"+Which+" position", fancybox=True) + #plt.legend(loc='lower left',ncol=2, shadow=True, title="ScanNum: "+str(ScanNum)+"\nSlit-"+Which+" position", fancybox=True) + plt.grid(color='lightgray', linestyle='-', linewidth=0.5) + plt.show() + + +def read_flux(FileName='Flux_Curves.txt',FilePath="/home/beams22/29IDUSER/Documents/User_Macros/Macros_29id/IEX_Dictionaries/"): + print('test') + with open(join(FilePath, FileName)) as f: + for c,line in enumerate(f.readlines()): + if line[0] == '=': + lastdate=line[8:16] + print(lastdate) + if line[0] == '-' and line[-2] == 'x': + axis='x' + print(axis) + line_x=line + if line[0] == '-' and line[-2] == 'y': + axis='y' + print(axis) + line_y=line + mydict_x=ast.literal_eval(line_x) + mydict_y=ast.literal_eval(line_y) + return mydict_x,mydict_y + + diff --git a/iexcode.egg-info/SOURCES.txt b/iexcode.egg-info/SOURCES.txt index 961d7f5366e18664595059cd5ce21e048a484a50..96e4bca3e9f806b8d9fd2868636f03c0b70768f7 100644 --- a/iexcode.egg-info/SOURCES.txt +++ b/iexcode.egg-info/SOURCES.txt @@ -3,6 +3,7 @@ setup.py iexcode/__init__.py iexcode/launch_ARPES.py iexcode/launch_Kappa.py +iexcode/launch_all.py iexcode/launch_staff.py iexcode/launch_xrays.py iexcode.egg-info/PKG-INFO @@ -13,10 +14,9 @@ iexcode.egg-info/top_level.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_endstations.py iexcode/instruments/Kappa.py -iexcode/instruments/Kappa_Euler.py iexcode/instruments/Kappa_det.py iexcode/instruments/Lakeshore_335.py iexcode/instruments/Logfile.py @@ -26,7 +26,6 @@ iexcode/instruments/Scienta.py iexcode/instruments/VLS_PGM.py iexcode/instruments/__init__.py iexcode/instruments/bakeout.py -iexcode/instruments/beamline.py iexcode/instruments/cameras.py iexcode/instruments/cfg.py iexcode/instruments/conversions_constants.py @@ -36,6 +35,7 @@ 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 @@ -54,8 +54,10 @@ 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/ScanFunctions_plot.py iexcode/macros/__init__.py iexcode/macros/commissioning.py -iexcode/macros/start_of_the_week.py \ No newline at end of file +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/instruments/AD_utilities.py b/iexcode/instruments/AD_utilities.py index a10c752426a0c1d0e3d37c3c0a7545e6b06b0f91..cbe60f3ee47135bbcc4875ba9ae578ebf5139c1e 100644 --- a/iexcode/instruments/AD_utilities.py +++ b/iexcode/instruments/AD_utilities.py @@ -6,9 +6,10 @@ work in progress need to redo ############################################################################################################## ############################## General Area Detector ############################## ############################################################################################################## +import os import datetime import re -from os import listdir,mkdir,chown,system,chmod,path + from time import sleep from epics import caget, caput @@ -36,7 +37,7 @@ def AD_CurrentDirectory(ADplugin): else: Dir = SubDir SubDir=[] - FilePath=path.join(Dir,*SubDir,'') + FilePath=os.path.join(Dir,*SubDir,'') return FilePath def AD_prefix(ADplugin): @@ -55,7 +56,15 @@ def AD_EnableStats(ADplugin): 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 @@ -73,7 +82,7 @@ def AD_SaveFileSetup(ADplugin,**kwargs): FileTemplate="%s%s_%4.4d."+ext; format for filename first %s = filepath, second %s = prefix """ - kwargs.setdefault("userpath",path.dirname(iex.BL.mda.filepath())) + kwargs.setdefault("userpath",os.path.dirname(iex.BL.mda.filepath())) kwargs.setdefault("subfolder",ADplugin.split(":")[-2][:-1]) kwargs.setdefault("prefix",ADplugin.split(":")[-2][:-1]) @@ -85,9 +94,9 @@ def AD_SaveFileSetup(ADplugin,**kwargs): if kwargs['debug']: print("kwargs: ",kwargs) - fpath=path.join(kwargs['userpath'],kwargs['subfolder'],'') + fpath=os.path.join(kwargs['userpath'],kwargs['subfolder'],'') print("\nFolder: " + fpath) - if not (path.exists(fpath)): + if not (os.path.exists(fpath)): fileNumber=1 else: fileNumber=get_next_fileNumber(fpath,kwargs["prefix"]) diff --git a/iexcode/instruments/IEX_VPU.py b/iexcode/instruments/IEX_VPU.py index b3fd7660873c20cfed073306effb4b4533ffc4d5..45ddf3a2fceb35a290deafa7bfd69d96d9a1225e 100644 --- a/iexcode/instruments/IEX_VPU.py +++ b/iexcode/instruments/IEX_VPU.py @@ -199,13 +199,16 @@ def ID_start(ID_mode='RCP',QP_ratio=None, verbose=True): mode = \"H\", \"V\", \"RCP\" or \"LCP\" QP ratio if specified """ - if ID_power_status =='Off' + #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(): main_shutter_open() diff --git a/iexcode/instruments/__pycache__/AD_utilites.cpython-37.pyc b/iexcode/instruments/__pycache__/AD_utilites.cpython-37.pyc deleted file mode 100644 index 8a370ff2b8c85e414b0f9ab7954b00e977d81b09..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/AD_utilites.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/AD_utilities.cpython-37.pyc b/iexcode/instruments/__pycache__/AD_utilities.cpython-37.pyc deleted file mode 100644 index 1a6e8475e8f93358fb1fe83baa8349354c91d9ae..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/AD_utilities.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/ARPES.cpython-37.pyc b/iexcode/instruments/__pycache__/ARPES.cpython-37.pyc deleted file mode 100644 index 75597a47c882b71d008e0bc4b04a61212dbc3b03..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/ARPES.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/FMB_mirrors.cpython-37.pyc b/iexcode/instruments/__pycache__/FMB_mirrors.cpython-37.pyc deleted file mode 100644 index 57c1211c32d375f886d98398dd6a047fcccc963b..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/FMB_mirrors.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/IEX_VPU.cpython-37.pyc b/iexcode/instruments/__pycache__/IEX_VPU.cpython-37.pyc deleted file mode 100644 index 48fdfabc4675e10f548048eafc93655f24cb372c..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/IEX_VPU.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/IEX_endstations.cpython-37.pyc b/iexcode/instruments/__pycache__/IEX_endstations.cpython-37.pyc deleted file mode 100644 index 8e65b8fe990c1e2b9197a6c897ee4d0453c48d44..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/IEX_endstations.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/Kappa.cpython-37.pyc b/iexcode/instruments/__pycache__/Kappa.cpython-37.pyc deleted file mode 100644 index 4cdb02de5338be6e406d459d6ab54bc1ffec6a31..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/Kappa.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/Kappa_Euler.cpython-37.pyc b/iexcode/instruments/__pycache__/Kappa_Euler.cpython-37.pyc deleted file mode 100644 index e36da7b8c710469157f0613f122dab8b950e3934..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/Kappa_Euler.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/Kappa_det.cpython-37.pyc b/iexcode/instruments/__pycache__/Kappa_det.cpython-37.pyc deleted file mode 100644 index 8abdb62bdff80a559d717666b3bb53156017a41d..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/Kappa_det.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/Lakeshore_335.cpython-37.pyc b/iexcode/instruments/__pycache__/Lakeshore_335.cpython-37.pyc deleted file mode 100644 index 8fe68e9b0219fe031f8768107e920399efdadc2c..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/Lakeshore_335.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/Motors.cpython-37.pyc b/iexcode/instruments/__pycache__/Motors.cpython-37.pyc deleted file mode 100644 index 65303762f5649d738bebae3d0b95eefade32aa4c..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/Motors.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/Scienta.cpython-37.pyc b/iexcode/instruments/__pycache__/Scienta.cpython-37.pyc deleted file mode 100644 index 3749ba4d74f6697e31add388485ca2ac10d6c38c..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/Scienta.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/VLS_PGM.cpython-37.pyc b/iexcode/instruments/__pycache__/VLS_PGM.cpython-37.pyc deleted file mode 100644 index b24f7623fd135e0ec917cb7d239a015d5dc153ef..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/VLS_PGM.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/__init__.cpython-37.pyc b/iexcode/instruments/__pycache__/__init__.cpython-37.pyc deleted file mode 100644 index 4c3c008b246ea4aaf58e2d55d10549b1f5dd589b..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/__init__.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/bakeout.cpython-37.pyc b/iexcode/instruments/__pycache__/bakeout.cpython-37.pyc deleted file mode 100644 index f66bfe8286efa29bc098861333f411d46e5eddd0..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/bakeout.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/beamline.cpython-37.pyc b/iexcode/instruments/__pycache__/beamline.cpython-37.pyc deleted file mode 100644 index 084b895e5db96a6afb98a4b3acb29e2dbfa44245..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/beamline.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/cameras.cpython-37.pyc b/iexcode/instruments/__pycache__/cameras.cpython-37.pyc deleted file mode 100644 index 314916561858f01cd5b932833b4edd3f4acfa988..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/cameras.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/conversions_constants.cpython-37.pyc b/iexcode/instruments/__pycache__/conversions_constants.cpython-37.pyc deleted file mode 100644 index 2eaf10078a2d3ae7767b79bdbca730a979c03442..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/conversions_constants.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/current_amplifiers.cpython-37.pyc b/iexcode/instruments/__pycache__/current_amplifiers.cpython-37.pyc deleted file mode 100644 index 17f97f1549d6930c4f0d1af030b664f4227c3664..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/current_amplifiers.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/diagnostics.cpython-37.pyc b/iexcode/instruments/__pycache__/diagnostics.cpython-37.pyc deleted file mode 100644 index bc05a7a8e2024e0b4a86b65d0f8a0ca36bdad5f6..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/diagnostics.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/electron_analyzer.cpython-37.pyc b/iexcode/instruments/__pycache__/electron_analyzer.cpython-37.pyc deleted file mode 100644 index f9ca29030ddab11737767a189ff852583fe69d2c..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/electron_analyzer.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/encoders.cpython-37.pyc b/iexcode/instruments/__pycache__/encoders.cpython-37.pyc deleted file mode 100644 index 3b073fe79b3370736b5f54c0b7df04e2a5372cc9..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/encoders.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/files_and_folders.cpython-37.pyc b/iexcode/instruments/__pycache__/files_and_folders.cpython-37.pyc deleted file mode 100644 index d07f6e1e79cca22aff31195d4481cfe94d9ffbaa..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/files_and_folders.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/gate_valves.cpython-37.pyc b/iexcode/instruments/__pycache__/gate_valves.cpython-37.pyc deleted file mode 100644 index b226d256630f6017a49ca7160868608128964e54..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/gate_valves.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/hxp_mirrors.cpython-37.pyc b/iexcode/instruments/__pycache__/hxp_mirrors.cpython-37.pyc deleted file mode 100644 index 8747a50a2eed658297f8b7cb72d64d78f027bda7..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/hxp_mirrors.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/logfile.cpython-37.pyc b/iexcode/instruments/__pycache__/logfile.cpython-37.pyc deleted file mode 100644 index 68a3b11783f01b7a8f197290c663bd7183375a04..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/logfile.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/m3r.cpython-37.pyc b/iexcode/instruments/__pycache__/m3r.cpython-37.pyc deleted file mode 100644 index bc9f6764e739a8d6050c03f89d8ed03dc58736b8..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/m3r.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/mpa.cpython-37.pyc b/iexcode/instruments/__pycache__/mpa.cpython-37.pyc deleted file mode 100644 index d08115e60825b3719c2b6d5775a66c30eaf8a333..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/mpa.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/remote_controlers.cpython-37.pyc b/iexcode/instruments/__pycache__/remote_controlers.cpython-37.pyc deleted file mode 100644 index 6af0c322f5a4b610f11108737fbae1bc8057e3ec..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/remote_controlers.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/resolution.cpython-37.pyc b/iexcode/instruments/__pycache__/resolution.cpython-37.pyc deleted file mode 100644 index e396add37e1deb4258a5e6078e6261a4e7fb4c97..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/resolution.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/s29_temp_cntl.cpython-37.pyc b/iexcode/instruments/__pycache__/s29_temp_cntl.cpython-37.pyc deleted file mode 100644 index fb69f7e781be3eb592bbd3fe33c50cba8a604c99..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/s29_temp_cntl.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/scalers.cpython-37.pyc b/iexcode/instruments/__pycache__/scalers.cpython-37.pyc deleted file mode 100644 index 66dfe7809dd855ff40fe37bc83daf9b7275f17a3..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/scalers.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/scanRecord.cpython-37.pyc b/iexcode/instruments/__pycache__/scanRecord.cpython-37.pyc deleted file mode 100644 index 4a2f063245c768dd7a2f4c18e550b51ae6fa01c5..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/scanRecord.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/shutters.cpython-37.pyc b/iexcode/instruments/__pycache__/shutters.cpython-37.pyc deleted file mode 100644 index 63ecf2bc4e4cee714175f614eaa967f2b1e6e58c..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/shutters.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/slits.cpython-37.pyc b/iexcode/instruments/__pycache__/slits.cpython-37.pyc deleted file mode 100644 index 1d3c0b6595d26512aaace68743436f4a86bc9707..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/slits.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/spec_stuff.cpython-37.pyc b/iexcode/instruments/__pycache__/spec_stuff.cpython-37.pyc deleted file mode 100644 index 233507689e4b15634113b3e21e2bbb3cc81c6e5a..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/spec_stuff.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/staff.cpython-37.pyc b/iexcode/instruments/__pycache__/staff.cpython-37.pyc deleted file mode 100644 index df7f088dba4cb799008ae549f7e7b4d2d635dcd8..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/staff.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/storage_ring.cpython-37.pyc b/iexcode/instruments/__pycache__/storage_ring.cpython-37.pyc deleted file mode 100644 index efa0198e6e77c11ece2df7d1e27b632650dc0c14..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/storage_ring.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/userCalcs.cpython-37.pyc b/iexcode/instruments/__pycache__/userCalcs.cpython-37.pyc deleted file mode 100644 index 580ff6a9df83ae20d6aa1f0833e6156dee94d33f..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/userCalcs.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/utilities.cpython-37.pyc b/iexcode/instruments/__pycache__/utilities.cpython-37.pyc deleted file mode 100644 index 5d801bc7a5477c18181ad534cbc761ccf908fe29..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/utilities.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/vortexs29.cpython-37.pyc b/iexcode/instruments/__pycache__/vortexs29.cpython-37.pyc deleted file mode 100644 index ac73f08f263bedd80815a13b5b4a6dae8cf422fb..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/vortexs29.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/__pycache__/xrays.cpython-37.pyc b/iexcode/instruments/__pycache__/xrays.cpython-37.pyc deleted file mode 100644 index 39194f37bc4eab31c1f8b35004e0612b2b371888..0000000000000000000000000000000000000000 Binary files a/iexcode/instruments/__pycache__/xrays.cpython-37.pyc and /dev/null differ diff --git a/iexcode/instruments/current_amplifiers.py b/iexcode/instruments/current_amplifiers.py index 4ac0ed8e91bfa6ee6c3719925205108626c7407b..cb6a1b778a92facd0dbcb22c3a4e22fcc3cca7fe 100644 --- a/iexcode/instruments/current_amplifiers.py +++ b/iexcode/instruments/current_amplifiers.py @@ -21,6 +21,7 @@ def _ca_dictionary(): Previously: CA_Name """ + #For new endstation modify here: ca={} ca["b"] = { 1: 'W-mesh', diff --git a/iexcode/instruments/m3r.py b/iexcode/instruments/m3r.py index 87129777f309c561af05bdbd80d4cbe9c626361e..fe8d151fd14b930d65df4b8c7c442ce418045d62 100644 --- a/iexcode/instruments/m3r.py +++ b/iexcode/instruments/m3r.py @@ -1,5 +1,5 @@ from cgi import print_arguments -from build.lib.iexcode.instruments.VLS_PGM import mono_energy_get +from iexcode.instruments.VLS_PGM import mono_energy_get from epics import caget, caput diff --git a/iexcode/instruments/scalers.py b/iexcode/instruments/scalers.py index 4ddad3b0ac821d1c111f2908e362a8b5ece8b535..c3cef3bf48a9f7ac23ac76f28811f5e2e99f4ab5 100644 --- a/iexcode/instruments/scalers.py +++ b/iexcode/instruments/scalers.py @@ -8,7 +8,7 @@ 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': + if iex.BL.endstation_name == 'kappa': Kappa_scaler(time_seconds,verbose=verbose) else: pass @@ -30,3 +30,21 @@ def Kappa_scaler(time_seconds=0.1,verbose=True): if verbose: print("Integration time set to:", str(time_seconds)) +class Scaler: + def __inti__(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/iexcode/instruments/staff.py b/iexcode/instruments/staff.py index 4206824ef9e2c0758dd522522908ea9d71e8dcd0..dfca99fdd25c07ea7fd5e109bd40413c88014bac 100644 --- a/iexcode/instruments/staff.py +++ b/iexcode/instruments/staff.py @@ -1,39 +1,4 @@ -from os import listdir,mkdir,chmod -from os.path import join, isfile, exists - import iexcode.instruments.cfg as iex -from iexcode.instruments.ARPES import folders_ARPES, ARPES_init -from iexcode.instruments.kappa import folders_kappa, kappa_init - -def folders_startup(run): - """ - Creates the run directories for the following: - data_29idb - data_29idc - data_29idd - - calls folder_ARPES('Staff');folder_Kappa('Staff') - - print text required to modify the rsynch crontab - - previously: Folders_Startup - """ - data_directories=['data_29idb','data_29idc','data_29idd'] - dserv="/net/s29data/export/" - for dataDir in data_directories: - path=join(dserv,dataDir,run) - print(path) - if not (exists(path)): - mkdir(path) - - folders_ARPES('Staff',create_only=True) - folders_kappa('Staff',create_only=True) - - txt="\n\n\nupdate the rsync portion the 29id@nerdy crontab\n" - txt+="*/1 * * * * /usr/bin/rsync -av --exclude=core /net/s29data/export/data_29idd/"+run+" kip:/net/kip/sftp/pub/29iddftp/files > /home/beams22/29ID/cronfiles/cptoftp-currrun-d.log 2>&1" - txt+=("\n") - txt+="*/1 * * * * /usr/bin/rsync -av --exclude=core /net/s29data/export/data_29idd/"+run+" kip:/net/kip/sftp/pub/29iddftp/files > /home/beams22/29ID/cronfiles/cptoftp-currrun-d.log 2>&1" - print(txt) ############################################################################################################## ############################## staff detectors ############################## @@ -82,32 +47,3 @@ def staff_detector_dictionary(): return det_dict -############################################################################################################## -################################ setting the mda folder ############################## -############################################################################################################## - -def staff_init(endstation_name=None,**kwargs): - """ - endstation_name : sets the scan record and BL - set_folders: sets the mda and EA folders; default => False - reset: resets the scanRecord (detectors,triggers...) - - **kwargs: - xrays: sets global variable; default => True - BL_mode: 'user' / 'staff' => used for saving, detectors - - Previously: folders_staff - """ - kwargs.setdefault('mode','staff') - kwargs.setdefault('xrays',True) - kwargs.setdefault('set_folders',True) - kwargs.setdefault('reset',True) - - if endstation_name is None: - endstation_name = iex.BL.endstation - - if endstation_name == 'ARPES': - ARPES_init('staff',**kwargs) - if endstation_name == 'Kappa': - kappa_init('staff',**kwargs) - diff --git a/iexcode/launch_all.py b/iexcode/launch_all.py index 8c8d3a952dd528e272d8132048c74f1bc9841efc..d9a72a11094e6f81433093513a68d94f8d03bcf1 100644 --- a/iexcode/launch_all.py +++ b/iexcode/launch_all.py @@ -1,5 +1,5 @@ -from iexcode.instruments.cameras import * +from iexcode.macros.cameras import * import iexcode.instruments.cfg as iex from iexcode.instruments.conversions_constants import * from iexcode.instruments.current_amplifiers import Keithley,SRS diff --git a/iexcode/instruments/cameras.py b/iexcode/macros/cameras.py similarity index 82% rename from iexcode/instruments/cameras.py rename to iexcode/macros/cameras.py index 9f43d0f96196135b350fe502eab382f031688ecd..877769bd7ca6fb6bbb4a0f974039657d9c2950c1 100644 --- a/iexcode/instruments/cameras.py +++ b/iexcode/macros/cameras.py @@ -4,6 +4,7 @@ from epics import caget,caput,PV import iexcode.instruments.cfg as iex from iexcode.instruments.AD_utilities import * +from iexcode.macros.quick_plot import * ############################################################################################################## ############################## Camera PV dictionary ############################## @@ -20,6 +21,7 @@ def _pv_dictionary(): 4:"29id_ps4:", 5:"29idarv5:", 6:"29id_ps6:", + 7:"29id_ps7:", } return d @@ -72,8 +74,7 @@ def cam_snap(cam_num,ADtype='TIFF',**kwargs): False => leave saving enabled and camera in single acquision """ - ADplugin = _pv_dictionary()[cam_num]+ADtype+":" - AD_SaveFileSetup(ADplugin,iex.BL.mda,**kwargs) + ADplugin = _pv_dictionary()[cam_num]+ADtype+"1:" AD_snap(ADplugin,**kwargs) @@ -96,8 +97,7 @@ def cam_scan_setup(cam_num,ADtype='TIFF',**kwargs): FileTemplate="%s%s_%4.4d."+dtype; format for filename first %s = filepath, second %s = prefix prefix = dtype by default """ - kwargs.update('ADtype',ADtype) - ADplugin = _pv_dictionary()[cam_num]+ADtype+":" + ADplugin = _pv_dictionary()[cam_num]+ADtype+"1:" ADplugin_ScanSetup(ADplugin,iex.BL.mda, **kwargs) def cam_live(cam_num): @@ -106,22 +106,39 @@ def cam_live(cam_num): a.k.a free run """ - ADtype='TIFF' - ADplugin = _pv_dictionary()[cam_num]+ADtype+":" + ADplugin = _pv_dictionary()[cam_num] AD_FreeRun(ADplugin) def cam_done(cam_num,**kwargs): """ stops camera acquisition (not will stop after current acquisition) """ - ADtype='TIFF' - ADplugin = _pv_dictionary()[cam_num]+ADtype+":" + ADplugin = _pv_dictionary()[cam_num] AD_Done(ADplugin,**kwargs) -def cam_save_setup(cam_num,**kwargs): +def cam_save_setup(cam_num,ADtype='TIFF',**kwargs): """ sets up the save paths using iex.BL.mda.current_user + **kwargs + prefix: beginning of filename """ - ADtype='TIFF' - ADplugin = _pv_dictionary()[cam_num]+ADtype+":" + ADplugin = _pv_dictionary()[cam_num]+ADtype+"1:" AD_SaveFileSetup(ADplugin,**kwargs) + +def cam_last_filepath(cam_num,ADtype='TIFF',verbose=True): + """ + returns the full path for the last saved image + """ + ADplugin = _pv_dictionary()[cam_num]+ADtype+"1:" + fpath = AD_last_filename(ADplugin) + return fpath + +def cam_plot_last(cam_num,ADtype='TIFF',h=5,v=10,**kwargs): + """ + plots last file from cam_num + using iexcode.macros.quick_plot + """ + fpath = cam_last_filepath(cam_num,verbose=2) + plot_image(fpath,h,v,**kwargs) + + diff --git a/iexcode/macros/quick_plot.py b/iexcode/macros/quick_plot.py index f8210df5ed31768d707a35fe77220f428f5561e1..407c7c239efd093412849a05dd49bac6c477c004 100755 --- a/iexcode/macros/quick_plot.py +++ b/iexcode/macros/quick_plot.py @@ -19,8 +19,7 @@ from epics import caget from iexplot.mda import readMDA,scanDim import iexcode.instruments.cfg as iex from iexcode.instruments.current_amplifiers import current2flux -except: - print("EPICS package and dependent functions are not installed") +#print("EPICS package and dependent functions are not installed") diff --git a/iexcode/macros/start_up.py b/iexcode/macros/start_up.py new file mode 100644 index 0000000000000000000000000000000000000000..c0e299c832342f3cf0756badf7f9c82ea6bf855a --- /dev/null +++ b/iexcode/macros/start_up.py @@ -0,0 +1,34 @@ +import iexcode.instruments.cfg as iex + +from iexcode.instruments.ARPES import folders_ARPES +from iexcode.instruments.kappa import folders_kappa + +def folders_startup(run): + """ + Creates the run directories for the following: + data_29idb + data_29idc + data_29idd + + calls folder_ARPES('Staff');folder_Kappa('Staff') + + print text required to modify the rsynch crontab + + previously: Folders_Startup + """ + data_directories=['data_29idb','data_29idc','data_29idd'] + dserv="/net/s29data/export/" + for dataDir in data_directories: + path=join(dserv,dataDir,run) + print(path) + if not (exists(path)): + mkdir(path) + + folders_ARPES('Staff',create_only=True) + folders_kappa('Staff',create_only=True) + + txt="\n\n\nupdate the rsync portion the 29id@nerdy crontab\n" + txt+="*/1 * * * * /usr/bin/rsync -av --exclude=core /net/s29data/export/data_29idd/"+run+" kip:/net/kip/sftp/pub/29iddftp/files > /home/beams22/29ID/cronfiles/cptoftp-currrun-d.log 2>&1" + txt+=("\n") + txt+="*/1 * * * * /usr/bin/rsync -av --exclude=core /net/s29data/export/data_29idd/"+run+" kip:/net/kip/sftp/pub/29iddftp/files > /home/beams22/29ID/cronfiles/cptoftp-currrun-d.log 2>&1" + print(txt) \ No newline at end of file