Files
x07mb/script/Run_OTF_MA.py
2026-03-02 13:49:55 +01:00

380 lines
11 KiB
Python

import traceback
import imp
import os
#from CaChannel import *
#from epicsMotor import *
#from epicsPV import *
import time
import string
import sys
import json
# TO DO: Energy scan has onlz 1 positioner
# need to generalize definition of scans to several paraller positiner,
# to be able to use Create_Channels, alteratively need a dedicate channel creation for each scan type
# tricky, code should stay simple
# options.
# Define channel generation for each chanenl separatelz
# generalze scand to 1d and 2d with seveal posittioner in each dimension.
# this will get complicated .....
import X_X07MB_Pscan as PS
import X_X07MB_lib as PL
imp.reload(PS) # always reload module
imp.reload(PL) # always reload module
E_start = 445
E_end = 780
N_repeats = 1 # repetitions of each run without moving sample
time_of_scan = 8
# time in minutes
delay = 0.2
mode = None
offset = None
alpha = None
filename = None
NoRead=0
def before_pass():
# Called at begining pf scan
print('before_pass')
SC.PerformActions('Pre_Actions')
pars=get_exec_pars()
print('pars.output : ')
print(pars.output)
print('pars.scanPath: ')
print(pars.scanPath)
print('pars.name: (filename) ')
print(pars.name)
# missing
# NEED TO SET path for Moench here
#end before_pass
def before_read():
# Cannot call routine in class in rscan call, need to go via local routine
#print('before_read')
# SC.DetectorActions() excecutes all standard action as defied in GUI
SC.PerformActions('Detector_Actions')
#print('.... done before_read ' )
# alternativly use caput here explicitly...
# if needed
#end before read
def after_read(rec,scan):
print('ENTER after_read .................' )
# Called after reading
# calculate default dead time corrections and writ to file
SC.after_read_dtc(rec,scan)
print('.... done after_read ' )
return
#end after_read init
def after_pass():
# Called after scan
print('after_pass')
SC.PerformActions('Post_Actions')
print('................ done after_pass')
#end after pass
def before_region(index,scan):
print (index)
# make some reset
try:
del SC
except:
SC=0
#endexept
# originbal tag for data saving
# '{data}/{year}/{month}/{day}/{year}_{month}{day}_{time}_{name}'
# ........... FIrst read the scan
#
# ====================================================
#
# SCRIPT STARTS HERE
#
# ====================================================
if NoRead==0:
try:
SD = 0
SD = PS.get_channels('SPECTRA') # READ SCAN DEFINITION FROM GUI USING OLD CODE
print('returned from PS.get_channels()')
SC=0
SC=PL.PscanLib(SD,Channel,caput,caputq,caget,cawait,get_exec_pars,create_table,append_table) # create instance of library
print('... done SC.Create_All_Sensors()')
SD.update({'All_Sensors':[]})
except:
traceback.print_tb(sys.exc_info()[2])
raise
# endexcept
# endif
print('dddddddddddddddddddddddddd')
# example add new sensor, similarly add pre and postactions to existing code
New_Sensors=[]
New_Sensors.append({'channel_name': 'X07MB-ES-MA1:ScanY.RBV'
, 'Subset_1': False
, 'Det_type': 'ScalarDetector'
, 'alias': 'MYSCANY_RBV'
, 'data_type': 'double'})
# examples add post action light on
SD['Post_Actions'].append({'channel_name': 'X07MB-ES1-PP2:VO5'
, 'data_type': 'String'
, 'alias': 'Light_ON'
, 'operation': 'put'
, 'delay' : 0.1
, 'value' : 5 })
# END OF USER INPUT
# .... add new sensors to list
try:
try:
del AllSensors
except:
AllSensors=0
#endecsept
All_Sensors = SC.Create_Sensor_List() # Create instance for all sensors
SC.Add_New_Sensors(New_Sensors) # Add user sensors
except:
traceback.print_tb(sys.exc_info()[2])
raise
# endexcept
# STRUCTUALR INCONSITENCY NEED TO CREATE List of sensors first
# without making Channel command.... !
#
# TEST SAVE SCAN DEFINITION...Needs to be before definition
# SD is full GUI definiton of the scan try to save and reread this definiton
SD.update({'New_Sensors' : New_Sensors})
f=open('scandef.dat','w')
# Method to save abnd restore full scan definition...
with open('BaseScanDefinition.json', 'w') as fp:
json.dump(SD, fp,ensure_ascii=True)
#endwith
with open('BaseScanDefinition.json', 'r') as dd:
SD_reread=json.load(dd)
# .. this works, reread is unicode not string, but code seems still to work if all entries are in unicode
# step I: CREATE ALL SENSORS AND STORE IN A LIST
print('++++++++++++++++++++++++++')
AllSensors=0
try:
# Code for beamline save......
SavePhoenix=PL.SavePhoenix(Channel,caput,caputq,caget,cawait) # Channel,caput,caputq,caget,cawait)
# SavePhoenix.write_beamline_data().. Works., move to before pass...
SC.noprint=0 # chose printing from SD on / off
# Now creat all epic s instances. print('... done SC.Create_All_Sensors()')
SD.update({'All_Sensors':All_Sensors})
SC.Create_Channels('All_Sensors')
SC.Create_Channels('All_Positioner')
SC.Create_Channels('Detector_Actions')
SC.Create_Channels('Pre_Actions')
SC.Create_Channels('Post_Actions')
SC.Create_Channels('Energy_Scan')
except:
traceback.print_tb(sys.exc_info()[2])
raise
# endexcept
# ... create some abbreviations...
All_Sensors = SC.All_Sensors
All_Positioner = SD['All_Positioner']
Pre_Actions = SD['Pre_Actions']
Post_Actions = SD['Post_Actions']
Detector_Actions = SD['Detector_Actions']
Energy_Scan = SD['Energy_Scan']
#............SOME OUTPUT
#print('----------- All_Positioner ---')
#print(' ')
#print(SD['All_Positioner'])
#print(' ------------ Pre_Action -------- ')
#print(' ')
#print(SD['Pre_Actions'])
#print(' ------------ Post_Action -------- ')
#print(' ')
#print(SD['Post_Actions'])
#print(' ')
#print(' ----------- Detector_Action--------- ')
#print(' ')
#print(SD['Detector_Actions'])
## ............. MISSING CREATE POSTACTIONS::::::
# STEP II read the energy position
print('')
print('..................................... positioner Energy ID? readback automatically saved? ')
print('initial energies e_i ',SD['e_i'])
print('final energies e_f ',SD['e_f'])
print('DELTA E e_delta ',SD['e_delta'])
print('DWELL TIME e_n_cycles',SD['e_n_cycles'])
print(SD['Energy_Scan']['Energy_Ranges'])
#try:
# EnergyRanges,Cycles = SC.PositionerEnergyScan()
#except:
# traceback.print_tb(sys.exc_info()[2])
# raise
# endexcept nowcall
#print(EnergyRanges,Cycles)
# STEP II ... read the detector actions
# Step IV perform the Preaction
#P=SC.DetectorActions()
print(All_Sensors)
print('Energy_Ranges')
print(SD['Energy_Scan']['Energy_Ranges'])
pars=get_exec_pars()
print('pars.output')
print(pars.output)
print('pars.scanPath')
print(pars.scanPath)
print(' ')
print('---------------')
print(' ')
print(' CALL SCAN NOW ')
print(' ')
p=set_exec_pars(name=SD['filename'])
time.sleep(.2)
print(' -')
print(' -')
print('-----------DATA READ START SCAN ----------------- ')
print(' -')
print(' -')
TOP_UP=ChannelString('TOPUP_STAT','X07MB-ES-EVR:TOPUP-STAT')
TOP_UP.initialize()
# make sure that X07MB trigger is on other wise there is no reading of the data
#ContSample=Channel('X07MB-OP2:START-CSMPL')
#SingleSample=Channel('X07MB-OP2:SMPL')
#ContSample.put('1')
#time.sleep(.2)
#SingleSample.put(1)
#SingleSample.put(0)
for i_n in range(SD['number_of_executions']):
for i in range(len(All_Positioner[0]['value'])): # loop in number of points
# set all positioner
time.sleep(.2)
print('--------- set next positioner -----------',i)
for j in range(len(All_Positioner)): # set positioner
time.sleep(.2)
print('--------- set positioner -----------',j)
t0=time.time()
ThisPositioner = All_Positioner[j]['Channel']
ThisPosition = All_Positioner[j]['value'][i]
print('next,i,j',i,j)
print('name',All_Positioner[j]['channel_name'])
print('value',All_Positioner[j]['value'][i])
print(time.time()-t0)
# .............. SET NEW POSITIONER
#ThisPositioner.write(ThisPosition)
ThisPositioner.put(ThisPosition)
#ThisPositioner.putq(ThisPosition) # simultaneous walk no waiting..
print(time.time()-t0)
print('wait .2 seconds')
time.sleep(.2)
#endfor loop set positioner
# generate filename
#.......... START TOPUP CHECK
#while TOP_UP.read() == 'TOPUP-OFF':
# print('wait for next topup')
# time.sleep(0.05)
#end wait for toput
#while TOP_UP.read() == 'TOPUP-ON':
# print('wait to finish top up ')
# time.sleep(0.05)
#end topup
#time.sleep(2)
#end top up check
for i_repeat in range(N_repeats):
time.sleep(1)
filename=SD['filename']+'_'+All_Positioner[0]['label'][i]
filename=set_exec_pars(name=SD['filename']+'_'+All_Positioner[0]['label'][i])
pars=get_exec_pars()
print('')
print('======================================')
print('CHOSEN FILENANME IS')
print(pars.name)
print('====================================')
print('')
# TO DO CHECKL FOR SPECIAL SIGN IN NAMES
time.sleep(1)
#print('filename this run : ')
#print(pars.name)
print('--------------- NEXT CALL TO OTF ----------------')
try:
print('in try')
print('filenname',filename)
print('start')
# make sure that our trigger is set to 'on'
print('---CALL OTF ----',i_n,i,'\n')
print(E_start, E_end)
#for i_repeat in range(N_repeats):
time.sleep(1)
print('input into otf (before call)')
print(E_start, E_end, time_of_scan)
print('Call OTF')
otf(E_start, E_end, time_of_scan, delay=0.3, mode = None, offset = None, alpha = None, name = filename)
##endfor
time.sleep(1)
print('---OTF DONE ----')
except:
print('exception')
traceback.print_tb(sys.exc_info()[2])
raise
# END EXecpt
#endfor
#endfor
#endfor
#endfor
print('... scan finished ')