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. PixelData objects have methods to read and write HDF5 and FITS format files.

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
 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
417
418
419
420
421
422
423
424
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
134
135
def __del__(self):
    self.clear()

__eq__(other)

Source code in toast/pixels.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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
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
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
118
119
def __ne__(self, other):
    return not self.__eq__(other)

__repr__()

Source code in toast/pixels.py
229
230
231
232
233
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
411
412
def _accel_create(self):
    self._glob2loc = accel_data_create(self._glob2loc, self._accel_name)

_accel_delete()

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

_accel_exists()

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

_accel_reset()

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

_accel_update_device()

Source code in toast/pixels.py
414
415
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
417
418
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
121
122
123
124
125
126
127
128
129
130
131
132
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
@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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
@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
 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
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
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 Exception:
                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)

        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 _write_wcs(
        self,
        path,
        comm_bytes=10000000,
        report_memory=False,
        single_precision=False,
    ):
        """Write distributed PixelData to a WCS file.

        The output will be written to a WCS file in either FITS or HDF5 (determined
        by the path filename suffix).

        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:
            path (str): The path to the output WCS file (FITS or HDF5).
            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): If True, write floats and integers in single
                precision.

        Returns:
            None

        """
        log = Logger.get()

        # The distribution
        dist = self.distribution
        rank = 0
        if dist.comm is not None:
            rank = dist.comm.rank

        # For both FITS and HDF5 formats, this type of pixel
        # data is always serialized to the root process for writing.
        image = collect_wcs_submaps(self, comm_bytes=comm_bytes)

        if rank == 0:
            dtype = None
            if single_precision:
                if image.dtype == np.dtype(np.float64):
                    dtype = np.float32
                elif image.dtype == np.dtype(np.int32):
                    dtype = np.int32
            if report_memory:
                mem = memreport(msg="(root node)", silent=True)
                log.info(f"About to write {path}:  {mem}")
            write_wcs(path, image, dist.wcs, self.units, dtype=dtype)
        del image

    def _write_healpix_fits(
        self,
        path,
        comm_bytes=10000000,
        report_memory=False,
        single_precision=False,
    ):
        """Write distributed PixelData to a healpix FITS file.

        Args:
            path (str): The path to the output WCS file (FITS or HDF5).
            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): If True, write floats and integers in single
                precision.

        Returns:
            None

        """
        log = Logger.get()

        # The distribution
        dist = self.distribution
        rank = 0
        if dist.comm is not None:
            rank = dist.comm.rank

        # Healpix PixelDistribution should have the nest information.
        nest = dist.nest

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

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

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

    def _write_healpix_hdf5(
        self,
        path,
        comm_bytes=10000000,
        report_memory=False,
        single_precision=False,
        force_serial=True,
    ):
        """Write distributed PixelData to a healpix HDF5 file.

        Args:
            path (str): The path to the output WCS file (FITS or HDF5).
            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): If True, write floats and integers in single
                precision.
            force_serial (bool): If True, use serial I/O, even if the HDF5
                implementation is built with MPI.

        Returns:
            None

        """
        log = Logger.get()

        # The distribution
        dist = self.distribution
        rank = 0
        nproc = 1
        if dist.comm is not None:
            rank = dist.comm.rank
            nproc = dist.comm.size

        # Healpix PixelDistribution should have the nest information.
        nest = dist.nest

        # When writing to healpix HDF5 format, we have the option to write
        # submaps in parallel.  This is a substantial performance boost when
        # dealing with many processes and large maps.

        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(self.units)

        dtype = self.dtype
        if single_precision:
            if dtype == np.dtype(np.float64):
                dtype = np.float32
            elif dtype == np.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",
                    (self.n_value, dist.n_pix),
                    chunks=(self.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] = self.data[
                            local_submap, 0 : last - first
                        ].T
        else:
            # No luck, write serially from root process
            if use_mpi and not force_serial:
                # 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, self.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] = self.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",
                        (self.n_value, dist.n_pix),
                        chunks=(self.n_value, dist.n_pix_submap),
                        dtype=dtype,
                    )
                    for rank_send in range(nproc):
                        # 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,
                                        self.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)

    def _write_healpix(
        self,
        path,
        comm_bytes=10000000,
        report_memory=False,
        single_precision=False,
        force_serial=True,
    ):
        """Write distributed PixelData to a healpix file.

        The output format (FITS or HDF5) is determined by the filename suffix.

        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:
            path (str): The path to the output WCS file (FITS or HDF5).
            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): If True, write floats and integers in single
                precision.
            force_serial (bool): If True, use serial I/O, even if the HDF5
                implementation is built with MPI.

        Returns:
            None

        """
        if filename_is_fits(path):
            self._write_healpix_fits(
                path,
                comm_bytes=comm_bytes,
                report_memory=report_memory,
                single_precision=single_precision,
            )
        elif filename_is_hdf5(path):
            self._write_healpix_hdf5(
                path,
                comm_bytes=comm_bytes,
                report_memory=report_memory,
                single_precision=single_precision,
                force_serial=force_serial,
            )
        else:
            msg = f"Could not determine file type for '{path}'"
            raise RuntimeError(msg)

    @function_timer
    def write(
        self,
        path,
        comm_bytes=10000000,
        report_memory=False,
        single_precision=False,
        force_serial=True,
    ):
        """Write distributed PixelData to a file.

        If the internal PixelDistribution has a WCS object, then the output will be
        written to a WCS file in either FITS or HDF5 (determined by the `path`).

        If the PixelDistribution has a 'nest' member, a Healpix file is written
        in either FITS or HDF5 format.

        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:
            path (str): The path to the output WCS file (FITS or HDF5).
            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): If True, write floats and integers in single
                precision.
            force_serial (bool): If True, use serial I/O, even if the HDF5
                implementation is built with MPI.

        Returns:
            None

        """
        dist = self.distribution

        # Check if we have WCS information
        if hasattr(dist, "wcs"):
            self._write_wcs(
                path,
                comm_bytes=comm_bytes,
                report_memory=report_memory,
                single_precision=single_precision,
            )
        elif hasattr(dist, "nest"):
            self._write_healpix(
                path,
                comm_bytes=comm_bytes,
                report_memory=report_memory,
                single_precision=single_precision,
                force_serial=force_serial,
            )
        else:
            msg = "Could not determine pixelization type.  PixelDistribution"
            msg += " does not have 'wcs' or 'nest' members."
            raise RuntimeError(msg)

    def _read_wcs(self, path, comm_bytes=10000000):
        """Read distributed PixelData from a WCS file.

        The input path should be a WCS file in either FITS or HDF5 (determined by
        the suffix).

        Args:
            path (str): The path to the input WCS file (FITS or HDF5).
            comm_bytes (int): The approximate message size to use.

        Returns:
            None

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

        image = None
        fscale = 1.0
        if rank == 0:
            image, funits = read_wcs(path, units=True)
            if funits is None:
                msg = f"Pixel data in {path} does not have BUNIT key.  "
                msg += f"Assuming {self.units}."
                funits = self.units
            elif funits != self.units:
                scale = 1.0 * funits
                scale.to(self.units)
                fscale = scale.value

            # Check dimensions
            impix = np.prod(image.shape)
            tot_pix = dist.n_pix * self.n_value
            if tot_pix != impix:
                raise RuntimeError(
                    f"Input file has {impix} pixel values instead of {tot_pix}"
                )
        broadcast_image(image, fscale, self, comm_bytes)

    def _read_healpix_fits(self, path, comm_bytes=10000000):
        """Read distributed PixelData from a healpix FITS file.

        Args:
            path (str): The path to the input healpix FITS file.
            comm_bytes (int): The approximate message size to use.

        Returns:
            None

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

        # Healpix PixelDistribution should have the nest information.
        nest = dist.nest

        # We have Healpix data
        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 = 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 '{self.units}'."
                log.info(msg)
                funits = self.units
            if funits != self.units:
                fscale = unit_conversion(funits, self.units)
            if nside_map != nside:
                errors += f"Wrong NSide: {path} has {nside_map}, expected {nside}\n"
            map_nnz = h[1].header["tfields"]
            h.close()
            if self.n_value == 2:
                if map_nnz < 3:
                    errors += f"Wrong number of columns: {path} has {map_nnz}, "
                    errors += f"expected at least 3\n"
                # Skip I and read QU
                field = (1, 2)
            else:
                if map_nnz < self.n_value:
                    errors += f"Wrong number of columns: {path} has {map_nnz}, "
                    errors += f"expected at least {self.n_value}\n"
                field = tuple(np.arange(self.n_value))
            if len(errors) != 0:
                raise RuntimeError(errors)
            # Now read the map
            fdata = hp.read_map(
                path,
                field=field,
                dtype=[self.dtype for x in range(self.n_value)],
                memmap=True,
                nest=nest,
            )
            if self.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 * self.n_value, dtype=self.dtype)
        view = buf.reshape(comm_submap, dist.n_pix_submap, self.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(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 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]
                        self.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]
                    self.data[loc, :, :] = fscale * view[sm - submap_off, :, :]

    def _read_healpix_hdf5(self, path, comm_bytes=10000000):
        """Read distributed PixelData from a healpix HDF5 file.

        Args:
            path (str): The path to the input healpix HDF5 file.
            comm_bytes (int): The approximate message size to use.

        Returns:
            None

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

        # Healpix PixelDistribution should have the nest information.
        nest = dist.nest

        # We have Healpix data
        comm_submap = self.comm_nsubmap(comm_bytes)

        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.  "
                msg += f"Assuming {self.units}."
                log.info(msg)
                funits = self.units
            if funits != self.units:
                scale = 1.0 * funits
                scale.to(self.units)
                fscale = scale.value

            nnz, npix = dset.shape
            if nnz < self.n_value:
                msg = f"Map in {path} has {nnz} columns but we "
                msg += f"require {self.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 * self.n_value * dist.n_pix_submap, dtype=self.dtype)
        view = buf.reshape(comm_submap, self.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 : self.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]
                    self.data[loc] = fscale * view[i].T

            submap_offset = submap_last
        if rank == 0:
            f.close()

    def _read_healpix(self, path, comm_bytes=10000000):
        """Read distributed PixelData from a healpix file.

        Args:
            path (str): The path to the input healpix file (FITS or HDF5).
            comm_bytes (int): The approximate message size to use.

        Returns:
            None

        """
        if filename_is_fits(path):
            # FITS format
            self._read_healpix_fits(path, comm_bytes=comm_bytes)
        elif filename_is_hdf5(path):
            # HDF5 Format
            self._read_healpix_hdf5(path, comm_bytes=comm_bytes)
        else:
            msg = f"Could not determine file type for '{path}'"
            raise RuntimeError(msg)

    @function_timer
    def read(
        self,
        path,
        comm_bytes=10000000,
    ):
        """Read distributed PixelData from a file.

        If the internal PixelDistribution has a WCS object, then the input should be
        a WCS file in either FITS or HDF5 (determined by the `path`).

        If no WCS object exists in the PixelDistribution, a Healpix file is loaded
        in either FITS or HDF5 format.  The NEST or RING ordering is determined by
        the PixelDistribution.nest member.

        Args:
            path (str): The path to the output WCS file (FITS or HDF5).
            comm_bytes (int): The approximate message size to use.

        Returns:
            None

        """
        dist = self.distribution

        # Check if we have WCS information
        if hasattr(dist, "wcs"):
            # We have WCS data.
            self._read_wcs(path, comm_bytes=comm_bytes)
        elif hasattr(dist, "nest"):
            self._read_healpix(path, comm_bytes=comm_bytes)
        else:
            msg = "Could not determine pixelization type.  PixelDistribution"
            msg += " does not have 'wcs' or 'nest' members."
            raise RuntimeError(msg)

    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
565
566
def __del__(self):
    self.clear()

__delitem__(key)

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

__eq__(other)

Source code in toast/pixels.py
622
623
624
625
626
627
628
629
630
631
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
598
599
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
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
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
608
609
def __iter__(self):
    return iter(self.data)

__len__()

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

__ne__(other)

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

__repr__()

Source code in toast/pixels.py
614
615
616
617
618
619
620
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
605
606
def __setitem__(self, key, value):
    self.data[key] = value

_accel_create(zero_out=False)

Source code in toast/pixels.py
1925
1926
1927
1928
1929
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
1949
1950
1951
1952
1953
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
1917
1918
1919
1920
1921
1922
1923
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
1943
1944
1945
1946
1947
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
1931
1932
1933
1934
1935
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
1937
1938
1939
1940
1941
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)

_read_healpix(path, comm_bytes=10000000)

Read distributed PixelData from a healpix file.

Parameters:

Name Type Description Default
path str

The path to the input healpix file (FITS or HDF5).

required
comm_bytes int

The approximate message size to use.

10000000

Returns:

Type Description

None

Source code in toast/pixels.py
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
def _read_healpix(self, path, comm_bytes=10000000):
    """Read distributed PixelData from a healpix file.

    Args:
        path (str): The path to the input healpix file (FITS or HDF5).
        comm_bytes (int): The approximate message size to use.

    Returns:
        None

    """
    if filename_is_fits(path):
        # FITS format
        self._read_healpix_fits(path, comm_bytes=comm_bytes)
    elif filename_is_hdf5(path):
        # HDF5 Format
        self._read_healpix_hdf5(path, comm_bytes=comm_bytes)
    else:
        msg = f"Could not determine file type for '{path}'"
        raise RuntimeError(msg)

_read_healpix_fits(path, comm_bytes=10000000)

Read distributed PixelData from a healpix FITS file.

Parameters:

Name Type Description Default
path str

The path to the input healpix FITS file.

required
comm_bytes int

The approximate message size to use.

10000000

Returns:

Type Description

None

Source code in toast/pixels.py
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
def _read_healpix_fits(self, path, comm_bytes=10000000):
    """Read distributed PixelData from a healpix FITS file.

    Args:
        path (str): The path to the input healpix FITS file.
        comm_bytes (int): The approximate message size to use.

    Returns:
        None

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

    # Healpix PixelDistribution should have the nest information.
    nest = dist.nest

    # We have Healpix data
    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 = 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 '{self.units}'."
            log.info(msg)
            funits = self.units
        if funits != self.units:
            fscale = unit_conversion(funits, self.units)
        if nside_map != nside:
            errors += f"Wrong NSide: {path} has {nside_map}, expected {nside}\n"
        map_nnz = h[1].header["tfields"]
        h.close()
        if self.n_value == 2:
            if map_nnz < 3:
                errors += f"Wrong number of columns: {path} has {map_nnz}, "
                errors += f"expected at least 3\n"
            # Skip I and read QU
            field = (1, 2)
        else:
            if map_nnz < self.n_value:
                errors += f"Wrong number of columns: {path} has {map_nnz}, "
                errors += f"expected at least {self.n_value}\n"
            field = tuple(np.arange(self.n_value))
        if len(errors) != 0:
            raise RuntimeError(errors)
        # Now read the map
        fdata = hp.read_map(
            path,
            field=field,
            dtype=[self.dtype for x in range(self.n_value)],
            memmap=True,
            nest=nest,
        )
        if self.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 * self.n_value, dtype=self.dtype)
    view = buf.reshape(comm_submap, dist.n_pix_submap, self.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(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 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]
                    self.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]
                self.data[loc, :, :] = fscale * view[sm - submap_off, :, :]

