C++ reference

Generated from the public headers otswap/OT.h, otswap/RSD.h, otswap/io.h, otswap/ParameterFile.h, otswap/Maths.h and otswap/Random.h by Doxygen.

otswap/OT.h

Errors

class Error : public std::runtime_error

Base class of every exception otswap throws on invalid input or failure. std::bad_alloc is not converted, and propagates unchanged, from inside a parallel region too. An error of the neighbour search, a meshsearch::Error or an exception derived from it, reaches the caller as an Error whose message is “meshsearch: “ followed by its own, with the original nested in it (std::throw_with_nested), so std::rethrow_if_nested recovers it.

An Error records where in otswap’s sources it was raised: file(), function() and line(). The location is not part of what(), which holds the message alone.

Public Functions

inline explicit Error(const std::string &what, const char *file = __builtin_FILE(), const char *function = __builtin_FUNCTION(), int line = __builtin_LINE())
Parameters:
  • what – the message, returned by what()

  • file, function, line – the location; left to their defaults, they are those of the expression that constructs the Error

inline const char *file() const noexcept

Source file in which the Error was constructed, as the compiler named it.

inline const char *function() const noexcept

Name of the function in which the Error was constructed.

inline int line() const noexcept

Line at which the Error was constructed.

Configuration

struct Config

Free parameters of the reconstruction.

The multipliers that govern the seeding radius, the neighbourhood size and the initial pairing are absent: they are internal constants of the algorithm, not parameters.

Public Members

unsigned nRealizations = 30

Independent reconstructions to run, at least 1. Each consumes as many randoms as there are tracers reconstructed. Advice on the choice: the guide, section “Choosing the parameters”.

double convergence = 1.e-3

The sweeps stop once the fraction of successful swaps in a sweep, swaps per tracer visited, no longer exceeds this threshold; it must lie strictly between 0 and 1. Every tracer is examined in every sweep. Advice on the choice: the guide, section “Choosing the

parameters”.

unsigned seed = 0

Seed of the random streams, 0 to 2^32 - 1. 0 draws one from std::random_device, and the result records the seed drawn (Result::config).

double cellSize = 3.

Grid cell size, in units of the representative mean particle separation; must be positive. Affects speed only, never the result. Advice on the choice: the guide, section “Choosing the parameters”.

bool rejectCrossings = true

With a Mask given to reconstructLightcone, apply rejectMaskCrossings to the result, with maxUnobservedPixelsCrossed, before returning it. Read by the mask overloads of reconstructLightcone only.

unsigned maxUnobservedPixelsCrossed = 0

The threshold of that call, the longest run of unobserved pixels a displacement’s arc may cross; rejectMaskCrossings gives the rule. Read by the mask overloads of reconstructLightcone only. Advice on the choice: the guide, section “Choosing the parameters”.

Verbosity verbosity = Verbosity::Normal

What the call reports; see Verbosity.

std::ostream *log = &std::clog

Where the report is written; null writes nothing, as Silent.

enum class otswap::Verbosity

What a reconstruction or a redshift-space correction reports.

Each line starts with “otswap: “ and ends in ‘

’; the counts behind every line are in the object returned, so nothing printed is unavailable to a program. What is discarded is always reported at Normal.

The lines go to the stream set in Config::log, CorrectionConfig::log or the log argument of measureMpsProfile, std::clog by default; null writes nothing. Each line is written, and the stream flushed, as soon as its step finishes. A call that throws keeps the lines of the steps it finished and does not write its call line.

Values:

enumerator Silent

Nothing.

enumerator Normal

The selection report of a lightcone, when a selection applied, and of a box, when limits were given (SelectionCounts::message), and the extrapolation of b(z), when it happened; 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

enumerator 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 (moved by their neighbours) and of the uncorrected (left out of the reconstruction, or with no valid neighbour).

enum class otswap::Geometry

The geometry a Result was reconstructed in.

Values:

enumerator Box

reconstructBox

enumerator LightconeSky

reconstructLightcone with right ascension, declination and redshift

enumerator LightconeCartesian

reconstructLightcone with Cartesian positions

struct RedshiftCut

A closed redshift range for reconstructLightcone. The default, (-inf, +inf), cuts nothing.

Public Members

double min = -std::numeric_limits<double>::infinity()

lower bound, redshift

double max = std::numeric_limits<double>::infinity()

upper bound, redshift

struct DistanceCut

A closed range of comoving distance from the origin, in coordinate units, for the Cartesian overloads of reconstructLightcone and measureMpsProfile: the counterpart of RedshiftCut. The default, (-inf, +inf), cuts nothing.

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::outsideDistanceCut, and the randoms outside it are dropped. A mean Lagrangian position may lie outside it.

Public Members

double min = -std::numeric_limits<double>::infinity()

lower bound, in coordinate units

double max = std::numeric_limits<double>::infinity()

upper bound, in coordinate units

struct BoxLimits

The closed limits of a box for reconstructBox: the points with lower[k] <= x[k] <= upper[k] on each axis k, in coordinate units. Each bound must be finite, with lower[k] < upper[k]; the default, NaN, is refused.

For a periodic box, the period of axis k is upper[k] - lower[k]; reconstructBox, at its periodic parameter, gives the rule the periods must follow.

Public Members

std::array<double, 3> lower{std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN()}

x, y, z of the lower corner.

std::array<double, 3> upper{std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN()}

x, y, z of the upper corner.

Distances

class DistanceTable

Sampled redshift to comoving distance relation, interpolated in both directions, and the linear growth rate on the same grid.

The object is immutable once built and holds no external state, so one instance can serve any number of reconstructions concurrently.

Public Functions

DistanceTable(double OmegaM, double h, double w0 = -1., double wa = 0., double zMin = 0., double zMax = 10., unsigned nSamples = 50000)

Build from the parameters of a flat cosmology.

Samples nSamples points over [zMin, zMax] and integrates 1/E(z), with E^2(z) the sum of matter and of dark energy with equation of state w(a) = w0 + wa (1 - a); radiation is neglected. The distances are in Mpc/h, so h does not enter them: it is only checked. The defaults of w0 and wa give flat LCDM. Other cosmologies are served by the table constructor below.

With the default range and sampling, for flat LCDM and w0-wa cosmologies near it, the relative error of distanceAt, redshiftAt and growthRateAt is below 1e-6 for z >= 0.01, and that of growthRateAt over the whole range; the absolute error of distanceAt, and that of redshiftAt expressed as a distance along the line of sight, is below 2e-5 Mpc/h over [0, 10]. Below z = 0.01 the relative error of the distances grows, because the distance itself vanishes at z = 0 while the absolute error does not.

The growth rate f = dlnD/dlna is sampled on the same grid, by integrating the linear growth equation from deep in matter domination and taking f from the solution.

Parameters:
  • OmegaM – matter density parameter; must lie in (0, 1]

  • h – Hubble constant in units of 100 km/s/Mpc; must be positive

  • w0 – dark energy equation of state, constant term; default -1; must be finite

  • wa – dark energy equation of state, evolution term; default 0; must be finite

  • zMin – lower end of the sampled range; must be non-negative

  • zMax – upper end; must exceed zMin

  • nSamples – sampling points, uniform in redshift; must be at least two

Throws:

Error – if any parameter is out of range, or if the parameters make E^2 or the growth rate non-positive or not finite where they are computed.

DistanceTable(std::vector<double> redshift, std::vector<double> distance, std::vector<double> growthRate = {})

Build from a table the caller has computed.

Parameters:
  • redshift – strictly increasing, at least two entries

  • distance – strictly increasing, same length, comoving, in the unit that Cartesian coordinates and every length will then have

  • growthRate – f = dlnD/dlna on the same grid, or empty. When empty the table carries no growth rate and growthRateAt throws. Need not be monotonic; every entry must be finite and positive.

Throws:

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

double distanceAt(double z) const

Comoving distance at z. Throws outside the sampled range. A value outside it by at most 8 rounding errors of the range’s largest magnitude is taken to be at the nearer end, so that values computed from the table’s own ends, such as the radius of a position converted at the largest redshift, are accepted. The same holds for redshiftAt and growthRateAt.

double redshiftAt(double distance) const

Redshift at a comoving distance. Throws outside the sampled range, with the end tolerance of distanceAt.

double growthRateAt(double z) const

Growth rate f = dlnD/dlna at z. Throws outside the sampled range, with the end tolerance of distanceAt, and when the table carries no growth rate.

bool hasGrowthRate() const

True when the table carries a growth rate.

double minRedshift() const

lowest sampled redshift

double maxRedshift() const

highest sampled redshift

const std::vector<double> &redshift() const

The sampled redshifts, strictly increasing, as given to the table constructor or as the cosmology constructor sampled them. A table built from redshift(), distance() and growthRate() with the table constructor gives the same value, bit for bit, at every lookup.

const std::vector<double> &distance() const

The comoving distance at each sampled redshift: Mpc/h from the cosmology constructor, the unit of the table given to the table constructor.

const std::vector<double> &growthRate() const

The growth rate at each sampled redshift; empty when the table carries none.

std::vector<double> otswap::toCartesian(const std::vector<double> &sky, const DistanceTable &distances)

Convert sky coordinates to Cartesian comoving coordinates.

Object i at right ascension ra, declination dec and redshift z maps to x = d cos(dec) cos(ra), y = d cos(dec) sin(ra), z = d sin(dec), with d = distances.distanceAt(z). reconstructLightcone converts its sky arrays with this function, so Cartesian arrays made with it are exactly the ones that overload uses.

Parameters:
  • sky – sky coordinates, 3 * nObjects entries, ordered right ascension, declination, redshift; angles in radians. May be empty.

  • distances – the redshift to distance relation.

Throws:

Error – if the array’s size is not a multiple of three, if an entry is not finite, if a declination lies outside [-pi/2, pi/2], or if a redshift falls outside the distance table; the message names the object.

Returns:

Cartesian coordinates in the unit of the distance table, 3 * nObjects entries ordered x, y, z.

