Skip to content

Map Domain

Internally, map domain objects (hit maps, signal maps, pixel noise covariances, etc) are stored in a distributed fashion. This enables each process to only store a subset of the sky pixels, which saves memory for large maps at high resolution.

toast.pixels.PixelDistribution

Bases: AcceleratorObject

Class representing the distribution of submaps.

This object is used to describe the properties of a pixelization scheme and which "submaps" are strored on each process. The size of the submap can be tuned to balance storage (smaller submap size means fewer wasted pixels stored) and ease of indexing (larger submap size means faster global-to-local pixel lookups).

Parameters:

Name Type Description Default
n_pix int

the total number of pixels.

None
n_submap int

the number of submaps to use.

1000
local_submaps array

the list of local submaps (integers).

None
comm Comm

The MPI communicator or None.

None
Source code in toast/pixels.py
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
class PixelDistribution(AcceleratorObject):
    """Class representing the distribution of submaps.

    This object is used to describe the properties of a pixelization scheme and which
    "submaps" are strored on each process.  The size of the submap can be tuned to
    balance storage (smaller submap size means fewer wasted pixels stored) and ease of
    indexing (larger submap size means faster global-to-local pixel lookups).

    Args:
        n_pix (int): the total number of pixels.
        n_submap (int): the number of submaps to use.
        local_submaps (array): the list of local submaps (integers).
        comm (mpi4py.MPI.Comm): The MPI communicator or None.

    """

    def __init__(self, n_pix=None, n_submap=1000, local_submaps=None, comm=None):
        super().__init__()
        self._n_pix = n_pix
        self._n_submap = n_submap
        if self._n_submap > self._n_pix:
            msg = "Cannot create a PixelDistribution with more submaps ({}) than pixels ({})".format(
                n_submap, n_pix
            )
            raise RuntimeError(msg)
        self._n_pix_submap = self._n_pix // self._n_submap
        if self._n_pix % self._n_submap != 0:
            self._n_pix_submap += 1

        self._local_submaps = local_submaps
        self._comm = comm

        self._n_local = 0
        self._glob2loc = AlignedI64.zeros(self._n_submap)
        self._glob2loc[:] = -1

        if self._local_submaps is not None and len(self._local_submaps) > 0:
            if np.max(self._local_submaps) > self._n_submap - 1:
                raise RuntimeError("local submap indices out of range")
            self._n_local = len(self._local_submaps)
            for ilocal_submap, iglobal_submap in enumerate(self._local_submaps):
                self._glob2loc[iglobal_submap] = ilocal_submap

        self._submap_owners = None
        self._owned_submaps = None
        self._alltoallv_info = None
        self._all_hit_submaps = None

    def __eq__(self, other):
        local_eq = True
        if self._n_pix != other._n_pix:
            local_eq = False
        if self._n_submap != other._n_submap:
            local_eq = False
        if self._n_pix_submap != other._n_pix_submap:
            local_eq = False
        if not np.array_equal(self._local_submaps, other._local_submaps):
            local_eq = False
        if self._comm is None and other._comm is not None:
            local_eq = False
        if self._comm is not None and other._comm is None:
            local_eq = False
        if self._comm is not None:
            comp = MPI.Comm.Compare(self._comm, other._comm)
            if comp not in (MPI.IDENT, MPI.CONGRUENT):
                local_eq = False
        return local_eq

    def __ne__(self, other):
        return not self.__eq__(other)

    def clear(self):
        """Delete the underlying memory.

        This will forcibly delete the C-allocated memory and invalidate all python
        references to this object.  DO NOT CALL THIS unless you are sure all references
        are no longer being used and you are about to delete the object.

        """
        if hasattr(self, "_glob2loc"):
            if self._glob2loc is not None:
                self._glob2loc.clear()
                del self._glob2loc

    def __del__(self):
        self.clear()

    @property
    def comm(self):
        """(mpi4py.MPI.Comm): The MPI communicator used (or None)"""
        return self._comm

    @property
    def n_pix(self):
        """(int): The global number of pixels."""
        return self._n_pix

    @property
    def n_pix_submap(self):
        """(int): The number of pixels in each submap."""
        return self._n_pix_submap

    @property
    def n_submap(self):
        """(int): The total number of submaps."""
        return self._n_submap

    @property
    def n_local_submap(self):
        """(int): The number of submaps stored on this process."""
        return self._n_local

    @property
    def local_submaps(self):
        """(array): The list of local submaps or None if process has no data."""
        return self._local_submaps

    @property
    def all_hit_submaps(self):
        """(array): The list of submaps local to atleast one process."""
        if self._all_hit_submaps is None:
            hits = np.zeros(self._n_submap)
            hits[self._local_submaps] += 1
            if self._comm is not None:
                self._comm.Allreduce(MPI.IN_PLACE, hits)
            self._all_hit_submaps = np.argwhere(hits != 0).ravel()
        return self._all_hit_submaps

    @property
    def global_submap_to_local(self):
        """(array): The mapping from global submap to local."""
        return self._glob2loc

    @function_timer
    def global_pixel_to_submap(self, gl):
        """Convert global pixel indices into the local submap and pixel.

        Args:
            gl (array): The global pixel numbers.

        Returns:
            (tuple):  A tuple of arrays containing the local submap index (int) and the
                pixel index local to that submap (int).

        """
        if len(gl) == 0:
            return (np.zeros_like(gl), np.zeros_like(gl))
        log = Logger.get()
        if np.max(gl) >= self._n_pix:
            msg = "Global pixel indices exceed the maximum for the pixelization"
            log.error(msg)
            raise RuntimeError(msg)
        return libtoast_global_to_local(gl, self._n_pix_submap, self._glob2loc)

    @function_timer
    def global_pixel_to_local(self, gl):
        """Convert global pixel indices into local pixel indices.

        Args:
            gl (array): The global pixel numbers.

        Returns:
            (array): The local raw (flat packed) buffer index for each pixel.

        """
        if len(gl) == 0:
            return np.zeros_like(gl)
        if np.max(gl) >= self._n_pix:
            log = Logger.get()
            msg = "Global pixel indices exceed the maximum for the pixelization"
            log.error(msg)
            raise RuntimeError(msg)
        local_sm, pixels = libtoast_global_to_local(
            gl, self._n_pix_submap, self._glob2loc
        )
        local_sm *= self._n_pix_submap
        pixels += local_sm
        return pixels

    def __repr__(self):
        val = "<PixelDistribution {} pixels, {} submaps, submap size = {}>".format(
            self._n_pix, self._n_submap, self._n_pix_submap
        )
        return val

    @property
    def submap_owners(self):
        """The owning process for every hit submap.

        This information is used in several other operations, including serializing
        PixelData objects to a single process and also communication needed for
        reducing data globally.
        """
        if self._submap_owners is not None:
            # Already computed
            return self._submap_owners

        self._submap_owners = np.empty(self._n_submap, dtype=np.int32)
        self._submap_owners[:] = -1

        if self._comm is None:
            # Trivial case
            if self._local_submaps is not None and len(self._local_submaps) > 0:
                self._submap_owners[self._local_submaps] = 0
        else:
            # Need to compute it.
            local_hit_submaps = np.zeros(self._n_submap, dtype=np.uint8)
            local_hit_submaps[self._local_submaps] = 1

            hit_submaps = None
            if self._comm.rank == 0:
                hit_submaps = np.zeros(self._n_submap, dtype=np.uint8)

            self._comm.Reduce(local_hit_submaps, hit_submaps, op=MPI.LOR, root=0)
            del local_hit_submaps

            if self._comm.rank == 0:
                total_hit_submaps = np.sum(hit_submaps.astype(np.int32))
                tdist = distribute_uniform(total_hit_submaps, self._comm.size)

                # The target number of submaps per process
                target = [x[1] for x in tdist]

                # Assign the submaps in rank order.  This ensures better load
                # distribution when serializing some operations and also reduces needed
                # memory copies when using Alltoallv.
                proc_offset = 0
                proc = 0
                for sm in range(self._n_submap):
                    if hit_submaps[sm] > 0:
                        self._submap_owners[sm] = proc
                        proc_offset += 1
                        if proc_offset >= target[proc]:
                            proc += 1
                            proc_offset = 0
                del hit_submaps

            self._comm.Bcast(self._submap_owners, root=0)
        return self._submap_owners

    @property
    def owned_submaps(self):
        """The submaps owned by this process."""
        if self._owned_submaps is not None:
            # Already computed
            return self._owned_submaps
        owners = self.submap_owners
        if self._comm is None:
            self._owned_submaps = np.array(
                [x for x, y in enumerate(owners) if y == 0], dtype=np.int32
            )
        else:
            self._owned_submaps = np.array(
                [x for x, y in enumerate(owners) if y == self._comm.rank],
                dtype=np.int32,
            )
        return self._owned_submaps

    @property
    def alltoallv_info(self):
        """Return the offset information for Alltoallv communication.

        This returns a tuple containing:
            - The send displacements for the Alltoallv submap gather
            - The send counts for the Alltoallv submap gather
            - The receive displacements for the Alltoallv submap gather
            - The receive counts for the Alltoallv submap gather
            - The locations in the receive buffer of each submap.

        """
        log = Logger.get()
        if self._alltoallv_info is not None:
            # Already computed
            return self._alltoallv_info

        owners = self.submap_owners
        our_submaps = self.owned_submaps

        send_counts = None
        send_displ = None
        recv_counts = None
        recv_displ = None
        recv_locations = None

        if self._comm is None:
            recv_counts = len(self._local_submaps) * np.ones(1, dtype=np.int32)
            recv_displ = np.zeros(1, dtype=np.int32)
            recv_locations = dict()
            for offset, sm in enumerate(self._local_submaps):
                recv_locations[sm] = np.array([offset], dtype=np.int32)
            send_counts = len(self._local_submaps) * np.ones(1, dtype=np.int32)
            send_displ = np.zeros(1, dtype=np.int32)
        else:
            # Compute the other "contributing" processes that have submaps which we own.
            # Also track the receive buffer offsets for each owned submap.
            send = [list() for x in range(self._comm.size)]
            for sm in self._local_submaps:
                # Tell the owner of this submap that we are a contributor
                send[owners[sm]].append(sm)
            recv = self._comm.alltoall(send)

            recv_counts = np.zeros(self._comm.size, dtype=np.int32)
            recv_displ = np.zeros(self._comm.size, dtype=np.int32)
            recv_locations = dict()

            offset = 0
            for proc, sms in enumerate(recv):
                recv_displ[proc] = offset
                for sm in sms:
                    if sm not in recv_locations:
                        recv_locations[sm] = list()
                    recv_locations[sm].append(offset)
                    recv_counts[proc] += 1
                    offset += 1

            for sm in list(recv_locations.keys()):
                recv_locations[sm] = np.array(recv_locations[sm], dtype=np.int32)

            # Compute the Alltoallv send offsets in terms of submaps
            send_counts = np.zeros(self._comm.size, dtype=np.int32)
            send_displ = np.zeros(self._comm.size, dtype=np.int32)
            offset = 0
            last_offset = 0
            last_own = -1
            for sm in self._local_submaps:
                if last_own != owners[sm]:
                    # Moving on to next owning process...
                    if last_own >= 0:
                        send_displ[last_own] = last_offset
                        last_offset = offset
                send_counts[owners[sm]] += 1
                offset += 1
                last_own = owners[sm]
            if last_own >= 0:
                # Finish up last process
                send_displ[last_own] = last_offset

        self._alltoallv_info = (
            send_counts,
            send_displ,
            recv_counts,
            recv_displ,
            recv_locations,
        )

        msg_rank = 0
        if self._comm is not None:
            msg_rank = self._comm.rank
        msg = f"alltoallv_info[{msg_rank}]:\n"
        msg += f"  send_counts={send_counts} "
        msg += f"send_displ={send_displ}\n"
        msg += f"  recv_counts={recv_counts} "
        msg += f"recv_displ={recv_displ} "
        msg += f"recv_locations={recv_locations}"
        log.verbose(msg)

        return self._alltoallv_info

    def _accel_exists(self):
        return accel_data_present(self._glob2loc, self._accel_name)

    def _accel_create(self):
        self._glob2loc = accel_data_create(self._glob2loc, self._accel_name)

    def _accel_update_device(self):
        self._glob2loc = accel_data_update_device(self._glob2loc, self._accel_name)

    def _accel_update_host(self):
        self._glob2loc = accel_data_update_host(self._glob2loc, self._accel_name)

    def _accel_reset(self):
        accel_data_reset(self._glob2loc, self._accel_name)

    def _accel_delete(self):
        self._glob2loc = accel_data_delete(self._glob2loc, self._accel_name)

_all_hit_submaps = None instance-attribute

_alltoallv_info = None instance-attribute

_comm = comm instance-attribute

_glob2loc = AlignedI64.zeros(self._n_submap) instance-attribute

_local_submaps = local_submaps instance-attribute

_n_local = 0 instance-attribute

_n_pix = n_pix instance-attribute

_n_pix_submap = self._n_pix // self._n_submap instance-attribute

_n_submap = n_submap instance-attribute

_owned_submaps = None instance-attribute

_submap_owners = None instance-attribute

all_hit_submaps property

(array): The list of submaps local to atleast one process.

alltoallv_info property

Return the offset information for Alltoallv communication.