_read_healpix_hdf5(path, comm_bytes=10000000)

Read distributed PixelData from a healpix HDF5 file.

Parameters:

Name Type Description Default
path str

The path to the input healpix HDF5 file.

required
comm_bytes int

The approximate message size to use.

10000000

Returns:

Type Description

None

Source code in toast/pixels.py
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
def _read_healpix_hdf5(self, path, comm_bytes=10000000):
    """Read distributed PixelData from a healpix HDF5 file.

    Args:
        path (str): The path to the input healpix HDF5 file.
        comm_bytes (int): The approximate message size to use.

    Returns:
        None

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

    # Healpix PixelDistribution should have the nest information.
    nest = dist.nest

    # We have Healpix data
    comm_submap = self.comm_nsubmap(comm_bytes)

    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.  "
            msg += f"Assuming {self.units}."
            log.info(msg)
            funits = self.units
        if funits != self.units:
            scale = 1.0 * funits
            scale.to(self.units)
            fscale = scale.value

        nnz, npix = dset.shape
        if nnz < self.n_value:
            msg = f"Map in {path} has {nnz} columns but we "
            msg += f"require {self.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 * self.n_value * dist.n_pix_submap, dtype=self.dtype)
    view = buf.reshape(comm_submap, self.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 : self.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]
                self.data[loc] = fscale * view[i].T

        submap_offset = submap_last
    if rank == 0:
        f.close()

_read_wcs(path, comm_bytes=10000000)

Read distributed PixelData from a WCS file.

The input path should be a WCS file in either FITS or HDF5 (determined by the suffix).

Parameters:

Name Type Description Default
path str

The path to the input WCS file (FITS or HDF5).

required
comm_bytes int

The approximate message size to use.

10000000

Returns:

Type Description

None

Source code in toast/pixels.py
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
def _read_wcs(self, path, comm_bytes=10000000):
    """Read distributed PixelData from a WCS file.

    The input path should be a WCS file in either FITS or HDF5 (determined by
    the suffix).

    Args:
        path (str): The path to the input WCS file (FITS or HDF5).
        comm_bytes (int): The approximate message size to use.

    Returns:
        None

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

    image = None
    fscale = 1.0
    if rank == 0:
        image, funits = read_wcs(path, units=True)
        if funits is None:
            msg = f"Pixel data in {path} does not have BUNIT key.  "
            msg += f"Assuming {self.units}."
            funits = self.units
        elif funits != self.units:
            scale = 1.0 * funits
            scale.to(self.units)
            fscale = scale.value

        # Check dimensions
        impix = np.prod(image.shape)
        tot_pix = dist.n_pix * self.n_value
        if tot_pix != impix:
            raise RuntimeError(
                f"Input file has {impix} pixel values instead of {tot_pix}"
            )
    broadcast_image(image, fscale, self, comm_bytes)

