Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/source/explanation/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ quads = accelerator.design.magnets.get("QForTune")
k = quads.strengths.get() # numpy array, one value per magnet
quads.strengths.set(k * 1.001)

orbit = accelerator.design.bpms.get("BPM").positions.get()
orbit = accelerator.design.diagnostic.bpms.get("BPM").positions.get()
```

Arrays are also how high-level tools know which elements to use: a tune correction tool, for example, is configured with the *name* of the quadrupole array it should act on.
Expand Down
11 changes: 11 additions & 0 deletions docs/source/explanation/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,20 @@ The following built-in resolvers are available:
| `env` | Environment variable | The value of the named environment variable. An error is raised if it is not set. |
| `path` | A file or directory path | The absolute, normalized path, resolved relative to pyAML's configuration root. The target is not loaded as part of loading the configuration. |
| `file` | A YAML, YML, or JSON file path | The path to a file which should be loaded and expanded into the configuration as part of loading it. Relative paths use the configuration root. |
| `template` | A template name and positional arguments | `${template:NAME,ARG1,ARG2}` inserts a copy of a registered template with its parameters substituted. |

Configuration files can also be included without an explicit `file` expression. A string ending in `.yaml`, `.yml`, or `.json` is loaded automatically for convenience. This makes it easy to split the configuration into several files if one wishes.

```{warning}
If you include a `.yaml`, `.yml`, or `.json` in the configuration file which you do not want to be loaded and expanded into the configuration (for example a lattice in JSON format), remember to put `${path:filename}` or you will get an error when loading the configuration.
```

## Configuration Templates

Templates reduce repetition in YAML or JSON configuration files. A root-level `templates` list defines reusable configuration bodies. The loader registers these definitions before expanding the file, then removes the list: `templates` is loader metadata, an exception to the constructor-argument rule above.

A template call produces an independent copy of its body. After parameter substitution, the loader expands any resolver expressions in that copy. Use the call as the whole value where a configuration object is expected, such as an entry in `devices`.

Template names must be unique within a loading session. Included files share that session's templates, while independent `Accelerator.load()` calls have separate registries; loading one file does not make its templates available to a later call.

See [Use Configuration Templates](../how-to/configuration/use-templates.md) for the syntax.
6 changes: 3 additions & 3 deletions docs/source/explanation/control-modes.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ Since every mode exposes the same elements, arrays and tools, a script can be wr

```python
def correct_tune(sr):
accelerator.tune.set([0.2, 0.3])
sr.tool.tune.set([0.2, 0.3])

correct_tune(accelerator.design) # Try it on the simulator first
correct_tune(accelerator.live) # Then run it on the machine
Expand All @@ -73,8 +73,8 @@ Different modes can also be used side by side, for example to compare the measur

```python
delta = (
accelerator.live.bpms.get("BPM").positions.get()
- accelerator.design.bpms.get("BPM").positions.get()
accelerator.live.diagnostic.bpms.get("BPM").positions.get()
- accelerator.design.diagnostic.bpms.get("BPM").positions.get()
)
```

Expand Down
10 changes: 7 additions & 3 deletions docs/source/how-to/configuration/create-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ Before writing an item, look up the constructor parameters of the class you want
For example:

