This commit is contained in:
root
2018-03-06 08:21:09 +01:00
parent 8d18ec8059
commit 1bcb32c8f2
32 changed files with 1141 additions and 1121 deletions
+6 -6
View File
@@ -2,8 +2,8 @@ import ch.psi.pshell.epics.ChannelDouble as ChannelDouble
dry_run = False
do_elog = True
base_name = "SINEG01-DICT009" # SINEG01-DICT009 S10DI01-DICT113 SARMA01-DICT482 SARBD01-DICT599
dev_name = "SINEG01-DICT215" # SINEG01-DICT215 S10DI01-DICT025 SARMA01-DICT090 SARBD01-DICT030
base_name = "SARBD01-DICT599" # SINEG01-DICT009 S10DI01-DICT113 SARMA01-DICT482 SARBD01-DICT599
dev_name = "SARBD01-DICT030" # SINEG01-DICT215 S10DI01-DICT025 SARMA01-DICT090 SARBD01-DICT030
run("CPython/wrapper")
@@ -22,10 +22,10 @@ V.initialize()
t0 = t.read()
start = 2.2
stop = 7.0
start = 3
stop = 10
step = 0.1
nb = 10
nb = 4
lat = 0.150
plt = plot(None, title="Output")[0]
@@ -64,7 +64,7 @@ finally:
try:
i_max = charge.index(max(charge))
min_i, max_i = max(i_max-30, 0), min(i_max+31, len(charge))
(delay_max, charge_max, delay_fit, charge_fit) = extremum(delay[min_i:max_i], charge[min_i:max_i])
(delay_max, charge_max, delay_fit, charge_fit, R2) = extremum(delay[min_i:max_i], charge[min_i:max_i])
print delay_max, charge_max
except:
raise Exception("Fit failure")
+52 -30
View File
@@ -19,17 +19,18 @@ blms = args[6] if is_panel else get_wire_scanners_blms(prefix)
bkgrd = args[7] if is_panel else 10
plt = args[8] if is_panel else plot(None, title = "Wire Scan")[0]
save_raw = args[9] if is_panel else False
do_elog = True if is_panel else True
do_elog = False if (plt is None) else (True if is_panel else True)
print "WireScan parameters: ", prefix, scan_type, scan_range, cycles, velocity, bpms, blms, bkgrd
#Plot setup
plt.clear()
plt.removeMarker(None)
plt.getAxis(plt.AxisId.X).setLabel("Position");
plt.getAxis(plt.AxisId.Y).setLabel("");
plt.getAxis(plt.AxisId.Y2).setLabel("");
plt.setLegendVisible(True);
if plt is not None:
plt.clear()
plt.removeMarker(None)
plt.getAxis(plt.AxisId.X).setLabel("Position");
plt.getAxis(plt.AxisId.Y).setLabel("");
plt.getAxis(plt.AxisId.Y2).setLabel("");
plt.setLegendVisible(True);
snapshots = []
#Creating WireScanner object
@@ -44,10 +45,11 @@ channels = [("m_pos", scanner.motor_bs_readback.get_name()),
("scanning", scanner.status_channels[0].get_name())]
for i in range (len(blms)):
channels.append (("blm" + str(i+1), blms[i] + ":B1_LOSS"))
series = LinePlotSeries(blms[i], None, min(i+1, 2))
plt.addSeries(series)
series.setLinesVisible(False)
series.setPointSize(2)
if plt is not None:
series = LinePlotSeries(blms[i], None, min(i+1, 2))
plt.addSeries(series)
series.setLinesVisible(False)
series.setPointSize(2)
if save_raw:
channels.append (("blm" + str(i+1) + "_raw" , blms[i] + ":LOSS_SIGNAL_RAW"))
for i in range (len(bpms)):
@@ -106,9 +108,10 @@ def check_end_scan(record, scan):
if record[3] != cur_cycle:
cur_cycle = record[3]
get_context().dataManager.splitScanData(scan)
#for s in plt.getAllSeries(): s.clear()
for i in range (len(blms)):
plt.getSeries(i).appendData(position, record[5 + i])
#if plt is not None: for s in plt.getAllSeries(): s.clear()
if plt is not None:
for i in range (len(blms)):
plt.getSeries(i).appendData(position, record[5 + i])
#Process background
def do_background():
@@ -122,30 +125,42 @@ def do_background():
path = get_exec_pars().group + "/"+ r.getReadables()[i].name
set_attribute(path, "Mean", mean(d))
set_attribute(path, "Sigma", stdev(d) )
#Scan
def do_scan(index):
global scan_complete, cur_cycle, wire
wire = "y" if (index==1) or (scan_type in [WireScanner.WireY1, WireScanner.WireY2]) else "x"
set_exec_pars(group=wire+"_{count}", reset=True)
scanner.set_selection(get_scan_selection(scan_type, index))
if wire == "x":
plt.getAxis(plt.AxisId.X).setRange(scan_range[0], scan_range[1])
else:
plt.getAxis(plt.AxisId.X).setRange(scan_range[2], scan_range[3])
if plt is not None:
if wire == "x":
plt.getAxis(plt.AxisId.X).setRange(scan_range[0], scan_range[1])
else:
plt.getAxis(plt.AxisId.X).setRange(scan_range[2], scan_range[3])
scanner.init(wait=True)
scanner.curr_cycl.write(0)
scan_complete=False
cur_cycle = 1.0
for s in plt.getAllSeries():
s.clear()
plt.removeMarker(None)
if plt is not None:
for s in plt.getAllSeries():
s.clear()
plt.removeMarker(None)
try:
scanner.scan() #scanner.waitState(State.Busy, 60000) Not needed as stream filter will make the wait
st.getChild("scanning").waitValue(1.0, 10000)
mscan (st, [w_pos()] + st.getReadables() + [Timestamp(),], -1, -1, take_initial = True, after_read = check_end_scan)
#print st.getValues()
#TODO: Check what the problem is
#mscan (st, [w_pos(),] + st.getReadables() + [Timestamp(),], -1, -1, take_initial = True, after_read = check_end_scan)
l=[w_pos()] ; l.extend(st.getReadables()); l.append(Timestamp())
mscan (st, l, -1, -1, take_initial = True, after_read = check_end_scan)
#tscan([w_pos()] + st.getReadables() + [Timestamp(),], 10, 0.5)
except:
print sys.exc_info()[1]
if not scanner.isReady():
print "Aborting scan"
scanner.abort()
@@ -160,10 +175,12 @@ def do_scan(index):
calculate()
img_file = os.path.abspath(filename + "_" + get_exec_pars().group[0:1] + ".png")
time.sleep(0.1) #Give some time to plot finish (async)
plt.saveSnapshot(img_file, "png")
snapshots.append(img_file)
if plt is not None:
plt.saveSnapshot(img_file, "png")
snapshots.append(img_file)
msg = ""
ret = []
def calculate():
global msg
stats = []
@@ -172,8 +189,9 @@ def calculate():
try:
bg = get_attributes("background/blm" + str(i+1))["Mean"] if bkgrd>0 else 0.0
samples = [[], [], [], []]
for cycle in range (cycles):
pos = load_data(wire+"_" + ("%04d" % (cycle+1)) + "/w_pos")
for cycle in range (cycles):
pos_path = wire+"_" + ("%04d" % (cycle+1)) + "/w_pos"
pos = load_data(pos_path)
path = wire+"_" + ("%04d" % (cycle+1)) + "/blm" + str(i+1)
data = load_data(path)
sp = blm_remove_spikes(data)
@@ -194,14 +212,16 @@ def calculate():
#from mathutils import Gaussian
#g = Gaussian(amp, com, sigma)
#gauss = [g.value(v)+off for v in pos]
#plot([data, sp, sig, gauss], ["data", "sp", "signal", "gauss", ], xdata = pos, title="Fit blm" + str(i+1) + " - " + str(cycle+1))
#plot([data, sp, sig, gauss], ["data", "sp", "signal", "gauss", ], xdata = pos, title="Fit blm" + str(i+1) + " - " + str(cycle+1))
ret.extend([rms_com, rms_sigma, com, sigma, get_exec_pars().path + "|"+ pos_path, get_exec_pars().path + "|"+ path])
stats.append([])
for sample in samples:
sample = [v for v in sample if v is not None]
stats[i].append( (mean(sample), stdev(sample)) if len(sample)>0 else (float("nan"), float("nan")) )
plt.addMarker(stats[i][2][0], None, "Gcom=" + "%.2f" % stats[i][2][0], plt.getSeries(i).color)
plt.addMarker(stats[i][0][0], None, "Rcom=" + "%.2f" % stats[i][0][0], plt.getSeries(i).color.brighter())
if plt is not None:
plt.addMarker(stats[i][2][0], None, "Gcom=" + "%.2f" % stats[i][2][0], plt.getSeries(i).color)
plt.addMarker(stats[i][0][0], None, "Rcom=" + "%.2f" % stats[i][0][0], plt.getSeries(i).color.brighter())
msg += " RMS COM: " + "%.4f" % stats[i][0][0] + " +- " +"%.4f" % stats[i][0][1] + "\n" #unichr(0x03C3) + "="
msg += " RMS Sigma: " + "%.4f" % stats[i][1][0] + " +- " + "%.4f" % stats[i][1][1] + "\n"
@@ -243,3 +263,5 @@ if do_elog:
log_msg = log_msg + "\n" + msg
elog("Wire Scan", log_msg, snapshots)
set_exec_pars(open=False)
set_return(ret)
+9
View File
@@ -0,0 +1,9 @@
Eph1 = 2365
Eph2 = 2150
undlist = (SARUN03,SARUN04,SARUN05,SARUN06,SARUN07,SARUN08,SARUN09,SARUN10,SARUN11,SARUN12,SARUN13,SARUN14,SARUN15)
for und in undlist
K1 = caget(und + "-RSYS:SET-SCAN-START")
K2 = SQRT(2*(Eph1/Eph2*(1+0.5*K1^2)-1))
+1 -1
View File
@@ -1,4 +1,4 @@
GAP = "SARUN03-UIND030"
GAP = "SARUN14-UIND030"
SAMPLES = 20
TOLERANCE = 0.01
TIMEOUT = 10.0
+10 -8
View File
@@ -1,24 +1,26 @@
GAP = "SARUN07-UPHS060"
SAMPLES = 20
GAP = "SARUN03-UPHS060"
SAMPLES = 10
TOLERANCE = 0.01
TIMEOUT = 10.0
intensity = Channel("SARFE10-PBPG050:PHOTON-ENERGY-PER-PULSE-US", alias = "gas det")
#intensity = Channel("SARFE10-PBPG050:PHOTON-ENERGY-PER-PULSE-US", alias = "gas det")
#gap = Channel(GAP + ":GAP_SP", alias = "gap")
gap = Channel(GAP + ":GAP_SP", alias = "gap")
readout = Channel(GAP + ":GAP")
av = create_averager(intensity, SAMPLES, interval = -1, name = None)
av = create_averager("ca://SARFE10-PBPG050:PHOTON-ENERGY-PER-PULSE-US",
SAMPLES, interval =0.1, name = "gas det")
def before(position, scan):
caput(GAP + ":GO", 1)
start = time.time()
while abs(readout.read() - gap.read()) > TOLERANCE:
start = time.time()
while abs(readout.read() - GAP.read()) > TOLERANCE:
time.sleep(0.1)
if time.time() - start > TIMEOUT:
raise Exception ("Timeout waiting gap change")
ret = lscan (gap, av, 17.5, 19.5, 20, latency=20.0, before_read=before)
ret = lscan ("ca://" + GAP + ":GAP_SP?name=gap", av, 14, 16, 20,
latency=20.0, before_read=before)
#run("CPython/wrapper")
+7 -13
View File
@@ -57,19 +57,13 @@ phase.config.save()
phase.initialize()
phase0 = phase.read()
##Camtool setup
#kill_camtool()
#check_camtool()
#camtool.start(camera_name)
#wait_camtool_message()
#x = camtool.stream.getChild("x_fit_mean")
#dx = camtool.stream.getChild("x_fit_standard_deviation")
#Camera setup
cam_server.start(camera_name)
wait_cam_server_message()
x = cam_server.stream.getChild("x_fit_mean")
dx = cam_server.stream.getChild("x_fit_standard_deviation")
#x = cam_server.stream.getChild("x_fit_mean")
#dx = cam_server.stream.getChild("x_fit_standard_deviation")
x = cam_server.stream.getChild("x_center_of_mass")
dx = cam_server.stream.getChild("x_rms")
#Creating averagers
x_averager = create_averager(x, nb, -1) # -1 event based, waits for the next value
@@ -105,9 +99,9 @@ dp = [abs(A) * val.mean for val in r.getReadable(1)]
try:
i_max = p.index(max(p))
i_min = dp.index(min(dp))
min_i, max_i = max(i_max-5, 0), min(i_max+6, len(p))
min_i, max_i = max(i_max-8, 0), min(i_max+6, len(p))
(ph_p_max, p_max, ph_p_fit, p_fit, p_R2) = extremum(ph[min_i:max_i], p[min_i:max_i])
min_i, max_i = max(i_min-5, 0), min(i_min+6, len(dp))
min_i, max_i = max(i_min-8, 0), min(i_min+6, len(dp))
(ph_dp_min, dp_min, ph_dp_fit, dp_fit, dp_R2) = extremum(ph[min_i:max_i], dp[min_i:max_i])
plt.addSeries(LinePlotErrorSeries("Momentum Fit", plt.getSeries(0).color))
plt.addSeries(LinePlotErrorSeries("Momentum Spread Fit", plt.getSeries(1).color, 2))
@@ -133,7 +127,7 @@ set_attribute(get_exec_pars().group + "/dp", "dp fit R2", dp_R2)
#Elog entry
if do_elog:
if get_option("Generated data file:\n" + get_exec_pars().path +"\n\n" + "Save to ELOG?", "YesNo") == "Yes":
Laser = str(caget("SLGTV-LMTO-M055:MOT-KNOWN-POS"))
Laser = str(caget("SLG-LGEN:WHICH_LASER"))
log_msg = "Data file: " + get_exec_pars().path + "\n\n"
log_msg = log_msg + "Laser: " + Laser + "\n"
if Laser == "Alcor":
+40 -22
View File
@@ -15,27 +15,43 @@ stop = caget(station + "-RSYS:SET-SCAN-STOP")
step = caget(station + "-RSYS:SET-SCAN-STEP")
lat = caget(station + "-RSYS:SET-SCAN-WAIT-TIME")
nb = caget(station + "-RSYS:SET-NUM-AVERAGE")
disp = caget(bpm_ch + ":DISPERSION")
energy0 = caget(bpm_ch + ":ENERGY-OP")
A = energy0 / disp / 1e3
disp = caget(bpm_ch + ":DISPERSION-OP")
def mbnd(bpm_ch):
return {
'SINLH02-DBPM210': 'SINLH02-MBND100',
'SINLH02-DBPM240': 'SINLH02-MBND100',
'SINBC02-DBPM140': 'SINBC02-MBND100',
'SINBC02-DBPM320': 'SINBC02-MBND100',
'S10DI01-DBPM020': 'S10DI01-MBND100',
'S10BC02-DBPM140': 'S10BC02-MBND100',
'S10BC02-DBPM320': 'S10BC02-MBND100',
'SARCL02-DBPM110': 'SARCL02-MBND100',
'SARCL02-DBPM220': 'SARCL02-MBND100',
'SARCL02-DBPM260': 'SARCL02-MBND100',
'SARCL02-DBPM330': 'SARCL02-MBND100',
'SARCL02-DBPM470': 'SARCL02-MBND100'
}[bpm_ch]
p0 = caget(mbnd(bpm_ch) + ":P-READ")
energy0 = p0 - 0.511
A = energy0 / (disp * 1000)
B = energy0
phase = Positioner("Phase", station + "-RSYS:SET-VSUM-PHASE", station + "-RSYS:GET-VSUM-PHASE")
phase.config.minValue =-360.0
phase.config.minValue =-90.0
phase.config.maxValue = 360.0
phase.config.precision = 4
phase.config.rotation = False
phase.config.rotation = True
phase.config.resolution = 0.1
phase.initialize()
V = ChannelDouble("Amplitude Readback", station + "-RSYS:GET-VSUM-AMPLT")
V.initialize()
P = ChannelDouble("Power Readback", station + "-RSYS:GET-KLY-POWER")
V.initialize()
P.initialize()
if dry_run:
x = ChannelDouble("BPM-X", bpm_ch + ":X1-SIMU")
else:
x = ChannelDouble("BPM-X", bpm_ch + ":X1")
x.initialize()
phase0 = phase.read()
phase0 = phase.read() % 360
caput(station + "-RSYS:GET-FIT-PHASE-ARRAY", to_array([0.0],'d'))
caput(station + "-RSYS:GET-FIT-ENERGY-ARRAY", to_array([0.0],'d'))
caput(station + "-RSYS:GET-ONCREST-VSUM-PHASE", float('nan'))
@@ -56,9 +72,11 @@ def after(rec):
try:
phase.write(start)
time.sleep(1.0)
x_averager = create_averager(x, nb, 0.100)
x_averager = create_averager(x, nb, lat)
r = lscan(phase, x_averager, start, stop, step, latency=lat, after_read = after)
rf_phase = r.getPositions(0)
if start < 0:
rf_phase = [((ph + 90) % 360) -90 for ph in rf_phase ]
energy = [A * val.mean + B for val in r.getReadable(0)]
caput(station + "-RSYS:GET-ENERGY-ARRAY", to_array(energy, 'd'))
caput(station + "-RSYS:GET-PHASE-ARRAY", to_array(rf_phase,'d'))
@@ -66,17 +84,17 @@ try:
run("CPython/wrapper")
(fit_amplitude, fit_phase_deg, fit_offset, ph_crest, fit_x, fit_y) = hfitoff(energy , rf_phase)
except:
raise Exception("Fit failure")
# plt = plot(None,name="phase scan")[0]
# # This only works when pshell is visible not in server mode to be fixed
# if plt is not None:
# plt.getSeries(0).setData(to_array(rf_phase,'d'), to_array(energy,'d'))
# plt.getSeries(0).setPointSize(6)
# plt.getSeries(0).setLinesVisible(False)
# plt.addSeries(LinePlotSeries("fit"))
# plt.getSeries(1).setData(fit_x, fit_y)
# plt.getSeries(1).setPointsVisible(False)
# plt.setLegendVisible(True)
raise Exception("Fit failure")
plt = plot(None,name="phase scan")[0]
if plt is not None:
plt.getSeries(0).setData(to_array(rf_phase,'d'), to_array(energy,'d'))
plt.getSeries(0).setPointSize(6)
plt.getSeries(0).setLinesVisible(False)
plt.addSeries(LinePlotSeries("fit"))
plt.getSeries(1).setData(fit_x, fit_y)
plt.getSeries(1).setPointsVisible(False)
plt.setLegendVisible(True)
ph_crest = ph_crest % 360
phase.write(ph_crest)
time.sleep(lat)
Ampl = V.read()
@@ -95,7 +113,7 @@ finally:
x.close()
phase_corr = caget(station + "-RSYS:GET-VSUM-PHASE-OFFSET-CORR")
phase_offset = 90.0 - ph_crest - phase_corr
amplitude_scale = fit_amplitude / Ampl
amplitude_scale = fit_amplitude / Ampl if Ampl != 0 else 0.0
power_scale = Power / fit_amplitude**2 if fit_amplitude != 0 else 0.0
caput(station + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE-CALC", phase_offset)
caput(station + "-RSYS:SET-VSUM-AMPLT-SCALE-CALC", amplitude_scale)
@@ -120,12 +138,12 @@ set_attribute(get_exec_pars().group + "/BPM-X averager" , "Unit", "mm"
#Elog entry
if do_elog:
title = "Phase scan" + station
title = "Phase scan " + station
log_msg = "Data file: " + get_exec_pars().path + "\n"
log_msg = log_msg + "On-crest VS phase: %0.2f" % ph_crest + " deg \n"
log_msg = log_msg + "Energy gain: %0.3f" % fit_amplitude + " MeV \n"
log_msg = log_msg + "VS-phase offset: %0.2f" % phase_offset + " deg \n"
log_msg = log_msg + "Amplitude scale: %0.3f" % amplitude_scale + " MV \n"
log_msg = log_msg + "Power scale: %0.6f" % power_scale + " MW/MV^2"
attachments = get_plot_snapshots()
attachments = get_plot_snapshots(size=(600,400))
elog(title, log_msg, attachments)
+2 -2
View File
@@ -29,7 +29,7 @@ if n > 0:
title = "Set RF calibration:" + station
log_msg = ""
if (phase_set == 'True'): log_msg = log_msg + station + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE: %0.2f" % phase_offset + " deg (was %0.2f" % phase_offset_old + " deg)\n"
if (ampli_set == 'True'): log_msg = log_msg + station + "-RSYS:SET-VSUM-AMPLT-SCALE: %0.3f" % amplitude_scale + " MV (was %0.3f" % amplitude_scale_old + " MV)\n"
if (power_set == 'True'): log_msg = log_msg + station + "-RSYS:SET-VOLT-POWER-SCALE: %0.5f" % power_scale + " MW/MV^2 (was %0.5f" % power_scale_old + " MW/MV^2)"
if (ampli_set == 'True'): log_msg = log_msg + station + "-RSYS:SET-VSUM-AMPLT-SCALE: %0.3f" % amplitude_scale + " MV (was %0.3f" % amplitude_scale_old + " MV)\n"
if (power_set == 'True'): log_msg = log_msg + station + "-RSYS:SET-VOLT-POWER-SCALE: %0.5f" % power_scale + " MW/MV^2 (was %0.5f" % power_scale_old + " MW/MV^2)"
attachments = []
elog(title, log_msg, attachments)
+21
View File
@@ -0,0 +1,21 @@
import random
positioner = DummyPositioner("positioner")
class Sensor(Readable):
def __init__(self):
self.index = -1
def read(self):
#time.sleep(0.001)
self.index +=1
return self.index
#noise = (random.random() - 0.5) / 10.0
#return math.sin(time.time()) + noise
sensor = Sensor()
ret = lscan(positioner, sensor, scan_start, scan_stop, scan_steps, 0.01)
av = mean(ret.getReadable(0))
set_exec_pars(open=False)
set_return([av, ret.path + sensor.name])
+259
View File
@@ -0,0 +1,259 @@
import traceback
is_panel = get_exec_pars().source != CommandSource.ui #Must be checked before callin "run"
BPM_SENSORS = [("x","X1"), ("y","Y1"), ("q","Q1")] #(logic name sufix, channel sufix)
#Paramter parsing
prefix = args[0] if is_panel else "S30CB09-DWSC440" #"SINDI01-DWSC090"
scan_type = args[1] if is_panel else "X1"
scan_range = args[2] if is_panel else [-200, 200, -200, 200]
cycles = args[3] if is_panel else 3
velocity = args[4] if is_panel else 200
bpms = args[5] if is_panel else ["BPM1", "BPM2"]
blms = args[6] if is_panel else ["BLM1", "BLM2"]
bkgrd = args[7] if is_panel else 10
plt = args[8] if is_panel else plot(None, title = "Wire Scan")[0]
save_raw = args[9] if is_panel else False
do_elog = False if (plt is None) else (True if is_panel else False)
print "WireScan parameters: ", prefix, scan_type, scan_range, cycles, velocity, bpms, blms, bkgrd
#Plot setup
if plt is not None:
plt.clear()
plt.removeMarker(None)
plt.getAxis(plt.AxisId.X).setLabel("Position");
plt.getAxis(plt.AxisId.Y).setLabel("");
plt.getAxis(plt.AxisId.Y2).setLabel("");
plt.setLegendVisible(True);
snapshots = []
#Creating WireScanner object
print "Creating scanner..."
scanner = DummyPositioner("scanner")
class Sensor(ReadonlyRegisterBase):
def __init__(self, name):
ReadonlyRegisterBase.__init__(self, name)
self.index = -1
self.initialize()
def doRead(self):
self.index +=1
return float(self.index)
#Lis of stream channels
channels = [Sensor("m_pos"),
Sensor("cur_cycle"),
Sensor("scanning")]
for i in range (len(blms)):
channels.append (Sensor("blm" + str(i+1)))
if plt is not None:
series = LinePlotSeries(blms[i], None, min(i+1, 2))
plt.addSeries(series)
series.setLinesVisible(False)
series.setPointSize(2)
if save_raw:
channels.append (Sensor("blm" + str(i+1) + "_raw"))
for i in range (len(bpms)):
for sensor in BPM_SENSORS:
channels.append (Sensor("bpm" + str(i+1) + "_" + sensor[0]))
#Metadata
set_attribute("/", "Wire Scanner", prefix)
set_attribute("/", "Scan Type", scan_type)
set_attribute("/", "Range", scan_range)
set_attribute("/", "Cycles", cycles)
set_attribute("/", "Motor Velocity", velocity*math.sqrt(2))
set_attribute("/", "Wire Velocity", velocity)
set_attribute("/", "Background Measures", bkgrd)
set_attribute("/", "BPMs", bpms)
set_attribute("/", "BLMs", blms)
filename = get_exec_pars().path
class Timestamp(Readable):
def read(self):
return time.time()
#End of scan checking
scan_complete, cur_cycle, wire = None, None, None
def check_end_scan(record, scan):
global scan_complete,cur_cycle
if record[4]<1:
print "Data aquisition completed"
scan_complete=True
scan.abort()
record.cancel() #So it won't be saved
else:
position = record[0]
if record[3] != cur_cycle:
cur_cycle = record[3]
get_context().dataManager.splitScanData(scan)
#if plt is not None: for s in plt.getAllSeries(): s.clear()
if plt is not None:
for i in range (len(blms)):
plt.getSeries(i).appendData(position, record[5 + i])
#Process background
def do_background():
#Store Background
if bkgrd>0:
set_exec_pars(group = "background")
r = tscan ( channels, bkgrd, 0.01)
for i in range(len(r.getReadables())):
d = r.getReadable(i)
path = get_exec_pars().group + "/"+ r.getReadables()[i].name
set_attribute(path, "Mean", mean(d))
set_attribute(path, "Sigma", stdev(d) )
#Scan
def do_scan(index):
global scan_complete, cur_cycle, wire
wire = "y" if (index==1) or (scan_type in ["Y1", "Y2"]) else "x"
if plt is not None:
if wire == "x":
plt.getAxis(plt.AxisId.X).setRange(scan_range[0], scan_range[1])
else:
plt.getAxis(plt.AxisId.X).setRange(scan_range[2], scan_range[3])
scan_complete=False
cur_cycle = 1.0
if plt is not None:
for s in plt.getAllSeries():
s.clear()
plt.removeMarker(None)
try:
#TODO: Check what the problem is
#mscan (st, [w_pos(),] + st.getReadables() + [Timestamp(),], -1, -1, take_initial = True, after_read = check_end_scan)
l=[Sensor("w_pos")] ; l.extend(channels); l.append(Timestamp())
#mscan (st, l, -1, -1, take_initial = True, after_read = check_end_scan)
#tscan([w_pos()] + getReadables() + [Timestamp(),], 10, 0.5)
for i in range(cycles):
set_exec_pars(group=wire+"_{count}", reset=(i==0))
tscan(l, 10, 0.5)
except:
print sys.exc_info()[1]
if not scan_complete:
raise
finally:
#Combining data of multiple series
#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)
calculate()
img_file = os.path.abspath(filename + "_" + get_exec_pars().group[0:1] + ".png")
time.sleep(0.1) #Give some time to plot finish (async)
if plt is not None:
plt.saveSnapshot(img_file, "png")
snapshots.append(img_file)
msg = ""
ret = []
def calculate():
global msg
stats = []
for i in range(len(blms)):
msg += "Wire " + wire + " - BLM " + str(i+1) + ":\n"
try:
bg = get_attributes("background/blm" + str(i+1))["Mean"] if bkgrd>0 else 0.0
samples = [[], [], [], []]
for cycle in range (cycles):
pos_path = wire+"_" + ("%04d" % (cycle+1)) + "/w_pos"
pos = load_data(pos_path)
path = wire+"_" + ("%04d" % (cycle+1)) + "/blm" + str(i+1)
data = load_data(path)
sp = data #blm_remove_spikes(data)
sig = sp if bg is None else [v-bg for v in sp]
rms_com, rms_sigma = [10.0, 20.0] #[profile_rms_stats(pos, sig,noise_std=0, n_sigma=3.5)
set_attribute(path, "RMS COM", float("nan") if (rms_com is None) else rms_com)
set_attribute(path, "RMS Sigma", float("nan") if (rms_sigma is None) else rms_sigma)
#print [com, rms]
[off, amp, com, sigma] = [30.0, 40.0, 50.0, 60.0] #profile_gauss_stats(pos, sig, off=None, amp=None, com=None, sigma=None)
set_attribute(path, "Gauss COM", float("nan") if (com is None) else com)
set_attribute(path, "Gauss Sigma", float("nan") if (sigma is None) else sigma)
samples[0].append(rms_com);samples[1].append(rms_sigma);samples[2].append(com);samples[3].append(sigma)
print get_exec_pars().path + " | "+ path
ret.append([rms_com, rms_sigma, com, sigma, get_exec_pars().path + "|"+ pos_path, get_exec_pars().path + "|"+ path])
#print [off, amp, com, sigma]
#from mathutils import Gaussian
#g = Gaussian(amp, com, sigma)
#gauss = [g.value(v)+off for v in pos]
#plot([data, sp, sig, gauss], ["data", "sp", "signal", "gauss", ], xdata = pos, title="Fit blm" + str(i+1) + " - " + str(cycle+1))
print "X"
stats.append([])
for sample in samples:
sample = [v for v in sample if v is not None]
stats[i].append( (mean(sample), stdev(sample)) if len(sample)>0 else (float("nan"), float("nan")) )
if plt is not None:
plt.addMarker(stats[i][2][0], None, "Gcom=" + "%.2f" % stats[i][2][0], plt.getSeries(i).color)
plt.addMarker(stats[i][0][0], None, "Rcom=" + "%.2f" % stats[i][0][0], plt.getSeries(i).color.brighter())
msg += " RMS COM: " + "%.4f" % stats[i][0][0] + " +- " +"%.4f" % stats[i][0][1] + "\n" #unichr(0x03C3) + "="
msg += " RMS Sigma: " + "%.4f" % stats[i][1][0] + " +- " + "%.4f" % stats[i][1][1] + "\n"
msg += " Gauss COM: " + "%.4f" % stats[i][2][0] + " +- " + "%.4f" % stats[i][2][1] + "\n"
msg += " Gauss Sigma: " + "%.4f" % stats[i][3][0] + " +- " + "%.4f" % stats[i][3][1] + "\n"
except Exception, e:
print >> sys.stderr, traceback.format_exc()
msg += str(e)+ "\n"
print "Starting scan..."
try:
do_background()
do_scan(0)
if scan_type in ["Set1", "Set2"]:
do_scan(1)
finally:
print "Closing scanner"
print "Closing stream"
print msg
# save the entry in the logbook
if do_elog:
if get_option("Generated data file:\n" + filename +"\n\n" + msg + "\n\n" + "Save to ELOG?", "YesNo") == "Yes":
log_msg = "Data file: " + filename
log_msg = log_msg + "\nWire Scanner: " + prefix
log_msg = log_msg + "\nScan Type: " + str(scan_type)
log_msg = log_msg + "\nRange: " + str(scan_range)
log_msg = log_msg + "\nCycles: " + str(cycles)
log_msg = log_msg + "\nWire Velocity: " + str(velocity)
log_msg = log_msg + "\nBackground Measures: " + str(bkgrd)
log_msg = log_msg + "\nBPMs: " + str(bpms)
log_msg = log_msg + "\nBLMs: " + str(blms)
log_msg = log_msg + "\n" + msg
elog("Wire Scan", log_msg, snapshots)
set_exec_pars(open=False)
set_return(ret)
+6 -5
View File
@@ -1,11 +1,12 @@
devlist = ['SARUN01', 'SARUN02', 'SARUN03', 'SARUN04', 'SARUN05', \
'SARUN06', 'SARUN07', 'SARUN08', 'SARUN09', 'SARUN10', \
'SARUN11', 'SARUN12', 'SARUN13', 'SARUN14', 'SARUN15']#\
devlist = ['SARUN13']#\
#'SARUN01', 'SARUN02', 'SARUN03', 'SARUN04', 'SARUN05', \
# 'SARUN06', 'SARUN07', 'SARUN08', 'SARUN09', 'SARUN10', \
# 'SARUN11', 'SARUN12', , 'SARUN14', 'SARUN15'
# 'SARUN16' 'SARUN17' 'SARUN18' 'SARUN19' 'SARUN20' ]
for dev in devlist:
off_x = caget(dev + "-DBPM070:OFFS-X")
off_y = caget(dev + "-DBPM070:OFFS-Y")
off_x = off_x + 0.000
off_y = off_y + 0.010
off_x = off_x + 0.010
off_y = off_y - 0.000
caput(dev + "-DBPM070:OFFS-X", float(off_x))
caput(dev + "-DBPM070:OFFS-Y", float(off_y))
+25
View File
@@ -0,0 +1,25 @@
devlist = ['SARUN08', 'SARUN09', 'SARUN10', \
'SARUN11', 'SARUN12', 'SARUN13', 'SARUN14', 'SARUN15']#\
#'SARUN01', 'SARUN02', 'SARUN03', 'SARUN04', 'SARUN05', \
# 'SARUN06', 'SARUN07',
# 'SARUN16' 'SARUN17' 'SARUN18' 'SARUN19' 'SARUN20' ]
namex = '-MQUA080:X'
namey = '-MQUA080:Y'
n = 0
for dev in devlist:
n = n + 1
off_x = caget(dev + namex)
off_y = caget(dev + namey)
off_x = off_x + (0.006 * float(n))
off_y = off_y + (0.000 * float(n))
caput(dev + namex, float(off_x))
caput(dev + namey, float(off_y))
#for dev in devlist:
# off_x = caget(dev + "-DBPM070:OFFS-X")
# off_y = caget(dev + "-DBPM070:OFFS-Y")
# off_x = off_x - 0.009
# off_y = off_y + 0.000
# caput(dev + "-DBPM070:OFFS-X", float(off_x))
# caput(dev + "-DBPM070:OFFS-Y", float(off_y))
+14
View File
@@ -0,0 +1,14 @@
devlist = ['SARUN03', 'SARUN04', 'SARUN05', \
'SARUN06', 'SARUN07''SARUN08', 'SARUN09', 'SARUN10', \
'SARUN11', 'SARUN12', 'SARUN13', 'SARUN14', 'SARUN15']#\
#'SARUN01', 'SARUN02', ,
# 'SARUN16' 'SARUN17' 'SARUN18' 'SARUN19' 'SARUN20' ]
name = '-UIND030:K-SET'
n = 0
for dev in devlist:
n = n + 1
off_x = caget(dev + name)
off_x = off_x + (0.006 * float(n))
caput(dev + namex, float(off_x))
+65 -26
View File
@@ -15,27 +15,43 @@ stop = caget(station + "-RSYS:SET-SCAN-STOP")
step = caget(station + "-RSYS:SET-SCAN-STEP")
lat = caget(station + "-RSYS:SET-SCAN-WAIT-TIME")
nb = caget(station + "-RSYS:SET-NUM-AVERAGE")
disp = caget(bpm_ch + ":DISPERSION")
energy0 = caget(bpm_ch + ":ENERGY")
A = energy0 / disp / 1e3
disp = caget(bpm_ch + ":DISPERSION-OP")
def mbnd(bpm_ch):
return {
'SINLH02-DBPM210': 'SINLH02-MBND100',
'SINLH02-DBPM240': 'SINLH02-MBND100',
'SINBC02-DBPM140': 'SINBC02-MBND100',
'SINBC02-DBPM320': 'SINBC02-MBND100',
'S10DI01-DBPM020': 'S10DI01-MBND100',
'S10BC02-DBPM140': 'S10BC02-MBND100',
'S10BC02-DBPM320': 'S10BC02-MBND100',
'SARCL02-DBPM110': 'SARCL02-MBND100',
'SARCL02-DBPM220': 'SARCL02-MBND100',
'SARCL02-DBPM260': 'SARCL02-MBND100',
'SARCL02-DBPM330': 'SARCL02-MBND100',
'SARCL02-DBPM470': 'SARCL02-MBND100'
}[bpm_ch]
p0 = caget(mbnd(bpm_ch) + ":P-READ")
energy0 = p0 - 0.511
A = energy0 / (disp * 1000)
B = energy0
phase = Positioner("Phase", station + "-RSYS:SET-VSUM-PHASE", station + "-RSYS:GET-VSUM-PHASE")
phase.config.minValue =-360.0
phase.config.minValue =-90.0
phase.config.maxValue = 360.0
phase.config.precision = 4
phase.config.rotation = False
phase.config.rotation = True
phase.config.resolution = 0.1
phase.initialize()
V = ChannelDouble("Amplitude Readback", station + "-RSYS:GET-VSUM-AMPLT")
V.initialize()
P = ChannelDouble("Power Readback", station + "-RSYS:GET-KLY-POWER")
V.initialize()
P.initialize()
if dry_run:
x = ChannelDouble("BPM-X", bpm_ch + ":X1-SIMU")
else:
x = ChannelDouble("BPM-X", bpm_ch + ":X1")
x.initialize()
phase0 = phase.read()
phase0 = phase.read() % 360
caput(station + "-RSYS:GET-FIT-PHASE-ARRAY", to_array([0.0],'d'))
caput(station + "-RSYS:GET-FIT-ENERGY-ARRAY", to_array([0.0],'d'))
caput(station + "-RSYS:GET-ONCREST-VSUM-PHASE", float('nan'))
@@ -56,9 +72,11 @@ def after(rec):
try:
phase.write(start)
time.sleep(1.0)
x_averager = create_averager(x, nb, 0.100)
x_averager = create_averager(x, nb, lat)
r = lscan(phase, x_averager, start, stop, step, latency=lat, after_read = after)
rf_phase = r.getPositions(0)
if start < 0:
rf_phase = [((ph + 90) % 360) -90 for ph in rf_phase ]
energy = [A * val.mean + B for val in r.getReadable(0)]
caput(station + "-RSYS:GET-ENERGY-ARRAY", to_array(energy, 'd'))
caput(station + "-RSYS:GET-PHASE-ARRAY", to_array(rf_phase,'d'))
@@ -67,15 +85,16 @@ try:
(fit_amplitude, fit_phase_deg, fit_offset, ph_crest, fit_x, fit_y) = hfitoff(energy , rf_phase)
except:
raise Exception("Fit failure")
# This only works when pshell is visible not in server mode to be fixed
plt = plot(None,name="phase scan")[0]
plt.getSeries(0).setData(to_array(rf_phase,'d'), to_array(energy,'d'))
plt.getSeries(0).setPointSize(6)
plt.getSeries(0).setLinesVisible(False)
plt.addSeries(LinePlotSeries("fit"))
plt.getSeries(1).setData(fit_x, fit_y)
plt.getSeries(1).setPointsVisible(False)
plt.setLegendVisible(True)
if plt is not None:
plt.getSeries(0).setData(to_array(rf_phase,'d'), to_array(energy,'d'))
plt.getSeries(0).setPointSize(6)
plt.getSeries(0).setLinesVisible(False)
plt.addSeries(LinePlotSeries("fit"))
plt.getSeries(1).setData(fit_x, fit_y)
plt.getSeries(1).setPointsVisible(False)
plt.setLegendVisible(True)
ph_crest = ph_crest % 360
phase.write(ph_crest)
time.sleep(lat)
Ampl = V.read()
@@ -92,19 +111,39 @@ finally:
V.close()
P.close()
x.close()
phase_offset = 90.0 - ph_crest
amplitude_scale = fit_amplitude / Ampl
power_scale = Power / math.pow(fit_amplitude,2)
phase_corr = caget(station + "-RSYS:GET-VSUM-PHASE-OFFSET-CORR")
phase_offset = 90.0 - ph_crest - phase_corr
amplitude_scale = fit_amplitude / Ampl if Ampl != 0 else 0.0
power_scale = Power / fit_amplitude**2 if fit_amplitude != 0 else 0.0
caput(station + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE-CALC", phase_offset)
caput(station + "-RSYS:SET-VSUM-AMPLT-SCALE-CALC", amplitude_scale)
caput(station + "-RSYS:SET-VOLT-POWER-SCALE-CALC", power_scale)
#Saving metadata
save_dataset (get_exec_pars().group + "/Station" , station )
save_dataset (get_exec_pars().group + "/Energy" , energy )
save_dataset (get_exec_pars().group + "/Energy gain" , fit_amplitude )
save_dataset (get_exec_pars().group + "/On-crest VS-phase" , ph_crest )
save_dataset (get_exec_pars().group + "/VS-phase offset" , phase_offset )
save_dataset (get_exec_pars().group + "/Amplitude scale" , amplitude_scale )
save_dataset (get_exec_pars().group + "/Power scale" , power_scale )
set_attribute(get_exec_pars().group + "/Energy" , "Unit", "MeV" )
set_attribute(get_exec_pars().group + "/Energy gain" , "Unit", "MeV" )
set_attribute(get_exec_pars().group + "/On-crest VS-phase" , "Unit", "deg" )
set_attribute(get_exec_pars().group + "/VS-phase offset" , "Unit", "deg" )
set_attribute(get_exec_pars().group + "/Amplitude scale" , "Unit", "MV" )
set_attribute(get_exec_pars().group + "/Power scale" , "Unit", "MW/MV^2" )
set_attribute(get_exec_pars().group + "/Phase" , "Unit", "deg" )
set_attribute(get_exec_pars().group + "/BPM-X averager" , "Unit", "mm" )
#Elog entry
if do_elog:
title = "Phase scan" + station
title = "Phase scan " + station
log_msg = "Data file: " + get_exec_pars().path + "\n"
log_msg = log_msg + "On-crest VS phase: %0.2f" % ph_crest + " deg \n"
log_msg = log_msg + "Energy Gain: %0.3f" % fit_amplitude + " MeV \n"
log_msg = log_msg + "VS -phase Offset: %0.2f" % phase_offset + " deg \n"
log_msg = log_msg + "Amplitude Scale: %0.3f" % amplitude_scale + " MV \n"
log_msg = log_msg + "Power Scale: %0.3f" % power_scale + " MW/MV^2"
attachments = get_plot_snapshots()
elog(title, log_msg, attachments)
log_msg = log_msg + "Energy gain: %0.3f" % fit_amplitude + " MeV \n"
log_msg = log_msg + "VS-phase offset: %0.2f" % phase_offset + " deg \n"
log_msg = log_msg + "Amplitude scale: %0.3f" % amplitude_scale + " MV \n"
log_msg = log_msg + "Power scale: %0.6f" % power_scale + " MW/MV^2"
attachments = get_plot_snapshots(size=(600,400))
elog(title, log_msg, attachments)