Usage
PyTao with JupyterLab
PyTao has advanced JupyterLab integration for plotting and is generally the recommended method for using PyTao.
Start up JupyterLab as you would normally:
jupyter lab
And then use PyTao, enabling your preferred plotting backend:
from pytao import Tao
# Best available (Bokeh first, Matplotlib second)
tao = Tao(init_file="$ACC_ROOT_DIR/bmad-doc/tao_examples/cbeta_cell/tao.init", plot=True)
# Matplotlib:
tao = Tao(init_file="$ACC_ROOT_DIR/bmad-doc/tao_examples/cbeta_cell/tao.init", plot="mpl")
# Bokeh
tao = Tao(init_file="$ACC_ROOT_DIR/bmad-doc/tao_examples/cbeta_cell/tao.init", plot="bokeh")
If you wish to use Tao's internal plotting mechanism, leave the plot keyword argument off or specify plot="tao":
from pytao import Tao
# Use Tao's internal plotting mechanism:
tao = Tao(init_file="$ACC_ROOT_DIR/bmad-doc/tao_examples/cbeta_cell/tao.init")
To disable plotting entirely, use:
from pytao import Tao
# Use Tao's internal plotting mechanism:
tao = Tao(init_file="$ACC_ROOT_DIR/bmad-doc/tao_examples/cbeta_cell/tao.init", noplot=True)
The Tao object supports all Tao initialization arguments as Python keyword arguments.
That is, any of the following may be specified to Tao:
Tao(
beam_file="file_name", # File containing the tao_beam_init namelist.
beam_init_position_file="file_name", # File containing initial particle positions.
building_wall_file="file_name", # Define the building tunnel wall
command="command_string", # Commands to run after startup file commands
data_file="file_name", # Define data for plotting and optimization
debug=True, # Debug mode for Wizards
disable_smooth_line_calc=True, # Disable the smooth line calc used in plotting
external_plotting=True, # Tells Tao that plotting is done externally to Tao.
geometry="<width>x<height>", # Plot window geometry (pixels)
hook_init_file="file_name", # Init file for hook routines (Default = tao_hook.init)
init_file="file_name", # Tao init file
lattice_file="file_name", # Bmad lattice file
log_startup=True, # Write startup debugging info
no_stopping=True, # For debugging: Prevents Tao from exiting on errors
noinit=True, # Do not use Tao init file.
noplot=True, # Do not open a plotting window
nostartup=True, # Do not open a startup command file
no_rad_int=True, # Do not do any radiation integrals calculations.
plot_file="file_name", # Plotting initialization file
prompt_color="color", # Set color of prompt string. Default is blue.
reverse=True, # Reverse lattice element order?
rf_on=True, # Use "--rf_on" to turn off RF (default is now RF on)
quiet=True, # Suppress terminal output when running a command file?
slice_lattice="ele_list", # Discards elements from lattice that are not in the list
start_branch_at="ele_name", # Start lattice branch at element.
startup_file="file_name", # Commands to run after parsing Tao init file
symbol_import=True, # Import symbols defined in lattice files(s)?
var_file="file_name", # Define variables for plotting and optimization
)
Note that quiet mode may cause portions of PyTao to function improperly. See
upstream issue.
SubprocessTao - Tao in a subprocess
If you wish to load multiple lattices at the same time, consider using SubprocessTao.
It can be used in the same way as the Tao class.
Use this form when possible:
with SubprocessTao(lattice_file) as tao:
print(tao.cmd("show lat"))
Once the with block ends, the subprocess will automatically be closed and cleaned up.
For manual lifetime control, use tao.close_subprocess().
PyTao on the command-line
PyTao has a simple IPython entrypoint, giving you quick access to Tao in Python.
The following will start IPython with a Tao instance available as tao:
pytao -init_file "$ACC_ROOT_DIR/bmad-doc/tao_examples/cbeta_cell/tao.init"
To use PyTao's Matplotlib backend, set --pyplot=mpl:
pytao --pyplot=mpl -init "$ACC_ROOT_DIR/bmad-doc/tao_examples/cbeta_cell/tao.init"
Or use the environment variable PYTAO_PLOT:
PYTAO_PLOT=mpl pytao -init_file "$ACC_ROOT_DIR/bmad-doc/tao_examples/cbeta_cell/tao.init"
In [1]: tao.plot("beta")
Logging
PyTao uses the standard Python logging
module, with all of its loggers under the "pytao" namespace. Until logging is
configured, PyTao stays silent: a NullHandler is attached at import, so it
never emits unexpected output or interferes with other logging in your program.
The simplest way to turn logging on is pytao.configure_logging:
import pytao
pytao.configure_logging(level="DEBUG")
This configures the "pytao" logger alone. It does not touch the root
logger, and PyTao's records do not propagate to it, so configure_logging will
not conflict with — or be affected by — logging your application configures
elsewhere.
configure_logging accepts the following arguments (all optional):
| Argument | Default | Description |
|---|---|---|
level |
PYTAO_LOG env, else WARNING |
Console logging level for the pytao logger, e.g. "DEBUG" or "WARNING". |
filename |
PYTAO_LOG_FILE env |
If set, also write logs at DEBUG to this file while the console stays at level. |
mode |
PYTAO_LOG_MODE env, else quiet |
How Tao message levels map onto Python logging levels (see below). |
console |
True |
Emit records to the console (stderr) at level. Set False for file-only logging. |
format |
timestamped default | Format string for records. |
It returns the configured "pytao" logger.
If you would rather configure logging yourself, everything lives under the
"pytao" logger and can be driven with the standard library directly:
import logging
logging.basicConfig()
logging.getLogger("pytao").setLevel(logging.DEBUG)
Messages that Tao itself reports ([INFO ...], [ERROR ...], and so on) are
captured from its output and re-emitted as Python log records on the
pytao.core logger.
Tao message levels
Tao messages have their own severity levels (INFO, SUCCESS, MESSAGE,
WARNING, ERROR, FATAL, and ABORT). How these are translated to Python
logging levels is controlled by the PYTAO_LOG_MODE environment variable:
quiet(default): non-error Tao messages are logged atDEBUGso that chatty Bmad/Tao output stays out of the way; errors are logged atERROR.matching: each Tao level is translated to its closest Python equivalent, so standard logging verbosity settings (INFO,WARNING, ...) apply to Tao messages as you would expect.
| Tao level | quiet (default) |
matching |
|---|---|---|
INFO |
DEBUG |
INFO |
SUCCESS |
DEBUG |
INFO |
MESSAGE |
DEBUG |
INFO |
WARNING |
DEBUG |
WARNING |
ERROR |
ERROR |
ERROR |
FATAL |
ERROR |
CRITICAL |
ABORT |
ERROR |
CRITICAL |
PYTAO_LOG_MODE=matching python my_script.py
The mode is read from PYTAO_LOG_MODE once when PyTao is imported. It may also
be set through configure_logging(mode=...), or changed at runtime with
pytao.set_log_mode (and read back with pytao.get_log_mode):
import pytao
pytao.set_log_mode("matching")
Logging on the command-line
At startup the pytao CLI calls configure_logging for you, mapping
--pylog to level, --pylog-file to filename, and --pylog-mode to
mode. Each falls back to its environment variable (PYTAO_LOG,
PYTAO_LOG_FILE, PYTAO_LOG_MODE), with --pylog defaulting to WARNING.
pytao --pylog DEBUG -init_file "$ACC_ROOT_DIR/bmad-doc/tao_examples/cbeta_cell/tao.init"
Combining PYTAO_LOG_MODE=matching with --pylog INFO shows Tao's
informational and warning messages as they arrive, without PyTao's internal
debugging output:
PYTAO_LOG_MODE=matching pytao --pylog INFO -init_file "$ACC_ROOT_DIR/bmad-doc/tao_examples/cbeta_cell/tao.init"
To leave logging entirely unconfigured, set PYTAO_LOG to an empty string
(and omit --pylog).
For debugging, --pylog-file (or the PYTAO_LOG_FILE environment variable)
additionally writes PyTao logs to a file. The file always captures DEBUG
level and above, while console output stays at the --pylog level:
pytao --pylog-file pytao-debug.log -init_file "$ACC_ROOT_DIR/bmad-doc/tao_examples/cbeta_cell/tao.init"
PyTao plotting and startup scripts
When PyTao is instructed to use its Matplotlib or Bokeh backends, it configures
the underlying Tao instance to work in -noplot mode. If you have plotting
calls in your startup script, you may see warnings and errors that prevent you
from using your Tao object.
Consider these alternatives:
- Use
-nostartup(orTao(nostartup=True)) to avoid using your startup file. - Consider making a "no plot" alternative startup file.
- Use PyTao error filtering to ignore errors coming from specific Tao functions at startup:
import matplotlib.pyplot as plt
from pytao import Tao, filter_tao_messages_context
with filter_tao_messages_context(functions=["tao_find_plots"]):
tao = Tao(init_file="tao.init", plot="mpl")
tao.plot("beta")
plt.show()
Notes about Bokeh on JupyterHub
If you are using PyTao with Bokeh on your computer and are running JupyterLab locally, you can safely ignore this section.
If you are accessing a JupyterHub deployment on an HPC cluster through a
non-localhost website, there are some additional setup steps required.
Please read this document from Bokeh for full details.
At minimum, you will need to:
- Configure
JUPYTER_BOKEH_EXTERNAL_URLto point to your server. For example, users may specify the following in their~/.bashrc:export JUPYTER_BOKEH_EXTERNAL_URL="https//example.com"(replacingexample.comwith the URL you use to access JupyterHub)
Additionally, you may be required to:
- In the JupyterHub environment,
conda install jupyter-server-proxy - Restart JupyterHub
Environment variables
| Variable | Default | Description |
|---|---|---|
PYTAO_LOG_MODE |
quiet |
How Tao message levels are translated to Python logging levels. quiet logs non-error Tao messages at DEBUG; matching translates each to its closest Python equivalent. See Logging. |
PYTAO_LOG |
WARNING |
Default level for configure_logging (and the pytao CLI when --pylog is not given). Set to an empty string to leave logging unconfigured. |
PYTAO_LOG_FILE |
(unset) | Default filename for configure_logging (and the pytao CLI when --pylog-file is not given). The file captures DEBUG and above; console output stays at the level. |
PYTAO_PLOT |
tao |
Plotting backend for the pytao CLI: tao, mpl, or bokeh. Takes precedence over --pyplot. |
PYTAO_FILTER_TAB |
y |
Filter tab completion on PyTao model classes, hiding private and pydantic-internal attributes. Set to n to show all attributes. Also toggleable at runtime with pytao.model.base.toggle_tab_completion_filtering. |
PYTAO_BOKEH_NBCONVERT |
(unset) | Set to 1 or y when exporting notebooks with nbconvert. Bokeh plots are then rendered as static grid plots instead of server-backed applications, which would show up blank in exported HTML. |