```python
from pyaml.bpm.bpm import BPM
from pyaml.diagnostics.bpm.bpm import BPM

help(BPM)
# class BPM(...)
Expand Down Expand Up @@ -115,7 +115,7 @@ devices:
class: pyaml.magnet.identity_model.IdentityMagnetModel
unit: 1/m
physics: AN01-AR/EM-QP/QD.01/magnetic_strength
- class: pyaml.bpm.bpm.BPM
- class: pyaml.diagnostics.bpm.bpm.BPM
name: BPM_001
x_pos: AN01-AR/DG-EPOS/BPM.01/x
y_pos: AN01-AR/DG-EPOS/BPM.01/y
Expand Down Expand Up @@ -170,7 +170,7 @@ devices:
class: pyaml.magnet.identity_model.IdentityMagnetModel
unit: 1/m
physics: AN01-AR/EM-QP/QD.01/magnetic_strength
- class: pyaml.bpm.bpm.BPM
- class: pyaml.diagnostics.bpm.bpm.BPM
name: BPM_001
x_pos: AN01-AR/DG-EPOS/BPM.01/x
y_pos: AN01-AR/DG-EPOS/BPM.01/y
Expand Down Expand Up @@ -213,6 +213,10 @@ devices:

Values can also come from environment variables with `${env:NAME}`. See [Resolvers](../../explanation/configuration.md#resolvers) for all options.

## Reuse Configuration with Templates

If several devices share the same structure, define it once and supply names or catalog keys as parameters. See [Use Configuration Templates](./use-templates.md) for a complete example.

## Use Your Own Classes

The configuration is not limited to pyAML classes. Any class that can be imported can be used in the configuration, for example a magnet model specific to your facility:
Expand Down
94 changes: 94 additions & 0 deletions docs/source/how-to/configuration/use-templates.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Use Configuration Templates

Use a template when several devices share the same configuration and only names or catalog keys differ. Define the common fields once, then supply the differences as arguments.

## Define and Use a Template

Save this complete example as `accelerator.yaml`:

```yaml
class: pyaml.accelerator.Accelerator
facility: my_facility
machine: storage_ring
energy: 1.0e9
controls:
- class: tango.pyaml.controlsystem.TangoControlSystem
tango_host: my_host
name: live
catalog:
class: tango.pyaml.tango_catalog.TangoCatalog
disconnected: True
templates:
- name: quadrupole
parameters:
- name
- catalog_key
config:
class: pyaml.magnet.quadrupole.Quadrupole
name: "{name}"
model:
class: pyaml.magnet.identity_model.IdentityMagnetModel
unit: 1/m
physics: "domain/family/{catalog_key}/strength"
devices:
- ${template:quadrupole,QF_001,QF.01}
- ${template:quadrupole,QD_001,QD.01}
```

Each template has a unique `name`, an ordered list of `parameters`, and a `config` body.

```{warning}
Unquoted braces can be interpreted as YAML syntax. For example, `name: {name}` creates a mapping with the key `name` and a null value, rather than the string placeholder intended for substitution. You can write `name: "{name}"` instead. Always quote strings containing substitution placeholders to avoid mistakes.
```

Each `${template:NAME,args}` call inserts a copy of the body with its placeholders replaced. Here, the first argument sets the device name and the second supplies the non-repeatable part of the catalog key prefix. The result is two quadrupoles, `QF_001` and `QD_001`, with their own model configurations.

## Example to run:

Run the example in Python with the following snippet (requires `tango-pyaml`):

```python
from pathlib import Path
from tempfile import TemporaryDirectory

from pyaml.accelerator import Accelerator

configuration = """
class: pyaml.accelerator.Accelerator
facility: my_facility
machine: storage_ring
energy: 1.0e9
controls:
- class: tango.pyaml.controlsystem.TangoControlSystem
tango_host: my_host
name: live
catalog:
class: tango.pyaml.tango_catalog.TangoCatalog
disconnected: True
templates:
- name: quadrupole
parameters:
- name
- catalog_key
config:
class: pyaml.magnet.quadrupole.Quadrupole
name: "{name}"
model:
class: pyaml.magnet.identity_model.IdentityMagnetModel
unit: 1/m
physics: "domain/family/{catalog_key}/strength"
devices:
- ${template:quadrupole,QF_001,QF.01}
- ${template:quadrupole,QD_001,QD.01}
"""

with TemporaryDirectory() as directory:
path = Path(directory) / "accelerator.yaml"
path.write_text(configuration, encoding="utf-8")

