megatop.utils
megatop.utils.Timer
Timer class to measure elapsed time.
A thread-safe singleton class that provides functionality to measure and log elapsed time. Can be used either as a context manager or with explicit start/stop calls.
Examples:
Using as context manager:
Using with explicit start/stop:
Source code in src/megatop/utils/timer.py
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 | |
__enter__()
Enter the Timer context manager and start timing.
This method is automatically called when entering a context manager block ('with' statement). It adds the current thread to the context threads queue and starts timing.
Returns:
-
Timer–The Timer instance for use in the context.
Source code in src/megatop/utils/timer.py
__exit__(*_exc_info)
Exit the Timer context manager and stop timing.
This method is automatically called when exiting a context manager block ('with' statement). It stops the timer for the current thread and logs the elapsed time.
Source code in src/megatop/utils/timer.py
__init__(thread='default')
Initialize a new Timer instance.
Parameters:
-
thread(str, default:'default') –Name to identify this timer instance.
Source code in src/megatop/utils/timer.py
start(thread='default')
Start the Timer with given name.
Should always be followed by a stop() call later in the code.
Parameters:
-
thread(str, default:'default') –Name of the timer to start.
Raises:
-
ValueError–when timer with given name already exists.
Source code in src/megatop/utils/timer.py
stop(thread='default')
Stop the Timer with given name and log the time elapsed since the start() call.
Parameters:
-
thread(str, default:'default') –Name of the timer to stop.
Raises:
-
ValueError–when timer with given name does not exist.
Source code in src/megatop/utils/timer.py
megatop.utils.function_timer(thread=None)
Function decorator to time a function.
Wraps a function with a Timer context manager to measure and log its execution time.
Parameters:
-
thread(str | None, default:None) –Optional thread name to distinguish timer. If None, uses function name with arguments as thread name.
Returns:
-
Callable–A wrapped function that logs timing information when called.
Source code in src/megatop/utils/timer.py
megatop.utils.TF_utils
get_alm_ordering(fields='TEB', components=None)
Build an iterator that yields the ordering of the alm components given fields and components (e.g. frequencies). Expected behavior for T,E,B fields and f1, f2 is : almT_f1, almE_f1, almB_f1, almT_f2, almE_f2, almB_f2
Parameters
fields : str The fields to consider. Default is "TEB". components : list The components to consider. Default is None.
Source code in src/megatop/utils/TF_utils.py
get_alms_from_cls(ps_array, lmax, seed=None)
Generate alms from power spectra.
Parameters
ps_array : np.ndarray A 2D array containing the power spectra with shape [fields, lmax]. With fields ordered with NEW ordering from healpy: TT, EE, BB, TE, EB, TB or TT, EE, BB, TE lmax : int The maximum multipole to consider.
fields : str
The fields to consider. Default is "TEB".
components : list
The components to consider. Default is None.
seed : int The seed for the random number generator. Default is None.
Source code in src/megatop/utils/TF_utils.py
get_map_from_alms(alms, nside)
Get a map from alms and a template.
Parameters
alms : np.ndarray The alms to use. nside : int
Returns
map : np.ndarray Returns the corresponding map.
Source code in src/megatop/utils/TF_utils.py
get_ps_matrix_for_sim(ps_dict, lmax, components=None, fields='TEB')
Build a matrix of power spectra for simulation of correlated alms.
Parameters
ps_dict : dict A dictionary containing the power spectra. lmax : int The maximum multipole to consider. components : list The components to consider. Default is None. fields : str The fields to consider. Default is "TEB".
Returns
ps_matrix : np.ndarray A 3D array containing the power spectra with dimension (nfields * ncomponents, nfields * ncomponents, lmax).
Source code in src/megatop/utils/TF_utils.py
power_law_cl(ell, amp, delta_ell, power_law_index)
Source code in src/megatop/utils/TF_utils.py
megatop.utils.V3p1calc
Simons Observatory LAT Noise Model
This is release v3.1.2.
Version 3.1.0 brings an update to the LAT T noise model, relative to v3.0. Version 3.1.1 brings the SAT noise model into the same file and framework, for convenience (but the SAT noise is the same as for 3.0).
This code includes one SO SAT noise model:
SOSatV3point1
This code includes two SO LAT noise models:
SOLatV3 - the original V3 noise model, but expanded to include elevation dependence. This should reproduced original V3 results at the reference elevation of 50 degrees.
SOLatV3point1 - like SOLatV3 but with an updated atmospheric 1/f model.
This code is based on the original SO LAT Noise Model released with the SO forecasts paper, but with some functional changes:
- Object-oriented organization to make it easier to swap in different noise models for the same calculation.
- Beam deconvolution is optional.
- Plotting code is not included, and instead found separately in this repo.
Version 3.1.2 fixes the noise elevation scaling for the LAT MF bands. The MF noise elevation scalings were using an average of the feedhorn and lenslet values, but we are only using feedhorns at MF now.
SOLatV3
Bases: SOTel
Source code in src/megatop/utils/V3p1calc.py
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 | |
__init__(sensitivity_mode=None, N_tubes=None, survey_years=5.0, survey_efficiency=0.2 * 0.85, el=None)
Arguments:
sensitivity_mode (int or string): Should be 'threshold', 'baseline', or 'goal'. Alternately you can pass 0, 1, or 2.
A list of tuples giving the survey-averaged number
of each LAT tube in operation. For example, the default is [('LF', 1), ('MF', 4), ('UHF', 2)], populating a total of 7 tubes in this LAT. Fractional tubes are acceptable (imagine a tube were swapped out part way through the survey).
survey_years: Total calendar years that the survey operates.
Fraction of calendar time that may be
used to compute map depth.
Elevation, in degrees. This affects white noise and red
noise, through separate scalings.
Source code in src/megatop/utils/V3p1calc.py
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 | |
SOSatV3point1
Bases: SOTel
Source code in src/megatop/utils/V3p1calc.py
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 | |
__init__(sensitivity_mode=None, N_tubes=None, survey_years=5.0, survey_efficiency=0.2 * 0.85, el=None, one_over_f_mode=0)
Arguments:
sensitivity_mode (int or string): Should be 'threshold', 'baseline', or 'goal'. Alternately you can pass 0, 1, or 2.
A list of tuples giving the survey-averaged number
of each SAT type in operation. For example, the default is [('LF', .4), ('MF', 1.6), ('UHF', 1)]
survey_years: Total calendar years that the survey operates.
Fraction of calendar time that may be
used to compute map depth.
Elevation, in degrees. The present SAT model does not
support this parameter.
0 or 1 to select 'pessimistic' or
'optimistic' red-noise behavior, respectively.
Source code in src/megatop/utils/V3p1calc.py
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 | |
SOTel
Base class for SO SAT and LAT noise models. The sub-class constructors should set up all the internal variables and then call precompute(). Then the noise levels can be obtained with get_white_noise / get_noise_curves.
Source code in src/megatop/utils/V3p1calc.py
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 | |
get_noise_curves(f_sky, ell_max, delta_ell, deconv_beam=True, full_covar=False, rolloff_ell=None)
Get the noise curves N(ell) for all bands.
The ell vector is determined by ell_max and delta_ell: ell = range(2, ell_max, delta_ell).
The f_sky is the area of the survey in units of a full sky; (0 < f_sky <= 1).
Returns (ell, T_noise, P_noise). If a model does not describe one of these spectra (has_T == False, or has_P == False), the corresponding spectrum will return as None. Otherwise, the shape of T_noise and P_noise will be (n_bands, n_ell) if full_covar is False, and (n_bands, n_bands, n_ell) if full_covar is True.
If deconv_beam is True, then the beam transfer functions are deconvolved, to give the effective noise level relative to a signal at each ell.
If rolloff_ell is specified, a transfer function is applied to reduce red noise below this cutoff. The transfer function at ell > rolloff_ell will be 1. See code if you care about what happens below that.
Source code in src/megatop/utils/V3p1calc.py
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 | |
get_survey_spread(f_sky, units='arcmin2')
Returns the dilution factor that converts array instrument sensitivity (in units uK^2 sec) to map white noise level (units uK^2 arcmin^2). Units are arcmin^2 / second (unless units='sr' is set)
Source code in src/megatop/utils/V3p1calc.py
get_survey_time()
Returns the effective survey time (survey_years * efficiency), in seconds.
get_white_noise(f_sky, units='arcmin2')
Returns the survey white noise level, in temperature, for each band, in uK^2 arcmin2, for the specified f_sky (0 < f_sky <= 1).
Pass units='sr' to get uK^2 steradian units.
Source code in src/megatop/utils/V3p1calc.py
get_atmosphere_params(freqs, version=1, el=None)
Returns atmospheric noise power parameters, for an ACTPol optics tube.
Arguments:
freqs: array of frequencies (in GHz) to process. This function only handles the standard SO frequency values. version: version of the C factors to return. See below. el: elevation angle, in degrees. Default is 50.
Returns (C_array, alpha_array), where each array has the same shape as freqs. The red noise contribution to each band is then:
N_red(ell) = C * (ell/1000)^alpha
with units of [uK^2 sec].
The model is naturally calibrated for boresight elevation el = 50 degrees. A simple rescaling (proportional to csc(el)) is applied for other values of el.
In the present model, alpha=-3.5 always.
version=0: This atmospheric model was used in SO V3 forecasts but contains an error.
version=1: This atmospheric model is better than version=0, in that at least one error has been corrected. The relative atmospheric powers have been measured in AT model, and then calibrated to ACT. Low frequency results are inflated somewhat because ACT sees more power at 90 GHz than predicted by this modeling.
Source code in src/megatop/utils/V3p1calc.py
rolloff(ell, ell_off=None, alpha=-4, patience=2.0)
Get a transfer function T(ell) to roll off red noise at ell <
ell_off. ell should be an ndarray. Above the cut-off,
T(ell>=ell_off) = 1. For T(ell
T(ell) * ell**alpha
-----------------------------
T(ell_off) * ell_off**alpha
I.e, supposing you were fighting an ellalpha spectrum, the roll-off in T(ell) will be applied aggressively enough that T(ell)*ellalpha does not rise above "patience" times its value at ell_off.
Source code in src/megatop/utils/V3p1calc.py
megatop.utils.binning
create_binning(lmax, delta_ell, uniform_start=None)
Create multipole bin edges for NaMaster.
All edges are inclusive: bin i covers ell in [bin_low[i], bin_high[i]]. The first bin always starts at ell=2 and the last bin always ends at lmax. When saving and reloading via NmtBin.from_edges, pass bin_high + 1 because namaster treats its upper edge argument as exclusive.
Parameters:
-
lmax(int) –Maximum multipole, inclusive. The last bin always ends at lmax.
-
delta_ell(int) –Width of the uniform bins.
-
uniform_start(int | None, default:None) –If provided, the first bin spans [2, uniform_start - 1] and uniform bins of width delta_ell start at uniform_start. If None, all bins have width delta_ell aligned to multiples of delta_ell from 0, with the first bin forced to start at ell=2.
Returns:
-
bin_low(ndarray) –Lower edge of each bin (inclusive).
-
bin_high(ndarray) –Upper edge of each bin (inclusive).
-
bin_center(ndarray) –Arithmetic center of each bin.
Source code in src/megatop/utils/binning.py
load_nmt_binning(manager)
Load the binning from the file.
Source code in src/megatop/utils/binning.py
megatop.utils.compsep
set_alm_tozero_above_lmax(alm, lmax)
Truncate the spherical harmonic coefficients (alm) to a new lmax. Parameters
alm : array_like Input spherical harmonic coefficients, shape (..., N), where N = (lmax_old + 1) * (lmax_old + 2) / 2. lmax_new : int New maximum multipole to truncate to. Returns
alm_new : array_like Truncated spherical harmonic coefficients, shape (..., M), where M = (lmax_new + 1) * (lmax_new + 2) / 2.
Source code in src/megatop/utils/compsep.py
set_alm_tozero_below_lmin(alm, lmin)
Truncate the spherical harmonic coefficients (alm) to a new lmax. Parameters
alm : array_like Input spherical harmonic coefficients, shape (..., N), where N = (lmax_old + 1) * (lmax_old + 2) / 2. lmax_new : int New maximum multipole to truncate to. Returns
alm_new : array_like Truncated spherical harmonic coefficients, shape (..., M), where M = (lmax_new + 1) * (lmax_new + 2) / 2.
Source code in src/megatop/utils/compsep.py
megatop.utils.harmonic
Pixelization-agnostic spherical harmonic transforms.
Dispatches between HEALPix (via ducc0) and CAR (via pixell.curvedsky) based on
the input map type. Shapes are (..., npix) for HEALPix and (..., ny, nx)
for CAR. All public functions are keyword-only.
Environment variables
MEGATOP_SHT_NTHREADS: Default ducc0 thread count (HEALPix path). Read once
at import; 0 (default) lets ducc0 choose. Overridden per-call via
nthreads (0 or None falls back to this default).
alm2map(alms, *, spin=0, nside=None, shape=None, wcs=None, out=None, lmax=None, mmax=None, nthreads=None)
Inverse SHT. Target pixelization set by kwargs:
out(enmap) → CAR in-place.shape+wcs→ CAR, new enmap.nside→ HEALPix.
Parameters:
-
alms–Spherical harmonic coefficients.
-
spin–Spin weight:
0(T),2(Q/U), or a list like[0, 2]for mixed-spin fields. HEALPix splits the alm axis by spin group; CAR passes to pixell.TEB → TQU requires
spin=[0, 2]. With a(3, nalm)input the output is(3, npix)with rows[T, Q, U]. Batch dimensions are supported:(batch, 3, nalm)→(batch, 3, npix). -
nside–HEALPix resolution. Mutually exclusive with CAR options.
-
shape–CAR pixel shape. Used with
wcs. -
wcs–CAR world coordinate system. Used with
shape. -
out–Pre-allocated output written in-place and returned. enmap for CAR, ndarray for HEALPix. Mutually exclusive with
shape/wcs. -
lmax–Bandlimit (HEALPix only — CAR infers it from
alms). -
mmax–Azimuthal bandlimit (HEALPix only). Defaults to
lmax. -
nthreads–ducc0 thread count (HEALPix).
NoneusesMEGATOP_SHT_NTHREADS.
Returns:
-
–
np.ndarray(..., npix)for HEALPix orpixell.enmap.ndmap -
–
(..., ny, nx)for CAR. Returnsoutwhen provided.
Raises:
-
ValueError–Conflicting or missing pixelization targets.
Source code in src/megatop/utils/harmonic.py
almxfl(alms, fl, *, mmax=None, inplace=False)
Multiply each a_lm by f_l. Pixel-agnostic.
Parameters:
-
alms–1-D alm array or 2-D
(ncomp, nalm). -
fl–Filter of length
lmax + 1. -
mmax–Azimuthal bandlimit. Defaults to
lmax(full triangular layout). -
inplace–Modify
almsin place.
Returns:
-
–
Filtered alms, same shape as input.
Source code in src/megatop/utils/harmonic.py
anafast(maps, maps2=None, *, lmax=None, mmax=None, niter=3, pol=True, nthreads=None)
Compute auto or cross power spectrum.
Routes through map2alm then hp.alm2cl. For TQU input (pol=True),
spin-0/spin-2 decomposition yields TEB alms; output is six spectra
TT EE BB TE EB TB in diagonal order, consistent with synfast(new=True).
Parameters:
-
maps–Input map (HEALPix ndarray or CAR enmap).
-
maps2–Second map for cross-spectrum.
-
lmax–Bandlimit.
-
mmax–Azimuthal bandlimit (HEALPix only — pixell does not expose it).
-
niter–Jacobi iterations for the forward SHT.
-
pol–If
Trueand the map has a Stokes axis of length 3, decompose into TEB and return all six spectra. RaisesValueErrorif the Stokes axis exists but has length ≠ 3. -
nthreads–ducc0 thread count (HEALPix only).
Returns:
-
–
Power spectrum array. For TQU input: TT EE BB TE EB TB in diagonal
-
–
order, directly usable as
synfastinput.
Source code in src/megatop/utils/harmonic.py
gauss_beam(fwhm_arcmin, lmax, *, pol=False)
Wrapper around healpy.gauss_beam with FWHM in arcminutes.
See healpy documentation for full details. The only difference is that
fwhm_arcmin is in arcminutes whereas healpy's fwhm is in radians.
Source code in src/megatop/utils/harmonic.py
getlmax(alm, mmax=None)
Infer lmax from alm.shape[-1].
Parameters:
-
alm–Alm array; last axis stores the
(l, m)layout. -
mmax–Azimuthal bandlimit if the layout is truncated (
mmax < lmax). Defaults tolmax(full triangular layout).
Returns:
-
int–lmaxconsistent withalm.shape[-1]andmmax.
Source code in src/megatop/utils/harmonic.py
map2alm(maps, *, spin=0, lmax=None, mmax=None, niter=3, nthreads=None)
Forward SHT, dispatching on pixelization.
Parameters:
-
maps–HEALPix
(..., npix)ndarray or CARpixell.enmap.ndmap(..., ny, nx). -
spin–Spin weight:
0(T),2(Q/U), or a list like[0, 2]for mixed-spin fields. HEALPix splits the map axis by spin group; CAR passes to pixell.Unlike healpy's
pol=True, TQU → TEB requiresspin=[0, 2]explicitly. Withspin=[0, 2]and a(3, npix)input the output is(3, nalm)with rows[alm_T, alm_E, alm_B]. Batch dimensions are supported:(batch, 3, npix)→(batch, 3, nalm). -
lmax–Bandlimit. HEALPix default:
3 * nside - 1; CAR: library default. -
mmax–Azimuthal bandlimit (HEALPix only). Defaults to
lmax. -
niter–Refinement steps. HEALPix: Jacobi iterations; CAR: passed to pixell.
-
nthreads–ducc0 thread count (HEALPix).
NoneusesMEGATOP_SHT_NTHREADS.
Returns:
-
–
Alm array, last axis in triangular
(l, m)layout.
Source code in src/megatop/utils/harmonic.py
smooth(maps, fwhm_arcmin, *, pol=False, lmax=None, nside=None, shape=None, wcs=None, out=None, niter=3, nthreads=None)
Smooth a map with a Gaussian beam.
When no output geometry is given the input geometry is reused: HEALPix nside is inferred from the input pixel count; CAR shape and WCS are copied from the input enmap.
Parameters:
-
maps–Input map — HEALPix
(..., npix)ndarray or CARpixell.enmap.ndmap(..., ny, nx). -
fwhm_arcmin–FWHM of the Gaussian beam in arcminutes.
-
pol–If
True, treatmapsas TQU and apply separate T and P beams (spin[0, 2]). IfFalse(default), apply a single spin-0 beam to all components. -
lmax–Bandlimit. Inferred from the alm output of
map2almifNone. -
nside–HEALPix output resolution. Defaults to input nside.
-
shape–CAR output pixel shape. Defaults to input shape.
-
wcs–CAR world coordinate system. Defaults to input WCS.
-
out–Pre-allocated output map written in-place and returned.
-
niter–Jacobi iterations for the forward SHT (HEALPix).
-
nthreads–ducc0 thread count (HEALPix).
Returns:
-
–
Smoothed map, same type and geometry as input unless overridden.
Source code in src/megatop/utils/harmonic.py
synfast(cl, *, nside=None, shape=None, wcs=None, lmax=None, seed=None, new=True, nthreads=None)
Generate a Gaussian random map from a power spectrum.
Parameters:
-
cl–Power spectrum. Accepted shapes:
- 1-D
(lmax+1,)— single TT spectrum. - 2-D
(nspec, lmax+1)— flat spectra; ordering set bynew. - 2-D
(4, lmax+1)— healpy shorthand TT EE BB TE (EB=TB=0). - 3-D
(n, n, lmax+1)— covariance matrix.
- 1-D
-
nside–HEALPix resolution. Mutually exclusive with
shape/wcs. -
shape–CAR pixel shape. Used with
wcs. -
wcs–CAR world coordinate system. Used with
shape. -
lmax–Bandlimit. Defaults to library default.
-
seed–PRNG seed.
-
nthreads–ducc0 thread count (HEALPix).
NoneusesMEGATOP_SHT_NTHREADS. -
new–Ordering for 2-D
cl, passed tohp.synalm. Defaults toTrue(TT EE BB TE EB TB), unlike healpy's defaultFalse. No effect for 1-D or 3-D input.
Returns:
-
–
np.ndarrayfor HEALPix,pixell.enmap.ndmapfor CAR.
Raises:
-
ValueError–Missing or conflicting pixelization targets.
Source code in src/megatop/utils/harmonic.py
megatop.utils.mask
get_analysis_mask(common_hitmap, binary_mask, apod_radius_deg, apod_type)
Create analysis mask and apodize it.
get_apodized_mask_from_nhits(nhits_map, nside, galactic_mask=None, point_source_mask=None, zero_threshold=0.001, apod_radius=10.0, apod_radius_point_source=4.0, apod_type='C1', no_nhits_rescaling=False)
Produce an appropriately apodized mask from an nhits map as used in
the BB pipeline paper (https://arxiv.org/abs/2302.04276).
Procedure:
* Make binary mask by smoothing, normalizing and thresholding nhits map
* (optional) multiply binary mask by galactic mask
* Apodize (binary * galactic)
* (optional) multiply (binary * galactic) with point source mask
* (optional) apodize (binary * galactic * point source)
* Multiply everything by (smoothed) nhits map (if no_nhits_rescaling is False)
Parameters
----------
nhits_map : array
maps of the nhits
nside : int
nside of the output mask.
galactic_mask : array, optional
galactic mask to apply.
point_source_mask : array, optional
point source mask to apply.
zero_threshold : float, optional
Threshold below which nhits values are set to zero.
apod_radius : float, optional
Apodization radius for the galactic mask (in degrees).
apod_radius_point_source : float, optional
Apodization radius for the point source mask (in degrees).
apod_type : str, optional
Type of apodization, default is "C1".
no_nhits_rescaling : bool, optional
If True, the apodized binary mask outputed is not resacled by nhits . Default is False.
Returns
-------
array
The apodized mask.
Source code in src/megatop/utils/mask.py
get_binary_mask(common_hitmap, gal_mask, zero_threshold)
Compute a binary mask by thresholding the common_hitmap and galactic mask.
Source code in src/megatop/utils/mask.py
get_binary_mask_from_nhits(nhits_map, nside, zero_threshold=0.001)
Generate a binary mask from a nhits by setting to zero pixels below a certain threshold and to 1 others.
Parameters
nhits_map : array maps of the nhits nside : int nside of the output mask zero_threshold: float threshold for setting pixels to 0 and 1.
Returns
binary_mask: array
Source code in src/megatop/utils/mask.py
get_common_nhits_map(hit_maps, fwhm_arcmin_nhits)
Get the 'common' nhits map by mutpliplying the (normalised) nhits maps for all frequencies together.
Source code in src/megatop/utils/mask.py
get_norm_smooth_nhits_from_depth(depth_maps, fwhm_arcmin_nhits)
Compute normalised and smoothed hitmap(s) from a depth map(s). Parameters
depth_maps : array input depth map (in muk_arcmin), shape is (..., npix)
Source code in src/megatop/utils/mask.py
get_spin_derivatives(map)
First and second spin derivatives of a given spin-0 map. Parameters
map : array Input spin-0 map in HEALPix format.
Returns
tuple of arrays First and second spin derivatives of the input map.
Source code in src/megatop/utils/mask.py
norm_smooth_nhits_maps(nhits_maps, fwhm_arcmin_nhits)
Normalize nhits_map(s)
Source code in src/megatop/utils/mask.py
random_src_mask(mask, nsrcs, mask_radius_arcmin)
Generate a modified version of a mask by randomly masking circular regions around selected points.
Parameters
mask : array input mask on which random point sources will be substracted nrscs : int number of random sources to be masked mask_radius_arcmin: float radius (in arcmin) of the mask around each source
Returns
ps_mask: array
Source code in src/megatop/utils/mask.py
read_depth_maps(list_depthmapname, nside)
Read depth maps and ud_grade. Maps are assumed equatorial (celestial).
Source code in src/megatop/utils/mask.py
read_nhits_maps(list_hitmapname, nside)
Read hit maps and ud_grade. Maps are assumed equatorial (celestial).
Source code in src/megatop/utils/mask.py
smooth_mask(mask, fwhm_arcmin)
megatop.utils.mpi
MPIGATHER(array, comm, rank, size, root)
Gathers an array to the root process using MPI.
Parameters
array : np.ndarray The array to gather. comm : MPI.COMM_WORLD The MPI communicator. rank : int The rank of the process. size : int The size of the communicator. root : int The root process.
Returns
array_recvbuf : np.ndarray The gathered array.
Source code in src/megatop/utils/mpi.py
MPISUM(array, comm, rank, root)
Reduces an array using the SUM operator to the root process using MPI.
Parameters
array : np.ndarray The array to reduce. comm : MPI.COMM_WORLD The MPI communicator. rank : int The rank of the process. root : int The root process.
Returns
array_recvbuf : np.ndarray The reduced array.
Source code in src/megatop/utils/mpi.py
megatop.utils.passband
fgbuster_passband(map_sets)
Source code in src/megatop/utils/passband.py
passband_constructor(config, manager, passband_int)
Read passbands from config file and outputs
Source code in src/megatop/utils/passband.py
megatop.utils.plot
freq_maps_plotter(config, map_set, plot_dir, plot_name, vmin=None, vmax=None, cmap_set_under='w', component='CMB')
This function plots the frequency maps. It directly saves the plot directly.
Parameters:
-
config–The configuration object.
-
map_set(ndarray) –The frequency maps, with shape (num_freq, num_stokes, num_pixels) or (1, num_stokes, num_pixels) if there is only one set of (TQU) map to display (e.g. CMB maps).
-
plot_dir(str) –The path to the directory where the plot will be saved.
-
plot_name(str) –The name of the file to save the plot.
-
vmin(dict, default:None) –The minimum values for the colorbar of the plots.
-
vmax(dict, default:None) –The maximum values for the colorbar of the plots.
-
cmap(colormap) –The colormap to use for the plots.
-
cmap_set_under(str, default:'w') –The color to set for the values under vmin.
-
component(str, default:'CMB') –If map_set of the shape (1, num_stokes, num_pixels) this parameter gives the name of the component to plot, e.g. CMB, fg, etc.
Returns:
-
–
None
Source code in src/megatop/utils/plot.py
freq_maps_plotter_one_stoke(config, map_set, plot_dir, plot_name, vmin=None, vmax=None, cmap=cm.RdBu, cmap_set_under='w', title_prefix='')
This function plots the frequency maps. It directly saves the plot directly.
Parameters:
-
config–The configuration object.
-
map_set(ndarray) –The frequency maps, with shape (num_freq, 1, num_pixels).
-
plot_dir(str) –The path to the directory where the plot will be saved.
-
plot_name(str) –The name of the file to save the plot.
-
vmin(dict, default:None) –The minimum values for the colorbar of the plots.
-
vmax(dict, default:None) –The maximum values for the colorbar of the plots.
-
cmap(colormap, default:RdBu) –The colormap to use for the plots.
-
cmap_set_under(str, default:'w') –The color to set for the values under vmin.
Returns:
-
–
None
Source code in src/megatop/utils/plot.py
plotTTEEBB(plot_dir, freqs, Cl, save_name, legend_labels=('fg $C_\\ell$ $\\nu=$',), y_axis_label='y_axis', use_D_ell=True, lims_x=(2, 2000), lims_y=(0.01, 10000000.0), ell=None)
This function plots the Cls. It directly saves the plot directly.
Parameters:
-
plot_dir(str) –The path to the directory where the plot will be saved.
-
freqs(list) –The frequencies of the maps.
-
Cl(ndarray) –The Cls, with shape (num_freq, num_spectra [TT,EE,BB], num_ell).
-
save_name(str) –The name of the file to save the plot.
-
legend_labels(list, default:('fg $C_\\ell$ $\\nu=$',)) –The labels for the legend of the plot.
-
y_axis_label(str, default:'y_axis') –The label for the y axis of the plot.
-
use_D_ell(bool, default:True) –If True, the Cls are multiplied by ell*(ell+1)/2/pi.
-
lims_x(tuple, default:(2, 2000)) –The limits for the x axis of the plot.
-
lims_y(tuple, default:(0.01, 10000000.0)) –The limits for the y axis of the plot.
-
ell(ndarray, default:None) –The ell values to use for the x axis. If None, it will be set to np.arange(0, Cl.shape[-1]).
Source code in src/megatop/utils/plot.py
plotTTEEBB_diff(plot_dir, freqs, Cl_data, Cl_model, save_name, legend_labels=('label data $C_\\ell$ $\\nu=$', 'label model $C_\\ell$ $\\nu=$'), axis_labels=('y_axis_row0', 'y_axis_row1'), use_D_ell=True, lims_x=(2, 2000), lims_y=(0.01, 10000000.0))
This function plots the difference between the data and the model Cls. It directly saves the plot directly.
Parameters:
-
plot_dir(str) –The path to the directory where the plot will be saved.
-
freqs(list) –The frequencies of the maps.
-
Cl_data(ndarray) –The Cls of the data, with shape (num_freq, num_spectra [TT,EE,BB], num_ell).
-
Cl_model(ndarray) –The Cls of the model that the data will be compared to, with shape (num_freq, num_spectra [TT,EE,BB], num_ell).
-
save_name(str) –The name of the file to save the plot.
-
legend_labels(list, default:('label data $C_\\ell$ $\\nu=$', 'label model $C_\\ell$ $\\nu=$')) –The labels for the legend of the plot (one for data, one for model)
-
axis_labels(list, default:('y_axis_row0', 'y_axis_row1')) –The labels for the y axis of the plot.
-
use_D_ell(bool, default:True) –If True, the Cls are multiplied by ell*(ell+1)/2/pi.
-
lims_x(tuple, default:(2, 2000)) –The limits for the x axis of the plot.
-
lims_y(tuple, default:(0.01, 10000000.0)) –The limits for the y axis of the plot.
Returns:
-
–
None
Source code in src/megatop/utils/plot.py
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 | |
plot_all_Cls(all_Cls, bin_centre, plot_dir, plot_name, use_D_ell=True, y_axis_label='y_axis')
This function plots the Cls outputed from map_to_cl or noise_spectra_estimator. It directly saves the plot directly.
Parameters:
-
all_Cls(dict) –Each entry correspond to auto or cross correlation between component maps (e.g "CMBxCMB", "CMBxDust" etc) in the shape of (num_spectra, num_ell) where num_spectra=4 : [EE,EB,BE,BB]
-
bin_centre(ndarray) –The bin centres.
-
plot_dir(str) –The path to the directory where the plot will be saved.
-
plot_name(str) –The name of the file to save the plot.
-
use_D_ell(bool, default:True) –If True, the Cls are multiplied by ell*(ell+1)/2/pi.
-
y_axis_label(str, default:'y_axis') –The label for the y axis of the plot.
Returns:
-
–
None
Source code in src/megatop/utils/plot.py
megatop.utils.preproc
read_input_maps(list_mapnames)
This function reads the frequency maps from the files and returns them as an array.
Parameters
list_mapnames: list list of paths to maps
Returns
freq_maps_input : (list)
The list of frequency maps, with len (num_freq), each of them having shape (num_stokes, num_pixels).s
Notes
- The input maps are allowed to have different `num_pixels' to allow for different resolutions.
Source code in src/megatop/utils/preproc.py
megatop.utils.spectra
compute_spectra_from_camb(r, cosmo_pars, which='total')
Compute CMB TT, EE, BB, TE spectra from CAMB. Parameters
r : float Tensor-to-scalar ratio. cosmo_pars : CAMBCosmoPars Cosmological parameters passed to camb.set_params(). which : str One of the spectra keys returned by results.get_cmb_power_spectra(). Returns
TT, EE, BB, TE : array-like Each with shape (LMAX+1,)
Source code in src/megatop/utils/spectra.py
get_effective_transfer_function(transfer_freq, W_maxL, binary_mask=None)
Computes the effective transfer function from the transfer functions at each frequency and the maximum likelihood results for the component separation operator Parameters
transfer_freq : np.ndarray Frequency transfer functions, shape (n_freq, 9 , 9, n_bins). Where 9 refers to the T, E, B, and their cross-spectra (xy->wz). W_maxL : np.ndarray Component separation operator, shape (ncomp, nfreq, n_stokes, n_pix). binary_mask : np.ndarray, optional Binary mask, shape (n_pix,). If provided, the effective transfer function is computed only over the observed pixels. Default is None, which means the effective transfer function is computed over all pixels. Returns
effective_transfer_function : np.ndarray Effective transfer function, shape (ncomp, ncomp, pol_spectra, pol_spectra ,nbin). pol_spectra refers EE, EB, BE, BB
Source code in src/megatop/utils/spectra.py
get_effective_transfer_function_WCl(transfer_freq, W_maxL, binary_mask=None)
Computes the effective transfer function from the transfer functions at each frequency and the maximum likelihood results for the component separation operator Parameters
transfer_freq : np.ndarray Frequency transfer functions, shape (n_freq, 9 , 9, n_bins). Where 9 refers to the T, E, B, and their cross-spectra (xy->wz). W_maxL : np.ndarray Component separation operator, shape (ncomp, nfreq, n_stokes, n_pix). binary_mask : np.ndarray, optional Binary mask, shape (n_pix,). If provided, the effective transfer function is computed only over the observed pixels. Default is None, which means the effective transfer function is computed over all pixels. Returns
effective_transfer_function : np.ndarray Effective transfer function, shape (ncomp, ncomp, pol_spectra, pol_spectra ,nbin). pol_spectra refers EE, EB, BE, BB
Source code in src/megatop/utils/spectra.py
limit_namaster_output(all_Cls, bin_index_lminlmax)
This function limits the output of namaster to the desired l range.
Parameters:
-
all_Cls(dict) –The dictionary containing the Cls computed by namaster.
-
bin_index_lminlmax(ndarray) –The indices of the bins corresponding to the desired l range.
Returns:
-
dict–The dictionary containing the Cls computed by namaster, limited to the desired l range.
Source code in src/megatop/utils/spectra.py
spectra_from_namaster(freq_noise_maps, mask_analysis, workspaceff, nmt_bins, compute_cross_freq=False, purify_e=False, purify_b=False, beam=None, return_all_spectra=False, lmax=None)
Computes the auto and cross-spectra from the frequency noise maps using NaMaster. Parameters
freq_noise_maps : np.ndarray Frequency noise maps, shape (n_freq, 3, n_pix). where 3 refers to the T, Q, U components. mask_analysis : np.ndarray Analysis mask, shape (n_pix,). workspaceff : nmt.NmtWorkspace NaMaster workspace for decoupling the spectra. nmt_bins : nmt.NmtBin NaMaster binning object for the spectra. compute_cross_freq : bool, optional Whether to compute cross-frequency spectra. Default is False. purify_e : bool, optional Whether to purify E-mode polarization. Default is False. purify_b : bool, optional Whether to purify B-mode polarization. Default is False. beam : np.ndarray, optional Beam correction factors, shape (n_freq, n_bins). If None, no beam correction is applied. Default is None. Returns
cl_decoupled_freq : np.ndarray Decoupled power spectra for each frequency, shape (n_freq, n_bins, 3). Where 3 refers to the T, E, B components. And T is set to zero. unbin_cl_decoupled_freq : np.ndarray Unbinned decoupled power spectra for each frequency, shape (n_freq, n_bins, 3). Where 3 refers to the T, E, B components. And T is set to zero.
Notes
- The function computes the auto-spectra for each frequency noise map.
- The T component is set to zero in the output spectra.
- The EB cross-spectra are ignored in the output.
Source code in src/megatop/utils/spectra.py
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 | |
megatop.utils.timer
Timer
Timer class to measure elapsed time.
A thread-safe singleton class that provides functionality to measure and log elapsed time. Can be used either as a context manager or with explicit start/stop calls.
Examples:
Using as context manager:
Using with explicit start/stop:
Source code in src/megatop/utils/timer.py
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 | |
__enter__()
Enter the Timer context manager and start timing.
This method is automatically called when entering a context manager block ('with' statement). It adds the current thread to the context threads queue and starts timing.
Returns:
-
Timer–The Timer instance for use in the context.
Source code in src/megatop/utils/timer.py
__exit__(*_exc_info)
Exit the Timer context manager and stop timing.
This method is automatically called when exiting a context manager block ('with' statement). It stops the timer for the current thread and logs the elapsed time.
Source code in src/megatop/utils/timer.py
__init__(thread='default')
Initialize a new Timer instance.
Parameters:
-
thread(str, default:'default') –Name to identify this timer instance.
Source code in src/megatop/utils/timer.py
start(thread='default')
Start the Timer with given name.
Should always be followed by a stop() call later in the code.
Parameters:
-
thread(str, default:'default') –Name of the timer to start.
Raises:
-
ValueError–when timer with given name already exists.
Source code in src/megatop/utils/timer.py
stop(thread='default')
Stop the Timer with given name and log the time elapsed since the start() call.
Parameters:
-
thread(str, default:'default') –Name of the timer to stop.
Raises:
-
ValueError–when timer with given name does not exist.
Source code in src/megatop/utils/timer.py
function_timer(thread=None)
Function decorator to time a function.
Wraps a function with a Timer context manager to measure and log its execution time.
Parameters:
-
thread(str | None, default:None) –Optional thread name to distinguish timer. If None, uses function name with arguments as thread name.
Returns:
-
Callable–A wrapped function that logs timing information when called.
Source code in src/megatop/utils/timer.py
megatop.utils.utils
MemoryUsage(message='')
' Prints the memory usage of the current process.
Parameters
args : argparse.Namespace The arguments from the command line. In particular looks for the verbose flag. If false, the function does nothing. message : str, optional The message to print. The default is ''.
Returns
None