This commit is contained in:
gobbo_a
2023-08-17 15:16:51 +02:00
parent c545879253
commit 8beeb7dbc7
134 changed files with 3722 additions and 1287 deletions

View File

@@ -10,8 +10,9 @@
import datetime
do_elog = True
dry_run = False
do_elog = True
is_panel = get_exec_pars().source != CommandSource.ui #Must be checked before callin "run"
camera_name = "simulation" if dry_run else "SINEG01-DSCR190"
bpm_name = "SINEG01-DBPM340"

View File

@@ -13,4 +13,6 @@ def linfit(x, y):
ssreg = np.sum((yhat - ybar)**2)
sstot = np.sum((y - ybar)**2)
R2 = ssreg / sstot
return (p, x_fit, y_fit, R2)
return (p, x_fit, y_fit, R2)

6
script/Correlation/Correlation.py Executable file → Normal file
View File

@@ -2,7 +2,7 @@ import math
import sys, traceback
from mathutils import fit_polynomial, PolynomialFunction
from plotutils import plot_line, plot_function
from ch.psi.pshell.swing.Shell import STDOUT_COLOR
from ch.psi.pshell.swing.Shell import getColorStdout
import org.apache.commons.math3.stat.correlation.PearsonsCorrelation as PearsonsCorrelation
if get_exec_pars().source == CommandSource.ui:
@@ -120,7 +120,7 @@ try:
#Sample and plot data
if bs == True:
_stream.waitValueNot(_stream.take(), 10000)
(x,y) = _stream.take().values
(x,y) = _stream.take().values()
else:
x=dx.read()
y=dy.read()
@@ -142,7 +142,7 @@ try:
if marker is not None:
p.removeMarker(marker)
marker = p.addMarker(x2+res, p.AxisId.X, s, p.getBackground())
marker.setLabelPaint(STDOUT_COLOR)
marker.setLabelPaint(getColorStdout())
if linear_fit:
#Calculate, print and plot linear fit
pars_lin = (a0,a1) = fit_polynomial(ay, ax, 1)

4
script/Correlation/Correlation2.py Executable file → Normal file
View File

@@ -2,7 +2,7 @@ import math
import sys, traceback
from mathutils import fit_polynomial, PolynomialFunction
from plotutils import plot_line, plot_function
from ch.psi.pshell.swing.Shell import STDOUT_COLOR
from ch.psi.pshell.swing.Shell import getColorStdout
import org.apache.commons.math3.stat.correlation.PearsonsCorrelation as PearsonsCorrelation
import ch.psi.pshell.bs.PipelineServer as PipelineServer
@@ -186,7 +186,7 @@ try:
if marker is not None:
p.removeMarker(marker)
marker = p.addMarker(x2+res, p.AxisId.X, s, p.getBackground())
marker.setLabelPaint(STDOUT_COLOR)
marker.setLabelPaint(getColorStdout())
if linear_fit:
#Calculate, print and plot linear fit
pars_lin = (a0,a1) = fit_polynomial(ay, ax, 1)

30
script/Correlation/CorrelationStream.py Executable file → Normal file
View File

@@ -14,7 +14,7 @@ class CorrelationStream():
self.st=None
self.running = False
self.task=None
def get_channel_list(self):
ch=[]
@@ -41,7 +41,7 @@ class CorrelationStream():
def start_stream(self, channel_list):
try:
self.st=None
print "Starting stream"
log("Starting stream: " + str(self.prefix))
if len(channel_list)==0:
raise Exception ("No channel defined")
self. st = Stream("pulse_id", dispatcher)
@@ -54,19 +54,20 @@ class CorrelationStream():
if self.st.take() is None:
raise Exception("Error initializing data stream")
self.ack_channel_list(channel_list)
print "Stream started"
log("Stream started: " + str(self.prefix))
except:
self.stop_stream()
self.st=None
print sys.exc_info()[1]
log(sys.exc_info()[1])
def stop_stream(self):
log("Closing stream: " + str(self.prefix))
try:
if self.st:
self.st.close()
print "Stream closed"
log("Stream closed: " + str(self.prefix))
except:
print sys.exc_info()[1]
log(sys.exc_info()[1])
finally:
self.st=None
self.ack_channel_list([])
@@ -81,7 +82,7 @@ class CorrelationStream():
buf[1] = num_channels
buf[4] = self.empty_value
#if (self.pid is not None) and ((self.pid+1) != msg.pulseId):
# print "Missing pid: ", (self.pid+1)
# msg("Missing pid: +str(self.pid+1))
self.pid = msg.pulseId
#Count
if buf[2] < size_buffer:
@@ -105,7 +106,7 @@ class CorrelationStream():
def _run(self):
print "Start running correlation stream " + str(self.prefix)
log("Start running thread: " + str(self.prefix))
channel_list = []
try:
@@ -115,11 +116,10 @@ class CorrelationStream():
while self.running:
started = (start_channel.get()==1)
if started and not self.st:
print "Started"
buf[2] = 0
buf[3]= -1
channel_list=self.get_channel_list()
print "Channel list: ", channel_list
log("Started " + str(self.prefix) + " - Channel list: " + str(channel_list) )
self.start_stream(channel_list)
if self.st is not None:
class StreamListener (DeviceListener):
@@ -132,14 +132,14 @@ class CorrelationStream():
self.st.addListener(listener)
elif self.st and not started:
print "Stopped"
log("Stopped " + str(self.prefix))
channel_list=[]
self.stop_stream()
time.sleep(0.1)
except:
print sys.exc_info()[1]
log(sys.exc_info()[1])
finally:
print "Stop running correlation stream " + str(self.prefix)
log("Stop running thread: " + str(self.prefix))
self.stop_stream()
if output_channel: output_channel.close()
if start_channel: start_channel.close()
@@ -155,9 +155,9 @@ class CorrelationStream():
if self.running:
self.running = False
if (self.task is not None):
print "Waiting correlation stream thread to stop..."
log("Waiting correlation stream thread to stop..." + str(self.prefix))
join([self.task,])
print "Done"
log("Done" + str(self.prefix))
def is_running(self):
return (self.task is not None) and not (self.task.isDone())

10
script/Correlation/correlation_stream_mult.py Executable file → Normal file
View File

@@ -1,9 +1,13 @@
run("Correlation/CorrelationStream")
#PREFIX = "SLAAR"
PREFIX = "SLG"
correlation_endstations=["SLAAR-LBSTREAM1","SLAAR-LBSTREAM2", "SLAAR-LBSTREAM3", "SLAAR-LBSTREAM4", "SLAAR-LBSTREAM5", "SLAAR-LBSTREAM6"]
correlation_endstations=[PREFIX+"-LBSTREAM1",PREFIX+"-LBSTREAM2", PREFIX+"-LBSTREAM3", PREFIX+"-LBSTREAM4", PREFIX+"-LBSTREAM5", PREFIX+"-LBSTREAM6"]
correlation_streams = []
log("Initializing...")
for es in correlation_endstations:
correlation_streams.append(CorrelationStream(es))
@@ -14,5 +18,7 @@ try:
cs.run()
time.sleep(10.0)
finally:
log("Finalizing...")
for cs in correlation_streams:
cs.stop()
cs.stop()
log("Quit")

View File

