For Developers

This page is for those who work on SciBmad itself: the Julia package, the Python package scibmad, the SciBmad distribution and this documentation. How the project is run, and the rules for contributions written with AI tools, are described in Governance.

Repository Layout

All of SciBmad is in the repository bmad-sim/SciBmad:

Directory

Contents

julia/

The Julia package SciBmad (src, ext, test, benchmark), registered in the General registry from this subdirectory

python/

The Python package pyscibmad (import scibmad), see its README

distribution/

The SciBmad distribution (installed with conda), see its README

docs/

This documentation, in both languages, see its README

examples/

Notebooks in Julia and Python

lattices/

Lattice files used by the examples

python/ was the repository bmad-sim/PySciBmad and distribution/ the repository bmad-sim/SciBmad-Distribution until December 2026. Both moved here with their history. Their old pull requests are referred to as bmad-sim/PySciBmad#n and bmad-sim/SciBmad-Distribution#n.

Working on the Julia Package

Develop julia/ (and, if you change them too, the other SciBmad packages) in an environment of your own, and run the tests there:

julia --project=myenv -e 'using Pkg; Pkg.develop(path="path/to/SciBmad/julia")'
julia --project=myenv -e 'using Pkg; Pkg.add(["Test", "GTPSA", "DelimitedFiles", "Random"])'
julia --project=myenv -e 'include("path/to/SciBmad/julia/test/runtests.jl")'

SciBmad’s precompile workload takes several minutes. To turn it off while developing, put this in the environment’s LocalPreferences.toml:

[SciBmad]
precompile_workload = false

Working on the Python Package

The Python package is a thin layer on juliacall. It has no list of SciBmad’s functions: every name of SciBmad, and of the packages it includes (Beamlines, BeamTracking, GTPSA, NonlinearNormalForm, …), is looked up in Julia when Python asks for it, with the same arguments and keyword arguments. New functionality of the Julia packages is therefore available in Python without changes to the Python package, following the rules below.

To work on it, install it from the checkout and run its tests with a Julia project in which SciBmad (developed from julia/) and PythonCall are installed:

pip install -e "python[test]"
cd python
SCIBMAD_JULIA=/path/to/julia SCIBMAD_PROJECT=/path/to/project python -m pytest

How scibmad chooses the Julia it runs (the conda distribution, a downloaded distribution, or one installed with juliapkg) is described in its README.

What Python Writes Differently

The Python version of this documentation shows every example in Python. These are the rules by which the Python form follows from the Julia form:

Julia

Python

@elements begin qf = Quadrupole(...) end

with sb.elements(): qf = sb.Quadrupole(...)

names the elements after their variables (or give name="qf")

@knob(qf.Kn1, lower=0)

sb.Knob(qf, "Kn1", lower=0)

Python cannot capture qf.Kn1 itself, only its value

res.x[qd, turn=3]

res.x(qd, turn=3)

Python has no keywords in indexing: a call of a result that cannot be called is indexing

res.x[]

res.x()

tw.beta1[qd, :], at=:

tw.beta1[qd, :], at=...

: in brackets; elsewhere ... (or slice(None))

tw.beta1[end], bl[end-1], tw.beta1[begin]

tw.beta1[-1], bl[-2], tw.beta1[sb.begin]

also sb.end, sb.end - 1

tw.beta1[(0, 1.23)]

tw.beta1[0:1.23]

an s-range is a slice of floats (a tuple in brackets would be two indexes)

tw.beta1[2:4]

tw.beta1[2:5]

a Python slice does not include its stop

:exit, rawget(qf, :Kn1)

"exit", sb.rawget(qf, "Kn1")

strings are Symbols where a function needs one (or sb.Symbol("exit"))

optimize!, push!

sb.optimize, sb.push_

f! is f_; optimize, undo, setknobs, phase_trombone, scalarize also have their name without !

CMAES(lambda=8)

sb.CMAES(lambda_=8)

a keyword argument or property named like a Python keyword takes a trailing underscore

sum(abs2, exprs)

sb.sum(sb.abs2, exprs)

Julia’s functions build an expression (see Values and operators)

[1e-3 0 0 0 0 0]

[[1e-3, 0, 0, 0, 0, 0]]

a list of lists of numbers, or a NumPy array, is a matrix

(beta1=10, alpha1=0)

dict(beta1=10, alpha1=0)

also fidelity levels of CMAES

Xoshiro(1)

sb.julia.package("Random").Xoshiro(1)

a Julia random number generator, e.g. rng of CMAES

x -> x.kind == "Quadrupole"

lambda x: x.kind == "Quadrupole"

r"q.*"i

re.compile("q.*", re.I)

DefExpr(c -> -c.kq)

sb.DefExpr(lambda c: -c.kq)

see Deferred expressions

withvalues(c; k=1.0) do ... end

with sb.withvalues(c, k=1.0): ...

x === y, x isa Twiss

