Tracking

A. Petrenko (Novosibirsk, 2019)

In [1]:
import numpy as np
import pandas as pd
import holoviews as hv
import os
from IPython.display import Latex
from IPython.display import Image

hv.extension("bokeh")
In [2]:
%opts Curve Spread [width=700 height=300 show_grid=True \
            default_tools=['box_zoom','pan','wheel_zoom','reset']]

Elegant lattice file:

Plot sdds-beam

In [56]:
w = "../debuncher/results/w3.sdds"
In [58]:
png = "results/image.png"
!sddsplot -lay=2,2 -device=lpng -output=$png \
    -col=x,y -graph=dot,type=2   $w -endPanel \
    -col=yp,y -graph=dot,type=2  $w -endPanel \
    -col=x,xp -graph=dot,type=2  $w -endPanel \
    -col=yp,xp -graph=dot,type=2 $w
Image(png) 
Out[58]:
In [59]:
!sddsplot -device=lpng -output=$png -lay=2,2 "-title=" \
    -col=t,p -factor=yMult=0.511,xMult=-3e11 \
        "-xlabel=z (mm)" "-ylabel=p (MeV/c)" -graph=dot,type=2 $w -endPanel \
    -col=xp,p -factor=yMult=0.511,xMult=1e3 \
        "-xlabel=xp (mrad)" "-ylabel=p (MeV/c)" -graph=dot,type=2 $w -endPanel \
    -col=t,x -factor=xMult=-3e11,yMult=1e3 \
        "-xlabel=z (mm)" "-ylabel=x (mm)" -graph=dot,type=2 $w -endPanel \
    -col=xp,x -factor=yMult=1e3,xMult=1e3 \
        "-xlabel=xp (mrad)" "-ylabel=x (mm)" -graph=dot,type=2 $w -endPanel
Image(png)
Out[59]:

Run sddsanalyzebeam to check the beam parameters:

In [60]:
with open("machine.lte", "r") as f:
    print(f.read())
! beta_x = 12.81770927 alpha_x = -0.00000017 beta_y = 3.11122611 alpha_y = 0.00000003
! eta_x = -0.00000244 eta_y = -0.00000000 etap_x = 0.00000001 etap_y = -0.00000000

q: charge,total=3.47e-9

w0: watch,filename="results/w0.sdds",mode=coord
w1: watch,filename="results/w1.sdds",mode=coord
w2: watch,filename="results/w2.sdds",mode=coord
w3: watch,filename="results/w3.sdds",mode=coord

MA30: MAXAMP, X_MAX=15.0e-3, Y_MAX=15.0e-3, ELLIPTICAL=1

QFW1: KQUAD, L=0.04858934169278997, K1 = 6.380867488799166
D243: DRIFT, L=0.24294670846394986
WIGHALFPOLEPOS: RBEND, L=0.018221046865203764, ANGLE = 0.00744334
D36: DRIFT, L=0.03644200626959248
WIGPOLENEG: RBEND, L=0.03644234153605016, ANGLE = -0.01488668
WIGPOLEPOS: RBEND, L=0.03644234153605016, ANGLE = 0.01488668
QDW1: KQUAD, L=0.04858934169278997, K1 = -5.327257602543184
D972: DRIFT, L=0.9717868338557994
QDS27: KQUAD, L=0.1700626959247649, K1 = -5.76580494446618
QDS26: KQUAD, L=0.1700626959247649, K1 = 5.6377219271568295
D292: DRIFT, L=0.29153605015673983
QDS25: KQUAD, L=0.1700626959247649, K1 = 1.943702204473911
QDS24: KQUAD, L=0.1700626959247649, K1 = -6.227583201760073
D194: DRIFT, L=0.19435736191222575

DIP1: CSBEND, L=0.31934524153605015, ANGLE = 0.08267349, E1="0.08267349 2 /", E2=0
DIP2: CSBEND, L=0.31934524153605015, ANGLE = 0.08267349, E1=0, E2="0.08267349 2 /"

