|
| 1 | +import os |
| 2 | +# import tempfile |
| 3 | +from enum import IntEnum |
| 4 | +from typing import Optional, TypedDict |
| 5 | + |
| 6 | +from orbit.core.bunch import Bunch |
| 7 | +from orbit.core import orbit_mpi |
| 8 | + |
| 9 | +import numpy as np |
| 10 | +from numpy.typing import NDArray |
| 11 | + |
| 12 | + |
| 13 | +class SyncPartDict(TypedDict): |
| 14 | + coords: NDArray[np.float64] |
| 15 | + kin_energy: np.float64 |
| 16 | + momentum: np.float64 |
| 17 | + beta: np.float64 |
| 18 | + gamma: np.float64 |
| 19 | + time: np.float64 |
| 20 | + |
| 21 | + |
| 22 | +class BunchDict(TypedDict): |
| 23 | + coords_array: NDArray[np.float64] |
| 24 | + sync_part: SyncPartDict |
| 25 | + attr: dict[str, np.float64 | np.int32] |
| 26 | + |
| 27 | + |
| 28 | +class BunchCoord(IntEnum): |
| 29 | + X = 0 |
| 30 | + XP = 1 |
| 31 | + Y = 2 |
| 32 | + YP = 3 |
| 33 | + Z = 4 |
| 34 | + DE = 5 |
| 35 | + |
| 36 | + |
| 37 | +def collect_bunch( |
| 38 | + bunch: Bunch, |
| 39 | + return_memmap: bool = True, |
| 40 | + output_fname: Optional[str] = None, |
| 41 | +) -> BunchDict | None: |
| 42 | + """Collects attributes from a PyOrbit Bunch across all MPI ranks and returns it as a dictionary. |
| 43 | + Parameters |
| 44 | + ---------- |
| 45 | + bunch : Bunch |
| 46 | + The PyOrbit::Bunch object from which to collect attributes. |
| 47 | + return_memmap : bool, optional |
| 48 | + Return the bunch coordinates as a memory-mapped NumPy array, otherwise the |
| 49 | + entire array is copied into RAM and returned as normal NDArray. Default is True. |
| 50 | + Returns |
| 51 | + ------- |
| 52 | + BunchDict | None |
| 53 | + A dictionary containing the collected bunch attributes. Returns None if not on the root MPI rank or if the global bunch size is 0. |
| 54 | + BunchDict structure: |
| 55 | + { |
| 56 | + "coords": NDArray[np.float64] of shape (N, 6) where N is the total number of macroparticles, |
| 57 | + and the 6 columns correspond to [x, xp, y, yp, z, dE] in units of [m, rad, m, rad, m, eV], respectively. |
| 58 | + "sync_part": { |
| 59 | + "coords": NDArray[np.float64] of shape (3,), |
| 60 | + "kin_energy": np.float64, |
| 61 | + "momentum": np.float64, |
| 62 | + "beta": np.float64, |
| 63 | + "gamma": np.float64, |
| 64 | + "time": np.float64 |
| 65 | + }, |
| 66 | + "attributes": { |
| 67 | + <bunch attribute name>: <attribute value (np.float64 or np.int32)>, |
| 68 | + ... |
| 69 | + } |
| 70 | + } |
| 71 | + """ |
| 72 | + |
| 73 | + global_size = bunch.getSizeGlobal() |
| 74 | + |
| 75 | + if global_size == 0: |
| 76 | + return None |
| 77 | + |
| 78 | + mpi_comm = bunch.getMPIComm() |
| 79 | + mpi_rank = orbit_mpi.MPI_Comm_rank(mpi_comm) |
| 80 | + |
| 81 | + coords_shape = (bunch.getSizeGlobal(), 6) |
| 82 | + |
| 83 | + local_rows = bunch.getSize() |
| 84 | + |
| 85 | + # print(f"[DEBUG] Rank {mpi_rank}: start_row={start_row}, stop_row={stop_row}, local_rows={local_rows} bunch.getSize()={bunch.getSize()}") |
| 86 | + |
| 87 | + # if mpi_rank == 0: |
| 88 | + # file_desc, fname = tempfile.mkstemp(suffix=".dat", prefix="collect_bunch_", dir="/tmp") |
| 89 | + # os.close(file_desc) |
| 90 | + # |
| 91 | + # TODO: this doesn't seem to work. "SystemError: PY_SSIZE_T_CLEAN macro must be defined for '#' formats" |
| 92 | + # fname = orbit_mpi.MPI_Bcast(fname, orbit_mpi.mpi_datatype.MPI_CHAR, 0, mpi_comm) |
| 93 | + |
| 94 | + # Using a fixed filename in the temp directory for now. Maybe that's sufficient. |
| 95 | + fname = f"/tmp/collect_bunch_tmpfile_{mpi_rank}.dat" |
| 96 | + |
| 97 | + local_shape = (local_rows, coords_shape[1]) |
| 98 | + dtype = np.float64 |
| 99 | + coords_memmap = np.memmap(fname, dtype=dtype, mode="w+", shape=local_shape) |
| 100 | + |
| 101 | + for i in range(local_rows): |
| 102 | + coords_memmap[i, BunchCoord.X] = bunch.x(i) |
| 103 | + coords_memmap[i, BunchCoord.XP] = bunch.xp(i) |
| 104 | + coords_memmap[i, BunchCoord.Y] = bunch.y(i) |
| 105 | + coords_memmap[i, BunchCoord.YP] = bunch.yp(i) |
| 106 | + coords_memmap[i, BunchCoord.Z] = bunch.z(i) |
| 107 | + coords_memmap[i, BunchCoord.DE] = bunch.dE(i) |
| 108 | + |
| 109 | + coords_memmap.flush() |
| 110 | + |
| 111 | + bunch_dict = {"coords": None, "sync_part": {}, "attributes": {}} |
| 112 | + |
| 113 | + if mpi_rank == 0: |
| 114 | + sync_part = bunch.getSyncParticle() |
| 115 | + |
| 116 | + bunch_dict["sync_part"] |= { |
| 117 | + "coords": np.array(sync_part.pVector()), |
| 118 | + "kin_energy": np.float64(sync_part.kinEnergy()), |
| 119 | + "momentum": np.float64(sync_part.momentum()), |
| 120 | + "beta": np.float64(sync_part.beta()), |
| 121 | + "gamma": np.float64(sync_part.gamma()), |
| 122 | + "time": np.float64(sync_part.time()), |
| 123 | + } |
| 124 | + |
| 125 | + for attr in bunch.bunchAttrDoubleNames(): |
| 126 | + bunch_dict["attributes"][attr] = np.float64(bunch.bunchAttrDouble(attr)) |
| 127 | + |
| 128 | + for attr in bunch.bunchAttrIntNames(): |
| 129 | + bunch_dict["attributes"][attr] = np.int32(bunch.bunchAttrInt(attr)) |
| 130 | + |
| 131 | + orbit_mpi.MPI_Barrier(mpi_comm) |
| 132 | + |
| 133 | + if mpi_rank == 0: |
| 134 | + coords_memmap = np.memmap(fname, dtype=dtype, mode="r+", shape=coords_shape) |
| 135 | + |
| 136 | + start_row = local_rows |
| 137 | + |
| 138 | + for r in range(1, orbit_mpi.MPI_Comm_size(mpi_comm)): |
| 139 | + src_fname = f"/tmp/collect_bunch_tmpfile_{r}.dat" |
| 140 | + |
| 141 | + if not os.path.exists(src_fname): |
| 142 | + raise FileNotFoundError(f"Expected temporary file '{src_fname}' not found. Something went wrong.") |
| 143 | + |
| 144 | + src_memmap = np.memmap(src_fname, dtype=dtype, mode="r") |
| 145 | + src_memmap = src_memmap.reshape((-1, coords_shape[1])) |
| 146 | + |
| 147 | + stop_row = start_row + src_memmap.shape[0] |
| 148 | + |
| 149 | + coords_memmap[start_row:stop_row, :] = src_memmap[:, :] |
| 150 | + coords_memmap.flush() |
| 151 | + |
| 152 | + del src_memmap |
| 153 | + os.remove(src_fname) |
| 154 | + start_row = stop_row |
| 155 | + |
| 156 | + bunch_dict["coords"] = ( |
| 157 | + coords_memmap if return_memmap else np.array(coords_memmap) |
| 158 | + ) |
| 159 | + |
| 160 | + return bunch_dict |
0 commit comments