This returns a tuple containing
  • The send displacements for the Alltoallv submap gather
  • The send counts for the Alltoallv submap gather
  • The receive displacements for the Alltoallv submap gather
  • The receive counts for the Alltoallv submap gather
  • The locations in the receive buffer of each submap.

comm property

(mpi4py.MPI.Comm): The MPI communicator used (or None)

global_submap_to_local property

(array): The mapping from global submap to local.

local_submaps property

(array): The list of local submaps or None if process has no data.

n_local_submap property

(int): The number of submaps stored on this process.

n_pix property

(int): The global number of pixels.

n_pix_submap property

(int): The number of pixels in each submap.

n_submap property

(int): The total number of submaps.

owned_submaps property

The submaps owned by this process.

submap_owners property

The owning process for every hit submap.

This information is used in several other operations, including serializing PixelData objects to a single process and also communication needed for reducing data globally.

__del__()

Source code in toast/pixels.py
126
127
def __del__(self):
    self.clear()

__eq__(other)

Source code in toast/pixels.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def __eq__(self, other):
    local_eq = True
    if self._n_pix != other._n_pix:
        local_eq = False
    if self._n_submap != other._n_submap:
        local_eq = False
    if self._n_pix_submap != other._n_pix_submap:
        local_eq = False
    if not np.array_equal(self._local_submaps, other._local_submaps):
        local_eq = False
    if self._comm is None and other._comm is not None:
        local_eq = False
    if self._comm is not None and other._comm is None:
        local_eq = False
    if self._comm is not None:
        comp = MPI.Comm.Compare(self._comm, other._comm)
        if comp not in (MPI.IDENT, MPI.CONGRUENT):
            local_eq = False
    return local_eq

__init__(n_pix=None, n_submap=1000, local_submaps=None, comm=None)

Source code in toast/pixels.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def __init__(self, n_pix=None, n_submap=1000, local_submaps=None, comm=None):
    super().__init__()
    self._n_pix = n_pix
    self._n_submap = n_submap
    if self._n_submap > self._n_pix:
        msg = "Cannot create a PixelDistribution with more submaps ({}) than pixels ({})".format(
            n_submap, n_pix
        )
        raise RuntimeError(msg)
    self._n_pix_submap = self._n_pix // self._n_submap
    if self._n_pix % self._n_submap != 0:
        self._n_pix_submap += 1

    self._local_submaps = local_submaps
    self._comm = comm

    self._n_local = 0
    self._glob2loc = AlignedI64.zeros(self._n_submap)
    self._glob2loc[:] = -1

    if self._local_submaps is not None and len(self._local_submaps) > 0:
        if np.max(self._local_submaps) > self._n_submap - 1:
            raise RuntimeError("local submap indices out of range")
        self._n_local = len(self._local_submaps)
        for ilocal_submap, iglobal_submap in enumerate(self._local_submaps):
            self._glob2loc[iglobal_submap] = ilocal_submap

    self._submap_owners = None
    self._owned_submaps = None
    self._alltoallv_info = None
    self._all_hit_submaps = None

__ne__(other)

Source code in toast/pixels.py
110
111
def __ne__(self, other):
    return not self.__eq__(other)

__repr__()

Source code in toast/pixels.py
221
222
223
224
225
def __repr__(self):
    val = "<PixelDistribution {} pixels, {} submaps, submap size = {}>".format(
        self._n_pix, self._n_submap, self._n_pix_submap
    )
    return val

_accel_create()

Source code in toast/pixels.py
403
404
def _accel_create(self):
    self._glob2loc = accel_data_create(self._glob2loc, self._accel_name)

_accel_delete()

Source code in toast/pixels.py
415
416
def _accel_delete(self):
    self._glob2loc = accel_data_delete(self._glob2loc, self._accel_name)

_accel_exists()

Source code in toast/pixels.py
400
401
def _accel_exists(self):
    return accel_data_present(self._glob2loc, self._accel_name)

_accel_reset()

Source code in toast/pixels.py
412
413
def _accel_reset(self):
    accel_data_reset(self._glob2loc, self._accel_name)

_accel_update_device()

Source code in toast/pixels.py
406
407
def _accel_update_device(self):
    self._glob2loc = accel_data_update_device(self._glob2loc, self._accel_name)

_accel_update_host()

Source code in toast/pixels.py
409
410
def _accel_update_host(self):
    self._glob2loc = accel_data_update_host(self._glob2loc, self._accel_name)

clear()

Delete the underlying memory.

This will forcibly delete the C-allocated memory and invalidate all python references to this object. DO NOT CALL THIS unless you are sure all references are no longer being used and you are about to delete the object.

Source code in toast/pixels.py
113
114
115
116
117
118
119
120
121
122
123
124
def clear(self):
    """Delete the underlying memory.

    This will forcibly delete the C-allocated memory and invalidate all python
    references to this object.  DO NOT CALL THIS unless you are sure all references
    are no longer being used and you are about to delete the object.

    """
    if hasattr(self, "_glob2loc"):
        if self._glob2loc is not None:
            self._glob2loc.clear()
            del self._glob2loc

global_pixel_to_local(gl)

Convert global pixel indices into local pixel indices.

Parameters:

Name Type Description Default
gl array

The global pixel numbers.

required

Returns:

Type Description
array

The local raw (flat packed) buffer index for each pixel.

Source code in toast/pixels.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
@function_timer
def global_pixel_to_local(self, gl):
    """Convert global pixel indices into local pixel indices.

    Args:
        gl (array): The global pixel numbers.

    Returns:
        (array): The local raw (flat packed) buffer index for each pixel.

    """
    if len(gl) == 0:
        return np.zeros_like(gl)
    if np.max(gl) >= self._n_pix:
        log = Logger.get()
        msg = "Global pixel indices exceed the maximum for the pixelization"
        log.error(msg)
        raise RuntimeError(msg)
    local_sm, pixels = libtoast_global_to_local(
        gl, self._n_pix_submap, self._glob2loc
    )
    local_sm *= self._n_pix_submap
    pixels += local_sm
    return pixels

global_pixel_to_submap(gl)

Convert global pixel indices into the local submap and pixel.

Parameters:

Name Type Description Default
gl array

The global pixel numbers.

required

Returns:

Type Description
tuple

A tuple of arrays containing the local submap index (int) and the pixel index local to that submap (int).

Source code in toast/pixels.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
@function_timer
def global_pixel_to_submap(self, gl):
    """Convert global pixel indices into the local submap and pixel.

    Args:
        gl (array): The global pixel numbers.

    Returns:
        (tuple):  A tuple of arrays containing the local submap index (int) and the
            pixel index local to that submap (int).

    """
    if len(gl) == 0:
        return (np.zeros_like(gl), np.zeros_like(gl))
    log = Logger.get()
    if np.max(gl) >= self._n_pix:
        msg = "Global pixel indices exceed the maximum for the pixelization"
        log.error(msg)
        raise RuntimeError(msg)
    return libtoast_global_to_local(gl, self._n_pix_submap, self._glob2loc)

toast.pixels.PixelData

Bases: AcceleratorObject

Distributed map-domain data.

The distribution information is stored in a PixelDistribution instance passed to the constructor. Each process has local data stored in one or more "submaps".

Although multiple processes may have the same submap of data stored locally, only one process is considered the "owner". This ownership is used when serializing the data and when doing reductions in certain cases. Ownership can be set to either the lowest rank process which has the submap or to a balanced distribution.

Parameters:

Name Type Description Default
dist PixelDistribution

The distribution of submaps.

required
dtype dtype

A numpy-compatible dtype for each element of the data. The only supported types are 1, 2, 4, and 8 byte signed and unsigned integers, 4 and 8 byte floating point numbers, and 4 and 8 byte complex numbers.

required
n_value int

The number of values per pixel.

1
units Unit

The units of the map data.