QDS23: KQUAD, L=0.1700626959247649, K1 = 12.507544803656904
D49: DRIFT, L=0.04858934169278997
SY2: SEXT, L=0.14576802507836992, K2 = 0.002877583106
QDS22: KQUAD, L=0.1700626959247649, K1 = -13.53114362079025
QDS21: KQUAD, L=0.1700626959247649, K1 = 9.292210519225806
D73: DRIFT, L=0.07288401253918496
SX2: KSEXT, L=0.14576802507836992, K2=-0.001201865064
D146: DRIFT, L=0.14576802507836992
SX1: KSEXT, L=0.14576802507836992, K2=+140.0
D78: DRIFT, L=0.07774294670846396
QFA: KQUAD, L=0.13605015673981194, K1 = 10.556848152830382
D155: DRIFT, L=0.15548589341692792
QDA: KQUAD, L=0.13605015673981194, K1 = -8.765279717391106
D102: DRIFT, L=0.10203761755485893
SY1: KSEXT, L=0.14576802507836992, K2=-245.0
QDS11: KQUAD, L=0.1700626959247649, K1 = -2.6480964754119216
QDS12: KQUAD, L=0.1700626959247649, K1 = 12.357911508274118
QDS13: KQUAD, L=0.1700626959247649, K1 = -7.5842513538480745
QDS14: KQUAD, L=0.1700626959247649, K1 = -7.879434676707003
QDS15: KQUAD, L=0.1700626959247649, K1 = 9.04647696121302
QDS16: KQUAD, L=0.1700626959247649, K1 = -0.20539330113631632
D160: DRIFT, L=0.159516670846395
RF: DRIFT, L=4.858934169278997e-6
D0: DRIFT, L=4.615987460815047e-5
D1444: DRIFT, L=1.4438805862068966
QDS17: KQUAD, L=0.1700626959247649, K1 = -4.849284899727069
D1603: DRIFT, L=1.603448275862069
QDS18: KQUAD, L=0.1700626959247649, K1 = 3.46260053525197
D1458: DRIFT, L=1.4576802507836992
QDS19: KQUAD, L=0.1700626959247649, K1 = -3.0509003681938456

WIGGLE: LINE=(WIGPOLENEG,D36,WIGPOLEPOS,D36)

WIGGLER: LINE=(WIGHALFPOLEPOS,D36,9*WIGGLE,WIGPOLENEG,D36,WIGHALFPOLEPOS)
WIGGLER_FODO: LINE=(QFW1,D243,WIGGLER,D243,QDW1,QDW1,D243,WIGGLER,D243,QFW1)

TME_CELL: LINE=(DIP2,D146,SX1,D78,QFA,D155,QDA,D102,SY1,D102,QDA,D155,QFA,D78,SX1,D146,DIP1)

machine: LINE=(q,w0,MA30,2*WIGGLER_FODO,QFW1,&
D972,QDS27,D972,QDS26,D292,QDS25,D292,QDS24,D194,&
DIP1,DIP2,D243,QDS23,D49,SY2,D49,QDS22,D292,QDS21,D73,SX2,D73,DIP1,&
16*TME_CELL,&
DIP2,D73,SX2,D73,QDS11,D292,QDS12,D49,SY2,D49,QDS13,D243,DIP1,DIP2,&
D194,QDS14,D292,QDS15,D292,QDS16,D160,RF,D0,D1444,QDS17,D1603,QDS18,D1458,QDS19,D1458,&
w1,QFW1,2*WIGGLER_FODO,QFW1,&
D972,QDS27,D972,QDS26,D292,QDS25,D292,QDS24,D194,&
DIP1,DIP2,D243,QDS23,D49,SY2,D49,QDS22,D292,QDS21,D73,SX2,D73,DIP1,&
16*TME_CELL,&
DIP2,D73,SX2,D73,QDS11,D292,QDS12,D49,SY2,D49,QDS13,D243,DIP1,DIP2,&
D194,QDS14,D292,QDS15,D292,QDS16,D1603,QDS17,D1603,QDS18,D1458,QDS19,D1458,QFW1,&
w3)

In [61]:
with open("track.ele", "r") as f:
    print(f.read())
