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

otswap.__version__: str

The version of the library the module was built from, a string such as "0.5.0"; the same as OTSWAP_VERSION in C++.

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: the config of reconstruct_box, reconstruct_lightcone and reconstruct_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 Error if it cannot be; its rules (n_realizations at 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. repr gives 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.seed records 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_lightcone or reconstruct_lightcone_cartesian, filter the result with reject_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_crossings defines 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”.

verbosity: Verbosity

What the call prints; see Verbosity and each function.

class otswap.CorrectionConfig(*, weight_by_realizations: bool = False, verbosity: Verbosity = 'normal')

Options of real_space_lightcone and real_space_box, as otswap::CorrectionConfig: their correction. Keywords, attributes, repr and equality as Config.

weight_by_realizations: bool

Weight each neighbour by its number of valid realizations as well; default False. Advice on the choice: the guide, section “Choosing the parameters”.

verbosity: Verbosity

What the call prints; see Verbosity and each function.

class otswap.RedshiftCut(min: float = -inf, max: float = inf)

A closed redshift range for reconstruct_lightcone and measure_mps_profile, as otswap::RedshiftCut. The default, (-inf, +inf), cuts nothing. Wherever a RedshiftCut is taken, a (min, max) pair is accepted too.

min and max are read/write; the call that reads the cut checks them (neither NaN, min not above max). repr and equality as Config.

min: float

The lowest redshift kept.

max: float

The highest redshift kept.

class otswap.DistanceCut(min: float = -inf, max: float = inf)

A closed range of comoving distance from the origin, in coordinate units, for reconstruct_lightcone_cartesian and measure_mps_profile_cartesian, as otswap::DistanceCut: the counterpart of RedshiftCut. 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.

min and max are read/write; the call that reads the cut checks them (neither NaN, min not above max). repr and equality as Config.

min: float

The shortest distance kept, in coordinate units.

max: float

The longest distance kept, in coordinate units.

class otswap.BoxLimits(lower: numpy.typing.ArrayLike, upper: numpy.typing.ArrayLike)

The closed limits of a box for reconstruct_box: the points with lower[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_box checks that each bound is finite and that lower[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_box checks that each bound is finite and that lower[k] < upper[k].

property lower: tuple[float, float, float]

x, y, z of the lower corner.

property upper: tuple[float, float, float]

x, y, z of the upper corner.

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.flat or DistanceTable.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 h cancels 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_m must lie in (0, 1], h be positive, w0 and wa finite, z_min non-negative, z_max above z_min, and n_samples at 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. Without growth_rate, growth_rate_at raises.

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_rate is neither None nor of the same length, or holds a value that is not finite and positive.

property min_redshift: float
property max_redshift: float
property has_growth_rate: bool
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 to from_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 of reconstruct_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 in angle_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_unit is invalid. As otswap::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 nest that is not a bool.

property nside: int

NSIDE of the map, from 1 to 2**29.

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 inside box when it is given; each realization uses a disjoint subset. If omitted, R * N randoms are drawn uniformly in box, 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: box or, 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 is Result.mps. Without box, 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.box holds it.

  • periodic (bool, optional) –

    Whether the box is periodic, with box required: 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.tracers holds the wrapped positions, outside_box is all False, and the numbers wrapped are selection.tracers_wrapped and selection.randoms_wrapped. Distances are minimum-image; displacements lie in [-L/2, L/2) on each axis, of period L, and Result.lagrangian is wrapped into the box. Without mps, the mean particle separation is (V / N)^(1/3) of the box with N all the tracers. With periodic, "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_size and verbosity; reject_crossings and max_unobserved_pixels_crossed are not read. With n_realizations R, the randoms given must number at least R N. verbosity: see Verbosity; "normal" prints one line, "detailed" the mps and its source before it. With box, "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 if mps is not positive; without mps and box, 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 config is out of range, the message describing the quantity and its rule.

  • Error – With periodic, if box is not given or its sides are not integer multiples of the shortest; the message names the sides.

  • Error – If a bound of box is not finite or a lower bound is not below the upper one, or if box keeps 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 of config.cell_size mps (in a periodic box, reduced to divide the shortest side a whole number of times: see Result.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, see reconstruct_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_realizations times the tracers kept, which is M >= R * N, with R config.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_deg2 and mask.

  • 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, as Mask.allows decides: the randoms are dropped, and the tracers keep their row, flagged in Result.outside_mask. After it, with config.reject_crossings, reject_mask_crossings is applied with config.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, and RedshiftCut() cut nothing.

  • config (Config, optional) –

    Every field; reject_crossings and max_unobserved_pixels_crossed are read only with a mask. verbosity: see Verbosity. 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, as Result.selection records 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_deg2 and mask are 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_realizations times 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 config is out of range, as in reconstruct_box.

  • Error – From the neighbour search, as in reconstruct_box, the cell being config.cell_size mean 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.

tracers and randoms are comoving coordinates with the observer at the origin, in coordinate units. No cosmology is needed: the mean particle separation is measured in n_bins uniform bins of comoving distance from the origin, Result.mps_profile is a profile in distance, the objects are selected on the angles and distance of point_to_sky, distance_cut is the counterpart of reconstruct_lightcone’s redshift_cut, and distances is optional: it only fills the redshifts of Result.tracers_sky and Result.lagrangian_sky, NaN without it, and the result is otherwise the same with or without it. Everything else is as in reconstruct_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_realizations times the tracers kept.

  • randoms (array_like, shape (N, 3) and (M, 3)) – Cartesian coordinates, finite. The randoms kept must number at least config.n_realizations times 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, and DistanceCut() 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 and config; 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_lightcone that 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_profile of a reconstruct_lightcone call with the same tracers, sky area or mask, n_bins, distances and redshift_cut, whatever its randoms and other arguments. Use it to choose n_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 of sky_area_deg2 and mask.

  • 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, as reconstruct_lightcone leaves 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 of reconstruct_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:

MpsProfile

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 of sky_area_deg2 and mask are 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_cartesian measures from the same tracers, sky area or mask, n_bins and distance_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 reads otswap: measureMpsProfile: <B> bins over [<dmin>, <dmax>] in coordinate units, the cut as in reconstruct_lightcone_cartesian.

Returns:

The profile, in distance.

Return type:

MpsProfile

Raises:

Error – As measure_mps_profile for 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_crossed unobserved 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. Updates result in place; it only ever marks displacements invalid, and raises if result was already filtered against a mask of a different NSIDE, or if result is a box result, which has no sky to filter against. It also raises if result is malformed: a NaN in a tracer outside the flagged ones or in a valid displacement, a flagged tracer with a valid entry, a tracers array without N rows, a flag, tracers_sky, lagrangian or lagrangian_sky array whose size is neither 0 nor the one of its layout, or an entry of valid neither 0 nor 1. Tracers that took no part in the reconstruction (any outside_* flag) are left as they are. valid_realizations, mean_displacement, lagrangian, lagrangian_sky and lagrangian_distance are recomputed, and result.selection records the filter. On a result holding a mean (n_realizations_mean above 1, one realization), valid_realizations keeps 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_sky and lagrangian_distance from displacement and valid, as the reconstruction computes them: the sum over the valid realizations in realization order, divided by their count; then lagrangian, wrapped into the box of a periodic result, and from it lagrangian_sky and lagrangian_distance, as Result.lagrangian_sky describes. Updates result in place. Raises if displacement or valid has the wrong size, an entry of valid is neither 0 nor 1, or a flag, tracers or tracers_sky array 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 ids can be assigned. The sky arrays (tracers_sky, lagrangian_sky) are in the angle_unit of the call that made the result; in degrees they are converted once, on first access, and kept. ids is 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 with reject_mask_crossings updates valid, valid_realizations, mean_displacement and lagrangian in place, so views taken earlier reflect it; lagrangian_sky is recomputed, and an array taken from it in degrees before the filter is not updated.

The type is otswap::Result itself, 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 raises otswap.Error for 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 of tracers_sky, angle_unit and distances. "lightcone_sky" requires all three. "lightcone_cartesian" requires angle_unit (the unit of tracers_sky and of the sky arrays of the result) and takes the other two as optional. outside_box, periodic and box describe 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 from tracers when omitted, as reconstruct_lightcone_cartesian does: the redshift from distances when 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_sky and of the sky arrays of the result.

  • distances (DistanceTable, optional) – The table of the reconstruction, from which lagrangian_sky is 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; its n_realizations must 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_box with periodic); requires box; for a box result only. The displacements must already be minimum-image, in [-L/2, L/2) on each axis; lagrangian is wrapped into the box.

  • box (BoxLimits or ((x0, y0, z0), (x1, y1, z1)), optional) – The limits of the box, recorded as box and selection.box_limits, as reconstruct_box does when given box. Required with periodic, each side then an integer multiple of the shortest. For a box result only.

Notes

valid_realizations, mean_displacement, lagrangian, lagrangian_sky and lagrangian_distance are computed as recompute_means computes 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: mps and mps_profile are None; box is the box given, or None.

property n_objects: int
property n_realizations: int
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_mean returns 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_realizations then counts the realizations averaged that were valid, up to it: always at most n_realizations x n_realizations_mean.

property geometry: Literal['box', 'lightcone_sky', 'lightcone_cartesian']

"box" for reconstruct_box; "lightcone_sky" for reconstruct_lightcone; "lightcone_cartesian" for reconstruct_lightcone_cartesian. For a result read from a file, the file’s, a file of otswap 0.4 or earlier reading as "lightcone_sky"; for from_arrays, the geometry given.

property angle_unit: AngleUnit | None

the angle_unit of the call that made the result; "rad" for a result made by another module. None for a box.

Type:

The unit of tracers_sky and lagrangian_sky

property config: Config

a new copy on each access, so changing it changes nothing in the result. seed is 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_box and real_space_lightcone copy them into the RealSpaceCatalog. 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 as x * (pi/180) * (180/pi), which can differ from the input in the last bit. For a result of reconstruct_lightcone_cartesian, the angles of point_to_sky and the redshift at which distances reaches the tracer’s distance, NaN when no distances were 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 into box, its displacements in [-L/2, L/2) on each axis, of period L, and lagrangian wrapped 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_size times 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 box given to reconstruct_box or, without it, the bounding box of the tracers and the given randoms (of the tracers alone when the randoms were drawn), also when mps was 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 filtered_nside: int

NSIDE of the mask the result was filtered against, 0 if none.

property outside_redshift_cut: numpy.typing.NDArray[numpy.bool_]

Whether each tracer lay outside the redshift_cut of reconstruct_lightcone and took no part in the reconstruction, shape (n_objects,). All false without a cut, for a box and for a result of reconstruct_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_cut of reconstruct_lightcone_cartesian and 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 mask of reconstruct_lightcone or reconstruct_lightcone_cartesian and took no part in the reconstruction, shape (n_objects,). All false without a mask. Independent of outside_redshift_cut and outside_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 box given to reconstruct_box and 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), in angle_unit: right ascension in [0, 360) degrees ([0, 2 pi) radians), declination, redshift, as to_sky computes them with the reconstruction’s distance table. NaN rows where lagrangian is 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 of reconstruct_lightcone_cartesian the angles are those of point_to_sky, and every redshift is NaN when no distances were given. None for a box. Recomputed by reject_mask_crossings.

property lagrangian_distance: numpy.typing.NDArray[numpy.float64] | None

Distance from the origin of each tracer’s mean Lagrangian position, lagrangian, as point_to_sky computes it, in coordinate units, shape (n_objects,). NaN where lagrangian is NaN. None for a box. Recomputed by reject_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 by measure_mps_profile, a profile in redshift: the tracers kept in n_bins uniform 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 by measure_mps_profile_cartesian, a profile in comoving distance from the origin: the bins are uniform in distance over [distance_min, distance_max], distance holds their centres, redshift is empty, and redshift_min and redshift_max are 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 redshift_min: float

The smallest redshift binned; NaN in a profile in distance.

property redshift_max: float

The largest redshift binned; NaN in a profile in distance.

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 of value kept: 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 are tracers_outside_redshift_cut + tracers_outside_mask - tracers_outside_both; for reconstruct_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. For reconstruct_box with box, the tracers removed are tracers_outside_box, and the randoms removed randoms_outside_box; with periodic nothing is removed, these are 0, and tracers_wrapped and randoms_wrapped give what was wrapped into the box. tracers and randoms are set only when a box was given, randoms 0 when the randoms were drawn. Every other count is 0, and nothing else is applied, for reconstruct_box; the box counts are 0 for a lightcone. repr gives the report the reconstruction prints.

property redshift_cut: RedshiftCut | None

The redshift cut applied, a new RedshiftCut on each access; None when no cut was applied.

property distance_cut: DistanceCut | None

The distance cut applied, a new DistanceCut on each access; None when no cut was applied.

property mask_applied: bool

Whether a mask was given.

property box_limits: BoxLimits | None

The box given to reconstruct_box; None when none was.

property periodic: bool

Whether the box was periodic.

property tracers: int

Tracers given.

property tracers_wrapped: int

Tracers wrapped into the periodic box, because they lay outside it; 0 unless periodic.

property tracers_outside_redshift_cut: int
property tracers_outside_distance_cut: int
property tracers_outside_mask: int
property tracers_outside_both: int

Tracers outside the cut, redshift or distance, and the mask.

property tracers_outside_box: int

Tracers outside the box limits.

property randoms: int

Randoms given.

property randoms_wrapped: int

Randoms given wrapped into the periodic box; 0 unless periodic.

property randoms_outside_redshift_cut: int
property randoms_outside_distance_cut: int
property randoms_outside_mask: int
property randoms_outside_both: int

Randoms outside the cut, redshift or distance, and the mask.

property randoms_outside_box: int

Randoms given outside the box limits.

property max_unobserved_pixels_crossed: int | None

The threshold of the latest mask filter applied to the result, by reconstruct_lightcone or reconstruct_lightcone_cartesian (config.reject_crossings) or by reject_mask_crossings afterwards; None when none was.

property displacements: int

Valid displacements before the first mask filter.

property displacements_crossing_mask: int

Of them, those rejected by the mask filters so far, in total.

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_displacement on its line of sight, at result.tracers, the Gaussian average of width sigma over 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_sky when it is not NaN. Where it is NaN, as for the tracers of a result of reconstruct_lightcone_cartesian built without a table, it is the redshift at which distances reaches the tracer’s distance from the origin.

Parameters:
  • result (Result) – A lightcone result, which carries its tracers; sky comes back in its angle_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; warns ExtrapolationWarning once 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 (see CorrectionConfig). verbosity: what the call prints; see Verbosity. "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 tracers or tracers_sky; if its ids are 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; if bias extrapolates 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_complete the correction is that of the reconstruction itself, bit for bit, but for the right ascension and declination of sky, 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 along axis: the chain of real_space_lightcone with the projection on the axis, a single factor at redshift with the constant bias, 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’s ids.

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:
  • Error – For a lightcone result, or one that is malformed or lacks its tracers; if its ids are neither empty nor one per object or hold a value twice; if the axis is not 0, 1 or 2; or as rsd_factor_box.

  • Error – From the neighbour search, as in neighbour_average, for the tracers corrected.

class otswap.RealSpaceCatalog

A catalogue moved to real space; row i describes input tracer i.

Every array attribute is read-only; sky is in the angle_unit of the result corrected, converted once and kept, ids is 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 is otswap::RealSpaceCatalog itself: a catalogue made by another module is in radians, and its array getters check the sizes first.

property n_objects: int
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 Result corrected, 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 as x * (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). See CorrectionStatus.

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,).

property n_extrapolated: int

Tracers at whose redshift b(z) was extrapolated beyond its table; 0 for a box.

property sigma: float

The width of the average, in coordinate units, as given.

property weight_by_realizations: bool
property axis: int | None

the line-of-sight axis; None for a lightcone.

Type:

Box

property box_redshift: float | None

the redshift of the box; None for a lightcone.

Type:

Box

property box_bias: float | None

the bias of the tracers; None for a lightcone.

Type:

Box

property elapsed_seconds: float

Wall time of the call that made the catalogue, in seconds.

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 values over the neighbours of each object.

An object is valid when its entry of valid_realizations is 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, with weight_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, values is 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:

NeighbourAverage

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 periodic is given without box or box without periodic; with periodic, if a bound of box is 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, without periodic, 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_average returns, 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) the bias table at z. Beyond the table’s nodes b(z) is extrapolated linearly from the end segments, and one ExtrapolationWarning is 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 with otswap::

  • "silent": nothing;

  • "normal": the selection report of a lightcone, when a selection applied, and of a box, when box was 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 openmp directory of the package: lib/libomp.dylib, the LLVM libomp otswap was built with, whose install name is @rpath/libomp.dylib; include/omp.h and include/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 name: str