_write_healpix(path, comm_bytes=10000000, report_memory=False, single_precision=False, force_serial=True)

Write distributed PixelData to a healpix file.

The output format (FITS or HDF5) is determined by the filename suffix.

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
path str

The path to the output WCS file (FITS or HDF5).

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
single_precision bool

If True, write floats and integers in single precision.

False
force_serial bool

If True, use serial I/O, even if the HDF5 implementation is built with MPI.

True

Returns:

Type Description

None

Source code in toast/pixels.py
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
def _write_healpix(
    self,
    path,
    comm_bytes=10000000,
    report_memory=False,
    single_precision=False,
    force_serial=True,
):
    """Write distributed PixelData to a healpix file.

    The output format (FITS or HDF5) is determined by the filename suffix.

    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:
        path (str): The path to the output WCS file (FITS or HDF5).
        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): If True, write floats and integers in single
            precision.
        force_serial (bool): If True, use serial I/O, even if the HDF5
            implementation is built with MPI.

    Returns:
        None

    """
    if filename_is_fits(path):
        self._write_healpix_fits(
            path,
            comm_bytes=comm_bytes,
            report_memory=report_memory,
            single_precision=single_precision,
        )
    elif filename_is_hdf5(path):
        self._write_healpix_hdf5(
            path,
            comm_bytes=comm_bytes,
            report_memory=report_memory,
            single_precision=single_precision,
            force_serial=force_serial,
        )
    else:
        msg = f"Could not determine file type for '{path}'"
        raise RuntimeError(msg)