!&transmute_elements name=*, type=*QUAD, new_type=DRIF &end

!&divide_elements
!    name = *
!    maximum_length = 0.05
!&end

&run_setup
    lattice = machine.lte
    use_beamline = machine
    p_central_mev = 1500.0
    sigma = results/%s.sig
    centroid = results/%s.cen
    magnets = results/beamline.mag
!    output = results/%s.out
!    final = results/%s.fin
    default_order=2
!    default_order=1
&end

&run_control
    n_steps = 1
    n_passes = 500
&end

&sdds_beam
    input = ../../debuncher/results/w3.sdds
&end

&track &end

Run Elegant

In [9]:
#!elegant track.ele
In [69]:
import subprocess
import sys

def run_cmd(cmd):
    sub_process = subprocess.Popen(cmd, shell=True,
                               stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    while sub_process.poll() is None:
        out = sub_process.stdout.read(10)
        sys.stdout.write(out)
        sys.stdout.flush()
In [71]:
#run_cmd("elegant track.ele")
#or run "mpirun -np 36 Pelegant track.ele"
In [83]:
turn = 500
w = "results/page.sdds"
In [84]:
!sddsconvert "results/w0.sdds" $w -keepPages=$turn
In [85]:
!sddsplot -lay=2,2 -device=lpng -output=$png \
    -col=x,y -graph=dot,type=2 $w -endPanel \
    -col=yp,y -graph=dot,type=2 $w -endPanel \
    -col=x,xp -graph=dot,type=2  $w -endPanel \
    -col=yp,xp -graph=dot,type=2 $w
Image(png)
Out[85]:
In [86]:
!sddsplot -device=lpng -output=$png -lay=2,2 "-title=" \
    -col=dt,p -factor=yMult=0.511,xMult=-3e11 \
        "-xlabel=z (mm)" "-ylabel=p (MeV/c)" -graph=dot,type=2 $w -endPanel \
    -col=xp,p -factor=yMult=0.511,xMult=1e3 \
        "-xlabel=xp (mrad)" "-ylabel=p (MeV/c)" -graph=dot,type=2 $w -endPanel \
    -col=dt,x -factor=xMult=-3e11,yMult=1e3 \
        "-xlabel=z (mm)" "-ylabel=x (mm)" -graph=dot,type=2 $w -endPanel \
    -col=xp,x -factor=yMult=1e3,xMult=1e3 \
        "-xlabel=xp (mrad)" "-ylabel=x (mm)" -graph=dot,type=2 $w -endPanel
Image(png)
Out[86]:
In [87]:
!sddsconvert "results/w3.sdds" $w -keepPages=$turn
In [88]:
!sddsplot -lay=2,2 -device=lpng -output=$png \
    -col=x,y -graph=dot,type=2 $w -endPanel \
    -col=yp,y -graph=dot,type=2  $w -endPanel \
    -col=x,xp -graph=dot,type=2  $w -endPanel \
    -col=yp,xp -graph=dot,type=2 $w
Image(png)
Out[88]:
In [89]:
!sddsplot -device=lpng -output=$png -lay=2,2 "-title=" \
    -col=dt,p -factor=yMult=0.511,xMult=-3e11 \
        "-xlabel=z (mm)" "-ylabel=p (MeV/c)" -graph=dot,type=2 $w -endPanel \
    -col=xp,p -factor=yMult=0.511,xMult=1e3 \
        "-xlabel=xp (mrad)" "-ylabel=p (MeV/c)" -graph=dot,type=2 $w -endPanel \
    -col=dt,x -factor=xMult=-3e11,yMult=1e3 \
        "-xlabel=z (mm)" "-ylabel=x (mm)" -graph=dot,type=2 $w -endPanel \
    -col=xp,x -factor=yMult=1e3,xMult=1e3 \
        "-xlabel=xp (mrad)" "-ylabel=x (mm)" -graph=dot,type=2 $w -endPanel
Image(png)
Out[89]:

Plot beam charge vs turn:

In [90]:
!sddsplot -device=lpng -output=$png "-title=" -scale=0,0,0,4e-9 \
    -par=Pass,Charge -graph=line,type=1,thick=3 "results/w3.sdds"
Image(png)
Out[90]:

Now let's plot the results with holoviews

In [91]:
os.listdir("results")
Out[91]:
['xyz.sdds',
 'beamline.mag',
 'parameters.sdds',
 'twiss.twi',
 'beam.cen',
 'image.png',
 'track.sig',
 'w0.sdds',
 'w1.sdds',
 'w3.sdds',
 'beam_analyzed.sdds',
 'track.cen',
 'resdiag.sdds',
 'page.sdds']

Reading beamline.mag

In [92]:
out = !sdds2stream results/beamline.mag -col=ElementName,s,Profile -pipe=out
In [93]:
out[:3]
Out[93]:
['_BEGIN_ 0.000000000000000e+00 0.000000000000000e+00',
 'Q 0.000000000000000e+00 0.000000000000000e+00',
 'W0 0.000000000000000e+00 0.000000000000000e+00']
In [94]:
print("\n".join(out[:3]))
_BEGIN_ 0.000000000000000e+00 0.000000000000000e+00
Q 0.000000000000000e+00 0.000000000000000e+00
W0 0.000000000000000e+00 0.000000000000000e+00
In [95]:
from io import StringIO
In [96]:
DATA = StringIO("\n".join(out))
In [97]:
df = pd.read_csv(DATA, names=['ElementName', 's', 'Profile'], delim_whitespace=True)
In [98]:
df.head(3)
Out[98]:
ElementName s Profile
0 _BEGIN_ 0.0 0.0
1 Q 0.0 0.0
2 W0 0.0 0.0
In [99]:
df.tail(3)
Out[99]:
ElementName s Profile
4381 QFW1 131.8957 0.0
4382 QFW1 131.9443 0.0
4383 W3 131.9443 0.0
In [100]:
dim_s = hv.Dimension('s', unit='m', label="s") # range=(-80,0))
In [101]:
#hv.help(hv.Curve)
In [102]:
from bokeh.models import HoverTool
#hover = HoverTool(tooltips=[("Name", "@ElementName")])
hover = HoverTool(tooltips="@ElementName")

%opts Curve.mag [height=70 show_frame=False show_title=False \
                 xaxis=None yaxis=None tools=['xbox_zoom, xpan', hover]] (color='black', alpha=0.3)

mag = hv.Curve(df, kdims=dim_s, vdims=['Profile', 'ElementName'], group='mag')
mag
Out[102]:

Reading track.sig file

In [103]:
#!sddsquery results/track.sig
In [104]:
out = !sdds2stream results/track.sig -col=ElementName,s,minimum1,maximum1,minimum3,maximum3,Sx,Sy -pipe=out
DATA = StringIO("\n".join(out))
df = pd.read_csv(DATA, names=['ElementName','s','xmin','xmax','ymin','ymax','sigma_x','sigma_y'],
                   delim_whitespace=True)
In [105]:
df.tail(3)
Out[105]:
ElementName s xmin xmax ymin ymax sigma_x sigma_y
1014 D1458 131.895734 -0.014992 0.014863 -0.007614 0.007566 0.002585 0.001676
1015 QFW1 131.944323 -0.014981 0.014964 -0.007612 0.007539 0.002604 0.001628
1016 W3 131.944323 -0.014981 0.014964 -0.007612 0.007539 0.002604 0.001628
In [106]:
df['xmin'] = df['xmin']*1e3; df['xmax'] = df['xmax']*1e3 # mm
df['ymin'] = df['ymin']*1e3; df['ymax'] = df['ymax']*1e3 # mm
df['sigma_x'] = df['sigma_x']*1e3; df['sigma_y'] = df['sigma_y']*1e3 # mm
In [107]:
#df.tail(3)
In [108]:
dim_x = hv.Dimension('x', unit='mm', label="x", range=(0,None))
dim_y = hv.Dimension('y', unit='mm', label="y", range=(0,None))

%opts Curve.fx (color='red', alpha=0.7, line_width=3)
%opts Curve.fy (color='blue', alpha=0.7, line_width=3)
In [109]:
Sx = hv.Curve((df.s, df.sigma_x), label='σx', kdims=dim_s, vdims=dim_x, group='fx')
Sy = hv.Curve((df.s, df.sigma_y), label='σy', kdims=dim_s, vdims=dim_y, group='fy')
In [110]:
(Sx*Sy + mag).cols(1)
Out[110]:

Reading track.cen file

In [111]:
#!sddsquery results/track.cen
In [112]:
out = !sdds2stream results/track.cen -col=ElementName,s,Particles,pCentral,Cx,Cy,Charge -pipe=out
DATA = StringIO("\n".join(out))
df_cen = pd.read_csv(DATA, names=['ElementName','s','Particles','p','Cx','Cy','Charge'],
                   delim_whitespace=True)

df_cen['p'] = 0.511*df_cen['p'] # MeV/c
df_cen['Cx'] = 1e3*df_cen['Cx'] # mm
df_cen['Cy'] = 1e3*df_cen['Cy'] # mm
In [113]:
df_cen.tail(3)
Out[113]:
ElementName s Particles p Cx Cy Charge
1014 D1458 131.895734 31810694 1500.002759 -0.223541 0.013358 3.008026e-09
1015 QFW1 131.944323 31810693 1500.002759 -0.226553 0.012652 3.008026e-09
1016 W3 131.944323 31810693 1500.002759 -0.226553 0.012652 3.008026e-09
In [114]:
dim_Q = hv.Dimension('Q', range=(0,None), unit='nC') # range=(-80,0))

Charge = hv.Curve((df_cen.s, df_cen.Charge*1e9), kdims=dim_s, vdims=dim_Q)
In [115]:
(Charge + mag).cols(1)
Out[115]:

Reading twiss.sdds file

In [116]:
out = !sdds2stream results/twiss.twi \
    -col=ElementName,s,betax,betay,alphax,alphay,etax,etay,pCentral0,xAperture,yAperture -pipe=out
DATA = StringIO("\n".join(out))
df_twi = pd.read_csv(DATA, names=['ElementName','s','betax','betay','alphax','alphay',
                              'etax','etay','p','xAperture','yAperture'],
                   delim_whitespace=True)
In [117]:
df_twi['xAperture'] = 1e3*df_twi['xAperture'] # mm
df_twi['yAperture'] = 1e3*df_twi['yAperture'] # mm
In [118]:
df_twi.tail(3)
Out[118]:
ElementName s betax betay alphax alphay etax etay p xAperture yAperture
1461 D1458 131.895734 6.135057 1.536181 -1.903896 5.058840e-01 -0.000001 0.0 2935.426143 15.0 15.0
1462 QFW1 131.944323 6.228034 1.511723 -0.000001 -8.805023e-07 -0.000001 0.0 2935.426143 15.0 15.0
1463 W3 131.944323 6.228034 1.511723 -0.000001 -8.805023e-07 -0.000001 0.0 2935.426143 15.0 15.0
In [119]:
dim_x = hv.Dimension('x', unit='mm', label="x", range=(-16,+16))
dim_y = hv.Dimension('y', unit='mm', label="y", range=(-16,+16))
dim_p = hv.Dimension('p', unit='MeV/c', label="p", range=(0,None))
In [120]:
%opts Curve.Aper (color='gray', alpha=0.5, line_width=3)

dim_sigma = hv.Dimension('sigma', unit='mm', label="2σ")#, range=(0,None))
dim_aper  = hv.Dimension('aper', unit='mm', label="Aperture")#, range=(0,None))

Ax =     hv.Curve((df_twi.s,  df_twi.xAperture), label='Aperture', kdims=dim_s, vdims=dim_sigma, group='Aper')
Ax_pos = Ax
Ax_neg = hv.Curve((df_twi.s, -df_twi.xAperture), label='Aperture', kdims=dim_s, vdims=dim_sigma, group='Aper')
In [121]:
#Ax_pos*Ax_neg
In [122]:
#s_p = hv.Curve((df_cen.s, df_cen.p), kdims=dim_s, vdims=dim_p)

Cx  = hv.Spread((df_cen.s, df_cen.Cx, 2*df.sigma_x), label='x', \
               kdims=dim_s, vdims=[dim_x,dim_aper])
Cy  = hv.Spread((df_cen.s, df_cen.Cy, 2*df.sigma_y), label='y', \
               kdims=dim_s, vdims=[dim_y,dim_aper])
In [123]:
(Ax_pos*Ax_neg*Cy*Cx + mag).cols(1)
Out[123]:
In [124]:
s_Cx = hv.Curve((df_cen.s, df_cen.Cx), kdims=dim_s, vdims=dim_x, group='fx', label='x')
s_Cy = hv.Curve((df_cen.s, df_cen.Cy), kdims=dim_s, vdims=dim_x, group='fy', label='y')
In [125]:
(s_Cx*s_Cy*Ax_pos*Ax_neg + mag).cols(1)
Out[125]:

Resulting beam paramaters:

In [126]:
beam_analyzed = 'results/beam_analyzed.sdds'
#w = "results/w3.sdds"
!sddsanalyzebeam $w $beam_analyzed
In [127]:
items = np.array([
    # name in file   symbol                   factor   units
    ['enx',        '\\epsilon_{nx}',         1.0e6,   'mm \\cdot mrad'],
    ['betax',      '\\beta_x',               1.0,     'm'             ],
    ['alphax',     '\\alpha_x',              1.0,     ''              ],
    ['Sx',         '\\sigma_x',              1.0e3,   'mm'            ],
    ['Sxp',        "\\sigma_{x'}",           1.0e3,   'mrad'          ],
    ['eny',        '\\epsilon_{ny}',         1.0e6,   'mm \\cdot mrad'],
    ['betay',      '\\beta_y',               1.0,     'm'             ],
    ['alphay',     '\\alpha_y',              1.0,     ''              ],
#   ['Sy',         '\\sigma_y',              1.0e3,   'mm'            ],
#   ['Syp',        "\\sigma_{y'}",           1.0e3,   'mrad'          ],
    ['St',         '\\sigma_t',              1e12,    'ps'            ],
    ['St',         '\\sigma_z',              3e11,    'mm'            ],
    ['Sdelta',     '\\sigma_{\\Delta p/p}',  100.0,   '\\%'           ],
    ['pAverage',   'p_{average}',            0.511,   'MeV/c'         ],
    ['Charge',     'Q',                      1.0e9,   'nC'            ],
])

names = items[:,0]
cols_str = "-col=" + ",".join(names)
cols_str
Out[127]:
'-col=enx,betax,alphax,Sx,Sxp,eny,betay,alphay,St,St,Sdelta,pAverage,Charge'
In [128]:
out = !sdds2stream $beam_analyzed $cols_str -pipe=out
values = out[0].split()
values = np.array(values)
values = values.astype(np.float)
values = dict(zip(names, values))
In [129]:
latex_str = r"\begin{aligned}"

for name,symbol,factor,units in items:
    value = values[name]*factor.astype(float)
    latex_str = latex_str + r"%s &= %.3f~\rm{%s} \\" % (symbol, value, units)

latex_str = latex_str + r"\end{aligned}"
In [130]:
from IPython.display import Latex
In [131]:
Latex(latex_str)
Out[131]:
\begin{aligned}\epsilon_{nx} &= 3934.118~\rm{mm \cdot mrad} \\\beta_x &= 5.024~\rm{m} \\\alpha_x &= -0.011~\rm{} \\\sigma_x &= 2.590~\rm{mm} \\\sigma_{x'} &= 0.516~\rm{mrad} \\\epsilon_{ny} &= 5727.716~\rm{mm \cdot mrad} \\\beta_y &= 1.343~\rm{m} \\\alpha_y &= 0.586~\rm{} \\\sigma_t &= 6425.874~\rm{ps} \\\sigma_z &= 1927.762~\rm{mm} \\\sigma_{\Delta p/p} &= 0.535~\rm{\%} \\p_{average} &= 1505.708~\rm{MeV/c} \\Q &= 3.008~\rm{nC} \\\end{aligned}
In [ ]: