Guide

The concepts of otswap and their use, in the order a new user needs them. Everything applies to both languages; where the names differ, the C++ name comes first and the Python one follows in brackets, and names side by side lists them all. Each geometry has a numbered path of steps and the example that runs them.

Tracers, randoms and the result

A reconstruction takes \(N\) tracers, the observed objects, and a catalogue of randoms, points that sample the same volume uniformly. It pairs each tracer with one random so that the sum of the squared distances is small (the method page describes how), and repeats the pairing on nRealizations (n_realizations) disjoint sets of \(N\) randoms. In each realization a tracer’s displacement points from the tracer to its random; its mean over the realizations is the mean displacement, and the tracer plus its mean displacement is its mean Lagrangian position. All of this is returned in a otswap::Result (otswap.Result), with one row per input object, in input order.

The scale at which otswap works is the mean particle separation (mps), \((V/N)^{1/3}\) for \(N\) tracers in a volume \(V\): the first guess pairs tracers with randoms within 8 mps, and the neighbour grids have cells of cellSize (cell_size) mps. In a box it is a single number; in a lightcone it changes with redshift, and otswap measures it from the tracers.

There are four geometries, each described below: a box, a periodic box, a lightcone on the sky and a lightcone in Cartesian coordinates.

Coordinates and units

  • Cartesian coordinates and every length (the mps, box limits, displacements, σ) are in coordinate units, as the layout below defines; otswap assumes no unit, and the files it writes give lengths none.

  • Sky coordinates are ordered right ascension, declination, redshift.

  • In C++ angles are in radians; otswap::skyToRadians() and otswap::skyToDegrees() convert a sky array. In Python every function that takes or returns angles has a required angle_unit, "deg" or "rad"; the file readers take it only for a lightcone file, since a box file has no angles.

  • Right ascensions that otswap computes come back folded into [0, 2π), or [0, 360) degrees.

  • In Python a coordinate array has shape (N, 3) and is converted to float64; the arrays of a result have the shapes below, with the realization first.

The layout of the C++ arrays, which the Python arrays map onto:

group Coordinate layout

How coordinate arrays and the arrays of a result are laid out.

Every coordinate array is flat and row-major, one object after the other. Cartesian arrays hold 3 * nObjects entries, ordered x, y, z, in coordinate units. Sky arrays hold 3 * nObjects entries, ordered right ascension, declination, redshift; angles are in radians.

Every length otswap takes or returns, the mean particle separation, box limits, displacements and smoothing widths included, is in coordinate units: the unit of the Cartesian coordinates. In a box it is the unit of the tracers given; otswap assumes none. In a lightcone given on the sky it is the unit of the distance table: Mpc/h when the table comes from the cosmology constructor of DistanceTable, the unit of the table given when it comes from the table constructor. In a lightcone given in Cartesian coordinates (the Cartesian overloads of reconstructLightcone and measureMpsProfile) it is the unit of those coordinates, which any distance table used with them must share.

A numpy array maps onto this layout without a copy. The arrays of a Result and of a RealSpaceCatalog:

[realization][object][3]  Result::displacement
[realization][object]     Result::valid (uint8, 0 or 1)
[object][3]               Result::tracers, tracersSky, meanDisplacement,
                          lagrangian, lagrangianSky;
                          RealSpaceCatalog::sky, cartesian
[object]                  Result::ids (int64), validRealizations,
                          outsideRedshiftCut, outsideDistanceCut,
                          outsideMask, outsideBox (uint8),
                          lagrangianDistance;
                          RealSpaceCatalog::ids (int64), shift,
                          factor, status, validRealizations,
                          nNeighbours, nRealizationsAveraged
Flags are uint8, 0 or 1; counts are unsigned; indices of objects are their rows.

Box