property type: Literal['D', 'J', 'K']
property description: str
property unit: str
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 n_rows: int
property n_columns: int

Columns read as float64.

property n_integer_columns: int

Columns read as int64.

property values: numpy.typing.NDArray[numpy.float64]

The columns of read, shape (n_rows, n_columns).

property integers: numpy.typing.NDArray[numpy.int64]

The integer_columns of read, 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: columns as float64, integer_columns exactly 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, where write puts the names. Lines that are empty, hold only blanks, tabs and delimiter, hold comment as their first other character, or start with ### (a names line, whatever comment is) are skipped; every other line is a data row, so a line of text such as a header must start with comment, after any blanks, tabs or delimiter. Fields are separated by delimiter, 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, inf or infinity, 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 form write takes; comment is 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 / comment lines of the header, before the ### line or the first data row; extname is 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 read finds 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. read looks a name up ignoring case.

ASCII: the fields of the last line starting with ### before the first data row, separated by delimiter, blanks or tabs, which is where read looks names up with the same delimiter and comment; extname is 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 as write writes it, readable by read.

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 extname and twin.

  • precision (int, optional) – As in write.

  • keywords (sequence of (str, str, str), optional) – As in write; a keyword named EXTNAME is refused by write_parts.

property columns: tuple[Column, ...]
property extname: str
property twin: str
property precision: int
property keywords: tuple[tuple[str, str, str], ...]
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_part still 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 as write for 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_parts wrote, the first included, as read does, given the extname and twin of the part. FITS: the table of that EXTNAME, compared ignoring case, or with an empty extname the first table; twin is ignored. ASCII: the table in twin_file(file, twin), or with an empty twin in the file itself; extname is 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 extname and twin of the part. FITS: whether it holds a table of that EXTNAME, compared ignoring case, or with an empty extname a first table; twin is ignored. ASCII: whether twin_file(file, twin) or, with an empty twin, the file itself can be opened; extname is ignored, and with a twin the file itself is not checked. Raises Error if 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 example out/field.dat with twin mps gives out/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 BiasTable checks its arrays. Raises if the file cannot be read (as read), 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 every lightcone_cartesian result, with or without a cut, or one that flags a tracer in outside_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 box was given to reconstruct_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_mean needs 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, if ids is 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 in outside_box, or if the profile written does not have one mps and one count per node; or as write.

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_complete writes 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 when lightcone_tables is true and the result is a lightcone that holds it; a result made by Result.from_arrays holds no profile, and a table only when given distances. The file then carries both, and read_displacement_mean returns 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_mean into a Result holding the mean as its only realization, its sky arrays in angle_unit.