dimensionless_unscaled
Source code in toast/pixels.py
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
class PixelData(AcceleratorObject):
    """Distributed map-domain data.

    The distribution information is stored in a PixelDistribution instance passed to
    the constructor.  Each process has local data stored in one or more "submaps".

    Although multiple processes may have the same submap of data stored locally, only
    one process is considered the "owner".  This ownership is used when serializing the
    data and when doing reductions in certain cases.  Ownership can be set to either
    the lowest rank process which has the submap or to a balanced distribution.

    Args:
        dist (PixelDistribution):  The distribution of submaps.
        dtype (numpy.dtype):  A numpy-compatible dtype for each element of the data.
            The only supported types are 1, 2, 4, and 8 byte signed and unsigned
            integers, 4 and 8 byte floating point numbers, and 4 and 8 byte complex
            numbers.
        n_value (int):  The number of values per pixel.
        units (Unit):  The units of the map data.

    """

    def __init__(self, dist, dtype, n_value=1, units=u.dimensionless_unscaled):
        super().__init__()
        log = Logger.get()

        self._dist = dist
        self._n_value = n_value
        self._units = units

        # construct a new dtype in case the parameter given is shortcut string
        ttype = np.dtype(dtype)

        self.storage_class = None
        if ttype.char == "b":
            self.storage_class = AlignedI8
        elif ttype.char == "B":
            self.storage_class = AlignedU8
        elif ttype.char == "h":
            self.storage_class = AlignedI16
        elif ttype.char == "H":
            self.storage_class = AlignedU16
        elif ttype.char == "i":
            self.storage_class = AlignedI32
        elif ttype.char == "I":
            self.storage_class = AlignedU32
        elif (ttype.char == "q") or (ttype.char == "l"):
            self.storage_class = AlignedI64
        elif (ttype.char == "Q") or (ttype.char == "L"):
            self.storage_class = AlignedU64
        elif ttype.char == "f":
            self.storage_class = AlignedF32
        elif ttype.char == "d":
            self.storage_class = AlignedF64
        elif ttype.char == "F":
            raise NotImplementedError("No support yet for complex numbers")
        elif ttype.char == "D":
            raise NotImplementedError("No support yet for complex numbers")
        else:
            msg = "Unsupported data typecode '{}'".format(ttype.char)
            log.error(msg)
            raise ValueError(msg)
        self._dtype = ttype

        self.mpitype = None
        self.mpibytesize = None
        if self._dist.comm is not None:
            self.mpibytesize, self.mpitype = mpi_data_type(self._dist.comm, self._dtype)

        self._shape = (
            self._dist.n_local_submap,
            self._dist.n_pix_submap,
            self._n_value,
        )
        self._flatshape = (
            self._dist.n_local_submap * self._dist.n_pix_submap * self._n_value
        )
        self._n_submap_value = self._dist.n_pix_submap * self._n_value

        self.raw = self.storage_class.zeros(self._flatshape)
        self.data = self.raw.array().reshape(self._shape)

        # Allreduce quantities
        self._all_comm_submap = None
        self._all_send = None
        self._all_send_raw = None
        self._all_recv = None
        self._all_recv_raw = None

        # Alltoallv quantities
        self._send_counts = None
        self._send_displ = None
        self._recv_counts = None
        self._recv_displ = None
        self._recv_locations = None
        self.receive = None
        self._receive_raw = None
        self.reduce_buf = None
        self._reduce_buf_raw = None

    def clear(self):
        """Delete the underlying memory.

        This will forcibly delete the C-allocated memory and invalidate all python
        references to this object.  DO NOT CALL THIS unless you are sure all references
        are no longer being used and you are about to delete the object.

        """
        if hasattr(self, "data"):
            # we keep the attribute to avoid errors in _accel_exists
            self.data = None
        if hasattr(self, "raw"):
            if self.accel_exists():
                self.accel_delete()
            if self.raw is not None:
                self.raw.clear()
            del self.raw
        if hasattr(self, "receive"):
            del self.receive
            if self._receive_raw is not None:
                self._receive_raw.clear()
            del self._receive_raw
        if hasattr(self, "reduce_buf"):
            del self.reduce_buf
            if self._reduce_buf_raw is not None:
                self._reduce_buf_raw.clear()
            del self._reduce_buf_raw
        if hasattr(self, "_all_send"):
            del self._all_send
            if self._all_send_raw is not None:
                self._all_send_raw.clear()
            del self._all_send_raw
        if hasattr(self, "_all_recv"):
            del self._all_recv
            if self._all_recv_raw is not None:
                self._all_recv_raw.clear()
            del self._all_recv_raw

    def __del__(self):
        self.clear()

    def reset(self):
        """Set memory to zero"""
        self.raw[:] = 0
        if self.accel_exists():
            self.accel_reset()

    @property
    def distribution(self):
        """(PixelDistribution): The distribution information."""
        return self._dist

    @property
    def dtype(self):
        """(numpy.dtype): The data type of the values."""
        return self._dtype

    @property
    def n_value(self):
        """(int): The number of non-zero values per pixel."""
        return self._n_value

    @property
    def units(self):
        """(Unit):  The map data units."""
        return self._units

    def update_units(self, new_units):
        """Update the units associated with the data."""
        self._units = new_units

    def __getitem__(self, key):
        return np.array(self.data[key], dtype=self._dtype, copy=False)

    def __delitem__(self, key):
        raise NotImplementedError("Cannot delete individual memory elements")
        return

    def __setitem__(self, key, value):
        self.data[key] = value

    def __iter__(self):
        return iter(self.data)

    def __len__(self):
        return len(self.data)

    def __repr__(self):
        val = (
            "<PixelData {} values per pixel, dtype = {}, units= {}, dist = {}>".format(
                self._n_value, self._dtype, self._units, self._dist
            )
        )
        return val

    def __eq__(self, other):
        if self.distribution != other.distribution:
            return False
        if self.dtype.char != other.dtype.char:
            return False
        if self.n_value != other.n_value:
            return False
        if not np.allclose(self.data, other.data):
            return False
        return True

    def __ne__(self, other):
        return not self.__eq__(other)

    def duplicate(self):
        """Create a copy of the data with the same distribution.

        Returns:
            (PixelData):  A duplicate of the instance with copied data but the same
                distribution.

        """
        dup = PixelData(
            self.distribution, self.dtype, n_value=self.n_value, units=self._units
        )
        dup.data[:] = self.data
        return dup

    def comm_nsubmap(self, bytes):
        """Given a buffer size, compute the number of submaps to communicate.

        Args:
            bytes (int):  The number of bytes.

        Returns:
            (int):  The number of submaps in each buffer.

        """
        dbytes = self._dtype.itemsize
        nsub = int(bytes / (dbytes * self._n_submap_value))
        if nsub == 0:
            nsub = 1
        allsub = int(self._dist.n_pix / self._dist.n_pix_submap)
        if nsub > allsub:
            nsub = allsub
        return nsub

    @function_timer
    def setup_allreduce(self, n_submap):
        """Check that allreduce buffers exist and create them if needed."""
        # Allocate persistent send / recv buffers that only change if number of submaps
        # change.
        if self._all_comm_submap is not None:
            # We have already done a reduce...
            if n_submap == self._all_comm_submap:
                # Already allocated with correct size
                return
            else:
                # Delete the old buffers.
                del self._all_send
                self._all_send_raw.clear()
                del self._all_send_raw
                del self._all_recv
                self._all_recv_raw.clear()
                del self._all_recv_raw
        # Allocate with the new size
        self._all_comm_submap = n_submap
        self._all_recv_raw = self.storage_class.zeros(n_submap * self._n_submap_value)
        self._all_recv = self._all_recv_raw.array()
        self._all_send_raw = self.storage_class.zeros(n_submap * self._n_submap_value)
        self._all_send = self._all_send_raw.array()

    @function_timer
    def sync_allreduce(self, comm_bytes=10000000):
        """Perform a buffered allreduce of the data.

        Args:
            comm_bytes (int): The approximate message size to use.

        Returns:
            None.

        """
        if self.accel_in_use():
            msg = f"PixelData {self._accel_name} currently on accelerator"
            msg += " cannot do MPI communication"
            raise RuntimeError(msg)

        if self._dist.comm is None:
            return

        comm_submap = self.comm_nsubmap(comm_bytes)
        self.setup_allreduce(comm_submap)

        dist = self._dist
        nsub = dist.n_submap

        sendview = self._all_send.reshape(
            (comm_submap, dist.n_pix_submap, self._n_value)
        )

        recvview = self._all_recv.reshape(
            (comm_submap, dist.n_pix_submap, self._n_value)
        )

        owners = dist.submap_owners

        submap_off = 0
        ncomm = comm_submap

        gt = GlobalTimers.get()

        while submap_off < nsub:
            if submap_off + ncomm > nsub:
                ncomm = nsub - submap_off
            if np.sum(owners[submap_off : submap_off + ncomm]) != -ncomm:
                # At least one submap has some hits.  Do the allreduce.
                # Otherwise we would skip this buffer to avoid reducing a
                # bunch of zeros.
                for c in range(ncomm):
                    glob = submap_off + c
                    if glob in dist.local_submaps:
                        # copy our data in.
                        loc = dist.global_submap_to_local[glob]
                        sendview[c, :, :] = self.data[loc, :, :]

                gt.start("PixelData.sync_allreduce MPI Allreduce")
                dist.comm.Allreduce(self._all_send, self._all_recv, op=MPI.SUM)
                gt.stop("PixelData.sync_allreduce MPI Allreduce")

                for c in range(ncomm):
                    glob = submap_off + c
                    if glob in dist.local_submaps:
                        # copy the reduced data
                        loc = dist.global_submap_to_local[glob]
                        self.data[loc, :, :] = recvview[c, :, :]

                self._all_send.fill(0)
                self._all_recv.fill(0)

            submap_off += ncomm

        return

    @staticmethod
    def local_reduction(n_submap_value, receive_locations, receive, reduce_buf):
        # Locally reduce owned submaps
        for sm, locs in receive_locations.items():
            reduce_buf[:] = 0
            for lc in locs:
                reduce_buf += receive[lc : lc + n_submap_value]
            for lc in locs:
                receive[lc : lc + n_submap_value] = reduce_buf

    @function_timer
    def setup_alltoallv(self):
        """Check that alltoallv buffers exist and create them if needed."""
        if self._send_counts is None:
            if self.accel_in_use():
                msg = f"PixelData {self._accel_name} currently on accelerator"
                msg += " cannot do MPI communication"
                raise RuntimeError(msg)
            log = Logger.get()
            # Get the parameters in terms of submaps.
            (
                send_counts,
                send_displ,
                recv_counts,
                recv_displ,
                recv_locations,
            ) = self._dist.alltoallv_info

            # Pixel values per submap
            scale = self._n_submap_value

            # Scale these quantites by the submap size and the number of values per
            # pixel.

            self._send_counts = scale * np.array(send_counts, dtype=np.int32)
            self._send_displ = scale * np.array(send_displ, dtype=np.int32)
            self._recv_counts = scale * np.array(recv_counts, dtype=np.int32)
            self._recv_displ = scale * np.array(recv_displ, dtype=np.int32)
            self._recv_locations = dict()
            for sm, locs in recv_locations.items():
                self._recv_locations[sm] = scale * np.array(locs, dtype=np.int32)

            msg_rank = 0
            if self._dist.comm is not None:
                msg_rank = self._dist.comm.rank
            msg = f"setup_alltoallv[{msg_rank}]:\n"
            msg += f"  send_counts={self._send_counts} "
            msg += f"send_displ={self._send_displ}\n"
            msg += f"  recv_counts={self._recv_counts} "
            msg += f"recv_displ={self._recv_displ} "
            msg += f"recv_locations={self._recv_locations}"
            log.verbose(msg)

            # Allocate a persistent single-submap buffer
            self._reduce_buf_raw = self.storage_class.zeros(self._n_submap_value)
            self.reduce_buf = self._reduce_buf_raw.array()

            buf_check_fail = False
            try:
                if self._dist.comm is None:
                    # For this case, point the receive member to the original data.
                    # This will allow codes processing locally owned submaps to work
                    # transparently in the serial case.
                    self.receive = self.data.reshape((-1,))
                else:
                    # Check that our send and receive buffers do not exceed 32bit
                    # indices required by MPI
                    max_int = 2147483647
                    recv_buf_size = self._recv_displ[-1] + self._recv_counts[-1]
                    if recv_buf_size > max_int:
                        msg = "Proc {} Alltoallv receive buffer size exceeds max 32bit integer".format(
                            self._dist.comm.rank
                        )
                        log.error(msg)
                        buf_check_fail = True
                    if len(self.raw) > max_int:
                        msg = "Proc {} Alltoallv send buffer size exceeds max 32bit integer".format(
                            self._dist.comm.rank
                        )
                        log.error(msg)
                        buf_check_fail = True

                    # Allocate a persistent receive buffer
                    msg = f"{msg_rank}:  allocate receive buffer of "
                    msg += f"{recv_buf_size} elements"
                    log.verbose(msg)
                    self._receive_raw = self.storage_class.zeros(recv_buf_size)
                    self.receive = self._receive_raw.array()
            except:
                buf_check_fail = True
            if self._dist.comm is not None:
                buf_check_fail = self._dist.comm.allreduce(buf_check_fail, op=MPI.LOR)
            if buf_check_fail:
                msg = "alltoallv buffer setup failed on one or more processes"
                raise RuntimeError(msg)

    @function_timer
    def forward_alltoallv(self):
        """Communicate submaps into buffers on the owning process.

        On the first call, some initialization is done to compute send and receive
        displacements and counts.  A persistent receive buffer is allocated.  Submap
        data is sent to their owners simultaneously using alltoallv.

        Returns:
            None.

        """
        if self.accel_in_use():
            msg = f"PixelData {self._accel_name} currently on accelerator"
            msg += " cannot do MPI communication"
            raise RuntimeError(msg)

        log = Logger.get()
        gt = GlobalTimers.get()
        self.setup_alltoallv()

        if self._dist.comm is None:
            # No communication needed
            return

        # Gather owned submaps locally
        gt.start("PixelData.forward_alltoallv MPI Alltoallv")
        self._dist.comm.Alltoallv(
            [self.raw, self._send_counts, self._send_displ, self.mpitype],
            [self.receive, self._recv_counts, self._recv_displ, self.mpitype],
        )
        gt.stop("PixelData.forward_alltoallv MPI Alltoallv")
        return

    @function_timer
    def reverse_alltoallv(self):
        """Communicate submaps from the owning process back to all processes.

        Returns:
            None.

        """
        if self.accel_in_use():
            msg = f"PixelData {self._accel_name} currently on accelerator"
            msg += " cannot do MPI communication"
            raise RuntimeError(msg)

        gt = GlobalTimers.get()
        if self._dist.comm is None:
            # No communication needed
            return
        if self._send_counts is None:
            raise RuntimeError(
                "Cannot do reverse alltoallv before buffers have been setup"
            )

        # Scatter result back
        gt.start("PixelData.reverse_alltoallv MPI Alltoallv")
        self._dist.comm.Alltoallv(
            [self.receive, self._recv_counts, self._recv_displ, self.mpitype],
            [self.raw, self._send_counts, self._send_displ, self.mpitype],
        )
        gt.stop("PixelData.reverse_alltoallv MPI Alltoallv")
        return

    @function_timer
    def sync_alltoallv(self, local_func=None):
        """Perform operations on locally owned submaps using Alltoallv communication.

        On the first call, some initialization is done to compute send and receive
        displacements and counts.  A persistent receive buffer is allocated.  Submap
        data is sent to their owners simultaneously using alltoallv.  Each process does
        a local operation on their owned submaps before sending the result back with
        another alltoallv call.

        Args:
            local_func (function):  A function for processing the local submap data.

        Returns:
            None.

        """
        self.forward_alltoallv()

        if local_func is None:
            local_func = self.local_reduction

        # Run operation on locally owned submaps
        local_func(
            self._n_submap_value, self._recv_locations, self.receive, self.reduce_buf
        )

        self.reverse_alltoallv()
        return

    @function_timer
    def stats(self, comm_bytes=10000000):
        """Compute some simple statistics of the pixel data.

        The map should already be consistent across all processes with overlapping
        submaps.

        Args:
            comm_bytes (int): The approximate message size to use.

        Returns:
            (dict):  The computed properties on rank zero, None on other ranks.

        """
        if self.accel_in_use():
            msg = f"PixelData {self._accel_name} currently on accelerator"
            msg += " cannot do MPI communication"
            raise RuntimeError(msg)
        dist = self._dist
        nsub = dist.n_submap

        if dist.comm is None:
            return {
                "sum": [np.sum(self.data[:, :, x]) for x in range(self._n_value)],
                "mean": [np.mean(self.data[:, :, x]) for x in range(self._n_value)],
                "rms": [np.std(self.data[:, :, x]) for x in range(self._n_value)],
            }

        # The lowest rank with a locally-hit submap will contribute to the reduction
        local_hit_submaps = dist.comm.size * np.ones(nsub, dtype=np.int32)
        local_hit_submaps[dist.local_submaps] = dist.comm.rank
        hit_submaps = np.zeros_like(local_hit_submaps)
        dist.comm.Allreduce(local_hit_submaps, hit_submaps, op=MPI.MIN)
        del local_hit_submaps

        comm_submap = self.comm_nsubmap(comm_bytes)

        send_buf = np.zeros(
            comm_submap * dist.n_pix_submap * self._n_value,
            dtype=self._dtype,
        ).reshape((comm_submap, dist.n_pix_submap, self._n_value))

        recv_buf = None
        if dist.comm.rank == 0:
            # Alloc receive buffer
            recv_buf = np.zeros(
                comm_submap * dist.n_pix_submap * self._n_value,
                dtype=self._dtype,
            ).reshape((comm_submap, dist.n_pix_submap, self._n_value))
            # Variables for variance calc
            accum_sum = np.zeros(self._n_value, dtype=np.float64)
            accum_count = np.zeros(self._n_value, dtype=np.int64)
            accum_mean = np.zeros(self._n_value, dtype=np.float64)
            accum_var = np.zeros(self._n_value, dtype=np.float64)

        # Doing a two-pass variance calculation is faster than looping
        # over individual samples in python.

        submap_off = 0
        ncomm = comm_submap

        while submap_off < nsub:
            if submap_off + ncomm > nsub:
                ncomm = nsub - submap_off
            send_buf[:, :, :] = 0
            for sm in range(ncomm):
                abs_sm = submap_off + sm
                if hit_submaps[abs_sm] == dist.comm.rank:
                    # Contribute
                    loc = dist.global_submap_to_local[abs_sm]
                    send_buf[sm, :, :] = self.data[loc, :, :]

            dist.comm.Reduce(send_buf, recv_buf, op=MPI.SUM, root=0)

            if dist.comm.rank == 0:
                for sm in range(ncomm):
                    for v in range(self._n_value):
                        accum_sum[v] += np.sum(recv_buf[sm, :, v])
                        accum_count[v] += dist.n_pix_submap
            dist.comm.barrier()
            submap_off += ncomm

        if dist.comm.rank == 0:
            for v in range(self._n_value):
                accum_mean[v] = accum_sum[v] / accum_count[v]

        submap_off = 0
        ncomm = comm_submap

        while submap_off < nsub:
            if submap_off + ncomm > nsub:
                ncomm = nsub - submap_off
            send_buf[:, :, :] = 0
            for sm in range(ncomm):
                abs_sm = submap_off + sm
                if hit_submaps[abs_sm] == dist.comm.rank:
                    # Contribute
                    loc = dist.global_submap_to_local[abs_sm]
                    send_buf[sm, :, :] = self.data[loc, :, :]

            dist.comm.Reduce(send_buf, recv_buf, op=MPI.SUM, root=0)

            if dist.comm.rank == 0:
                for sm in range(ncomm):
                    for v in range(self._n_value):
                        accum_var[v] += np.sum(
                            (recv_buf[sm, :, v] - accum_mean[v]) ** 2
                        )
            dist.comm.barrier()
            submap_off += ncomm

        if dist.comm.rank == 0:
            return {
                "sum": [float(accum_sum[x]) for x in range(self._n_value)],
                "mean": [float(accum_mean[x]) for x in range(self._n_value)],
                "rms": [
                    np.sqrt(accum_var[x] / (accum_count[x] - 1))
                    for x in range(self._n_value)
                ],
            }
        else:
            return None

    @function_timer
    def broadcast_map(self, fdata, comm_bytes=10000000):
        """Distribute a map located on a single process.

        The root process takes a map in memory and distributes it.   Chunks of submaps
        are broadcast to all processes, and each process copies data to its local
        submaps.

        Args:
            fdata (array): The input data (only significant on process 0).
            comm_bytes (int): The approximate message size to use.

        Returns:
            None

        """
        if self.accel_in_use():
            msg = f"PixelData {self._accel_name} currently on accelerator"
            msg += " cannot do MPI communication"
            raise RuntimeError(msg)
        rank = 0
        if self._dist.comm is not None:
            rank = self._dist.comm.rank
        comm_submap = self.comm_nsubmap(comm_bytes)

        # we make the assumption that FITS binary tables are still stored in
        # blocks of 2880 bytes just like always...
        dbytes = self._dtype.itemsize
        rowbytes = self._n_value * dbytes
        optrows = int(2880 / rowbytes)

        # Get a tuple of all columns in the table.  We choose memmap here so
        # that we can (hopefully) read through all columns in chunks such that
        # we only ever have a couple FITS blocks in memory.
        if rank == 0:
            if self._n_value == 1:
                fdata = (fdata,)

        buf = np.zeros(
            comm_submap * self._dist.n_pix_submap * self._n_value, dtype=self._dtype
        )
        view = buf.reshape((comm_submap, self._dist.n_pix_submap, self._n_value))

        in_off = 0
        out_off = 0
        submap_off = 0

        rows = optrows
        while in_off < self._dist.n_pix:
            if in_off + rows > self._dist.n_pix:
                rows = self._dist.n_pix - in_off
            # is this the last block for this communication?
            islast = False
            copyrows = rows
            if out_off + rows > (comm_submap * self._dist.n_pix_submap):
                copyrows = (comm_submap * self._dist.n_pix_submap) - out_off
                islast = True

            if rank == 0:
                for col in range(self._n_value):
                    coloff = (out_off * self._n_value) + col
                    buf[
                        coloff : coloff + (copyrows * self._n_value) : self._n_value
                    ] = fdata[col][in_off : in_off + copyrows]

            out_off += copyrows
            in_off += copyrows

            if islast:
                if self._dist.comm is not None:
                    self._dist.comm.Bcast(buf, root=0)
                # loop over these submaps, and copy any that we are assigned
                for sm in range(submap_off, submap_off + comm_submap):
                    if sm in self._dist.local_submaps:
                        loc = self._dist.global_submap_to_local[sm]
                        self.data[loc, :, :] = view[sm - submap_off, :, :]
                out_off = 0
                submap_off += comm_submap
                buf.fill(0)
                islast = False

        # flush the remaining buffer

        if out_off > 0:
            if self._dist.comm is not None:
                self._dist.comm.Bcast(buf, root=0)
            # loop over these submaps, and copy any that we are assigned
            for sm in range(submap_off, submap_off + comm_submap):
                if sm in self._dist.local_submaps:
                    loc = self._dist.global_submap_to_local[sm]
                    self.data[loc, :, :] = view[sm - submap_off, :, :]
        return

    def _accel_exists(self):
        if use_accel_omp:
            return accel_data_present(self.raw, self._accel_name)
        elif use_accel_jax:
            return accel_data_present(self.data)
        else:
            return False

    def _accel_create(self, zero_out=False):
        if use_accel_omp:
            self.raw = accel_data_create(self.raw, self._accel_name, zero_out=zero_out)
        elif use_accel_jax:
            self.data = accel_data_create(self.data, zero_out=zero_out)

    def _accel_update_device(self):
        if use_accel_omp:
            self.raw = accel_data_update_device(self.raw, self._accel_name)
        elif use_accel_jax:
            self.data = accel_data_update_device(self.data)

    def _accel_update_host(self):
        if use_accel_omp:
            self.raw = accel_data_update_host(self.raw, self._accel_name)
        elif use_accel_jax:
            self.data = accel_data_update_host(self.data)

    def _accel_reset(self):
        if use_accel_omp:
            accel_data_reset(self.raw, self._accel_name)
        elif use_accel_jax:
            accel_data_reset(self.data)

    def _accel_delete(self):
        if use_accel_omp:
            self.raw = accel_data_delete(self.raw, self._accel_name)
        elif use_accel_jax:
            self.data = accel_data_delete(self.data)