_write_healpix_fits(path, comm_bytes=10000000, report_memory=False, single_precision=False)

Write distributed PixelData to a healpix FITS file.

Parameters:

Name Type Description Default
path str

The path to the output WCS file (FITS or HDF5).

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
single_precision bool

If True, write floats and integers in single precision.

False

Returns:

Type Description

None

Source code in toast/pixels.py
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
def _write_healpix_fits(
    self,
    path,
    comm_bytes=10000000,
    report_memory=False,
    single_precision=False,
):
    """Write distributed PixelData to a healpix FITS file.

    Args:
        path (str): The path to the output WCS file (FITS or HDF5).
        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): If True, write floats and integers in single
            precision.

    Returns:
        None

    """
    log = Logger.get()

    # The distribution
    dist = self.distribution
    rank = 0
    if dist.comm is not None:
        rank = dist.comm.rank

    # Healpix PixelDistribution should have the nest information.
    nest = dist.nest

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

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

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

_write_healpix_hdf5(path, comm_bytes=10000000, report_memory=False, single_precision=False, force_serial=True)

Write distributed PixelData to a healpix HDF5 file.

Parameters:

Name Type Description Default
path str

The path to the output WCS file (FITS or HDF5).

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
single_precision bool

If True, write floats and integers in single precision.

