-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathdestriper.py
2078 lines (1755 loc) · 74.2 KB
/
destriper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- encoding: utf-8 -*-
import logging
import time
# The implementation of the destriping algorithm provided here is based on the paper
# «Destriping CMB temperature and polarization maps» by Kurki-Suonio et al. 2009,
# A&A 506, 1511–1539 (2009), https://dx.doi.org/10.1051/0004-6361/200912361
#
# It is important to have that paper at hand while reading this code, as many
# functions and variable defined here use the same letters and symbols of that
# paper. We refer to it in code comments and docstrings as "KurkiSuonio2009".
from dataclasses import dataclass
import gc
from pathlib import Path
import numpy as np
import numpy.typing as npt
from ducc0.healpix import Healpix_Base
from numba import njit, prange
import healpy as hp
from litebird_sim.mpi import MPI_ENABLED, MPI_COMM_WORLD
from typing import Union, List, Optional, Tuple, Any, Dict
from litebird_sim.observations import Observation
from litebird_sim.coordinates import CoordinateSystem, coord_sys_to_healpix_string
from .common import (
_compute_pixel_indices,
_normalize_observations_and_pointings,
COND_THRESHOLD,
get_map_making_weights,
cholesky,
solve_cholesky,
estimate_cond_number,
)
if MPI_ENABLED:
import mpi4py.MPI
__DESTRIPER_RESULTS_FILE_NAME = "destriper_results.fits"
__BASELINES_FILE_NAME = f"baselines_mpi{MPI_COMM_WORLD.rank:04d}.fits"
def _split_items_into_n_segments(n: int, num_of_segments: int) -> List[int]:
"""Divide a quantity `length` into chunks, each roughly of the same length
This low-level function is used to determine how many samples in a TOD should be
collected by the toast_destriper within the same baseline.
.. testsetup::
from litebird_sim.mapping import _split_items_into_n_segments
.. testcode::
# Divide 10 items into 4 groups, so that each of them will
# have roughly the same number of items
print(_split_items_into_n_segments(10, 4))
.. testoutput::
[2 3 2 3]
"""
assert num_of_segments > 0, f"num_of_segments={num_of_segments} is not positive"
assert (
n >= num_of_segments
), f"n={n} is smaller than num_of_segments={num_of_segments}"
start_positions = np.array(
[int(i * n / num_of_segments) for i in range(num_of_segments + 1)],
dtype="int",
)
return start_positions[1:] - start_positions[0:-1]
def split_items_evenly(n: int, sub_n: int) -> List[int]:
"""Evenly split `n` items into groups, each with roughly `sub_n` elements
.. testsetup::
from litebird_sim.mapping import split_items_evenly
.. testcode::
# Divide 10 items into groups, so that each of them will contain
# roughly 4 items
print(split_items_evenly(10, 4))
.. testoutput::
[3 3 4]
"""
assert sub_n > 0, "sub_n={0} is not positive".format(sub_n)
assert sub_n < n, "sub_n={0} is not smaller than n={1}".format(sub_n, n)
return _split_items_into_n_segments(n=n, num_of_segments=int(np.ceil(n / sub_n)))
@njit(parallel=True)
def _get_invnpp(
nobs_matrix_cholesky: npt.NDArray,
valid_pixel: npt.ArrayLike,
result: npt.NDArray,
):
npix = nobs_matrix_cholesky.shape[0]
for ipix in range(npix):
if not valid_pixel[ipix]:
result[ipix, :, :] = 0.0
continue
# We associate each coefficient of the i-th matrix in
# `nobs_matrix_cholesky` to the following variables:
#
# | a 0 0 |
# L = | b c 0 |
# | d e f |
a, b, c, d, e, f = nobs_matrix_cholesky[ipix, :]
# Computing the inverse of L is trivial, the result is
#
# | 1/a 0 0 |
# L⁻¹ = | −b/ac 1/c 0 |
# | (be − cd)/acf −e/cf 1/f |
#
# We assign its coefficients to the following letters:
#
# | g 0 0 |
# L⁻¹ = | h i 0 |
# | j k m |
g = 1 / a
h = -b / (a * c)
i = 1 / c
j = (b * e - c * d) / (a * c * f)
k = -e / (c * f)
m = 1 / f
# Now it's time for us to compute M⁻¹. We can do this quickly:
#
# M⁻¹ = (L L^T)⁻¹ = (L^T)⁻¹ L⁻¹ = (L⁻¹)^T L⁻¹
#
# where we used the fact that (AB)⁻¹ = B⁻¹ A⁻¹, and that
# (L^T)⁻¹ = (L⁻¹)^T. The product of (L⁻¹)^T and L⁻¹ is
#
# | g h j | | g 0 0 | | g²+h²+j² hi+jk jm |
# | 0 i k | · | h i 0 | = | hi+jk i²+k² km |
# | 0 0 m | | j k m | | jm km m² |
result[ipix, 0, 0] = g**2 + h**2 + j**2
result[ipix, 1, 0] = h * i + j * k
result[ipix, 0, 1] = result[ipix, 1, 0]
result[ipix, 1, 1] = i**2 + k**2
result[ipix, 2, 0] = j * m
result[ipix, 0, 2] = result[ipix, 2, 0]
result[ipix, 2, 1] = k * m
result[ipix, 1, 2] = result[ipix, 2, 1]
result[ipix, 2, 2] = m**2
@dataclass
class NobsMatrix:
"""
A class containing the N_obs matrix described in Kurki-Suonio et al. (2009)
The matrix is used to “solve” for the value of the Stokes parameters I/Q/U
per each pixel given a set of intensity measurements for that pixel.
The N_obs matrix is a block-diagonal matrix where each 3×3 block corresponds
to one pixel. (See Eq. 10 in Kurki-Suonio et al.) However, since the matrix
is symmetric, this class only stores its lower-triangular part, and the
``nobs_matrix`` field is thus a 2D array of shape ``(6, N_pix)``, with
``N_pix`` the number of pixels in the map.
The array `valid_pixel` is an array of ``N_pix`` booleans, telling whether
the corresponding pixel was observed enough times to make the problem of
reconstructing the Stokes I/Q/U components solvable or not.
If `is_cholesky` is true, the `nobs_matrix` contains the coefficients of
the lower triangular L such that L·L^t = M, where M is the 3×3 submatrix
in Eq. (10). This is extremely efficient, as in this way it is trivial
to invert matrix M to solve for the three Stokes parameter. And since L
is lower-triangular, 6 elements are still enough to keep it.
"""
# Shape: (Npix, 6)
nobs_matrix: npt.NDArray
# Shape: (Npix,) (array of Boolean flags)
valid_pixel: npt.NDArray
# True if `nobs_matrix` contains the Cholesky decomposition of M_i
is_cholesky: bool
@property
def nbytes(self) -> int:
"""Return the number of bytes used by this object"""
return self.nobs_matrix.nbytes + self.valid_pixel.nbytes
def get_invnpp(self) -> npt.NDArray:
"""Return the inverse noise covariance matrix per pixel
This method returns a (N_pix, 3, 3) array containing the
3×3 matrices associated with each pixel that contain the
estimate noise per pixel. Each of the N_pix matrices
corresponds to Mᵢ⁻¹, the inverse of Mᵢ in Eq. (10) of
Kurki-Suonio et al. (2009).
A null matrix is associated with each invalid pixel.
"""
assert self.is_cholesky, (
"You can use NobsMatrix.get_invnpp only after "
"having called the binner/destriper"
)
npix = self.nobs_matrix.shape[0]
result = np.empty((npix, 3, 3), dtype=np.float64)
_get_invnpp(
nobs_matrix_cholesky=self.nobs_matrix,
valid_pixel=self.valid_pixel,
result=result,
)
return result
@dataclass
class DestriperParameters:
"""
Parameters used by the function :func:`.make_destriped_map`
The class is used to tell the destriper how to solve the map-making
equation. The fields are:
- ``nside`` (integer, power of two): resolution of the output map
- ``output_coordinate_system`` (:class:`.CoordinateSystem`): the
coordinate system of the output map
- ``samples_per_baseline`` (integer): how many consecutive samples
in the TOD must be assigned to the same baseline. If ``None``,
the destriper algorithm is skipped and a simple binning will
be done.
- ``iter_max`` (integer): maximum number of iterations for the
Conjugate Gradient
- ``threshold`` (float): minimum value of the discrepancy between
the estimated baselines and the baselines deduced by the
destriped map. The lower this value, the better the map
produced by the destriper
- ``use_preconditioner`` (Boolean): if ``True``, use the preconditioned
conjugate gradient algorithm. If ``False`` do not use the
preconditioner. (The latter is probably useful only to debug the
code.)
"""
output_coordinate_system: CoordinateSystem = CoordinateSystem.Galactic
samples_per_baseline: Optional[Union[int, List[npt.ArrayLike]]] = 100
iter_max: int = 100
threshold: float = 1e-7
use_preconditioner: bool = True
@dataclass
class DestriperResult:
"""
Result of a call to :func:`.make_destriped_map`
The fields `baselines`, `baseline_lengths`, `stopping_factors`,
`destriped_map`, and `converged` are only relevant if you actually
used the destriper; otherwise, they will be set to ``None``.
If you are running several MPI processes, keep in mind that the fields
`hit_map`, `binned_map`, `destriped_map`, `nobs_matrix_cholesky`,
and `bytes_in_temporary_buffers` contain the *global* map, but
`baselines` and `baseline_lengths` only refer to the TODs within
the *current* MPI process.
List of fields:
- ``params``: an instance of the class :class:`.DestriperParameters`
- ``nside``: the resolution of the Healpix maps.
- ``hit_map``: a map of scalar values, each representing the sum
of weights per pixel (normalized over the σ of each detector).
- ``binned_map``: the binned map (i.e., *without* subtracting the
1/f baselines estimated by the destriper).
- ``nobs_matrix_cholesky``: an instance of the class
:class:`.NobsMatrix`.
- ``coordinate_system``: the coordinate system of the maps
``hit_map``, ``binned_map``, and ``destriped_map``.
- ``baselines``: a Python list of NumPy arrays (one per each
observation passed to the destriper) containing the value
of the baselines.
- ``baseline_errors``: a Python list of NumPy arrays (one per
each observation passed to the destriper) containing an
optimistic estimate of the error per each baseline. This error
is estimated assuming that there is no correlation between
baselines, which is only a rough approximation.
- ``baseline_lengths``: a Python list of NumPy arrays (one per
each observation passed to the destriper) containing the
number of TOD samples per each baseline.
- ``stopping_factor``: the maximum residual for the destriping
solution stored in the field `baselines`. It is an assessment
of the quality of the solution found by the destriper: the
lower, the better.
- ``history_of_stopping_factors``: list of stopping factors
computed by the iterative algorithm. This list should ideally
be monothonically decreasing, as this means that the destriping
algorithm was able to converge to the correct solution.
- ``converged``: a Boolean flag telling whether the destriper
was able to achieve the desired accuracy (the value of
``params.threshold``).
- ``elapsed_time_s``: the elapsed time spent by the function
:func:`.make_destriped_map`.
- ``bytes_in_temporary_buffers``: the number of bytes allocated
internally by the destriper for temporary buffers.
"""
params: DestriperParameters
nside: int
components: List[str]
hit_map: npt.ArrayLike
binned_map: npt.ArrayLike
nobs_matrix_cholesky: NobsMatrix
coordinate_system: CoordinateSystem
# The following fields are filled only if the CG algorithm was used
baselines: Optional[npt.ArrayLike]
baseline_errors: Optional[npt.ArrayLike]
baseline_lengths: Optional[npt.ArrayLike]
stopping_factor: Optional[float]
history_of_stopping_factors: Optional[List[float]]
destriped_map: Optional[npt.ArrayLike]
converged: bool
elapsed_time_s: float
bytes_in_temporary_buffers: int
def _sum_components_into_obs(
obs_list: List[Observation],
target: str,
other_components: List[str],
factor: float,
) -> None:
"""Sum all the TOD components into the first one
If `target` is “tod” and `other_components` is the list ``["sky", "noise"]``,
this function will do the operation ``tod += factor * (sky + noise)``.
The value of `factor` is usually ±1, which means that you can either sum
or subtract the sky and the noise in the above example.
"""
for cur_obs in obs_list:
target_tod = getattr(cur_obs, target)
for other_component in other_components:
target_tod += factor * getattr(cur_obs, other_component)
@njit
def _accumulate_nobs_matrix(
pix_idx: npt.ArrayLike, # Shape: (Ndet, 1)
psi_angle_rad: npt.ArrayLike, # Shape: (Ndet, 1)
weights: npt.ArrayLike, # Shape: (N_det,)
nobs_matrix: npt.ArrayLike, # Shape: (N_pix, 6)
) -> None:
"""
Fill the upper triangle of the N_obs matrix following Eq. (10)
of KurkiSuonio2009. This must be set just once during destriping,
as it only depends on the pointing information
Note that `nobs_matrix` must have been set to 0 before starting
calling this function!
"""
assert pix_idx.shape == psi_angle_rad.shape
num_of_detectors = pix_idx.shape[0]
for det_idx in range(num_of_detectors):
inv_sigma = 1.0 / np.sqrt(weights[det_idx])
inv_sigma2 = inv_sigma * inv_sigma
# Fill the lower triangle of M_i only for i = 1…N_pix
for cur_pix_idx, cur_psi in zip(pix_idx[det_idx], psi_angle_rad[det_idx]):
cos_over_sigma = np.cos(2 * cur_psi) * inv_sigma
sin_over_sigma = np.sin(2 * cur_psi) * inv_sigma
cur_matrix = nobs_matrix[cur_pix_idx]
cur_matrix[0] += inv_sigma2
cur_matrix[1] += cos_over_sigma * inv_sigma
cur_matrix[2] += cos_over_sigma * cos_over_sigma
cur_matrix[3] += sin_over_sigma * inv_sigma
cur_matrix[4] += sin_over_sigma * cos_over_sigma
cur_matrix[5] += sin_over_sigma * sin_over_sigma
@njit(parallel=True)
def _nobs_matrix_to_cholesky(
nobs_matrix: npt.ArrayLike, # Shape: (N_pix, 6)
dest_valid_pixel: npt.ArrayLike, # Shape: (N_pix,)
dest_nobs_matrix_cholesky: npt.ArrayLike, # Shape: (N_pix, 6)
) -> None:
"""Apply `cholesky` iteratively on all the input maps in `nobs_matrix`
and save each result in `nobs_matrix_cholesky`"""
for pixel_idx in prange(nobs_matrix.shape[0]):
cur_nobs_matrix = nobs_matrix[pixel_idx]
(cond_number, flag) = estimate_cond_number(
a00=cur_nobs_matrix[0],
a10=cur_nobs_matrix[1],
a11=cur_nobs_matrix[2],
a20=cur_nobs_matrix[3],
a21=cur_nobs_matrix[4],
a22=cur_nobs_matrix[5],
)
dest_valid_pixel[pixel_idx] = flag and (cond_number < COND_THRESHOLD)
if dest_valid_pixel[pixel_idx]:
cholesky(
a00=cur_nobs_matrix[0],
a10=cur_nobs_matrix[1],
a11=cur_nobs_matrix[2],
a20=cur_nobs_matrix[3],
a21=cur_nobs_matrix[4],
a22=cur_nobs_matrix[5],
dest_L=dest_nobs_matrix_cholesky[pixel_idx],
)
# There is no `else`: we assume that
# `nobs_matrix_cholesky` was already initialized
# to zero everywhere
def _store_pixel_idx_and_pol_angle_in_obs(
hpx: Healpix_Base,
obs_list: List[Observation],
ptg_list: List[npt.ArrayLike],
psi_list: List[npt.ArrayLike],
output_coordinate_system: CoordinateSystem,
):
for cur_obs, cur_ptg, cur_psi in zip(obs_list, ptg_list, psi_list):
cur_obs.destriper_weights = get_map_making_weights(cur_obs, check=True)
(
cur_obs.destriper_pixel_idx,
cur_obs.destriper_pol_angle_rad,
) = _compute_pixel_indices(
hpx=hpx,
pointings=cur_ptg,
psi=cur_psi,
output_coordinate_system=output_coordinate_system,
)
def _build_nobs_matrix(
hpx: Healpix_Base,
obs_list: List[Observation],
ptg_list: List[npt.ArrayLike],
psi_list: List[npt.ArrayLike],
) -> NobsMatrix:
# Instead of a shape like (Npix, 3, 3), i.e., one 3×3 matrix per each
# pixel, we only store the lower triangular part in a 6-element array.
# In this way we reduce the memory usage by ~30% and the code is faster too.
nobs_matrix = np.zeros((hpx.npix(), 6)) # Do not use np.empty() here!
for cur_obs, cur_ptg, cur_psi in zip(obs_list, ptg_list, psi_list):
_accumulate_nobs_matrix(
pix_idx=cur_obs.destriper_pixel_idx,
psi_angle_rad=cur_obs.destriper_pol_angle_rad,
weights=cur_obs.destriper_weights,
nobs_matrix=nobs_matrix,
)
# Now we must accumulate the result of every MPI process
if MPI_ENABLED:
MPI_COMM_WORLD.Allreduce(mpi4py.MPI.IN_PLACE, nobs_matrix, op=mpi4py.MPI.SUM)
# `nobs_matrix_cholesky` will *not* contain the M_i maps shown in
# Eq. 9 of KurkiSuonio2009, but its Cholesky decomposition, i.e.,
# a lower-triangular matrix L such that M_i = L_i · L_i†.
nobs_matrix_cholesky = np.zeros((hpx.npix(), 6)) # Do not use np.empty() here!
valid_pixel = np.empty(hpx.npix(), dtype=np.bool_)
_nobs_matrix_to_cholesky(
nobs_matrix=nobs_matrix,
dest_valid_pixel=valid_pixel,
dest_nobs_matrix_cholesky=nobs_matrix_cholesky,
)
# We can get rid of all the M_i, as we are going to use their
# Cholesky's decompositions from now on
del nobs_matrix
return NobsMatrix(
nobs_matrix=nobs_matrix_cholesky,
valid_pixel=valid_pixel,
is_cholesky=True,
)
@njit
def _step_over_baseline(baseline_idx, samples_in_this_baseline, baseline_length):
samples_in_this_baseline += 1
if samples_in_this_baseline >= baseline_length[baseline_idx]:
baseline_idx += 1
samples_in_this_baseline = 0
return (baseline_idx, samples_in_this_baseline)
@njit
def _sum_map_contribution_from_one_sample(
pol_angle_rad: float, sample: float, weight: float, dest_array: npt.ArrayLike
) -> None:
"This code implements Eqq. (18)–(20)"
dest_array[0] += sample / weight
dest_array[1] += sample * np.cos(2 * pol_angle_rad) / weight
dest_array[2] += sample * np.sin(2 * pol_angle_rad) / weight
@njit
def _update_sum_map_with_tod(
sky_map: npt.ArrayLike,
hit_map: npt.ArrayLike,
tod: npt.ArrayLike,
pol_angle_rad: npt.ArrayLike,
pixel_idx: npt.ArrayLike,
weights: npt.ArrayLike,
baseline_lengths: npt.ArrayLike, # Number of samples per baseline
) -> None:
"""
Compute the sum map within the current MPI process for TOD y
This function implements the calculation of the operator P^t C_w⁻¹
(Eqq. 18–20), the so-called “sum map”. Note that the summation
is done on the samples of the current MPI process; the overall
summation is done by `_compute_binned_map`, which solves the
three I/Q/U Stokes parameters.
"""
for det_idx in range(pixel_idx.shape[0]):
cur_weight = weights[det_idx]
baseline_idx = 0
samples_in_this_baseline = 0
for sample_idx in range(tod.shape[1]):
cur_pix = pixel_idx[det_idx, sample_idx]
_sum_map_contribution_from_one_sample(
pol_angle_rad=pol_angle_rad[det_idx, sample_idx],
sample=tod[det_idx, sample_idx],
dest_array=sky_map[:, cur_pix],
weight=cur_weight,
)
hit_map[cur_pix] += 1.0 / cur_weight
(baseline_idx, samples_in_this_baseline) = _step_over_baseline(
baseline_idx, samples_in_this_baseline, baseline_lengths
)
@njit
def _update_sum_map_with_baseline(
sky_map: npt.ArrayLike,
hit_map: npt.ArrayLike,
pol_angle_rad: npt.ArrayLike,
pixel_idx: npt.ArrayLike,
weights: npt.ArrayLike,
baselines: npt.ArrayLike, # Value of each baseline
baseline_lengths: npt.ArrayLike, # Number of samples per baseline
) -> None:
"""
Compute the sum map within the current MPI process for baselines Fa
This function is the same as `_update_sum_map_with_tod`, but it
sums the baselines unrolled over the TOD instead of the TOD itself.
(Note that we could have avoided code duplication between these
two functions, had we used some more advanced language like Julia! ☹)
"""
for det_idx in range(pixel_idx.shape[0]):
cur_weight = weights[det_idx]
baseline_idx = 0
samples_in_this_baseline = 0
for sample_idx in range(pixel_idx.shape[1]):
cur_pix = pixel_idx[det_idx, sample_idx]
_sum_map_contribution_from_one_sample(
pol_angle_rad=pol_angle_rad[det_idx, sample_idx],
sample=baselines[det_idx, baseline_idx],
dest_array=sky_map[:, cur_pix],
weight=cur_weight,
)
hit_map[cur_pix] += 1.0 / cur_weight
(baseline_idx, samples_in_this_baseline) = _step_over_baseline(
baseline_idx, samples_in_this_baseline, baseline_lengths
)
@njit
def _sum_map_to_binned_map(
sky_map: npt.ArrayLike,
nobs_matrix_cholesky: npt.ArrayLike,
valid_pixels: npt.ArrayLike,
) -> None:
"""Convert a “sum map” into a “binned map” using the N_obs matrix"""
for cur_pix in range(sky_map.shape[1]):
if valid_pixels[cur_pix]:
cur_i, cur_q, cur_u = solve_cholesky(
L=nobs_matrix_cholesky[cur_pix, :],
v0=sky_map[0, cur_pix],
v1=sky_map[1, cur_pix],
v2=sky_map[2, cur_pix],
)
sky_map[0, cur_pix] = cur_i
sky_map[1, cur_pix] = cur_q
sky_map[2, cur_pix] = cur_u
else:
sky_map[0, cur_pix] = np.nan
sky_map[1, cur_pix] = np.nan
sky_map[2, cur_pix] = np.nan
def _compute_binned_map(
obs_list: List[Observation],
nobs_matrix_cholesky: NobsMatrix,
baselines_list: Optional[List[npt.ArrayLike]],
baseline_lengths_list: List[npt.ArrayLike],
component: Optional[str],
output_hit_map: npt.ArrayLike,
output_sky_map: npt.ArrayLike,
) -> None:
"""
Compute the global binned map
This function computes the B≡M⁻¹·P^t·C_w⁻¹ operator (Eq. 21),
which “bins” the TODs contained in `obs_list` in a sum map
(using `_update_sum_map_local`), reduces the sums from all the
MPI processes, and then solves for the I/Q/U parameters.
This is applied either to `y` or to `Fa`, depending on whether
the parameter `baselines_list` is ``None`` or not, respectively.
(You *must* pass one of them, but not both.)
The result is saved in `sky_map` (a 3,N_p tensor) and `hit_map`
(a N_p vector).
"""
assert nobs_matrix_cholesky.is_cholesky, (
"The parameter nobs_matrix_cholesky should already "
"contain the Cholesky decompositions of the 3×3 M_i matrices"
)
assert ((baselines_list is not None) and (component is None)) or (
(baselines_list is None) and (component is not None)
), (
"To call _compute_binned_map you must either provide "
"the baselines or the TOD component, but not both"
)
# Step 1: compute the “sum map” (Eqq. 18–20)
output_sky_map[:] = 0
output_hit_map[:] = 0
for obs_idx, (cur_obs, cur_baseline_lengths) in enumerate(
zip(obs_list, baseline_lengths_list)
):
if baselines_list is None:
_update_sum_map_with_tod(
sky_map=output_sky_map,
hit_map=output_hit_map,
tod=getattr(cur_obs, component),
pol_angle_rad=cur_obs.destriper_pol_angle_rad,
pixel_idx=cur_obs.destriper_pixel_idx,
weights=cur_obs.destriper_weights,
baseline_lengths=cur_baseline_lengths,
)
else:
cur_baselines = baselines_list[obs_idx]
_update_sum_map_with_baseline(
sky_map=output_sky_map,
hit_map=output_hit_map,
pol_angle_rad=cur_obs.destriper_pol_angle_rad,
pixel_idx=cur_obs.destriper_pixel_idx,
weights=cur_obs.destriper_weights,
baselines=cur_baselines,
baseline_lengths=cur_baseline_lengths,
)
if MPI_ENABLED:
MPI_COMM_WORLD.Allreduce(mpi4py.MPI.IN_PLACE, output_sky_map, op=mpi4py.MPI.SUM)
MPI_COMM_WORLD.Allreduce(mpi4py.MPI.IN_PLACE, output_hit_map, op=mpi4py.MPI.SUM)
# Step 2: compute the “binned map” (Eq. 21)
_sum_map_to_binned_map(
sky_map=output_sky_map,
nobs_matrix_cholesky=nobs_matrix_cholesky.nobs_matrix,
valid_pixels=nobs_matrix_cholesky.valid_pixel,
)
@njit
def estimate_sample_from_map(
cur_pixel: int, cur_psi: float, sky_map: npt.ArrayLike
) -> float:
cur_i = sky_map[0, cur_pixel]
cur_q = sky_map[1, cur_pixel]
cur_u = sky_map[2, cur_pixel]
return cur_i + cur_q * np.cos(2 * cur_psi) + cur_u * np.sin(2 * cur_psi)
@njit
def _compute_tod_sums_for_one_component(
weights: npt.ArrayLike,
tod: npt.ArrayLike,
pixel_idx: npt.ArrayLike,
psi_angle_rad: npt.ArrayLike,
sky_map: npt.ArrayLike,
baseline_length: npt.ArrayLike,
output_sums: npt.ArrayLike,
) -> None:
"""
Compute F^t C_w⁻¹ Z over TOD y
:param weights: The detector weights (array of N_det elements)
:param tod: The vector `y` (a NumPy array with N_samp elements)
:param pixel_idx: A NumPy array of N_samp Healpix indexes
:param psi_angle_rad: Values of the polarization angles (N_samp elements)
:param sky_map: The sky map used to compute operator Z
:param baseline_length: Array of N_base integers (the number
of samples per baseline)
:param output_sums: An array of N_base elements that will contain the result
"""
output_sums[:] = 0
for det_idx, cur_weight in enumerate(weights):
det_pixel_idx = pixel_idx[det_idx, :]
det_psi_angle_rad = psi_angle_rad[det_idx, :]
baseline_idx = 0
samples_in_this_baseline = 0
for sample_idx in range(len(det_pixel_idx)):
map_value = estimate_sample_from_map(
cur_pixel=det_pixel_idx[sample_idx],
cur_psi=det_psi_angle_rad[sample_idx],
sky_map=sky_map,
)
value_to_add = (tod[det_idx, sample_idx] - map_value) / cur_weight
if np.isfinite(value_to_add):
output_sums[det_idx, baseline_idx] += value_to_add
(baseline_idx, samples_in_this_baseline) = _step_over_baseline(
baseline_idx, samples_in_this_baseline, baseline_length
)
@njit
def _compute_baseline_sums_for_one_component(
weights: npt.ArrayLike,
pixel_idx: npt.ArrayLike,
psi_angle_rad: npt.ArrayLike,
sky_map: npt.ArrayLike,
baselines: npt.ArrayLike,
baseline_length: npt.ArrayLike,
output_sums: npt.ArrayLike,
) -> None:
"""
Compute F^t C_w⁻¹ Z over TOD Fa (baselines projected in TOD space)
:param weights: The detector weights (array of N_det elements)
:param pixel_idx: A NumPy array of N_samp Healpix indexes
:param psi_angle_rad: Values of the polarization angles (N_samp elements)
:param sky_map: The sky map used to compute operator Z
:param baselines: Array of N_base numbers (the value of each baseline)
:param baseline_length: Array of N_base integers (the number
of samples per baseline)
:param output_sums: An array of N_base elements that will contain the result
"""
output_sums[:] = 0
for det_idx, cur_weight in enumerate(weights):
det_pixel_idx = pixel_idx[det_idx, :]
det_psi_angle_rad = psi_angle_rad[det_idx, :]
baseline_idx = 0
samples_in_this_baseline = 0
for sample_idx in range(len(det_pixel_idx)):
map_value = estimate_sample_from_map(
cur_pixel=det_pixel_idx[sample_idx],
cur_psi=det_psi_angle_rad[sample_idx],
sky_map=sky_map,
)
cur_value = (baselines[det_idx, baseline_idx] - map_value) / cur_weight
if np.isfinite(cur_value):
output_sums[det_idx, baseline_idx] += cur_value
(baseline_idx, samples_in_this_baseline) = _step_over_baseline(
baseline_idx, samples_in_this_baseline, baseline_length
)
def _compute_baseline_sums(
obs_list: List[Observation],
sky_map: npt.ArrayLike,
baselines_list: Optional[List[npt.ArrayLike]],
baseline_lengths_list: List[npt.ArrayLike],
component: Optional[str],
output_sums_list: List[npt.ArrayLike],
):
"""
Compute F^t C_w⁻¹ Z either on the TOD Fa (baselines) or y (TOD)
The matrix F “spreads” the baseline values “a” over the TOD space,
while “y” is the TOD owned by each :class:`.Observation` object
contained in `obs_list`. If `baselines_list` is not None,
the operator is applied on Fa, otherwise on y, where the name of
the field of the :class:`.Observation` class holding the TOD
is specified by `component`.
The field `baselines_list` (if specified) and `baseline_lengths_list`
are lists of NumPy arrays; they are lists with the same length as
`obs_list` and must contain the input value of the baselines and
their lengths in terms of number of TOD samples, respectively.
When using MPI, the baselines must refer to the TOD samples handled
by the TOD owned by the current MPI process.
The result is saved in `output_sums_list`, which must have already
been allocated. Note that you *cannot* make this field point to
the same memory location as `baselines_list`, although the two
objects share the same shape.
"""
assert len(baseline_lengths_list) == len(obs_list), (
f"The baselines have been specified for {len(baseline_lengths_list)} "
f"observations, but there are {len(obs_list)} observation(s) available"
)
assert len(output_sums_list) == len(obs_list), (
f"There are {len(output_sums_list)} buffers for the output but "
f"{len(obs_list)} observation(s)"
)
# Compute the value of the F^t C_w⁻¹ Z operator
for obs_idx, (cur_obs, cur_baseline_lengths, cur_sums) in enumerate(
zip(obs_list, baseline_lengths_list, output_sums_list)
):
assert len(cur_baseline_lengths) == cur_sums.shape[1], (
f"The output buffer for observation {obs_idx=} "
f"has room for {cur_sums.shape[1]} elements, but there"
f"are {len(cur_baseline_lengths)=} baselines in this observation"
)
if baselines_list is not None:
cur_baseline = baselines_list[obs_idx]
assert cur_baseline is not cur_sums, (
"The input and output arrays used to hold the baselines "
"must be different"
)
_compute_baseline_sums_for_one_component(
weights=cur_obs.destriper_weights,
pixel_idx=cur_obs.destriper_pixel_idx,
psi_angle_rad=cur_obs.destriper_pol_angle_rad,
sky_map=sky_map,
baselines=cur_baseline,
baseline_length=cur_baseline_lengths,
output_sums=cur_sums,
)
else:
_compute_tod_sums_for_one_component(
weights=cur_obs.destriper_weights,
tod=getattr(cur_obs, component),
pixel_idx=cur_obs.destriper_pixel_idx,
psi_angle_rad=cur_obs.destriper_pol_angle_rad,
sky_map=sky_map,
baseline_length=cur_baseline_lengths,
output_sums=cur_sums,
)
def _mpi_dot(a: List[npt.ArrayLike], b: List[npt.ArrayLike]) -> float:
"""Compute a dot product between lists of vectors using MPI
This function is a glorified version of ``numpy.dot``. It assumes
that `a` and `b` are lists of vectors spread among several
observations, and it computes their inner product Σ aᵢ·bᵢ.
If the code uses MPI, it makes the additional assumptions that
the vectors aᵢ and bᵢ have been split among the MPI processes,
so it computes the local dot product and then sums the contribution
from every MPI process.
"""
# As both x1 and x2 are 2D arrays with shape (N_detectors, N_baselines),
# we call “flatten” to make them 1D and produce *one* scalar out of
# the dot product
local_result = sum([np.dot(x1.flatten(), x2.flatten()) for (x1, x2) in zip(a, b)])
if MPI_ENABLED:
return MPI_COMM_WORLD.allreduce(local_result, op=mpi4py.MPI.SUM)
else:
return local_result
def _get_stopping_factor(residual: List[npt.ArrayLike]) -> float:
"""Given a list of baseline residuals, estimate the stopping factor
Our assumption here is that the stopping factor is the maximum absolute
value of all the residuals. This is unlike other implementations of the
CG algorithm, which just consider the value of ‖v‖ or ‖v‖²; we choose
to use max(vᵢ) because this is stricter: it prevents to get low
stopping factors for solutions where nearly all the baselines are ok
but a few of them are significantly off.
"""
local_result = np.max(np.abs(residual))
if MPI_ENABLED:
return MPI_COMM_WORLD.allreduce(local_result, op=mpi4py.MPI.MAX)
else:
return local_result
def _compute_b_or_Ax(
obs_list: List[Observation],
nobs_matrix_cholesky: NobsMatrix,
sky_map: npt.ArrayLike,
hit_map: npt.ArrayLike,
baselines_list: Optional[List[npt.ArrayLike]],
baseline_lengths_list: List[npt.ArrayLike],
component: Optional[str],
result: List[npt.ArrayLike],
):
"""Either compute `Ax` or `b` in the map-making equation `Ax=b`
The two terms `Ax` and `b` are similar, as `Ax` applies the
`F^t·C_w⁻¹·Z·F` operator to the baselines `a`, while `b` is
the vector `F^t·C_w⁻¹·Z·y`.
"""
_compute_binned_map(
obs_list=obs_list,
nobs_matrix_cholesky=nobs_matrix_cholesky,
baselines_list=baselines_list,
baseline_lengths_list=baseline_lengths_list,
component=component,
output_sky_map=sky_map,
output_hit_map=hit_map,
)
_compute_baseline_sums(
obs_list=obs_list,
sky_map=sky_map,
baselines_list=baselines_list,
baseline_lengths_list=baseline_lengths_list,
component=component,
output_sums_list=result,
)
def compute_b(
obs_list: List[Observation],
nobs_matrix_cholesky: NobsMatrix,
sky_map: npt.ArrayLike,
hit_map: npt.ArrayLike,
baseline_lengths_list: List[npt.ArrayLike],
component: str,
result: List[npt.ArrayLike],
) -> None:
"""
Compute `F^t·C_w⁻¹·Z·y
The value of `y` is the TOD component taken from the list
of observations `obs_list` with name `component`.
"""
_compute_b_or_Ax(
obs_list=obs_list,
nobs_matrix_cholesky=nobs_matrix_cholesky,
sky_map=sky_map,
hit_map=hit_map,
baselines_list=None,
baseline_lengths_list=baseline_lengths_list,
component=component,
result=result,
)
def compute_Ax(
obs_list: List[Observation],
nobs_matrix_cholesky: NobsMatrix,
sky_map: npt.ArrayLike,
hit_map: npt.ArrayLike,
baselines_list: List[npt.ArrayLike],
baseline_lengths_list: List[npt.ArrayLike],
result: List[npt.ArrayLike],
) -> None:
"""
Compute `F^t·C_w⁻¹·Z·F·a
The value of `a` is the list of baselines in the
parameter `baselines_list`, each with length
`baseline_lengths_list`.