_all_comm_submap = None instance-attribute

_all_recv = None instance-attribute

_all_recv_raw = None instance-attribute

_all_send = None instance-attribute

_all_send_raw = None instance-attribute

_dist = dist instance-attribute

_dtype = ttype instance-attribute

_flatshape = self._dist.n_local_submap * self._dist.n_pix_submap * self._n_value instance-attribute

_n_submap_value = self._dist.n_pix_submap * self._n_value instance-attribute

_n_value = n_value instance-attribute

_receive_raw = None instance-attribute

_recv_counts = None instance-attribute

_recv_displ = None instance-attribute

_recv_locations = None instance-attribute

_reduce_buf_raw = None instance-attribute

_send_counts = None instance-attribute

_send_displ = None instance-attribute

_shape = (self._dist.n_local_submap, self._dist.n_pix_submap, self._n_value) instance-attribute

_units = units instance-attribute

data = self.raw.array().reshape(self._shape) instance-attribute

distribution property

(PixelDistribution): The distribution information.

dtype property

(numpy.dtype): The data type of the values.

mpibytesize = None instance-attribute

mpitype = None instance-attribute

n_value property

(int): The number of non-zero values per pixel.

raw = self.storage_class.zeros(self._flatshape) instance-attribute

receive = None instance-attribute

reduce_buf = None instance-attribute

storage_class = None instance-attribute

units property

(Unit): The map data units.

__del__()

Source code in toast/pixels.py
557
558
def __del__(self):
    self.clear()

__delitem__(key)

Source code in toast/pixels.py
593
594
595
def __delitem__(self, key):
    raise NotImplementedError("Cannot delete individual memory elements")
    return

__eq__(other)

Source code in toast/pixels.py
614
615
616
617
618
619
620
621
622
623
def __eq__(self, other):
    if self.distribution != other.distribution:
        return False
    if self.dtype.char != other.dtype.char:
        return False
    if self.n_value != other.n_value:
        return False
    if not np.allclose(self.data, other.data):
        return False
    return True

__getitem__(key)

Source code in toast/pixels.py
590
591
def __getitem__(self, key):
    return np.array(self.data[key], dtype=self._dtype, copy=False)

__init__(dist, dtype, n_value=1, units=u.dimensionless_unscaled)

Source code in toast/pixels.py
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
def __init__(self, dist, dtype, n_value=1, units=u.dimensionless_unscaled):
    super().__init__()
    log = Logger.get()

    self._dist = dist
    self._n_value = n_value
    self._units = units

    # construct a new dtype in case the parameter given is shortcut string
    ttype = np.dtype(dtype)

    self.storage_class = None
    if ttype.char == "b":
        self.storage_class = AlignedI8
    elif ttype.char == "B":
        self.storage_class = AlignedU8
    elif ttype.char == "h":
        self.storage_class = AlignedI16
    elif ttype.char == "H":
        self.storage_class = AlignedU16
    elif ttype.char == "i":
        self.storage_class = AlignedI32
    elif ttype.char == "I":
        self.storage_class = AlignedU32
    elif (ttype.char == "q") or (ttype.char == "l"):
        self.storage_class = AlignedI64
    elif (ttype.char == "Q") or (ttype.char == "L"):
        self.storage_class = AlignedU64
    elif ttype.char == "f":
        self.storage_class = AlignedF32
    elif ttype.char == "d":
        self.storage_class = AlignedF64
    elif ttype.char == "F":
        raise NotImplementedError("No support yet for complex numbers")
    elif ttype.char == "D":
        raise NotImplementedError("No support yet for complex numbers")
    else:
        msg = "Unsupported data typecode '{}'".format(ttype.char)
        log.error(msg)
        raise ValueError(msg)
    self._dtype = ttype

    self.mpitype = None
    self.mpibytesize = None
    if self._dist.comm is not None:
        self.mpibytesize, self.mpitype = mpi_data_type(self._dist.comm, self._dtype)

    self._shape = (
        self._dist.n_local_submap,
        self._dist.n_pix_submap,
        self._n_value,
    )
    self._flatshape = (
        self._dist.n_local_submap * self._dist.n_pix_submap * self._n_value
    )
    self._n_submap_value = self._dist.n_pix_submap * self._n_value

    self.raw = self.storage_class.zeros(self._flatshape)
    self.data = self.raw.array().reshape(self._shape)

    # Allreduce quantities
    self._all_comm_submap = None
    self._all_send = None
    self._all_send_raw = None
    self._all_recv = None
    self._all_recv_raw = None

    # Alltoallv quantities
    self._send_counts = None
    self._send_displ = None
    self._recv_counts = None
    self._recv_displ = None
    self._recv_locations = None
    self.receive = None
    self._receive_raw = None
    self.reduce_buf = None
    self._reduce_buf_raw = None

__iter__()

Source code in toast/pixels.py
600
601
def __iter__(self):
    return iter(self.data)

__len__()

Source code in toast/pixels.py
603
604
def __len__(self):
    return len(self.data)

__ne__(other)

Source code in toast/pixels.py
625
626
def __ne__(self, other):
    return not self.__eq__(other)

__repr__()

Source code in toast/pixels.py
606
607
608
609
610
611
612
def __repr__(self):
    val = (
        "<PixelData {} values per pixel, dtype = {}, units= {}, dist = {}>".format(
            self._n_value, self._dtype, self._units, self._dist
        )
    )
    return val

__setitem__(key, value)

Source code in toast/pixels.py
597
598
def __setitem__(self, key, value):
    self.data[key] = value

_accel_create(zero_out=False)

Source code in toast/pixels.py
1173
1174
1175
1176
1177
def _accel_create(self, zero_out=False):
    if use_accel_omp:
        self.raw = accel_data_create(self.raw, self._accel_name, zero_out=zero_out)
    elif use_accel_jax:
        self.data = accel_data_create(self.data, zero_out=zero_out)

_accel_delete()

Source code in toast/pixels.py
1197
1198
1199
1200
1201
def _accel_delete(self):
    if use_accel_omp:
        self.raw = accel_data_delete(self.raw, self._accel_name)
    elif use_accel_jax:
        self.data = accel_data_delete(self.data)

_accel_exists()

Source code in toast/pixels.py
1165
1166
1167
1168
1169
1170
1171
def _accel_exists(self):
    if use_accel_omp:
        return accel_data_present(self.raw, self._accel_name)
    elif use_accel_jax:
        return accel_data_present(self.data)
    else:
        return False

_accel_reset()

Source code in toast/pixels.py
1191
1192
1193
1194
1195
def _accel_reset(self):
    if use_accel_omp:
        accel_data_reset(self.raw, self._accel_name)
    elif use_accel_jax:
        accel_data_reset(self.data)

_accel_update_device()

Source code in toast/pixels.py
1179
1180
1181
1182
1183
def _accel_update_device(self):
    if use_accel_omp:
        self.raw = accel_data_update_device(self.raw, self._accel_name)
    elif use_accel_jax:
        self.data = accel_data_update_device(self.data)

_accel_update_host()

Source code in toast/pixels.py
1185
1186
1187
1188
1189
def _accel_update_host(self):
    if use_accel_omp:
        self.raw = accel_data_update_host(self.raw, self._accel_name)
    elif use_accel_jax:
        self.data = accel_data_update_host(self.data)

broadcast_map(fdata, comm_bytes=10000000)

Distribute a map located on a single process.

The root process takes a map in memory and distributes it. Chunks of submaps are broadcast to all processes, and each process copies data to its local submaps.

Parameters:

Name Type Description Default
fdata array

The input data (only significant on process 0).

required
comm_bytes int

The approximate message size to use.

10000000

Returns:

Type Description

None