std::vector<double> otswap::toSky(const std::vector<double> &cartesian, const DistanceTable &distances)

Convert Cartesian comoving coordinates to sky coordinates: the inverse of toCartesian, with the same observer at the origin.

Object i at (x, y, z) maps to the right ascension atan2(y, x) folded into [0, 2 pi), the declination asin(z / d), and the redshift at which the table’s comoving distance is d = |(x, y, z)|. A position at the origin gets right ascension and declination 0. toSky(toCartesian(sky)) returns sky within a few rounding errors, with the right ascension folded into [0, 2 pi).

Parameters:
  • cartesian – 3 * nObjects entries, ordered x, y, z, in the unit of the distance table. May be empty. A row holding a NaN gives a NaN row.

  • distances – the redshift to distance relation; its range bounds the distances accepted.

Throws:

Error – if the array’s size is not a multiple of three, if an entry is infinite, or if a distance falls outside the table (beyond its end tolerance); the message names the object and, for the distance, suggests a table covering a wider redshift range.

Returns:

sky coordinates, 3 * nObjects entries, ordered right ascension, declination, redshift; angles in radians.

void otswap::pointToSky(double x, double y, double z, double &distance, double &ra, double &dec) noexcept

Comoving distance, right ascension and declination of one Cartesian point, the observer at the origin; no distance table.

The geometric part of toSky, bit for bit: distance = |(x, y, z)|, the right ascension atan2(y, x) folded into [0, 2 pi), the declination asin(z / distance), the ratio clamped to [-1, 1]. The origin gets right ascension and declination 0. A NaN coordinate gives NaN in all three, as a NaN row of toSky does; an infinite one gives an infinite distance. Never throws.

Parameters:
  • x, y, z – the point, in coordinate units.

  • distance – [out] the distance from the origin, in coordinate units.

  • ra – [out] the right ascension, radians.

  • dec – [out] the declination, radians.

std::vector<double> otswap::skyToRadians(std::vector<double> skyDegrees)

Right ascension and declination of a sky array from degrees to radians, multiplied by pi/180; redshifts unchanged.

The factor is the double numpy.deg2rad multiplies by, so an array converted here and one converted by the Python package are the same.

Parameters:

skyDegrees – 3 * nObjects entries, ordered right ascension, declination, redshift; angles in degrees. May be empty.

Throws:

Error – if the size is not a multiple of three, or a finite declination lies outside [-90, 90] degrees; the message names the object.

std::vector<double> otswap::skyToDegrees(std::vector<double> skyRadians)

Right ascension and declination of a sky array from radians to degrees, multiplied by 180/pi; redshifts unchanged. A right ascension that rounds to 360 is folded to 0, so that one in [0, 2 pi) stays in [0, 360). NaN stays NaN.

Parameters:

skyRadians – 3 * nObjects entries, ordered right ascension, declination, redshift; angles in radians. May be empty.

Throws:

Error – if the size is not a multiple of three.

Returns:

the same array with the angles in degrees.

Mask

class Mask

Healpix veto mask, read from a FITS file or built from a full-sky map in memory.

A pixel is allowed (observed) when its value is greater than 0, whatever its magnitude: fractional values, the smallest positive ones and +inf are allowed. A pixel holding 0, a negative value, -inf, NaN or Healpix’s UNSEEN (-1.6375e30) is unobserved. Every value is accepted, and each is tested once, in double, when the mask is built; none is kept or used as a weight, so skyAreaDeg2 is a count of allowed pixels, not a sum of their values. The rule is the same for both sources.

NSIDE must be a power of 2 in the NESTED scheme. A map in memory may have any NSIDE from 1 to 2^29, Healpix’s limit. A FITS map holds 1024 pixels to a row, so its NSIDE is a multiple of 16, up to 2^29. 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. A map too large for memory raises std::bad_alloc.

The object is immutable once built.

Public Functions

explicit Mask(const std::string &fitsFile)
Parameters:

fitsFile – Healpix map: a binary table in HDU 2 whose first column holds the values, 1024 to a row (so NSIDE is a multiple of 16), in any numeric column type; other columns are ignored. NSIDE and ORDERING are taken from the header, in either RING or NESTED scheme. The values are read a block of rows at a time, so reading needs memory for the mask’s bytes only. Each value is tested as cfitsio converts it to double, after any TSCAL and TZERO; a null value of an integer column (TNULL) is unobserved.

Throws:

Error – if the file cannot be opened or read, if it is not a full-sky Healpix map in that layout, if NSIDE exceeds 2^29, or if the ordering is NESTED and NSIDE is not a power of 2.

Mask(const double *values, std::size_t count, PixelOrdering ordering)

Build from the pixel values of a full-sky Healpix map.

NSIDE follows from the number of values, which must be 12 NSIDE^2. The values are read once, during construction, and not kept.

Parameters:
  • values – one value per pixel, in the order of ordering

  • count – the number of values

  • ordering – the pixel ordering of values; no default

Throws:

Error – if count is 0 or not 12 NSIDE^2 for an integer NSIDE, if NSIDE exceeds 2^29, if the ordering is NESTED and NSIDE is not a power of 2, or if values is null; the message gives the number of values and the NSIDE it implies.

Mask(const std::vector<double> &values, PixelOrdering ordering)

As the constructor from a pointer and a count, over all of values.

Parameters:
  • values – one value per pixel, in the order of ordering

  • ordering – the pixel ordering of values; no default

bool allows(double rightAscension, double declination) const

True when the direction falls in an allowed pixel. Radians.

Throws:

Error – if the right ascension is not finite, or the declination is not in [-pi/2, pi/2].

double skyAreaDeg2() const

Sky area covered by the allowed pixels, in square degrees.

int nside() const

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

enum class otswap::PixelOrdering

Pixel ordering of a full-sky Healpix map given in memory.

Values:

enumerator Ring

the RING scheme

enumerator Nested

the NESTED scheme

Reconstruction

Result otswap::reconstructBox(const std::vector<double> &tracers, const std::vector<double> &randoms, double mps, const Config &config, const std::optional<BoxLimits> &limits = std::nullopt, bool periodic = false)

Reconstruct in box geometry, with a constant mean particle separation.

Note

Without periodic, the box is not periodic: nothing flows through its faces, so modes on the scale of the box itself cannot be reconstructed.

Note

In a periodic box the cells of the neighbour grids divide the shortest side, so they may be smaller than config.cellSize * mps.

Parameters:
  • tracers – Cartesian coordinates, 3 * nObjects entries.

  • randoms – Cartesian coordinates of the randoms, or empty. When empty, config.nRealizations * N randoms are drawn uniformly in the box limits, or without them in the bounding box of the tracers, N the tracers reconstructed. When given, the array must hold at least config.nRealizations * N of them, both counted inside the limits when they are given, since each realization consumes a disjoint subset; without limits they may lie outside the bounding box of the tracers.

  • mps – mean particle separation, in coordinate units; must be positive. It sets the radius of the first guess, 8 mps, and the cell of the neighbour grids.

  • config – the parameters of the run; rejectCrossings and maxUnobservedPixelsCrossed are not read.

  • limits – the box of the reconstruction, or none. Given, the tracers outside it take no part in the reconstruction and are flagged in Result::outsideBox, the randoms given outside it are dropped, and the neighbour grids span it. A point on a face is inside.

  • periodic – whether the box is periodic, for a whole simulation box with periodic boundary conditions (a sub-volume cut from one is not periodic). It requires limits, whose period on each axis, upper[k] - lower[k], must be an integer multiple of the shortest one, within a relative 1e-12: a cube, or a cuboid such as 500 x 500 x 1000. Every distance is then the minimum image, and nothing is left out: each tracer and each given random outside the limits is wrapped into them, by a whole number of periods per axis, and counted in Result::selection. Result::tracers holds the wrapped tracers, and the randoms are counted and drawn as with limits.

Throws:

Error – if config is invalid (see Config), if any array has a size that is not a multiple of three, if fewer than 114 tracers are reconstructed (each needs 113 distinct neighbours) or more than 2^32 - 1 are given, if the randoms are too few, if any coordinate is not finite, if a bound of the limits is not finite or a lower bound is not below the upper one, if the limits keep too few tracers or randoms, or if mps is not positive; with periodic, if no limits are given or a side is not an integer multiple of the shortest. Also, from the neighbour search (see Error), if the grid cannot be built: a cell of config.cellSize * mps (in a periodic box, reduced to divide the shortest side a whole number of times: see Result::cellSide) so small against the extent of the tracers and randoms that the grid would need more cells than it can count.

Returns:

the displacement field, one row per tracer given; every entry of valid is 1 and validRealizations is config.nRealizations, but for the tracers outside the limits, whose rows are as for Result::outsideBox, and meanDisplacement is the mean over all realizations. Result::mps is mps, and Result::box the limits or, without them, the bounding box of the tracers and the given randoms, or of the tracers alone when the randoms are drawn.

Result otswap::reconstructBox(const std::vector<double> &tracers, const std::vector<double> &randoms, const Config &config, const std::optional<BoxLimits> &limits = std::nullopt, bool periodic = false)

Reconstruct in box geometry, with the mean particle separation of the tracers: mps = (V / N)^(1/3), N the tracers inside the box and V its volume, the box being Result::box: the limits or, without them, 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). The value used is Result::mps. In a periodic box, V is the volume of the limits and N every tracer.

The other parameters, limits and periodic included, are as in the overload above.

Throws:

Error – as above, from the neighbour search included, and, without limits, if the tracers, with the given randoms, span no volume (all of them in one plane, on one line or at one point).

Result otswap::reconstructLightcone(const std::vector<double> &tracersSky, const std::vector<double> &randomsSky, double skyAreaDeg2, unsigned nBins, const DistanceTable &distances, const Config &config, const RedshiftCut &cut = {})

Reconstruct in lightcone geometry, from sky coordinates.

The mean particle separation is measured from the tracers themselves, as a profile in redshift over nBins bins: MpsProfile describes how, and the minimum number of tracers per bin.

Randoms are required and are not generated: they carry the survey geometry, the selection function and the completeness, none of which this package models.

