This commit is contained in:
2016-05-19 13:56:39 +02:00
commit ca1d73c31d
43 changed files with 752 additions and 0 deletions
@@ -0,0 +1,34 @@
#Tool to align the laser on the cathode.
# S. Bettoni, A. Gobbo, D. Voulot
#10/05/2016
#Procedure:
#I switch off all the magnets between the gun solenoid and the screen or BPM used for the measurement
#I change the current of the gun soleoid
#I look at the centroid position (BPM or screen) downstream of the gun.
#TO BE PUT THE SIGNAL I-READ IN THE DEVICE DEFINITION GUN SOLENOID
#caput("shutter:state", Closed)
start_I = 0.001 #20
end_I = 0.005 #150
step_I = 0.0001 #1
#Scan using the screen
r = lscan(gun_sol_current, [center_x, center_y], start_I, end_I, step_I, latency = 0.2)
#Scan using the BPM
#r = lscan(gun_sol_current, bpm_1_down_gun, start_I, end_I, step_I, latency = 0.2)
#I take the result of the scan and I do the plots
x = r.getReadable(0)
y = r.getReadable(1)
plot(y, xdata=x, title = "CM")
#I save the entry in the logbook
+37
View File
@@ -0,0 +1,37 @@
#Tool to align the laser on the cathode.
# S. Bettoni, A. Gobbo, D. Voulot
#10/05/2016
from operator import sub
#Procedure:
#I switch off all the magnets between the gun solenoid and the screen or BPM used for the measurement
#I change the current of the gun soleoid
#I look at the centroid position (BPM or screen) downstream of the gun.
#TO BE PUT THE SIGNAL I-READ IN THE DEVICE DEFINITION GUN SOLENOID
#caput("shutter:state", Closed)
start_I = 0.001 #20
end_I = 0.005 #150
step_I = 0.001 #1
#Scan using the screen
r = lscan(gun_sol_current, [center_x, center_y], start_I, end_I, step_I, latency = 0.2)
#Scan using the BPM
#r = lscan(gun_sol_current, bpm_1_down_gun, start_I, end_I, step_I, latency = 0.2)
#I take the result of the scan and I do the plots
x = r.getReadable(0)
y = r.getReadable(1)
p = plot(y, xdata=x, title = "CM")
yerr = 0.1
xerr = 0.5
#I save the entry in the logbook
#elog(title, message, attachments = [], author = None, category = "Info", domain = "", logbook = "SwissFEL commissioning data", encoding=1):
#elog("Test Simona", "message", author = "Simona", get_plot_snapshots(), logbook = "SwissFEL commissioning data", encoding=1)
+52
View File
@@ -0,0 +1,52 @@
import numpy as np
import matplotlib.pyplot as plt
# example data
x = np.arange(0.5, 5.5, 0.5)
y = np.exp(-x)
xerr = 0.1
yerr = 0.2
ls = 'dotted'
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
# standard error bars
plt.errorbar(x, y, xerr=xerr, yerr=yerr, ls=ls, color='blue')
# including upper limits
uplims = np.zeros(x.shape)
uplims[[1, 5, 9]] = True
plt.errorbar(x, y + 0.5, xerr=xerr, yerr=yerr, uplims=uplims, ls=ls,
color='green')
# including lower limits
lolims = np.zeros(x.shape)
lolims[[2, 4, 8]] = True
plt.errorbar(x, y + 1.0, xerr=xerr, yerr=yerr, lolims=lolims, ls=ls,
color='red')
# including upper and lower limits
plt.errorbar(x, y + 1.5, marker='o', ms=8, xerr=xerr, yerr=yerr,
lolims=lolims, uplims=uplims, ls=ls, color='magenta')
# including xlower and xupper limits
xerr = 0.2
yerr = np.zeros(x.shape) + 0.2
yerr[[3, 6]] = 0.3
xlolims = lolims
xuplims = uplims
lolims = np.zeros(x.shape)
uplims = np.zeros(x.shape)
lolims[[6]] = True
uplims[[3]] = True
plt.errorbar(x, y + 2.1, marker='o', ms=8, xerr=xerr, yerr=yerr,
xlolims=xlolims, xuplims=xuplims, uplims=uplims, lolims=lolims,
ls='none', mec='blue', capsize=0, color='cyan')
ax.set_xlim((0, 5.5))
ax.set_title('Errorbar upper and lower limits')
plt.show()
+1
View File
@@ -0,0 +1 @@
ascan((SARUN02_MCRX080,SARUN02_MCRY080), (SARUN03_DBPM070), (-2.0,-2.0), (2.0,2.0), (5,5), 0.01)
+1
View File
@@ -0,0 +1 @@
lscan(SINSB01_phase, BC1_energy, 0.0, 360.0, 10.0, 2.0)
+3
View File
@@ -0,0 +1,3 @@
///////////////////////////////////////////////////////////////////////////////////////////////////
// Deployment specific global definitions - executed after startup.groovy
///////////////////////////////////////////////////////////////////////////////////////////////////
+4
View File
@@ -0,0 +1,4 @@
///////////////////////////////////////////////////////////////////////////////////////////////////
// Deployment specific global definitions - executed after startup.js
///////////////////////////////////////////////////////////////////////////////////////////////////
+99
View File
@@ -0,0 +1,99 @@
###################################################################################################
# Deployment specific global definitions - executed after startup.py
###################################################################################################
from mathutils import estimate_peak_indexes, fit_gaussians, create_fit_point_list, Gaussian
import java.awt.Color as Color
def fit(ydata, xdata = None):
"""
"""
if xdata is None:
xdata = frange(0, len(ydata), 1)
max_y= max(ydata)
index_max = ydata.index(max_y)
max_x= xdata[index_max]
print "Max index:" + str(index_max),
print " x:" + str(max_x),
print " y:" + str(max_y)
gaussians = fit_gaussians(ydata, xdata, [index_max,])
(norm, mean, sigma) = gaussians[0]
p = plot([ydata],["data"],[xdata], title="Fit" )[0]
fitted_gaussian_function = Gaussian(norm, mean, sigma)
scale_x = [float(min(xdata)), float(max(xdata)) ]
points = max((len(xdata)+1), 100)
resolution = (scale_x[1]-scale_x[0]) / points
fit_y = []
fit_x = frange(scale_x[0],scale_x[1],resolution, True)
for x in fit_x:
fit_y.append(fitted_gaussian_function.value(x))
p.addSeries(LinePlotSeries("fit"))
p.getSeries(1).setData(fit_x, fit_y)
if abs(mean - xdata[index_max]) < ((scale_x[0] + scale_x[1])/2):
print "Mean -> " + str(mean)
p.addMarker(mean, None, "Mean="+str(round(norm,2)), Color.MAGENTA.darker())
return (norm, mean, sigma)
else:
p.addMarker(max_x, None, "Max="+str(round(max_x,2)), Color.GRAY)
print "Invalid gaussian fit: " + str(mean)
return (None, None, None)
def elog(title, message, attachments = [], author = None, category = "Info", domain = "", logbook = "SwissFEL commissioning data", encoding=1):
"""
Add entry to ELOG.
"""
if author is None:
author = "pshell" #controller.getUser().name
typ = "pshell"
entry = ""
cmd = 'G_CS_ELOG_add -l "' + logbook+ '" '
cmd = cmd + '-a "Author=' + author + '" '
cmd = cmd + '-a "Type=' + typ + '" '
cmd = cmd + '-a "Entry=' + entry + '" '
cmd = cmd + '-a "Title=' + title + '" '
cmd = cmd + '-a "Category=' + category + '" '
cmd = cmd + '-a "Domain=' + domain + '" '
for attachment in attachments:
cmd = cmd + '-f "' + attachment + '" '
cmd = cmd + '-n ' + str(encoding)
cmd = cmd + ' "' + message + '"'
#print cmd
#os.system (cmd)
#print os.popen(cmd).read()
import subprocess
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
if (err is not None) and err!="":
raise Exception(err)
print out
def get_plot_snapshots(title = None, file_type = "jpg", temp_path = controller.setup.getContextPath()):
"""
Returns list with file names of plots snapshots from a plotting context.
"""
sleep(0.02) #Give some time to plot to be finished - it is not sync with acquisition
ret = []
for p in get_plots(title):
file_name = os.path.abspath(temp_path + "/" + p.getTitle() + "." + file_type)
p.saveSnapshot(file_name , file_type)
ret.append(file_name)
return ret
class Sinusoid(ReadonlyRegisterBase):
def doRead(self):
self.x = self.x + 1.0 if hasattr(self, 'x') else 0.0
return math.sin(self.x * math.pi / 180.0)
add_device(Sinusoid("sim"), True)
add_device(Sinusoid("center_x"), True)
add_device(Sinusoid("center_y"), True)
center_x.setPolling(100)
center_y.setPolling(100)
+36
View File
@@ -0,0 +1,36 @@
"""
Parameters:
prefix
"""
prefix = "MINSB03-RSYS"
start = -179.0
stop = 180.0
step = 10.0
rf_phase_setpoint = Channel(prefix + ":SET-VSUM-PHASE")
rf_phase_readback = Channel(prefix + ":GET-VSUM-PHASE")
rf_ampl_readback = Channel(prefix + ":GET-VSUM-AMPLT")
r = lscan(rf_phase_setpoint, [rf_phase_readback, rf_ampl_readback, sim], start, stop, step , latency=0.2)
plot(r.getReadable(2), xdata = r.getReadable(0), title = "data")
#fit(r.getReadable(1))
set_return(r.print())
"""
r = lscan(rf_phase, [rf_phase_rb, rf_ampl_rb, sim], -179.0, 180, 10.0, latency=0.2)
plot(r.getReadable(2), xdata = r.getReadable(0), title = "data")
fit(r.getReadable(1))
set_return(r.print())
"""
+7
View File
@@ -0,0 +1,7 @@
#Execute the scan: 3 regions with different number of steps
a= rscan(ao1, (ai1,ai2), [(0,5,5), (10,15,20), (20,25,5)] , 0.01)
msg = str(a)
msg = msg + "\nFile: " + get_context().path + ".h5"
msg = msg + "\n\n" + a.print()
elog("Region scan", msg , get_plot_snapshots())
+21
View File
@@ -0,0 +1,21 @@
###################################################################################################
# Demonstrate use of scan callbacks to trigger a detector at falling edge.
###################################################################################################
def BeforeReadout():
ao1.write(1)
ao1.write(0)
#Example with an epics direct channel access
#caput("CHANNEL_NAME", 1)
#caput("CHANNEL_NAME", 0)
index=0
def AfterReadout():
global index
print "Aquired frame: " + str(index)
index=index+1
a= lscan((m1,m2), (ai1, ai2), (0,0), (4,8), steps=20, latency = 0.01, before_read=BeforeReadout, after_read=AfterReadout)
+29
View File
@@ -0,0 +1,29 @@
###################################################################################################
# Demonstrate the use of Line Scan: one or multiple positioners move together linearly.
###################################################################################################
#This optional preference limits the displayed plots
#set_preference(Preference.ENABLED_PLOTS, [ai1, ai2,])
#This optional preference displays wf1 as a 1d plot at each scan point, instead of a matrix plot
#set_preference(Preference.PLOT_TYPES, {wf1:1})
#Execute the scan: 200 steps, a1 from 0 to 40
a= lscan(ao1, (ai1,ai2,wf1), 0, 40, 200, 0.01)
#Also samples an image:
#a= lscan(ao1, (ai1,ai2,wf1), 0, 40, 200, 0.01)
#Alternative: Steps of size 0.1, a1 from 0 to 40
#a= lscan(ao1, (ai1,ai2,wf1), 0, 40, 0.5, 0.01)
#2 positioners moving together in 200 steps, a1 from 0 to 40 and a2 from 0 to 100
#a= lscan((ao1,ao2), (ai1,ai2,wf1), (0, 0), (40, 100), 200, 0.01)
#Setting attributes to the scan group
path = get_current_group()
set_attribute(path, "AttrString", "Value")
set_attribute(path, "AttrInteger", 1)
set_attribute(path, "AttrDouble", 2.0)
set_attribute(path, "AttrBoolean", True)
+1
View File
@@ -0,0 +1 @@
lscan(SINSB01_phase, energy_BC1, 0.0, 360.0, 10.0, 2.0)
+21
View File
@@ -0,0 +1,21 @@
###################################################################################################
# Demonstrate use of scan callbacks to trigger a detector at falling edge.
###################################################################################################
def BeforeReadout():
ao1.write(1)
ao1.write(0)
#Example with an epics direct channel access
#caput("CHANNEL_NAME", 1)
#caput("CHANNEL_NAME", 0)
index=0
def AfterReadout():
global index
print "Aquired frame: " + str(index)
index=index+1
a= lscan((m1,m2), (ai1, ai2), (0,0), (4,8), steps=20, latency = 0.01, before_read=BeforeReadout, after_read=AfterReadout)
+21
View File
@@ -0,0 +1,21 @@
###################################################################################################
# Demonstrate use of Vector Scan: one or multiple positioners set according to a position vector.
###################################################################################################
#1D vector scan, plot to 1D Vector tab
vector = [ 1, 3, 5, 10, 25, 40, 45, 47, 49]
a= vscan(ao1,(ai1,ai2),vector,False, 0.5, context = "1D Vector")
#2D vector scan, plot to 2D Vector tab
vector = [ [1,1] , [1,2] , [1,3] , [1,4] ,
[1.5,2.5] ,
[2,1] , [2,2] , [2,3] , [2,4] ,
[2.5,2.5] ,
[3,1] , [3,2] , [3,3] , [3,4] ]
a= vscan((m1,m2),(ai1,ai2),vector,False, 0.1, context = "2D Vector")
+52
View File
@@ -0,0 +1,52 @@
#Simona test
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example variable error bar values
yerr = 0.1 + 0.2*np.sqrt(x)
xerr = 0.1 + yerr
# First illustrate basic pyplot interface, using defaults where possible.
plt.figure()
plt.errorbar(x, y, xerr=0.2, yerr=0.4)
plt.title("Simplest errorbars, 0.2 in x, 0.4 in y")
# Now switch to a more OO interface to exercise more features.
fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True)
ax = axs[0,0]
ax.errorbar(x, y, yerr=yerr, fmt='o')
ax.set_title('Vert. symmetric')
# With 4 subplots, reduce the number of axis ticks to avoid crowding.
ax.locator_params(nbins=4)
ax = axs[0,1]
ax.errorbar(x, y, xerr=xerr, fmt='o')
ax.set_title('Hor. symmetric')
ax = axs[1,0]
ax.errorbar(x, y, yerr=[yerr, 2*yerr], xerr=[xerr, 2*xerr], fmt='--o')
ax.set_title('H, V asymmetric')
ax = axs[1,1]
ax.set_yscale('log')
# Here we have to be careful to keep all y values positive:
ylower = np.maximum(1e-2, y - yerr)
yerr_lower = y - ylower
ax.errorbar(x, y, yerr=[yerr_lower, 2*yerr], xerr=xerr,
fmt='o', ecolor='g', capthick=2)
ax.set_title('Mixed sym., log y')
fig.suptitle('Variable errorbars')
plt.show()
+38
View File
@@ -0,0 +1,38 @@
###################################################################################################
# Multiple Gaussians peak search with mathutils.py
###################################################################################################
from mathutils import estimate_peak_indexes, fit_gaussians, create_fit_point_list
start = 0
end = 50
step_size = 0.2
result= lscan(ao1,ai1,start,end,[step_size,])
readable = result.getReadable(0)
positions = result.getPositions(0)
threshold = (min(readable) + max(readable))/2
min_peak_distance = 5.0
peaks = estimate_peak_indexes(readable, positions, threshold, min_peak_distance)
print "Peak indexes: " + str(peaks)
print "Peak x: " + str(map(lambda x:positions[x], peaks))
print "Peak y: " + str(map(lambda x:readable[x], peaks))
gaussians = fit_gaussians(readable, positions, peaks)
plots = plot([readable],["sin"],[positions], title="Data" )
for i in range(len(peaks)):
peak = peaks[i]
(norm, mean, sigma) = gaussians[i]
if abs(mean - positions[peak]) < min_peak_distance:
print "Peak -> " + str(mean)
plots[0].addMarker(mean, None, "N="+str(round(norm,2)), None)
else:
print "Invalid gaussian fit: " + str(mean)
+7
View File
@@ -0,0 +1,7 @@
res = lscan(SINSB01_phase, BC1_energy, -90, 90, 21, latency = 1.0, relative = True)
y = res.getReadable(0)
x = res.getPositions(0)
fit(y, x)