@@ -119,14 +119,14 @@ elements = (
(DWSC, "S30CB05-DWSC440", 340.6330),
(DBPM, "SATDI01-DBPM030", 340.8637),
(DBPM, "SATDI01-DBPM060", 342.7637),
(DWSC, "SATDI01-DWSC065", 342.9837),
(DBPM, "SATDI01-DBPM210", 349.2197),
(DBPM, "S30CB06-DBPM420", 349.3150),
(DBLM, "S30CB06-DBLM445", 349.7625),
(DBLM, "SATDI01-DBLM225", 349.5613),
(DBPM, "SATDI01-DBPM240", 352.1997),
(DBPM, "SATDI01-DBPM270", 355.1797),
#(DWSC, "SATDI01-DWSC290", 356.4797),
(DWSC, "SATDI01-DWSC290", 356.3100),
(DBLM, "SATDI01-DBLM305", 356.5500),
(DBPM, "SATDI01-DBPM320", 357.0907),
(DBPM, "S30CB07-DBPM420", 358.4150),
(DBPM, "SATCB01-DBPM220", 361.5357),

View File

@@ -0,0 +1,68 @@
#CAS.setServerPort(5064)
import java.util.function.BiFunction as BiFunction
class ShellCommand(RegisterBase, RegisterArray):
def __init__(self, name):
RegisterBase.__init__(self, name)
self.val = ""
self.debug=False
self.max_size = 10000
def getSize(self):
return 1
def doRead(self):
if self.debug:
print "READ: ", self.val
return self.val
def doWrite(self, val):
self.val = "RUNNING"
try:
if self.debug:
print "WRITE: ", val
cmd = str(val[0])
class eval_callback(BiFunction):
def apply(self_callback, ret, ex):
try:
if ex is not None:
err=ex.message
if "Exception:" in err:
err = err[err.index("Exception:")+10:].strip()
self.val = "ERR:" + err
else:
self.val = "RET:" + str(ret)
self.val = self.val[0:self.max_size]
except:
err=str(sys.exc_info()[1])
self.val = "EXC: " + err
if self.debug:
print self.val
#self.val = cmd
get_context().evalLineBackgroundAsync(cmd).handle(eval_callback())
except:
err=str(sys.exc_info()[1])
if "Exception:" in err:
err = err[err.index("Exception:")+10:].strip()
self.val = "EXC: " + err
self.val = self.val[0:self.max_size]
if self.debug:
print self.val
add_device(ShellCommand("sc"), True)
cas = CAS("TESTCAS:sc", sc, 'string')
#print caget("TESTCAS:sc","s")
#/Users/gobbo_a/anaconda3/envs/epics/epics/bin/darwin-x86

View File

@@ -0,0 +1,93 @@
import ch.psi.pshell.device.Startable as Startable
import traceback
class StreamListener (DeviceListener):
def __init__(self, merger):
self.merger = merger
def onCacheChanged(self, device, value, former, timestamp, valueChange):
self.merger.update()
class StreamMerger(DeviceBase, Readable):
def __init__(self, name, st1, st2):
DeviceBase.__init__(self, name)
self.st1=st1
self.st2=st2
self.pulseId = -1
self.v1= None
self.v2= None
self.initialize()
self.running=False
self.listener = StreamListener(self)
self.setComponents([st1,st2])
def doUpdate(self):
try:
while True:
has_more_1 = has_more_2 = False
if (self.v1 is None) or ((self.v1 is not None) and (self.v2 is not None) and (self.v1.pulseId < self.v2.pulseId)):
if self.st1.bufferCapacity>0:
tm_value = self.st1.popBuffer()
self.v1 = None if tm_value is None else tm_value.value
has_more_1 = (v1 is not None)
else:
self.v1 = self.st1.take()
if (self.v2 is None) or ((self.v1 is not None) and (self.v2 is not None) and (self.v1.pulseId > self.v2.pulseId)):
if self.st2.bufferCapacity>0:
tm_value = self.st2.popBuffer()
self.v2 = None if tm_value is None else tm_value.value
has_more_2 = (v2 is not None)
else:
self.v2 = self.st2.take()
if ((self.v1 is not None) and (self.v2 is not None) and (self.v1.pulseId == self.v2.pulseId)):
if self.v1.pulseId > self.pulseId:
keys=self.v1.keys()
keys.addAll(self.v2.keys())
values=self.v1.values()
values.addAll(self.v2.values())
self.pulseId = self.v1.pulseId
self.values, self.keys = values, keys
self.setCache(values, None)
self.v1=self.v2=None
else:
if (not has_more_1) and (not has_more_2):
break
except Exception, ex:
print >> sys.stderr, traceback.format_exc()
def doSetMonitored(self,value):
if (value):
self.st1.addListener(self.listener)
self.st2.addListener(self.listener)
else:
self.st1.removeListener(self.listener)
self.st2.removeListener(self.listener)
def doClose(self):
self.doSetMonitored(False)
def getReadables(self):
ret = list(self.st1.children + self.st2.children)
ret = [item for item in ret if type(item)!=Stream.PidReader]
return [self.st1.getPidReader(),] + ret
def read(self):
return self.pulseId
def start(self):
if not self.st1.isStarted():
self.st1.start()
if not self.st2.isStarted():
self.st2.start()
def stop(self):
if self.st1.isStarted():
self.st1.stop()
if self.st2.isStarted():
self.st2.stop()
def isStarted(self):
return self.st1.isStarted() and self.st2.isStarted()
#TODO: Readable children devices

View File

@@ -0,0 +1,8 @@
# change LED EVR delay
blm = "SARMA01-DLLM125"
delta = 5.0 # us
led = caget(blm + ":LED-DELAY-OP.INPA").split()[0]
delay1 = caget(led)
delay2 = delay1 + delta
print(blm, led, delay1, delay2)
caput(led, delay2)

View File

@@ -0,0 +1,16 @@
# shift BLM ROI by desired offset in us and reinitialise ioc
blm = "SATUN22-DBLM005"
ioc = "SARCL02-DBLM469"
offset = 0.040 # us
PIX = 2.33426704 # 1 / (124.8 MHz * 3) = 2.33426704 ns
evr = caget(blm + ":GPAC-DELAY-OP.INPA").split()[0]
delay = caget(evr)
start_b1 = int(caget(blm + ":B1_ROI_START"))
new_start_b1 = int(start_b1 + offset * 1000 / PIX)
print(blm, ioc, delay, offset, start_b1, new_start_b1)
caput(blm + ":B1_ROI_START", new_start_b1)
caput(blm + ":B1_ROI_STOP", new_start_b1 + 18)
caput(blm + ":B2_ROI_START", new_start_b1 + 19)
caput(blm + ":B2_ROI_STOP", new_start_b1 + 37)
print(ioc + ":SYSTEM-INIT.PROC", 1)
caput(ioc + ":SYSTEM-INIT.PROC", 1)

View File

@@ -0,0 +1,36 @@
# shift all ROIs such that the GPAC EVRs have all the same delay, set GPAC delay, reinitialsie ioc
blm_list = {"S10BC01-DBLM065", "S10CB04-DBLM240", "S10CB06-DBLM240", "S10CB08-DBLM240", "S10DI01-DBLM015",
"S10DI01-DBLM045", "S20CB02-DBLM435", "S20SY02-DBLM075", "S20SY03-DBLM025", "S20SY03-DBLM110",
"S30CB02-DBLM445", "S30CB06-DBLM445", "S30CB10-DBLM445", "S30CB14-DBLM445", "SARCL02-DBLM135",
"SARCL02-DBLM355", "SARUN01-DBLM065", "SARUN03-DBLM030", "SARUN04-DBLM030", "SARUN05-DBLM030",
"SARUN06-DBLM030", "SARUN07-DBLM030", "SARUN08-DBLM030", "SARUN09-DBLM030", "SARUN10-DBLM030",
"SARUN11-DBLM030", "SARUN12-DBLM030", "SARUN13-DBLM030", "SARUN14-DBLM030", "SARUN15-DBLM030",
"SARUN15-DBLM035", "SARUN20-DBLM035", "SATBD01-DBLM205", "SATCB01-DBLM245", "SATCL01-DBLM135",
"SATCL02-DBLM295", "SATCL02-DBLM435", "SATDI01-DBLM095", "SATDI01-DBLM105", "SATDI01-DBLM225",
"SATDI01-DBLM305", "SATMA01-DBLM065", "SATSY03-DBLM085", "SATUN06-DBLM005", "SATUN14-DBLM405",
"SATUN22-DBLM005", "SINDI02-DBLM025", "SINDI02-DBLM085", "SINLH02-DBLM230", "SINLH02-DBLM235"}
ioc_list = {"SARCL02-DBLM469", "S10BC01-DBLM184", "S10CB06-DBLM153", "S10CB04-DBLM130", "SINLH02-DBLM018",
"S10DI01-DBLM113", "S20CB02-DBLM234", "S30CB10-DBLM381", "SINDI02-DBLM084", "S20SY03-DBLM292",
"S30CB02-DBLM310", "S30CB14-DBLM417", "SARUN01-DBLM499", "SARUN04-DBLM516", "SARUN08-DBLM537",
"SARUN11-DBLM546", "SARMA01-DBLM482", "SARUN20-DBLM599", "SATDI01-DBLM344", "SARUN13-DBLM555",
"SATCB01-DBLM355", "S10CB08-DBLM170", "SATCL01-DBLM328", "SARUN15-DBLM567", "S20CB04-DBLM255",
"SARCL02-DBLM457", "SINEG01-DBLM009", "S20SY03-DBLM269"}
PIX = 2.33426704 # 1 / (124.8 MHz * 3) = 2.33426704 ns
for blm in blm_list:
evr = caget(blm + ":GPAC-DELAY-OP.INPA").split()[0]
delay = caget(evr)
offset = delay - 7439.0 # 7439 ns
start_b1 = int(caget(blm + ":B1_ROI_START"))
new_start_b1 = int(start_b1 + offset * 1000 / PIX)
print(delay, offset, start_b1, new_start_b1)
caput(blm + ":B1_ROI_START", new_start_b1)
caput(blm + ":B1_ROI_STOP", new_start_b1 + 18)
caput(blm + ":B2_ROI_START", new_start_b1 + 19)
caput(blm + ":B2_ROI_STOP", new_start_b1 + 37)
for ioc in ioc_list:
caput(ioc + "-EVR0:Pul10-Delay-SP", 7439.0)
caput(ioc + ":SYSTEM-INIT.PROC", 1)
print(ioc + "-EVR0:Pul10-Delay-SP", 7439.0)
print(ioc + ":SYSTEM-INIT.PROC", 1)

View File

@@ -0,0 +1,17 @@
# shift (and scale) the position of the start and end of the LLM GPAC waveform
# delta is in m, scaling may be unphysical (change of signal speed in the fibber)
llmlist = ("SINEG01-DLLM335", "SINDI01-DLLM105", "S10CB09-DLLM110", "S20CB04-DLLM110",
"S30CB05-DLLM110", "S30CB13-DLLM110", "SARMA01-DLLM125", "SARUN15-DLLM075",
"SATSY01-DLLM005", "SATDI01-DLLM305", "SATUN09-DLLM035")
llm = "SATSY01-DLLM005"
delta = 1.0
scale = 1.0 # should not be changed individually (same fibber type-> same signal speed)
z1 = caget(llm + ":Z-START-OP")
z2 = caget(llm + ":Z-STOP-OP")
dz = (z2 - z1) * scale
zc = (z1 + z2) / 2 + delta
z1 = zc - dz / 2
z2 = zc + dz / 2
caput(llm + ":Z-START-OP", z1)
caput(llm + ":Z-STOP-OP", z2)

View File

@@ -0,0 +1,7 @@
# scale globally LLM GPAC waveform length
# the length in m should normally be: 1 / (142.8 MHz * 3) * 2047 * c / (1 + n=1.4585) = 582.7 m
llmlist = ("SINEG01-DLLM335", "SINDI01-DLLM105", "S10CB09-DLLM110", "S20CB04-DLLM110",
"S30CB05-DLLM110", "S30CB13-DLLM110", "SARMA01-DLLM125", "SARUN15-DLLM075",
"SATSY01-DLLM005", "SATDI01-DLLM305", "SATUN09-DLLM035")
for llm in llmlist: caput(llm + ":Z-STOP-OP", caget(llm + ":Z-START-OP") + 582.7)

View File

@@ -0,0 +1,21 @@
# shift LLM ROIs by set amount delta_m in m and init ioc
delta_m = 0.0 # m
llm = "SATSY01-DLLM005"
ioc = "S20SY03-DBLM269"
chlist = [":CH1", ":CH2", ":CH3", ":CH4", ":CH5", ":CH6", ":CH7", ":CH8"]
z_start = caget(llm + ":Z-START-OP")
z_stop = caget(llm + ":Z-STOP-OP")
delta_pt = int(delta_m * 2047 / (z_stop - z_start))
print(delta_pt)
for ch in chlist:
roi_start = int(caget(llm + ch + "_ROI_START"))
roi_stop = int(caget(llm + ch + "_ROI_STOP"))
print(roi_start, roi_stop)
roi_start = roi_start + delta_pt
roi_stop = roi_stop + delta_pt
print(roi_start, roi_stop)
caput(llm + ch + "_ROI_START", roi_start)
caput(llm + ch + "_ROI_STOP", roi_stop)
print(ioc + ":SYSTEM-INIT.PROC", 1)
caput(ioc + ":SYSTEM-INIT.PROC", 1)

View File

@@ -0,0 +1,21 @@
# shift and scale the position of the start and end of the LLM GPAC waveform
# keep llm center unchanged, set step-size to default value
# delta is in m, scaling may be unphysical (change of signal speed in the fibber)
llmlist = ("SINEG01-DLLM335", "SINDI01-DLLM105", "S10CB09-DLLM110", "S20CB04-DLLM110",
"S30CB05-DLLM110", "S30CB13-DLLM110", "SARMA01-DLLM125", "SARUN15-DLLM075",
"SATSY01-DLLM005", "SATDI01-DLLM305", "SATUN09-DLLM035")
llm = "SATUN09-DLLM035"
zllm1 = 429.9
zllm2 = 502.3
zc = (zllm1 + zllm2) / 2
z1i = caget(llm + ":Z-START-OP")
z2i = caget(llm + ":Z-STOP-OP")
stepi = (z2i - z1i) / 2047
n = int((zc - z1i) / stepi)
stepf = 0.28464 # n = 1.4585 (Silica)
z1f = zc - n * stepf
z2f = zc + (2047 - n) * stepf
caput(llm + ":Z-START-OP", z1f)
caput(llm + ":Z-STOP-OP", z2f)

View File

@@ -1,45 +0,0 @@
################################################################################
# s = eps * [[beta, -alpha],
# [-alpha, gamma]]
# R = R(1)->(2)
# s2 = R * s1 * RT
#
# s2_11 = s1_11 * R11**2 + 2 * s1_12 * R11 * R12 + s1_22 * R12**2
#
# A = [[R11,1**2, 2 * R11,1 * R12,1, R12,1**2],
# [R11,2**2, 2 * R11,2 * R12,2, R12,2**2],
# ...
# [R11,n**2, 2 * R11,n * R12,n, R12,n**2],
# B = [s2_11,1,
# s2_11,2,
# ...
# s2_11,n]
# X = [s1_11,
# s1_12,
# s1_22]
#
# A * X = B
################################################################################
import numpy as np
n = 5
bet = [1.74450, 1.34220, 0.99999, 0.71557, 0.48651]
eps = 25.0E-6 # m.rad
R11 = [ 0.85800, 0.71000, 0.56400, 0.42000, 0.27900]
R12 = [ 0.44100, 0.41900, 0.39800, 0.37600, 0.35500]
#A = [[1.0,2.0],[3.0,4.0],[2.0,3.0]]
#B = [[-1.0],[-1.0],[-1.2]]
#X = [[1.0],[-1.0]]
A = []
B = []
for i in range(0, n):
A.append([R11[i]**2, 2 * R11[i] * R12[i], R12[i]**2])
B.append([bet[i] * eps])
A = np.matrix(A)
B = np.matrix(B)
X = np.linalg.inv(A.T.dot(A)).dot(A.T).dot(B)
print(X)

View File

@@ -0,0 +1,14 @@
scaling_factor = 1.002 #SARCL02:SCALE-USER-OP
maglist = ("SARCL02-MQUA310","SARCL02-MQUA350","SARCL02-MQUA460","SARCL02-MQSK300",
"SARCL02-MQUA150","SARCL02-MQSK160","SARCL02-MQUA430","SARCL02-MQSK420",
"SARCL02-MQUA130","SARCL02-MQUA210","SARCL02-MQUA250")
I1, I2 = {}, {}
for mag in maglist:
I = caget(mag + ":I-SET")
I1[mag] = I
I2[mag] = I * scaling_factor
print I1,I2
for mag in maglist: caputq(mag + ":I-SET", I2[mag])

View File

@@ -0,0 +1,35 @@
# stop the beam
caput("SARCL02-MBND100:USER-DELTA-ENE-STATE", 1)
caput("SIN-TIMAST-TMA:Beam-RF-OnDelay-Sel", 1)
caput("SIN-TIMAST-TMA:Beam-Apply-Cmd.PROC", 1)
# read channels
dE = caget("SARCL02-MBND100:USER-DELTA-ENE")
S30_GAIN = caget("S30:SET-E-GAIN-OP")
SARCL02_P_SET = caget("SARCL02-MBND100:P-SET")
SARBD01_P_SET = caget("SARBD01-MBND100:P-SET")
# set new energy set-points
S30_GAIN = S30_GAIN + dE
SARCL02_P_SET = SARCL02_P_SET + dE
SARBD01_P_SET = SARBD01_P_SET + dE
caput("S30:SET-E-GAIN-OP", S30_GAIN)
caput("SARCL02-MBND100:P-SET", SARCL02_P_SET)
caput("SARBD01-MBND100:P-SET", SARBD01_P_SET)
# adjust optics to new energy
caput("S30:OPTICS-ONOFF-OP", 1)
caput("SAR:OPTICS-ONOFF-OP", 1)
time.sleep(10)
# start the beam at 1 Hz
caput("SIN-TIMAST-TMA:Beam-RF-OnDelay-Sel", 0)
caput("SIN-TIMAST-TMA:Bunch-1-Freq-Sel", 10)
caput("SIN-TIMAST-TMA:Bunch-2-Freq-Sel", 10)
caput("SIN-TIMAST-TMA:Beam-Apply-Cmd.PROC", 1)
time.sleep(10)
# beam at 10 Hz
caput("SIN-TIMAST-TMA:Bunch-1-Freq-Sel", 6)
caput("SIN-TIMAST-TMA:Bunch-2-Freq-Sel", 6)
caput("SIN-TIMAST-TMA:Beam-Apply-Cmd.PROC", 1)
time.sleep(10)
# optics feedback off
caput("S30:OPTICS-ONOFF-OP", 0)
caput("SAR:OPTICS-ONOFF-OP", 0)
caput("SARCL02-MBND100:USER-DELTA-ENE-STATE", 0)

View File

@@ -0,0 +1,14 @@
#import epics as ep
#import numpy as np
monoenePVset = 'SAROP11-ARAMIS:ENERGY_SP'
pbps122PVrb = 'SAROP11-PBPS122:INTENSITY'
startval = caget(monoenePVset)
for i in range(2485, 2515, 2):
caput(monoenePVset, i)
sleep(5)
#ep.caget(pbps122)
caput(monoenePVset, startval)

View File

View File

@@ -0,0 +1,60 @@
IN_POSITION_BAND = 10.0
# muss auskommentiert bleiben
#Keithley = Channel("SATOP31-CSSU-PCEL1381:READOUT",'d', monitored ='True')
#K_avg = create_averager(Keithley, 10, interval = -1)
def beam_ok():
I0 = caget ("SATFE10-PEPG046:PHOTON-ENERGY-PER-PULSE-AVG")
if I0 > 100:
return "Yes"
else :
return "Yes"
def before_sampling(rec):
while beam_ok() == "No":
time.sleep(0.1)
print(".")
def after_sampling(rec):
if beam_ok() == "No":
rec.invalidate()
#i0 = Channel("SATFE10-PEPG046:PHOTON-ENERGY-PER-PULSE-AVG",'d')
#i_avg = create_averager(i0, 10, interval = -1)
K=Channel("SATOP31-CSSU-PCEL1381:READOUT")
#K_avg = create_averager(K, 10, interval = -1)
my_keithley_avg= create_averager("ca://SATOP31-CSSU-PCEL1381:READOUT", count=10,interval=-1,name="my_keithley_avg")
class VLSSGM(RegisterBase):
def doWrite(self, value):
caput ("SATOP11-OSGM087:SetEnergy", value)
time.sleep(0.2)
cawait('SATOP11-OSGM087:MOVING', 1, timeout = 20.0, type = 'i')
def doRead(self):
return caget("SATOP11-OSGM087:photonenergy")
athos = VLSSGM()
athos.initialize()
lscan( athos, my_keithley_avg, 398.7, 401.0, 0.02, 0.2, setpoints=True,zigzag=True) # Scans mit PSCR136
#lscan( athos, my_keithley_avg, 200.0, 201.0, 0.01, 0.2, setpoints=True,zigzag=True) # Scans mit PSCR136#lscan( athos, [K], 870.0 , 885.00, 0.1, 0.5, setpoints=True,zigzag=True) # Scans mit PSCR136
#lscan( athos, [K], 856.0 , 865.00, 0.1, 0.5, setpoints=True,zigzag=True) # Scans mit PSCR136
#lscan( athos, [i0,K_avg], 833.5, 837, 0.05, 0.5, setpoints=True,zigzag=True) # Scans mit PCEL
#lscan( athos, [i0,i_avg], 760.0, 820.0, 2.0, 0.5, setpoints=True,zigzag=True) # Scans mit PSCR136
#lscan( athos, [i0,i_avg], 380.0, 410.0, 1.0, 0.5, setpoints=True,zigzag=True) # Scans mit PSCR136
#caput ("ATHOS:SetEnergy", 680.0)
#tscan( [i], 10, 1 , passes=1)

View File

@@ -0,0 +1,66 @@
IN_POSITION_BAND = 10.0
# EInkommentieren fuer Messungen Mit PSCR136
# Auskommentieren fuer Messungen Mit PCEL
#
#cam_server.start("SATOP31-PSCR136_sp1", True)
#cam_server.start("SATOP31-PSRD175_sp1", True)
cam_server.start("SATOP31-PSCR136_sp1", True)
#cam_server.start("SATOP31-PPRM176_sp1", True)
cam_server.stream.waitCacheChange(-1)
i= cam_server.stream.getChild("intensity")
i_avg = create_averager(i, 20, interval = -1)
# muss auskommentiert bleiben
#Keithley = Channel("SATOP31-CSSU-PCEL1381:READOUT",'d', monitored ='True')
#K_avg = create_averager(Keithley, 5, interval = -1)
def beam_ok():
I0 = caget ("SATFE10-PEPG046:PHOTON-ENERGY-PER-PULSE-AVG")
if I0 > 100:
return "Yes"
else :
return "Yes"
def before_sampling(rec):
while beam_ok() == "No":
time.sleep(0.1)
print(".")
def after_sampling(rec):
if beam_ok() == "No":
rec.invalidate()
i0 = Channel("SATFE10-PEPG046:PHOTON-ENERGY-PER-PULSE-AVG",'d')
K=Channel("SATOP31-CSSU-PCEL1381:READOUT")
class VLSSGM(RegisterBase):
def doWrite(self, value):
caput ("SATOP11-OSGM087:SetEnergy", value)
time.sleep(0.2)
cawait('SATOP11-OSGM087:MOVING', 1, timeout = 20.0, type = 'i')
def doRead(self):
return caget("SATOP11-OSGM087:photonenergy")
athos = VLSSGM()
athos.initialize()
lscan( athos, [i0,i_avg], 370.0, 420.0, 1.0, 0.5, setpoints=True,zigzag=True) # Scans mit PSCR136
#lscan( athos, [i0,K_avg], 833.5, 837, 0.05, 0.5, setpoints=True,zigzag=True) # Scans mit PCEL
#lscan( athos, [i0,i_avg], 760.0, 820.0, 2.0, 0.5, setpoints=True,zigzag=True) # Scans mit PSCR136
#lscan( athos, [i0,i_avg], 380.0, 410.0, 1.0, 0.5, setpoints=True,zigzag=True) # Scans mit PSCR136
#caput ("ATHOS:SetEnergy", 680.0)
#tscan( [i], 10, 1 , passes=1)

18
script/RFscan/GunEnergyScan.py Executable file → Normal file
View File

@@ -22,7 +22,7 @@ else:
stop = 95.0
step = 0.5
nb = 3
lat = 0.15
lat = 0.4
disp = -0.387
p0 = 7.1
plt = plot(None, title="Output")[0]
@@ -44,7 +44,8 @@ plt.setLegendVisible(True)
#Creating Phase positioner
if dry_run:
phase = Positioner("Gun Phase", "SINEG01-RSYS:SET-BEAM-PHASE-SIM", "SINEG01-RSYS:SET-BEAM-PHASE-SIM")
#phase = Positioner("Gun Phase", "SINEG01-RSYS:SET-BEAM-PHASE-SIM", "SINEG01-RSYS:SET-BEAM-PHASE-SIM")
phase = DummyPositioner("Gun Phase")
camera_name = "simulation"
else:
phase = Positioner("Gun Phase", "SINEG01-RSYS:SET-BEAM-PHASE", "SINEG01-RSYS:GET-BEAM-PHASE")
@@ -88,7 +89,7 @@ def after_sample(record, scan):
#The scan loop
try:
phase.write(start)
time.sleep(2.0)
time.sleep(1.0)
r = lscan(phase, [x_averager, dx_averager], start, stop, step , latency=lat, after_read = after_sample)
finally:
phase.write(phase0)
@@ -142,14 +143,11 @@ if do_elog:
title = "Gun Energy Scan"
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":
log_msg = log_msg + "Bunch: " + Laser + "\n"
if Laser == "Bunch 1":
log_msg = log_msg + "Energy plate Alcor: %0.2f" % caget("SLAUV01-LATN100:MOT.RBV") + " deg \n"
elif Laser == "Jaguar":
log_msg = log_msg + "Energy plate Jaguar: %0.2f" % caget("SLJUV01-LATN100:MOT.RBV") + " deg \n"
elif Laser == "Both":
log_msg = log_msg + "Energy plate Alcor: %0.2f" % caget("SLAUV01-LATN100:MOT.RBV") + " deg \n"
log_msg = log_msg + "Energy plate Jaguar: %0.2f" % caget("SLJUV01-LATN100:MOT.RBV") + " deg \n"
elif Laser == "Bunch 2":
log_msg = log_msg + "Energy plate Mizar: %0.2f" % caget("SLMUV01-LATN100:MOT.RBV") + " deg \n"
if caget("SLAUV01-LAPT100:IRIS-POS-GET") == "IRIS":
log_msg = log_msg + "Collimator Alcor: IRIS %0.2f" % caget("SLAUV01-LAPT100:SIZE-GET") + " mm \n"
else:

32
script/RFscan/RfEnergyCalib.py Executable file → Normal file
View File

@@ -1,20 +1,38 @@
station = "S10CB09"
dE = 233.5# MeV
# single station calibration, dE is the desired energy gain (measured with bends: station on-station off)
# the scaling factors A,P are updated, the Acc voltage is set to dE, the V-Sum Amplitude and power should not change
station = "SINSB01"
dE = 77.25 # MeV
do_elog = True
# set RF on-delay
caput("SIN-TIMAST-TMA:Beam-RF-OnDelay-Sel", 1)
caput("SIN-TIMAST-TMA:Beam-Apply-Cmd.PROC", 1)
# scale RF calibration
A1 = caget(station + "-RSYS:SET-VSUM-AMPLT-SCALE") # MV/unit
P1 = caget(station + "-RSYS:SET-VOLT-POWER-SCALE") # MW/MV^2
VSA = caget(station + "-RSYS:GET-VSUM-AMPLT") # unit
PWR = caget(station + "-RSYS:GET-KLY-POWER-GATED") # MW
ACC1 = caget(station + "-RSYS:SET-ACC-VOLT") # MV
print(A1,P1,VSA,PWR,ACC1)
A2 = dE / VSA
P2 = PWR / dE**2
ACC2 = ACC1 * A2 / A1
ACC2 = dE
caput(station + "-RSYS:SET-VSUM-AMPLT-SCALE", A2)
caput(station + "-RSYS:SET-VOLT-POWER-SCALE", P2)
time.sleep(2.0)
caput(station + "-RSYS:SET-ACC-VOLT", ACC2)
print(A2,P2,ACC2)
time.sleep(2.0)
VSA = caget(station + "-RSYS:GET-VSUM-AMPLT") # unit
PWR = caget(station + "-RSYS:GET-KLY-POWER-GATED") # MW
print(A2,P2,VSA,PWR,ACC2)
#caget S30CB01-RSYS:{SET-VSUM-AMPLT-SCALE,SET-VOLT-POWER-SCALE,GET-VSUM-AMPLT,GET-KLY-POWER-GATED,SET-ACC-VOLT}
#Elog entry
if do_elog:
title = "Energy calibration" + station
log_msg = "Old energy gain: %0.2f" % ACC1 + " MeV/c\n"
log_msg = log_msg + "New energy gain: %0.2f" % ACC2 + " MeV/c\n\n"
log_msg = log_msg + " A1 A2 P1 P2 \n"
log_msg = log_msg + station + "%10.2f%10.2f%10.6f%10.6f" % (A1,A2,P1,P2) + " \n"
attachments = None
elog(title, log_msg)

57
script/RFscan/RfEnergyCalibGlobal.py Executable file → Normal file
View File

@@ -1,47 +1,60 @@
E1 = 1962.0 # old energy gain
E2 = 1950.0 # new energy gain
# global energy scaling for a group of station (normally one full linac)
# dE1 and dE2 are the old and new energy gains (from bends)
dE1 = 1951.00 # old energy gain
dE2 = 1950.00 # new energy gain
do_elog = True
#stationlist = ("SINSB01","SINSB02","SINSB03","SINSB04","SINXB01")
#stationlist = ("S10CB01","S10CB02","S10CB03","S10CB04","S10CB05","S10CB06","S10CB07","S10CB08","S10CB09")
stationlist = ("S10CB01","S10CB02","S10CB03","S10CB04","S10CB05","S10CB06","S10CB07","S10CB08","S10CB09")
#stationlist = ("S20CB01","S20CB02","S20CB03","S20CB04")
#stationlist = ("S30CB01","S30CB02","S30CB03","S30CB04","S30CB05","S30CB06","S30CB07","S30CB08","S30CB09","S30CB10","S30CB11","S30CB12","S30CB13")
stationlist = ("S10CB01","S10CB02","S10CB03","S10CB04","S10CB05","S10CB06","S10CB07","S10CB08","S10CB09")
do_VRF = True
VRFGAIN = "S10:SET-E-GAIN-OP"
#VRFGAIN = "S20:SET-E-GAIN-OP"
#VRFGAIN = "S30:SET-E-GAIN-OP"
# set RF on-delay
caput("SIN-TIMAST-TMA:Beam-RF-OnDelay-Sel", 1)
caput("SIN-TIMAST-TMA:Beam-Apply-Cmd.PROC", 1)
time.sleep(1.0)
# energy calibration
A1, A2 = {}, {}
P1, P2 = {}, {}
new_acc_volt = {}
A1, P1, VSA1, PWR1, ACC1 = {}, {}, {}, {}, {}
A2, P2, VSA2, PWR2, ACC2 = {}, {}, {}, {}, {}
for station in stationlist:
A = caget(station + "-RSYS:SET-VSUM-AMPLT-SCALE") # MV/unit
P = caget(station + "-RSYS:SET-VOLT-POWER-SCALE") # MW/MV^2
vsum_ampl = caget(station + "-RSYS:GET-VSUM-AMPLT") # unit
VSA = caget(station + "-RSYS:GET-VSUM-AMPLT") # unit
PWR = caget(station + "-RSYS:GET-KLY-POWER-GATED") # MW
ACC = caget(station + "-RSYS:SET-ACC-VOLT") # MV
A1[station] = A
A2[station] = A * E2 / E1
P1[station] = P
P2[station] = P * (E1 / E2)**2
new_acc_volt[station] = vsum_ampl * A2[station]
for station in stationlist:
VSA1[station] = VSA
PWR1[station] = PWR
ACC1[station] = ACC
A2[station] = A * dE2 / dE1
P2[station] = P * (dE1 / dE2)**2
ACC2[station] = ACC * dE2 / dE1
caput(station + "-RSYS:SET-VSUM-AMPLT-SCALE", A2[station])
caput(station + "-RSYS:SET-VOLT-POWER-SCALE", P2[station])
caput(station + "-RSYS:SET-ACC-VOLT", new_acc_volt[station])
# set RF on-beam
caput("SIN-TIMAST-TMA:Beam-RF-OnDelay-Sel", 0)
caput("SIN-TIMAST-TMA:Beam-Apply-Cmd.PROC", 1)
caput(station + "-RSYS:SET-ACC-VOLT", ACC2[station])
if do_VRF:
caput(VRFGAIN, dE2)
time.sleep(10.0)
for station in stationlist:
VSA = caget(station + "-RSYS:GET-VSUM-AMPLT") # unit
PWR = caget(station + "-RSYS:GET-KLY-POWER-GATED") # MW
VSA2[station] = VSA
PWR2[station] = PWR
#Elog entry
if do_elog:
title = "Energy calibration scaling"
log_msg = "Old energy gain: %0.2f" % E1 + " MeV/c\n"
log_msg = log_msg + "New energy gain: %0.2f" % E2 + " MeV/c\n\n"
log_msg = log_msg + " A1 A2 P1 P2 \n"
log_msg = "Old energy gain: %0.2f" % dE1 + " MeV/c\n"
log_msg = log_msg + "New energy gain: %0.2f" % dE2 + " MeV/c\n\n"
log_msg = log_msg + " AmpScale1 AmpScale2 PwrScale1 PwrScale2 Acc-Volt1 Acc-Volt2 VSA1 VSA2 Power1 Power2\n"
for station in stationlist:
log_msg = log_msg + station + "%10.2f%10.2f%10.6f%10.6f" % (A1[station],A2[station],P1[station],P2[station]) + " \n"
log_msg = log_msg + station + "%12.2f%12.2f%12.6f%12.6f%12.2f%12.2f%12.4f%12.4f%12.2f%12.2f" % (A1[station],A2[station],P1[station],P2[station],ACC1[station],ACC2[station],VSA1[station],VSA2[station],PWR1[station],PWR2[station]) + "\n"
attachments = None
elog(title, log_msg)

7
script/RFscan/SchottkyScan.py Executable file → Normal file
View File

@@ -12,6 +12,7 @@ if is_panel:
nb = int(args[3])
lat = args[4]
plt = args[5]
bunch = args[6]
else:
start = -10.0
stop = 150.0
@@ -19,6 +20,7 @@ else:
nb = 1
lat = 0.110 # lat is applied after each step (but not between samples)
plt = plot(None, title="Output")[0]
bunch = 1
#Plot setup
plt.clear()
@@ -26,7 +28,7 @@ plt.removeMarker(None)
plt.setStyle(plt.Style.ErrorY)
plt.addSeries(LinePlotErrorSeries("Charge", Color.red))
plt.getAxis(plt.AxisId.X).setLabel("Gun Beam Phase (deg)")
plt.getAxis(plt.AxisId.Y).setLabel("SINEG01-DICT215:B1_CHARGE (pC)")
plt.getAxis(plt.AxisId.Y).setLabel("Bunch Charge (pC)")
plt.setLegendVisible(True)
if dry_run:
@@ -38,7 +40,7 @@ if dry_run:
else:
bph = Positioner("Beam phase", "SINEG01-RSYS:SET-BEAM-PHASE", "SINEG01-RSYS:GET-BEAM-PHASE")
rph = ChannelDouble("RF phase", "SINEG01-RSYS:SET-VSUM-PHASE")
q = ChannelDouble("Charge", "SINEG01-DICT215:B1_CHARGE")
q = ChannelDouble("Charge", "SINEG01-DICT215:B" + str(bunch) + "_CHARGE")
q.initialize()
q.monitored=True
@@ -49,6 +51,7 @@ bph.config.resolution = 0.5 # set and get have to be within resolution
bph.config.rotation = True # will go back to zero if > 360 deg
bph.config.save()
bph.initialize()
bph.update()
bph0 = bph.read() % 360.0
rph.initialize()
rph.monitored=True

View File

@@ -0,0 +1,13 @@
# TDS calibration from phase jitter, to be completed...
run('Tools/CameraCorrelation')
start_camera_correlation("SATMA02-RLLE-DSP:PHASE-VS",
"SATBD02-DSCR050_sp1 x_center_of_mass",
samples = 200, modulo = 10, offset = 0, plt = plot(None)[0])
while True:
# the loop should run until the value is stable or a timeout is reached
a = linear_fit.read()
b = correlation.read()
stop_camera_correlation()
MO_FREQ = 142.8e6 # MO = 142.8 MHz
calib = a * 360 * 84 * MO_FREQ / 1e15 # um/fs
print(calib)

View File

@@ -11,11 +11,15 @@ if is_panel:
bpm_ch = args[1]
bpm_field = args[2]
else:
#station = "SATCB01"
#bpm_ch = "SATBD02-DBPM010"
station = "STEST01"
bpm_ch = "SINBC02-DBPM140"
bpm_field = "X1"
station = "SATCB01"
bpm_ch = "SATBD02-DBPM010"
bpm_field = "Y2"
#station = "S30CB13"
#bpm_ch = "SARCL02-DBPM110"
#bpm_field = "X1"
#station = "STEST01"
#bpm_ch = "SINBC02-DBPM140"
#bpm_field = "X1"
start = caget(station + "-RSYS:SET-SCAN-START")
stop = caget(station + "-RSYS:SET-SCAN-STOP")
step = caget(station + "-RSYS:SET-SCAN-STEP")
@@ -78,7 +82,7 @@ def after(rec):
#scan and plot
try:
phase.write(start)
time.sleep(2.0)
time.sleep(5.0)
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)