The geometry is the file’s, and its keywords are read as read_displacement_complete reads them: the configuration (with n_realizations 1), the selection counts, the box and the mps of a box. The result has n_realizations 1; displacement and mean_displacement both hold the mean displacement; valid is true where the tracer has at least one valid realization; valid_realizations is the file’s count; n_realizations_mean is 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, and lagrangian is tracers + mean_displacement. In a lightcone, lagrangian_distance is always computed from lagrangian, and lagrangian_sky is computed from it as recompute_means does: with the distance table, with NaN redshifts for a profile in distance or a lightcone_cartesian file, and None for a lightcone_sky file with neither. The mps profile and the distance table are read when the file declares them (MPSPART, DISTPART), from the extensions or twin files of write_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_sky or lightcone_cartesian); a box file has no angles and refuses it.

Returns:

The mean as a result of one realization.

Return type:

Result

Raises:

Error – If angle_unit is given for a box file, or missing for a lightcone file; if the file cannot be read; if its PRODUCT is not that of write_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_means on the result read sets valid_realizations to 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.ids as in write_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 every lightcone_cartesian result, with or without a cut, or one that flags a tracer in outside_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_sky included, for a lightcone), if ids is 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 in outside_box, if the profile written does not have one mps and one count per node, or as write.

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_arrays on the arrays read back gives the reconstruction’s means bit for bit. read_displacement_complete reads the file back into a Result.