For a catalogue in comoving Cartesian coordinates whose density is about constant, cubic or not, such as a sub-volume of a simulation.

  1. Read the tracers and, if there are any, the randoms (Files).

  2. Set the parameters in a otswap::Config (otswap.Config); the defaults are the starting point for an analysis (Choosing the parameters).

  3. When the volume of the sample is known, give it as box limits, otswap::BoxLimits (otswap.BoxLimits, or a pair of corners).

  4. Reconstruct with otswap::reconstructBox() (otswap.reconstruct_box()).

  5. Write the mean displacements, or every realization (Files).

  6. For a catalogue in redshift space, move the tracers to real space with otswap::realSpaceBox() (otswap.real_space_box()), which takes the growth rate at the box’s redshift from a distance table (The redshift-space correction).

The box example runs steps 1 to 5 with limits, and the correction in a box steps 1, 2, 4 and 6, without limits. The snippet shows steps 3 and 4; the example reads the catalogues and sets the Config before it, and writes the files after it:

box = ([269.0, 269.0, 269.0], [669.0, 669.0, 669.0])

result = otswap.reconstruct_box(tracers, randoms, box=box, config=config)
otswap::BoxLimits box;
box.lower = {269., 269., 269.};
box.upper = {669., 669., 669.};

otswap::Result result = otswap::reconstructBox(tracers, randoms, config, box);

The box. With limits, closed on every face, the tracers outside them take no part: they keep their row, flagged in outsideBox (outside_box), with NaN displacements, and the randoms given outside them are dropped. Without limits, the box is the bounding box of the tracers and the given randoms, or of the tracers alone when the randoms are drawn. Drawn randoms fill the box. Result::box (Result.box) records the box used.

The mps. Unless it is given (the Python keyword mps; in C++, the overload of otswap::reconstructBox() that takes it after the randoms), it is \((V/N)^{1/3}\), with \(V\) the volume of the box and \(N\) the tracers inside it; Result::mps (Result.mps) records the value used. Give it when the mean density of the catalogue is known independently of the extent of its tracers and randoms.

The faces. The box is not periodic: its faces are boundaries through which nothing flows. Modes on the scale of the box cannot be reconstructed, and the displacements are least reliable near the faces. To use a region whole, reconstruct a larger volume around it and discard a margin near the faces; for the whole volume of a periodic simulation, use a periodic box.

Periodic box

For the whole volume of a simulation with periodic boundary conditions. A sub-volume cut from such a simulation is a box, not a periodic box.

  1. Read the tracers. The randoms are usually drawn by otswap, uniformly in the box; they may also be given.

  2. Give the box limits, which are the periods, and set periodic (periodic=True).

  3. Reconstruct with otswap::reconstructBox() (otswap.reconstruct_box()).

  4. Write the mean displacements, or every realization (Files).

  5. For a catalogue in redshift space, move the tracers to real space with otswap::realSpaceBox() (otswap.real_space_box()), as in a box (The redshift-space correction).

The periodic box example runs these steps, the correction included. The snippet shows steps 2 and 3, for a cube of side side, 1000 in the example; tracers and config are set before it, as in the box example:

result = otswap.reconstruct_box(tracers, box=((0.0, 0.0, 0.0), (side, side, side)),
                                periodic=True, config=config)
otswap::BoxLimits box;
box.lower = {0., 0., 0.};
box.upper = {side, side, side};
const bool periodic = true;

const otswap::Result result = otswap::reconstructBox(tracers, {}, config, box, periodic);

Every distance is then the minimum image, and nothing is left out: tracers and given randoms outside the limits are wrapped into the box by whole periods and counted (tracersWrapped, randomsWrapped in Result::selection), and the result holds the wrapped tracers. Each displacement is the minimum-image vector, within half a period on each axis, and the mean Lagrangian position is wrapped into the box. The mps, when computed, is that of the volume of the limits and of every tracer; it rarely needs replacing.

Each side must be a whole multiple of the shortest one, as in a cube or a cuboid of 500 × 500 × 1000: the neighbour grids use cubic cells that divide every side. A box of other proportions can still be reconstructed without periodic. The cells may therefore be smaller than cellSize mps; Result::cellSide (Result.cell_side) gives the side used. otswap::reconstructBox() states the rule in full.

Lightcone on the sky