x is y, isinstance(x, sb.Twiss)

sin.(x), x .* y

np.sin(x), x * y

arrays are NumPy arrays

MtlArray(Float32.(v0))

sb.device("metal").asarray(v0, dtype=np.float32)

see GPUs

try ... catch err ... end

try: ... except sb.JuliaError as err: ...

Numbers, Arrays and Indexes

Python numbers, strings, lists, tuples and dictionaries are converted to their Julia equivalents when they are passed to SciBmad: a list becomes a Julia vector of the type that the Julia literal [...] would have (so [qf, qd] is a vector of elements), a list of lists of numbers a matrix, as for NumPy. NumPy arrays become Julia arrays of the same element type (float32 stays 32-bit), with the same indexes: v0[i, j] in NumPy is v0[i+1, j+1] in Julia.

Julia arrays of numbers are returned as NumPy arrays. A CPU array shares its memory with Julia (no copy), so changing it changes the Julia array: ring.context.kicks[0] = 1e-5 sets a corrector. Other Julia arrays (of elements, of expressions, GPU arrays) are returned as sequences that are indexed as NumPy arrays are, from 0.

Two kinds of integers are not array indexes: the beamline index of an element (its position in the beamline, as in fodo[4] and tw.beta1[4]), and the particle number of track results (res.x(turn=3, particle=1)). They start at 1, in Python as in Julia and in the printed tables of SciBmad, so that the same element has the same number everywhere (for example the beamline_index of an element is its index in the beamline). The lists that SciBmad returns start at 0 as always in Python: fodo[[d]][0] is the first placement of d.

The quantities of a lazy dynamic aperture (sb.lazy_dynamic_aperture) are indexed as the arrays of the result of sb.dynamic_aperture, which are NumPy arrays: lda.area[0] is the expression for da.area[0], the area at the first δ. The rows of res.archive of an optimization are also NumPy rows, from 0, but sb.pareto_front(res).index holds Julia’s row numbers (from 1) of the candidates in the archive: use sb.pareto_front(res).x and .f.

Values and Operators

A SciBmad value without a Python equivalent (an element, a beamline, a twiss result, a Taylor series, an expression of a lazy twiss, …) is a proxy of the Julia value. Its attributes are the Julia properties (ele.Kn1, also to set them), repr and Jupyter show it as Julia does, help(sb.twiss) shows the Julia documentation, and dir() lists the properties.

The operators of SciBmad’s own values are Julia’s, so that Taylor series, deferred expressions, time-dependent parameters, batch parameters and the expressions of a lazy twiss combine as in Julia: 1e-4*np.sin(1e6*sb.Time()) is a time-dependent parameter, and tw.q1 == 0.25 a target. NumPy’s functions (np.sin, np.sqrt, …) of these values are the Julia functions. A comparison of expressions is a target, not a truth value: 0.1 <= tw.q1 <= 0.3 is an error (write sb.Target(tw.q1, lower=0.1, upper=0.3)).

The columns of twiss and track results behave as NumPy arrays of their values in arithmetic (tw.dx / np.sqrt(tw.beta1)), with NumPy (np.max(tw.beta1)), and with Matplotlib (plt.plot(tw.s, tw.beta1)); np.asarray(tw.beta1) is the array. Julia’s functions such as sb.maximum, sb.mean and sb.sum act on expressions of a lazy twiss, which NumPy cannot. The solvers sb.GN and sb.LM take a sum of squares written as Julia’s sum(abs2, exprs), sb.sum(sb.abs2, exprs): Python’s sum(e**2 for e in exprs) is an ordinary expression to them.

Errors in Julia are raised as sb.JuliaError with Julia’s message, also as the matching Python exception (IndexError, KeyError, TypeError, ValueError, AttributeError, …).

Deferred Expressions

sb.DefExpr(f) calls the Python function f once, with symbolic context variables, and keeps the Julia expression it builds from them: evaluating it later calls no Python, so it is as fast as a Julia function, and works on GPUs. This works for arithmetic, NumPy functions and entries of vector variables (c.dk[i], from 0 as for the NumPy array). Python values other than the context variables (such as i in a loop) are read when sb.DefExpr is called. A function that does more with the variables, for example math.sin(c.kq) or an if on them, is called from Julia every time instead, which is much slower and works only on the CPU (with a PerformanceWarning).

Python functions given to SciBmad elsewhere (fodo[lambda e: ...], sb.lazy(f), function knobs, the callback of sb.optimize) are called from Julia, with the arguments as proxies.

GPUs

gpu = sb.device("cuda")  # or "metal", "amdgpu", "oneapi"; sb.device() picks the one present
v0 = gpu.asarray(np.random.rand(100_000, 6) * 1e-5)
res = sb.track(fodo, v0=v0, n_turns=100)
x = np.asarray(res.x(turn=100))  # copied to the host