accelerator = Accelerator.load(str(path))
print(accelerator.live["QF_001"])
print(accelerator.live["QD_001"])
```

For a lower-level loading behavior and explanation, see [Configuration Templates](../../explanation/configuration.md#configuration-templates).
1 change: 1 addition & 0 deletions docs/source/how-to/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ installation/developer-installation
:caption: Configuration

configuration/create-configuration
configuration/use-templates
configuration/use-schema-registry
configuration/validate-configuration
configuration/generate-json-schema
Expand Down
2 changes: 1 addition & 1 deletion docs/tutorials/use_cases/chromaticity-measurement.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def chroma_callback(action: int, cb_data: dict):
return True

# %%
chroma_monitor = SR.get_chromaticity_monitor("CHROMATICITY_MONITOR")
chroma_monitor = SR.tool.get("CHROMATICITY_MONITOR")

# Measure the chromaticity
chroma_monitor.measure(
Expand Down
30 changes: 15 additions & 15 deletions docs/tutorials/use_cases/orbit_correction.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@
# --------------------------------

# Get BPMs
bpms = SR.bpms.get("BPM")
bpms = SR.diagnostic.bpms.get("BPM")

# Get correctors
hcorr = SR.magnets.get("HCorr")
Expand All @@ -87,27 +87,27 @@
# Orbit Response Matrix
# ---------------------
#
# The ORM can be saved in multiple formats. Load it into ``SR.orbit`` before correcting.
# The ORM can be saved in multiple formats. Load it into ``SR.tool.orbit`` before correcting.

# Print string representation of the orbit response matrix
print(SR.orm)
print(SR.tool.orm)

# %%
# Measure the ORM
# ~~~~~~~~~~~~~~~~~~~~

SR.orm.measure(sleep_between_step=wait_time)
SR.orm.save("orm.json")
SR.orm.save("orm.yaml", with_type="yaml")
SR.tool.orm.measure(sleep_between_step=wait_time)
SR.tool.orm.save("orm.json")
SR.tool.orm.save("orm.yaml", with_type="yaml")

SR.orbit.load("orm.json")
SR.tool.orbit.load("orm.json")
print("ORM measured, saved and loaded.")

# %%
# Visualise the ORM
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

orm_data = SR.orm.get()
orm_data = SR.tool.orm.get()
plt.imshow(np.array(orm_data["matrix"]))
plt.colorbar()
plt.title("Orbit response matrix")
Expand Down Expand Up @@ -136,8 +136,8 @@ def disp_callback(action: int, cb_data) -> bool:
return True

# Measure the dispersion
SR.dispersion.measure(callback=disp_callback)
disp_data = SR.dispersion.get()
SR.tool.dispersion.measure(callback=disp_callback)
disp_data = SR.tool.dispersion.get()

# Plot the results
plt.plot(disp_data["frequency_response_x"], label="H dispersion")
Expand Down Expand Up @@ -187,22 +187,22 @@ def disp_callback(action: int, cb_data) -> bool:
# Correct the Orbit
# ------------------
#
# Standard correction: ``SR.orbit.correct(reference=reference)``.
# Standard correction: ``SR.tool.orbit.correct(reference=reference)``.
#
# Optional variants (uncomment to use):
#
# - **Virtual corrector weight:** down-weights correctors that are already at large strengths.
# - **RF correction:** also adjusts the RF frequency to minimise dispersion-driven orbit.

# Standard correction
SR.orbit.correct(reference=reference)
SR.tool.orbit.correct(reference=reference)

# With virtual corrector weight (ESRF style):
# SR.orbit.set_virtual_weight(1000)
# SR.orbit.correct(reference=reference)
# SR.tool.orbit.set_virtual_weight(1000)
# SR.tool.orbit.correct(reference=reference)

# With RF orbit correction (ESRF style, requires dispersion in ORM):
# SR.orbit.correct(reference=reference, rf=True)
# SR.tool.orbit.correct(reference=reference, rf=True)

sleep(wait_time)

Expand Down
28 changes: 14 additions & 14 deletions docs/tutorials/use_cases/tune-correction.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
# The tune monitor is defined in the configuration file under the name `BETATRON_TUNE`.

# %%
tune_monitor = SR.get_betatron_tune_monitor("BETATRON_TUNE")
tune_monitor = SR.diagnostic.get("BETATRON_TUNE")

# Print the string representation of the tune monitor
print(tune_monitor)
Expand Down Expand Up @@ -115,12 +115,12 @@
# Tune Correction
# -----------------------------
#
# ``SR.tune`` is the `DEFAULT_TUNE_CORRECTION` tool. ``SR.trm`` is the `DEFAULT_TUNE_RESPONSE_MATRIX` tool.
# ``SR.tool.tune`` is the `DEFAULT_TUNE_CORRECTION` tool. ``SR.tool.trm`` is the `DEFAULT_TUNE_RESPONSE_MATRIX` tool.
#
# Before correcting the tune you need a response matrix. It can be measured as shown below or loaded from a previously saved file.

# Print the string representation of the tune correction tool
SR.tune
SR.tool.tune

# %%
# Measure the Tune Response Matrix
Expand All @@ -139,35 +139,35 @@ def tune_callback(action: int, cb_data: dict):
return True

# Measure the response matrix
SR.trm.measure(sleep_between_step=wait_time, callback=tune_callback)
SR.trm.save("trm.json")
SR.tool.trm.measure(sleep_between_step=wait_time, callback=tune_callback)
SR.tool.trm.save("trm.json")

# Load the measured response matrix
SR.tune.load("trm.json")
SR.tool.tune.load("trm.json")
print("Response matrix loaded.")

# Print string representation of the tune response matrix
print(SR.trm)
print(SR.tool.trm)

# %%
# Correcting the tune
# -----------------------------
#
# ``SR.tune.set([qx, qy])`` runs the correction iteratively.
# ``SR.tool.tune.set([qx, qy])`` runs the correction iteratively.
# The ``iter`` parameter controls the number of iterations and ``wait_time`` the settling time between each iteration.

# %%
print(f"Tune before correction: {SR.tune.readback()}")
print(f"Tune before correction: {SR.tool.tune.readback()}")

qx, qy = 0.19, 0.28
print(f"\nSetting tune to [{qx}, {qy}]")
SR.tune.set([qx, qy], iter=10, wait_time=wait_time)
print(f"Tune after correction: {SR.tune.readback()}")
SR.tool.tune.set([qx, qy], iter=10, wait_time=wait_time)
print(f"Tune after correction: {SR.tool.tune.readback()}")

qx, qy = 0.21, 0.30
print(f"\nSetting tune to [{qx}, {qy}]")
SR.tune.set([qx, qy], iter=10, wait_time=wait_time)
print(f"Tune after correction: {SR.tune.readback()}")
SR.tool.tune.set([qx, qy], iter=10, wait_time=wait_time)
print(f"Tune after correction: {SR.tool.tune.readback()}")

# Print the string representation of the tune correction
SR.tune
SR.tool.tune
Loading