False
force_serial bool

If True, use serial I/O, even if the HDF5 implementation is built with MPI.

True

Returns:

Type Description

None

Source code in toast/pixels.py
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
def _write_healpix_hdf5(
    self,
    path,
    comm_bytes=10000000,
    report_memory=False,
    single_precision=False,
    force_serial=True,
):
    """Write distributed PixelData to a healpix HDF5 file.

    Args:
        path (str): The path to the output WCS file (FITS or HDF5).
        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): If True, write floats and integers in single
            precision.
        force_serial (bool): If True, use serial I/O, even if the HDF5
            implementation is built with MPI.

    Returns:
        None

    """
    log = Logger.get()

    # The distribution
    dist = self.distribution
    rank = 0
    nproc = 1
    if dist.comm is not None:
        rank = dist.comm.rank
        nproc = dist.comm.size

    # Healpix PixelDistribution should have the nest information.
    nest = dist.nest

    # When writing to healpix HDF5 format, we have the option to write
    # submaps in parallel.  This is a substantial performance boost when
    # dealing with many processes and large maps.

    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(self.units)

    dtype = self.dtype
    if single_precision:
        if dtype == np.dtype(np.float64):
            dtype = np.float32
        elif dtype == np.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",
                (self.n_value, dist.n_pix),
                chunks=(self.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] = self.data[
                        local_submap, 0 : last - first
                    ].T
    else:
        # No luck, write serially from root process
        if use_mpi and not force_serial:
            # 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, self.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] = self.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",
                    (self.n_value, dist.n_pix),
                    chunks=(self.n_value, dist.n_pix_submap),
                    dtype=dtype,
                )
                for rank_send in range(nproc):
                    # 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,
                                    self.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)