The first sb.device of a kind installs its Julia package (CUDA.jl, Metal.jl, AMDGPU.jl or oneAPI.jl) if needed, once. Apple’s Metal GPUs have no 64-bit floats: give dtype=np.float32. GPU arrays are computed with on the GPU (v0 * 2 is a GPU array), and np.asarray copies them to the host.

The Julia Session

sb.julia is the Julia session: sb.julia.Base, sb.julia.Main and the modules of SciBmad are its modules, sb.julia.package("Optim", install=True) loads another Julia package, and sb.julia.seval("...") evaluates Julia code. SciBmad itself never needs Julia code, with one exception (below).

Limitations

These follow from Python and Julia themselves, and are not expected to change:

  • Callbacks of the tracking (callbacks of a Bunch, see Callbacks) run inside the compiled tracking kernels, for every particle and integration step, also on GPUs. They must be Julia functions, e.g. sb.julia.seval("(i, coords, p) -> ...").

  • Python functions in Julia run only on the CPU and are much slower than Julia code (see Deferred expressions); time-dependent parameters built from sb.Time() with operators and NumPy functions are Julia code.

  • Interrupting: Ctrl-C stops a long Julia computation only when it returns to Python.

  • Mixing Taylor series of two GTPSA Descriptors aborts Julia, and with it Python (see Parametric Normal Form).

  • Julia values cannot be pickled (e.g. for multiprocessing); save results as NumPy arrays.

  • Static tools (type checkers, IDE completion before running) do not know SciBmad’s names, which come from Julia when the program runs; dir(sb) and completion in IPython and Jupyter list them.

  • New Julia functionality is available in Python as soon as SciBmad has it, with the rules of this page. Only two of them could change meaning if SciBmad changed: a call of a value that cannot be called is indexing (if a type of result became callable, x(...) would call it), and the names without ! above (sb.optimize stays optimize!).

Writing the Documentation

This documentation is built twice from the same pages: the Julia version at the root of the site and the Python version under python/. The “Julia | Python” switch at the top right goes to the same page in the other version. In the pages:

  • Every Julia code cell is followed by its Python version, a {code-cell} python cell. Each version shows only the cells of its language. A Julia cell that has no Python version carries the tag julia-only.

  • Text for one language only goes in a :::{only} julia (or python) block, or inline in the roles {jl} and {py} (code) and {jltext} and {pytext} (plain text).

  • The Python version talks to Python users as the Julia version talks to Julia users: it shows how to do things in Python, without comparing with Julia. The rules above, which relate the two, belong on this page.

How to build the documentation, also without running its code, is described in its README.

Continuous Integration

Workflow

Runs on

Does

CI.yml

every PR, main, tags

Julia tests (lts and 1; Ubuntu, Windows), docs build and deployment

Python.yml

PRs that change python/, julia/src, julia/ext, julia/Project.toml

Python tests against julia/ of the checkout

Benchmark.yml

PRs into main

julia/benchmark/benchmarks.jl with SciBmad of the PR and of main, in the job summary

Release.yml

release tags, PRs that change distribution/, by hand

builds the distribution, and for a release publishes it and the Python package (below)

TagBot.yml, CompatHelper.yml

after a registration, daily

tags releases, proposes compat updates for julia/

Making a Release

A release of SciBmad is a release of the Julia package, the Python package and the distribution, all with the same version.

  1. In a PR, set the new version in all of these files:

    • julia/Project.toml (version)

    • python/src/scibmad/_version.py

    • python/src/scibmad/_runtime.py (SCIBMAD_VERSION; for a new minor version also SUPPORTED)

    • python/src/scibmad/juliapkg.json

    • python/conda/recipe.yaml (version; for a new minor version also the scibmad requirement)

  2. After the PR is merged, register the Julia package by commenting on the merge commit:

    @JuliaRegistrator register subdir=julia
    
  3. Once the General registry has merged the registration, TagBot tags the commit v<version> and makes a GitHub release. The tag starts Release.yml, which:

    • checks that the versions of step 1 all equal the tag (otherwise nothing is built),

    • builds the distribution with this SciBmad on five platforms (about an hour each),

    • publishes it to the scibmad-forge channel on anaconda.org, deleting releases older than the previous one (the channel has room for two),

    • attaches its packages to the GitHub release, where every release stays downloadable, with the index that pip installations of scibmad use to download the distribution,

    • publishes pyscibmad to PyPI and to the scibmad-forge channel.

If a step fails, rerun the failed jobs of that run (Actions > Release). To rebuild the distribution of a release, for example after a fix in distribution/, run the workflow by hand on the release tag with a higher build_number and publish ticked (see the distribution’s README).

Releasing a fix of the Python package alone, without a new SciBmad version, is not set up yet.

The workflow needs the repository secret ANACONDA_API_TOKEN (an organization token of scibmad-forge on anaconda.org with write access), and PyPI must list Release.yml of this repository with the environment pypi as a trusted publisher of pyscibmad.