diff --git a/.github/workflows/dt4acc-integration.yml b/.github/workflows/dt4acc-integration.yml index af0453b1..24385dd6 100644 --- a/.github/workflows/dt4acc-integration.yml +++ b/.github/workflows/dt4acc-integration.yml @@ -124,3 +124,112 @@ jobs: with: name: dt4acc-twin-log path: ${{ runner.temp }}/dt4acc-twin.log + + epics-smoke: + runs-on: ubuntu-24.04 + timeout-minutes: 30 + + defaults: + run: + shell: bash -el {0} + + env: + DT4ACC_IMAGE_URI: ${{ inputs.dt4acc_image_uri || 'oras://registry.synchrotron-soleil.fr/software_control_system_public/dt4acc-soleil-twin:latest' }} + DT4ACC_REGISTRY_USER: ${{ secrets.DT4ACC_REGISTRY_USER }} + DT4ACC_REGISTRY_PASSWORD: ${{ secrets.DT4ACC_REGISTRY_PASSWORD }} + PYAML_DT4ACC_EPICS_PREFIX: pyaml-it + EPICS_CA_AUTO_ADDR_LIST: "NO" + EPICS_CA_ADDR_LIST: 127.0.0.1 + EPICS_PVA_AUTO_ADDR_LIST: "NO" + EPICS_PVA_ADDR_LIST: 127.0.0.1 + + steps: + - uses: actions/checkout@v4 + with: + repository: ${{ github.event.pull_request.head.repo.full_name || github.repository }} + ref: ${{ github.event.pull_request.head.ref || github.ref_name }} + + - name: Set up Apptainer + uses: eWaterCycle/setup-apptainer@v2 + + - name: Set up Python environment + uses: mamba-org/setup-micromamba@v2 + with: + environment-name: pyaml-dt4acc-integration + create-args: >- + -c conda-forge + python=3.12 + pip + pytest + pytango + cache-environment: true + + - name: Install pyAML and the EPICS control-system backend + run: | + python -m pip install --upgrade pip + python -m pip install -e ".[test]" + python -m pip install "ophyd-async[ca, pva]<0.21" + python -m pip install --no-deps pyaml-cs-oa + python -c "import aioca; import pyaml_cs_oa" + + - name: Log in to GitLab registry + if: ${{ env.DT4ACC_REGISTRY_USER != '' && env.DT4ACC_REGISTRY_PASSWORD != '' }} + run: | + printf '%s' "${DT4ACC_REGISTRY_PASSWORD}" | + apptainer registry login \ + --username "${DT4ACC_REGISTRY_USER}" \ + --password-stdin \ + oras://gitlab-registry.synchrotron-soleil.fr + + - name: Pull dt4acc twin image + run: | + mkdir -p "${RUNNER_TEMP}/apptainer" + apptainer pull --force --disable-cache \ + "${RUNNER_TEMP}/apptainer/dt4acc-soleil-twin.sif" \ + "${DT4ACC_IMAGE_URI}" + + - name: Start dt4acc EPICS twin + run: | + LOG_FILE="${RUNNER_TEMP}/dt4acc-epics-twin.log" + PID_FILE="${RUNNER_TEMP}/dt4acc-epics-twin.pid" + + ACCEL_SETUP_FILE=$(python -c "from pyaml_test_lattice import configurations; print(configurations['dt4acc/fodo_1gev_6d_dt4acc_epics.json'])") + LATTICE_FILE=$(python -c "from pyaml_test_lattice import lattices; print(lattices['fodo_1gev_6d.json'])") + + bash tests/integration/start_dt4acc_twin.sh \ + --mode epics \ + --accelerator-setup-file "${ACCEL_SETUP_FILE}" \ + --lattice-file "${LATTICE_FILE}" \ + --prefix "${PYAML_DT4ACC_EPICS_PREFIX}" \ + --sif "${RUNNER_TEMP}/apptainer/dt4acc-soleil-twin.sif" \ + --log-file "${LOG_FILE}" \ + --pid-file "${PID_FILE}" \ + --timeout 900 \ + --detach + + - name: Run pyAML dt4acc EPICS smoke test + env: + PYAML_DT4ACC_INTEGRATION: "1" + run: | + python -m pytest -v tests/integration/test_dt4acc_epics_twin_smoke.py + + - name: Stop dt4acc EPICS twin + if: always() + run: | + PID_FILE="${RUNNER_TEMP}/dt4acc-epics-twin.pid" + if [ -f "${PID_FILE}" ]; then + TWIN_PID="$(cat "${PID_FILE}")" + kill -- "-${TWIN_PID}" 2>/dev/null || kill "${TWIN_PID}" 2>/dev/null || true + sleep 5 + kill -KILL -- "-${TWIN_PID}" 2>/dev/null || kill -KILL "${TWIN_PID}" 2>/dev/null || true + fi + if [ -f "${RUNNER_TEMP}/dt4acc-epics-twin.log" ]; then + tail -n 200 "${RUNNER_TEMP}/dt4acc-epics-twin.log" || true + fi + + - name: Upload dt4acc EPICS logs + if: always() + uses: actions/upload-artifact@v4 + with: + name: dt4acc-epics-twin-log + path: ${{ runner.temp }}/dt4acc-epics-twin.log diff --git a/pyproject.toml b/pyproject.toml index 76a44ebc..b19569eb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -63,7 +63,7 @@ cs-oa-tango = [ test = [ "pytest>=7.4", "pytest-cov>=3.0", - "pyaml-test-lattice>=0.2.0", + "pyaml-test-lattice>=0.4.0", "jsonschema>=4.18", ] doc = [ diff --git a/tests/integration/fodo_fixtures.py b/tests/integration/fodo_fixtures.py new file mode 100644 index 00000000..a07b0626 --- /dev/null +++ b/tests/integration/fodo_fixtures.py @@ -0,0 +1,41 @@ +"""Build pyAML accelerators from the pyaml-test-lattice FODO 1 GeV 6D fixtures.""" + +from pathlib import Path + +from pyaml_test_lattice import configurations, lattices + +from pyaml.accelerator import Accelerator +from pyaml.configuration import ConfigurationManager + +FODO_LATTICE_KEY = "fodo_1gev_6d.json" + + +def load_fodo_fragment(config_key: str, control_overrides: dict | None = None) -> dict: + """Load one pyaml-test-lattice FODO config fragment as a plain dict. + + The ``lattice`` reference is overridden since it lives in a different + package subtree (``data/lattice``) than the config fragment + (``data/configuration``). + + ``control_overrides`` entries are merged into every control system of the + fragment, for instance an EPICS PV ``prefix``. + """ + config_path = Path(configurations[config_key]) + manager = ConfigurationManager() + manager.add(config_path) + fragment = manager.to_dict() + + fragment["simulators"][0]["lattice"] = str(Path(lattices[FODO_LATTICE_KEY])) + + for control in fragment.get("controls", []): + control.update(control_overrides or {}) + + return fragment + + +def build_fodo_accelerator(config_key: str, control_overrides: dict | None = None) -> Accelerator: + """Build an Accelerator from one pyaml-test-lattice FODO config fragment.""" + configuration_manager = ConfigurationManager() + configuration_manager.add(load_fodo_fragment(config_key, control_overrides)) + + return Accelerator.from_dict(configuration_manager.to_dict()) diff --git a/tests/integration/start_dt4acc_twin.sh b/tests/integration/start_dt4acc_twin.sh index eea0bff3..36fd656c 100644 --- a/tests/integration/start_dt4acc_twin.sh +++ b/tests/integration/start_dt4acc_twin.sh @@ -2,7 +2,8 @@ set -Eeuo pipefail DEFAULT_IMAGE_URI="oras://registry.synchrotron-soleil.fr/software_control_system_public/dt4acc-soleil-twin:latest" -READY_PATTERN="Calculation heartbeat: simulator/ringsimulator/ringsimulator reachable" +TANGO_READY_PATTERN="Calculation heartbeat: simulator/ringsimulator/ringsimulator reachable" +EPICS_READY_PATTERN="EPICS IOC ready:" usage() { cat <<'EOF' @@ -15,8 +16,13 @@ Required simulator input data: --lattice-file FILE Lattice file passed to the twin. Options: - --tango-host HOST Tango database host. Default: localhost. - --tango-port PORT Tango database port. If omitted, the twin may choose it. + --mode tango|epics Twin flavour. Default: tango. + tango: Tango twin with an embedded Tango database. + epics: EPICS soft-IOC twin, no database. + --tango-host HOST Tango mode only. Tango database host. Default: localhost. + --tango-port PORT Tango mode only. Tango database port. If omitted, the twin may choose it. + --prefix PREFIX EPICS mode only. PV prefix. If omitted, the twin uses + DT4ACC_PREFIX, then the current user name. --image-uri URI Apptainer image URI. Default: dt4acc latest ORAS image. --sif FILE Use a local SIF file instead of --image-uri. --log-file FILE Log file path. Default: mktemp under /tmp. @@ -25,8 +31,9 @@ Options: --detach Exit after readiness and leave the twin running. -h, --help Show this help. -The script prints "Ready to use" when the twin reaches the same heartbeat used by -the dt4acc-integration CI workflow. Keep this process running; press Ctrl-C to +The script prints "Ready to use" when the twin reaches the readiness log line used by +the dt4acc-integration CI workflow (the calculation heartbeat in Tango mode, the +"EPICS IOC ready" line in EPICS mode). Keep this process running; press Ctrl-C to stop the twin. With --detach, the script exits after readiness; use --pid-file so a later step can stop the twin. EOF @@ -34,8 +41,12 @@ EOF accelerator_setup_file="" lattice_file="" +mode="tango" tango_host="localhost" tango_port="" +tango_option_given="0" +prefix="" +prefix_given="0" image_uri="${DEFAULT_IMAGE_URI}" sif_file="" log_file="" @@ -54,12 +65,23 @@ while (($#)); do lattice_file="${2:-}" shift 2 ;; + --mode) + mode="${2:-}" + shift 2 + ;; --tango-host) tango_host="${2:-}" + tango_option_given="1" shift 2 ;; --tango-port) tango_port="${2:-}" + tango_option_given="1" + shift 2 + ;; + --prefix) + prefix="${2:-}" + prefix_given="1" shift 2 ;; --image-uri) @@ -129,6 +151,27 @@ if [[ -z "${accelerator_setup_file}" || -z "${lattice_file}" ]]; then exit 2 fi +case "${mode}" in + tango) + if [[ "${prefix_given}" == "1" ]]; then + echo "--prefix is only valid with --mode epics." >&2 + exit 2 + fi + ready_pattern="${TANGO_READY_PATTERN}" + ;; + epics) + if [[ "${tango_option_given}" == "1" ]]; then + echo "--tango-host and --tango-port are only valid with --mode tango." >&2 + exit 2 + fi + ready_pattern="${EPICS_READY_PATTERN}" + ;; + *) + echo "--mode must be 'tango' or 'epics', got '${mode}'." >&2 + exit 2 + ;; +esac + if ! command -v apptainer >/dev/null 2>&1; then echo "apptainer is required but was not found in PATH." >&2 exit 127 @@ -253,11 +296,16 @@ detect_tango_port() { } echo "Starting dt4acc twin" +echo " mode: ${mode}" echo " accelerator setup: ${accelerator_setup_file}" echo " lattice file: ${lattice_file}" -echo " tango host: ${tango_host}" -echo " tango port: ${tango_port:-auto}" -echo " requested TANGO_HOST: ${requested_tango_host}" +if [[ "${mode}" == "tango" ]]; then + echo " tango host: ${tango_host}" + echo " tango port: ${tango_port:-auto}" + echo " requested TANGO_HOST: ${requested_tango_host}" +else + echo " PV prefix: ${prefix:-twin default}" +fi echo " image: ${image_ref}" echo " log file: ${log_file}" if [[ -n "${pid_file}" ]]; then @@ -266,15 +314,31 @@ fi trap cleanup INT TERM EXIT -setsid env TANGO_HOST="${requested_tango_host}" apptainer run \ - "${bind_args[@]}" \ - "${image_ref}" \ - tango-db-embedded \ - --force-kill-db \ - --tango-host "${requested_tango_host}" \ - --accelerator-setup-file "${accelerator_setup_container}" \ - --lattice-file "${lattice_container}" \ - >"${log_file}" 2>&1 & +if [[ "${mode}" == "tango" ]]; then + setsid env TANGO_HOST="${requested_tango_host}" apptainer run \ + "${bind_args[@]}" \ + "${image_ref}" \ + tango-db-embedded \ + --force-kill-db \ + --tango-host "${requested_tango_host}" \ + --accelerator-setup-file "${accelerator_setup_container}" \ + --lattice-file "${lattice_container}" \ + >"${log_file}" 2>&1 & +else + epics_args=( + --accelerator-setup-file "${accelerator_setup_container}" + --lattice-file "${lattice_container}" + ) + if [[ -n "${prefix}" ]]; then + epics_args+=(--prefix "${prefix}") + fi + setsid apptainer run \ + "${bind_args[@]}" \ + "${image_ref}" \ + epics-embedded \ + "${epics_args[@]}" \ + >"${log_file}" 2>&1 & +fi twin_pid="$!" if [[ -n "${pid_file}" ]]; then @@ -289,7 +353,7 @@ while true; do exit 1 fi - if [[ -z "${detected_tango_port}" ]]; then + if [[ "${mode}" == "tango" && -z "${detected_tango_port}" ]]; then if detected_tango_port="$(detect_tango_port)"; then echo "Detected Tango database port: ${detected_tango_port}" echo "Effective TANGO_HOST: ${tango_host}:${detected_tango_port}" @@ -298,8 +362,8 @@ while true; do fi fi - if grep -q "${READY_PATTERN}" "${log_file}"; then - if [[ -z "${detected_tango_port}" ]]; then + if grep -q "${ready_pattern}" "${log_file}"; then + if [[ "${mode}" == "tango" && -z "${detected_tango_port}" ]]; then if detected_tango_port="$(detect_tango_port)"; then echo "Detected Tango database port: ${detected_tango_port}" echo "Effective TANGO_HOST: ${tango_host}:${detected_tango_port}" diff --git a/tests/integration/test_dt4acc_epics_twin_smoke.py b/tests/integration/test_dt4acc_epics_twin_smoke.py new file mode 100644 index 00000000..0eb27251 --- /dev/null +++ b/tests/integration/test_dt4acc_epics_twin_smoke.py @@ -0,0 +1,106 @@ +import os + +import numpy as np +import pytest + +from pyaml.accelerator import Accelerator +from tests.integration.fodo_fixtures import build_fodo_accelerator + +FODO_1GEV_6D_EPICS_CONFIG_KEY = "pyaml/epics/pyaml-cs-oa/fodo_1gev_6d_pyaml-epics.yaml" + +# PV prefix the EPICS twin was started with (start_dt4acc_twin.sh --prefix). +EPICS_PREFIX = os.environ.get("PYAML_DT4ACC_EPICS_PREFIX", "pyaml-it") + +pytestmark = [ + pytest.mark.integration, + pytest.mark.skipif( + os.environ.get("PYAML_DT4ACC_INTEGRATION") != "1", + reason="dt4acc Apptainer integration test is opt-in", + ), +] + + +def _build_accelerator() -> Accelerator: + # The twin publishes ":QF_001:Cm:rdbk" while the fixture declares + # "QF_001:Cm:rdbk", so the pyaml-cs-oa control system adds ":". + return build_fodo_accelerator( + FODO_1GEV_6D_EPICS_CONFIG_KEY, + control_overrides={"prefix": f"{EPICS_PREFIX}:"}, + ) + + +def test_epics_twin_accelerator_instantiates_and_reads_live_values(): + # Build the accelerator from the FODO EPICS fixture, with its "live" EPICS control system. + accelerator = _build_accelerator() + + assert accelerator.live is not None + assert "live" in accelerator.controls() + + # Read the RF frequency through the RF plant. + rf_frequency = float(accelerator.live.rf.get("RF").frequency.get()) + + assert np.isfinite(rf_frequency), f"RF frequency is not finite: {rf_frequency!r}" + assert rf_frequency > 0.0, f"RF frequency should be positive, got {rf_frequency!r}" + + # Read one focusing quadrupole strength. + qf_strength = float(accelerator.live.magnet.get("QF_001").strength.get()) + + assert np.isfinite(qf_strength), f"QF_001 strength is not finite: {qf_strength!r}" + assert qf_strength > 0.0, f"QF_001 strength should be positive, got {qf_strength!r}" + + +def test_epics_twin_reads_all_declared_magnetic_strengths(): + # Build the accelerator and collect the single-function magnets and the combined function magnets. + # Magnets created by a combined function magnet (COR_001.hcorrector, ...) are read through their parent. + accelerator = _build_accelerator() + magnets = [magnet for magnet in accelerator.live.magnets.get() if magnet.get_model_name() == magnet.get_name()] + combined_function_magnets = accelerator.live.combined_function_magnet.all() + + assert magnets + assert combined_function_magnets + + # Read every strength and collect all failures, so one run reports every unavailable PV. + failures = [] + for magnet in magnets: + try: + value = float(magnet.strength.get()) + except Exception as exc: # noqa: BLE001 - report all unavailable PVs at once. + failures.append(f"{magnet.get_name()}: {type(exc).__name__}: {exc}") + continue + + if not np.isfinite(value): + failures.append(f"{magnet.get_name()}: non-finite value {value!r}") + + for magnet in combined_function_magnets: + try: + values = np.asarray(magnet.strengths.get(), dtype=float) + except Exception as exc: # noqa: BLE001 - report all unavailable PVs at once. + failures.append(f"{magnet.get_name()}: {type(exc).__name__}: {exc}") + continue + + if not np.all(np.isfinite(values)): + failures.append(f"{magnet.get_name()}: non-finite values {values!r}") + + assert not failures, "Magnetic strength readback failures:\n" + "\n".join(failures) + + +def test_epics_twin_reads_bpm_positions(): + # Build the accelerator and collect every declared BPM. + accelerator = _build_accelerator() + bpms = accelerator.live.diagnostic.bpm.all() + + assert bpms + + # Read the (x, y) position of every BPM and collect all failures. + failures = [] + for bpm in bpms: + try: + positions = np.asarray(bpm.positions.get(), dtype=float) + except Exception as exc: # noqa: BLE001 - report all unavailable PVs at once. + failures.append(f"{bpm.get_name()}: {type(exc).__name__}: {exc}") + continue + + if not np.all(np.isfinite(positions)): + failures.append(f"{bpm.get_name()}: non-finite positions {positions!r}") + + assert not failures, "BPM position readback failures:\n" + "\n".join(failures) diff --git a/tests/integration/test_dt4acc_twin_smoke.py b/tests/integration/test_dt4acc_twin_smoke.py index d9edec86..35f9c8f8 100644 --- a/tests/integration/test_dt4acc_twin_smoke.py +++ b/tests/integration/test_dt4acc_twin_smoke.py @@ -3,17 +3,15 @@ import numpy as np import pytest -from pyaml_test_lattice import configurations, lattices from pyaml.accelerator import Accelerator -from pyaml.configuration import ConfigurationManager +from tests.integration.fodo_fixtures import build_fodo_accelerator QF_001 = "QF_001" QF_001_STRENGTH = "AN01-AR/EM-QP/QF.01/magnetic_strength" RF_REFERENCE_FREQUENCY = "simulator/ringsimulator/ringsimulator/reference_frequency" EXAMPLES_ROOT = Path(__file__).parent.parent.parent / "examples" / "use_cases" / "config" -FODO_LATTICE_KEY = "fodo_1gev_6d.json" FODO_1GEV_6D_TANGO_PYAML_CONFIG_KEY = "pyaml/tango/tango-pyaml/fodo_1gev_6d_pyaml.yaml" FODO_1GEV_6D_CS_OA_CONFIG_KEY = "pyaml/tango/pyaml-cs-oa/fodo_1gev_6d_pyaml-oa.yaml" FODO_1GEV_6D_CONFIGS = [ @@ -33,28 +31,8 @@ def _readback_value(device_access): return float(device_access.readback()) -def _load_fragment(config_key: str) -> dict: - """Load one pyaml-test-lattice merged config fragment as a plain dict. - - The ``lattice`` reference is overridden since it lives in a different - package subtree (``data/lattice``) than the config fragment - (``data/configuration``). - """ - config_path = Path(configurations[config_key]) - manager = ConfigurationManager() - manager.add(config_path) - fragment = manager.to_dict() - - fragment["simulators"][0]["lattice"] = str(Path(lattices[FODO_LATTICE_KEY])) - - return fragment - - -def _build_accelerator(config_key: str): - configuration_manager: ConfigurationManager = ConfigurationManager() - configuration_manager.add(_load_fragment(config_key)) - - return Accelerator.from_dict(configuration_manager.to_dict()) +def _build_accelerator(config_key: str) -> Accelerator: + return build_fodo_accelerator(config_key) @pytest.mark.parametrize("config_key", FODO_1GEV_6D_CONFIGS, ids=["tango-pyaml", "pyaml-cs-oa"])