This commit is contained in:
root
2019-08-08 10:10:28 +02:00
parent 1f4edcbc88
commit 7f88d445af
37 changed files with 6480 additions and 501 deletions
+12
View File
@@ -0,0 +1,12 @@
st = Stream("st1",dispatcher)
st.setFilter("SIN-CVME-TIFGUN-EVR0:BEAMOK == 1")
c = "SARCL02-DBLM135:LOSS_SIGNAL_RAW"
st.addWaveform(c, c, 1, 2048)
try:
st.initialize()
st.start()
st.waitCacheChange(10000) #Wait stream be running before starting scan
mscan(st, st.getReadables()[1], -1, line_plots= [c,], keep=False, save=False)
finally:
st.close()
+115 -26
View File
@@ -1,8 +1,10 @@
import traceback
has_args = get_exec_pars().source != CommandSource.ui #Must be checked before callin "run"
is_script = get_exec_pars().source == CommandSource.script
is_embedded = (get_exec_pars().getCommand(False).parent != None)
has_args = is_embedded or (get_exec_pars().source != CommandSource.ui)
STREAM_CREATION_RETRIES = 3
MAX_RANGE_STEP = 3
run("Devices/Elements")
run("Devices/WireScanner")
@@ -23,12 +25,19 @@ bkgrd = args[7] if has_args else 10
plt = args[8] if has_args else plot(None, title = "Wire Scan")[0]
save_raw = args[9] if has_args else False
bunch = args[10] if has_args else 1
do_elog = True if (has_args and (not is_script) and (plt is not None)) else False
print has_args, do_elog
adaptive = args[11] if has_args else 1 #0=Off, 1=Gain, 2=Gain+range
filter_beam_ok = (args[12] if has_args else True) if len(args)>12 else True
do_elog = True if (has_args and (not is_embedded) and (plt is not None)) else False
print has_args, is_embedded, do_elog
print "WireScan parameters: ", prefix, scan_type, scan_range, cycles, n_shot, bpms, blms, bkgrd, bunch
print "WireScan parameters: ", prefix, scan_type, scan_range, cycles, n_shot, bpms, blms, bkgrd, bunch, adaptive
#Adaptive mode parameters
MIN_GAIN, MAX_GAIN = 0.5, 1.1
INCREMENT_FACTOR = 0.5
SCAN_RANGE_FACTOR = 6
MAX_RANGE_STEP = 300
FILTER_BEAM_OK = True
SET_BLM_WS_MODE = True
SET_BLM_WS_SETTLING_TIME = 2.0
SET_BLM_WS_BS_READBACK_TIMEOUT = 10000 #ms
@@ -116,18 +125,27 @@ filename = get_exec_pars().path
#Stream creation
print "Starting stream..."
st = Stream("pulse_id", dispatcher)
for c in channels:
if c[1].endswith("LOSS_SIGNAL_RAW"):
st.addWaveform(c[0], c[1], int(100.0 / get_repetition_rate()), 0)
else:
st.addScalar(c[0], c[1], int(100.0 / get_repetition_rate()), 0)
st.initialize()
st.start()
st.waitCacheChange(10000) #Wait stream be running before starting scan
for retry in range(STREAM_CREATION_RETRIES):
try:
print "Starting stream..."
st = Stream("pulse_id", dispatcher)
for c in channels:
if c[1].endswith("LOSS_SIGNAL_RAW"):
st.addWaveform(c[0], c[1], int(100.0 / get_repetition_rate()), 0)
else:
st.addScalar(c[0], c[1], int(100.0 / get_repetition_rate()), 0)
st.initialize()
st.start()
st.waitCacheChange(10000) #Wait stream be running before starting scan
break
except:
print "Error starting stream"
print sys.exc_info()[1]
if retry >= (STREAM_CREATION_RETRIES-1):
raise
else:
print "Retrying"
class Timestamp(Readable):
def read(self):
return st.getTimestamp()
@@ -147,6 +165,8 @@ rec =None
def check_end_scan(record, scan):
global scan_complete,cur_cycle
global rec
if (rec is None) and (record is not None):
print "Started receiving from stream"
rec = record
if record[4]<1:
print "Data aquisition completed"
@@ -163,7 +183,9 @@ def check_end_scan(record, scan):
for i in range (len(blms)):
plt.getSeries(i).appendData(position, record[5 + i])
scanner.park(wait=True)
if scanner.take() != "At start":
print "Not at start: parking scanner"
scanner.park(wait=True)
#Process background
def do_background():
#Store Background
@@ -186,17 +208,18 @@ def set_blm_gain(scan_type, index):
scan_type = (WireScanner.WireX1 if index == 0 else WireScanner.WireY1)
if scan_type == WireScanner.Set2:
scan_type = (WireScanner.WireX2 if index == 0 else WireScanner.WireY2)
cfg_gain = get_setting(blms[0] + "GainWs" + scan_type)
cfg_gain = read_ws_gain (blms[0], scan_type)
print "cfg_gain = " , cfg_gain
if cfg_gain is not None:
set_blm_ws_gain(blms[0],cfg_gain)
print "Set = " , blms[0]
print "Set = " , blms[0], cfg_gain
#Scan
def do_scan(index):
global scan_complete, cur_cycle, wire
global scan_complete, cur_cycle, wire, rec
rec =None
wire = "y" if (index==1) or (scan_type in [WireScanner.WireY1, WireScanner.WireY2]) else "x"
if wire == "x":
scanner.set_velocity(velocity_x)
@@ -248,8 +271,13 @@ def do_scan(index):
#s=plt.getSeries(0)
#indexes = sorted(range(len(s.x)),key=lambda x:s.x[x])
#x,y = [s.x[x] for x in indexes], [s.y[x] for x in indexes]
#plot(y, xdata = x)
#plot(y, xdata = x)
if rec is None:
raise Exception("Didn't receive from stream")
if not scan_complete:
raise Exception("Scan didn't conmplete")
print "Calculating"
rec
calculate()
print "Ok"
img_file = os.path.abspath(filename + "_" + get_exec_pars().group[0:1] + ".png")
@@ -259,6 +287,7 @@ def do_scan(index):
snapshots.append(img_file)
print "Finished"
pars = []
msg = ""
ret = []
def calculate():
@@ -271,7 +300,7 @@ def calculate():
samples = [[], [], [], [], [], []]
for cycle in range (cycles):
pos_path = wire+"_" + ("%04d" % (cycle+1)) + "/data/w_pos"
print "Loading ", pos_path
print "Loading: ", pos_path
pos = load_data(pos_path+"/value")
path = wire+"_" + ("%04d" % (cycle+1)) + "/data/blm" + str(i+1)
print "Loading ", path
@@ -342,7 +371,63 @@ def calculate():
except:
traceback.print_exc()
gauss = [0.0] * SAMPLE_CHANNEL_SIZE
scanner.set_out_gauss(bunch,wire,gauss)
scanner.set_out_gauss(bunch,wire,gauss)
#com = stats[i][2][0]
#sigma = stats[i][3][0]
#saturration_loss = get_blm_saturation(blms[i])
#current_gain = get_blm_ws_gain(blms[i]) #read_ws_gain (blms[i], wire)
#current_loss = get_blm_loss(blms[i])
#global pars
#pars = [blms, com, sigma, saturration_loss, current_gain, current_loss]
com = stats[i][0][0]
rms = stats[i][1][0]
mn = stats[i][2][0]
sigma = stats[i][3][0]
(cur_x_range_min, cur_x_range_max) = (scan_range[0], scan_range[1]) if wire == "x" else (scan_range[2], scan_range[3])
x_range_min, x_range_max = mn - SCAN_RANGE_FACTOR * sigma, mn + SCAN_RANGE_FACTOR * sigma
off_min, off_max = (x_range_min - cur_x_range_min), (x_range_max - cur_x_range_max)
valid_range = (abs(off_min) < MAX_RANGE_STEP) and (abs(off_max) < MAX_RANGE_STEP)
valid_fitting = (com!=float('NaN')) and (mn!=float('NaN')) and \
(com>cur_x_range_min) and (com<cur_x_range_max) and \
(mn>cur_x_range_min) and (mn<cur_x_range_max)
print "Scan range: ", (cur_x_range_min, cur_x_range_max)
print "Valid fitting: ", valid_fitting
print "Valid range: ", valid_range
if adaptive > 0 and \
valid_fitting and \
(scan_type not in [WireScanner.Set1, WireScanner.Set2]):
new_gain, new_voltage = None, None
#desired_loss= 800
desired_loss= get_blm_saturation(blms[i])
current_voltage = get_blm_ws_gain(blms[i]) #read_ws_gain (blms[i], scan_type)
#current_loss = float(get_blm_loss(blms[i]))
current_loss = max(sig)
print "current_loss=", current_loss
current_gain = get_gain_from_voltage(current_voltage)
dg = current_gain * (desired_loss/ current_loss -1)
new_gain = current_gain + dg * INCREMENT_FACTOR
new_voltage = get_voltage_from_gain(new_gain)
new_voltage = max(min(new_voltage, MAX_GAIN),MIN_GAIN)
print "dg=", dg, " ng=", new_gain
if (new_voltage is not None) and (new_voltage != current_voltage):
logstr= "Adapting " + str(blms[i]) + " - " + str(scan_type) + "gain: " + str(new_voltage)
print logstr
log(logstr)
write_ws_gain(blms[i], scan_type, new_voltage)
set_blm_ws_gain(blms[i], new_voltage)
if adaptive > 1:
if valid_range:
new_min, new_max = (cur_x_range_min + INCREMENT_FACTOR*off_min), (cur_x_range_max + INCREMENT_FACTOR*off_max)
logstr= "Adapting range: " , new_min , " to " , new_max
set_wire_scan_range(prefix, scan_type, new_min, new_max)
print logstr
log(logstr)
except Exception, e:
print >> sys.stderr, traceback.format_exc()
msg += str(e)+ "\n"
@@ -374,7 +459,7 @@ try:
print "Reading background..."
do_background()
stream_filter = scanner.curr_cycl.get_name() + ">0"
if FILTER_BEAM_OK:
if filter_beam_ok:
stream_filter = stream_filter + " AND SIN-CVME-TIFGUN-EVR0:BEAMOK == 1"
st.setFilter(stream_filter)
print "Executing scan 1..."
@@ -383,6 +468,10 @@ try:
print "Executing scan 2..."
do_scan(1)
finally:
try:
scanner.park(wait=False)
except:
pass
if SET_BLM_WS_MODE and len(blms)>0:
stop_blm_ws(blms[0])
print "Closing scanner"
+59 -61
View File
@@ -29,44 +29,20 @@ OPT_STEP = 0.02
print "WireScanCalibration parameters: ", ws_prefix, ws_wire, range_start, range_end, n_shot, saturation, scan_range_factor, initial_gain
###################################################################################################
# Utilities
###################################################################################################
def write_ws_gain(val):
set_setting(ws_blm + "GainWs" + ws_wire, val)
def read_ws_gain():
return get_setting(ws_blm + "GainWs" + ws_wire)
def get_gain():
return get_blm_ws_gain(ws_blm)
def set_gain(val):
set_blm_ws_gain(ws_blm,val)
def set_wire_scan_range(wire, start, end):
sel = {'X1':"W1X" , 'Y1': "W1Y", 'X2':"W2X", 'Y2' : "W2Y"}
start = min (max(start, -2000), 2000.0)
end = min (max(end, -2000), 2000.0)
caput((ws_prefix + ":" + sel[wire] +"_START_SP"), start)
caput((ws_prefix + ":" + sel[wire] +"_END_SP"), end)
###################################################################################################
# Find COM
###################################################################################################
print "--------------- Find COM --------------- "
set_status("Performing wire scan to find initial COM...")
write_ws_gain(initial_gain)
set_gain(initial_gain)
write_ws_gain(ws_blm,ws_wire, initial_gain)
set_blm_ws_gain(ws_blm, initial_gain)
print "Setting gain=", initial_gain
#Calculate speed
x_min, x_max = range_start, range_end
#rr = get_repetition_rate()
#ws_speed = (x_max- x_min)*rr/n_shot
args = [ ws_prefix , ws_wire, [x_min, x_max, x_min, x_max], 1, n_shot, [], [ws_blm], 10, plt, False,1]
args = [ ws_prefix , ws_wire, [x_min, x_max, x_min, x_max], 1, n_shot, [], [ws_blm], 10, plt, False,1,0]
ret = run("Diagnostics/WireScan", args)
[rms_com, rms_sigma, com, sigma, pos_path, path] = ret
@@ -96,74 +72,96 @@ print "Starting stream..."
set_status("Creating stream for gain search..." )
st = Stream("blm_stream", dispatcher)
ch = ws_blm + ":B1_LOSS"
st.addScalar(ch, ch, int(100.0 / get_repetition_rate()), 0)
ch_int = ws_blm + ":B1_LOSS"
ch_raw = ws_blm + ":LOSS_SIGNAL_RAW"
st.addScalar(ch_int, ch_int, int(100.0 / get_repetition_rate()), 0)
st.addWaveform(ch_raw, ch_raw, int(100.0 / get_repetition_rate()), 0)
st.addScalar("blm1_ws_mode", ws_blm + ":WS_RUNNING", int(100.0 / get_repetition_rate()), 0)
st.initialize()
st.start()
st.waitCacheChange(10000) #Wait stream be running before starting scan
baseline=get_blm_baseline(ws_blm)
def change_blm_ws_gain(gain):
set_gain(gain)
#stop_blm_ws(ws_blm)
#st.getChild("blm1_ws_mode").waitValue(0, SET_BLM_WS_BS_READBACK_TIMEOUT)
#start_blm_ws(ws_blm, 600.0)
#st.getChild("blm1_ws_mode").waitValue(1, SET_BLM_WS_BS_READBACK_TIMEOUT)
set_blm_ws_gain(ws_blm, gain)
time.sleep(0.25)
def get_loss():
global ch
def get_loss_int():
samples = []
for i in range(10):
st.waitCacheChange(-1)
val = st.getValue(ch)
val = st.getValue(ch_int)
samples.append(val)
samples.remove(max(samples))#Remove max value
return max(samples)
def get_loss_range():
st.waitCacheChange(-1)
raw = st.getValue(ch_raw)
m = min(raw)
ret = (baseline-m)/baseline
ret = min(max(ret, 0.0), 1.0)
return ret
change_blm_ws_gain(MIN_GAIN)
time.sleep(2.0)
start_gain = get_gain()
pos = start_val = get_loss()
loss = get_loss()
pos = read_ws_gain(ws_blm, ws_wire)
loss = get_loss_int()
print "Current Gain = ", pos, "\nStart Loss = ", loss
"""
target = saturation * 0.8
print "Start Gain = ", start_gain
print "Start Loss = ", start_val
print "Target = ", target
set_status("Searching gain to match peak losses of " + str(target) + "...")
set_status("Searching gain to match peak losses of " + str(target) + "..."
try:
#Search loop
for pos in frange(MIN_GAIN, MAX_GAIN, OPT_STEP, True):
change_blm_ws_gain(pos)
loss = get_loss()
loss = get_loss_int()
print "Pos = ", pos, " Loss = ", loss
if loss>=target:
break
#stop_blm_ws(ws_blm)
break
finally:
stop_blm_ws(ws_blm)
print "Final Gain: ", pos
print "Final Loss: ", loss
print "Final Gain: ", pos, "\nFinal Loss: ", loss
result = "Loss value for final gain: " + str(loss) + " - Target value: " + str(target) + "\n"
if loss<target:
result = result + "Cannot reach target value. Setting gain to " + str(pos) + "\n"
else:
result = result + "Optimized gain: " + str(pos) + "\n"
"""
target = 0.9
loss_range = 0.0
blm_saturation = None
set_status("Searching loss range of " + str(target) + "...")
try:
#Search loop
for pos in frange(MIN_GAIN, MAX_GAIN, OPT_STEP, True):
change_blm_ws_gain(pos)
time.sleep(0.1)
loss_range = get_loss_range()
print "Pos = ", pos, " Loss Range= ", loss_range
if loss_range>=target:
print "Done..."
blm_saturation = get_loss_int()
set_blm_saturation(ws_blm,blm_saturation)
break
finally:
stop_blm_ws(ws_blm)
print "Final Gain: ", pos, "\nFinal Loss Range: ", loss_range , "\nBLM satiuration: ", blm_saturation
result = "Loss range for final gain: " + str(loss_range) + " - Target value: " + str(target) + "\n"
if blm_saturation is None:
result = result + "Cannot reach target value. Setting gain to " + str(pos) + "\n"
else:
result = result + "Optimized gain: " + str(pos) + " - BLM satiuration: " +str(blm_saturation) + "\n"
st.close()
write_ws_gain(pos)
write_ws_gain(ws_blm, ws_wire, pos)
time.sleep(1.0)
###################################################################################################
@@ -176,12 +174,12 @@ print "--------------- Optimize scan range --------------- "
set_status("Performing scan with optimal gain to define optimal range..." )
#caget(ws_blm+":SAT_RAW_SUM")
args = [ ws_prefix , ws_wire, [x_min, x_max, x_min, x_max], 1, n_shot, [], [ws_blm], 10, plt, False,1]
args = [ ws_prefix , ws_wire, [x_min, x_max, x_min, x_max], 1, n_shot, [], [ws_blm], 10, plt, False,1,0]
[rms_com, rms_sigma, com, sigma, pos_path, path] = run("Diagnostics/WireScan", args)
x_range_min, x_range_max = com - scan_range_factor * sigma, com + scan_range_factor * sigma
print "Optimized range: " , x_range_min , " to " , x_range_max
set_wire_scan_range(ws_wire, x_range_min, x_range_max)
set_wire_scan_range(ws_prefix, ws_wire, x_range_min, x_range_max)
result = result + "Optimized range: " + str(x_range_min) + " to " + str(x_range_max)