For a survey catalogue in right ascension, declination and redshift.

  1. Build a distance table from the fiducial cosmology (The distance table).

  2. Read the survey’s mask (The mask), or know its sky area in square degrees.

  3. Read the tracers and the randoms, which are required: they carry the survey’s geometry, selection function and completeness, which otswap does not model (Choosing the parameters, “Randoms”). C++ takes the angles in radians (otswap::skyToRadians() converts them); Python in the unit given by angle_unit.

  4. To reconstruct a slice of the catalogue, set a redshift cut, otswap::RedshiftCut (otswap.RedshiftCut, or a pair).

  5. Choose the number of redshift bins of the mps, nBins (n_bins), with otswap::measureMpsProfile() (otswap.measure_mps_profile()), given the same cut, the same mask or area and the same distance table as the reconstruction. It checks the tracers only; the randoms are checked by the reconstruction.

  6. Reconstruct with otswap::reconstructLightcone() (otswap.reconstruct_lightcone()).

  7. Write the mean displacements, or every realization (Files).

  8. For a catalogue in redshift space, move the tracers to real space with otswap::realSpaceLightcone() (otswap.real_space_lightcone()), given the same distance table and the bias b(z) of the tracers (The redshift-space correction).

The lightcone example runs steps 1 to 7, and the correction in a lightcone steps 1 to 3, 6 and 8. The snippet shows step 6; mask, n_bins, the cut, distances and config are set before it in the example:

result = otswap.reconstruct_lightcone(tracers_sky, randoms_sky, mask=mask, n_bins=n_bins,
                                      distances=distances, angle_unit="deg",
                                      redshift_cut=redshift_cut, config=config)

const otswap::Result result = otswap::reconstructLightcone(tracersSky, randomsSky, mask, nBins,
                                                           distances, config, cut);

The tracers and randoms outside the cut or on unobserved pixels of the mask are left out; the tracers keep their row, flagged in outsideRedshiftCut and outsideMask (outside_redshift_cut, outside_mask), with NaN displacements. \(N\) is the number of tracers kept. The mps is measured from them in nBins uniform redshift bins over their range, and kept in the result as a piecewise linear profile (otswap::MpsProfile, otswap.MpsProfile).

Mask or sky area. Given the sky area instead of a mask, otswap selects nothing on the sky and rejects no displacement, so the tracers and randoms must already be restricted to the footprint. The mask is the better choice whenever one exists.

Lightcone in Cartesian coordinates

For a lightcone already in comoving Cartesian coordinates, with the observer at the origin, such as a mock catalogue built in a simulation.

  1. Read the tracers and the randoms as Cartesian coordinates; the randoms are required, as on the sky.

  2. Read the mask, or know the sky area. The mask is applied to the direction of each point, otswap::pointToSky() (otswap.point_to_sky()), which also gives its distance from the origin.

  3. To reconstruct a shell of the catalogue, set a distance cut, otswap::DistanceCut (otswap.DistanceCut).

  4. Choose the number of distance bins of the mps with the Cartesian overload of otswap::measureMpsProfile() (otswap.measure_mps_profile_cartesian()), given the same cut and the same mask or area as the reconstruction.

  5. Give a distance table, whose distances must be in the unit of the coordinates (The distance table). The reconstruction does not need it; the correction does.

  6. Reconstruct with the Cartesian overload of otswap::reconstructLightcone() (otswap.reconstruct_lightcone_cartesian()).

  7. Write the mean displacements, or every realization (Files).

  8. For a catalogue in redshift space, move the tracers to real space with otswap::realSpaceLightcone() (otswap.real_space_lightcone()), given the distance table and the bias b(z) of the tracers (The redshift-space correction).

The Cartesian lightcone example runs these steps, the reconstruction with the table and again without it. The snippet shows step 6; mask, n_bins, the cut, distances and config are set before it in the example:

result = otswap.reconstruct_lightcone_cartesian(tracers, randoms, mask=mask, n_bins=n_bins,
                                                distances=distances, angle_unit="deg",
                                                distance_cut=distance_cut, config=config)

const otswap::Result result = otswap::reconstructLightcone(tracers, randoms, mask, nBins, config, &distances, cut);