Keywords, those of write_displacement_mean too: NREC and, when Result.n_realizations_mean is 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.box when it is set, and BOXLIM = 1 when it holds the limits given to reconstruct_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 of reject_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 a write_mps_profile file of that name, and is replaced by it when that is written later. Each is written when lightcone_tables is true and the result is a lightcone that holds it; a result made by Result.from_arrays holds no profile, and a table only when given distances, and one of reconstruct_lightcone_cartesian without distances a 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_complete back into a Result, its sky arrays in angle_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_cut when its column is present), the selection counts, the box, the mps profile and the distance table. Recomputed, as recompute_means does: the valid realizations, mean_displacement, lagrangian, lagrangian_sky and lagrangian_distance. ids reads 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_sky or lightcone_cartesian); a box file has no angles and refuses it.

Returns:

The result written, but for the differences below.

Return type:

Result

Raises:

Error – If angle_unit is given for a box file, or missing for a lightcone file; if the file cannot be read; if its PRODUCT is not that of write_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, and cell_side, which is not written and reads as None; NaN reads back as NaN, with its sign and payload in FITS only. real_space_lightcone on 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 with lightcone_tables=False, and for a file of otswap 0.1, whose result has no tracers_sky either, 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, as RealSpaceCatalog.status, the value of CorrectionStatus (0 to 3).

The shift and the factor are written when "shift" is listed in groups. 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: read reads 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, if ids is neither empty nor one per object or holds a value twice, or as write.

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.at gives the profile anywhere. The file has no reader of its own: read reads its columns by name. Raises if the profile is empty or malformed, holds both redshift and distance nodes, or as write.