_write_wcs(path, comm_bytes=10000000, report_memory=False, single_precision=False)

Write distributed PixelData to a WCS file.

The output will be written to a WCS file in either FITS or HDF5 (determined by the path filename suffix).

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
path str

The path to the output WCS file (FITS or HDF5).

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
single_precision bool

If True, write floats and integers in single precision.

False

Returns:

Type Description

None

Source code in toast/pixels.py
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
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
def _write_wcs(
    self,
    path,
    comm_bytes=10000000,
    report_memory=False,
    single_precision=False,
):
    """Write distributed PixelData to a WCS file.

    The output will be written to a WCS file in either FITS or HDF5 (determined
    by the path filename suffix).

    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:
        path (str): The path to the output WCS file (FITS or HDF5).
        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): If True, write floats and integers in single
            precision.

    Returns:
        None

    """
    log = Logger.get()

    # The distribution
    dist = self.distribution
    rank = 0
    if dist.comm is not None:
        rank = dist.comm.rank

    # For both FITS and HDF5 formats, this type of pixel
    # data is always serialized to the root process for writing.
    image = collect_wcs_submaps(self, comm_bytes=comm_bytes)

    if rank == 0:
        dtype = None
        if single_precision:
            if image.dtype == np.dtype(np.float64):
                dtype = np.float32
            elif image.dtype == np.dtype(np.int32):
                dtype = np.int32
        if report_memory:
            mem = memreport(msg="(root node)", silent=True)
            log.info(f"About to write {path}:  {mem}")
        write_wcs(path, image, dist.wcs, self.units, dtype=dtype)
    del image

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
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
@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
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
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
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
636
637
638
639
640
641
642
643
644
645
646
647
648
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
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
@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)

    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