Source code in toast/pixels.py
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
@function_timer
def broadcast_map(self, fdata, comm_bytes=10000000):
    """Distribute a map located on a single process.

    The root process takes a map in memory and distributes it.   Chunks of submaps
    are broadcast to all processes, and each process copies data to its local
    submaps.

    Args:
        fdata (array): The input data (only significant on process 0).
        comm_bytes (int): The approximate message size to use.

    Returns:
        None

    """
    if self.accel_in_use():
        msg = f"PixelData {self._accel_name} currently on accelerator"
        msg += " cannot do MPI communication"
        raise RuntimeError(msg)
    rank = 0
    if self._dist.comm is not None:
        rank = self._dist.comm.rank
    comm_submap = self.comm_nsubmap(comm_bytes)

    # we make the assumption that FITS binary tables are still stored in
    # blocks of 2880 bytes just like always...
    dbytes = self._dtype.itemsize
    rowbytes = self._n_value * dbytes
    optrows = int(2880 / rowbytes)

    # Get a tuple of all columns in the table.  We choose memmap here so
    # that we can (hopefully) read through all columns in chunks such that
    # we only ever have a couple FITS blocks in memory.
    if rank == 0:
        if self._n_value == 1:
            fdata = (fdata,)

    buf = np.zeros(
        comm_submap * self._dist.n_pix_submap * self._n_value, dtype=self._dtype
    )
    view = buf.reshape((comm_submap, self._dist.n_pix_submap, self._n_value))

    in_off = 0
    out_off = 0
    submap_off = 0

    rows = optrows
    while in_off < self._dist.n_pix:
        if in_off + rows > self._dist.n_pix:
            rows = self._dist.n_pix - in_off
        # is this the last block for this communication?
        islast = False
        copyrows = rows
        if out_off + rows > (comm_submap * self._dist.n_pix_submap):
            copyrows = (comm_submap * self._dist.n_pix_submap) - out_off
            islast = True

        if rank == 0:
            for col in range(self._n_value):
                coloff = (out_off * self._n_value) + col
                buf[
                    coloff : coloff + (copyrows * self._n_value) : self._n_value
                ] = fdata[col][in_off : in_off + copyrows]

        out_off += copyrows
        in_off += copyrows

        if islast:
            if self._dist.comm is not None:
                self._dist.comm.Bcast(buf, root=0)
            # loop over these submaps, and copy any that we are assigned
            for sm in range(submap_off, submap_off + comm_submap):
                if sm in self._dist.local_submaps:
                    loc = self._dist.global_submap_to_local[sm]
                    self.data[loc, :, :] = view[sm - submap_off, :, :]
            out_off = 0
            submap_off += comm_submap
            buf.fill(0)
            islast = False

    # flush the remaining buffer

    if out_off > 0:
        if self._dist.comm is not None:
            self._dist.comm.Bcast(buf, root=0)
        # loop over these submaps, and copy any that we are assigned
        for sm in range(submap_off, submap_off + comm_submap):
            if sm in self._dist.local_submaps:
                loc = self._dist.global_submap_to_local[sm]
                self.data[loc, :, :] = view[sm - submap_off, :, :]
    return

clear()

Delete the underlying memory.

This will forcibly delete the C-allocated memory and invalidate all python references to this object. DO NOT CALL THIS unless you are sure all references are no longer being used and you are about to delete the object.

Source code in toast/pixels.py
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
def clear(self):
    """Delete the underlying memory.

    This will forcibly delete the C-allocated memory and invalidate all python
    references to this object.  DO NOT CALL THIS unless you are sure all references
    are no longer being used and you are about to delete the object.

    """
    if hasattr(self, "data"):
        # we keep the attribute to avoid errors in _accel_exists
        self.data = None
    if hasattr(self, "raw"):
        if self.accel_exists():
            self.accel_delete()
        if self.raw is not None:
            self.raw.clear()
        del self.raw
    if hasattr(self, "receive"):
        del self.receive
        if self._receive_raw is not None:
            self._receive_raw.clear()
        del self._receive_raw
    if hasattr(self, "reduce_buf"):
        del self.reduce_buf
        if self._reduce_buf_raw is not None:
            self._reduce_buf_raw.clear()
        del self._reduce_buf_raw
    if hasattr(self, "_all_send"):
        del self._all_send
        if self._all_send_raw is not None:
            self._all_send_raw.clear()
        del self._all_send_raw
    if hasattr(self, "_all_recv"):
        del self._all_recv
        if self._all_recv_raw is not None:
            self._all_recv_raw.clear()
        del self._all_recv_raw

comm_nsubmap(bytes)

Given a buffer size, compute the number of submaps to communicate.

Parameters:

Name Type Description Default
bytes int

The number of bytes.

required

Returns:

Type Description
int

The number of submaps in each buffer.

Source code in toast/pixels.py
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
def comm_nsubmap(self, bytes):
    """Given a buffer size, compute the number of submaps to communicate.

    Args:
        bytes (int):  The number of bytes.

    Returns:
        (int):  The number of submaps in each buffer.

    """
    dbytes = self._dtype.itemsize
    nsub = int(bytes / (dbytes * self._n_submap_value))
    if nsub == 0:
        nsub = 1
    allsub = int(self._dist.n_pix / self._dist.n_pix_submap)
    if nsub > allsub:
        nsub = allsub
    return nsub

duplicate()

Create a copy of the data with the same distribution.

Returns:

Type Description
PixelData

A duplicate of the instance with copied data but the same distribution.

Source code in toast/pixels.py
628
629
630
631
632
633
634
635
636
637
638
639
640
def duplicate(self):
    """Create a copy of the data with the same distribution.

    Returns:
        (PixelData):  A duplicate of the instance with copied data but the same
            distribution.

    """
    dup = PixelData(
        self.distribution, self.dtype, n_value=self.n_value, units=self._units
    )
    dup.data[:] = self.data
    return dup

forward_alltoallv()

Communicate submaps into buffers on the owning process.

On the first call, some initialization is done to compute send and receive displacements and counts. A persistent receive buffer is allocated. Submap data is sent to their owners simultaneously using alltoallv.

Returns:

Type Description

None.

Source code in toast/pixels.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
@function_timer
def forward_alltoallv(self):
    """Communicate submaps into buffers on the owning process.

    On the first call, some initialization is done to compute send and receive
    displacements and counts.  A persistent receive buffer is allocated.  Submap
    data is sent to their owners simultaneously using alltoallv.

    Returns:
        None.

    """
    if self.accel_in_use():
        msg = f"PixelData {self._accel_name} currently on accelerator"
        msg += " cannot do MPI communication"
        raise RuntimeError(msg)

    log = Logger.get()
    gt = GlobalTimers.get()
    self.setup_alltoallv()

    if self._dist.comm is None:
        # No communication needed
        return

    # Gather owned submaps locally
    gt.start("PixelData.forward_alltoallv MPI Alltoallv")
    self._dist.comm.Alltoallv(
        [self.raw, self._send_counts, self._send_displ, self.mpitype],
        [self.receive, self._recv_counts, self._recv_displ, self.mpitype],
    )
    gt.stop("PixelData.forward_alltoallv MPI Alltoallv")
    return

local_reduction(n_submap_value, receive_locations, receive, reduce_buf) staticmethod

Source code in toast/pixels.py
758
759
760
761
762
763
764
765
766
@staticmethod
def local_reduction(n_submap_value, receive_locations, receive, reduce_buf):
    # Locally reduce owned submaps
    for sm, locs in receive_locations.items():
        reduce_buf[:] = 0
        for lc in locs:
            reduce_buf += receive[lc : lc + n_submap_value]
        for lc in locs:
            receive[lc : lc + n_submap_value] = reduce_buf

reset()

Set memory to zero

Source code in toast/pixels.py
560
561
562
563
564
def reset(self):
    """Set memory to zero"""
    self.raw[:] = 0
    if self.accel_exists():
        self.accel_reset()

reverse_alltoallv()

Communicate submaps from the owning process back to all processes.

Returns:

Type Description

None.

Source code in toast/pixels.py
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
@function_timer
def reverse_alltoallv(self):
    """Communicate submaps from the owning process back to all processes.

    Returns:
        None.

    """
    if self.accel_in_use():
        msg = f"PixelData {self._accel_name} currently on accelerator"
        msg += " cannot do MPI communication"
        raise RuntimeError(msg)

    gt = GlobalTimers.get()
    if self._dist.comm is None:
        # No communication needed
        return
    if self._send_counts is None:
        raise RuntimeError(
            "Cannot do reverse alltoallv before buffers have been setup"
        )

    # Scatter result back
    gt.start("PixelData.reverse_alltoallv MPI Alltoallv")
    self._dist.comm.Alltoallv(
        [self.receive, self._recv_counts, self._recv_displ, self.mpitype],
        [self.raw, self._send_counts, self._send_displ, self.mpitype],
    )
    gt.stop("PixelData.reverse_alltoallv MPI Alltoallv")
    return

setup_allreduce(n_submap)

Check that allreduce buffers exist and create them if needed.

Source code in toast/pixels.py
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
@function_timer
def setup_allreduce(self, n_submap):
    """Check that allreduce buffers exist and create them if needed."""
    # Allocate persistent send / recv buffers that only change if number of submaps
    # change.
    if self._all_comm_submap is not None:
        # We have already done a reduce...
        if n_submap == self._all_comm_submap:
            # Already allocated with correct size
            return
        else:
            # Delete the old buffers.
            del self._all_send
            self._all_send_raw.clear()
            del self._all_send_raw
            del self._all_recv
            self._all_recv_raw.clear()
            del self._all_recv_raw
    # Allocate with the new size
    self._all_comm_submap = n_submap
    self._all_recv_raw = self.storage_class.zeros(n_submap * self._n_submap_value)
    self._all_recv = self._all_recv_raw.array()
    self._all_send_raw = self.storage_class.zeros(n_submap * self._n_submap_value)
    self._all_send = self._all_send_raw.array()

setup_alltoallv()

Check that alltoallv buffers exist and create them if needed.

Source code in toast/pixels.py
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@function_timer
def setup_alltoallv(self):
    """Check that alltoallv buffers exist and create them if needed."""
    if self._send_counts is None:
        if self.accel_in_use():
            msg = f"PixelData {self._accel_name} currently on accelerator"
            msg += " cannot do MPI communication"
            raise RuntimeError(msg)
        log = Logger.get()
        # Get the parameters in terms of submaps.
        (
            send_counts,
            send_displ,
            recv_counts,
            recv_displ,
            recv_locations,
        ) = self._dist.alltoallv_info

        # Pixel values per submap
        scale = self._n_submap_value

        # Scale these quantites by the submap size and the number of values per
        # pixel.

        self._send_counts = scale * np.array(send_counts, dtype=np.int32)
        self._send_displ = scale * np.array(send_displ, dtype=np.int32)
        self._recv_counts = scale * np.array(recv_counts, dtype=np.int32)
        self._recv_displ = scale * np.array(recv_displ, dtype=np.int32)
        self._recv_locations = dict()
        for sm, locs in recv_locations.items():
            self._recv_locations[sm] = scale * np.array(locs, dtype=np.int32)

        msg_rank = 0
        if self._dist.comm is not None:
            msg_rank = self._dist.comm.rank
        msg = f"setup_alltoallv[{msg_rank}]:\n"
        msg += f"  send_counts={self._send_counts} "
        msg += f"send_displ={self._send_displ}\n"
        msg += f"  recv_counts={self._recv_counts} "
        msg += f"recv_displ={self._recv_displ} "
        msg += f"recv_locations={self._recv_locations}"
        log.verbose(msg)

        # Allocate a persistent single-submap buffer
        self._reduce_buf_raw = self.storage_class.zeros(self._n_submap_value)
        self.reduce_buf = self._reduce_buf_raw.array()

        buf_check_fail = False
        try:
            if self._dist.comm is None:
                # For this case, point the receive member to the original data.
                # This will allow codes processing locally owned submaps to work
                # transparently in the serial case.
                self.receive = self.data.reshape((-1,))
            else:
                # Check that our send and receive buffers do not exceed 32bit
                # indices required by MPI
                max_int = 2147483647
                recv_buf_size = self._recv_displ[-1] + self._recv_counts[-1]
                if recv_buf_size > max_int:
                    msg = "Proc {} Alltoallv receive buffer size exceeds max 32bit integer".format(
                        self._dist.comm.rank
                    )
                    log.error(msg)
                    buf_check_fail = True
                if len(self.raw) > max_int:
                    msg = "Proc {} Alltoallv send buffer size exceeds max 32bit integer".format(
                        self._dist.comm.rank
                    )
                    log.error(msg)
                    buf_check_fail = True

                # Allocate a persistent receive buffer
                msg = f"{msg_rank}:  allocate receive buffer of "
                msg += f"{recv_buf_size} elements"
                log.verbose(msg)
                self._receive_raw = self.storage_class.zeros(recv_buf_size)
                self.receive = self._receive_raw.array()
        except:
            buf_check_fail = True
        if self._dist.comm is not None:
            buf_check_fail = self._dist.comm.allreduce(buf_check_fail, op=MPI.LOR)
        if buf_check_fail:
            msg = "alltoallv buffer setup failed on one or more processes"
            raise RuntimeError(msg)

stats(comm_bytes=10000000)

Compute some simple statistics of the pixel data.

The map should already be consistent across all processes with overlapping submaps.

Parameters:

Name Type Description Default
comm_bytes int

The approximate message size to use.

10000000

Returns:

Type Description
dict