The counts are recorded in Result::selection and, with a cut that has a finite bound, reported as config.verbosity says.

Parameters:
  • tracersSky – sky coordinates, 3 * nObjects entries, angles in radians.

  • randomsSky – sky coordinates of the randoms, angles in radians. Their number is checked after the redshift cut and, in the overloads with a mask, the mask: the randoms kept must number at least config.nRealizations times the tracers kept, which is config.nRealizations * nObjects when nothing is left out. They may lie outside the Cartesian bounding box of the tracers.

  • skyAreaDeg2 – effective area of the survey, in square degrees, in (0, 41252.96], the whole sky. When a mask is available, pass the mask instead, to the overload below, which takes the area from it; otherwise supply the published value: a bounding box in right ascension and declination overestimates it for any footprint that is not rectangular, and the error propagates into the mean particle separation.

  • nBins – redshift bins used to measure mps(z), at least 1; each must hold enough tracers (see MpsProfile). measureMpsProfile gives the profile without reconstructing. Advice on the choice: the guide, section “Choosing the parameters”.

  • distances – 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.

  • config – the parameters of the run; rejectCrossings and maxUnobservedPixelsCrossed are read by the mask overloads only.

  • cut – tracers and randoms whose redshift lies outside [cut.min, cut.max] are left out of the reconstruction, before anything else: the randoms are dropped, and the tracers keep their row, flagged in Result::outsideRedshiftCut. mps(z) is measured on the tracers kept, and the redshifts of the tracers and randoms kept must lie in the distance table. The default cuts nothing.

Throws:

Error – if config is invalid (see Config), if nBins is 0, if skyAreaDeg2 is outside its range, if a bin holds too few tracers for its density to be meaningful (the message gives an upper bound on the number of bins: see MpsProfile), or if every tracer kept lies at one redshift. Also if the profile extrapolates to a mps that is not positive at a tracer’s redshift, if any array is malformed, if fewer than 114 tracers are kept or more than 2^32 - 1 are given, if a declination lies outside [-pi/2, pi/2], if the randoms are too few, or if the redshift of a tracer or random kept falls outside the distance table (the message names which, and its row in the array given). Also if a bound of the cut is NaN or min > max, or if too few tracers or randoms remain inside it; the message gives the counts kept and dropped. Also, from the neighbour search (see Error), if the grid cannot be built: a cell of config.cellSize mean particle separations so small against the extent of the tracers and randoms that the grid would need more cells than it can count.

Result otswap::reconstructLightcone(const std::vector<double> &tracersSky, const std::vector<double> &randomsSky, const Mask &mask, unsigned nBins, const DistanceTable &distances, const Config &config, const RedshiftCut &cut = {})

Reconstruct in lightcone geometry, from sky coordinates, within the observed pixels of a mask.

As the overload with the sky area, with the area taken from the mask, mask.skyAreaDeg2(), and the mask applied twice:

  • before the reconstruction, tracers and randoms on unobserved pixels are left out, decided on their right ascension and declination as Mask::allows decides: the randoms are dropped, and the tracers keep their row, flagged in Result::outsideMask;

  • after it, when config.rejectCrossings is set, rejectMaskCrossings is applied with config.maxUnobservedPixelsCrossed, so the result carries filteredNside = mask.nside().

The mask and the redshift cut are both evaluated on every object, so a tracer may be flagged by both; the objects kept are those that pass both. The counts are recorded in Result::selection and reported as config.verbosity says.

Set the threshold in config: a later rejectMaskCrossings with a higher threshold changes nothing, the filter only clearing entries. To choose it afterwards, set config.rejectCrossings to false and call rejectMaskCrossings on the result.

Parameters:
  • tracersSky – as in the overload with the sky area.

  • randomsSky – as in the overload with the sky area.

  • nBins – as in the overload with the sky area.

  • distances – as in the overload with the sky area.

  • mask – the survey’s veto mask; borrowed for the call only.

  • config – as in the overload with the sky area; rejectCrossings and maxUnobservedPixelsCrossed are read here.

  • cut – as in the overload with the sky area, evaluated with the mask on every object.

Throws:

Error – as the overload with the sky area, from the neighbour search included, the counts in the message naming the mask as well as the cut.

Result otswap::reconstructLightcone(const std::vector<double> &tracers, const std::vector<double> &randoms, double skyAreaDeg2, unsigned nBins, const Config &config, const DistanceTable *distances = nullptr, const DistanceCut &cut = {})

Reconstruct in lightcone geometry, from Cartesian comoving coordinates, the observer at the origin; no cosmology.

As the overload from sky coordinates, with the mean particle separation measured as a profile in comoving distance from the origin rather than in redshift (see MpsProfile). Result::mpsProfile is that profile, and each tracer’s mps is its value at the tracer’s distance.

The result is filled as by the sky overload, with tracers the array given and tracersSky, lagrangianSky and lagrangianDistance computed with pointToSky; the redshifts come from distances when one is given and are NaN otherwise, or where a distance lies outside it.

Parameters:
  • tracers – Cartesian coordinates, 3 * nObjects entries, in coordinate units.

  • randoms – Cartesian coordinates of the randoms, required, as in the sky overload, in the same units.

  • skyAreaDeg2 – as in the sky overload.

  • nBins – distance bins used to measure mps(d), as nBins in the sky overload.

  • config – as in the sky overload.

  • distances – optional; the table whose redshifts fill those of tracersSky and lagrangianSky, and which the result keeps. It plays no part in the reconstruction: the result is the same with or without it but for those redshifts and Result::distances.

  • cut – the redshift cut of the sky overload, in comoving distance from the origin: tracers and randoms whose distance lies outside [cut.min, cut.max] are left out before anything else, the randoms dropped and the tracers kept in their row, flagged in Result::outsideDistanceCut; mps(d) is measured on the tracers kept. The counts are recorded in Result::selection and, with a cut that has a finite bound, reported as config.verbosity says. The default cuts nothing.

Throws:

Error – if config is invalid (see Config), if nBins is 0, if skyAreaDeg2 is outside its range, if a bin holds too few tracers, if the profile extrapolates to a mps that is not positive at a tracer’s distance, if every tracer kept lies at the same distance, if any array is malformed or holds a non-finite coordinate, if fewer than 114 tracers are kept or more than 2^32 - 1 are given, or if the randoms are too few; also from the neighbour search, as in the sky overload. Also if a bound of the cut is NaN or min > max, or if too few tracers or randoms remain inside it; the message gives the counts kept and dropped.

Result otswap::reconstructLightcone(const std::vector<double> &tracers, const std::vector<double> &randoms, const Mask &mask, unsigned nBins, const Config &config, const DistanceTable *distances = nullptr, const DistanceCut &cut = {})

Reconstruct in lightcone geometry, from Cartesian comoving coordinates, within the observed pixels of a mask; no cosmology.

The Cartesian overload with the sky area, with the area taken from the mask and the mask applied as by the sky overload with a mask: the objects on unobserved pixels, decided on the right ascension and declination pointToSky gives, are left out before the reconstruction, and, when config.rejectCrossings is set, the displacements crossing unobserved pixels are rejected after it.

Parameters:
  • tracers – as in the Cartesian overload with the sky area.

  • randoms – as in the Cartesian overload with the sky area.

  • mask – the survey’s veto mask; borrowed for the call only.

  • nBins – as in the Cartesian overload with the sky area.

  • config – as in the sky overload with a mask.

  • distances – as in the Cartesian overload with the sky area.

  • cut – as in the Cartesian overload with the sky area, evaluated with the mask on every object, as in the sky overload with a mask.

Throws:

Error – as the Cartesian overload with the sky area, and if too few tracers or randoms remain inside the mask; the counts in the message name the mask as well as the cut.

MpsProfile otswap::measureMpsProfile(const std::vector<double> &tracersSky, double skyAreaDeg2, unsigned nBins, const DistanceTable &distances, const RedshiftCut &cut = {}, Verbosity verbosity = Verbosity::Normal, std::ostream *log = &std::clog)

The mps(z) profile reconstructLightcone measures, without reconstructing: from sky coordinates, with the sky area given.

The steps of reconstructLightcone that concern the tracers, in the same order and with the same code: the checks of the sky array and of the cut, the redshift cut, the minimum number of tracers kept, and the profile with its per-bin threshold. The profile equals, bit for bit, Result::mpsProfile of a reconstructLightcone call with the same tracers, skyAreaDeg2, nBins, distances and cut, whatever its randoms and config. Use it to choose nBins, or to inspect the profile, before a reconstruction.

Parameters:
  • tracersSky – as in reconstructLightcone.

  • skyAreaDeg2 – as in reconstructLightcone.

  • nBins – as in reconstructLightcone.

  • distances – as in reconstructLightcone; it must cover the redshifts of the tracers kept.

  • cut – as in reconstructLightcone, applied to the tracers.

  • verbosity – what the call reports (see Verbosity). At Normal, when the cut has a finite bound, the tracer line of the selection report (SelectionCounts::message), then the measureMpsProfile line; at Detailed, the mps(z) line of reconstructLightcone before the last.

  • log – where the report is written; null writes nothing.

Throws:

Error – as reconstructLightcone, with the same messages, if the tracer array is malformed, if nBins is 0, if skyAreaDeg2 is outside its range, if a declination lies outside [-pi/2, pi/2], if a bound of the cut is NaN or min > max, if a cut with a finite bound keeps too few tracers, if every tracer kept lies at one redshift, if a bin holds too few tracers, or if a redshift kept falls outside the distance table.

MpsProfile otswap::measureMpsProfile(const std::vector<double> &tracersSky, const Mask &mask, unsigned nBins, const DistanceTable &distances, const RedshiftCut &cut = {}, Verbosity verbosity = Verbosity::Normal, std::ostream *log = &std::clog)

The mps(z) profile reconstructLightcone measures, without reconstructing: from sky coordinates, within the observed pixels of a mask.

As the overload with the sky area, with the area taken from the mask, mask.skyAreaDeg2(), and the tracers on unobserved pixels left out as reconstructLightcone leaves them out. The profile equals, bit for bit, Result::mpsProfile of the mask overloads of reconstructLightcone with the same tracers, mask, nBins, distances and cut.

Parameters:
  • tracersSky – as in reconstructLightcone.

  • mask – the survey’s veto mask; borrowed for the call only.

  • nBins – as in reconstructLightcone.

  • distances – as in the overload with the sky area.

  • cut – as in reconstructLightcone, evaluated with the mask on every tracer.

  • verbosity – as in the overload with the sky area; the tracer line of the selection report is always written, since the mask applies.

  • log – as in the overload with the sky area.

Throws:

Error – as the overload with the sky area, the counts in the message naming the mask as well as the cut.

MpsProfile otswap::measureMpsProfile(const std::vector<double> &tracers, double skyAreaDeg2, unsigned nBins, const DistanceCut &cut = {}, Verbosity verbosity = Verbosity::Normal, std::ostream *log = &std::clog)

The mps(d) profile the Cartesian overloads of reconstructLightcone measure, without reconstructing: from Cartesian coordinates, with the sky area given.

The steps of the Cartesian reconstructLightcone that concern the tracers, in the same order and with the same code: the checks of the array and of the cut, the distance cut, the minimum number of tracers kept, and the profile in distance with its per-bin threshold. The profile equals, bit for bit, Result::mpsProfile of the Cartesian reconstructLightcone with the same tracers, skyAreaDeg2, nBins and cut, whatever its randoms, config and table.

Parameters:
  • tracers – as in the Cartesian reconstructLightcone.

  • skyAreaDeg2 – as in reconstructLightcone.

  • nBins – as in the Cartesian reconstructLightcone.

  • cut – as in the Cartesian reconstructLightcone, applied to the tracers.

  • verbosity – what the call reports (see Verbosity). At Normal, when the cut has a finite bound, the tracer line of the selection report (SelectionCounts::message), then the measureMpsProfile line in coordinate units; at Detailed, the mps(d) line of reconstructLightcone before the last.

  • log – where the report is written; null writes nothing.

Throws:

Error – as the Cartesian reconstructLightcone, with the same messages, if the array is malformed, if nBins is 0, if skyAreaDeg2 is outside its range, if a bound of the cut is NaN or min > max, if a cut with a finite bound keeps too few tracers, if every tracer kept lies at the same distance, or if a bin holds too few tracers.

MpsProfile otswap::measureMpsProfile(const std::vector<double> &tracers, const Mask &mask, unsigned nBins, const DistanceCut &cut = {}, Verbosity verbosity = Verbosity::Normal, std::ostream *log = &std::clog)

The mps(d) profile of the Cartesian reconstructLightcone with a mask, without reconstructing.

As the Cartesian overload with the sky area, with the area taken from the mask, mask.skyAreaDeg2(), and the tracers on unobserved pixels left out as the Cartesian reconstructLightcone with a mask leaves them out; at Normal the tracer line of the selection report comes first. The profile equals, bit for bit, Result::mpsProfile of that overload with the same tracers, mask, nBins and cut. The cut is evaluated with the mask on every tracer.

Parameters:
  • tracers – as in the Cartesian reconstructLightcone.

  • mask – the survey’s veto mask; borrowed for the call only.

  • nBins – as in the Cartesian reconstructLightcone.

  • cut – as in the Cartesian reconstructLightcone, evaluated with the mask on every tracer.

  • verbosity – as in the Cartesian overload with the sky area; the tracer line of the selection report is always written, since the mask applies.

  • log – as in the Cartesian overload with the sky area.

Throws:

Error – as the Cartesian overload with the sky area, and if too few tracers remain inside the mask; the counts in the message name the mask as well as the cut.

void otswap::rejectMaskCrossings(Result &result, const Mask &mask, unsigned maxUnobservedPixelsCrossed = 0)

Reject the displacements whose path crosses masked sky.

The segment from the Eulerian position, the tracer (Result::tracers), to the Lagrangian one, the tracer plus its displacement, lies in the plane through the origin and both endpoints, so its projection on the sky is exactly the great circle arc between them. The arc is bisected adaptively. A sub-arc is not split further when:

  • its ends fall in the same pixel;

  • it is shorter than a millionth of the pixel size;

  • it is shorter than a pixel, its end pixels share an edge, and they have no common neighbour that could change a run: none at all when both end pixels are unobserved, no unobserved one otherwise.

The pixels of the midpoints are examined in order along the arc, and the unobserved pixels met one after another, with no observed pixel between them, form a run; a run is counted in distinct pixels. The pixels holding the two endpoints are exempt, and end a run as an observed pixel does.

A displacement is rejected when the longest run along its arc holds more than maxUnobservedPixelsCrossed pixels; the search stops as soon as a run exceeds it. Unobserved pixels in separate runs are not added together: an arc that crosses two small holes is judged by the larger one. With 0, the first unobserved pixel rejects. A displacement with an endpoint at the origin is kept, and one whose endpoints lie in exactly opposite directions, which defines no arc, is rejected.

A rejected displacement has its entry of valid cleared; entries already cleared stay cleared, so the filter composes with any other and applying it twice with the same mask and threshold changes nothing. The fields that follow from valid are then recomputed, as recomputeMeans does: validRealizations, meanDisplacement, lagrangian, lagrangianSky and lagrangianDistance. On a result holding a mean (nRealizationsMean above 1, one realization), validRealizations keeps the counts of the objects kept, and is 0 for those rejected.

Result::selection records the filter: maxUnobservedPixelsCrossed the threshold of this call, displacements the valid displacements before the first filter applied to the result, and displacementsCrossingMask those rejected by the filters so far, in total.

A tracer that took no part in the reconstruction, flagged in any of Result::outsideRedshiftCut, outsideDistanceCut, outsideMask and outsideBox, is left as it is: its tracers and displacement rows may be NaN, and its entries of valid must be 0. Every other tracer and displacement must be finite.

Warning

The run is counted in pixels, not as an angular length, so it depends on NSIDE: the same arc crosses about twice as many pixels when NSIDE doubles, and the same threshold is a different criterion.

Parameters:
  • result – a lightcone result, updated in place; a box result is refused, so a Result built by hand must set Result::geometry.

  • mask – the mask whose unobserved pixels are counted.

  • maxUnobservedPixelsCrossed – the longest run of unobserved pixels tolerated along the arc, the endpoint pixels excluded.

Throws:

Error – if the result is a box result, which has no sky to filter against; if the result is malformed (including 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 3 * nObjects entries, or a flag, tracersSky, lagrangian or lagrangianSky array whose size is neither 0 nor the one of its layout), if an entry of valid is neither 0 nor 1, or if the result was already filtered against a mask of a different NSIDE.

void otswap::recomputeMeans(Result &result)

Recompute every field of a result that follows from valid: validRealizations and meanDisplacement, then lagrangian, lagrangianSky and lagrangianDistance.

meanDisplacement is summed over the valid realizations in realization order and divided by their count, as the reconstruction does, so a result whose displacement and valid were read back from a file gives the reconstruction’s bits. lagrangian is tracers + meanDisplacement, wrapped into the box of a periodic result, and left empty when tracers is; lagrangianSky and lagrangianDistance are then filled as Result::lagrangianSky and Result::lagrangianDistance describe, and left empty otherwise.

Throws:

Error – if displacement or valid has the wrong size, an entry of valid is neither 0 nor 1, or a flag, tracers or tracersSky array has a size that is neither 0 nor the one of its layout.

Results

struct Result

Displacement field produced by a reconstruction.

Displacements point from the Eulerian (observed) position to the Lagrangian one: the Lagrangian position of object i is its coordinate plus its displacement.

Public Members

std::size_t nObjects = 0

tracers, one row each, as given

unsigned nRealizations = 0

realizations held in displacement and valid

unsigned nRealizationsMean = 1

The number of realizations averaged into each displacement, when the result holds a mean as its only realization, as io::readDisplacementMean returns it; 1, the default, when it does not, as in every result of a reconstruction. A value above 1 requires nRealizations to be 1, and validRealizations then holds counts up to nRealizationsMean. The displacement writers record a value above 1 as the keyword NRECMEAN, with NREC = 1. No computation reads it.

Geometry geometry = Geometry::Box

The geometry of the reconstruction, which the writers and the redshift-space correction follow.

std::vector<std::int64_t> ids

The ID of each object, as the caller sets it: any 64-bit integer, negative ones included, each object its own. Empty means no IDs, and the writers then write object i’s row in the input, i, from 0. Flat, [object]; size nObjects or 0. The reconstruction functions leave it empty, and no computation reads it: realSpaceBox and realSpaceLightcone copy it into RealSpaceCatalog::ids, and the writers write it as the id column, among their default columns when it is not empty.

Config config

The configuration the reconstruction ran with. seed is the one used: the drawn one when 0 was given, so that the result can be reproduced.

std::vector<double> tracers

Cartesian position of each tracer, the start of its displacements: the array given to reconstructBox or to a Cartesian overload of reconstructLightcone, or toCartesian of the sky array given to a sky overload. In a periodic box, the tracers wrapped into the box: a coordinate outside the limits is shifted by a whole number of periods, one inside them is kept as given. A tracer left out by the redshift cut or the mask of a sky overload has its conversion when its redshift lies in the distance table, NaN otherwise. Flat, [object][xyz]; size 3 * nObjects.

std::vector<double> tracersSky

Sky coordinates of each tracer: right ascension, declination, redshift; radians. As given to a sky overload of reconstructLightcone; for a Cartesian overload, the right ascension and declination of pointToSky, and the redshift of the distance table given, NaN without one or where the distance lies outside it. Flat, [object][3]; size 3 * nObjects in a lightcone result, empty in a box result.

std::vector<double> displacement

Displacements: the random matched to each object in each realization, minus the tracer. Flat, [realization][object][xyz]. Size 3 * nRealizations * nObjects. In a periodic box, the minimum image: on each axis, d - L floor(d / L + 1/2), d the difference and L the period, in [-L/2, L/2) within rounding.

