Deferred Expressions and Contexts

Consider the simple FODO cell:

@elements begin
  qf = Quadrupole(Kn1=0.36, L=0.5)
  d = Drift(L=1.2)
  qd = Quadrupole(Kn1=-0.36, L=0.5)
end

fodo = Beamline([qf, d, qd, d], E_ref=18e9,
        species_ref=Species("electron"))
Beamline:
 species_ref = electron
 E_ref = 1.8e10

  Index   Name   Kind         L [m]   s [m]   s_downstream [m]   
  1       qf     Quadrupole   0.5     0.0f0   0.5
  2       d      Drift        1.2     0.5     1.7
  3       qd     Quadrupole   0.5     1.7     2.2
  4       d      Drift        1.2     2.2     3.4000000000000004

We set qf.Kn1 = 0.36, and qd.Kn1 = -0.36. But what if we want to ensure that qd.Kn1 == -qf.Kn1 always? We can bake-in such an interdependence, common in accelerator parameters, using a “deferred expression” - an expression where evaluation is postponed until its result is actually needed, rather than immediately when it is defined. To do this, let’s first define a variable kq = 0.36 in an object called a Context. For interactive use, there is a global context DEFAULT_CONTEXT available:

println("BEFORE:")
println(DEFAULT_CONTEXT)

DEFAULT_CONTEXT.kq = 0.36 # Set variable kq

println("AFTER:")
println(DEFAULT_CONTEXT)
BEFORE:
Context{Any} with 0 variables:

AFTER:
Context{Any} with 1 variable:
 kq = 0.36

Then, let’s write a lambda/anonymous function that receives the context as an argument (below, c) and returns either +kq or -kq:

# Define lambda functions
kqf = c -> c.kq
kqd = c -> -c.kq

# Call with the context:
@show kqf(DEFAULT_CONTEXT)
@show kqd(DEFAULT_CONTEXT);
kqf(DEFAULT_CONTEXT) = 0.36
kqd(DEFAULT_CONTEXT) = -0.36

Now, if we can just set the quadrupole strengths Kn1 of qf and qd to always be the outputs of these functions, then we have achieved our goal! SciBmad’s DefExpr type allows you to do this, by wrapping such lambda functions:

qf.Kn1 = DefExpr(kqf);
qd.Kn1 = DefExpr(kqd);

@show qf.Kn1;
@show qd.Kn1;
qf.Kn1 = 0.36
qd.Kn1 = -0.36

When we change the value of kq, it is reflected now in the quadrupoles

DEFAULT_CONTEXT.kq = 0.37
@show qf.Kn1;
@show qd.Kn1;
qf.Kn1 = 0.37
qd.Kn1 = -0.37

To try a value for a while, push! it onto the context and pop! it off again: the previous value is used again (and a variable that push! added is removed). For example:

DEFAULT_CONTEXT.vrf = 1e6
cav = RFCavity(L=0.1, voltage=DefExpr(c -> c.vrf), rf_frequency=5e8)
println("Before push! : ", cav.voltage)
push!(DEFAULT_CONTEXT; vrf=2e6)
println("After push!  : ", cav.voltage)
pop!(DEFAULT_CONTEXT)
println("After pop!   : ", cav.voltage);
Before push! : 1.0e6
After push!  : 2.0e6
After pop!   : 1.0e6

Alternatively, withvalues does the same around a block of code, and restores the values even if the code throws an error:

withvalues(DEFAULT_CONTEXT; vrf=2.0e6) do
  println("In withvalues block     : ", cav.voltage)
end
println("Out of withvalues block : ", cav.voltage); 
In withvalues block     : 2.0e6
Out of withvalues block : 1.0e6

Thus far, we have only been using the global DEFAULT_CONTEXT. However, all Beamlines have their own context property to store beamline-specific parameters, which the deferred expressions of the elements in the beamline are evaluated with. If a variable is not found in the beamline context, it will fall back to DEFAULT_CONTEXT if the variable is defined there. All of the above machinery (push!, pop!, withvalues) also works with individual beamline contexts.

DEFAULT_CONTEXT.kq = 0.1

qf = Quadrupole(Kn1=DefExpr(c -> c.kq), L=0.5);
bl = Beamline([qf]);

child_qf = bl[qf]
println("Before setting Beamline context ---------------")
println("Parent `qf` (not in a beamline): ", qf.Kn1)
println("Child `qf` in the beamline:      ", child_qf.Kn1) 

# Set kq in the beamline context
push!(bl.context, kq = 0.2)

println("After setting Beamline context ----------------")
println("Parent `qf` (not in a beamline): ", qf.Kn1)
println("Child `qf` in the beamline:      ", child_qf.Kn1) 
Before setting Beamline context ---------------
Parent `qf` (not in a beamline): 0.1
Child `qf` in the beamline:      0.1
After setting Beamline context ----------------
Parent `qf` (not in a beamline): 0.1
Child `qf` in the beamline:      0.2

Context — Type.

Context{T}

A “scope” of variables that can be used when evaluating DefExprs. Contexts serve as a single structure that stores all (control) variables associated with beamline parameters. Contexts essentially act as structures with arbitrary field names. The type parameter T can be specified as the variables’ return type, or Union of return types, to improve performance.

A Beamline stores a context, which is passed to all DefExprs when getting parameters from the LatElements in it (a Branch or Lattice shares one context with all its Beamlines). Elements that are not in a Beamline use DEFAULT_CONTEXT.