The computed properties on rank zero, None on other ranks.

Source code in toast/pixels.py
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
@function_timer
def stats(self, comm_bytes=10000000):
    """Compute some simple statistics of the pixel data.

    The map should already be consistent across all processes with overlapping
    submaps.

    Args:
        comm_bytes (int): The approximate message size to use.

    Returns:
        (dict):  The computed properties on rank zero, None on other ranks.

    """
    if self.accel_in_use():
        msg = f"PixelData {self._accel_name} currently on accelerator"
        msg += " cannot do MPI communication"
        raise RuntimeError(msg)
    dist = self._dist
    nsub = dist.n_submap

    if dist.comm is None:
        return {
            "sum": [np.sum(self.data[:, :, x]) for x in range(self._n_value)],
            "mean": [np.mean(self.data[:, :, x]) for x in range(self._n_value)],
            "rms": [np.std(self.data[:, :, x]) for x in range(self._n_value)],
        }

    # The lowest rank with a locally-hit submap will contribute to the reduction
    local_hit_submaps = dist.comm.size * np.ones(nsub, dtype=np.int32)
    local_hit_submaps[dist.local_submaps] = dist.comm.rank
    hit_submaps = np.zeros_like(local_hit_submaps)
    dist.comm.Allreduce(local_hit_submaps, hit_submaps, op=MPI.MIN)
    del local_hit_submaps

    comm_submap = self.comm_nsubmap(comm_bytes)

    send_buf = np.zeros(
        comm_submap * dist.n_pix_submap * self._n_value,
        dtype=self._dtype,
    ).reshape((comm_submap, dist.n_pix_submap, self._n_value))

    recv_buf = None
    if dist.comm.rank == 0:
        # Alloc receive buffer
        recv_buf = np.zeros(
            comm_submap * dist.n_pix_submap * self._n_value,
            dtype=self._dtype,
        ).reshape((comm_submap, dist.n_pix_submap, self._n_value))
        # Variables for variance calc
        accum_sum = np.zeros(self._n_value, dtype=np.float64)
        accum_count = np.zeros(self._n_value, dtype=np.int64)
        accum_mean = np.zeros(self._n_value, dtype=np.float64)
        accum_var = np.zeros(self._n_value, dtype=np.float64)

    # Doing a two-pass variance calculation is faster than looping
    # over individual samples in python.

    submap_off = 0
    ncomm = comm_submap

    while submap_off < nsub:
        if submap_off + ncomm > nsub:
            ncomm = nsub - submap_off
        send_buf[:, :, :] = 0
        for sm in range(ncomm):
            abs_sm = submap_off + sm
            if hit_submaps[abs_sm] == dist.comm.rank:
                # Contribute
                loc = dist.global_submap_to_local[abs_sm]
                send_buf[sm, :, :] = self.data[loc, :, :]

        dist.comm.Reduce(send_buf, recv_buf, op=MPI.SUM, root=0)

        if dist.comm.rank == 0:
            for sm in range(ncomm):
                for v in range(self._n_value):
                    accum_sum[v] += np.sum(recv_buf[sm, :, v])
                    accum_count[v] += dist.n_pix_submap
        dist.comm.barrier()
        submap_off += ncomm

    if dist.comm.rank == 0:
        for v in range(self._n_value):
            accum_mean[v] = accum_sum[v] / accum_count[v]

    submap_off = 0
    ncomm = comm_submap

    while submap_off < nsub:
        if submap_off + ncomm > nsub:
            ncomm = nsub - submap_off
        send_buf[:, :, :] = 0
        for sm in range(ncomm):
            abs_sm = submap_off + sm
            if hit_submaps[abs_sm] == dist.comm.rank:
                # Contribute
                loc = dist.global_submap_to_local[abs_sm]
                send_buf[sm, :, :] = self.data[loc, :, :]

        dist.comm.Reduce(send_buf, recv_buf, op=MPI.SUM, root=0)

        if dist.comm.rank == 0:
            for sm in range(ncomm):
                for v in range(self._n_value):
                    accum_var[v] += np.sum(
                        (recv_buf[sm, :, v] - accum_mean[v]) ** 2
                    )
        dist.comm.barrier()
        submap_off += ncomm

    if dist.comm.rank == 0:
        return {
            "sum": [float(accum_sum[x]) for x in range(self._n_value)],
            "mean": [float(accum_mean[x]) for x in range(self._n_value)],
            "rms": [
                np.sqrt(accum_var[x] / (accum_count[x] - 1))
                for x in range(self._n_value)
            ],
        }
    else:
        return None

sync_allreduce(comm_bytes=10000000)

Perform a buffered allreduce of the data.

Parameters:

Name Type Description Default
comm_bytes int

The approximate message size to use.

10000000

Returns:

Type Description

None.

Source code in toast/pixels.py
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
@function_timer
def sync_allreduce(self, comm_bytes=10000000):
    """Perform a buffered allreduce of the data.

    Args:
        comm_bytes (int): The approximate message size to use.

    Returns:
        None.

    """
    if self.accel_in_use():
        msg = f"PixelData {self._accel_name} currently on accelerator"
        msg += " cannot do MPI communication"
        raise RuntimeError(msg)

    if self._dist.comm is None:
        return

    comm_submap = self.comm_nsubmap(comm_bytes)
    self.setup_allreduce(comm_submap)

    dist = self._dist
    nsub = dist.n_submap

    sendview = self._all_send.reshape(
        (comm_submap, dist.n_pix_submap, self._n_value)
    )

    recvview = self._all_recv.reshape(
        (comm_submap, dist.n_pix_submap, self._n_value)
    )

    owners = dist.submap_owners

    submap_off = 0
    ncomm = comm_submap

    gt = GlobalTimers.get()

    while submap_off < nsub:
        if submap_off + ncomm > nsub:
            ncomm = nsub - submap_off
        if np.sum(owners[submap_off : submap_off + ncomm]) != -ncomm:
            # At least one submap has some hits.  Do the allreduce.
            # Otherwise we would skip this buffer to avoid reducing a
            # bunch of zeros.
            for c in range(ncomm):
                glob = submap_off + c
                if glob in dist.local_submaps:
                    # copy our data in.
                    loc = dist.global_submap_to_local[glob]
                    sendview[c, :, :] = self.data[loc, :, :]

            gt.start("PixelData.sync_allreduce MPI Allreduce")
            dist.comm.Allreduce(self._all_send, self._all_recv, op=MPI.SUM)
            gt.stop("PixelData.sync_allreduce MPI Allreduce")

            for c in range(ncomm):
                glob = submap_off + c
                if glob in dist.local_submaps:
                    # copy the reduced data
                    loc = dist.global_submap_to_local[glob]
                    self.data[loc, :, :] = recvview[c, :, :]

            self._all_send.fill(0)
            self._all_recv.fill(0)

        submap_off += ncomm

    return

sync_alltoallv(local_func=None)

Perform operations on locally owned submaps using Alltoallv communication.

On the first call, some initialization is done to compute send and receive displacements and counts. A persistent receive buffer is allocated. Submap data is sent to their owners simultaneously using alltoallv. Each process does a local operation on their owned submaps before sending the result back with another alltoallv call.

Parameters:

Name Type Description Default
local_func function

A function for processing the local submap data.

None

Returns:

Type Description

None.

Source code in toast/pixels.py
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
@function_timer
def sync_alltoallv(self, local_func=None):
    """Perform operations on locally owned submaps using Alltoallv communication.

    On the first call, some initialization is done to compute send and receive
    displacements and counts.  A persistent receive buffer is allocated.  Submap
    data is sent to their owners simultaneously using alltoallv.  Each process does
    a local operation on their owned submaps before sending the result back with
    another alltoallv call.

    Args:
        local_func (function):  A function for processing the local submap data.

    Returns:
        None.

    """
    self.forward_alltoallv()

    if local_func is None:
        local_func = self.local_reduction

    # Run operation on locally owned submaps
    local_func(
        self._n_submap_value, self._recv_locations, self.receive, self.reduce_buf
    )

    self.reverse_alltoallv()
    return

update_units(new_units)

Update the units associated with the data.

Source code in toast/pixels.py
586
587
588
def update_units(self, new_units):
    """Update the units associated with the data."""
    self._units = new_units

Map domain objects can be saved to and loaded from different formats on disk depending on the pixelization. Healpix maps support both FITS and a more performant HDF5 format. Maps in WCS flat projections only support FITS formats.

toast.pixels_io_healpix.read_healpix_fits(pix, path, nest=True, comm_bytes=10000000)

Read and broadcast a HEALPix FITS table.

The root process opens the FITS file in memmap mode and iterates over chunks of the map in a way to minimize cache misses in the internal FITS buffer. Chunks of submaps are broadcast to all processes, and each process copies data to its local submaps.

Parameters:

Name Type Description Default
pix PixelData

The distributed PixelData object.

required
path str

The path to the FITS file.

required
nest bool

If True, convert input to NESTED ordering, else use RING.

True
comm_bytes int

The approximate message size to use in bytes.

10000000

Returns:

Type Description

None

Source code in toast/pixels_io_healpix.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
@function_timer
def read_healpix_fits(pix, path, nest=True, comm_bytes=10000000):
    """Read and broadcast a HEALPix FITS table.

    The root process opens the FITS file in memmap mode and iterates over
    chunks of the map in a way to minimize cache misses in the internal
    FITS buffer.  Chunks of submaps are broadcast to all processes, and
    each process copies data to its local submaps.

    Args:
        pix (PixelData): The distributed PixelData object.
        path (str): The path to the FITS file.
        nest (bool): If True, convert input to NESTED ordering, else use RING.
        comm_bytes (int): The approximate message size to use in bytes.

    Returns:
        None

    """
    log = Logger.get()
    dist = pix.distribution
    rank = 0
    if dist.comm is not None:
        rank = dist.comm.rank

    comm_submap = pix.comm_nsubmap(comm_bytes)

    # we make the assumption that FITS binary tables are still stored in
    # blocks of 2880 bytes just like always...
    dbytes = pix.dtype.itemsize
    rowbytes = pix.n_value * dbytes
    optrows = 2880 // rowbytes

    # get a tuple of all columns in the table.  We choose memmap here so
    # that we can (hopefully) read through all columns in chunks such that
    # we only ever have a couple FITS blocks in memory.
    fdata = None
    fscale = 1.0
    if rank == 0:
        # Check that the file is in expected format
        errors = ""
        h = hp.fitsfunc.pf.open(path, "readonly")
        nside = hp.npix2nside(dist.n_pix)
        nside_map = h[1].header["nside"]
        if "TUNIT1" in h[1].header:
            if h[1].header["TUNIT1"] == "":
                funits = u.dimensionless_unscaled
            elif h[1].header["TUNIT1"] in ["K", "K_CMB"]:
                funits = u.K
            elif h[1].header["TUNIT1"] in ["mK", "mK_CMB"]:
                funits = u.mK
            elif h[1].header["TUNIT1"] in ["uK", "uK_CMB"]:
                funits = u.uK
            else:
                funits = u.Unit(h[1].header["TUNIT1"])
        else:
            msg = f"Pixel data in {path} does not have TUNIT1 key.  "
            msg += f"Assuming '{pix.units}'."
            log.info(msg)
            funits = pix.units
        if funits != pix.units:
            fscale = unit_conversion(funits, pix.units)

        if nside_map != nside:
            errors += f"Wrong NSide: {path} has {nside_map}, expected {nside}\n"
        map_nnz = h[1].header["tfields"]
        if map_nnz != pix.n_value:
            errors += f"Wrong number of columns: {path} has {map_nnz}, "
            errors += f"expected {pix.n_value}\n"
        h.close()
        if len(errors) != 0:
            raise RuntimeError(errors)
        # Now read the map
        fdata = hp.read_map(
            path,
            field=tuple([x for x in range(pix.n_value)]),
            dtype=[pix.dtype for x in range(pix.n_value)],
            memmap=True,
            nest=nest,
        )
        if pix.n_value == 1:
            fdata = (fdata,)

    if dist.comm is not None:
        fscale = dist.comm.bcast(fscale, root=0)
    buf = np.zeros(comm_submap * dist.n_pix_submap * pix.n_value, dtype=pix.dtype)
    view = buf.reshape(comm_submap, dist.n_pix_submap, pix.n_value)

    in_off = 0
    out_off = 0
    submap_off = 0

    rows = optrows
    while in_off < dist.n_pix:
        if in_off + rows > dist.n_pix:
            rows = dist.n_pix - in_off
        # is this the last block for this communication?
        islast = False
        copyrows = rows
        if out_off + rows > (comm_submap * dist.n_pix_submap):
            copyrows = (comm_submap * dist.n_pix_submap) - out_off
            islast = True

        if rank == 0:
            for col in range(pix.n_value):
                coloff = (out_off * pix.n_value) + col
                buf[coloff : coloff + (copyrows * pix.n_value) : pix.n_value] = fdata[
                    col
                ][in_off : in_off + copyrows]

        out_off += copyrows
        in_off += copyrows

        if islast:
            if dist.comm is not None:
                dist.comm.Bcast(buf, root=0)
            # loop over these submaps, and copy any that we are assigned
            for sm in range(submap_off, submap_off + comm_submap):
                if sm in dist.local_submaps:
                    loc = dist.global_submap_to_local[sm]
                    pix.data[loc, :, :] = fscale * view[sm - submap_off, :, :]
            out_off = 0
            submap_off += comm_submap
            buf.fill(0)
            islast = False

    # flush the remaining buffer
    if out_off > 0:
        if dist.comm is not None:
            dist.comm.Bcast(buf, root=0)
        # loop over these submaps, and copy any that we are assigned
        for sm in range(submap_off, submap_off + comm_submap):
            if sm in dist.local_submaps:
                loc = dist.global_submap_to_local[sm]
                pix.data[loc, :, :] = fscale * view[sm - submap_off, :, :]
    return