std::vector<std::uint8_t> valid

Validity of each displacement: 1 valid, 0 rejected by a filter. Flat, [realization][object]. Size nRealizations * nObjects. Every entry is 1 until a filter is applied; a filter only ever clears entries.

std::vector<double> meanDisplacement

Mean displacement per object, over its valid realizations only, summed in realization order, then divided by their count. NaN in all three components for an object with no valid realization. Flat, [object][xyz]. Size 3 * nObjects.

std::vector<unsigned> validRealizations

Valid realizations per object: the count of 1 entries of valid for that object, and the number of terms in its meanDisplacement. In a result holding a mean (nRealizationsMean above 1), the count of the realizations averaged into it that were valid. Always at most nRealizations x nRealizationsMean. Size nObjects.

int filteredNside = 0

NSIDE of the mask this result was last filtered against, or 0 when it has not been filtered. Set by rejectMaskCrossings, which refuses to filter the same result against a mask of a different NSIDE.

std::vector<std::uint8_t> outsideRedshiftCut

Whether each tracer lay outside the redshift cut of reconstructLightcone and so took no part in the reconstruction: 1 for such a tracer, 0 otherwise. Flat, [object]. Size nObjects, all 0 when no cut was given, in a result of a Cartesian overload and in a box result.

A cut tracer has NaN in every component of its displacement rows, valid 0 in every realization, validRealizations 0 and meanDisplacement NaN. No filter changes the flag. A Result built by hand may leave the field empty, which every function reads as all 0.

std::vector<std::uint8_t> outsideDistanceCut

Whether each tracer lay outside the distance cut of a Cartesian overload of reconstructLightcone, and so took no part in the reconstruction: 1 for such a tracer, 0 otherwise. Flat, [object]. Size nObjects, all 0 when no cut was given, in a result of a sky overload and in a box result. A flagged tracer’s rows are as for outsideRedshiftCut, and no filter changes the flag. An empty field is read as all 0.

std::vector<std::uint8_t> outsideMask

Whether each tracer fell on an unobserved pixel of the Mask given to reconstructLightcone, and so took no part in the reconstruction: 1 for such a tracer, 0 otherwise. Flat, [object]. Size nObjects, all 0 when no mask was given and in a box result. Independent of outsideRedshiftCut: a tracer may carry both flags. A flagged tracer’s rows are as for outsideRedshiftCut, and no filter changes the flag. An empty field is read as all 0.

std::vector<std::uint8_t> outsideBox

Whether each tracer lay outside the limits given to reconstructBox, and so took no part in the reconstruction: 1 for such a tracer, 0 otherwise. Flat, [object]. Size nObjects, all 0 when no limits were given, in a periodic box and in a lightcone result. A flagged tracer’s rows are as for outsideRedshiftCut, and no filter changes the flag. An empty field is read as all 0.

SelectionCounts selection

What the reconstruction left out, and why, and what the mask filters rejected; updated by every rejectMaskCrossings.

std::vector<double> lagrangian

Mean Lagrangian position of each tracer, tracers + meanDisplacement, in a periodic box wrapped into the box as the tracers are. NaN rows where meanDisplacement is NaN. Flat, [object][xyz]; size 3 * nObjects. Recomputed with meanDisplacement by rejectMaskCrossings and recomputeMeans.

std::vector<double> lagrangianSky

Sky coordinates of each tracer’s mean Lagrangian position, as toSky computes them from lagrangian with the reconstruction’s distance table: right ascension in [0, 2 pi), declination, redshift; radians. Flat, [object][3]; size 3 * nObjects in a LightconeCartesian result, and in a LightconeSky result with a distance table or a profile in distance; empty otherwise (a box result included). Recomputed with lagrangian.

NaN rows where lagrangian is NaN: the tracers flagged in outsideRedshiftCut, outsideDistanceCut or outsideMask and those with no valid realization. A position whose distance falls outside the table, which a table that does not start at distance 0 allows, has a NaN redshift and keeps its right ascension and declination. Without a table, as a Cartesian overload of reconstructLightcone given none returns it, every redshift is NaN and the angles are filled.

std::vector<double> lagrangianDistance

Comoving distance from the origin of each tracer’s mean Lagrangian position, as pointToSky computes it from lagrangian, in coordinate units. Flat, [object]; size nObjects when lagrangianSky is filled, empty otherwise; NaN where lagrangian is NaN. Recomputed with lagrangian.

double mps = std::numeric_limits<double>::quiet_NaN()

Box: the mean particle separation used, given or computed, in coordinate units. NaN in a lightcone result, whose separation is mpsProfile.

std::optional<BoxLimits> box

Box: the box of the reconstruction, the limits given to reconstructBox or, without them, 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. Empty in a lightcone result.

bool periodic = false

Box: whether the box was periodic, as given to reconstructBox. A periodic result has geometry Box and its limits in box; its tracers, displacements and lagrangian follow the periodic box. Always false in a lightcone result.

double cellSide = std::numeric_limits<double>::quiet_NaN()

The cell side of the neighbour grids actually used, in coordinate units. It is config.cellSize times the mean particle separation (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. NaN in a Result built by hand (Python Result.from_arrays) or read from a file. Not written to files.

MpsProfile mpsProfile

Lightcone: the mean particle separation profile measured on the tracers kept: in redshift for a sky overload of reconstructLightcone, in distance for a Cartesian one. Empty in a box result.

std::shared_ptr<const DistanceTable> distances

Lightcone: the distance table of the reconstruction, shared by the copies of this result, with which rejectMaskCrossings and recomputeMeans recompute lagrangianSky. Null in a box result, and in the result of a Cartesian overload of reconstructLightcone given no table.

double elapsedSeconds = 0.

Wall time of the call that made the result, in seconds. Two runs with the same seed give the same result but for this field.

struct MpsProfile

The mean particle separation of a lightcone as a function of redshift or of comoving distance, measured by reconstructLightcone, or alone by measureMpsProfile.

The overloads that take sky coordinates bin the tracers kept in nBins uniform redshift bins over [redshiftMin, redshiftMax]: a profile in redshift, with redshift filled and distance empty. The overloads that take Cartesian coordinates bin them in nBins uniform bins of comoving distance from the origin over [distanceMin, distanceMax]: a profile in distance, with distance filled and redshift empty. In each bin mps = (N / V)^(-1/3), V the shell volume implied by the sky area (and, for a profile in redshift, the distance table). Each bin must hold at least 1/(9 eps^2) tracers, eps = 0.02, that is 278: below that count the Poisson error on its mps exceeds 2%. A bin holding fewer is refused, and the error gives an upper bound on the number of bins, the number of tracers kept divided by 278; the bins being uniform, a sparse tail may need fewer. The bin values are the nodes of a piecewise linear profile, extrapolated linearly beyond the terminal ones; at() evaluates it. Empty in a box result.

Public Functions

double at(double value) const

The mps at value, in coordinate units: a redshift for a profile in redshift, a comoving distance for a profile in distance. Linear between the nodes, extrapolated linearly beyond the terminal ones along the terminal segment, constant with a single node. This is the value the reconstruction used at each tracer.

Throws:

Error – if the profile is empty, holds both redshift and distance nodes, or holds a number of nodes different from the number of values, or if the value found is not positive, which only an extrapolation can give, or NaN.

Public Members

std::vector<double> redshift

bin centres of a profile in redshift

std::vector<double> mps

in coordinate units, at each centre

std::vector<std::size_t> count

tracers in each bin

double redshiftMin = std::numeric_limits<double>::quiet_NaN()

The binned range of a profile in redshift: the smallest and largest redshift of the tracers kept. NaN in a profile in distance.

double redshiftMax = std::numeric_limits<double>::quiet_NaN()

see redshiftMin

double representative = std::numeric_limits<double>::quiet_NaN()

The count-weighted median of the nodes, in coordinate units, which sizes the grids of the reconstruction.

std::vector<double> distance

Bin centres of a profile in distance, in coordinate units.

double distanceMin = std::numeric_limits<double>::quiet_NaN()

The binned range of a profile in distance: the smallest and largest distance of the tracers kept, in coordinate units. NaN in a profile in redshift.

double distanceMax = std::numeric_limits<double>::quiet_NaN()

see distanceMin

struct SelectionCounts

The objects a reconstruction left out, and why, and the displacements its mask filter rejected.

In a lightcone result, the tracers removed are tracersOutsideRedshiftCut + tracersOutsideMask - tracersOutsideBoth from a sky overload of reconstructLightcone, and tracersOutsideDistanceCut + tracersOutsideMask - tracersOutsideBoth from a Cartesian one, and the same for the randoms; the counts of the other cut are 0. In a box result, the tracers removed are tracersOutsideBox, and the randoms removed randomsOutsideBox; these and the counts of what was given are set only when limits were given to reconstructBox, with randoms 0 when the randoms were drawn. In a periodic box nothing is removed: the objects outside the limits are wrapped into them, counted in tracersWrapped and randomsWrapped, and the counts outside the box are 0. Every other count is 0, and nothing else is applied, in a box result; the box and wrapping counts are 0 in a lightcone result.

Public Functions

std::string message() const

The selection report of a reconstruction.

One line for the tracers and one for the randoms, each listing the selections applied, then one for the rejected crossings when a filter was applied; each line ends in ‘

’. A line is written even when nothing was removed. 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
With a distance cut, from a Cartesian overload, the cut reads “<a> outside the distance cut [<dmin>, <dmax>] in coordinate units”.

For a box with limits, the tracer line, and the random line when randoms were given:

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>]
For a periodic box, in their place:
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>]

Returns:

the report, or an empty string when no selection and no filter was applied.

Public Members

std::optional<RedshiftCut> redshiftCut

the cut, when a bound was finite

std::optional<DistanceCut> distanceCut

the distance cut, when a bound was finite

bool maskApplied = false

a Mask was given

std::optional<BoxLimits> boxLimits

the limits, when given to reconstructBox

bool periodic = false

the box of reconstructBox was periodic

std::size_t tracers = 0