766
767
768
769
770
771
772
773
774
@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

read(path, comm_bytes=10000000)

Read distributed PixelData from a file.

If the internal PixelDistribution has a WCS object, then the input should be a WCS file in either FITS or HDF5 (determined by the path).

If no WCS object exists in the PixelDistribution, a Healpix file is loaded in either FITS or HDF5 format. The NEST or RING ordering is determined by the PixelDistribution.nest member.

Parameters:

Name Type Description Default
path str

The path to the output WCS file (FITS or HDF5).

required
comm_bytes int

The approximate message size to use.

10000000

Returns:

Type Description

None

Source code in toast/pixels.py
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
@function_timer
def read(
    self,
    path,
    comm_bytes=10000000,
):
    """Read distributed PixelData from a file.

    If the internal PixelDistribution has a WCS object, then the input should be
    a WCS file in either FITS or HDF5 (determined by the `path`).

    If no WCS object exists in the PixelDistribution, a Healpix file is loaded
    in either FITS or HDF5 format.  The NEST or RING ordering is determined by
    the PixelDistribution.nest member.

    Args:
        path (str): The path to the output WCS file (FITS or HDF5).
        comm_bytes (int): The approximate message size to use.

    Returns:
        None

    """
    dist = self.distribution

    # Check if we have WCS information
    if hasattr(dist, "wcs"):
        # We have WCS data.
        self._read_wcs(path, comm_bytes=comm_bytes)
    elif hasattr(dist, "nest"):
        self._read_healpix(path, comm_bytes=comm_bytes)
    else:
        msg = "Could not determine pixelization type.  PixelDistribution"
        msg += " does not have 'wcs' or 'nest' members."
        raise RuntimeError(msg)

reset()

Set memory to zero

Source code in toast/pixels.py
568
569
570
571
572
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
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
@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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
@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
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
@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 Exception:
            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
 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
@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
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
@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
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
@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
594
595
596
def update_units(self, new_units):
    """Update the units associated with the data."""
    self._units = new_units

write(path, comm_bytes=10000000, report_memory=False, single_precision=False, force_serial=True)

Write distributed PixelData to a file.

If the internal PixelDistribution has a WCS object, then the output will be written to a WCS file in either FITS or HDF5 (determined by the path).

If the PixelDistribution has a 'nest' member, a Healpix file is written in either FITS or HDF5 format.

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
path str

The path to the output WCS file (FITS or HDF5).

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
single_precision bool

If True, write floats and integers in single precision.

False
force_serial bool

If True, use serial I/O, even if the HDF5 implementation is built with MPI.

True

Returns:

Type Description

None