The reconstruction needs no cosmology. The mps is measured in bins of comoving distance from the origin, a profile in distance. The distance cut tests the distance of the given positions, tracers and randoms, before the reconstruction: the tracers outside it keep their row, flagged in outsideDistanceCut (outside_distance_cut), and the randoms outside it are dropped; a mean Lagrangian position may lie outside it. The distance table plays no part in the reconstruction: it only fills the redshifts of the result, which are NaN without it. In C++ it is passed by pointer, after the Config, since it is optional.

The distance table

A otswap::DistanceTable (otswap.DistanceTable) holds the comoving distance and the linear growth rate \(f\) on a grid of redshifts, and interpolates linearly between its nodes. It is built in one of two ways:

  • from a flat w0-wa cosmology, \(\Omega_m\) and \(h\) with \(w_0 = -1\) and \(w_a = 0\) by default, over redshifts 0 to 10 by default, with distances in Mpc/h: DistanceTable(OmegaM, h, ...) (otswap.DistanceTable.flat());

  • from the caller’s own columns of redshift, distance and, optionally, growth rate: DistanceTable(redshift, distance, growthRate) (otswap.DistanceTable.from_table()), for instance to give a growth rate of one’s own.

distances = otswap.DistanceTable.flat(0.286, 0.7, w0=-1.0, wa=0.0)
const otswap::DistanceTable distances(0.286, 0.7, -1., 0.);

The table is never extrapolated. For a lightcone on the sky, the redshifts of the tracers and randoms kept must lie in its range; otherwise the call raises, naming the object and its row. In the reconstruction of a Cartesian lightcone, a position beyond the table gets a NaN redshift, without error. In the redshift-space correction of a lightcone, every tracer the reconstruction kept must lie in the table, moved or not, and so must each corrected position, or the call raises; in a box, only the box’s redshift must. A mean Lagrangian position beyond the table gets a NaN redshift, without error.

Its distances must be in the coordinate units. For a lightcone on the sky they define them (Mpc/h from a cosmology). For a lightcone in Cartesian coordinates they must be in the unit of the coordinates: a table in Mpc/h with coordinates in Mpc gives wrong redshifts and growth rates, and nothing can detect it. The redshift-space correction must be given the table the result was reconstructed with, or one with the same distances.

Realizations and validity

The reconstruction is repeated nRealizations (n_realizations) times, each on its own set of \(N\) randoms, disjoint from the others. Each displacement has a validity flag, valid, per realization and object; every flag of a tracer that took part is set after the reconstruction, and the mask filter only ever clears them. For each tracer, validRealizations (valid_realizations) counts the valid ones, and meanDisplacement (mean_displacement) is their mean, NaN when there is none. lagrangian, the tracer plus its mean displacement, follows from it; the method page explains what it approximates.

After a change to valid, otswap::recomputeMeans() (otswap.recompute_means()) recomputes in place the fields that follow from it, as the reconstruction computes them. In Python the arrays of a Result are read-only: to change valid, change a copy and build a new result with otswap.Result.from_arrays() (with its geometry=), which computes the means in the same way but records no mps, profile or selection counts.

Every output keeps one row per input object, in input order: a tracer left out by a box, a cut or a mask keeps its row, flagged, with NaN displacements and no valid realization.

The mask

The mask describes the survey’s footprint on the sky, so that a lightcone reconstruction uses only what was observed and discards the displacements that pass through what was not. It is a full-sky HEALPix map:

  • from a FITS file, otswap::Mask (otswap.Mask): a binary table in HDU 2 whose first column holds the values, 1024 to a row, so that NSIDE is a multiple of 16. The ordering, RING or NESTED, is read from the header. A cut-sky map is refused;

  • from an array in memory, Mask(values, ordering) (otswap.Mask.from_array(), with nest). The ordering is the caller’s to give, and a wrong one gives a wrong footprint without error.

A pixel is observed when its value is greater than 0. The value is not a weight: a fractional map is turned into observed and unobserved pixels, and the completeness of the survey belongs in the randoms. Given to the lightcone reconstruction, the mask is applied twice:

  • before it, tracers and randoms on unobserved pixels are left out;

  • after it, a displacement whose great-circle arc crosses more than maxUnobservedPixelsCrossed (max_unobserved_pixels_crossed) unobserved pixels in a row is marked invalid; 0, the default, rejects it at the first one. otswap::rejectMaskCrossings() (otswap.reject_mask_crossings()) gives the rule.