tracers given

std::size_t tracersOutsideRedshiftCut = 0

of them, outside the cut

std::size_t tracersOutsideDistanceCut = 0

of them, outside the distance cut

std::size_t tracersOutsideMask = 0

of them, on an unobserved pixel

std::size_t tracersOutsideBoth = 0

outside the cut, redshift or distance, and the mask

std::size_t tracersOutsideBox = 0

of them, outside the box limits

std::size_t tracersWrapped = 0

of them, wrapped into the periodic box

std::size_t randoms = 0

randoms given

std::size_t randomsOutsideRedshiftCut = 0

of them, outside the cut

std::size_t randomsOutsideDistanceCut = 0

of them, outside the distance cut

std::size_t randomsOutsideMask = 0

of them, on an unobserved pixel

std::size_t randomsOutsideBoth = 0

outside the cut, redshift or distance, and the mask

std::size_t randomsOutsideBox = 0

of them, outside the box limits

std::size_t randomsWrapped = 0

of them, wrapped into the periodic box

std::optional<unsigned> maxUnobservedPixelsCrossed

The threshold of the latest rejectMaskCrossings applied to the result, by reconstructLightcone or afterwards; empty when none was.

std::size_t displacements = 0

valid displacements before the first filter

std::size_t displacementsCrossingMask = 0

of them, rejected by the filters so far, in total

otswap/RSD.h

The chain

RealSpaceCatalog otswap::realSpaceLightcone(const Result &result, const DistanceTable &distances, const BiasTable &bias, double sigma, const CorrectionConfig &config = {})

Move a lightcone catalogue from redshift space to real space.

The chain, for the tracers of the result:

  1. the projection of result.meanDisplacement on the line of sight of each tracer, at result.tracers (radialProjection);

  2. its Gaussian average of width sigma over the tracers with a valid realization (neighbourAverage); a tracer without one still receives the average around its own position;

  3. the factor f / (b + 3 f / 5) at each observed redshift, as rsdFactor computes it; the tracers at which b(z) is extrapolated are counted in RealSpaceCatalog::nExtrapolated, and reported;

  4. each tracer keeps its right ascension and declination and moves to the redshift of comoving distance d(z_i) + s_i, where s_i is the factor times the average; its Cartesian position moves by s_i along its line of sight.

Tracers flagged in result.outsideRedshiftCut, result.outsideDistanceCut or result.outsideMask are left out: they take no part in any average, are not moved, have diagnostics 0, and the status LeftOut.

The observed redshift of a tracer is read from tracersSky when it is not NaN. A tracer whose redshift is NaN, as in a result of a Cartesian overload of reconstructLightcone built without a distance table, or whose distance fell outside it, or one read from a file with no redshift, takes it from its position: it is the redshift at which distances reaches the tracer’s distance from the origin, which is also the d(z_i) of step 4. The right ascension and declination are always those of tracersSky.

A tracer that has a redshift is moved from the distance distances gives at that redshift, one without from its position’s distance, so a Cartesian result built with a distance table and the same result built without one can differ in the corrected positions, by rounding only: redshifts and distances are interpolated linearly between the same nodes of the table.

On a Result read by io::readDisplacementComplete the correction is that of the reconstruction itself, bit for bit, but for the right ascension and declination of RealSpaceCatalog::sky, which match within the rounding of the file’s conversion to degrees and back.

Parameters:
  • result – a lightcone reconstruction, with its tracers and tracersSky, as reconstructLightcone returns it, from a sky or a Cartesian overload.

  • distances – the table the result was reconstructed with, or one with the same distances, in the unit of the coordinates; it must carry the growth rate, and cover the corrected distances as well as the observed ones.

  • bias – the b(z) table.

  • sigma – width of the average, in coordinate units; 0 for none. Advice on the choice: the guide, section “Choosing the parameters”.

  • config – the weighting, and what the call reports.

Throws:
  • Error – if result is not a lightcone result, is malformed or lacks its tracers or tracersSky, 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 table carries no growth rate, if the bias table is malformed or extrapolates to a bias that is not positive, if the distance of a tracer with no redshift lies outside the distance table, or if a corrected comoving distance is not positive or lies outside the distance table; the message names the object, and in the last two cases suggests a table covering a wider redshift range.

  • Error – from the neighbour search, as neighbourAverage, for the tracers corrected.

RealSpaceCatalog otswap::realSpaceBox(const Result &result, unsigned axis, double redshift, const DistanceTable &distances, double bias, double sigma, const CorrectionConfig &config = {})

Move a box catalogue from redshift space to real space, with the line of sight along a Cartesian axis.

The chain is that of realSpaceLightcone, on result.tracers, with the projection on the axis, a single factor f / (b + 3 f / 5) at the box’s redshift, and the shift applied along the axis. For a periodic result (Result::periodic) the neighbours are found across the faces, with minimum-image distances (see neighbourAverage), and the corrected coordinate along the axis is wrapped into the box; otherwise no position is wrapped.

Tracers flagged in result.outsideBox are left out, as in realSpaceLightcone, with the status LeftOut.

Parameters:
  • result – a box reconstruction, with its tracers.

  • axis – the line of sight: 0, 1 or 2.

  • redshift – the box’s redshift, at which f is taken.

  • distances – a table carrying the growth rate at that redshift.

  • bias – the tracers’ linear bias; finite and positive.

  • sigma – as in realSpaceLightcone.

  • config – the weighting, and what the call reports.

Throws:
  • Error – if result is not a box result, 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 rsdFactorBox.

  • Error – from the neighbour search, as neighbourAverage, for the tracers corrected.

struct CorrectionConfig

Options of realSpaceLightcone and realSpaceBox.

Public Members

bool weightByRealizations = false

Weight each neighbour by its count of valid realizations as well, as in neighbourAverage. Advice on the choice: the guide, section “Choosing the parameters”.

Verbosity verbosity = Verbosity::Normal

What the call reports; see Verbosity.

std::ostream *log = &std::clog

Where the report is written; null writes nothing, as Silent.

struct RealSpaceCatalog

A catalogue moved to real space. Row i describes input object i.

Public Members

std::size_t nObjects = 0

The number of objects: the rows of every per-object array.

Geometry geometry = Geometry::Box

The geometry of the reconstruction corrected.

std::vector<std::int64_t> ids

The IDs of the objects, copied from Result::ids of the result corrected: empty, or nObjects entries. Written as the id column.

std::vector<double> sky

Lightcone: right ascension, folded into [0, 2 pi), and declination of the tracer, and its corrected redshift; radians. Flat, [object][3]. NaN rows for the tracers not moved. Empty in a box.

std::vector<double> cartesian

The corrected Cartesian position, in coordinate units. Box: the tracer with its axis coordinate moved. Lightcone: r (1 + shift / |r|), the tracer r moved along its line of sight. Flat, [object][xyz]. NaN rows for the tracers not moved.

std::vector<double> shift

The shift applied along the line of sight, in coordinate units: the factor times the averaged projection. NaN for a tracer not moved. nObjects entries.

std::vector<double> factor

The factor f / (b + 3 f / 5) at each tracer’s observed redshift; in a box, the single factor repeated. NaN for a tracer left out of the reconstruction. nObjects entries.

std::vector<CorrectionStatus> status

What the correction did with each tracer. nObjects entries.

std::vector<unsigned> validRealizations

The valid realizations of each tracer, copied from the result corrected. nObjects entries.

std::vector<unsigned> nNeighbours

The valid tracers averaged, as neighbourAverage counts them; 0 for a tracer left out. nObjects entries.

std::vector<unsigned> nRealizationsAveraged

The sum of the valid realizations of the tracers averaged; 0 for a tracer left out. nObjects entries.

std::size_t nExtrapolated = 0

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

double sigma = std::numeric_limits<double>::quiet_NaN()

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

bool weightByRealizations = false

The weighting of the average, as given in CorrectionConfig::weightByRealizations.

unsigned axis = 0

Box: the line-of-sight axis, as given; 0 in a lightcone.

double boxRedshift = std::numeric_limits<double>::quiet_NaN()

Box: the redshift, as given; NaN in a lightcone.

double boxBias = std::numeric_limits<double>::quiet_NaN()

Box: the bias, as given; NaN in a lightcone.

double elapsedSeconds = 0.

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

enum class otswap::CorrectionStatus : std::uint8_t

What the correction did with each tracer.

Values:

enumerator Corrected

had a valid realization; moved

enumerator MovedByNeighbours

had no valid realization; moved with its neighbours’ average

enumerator NoValidNeighbour

no valid tracer within 3 sigma (with sigma = 0: no valid realization); not moved

enumerator LeftOut

outside the reconstruction’s redshift or distance cut, mask or box limits; not moved

The four steps

std::vector<double> otswap::radialProjection(const std::vector<double> &displacement, const std::vector<double> &positions)

Component of each displacement along the line of sight of its object, r_i . d_i / |r_i|: positive when the displacement points away from the observer.

Parameters:
  • displacement – 3 * N, for example Result::meanDisplacement. NaN is allowed, and gives NaN for that object; infinities are not.

  • positions – Cartesian, 3 * N, for example Result::tracers; every position finite and away from the origin.

Throws:

Error – if the sizes differ or are not multiples of three, if a position is not finite or is at the origin, or if a displacement is infinite; the message names the object.

std::vector<double> otswap::axisProjection(const std::vector<double> &displacement, unsigned axis)

Component of each displacement along a Cartesian axis, the line of sight of a box.

Parameters:
  • displacement – 3 * N; NaN allowed, infinities not.

  • axis – 0, 1 or 2.

Throws:

Error – if the size is not a multiple of three, if the axis is not 0, 1 or 2, or if a displacement is infinite.

NeighbourAverage otswap::neighbourAverage(const std::vector<double> &positions, const std::vector<double> &values, const std::vector<unsigned> &validRealizations, double sigma, bool weightByRealizations = false)

Gaussian average of a value over the neighbours of each object.