toast.pixels_io_healpix.write_healpix_fits(pix, path, nest=True, comm_bytes=10000000, report_memory=False, single_precision=False)

Write pixel data to a HEALPix format FITS table.

The data across all processes is assumed to be synchronized (the data for a given submap shared between processes is identical). The submap data is sent to the root process which writes it out. For parallel writing, see write_hdf5().

Parameters:

Name Type Description Default
pix PixelData

The distributed pixel object.

required
path str

The path to the output FITS file.

required
nest bool

If True, data is in NESTED ordering, else data is in RING.

True
comm_bytes int

The approximate message size to use.

10000000
report_memory bool

Report the amount of available memory on the root node just before writing out the map.

False
single_precision bool

Cast float and integer maps to single precision.

False

Returns:

Type Description

None

Source code in toast/pixels_io_healpix.py
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
@function_timer
def write_healpix_fits(
    pix,
    path,
    nest=True,
    comm_bytes=10000000,
    report_memory=False,
    single_precision=False,
):
    """Write pixel data to a HEALPix format FITS table.

    The data across all processes is assumed to be synchronized (the data for a given
    submap shared between processes is identical).  The submap data is sent to the root
    process which writes it out.  For parallel writing, see write_hdf5().

    Args:
        pix (PixelData): The distributed pixel object.
        path (str): The path to the output FITS file.
        nest (bool): If True, data is in NESTED ordering, else data is in RING.
        comm_bytes (int): The approximate message size to use.
        report_memory (bool): Report the amount of available memory on the root
            node just before writing out the map.
        single_precision (bool): Cast float and integer maps to single precision.

    Returns:
        None

    """
    log = Logger.get()
    timer = Timer()
    timer.start()

    # The distribution
    dist = pix.distribution

    # Unit string to write
    if pix.units == u.K:
        funits = "K"
    elif pix.units == u.mK:
        funits = "mK"
    elif pix.units == u.uK:
        funits = "uK"
    else:
        funits = str(pix.units)

    rank = 0
    if dist.comm is not None:
        rank = dist.comm.rank

    fdata, fview = collect_healpix_submaps(pix, comm_bytes=comm_bytes)

    if rank == 0:
        if os.path.isfile(path):
            os.remove(path)
        dtypes = [np.dtype(pix.dtype) for x in range(pix.n_value)]
        if single_precision:
            for i, dtype in enumerate(dtypes):
                if dtype == np.float64:
                    dtypes[i] = np.float32
                elif dtype == np.int64:
                    dtypes[i] = np.int32
        if report_memory:
            mem = memreport(msg="(root node)", silent=True)
            log.info_rank(f"About to write {path}:  {mem}")
        extra = [(f"TUNIT{x}", f"{funits}") for x in range(pix.n_value)]
        hp.write_map(
            path, fview, dtype=dtypes, fits_IDL=False, nest=nest, extra_header=extra
        )
        del fview
        for col in range(pix.n_value):
            fdata[col].clear()
        del fdata

    return

toast.pixels_io_healpix.read_healpix_hdf5(pix, path, nest=True, comm_bytes=10000000)

Read and broadcast a HEALPix map from an HDF5 file.

The root process opens the file and iterates over chunks of the map. Chunks of submaps are broadcast to all processes, and each process copies data to its local submaps.

Parameters:

Name Type Description Default
pix PixelData

The distributed PixelData object.

required
path str

The path to the FITS file.

required
nest bool

If True, convert input to NESTED ordering, else use RING.

True
comm_bytes int

The approximate message size to use in bytes.

10000000

Returns:

Type Description

None

Source code in toast/pixels_io_healpix.py
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
@function_timer
def read_healpix_hdf5(pix, path, nest=True, comm_bytes=10000000):
    """Read and broadcast a HEALPix map from an HDF5 file.

    The root process opens the file and iterates over chunks of the map.
    Chunks of submaps are broadcast to all processes, and each process
    copies data to its local submaps.

    Args:
        pix (PixelData): The distributed PixelData object.
        path (str): The path to the FITS file.
        nest (bool): If True, convert input to NESTED ordering, else use RING.
        comm_bytes (int): The approximate message size to use in bytes.

    Returns:
        None

    """
    log = Logger.get()
    timer = Timer()
    timer.start()

    dist = pix.distribution
    rank = 0
    if dist.comm is not None:
        rank = dist.comm.rank

    comm_submap = pix.comm_nsubmap(comm_bytes)

    fdata = None
    fscale = 1.0
    if rank == 0:
        try:
            f = h5py.File(path, "r")
        except OSError as e:
            msg = f"Failed to open {path} for reading: {e}"
            raise RuntimeError(msg)

        dset = f["map"]
        header = dict(dset.attrs)
        nside_file = header["NSIDE"]
        nside = hp.npix2nside(dist.n_pix)
        if nside_file != nside:
            msg = f"Wrong resolution in {path}: expected {nside} but found {nside_file}"
            raise RuntimeError(msg)
        if header["ORDERING"] == "NESTED":
            file_nested = True
        elif header["ORDERING"] == "RING":
            file_nested = False
        else:
            msg = f"Could not determine {path} pixel ordering."
            raise RuntimeError(msg)
        if "UNITS" in header:
            if header["UNITS"] == "":
                funits = u.dimensionless_unscaled
            else:
                funits = u.Unit(header["UNITS"])
        else:
            msg = f"Pixel data in {path} does not have UNITS.  Assuming {pix.units}."
            log.info(msg)
            funits = pix.units
        if funits != pix.units:
            scale = 1.0 * funits
            scale.to(pix.units)
            fscale = scale.value

        nnz, npix = dset.shape
        if nnz < pix.n_value:
            msg = f"Map in {path} has {nnz} columns but we require {pix.n_value}."
            raise RuntimeError(msg)
        if file_nested != nest:
            log.warning(
                f"{path} has ORDERING={header['ORDERING']}, "
                f"reordering serially upon load."
            )
            if file_nested and not nest:
                mapdata = hp.reorder(dset[:], n2r=True)
            elif not file_nested and nest:
                mapdata = hp.reorder(dset[:], r2n=True)
        else:
            # No reorder, we'll only load what we need
            mapdata = dset

    if dist.comm is not None:
        fscale = dist.comm.bcast(fscale, root=0)

    buf = np.zeros(comm_submap * pix.n_value * dist.n_pix_submap, dtype=pix.dtype)
    view = buf.reshape(comm_submap, pix.n_value, dist.n_pix_submap)

    # Load and broadcast submaps that are used
    hit_submaps = dist.all_hit_submaps
    n_hit_submaps = len(hit_submaps)

    submap_offset = 0
    while submap_offset < n_hit_submaps:
        submap_last = min(submap_offset + comm_submap, n_hit_submaps)
        if rank == 0:
            for i, submap in enumerate(hit_submaps[submap_offset:submap_last]):
                pix_offset = submap * dist.n_pix_submap
                # Healpix submaps are always complete but capping the upper
                # limit helps when users are embedding other pixelizations
                # into Healpix
                pix_last = min(pix_offset + dist.n_pix_submap, dist.n_pix)
                view[i, :, 0 : pix_last - pix_offset] = mapdata[
                    0 : pix.n_value, pix_offset:pix_last
                ]

        if dist.comm is not None:
            dist.comm.Bcast(buf, root=0)

        # loop over these submaps, and copy any that we are assigned
        for i, submap in enumerate(hit_submaps[submap_offset:submap_last]):
            if submap in dist.local_submaps:
                loc = dist.global_submap_to_local[submap]
                pix.data[loc] = fscale * view[i].T

        submap_offset = submap_last

    if rank == 0:
        f.close()

    return

toast.pixels_io_healpix.write_healpix_hdf5(pix, path, nest=True, comm_bytes=10000000, single_precision=False, force_serial=True)

Write pixel data to a HEALPix format HDF5 dataset.

The data across all processes is assumed to be synchronized (the data for a given submap shared between processes is identical).

Parameters:

Name Type Description Default
pix PixelData

The distributed pixel object.

required
path str

The path to the output FITS file.

required
nest bool

If True, data is in NESTED ordering, else data is in RING.

True
comm_bytes int

The approximate message size to use.

10000000
single_precision bool

If True, write floats and integers in single precision

False
force_serial bool

If True, use the serial h5py implementation, even if parallel support is available.

True

Returns:

Type Description

None

Source code in toast/pixels_io_healpix.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
@function_timer
def write_healpix_hdf5(
    pix, path, nest=True, comm_bytes=10000000, single_precision=False, force_serial=True
):
    """Write pixel data to a HEALPix format HDF5 dataset.

    The data across all processes is assumed to be synchronized (the data for a given
    submap shared between processes is identical).

    Args:
        pix (PixelData): The distributed pixel object.
        path (str): The path to the output FITS file.
        nest (bool): If True, data is in NESTED ordering, else data is in RING.
        comm_bytes (int): The approximate message size to use.
        single_precision (bool): If True, write floats and integers in single precision
        force_serial (bool):  If True, use the serial h5py implementation, even if
            parallel support is available.

    Returns:
        None

    """
    log = Logger.get()

    # The distribution
    dist = pix.distribution

    rank = 0
    ntask = 1
    if dist.comm is not None:
        rank = dist.comm.rank
        ntask = dist.comm.size

    not_owned = None
    allowners = None
    if dist.comm is None:
        not_owned = 1
        allowners = np.zeros(dist.n_submap, dtype=np.int32)
        allowners.fill(not_owned)
        for m in dist.local_submaps:
            allowners[m] = rank
    else:
        not_owned = dist.comm.size
        owners = np.zeros(dist.n_submap, dtype=np.int32)
        owners.fill(not_owned)
        for m in dist.local_submaps:
            owners[m] = dist.comm.rank
        allowners = np.zeros_like(owners)
        dist.comm.Allreduce(owners, allowners, op=MPI.MIN)

    header = {}
    if nest:
        header["ORDERING"] = "NESTED"
    else:
        header["ORDERING"] = "RING"
    header["NSIDE"] = hp.npix2nside(dist.n_pix)
    header["UNITS"] = str(pix.units)

    dtype = pix.dtype
    if single_precision:
        if dtype == np.float64:
            dtype = np.float32
        elif dtype == np.int64:
            dtype = np.int32

    if have_hdf5_parallel() and not force_serial:
        # Open the file for parallel access.
        with h5py.File(path, "w", driver="mpio", comm=dist.comm) as f:
            # Each process writes their own submaps to the file
            dset = f.create_dataset(
                "map",
                (pix.n_value, dist.n_pix),
                chunks=(pix.n_value, dist.n_pix_submap),
                dtype=dtype,
            )
            for key, value in header.items():
                dset.attrs[key] = value
            for submap in range(dist.n_submap):
                if allowners[submap] == rank:
                    local_submap = dist.global_submap_to_local[submap]
                    # Accommodate submap sizes that do not fit the map cleanly
                    first = submap * dist.n_pix_submap
                    last = min(first + dist.n_pix_submap, dist.n_pix)
                    dset[:, first:last] = pix[local_submap, 0 : last - first].T
    else:
        # No luck, write serially from root process
        if use_mpi:
            # MPI is enabled, but we are not using it.  Warn the user.
            log.warning_rank(
                f"h5py not built with MPI support.  Writing {path} in serial mode.",
                comm=dist.comm,
            )

        # n_send = len(dist.owned_submaps)
        n_send = np.sum(allowners == rank)
        if n_send == 0:
            sendbuffer = None
        else:
            sendbuffer = np.empty(
                [n_send, pix.n_value, dist.n_pix_submap],
                dtype=dtype,
            )
            offset = 0
            # for submap in dist.owned_submaps:
            for submap in range(dist.n_submap):
                if allowners[submap] == rank:
                    local_submap = dist.global_submap_to_local[submap]
                    sendbuffer[offset] = pix.data[local_submap].T
                    offset += 1

        if rank == 0:
            # Root process receives the submaps from other processes and writes
            # them to file
            with h5py.File(path, "w") as f:
                dset = f.create_dataset(
                    "map",
                    (pix.n_value, dist.n_pix),
                    chunks=(pix.n_value, dist.n_pix_submap),
                    dtype=dtype,
                )
                for rank_send in range(ntask):
                    # submaps = np.argwhere(dist.submap_owners == rank_send).ravel()
                    submaps = np.arange(dist.n_submap)[allowners == rank_send]
                    n_receive = len(submaps)
                    if n_receive > 0:
                        if rank_send == rank:
                            recvbuffer = sendbuffer
                        else:
                            recvbuffer = np.empty(
                                [n_receive, pix.n_value, dist.n_pix_submap],
                                dtype=dtype,
                            )
                            dist.comm.Recv(recvbuffer, source=rank_send, tag=rank_send)
                    for i, submap in enumerate(submaps):
                        # Accommodate submap sizes that do not fit the map cleanly
                        first = submap * dist.n_pix_submap
                        last = min(first + dist.n_pix_submap, dist.n_pix)
                        dset[:, first:last] = recvbuffer[i, :, 0 : last - first]

                for key, value in header.items():
                    dset.attrs[key] = value
        else:
            # All others wait for their turn to send
            if sendbuffer is not None:
                dist.comm.Send(sendbuffer, dest=0, tag=rank)

    return