The count is of pixels, not an angle, so the same threshold means a different criterion at a different NSIDE. A second filter with a higher threshold changes nothing, and one with a lower threshold rejects more: set the threshold in the call that reconstructs, or set rejectCrossings (reject_crossings) to false and filter afterwards with otswap::rejectMaskCrossings().

The redshift-space correction

The displacements of a reconstruction in redshift space move the catalogue to real space: otswap::realSpaceBox() and otswap::realSpaceLightcone() (otswap.real_space_box(), otswap.real_space_lightcone()) shift each tracer along its line of sight by the line-of-sight component of its mean displacement, averaged over its neighbours with a Gaussian of width σ and scaled by \(f/(b + 3f/5)\). The method page derives the factor. The inputs are:

  • the result, of a reconstruction of the observed catalogue;

  • the line of sight: a Cartesian axis in a box, 0, 1 or 2; in a lightcone, the direction of each tracer from the origin;

  • the growth rate, from a distance table carrying it: in a box at the box’s redshift, in a lightcone at each tracer’s redshift. A result of a Cartesian lightcone reconstructed without a table can still be corrected: the table given to the correction supplies the redshifts;

  • the bias of the tracers, the caller’s: one number for a box; for a lightcone a b(z) table (otswap::BiasTable, otswap.BiasTable, or read with io::readBiasTable, otswap.io.read_bias_table()), extrapolated linearly beyond its nodes with a warning;

  • σ, in coordinate units; 0 applies no average (Choosing the parameters).

A periodic result needs nothing more: the neighbours are found across the faces, and the corrected coordinate is wrapped into the box. In a lightcone, a corrected position outside the distance table raises for the whole call; a table covering a wider redshift range solves it.

The two correction examples correct a box and a lightcone, the periodic box example a periodic box and the Cartesian lightcone example a Cartesian lightcone. The result, an otswap::RealSpaceCatalog (otswap.RealSpaceCatalog), gives each tracer its corrected position and a status (otswap::CorrectionStatus, otswap.CorrectionStatus): moved with its own displacement; moved with its neighbours’ average, when it has no valid realization; not moved, when no valid tracer lies within 3σ; or left out of the reconstruction.

Files

Tables are read and written by otswap::io (otswap.io), in ASCII or FITS by the extension, and a file written from Python is the same, byte for byte, as the one C++ writes from the same values. The file formats page gives the layouts, and the columns and keywords of every file.

  • Inputs: otswap::io::read() (otswap.io.read()) reads columns by index or by name; Table::values (Table.values) are the coordinates.

  • Displacements: writeDisplacementMean (write_displacement_mean) writes the mean displacement of each tracer; writeDisplacementComplete (write_displacement_complete) writes every realization, without loss. Each has its reader, which rebuilds a Result.

  • The corrected catalogue: writeRealSpaceCatalog (write_real_space_catalog).

  • The mps profile: writeMpsProfile (write_mps_profile).

IDs. To carry the catalogue’s own IDs into the files, read them exactly as integers (the integerColumns overload of io::read, integer_columns= in Python) and set them on the result before writing or correcting it: Result::ids (result.ids = ...), one 64-bit integer per object, no value twice. The writers then add an id column, and the corrected catalogue copies them. IDs equal to 0, 1, …, N − 1 count as none; an id column, where written without IDs, holds each object’s row, from 0.

Choosing the parameters