7
script/RFscan/setRFphaseGlobal.py Executable file → Normal file
View File

@@ -1,3 +1,4 @@
# change V-sum offset base globally (for example to compensate a laser delay change), dph is the desired phase shift
dph = 34.0
stationlist0 = ("SINSB01","SINSB02","SINSB03","SINSB04","SINXB01")
@@ -9,9 +10,9 @@ stationlist = stationlist1 + stationlist2 + stationlist3
Ph = {}
for station in stationlist:
ph0 = caget(station + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE") # deg
Ph[station] = ph0 - dph
Ph[station] = (ph0 - dph) % 360
for station in stationlist:
#caput(station + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE", Ph[station])
print(Ph[station])
caput(station + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE", Ph[station])
print(station + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE", Ph[station])

6
script/RFscan/setRFscanRange.py Executable file → Normal file
View File

@@ -1,11 +1,11 @@
scan_range = 80.0
# set scan parameters globally for the qt phasing tool
scan_range = 100.0
nb_steps = 21
#stationlist = ("SINSB01","SINSB02","SINSB03","SINSB04","SINXB01")
#stationlist = ("S10CB01","S10CB02","S10CB03","S10CB04","S10CB05","S10CB06","S10CB07","S10CB08","S10CB09")
#stationlist = ("S20CB01","S20CB02","S20CB03","S20CB04")
stationlist = ("S20CB01","S20CB02","S20CB03","S20CB04","S30CB01","S30CB02","S30CB03","S30CB04","S30CB05","S30CB06","S30CB07","S30CB08","S30CB09","S30CB10","S30CB11","S30CB12","S30CB13")
stationlist = ("S30CB01","S30CB02","S30CB03","S30CB04","S30CB05","S30CB06","S30CB07","S30CB08","S30CB09","S30CB10","S30CB11","S30CB12","S30CB13")
P1, P2 = {}, {}
for station in stationlist:

View File

@@ -0,0 +1,8 @@
MO_FREQ = 142.8e6 # MO = 142.8 MHz
rf_period = 1 / MO_FREQ / 21 / 1e-12 # ps
delay = caget("SLGOS01-TSPL-ALC:NEW_DELTA_T")
delay = delay + rf_period
print("SLGOS01-TSPL-ALC:NEW_DELTA_T", delay)
print("SLGOS01-TSPL-ALC:SET_NEW_PHASE.PROC", 1)
caput("SLGOS01-TSPL-ALC:NEW_DELTA_T", delay)
caput("SLGOS01-TSPL-ALC:SET_NEW_PHASE.PROC", 1)

View File

@@ -0,0 +1,8 @@
MO_FREQ = 142.8e6 # MO = 142.8 MHz
rf_period = 1 / MO_FREQ / 21 / 1e-12 # ps
delay = caget("SLGOS01-TSPL-ALC:NEW_DELTA_T")
delay = delay - rf_period
print("SLGOS01-TSPL-ALC:NEW_DELTA_T", delay)
print("SLGOS01-TSPL-ALC:SET_NEW_PHASE.PROC", 1)
caput("SLGOS01-TSPL-ALC:NEW_DELTA_T", delay)
caput("SLGOS01-TSPL-ALC:SET_NEW_PHASE.PROC", 1)

View File

@@ -0,0 +1,8 @@
MO_FREQ = 142.8e6 # MO = 142.8 MHz
rf_period = 1 / MO_FREQ / 21 / 1e-12 # ps
delay = caget("SLGOS01-TSPL-MIZ:NEW_DELTA_T")
delay = delay + rf_period
print("SLGOS01-TSPL-MIZ:NEW_DELTA_T", delay)
print("SLGOS01-TSPL-MIZ:SET_NEW_PHASE.PROC", 1)
caput("SLGOS01-TSPL-MIZ:NEW_DELTA_T", delay)
caput("SLGOS01-TSPL-MIZ:SET_NEW_PHASE.PROC", 1)

View File

@@ -0,0 +1,8 @@
MO_FREQ = 142.8e6 # MO = 142.8 MHz
rf_period = 1 / MO_FREQ / 21 / 1e-12 # ps
delay = caget("SLGOS01-TSPL-MIZ:NEW_DELTA_T")
delay = delay - rf_period
print("SLGOS01-TSPL-MIZ:NEW_DELTA_T", delay)
print("SLGOS01-TSPL-MIZ:SET_NEW_PHASE.PROC", 1)
caput("SLGOS01-TSPL-MIZ:NEW_DELTA_T", delay)
caput("SLGOS01-TSPL-MIZ:SET_NEW_PHASE.PROC", 1)

View File

@@ -0,0 +1,29 @@
#Parameters
is_panel = get_exec_pars().source != CommandSource.ui # run from panel
if is_panel:
tds = args[0]
else:
tds = "S30CB14"
run("Tools/BunchLengthTDSdata.py")
# stop the beam
caput("SIN-TIMAST-TMA:Beam-RF-OnDelay-Sel", 1)
caput("SIN-TIMAST-TMA:Beam-Apply-Cmd.PROC", 1)
caput("SIN-TIMAST-TMA:Bunch-1-Freq-Sel", 10)
caput("SIN-TIMAST-TMA:Bunch-2-Freq-Sel", 10)
# beam stopper and coll.
if tds == "SINDI01":
caput("S10CB01-RSYS:REQUIRED-OP", 0)
caput("S10CB02-RSYS:REQUIRED-OP", 0)
caput("S10DI01-MBND100:P-SET", 297.0)
if tds == "S30CB14":
caput("SARMA02-MBNP100:REQUEST", 1)
#caput("SARCL01-DCOL030:GAP", 5.0)
caput("SARCL02-VCOL290:GAP", 8.0)
# set optics
quads = tds_data[tds]["quads"]
k1l = tds_data[tds]["K1L-meas"]
for i in range(len(quads)):
caput(quads[i] + ":K1L-SET", k1l[i])

View File

@@ -0,0 +1,26 @@
#Parameters
is_panel = get_exec_pars().source != CommandSource.ui # run from panel
if is_panel:
tds = args[0]
else:
tds = "S30CB14"
run("Tools/BunchLengthTDSdata.py")
# stop the beam
caput("SIN-TIMAST-TMA:Beam-RF-OnDelay-Sel", 1)
caput("SIN-TIMAST-TMA:Beam-Apply-Cmd.PROC", 1)
caput("SIN-TIMAST-TMA:Bunch-1-Freq-Sel", 10)
caput("SIN-TIMAST-TMA:Bunch-2-Freq-Sel", 10)
# beam stopper and coll.
if tds == "S30CB14":
#caput("SARCL01-DCOL030:GAP", 5.0)
caput("SARCL02-VCOL290:GAP", 5.0)
# restore nominal optics
quads = tds_data[tds]["quads"]
k1l = tds_data[tds]["K1L-nom"]
for i in range(len(quads)):
caput(quads[i] + ":K1L-SET", k1l[i])
# show message: restore optics and coll.

View File

@@ -0,0 +1,261 @@
import ch.psi.pshell.epics.Positioner as Positioner
from mathutils import fit_polynomial
#Parameters
dry_run = False
do_elog = True
USE_SCREEN_PANEL = True
MO_FREQ = 142.8e6 # MO = 142.8 MHz
is_panel = get_exec_pars().source != CommandSource.ui # run from panel
if is_panel:
start = args[0]
stop = args[1] + 0.001 # needed to get the last point
step = args[2]
nb = int(args[3])
lat = args[4]
thr = args[5]
tds = args[6]
bunch = args[7]
plt11 = args[8]
plt12 = args[9]
plt21 = args[10]
plt22 = args[11]
else:
start = -0.1
stop = 0.1 + 0.001
step = 0.05
nb = 5
lat = 2.0
thr = 250
tds = "S30CB14"
bunch = "Bunch1"
plt11 = plot(None, title="Output")[0]
plt12 = plot(None, title="Output")[0]
plt21 = plot(None, title="Output")[0]
plt22 = plot(None, title="Output")[0]
run("Tools/BunchLengthTDSdata.py")
#Record callback: update of output plot
def update_plot(record, scan, plt):
com_mean, com_stdev = record[0].mean, record[0].stdev
rms_mean, rms_stdev = record[1].mean, record[1].stdev
fw_mean, fw_stdev = record[2].mean, record[2].stdev
fit_mean, fit_stdev = record[3].mean, record[3].stdev
phase = record.positions[0]
plt.getSeries(0).appendData(phase, com_mean, com_stdev)
plt.getSeries(1).appendData(phase, rms_mean, rms_stdev)
plt.getSeries(2).appendData(phase, fw_mean, fw_stdev)
plt.getSeries(3).appendData(phase, fit_mean, fit_stdev)
def update_plot_1(record, scan):
global plt11
update_plot(record, scan, plt11)
def update_plot_2(record, scan):
global plt12
update_plot(record, scan, plt12)
#Plot setup
def init_plots(plt1, plt2):
plt1.clear()
plt1.removeMarker(None)
plt1.setStyle(plt1.Style.ErrorY)
plt1.addSeries(LinePlotErrorSeries("Bunch center of mass", Color.red))
plt1.addSeries(LinePlotErrorSeries("Bunch length rms", Color.yellow, 2))
plt1.addSeries(LinePlotErrorSeries("Bunch length fw", Color.green, 2))
plt1.addSeries(LinePlotErrorSeries("Bunch length gauss fit", Color.blue, 2))
plt1.getAxis(plt1.AxisId.X).setLabel("TDS Phase (deg)")
plt1.getAxis(plt1.AxisId.Y).setLabel("Bunch center of mass (um)")
plt1.getAxis(plt1.AxisId.Y2).setLabel("Bunch length (um)")
plt1.setLegendVisible(True)
plt2.clear()
plt2.removeMarker(None)
plt2.setStyle(plt2.Style.Normal)
plt2.getAxis(plt2.AxisId.X).setLabel("Time (fs)")
plt2.getAxis(plt2.AxisId.Y).setLabel("Current (kA)")
plt2.setLegendVisible(False)
init_plots(plt11, plt21)
init_plots(plt12, plt22)
#Creating Phase positioner
if dry_run:
phase = DummyPositioner("TDS Phase")
camera_name = "simulation"
else:
phase = Positioner("TDS Phase", tds + "-RSYS:SET-BEAM-PHASE", tds + "-RSYS:SET-BEAM-PHASE")
camera_name = tds_data[tds]["screen"]
phase.config.minValue = -90.0
phase.config.maxValue = 270.0
phase.config.precision = 4
phase.config.resolution = 0.05
phase.config.rotation = True
phase.config.save()
phase.initialize()
phase0 = phase.read() % 360
#Camera setup
if USE_SCREEN_PANEL:
cam_server.start(camera_name+"_sp1", True) # shared pipeline
else:
cam_server.start(camera_name) # generic pipeline
cam_server.setFunction("beam_full_width")
cam_server.setInstanceConfigValue("fw_threshold", 0.3)
cam_server.setThreshold(thr)
cam_server.setBackgroundSubtraction(False)
cam_server.setGoodRegion(0.1, 3.0)
print "Waiting for y_fw and y_fit"
timeout = 1.0
start_time = time.time()
while (True):
wait_cam_server_message()
y_fw = cam_server.stream.getChild("y_fw")
y_fit = cam_server.stream.getChild("gr_y_fit_standard_deviation")
if (y_fw is not None) and (y_fit is not None):
break
if time.time() - start_time > timeout:
if y_fw is None:
raise Exception("y_fw not in camera stream")
if y_fit is None:
raise Exception("y_fit not in camera stream")
y_center_of_mass = cam_server.stream.getChild("y_center_of_mass")
y_rms = cam_server.stream.getChild("y_rms")
y_profile = cam_server.stream.getChild("y_profile")
y_axis = cam_server.stream.getChild("y_axis")
#Creating averagers
com_averager = create_averager(y_center_of_mass, nb, -1) # -1 event based, waits for the next value
rms_averager = create_averager(y_rms, nb, -1)
fw_averager = create_averager(y_fw, nb, -1)
fit_averager = create_averager(y_fit, nb, -1)
rms_averager.monitored = True # not blocking, will return last nb values
fw_averager.monitored = True
fit_averager.monitored = True
#switch BLMs off
blm = tds_data[tds]["BLM"]
strg = ":B1_ROI_ACTIVE_OP" if bunch == "Bunch1" else ":B2_ROI_ACTIVE_OP"
for i in range(len(blm)):
if dry_run:
print(blm[i] + strg, 0)
else:
caput(blm[i] + strg, 0)
#The scan loop
try:
bunch1_charge = caget("SINEG01-DBPM340:Q1")
bunch2_charge = caget("SINEG01-DBPM340:Q2")
bunch_charge = bunch1_charge if bunch == "Bunch1" else bunch2_charge
sensor_list = [com_averager, rms_averager, fw_averager, fit_averager, y_axis, y_profile, y_center_of_mass]
phase.write(start)
time.sleep(1.0)
# get bs phase-jitter / screen position data for SATMA02 calib
r1 = lscan(phase, sensor_list, start, stop, step , latency=lat, after_read = update_plot_1)
start, stop = start + 180.0, stop + 180.0
phase.write(start)
time.sleep(10.0)
r2 = lscan(phase, sensor_list, start, stop, step , latency=lat, after_read = update_plot_2)
finally:
phase.write(phase0)
phase.close()
cam_server.stop() # stops cam_server but does not close it cam_server is a global object
# stop the beam
if dry_run:
print("SIN-TIMAST-TMA:Beam-RF-OnDelay-Sel", 1)
print("SIN-TIMAST-TMA:Beam-Apply-Cmd.PROC", 1)
else:
caput("SIN-TIMAST-TMA:Beam-RF-OnDelay-Sel", 1)
caput("SIN-TIMAST-TMA:Beam-Apply-Cmd.PROC", 1)
#switch BLMs on
for i in range(len(blm)):
if dry_run:
print(blm[i] + strg, 1)
else:
caput(blm[i] + strg, 1)
#output
def write_output(r, plt):
phase_pos = r.getPositions(0)
rf_period = 1 / MO_FREQ / tds_data[tds]["harm"]
time_pos = [val / 360.0 * rf_period * 1e15 for val in phase_pos] # in fs
bunch_center = [val.mean for val in r.getReadable(0)]
bunch_center_stdev = [val.stdev for val in r.getReadable(0)]
a0, a1 = fit_polynomial(time_pos, bunch_center, 1)
calib = abs(a1) # in fs/um
#calib = 1
bunch_length_rms = [val.mean * calib for val in r.getReadable(1)]
bunch_length_rms_average = sum(bunch_length_rms) / len(bunch_length_rms)
bunch_length_fw = [val.mean * calib for val in r.getReadable(2)]
bunch_length_fw_average = sum(bunch_length_fw) / len(bunch_length_fw)
bunch_length_fit = [val.mean * calib for val in r.getReadable(3)]
bunch_length_fit_average = sum(bunch_length_fit) / len(bunch_length_fit)
profiles_um = r[y_axis]
profiles_dig = r[y_profile]
profiles_com = r[y_center_of_mass]
com = sum(profiles_com) / len(profiles_com)
profiles_fs = []
profiles_kA = []
for i in range(len(r[y_axis])):
delta_um = profiles_com[i] - com
profiles_fs.append([(val - delta_um) * calib for val in profiles_um[i]])
step_fs = (max(profiles_fs[i]) - min(profiles_fs[i])) / (len(profiles_fs[i]) - 1)
total_dig = float(sum(profiles_dig[i]))
profiles_kA.append([val / total_dig * bunch_charge / step_fs for val in profiles_dig[i]]) # pC / fs = kA
for i in range(len(profiles_um)):
plt.addSeries(LinePlotSeries("Bunch current " + str(i), Color.red))
plt.getSeries(i).setData(profiles_fs[i], profiles_kA[i])
return bunch_length_rms_average, bunch_length_fw_average, bunch_length_fit_average, calib
bunch_length_rms_average1, bunch_length_fw_average1, bunch_length_fit_average1, calib1 = write_output(r1, plt21)
bunch_length_rms_average2, bunch_length_fw_average2, bunch_length_fit_average2, calib2 = write_output(r2, plt22)
bunch_length_rms = (bunch_length_rms_average1 + bunch_length_rms_average2) / 2
bunch_length_fw = (bunch_length_fw_average1 + bunch_length_fw_average2) / 2
bunch_length_fit = (bunch_length_fit_average1 + bunch_length_fit_average2) / 2
calib = (calib1 + calib2) / 2
#archiver channels
if bunch == "Bunch1":
caput(tds + "-RTDS100:BD-BUNCH1-DURATION", bunch_length_fw)
caput(tds + "-RTDS100:BD-BUNCH1-CALIBRATION", 1 / calib)
else:
caput(tds + "-RTDS100:BD-BUNCH2-DURATION", bunch_length_fw)
caput(tds + "-RTDS100:BD-BUNCH2-CALIBRATION", 1 / calib)
#Elog entry
if do_elog:
if get_option("Generated data file:\n" + get_exec_pars().path +"\n\n" + "Save to ELOG?", "YesNo") == "Yes":
title = "Bunch length Scan"
log_msg = "Data file: " + get_exec_pars().path + "\n\n"
log_msg = log_msg + "TDS: " + tds + "\n"
log_msg = log_msg + "Bunch: " + bunch + "\n\n"
log_msg = log_msg + "#### 0 deg ####\n"
log_msg = log_msg + "Bunch length rms: %0.1f" % bunch_length_rms_average1 + " fs\n"
log_msg = log_msg + "Bunch length fw: %0.1f" % bunch_length_fw_average1 + " fs\n"
log_msg = log_msg + "Bunch length fit: %0.1f" % bunch_length_fit_average1 + " fs\n"
log_msg = log_msg + "Calibration: %0.4f" % calib1 + " fs/um\n\n"
log_msg = log_msg + "#### 180 deg ####\n"
log_msg = log_msg + "Bunch length rms: %0.1f" % bunch_length_rms_average2 + " fs\n"
log_msg = log_msg + "Bunch length fw: %0.1f" % bunch_length_fw_average2 + " fs\n"
log_msg = log_msg + "Bunch length fit: %0.1f" % bunch_length_fit_average2 + " fs\n"
log_msg = log_msg + "Calibration: %0.4f" % calib2 + " fs/um\n\n"
log_msg = log_msg + "#### mean ####\n"
log_msg = log_msg + "Bunch length rms: %0.1f" % bunch_length_rms + " fs\n"
log_msg = log_msg + "Bunch length fw: %0.1f" % bunch_length_fw + " fs\n"
log_msg = log_msg + "Bunch length fit: %0.1f" % bunch_length_fit + " fs\n"
log_msg = log_msg + "Calibration: %0.4f" % calib + " fs/um"
sleep(0.1) #Give some time to plot to be finished - it is not sync with acquisition
file_name1 = os.path.abspath(get_context().setup.getContextPath() + "/BunchLengthScanPlot1.png")
plt11.saveSnapshot(file_name1, "png")
file_name2 = os.path.abspath(get_context().setup.getContextPath() + "/BunchLengthCurrent1.png")
plt21.saveSnapshot(file_name2, "png")
file_name3 = os.path.abspath(get_context().setup.getContextPath() + "/BunchLengthScanPlot2.png")
plt12.saveSnapshot(file_name3, "png")
file_name4 = os.path.abspath(get_context().setup.getContextPath() + "/BunchLengthCurrent2.png")
plt22.saveSnapshot(file_name4, "png")
elog(title, log_msg, [file_name1, file_name2, file_name3, file_name4])
set_return([bunch_length_rms_average1, bunch_length_fw_average1, bunch_length_fit_average1, calib1,
bunch_length_rms_average2, bunch_length_fw_average2, bunch_length_fit_average2, calib2,
bunch_length_rms, bunch_length_fw, bunch_length_fit, calib])

View File

@@ -0,0 +1,47 @@
#tds config
tds_data = {'SINDI01': {"harm": 21, "screen": "SINDI02-DSCR075",
"quads":
["SINDI02-MQUA020", "SINDI02-MQUA030", "SINDI02-MQUA050",
"SINDI02-MQUA060"],
"K1L-nom":
[-0.020000, 0.050000, -0.165000,
0.200000],
"K1L-meas":
[-0.389776, 0.324016, 0.067305,
0.174710],
"BLM": []},
'S30CB14': {"harm": 40, "screen": "SARCL01-DSCR170",
"quads":
["S30CB10-MQUA430", "S30CB11-MQUA430", "S30CB12-MQUA430",
"S30CB13-MQUA430", "S30CB14-MQUA430", "S30CB15-MQUA430",
"SARCL01-MQUA020", "SARCL01-MQUA050", "SARCL01-MQUA080",
"SARCL01-MQUA100", "SARCL01-MQUA140", "SARCL01-MQUA190"],
"K1L-nom":
[-0.125000, 0.125000, -0.125000,
0.125000, -0.125000, 0.125000,
-0.070000, 0.010000, -0.145000,
0.155000, 0.415000, -0.490000],
"K1L-meas":
[-0.102751, -0.014919, 0.112685,
-0.064000, -0.053854, 0.048777,
0.104904, -0.039548, -0.005735,
0.005119, -0.027870, -0.011176],
"BLM":
["SARCL02-DBLM135", "SARCL02-DBLM355", "SARUN01-DBLM065",
"SARUN03-DBLM030", "SARUN04-DBLM030", "SARUN05-DBLM030",
"SARUN06-DBLM030", "SARUN07-DBLM030", "SARUN08-DBLM030",
"SARUN09-DBLM030", "SARUN10-DBLM030", "SARUN11-DBLM030",
"SARUN12-DBLM030", "SARUN13-DBLM030", "SARUN14-DBLM030",
"SARUN15-DBLM030", "SARUN15-DBLM035", "SARUN20-DBLM035"]},
'SATMA02': {"harm": 84, "screen": "SATBD01-DSCR120",
"quads":
["SATBD01-MQUA010", "SATBD01-MQUA030", "SATBD01-MQUA050",
"SATBD01-MQUA070", "SATBD01-MQUA090"],
"K1L-nom":
[ 0.150000, -0.185000, 0.040000,
0.140000, -0.225000],
"K1L-meas":
[-0.090111, 0.108271, 0.025250,
-0.072006, -0.382500],
"BLM": []}}

View File

@@ -0,0 +1,119 @@
import math
import sys, traceback
from mathutils import fit_polynomial, PolynomialFunction
from plotutils import plot_line, plot_function
from ch.psi.pshell.swing.Shell import getColorStdout
import org.apache.commons.math3.stat.correlation.PearsonsCorrelation as PearsonsCorrelation
import ch.psi.pshell.bs.StreamMerger as StreamMerger
_stop_exec = False
_task = None
_dispatcher_stream = None
def start_camera_correlation(dispatcer_channel, camera_channel, samples=50, modulo=1, offset=0, plt=None):
global _stop_exec, _task, _dispatcher_stream
stop_camera_correlation()
if plt:
for s in plt.getAllSeries():
plt.removeSeries(s)
class LinearFit(ReadonlyAsyncRegisterBase, ReadonlyRegisterArray):
def getSize(self):
return 2
def set(self, pars):
self.onReadout(to_array(pars, 'd'))
class Correlation(ReadonlyAsyncRegisterBase):
def set(self, val):
self.onReadout(val)
add_device(LinearFit("linear_fit"), True)
add_device(Correlation("correlation"), True)
try:
_dispatcher_stream = Stream("corr_stream", dispatcher)
_dispatcher_stream.addScalar(dispatcer_channel, dispatcer_channel, modulo, offset)
_dispatcher_stream.initialize()
_dispatcher_stream.start(True)
_dispatcher_stream.setBufferCapacity(500)
camera_name, camera_channel = camera_channel.split(" ")
shared = camera_name.endswith("_sp1")
cam_server.start(camera_name, shared )
camera_stream = cam_server.stream
camera_stream.setBufferCapacity(500)
camera_stream.waitCacheChange(10000);
def merger_task():
merger = StreamMerger("stream", _dispatcher_stream, camera_stream)
try:
if plt:
sd = LinePlotSeries("Data")
plt.addSeries(sd)
sd.setLinesVisible(False)
sd.setPointSize(4)
else:
ax,ay = [],[]
merger.monitored=True
merger.start()
merger.waitCacheChange(5000)
dx=merger.getChild(dispatcer_channel)
dy=merger.getChild(camera_channel)
while(not _stop_exec):
merger.waitCacheChange(10000)
x=dx.read()
y=dy.read()
if plt:
sd.appendData(x, y)
while len(sd.x) > samples:
sd.token.remove(0) #Remove First Element
ax,ay = sd.x,sd.y
else:
ax.append(x); ay.append(y)
while len(ax) > samples:
ax.pop(0); ay.pop(0)
if len(ax)>2:
x1, x2 = min(ax), max(ax)
if x1!=x2:
#Display correlation
corr= PearsonsCorrelation().correlation(to_array(ax,'d'), to_array(ay,'d'))
correlation.set(corr)
pars_lin = (a0,a1) = fit_polynomial(ay, ax, 1)
linear_fit.set(pars_lin)
y1,y2 = poly(x1, pars_lin), poly(x2, pars_lin)
if plt:
invoke((plot_line,(plt, x1, y1, x2, y2, 2, Color.BLUE, "Fit Linear")), False)
finally:
merger.close()
_task = fork(merger_task)
except:
stop_camera_correlation()
raise
def stop_camera_correlation():
global _stop_exec, _task, _dispatcher_stream
_stop_exec = True
if _task:
join(_task)
cam_server.stop()
if _dispatcher_stream:
_dispatcher_stream.close()
_stop_exec = False
_task = None
_dispatcher_stream = None
#Testing
start_camera_correlation("SINEG01-DICT215:B1_CHARGE", "SATES31-CAMS187-RIXS1_sp1 intensity", samples = 40, plt=plot(None)[0])
try:
time.sleep(10.0)
finally:
stop_camera_correlation()

View File

@@ -0,0 +1,15 @@
#Parameters
is_panel = get_exec_pars().source != CommandSource.ui # run from panel
if is_panel:
tds = args[0]
phase = args[1]
else:
tds = "S30CB14"
phase = 0.0
# set beam phase offset
phase_rf = caget(tds + "-RSYS:GET-VSUM-PHASE")
phase_corr = caget(tds + "-RSYS:GET-VSUM-PHASE-OFFSET-CORR")
phase_offset = phase - phase_rf - phase_corr
print(tds + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE", phase_offset)
caput(tds + "-RSYS:SET-VSUM-PHASE-OFFSET-BASE", phase_offset)

View File

@@ -0,0 +1,15 @@
print "Connecting to camera: " + str(CAMERA)
CAMERA_URL = caget(CAMERA + ":BSREADCONFIG").replace("tcp://daq", "tcp://")
print "Url: " + str(CAMERA_URL)
st1 = Stream("st1", CAMERA_URL, SocketType.PULL)
st1.initialize()
st1.start()
st1.waitCacheChange(3000)
try:
r=bscan (st1, records=10, timeout =10.0, save=False, enabled_plots=[st1,])
v= st1.getValues()
finally:
st1.close()

View File

@@ -0,0 +1,45 @@
import requests
import json
dispatcher_url = "https://dispatcher-api.psi.ch/sf"
def get_dispatcher(path):
response = requests.get(url=dispatcher_url+path)
if response.status_code != 200:
raise Exception(response.text)
return json.loads(response.text)
def post_dispatcher(path, data):
response = requests.post(url=dispatcher_url+path, json=data)
if response.status_code != 200:
raise Exception(response.text)
return json.loads(response.text)
def get_dispatcher_info(regex):
return post_dispatcher("/channels/live",{"regex": regex})[0]
def get_dispatcher_channels(regex):
return get_dispatcher_info(regex)["channels"]
def get_dispatcher_channel_info(channel_name):
return get_dispatcher_info(channel_name)["channels"][0]
def get_dispatcher_channel_modulo(channel_name):
return get_dispatcher_channel_info(channel_name)
def get_dispatcher_channel_modulo(channel_name):
return get_dispatcher_channel_info(channel_name).get("modulo", 1)
def get_dispatcher_channel_offset(channel_name):
return get_dispatcher_channel_info(channel_name).get("offset", 0)
def get_dispatcher_stream(channel_names):
channels = []
for channel_name in channel_names:
#info = get_dispatcher_channel_info(channel_name)
#channels.append({"name":channel_name,"backend":"sf-databuffer","modulo":info.get("modulo", 1), "offset":info.get("offset", 0)})
channels.append({"name":channel_name,"backend":"sf-databuffer","modulo":None, "offset":None})
return post_dispatcher("/stream",{"channels": channels})

1
script/Undulators/1DscanEarthField.py Executable file → Normal file
View File

@@ -1,6 +1,5 @@
import ch.psi.pshell.epics.ChannelDouble as ChannelDouble
A1 = ChannelDouble("Actuator1", "SARUN07-UIND030:I-SET")
#S1 = ChannelDouble("Sensor1", "SARFE10-PBPG050:PHOTON-ENERGY-PER-PULSE-US")
S1 = ChannelDouble("Sensor1", "SARFE10-PBPG050:HAMP-INTENSITY-CAL")
A1.initialize()
S1.initialize()

View File

@@ -1,14 +1,18 @@
import ch.psi.pshell.epics.ChannelDouble as ChannelDouble
A1 = ChannelDouble("K value", "SARUN15-UIND030:K_SET")
S1 = ChannelDouble("Energy per pulse (uJ)", "SARFE10-PBPG050:PHOTON-ENERGY-PER-PULSE-US")
import ch.psi.pshell.epics.ChannelDouble as ChannelDouble
from mathutils import fit_polynomial, PolynomialFunction
A1 = ChannelDouble("K value", "SARUN08-UIND030:K_SET")
#S1 = ChannelDouble("Energy per pulse (uJ)", "SARFE10-PBPG050:PHOTON-ENERGY-PER-PULSE-US")
#S1 = ChannelDouble("Energy per pulse (uJ)", "SARFE10-PBPG050:HAMP-INTENSITY-CAL")
S1 = ChannelDouble("Hamp RAW", "SARFE10-PBIG050-EVR0:CALCI")
A1.initialize()
S1.initialize()
A1_init = A1.read()
A1i = A1_init - 0.005
A1f = A1_init + 0.005
nstep = 21
lat = 1.0
nav = 5
nstep = 10
lat = 0.01
nav = 100
wait = 3
plt = plot(None, title="Output")[0]
plt.clear()
plt.setStyle(plt.Style.ErrorY)
@@ -20,7 +24,7 @@ def after_sample(record, scan):
try:
S1_averager = create_averager(S1, nav, lat)
A1.write(A1i)
time.sleep(30.0)
time.sleep(wait)
r = lscan(A1, (S1_averager), A1i, A1f, nstep, latency=5.0, after_read = after_sample)
Act1 = r.getPositions(0)
S1mean = [val.mean for val in r.getReadable(0)]
@@ -29,3 +33,15 @@ finally:
A1.write(A1_init)
A1.close()
S1.close()
## add fitting:
pars_polynomial = fit_polynomial(S1mean, Act1, 3)
p1 = PolynomialFunction(pars_polynomial)
resolution = (A1f - A1i)/100
fit_polinomial = []
for x in frange(A1i, A1f, resolution, True):
fit_polinomial.append(p1.value(x))
x = frange(A1i, A1f+resolution, resolution)
#plot(x, fit_polinomial)
plots = plot([S1mean, fit_polinomial] ,
["data", "polinomial"], xdata = [Act1,x], title="Data")

View File

@@ -0,0 +1,28 @@
import ch.psi.pshell.epics.ChannelDouble as ChannelDouble
A1 = ChannelDouble("Phase (deg.)", "SARUN10-UPHS060:PHI_SET")
S1 = ChannelDouble("energy per pulse (uJ)", "SARFE10-PBIG050-EVR0:CALCI")
A1.initialize()
S1.initialize()
A1_init = A1.read()
A1i = 0.
A1f = 360.
nstep = 20
lat = 1.
nav = 10
plt = plot(None, title="Output")[0]
plt.clear()
plt.setStyle(plt.Style.ErrorY)
plt.addSeries(LinePlotErrorSeries("Sensor1", Color.red))
def after_sample(record, scan):
plt.getSeries(0).appendData(record.positions[0], record.readables[0].mean, record.readables[0].stdev)
try:
S1_averager = create_averager(S1, nav, lat)
r = lscan(A1, S1_averager, A1i, A1f, nstep, latency=2.0, after_read = after_sample)
Act1 = r.getPositions(0)
S1mean = [val.mean for val in r.getReadable(0)]
S1rms = [val.stdev for val in r.getReadable(0)]
finally:
A1.write(A1_init)
A1.close()
S1.close()

View File

@@ -0,0 +1,23 @@
udlylist = ("SATUN06","SATUN07","SATUN08","SATUN09","SATUN10",
"SATUN11","SATUN12","SATUN13","SATUN15","SATUN16",
"SATUN17","SATUN18","SATUN19","SATUN20","SATUN21")
#for udly in udlylist: caputq(udly + "-UDLY060:OFF-OP", caget(udly + "-CHIC:OFFSET"))
#for udly in udlylist: caputq(udly + "-UDLY060:DEL-OP", caget(udly + "-CHIC:DELAY"))
#for udly in udlylist: caputq(udly + "-UDLY060:PH-SHIFT-OP", caget(udly + "-CHIC:PHASE"))
#for udly in udlylist: caputq(udly + "-UDLY060:GAP-U-SET-OP", caget(udly + "-CHIC:G1"))
#for udly in udlylist: caputq(udly + "-UDLY060:GAP-D-SET-OP", caget(udly + "-CHIC:G2"))
#for udly in udlylist: caputq(udly + "-UDLY060:GAP-U-SET-OP", caget(udly + "-UDLY060:GAP-U-SET"))
#for udly in udlylist: caputq(udly + "-UDLY060:GAP-D-SET-OP", caget(udly + "-UDLY060:GAP-D-SET"))
#for udly in udlylist: caputq(udly + "-UDLY060:OFF-OP", 0.0)
#for udly in udlylist: caputq(udly + "-UDLY060:DEL-OP", 0.600)
#for udly in udlylist: caputq(udly + "-UDLY060:GAP-U-SET", 75)
#for udly in udlylist: caputq(udly + "-UDLY060:GAP-D-SET", 75)
for udly in udlylist: caputq(udly + "-UDLY060:PH-SHIFT-OP", 0.0)
#for udly in udlylist: caputq(udly + "-CHIC:OFFSET", 50.0)
#for udly in udlylist: caputq(udly + "-CHIC:DELAY", 0.600)
#for udly in udlylist: caputq(udly + "-CHIC:G1", 32)
#for udly in udlylist: caputq(udly + "-CHIC:G2", 28)
#for udly in udlylist: caputq(udly + "-CHIC:PHASE", 0.0)

View File

@@ -0,0 +1,22 @@
udlylist = ("SATUN06","SATUN07","SATUN08","SATUN09","SATUN10",
"SATUN11","SATUN12","SATUN13","SATUN15","SATUN16",
"SATUN17","SATUN18","SATUN19","SATUN20","SATUN21")
uindlist = ("SATUN06","SATUN07","SATUN08","SATUN09","SATUN10","SATUN11","SATUN12","SATUN13",
"SATUN15","SATUN16","SATUN17","SATUN18","SATUN19","SATUN20","SATUN21","SATUN22")
#for udly in udlylist: caputq(udly + "-UDLY060:OFF-OP-SIMU", caget(udly + "-UDLY060:OFF-OP"))
#for udly in udlylist: caputq(udly + "-UDLY060:DEL-OP-SIMU", caget(udly + "-UDLY060:DEL-OP"))
#for udly in udlylist: caputq(udly + "-UDLY060:PH-SHIFT-OP-SIMU", caget(udly + "-UDLY060:PH-SHIFT-OP"))
#for udly in udlylist: caputq(udly + "-UDLY060:GAP-U-SET-SIMU", caget(udly + "-CHIC:G1"))
#for udly in udlylist: caputq(udly + "-UDLY060:GAP-D-SET-SIMU", caget(udly + "-CHIC:G2"))
for udly in udlylist: caputq(udly + "-UDLY060:GAP-U-SET-SIMU", caget(udly + "-UDLY060:GAP-U-SET"))
for udly in udlylist: caputq(udly + "-UDLY060:GAP-D-SET-SIMU", caget(udly + "-UDLY060:GAP-D-SET"))
#for udly in udlylist: caputq(udly + "-UDLY060:OFF-OP-SIMU", 0.0)
#for udly in udlylist: caputq(udly + "-UDLY060:DEL-OP-SIMU", 0.020)
#for udly in udlylist: caputq(udly + "-UDLY060:GAP-U-SET-SIMU", 70)
#for udly in udlylist: caputq(udly + "-UDLY060:GAP-D-SET-SIMU", 60)
#for udly in udlylist: caputq(udly + "-UDLY060:PH-SHIFT-OP-SIMU", 0.0)
#for udly in udlylist: caputq(udly + "-UDLY060:PH-SHIFT-OP-SIMU", caget(udly + "-UDLY060:PH-SHIFT-OP-SIMU") + 360)
#for uind in uindlist: caputq(uind + "-UIND030:K_SET_SIMU", caget(uind + "-UIND030:K_SET"))
#for uind in uindlist: caputq(uind + "-UIND030:POL-SET-SIMU", caget(uind + "-UIND030:POL-SET"))
#caputq("SATCB01:ENE-FILT-OP-SIMU", caget("SATCB01:ENE-FILT-OP"))

View File

@@ -0,0 +1,65 @@
caputq("SATUN06-UDLY060:GAP-U-SET-SIMU", 45.5284121698225)
caputq("SATUN06-UDLY060:GAP-D-SET-SIMU", 45.7245793466707)
caputq("SATUN07-UDLY060:GAP-U-SET-SIMU", 45.6122875866939)
caputq("SATUN07-UDLY060:GAP-D-SET-SIMU", 45.5495116792557)
caputq("SATUN08-UDLY060:GAP-U-SET-SIMU", 45.0316550113184)
caputq("SATUN08-UDLY060:GAP-D-SET-SIMU", 45.0726322443132)
caputq("SATUN09-UDLY060:GAP-U-SET-SIMU", 45.1859352796807)
caputq("SATUN09-UDLY060:GAP-D-SET-SIMU", 45.2128432714865)
caputq("SATUN10-UDLY060:GAP-U-SET-SIMU", 46.7937047025798)
caputq("SATUN10-UDLY060:GAP-D-SET-SIMU", 46.7513031527526)
caputq("SATUN11-UDLY060:GAP-U-SET-SIMU", 52.9447733636882)
caputq("SATUN11-UDLY060:GAP-D-SET-SIMU", 53.5729790819476)
caputq("SATUN12-UDLY060:GAP-U-SET-SIMU", 53.7916892349295)
caputq("SATUN12-UDLY060:GAP-D-SET-SIMU", 53.8300506580993)
caputq("SATUN13-UDLY060:GAP-U-SET-SIMU", 50.4352560592426)
caputq("SATUN13-UDLY060:GAP-D-SET-SIMU", 50.4669477318729)
caputq("SATUN15-UDLY060:GAP-U-SET-SIMU", 64.6414630104251)
caputq("SATUN15-UDLY060:GAP-D-SET-SIMU", 64.6278536657919)
caputq("SATUN16-UDLY060:GAP-U-SET-SIMU", 70.4210617446455)
caputq("SATUN16-UDLY060:GAP-D-SET-SIMU", 70.4253663428239)
caputq("SATUN17-UDLY060:GAP-U-SET-SIMU", 72.8843248347666)
caputq("SATUN17-UDLY060:GAP-D-SET-SIMU", 72.8889551373701)
caputq("SATUN18-UDLY060:GAP-U-SET-SIMU", 68.716248761714)
caputq("SATUN18-UDLY060:GAP-D-SET-SIMU", 68.7308510402703)
caputq("SATUN19-UDLY060:GAP-U-SET-SIMU", 73.4248071668705)
caputq("SATUN19-UDLY060:GAP-D-SET-SIMU", 73.414136218251)
caputq("SATUN20-UDLY060:GAP-U-SET-SIMU", 71.6780919568848)
caputq("SATUN20-UDLY060:GAP-D-SET-SIMU", 71.5809359122368)
caputq("SATUN21-UDLY060:GAP-U-SET-SIMU", 69.6290129308302)
caputq("SATUN21-UDLY060:GAP-D-SET-SIMU", 69.4142627102515)
caputq("SATUN06-UIND030:K_SET_SIMU", 1.51136800800815)
caputq("SATUN07-UIND030:K_SET_SIMU", 2.02084710399842)
caputq("SATUN08-UIND030:K_SET_SIMU", 1.53640591569033)
caputq("SATUN09-UIND030:K_SET_SIMU", 2.54178242706297)
caputq("SATUN10-UIND030:K_SET_SIMU", 2.54185323315769)
caputq("SATUN11-UIND030:K_SET_SIMU", 2.54186507638525)
caputq("SATUN12-UIND030:K_SET_SIMU", 2.54190460717311)
caputq("SATUN13-UIND030:K_SET_SIMU", 2.5418814596268)
caputq("SATUN15-UIND030:K_SET_SIMU", 2.54190138849029)
caputq("SATUN16-UIND030:K_SET_SIMU", 2.54186507638525)
caputq("SATUN17-UIND030:K_SET_SIMU", 2.54190460717311)
caputq("SATUN18-UIND030:K_SET_SIMU", 2.54190138849029)
caputq("SATUN19-UIND030:K_SET_SIMU", 2.54186507638525)
caputq("SATUN20-UIND030:K_SET_SIMU", 2.54186507638525)
caputq("SATUN21-UIND030:K_SET_SIMU", 2.54186507638525)
caputq("SATUN22-UIND030:K_SET_SIMU", 2.54182934195365)
caputq("SATUN06-UDLY060:PH-SHIFT-OP-SIMU", -14.0)
caputq("SATUN07-UDLY060:PH-SHIFT-OP-SIMU", -108.5)
caputq("SATUN08-UDLY060:PH-SHIFT-OP-SIMU", 101.0)
caputq("SATUN09-UDLY060:PH-SHIFT-OP-SIMU", -58.0)
caputq("SATUN10-UDLY060:PH-SHIFT-OP-SIMU", 158.0)
caputq("SATUN11-UDLY060:PH-SHIFT-OP-SIMU", -129.5)
caputq("SATUN12-UDLY060:PH-SHIFT-OP-SIMU", -48.5)
caputq("SATUN13-UDLY060:PH-SHIFT-OP-SIMU", 180.0)
caputq("SATUN15-UDLY060:PH-SHIFT-OP-SIMU", -12.8)
caputq("SATUN16-UDLY060:PH-SHIFT-OP-SIMU", 47.7)
caputq("SATUN17-UDLY060:PH-SHIFT-OP-SIMU", -9.0)
caputq("SATUN18-UDLY060:PH-SHIFT-OP-SIMU", 28.0)
caputq("SATUN19-UDLY060:PH-SHIFT-OP-SIMU", 14.1)
caputq("SATUN20-UDLY060:PH-SHIFT-OP-SIMU", -119.4)
caputq("SATUN21-UDLY060:PH-SHIFT-OP-SIMU", 112.5)

View File

@@ -0,0 +1,16 @@
caputq("SATUN06-UIND030:K_SET_SIMU", 2.04088453330036)
caputq("SATUN07-UIND030:K_SET_SIMU", 2.59901953158514)
caputq("SATUN08-UIND030:K_SET_SIMU", 2.06761290521536)
caputq("SATUN09-UIND030:K_SET_SIMU", 3.18987112455146)
caputq("SATUN10-UIND030:K_SET_SIMU", 3.18995231615947)
caputq("SATUN11-UIND030:K_SET_SIMU", 3.18996589651639)
caputq("SATUN12-UIND030:K_SET_SIMU", 3.19001122560207)
caputq("SATUN13-UIND030:K_SET_SIMU", 3.18998468281204)
caputq("SATUN15-UIND030:K_SET_SIMU", 3.19000753480694)
caputq("SATUN16-UIND030:K_SET_SIMU", 3.18996589651639)
caputq("SATUN17-UIND030:K_SET_SIMU", 3.19001122560207)
caputq("SATUN18-UIND030:K_SET_SIMU", 3.19000753480694)
caputq("SATUN19-UIND030:K_SET_SIMU", 3.18996589651639)
caputq("SATUN20-UIND030:K_SET_SIMU", 3.18996589651639)
caputq("SATUN21-UIND030:K_SET_SIMU", 3.18996589651639)
caputq("SATUN22-UIND030:K_SET_SIMU", 3.18992492068136)

3
script/Undulators/K-calc_AR.py Executable file → Normal file
View File

@@ -3,7 +3,8 @@ Eph2 = 2.425 # desired photon energy in keV. Don't forget .0 at the end!!
do_elog = True
undlist = ("SARUN03","SARUN04","SARUN05","SARUN06","SARUN07","SARUN08","SARUN09","SARUN10","SARUN11","SARUN12","SARUN13","SARUN14","SARUN15")
undlist = ("SARUN03","SARUN04","SARUN05","SARUN06","SARUN07","SARUN08","SARUN09",
"SARUN10","SARUN11","SARUN12","SARUN13","SARUN14","SARUN15")
K1, K2 = {}, {}
for und in undlist:

3
script/Undulators/K-calc_AT.py Executable file → Normal file
View File

@@ -3,7 +3,8 @@ Eph2 = 0.710 # desired photon energy in keV. Don't forget .0 at the end!!
do_elog = False
undlist = ("SATUN06", "SATUN07", "SATUN08","SATUN09","SATUN10","SATUN11","SATUN12","SATUN13","SATUN15","SATUN16","SATUN17","SATUN18","SATUN19","SATUN20","SATUN21","SATUN22")
undlist = ("SATUN06","SATUN07","SATUN08","SATUN09","SATUN10","SATUN11","SATUN12","SATUN13",
"SATUN15","SATUN16","SATUN17","SATUN18","SATUN19","SATUN20","SATUN21","SATUN22")
K1, K2 = {}, {}
for und in undlist:

View File

@@ -0,0 +1,20 @@
from random import random
undlist = ("SARUN03","SARUN04","SARUN05","SARUN06","SARUN07","SARUN08","SARUN09",
"SARUN10","SARUN11","SARUN12","SARUN13","SARUN14","SARUN15")
i = 0
for und in undlist:
K_taper = (-1)**i * 0.25 + random() * 0.050 - 0.025
i = i + 1
K = caget(und + "-UIND030:K_SET")
K_min = caget(und + "-UIND030:K_SET.DRVL")
K_max = caget(und + "-UIND030:K_SET.DRVH")
if K + K_taper > K_max:
K_taper = K_max - K - random() * 0.025
if K + K_taper < K_min:
K_taper = K_min - K + random() * 0.025
print(K, K_taper, K + K_taper)
caputq(und + "-UIND030:K_TAPER_SET", K_taper)
set_return("Success")

10
script/Undulators/K_AR_scale.py Executable file → Normal file
View File

@@ -3,9 +3,11 @@ Eph1 = caget("SARUN:FELPHOTENE")
Eph2 = Eph1 + dEph
do_elog = True
#do_elog = True
do_elog = False
undlist = ("SARUN03","SARUN04","SARUN05","SARUN06","SARUN07","SARUN08","SARUN09","SARUN10","SARUN11","SARUN12","SARUN13","SARUN14","SARUN15")
undlist = ("SARUN03","SARUN04","SARUN05","SARUN06","SARUN07","SARUN08","SARUN09",
"SARUN10","SARUN11","SARUN12","SARUN13","SARUN14","SARUN15")
K1, K2 = {}, {}
for und in undlist:
@@ -18,7 +20,7 @@ for und in undlist: caputq(und + "-UIND030:K_SET", K2[und])
#Elog entry
if do_elog:
title = "Wavelength change"
log_msg = "Old photon energy: %0.2f" % Eph1 + " kev\n"
log_msg = log_msg + "New photon energy: %0.2f" % Eph2 + " keV\n"
log_msg = "Old photon energy: %0.3f" % Eph1 + " kev\n"
log_msg = log_msg + "New photon energy: %0.3f" % Eph2 + " keV\n"
elog(title, log_msg)

View File

@@ -0,0 +1,21 @@
print "ENTER"
taper_lin = caget("SARUN:TAPER-LIN") * 1e-6
taper_qua = caget("SARUN:TAPER-QUA") * 1e-6
taper_lin_start = caget("SARUN:TAPER-LIN-START.RVAL")
taper_lin_stop = caget("SARUN:TAPER-LIN-STOP.RVAL")
taper_qua_start = caget("SARUN:TAPER-QUA-START.RVAL")
taper_qua_stop = caget("SARUN:TAPER-QUA-STOP.RVAL")
undlist = ("SARUN03","SARUN04","SARUN05","SARUN06","SARUN07","SARUN08","SARUN09",
"SARUN10","SARUN11","SARUN12","SARUN13","SARUN14","SARUN15")
u = 0
i, j = 0, 0
for und in undlist:
K_taper = taper_lin * i + taper_qua * j**2
if taper_lin_start <= u <= taper_lin_stop: i = i + 1
if taper_qua_start <= u <= taper_qua_stop: j = j + 1
caputq(und + "-UIND030:K_TAPER_SET", K_taper)
u = u + 1
set_return("Success")

View File

@@ -0,0 +1,10 @@
undlist = ("SARUN03","SARUN04","SARUN05","SARUN06","SARUN07","SARUN08","SARUN09",
"SARUN10","SARUN11","SARUN12","SARUN13","SARUN14","SARUN15")
for und in undlist:
K = caget(und + "-UIND030:K_SET")
K_taper = caget(und + "-UIND030:K_TAPER_SET")
K = K + K_taper
caputq(und + "-UIND030:K_SET", K)
caputq(und + "-UIND030:K_TAPER_SET", 0.0)

View File

@@ -0,0 +1,20 @@
from random import random
undlist = ("SATUN06","SATUN07","SATUN08","SATUN09",
"SATUN10","SATUN11","SATUN12","SATUN13")
i = 0
for und in undlist:
K_taper = (-1)**i * 0.25 + random() * 0.050 - 0.025
i = i + 1
K = caget(und + "-UIND030:K_SET")
K_min = caget(und + "-UIND030:K_SET.DRVL")
K_max = caget(und + "-UIND030:K_SET.DRVH")
if K + K_taper > K_max:
K_taper = K_max - K - random() * 0.025
if K + K_taper < K_min:
K_taper = K_min - K + random() * 0.025
print(K, K_taper, K + K_taper)
caputq(und + "-UIND030:K_TAPER_SET", K_taper)
set_return("Success")

View File

@@ -0,0 +1,20 @@
from random import random
undlist = ("SATUN15","SATUN16","SATUN17","SATUN18",
"SATUN19","SATUN20","SATUN21","SATUN22")
i = 0
for und in undlist:
K_taper = (-1)**i * 0.25 + random() * 0.050 - 0.025
i = i + 1
K = caget(und + "-UIND030:K_SET")
K_min = caget(und + "-UIND030:K_SET.DRVL")
K_max = caget(und + "-UIND030:K_SET.DRVH")
if K + K_taper > K_max:
K_taper = K_max - K - random() * 0.025
if K + K_taper < K_min:
K_taper = K_min - K + random() * 0.025
print(K, K_taper, K + K_taper)
caputq(und + "-UIND030:K_TAPER_SET", K_taper)
set_return("Success")

View File

@@ -0,0 +1,22 @@
from random import random
undlist = ("SATUN06","SATUN07","SATUN08","SATUN09",
"SATUN10","SATUN11","SATUN12","SATUN13",
"SATUN15","SATUN16","SATUN17","SATUN18",
"SATUN19","SATUN20","SATUN21","SATUN22")
i = 0
for und in undlist:
K_taper = (-1)**i * 0.25 + random() * 0.180 - 0.090
i = i + 1
K = caget(und + "-UIND030:K_SET")
K_min = caget(und + "-UIND030:K_SET.DRVL")
K_max = caget(und + "-UIND030:K_SET.DRVH")
if K + K_taper > K_max:
K_taper = K_max - K - random() * 0.025
if K + K_taper < K_min:
K_taper = K_min - K + random() * 0.025
print(K_taper)
caputq(und + "-UIND030:K_TAPER_SET", K_taper)
set_return("Success")

View File

@@ -1,11 +1,10 @@
dEph = caget("SATUN:USER-DELTA")
Eph1 = caget("SATUN13-UIND030:FELPHOTENE")
Eph1 = caget("SATUN:FELPHOTENE")
Eph2 = Eph1 + dEph
do_elog = True
undlist = ("SATUN06", "SATUN07", "SATUN08","SATUN09","SATUN10","SATUN11","SATUN12","SATUN13","SATUN15","SATUN16","SATUN17","SATUN18","SATUN19","SATUN20","SATUN21","SATUN22")
undlist = ("SATUN06","SATUN07","SATUN08","SATUN09","SATUN10","SATUN11","SATUN12","SATUN13",
"SATUN15","SATUN16","SATUN17","SATUN18","SATUN19","SATUN20","SATUN21","SATUN22")
K1, K2 = {}, {}
for und in undlist:
@@ -13,31 +12,9 @@ for und in undlist:
K1[und] = K
K2[und] = ((Eph1 / Eph2 * (K**2 + 2) - 2))**0.5
print K1,K2
for und in undlist: caputq(und + "-UIND030:K_SET", K2[und])
time.sleep(0.5) # Make sure the new K values have been written
onPVlist, goPVlist = [], []
for und in undlist:
caputq(und + "-UIND030:K_SET", K2[und])
onPVlist.append(und + '-UIND030:RADIAL-ON.PROC')
goPVlist.append(und + '-UIND030:RADIAL-GO.PROC')
time.sleep(0.5)
#Switching on radial motors (and pushing go) to ensure proper movements
for onPV in onPVlist: caput(onPV, 1)
time.sleep(0.5)
for goPV in goPVlist: caput(goPV, 1)
#Elog entry
if do_elog:
title = "Wavelength change"
log_msg = "Old photon energy: %0.2f" % Eph1 + " kev\n"
log_msg = log_msg + "New photon energy: %0.2f" % Eph2 + " keV\n"
elog(title, log_msg)
#Setting the gas detector photon energy
caputq("SATFE10-PEPG046:ENERGY", Eph2)
#Run Eugenio's phase-shifter/CHIC calculation
time.sleep(5.0)
caputq("SATUN-CHIC:PHOTON-ENERGY", Eph2)
time.sleep(0.2)
caputq("SATUN-CHIC:APPLY-DELAY-OFFSET-PHASE", 1)
for und in undlist: caput(und + "-UIND030:RADIAL-ON.PROC", 1)
for und in undlist: caput(und + "-UIND030:RADIAL-GO.PROC", 1)

View File

@@ -0,0 +1,19 @@
dEph = caget("SATUN:USER-DELTA")
Eph1 = caget("SATUN06-UIND030:FELPHOTENE")
Eph2 = Eph1 + dEph
undlist = ("SATUN06","SATUN07","SATUN08","SATUN09","SATUN10","SATUN11","SATUN12","SATUN13")
K1, K2 = {}, {}
for und in undlist:
K = caget(und + "-UIND030:K_SET")
K1[und] = K
K2[und] = ((Eph1 / Eph2 * (K**2 + 2) - 2))**0.5
print K1,K2
for und in undlist: caputq(und + "-UIND030:K_SET", K2[und])
time.sleep(0.5) # Make sure the new K values have been written
#Switching on radial motors (and pushing go) to ensure proper movements
for und in undlist: caput(und + "-UIND030:RADIAL-ON.PROC", 1)
for und in undlist: caput(und + "-UIND030:RADIAL-GO.PROC", 1)

View File

@@ -0,0 +1,19 @@
dEph = caget("SATUN:USER-DELTA")
Eph1 = caget("SATUN15-UIND030:FELPHOTENE")
Eph2 = Eph1 + dEph
undlist = ("SATUN15","SATUN16","SATUN17","SATUN18","SATUN19","SATUN20","SATUN21","SATUN22")
K1, K2 = {}, {}
for und in undlist:
K = caget(und + "-UIND030:K_SET")
K1[und] = K
K2[und] = ((Eph1 / Eph2 * (K**2 + 2) - 2))**0.5
print K1,K2
for und in undlist: caputq(und + "-UIND030:K_SET", K2[und])
time.sleep(0.5) # Make sure the new K values have been written
#Switching on radial motors (and pushing go) to ensure proper movements
for und in undlist: caput(und + "-UIND030:RADIAL-ON.PROC", 1)
for und in undlist: caput(und + "-UIND030:RADIAL-GO.PROC", 1)

View File

@@ -1,33 +0,0 @@
dEph = caget("SATUN:USER-DELTA")
Eph1 = caget("SATUN:FELPHOTENE")
Eph2 = Eph1 + dEph
do_elog = True
undlist = ("SATUN06", "SATUN07", "SATUN08","SATUN09","SATUN10","SATUN11","SATUN12","SATUN13","SATUN15","SATUN16","SATUN17","SATUN18","SATUN19","SATUN20","SATUN21","SATUN22")
K1, K2 = {}, {}
for und in undlist:
K = caget(und + "-UIND030:K_SET")
K1[und] = K
K2[und] = ((Eph1 / Eph2 * (K**2 + 2) - 2))**0.5
print K1,K2
for und in undlist: caputq(und + "-UIND030:K_SET", K2[und])
time.sleep(0.5) # Make sure the new K values have been written
#Switching on radial motors (and pushing go) to ensure proper movements
for und in undlist: caput(und + "-UIND030:RADIAL-ON.PROC", 1)
for und in undlist: caput(und + "-UIND030:RADIAL-GO.PROC", 1)
time.sleep(5.0) # Make sure the undulators finished moving
#Run Eugenio's phase-shifter/CHIC calculation
caput("SATUN-CHIC:PHOTON-ENERGY", Eph2)
caput("SATUN-CHIC:APPLY-DELAY-OFFSET-PHASE", 1)
#Elog entry
if do_elog:
title = "Wavelength change"
log_msg = "Old photon energy: %0.2f" % Eph1 + " kev\n"
log_msg = log_msg + "New photon energy: %0.2f" % Eph2 + " keV\n"
elog(title, log_msg)

View File

@@ -0,0 +1,18 @@
taper_lin = caget("SATUN:TAPER-LIN") * 1e-6
taper_qua = caget("SATUN:TAPER-QUA") * 1e-6
taper_lin_start = caget("SATUN:TAPER-LIN-START.RVAL")
taper_lin_stop = caget("SATUN:TAPER-LIN-STOP.RVAL")
taper_qua_start = caget("SATUN:TAPER-QUA-START.RVAL")
taper_qua_stop = caget("SATUN:TAPER-QUA-STOP.RVAL")
undlist = ("SATUN06","SATUN07","SATUN08","SATUN09","SATUN10","SATUN11","SATUN12","SATUN13",
"SATUN15","SATUN16","SATUN17","SATUN18","SATUN19","SATUN20","SATUN21","SATUN22")
u = 0
i, j = 0, 0
for und in undlist:
K_taper = taper_lin * i + taper_qua * j**2
if taper_lin_start <= u <= taper_lin_stop: i = i + 1
if taper_qua_start <= u <= taper_qua_stop: j = j + 1
caputq(und + "-UIND030:K_TAPER_SET", K_taper)
u = u + 1

View File

@@ -0,0 +1,18 @@
taper_lin = caget("SATUN:TAPER-LIN") * 1e-6
taper_qua = caget("SATUN:TAPER-QUA") * 1e-6
taper_lin_start = caget("SATUN:TAPER-LIN-START.RVAL")
taper_lin_stop = caget("SATUN:TAPER-LIN-STOP.RVAL")
taper_qua_start = caget("SATUN:TAPER-QUA-START.RVAL")
taper_qua_stop = caget("SATUN:TAPER-QUA-STOP.RVAL")
undlist = ("SATUN06","SATUN07","SATUN08","SATUN09","SATUN10","SATUN11","SATUN12","SATUN13",
"SATUN15","SATUN16","SATUN17","SATUN18","SATUN19","SATUN20","SATUN21","SATUN22")
u = 0
i, j = 0, 0
for und in undlist:
K_taper = taper_lin * i + taper_qua * j**2
if taper_lin_start <= u <= taper_lin_stop: i = i + 1
if taper_qua_start <= u <= taper_qua_stop: j = j + 1
if 0 <= u <= 7: caputq(und + "-UIND030:K_TAPER_SET", K_taper)
u = u + 1

View File

@@ -0,0 +1,18 @@
taper_lin = caget("SATUN:TAPER-LIN") * 1e-6
taper_qua = caget("SATUN:TAPER-QUA") * 1e-6
taper_lin_start = caget("SATUN:TAPER-LIN-START.RVAL")
taper_lin_stop = caget("SATUN:TAPER-LIN-STOP.RVAL")
taper_qua_start = caget("SATUN:TAPER-QUA-START.RVAL")
taper_qua_stop = caget("SATUN:TAPER-QUA-STOP.RVAL")
undlist = ("SATUN06","SATUN07","SATUN08","SATUN09","SATUN10","SATUN11","SATUN12","SATUN13",
"SATUN15","SATUN16","SATUN17","SATUN18","SATUN19","SATUN20","SATUN21","SATUN22")
u = 0
i, j = 0, 0
for und in undlist:
K_taper = taper_lin * i + taper_qua * j**2
if taper_lin_start <= u <= taper_lin_stop: i = i + 1
if taper_qua_start <= u <= taper_qua_stop: j = j + 1
if 8 <= u <= 15: caputq(und + "-UIND030:K_TAPER_SET", K_taper)
u = u + 1

View File

@@ -0,0 +1,10 @@
undlist = ("SATUN06","SATUN07","SATUN08","SATUN09","SATUN10","SATUN11","SATUN12","SATUN13",
"SATUN15","SATUN16","SATUN17","SATUN18","SATUN19","SATUN20","SATUN21","SATUN22")
for und in undlist:
K = caget(und + "-UIND030:K_SET")
K_taper = caget(und + "-UIND030:K_TAPER_SET")
K = K + K_taper
caputq(und + "-UIND030:K_SET", K)
caputq(und + "-UIND030:K_TAPER_SET", 0.0)

View File

@@ -0,0 +1,26 @@
unit = "SATUN06"
bpmlist = ("SATUN01-DBPM070","SATUN02-DBPM070", "SATUN03-DBPM070", "SATUN04-DBPM070", "SATUN05-DBPM410", "SATUN06-DBPM070", "SATUN07-DBPM070", "SATUN08-DBPM070", "SATUN09-DBPM070", "SATUN10-DBPM070", "SATUN11-DBPM070", "SATUN12-DBPM070", "SATUN13-DBPM070", "SATUN14-DBPM410", "SATUN15-DBPM070", "SATUN16-DBPM070", "SATUN17-DBPM070", "SATUN18-DBPM070", "SATUN19-DBPM070", "SATUN20-DBPM070", "SATUN21-DBPM070", "SATUN22-DBPM070", "SATMA02-DBPM030", "SATMA02-DBPM060", "SATBD01-DBPM020", "SATBD01-DBPM060", "SATBD01-DBPM100")
bpmlist2 = ("SATUN01-DBPM070","SATUN02-DBPM070", "SATUN03-DBPM070", "SATUN04-DBPM070", "SATUN05-DBPM410", "SATUN06-DBPM070", "SATUN07-DBPM070", "SATUN08-DBPM070", "SATUN09-DBPM070", "SATUN10-DBPM070")
def read(bpmlist):
X, Y = [], []
for bpm in bpmlist:
X.append(caget(bpm + ":X2"))
Y.append(caget(bpm + ":Y2"))
return X, Y
def average(bpmlist):
X,Y = [0 for i in range(27)], [0 for i in range(27)]
for i in range(10):
x, y = read(bpmlist)
X = arradd(X,x)
Y = arradd(Y,y)
print(i)
for val in X: val = val / 10
for val in Y: val = val / 10
return X, Y
X1, Y1 = average(bpmlist)
print(X1, Y1)
res = Lscan

View File

@@ -0,0 +1,20 @@
devlist = ['SARUN03', 'SARUN04', 'SARUN05', \
'SARUN06', 'SARUN07', 'SARUN08', 'SARUN09', 'SARUN10', \
'SARUN11', 'SARUN12', 'SARUN13', 'SARUN14', 'SARUN15']
bpm_x = "-DBPM070:OFFS-X"
bpm_y = "-DBPM070:OFFS-Y"
gm_x = "-UIND030:GM-X-SET"
gm_y = "-UIND030:GM-Y-SET"
for i,dev in enumerate(devlist):
off_x = round(caget(dev + bpm_x),3)
off_y = round(caget(dev + bpm_y),3)
#off_y = 0.01
gm_pos_x = round(caget(dev + gm_x),3)
gm_pos_y = round(caget(dev + gm_y),3)
gm_new_pos_x = gm_pos_x + off_x
gm_new_pos_y = gm_pos_y + off_y
#print(dev + gm_x + ': gm_new_pos_x = ' + str(gm_new_pos_x) + ' mm, offset = ' + str(off_x) + ' mm')
print(dev + gm_y + ': gm_new_pos_y = ' + str(gm_new_pos_y) + ' mm, offset = ' + str(off_y) + ' mm')
#caput(dev + gm_x, float(gm_new_pos_x))
caput(dev + gm_y, float(gm_new_pos_y))

View File

@@ -0,0 +1,24 @@
# PPRM113 position: OAPU044 closed (um)
x1_scr = 29.0
y1_scr = 75.0
# PPRM113 position: OAPU092 closed (um)
x2_scr = 14.0
y2_scr = 75.0
# PPRM113 position: max intensity (um)
xm_scr = 20.0
ym_scr = 75.0
z_sarun09 = 537.248
z_oapu044 = 612.238
z_oapu092 = 656.239
z_pprm113 = 680.843
d1 = z_pprm113 - z_oapu044
d2 = z_oapu044 - z_sarun09
d3 = z_pprm113 - z_oapu092
d4 = z_oapu092 - z_sarun09
k = d1 / d2 - d3 / d4
dx_offset = 1 / k * (x1_scr - x2_scr)
dy_offset = 1 / k * (y1_scr - y2_scr)
dx_slope = -(dx_offset / d4 + (xm_scr - x2_scr) / (d1 + d2)) * 4.750
dy_slope = -(dy_offset / d4 + (ym_scr - y2_scr) / (d1 + d2)) * 4.750
print(dx_offset, dy_offset)
print(dx_slope, dy_slope)

View File

@@ -0,0 +1,64 @@
IN_POSITION_BAND = 10.0
# EInkommentieren fuer Messungen Mit PSCR136
# Auskommentieren fuer Messungen Mit PCEL
#
#cam_server.start("SATOP31-PSCR136_sp1", True)
cam_server.start("SATOP31-PSRD175_sp1", True)
#cam_server.start("SATOP31-PPRM176_sp1", True)
cam_server.stream.waitCacheChange(-1)
i= cam_server.stream.getChild("intensity")
i_avg = create_averager(i, 20, interval = -1)
# muss auskommentiert bleiben
#Keithley = Channel("SATOP31-CSSU-PCEL1381:READOUT",'d', monitored ='True')
#K_avg = create_averager(Keithley, 5, interval = -1)
def beam_ok():
I0 = caget ("SATFE10-PEPG046:PHOTON-ENERGY-PER-PULSE-AVG")
if I0 > 100:
return "Yes"
else :
return "Yes"
def before_sampling(rec):
while beam_ok() == "No":
time.sleep(0.1)
print(".")
def after_sampling(rec):
if beam_ok() == "No":
rec.invalidate()
i0 = Channel("SATFE10-PEPG046:PHOTON-ENERGY-PER-PULSE-AVG",'d')
class VLSSGM(RegisterBase):
def doWrite(self, value):
caput ("SATOP11-OSGM087:SetEnergy", value)
time.sleep(0.2)
cawait('SATOP11-OSGM087:MOVING', 1, timeout = 20.0, type = 'i')
def doRead(self):
return caget("SATOP11-OSGM087:photonenergy")
athos = VLSSGM()
athos.initialize()
# startenergy, stopenergy, schrittweite, wartezeit,
lscan( athos, [i0,i_avg], 1600.0, 1720.0, 5.0, 0.5, setpoints=True,zigzag=True) # Scans mit PSCR136
#lscan( athos, [i0,K_avg], 833.5, 837, 0.05, 0.5, setpoints=True,zigzag=True) # Scans mit PCEL
#lscan( athos, [i0,i_avg], 760.0, 820.0, 2.0, 0.5, setpoints=True,zigzag=True) # Scans mit PSCR136
#lscan( athos, [i0,i_avg], 380.0, 410.0, 1.0, 0.5, setpoints=True,zigzag=True) # Scans mit PSCR136
#caput ("ATHOS:SetEnergy", 680.0)
#tscan( [i], 10, 1 , passes=1)

View File

@@ -14,7 +14,7 @@ run("Devices/Elements")
###################################################################################################
import ch.psi.pshell.data.LayoutSF as LayoutSF
LayoutSF.setExperimentArguments([charge, laser, rep_rate, destination_AR, energy_AR])
LayoutSF.setExperimentArguments([charge, laser, rep_rate_bunch_1, rep_rate_bunch_2, destination_AR, energy_AR])
@@ -391,7 +391,7 @@ def setup_camera_scan():
if not is_laser_on(1) and not is_laser_on(2):
raise Exception("Both bunches are on delay")
save_laser_state()
multiple_background = multiple_background and use_background
multiple_background = use_background and multiple_background
if source == "server":
if use_screen_panel_stream:
cam_server.start(camera_name + "_sp1", True)
@@ -499,17 +499,14 @@ def end_camera_scan():
###################################################################################################
if get_context().isServerEnabled():
import ch.psi.pshell.epics.CAS as CAS
#CAS.setServerPort(5062)
class ServerUrl(RegisterBase):
def doRead(self):
return get_context().server.baseURL
d = ServerUrl()
d.initialize()
cas5 = CAS("PSHELL_OP:SERVER_URL", d, 'string')
add_device(EpicsServerUrl("epics_server_url_old", "PSHELL_OP:SERVER_URL"), True) #TODO: Change dependencies to "SF-PSHELL_OP:SERVER_URL and remove
add_device(EpicsServerUrl("epics_server_url", "SF-PSHELL_OP:SERVER_URL"), True)
add_device(EpicsServerState("epics_server_state", "SF-PSHELL_OP:STATE"), True)
add_device(EpicsCmdAPI("epics_cmd", "SF-PSHELL_OP:CMD", as_string=False), True)
add_device(EpicsCmdAPI("epics_cmd_bg", "SF-PSHELL_OP:CMD_BG", as_string=False, background=True), True)
add_device(EpicsCmdAPI("epics_cmd_str", "SF-PSHELL_OP:CMD_STR", as_string=True), True)
add_device(EpicsCmdAPI("epics_cmd_str_bg", "SF-PSHELL_OP:CMD_STR_BG", as_string=True, background=True), True)

View File

@@ -0,0 +1,21 @@
CAMERA = "SARES20-CAMS142-M3"
CAMERA = "SARFE10-PSSS059"
CAMERA = "SATBD02-DSCR050"
CAMERA = "SATES31-CAMS187-RIXS1"
CAMERA = "SAROP21-PPRM138"
CAMERA = "SARES20-CAMS142-C2"
CAMERA_URL = caget(CAMERA + ":BSREADCONFIG").replace("tcp://daq", "tcp://")
#CAMERA_URL= "tcp://sf-sioc-cs-83:9020"
#CAMERA_URL= "tcp://sf-sioc-cs-64:9000"
print CAMERA_URL
st1 = Stream("st1", CAMERA_URL, SocketType.PULL)
st1.initialize()
st1.start()
st1.waitCacheChange(3000)
try:
r=bscan (st1, records=5, timeout=10.0, save=False, enabled_plots=[st1,])
v= st1.getValues()
finally:
st1.close()

View File

@@ -1,8 +1,29 @@
from jeputils import *
"""
import_py("CPython/linfit", "test")
def test():
return np.ones(5)
print test()
"""
"""
def test2(name, x=None, y=None):
print (name)
return x+y
import_py("CPython/linfit", "test2")
print test2("x", to_array([0,1,2,3,4],'d'), to_array([5,1,2,3,4],'d'))
"""
data, dims = [1,2,3,4,5,6,7,8,9,0], [2,5]
array = to_npa(data, dims,'d') #Auxiliary function to create numpy arrays from lists or java arrays.
ret = call_jep("test/cpython", "calc", [array,])
print ret.getDimensions(),ret.getData()
ret = call_jep("test/cpython", "test_pandas")
ret = call_jep("test/cpython", "test_pandas")

View File

@@ -0,0 +1,27 @@
dry_run = True
use_screen_panel_stream = True
camera_name = "simulation" if dry_run else "SINEG01-DSCR190"
use_good_region=False
number_images=5
use_background=False
source = "server"
plot_image = False
setup_camera_scan()
def after_sample(record, scan):
x = record[0]
y = record[1]
stdev_x = record[2]
stdev_y = record[3]
x, y, stdev_x, stdev_y = x.mean, y.mean, x.stdev, y.stdev
after_sample_camera_scan()
r = None
try:
sensors = get_camera_scan_sensors()
r = tscan(sensors, 10, 0.1, before_read = before_sample_camera_scan, after_read = after_sample)
finally:
end_camera_scan()

View File

@@ -0,0 +1,45 @@
dispatcher.config.validationInconsistency = dispatcher.config.Inconsistency.keep_as_is
#dispatcher.config.validationInconsistency = dispatcher.config.Inconsistency.adjust_global
import ch.psi.pshell.bs.StreamChannel as StreamChannel
def bsget(channel, modulo=StreamChannel.DEFAULT_MODULO, offset=StreamChannel.DEFAULT_OFFSET, timeout = 5.0):
"""Reads an values a bsread stream, using the default provider.
Args:
channel(str or list of str): channel name(s)
module(int, optional): stream modulo
offset(int, optional): stream offset
timeout(float, optional): stream timeout in secs
Returns:
BS value or list of values
"""
channels = to_list(channel)
ret = Stream.readChannels(channels, modulo, offset, int(timeout * 1000))
if is_string(channel):
return ret[0]
return ret
run ("Tools/dispatcher")
channel = "SATMA02-RLLE-DSP:PHASE-VS"
channel = "S10CB01-RLLE-DSP:PHASE-VS"
print get_dispatcher_channel_modulo(channel)
ch = get_dispatcher_channels("PHASE-VS")
for c in ch:
print c["name"],c.get("modulo")
print bsget(channel)
st1 = Stream("st1", dispatcher)
s1=st1.addScalar(channel,channel)
st1.initialize()
try:
bscan (st1, 10, title="bscan")
finally:
st1.close()

View File

@@ -0,0 +1,2 @@
#N_POINTS=3
tscan(charge, N_POINTS, 1.0)

22
script/test/TestJep.py Normal file
View File

@@ -0,0 +1,22 @@
from jeputils import import_py
import_py("CPython/linfit", "linfit")
import_py("CPython/gfitoff", "gfitoff")
x=[0,1,2,3,4,5,6,7,8,9]
y=[1,2,3,6,9,6,3,2,1,0]
(p, x_fit, y_fit, R2) = linfit(x,y)
#print "Fit: ", (p, x_fit, y_fit, R2)
plot((y,y_fit), name=("data", "fit"),xdata=(x,x_fit))
time.sleep(1.0)
from mathutils import Gaussian
x=to_array([-200.30429237268825, -200.2650700434188, -200.22115208318002, -199.9457671375377, -199.86345548879072, -199.85213073174933, -199.35687977133284, -199.13811861090275, -197.97304970346386, -197.2952215624348, -195.09076092936948, -192.92276048970703, -191.96871876227698, -189.49577852322938, -187.9652790409825, -183.63756456925222, -180.04899765472996, -178.43839623242422, -174.07311671294445, -172.0410133577918, -165.90824309893102, -160.99771795989466, -159.30176653939253, -154.27688897558514, -152.0854103810786, -145.75652847587313, -140.80843828908465, -139.23982133191495, -134.27073891256106, -132.12649284133064, -125.95947209775511, -121.00309550337462, -119.26736932643232, -114.2706655484383, -112.07393889578914, -105.72295990367157, -100.8088439880125, -99.2034906238494, -94.30042325164636, -92.15010048151461, -85.92203653534293, -81.03913275494665, -79.27412793784428, -74.33487658582118, -72.06274362408762, -65.76562628131825, -60.91255356825276, -59.20334389560392, -54.33286972659312, -52.19387171350535, -45.94978737932291, -41.03014719193582, -39.301602568238906, -34.35572209014114, -32.04464301272608, -25.8221033382824, -20.922074315528747, -19.21590299233186, -14.31090212502093, -12.217203140101386, -5.9283722049240435, -0.9863587170369246, 0.7408048387279834, 5.71126832601389, 7.972628957879352, 14.204559894256546, 19.11839959633025, 20.8218087836657, 25.678748486941828, 27.822718344586864, 34.062659474970715, 38.9745656819391, 40.77409719734158, 45.72080631619803, 47.974156754056835, 54.23453768983539, 59.12020360609568, 60.77306570712026, 65.70734521458867, 67.8344660434617, 74.03187028154134, 78.96532114824849, 80.76070945985495, 85.74802197591286, 87.9140889204674, 94.18082276873524, 99.25790470037091, 100.68454787413205, 105.7213026221542, 107.79483801526698, 113.99555681638138, 119.0707052529143, 120.72715813056156, 125.77551384921307, 127.91257836719551, 134.2011330887875, 139.23043006997628, 140.71673537840158, 145.76288138835983, 147.80216629676042, 154.06420451405637, 159.0846626604798, 160.76183155710717, 165.73699067536242, 167.9265357747636, 173.96705069576544, 178.2522282751915, 179.9042617354548, 183.54586165856657, 185.23269803071796, 189.41678143751972, 191.87149157986588, 192.8741468985015, 195.0241934550453, 195.966634211846, 197.9821647518146, 198.99006812859284, 199.33202054855676, 199.91897441965887, 200.11536227958896, 200.22280936469997, 200.25181179127208],'d')
y=to_array([11.0, 6.0, 8.0, 5.0, 11.0, 7.0, 18.0, 11.0, 12.0, 10.0, 8.0, 6.0, 16.0, 4.0, 12.0, 9.0, 15.0, 14.0, 8.0, 20.0, 15.0, 8.0, 9.0, 11.0, 13.0, 12.0, 13.0, 15.0, 13.0, 20.0, 10.0, 7.0, 17.0, 11.0, 20.0, 13.0, 13.0, 23.0, 14.0, 10.0, 17.0, 15.0, 20.0, 16.0, 14.0, 13.0, 18.0, 22.0, 9.0, 20.0, 12.0, 14.0, 17.0, 19.0, 14.0, 14.0, 23.0, 19.0, 15.0, 20.0, 20.0, 21.0, 20.0, 23.0, 22.0, 15.0, 10.0, 17.0, 21.0, 15.0, 23.0, 23.0, 25.0, 18.0, 16.0, 21.0, 22.0, 16.0, 16.0, 14.0, 19.0, 20.0, 18.0, 20.0, 23.0, 13.0, 16.0, 20.0, 25.0, 15.0, 15.0, 17.0, 22.0, 26.0, 19.0, 30.0, 25.0, 17.0, 17.0, 23.0, 16.0, 27.0, 21.0, 21.0, 26.0, 27.0, 21.0, 17.0, 20.0, 20.0, 21.0, 19.0, 25.0, 19.0, 13.0, 23.0, 20.0, 20.0, 18.0, 20.0, 19.0, 25.0],'d')
[off, amp, com, sigma] = gfitoff(x, y, off=None, amp=None, com=None, sigma=None)
#print "Fit: ", [off, amp, com, sigma]
g = Gaussian(amp, com, sigma)
plot([y, [g.value(i)+off for i in x]], ["data", "fit"], xdata = x)

View File

@@ -0,0 +1,6 @@
stream_url = cam_server.getStream("SATES21-CAMS154-GIGE3_proc") #It is fixed, it could be defined directly as: sf-daqsync-12.psi.ch:9051
st1 = Stream("st1", stream_url, SocketType.PULL)
add_device(st1, force = True)
st1.start()
st1.waitCacheChange(5000)
show_panel(st1)

View File

@@ -0,0 +1,258 @@
import math
import sys, traceback
from mathutils import fit_polynomial, PolynomialFunction
from plotutils import plot_line, plot_function
from ch.psi.pshell.swing.Shell import getColorStdout
import org.apache.commons.math3.stat.correlation.PearsonsCorrelation as PearsonsCorrelation
try:
import ch.psi.pshell.bs.StreamMerger as StreamMerger
except:
merge_camera_stream = False
TYPE_CHANNEL = 0
TYPE_STREAM = 1
TYPE_CAMERA= 2
INVOKE_PLOT_UPDATES = True
if get_exec_pars().source == CommandSource.ui:
dx = "SINEG01-DICT215:B1_CHARGE"
#dx=get_beam_ok_channel(1)
#dx = "SLG-LCAM-C042 x_rms"
#dxtype = TYPE_CHANNEL
dxtype = TYPE_STREAM
#dxtype = TYPE_CAMERA
#dy = "SINDI01-RLLE-STA:SLAVE1-DLTIMER"
#dy = "SLG-LCAM-C042 y_rms"
#dytype = TYPE_CHANNEL
dy = "SATES31-CAMS187-RIXS1_sp1 intensity"
dytype = TYPE_CAMERA
#dy=get_beam_ok_channel(2)
#dytype = TYPE_STREAM
interval = 0.01
window = 40
p = plot(None)[0]
linear_fit = True
quadratic_fit = True
merge_camera_stream = True
print dx, dxtype
print dy, dytype
corr = None
pars_lin = None
pars_quad = None
pos_peak = None
neg_peak = None
stop_exec = None
bs = TYPE_STREAM in [dxtype, dytype]
for s in p.getAllSeries():
p.removeSeries(s)
_stream = None
_camname = None
instances = []
def _get_device(d, type):
global _stream, _camname
egu = None
if isinstance(d, basestring):
name = d.strip()
d = None
try:
d = get_device(name)
if d is None:
d = eval(name)
#print name
if d is not None:
if not isinstance(r, Device):
d = None
else:
try:
egu = d.unit
except:
pass
except:
pass
if d is None:
offset = 0
if type==TYPE_STREAM:
if " " in name:
tokens = name.split(" ")
name = tokens[0]
offset = int(tokens[1])
if _stream == None:
_stream = Stream("corr_stream", dispatcher)
instances.append(_stream)
#d = _stream.addScalar(name, name, int(interval*100), offset)
_stream.addScalar(name, name, int(interval*100), offset)
d=name
elif type==TYPE_CHANNEL:
d = Channel(name)
d.set_monitored(True)
elif type==TYPE_CAMERA:
tokens = name.split(" ")
_camname = tokens[0]
field = tokens[1]
return field, ""
else:
raise Exception("Invalid type: " + str(type))
if not isinstance(d, basestring):
instances.append(d)
try:
if type==TYPE_CHANNEL:
egu = caget(name+".EGU",'s')
except:
pass
else:
try:
egu = d.unit
except:
pass
return d, egu
dx, egux = _get_device(dx, dxtype)
dy, eguy = _get_device(dy, dytype)
p.getAxis(p.AxisId.X).setLabel(egux)
p.getAxis(p.AxisId.Y).setLabel(eguy)
merge = False
try:
if _stream != None:
_stream.initialize()
_stream.start(True)
if _camname != None:
shared = _camname.endswith("_sp1")
print "Camera: " , _camname, " shared: ", shared
cam_server.start(_camname, shared )
cam_server.stream.waitCacheChange(10000);
_camera_stream = cam_server.stream
if merge_camera_stream:
merge = ((dxtype==TYPE_CAMERA) and (dytype == TYPE_STREAM)) or ((dxtype==TYPE_STREAM) and (dytype == TYPE_CAMERA))
if merge:
_merger = StreamMerger("stream", _stream, cam_server.stream)
_merger.monitored=True
_merger.start()
_camera_stream.setBufferCapacity(500)
_stream.setBufferCapacity(500)
instances.append(_merger)
_merger.waitCacheChange(5000)
#print _merger.readables
_camera_stream=_merger
_stream = _merger
if dxtype==TYPE_CAMERA:
dx=_camera_stream.getChild(dx)
if dytype==TYPE_CAMERA:
dy=_camera_stream.getChild(dy)
if dxtype==TYPE_STREAM:
dx=_stream.getChild(dx)
if dytype==TYPE_STREAM:
dy=_stream.getChild(dy)
p.addSeries(LinePlotSeries("Data"))
sd=p.getSeries(0)
sd.setLinesVisible(False)
sd.setPointSize(4)
if get_exec_pars().source == CommandSource.ui:
if globals().has_key("marker"):
p.removeMarker(marker)
if globals().has_key("peak_marker"):
p.removeMarker(peak_marker)
marker=None
peak_marker=None
while(True):
#Sample and plot data
if bs == True:
_stream.waitCacheChange(10000)
#bsdata = list(_stream.take().values())
x=dx.read()
y=dy.read()
def update():
global marker, peak_marker, corr, pars_lin, pars_quad, pos_peak, neg_peak, stop_exec
sd.appendData(x, y)
if len(sd.x) > window:
#Remove First Element
sd.token.remove(0)
ax = sd.x
ay = sd.y
if len(ax)>2:
x1, x2 = min(ax), max(ax)
res = (x2-x1)/100
if x1!=x2:
#Display correlation
corr= PearsonsCorrelation().correlation(to_array(ax,'d'), to_array(ay,'d'))
s = "Correlation=" + str(round(corr,4))
#print s
if get_exec_pars().source == CommandSource.ui:
if marker is not None:
p.removeMarker(marker)
marker = p.addMarker(x2+res, p.AxisId.X, s, p.getBackground())
marker.setLabelPaint(getColorStdout())
if linear_fit:
#Calculate, print and plot linear fit
pars_lin = (a0,a1) = fit_polynomial(ay, ax, 1)
#print "Fit lin a1:" , a1, " a0:",a0
y1 = poly(x1, pars_lin)
y2 = poly(x2, pars_lin)
plot_line(p, x1, y1, x2, y2, width = 2, color = Color.BLUE, name = "Fit Linear")
if quadratic_fit:
#Calculate, print and plot quadratic fit
pars_quad = (a0,a1,a2) = fit_polynomial(ay, ax, 2)
#print "Fit quad a2:" , a2, "a1:" , a1, " a0:",a0
fitted_quad_function = PolynomialFunction(pars_quad)
ax = frange(x1, x2, res, True)
plot_function(p, fitted_quad_function, "Fit Quadratic", ax, color=Color.GREEN)
peak = None
peaks = calculate_peaks(fitted_quad_function, x1, x2, positive=True)
if len(peaks)>0:
peak = peaks[0]
pos_peak = str(round(peak,4))
peak_str = "Positive peak: " + pos_peak
else:
peaks = calculate_peaks(fitted_quad_function, x1, x2, positive=False)
if len(peaks)>0:
peak = peaks[0]
neg_peak = str(round(peak,4))
peak_str = "Negative peak: " + neg_peak
else:
pos_peak = neg_peak = None
if get_exec_pars().source == CommandSource.ui:
if peak_marker is not None:
p.removeMarker(peak_marker)
if peak is not None:
peak_marker = p.addMarker(peak, p.AxisId.X, peak_str, Color(0,128,0))
if INVOKE_PLOT_UPDATES:
invoke(update, False)
else:
update()
if stop_exec == True:
stop_exec = False
break
if bs != True:
time.sleep(interval)
except KeyboardInterrupt:
pass
finally:
for dev in instances:
try:
dev.close()
except:
pass
if _camname != None:
cam_server.stop()

View File

@@ -0,0 +1,43 @@
SCAN_TIME = 60
#dispatcher.config.mappingIncomplete=ch.psi.pshell.bs.DispatcherConfig.Incomplete.drop
st1 = Stream("st1", "tcp://sf-daqsync-08.psi.ch:9001", SocketType.SUB)
#st1 = Stream("st1", "tcp://sf-daqsync-02.psi.ch:31852", SocketType.PULL)
st2 = Stream("st1", dispatcher)
st2.addScalar("B1","SIN-CVME-TIFGUN-EVR0:BUNCH-1-OK", 1, 0)
st2.addScalar("B2","SIN-CVME-TIFGUN-EVR0:BUNCH-2-OK", 1, 0)
pids={}
count={}
def after_read(record, scan):
global pids, count
lastpid=pids.get(scan)
pid=record[0]
if lastpid:
if (lastpid+1)!=pid:
print scan.tag, "received ", pid, " - waiting for ", (lastpid + 1)
count[scan]=count[scan]+(pid - (lastpid+1))
else:
count[scan]=0
pids[scan] = pid
def scan (st, name):
st.initialize()
st.start()
st.waitCacheChange(3000)
try:
r=bscan (st, records=-1, timeout=SCAN_TIME, save=False, keep=False, #
enabled_plots=[st1,], \
#manual_range_y=[17449000000, 17551000000],
title=name, tag=name, after_read=after_read)
v= st.getValues()
return r
finally:
st.close()
r1,r2 = parallelize( (scan,(st1, "Merge")) , \
(scan, (st2, "Dispatcher")))
for sc in count.keys():
print sc.tag, count[sc]

View File

@@ -0,0 +1,39 @@
#run ("Devices/StreamMerger")
from ch.psi.pshell.bs import StreamMerger as StreamMerger
set_exec_pars(save=False)
add_device (Stream("st1", cam_server.getStream("test_furka"), SocketType.SUB), True)
add_device (Stream("st2", cam_server.getStream("simulation_sp1"), SocketType.SUB), True)
add_device(Stream("st3", dispatcher), force = True)
st3.addScalar(get_beam_ok_channel(1))
st3.addScalar(get_beam_ok_channel(2))
add_device(Stream("st4","tcp://sf-daqsync-18.psi.ch:9000", SocketType.PULL), True)
#st1.setBufferCapacity(1000)
#st2.setBufferCapacity(1000)
st3.setBufferCapacity(2000)
st4.setBufferCapacity(2000)
#add_device(StreamMerger("merger",st1, st2), True)
add_device(StreamMerger("merger",st3, st4), True)
#merger.setPolling(10)
merger.monitored=True
merger.start()
merger.waitCacheChange(-1)
for i in range (5):
merger.waitCacheChange(-1)
#plot(merger.values, name=merger.keys) #"Devices/StreamMerger"
plot(merger.take().values(), name=merger.take().keys()) #ch.psi.pshell.bs.StreamMerger
#bscan(merger, 2000)
bscan(merger, -1, 3.0)
#r = mscan(merger, merger.getReadables(), 2, save=False)
r = mscan(merger, merger.getReadables(), timeout=1)

View File

@@ -0,0 +1,83 @@
import ch.psi.pshell.epics.Positioner as Positioner
USE_SCREEN_PANEL = False
start = 85.0
stop = 90.0
step = 0.5
nb = 3
lat = 0.1
disp = -0.387
p0 = 7.1
plt = plot(None, title="Output")[0]
thr = 500
A = p0 / disp / 1e6
B = p0
#Plot setup
plt.clear()
plt.removeMarker(None)
plt.setStyle(plt.Style.ErrorY)
plt.addSeries(LinePlotErrorSeries("Momentum", Color.red))
plt.addSeries(LinePlotErrorSeries("Momentum Spread", Color.yellow, 2))
plt.getAxis(plt.AxisId.X).setLabel("Gun Beam Phase (deg)")
plt.getAxis(plt.AxisId.Y).setLabel("Momentum (MeV/c)")
plt.getAxis(plt.AxisId.Y2).setLabel("Momentum Spread (MeV/c)")
plt.setLegendVisible(True)
phase = DummyPositioner("Gun Phase")
camera_name = "simulation"
phase.config.minValue = -90.0
phase.config.maxValue = 360.0
phase.config.precision = 4
phase.config.resolution = 0.5
phase.config.rotation = True
phase.config.save()
phase.initialize()
phase0 = phase.read() % 360
#Camera setup
if USE_SCREEN_PANEL:
cam_server.start(camera_name+"_sp1", True) # shared pipeline
else:
cam_server.start(camera_name) # generic pipeline
wait_cam_server_message()
x = cam_server.stream.getChild("x_center_of_mass")
dx = cam_server.stream.getChild("x_rms")
cam_server.setThreshold(thr)
cam_server.setBackgroundSubtraction(False)
#Creating averagers
x_averager = create_averager(x, nb, -1) # -1 event based, waits for the next value
dx_averager = create_averager(dx, nb, -1)
dx_averager.monitored = True # not blocking, will return last nb values
#Record callback: uptate of output plot
def after_sample(record, scan):
global A, B, plt
x_pos_mean, x_pos_stdev = record[0].mean, record[0].stdev
x_width_mean, x_width_stdev = record[1].mean, record[1].stdev
p_mean, p_stdev = A * x_pos_mean + B, abs(A) * x_pos_stdev
dp_mean, dp_stdev = abs(A) * x_width_mean, abs(A) * x_width_stdev
phase = ((record.positions[0] + 90) % 360) - 90 if start < 0 else record.positions[0]
plt.getSeries(0).appendData(phase, p_mean, p_stdev)
plt.getSeries(1).appendData(phase, dp_mean, dp_stdev)
#The scan loop
try:
phase.write(start)
time.sleep(1.0)
r = lscan(phase, [x_averager, dx_averager], start, stop, step , latency=lat, after_read = after_sample)
finally:
phase.write(phase0)
phase.close()
cam_server.stop() # stops cam_server but does not close it cam_server is a global object
ph = r.getPositions(0)
if start < 0:
ph = [((val + 90) % 360) -90 for val in ph ]
p = [A * val.mean + B for val in r.getReadable(0)]
dp = [abs(A) * val.mean for val in r.getReadable(1)]

View File

@@ -30,7 +30,7 @@ s1 = Stream("s1", dispatcher)
s1.setIncomplete("fill_null")
for c in channels:
s1.addScalar(c,c, 1, 0)
s1.addScalar("SAROP11-PBPS117:INTENSITY","SAROP11-PBPS117:INTENSITY", 10, 0)
#s1.addScalar("SAROP11-PBPS117:INTENSITY","SAROP11-PBPS117:INTENSITY", 10, 0)
add_device(s1, True)
@@ -43,4 +43,4 @@ for i in range(20):
s1.waitCacheChange(5000)
#ret = bscan (s1, 20, None, save=False)
ret = bscan (s1, 20, None, save=False)

View File

@@ -0,0 +1,15 @@
st1 = Stream("st1", dispatcher)
#st1.addScalar("X1", "SINEG01-DBPM340:X1", 10, 0)
#st1.addScalar("Y1", "SINEG01-DBPM340:Y1", 10, 0)
#st1.addScalar("Q1", "SINEG01-DBPM340:Q1", 10, 0)
#w,h = caget("SLG-LCAM-C103:WIDTH", 'i'), caget("SLG-LCAM-C103:HEIGHT", 'i')
#st1.addMatrix("VC", "SLG-LCAM-C103:FPICTURE", 10, 0, w,h)
st1.addScalar("i", "SINBC02-DSRM310:intensity", 1, 0)
st1.addWaveform("x", "SINBC02-DSRM310:x_profile", 1, 0,2048)
st1.addWaveform("y", "SINBC02-DSRM310:y_profile", 1, 0,2048)
st1.initialize()
st1.start()
st1.waitCacheChange(3000)
for c in st1.getChildren():
print c, c.shape, c.getType(None)

2
script/test/blm_gain_adjustment.py Executable file → Normal file
View File

@@ -1,5 +1,3 @@
MIN_GAIN, MAX_GAIN = 0.5, 1.1
DECREMENT_STEP = 0.02
INCREMENT_FACTOR = 0.5

View File

@@ -1,12 +1,15 @@
st1 = Stream("st1", dispatcher)
st1.addScalar("X1", "SINEG01-DBPM340:X1", 10, 0)
st1.addScalar("Y1", "SINEG01-DBPM340:Y1", 10, 0)
st1.addScalar("Q1", "SINEG01-DBPM340:Q1", 10, 0)
w,h = caget("SLG-LCAM-C103:WIDTH", 'i'), caget("SLG-LCAM-C103:HEIGHT", 'i')
st1.addMatrix("VCC", "SLG-LCAM-C103:FPICTURE", 10, 0, w,h)
#st1.addScalar("X1", "SINEG01-DBPM340:X1", 10, 0)
#st1.addScalar("Y1", "SINEG01-DBPM340:Y1", 10, 0)
#st1.addScalar("Q1", "SINEG01-DBPM340:Q1", 10, 0)
#w,h = caget("SLG-LCAM-C103:WIDTH", 'i'), caget("SLG-LCAM-C103:HEIGHT", 'i')
#st1.addMatrix("VC", "SLG-LCAM-C103:FPICTURE", 10, 0, w,h)
st1.addScalar("i", "SINBC02-DSRM310:intensity", 1, 0)
st1.addWaveform("x", "SINBC02-DSRM310:x_profile", 1, 0,2048)
st1.addWaveform("y", "SINBC02-DSRM310:y_profile", 1, 0,2048)
st1.initialize()
try:
bscan (st1, 3)
bscan (st1, 20)
finally:
st1.close()

View File

@@ -1,9 +1,9 @@
st1 = Stream("st1", dispatcher)
add_device(st1, force = True)
st1.addScalar("mcpu", "SINDI01-RLLE-STA:MASTER-CPUTIMER", 10, 0)
st1.addScalar("scpu", "SINDI01-RLLE-STA:SLAVE1-CPUTIMER", 10, 0)
#st1.addWaveform("phase", "SINXB01-RWVG100-DCP10:FOR-PHASE", 10, 0, 2048)
#st1.addWaveform("amplt", "SINXB01-RWVG100-DCP10:FOR-AMPLT", 10, 0, 2048)
#st1.addScalar("mcpu", "SINDI01-RLLE-STA:MASTER-CPUTIMER", 10, 0)
#st1.addScalar("scpu", "SINDI01-RLLE-STA:SLAVE1-CPUTIMER", 10, 0)
st1.addWaveform("phase", "SINXB01-RWVG100-DCP10:FOR-PHASE", 10, 0, 2048)
st1.addWaveform("amplt", "SINXB01-RWVG100-DCP10:FOR-AMPLT", 10, 0, 2048)
st1.initialize()
st1.start(True)
try:

19
script/test/bs5.py Normal file
View File

@@ -0,0 +1,19 @@
st1 = Stream("st1", dispatcher)
add_device(st1, force = True)
ch1="SINEG01-DICT210:GUN_CHARGE"
ch1="SATMA02-RLLE-DSP:PHASE-VS"
wv1="SARES11-SPEC125-M1.roi_signal_x_profile"
s1=st1.addScalar(ch1,ch1, 1, 0)
#w1=st1.addWaveform(wv1,wv1, 1, 0)
#st1.addWaveform("phase", "SINXB01-RWVG100-DCP10:FOR-PHASE", 10, 0, 2048)
#st1.addWaveform("amplt", "SINXB01-RWVG100-DCP10:FOR-AMPLT", 10, 0, 2048)
st1.initialize()
st1.start(True)
print st1.waitCacheChange(5000)
try:
bscan (st1, 10, title="bscan")
#tscan (st1.getReadables(), 10, 1, title="tscan")
x = st1.take()
finally:
st1.close()

11
script/test/bs6.py Normal file
View File

@@ -0,0 +1,11 @@
st1 = Stream("st1", dispatcher)
add_device(st1, force = True)
st1.addScalar("SLAAR21-LCAM-C561:intensity")
st1.addScalar("SLAAR21-LCAM-C561:x_fit_mean")
st1.addScalar("SLAAR21-LCAM-C561:y_fit_mean")
st1.initialize()
st1.start(True)
try:
bscan (st1, 10, save=False)
finally:
st1.close()

View File

@@ -0,0 +1,9 @@
import data_utils
import ijutils
import jeputils
import mathutils
import plotutils
import sessions
import rsync
import statsutils
import diffutils

View File

@@ -0,0 +1,8 @@
url = cam_server.getStream("test_merge_disp_sp")
print url
add_device (Stream("st", url, SocketType.SUB), True)
st.start()
show_panel(st)
bscan(st, 5)

View File

@@ -0,0 +1,43 @@
NUM_PIDS = 10000
CHANNEL = "SARES11-SPEC125-M2.roi_signal_x_profile"
KEEP=True
#CHANNEL = "SARES11-SPEC125-M1.roi_signal_x_profile"
st = Stream("pulse_id", dispatcher)
st.addWaveform(c, c, 1, 0)
st.initialize()
st.start()
st.waitCacheChange(10000) #Wait stream be running before starting scan
if KEEP:
try:
r=bscan(st, NUM_PIDS, display=False, save=False)
finally:
st.close()
pids=r.getReadable(0)
plot(pids)
error_count = 0
cur = pids[0]
for i in range(len(pids)-1):
if pids[i+1] != cur+1:
print ("Error in " + str(i))
error_count = error_count+1
cur = pids[i+1]
pid_range = (pids[-1]-pids[0]+1)
else:
first = None
last = None
def after_read(record, scan):
global first, last
last=record[0]
if first is None: first = last
try:
r=bscan(st, NUM_PIDS, display=False, save=False, keep=False, after_read=after_read)
finally:
st.close()
pid_range = (last-first+1)
missing = pid_range-NUM_PIDS
print "TOTAL MISSING: ", missing, "/", pid_range, " RATE: ", (100.0*missing/pid_range), "%"