cu_inj Live¶
In [1]:
Copied!
# Useful for debugging
%load_ext autoreload
%autoreload 2
%config InlineBackend.figure_format = 'retina'
%matplotlib inline
# Useful for debugging
%load_ext autoreload
%autoreload 2
%config InlineBackend.figure_format = 'retina'
%matplotlib inline
In [37]:
Copied!
from lcls_live.datamaps import get_datamaps
from lcls_live.archiver import lcls_archiver_restore
from lcls_live.tools import isotime
import matplotlib.pyplot as plt
import numpy as np
import os
from lcls_live.datamaps import get_datamaps
from lcls_live.archiver import lcls_archiver_restore
from lcls_live.tools import isotime
import matplotlib.pyplot as plt
import numpy as np
import os
In [3]:
Copied!
BEAMPATH = 'cu_spec'
BEAMPATH = 'cu_spec'
Datamaps, and all PVs needed¶
In [4]:
Copied!
DM = get_datamaps(BEAMPATH)
# Hack in 10 Hz
df = DM['bpms'].data
DM['bpms'].data['pvname'] = [name[:-2]+'TH' for name in df['pvname']]
DM.keys()
DM = get_datamaps(BEAMPATH)
# Hack in 10 Hz
df = DM['bpms'].data
DM['bpms'].data['pvname'] = [name[:-2]+'TH' for name in df['pvname']]
DM.keys()
Out[4]:
dict_keys(['bpms', 'correctors', 'quad', 'linac'])
In [5]:
Copied!
# datamaps to exclude
DENYLIST = ['correctors', 'linac'] #, 'quad']
# datamaps to exclude
DENYLIST = ['correctors', 'linac'] #, 'quad']
In [6]:
Copied!
# PVs needed
PVLIST = []
for name, dm in DM.items():
if name in DENYLIST:
continue
PVLIST.extend(dm.pvlist)
PVLIST = list(set(PVLIST))
len(PVLIST)
# PVs needed
PVLIST = []
for name, dm in DM.items():
if name in DENYLIST:
continue
PVLIST.extend(dm.pvlist)
PVLIST = list(set(PVLIST))
len(PVLIST)
Out[6]:
46
EPICS¶
In [8]:
Copied!
import epics
from time import sleep, time
import epics
from time import sleep, time
In [9]:
Copied!
MONITOR = {pvname:epics.PV(pvname) for pvname in PVLIST}
sleep(5) # Wait for all to connect
MONITOR = {pvname:epics.PV(pvname) for pvname in PVLIST}
sleep(5) # Wait for all to connect
In [10]:
Copied!
def get_pvdata():
itime = isotime()
pvdata = {k:MONITOR[k].get() for k in MONITOR}
return pvdata
PVDATA = get_pvdata()
def get_pvdata():
itime = isotime()
pvdata = {k:MONITOR[k].get() for k in MONITOR}
return pvdata
PVDATA = get_pvdata()
In [11]:
Copied!
# Check for bad PVs
bad = set()
for k, v in PVDATA.items():
if v is None:
bad.add(k.split(':')[2])
print(k)
assert len(bad) == 0
# Check for bad PVs
bad = set()
for k, v in PVDATA.items():
if v is None:
bad.add(k.split(':')[2])
print(k)
assert len(bad) == 0
Tao conveniences¶
In [12]:
Copied!
def tao_commands(pvdata):
cmds = []
for name, dm in DM.items():
cmds.extend(dm.as_tao(pvdata))
return cmds
def tao_commands(pvdata):
cmds = []
for name, dm in DM.items():
cmds.extend(dm.as_tao(pvdata))
return cmds
In [13]:
Copied!
def save_cmds(cmds, filename='cmds.tao'): # Write to file for running with vanilla Tao
with open(filename, 'w') as f:
f.write('set global lattice_calc_on = F\n')
f.write('set global plot_on = F\n')
for cmd in CMDS:
f.write(cmd+'\n')
f.write('set global lattice_calc_on = T\n')
f.write('set global plot_on = T\n')
def save_cmds(cmds, filename='cmds.tao'): # Write to file for running with vanilla Tao
with open(filename, 'w') as f:
f.write('set global lattice_calc_on = F\n')
f.write('set global plot_on = F\n')
for cmd in CMDS:
f.write(cmd+'\n')
f.write('set global lattice_calc_on = T\n')
f.write('set global plot_on = T\n')
In [14]:
Copied!
def toggle_beam():
tao.cmd('set global track_type = beam')
tao.cmd('set global track_type = single')
def toggle_beam():
tao.cmd('set global track_type = beam')
tao.cmd('set global track_type = single')
Form commands using PVDATA and datamaps¶
In [15]:
Copied!
tao_commands(PVDATA)[0:5]
tao_commands(PVDATA)[0:5]
Out[15]:
['set data orbit.x[1]|meas = 0.001 * 0.18149997293949127', 'set data orbit.x[2]|meas = 0.001 * 0.3294964134693146', 'set data orbit.x[3]|meas = 0.001 * 2.2582709789276123e-05', 'set data orbit.x[4]|meas = 0.001 * -0.008475333452224731', 'set data orbit.x[5]|meas = 0.001 * -0.03837699070572853']
Start Tao¶
In [16]:
Copied!
from pytao import Tao
from pytao import Tao
In [18]:
Copied!
MODEL_ROOT = f'$LCLS_LATTICE/bmad/models/{BEAMPATH}/'
init = f'-init {MODEL_ROOT}/tao.init'
tao = Tao(init)
tao.cmd('set ele quad::* field_master = T')
init
MODEL_ROOT = f'$LCLS_LATTICE/bmad/models/{BEAMPATH}/'
init = f'-init {MODEL_ROOT}/tao.init'
tao = Tao(init)
tao.cmd('set ele quad::* field_master = T')
init
Out[18]:
'-init $LCLS_LATTICE/bmad/models/cu_spec//tao.init'
In [19]:
Copied!
%%time
# Turn on the beam
tao.cmd('set beam_init n_particle = 10000')
toggle_beam()
%%time
# Turn on the beam
tao.cmd('set beam_init n_particle = 10000')
toggle_beam()
CPU times: user 1.39 s, sys: 146 ms, total: 1.54 s Wall time: 536 ms
In [27]:
Copied!
%%tao
place floor none
place top2 bpm_orbit
place middle2 bunch_sigma_xy
sc top2 -2 2
set graph middle2 y%label = "\gs\fn\dx\u, \gs\fn\dy\u (\gmm)"
set curve middle2.g.x y_axis_scale_factor = 1e6
set curve middle2.g.y y_axis_scale_factor = 1e6
sc middle2 ! 0 600
x-a all s
%%tao
place floor none
place top2 bpm_orbit
place middle2 bunch_sigma_xy
sc top2 -2 2
set graph middle2 y%label = "\gs\fn\dx\u, \gs\fn\dy\u (\gmm)"
set curve middle2.g.x y_axis_scale_factor = 1e6
set curve middle2.g.y y_axis_scale_factor = 1e6
sc middle2 ! 0 600
x-a all s
------------------------- Tao> place floor none ------------------------- Tao> place top2 bpm_orbit ------------------------- Tao> place middle2 bunch_sigma_xy ------------------------- Tao> ------------------------- Tao> sc top2 -2 2 ------------------------- Tao> ------------------------- Tao> set graph middle2 y%label = "\gs\fn\dx\u, \gs\fn\dy\u (\gmm)" ------------------------- Tao> set curve middle2.g.x y_axis_scale_factor = 1e6 ------------------------- Tao> set curve middle2.g.y y_axis_scale_factor = 1e6 ------------------------- Tao> sc middle2 ! 0 600 ------------------------- Tao> ------------------------- Tao> ------------------------- Tao> x-a all s ------------------------- Tao>
In [28]:
Copied!
#tao.cmd(f'call {MODEL_ROOT}/scripts/SC.tao')
#tao.cmd(f'call {MODEL_ROOT}/scripts/SC.tao')
Continuous loop¶
In [29]:
Copied!
def run1():
#sleep(.001)
t1 = time()
pvdata = get_pvdata()
cmds = tao_commands(pvdata)
tao.cmd('set global plot_on = F;set global lattice_calc_on = F')
tao.cmds(cmds); # Apply
tao.cmd('set global lattice_calc_on = T')
tao.cmd('set global plot_on = T')
toggle_beam()
dt = time()-t1
#print(dt)
def run1():
#sleep(.001)
t1 = time()
pvdata = get_pvdata()
cmds = tao_commands(pvdata)
tao.cmd('set global plot_on = F;set global lattice_calc_on = F')
tao.cmds(cmds); # Apply
tao.cmd('set global lattice_calc_on = T')
tao.cmd('set global plot_on = T')
toggle_beam()
dt = time()-t1
#print(dt)
In [30]:
Copied!
%%time
run1()
%%time
run1()
CPU times: user 2.57 s, sys: 274 ms, total: 2.85 s Wall time: 727 ms
In [ ]:
Copied!
while True:
run1()
while True:
run1()
In [32]:
Copied!
%%time
#toggle on and off
tao.cmd('set global track_type = beam', raises=False)
tao.cmd('set global track_type = single')
%%time
#toggle on and off
tao.cmd('set global track_type = beam', raises=False)
tao.cmd('set global track_type = single')
CPU times: user 1.33 s, sys: 113 ms, total: 1.44 s Wall time: 382 ms
Out[32]:
[]
In [33]:
Copied!
%%tao
place top2 beambeta
place middle2 bunch_sigma_xy
x-a all s
sc
%%tao
place top2 beambeta
place middle2 bunch_sigma_xy
x-a all s
sc
------------------------- Tao> place top2 beambeta ------------------------- Tao> place middle2 bunch_sigma_xy ------------------------- Tao> x-a all s ------------------------- Tao> sc ------------------------- Tao>
Get particles¶
In [34]:
Copied!
from pmd_beamphysics import ParticleGroup
from pmd_beamphysics import ParticleGroup
In [35]:
Copied!
P = ParticleGroup(data=tao.bunch_data('OTR2'))
# Select out live particles
P = P[P.status==1]
P.drift_to_z()
P = ParticleGroup(data=tao.bunch_data('OTR2'))
# Select out live particles
P = P[P.status==1]
P.drift_to_z()
In [38]:
Copied!
P.plot('delta_t', 'energy')
plt.title('OTR2')
P.plot('delta_t', 'energy')
plt.title('OTR2')
Out[38]:
Text(0.5, 1.0, 'OTR2')
In [39]:
Copied!
P.plot('x', 'y')
P.plot('x', 'y')
In [40]:
Copied!
P.plot('t', 'x')
P.plot('t', 'x')
In [41]:
Copied!
# Make a function for this
def get_beam(ele):
P = ParticleGroup(data=tao.bunch_data(ele))
# Select out live particles
P = P[P.status==1]
return P
# Make a function for this
def get_beam(ele):
P = ParticleGroup(data=tao.bunch_data(ele))
# Select out live particles
P = P[P.status==1]
return P
In [42]:
Copied!
P1 = get_beam('OTR2')
P1.plot('delta_t', 'delta_energy')
P1 = get_beam('OTR2')
P1.plot('delta_t', 'delta_energy')
In [43]:
Copied!
P2 = get_beam('OTR2')
P2.plot('x', 'y')
P2 = get_beam('OTR2')
P2.plot('x', 'y')
Get giant table of bunch stats¶
In [44]:
Copied!
import pandas as pd
import pandas as pd
In [45]:
Copied!
# Get list of indices
IX = tao.lat_list('*', 'ele.ix_ele')
# Stop before the dump
S_STOP = tao.ele_head('OTR2')['s']
stats = []
for ele in IX:
d = tao.bunch_params(ele)
# Skipl ones with no beam
if d['charge_live'] == 0:
continue
if d['s'] > S_STOP:
break
stats.append(d)
df = pd.DataFrame(stats)#.set_index('ix_ele')
df
# Get list of indices
IX = tao.lat_list('*', 'ele.ix_ele')
# Stop before the dump
S_STOP = tao.ele_head('OTR2')['s']
stats = []
for ele in IX:
d = tao.bunch_params(ele)
# Skipl ones with no beam
if d['charge_live'] == 0:
continue
if d['s'] > S_STOP:
break
stats.append(d)
df = pd.DataFrame(stats)#.set_index('ix_ele')
df
Out[45]:
beta_x | alpha_x | gamma_x | phi_x | eta_x | etap_x | sigma_x | sigma_p_x | emit_x | norm_emit_x | ... | ix_ele | direction | species | location | s | charge_live | n_particle_tot | n_particle_live | n_particle_lost_in_ele | beam_saved | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 17.172295 | -4.832192 | 1.417986 | 0.0 | -0.001708 | -0.000506 | 0.000245 | 0.000070 | 3.502335e-09 | 4.377142e-07 | ... | 62 | 1 | Electron | Downstream_End | 4.614539 | 2.500000e-11 | 10000 | 10000 | 0 | True |
1 | 18.282401 | -4.992310 | 1.417929 | 0.0 | -0.001765 | -0.000506 | 0.000253 | 0.000070 | 3.502475e-09 | 4.377317e-07 | ... | 63 | 1 | Electron | Downstream_End | 4.727324 | 2.500000e-11 | 10000 | 10000 | 0 | False |
2 | 19.026422 | -5.096805 | 1.417892 | 0.0 | -0.001803 | -0.000506 | 0.000258 | 0.000070 | 3.502567e-09 | 4.377431e-07 | ... | 64 | 1 | Electron | Downstream_End | 4.800934 | 2.500000e-11 | 10000 | 10000 | 0 | False |
3 | 23.573059 | -39.263591 | 65.440366 | 0.0 | -0.002009 | -0.003367 | 0.000287 | 0.000479 | 3.504147e-09 | 4.379407e-07 | ... | 65 | 1 | Electron | Downstream_End | 4.908934 | 2.500000e-11 | 10000 | 10000 | 0 | False |
4 | 31.566605 | -45.416435 | 65.374550 | 0.0 | -0.002327 | -0.003367 | 0.000333 | 0.000479 | 3.507675e-09 | 4.383816e-07 | ... | 66 | 1 | Electron | Downstream_End | 5.003418 | 2.500000e-11 | 10000 | 10000 | 0 | False |
... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
82 | 74.549507 | -0.570622 | 0.017782 | 0.0 | -0.009313 | -0.000028 | 0.000353 | 0.000005 | 1.672918e-09 | 4.413671e-07 | ... | 144 | 1 | Electron | Downstream_End | 14.089061 | 2.500000e-11 | 10000 | 10000 | 0 | True |
83 | 74.636433 | -0.571975 | 0.017782 | 0.0 | -0.009315 | -0.000028 | 0.000353 | 0.000005 | 1.672918e-09 | 4.413671e-07 | ... | 145 | 1 | Electron | Downstream_End | 14.165045 | 2.500000e-11 | 10000 | 10000 | 0 | False |
84 | 74.636433 | -0.571975 | 0.017782 | 0.0 | -0.009315 | -0.000028 | 0.000353 | 0.000005 | 1.672918e-09 | 4.413671e-07 | ... | 146 | 1 | Electron | Downstream_End | 14.165045 | 2.500000e-11 | 10000 | 10000 | 0 | True |
85 | 74.723564 | -0.573328 | 0.017782 | 0.0 | -0.009317 | -0.000028 | 0.000354 | 0.000005 | 1.672918e-09 | 4.413670e-07 | ... | 147 | 1 | Electron | Downstream_End | 14.241029 | 2.500000e-11 | 10000 | 10000 | 0 | False |
86 | 74.723564 | -0.573328 | 0.017782 | 0.0 | -0.009317 | -0.000028 | 0.000354 | 0.000005 | 1.672918e-09 | 4.413670e-07 | ... | 148 | 1 | Electron | Downstream_End | 14.241029 | 2.500000e-11 | 10000 | 10000 | 0 | True |
87 rows × 127 columns
In [46]:
Copied!
fig, ax = plt.subplots(figsize=(12,5))
plt.plot(df['s'], df['sigma_x']*1e6, label=r'$\sigma_x$')
plt.plot(df['s'], df['sigma_y']*1e6, label=r'$\sigma_y$')
plt.xlabel('s (m)')
plt.ylabel('beam sizes (µm)')
plt.legend();
fig, ax = plt.subplots(figsize=(12,5))
plt.plot(df['s'], df['sigma_x']*1e6, label=r'$\sigma_x$')
plt.plot(df['s'], df['sigma_y']*1e6, label=r'$\sigma_y$')
plt.xlabel('s (m)')
plt.ylabel('beam sizes (µm)')
plt.legend();
In [47]:
Copied!
# Get an array of where the beam is saved
s_saved = np.array(df[df['beam_saved']]['s'])
# Get an array of where the beam is saved
s_saved = np.array(df[df['beam_saved']]['s'])
In [48]:
Copied!
fig, ax = plt.subplots(figsize=(12,5))
plt.plot(df['s'], df['norm_emit_x']*1e6, label=r'$\epsilon_{n,x}$')
plt.plot(df['s'], df['norm_emit_y']*1e6, label=r'$\epsilon_{n,y}$')
plt.xlabel('s (m)')
plt.ylabel('Beam emittance(mm-mrad)')
# This is where the beam is saved
plt.scatter(s_saved, np.ones(len(s_saved))*0, color = 'black', marker = 'x')
plt.legend();
fig, ax = plt.subplots(figsize=(12,5))
plt.plot(df['s'], df['norm_emit_x']*1e6, label=r'$\epsilon_{n,x}$')
plt.plot(df['s'], df['norm_emit_y']*1e6, label=r'$\epsilon_{n,y}$')
plt.xlabel('s (m)')
plt.ylabel('Beam emittance(mm-mrad)')
# This is where the beam is saved
plt.scatter(s_saved, np.ones(len(s_saved))*0, color = 'black', marker = 'x')
plt.legend();