Python reference¶
Generated from the type stubs otswap/__init__.pyi and otswap/io.pyi,
whose docstrings are the ones an IDE shows. Every function runs the code the
C++ reference documents, and the guide
explains how they work together.
otswap¶
Version¶
Errors¶
- exception otswap.Error¶
Raised by every otswap function on invalid input or failure.
- exception otswap.ExtrapolationWarning¶
Issued, once per call, when b(z) is extrapolated beyond the redshift range of its table.
Configuration¶
- class otswap.Config(*, n_realizations: int = 30, convergence: float = 0.001, seed: int = 0, cell_size: float = 3.0, reject_crossings: bool = True, max_unobserved_pixels_crossed: int = 0, verbosity: Verbosity = 'normal')¶
Free parameters of the reconstruction, as
otswap::Config: theconfigofreconstruct_box,reconstruct_lightconeandreconstruct_lightcone_cartesian.Every field is a keyword of the constructor, with the default of the C++ struct, and a read/write attribute. A value is converted to the field’s C++ type when it is stored, and raises
Errorif it cannot be; its rules (n_realizationsat least 1, …) are checked by the call that reads it, which refuses it with the library’s message. Each call works on its own copy, so the object passed is never changed.reprgives the constructor call; two configs compare equal when every field is equal. Unhashable, being mutable.- n_realizations: int¶
Independent reconstructions to run, each on its own N randoms; at least 1, default 30. Advice on the choice: the guide, section “Choosing the parameters”.
- convergence: float¶
The sweeps stop once the fraction of successful swaps in a sweep, swaps per tracer visited, no longer exceeds this threshold; in (0, 1), default 1e-3. Advice on the choice: the guide, section “Choosing the parameters”.
- seed: int¶
Seed of the random streams, 0 to 2**32 - 1; 0 draws one at random, and
Result.config.seedrecords the seed used.
- cell_size: float¶
Grid cell size in units of the mps; positive, default 3. Affects speed only, never the result. Advice on the choice: the guide, section “Choosing the parameters”.
- reject_crossings: bool¶
With a mask given to
reconstruct_lightconeorreconstruct_lightcone_cartesian, filter the result withreject_mask_crossings. Read with a mask only.
- max_unobserved_pixels_crossed: int¶
The threshold of that filter, the longest run of unobserved pixels a displacement’s arc may cross, as
reject_mask_crossingsdefines it; default 0, which rejects any crossing. Set it here: a second filter with the same mask and a higher threshold changes nothing, since the filter only marks displacements invalid. Read with a mask only. Advice on the choice: the guide, section “Choosing the parameters”.
- class otswap.CorrectionConfig(*, weight_by_realizations: bool = False, verbosity: Verbosity = 'normal')¶
Options of
real_space_lightconeandreal_space_box, asotswap::CorrectionConfig: theircorrection. Keywords, attributes,reprand equality asConfig.
- class otswap.RedshiftCut(min: float = -inf, max: float = inf)¶
A closed redshift range for
reconstruct_lightconeandmeasure_mps_profile, asotswap::RedshiftCut. The default, (-inf, +inf), cuts nothing. Wherever a RedshiftCut is taken, a(min, max)pair is accepted too.minandmaxare read/write; the call that reads the cut checks them (neither NaN,minnot abovemax).reprand equality asConfig.
- class otswap.DistanceCut(min: float = -inf, max: float = inf)¶
A closed range of comoving distance from the origin, in coordinate units, for
reconstruct_lightcone_cartesianandmeasure_mps_profile_cartesian, asotswap::DistanceCut: the counterpart ofRedshiftCut. The default, (-inf, +inf), cuts nothing. Wherever a DistanceCut is taken, a(min, max)pair is accepted too.The cut tests the distance of the given positions, tracers and randoms, before the reconstruction: the tracers outside it keep their row, flagged in
Result.outside_distance_cut, and the randoms outside it are dropped. A mean Lagrangian position may lie outside it.minandmaxare read/write; the call that reads the cut checks them (neither NaN,minnot abovemax).reprand equality asConfig.
- class otswap.BoxLimits(lower: numpy.typing.ArrayLike, upper: numpy.typing.ArrayLike)¶
The closed limits of a box for
reconstruct_box: the points withlower[k] <= x[k] <= upper[k]on each axis k, in coordinate units. Read-only.Wherever a BoxLimits is taken, a pair of corners
((x0, y0, z0), (x1, y1, z1))is accepted too. Two box limits compare equal when both corners are equal; unhashable.- Parameters:
lower (array_like, shape (3,)) – x, y, z of the lower and of the upper corner. Only their shape is checked here;
reconstruct_boxchecks that each bound is finite and thatlower[k] < upper[k].upper (array_like, shape (3,)) – x, y, z of the lower and of the upper corner. Only their shape is checked here;
reconstruct_boxchecks that each bound is finite and thatlower[k] < upper[k].
Distances¶
- class otswap.DistanceTable¶
Sampled relation between redshift, comoving distance and, optionally, the linear growth rate, interpolated in both directions. Immutable.
Build it with
DistanceTable.flatorDistanceTable.from_table.- static flat(omega_m: float, h: float, w0: float = -1.0, wa: float = 0.0, z_min: float = 0.0, z_max: float = 10.0, n_samples: int = 50000) DistanceTable¶
Tabulate a flat cosmology with dark energy w(a) = w0 + wa (1 - a).
Comoving distances are in Mpc/h, so
hcancels out of them and is only checked. The growth rate f = dlnD/dlna comes from integrating the linear growth equation. The range must cover every redshift of the tracers and randoms kept and of the corrected positions of the redshift-space correction, which can fall slightly outside the range of the data; a mean Lagrangian position beyond it gets a NaN redshift, without error.- Raises:
Error – If any parameter is out of range:
omega_mmust lie in (0, 1],hbe positive,w0andwafinite,z_minnon-negative,z_maxabovez_min, andn_samplesat least two.
- static from_table(redshift: numpy.typing.ArrayLike, distance: numpy.typing.ArrayLike, growth_rate: numpy.typing.ArrayLike | None = None) DistanceTable¶
Use a table computed by the caller. Redshift and distance must be strictly increasing, with at least two entries; distance in the unit that Cartesian coordinates and every length will then have.
growth_rate, when given, has the same length, every entry finite and positive. Withoutgrowth_rate,growth_rate_atraises.- Raises:
Error – If either of the first two arrays is not strictly increasing, if the lengths differ, if fewer than two points are given, if an entry is not finite, or if
growth_rateis neither None nor of the same length, or holds a value that is not finite and positive.
- property redshift: numpy.typing.NDArray[numpy.float64]¶
The sampled redshifts, shape (n_samples,), strictly increasing; a read-only view.
DistanceTable.from_table(t.redshift, t.distance, t.growth_rate)gives the same values, bit for bit, at every lookup.
- property distance: numpy.typing.NDArray[numpy.float64]¶
The comoving distance at each sampled redshift, Mpc/h from
flat, the unit of the table given tofrom_table; a read-only view.
- property growth_rate: numpy.typing.NDArray[numpy.float64] | None¶
The growth rate at each sampled redshift, a read-only view; None when the table carries none.
- distance_at(z: numpy.typing.ArrayLike) numpy.typing.NDArray[numpy.float64]¶
Comoving distance at each redshift. Raises outside the table.
- redshift_at(distance: numpy.typing.ArrayLike) numpy.typing.NDArray[numpy.float64]¶
Redshift at each comoving distance. Raises outside the table.
- growth_rate_at(z: numpy.typing.ArrayLike) numpy.typing.NDArray[numpy.float64]¶
Linear growth rate at each redshift. Raises outside the table, or if the table has no growth rate.
- otswap.to_cartesian(sky: numpy.typing.ArrayLike, distances: DistanceTable, *, angle_unit: AngleUnit) numpy.typing.NDArray[numpy.float64]¶
Convert sky coordinates, shape (N, 3), to Cartesian ones in the unit of the distance table, with the observer at the origin:
x = d cos(dec) cos(ra),y = d cos(dec) sin(ra),z = d sin(dec), d the comoving distance at the redshift, the convention ofreconstruct_lightcone. Raises if the array is not of shape (N, 3), if an entry is not finite, if a declination lies outside [-90, 90] degrees ([-pi/2, pi/2] radians), or if a redshift falls outside the distance table; the message names the object and gives the angle inangle_unit.
- otswap.to_sky(cartesian: numpy.typing.ArrayLike, distances: DistanceTable, *, angle_unit: AngleUnit) numpy.typing.NDArray[numpy.float64]¶
Convert Cartesian coordinates, shape (N, 3), in the distance table’s unit, to sky coordinates, shape (N, 3): right ascension in [0, 360) degrees ([0, 2 pi) radians), declination, redshift. The inverse of
to_cartesian, with the same observer; a position at the origin gets right ascension and declination 0. A row holding a NaN gives a NaN row. Raises if the array is not of shape (N, 3), if an entry is infinite, or if a distance falls outside the table; the message names the object and, for the distance, suggests a table covering a wider redshift range.
- otswap.point_to_sky(cartesian: numpy.typing.ArrayLike, *, angle_unit: AngleUnit) numpy.typing.NDArray[numpy.float64]¶
Distance from the origin, right ascension and declination of Cartesian points, shape (N, 3) each way, without a distance table.
- Parameters:
cartesian (array_like, shape (N, 3)) – x, y, z, in coordinate units.
angle_unit ({"deg", "rad"}) – The unit of the angles returned.
- Returns:
Per point: the distance, in coordinate units; the right ascension in [0, 360) degrees ([0, 2 pi) radians); the declination. The angles and distance of
to_sky, bit for bit, in the same unit; the origin gets right ascension and declination 0.- Return type:
ndarray, shape (N, 3)
Notes
Never raises on a value: a row holding a NaN gives NaN in all three, and an infinite coordinate an infinite distance. Raises only if the array is not of shape (N, 3) or
angle_unitis invalid. Asotswap::pointToSky, one point at a time.
Mask¶
- class otswap.Mask(fits_file: str)¶
HEALPix mask, read from a FITS file or built from a full-sky map in memory with
Mask.from_array. Immutable.A pixel is observed when its value is greater than 0, whatever its magnitude: fractional values, the smallest positive ones and +inf included. 0, negative values, -inf, NaN and UNSEEN mark an unobserved pixel. Each value is tested once, in float64, when the mask is built; no value is kept or used as a weight. The rule is the same for both sources.
NSIDE may be any integer from 1 to 2**29, HEALPix’s limit, and must be a power of 2 in the NESTED scheme. The mask holds one byte per pixel, 12 NSIDE**2 bytes: 12.6 MB at NSIDE 1024, 805 MB at NSIDE 8192, 3.2 GB at NSIDE 16384.
- static from_array(values: numpy.typing.ArrayLike, nest: bool = False) Mask¶
A full-sky HEALPix map given in memory, as healpy holds one.
- Parameters:
values (array_like, shape (12 NSIDE**2,)) – One value per pixel, of any real dtype: integer, unsigned, floating, or bool as 0 and 1. It is read once and not kept. A C-contiguous float64 array is read in place; any other input is first converted to one, which takes 8 bytes per pixel while the mask is built.
nest (bool, optional) – True for NESTED, False for RING, as healpy’s
nest.
- Raises:
Error – For another length, NSIDE above 2**29, NESTED with an NSIDE that is not a power of 2, an array that is not 1-D, values that are not real numbers, or a
nestthat is not a bool.
- property sky_area_deg2: float¶
their count times the pixel area, whatever their values.
- Type:
Area covered by the observed pixels, in square degrees
- allows(ra: numpy.typing.ArrayLike, dec: numpy.typing.ArrayLike, *, angle_unit: AngleUnit) numpy.typing.NDArray[numpy.bool_]¶
Whether each direction falls in an observed pixel. Raises if a right ascension is not finite, or a declination is not in [-90, 90] degrees ([-pi/2, pi/2] radians); the message gives it in
angle_unit.
Reconstruction¶
- otswap.reconstruct_box(tracers: numpy.typing.ArrayLike, randoms: numpy.typing.ArrayLike | None = None, *, mps: float | None = None, box: BoxLimits | tuple[numpy.typing.ArrayLike, numpy.typing.ArrayLike] | None = None, periodic: bool = False, config: Config = Config()) Result¶
Reconstruct in box geometry, with a constant mean particle separation.
- Parameters:
tracers (array_like, shape (N, 3)) – Cartesian coordinates.
randoms (array_like, shape (M, 3), optional) – Cartesian coordinates, M >= R * N with R
config.n_realizations, both counted insideboxwhen it is given; each realization uses a disjoint subset. If omitted, R * N randoms are drawn uniformly inbox, or without it in the bounding box of the tracers.mps (float, optional) – Mean particle separation, in coordinate units. If omitted, (V / N)^(1/3), with N the tracers inside the box and V its volume, the box being
Result.box:boxor, without it, the bounding box of the tracers and the given randoms, or of the tracers alone when the randoms are drawn (the box drawn randoms fill); it isResult.mps. Withoutbox, raises if the tracers, with the given randoms, span no volume.box (BoxLimits or ((x0, y0, z0), (x1, y1, z1)), optional) – The box of the reconstruction, closed: a point on a face is inside. The tracers outside it take no part in the reconstruction and are flagged in
Result.outside_box, the randoms given outside it are dropped, and the neighbour grids span it.Result.boxholds it.periodic (bool, optional) –
Whether the box is periodic, with
boxrequired: a whole simulation box with periodic boundary conditions; a sub-volume cut from one is not periodic (advice on the choice: the guide, section “Choosing the parameters”). Each side must be an integer multiple of the shortest, within a relative 1e-12 (a cube, or for instance 500 x 500 x 1000). The tracers and the given randoms outside the box are wrapped into it, not removed:Result.tracersholds the wrapped positions,outside_boxis all False, and the numbers wrapped areselection.tracers_wrappedandselection.randoms_wrapped. Distances are minimum-image; displacements lie in [-L/2, L/2) on each axis, of period L, andResult.lagrangianis wrapped into the box. Withoutmps, the mean particle separation is (V / N)^(1/3) of the box with N all the tracers. Withperiodic,"normal"prints in place of the box lines:otswap: wrapped <a> of <N> tracers into the periodic box [<x0>, <x1>] x [<y0>, <y1>] x [<z0>, <z1>] otswap: wrapped <b> of <M> randoms into the periodic box [<x0>, <x1>] x [<y0>, <y1>] x [<z0>, <z1>]
the second line only when randoms are given.
config (Config, optional) –
n_realizations,convergence,seed,cell_sizeandverbosity;reject_crossingsandmax_unobserved_pixels_crossedare not read. Withn_realizationsR, the randoms given must number at least R N.verbosity: seeVerbosity;"normal"prints one line,"detailed"the mps and its source before it. Withbox,"normal"prints first what the box left out:otswap: kept <n> of <N> tracers: <a> outside the box [<x0>, <x1>] x [<y0>, <y1>] x [<z0>, <z1>] otswap: kept <m> of <M> randoms: <b> outside the box [<x0>, <x1>] x [<y0>, <y1>] x [<z0>, <z1>]
the second line only when randoms are given.
- Raises:
Error – If an array is not of shape (N, 3), if fewer than 114 tracers are reconstructed (those inside
box, when given), if the randoms are too few, if any coordinate is not finite, or ifmpsis not positive; withoutmpsandbox, also if the tracers span no volume (all of them in one plane, on one line or at one point).Error – If a field of
configis out of range, the message describing the quantity and its rule.Error – With
periodic, ifboxis not given or its sides are not integer multiples of the shortest; the message names the sides.Error – If a bound of
boxis not finite or a lower bound is not below the upper one, or ifboxkeeps too few tracers or randoms; the message names the box.Error – From the neighbour search, with a message starting
"meshsearch: ", if its grid cannot be built: a cell ofconfig.cell_sizemps (in a periodic box, reduced to divide the shortest side a whole number of times: seeResult.cell_side) so small against the extent of the tracers and randoms that the grid would need more cells than it can count.
Notes
Without
periodic, the box is not periodic: nothing flows through its faces, so modes on the scale of the box itself cannot be reconstructed.
- otswap.reconstruct_lightcone(tracers_sky: numpy.typing.ArrayLike, randoms_sky: numpy.typing.ArrayLike, *, sky_area_deg2: float | None = None, mask: Mask | None = None, n_bins: int, distances: DistanceTable, angle_unit: AngleUnit, redshift_cut: RedshiftCut | tuple[float, float] | None = None, config: Config = Config()) Result¶
Reconstruct in lightcone geometry, from sky coordinates.
The mean particle separation is measured from the tracers: n_bins uniform redshift bins over the observed range, mps = (N / V)^(-1/3) in each, with V the shell volume implied by the sky area. The bin values are joined by linear interpolation and extrapolated linearly beyond the outermost bins. Raises if a bin holds fewer than 278 tracers, for a 2% accuracy on its mps (see
MpsProfile). For Cartesian coordinates, seereconstruct_lightcone_cartesian.Randoms are required: they carry the survey geometry, the selection function and the completeness.
- Parameters:
tracers_sky (array_like, shape (N, 3)) – Sky coordinates of the tracers.
randoms_sky (array_like, shape (M, 3)) – Sky coordinates of the randoms. Their number is checked after the redshift cut and the mask: the randoms kept must number at least
config.n_realizationstimes the tracers kept, which is M >= R * N, with Rconfig.n_realizations, when nothing is left out.sky_area_deg2 (float, optional) – Effective survey area, in square degrees, when no mask is given: the published value. Give exactly one of
sky_area_deg2andmask.mask (Mask, optional) – The survey’s mask. The sky area is then
mask.sky_area_deg2, and the mask is applied twice. Before the reconstruction, tracers and randoms on unobserved pixels are left out, asMask.allowsdecides: the randoms are dropped, and the tracers keep their row, flagged inResult.outside_mask. After it, withconfig.reject_crossings,reject_mask_crossingsis applied withconfig.max_unobserved_pixels_crossed; that function gives the rule. The mask and the redshift cut are both evaluated on every object; the objects kept pass both.n_bins (int) – Redshift bins used to measure mps(z), at least 1. Advice on the choice: the guide, section “Choosing the parameters”.
distances (DistanceTable) – The redshift to distance relation, with which the sky coordinates are converted and the shell volumes computed; it must cover the redshifts of the objects kept.
angle_unit (AngleUnit) – Unit of right ascension and declination, of the sky arrays given and of those of the result. A declination outside [-90, 90] degrees ([-pi/2, pi/2] radians) raises, the message giving it in this unit.
redshift_cut (RedshiftCut or (float, float), optional) – Tracers and randoms whose redshift lies outside this closed range are left out of the reconstruction, before anything else: the randoms are dropped, and the tracers keep their row, flagged in
Result.outside_redshift_cut. mps(z) is measured on the tracers kept, and the redshifts of the tracers and randoms kept must lie in the distance table. None, the default, andRedshiftCut()cut nothing.config (Config, optional) –
Every field;
reject_crossingsandmax_unobserved_pixels_crossedare read only with a mask.verbosity: seeVerbosity. With"normal", when a mask or a cut with a finite bound is applied, what was left out: one line for the tracers, one for the randoms, and one for the rejected crossings when the mask filter was applied, asResult.selectionrecords them; then the line of the call. In the form:otswap: kept <n> of <N> tracers: <a> outside the redshift cut [<zmin>, <zmax>], <b> outside the mask (<c> outside both) otswap: kept <m> of <M> randoms: <a> outside the redshift cut [<zmin>, <zmax>], <b> outside the mask (<c> outside both) otswap: rejected <r> of <D> displacements crossing more than <L> unobserved pixels in a row otswap: reconstructLightcone: <R> realizations of <N> tracers in <T> s; <K> without a valid displacement
"detailed"adds the mps(z) profile before the last line.
- Raises:
Error – If an array is not of shape (N, 3), if a declination is out of range, or if the redshift of a tracer or random kept falls outside the distance table (the message names which, and its row from 0 in the array given); if the randoms are too few; if both or neither of
sky_area_deg2andmaskare given.Error – If a bound of the cut is NaN or its minimum exceeds its maximum, or if too few tracers or randoms remain inside the cut and the mask (fewer than 114 tracers, or fewer randoms than
n_realizationstimes the tracers kept); the message gives the counts kept and dropped.Error – If a bin holds too few tracers for its density to be meaningful, the message giving an upper bound on the number of bins (see
MpsProfile), or if the profile extrapolates to an mps that is not positive at a tracer’s redshift.Error – If a field of
configis out of range, as inreconstruct_box.Error – From the neighbour search, as in
reconstruct_box, the cell beingconfig.cell_sizemean particle separations.
- otswap.reconstruct_lightcone_cartesian(tracers: numpy.typing.ArrayLike, randoms: numpy.typing.ArrayLike, *, sky_area_deg2: float | None = None, mask: Mask | None = None, n_bins: int, distances: DistanceTable | None = None, angle_unit: AngleUnit, distance_cut: DistanceCut | tuple[float, float] | None = None, config: Config = Config()) Result¶
Reconstruct in lightcone geometry, from Cartesian coordinates.
tracersandrandomsare comoving coordinates with the observer at the origin, in coordinate units. No cosmology is needed: the mean particle separation is measured inn_binsuniform bins of comoving distance from the origin,Result.mps_profileis a profile in distance, the objects are selected on the angles and distance ofpoint_to_sky,distance_cutis the counterpart ofreconstruct_lightcone’sredshift_cut, anddistancesis optional: it only fills the redshifts ofResult.tracers_skyandResult.lagrangian_sky, NaN without it, and the result is otherwise the same with or without it. Everything else is as inreconstruct_lightcone, which see.- Parameters:
tracers (array_like, shape (N, 3) and (M, 3)) – Cartesian coordinates, finite. The randoms kept must number at least
config.n_realizationstimes the tracers kept.randoms (array_like, shape (N, 3) and (M, 3)) – Cartesian coordinates, finite. The randoms kept must number at least
config.n_realizationstimes the tracers kept.sky_area_deg2 (optional) – As in
reconstruct_lightcone; give exactly one.mask (optional) – As in
reconstruct_lightcone; give exactly one.n_bins (int) – Distance bins used to measure mps(d), at least 1. Advice on the choice: the guide, section “Choosing the parameters”.
distances (DistanceTable, optional) – Only to fill the redshifts of the result, as above; its distances in the unit of the coordinates.
angle_unit (AngleUnit) – Unit of the right ascension and declination of the sky arrays of the result.
distance_cut (DistanceCut or (float, float), optional) – Objects whose comoving distance from the origin lies outside this closed range are left out, in coordinate units: the randoms are dropped, and the tracers keep their row, flagged in
Result.outside_distance_cut. mps(d) is measured on the tracers kept. None, the default, andDistanceCut()cut nothing.config (Config, optional) – As in
reconstruct_lightcone. With a distance cut, the report names it:<a> outside the distance cut [<dmin>, <dmax>] in coordinate units, and"detailed"adds mps(d).
- Raises:
Error – As
reconstruct_lightcone, with the same messages, for the arrays, the cut, the mask, the numbers of tracers and randoms, the profile andconfig; also if every tracer kept lies at the same distance.
- otswap.measure_mps_profile(tracers_sky: numpy.typing.ArrayLike, *, sky_area_deg2: float | None = None, mask: Mask | None = None, n_bins: int, distances: DistanceTable, redshift_cut: RedshiftCut | tuple[float, float] | None = None, angle_unit: AngleUnit, verbosity: Verbosity = 'normal') MpsProfile¶
Measure the mps(z) profile of a lightcone without reconstructing.
The steps of
reconstruct_lightconethat concern the tracers, in the same order and with the same code: the checks of the sky coordinates and of the cut, the redshift cut and the mask, the minimum number of tracers kept, and the profile with its per-bin threshold. The profile equals, bit for bit,Result.mps_profileof areconstruct_lightconecall with the same tracers, sky area or mask,n_bins,distancesandredshift_cut, whatever its randoms and other arguments. Use it to choosen_bins, or to inspect the profile, before a reconstruction.- Parameters:
tracers_sky (array_like, shape (N, 3)) – Sky coordinates of the tracers.
sky_area_deg2 (float, optional) – Effective survey area, in square degrees, when no mask is given, as in
reconstruct_lightcone. Give exactly one ofsky_area_deg2andmask.mask (Mask, optional) – The survey’s mask. The sky area is then
mask.sky_area_deg2, and the tracers on unobserved pixels are left out, asreconstruct_lightconeleaves them out.n_bins (int) – Redshift bins used to measure mps(z), at least 1. Advice on the choice: the guide, section “Choosing the parameters”.
distances (DistanceTable) – The redshift to distance relation; it must cover the redshifts of the tracers kept.
redshift_cut (RedshiftCut or (float, float), optional) – As in
reconstruct_lightcone: the tracers whose redshift lies outside this closed range are left out. None, the default, cuts nothing.angle_unit (AngleUnit) – The unit of right ascension and declination. A declination outside [-90, 90] degrees ([-pi/2, pi/2] radians) raises, the message giving it in this unit.
verbosity (Verbosity, optional) –
What the call prints; see
Verbosity. With"normal", when a mask or a cut with a finite bound is applied, the tracer line of the selection report ofreconstruct_lightcone; then the line of the call. In the form:otswap: kept <n> of <N> tracers: <a> outside the redshift cut [<zmin>, <zmax>], <b> outside the mask (<c> outside both) otswap: measureMpsProfile: <B> bins over [<zmin>, <zmax>]
"detailed"adds the mps(z) profile before the last line.
- Returns:
The profile.
- Return type:
- Raises:
Error – As
reconstruct_lightcone, with the same messages, if the tracer array is malformed, if a declination is out of range, if a bound of the cut is NaN or its minimum exceeds its maximum, if a cut or the mask keeps too few tracers, if a bin holds too few tracers, or if a redshift kept falls outside the distance table; also if both or neither ofsky_area_deg2andmaskare given.
- otswap.measure_mps_profile_cartesian(tracers: numpy.typing.ArrayLike, *, sky_area_deg2: float | None = None, mask: Mask | None = None, n_bins: int, distance_cut: DistanceCut | tuple[float, float] | None = None, verbosity: Verbosity = 'normal') MpsProfile¶
Measure the mps(d) profile of Cartesian tracers without reconstructing.
The profile in distance that
reconstruct_lightcone_cartesianmeasures from the same tracers, sky area or mask,n_binsanddistance_cut, bit for bit, with the same checks and messages. It needs neither a distance table nor an angle unit.- Parameters:
tracers (array_like, shape (N, 3)) – Cartesian coordinates of the tracers, with the observer at the origin, in coordinate units.
sky_area_deg2 (optional) – As in
measure_mps_profile; give exactly one.mask (optional) – As in
measure_mps_profile; give exactly one.n_bins (int) – Distance bins used to measure mps(d), at least 1. Advice on the choice: the guide, section “Choosing the parameters”.
distance_cut (DistanceCut or (float, float), optional) – As in
reconstruct_lightcone_cartesian.verbosity (Verbosity, optional) – What the call prints; see
Verbosity. The last line readsotswap: measureMpsProfile: <B> bins over [<dmin>, <dmax>] in coordinate units, the cut as inreconstruct_lightcone_cartesian.
- Returns:
The profile, in distance.
- Return type:
- Raises:
Error – As
measure_mps_profilefor the tracer array, the cut, the mask and the bins; also if every tracer kept lies at the same distance.
- otswap.reject_mask_crossings(result: Result, mask: Mask, max_unobserved_pixels_crossed: int = 0) None¶
Mark as invalid the displacements whose path crosses more than
max_unobserved_pixels_crossedunobserved pixels of the mask in a row; 0 rejects at the first one.The path is the great-circle arc between the directions of the tracer (
result.tracers) and of the tracer plus its displacement. Unobserved pixels met one after another along it, with no observed pixel between them, form a run, counted in distinct pixels; a displacement is judged by its longest run, and pixels in separate runs are not added together. The pixels containing the two endpoints are not tested and end a run. The count depends on NSIDE. Updatesresultin place; it only ever marks displacements invalid, and raises ifresultwas already filtered against a mask of a different NSIDE, or ifresultis a box result, which has no sky to filter against. It also raises ifresultis malformed: a NaN in a tracer outside the flagged ones or in a valid displacement, a flagged tracer with a valid entry, atracersarray without N rows, a flag,tracers_sky,lagrangianorlagrangian_skyarray whose size is neither 0 nor the one of its layout, or an entry ofvalidneither 0 nor 1. Tracers that took no part in the reconstruction (anyoutside_*flag) are left as they are.valid_realizations,mean_displacement,lagrangian,lagrangian_skyandlagrangian_distanceare recomputed, andresult.selectionrecords the filter. On a result holding a mean (n_realizations_meanabove 1, one realization),valid_realizationskeeps the counts of the tracers kept, and is 0 for those rejected.
- otswap.recompute_means(result: Result) None¶
Recompute
valid_realizations,mean_displacement,lagrangian,lagrangian_skyandlagrangian_distancefromdisplacementandvalid, as the reconstruction computes them: the sum over the valid realizations in realization order, divided by their count; thenlagrangian, wrapped into the box of a periodic result, and from itlagrangian_skyandlagrangian_distance, asResult.lagrangian_skydescribes. Updatesresultin place. Raises ifdisplacementorvalidhas the wrong size, an entry ofvalidis neither 0 nor 1, or a flag,tracersortracers_skyarray has a size that is neither 0 nor the one of its layout.
Results¶
- class otswap.Result¶
Displacement field produced by a reconstruction.
Displacements point from the observed (Eulerian) position of a tracer to its reconstructed (Lagrangian) position, which is the position of the random it is matched to.
Every array attribute is read-only, and only
idscan be assigned. The sky arrays (tracers_sky,lagrangian_sky) are in theangle_unitof the call that made the result; in degrees they are converted once, on first access, and kept.idsis a new copy on each access. Every other array is a view on memory owned by this object, and keeps it alive. Use.copy()to obtain a writable array. Filtering withreject_mask_crossingsupdatesvalid,valid_realizations,mean_displacementandlagrangianin place, so views taken earlier reflect it;lagrangian_skyis recomputed, and an array taken from it in degrees before the filter is not updated.The type is
otswap::Resultitself, so another nanobind module can take and return it (see “Using otswap from another package” in the documentation). The angle unit is kept by the module, not in the object: a result made by another module is in radians. Each array getter checks the size of the C++ array first, and raisesotswap.Errorfor a malformed result, which only another module can make. No attribute can be added to a result.- static from_arrays(displacement: numpy.typing.ArrayLike, valid: numpy.typing.ArrayLike, tracers: numpy.typing.ArrayLike, *, geometry: Literal['box', 'lightcone_sky', 'lightcone_cartesian'], tracers_sky: numpy.typing.ArrayLike | None = None, angle_unit: AngleUnit | None = None, distances: DistanceTable | None = None, outside_redshift_cut: numpy.typing.ArrayLike | None = None, outside_mask: numpy.typing.ArrayLike | None = None, outside_box: numpy.typing.ArrayLike | None = None, ids: numpy.typing.ArrayLike | None = None, config: Config | None = None, periodic: bool = False, box: BoxLimits | tuple[numpy.typing.ArrayLike, numpy.typing.ArrayLike] | None = None, outside_distance_cut: numpy.typing.ArrayLike | None = None) Result¶
Build a result from its arrays, as read back from a file.
- Parameters:
displacement (array_like, shape (n_realizations, n_objects, 3))
valid (array_like, shape (n_realizations, n_objects)) – Each entry 0 or 1 (or bool).
tracers (array_like, shape (n_objects, 3)) – Cartesian, in coordinate units.
geometry ({"box", "lightcone_sky", "lightcone_cartesian"}) – Required; never inferred.
"box"takes none oftracers_sky,angle_unitanddistances."lightcone_sky"requires all three."lightcone_cartesian"requiresangle_unit(the unit oftracers_skyand of the sky arrays of the result) and takes the other two as optional.outside_box,periodicandboxdescribe a box result and raise for either lightcone.tracers_sky (array_like, shape (n_objects, 3), optional) – Right ascension, declination and redshift, in
angle_unit. For"lightcone_cartesian"it is computed fromtracerswhen omitted, asreconstruct_lightcone_cartesiandoes: the redshift fromdistanceswhen given, NaN otherwise and where a distance falls outside the table.angle_unit ({"deg", "rad"}, optional) – Required for either lightcone, refused for a box; the unit of
tracers_skyand of the sky arrays of the result.distances (DistanceTable, optional) – The table of the reconstruction, from which
lagrangian_skyis computed. For"lightcone_cartesian"without it, the redshifts are NaN.outside_redshift_cut (array_like, shape (n_objects,), optional) – 0 or 1; all 0 when omitted.
outside_mask (array_like, shape (n_objects,), optional) – 0 or 1; all 0 when omitted.
outside_distance_cut (array_like, shape (n_objects,), optional) – 0 or 1; all 0 when omitted.
outside_box (array_like, shape (n_objects,), optional) – 0 or 1; all 0 when omitted. For a box result only.
ids (array_like, shape (n_objects,), optional) – The IDs, checked and stored as by assigning
Result.ids; none when omitted.config (Config, optional) – The configuration to record, as
Result.config; itsn_realizationsmust equal the arrays’. When omitted, the defaults with the arrays’n_realizations.periodic (bool, optional) – Whether the result is that of a periodic box (
reconstruct_boxwithperiodic); requiresbox; for a box result only. The displacements must already be minimum-image, in [-L/2, L/2) on each axis;lagrangianis wrapped into the box.box (BoxLimits or ((x0, y0, z0), (x1, y1, z1)), optional) – The limits of the box, recorded as
boxandselection.box_limits, asreconstruct_boxdoes when givenbox. Required withperiodic, each side then an integer multiple of the shortest. For a box result only.
Notes
valid_realizations,mean_displacement,lagrangian,lagrangian_skyandlagrangian_distanceare computed asrecompute_meanscomputes them, so arrays read back exactly give the reconstruction’s values, bit for bit. The profile, the mps and the selection counts are not reconstructed:mpsandmps_profileare None;boxis theboxgiven, or None.
- property n_realizations_mean: int¶
The number of realizations averaged into each displacement, when the result holds a mean as its only realization, as
io.read_displacement_meanreturns it; 1 when it does not, as in every result of a reconstruction. The displacement writers record a value above 1 as the keyword NRECMEAN, with NREC = 1.valid_realizationsthen counts the realizations averaged that were valid, up to it: always at mostn_realizationsxn_realizations_mean.
- property geometry: Literal['box', 'lightcone_sky', 'lightcone_cartesian']¶
"box"forreconstruct_box;"lightcone_sky"forreconstruct_lightcone;"lightcone_cartesian"forreconstruct_lightcone_cartesian. For a result read from a file, the file’s, a file of otswap 0.4 or earlier reading as"lightcone_sky"; forfrom_arrays, thegeometrygiven.
- property angle_unit: AngleUnit | None¶
the
angle_unitof the call that made the result;"rad"for a result made by another module. None for a box.- Type:
The unit of
tracers_skyandlagrangian_sky
- property config: Config¶
a new copy on each access, so changing it changes nothing in the result.
seedis the one used: the one drawn when 0 was given, so that the result can be reproduced.- Type:
The parameters of the run
- property distances: DistanceTable | None¶
The distance table of a lightcone result, a new copy on each access; None for a box.
- property ids: numpy.typing.NDArray[numpy.int64]¶
The ID of each object, shape (n_objects,), read-only; when none were set, 0..n_objects-1, the row of each object in the input.
Assignable, before writing or correcting the result: one 64-bit integer per object, negative ones allowed, no value twice; a float array is accepted when every entry is an integer. None, an empty array or exactly 0..n_objects-1 set no IDs. Any other value raises
Error, naming the first repeated value and its two entries, and leaves the IDs unchanged.The writers write them as the id column, among their default columns when IDs were set;
real_space_boxandreal_space_lightconecopy them into theRealSpaceCatalog. No computation reads them, and the reconstruction sets none.Each access returns a new copy, so store it once (
ids = result.ids) before indexing it in a loop.
- property tracers: numpy.typing.NDArray[numpy.float64]¶
Cartesian position of each tracer, the start of its displacements, shape (n_objects, 3): the array given, or the conversion of
tracers_sky. A tracer left out by the redshift cut or the mask has its conversion when its redshift lies in the distance table, NaN otherwise.
- property tracers_sky: numpy.typing.NDArray[numpy.float64] | None¶
Sky coordinates of each tracer, shape (n_objects, 3), in
angle_unit; None for a box. For sky input, in degrees, the angles come back asx * (pi/180) * (180/pi), which can differ from the input in the last bit. For a result ofreconstruct_lightcone_cartesian, the angles ofpoint_to_skyand the redshift at whichdistancesreaches the tracer’s distance, NaN when nodistanceswere given.
- property lagrangian: numpy.typing.NDArray[numpy.float64]¶
Mean Lagrangian position of each tracer,
tracers + mean_displacement, shape (n_objects, 3). NaN rows where the mean displacement is NaN.
- property mps: float | None¶
the mean particle separation used, given or computed, in coordinate units. None for a lightcone, whose separation is
mps_profile.- Type:
Box
- property periodic: bool¶
whether the box was periodic, as given to
reconstruct_box; False for a lightcone. A periodic result holds its tracers wrapped intobox, its displacements in [-L/2, L/2) on each axis, of period L, andlagrangianwrapped into the box.- Type:
Box
- property cell_side: float | None¶
The cell side of the neighbour grids actually used, in coordinate units. It is
config.cell_sizetimes the mps (for a lightcone, its representative value). In a periodic box it is the largest side, not above that value, that divides the shortest side of the box a whole number of times. None for a result not made by a reconstruction. Not written to files.
- property box: BoxLimits | None¶
the box of the reconstruction, the
boxgiven toreconstruct_boxor, without it, the bounding box of the tracers and the given randoms (of the tracers alone when the randoms were drawn), also whenmpswas given; every random matched to a tracer lies inside it; a copy. None for a lightcone.- Type:
Box
- property mps_profile: MpsProfile | None¶
the mean particle separation as a function of redshift or, for a result of
reconstruct_lightcone_cartesian, of comoving distance, measured on the tracers kept. None for a box. Keeps this result alive.- Type:
Lightcone
- property elapsed_seconds: float¶
Wall time of the call that made the result, in seconds. Two runs with the same seed give the same result but for this value.
- property displacement: numpy.typing.NDArray[numpy.float64]¶
Displacements, shape (n_realizations, n_objects, 3).
- property valid: numpy.typing.NDArray[numpy.bool_]¶
Whether each displacement is valid, shape (n_realizations, n_objects). All true unless a filter was applied.
- property valid_realizations: numpy.typing.NDArray[numpy.uint32]¶
Number of valid realizations per tracer, shape (n_objects,).
- property mean_displacement: numpy.typing.NDArray[numpy.float64]¶
Displacement averaged over the valid realizations, shape (n_objects, 3). NaN for a tracer with no valid realization.
- property outside_redshift_cut: numpy.typing.NDArray[numpy.bool_]¶
Whether each tracer lay outside the
redshift_cutofreconstruct_lightconeand took no part in the reconstruction, shape (n_objects,). All false without a cut, for a box and for a result ofreconstruct_lightcone_cartesian. A cut tracer has NaN displacements, no valid realization and a NaN mean displacement.
- property outside_distance_cut: numpy.typing.NDArray[numpy.bool_]¶
Whether each tracer lay outside the
distance_cutofreconstruct_lightcone_cartesianand took no part in the reconstruction, shape (n_objects,). All false without a cut, and for sky tracers or a box. A flagged tracer’s rows are as for a cut one.
- property outside_mask: numpy.typing.NDArray[numpy.bool_]¶
Whether each tracer fell on an unobserved pixel of the
maskofreconstruct_lightconeorreconstruct_lightcone_cartesianand took no part in the reconstruction, shape (n_objects,). All false without a mask. Independent ofoutside_redshift_cutandoutside_distance_cut: a tracer may carry both flags. A flagged tracer’s rows are as for a cut one.
- property outside_box: numpy.typing.NDArray[numpy.bool_]¶
Whether each tracer lay outside the
boxgiven toreconstruct_boxand took no part in the reconstruction, shape (n_objects,). All false without a box and for a lightcone. A flagged tracer’s rows are as for a cut one.
- property selection: SelectionCounts¶
What the reconstruction left out, and why. Keeps this result alive.
- property lagrangian_sky: numpy.typing.NDArray[numpy.float64] | None¶
Sky coordinates of each tracer’s mean Lagrangian position,
lagrangian, shape (n_objects, 3), inangle_unit: right ascension in [0, 360) degrees ([0, 2 pi) radians), declination, redshift, asto_skycomputes them with the reconstruction’s distance table. NaN rows wherelagrangianis NaN: the tracers left out by a selection and those with no valid realization; a position whose distance falls outside the table has a NaN redshift. For a result ofreconstruct_lightcone_cartesianthe angles are those ofpoint_to_sky, and every redshift is NaN when nodistanceswere given. None for a box. Recomputed byreject_mask_crossings.
- property lagrangian_distance: numpy.typing.NDArray[numpy.float64] | None¶
Distance from the origin of each tracer’s mean Lagrangian position,
lagrangian, aspoint_to_skycomputes it, in coordinate units, shape (n_objects,). NaN wherelagrangianis NaN. None for a box. Recomputed byreject_mask_crossings.
- class otswap.MpsProfile¶
The mean particle separation of a lightcone as a function of redshift or of comoving distance.
Measured by
reconstruct_lightcone, or alone bymeasure_mps_profile, a profile in redshift: the tracers kept inn_binsuniform redshift bins over [redshift_min,redshift_max], mps = (N / V)^(-1/3) in each, joined linearly and extrapolated linearly beyond the outermost bins. Each bin must hold at least 278 tracers, for a 2% accuracy on its mps; a refused number of bins comes with an upper bound, the number of tracers kept divided by 278, and a sparse tail may need fewer. Read-only.Measured by
reconstruct_lightcone_cartesian, or alone bymeasure_mps_profile_cartesian, a profile in comoving distance from the origin: the bins are uniform in distance over [distance_min,distance_max],distanceholds their centres,redshiftis empty, andredshift_minandredshift_maxare NaN; the other way round for a profile in redshift.- property redshift: numpy.typing.NDArray[numpy.float64]¶
Bin centres of a profile in redshift, shape (n_bins,); empty in a profile in distance.
- property distance: numpy.typing.NDArray[numpy.float64]¶
Bin centres of a profile in distance, in coordinate units, shape (n_bins,); empty in a profile in redshift.
- property mps: numpy.typing.NDArray[numpy.float64]¶
Mean particle separation at each centre, in coordinate units, shape (n_bins,).
- property count: numpy.typing.NDArray[numpy.uint64]¶
Tracers in each bin, shape (n_bins,).
- property distance_min: float¶
The smallest distance binned, in coordinate units; NaN in a profile in redshift.
- property distance_max: float¶
The largest distance binned, in coordinate units; NaN in a profile in redshift.
- property representative: float¶
The count-weighted median of
mps, in coordinate units, which sizes the grids of the reconstruction.
- at(value: numpy.typing.ArrayLike) numpy.typing.NDArray[numpy.float64]¶
The mps at each
value, in coordinate units, the shape ofvaluekept: a redshift for a profile in redshift, a comoving distance for a profile in distance. It is the value the reconstruction used at a tracer of that redshift or distance. Raises if the profile is empty or holds both redshift and distance nodes, or where the extrapolation is not positive.
- class otswap.SelectionCounts¶
What a reconstruction left out, and why. Read-only.
For
reconstruct_lightcone, the tracers removed aretracers_outside_redshift_cut + tracers_outside_mask - tracers_outside_both; forreconstruct_lightcone_cartesian,tracers_outside_distance_cut + tracers_outside_mask - tracers_outside_both; the same for the randoms, and the counts of the other cut are 0. Forreconstruct_boxwithbox, the tracers removed aretracers_outside_box, and the randoms removedrandoms_outside_box; withperiodicnothing is removed, these are 0, andtracers_wrappedandrandoms_wrappedgive what was wrapped into the box.tracersandrandomsare set only when aboxwas given,randoms0 when the randoms were drawn. Every other count is 0, and nothing else is applied, forreconstruct_box; the box counts are 0 for a lightcone.reprgives the report the reconstruction prints.- property redshift_cut: RedshiftCut | None¶
The redshift cut applied, a new
RedshiftCuton each access; None when no cut was applied.
- property distance_cut: DistanceCut | None¶
The distance cut applied, a new
DistanceCuton each access; None when no cut was applied.
- property tracers_wrapped: int¶
Tracers wrapped into the periodic box, because they lay outside it; 0 unless periodic.
Redshift-space correction¶
- otswap.real_space_lightcone(result: Result, *, distances: DistanceTable, bias: BiasTable, sigma: float, correction: CorrectionConfig = CorrectionConfig()) RealSpaceCatalog¶
Move a lightcone catalogue, the tracers of
result, from redshift space to real space.For each tracer: the projection of
result.mean_displacementon its line of sight, atresult.tracers, the Gaussian average of widthsigmaover the tracers with a valid realization, times f / (b + 3 f / 5) at its observed redshift; the tracer keeps its right ascension and declination and moves to the redshift of comoving distance d(z) + shift. A tracer without a valid realization still moves with the average of its neighbours; only one with no valid tracer within 3 sigma is not moved.The observed redshift of a tracer is that of
result.tracers_skywhen it is not NaN. Where it is NaN, as for the tracers of a result ofreconstruct_lightcone_cartesianbuilt without a table, it is the redshift at whichdistancesreaches the tracer’s distance from the origin.- Parameters:
result (Result) – A lightcone result, which carries its tracers;
skycomes back in itsangle_unit.distances (DistanceTable) – The table the result was reconstructed with, or one with the same distances, in the unit of the coordinates. Must carry the growth rate, and cover the corrected distances as well as the observed ones.
bias (BiasTable) – The b(z) table, as in
rsd_factor; warnsExtrapolationWarningonce if b(z) is extrapolated.sigma (float) – Width of the average, in coordinate units; 0 for none. Advice on the choice: the guide, section “Choosing the parameters”.
correction (CorrectionConfig, optional) –
weight_by_realizations: weight each neighbour by its number of valid realizations as well (seeCorrectionConfig).verbosity: what the call prints; seeVerbosity."normal"prints the line of the call;"detailed"before it how many of the corrected moved with their neighbours’ average, having no valid realization, and how many of the uncorrected were left out of the reconstruction or had no valid tracer within 3 sigma.
- Raises:
Error – For a box result, or one that is malformed or lacks its
tracersortracers_sky; if itsidsare neither empty nor one per object or hold a value twice; if a tracer kept is not finite or is at the origin; if the distance table has no growth rate; ifbiasextrapolates to a bias that is not positive; or if a corrected comoving distance is not positive or lies outside the distance table. The message names the tracer, and in the last case suggests a table covering a wider redshift range.Error – From the neighbour search, as in
neighbour_average, for the tracers corrected.
Notes
Tracers outside the reconstruction’s redshift or distance cut or mask are not corrected, take no part in any average, and have status 3. The catalogue carries the result’s
ids.On a result read by
otswap.io.read_displacement_completethe correction is that of the reconstruction itself, bit for bit, but for the right ascension and declination ofsky, which match within the rounding of the file’s conversion to degrees and back.
- otswap.real_space_box(result: Result, *, axis: int, redshift: float, distances: DistanceTable, bias: float, sigma: float, correction: CorrectionConfig = CorrectionConfig()) RealSpaceCatalog¶
Move a box catalogue, the tracers of
result, from redshift space to real space, with the line of sight alongaxis: the chain ofreal_space_lightconewith the projection on the axis, a single factor atredshiftwith the constantbias, and the shift along the axis.Unless
result.periodic, positions are not wrapped. For a periodic result the neighbours are found across the faces with minimum-image distances, and the corrected coordinate along the axis is wrapped into the box. Tracers outside the reconstruction’s box limits are not corrected, take no part in any average, and have status 3. The catalogue carries the result’sids.- Parameters:
result (Result) – A box result, which carries its tracers.
axis (int) – The line of sight: 0, 1 or 2 for x, y or z.
redshift (float) – The box’s redshift, at which the growth rate is taken.
distances (DistanceTable) – A table carrying the growth rate at
redshift.bias (float) – The tracers’ linear bias; finite and positive.
sigma (float) – Width of the average, in coordinate units; 0 for none. Advice on the choice: the guide, section “Choosing the parameters”.
correction (CorrectionConfig, optional) – As in
real_space_lightcone.
- Raises:
- class otswap.RealSpaceCatalog¶
A catalogue moved to real space; row i describes input tracer i.
Every array attribute is read-only;
skyis in theangle_unitof the result corrected, converted once and kept,idsis a new copy on each access, and every other array is a view on memory owned by this object, as for Result. As Result, the type isotswap::RealSpaceCatalogitself: a catalogue made by another module is in radians, and its array getters check the sizes first.- property geometry: Literal['box', 'lightcone_sky', 'lightcone_cartesian']¶
The geometry of the result corrected.
- property ids: numpy.typing.NDArray[numpy.int64]¶
The IDs of the objects, copied from the
Resultcorrected, shape (n_objects,), read-only; 0..n_objects-1 when it had none. Each access returns a new copy, so store it once (ids = catalog.ids) before indexing it in a loop.
- property angle_unit: AngleUnit | None¶
The unit of
sky, that of the result corrected;"rad"for a catalogue made by another module. None for a box.
- property sky: numpy.typing.NDArray[numpy.float64] | None¶
right ascension, in [0, 360) degrees ([0, 2 pi) radians), and declination of each tracer, and its corrected redshift, shape (n_objects, 3). The angles are those of
Result.tracers_sky; in degrees they come back asx * (pi/180) * (180/pi), which can differ from the input in the last bit. NaN rows for the tracers not moved. None for a box.- Type:
Lightcone
- property cartesian: numpy.typing.NDArray[numpy.float64]¶
Corrected Cartesian position, in coordinate units, shape (n_objects, 3). Box: the tracer with its axis coordinate moved. Lightcone:
r (1 + shift / |r|), the tracer moved along its line of sight. NaN rows for the tracers not moved.
- property shift: numpy.typing.NDArray[numpy.float64]¶
Shift applied along the line of sight, in coordinate units, shape (n_objects,): the factor times the averaged projection. NaN where nothing moved.
- property factor: numpy.typing.NDArray[numpy.float64]¶
f / (b + 3 f / 5) at each tracer’s observed redshift, shape (n_objects,); in a box the single factor, repeated. NaN for the tracers left out of the reconstruction.
- property status: numpy.typing.NDArray[numpy.uint8]¶
0 corrected, 1 moved with the average of its neighbours (it had no valid realization), 2 not moved, with no valid tracer within 3 sigma (with sigma = 0: no valid realization), 3 not moved, left out of the reconstruction by its redshift or distance cut, mask or box limits (
Result.outside_*say which). SeeCorrectionStatus.- Type:
What the correction did with each tracer, shape (n_objects,)
- property valid_realizations: numpy.typing.NDArray[numpy.uint32]¶
Valid realizations of each tracer, as in the result corrected, shape (n_objects,).
- property n_neighbours: numpy.typing.NDArray[numpy.uint32]¶
Tracers with a valid realization averaged for each tracer, itself included if valid, shape (n_objects,); 0 for a tracer left out.
- property n_realizations_averaged: numpy.typing.NDArray[numpy.uint32]¶
Sum of the valid realizations of those tracers, shape (n_objects,).
- class otswap.CorrectionStatus¶
The values of
RealSpaceCatalog.status.- CORRECTED = 0¶
Had a valid realization; moved.
- MOVED_BY_NEIGHBOURS = 1¶
Had no valid realization; moved with its neighbours’ average.
- NO_VALID_NEIGHBOUR = 2¶
no valid realization); not moved.
- Type:
No valid tracer within 3 sigma (with sigma = 0
- LEFT_OUT = 3¶
Outside the reconstruction’s redshift or distance cut, mask or box limits; not moved.
- otswap.radial_projection(displacement: numpy.typing.ArrayLike, positions: numpy.typing.ArrayLike) numpy.typing.NDArray[numpy.float64]¶
Component of each displacement, shape (N, 3), along the line of sight of its position, shape (N, 3), Cartesian, finite and away from the origin (for example
Result.tracers):r . d / |r|, shape (N,), positive when the displacement points away from the observer. NaN displacements give NaN. Raises if the shapes differ, if a position is not finite or is at the origin, or if a displacement is infinite; the message names the object.
- otswap.axis_projection(displacement: numpy.typing.ArrayLike, axis: int) numpy.typing.NDArray[numpy.float64]¶
Component of each displacement, shape (N, 3), along the Cartesian axis 0, 1 or 2, the line of sight of a box; shape (N,). NaN displacements give NaN. Raises if the axis is not 0, 1 or 2, or if a displacement is infinite.
- otswap.neighbour_average(positions: numpy.typing.ArrayLike, values: numpy.typing.ArrayLike, valid_realizations: numpy.typing.ArrayLike, *, sigma: float, weight_by_realizations: bool = False, box: BoxLimits | tuple[numpy.typing.ArrayLike, numpy.typing.ArrayLike] | None = None, periodic: bool = False) NeighbourAverage¶
Gaussian average of
valuesover the neighbours of each object.An object is valid when its entry of
valid_realizationsis greater than zero. Each object, valid or not, receives the mean of the values of the valid objects within 3 sigma of its position, itself included when valid, weighted by exp(-d^2 / (2 sigma^2)) and, withweight_by_realizations, by their valid realizations; the weights are normalised, so a constant value comes back unchanged. NaN when no valid object lies within 3 sigma. With sigma = 0,valuesis returned unchanged.- Parameters:
positions (array_like, shape (N, 3)) – Cartesian coordinates, finite.
values (array_like, shape (N,)) – Finite wherever the object is valid.
valid_realizations (array_like, shape (N,)) – Non-negative integers, such as
Result.valid_realizations.sigma (float) – Width of the Gaussian, in the unit of the positions; finite and non-negative. Advice on the choice: the guide, section “Choosing the parameters”.
weight_by_realizations (bool, optional) – Weight each neighbour by its valid realizations as well.
box (BoxLimits or ((x0, y0, z0), (x1, y1, z1)), optional) – The limits of a periodic box; given only with
periodic. Each side must be an integer multiple of the shortest, and every position must lie inside the limits (closed): wrap them first.periodic (bool, optional) – Find the neighbours across the faces of
box, with minimum-image distances.
- Returns:
The averages and, per object, the number of valid objects averaged and the sum of their valid realizations.
- Return type:
- Raises:
Error – If the shapes differ, if a position is not finite, if the value of a valid object is not finite, or if sigma is negative or not finite; the message names the object.
Error – If
periodicis given withoutboxorboxwithoutperiodic; withperiodic, if a bound ofboxis not finite, a lower bound is not below the upper one, a side is not an integer multiple of the shortest, or a position lies outside the box.Error – From the neighbour search, with a message starting
"meshsearch: ", if sigma > 0 and, withoutperiodic, the positions span no volume (a single object, or all in one plane or on one line).
Notes
The result does not depend on the internal neighbour grid within rounding, and is the same bit for bit for the same inputs, whatever the number of threads.
- class otswap.NeighbourAverage¶
What
neighbour_averagereturns, shape (N,) each.- values: numpy.typing.NDArray[numpy.float64]¶
The average at each object; NaN with no valid object within 3 sigma; with sigma = 0, the input value.
- n_neighbours: numpy.typing.NDArray[numpy.uint32]¶
Valid objects averaged, the object itself included when it is valid.
- n_realizations_averaged: numpy.typing.NDArray[numpy.uint32]¶
Sum of the valid realizations of those objects.
- otswap.rsd_factor(redshift: numpy.typing.ArrayLike, distances: DistanceTable, *, bias: BiasTable) numpy.typing.NDArray[numpy.float64]¶
The factor f / (b + 3 f / 5) at each redshift, shape (N,).
f is
distances.growth_rate_at(z), b(z) thebiastable at z. Beyond the table’s nodes b(z) is extrapolated linearly from the end segments, and oneExtrapolationWarningis issued for the call. Raises if the table has no growth rate, if a redshift is not finite or lies outside the distance table, or if the extrapolated bias at a redshift is not positive; the message names the object.
- otswap.rsd_factor_box(redshift: float, distances: DistanceTable, *, bias: float) float¶
The factor f / (b + 3 f / 5) of a box at a single redshift, with a constant, positive bias. Raises if the redshift is not finite or lies outside the distance table, if the table has no growth rate, or if the bias is not positive.
- class otswap.BiasTable(redshift: numpy.typing.ArrayLike, bias: numpy.typing.ArrayLike)¶
A b(z) table: the linear bias of the tracers at redshift nodes, interpolated linearly between them and extrapolated linearly beyond them from the first or last segment. Immutable.
Read one from a file with
otswap.io.read_bias_table.- property redshift: numpy.typing.NDArray[numpy.float64]¶
Redshifts of the nodes, shape (n,).
- property bias: numpy.typing.NDArray[numpy.float64]¶
Bias at each node, shape (n,).
- otswap.shift_radially(positions: numpy.typing.ArrayLike, shift: numpy.typing.ArrayLike) numpy.typing.NDArray[numpy.float64]¶
Move each position, shape (N, 3), by its shift, shape (N,), along its own line of sight:
r (1 + shift / |r|). A positive shift moves away from the observer. A NaN shift gives a NaN row. Raises if the shapes differ, if a position is not finite or is at the origin, or if a shift is infinite; the message names the object.
- otswap.shift_along_axis(positions: numpy.typing.ArrayLike, shift: numpy.typing.ArrayLike, axis: int) numpy.typing.NDArray[numpy.float64]¶
Move each position, shape (N, 3), by its shift, shape (N,), along the Cartesian axis 0, 1 or 2, without wrapping, whether or not a box is periodic. A NaN shift gives NaN along the axis; infinite ones raise.
Aliases¶
- otswap.AngleUnit: TypeAlias = Literal['deg', 'rad']¶
- otswap.Verbosity: TypeAlias = Literal['silent', 'normal', 'detailed']¶
What a reconstruction or a correction prints, to
sys.stdout, each line starting withotswap::"silent": nothing;"normal": the selection report of a lightcone, when a selection applied, and of a box, whenboxwas given; then one line per call with its time and what was lost:otswap: reconstructBox: <R> realizations of <N> tracers in <T> s; <K> without a valid displacement otswap: reconstructLightcone: <R> realizations of <N> tracers in <T> s; <K> without a valid displacement otswap: measureMpsProfile: <B> bins over [<zmin>, <zmax>] otswap: measureMpsProfile: <B> bins over [<dmin>, <dmax>] in coordinate units otswap: realSpaceLightcone: corrected <C> of <N> tracers in <T> s; <U> left uncorrected otswap: realSpaceBox: corrected <C> of <N> tracers in <T> s; <U> left uncorrected
"detailed": as"normal", with the lines that explain it: the mean particle separation of a box and its source, the mps(z) or mps(d) profile of a lightcone, and the breakdown of the corrected and of the uncorrected.
The counts behind every line are in the object returned. The extrapolation of b(z) is an
ExtrapolationWarning, whatever the verbosity.
OpenMP runtime¶
- otswap.openmp_root() str | None¶
The directory of the OpenMP runtime a macOS wheel of otswap ships, the
openmpdirectory of the package:lib/libomp.dylib, the LLVM libomp otswap was built with, whose install name is@rpath/libomp.dylib;include/omp.handinclude/ompx.h; and LLVM’s licence,LICENSE.TXT. None when otswap ships no runtime: a Linux wheel, or a build from source, which uses the runtime it was built against.A package with OpenMP code of its own gives this directory to CMake as
OpenMP_ROOT, so that its extension loads the same runtime as otswap; see “Using otswap from another package” in the documentation. The version of the runtime may change between minor releases of otswap.
otswap.io¶
Tables¶
- class otswap.io.Column(name: str, data: numpy.typing.ArrayLike, *, type: Literal['D', 'J', 'K'] = 'D', description: str = '', unit: str = '')¶
One column of a table to write. Read-only.
- property type: Literal['D', 'J', 'K']¶
- property data: numpy.typing.NDArray[numpy.float64] | numpy.typing.NDArray[numpy.int64]¶
int64 for a
"K"column, float64 otherwise.- Type:
The values
- class otswap.io.Table¶
A table read from file. Read-only; its arrays are views that keep it alive.
- property values: numpy.typing.NDArray[numpy.float64]¶
The
columnsofread, shape (n_rows, n_columns).
- property integers: numpy.typing.NDArray[numpy.int64]¶
The
integer_columnsofread, shape (n_rows, n_integer_columns).
- otswap.io.read(file: Path, columns: Sequence[str | int], *, integer_columns: Sequence[str | int] = (), delimiter: str = ' ', comment: str = '#') Table¶
Read selected columns of a table:
columnsas float64,integer_columnsexactly as int64, each in the order given.In FITS the columns are named, case insensitively, and must be scalar; an integer column must have an integer type. In ASCII an int, or a str of digits, is a 0-based index; any other str is a name, looked up in the last line starting with
###before the first data row, wherewriteputs the names. Lines that are empty, hold only blanks, tabs anddelimiter, holdcommentas their first other character, or start with###(a names line, whatevercommentis) are skipped; every other line is a data row, so a line of text such as a header must start withcomment, after any blanks, tabs ordelimiter. Fields are separated bydelimiter, blanks or tabs. Each requested field, and the first field of every data row, must be a number as a whole: decimal, hexadecimal (0x10),nan,inforinfinity, in any case and with an optional sign. Fields not requested after the first are not read. A carriage return ending a line is ignored. An ASCII integer field is an optional-followed by digits.NaN and infinities are returned as stored, in both formats. Raises if the file is missing or unreadable, a column is absent (in ASCII the message lists the names of the
###line) or requested twice, a requested index is too large, a row is too short, a field that must be a number is not one, an integer field is not an integer, lies outside the 64-bit range or comes from a FITS column of floating type, or a FITS integer column holds a null value. The message names the ASCII line, counted from 1 with comments and blank lines, the field, counted from 1, or the FITS row, counted from 1.
- otswap.io.write(file: Path, columns: Sequence[Column], *, precision: int = 9, keywords: Sequence[tuple[str, str, str]] | None = None) None¶
Write a table. An existing file is overwritten.
- Parameters:
precision (int, optional) – Significant digits of a
"D"value in ASCII, from 1 to 17; 17 reads back as the same float64. FITS stores the values themselves.keywords (sequence of (str, str, str), optional) –
(name, value, comment)tuples, written in this order; a name is 1 to 8 characters of A-Z, 0-9,-and_, a value at most 68 characters, and neither value nor comment holds a line break. In FITS a value that reads entirely as an integer or a finite number is written as one, anything else as a string. A comment fits what a FITS card leaves after the value: 47 characters after a value within 20 columns, fewer after a longer one (a string takes its length plus its two quotes, an apostrophe counting twice; a number its length), the card holding 80 columns of which the name takes 10 and “ / “ 3.
- Raises:
Error – If no column is given, the columns differ in length, or a
"J"value is not an integer in [-2**31, 2**31) (the message names the column and the row); if a keyword name is invalid, a keyword value exceeds 68 characters, a keyword comment exceeds the room its card leaves, a column description exceeds 68 characters (an apostrophe counting twice), or a keyword holds a line break; if the precision is outside [1, 17]; or if the file cannot be written.
- otswap.io.read_keywords(file: Path, *, extname: str = '') list[tuple[str, str, str]]¶
Read the keywords of a table, in file order, as
(name, value, comment)tuples, the formwritetakes;commentis always “”.FITS (a name ending in .fits, .fit or .fits.gz): the header of the first extension or, with
extname, of the extension of that EXTNAME. Every card is returned but COMMENT, HISTORY and those without a name, the structural ones included (XTENSION, NAXISn, TTYPEn, TFORMn, EXTNAME and the like). A string value is returned without its quotes and outer blanks, any other value as its card text: a number as written, with an exponent in E, a logical as T or F.ASCII: the
## NAME = value / commentlines of the header, before the###line or the first data row;extnameis ignored. The value is the text after the=up to the first/with a blank on each side, as written, so a value that itself holds such a/is cut there.Values are str: convert them as needed, for example with
float, which reads a number written with 17 significant digits back exactly.- Raises:
Error – If the file cannot be opened, is not a valid FITS file, has no first extension, or has no extension of that EXTNAME.
- otswap.io.column_names(file: Path, *, extname: str = '', delimiter: str = ' ', comment: str = '#') list[str]¶
The names of the columns of a table, in column order: the names
readfinds in the same file.FITS (a name ending in .fits, .fit or .fits.gz): the TTYPEn of the table in the first extension or, with
extname, of the extension of that EXTNAME, compared ignoring case, as written.readlooks a name up ignoring case.ASCII: the fields of the last line starting with
###before the first data row, separated bydelimiter, blanks or tabs, which is wherereadlooks names up with the samedelimiterandcomment;extnameis ignored. A part written to a twin file is read by giving that file,twin_file(file, twin).- Raises:
Error – If the file cannot be opened or is not a valid FITS file, if the first extension or the extension of that EXTNAME is missing or is not a table, or if an ASCII file has no
###line before its first data row; the message names the file.
- class otswap.io.TablePart(columns: Sequence[Column], *, extname: str = '', twin: str = '', precision: int = 9, keywords: Sequence[tuple[str, str, str]] | None = None)¶
One table of a file holding several, for
write_parts.In FITS each part is a binary table of the same file, the first in the first extension and the others after it, in order, each with its EXTNAME. In ASCII the first part is written to the file itself and each other one to its twin file,
twin_file(file, twin); each file is a table aswritewrites it, readable byread.- Parameters:
columns (sequence of Column) – The columns, all of the same length.
extname (str, optional) – The EXTNAME of the FITS table: 1 to 68 characters of A-Z, a-z, 0-9,
-and_. Optional for the first part; required for the others, and unique in the file, ignoring case.twin (str, optional) – The name of the ASCII twin file, with the same rules. Empty for the first part, which is written to the file itself; required for the others, and unique in the file, ignoring case. So every part reads back with its own
extnameandtwin.precision (int, optional) – As in
write.keywords (sequence of (str, str, str), optional) – As in
write; a keyword named EXTNAME is refused bywrite_parts.
- otswap.io.write_parts(file: Path, parts: Sequence[TablePart]) None¶
Write a file holding several tables: FITS, one binary table per part, from the first extension; ASCII, the first part in the file and each other one in its twin file. Existing files are overwritten; twin files of an earlier write that this one does not write are left where they are, so
has_partstill finds them.- Raises:
Error – If no part is given, if an extname or a twin is missing, malformed or repeated as described in
TablePart, if the first part has a twin, if a part holds a keyword named EXTNAME, or aswritefor any part.
- otswap.io.read_part(file: Path, *, extname: str, twin: str, columns: Sequence[str | int], integer_columns: Sequence[str | int] = ()) Table¶
Read selected columns of one part of a file
write_partswrote, the first included, asreaddoes, given theextnameandtwinof the part. FITS: the table of that EXTNAME, compared ignoring case, or with an emptyextnamethe first table;twinis ignored. ASCII: the table intwin_file(file, twin), or with an emptytwinin the file itself;extnameis ignored.- Raises:
Error – As
read, and if the file has no table of that EXTNAME, or the twin file is missing.
- otswap.io.has_part(file: Path, *, extname: str, twin: str) bool¶
Whether a file holds a part, the first included, given the
extnameandtwinof the part. FITS: whether it holds a table of that EXTNAME, compared ignoring case, or with an emptyextnamea first table;twinis ignored. ASCII: whethertwin_file(file, twin)or, with an emptytwin, the file itself can be opened;extnameis ignored, and with atwinthe file itself is not checked. RaisesErrorif a FITS file cannot be opened.
- otswap.io.twin_file(file: Path, twin: str) str¶
The ASCII twin file of a part:
<stem>.<twin>.<ext>, ext the text after the last.of the file name and stem what precedes it, or<file>.<twin>when the name holds no.; for exampleout/field.datwith twinmpsgivesout/field.mps.dat.
- otswap.io.read_bias_table(file: Path, *, delimiter: str = ' ', comment: str = '#') otswap.BiasTable¶
Read a b(z) table: FITS from the columns named REDSHIFT and BIAS, ASCII from columns 0 and 1. Checked as
BiasTablechecks its arrays. Raises if the file cannot be read (asread), if it holds fewer than two rows, if a redshift is not finite or not greater than the one before, or if a bias is not finite or not positive; the message names the file and the row, as the ASCII line or the FITS row, each counted from 1.
Writers¶
- otswap.io.write_displacement_mean(file: Path, result: otswap.Result, *, groups: Sequence[DisplacementGroup] | None = None, lightcone_tables: bool = True) None¶
Write the mean displacement field of a result, one row per tracer.
The groups and their columns:
"id": id (64-bit integer),Result.ids: the row of the tracer in the input when no IDs were set;"tracer_sky": tracRA, tracDec (degrees), tracRed, the observed tracer; lightcone only;"lagrangian_sky": lagrRA, lagrDec, lagrRed,Result.lagrangian_sky; lightcone only;"tracer": tracX, tracY, tracZ,Result.tracers;"lagrangian": lagrX, lagrY, lagrZ,Result.lagrangian;"displacement": displX, displY, displZ,Result.mean_displacement;"valid_realizations": nValidRec;"selection": outsideRedshiftCut, outsideMask (0 or 1), and outsideDistanceCut for everylightcone_cartesianresult, with or without a cut, or one that flags a tracer inoutside_distance_cut; lightcone only;"outside_box": outsideBox (0 or 1),Result.outside_box; box only, all 0 in a periodic box.
- Parameters:
groups (sequence of DisplacementGroup, optional) – In output order; None for the default: box tracer, lagrangian, displacement, valid_realizations, and outside_box when a
boxwas given toreconstruct_box; lightcone tracer_sky, lagrangian_sky, tracer, lagrangian, displacement, valid_realizations, selection; id first when IDs were set. With groups given, id is written only when listed;read_displacement_meanneeds tracer, displacement and valid_realizations, and tracer_sky in a lightcone.lightcone_tables (bool, optional) – False to leave out the profile and the table of a lightcone result; no effect on a box result, which has neither.
- Raises:
Error – If a group is repeated or does not apply to the geometry (
"outside_box"to a lightcone, or a lightcone group to a box), or if a field a group reads does not have the size of its layout; whatever the groups, ifidsis neither empty nor one per object or holds a value twice, if the result’s realization count differs from its configuration’s, if its count of realizations averaged is 0, or above 1 while it holds several realizations, if a box result’s box differs from the limits recorded in its selection, if a periodic result is not a box result, has no recorded limits or flags a tracer inoutside_box, or if the profile written does not have one mps and one count per node; or aswrite.
Notes
Floating values are written with 9 significant digits in ASCII, so a position or displacement read back from ASCII equals the one written within that rounding, and the box keywords of a box that is not periodic are rounded outward to that precision, so that the tracers as written lie within the box as written; a periodic box keeps its limits exactly. FITS stores the values themselves. Keywords: those of the reconstruction, listed with
write_displacement_complete(PERIODIC, NTRWRAP and NRNWRAP for a periodic box, the counts each omitted when 0), and MPSPART = 1 and DISTPART = 1 when the profile and the table are written. In FITS the table is named DISPLACEMENTS.A lightcone file also holds the mps(z) profile and the distance table of the result, as
write_displacement_completewrites them (the same columns and keywords, 17 digits in ASCII, the HDUs MPSPROF and DISTANCE in FITS, the twin files .mps and .distances in ASCII), each with its own PRODUCT, mean displacements mps profile and mean displacements distance table. Each is written whenlightcone_tablesis true and the result is a lightcone that holds it; a result made byResult.from_arraysholds no profile, and a table only when givendistances. The file then carries both, andread_displacement_meanreturns them.
- otswap.io.DisplacementGroup: TypeAlias = Literal['id', 'tracer_sky', 'lagrangian_sky', 'tracer', 'lagrangian', 'displacement', 'valid_realizations', 'selection', 'outside_box']¶
- otswap.io.read_displacement_mean(file: Path, *, angle_unit: otswap.AngleUnit | None = None) otswap.Result¶
Read a file written by
write_displacement_meaninto aResultholding the mean as its only realization, its sky arrays inangle_unit.The geometry is the file’s, and its keywords are read as
read_displacement_completereads them: the configuration (withn_realizations1), the selection counts, the box and the mps of a box. The result hasn_realizations1;displacementandmean_displacementboth hold the mean displacement;validis true where the tracer has at least one valid realization;valid_realizationsis the file’s count;n_realizations_meanis the number of realizations averaged, NRECMEAN when the file holds it, NREC otherwise.Required columns: tracX..tracZ, displX..displZ and nValidRec, and in a lightcone tracRA, tracDec and tracRed. The others are read when the file holds them: id (
ids, as having no IDs when they are 0..n_objects-1), lagrX..lagrZ (lagrangian), lagrRA..lagrRed (lagrangian_sky, in a lightcone), outsideRedshiftCut, outsideMask and outsideDistanceCut (lightcone), outsideBox (box). Without them a flag is all false, andlagrangianistracers+mean_displacement. In a lightcone,lagrangian_distanceis always computed fromlagrangian, andlagrangian_skyis computed from it asrecompute_meansdoes: with the distance table, with NaN redshifts for a profile in distance or alightcone_cartesianfile, and None for alightcone_skyfile with neither. The mps profile and the distance table are read when the file declares them (MPSPART, DISTPART), from the extensions or twin files ofwrite_displacement_mean; a file of otswap 0.2 has neither.- Parameters:
file (str or os.PathLike) – A mean displacement file; its extension sets the format.
angle_unit ({"deg", "rad"}, optional) – The unit of the sky arrays of the result. Required for a lightcone file (
lightcone_skyorlightcone_cartesian); a box file has no angles and refuses it.
- Returns:
The mean as a result of one realization.
- Return type:
- Raises:
Error – If
angle_unitis given for a box file, or missing for a lightcone file; if the file cannot be read; if its PRODUCT is not that ofwrite_displacement_mean; if a keyword is malformed or a required column is missing; if it does not hold NOBJECTS rows; if a flag is neither 0 nor 1, a count of valid realizations lies outside [0,n_realizations_mean], or an ID is repeated; if the file records the tracer counts of the selection (NTRAC) and one disagrees with the flags read; if a box file declares a profile or a table; if a declared profile or table is missing, is not the part written, by its PRODUCT, or is malformed. Every message names the file, and a row by its ASCII line or FITS row, counted from 1.
Notes
FITS reads back every value as written. ASCII reads back what was written with 9 significant digits: the positions, the displacements and the sky coordinates, the right ascension in [0, 360) degrees as the writer folds it; the profile and the table, with 17 digits, read back identical.
recompute_meanson the result read setsvalid_realizationsto 0 or 1, the count of its one realization.
- otswap.io.write_displacement_complete(file: Path, result: otswap.Result, *, lightcone_tables: bool = True) None¶
Write every realization of a result, losslessly, with what a reader needs to rebuild it: one row per realization and tracer, ordered [realization][object]; and, for a lightcone, its mps profile and its distance table when it holds one.
Columns: realization; id (
Result.idsas inwrite_displacement_mean); for a lightcone, tracRA, tracDec (degrees, the right ascension as given, not folded into [0, 360)) and tracRed; tracX..tracZ (Result.tracers); displX..displZ (Result.displacement); valid; outsideRedshiftCut, outsideMask, outsideBox (0 or 1, in both geometries); outsideDistanceCut (0 or 1) last, for everylightcone_cartesianresult, with or without a cut, or one that flags a tracer inoutside_distance_cut, absent otherwise. The columns of the tracer, id and flags are repeated in every realization.- Parameters:
lightcone_tables (bool, optional) – False to leave out the profile and the table of a lightcone result; no effect on a box result, which has neither.
- Raises:
Error – If a field read does not have the size of its layout (
tracers_skyincluded, for a lightcone), ifidsis neither empty nor one per object or holds a value twice, if the result’s realization count differs from its configuration’s, if its count of realizations averaged is 0, or above 1 while it holds several realizations, if a box result’s box differs from the limits recorded in its selection, if a periodic result is not a box result, has no recorded limits or flags a tracer inoutside_box, if the profile written does not have one mps and one count per node, or aswrite.
Notes
Floating values are written with 17 significant digits in ASCII, and as they are in FITS, so every value reads back identical, NaN included, in both formats;
Result.from_arrayson the arrays read back gives the reconstruction’s means bit for bit.read_displacement_completereads the file back into aResult.Keywords, those of
write_displacement_meantoo: NREC and, whenResult.n_realizations_meanis above 1, NRECMEAN, the realizations averaged (NREC is then 1); SEED (the seed used), CONVERG, CELLSIZE, REJCROSS (0 or 1), CFMAXPIX, VERBOSE (silent, normal or detailed): the configuration; MPS for a box; BOXXLO, BOXXHI, BOXYLO, BOXYHI, BOXZLO, BOXZHI,Result.boxwhen it is set, and BOXLIM = 1 when it holds the limits given toreconstruct_box; PERIODIC = 1 when the box is periodic (written with BOXLIM, absent for a box that is not periodic); ZCUTMIN and ZCUTMAX for the finite bounds of a redshift cut, DCUTMIN and DCUTMAX for those of a distance cut, MASK = 1 when a mask selected the objects, FILTNSID and MAXPIXCR when a mask filter was applied (CFMAXPIX and MAXPIXCR are thresholds ofreject_mask_crossings: the longest run of unobserved pixels a displacement’s arc may cross); NTRAC, NTRCUT, NTRDCUT, NTRMASK, NTRBOTH, NTRBOX, NRAND, NRNCUT, NRNDCUT, NRNMASK, NRNBOTH, NRNBOX, NTRWRAP, NRNWRAP, NDISPL and NDISPCR, the selection counts, each when it is not 0. Then MPSPART = 1 and DISTPART = 1 when the profile and the table are written.The profile (redshift, MPS, nTracers, with the keywords ZMIN, ZMAX and MPSREPR of
write_mps_profile; for a profile in distance, distance in place of redshift and DISTMIN, DISTMAX in place of ZMIN, ZMAX) and the table (redshift, distance and, when the table has one, growthRate, with the keywords ZMIN and ZMAX) are written with 17 digits in ASCII, each with its own PRODUCT, complete displacements mps profile and complete displacements distance table. In FITS they are the HDUs MPSPROF and DISTANCE, after the main table DISPLACEMENTS. In ASCII they are twin files next to the file, the name with .mps and .distances inserted before the text after its last ‘.’ (run.dat gives run.mps.dat and run.distances.dat), or appended when the name has no ‘.’. A file renamed needs its twins renamed by the same rule. Existing files of those names are overwritten: the twin run.mps.dat replaces awrite_mps_profilefile of that name, and is replaced by it when that is written later. Each is written whenlightcone_tablesis true and the result is a lightcone that holds it; a result made byResult.from_arraysholds no profile, and a table only when givendistances, and one ofreconstruct_lightcone_cartesianwithoutdistancesa profile but no table, so DISTANCE is then absent.
- otswap.io.read_displacement_complete(file: Path, *, angle_unit: otswap.AngleUnit | None = None) otswap.Result¶
Read a file written by
write_displacement_completeback into aResult, its sky arrays inangle_unit.Read as written: the geometry,
periodic,ids,n_realizations_mean(NRECMEAN, 1 when absent), the configuration (the fields a file does not record take the current defaults),tracers,tracers_sky,displacement,valid, the four flags (outside_distance_cutwhen its column is present), the selection counts, the box, the mps profile and the distance table. Recomputed, asrecompute_meansdoes: the valid realizations,mean_displacement,lagrangian,lagrangian_skyandlagrangian_distance.idsreads as having no IDs when the file’s IDs are 0..n_objects-1. The columns of the tracer, id and flags are taken from realization 0.- Parameters:
file (str or os.PathLike) – A complete displacement file; its extension sets the format.
angle_unit ({"deg", "rad"}, optional) – The unit of the sky arrays of the result. Required for a lightcone file (
lightcone_skyorlightcone_cartesian); a box file has no angles and refuses it.
- Returns:
The result written, but for the differences below.
- Return type:
- Raises:
Error – If
angle_unitis given for a box file, or missing for a lightcone file; if the file cannot be read; if its PRODUCT is not that ofwrite_displacement_complete; if a keyword or a column its layout requires is missing or malformed; if the rows are not NOBJECTS x NREC, ordered in blocks of realization 0, 1, and so on; if a flag or valid entry is neither 0 nor 1, or an ID is repeated; if the file records the tracer counts of the selection (NTRAC) and one disagrees with the flags; if a box file declares a profile or a table; if a declared profile or table is missing, the message naming the file and the part, or is not the part written, by its PRODUCT, or is malformed. Every message names the file, and a row by its ASCII line or FITS row, counted from 1.
Notes
Every value reads back identical but
tracers_sky, whose right ascension and declination are equal within the rounding of the conversion to degrees and back, andcell_side, which is not written and reads as None; NaN reads back as NaN, with its sign and payload in FITS only.real_space_lightconeon the result read gives the catalogue of the reconstruction bit for bit, but for its right ascension and declination, equal within that rounding.The profile and the table are read when the file declares them (MPSPART, DISTPART): in FITS from the HDUs MPSPROF and DISTANCE, in ASCII from the twin files named by the rule of
write_displacement_complete, from the name of the file read. They are left empty when it does not: for a file written withlightcone_tables=False, and for a file of otswap 0.1, whose result has notracers_skyeither, and whose index column is read as the IDs. A box file of otswap 0.1 gets the bounding box of its tracers as its box, the box its reconstruction used. The columns lagrX..lagrZ of a file of otswap 0.1 are not read.
- otswap.io.write_real_space_catalog(file: Path, catalog: otswap.RealSpaceCatalog, *, groups: Sequence[CatalogGroup] | None = None) None¶
Write a catalogue moved to real space, one row per tracer.
The groups and their columns:
"id": id (64-bit integer),RealSpaceCatalog.ids;"sky": tracRA, tracDec (degrees), tracRed,RealSpaceCatalog.sky; lightcone only;"cartesian": tracX, tracY, tracZ,RealSpaceCatalog.cartesian;"valid_realizations": nValidRec;"neighbours": nNeighbours, nRealizationsAveraged;"shift": shift (coordinate units), rsdFactor;"status": status, asRealSpaceCatalog.status, the value ofCorrectionStatus(0 to 3).
The shift and the factor are written when
"shift"is listed ingroups. The columns tracX..tracZ and tracRA..tracRed hold the corrected positions here, where the displacement files hold the observed ones; a lightcone tracer moves along its line of sight, so tracRA and tracDec keep the observed angles. The file has no reader of its own:readreads its columns by name.- Parameters:
groups (sequence of CatalogGroup, optional) – In output order; None for the default: lightcone sky, cartesian, valid_realizations, neighbours, status; box the same without sky; id first when IDs were set.
- Raises:
Error – If a group is repeated, if
"sky"is given for a box, if a field a group reads does not have the size of its layout, ifidsis neither empty nor one per object or holds a value twice, or aswrite.
Notes
Floating values are written with 9 significant digits in ASCII. Keywords: SIGMA, WEIGHTED (0 or 1); NEXTRAP for a lightcone; AXIS, ZBOX and BIAS for a box. A periodic box has no PERIODIC keyword here; its corrected coordinate along the axis is wrapped into the box.
- otswap.io.CatalogGroup: TypeAlias = Literal['id', 'sky', 'cartesian', 'valid_realizations', 'neighbours', 'shift', 'status']¶
- otswap.io.write_mps_profile(file: Path, profile: otswap.MpsProfile) None¶
Write a mean particle separation profile: redshift (the bin centre), MPS, nTracers, one row per bin. Keywords: ZMIN, ZMAX, MPSREPR (the representative value). A profile in distance has the column distance (the bin centre, in coordinate units) in place of redshift, and the keywords DISTMIN and DISTMAX in place of ZMIN and ZMAX.
MpsProfile.atgives the profile anywhere. The file has no reader of its own:readreads its columns by name. Raises if the profile is empty or malformed, holds both redshift and distance nodes, or aswrite.