The defaults are the starting point for an analysis; the examples use smaller values to run quickly.

  • Randoms. Each realization takes \(N\) randoms, disjoint from those of the others, so the catalogue must hold at least nRealizations × \(N\); a surplus is not used, the randoms of each realization being drawn at random from the catalogue. \(N\) is the number of tracers reconstructed: those inside the box limits, or kept by the cut and the mask, the randoms being counted after the same selection. In a box, randoms may also be drawn by otswap, uniformly in the box; given randoms are needed when the volume is not filled uniformly. The default of 30 realizations needs 30 randoms per tracer; the example catalogues hold about 8, which is why the examples run 8 realizations.

  • convergence, default 1e-3: the sweeps stop once the fraction of successful swaps in a sweep, swaps per tracer visited, no longer exceeds this threshold. In the void analysis of Sartori et al. (2026, Appendix B), void abundances were stable for thresholds of about 1e-2 or below, and stacked void profiles for 1e-3 or below; larger values are faster.

  • nRealizations (n_realizations), default 30: that analysis used 10 to 50, depending on the geometry, the small scales needing the most.

  • nBins (n_bins), lightcone only: the bins are uniform over the range of the tracers kept, and each must hold at least 278 tracers, for a 2% accuracy on its mps (see otswap::MpsProfile). Take enough bins to follow the change of the density with redshift or distance. Choose them before reconstructing: call measureMpsProfile (otswap.measure_mps_profile(), otswap.measure_mps_profile_cartesian()) with a trial number and read count. A refused number comes with an upper bound, the number of tracers divided by 278; a sparse tail of the distribution may need fewer bins.

  • maxUnobservedPixelsCrossed (max_unobserved_pixels_crossed), default 0: 0 rejects any crossing; to tolerate small holes such as bright-star masks, set the size of those holes in pixels at the mask’s NSIDE.

  • mps, box only: computed by default (Box); give it when the mean density of the catalogue is known independently of the extent of its tracers and randoms. In a periodic box the computed value rarely needs replacing.

  • periodic, box only: for the whole volume of a simulation with periodic boundary conditions (Periodic box).

  • Redshift or distance cut: to reconstruct a slice of a wider catalogue.

  • cellSize (cell_size), default 3 mps: affects the speed only, never the result.

  • σ of the redshift-space correction: for coordinates in Mpc/h, 10 Mpc/h is a starting value, to be calibrated on the sample.

  • weightByRealizations (weight_by_realizations), default false: set it to give less weight to tracers whose displacement averages few valid realizations, as near the edges of a masked footprint. It changes nothing where every tracer has all its realizations, as in a box.

Reproducibility and threads

With a fixed seed, a reconstruction gives the same result whatever the number of threads, bit for bit. The seed 0 draws one, and the seed used is recorded in the result, so any run can be repeated. Every translation unit is compiled with -ffp-contract=off, and the math functions the results depend on come from a vendored copy of the FreeBSD msun library rather than from the platform library, so the same inputs give the same bits on every supported platform and compiler.

The seed used is Result::config.seed (Result.config.seed). The number of threads follows OMP_NUM_THREADS. The reconstructions, the mask filter, the redshift-space correction and the table readers and writers of otswap.io release the GIL while they run. A Result must not be read from one thread while another modifies it in place, as otswap::rejectMaskCrossings() and otswap::recomputeMeans() (otswap.reject_mask_crossings(), otswap.recompute_means()) do.

What it prints

Each call reports what it did, in lines starting with otswap:, at the level verbosity sets: silent, normal (the default: what was selected and lost) or detailed (otswap::Verbosity, otswap.Verbosity, which list the lines). The periodic box example prints, at the normal level:

otswap: wrapped 0 of 50000 tracers into the periodic box [0, 1000] x [0, 1000] x [0, 1000]
otswap: reconstructBox: 8 realizations of 50000 tracers in 0.88 s; 0 without a valid displacement
otswap: realSpaceBox: corrected 50000 of 50000 tracers in 0.01 s; 0 left uncorrected

C++ writes to the stream set in Config::log, CorrectionConfig::log or the log argument of measureMpsProfile, std::clog by default; Python to sys.stdout, which a notebook shows. In Python, Ctrl+C stops a reconstruction, measure_mps_profile or a correction at its next line with KeyboardInterrupt.

Errors

Invalid input and failures raise otswap::Error (otswap.Error), whose message names the object at fault; names side by side describes them in both languages. Among the conditions every reconstruction checks: at least 114 tracers reconstructed (each needs 113 distinct neighbours), and enough randoms.