An object is valid when its validRealizations is greater than zero. Each object, valid or not, receives the weighted mean of the values of the valid objects within 3 sigma of its own position, its own value included when it is valid. The weight of a neighbour at distance d is exp(-d^2 / (2 sigma^2)), multiplied by its validRealizations when weightByRealizations is set, and the weights are normalised on their sum, so a constant value is returned unchanged, at the edges of the catalogue too. An object with no valid object within 3 sigma receives NaN.

With sigma = 0 no average is taken and values is returned unchanged.

The neighbours are found on a grid built inside, over the bounding box of the positions given; nothing passed in is modified. The result does not depend on that grid within rounding, and is the same bit for bit for the same inputs, whatever the number of threads.

Parameters:
  • positions – Cartesian, 3 * N, finite.

  • values – N entries; finite wherever validRealizations > 0, and not read elsewhere.

  • validRealizations – N entries.

  • sigma – width of the Gaussian, in the unit of the positions; finite and non-negative. For coordinates in Mpc/h, 10 Mpc/h is a reasonable starting value, to be checked in each analysis; advice on the choice: the guide, section “Choosing the parameters”.

  • weightByRealizations – weight each neighbour by its count of valid realizations as well.

Throws:
  • Error – if the sizes 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 – from the neighbour search (see Error) if sigma > 0 and the positions span no volume (a single object, or all of them in one plane or on one line): the neighbour grid cannot be built.

Returns:

the average and two diagnostics per object.

NeighbourAverage otswap::neighbourAverage(const std::vector<double> &positions, const std::vector<double> &values, const std::vector<unsigned> &validRealizations, double sigma, bool weightByRealizations, const BoxLimits &box, bool periodic)

neighbourAverage in a periodic box.

The neighbours are found on a periodic grid over the limits and their distances are minimum-image, so a tracer near a face averages over the tracers near the opposite face. With periodic false it is the first overload, and box is not used.

Parameters:
  • positions – as in the first overload.

  • values – as in the first overload.

  • validRealizations – as in the first overload.

  • sigma – as in the first overload.

  • weightByRealizations – as in the first overload.

  • box – the limits of the box; with periodic, each side an integer multiple of the shortest, as for reconstructBox.

  • periodic – whether the box is periodic. The positions must lie inside the limits (closed); wrap them first.

Throws:

Error – as the first overload but for the span of the positions, and if the limits are not a valid periodic box or a position lies outside them.

struct NeighbourAverage

The result of neighbourAverage: N entries each.

Public Members

std::vector<double> values

The average at each object; NaN with no valid object within 3 sigma; with sigma = 0, the input value.

std::vector<unsigned> nNeighbours

The number of valid objects averaged, the object itself included when it is valid. With sigma = 0, 1 for a valid object and 0 otherwise.

std::vector<unsigned> nRealizationsAveraged

The sum of validRealizations over those objects.

std::vector<double> otswap::rsdFactor(const std::vector<double> &redshift, const DistanceTable &distances, const BiasTable &bias, std::size_t *nExtrapolated = nullptr)

The factor f / (b + 3 f / 5) that turns the averaged line-of-sight displacement into the shift to real space, at each redshift.

f is distances.growthRateAt(z), b(z) the bias table at z. It writes no report; the redshifts at which b(z) is extrapolated beyond the table are counted in *nExtrapolated, when given.

Parameters:
  • redshift – observed redshifts, inside the distance table’s range.

  • distances – a table carrying the growth rate.

  • bias – the b(z) table.

  • nExtrapolated – if not null, receives the number of redshifts outside the bias table.

Throws:

Error – if the distance table carries no growth rate, if a redshift is not finite or lies outside the distance table, if the bias table is malformed, or if the extrapolated bias at a redshift is not positive; the message names the object.

double otswap::rsdFactorBox(double redshift, const DistanceTable &distances, double bias)

The factor f / (b + 3 f / 5) of a box at a single redshift, f = distances.growthRateAt(redshift), with a constant bias.

Parameters:
  • redshift – the box’s redshift, inside the distance table’s range.

  • distances – a table carrying the growth rate.

  • bias – finite and positive.

Throws:

Error – if the redshift is not finite or lies outside the distance table, if the table carries no growth rate, or if the bias is not positive.

struct BiasTable

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. Read one from a file with io::readBiasTable.

Public Members

std::vector<double> redshift

at least two, finite, strictly increasing

std::vector<double> bias

same length, finite and positive

std::vector<double> otswap::shiftRadially(const std::vector<double> &positions, const std::vector<double> &shift)

Move each position by shift_i along its own line of sight: r_i (1 + shift_i / |r_i|). A positive shift moves the object away from the observer.

Parameters:
  • positions – Cartesian, 3 * N; every position finite and away from the origin.

  • shift – N entries; NaN gives NaN in the whole row, infinities are refused.

Throws:

Error – if the sizes differ, if a position is not finite or is at the origin, or if a shift is infinite; the message names the object.

std::vector<double> otswap::shiftAlongAxis(const std::vector<double> &positions, const std::vector<double> &shift, unsigned axis)

Move each position by shift_i along a Cartesian axis. Positions are not wrapped, whether or not the box is periodic; realSpaceBox wraps the corrected coordinate of a periodic result.

Parameters:
  • positions – Cartesian, 3 * N, finite.

  • shift – N entries; NaN gives NaN along the axis, infinities are refused.

  • axis – 0, 1 or 2.

Throws:

Error – if the axis is not 0, 1 or 2, if the size of positions is not a multiple of three or a position is not finite, if shift does not hold one entry per object, or if a shift is infinite.

otswap/io.h

Tables

struct Column

One column of a table to write.

‘D’ (double) and ‘J’ (32-bit integer) columns hold their values in data; ‘K’ (64-bit integer) columns in integers, exactly. The other vector is ignored.

Public Members

std::string name

The column name. To be read back by name, it holds no blank or tab and is not made of digits alone, which io::read takes as an index.

char type = 'D'

‘D’, ‘J’ or ‘K’

std::string description

ASCII header comment; FITS TCOMMn. At most 68 characters, an apostrophe counting twice.

std::string unit

ASCII “[unit]” after the description; FITS TUNITn.

std::vector<double> data

the values of a ‘D’ or ‘J’ column

std::vector<std::int64_t> integers

the values of a ‘K’ column

struct Table

A table read from file.

Public Members

std::size_t nRows = 0

the data rows read

std::size_t nColumns = 0

the columns read as double

std::vector<double> values

flat, row-major [row][column]

std::size_t nIntegerColumns = 0

the columns read as 64-bit integers

std::vector<std::int64_t> integers

flat, row-major [row][integer column]

struct Keyword

A header keyword: a FITS keyword in the header of the HDU of a table, an ASCII “## NAME = value / comment” line. The name is at most 8 characters of A-Z, 0-9, ‘-’ and ‘_’. The value is 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. The comment holds up to 47 characters after a value of 20 columns or fewer, less after a longer one; io::write reports a comment that does not fit.

Public Members

std::string name

1 to 8 characters of A-Z, 0-9, ‘-’ and ‘_’

std::string value

at most 68 characters

std::string comment

written after the value, as above

struct WriteOptions

Options of io::write.

Public Members

int precision = 9

Significant digits of a ‘D’ value in ASCII, from 1 to 17; 17 reads back as the same double. FITS stores the doubles themselves.

std::vector<Keyword> keywords

Keywords written in the header, in this order.

Table otswap::io::read(const std::string &file, const std::vector<std::string> &columns, char delimiter = ' ', char comment = '#')

Read selected columns of a table, as double.

In FITS the columns are named, case insensitively, and must be scalar. In ASCII a column given by digits alone is a 0-based index; any other string is a name, looked up in the last line starting with “###” before the first data row, which is where io::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.

NaN and infinities are returned as stored, in both formats: a file io::write wrote with NaN rows reads back with them. A null value of a FITS integer column (TNULL) is an error.

Throws:

Error – if no column is requested, the file is missing or unreadable, a column is absent (in ASCII the message lists the names of the ### line), a column is requested twice, a requested index is too large, a row is too short, a field that must be a number is not one, or a null integer is met. 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.

Table otswap::io::read(const std::string &file, const std::vector<std::string> &columns, const std::vector<std::string> &integerColumns, char delimiter = ' ', char comment = '#')

Read selected columns as double, and others exactly as 64-bit integers.

columns are returned in Table::values, integerColumns in Table::integers, each in the order requested. In ASCII an integer field is an optional ‘-’ followed by digits; in FITS an integer column has an integer type (B, I, J or K).

Throws:

Error – as above, and if an integer field holds anything else (a decimal point, an exponent, a ‘+’, nan), lies outside the 64-bit range, is null, or comes from a FITS column of floating type; the message names the column and the ASCII line or FITS row, each counted from 1.

void otswap::io::write(const std::string &file, const std::vector<Column> &columns, const WriteOptions &options = {})

Write a table. An existing file is overwritten.

Throws:

Error – if no column is given, a column type is not ‘D’, ‘J’ or ‘K’, the columns differ in length (data for ‘D’ and ‘J’, integers for ‘K’), a ‘J’ value is NaN, not an integer, or outside [-2^31, 2^31) (the message names the column and the row), a keyword name is invalid, a keyword value exceeds 68 characters, a keyword comment exceeds the room its card leaves (see Keyword), a column description exceeds 68 characters (an apostrophe counting twice), a keyword holds a line break, the precision is outside [1, 17], or the file cannot be written.

void otswap::io::write(const std::string &file, const std::vector<Column> &columns, std::size_t nRows, const std::function<void(std::size_t, std::vector<double>&)> &fillRow, const WriteOptions &options = {})

Write a table whose rows are produced on demand.

The data and integers of each column are ignored; fillRow is called once per row, in order, with a buffer of one entry per column. Nothing is held in memory, so this is the variant for catalogue-sized output. ‘K’ columns need the overload below.

Throws:

Error – as above, and if a column is of type ‘K’.

void otswap::io::write(const std::string &file, const std::vector<Column> &columns, std::size_t nRows, const std::function<void(std::size_t, std::vector<double>&, std::vector<std::int64_t>&)> &fillRow, const WriteOptions &options = {})

As above, with ‘K’ columns: fillRow receives two buffers of one entry per column, and each column reads its own entry of the buffer of its type, values for ‘D’ and ‘J’, integers for ‘K’; the entry of the other buffer is ignored.

std::vector<Keyword> otswap::io::readKeywords(const std::string &file, const std::string &extname = "")

Read the keywords of a table, in file order.

FITS (a file name ending in .fits, .fit or .fits.gz): the header of HDU 2 or, with extname, of the HDU 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 “ = “ up to the first “ / “, as written, so a value that itself holds “ / “ is cut there.

Comments are not read: Keyword::comment is empty. A keyword written by io::write reads back with the same name and, but for the case of the exponent in FITS and outer blanks of a FITS string, the same value; numbers written with 17 significant digits read back as the same double.

Throws:

Error – if the file cannot be opened, is not a valid FITS file, has no HDU 2, or has no HDU of that EXTNAME (the message names the file).

std::vector<std::string> otswap::io::columnNames(const std::string &file, const std::string &extname = "", char delimiter = ' ', char comment = '#')

The names of the columns of a table, in column order: the names io::read finds in the same file.

FITS (a file name ending in .fits, .fit or .fits.gz): the TTYPEn of the table in HDU 2 or, with extname, of the HDU of that EXTNAME, compared ignoring case, as written. io::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 io::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, twinFile(file, twin).

Throws:

Error – if the file cannot be opened or is not a valid FITS file, if HDU 2 or the HDU 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.

struct TablePart

One table of a file holding several, for writeParts.

In FITS each part is a binary table of the same file, the first in HDU 2 and the others in the next HDUs, 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, twinFile(file, twin); each file is a table as io::write writes it, readable by io::read.

The rows come from fillRow when it is set, as with the row overload of io::write: nRows rows, the data and integers of the columns ignored. Without it they come from the columns, which must then all hold the same number of entries, as with io::write; nRows is ignored.

Public Members

std::string extname

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.

std::string twin

The name of the ASCII twin file: 1 to 68 characters of A-Z, a-z, 0-9, ‘-’ and ‘_’. 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.

std::vector<Column> columns

the columns, as for io::write

std::size_t nRows = 0

the rows, with fillRow; ignored without it

std::function<void(std::size_t, std::vector<double>&, std::vector<std::int64_t>&)> fillRow

Fills row i, as the row overload of io::write; empty to take the rows from the columns.

WriteOptions options

precision and keywords of this part

void otswap::io::writeParts(const std::string &file, const std::vector<TablePart> &parts)

Write a file holding several tables: FITS, one binary table per part, from HDU 2; 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 hasPart still finds them.

Throws:

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 io::write for any part. Every part is checked before any file is opened, but for the values of ‘J’ columns, checked as they are written.

Table otswap::io::readPart(const std::string &file, const std::string &extname, const std::string &twin, const std::vector<std::string> &columns, const std::vector<std::string> &integerColumns = {})

Read selected columns of one part of a file writeParts wrote, the first included, as io::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 (HDU 2); twin is ignored. ASCII: the table in twinFile(file, twin), or with an empty twin in the file itself, read with the default delimiter and comment character; extname is ignored.

Throws:

Error – as io::read, and if the file has no table of that EXTNAME, or the twin file is missing.

bool otswap::io::hasPart(const std::string &file, const std::string &extname, const std::string &twin)

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 (HDU 2); twin is ignored. ASCII: whether twinFile(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.

Throws:

Error – if a FITS file cannot be opened.

std::string otswap::io::twinFile(const std::string &file, const std::string &twin)

The ASCII twin file of a part: <stem>.<twin>.<ext>, where ext is 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.

BiasTable otswap::io::readBiasTable(const std::string &file, char delimiter = ' ', char comment = '#')

Read a b(z) table.

The format follows the extension: FITS from the columns named REDSHIFT and BIAS (case insensitively); ASCII from columns 0 and 1, with the given delimiter and comment character.

The table is checked as rsdFactor checks a BiasTable, so a table read without error is one rsdFactor accepts.

Throws:

Error – if the file cannot be read (as io::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

io::writeDisplacementMean, io::writeDisplacementComplete, io::writeRealSpaceCatalog, io::writeMpsProfile and their group enums are documented on the File formats page, with the layouts they write, and so are io::readDisplacementMean and io::readDisplacementComplete, which read a mean and a complete displacement file back.

otswap/ParameterFile.h

Not included by otswap/OT.h; the syntax of the file is on the File formats page.

class ParameterFile

A parameter file: one key = value per line, read once by the constructor and typed at each read.

The syntax (keys, comments, quoting, lists) is described on the documentation page “File formats”, section “Parameter files”.

A scalar read requires exactly one element; a std::vector read takes every element. The types are std::string, bool (true or false), int, unsigned, std::int64_t (decimal integers), double (finite, with an optional exponent), char (one character, or \t for a tab), and std::vector of each.

Every error is an otswap::Error whose message starts with the file and, when there is one, the line and the key: ‘run.ini:7: key ‘seed’: …`.

The marks behind unread() are the only state a read changes; reading one ParameterFile from several threads at once is not safe.

Public Functions

explicit ParameterFile(const std::string &file)

Reads and checks the syntax of the whole file.

Parameters:

file – the path; it appears as given in every error message

Throws:

otswap::Error – if the file cannot be opened or read, or at the first line that breaks the syntax

bool has(const std::string &key) const

True if the file sets the key. Does not mark it read.

std::size_t line(const std::string &key) const

The line, from 1, that sets the key. Does not mark it read.

Throws:

otswap::Error – if the file does not set the key, with the message of get: ‘run.ini: key ‘seed’ is missing`

template<typename T>
inline T get(const std::string &key) const

The value of a key the file must set, as a T. Marks the key read.

Throws:

otswap::Error – if the key is missing or its value is not a T

template<typename T>
inline T get(const std::string &key, const typename detail::NonDeduced<T>::type &defaultValue) const

The value of a key, as a T, or defaultValue if the file does not set it. Marks the key read if it is set. T is always given explicitly: get<double>(“sigma”, 1).

Throws:

otswap::Error – if the key is set and its value is not a T

std::vector<Entry> unread() const

The keys no get has read, in file order, each with its line.

struct Entry

A key of the file and the line, from 1, that sets it.

Public Members

std::string key

the key

std::size_t line

the line, from 1, that sets it

otswap/Maths.h

Elementary functions that return the same bits on every platform.

Each returns the same bits on every supported platform and compiler, whatever the system’s maths library, and is within one unit in the last place of the correctly rounded value. Use them in place of the standard library’s where a result must be reproducible bit for bit. sqrt, fabs, floor and fmod need no counterpart here: IEEE 754 already makes them exact or correctly rounded everywhere.

Author

Simone Sartori simone.sartori@inaf.it

namespace otswap
namespace maths

Functions

double sin(double x)

The sine of x, in radians.

double cos(double x)

The cosine of x, in radians.

double exp(double x)

e raised to the power x.

double log1p(double x)

The natural logarithm of 1 + x, accurate also for x near 0.

double cbrt(double x)

The cube root of x, negative for negative x.

double asin(double x)

The arc sine of x, in radians, in [-pi/2, pi/2].

double pow(double x, double y)

x raised to the power y.

double atan2(double y, double x)

The angle of the point (x, y) from the x axis, in radians, in [-pi, pi].

otswap/Version.h

Generated by CMake when the library is built, and installed with the other headers; not included by otswap/OT.h. It defines four macros:

OTSWAP_VERSION

The version as a string literal, such as "0.5.0".

OTSWAP_VERSION_MAJOR, OTSWAP_VERSION_MINOR, OTSWAP_VERSION_PATCH

Its three parts, as integer literals, for use in #if.

otswap/Random.h

Not included by otswap/OT.h.

Random draws that give the same values on every platform.

std::mt19937 is specified exactly by the C++ standard, but the standard distributions and std::shuffle are not: their algorithms are left to each library, so the same engine can give different values with different compilers. The functions here are written out over the engine’s 32-bit outputs, so a given engine state gives the same values on every supported platform and compiler. The reconstructions draw through them.

Their algorithms, described below down to the engine outputs each call consumes, are fixed: no later version of otswap changes them, so a program that draws with them keeps its values when otswap is updated.

Author

Simone Sartori simone.sartori@inaf.it

inline unsigned otswap::uniformInt(std::mt19937 &engine, const unsigned bound)

A uniform integer in [0, bound).

Lemire’s multiply-and-reject method: an engine output x gives the 64-bit product x * bound; when its low 32 bits are below 2^32 mod bound, x is rejected and a new output drawn. The result is the high 32 bits of the first product kept. Every value in [0, bound) is exactly equally likely. A bound of 0 returns 0 and draws nothing.

Parameters:
  • engine – the engine, advanced by one output per attempt

  • bound – the number of possible values

double otswap::uniformReal(std::mt19937 &engine, double lo, double hi)

A uniform double in [lo, hi).

Each call draws exactly two engine outputs, a then b, and forms u = ((a >> 5) * 2^26 + (b >> 6)) / 2^53, a multiple of 2^-53 in [0, 1). The result is lo + u * (hi - lo); when rounding makes it hi, the largest double below hi is returned instead, so the result is always below hi.

Parameters:
  • engine – the engine, advanced by two outputs

  • lo, hi – the interval’s bounds: both finite, lo below hi, and hi - lo finite

Throws:

Error – when a bound is not finite, lo is not below hi, or hi - lo overflows; the engine is then not advanced

template<typename T>
void otswap::shuffle(std::vector<T> &v, std::mt19937 &engine)

Puts the elements of v in a uniformly random order.

Fisher-Yates, from the end: for i = v.size() down to 2, the element at i - 1 is swapped with the one at uniformInt(engine, i). The engine is advanced only by those calls.

Parameters:
  • v – the elements, at most 2^32 - 1 of them

  • engine – the engine

Throws:

Error – when v holds more than 2^32 - 1 elements; v and the engine are then unchanged