Values can be tried temporarily: push!(c; name=value, ...) sets the variables and remembers their previous values, and pop!(c) restores them (a variable that push! added is removed again). withvalues(f, c; name=value, ...) does the same around f(), also if it throws.

Examples

julia> qf = Quadrupole(Kn1=DefExpr(c -> c.k1), L=0.5);

julia> bl = Beamline([qf], context=Context(k1 = 0.36));

julia> bl.line[1].Kn1
0.36

julia> push!(bl.context; k1 = 0.4);

julia> bl.line[1].Kn1
0.4

julia> pop!(bl.context);

julia> bl.line[1].Kn1
0.36

julia> withvalues(bl.context; k1 = 0.5) do
         bl.line[1].Kn1
       end
0.5

withvalues — Function.

withvalues(f, c::Context; name=value, ...)

Calls f() with the variables of c set to the given values, and restores them afterwards, also if f throws (as push! and pop!). Returns what f returns.

Examples

withvalues(ring.context; vrf = 0.0) do
  twiss(ring)
end

DefExpr — Type.

DefExpr{T}

A lazily-evaluated deferred expression returning type T. A deferred expression is a function of a Context c that computes a value from the variables of the context, e.g. DefExpr(c -> -c.kq). It is evaluated every time the value is needed, with the current values of the variables, so parameters that depend on each other never become “stale”.

A parameter of an element in a Beamline is evaluated with the Context of the Beamline (bl.context; a variable it does not have is taken from DEFAULT_CONTEXT). An element that is not in a Beamline uses DEFAULT_CONTEXT.

Also see Context, withvalues, rawget and deval.

Examples

julia> qf = Quadrupole(L=0.5, Kn1=DefExpr(c -> c.kq));

julia> qd = Quadrupole(L=0.5, Kn1=DefExpr(c -> -c.kq));

julia> bl = Beamline([qf, Drift(L=1.0), qd], context=Context(kq=0.36));

julia> bl[qd].Kn1
-0.36

julia> bl.context.kq = 0.4;

julia> (bl[qf].Kn1, bl[qd].Kn1)
(0.4, -0.4)

Deferred expressions can be used in arithmetic like numbers: the result is a deferred expression too. A deferred expression is evaluated in a Context by calling it with the context, or with deval:

julia> d = DefExpr(c -> c.a + c.b);

julia> c = Context(a=1.0, b=2.0);

julia> d(c)
3.0

julia> e = 2*d + 1;

julia> deval(e, c)
7.0

Getting the Deferred Expression Itself

Getting a parameter of an element always gives its current value: any deferred expression is evaluated first, as above. Sometimes you want the deferred expression itself instead, for example to build a new one from it. rawget gets a parameter exactly as it was set, and deval evaluates it in a context:

d = rawget(qf, :Kn1);
println(d isa DefExpr)
println(deval(d, bl.context)) # The same as bl[qf].Kn1
true
0.2

For example, to make qf 10% stronger while it keeps following kq in the context:

qf.Kn1 = 1.1*rawget(qf, :Kn1)
println(bl[qf].Kn1)
bl.context.kq = 0.4
println(bl[qf].Kn1)
0.22000000000000003
0.44000000000000006

Only the parameters stored as independent variables (set explicitly by the user) can be gotten this way. Others are computed from them: here Kn1 was set, so e.g. the integrated strength Kn1L and the field gradient Bn1 are computed from Kn1 (and the length or the reference energy). rawget gives an error for these, saying which parameter to use instead:

rawget(qf, :Kn1L)
Unable to rawget Kn1L: Kn1L is a dependent variable, computed from the independent variable Kn1. Use rawget with :Kn1 instead

Stacktrace:
 [1] error(s::String)
   @ Base ./error.jl:44
 [2] rawget(b::BMultipoleParams{DefExpr{Any}, 1}, key::Symbol)
   @ Beamlines ~/.julia/packages/Beamlines/gJoEL/src/bmultipole.jl:135
 [3] rawget(ele::LatElement, key::Symbol)
   @ Beamlines ~/.julia/packages/Beamlines/gJoEL/src/element.jl:282
 [4] top-level scope
   @ In[12]:1
 [5] eval(m::Module, e::Any)
   @ Core ./boot.jl:489

rawget — Function.

rawget(p::AbstractParams, key::Symbol)
rawget(ele::LatElement, key::Symbol)

Gets the independent variable key of the parameter group p or of the element ele exactly as it is stored, without evaluating deferred expressions: e.g. a DefExpr set for Kn1 is returned as that DefExpr. Evaluating it with deval in the Context of the element’s Beamline gives getproperty(ele, key).

Properties which are not independent variables but computed from them (e.g. Kn1L or Bn1 when Kn1 was set last, E_ref when p_over_q_ref was set, s) cannot be gotten raw, and give an error.

Examples

julia> qf = Quadrupole(Kn1=DefExpr(c -> c.kq), L=0.5);

julia> bl = Beamline([qf], context=Context(kq=0.36));

julia> d = rawget(qf, :Kn1);

julia> qf.Kn1 = 2*d; # Twice the stored expression, still dependent on kq

julia> bl.context.kq = 0.4;

julia> bl[qf].Kn1
0.8

deval — Function.

deval(d, c::Context=DEFAULT_CONTEXT)

Evaluates d in the Context c if it is a DefExpr, else returns d. E.g. deval(rawget(ele, :Kn1), c) for an element in a Beamline with Context c is ele.Kn1.

For a parameter group, returns a new parameter group with every DefExpr evaluated, or the parameter group itself if it contains no DefExpr.