Source code in toast/pixels.py
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
@function_timer
def write(
    self,
    path,
    comm_bytes=10000000,
    report_memory=False,
    single_precision=False,
    force_serial=True,
):
    """Write distributed PixelData to a file.

    If the internal PixelDistribution has a WCS object, then the output will be
    written to a WCS file in either FITS or HDF5 (determined by the `path`).

    If the PixelDistribution has a 'nest' member, a Healpix file is written
    in either FITS or HDF5 format.

    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:
        path (str): The path to the output WCS file (FITS or HDF5).
        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): If True, write floats and integers in single
            precision.
        force_serial (bool): If True, use serial I/O, even if the HDF5
            implementation is built with MPI.

    Returns:
        None

    """
    dist = self.distribution

    # Check if we have WCS information
    if hasattr(dist, "wcs"):
        self._write_wcs(
            path,
            comm_bytes=comm_bytes,
            report_memory=report_memory,
            single_precision=single_precision,
        )
    elif hasattr(dist, "nest"):
        self._write_healpix(
            path,
            comm_bytes=comm_bytes,
            report_memory=report_memory,
            single_precision=single_precision,
            force_serial=force_serial,
        )
    else:
        msg = "Could not determine pixelization type.  PixelDistribution"
        msg += " does not have 'wcs' or 'nest' members."
        raise RuntimeError(msg)

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(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
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
@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
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 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(filename, image, wcs, units=None, dtype=None)

Write a FITS or HDF5 WCS map on the calling process

Parameters:

Name Type Description Default
filename str

The path to the file

required
image ndarray

2 or 3-dimensional image

required
wcs WCS

The World Coordinate System

required
units str

Image units

None

Returns:

Type Description

None

Source code in toast/pixels_io_wcs.py
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
@function_timer
def write_wcs(filename, image, wcs, units=None, dtype=None):
    """Write a FITS or HDF5 WCS map on the calling process

    Args:
        filename (str):  The path to the file
        image (ndarray): 2 or 3-dimensional image
        wcs (astropy.WCS):  The World Coordinate System
        units (str):  Image units

    Returns:
        None
    """

    filename = filename.strip()
    if os.path.isfile(filename):
        os.remove(filename)

    # Basic wcs header
    header = wcs.to_header(relax=True)

    # Output units
    if dtype is None:
        dtype = image.dtype

    # Row-major to column major (FITS standanrd)
    # image = np.atleast_3d(image).transpose([0, 2, 1]).astype(dtype)
    image = np.atleast_3d(image).astype(dtype)

    if filename_is_fits(filename):
        # Add map dimensions
        header["NAXIS"] = image.ndim
        for i, n in enumerate(image.shape[::-1]):
            header[f"NAXIS{i + 1}"] = n
        if units is not None:
            # Add units
            header["BUNIT"] = str(units)
        hdus = af.HDUList([af.PrimaryHDU(image, header)])
        hdus.writeto(filename)
        del hdus
    elif filename_is_hdf5(filename):
        with h5py.File(filename, "w") as hfile:
            hfile["data"] = image
            for key, value in header.items():
                hfile[f"wcs/{key}"] = value
            if units is not None:
                # Add units
                hfile["bunit"] = str(units)
    else:
        msg = f"Could not ascertain file type for '{filename}'"
        raise RuntimeError(msg)
    return

toast.pixels_io_wcs.read_wcs(filename, units=False, extension=0, dtype=None)

Read a FITS or HDF5 WCS 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
units bool

If True, return the units of the map

False

Returns:

Type Description
tuple

The map data and the appropriate astropy units.

Source code in toast/pixels_io_wcs.py
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
@function_timer
def read_wcs(filename, units=False, extension=0, dtype=None):
    """Read a FITS or HDF5 WCS 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.
        units (bool):  If True, return the units of the map

    Returns:
        (tuple):  The map data and the appropriate astropy units.

    """

    log = Logger.get()

    filename = filename.strip()
    funits = None

    if filename_is_fits(filename):
        # Load a FITS format image
        with af.open(filename, mode="readonly") as hdul:
            hdu = hdul[extension]
            image = np.array(hdu.data)
            if units and "BUNIT" in hdu.header:
                bunit = hdu.header["BUNIT"]
    elif filename_is_hdf5(filename):
        # Load an HDF5 format image
        with h5py.File(filename, "r") as hfile:
            image = np.array(hfile["data"][()])
            if units and "bunit" in hfile:
                # Separately read the units
                bunit = hfile["bunit"][()].decode()
    else:
        msg = f"Could not ascertain file type for '{filename}'"
        raise RuntimeError(msg)

    # Column-major to row major
    # image = np.transpose(image, [0, 2, 1]).astype(dtype)
    image = np.atleast_3d(image).astype(dtype)

    # Optionally parse units
    if units:
        if bunit == "":
            funits = u.dimensionless_unscaled
        else:
            try:
                funits = u.Unit(bunit)
            except ValueError as e:
                log.warning(f"WARNING: failed to parse units in {filename}:\n{e}")
        result = (image, funits)
    else:
        result = image

    return result