toast.pixels_io_healpix.read_healpix(filename, *args, **kwargs)

Read a FITS or HDF5 map serially.

This reads the file into simple numpy arrays on the calling process. Units in the file are ignored.

Parameters:

Name Type Description Default
filename str

The path to the file.

required

Returns:

Type Description
tuple

The map data and optionally header.

Source code in toast/pixels_io_healpix.py
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
@function_timer
def read_healpix(filename, *args, **kwargs):
    """Read a FITS or HDF5 map serially.

    This reads the file into simple numpy arrays on the calling process.
    Units in the file are ignored.

    Args:
        filename (str):  The path to the file.

    Returns:
        (tuple):  The map data and optionally header.

    """

    filename = filename.strip()

    if filename_is_fits(filename):
        # Load a FITS map with healpy
        result = hp.read_map(filename, *args, **kwargs)

    elif filename_is_hdf5(filename):
        # Translate positional arguments to keyword arguments
        if len(args) == 0:
            if "field" not in kwargs:
                kwargs["field"] = (0,)
        else:
            if "field" in kwargs:
                raise ValueError("'field' defined twice")
            field = args[0]
            if field is not None and not hasattr(field, "__len__"):
                field = (field,)
            kwargs["field"] = field

        if len(args) > 1:
            if "dtype" in kwargs:
                raise ValueError("'dtype' defined twice")
            kwargs["dtype"] = args[1]

        if len(args) > 2:
            if "nest" in kwargs:
                raise ValueError("'nest' defined twice")
            kwargs["nest"] = args[2]
        if "nest" in kwargs:
            nest = kwargs["nest"]
        else:
            nest = False

        if len(args) > 3:
            if "partial" in kwargs:
                raise ValueError("'partial' defined twice")
            kwargs["partial"] = args[3]
        if "partial" in kwargs and kwargs["partial"]:
            raise ValueError("HDF5 maps are never explicitly indexed")

        if len(args) > 4:
            if "hdu" in kwargs:
                raise ValueError("'hdu' defined twice")
            kwargs["hdu"] = args[4]
        if "hdu" in kwargs and kwargs["hdu"] != 1:
            raise ValueError("HDF5 maps do not have HDUs")

        if len(args) > 5:
            if "h" in kwargs:
                raise ValueError("'h' defined twice")
            kwargs["h"] = args[5]

        if len(args) > 6:
            if "verbose" in kwargs:
                raise ValueError("'verbose' defined twice")
            kwargs["verbose"] = args[6]
        if "verbose" in kwargs:
            verbose = kwargs["verbose"]
        else:
            # healpy default
            verbose = True

        if len(args) > 7:
            if "memmap" in kwargs:
                raise ValueError("'memmap' defined twice")
            kwargs["memmap"] = args[7]
        if "memmap" in kwargs and kwargs["memmap"]:
            raise ValueError("HDF5 maps do not have explicit memmap")

        # Load an HDF5 map
        try:
            f = h5py.File(filename, "r")
        except OSError as e:
            msg = f"Failed to open {filename} for reading: {e}"
            raise RuntimeError(msg)

        dset = f["map"]
        if "field" in kwargs and kwargs["field"] is not None:
            mapdata = []
            for field in kwargs["field"]:
                mapdata.append(dset[field])
            mapdata = np.vstack(mapdata)
        else:
            mapdata = dset[:]

        header = dict(dset.attrs)
        if "ORDERING" not in header or header["ORDERING"] not in ["NESTED", "RING"]:
            raise RuntimeError("Cannot determine pixel ordering")
        if header["ORDERING"] == "NESTED" and nest == False:
            if verbose:
                print(f"\nReordering {filename} to RING")
            mapdata = hp.reorder(mapdata, n2r=True)
        elif header["ORDERING"] == "RING" and nest == True:
            if verbose:
                print(f"\nReordering {filename} to NESTED")
            mapdata = hp.reorder(mapdata, r2n=True)
        else:
            if verbose:
                print(f"\n{filename} is already {header['ORDERING']}")
        f.close()

        if "dtype" in kwargs and kwargs["dtype"] is not None:
            mapdata = mapdata.astype(kwargs["dtype"])

        if mapdata.shape[0] == 1:
            mapdata = mapdata[0]

        if "h" in kwargs and kwargs["h"] == True:
            result = mapdata, header
        else:
            result = mapdata
    else:
        msg = f"Could not ascertain file type for '{filename}'"
        raise RuntimeError(msg)

    return result

toast.pixels_io_healpix.write_healpix(filename, mapdata, nside_submap=16, *args, **kwargs)

Write a FITS or HDF5 map serially.

This writes the map data from a simple numpy array on the calling process.

Parameters:

Name Type Description Default
filename str

The path to the file.

required
mapdata array

The data array.

required
nside_submap int

The submap NSIDE, used for dataset chunking.

16

Returns:

Type Description

None

Source code in toast/pixels_io_healpix.py
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
@function_timer
def write_healpix(filename, mapdata, nside_submap=16, *args, **kwargs):
    """Write a FITS or HDF5 map serially.

    This writes the map data from a simple numpy array on the calling process.

    Args:
        filename (str):  The path to the file.
        mapdata (array):  The data array.
        nside_submap (int):  The submap NSIDE, used for dataset chunking.

    Returns:
        None

    """

    if filename_is_fits(filename):
        # Write a FITS map with healpy
        return hp.write_map(filename, mapdata, *args, **kwargs)

    elif filename_is_hdf5(filename):
        if len(args) != 0:
            raise ValueError("No positional arguments supported")

        # Write an HDF5 map
        mapdata = np.atleast_2d(mapdata)
        n_value, n_pix = mapdata.shape
        nside = hp.npix2nside(n_pix)

        nside_submap = min(nside_submap, nside)
        n_pix_submap = 12 * nside_submap**2

        mode = "w-"
        if "overwrite" in kwargs and kwargs["overwrite"] == True:
            mode = "w"
        elif os.path.isfile(filename):
            raise FileExistsError(f"'{filename}' exists and `overwrite` is False")

        dtype = mapdata.dtype
        if "dtype" in kwargs and kwargs["dtype"] is not None:
            dtype = kwargs["dtype"]

        if "fits_IDL" in kwargs and kwargs["fits_IDL"]:
            raise ValueError("HDF5 does not support fits_IDL")

        if "partial" in kwargs and kwargs["partial"]:
            raise ValueError("HDF5 does not support partial; map is always chunked.")

        if "column_names" in kwargs and kwargs["column_names"] is not None:
            raise ValueError("HDF5 does not support column_names")

        ordering = "RING"
        if "nest" in kwargs and kwargs["nest"] == True:
            ordering = "NESTED"

        coord = None
        if "coord" in kwargs:
            coord = kwargs["coord"]

        units = None
        if "column_units" in kwargs:
            units = kwargs["column_units"]
            # Only one units attribute is supported
            if not isinstance(units, str):
                msg = f"ERROR: HDF5 map units must be a single string, "
                msg += f"not {units}"
                raise RuntimeError(msg)

        with h5py.File(filename, mode) as f:
            dset = f.create_dataset(
                "map",
                (n_value, n_pix),
                chunks=(n_value, n_pix_submap),
                dtype=dtype,
            )
            dset[:] = mapdata

            if "extra_header" in kwargs:
                header = kwargs["extra_header"]
                for key, value in header:
                    dset.attrs[key] = value

            dset.attrs["ORDERING"] = ordering
            dset.attrs["NSIDE"] = nside
            if units is not None:
                dset.attrs["UNITS"] = units
            if coord is not None:
                dset.attrs["COORDSYS"] = coord

    return

toast.pixels_io_wcs.write_wcs_fits(pix, path, comm_bytes=10000000, report_memory=False)

Write pixel data to a FITS image

The data across all processes is assumed to be synchronized (the data for a given submap shared between processes is identical). The submap data is sent to the root process which writes it out.

Parameters:

Name Type Description Default
pix PixelData

The distributed pixel object.

required
path str

The path to the output FITS file.

required
comm_bytes int

The approximate message size to use.

10000000
report_memory bool

Report the amount of available memory on the root node just before writing out the map.

False

Returns:

Type Description

None

Source code in toast/pixels_io_wcs.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
@function_timer
def write_wcs_fits(pix, path, comm_bytes=10000000, report_memory=False):
    """Write pixel data to a FITS image

    The data across all processes is assumed to be synchronized (the data for a given
    submap shared between processes is identical).  The submap data is sent to the root
    process which writes it out.

    Args:
        pix (PixelData): The distributed pixel object.
        path (str): The path to the output FITS file.
        comm_bytes (int): The approximate message size to use.
        report_memory (bool): Report the amount of available memory on the root
            node just before writing out the map.

    Returns:
        None

    """
    log = Logger.get()
    timer = Timer()
    timer.start()

    # The distribution
    dist = pix.distribution

    # Check that we have WCS information
    if not hasattr(dist, "wcs"):
        raise RuntimeError("Pixel distribution does not have WCS information")

    rank = 0
    if dist.comm is not None:
        rank = dist.comm.rank

    image = collect_wcs_submaps(pix, comm_bytes=comm_bytes)

    if rank == 0:
        if os.path.isfile(path):
            os.remove(path)
        # Basic wcs header
        header = dist.wcs.to_header(relax=True)
        # Add map dimensions
        header["NAXIS"] = image.ndim
        for i, n in enumerate(image.shape[::-1]):
            header[f"NAXIS{i+1}"] = n
        # Add units
        header["BUNIT"] = str(pix.units)
        hdus = af.HDUList([af.PrimaryHDU(image, header)])
        hdus.writeto(path)

    del image
    return

toast.pixels_io_wcs.read_wcs_fits(pix, path, ext=0, comm_bytes=10000000)

Read and broadcast pixel data stored in a FITS image.

The root process opens the FITS file and broadcasts the data in units of the submap size.

Parameters:

Name Type Description Default
pix PixelData

The distributed PixelData object.

required
path str

The path to the FITS file.

required
ext (int, str)

Then index or name of the FITS image extension to load.

0
comm_bytes int

The approximate message size to use in bytes.

10000000

Returns:

Type Description

None

Source code in toast/pixels_io_wcs.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
@function_timer
def read_wcs_fits(pix, path, ext=0, comm_bytes=10000000):
    """Read and broadcast pixel data stored in a FITS image.

    The root process opens the FITS file and broadcasts the data in units
    of the submap size.

    Args:
        pix (PixelData): The distributed PixelData object.
        path (str): The path to the FITS file.
        ext (int, str): Then index or name of the FITS image extension to load.
        comm_bytes (int): The approximate message size to use in bytes.

    Returns:
        None

    """
    log = Logger.get()
    dist = pix.distribution
    rank = 0
    if dist.comm is not None:
        rank = dist.comm.rank

    image = None
    fscale = 1.0
    if rank == 0:
        # Separately read the units.
        with af.open(path, mode="readonly") as hdul:
            if "BUNIT" in hdul[0].header:
                if hdul[0].header["BUNIT"] == "":
                    funits = u.dimensionless_unscaled
                else:
                    funits = u.Unit(hdul[0].header["BUNIT"])
            else:
                msg = f"Pixel data in {path} does not have BUNIT key.  "
                msg += f"Assuming {pix.units}."
                log.warning(msg)
                funits = pix.units
            if funits != pix.units:
                scale = 1.0 * funits
                scale.to(pix.units)
                fscale = scale.value
            image = np.array(hdul[0].data)

        # Check dimensions
        impix = 1
        for s in image.shape:
            impix *= s
        tot_pix = dist.n_pix * pix.n_value
        if tot_pix != impix:
            raise RuntimeError(
                f"Input file has {impix} pixel values instead of {tot_pix}"
            )

    n_val_submap = dist.n_pix_submap * pix.n_value

    if dist.comm is None:
        # Single process, just copy into place
        for sm in range(dist.n_submap):
            if sm in dist.local_submaps:
                loc = dist.global_submap_to_local[sm]
                image_to_submap(dist, image, sm, pix.data[loc], scale=fscale)
    else:
        # One reader broadcasts
        fscale = dist.comm.bcast(fscale, root=0)
        comm_submap = pix.comm_nsubmap(comm_bytes)

        buf = np.zeros(comm_submap * n_val_submap, dtype=pix.dtype)
        view = buf.reshape(comm_submap, dist.n_pix_submap, pix.n_value)
        submap_off = 0
        ncomm = comm_submap
        while submap_off < dist.n_submap:
            if submap_off + ncomm > dist.n_submap:
                ncomm = dist.n_submap - submap_off
            if rank == 0:
                # Fill the bcast buffer
                for c in range(ncomm):
                    image_to_submap(
                        dist, image, (submap_off + c), view[c], scale=fscale
                    )
            # Broadcast
            dist.comm.Bcast(buf, root=0)
            # Copy these submaps into local data
            for sm in range(submap_off, submap_off + ncomm):
                if sm in dist.local_submaps:
                    loc = dist.global_submap_to_local[sm]
                    pix.data[loc, :, :] = view[sm - submap_off, :, :]
            submap_off += comm_submap
            buf.fill(0)

    return