Examples¶
Six examples, each a C++ program and a Python script that do the same thing: the same inputs, parameters and seed, and the same output files, byte for byte. Each example folder in examples is a CMake project of its own, built against an installed otswap. The guide gives the path of steps each one follows. All of them run 8 realizations with a convergence threshold of 1e-2, to run in seconds; the defaults, 30 and 1e-3, are the starting point for an analysis. The mean particle separation (mps) is the scale the reconstruction works at (guide).
The data¶
The examples read the files of examples/data, which come with a clone of the repository; they are not in the Python package or the source distribution. They are provided for running the examples, may be redistributed unchanged with them, and may not be used for any other purpose: examples/data/README.md gives the terms and the content of each file. Lengths are in Mpc/h (the boxes are cubes of side 400 and 1000 Mpc/h) and angles in degrees.
Building and running¶
Install otswap first: the C++ library under a prefix <prefix> (README,
“Build from source”), the Python package with pip install otswap. Then, for
an example <name>, from the root of the repository:
cmake -S examples/<name> -B build/examples/<name> -DCMAKE_PREFIX_PATH=<prefix>
cmake --build build/examples/<name>
build/examples/<name>/<name> [data_dir]
python examples/<name>/<name>.py [data_dir]
Both read the examples’ data folder unless data_dir is given, and write to
examples/<name>/output/, created if missing. Where cfitsio is not in a
system path, give its prefix with -DCFITSIO_ROOT=... (and -DZLIB_ROOT=...
for a static cfitsio).
The parameter files of the executable,
in examples/executable, reproduce files of the examples:
box.ini the corrected catalogue of the correction in a box, lightcone.ini
that of the correction in a lightcone, periodic_box.ini and
lightcone_cartesian.ini the files of their examples, under the executable’s
file names.
Box¶
Reconstructs the displacement field of halos in a cube, in real space, with box geometry: Cartesian coordinates, the box limits, and the mps computed from them, as the guide describes; each realization runs on its own subset of the randoms. It then sets IDs on the result, writes every realization to a FITS file, reads it back, and compares the mean over half of the realizations with the mean over all of them. The periodic box example reconstructs a whole simulation box with periodic boundary conditions.
Reads:
Writes output/displacement_box.dat, with otswap.io.write_displacement_mean(), and
output/displacement_complete_box.fits, with otswap.io.write_displacement_complete(); their
columns and keywords are on the file formats page.
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2026 by Simone Sartori, simone.sartori@inaf.it
# =================================================================
# Example code: how to run the OT reconstruction with box geometry
# =================================================================
"""This example explains how to reconstruct the displacement field of a
tracer catalogue with box geometry. The box geometry can be used with any
catalogue in comoving Cartesian coordinates, including non-cubic ones,
provided that the mean particle separation is approximately constant
throughout the catalogue.
The reconstruction matches the tracers to randoms by optimal transport: in
each realization every tracer is paired with one random, and its
displacement points from the tracer (the Eulerian, observed position) to
that random (the Lagrangian position). Independent realizations are then
averaged.
The example then keeps every realization in a file, with the catalogue's
IDs, reads it back, and uses the realizations to check whether their number
is enough.
Without the periodic option, the box is not periodic: nothing flows
through its faces, so modes on the scale of the box itself are not
reconstructed, and the displacements are least reliable near the faces. A
box cut from a periodic simulation is treated as a plain sub-volume; a
whole simulation box with periodic boundary conditions is reconstructed
with the periodic option: see the periodic_box example.
Usage: python box.py [data_dir]. The catalogues are read from data_dir, by
default the examples' data folder; the output is written to the folder
output/ next to this file, created if missing.
"""
import sys
from pathlib import Path
import numpy as np
import otswap
def main():
# -------------------------------------------------------------
# ------------ Locate the input and output folders ------------
# -------------------------------------------------------------
# The data folder is the examples' one, next to this example's folder,
# unless a first command-line argument replaces it
here = Path(__file__).resolve().parent
data = Path(sys.argv[1]) if len(sys.argv) > 1 else here.parent / "data"
output = here / "output"
output.mkdir(parents=True, exist_ok=True)
# ---------------------------------------------------------------
# ------------ Read the tracer and random catalogues ------------
# ---------------------------------------------------------------
# otswap.io.read reads the listed columns of a table: for ASCII files
# 0-based indices, or the names of the "###" line of a file otswap
# wrote; for FITS files the column names. Table.values has shape (N, 3),
# x, y, z for each object; coordinates are comoving, in Mpc/h
tracers = otswap.io.read(data / "box_halos_real_space.dat", [0, 1, 2]).values
randoms = otswap.io.read(data / "box_randoms.dat", [0, 1, 2]).values
print(f"Tracers: {len(tracers)}")
print(f"Randoms: {len(randoms)}, {len(randoms) / len(tracers):g} per tracer")
# ------------------------------------------------------------------
# ------------ Set the parameters of the reconstruction ------------
# ------------------------------------------------------------------
# They are the fields of an otswap.Config, the struct otswap::Config of
# C++, passed to the call as config; a field left out keeps its default.
#
# n_realizations: independent realizations. Each one consumes N
# randoms, disjoint from those of the others, so the random catalogue
# must hold at least n_realizations x N objects: the catalogue read here
# has exactly 8 per tracer (404,376 randoms for 50,547 halos), hence 8
# realizations. Omitting the randoms lets otswap draw them itself,
# uniformly in the box limits, or without them in the bounding box of
# the tracers.
#
# convergence: the sweeps stop once the fraction of successful swaps in a
# sweep, swaps per tracer visited, no longer exceeds this threshold.
# Larger values are faster and less accurate; 1e-2 keeps the example
# fast. For an analysis, start from the defaults, 30 realizations and
# 1e-3: the guide's section "Choosing the parameters" advises on both.
#
# seed: a fixed seed makes the run reproducible; 0 draws a new seed at
# each run, and result.config.seed records the one drawn. The number
# of threads follows OMP_NUM_THREADS, and with a fixed seed the result
# is the same whatever the number of threads.
#
# cell_size: the grid cell, in units of mps, affects the speed only,
# never the result; the default is 3.
#
# verbosity: what the reconstruction prints: with box limits, how many
# tracers and randoms lie outside them, then the line of the call;
# "detailed" adds, before that line, the mean particle separation and
# its source
config = otswap.Config(n_realizations=8, convergence=1e-2, seed=12345, cell_size=3.0,
verbosity="detailed")
# ------------------------------------------------
# ------------ Run the reconstruction ------------
# ------------------------------------------------
# The catalogues fill a known volume, the cube [269, 669] Mpc/h, so it is
# given as the box limits, the keyword box, closed on every face.
# Tracers outside them would keep their row, flagged in
# Result.outside_box with NaN displacements, and randoms outside them
# would be dropped; here none is. Without limits the box is the bounding
# box of the tracers and the randoms, as in the full_recons_box example.
#
# In box geometry the mean particle separation (mps) is a single number.
# Without one, as here, otswap takes (V/N)^(1/3), with V the volume of
# the limits and N the number of tracers inside them, and records it in
# Result.mps; the keyword mps gives it instead. It sets the radius of the
# first guess, 8 mps, within which each tracer is paired with a free
# random, and the cell of the neighbour grids, so the density must be
# roughly uniform across the box
box = ([269.0, 269.0, 269.0], [669.0, 669.0, 669.0])
result = otswap.reconstruct_box(tracers, randoms, box=box, config=config)
# ----------------------------------------------
# ------------ Summarize the result ------------
# ----------------------------------------------
# Every realization is valid for every tracer inside the limits, and
# mean_displacement is the average over all of them. Its average over
# the tracers is the offset between the centres of mass of the randoms
# used and of the tracers
mean = result.mean_displacement
all_valid = int(np.count_nonzero(result.valid_realizations == result.n_realizations))
print(f"Realizations: {result.n_realizations}, all valid for {all_valid} tracers")
print(f"Mean length of the mean displacement: {np.linalg.norm(mean, axis=1).mean():g} Mpc/h")
print("Average of the mean displacement over the tracers: ({:g}, {:g}, {:g}) Mpc/h".format(*mean.mean(axis=0)))
print("Displacement of the first tracer in the first realization: ({:g}, {:g}, {:g}) Mpc/h"
.format(*result.displacement[0, 0]))
# ------------------------------------------
# ------------ Write the output ------------
# ------------------------------------------
# One row per tracer, in the order of the input: its position, its mean
# Lagrangian position (the position plus the mean displacement), the
# mean displacement, the number of valid realizations and the flag
# outsideBox, with a header describing the columns (lengths in
# coordinate units), the box and the parameters of the run. The writer
# is the C++ library's, so the file is the C++ example's, byte for byte;
# otswap.io.read_displacement_mean reads it back (see the lightcone
# example)
otswap.io.write_displacement_mean(output / "displacement_box.dat", result)
print("Written: output/displacement_box.dat")
# --------------------------------------------------------------
# ------------ Keep every realization, with the IDs ------------
# --------------------------------------------------------------
# A catalogue usually names its objects by an ID column, read exactly by
# otswap.io.read with integer_columns, and set as Result.ids. These
# files have none, so here the position of each halo among the data rows
# of its file, counted from 1, stands for it. The reconstruction sets no
# IDs and no computation reads them: the writers put them in a first
# column, id, and real_space_box and real_space_lightcone copy them into
# the corrected catalogue. None, or exactly 0..N-1, means none
result.ids = np.arange(1, len(tracers) + 1)
# write_displacement_complete writes every realization of every tracer,
# with its valid flag, the whole configuration and the box, exactly:
# with 17 significant digits in ASCII, in binary in FITS, as here, which
# is smaller and faster to read. read_displacement_complete rebuilds the
# Result, every double identical, the means recomputed from the
# realizations; angle_unit is for lightcone files only
otswap.io.write_displacement_complete(output / "displacement_complete_box.fits", result)
print("Written: output/displacement_complete_box.fits")
read_back = otswap.io.read_displacement_complete(output / "displacement_complete_box.fits")
identical = (np.array_equal(read_back.displacement, result.displacement)
and np.array_equal(read_back.valid, result.valid)
and np.array_equal(read_back.mean_displacement, result.mean_displacement)
and np.array_equal(read_back.ids, result.ids))
ids = read_back.ids
print(f"Read back: {read_back.n_realizations} realizations of {read_back.n_objects} tracers, "
f"IDs {ids[0]} to {ids[-1]}, {'identical' if identical else 'NOT identical'} to the result written")
# ----------------------------------------------------------
# ------------ Check the number of realizations ------------
# ----------------------------------------------------------
# The arrays of a Result are read-only in Python, so a filter of one's
# own, clearing some entries of valid, works on a copy:
# Result.from_arrays builds a new result from the edited arrays, and
# computes valid_realizations, mean_displacement and the Lagrangian
# positions from displacement and valid, as otswap.recompute_means
# computes them. Here it keeps the first half of the realizations. The
# rms difference between the mean over half of them and the mean over
# all of them shows how much the mean still depends on their number: the
# larger it is against the mean length printed above, the more
# realizations are worth adding
n_half = read_back.n_realizations // 2
valid = read_back.valid.copy()
valid[n_half:] = False
half = otswap.Result.from_arrays(read_back.displacement, valid, read_back.tracers, geometry="box")
difference = half.mean_displacement - read_back.mean_displacement
print(f"rms difference between the mean displacements of {n_half} and {read_back.n_realizations} "
f"realizations: {np.sqrt((difference ** 2).sum() / len(tracers)):g} Mpc/h")
if __name__ == "__main__":
main()
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 by Simone Sartori, simone.sartori@inaf.it
// =================================================================
// Example code: how to run the OT reconstruction with box geometry
// =================================================================
/*
This example explains how to reconstruct the displacement field of a
tracer catalogue with box geometry. The box geometry can be used with
any catalogue in comoving Cartesian coordinates, including non-cubic
ones, provided that the mean particle separation is approximately
constant throughout the catalogue.
The reconstruction matches the tracers to randoms by optimal
transport: in each realization every tracer is paired with one
random, and its displacement points from the tracer (the Eulerian,
observed position) to that random (the Lagrangian position).
Independent realizations are then averaged.
The example then keeps every realization in a file, with the
catalogue's IDs, reads it back, and uses the realizations to check
whether their number is enough.
Without the periodic option, the box is not periodic: nothing flows
through its faces, so modes on the scale of the box itself are not
reconstructed, and the displacements are least reliable near the
faces. A box cut from a periodic simulation is treated as a plain
sub-volume; a whole simulation box with periodic boundary conditions
is reconstructed with the periodic option: see the periodic_box
example.
Usage: box [data_dir]. The catalogues are read from data_dir, by
default the examples' data folder; the output is written to the
folder output/ next to this file, created if missing.
*/
#include <cmath>
#include <cstdint>
#include <filesystem>
#include <iostream>
#include <string>
#include <vector>
#include "otswap/OT.h"
// ==========================================================================
int main (int argc, char** argv)
{
try {
// -------------------------------------------------------------
// ------------ Locate the input and output folders ------------
// -------------------------------------------------------------
// OTSWAP_EXAMPLES_DATA and OTSWAP_EXAMPLE_OUTPUT are set by this
// example's CMakeLists.txt to the data folder and to output/ next to
// this file. A first command-line argument replaces the data folder
const std::string data = (argc > 1) ? argv[1] : OTSWAP_EXAMPLES_DATA;
const std::string output = OTSWAP_EXAMPLE_OUTPUT;
std::filesystem::create_directories(output);
// ---------------------------------------------------------------
// ------------ Read the tracer and random catalogues ------------
// ---------------------------------------------------------------
// io::read reads the listed columns of a table: for ASCII files
// 0-based indices, or the names of the "###" line of a file otswap
// wrote; for FITS files (.fits, .fit, .fits.gz) the column names.
// Table::values holds the rows one after the other, x, y, z for each
// object: the flat layout every otswap function takes. Coordinates
// are comoving, in Mpc/h
const std::vector<double> tracers = otswap::io::read(data + "/box_halos_real_space.dat", {"0", "1", "2"}).values;
const std::vector<double> randoms = otswap::io::read(data + "/box_randoms.dat", {"0", "1", "2"}).values;
const std::size_t nTracers = tracers.size() / 3;
const std::size_t nRandoms = randoms.size() / 3;
std::cout << "Tracers: " << nTracers << std::endl;
std::cout << "Randoms: " << nRandoms << ", " << (double)nRandoms / (double)nTracers << " per tracer" << std::endl;
// ------------------------------------------------------------------
// ------------ Set the parameters of the reconstruction ------------
// ------------------------------------------------------------------
otswap::Config config;
// Independent realizations. Each one consumes N randoms, disjoint
// from those of the others, so the random catalogue must hold at least
// nRealizations x N objects: the catalogue read here has exactly 8 per
// tracer (404,376 randoms for 50,547 halos), hence 8 realizations. An
// empty random array lets otswap draw the randoms itself, uniformly in
// the box limits, or without them in the bounding box of the tracers
config.nRealizations = 8;
// The sweeps stop once the fraction of successful swaps in a sweep,
// swaps per tracer visited, no longer exceeds this threshold. Larger
// values are faster and less accurate; 1e-2 keeps the example fast.
// For an analysis, start from the defaults, 30 realizations and 1e-3:
// the guide's section "Choosing the parameters" advises on both
config.convergence = 1.e-2;
// A fixed seed makes the run reproducible; 0 draws a new seed at each
// run, and Result::config.seed records the one drawn. The number of
// threads follows OMP_NUM_THREADS, and with a fixed seed the result is
// the same whatever the number of threads
config.seed = 12345;
// The grid cell, in units of mps, affects the speed only, never the
// result; the default is 3
config.cellSize = 3.;
// What the reconstruction reports, and where: with box limits, how many
// tracers and randoms lie outside them, then the line of the call;
// Detailed adds, before that line, the mean particle separation and its
// source. The report goes to std::clog by default; here to std::cout,
// in order with this program's own lines
config.verbosity = otswap::Verbosity::Detailed;
config.log = &std::cout;
// ------------------------------------------------
// ------------ Run the reconstruction ------------
// ------------------------------------------------
// The catalogues fill a known volume, the cube [269, 669] Mpc/h, so it
// is given as the box limits, closed on every face. Tracers outside
// them would keep their row, flagged in Result::outsideBox with NaN
// displacements, and randoms outside them would be dropped; here none
// is. Without limits the box is the bounding box of the tracers and the
// randoms, as in the full_recons_box example.
//
// In box geometry the mean particle separation (mps) is a single
// number. Without one, as here, otswap takes (V/N)^(1/3), with V the
// volume of the limits and N the number of tracers inside them, and
// records it in Result::mps; an overload takes it from the caller. It
// sets the radius of the first guess, 8 mps, within which each tracer
// is paired with a free random, and the cell of the neighbour grids, so
// the density must be roughly uniform across the box
otswap::BoxLimits box;
box.lower = {269., 269., 269.};
box.upper = {669., 669., 669.};
otswap::Result result = otswap::reconstructBox(tracers, randoms, config, box);
// ----------------------------------------------
// ------------ Summarize the result ------------
// ----------------------------------------------
// Every realization is valid for every tracer inside the limits, and
// meanDisplacement is the average over all of them. Its average over
// the tracers is the offset between the centres of mass of the
// randoms used and of the tracers
std::size_t allValid = 0;
for (std::size_t i = 0; i < nTracers; ++i)
allValid += result.validRealizations[i] == result.nRealizations ? 1 : 0;
std::cout << "Realizations: " << result.nRealizations << ", all valid for " << allValid << " tracers" << std::endl;
double length = 0., average[3] = {0., 0., 0.};
for (std::size_t i = 0; i < nTracers; ++i) {
const double* d = &result.meanDisplacement[3*i];
length += std::sqrt(d[0]*d[0] + d[1]*d[1] + d[2]*d[2]);
for (int c = 0; c < 3; ++c) average[c] += d[c];
}
std::cout << "Mean length of the mean displacement: " << length / (double)nTracers << " Mpc/h" << std::endl;
std::cout << "Average of the mean displacement over the tracers: (" << average[0] / (double)nTracers << ", "
<< average[1] / (double)nTracers << ", " << average[2] / (double)nTracers << ") Mpc/h" << std::endl;
std::cout << "Displacement of the first tracer in the first realization: (" << result.displacement[0] << ", "
<< result.displacement[1] << ", " << result.displacement[2] << ") Mpc/h" << std::endl;
// ------------------------------------------
// ------------ Write the output ------------
// ------------------------------------------
// One row per tracer, in the order of the input: its position, its
// mean Lagrangian position (the position plus the mean displacement),
// the mean displacement, the number of valid realizations and the flag
// outsideBox, with a header describing the columns (lengths in
// coordinate units), the box and the parameters of the run. The format
// follows the extension, ASCII here; io::readDisplacementMean reads
// this file back (see the lightcone example)
otswap::io::writeDisplacementMean(output + "/displacement_box.dat", result);
std::cout << "Written: output/displacement_box.dat" << std::endl;
// --------------------------------------------------------------
// ------------ Keep every realization, with the IDs ------------
// --------------------------------------------------------------
// A catalogue usually names its objects by an ID column, read exactly
// by the overload of io::read that takes integer columns, and set as
// Result::ids. These files have none, so here the position of each halo
// among the data rows of its file, counted from 1, stands for it. The
// reconstruction sets no IDs and no computation reads them: the writers
// put them in a first column, id, and realSpaceBox and
// realSpaceLightcone copy them into the corrected catalogue. An empty ids, or exactly 0..N-1, means none
result.ids.resize(nTracers);
for (std::size_t i = 0; i < nTracers; ++i) result.ids[i] = (std::int64_t)i + 1;
// writeDisplacementComplete writes every realization of every tracer,
// with its valid flag, the whole configuration and the box, exactly:
// with 17 significant digits in ASCII, in binary in FITS, as here,
// which is smaller and faster to read. readDisplacementComplete
// rebuilds the Result, every double identical, the means recomputed
// from the realizations
otswap::io::writeDisplacementComplete(output + "/displacement_complete_box.fits", result);
std::cout << "Written: output/displacement_complete_box.fits" << std::endl;
const otswap::Result readBack = otswap::io::readDisplacementComplete(output + "/displacement_complete_box.fits");
const bool identical = readBack.displacement == result.displacement && readBack.valid == result.valid &&
readBack.meanDisplacement == result.meanDisplacement && readBack.ids == result.ids;
std::cout << "Read back: " << readBack.nRealizations << " realizations of " << readBack.nObjects
<< " tracers, IDs " << readBack.ids.front() << " to " << readBack.ids.back() << ", "
<< (identical ? "identical" : "NOT identical") << " to the result written" << std::endl;
// ----------------------------------------------------------
// ------------ Check the number of realizations ------------
// ----------------------------------------------------------
// recomputeMeans recomputes validRealizations, meanDisplacement and the
// Lagrangian positions from displacement and valid, for instance after
// a filter of one's own has cleared some entries of valid. Here it
// keeps the first half of the realizations. The rms difference between
// the mean over half of them and the mean over all of them shows how
// much the mean still depends on their number: the larger it is
// against the mean length printed above, the more realizations are
// worth adding
otswap::Result half = readBack;
const std::size_t nHalf = half.nRealizations / 2;
for (std::size_t rec = nHalf; rec < half.nRealizations; ++rec)
for (std::size_t i = 0; i < nTracers; ++i) half.valid[rec * nTracers + i] = 0;
otswap::recomputeMeans(half);
double squares = 0.;
for (std::size_t k = 0; k < 3 * nTracers; ++k) {
const double difference = half.meanDisplacement[k] - readBack.meanDisplacement[k];
squares += difference * difference;
}
std::cout << "rms difference between the mean displacements of " << nHalf << " and " << readBack.nRealizations
<< " realizations: " << std::sqrt(squares / (double)nTracers) << " Mpc/h" << std::endl;
}
catch (const otswap::Error& e) { std::cerr << e.what() << std::endl; return 1; }
return 0;
}
Periodic box¶
Reconstructs the displacement field of halos in redshift space in a cube of a simulation, with periodic boundary conditions: the box is given by its limits, every distance is the minimum image, and nothing is cut at the faces. No randoms are given: otswap draws them in the box. The result reports the cell side of the neighbour grids actually used, which in a periodic box divides the shortest side. The halos are then corrected to real space, with neighbours across the faces and the corrected coordinate wrapped into the box, and compared with their real-space positions, which the data also give, along the line of sight and by the minimum image.
Reads:
Writes output/displacement_periodic_box.dat, with otswap.io.write_displacement_mean(), and
output/reconstructed_catalogue_periodic_box.dat, with otswap.io.write_real_space_catalog(); their
columns and keywords, those of the periodic box included, are on the file formats page.
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2026 by Simone Sartori, simone.sartori@inaf.it
# ======================================================================
# Example code: how to run the OT reconstruction and the redshift-space
# correction in a periodic box
# ======================================================================
"""This example explains how to reconstruct the displacement field of halos
in redshift space in a cube with periodic boundary conditions, such as a
simulation box, and how to move them back to real space with it. The box is
given by its limits; every distance is then the minimum image, so no face is
a boundary: a tracer near a face may be matched to a random near the
opposite one, as anywhere else in the box, and the correction averages the
displacements of neighbours across the faces.
Each side of a periodic box must be an integer multiple of the shortest one,
so a cube, or a cuboid such as 500 x 500 x 1000, is accepted. Tracers
outside the limits are wrapped into the box, by a whole number of periods
per axis, and reported; the displacements point along the shortest way,
within half a period on each axis.
The halos are at redshift 0, with the line of sight along the z axis. The
example data give each halo in real space too, so the corrected positions
can be compared with the true ones, as survey data do not allow.
Usage: python periodic_box.py [data_dir]. The catalogue is read from
data_dir, by default the examples' data folder; the output is written to the
folder output/ next to this file, created if missing.
"""
import sys
from pathlib import Path
import numpy as np
import otswap
def main():
# -------------------------------------------------------------
# ------------ Locate the input and output folders ------------
# -------------------------------------------------------------
# The data folder is the examples' one, next to this example's folder,
# unless a first command-line argument replaces it
here = Path(__file__).resolve().parent
data = Path(sys.argv[1]) if len(sys.argv) > 1 else here.parent / "data"
output = here / "output"
output.mkdir(parents=True, exist_ok=True)
# ---------------------------------------------------
# ------------ Read the tracer catalogue ------------
# ---------------------------------------------------
# Halos of a simulation at redshift 0 in a cube of side 1000 Mpc/h,
# [0, 1000] on each axis, comoving coordinates in Mpc/h. The file holds
# x, y and z in real space, then z in redshift space, with the line of
# sight along the z axis: the positions observed are x, y and the fourth
# column, those in real space the first three. Table.values has shape
# (N, 3)
tracers = otswap.io.read(data / "periodic_halos.dat", [0, 1, 3]).values
real = otswap.io.read(data / "periodic_halos.dat", [0, 1, 2]).values
side = 1000.0
print(f"Tracers: {len(tracers)}")
# ------------------------------------------------------------------
# ------------ Set the parameters of the reconstruction ------------
# ------------------------------------------------------------------
# n_realizations: independent realizations, each on its own set of
# randoms. With no randoms given, as here, otswap draws them itself,
# uniformly in the box, a different set for each realization; 8
# realizations keep the example fast.
#
# convergence: the sweeps stop once the fraction of successful swaps in
# a sweep no longer exceeds this threshold; 1e-2 keeps the example fast.
# For an analysis, start from the defaults, 30 realizations and 1e-3:
# the guide's section "Choosing the parameters" advises on both.
#
# seed: a fixed seed makes the run reproducible, whatever the number of
# threads.
#
# cell_size: the grid cell, in units of mps, affects the speed only,
# never the result; the default is 3. In a periodic box the cells divide
# the shortest side a whole number of times, so the cell used can be
# smaller: result.cell_side
config = otswap.Config(n_realizations=8, convergence=1e-2, seed=12345, cell_size=3.0,
verbosity="normal")
# ------------------------------------------------
# ------------ Run the reconstruction ------------
# ------------------------------------------------
# The box is periodic: the limits, the keyword box, are required, and
# the mean particle separation, (V/N)^(1/3) with V the volume of the
# limits, comes from them. The limits are closed: a tracer on an upper
# face stays there, and one outside the limits would be wrapped into the
# box and counted in result.selection; here none is. With the randoms
# omitted, otswap draws them
result = otswap.reconstruct_box(tracers, box=((0.0, 0.0, 0.0), (side, side, side)),
periodic=True, config=config)
# ----------------------------------------------
# ------------ Summarize the result ------------
# ----------------------------------------------
print(f"Periodic: {'yes' if result.periodic else 'no'}, tracers wrapped: {result.selection.tracers_wrapped}")
print(f"Mean particle separation: {result.mps:g} Mpc/h, grid cell side: {result.cell_side:g} Mpc/h")
# Each displacement component lies within half a period, [-500, 500)
# Mpc/h here, however far apart the tracer and its random lie in the
# plain coordinates
mean = result.mean_displacement
print(f"Mean length of the mean displacement: {np.linalg.norm(mean, axis=1).mean():g} Mpc/h")
print(f"Largest component of a mean displacement: {np.abs(mean).max():g} Mpc/h")
# ------------------------------------------
# ------------ Write the output ------------
# ------------------------------------------
# One row per tracer, in the order of the input: its position and its
# mean Lagrangian position, both wrapped into the box, the mean
# displacement, the number of valid realizations and the flag
# outsideBox, always 0 in a periodic box, with a header describing the
# columns (lengths in coordinate units), the box, the periodicity and
# the parameters of the run. The writer is the C++ library's, so the
# file is the C++ example's, byte for byte
otswap.io.write_displacement_mean(output / "displacement_periodic_box.dat", result)
print("Written: output/displacement_periodic_box.dat")
# ----------------------------------------------------
# ------------ Set the cosmological model ------------
# ----------------------------------------------------
# Only the linear growth rate f at the box's redshift is needed. The
# table computes it from Omega_m, h, w0 and wa of a flat cosmology; here
# Omega_m comes from the physical densities of baryons and cold dark
# matter, omega_b = 0.02244 and omega_c = 0.1206, and h = 0.67
h = 0.67
omega_m = (0.02244 + 0.1206) / (h * h)
distances = otswap.DistanceTable.flat(omega_m, h, w0=-1.0, wa=0.0)
# ----------------------------------------------------------------
# ------------ Correct the redshift-space distortions ------------
# ----------------------------------------------------------------
# The box's redshift, the tracers' linear bias, and the line of sight:
# axis 0, 1 or 2 for x, y or z
redshift, bias, axis = 0.0, 1.14, 2
# sigma, the width of the Gaussian average in Mpc/h: 10 Mpc/h is a
# starting value, and the value must be calibrated on the sample (the
# guide's section "Choosing the parameters"). The comparison below shows
# how close the corrected positions come to real space.
#
# The result is periodic, so the correction is too: the neighbours of a
# tracer near a face include those beyond it, and each corrected
# coordinate is wrapped into the box. catalogue.status records what was
# done with each tracer
correction = otswap.CorrectionConfig(weight_by_realizations=False)
catalogue = otswap.real_space_box(result, axis=axis, redshift=redshift, distances=distances,
bias=bias, sigma=10.0, correction=correction)
# The single factor f/(b + 3f/5) of the box
print(f"RSD factor f/(b + 3f/5): {catalogue.factor[0]:g}")
# One row per tracer, in the order of the input: the corrected position,
# NaN for an uncorrected tracer, then the number of valid realizations,
# the two diagnostics of the average and the status of the tracer. The
# writer is the C++ library's, so the file is the C++ example's, byte
# for byte
otswap.io.write_real_space_catalog(output / "reconstructed_catalogue_periodic_box.dat", catalogue)
print("Written: output/reconstructed_catalogue_periodic_box.dat")
# -----------------------------------------------------------
# ------------ Compare with the real-space halos ------------
# -----------------------------------------------------------
# Along the line of sight, the offset of each halo from its real-space
# position, before and after the correction. In a periodic box a halo
# moved across a face reappears at the opposite one, so the offset is
# the minimum image: d - L floor(d/L + 1/2), within half a period
def minimum_image(d):
return d - side * np.floor(d / side + 0.5)
moved = catalogue.cartesian[:, axis]
kept = ~np.isnan(moved)
before = minimum_image(tracers[kept, axis] - real[kept, axis])
after = minimum_image(moved[kept] - real[kept, axis])
print(f"rms offset from the real-space position along the line of sight, over {np.count_nonzero(kept)} "
f"halos: {np.sqrt(np.mean(before ** 2)):g} Mpc/h before the correction, "
f"{np.sqrt(np.mean(after ** 2)):g} Mpc/h after")
if __name__ == "__main__":
main()
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 by Simone Sartori, simone.sartori@inaf.it
// ======================================================================
// Example code: how to run the OT reconstruction and the redshift-space
// correction in a periodic box
// ======================================================================
/*
This example explains how to reconstruct the displacement field of
halos in redshift space in a cube with periodic boundary conditions,
such as a simulation box, and how to move them back to real space with
it. The box is given by its limits; every distance is then the minimum
image, so no face is a boundary: a tracer near a face may be matched to
a random near the opposite one, as anywhere else in the box, and the
correction averages the displacements of neighbours across the faces.
Each side of a periodic box must be an integer multiple of the
shortest one, so a cube, or a cuboid such as 500 x 500 x 1000, is
accepted. Tracers outside the limits are wrapped into the box, by a
whole number of periods per axis, and reported; the displacements
point along the shortest way, within half a period on each axis.
The halos are at redshift 0, with the line of sight along the z axis.
The example data give each halo in real space too, so the corrected
positions can be compared with the true ones, as survey data do not
allow.
Usage: periodic_box [data_dir]. The catalogue is read from data_dir, by
default the examples' data folder; the output is written to the folder
output/ next to this file, created if missing.
*/
#include <cmath>
#include <filesystem>
#include <iostream>
#include <string>
#include <vector>
#include "otswap/OT.h"
// ==========================================================================
int main (int argc, char** argv)
{
try {
// -------------------------------------------------------------
// ------------ Locate the input and output folders ------------
// -------------------------------------------------------------
// OTSWAP_EXAMPLES_DATA and OTSWAP_EXAMPLE_OUTPUT are set by this
// example's CMakeLists.txt to the data folder and to output/ next to
// this file. A first command-line argument replaces the data folder
const std::string data = (argc > 1) ? argv[1] : OTSWAP_EXAMPLES_DATA;
const std::string output = OTSWAP_EXAMPLE_OUTPUT;
std::filesystem::create_directories(output);
// ---------------------------------------------------
// ------------ Read the tracer catalogue ------------
// ---------------------------------------------------
// Halos of a simulation at redshift 0 in a cube of side 1000 Mpc/h,
// [0, 1000] on each axis, comoving coordinates in Mpc/h. The file holds
// x, y and z in real space, then z in redshift space, with the line of
// sight along the z axis: the positions observed are x, y and the
// fourth column, those in real space the first three
const std::vector<double> tracers = otswap::io::read(data + "/periodic_halos.dat", {"0", "1", "3"}).values;
const std::vector<double> real = otswap::io::read(data + "/periodic_halos.dat", {"0", "1", "2"}).values;
const std::size_t nTracers = tracers.size() / 3;
const double side = 1000.;
std::cout << "Tracers: " << nTracers << std::endl;
// ------------------------------------------------------------------
// ------------ Set the parameters of the reconstruction ------------
// ------------------------------------------------------------------
otswap::Config config;
// Independent realizations, each on its own set of randoms. With no
// randoms given, as here, otswap draws them itself, uniformly in the
// box, a different set for each realization; 8 realizations keep the
// example fast
config.nRealizations = 8;
// The sweeps stop once the fraction of successful swaps in a sweep no
// longer exceeds this threshold; 1e-2 keeps the example fast. For an
// analysis, start from the defaults, 30 realizations and 1e-3: the
// guide's section "Choosing the parameters" advises on both
config.convergence = 1.e-2;
// A fixed seed makes the run reproducible, whatever the number of threads
config.seed = 12345;
// The grid cell, in units of mps, affects the speed only, never the
// result; the default is 3. In a periodic box the cells divide the
// shortest side a whole number of times, so the cell used can be
// smaller: Result::cellSide
config.cellSize = 3.;
config.verbosity = otswap::Verbosity::Normal;
config.log = &std::cout;
// ------------------------------------------------
// ------------ Run the reconstruction ------------
// ------------------------------------------------
// The box is periodic: the limits are required, and the mean particle
// separation, (V/N)^(1/3) with V the volume of the limits, comes from
// them. The limits are closed: a tracer on an upper face stays there,
// and one outside the limits would be wrapped into the box and counted
// in Result::selection; here none is. The empty array {} in place of
// the randoms lets otswap draw them
otswap::BoxLimits box;
box.lower = {0., 0., 0.};
box.upper = {side, side, side};
const bool periodic = true;
const otswap::Result result = otswap::reconstructBox(tracers, {}, config, box, periodic);
// ----------------------------------------------
// ------------ Summarize the result ------------
// ----------------------------------------------
std::cout << "Periodic: " << (result.periodic ? "yes" : "no") << ", tracers wrapped: "
<< result.selection.tracersWrapped << std::endl;
std::cout << "Mean particle separation: " << result.mps << " Mpc/h, grid cell side: " << result.cellSide
<< " Mpc/h" << std::endl;
// Each displacement component lies within half a period, [-500, 500)
// Mpc/h here, however far apart the tracer and its random lie in the
// plain coordinates
double length = 0., largest = 0.;
for (std::size_t i = 0; i < nTracers; ++i) {
const double* d = &result.meanDisplacement[3*i];
length += std::sqrt(d[0]*d[0] + d[1]*d[1] + d[2]*d[2]);
for (int c = 0; c < 3; ++c) largest = std::fmax(largest, std::fabs(d[c]));
}
std::cout << "Mean length of the mean displacement: " << length / (double)nTracers << " Mpc/h" << std::endl;
std::cout << "Largest component of a mean displacement: " << largest << " Mpc/h" << std::endl;
// ------------------------------------------
// ------------ Write the output ------------
// ------------------------------------------
// One row per tracer, in the order of the input: its position and its
// mean Lagrangian position, both wrapped into the box, the mean
// displacement, the number of valid realizations and the flag
// outsideBox, always 0 in a periodic box, with a header describing the
// columns (lengths in coordinate units), the box, the periodicity and
// the parameters of the run
otswap::io::writeDisplacementMean(output + "/displacement_periodic_box.dat", result);
std::cout << "Written: output/displacement_periodic_box.dat" << std::endl;
// ----------------------------------------------------
// ------------ Set the cosmological model ------------
// ----------------------------------------------------
// Only the linear growth rate f at the box's redshift is needed. The
// table computes it from Omega_m, h, w0 and wa of a flat cosmology;
// here Omega_m comes from the physical densities of baryons and cold
// dark matter, omega_b = 0.02244 and omega_c = 0.1206, and h = 0.67
const double h = 0.67;
const double omegaM = (0.02244 + 0.1206) / (h * h);
const otswap::DistanceTable distances(omegaM, h, -1., 0.);
// ----------------------------------------------------------------
// ------------ Correct the redshift-space distortions ------------
// ----------------------------------------------------------------
// The box's redshift, the tracers' linear bias, and the line of sight:
// axis 0, 1 or 2 for x, y or z
const double redshift = 0.;
const double bias = 1.14;
const unsigned axis = 2;
// sigma, the width of the Gaussian average in Mpc/h: 10 Mpc/h is a
// starting value, and the value must be calibrated on the sample (the
// guide's section "Choosing the parameters"). The comparison below
// shows how close the corrected positions come to real space.
//
// The result is periodic, so the correction is too: the neighbours of
// a tracer near a face include those beyond it, and each corrected
// coordinate is wrapped into the box. RealSpaceCatalog::status records
// what was done with each tracer
const double sigma = 10.;
otswap::CorrectionConfig correction;
correction.weightByRealizations = false;
correction.log = &std::cout;
const otswap::RealSpaceCatalog catalogue = otswap::realSpaceBox(result, axis, redshift, distances, bias,
sigma, correction);
// The single factor f/(b + 3f/5) of the box
std::cout << "RSD factor f/(b + 3f/5): " << catalogue.factor[0] << std::endl;
// One row per tracer, in the order of the input: the corrected
// position, NaN for an uncorrected tracer, then the number of valid
// realizations, the two diagnostics of the average and the status of
// the tracer
otswap::io::writeRealSpaceCatalog(output + "/reconstructed_catalogue_periodic_box.dat", catalogue);
std::cout << "Written: output/reconstructed_catalogue_periodic_box.dat" << std::endl;
// -----------------------------------------------------------
// ------------ Compare with the real-space halos ------------
// -----------------------------------------------------------
// Along the line of sight, the offset of each halo from its real-space
// position, before and after the correction. In a periodic box a halo
// moved across a face reappears at the opposite one, so the offset is
// the minimum image: d - L floor(d/L + 1/2), within half a period
auto minimumImage = [side] (double d) { return d - side * std::floor(d / side + 0.5); };
double before = 0., after = 0.;
std::size_t compared = 0;
for (std::size_t i = 0; i < nTracers; ++i) {
const double moved = catalogue.cartesian[3*i+axis];
if (std::isnan(moved)) continue;
++compared;
const double inRedshiftSpace = minimumImage(tracers[3*i+axis] - real[3*i+axis]);
const double inRealSpace = minimumImage(moved - real[3*i+axis]);
before += inRedshiftSpace * inRedshiftSpace;
after += inRealSpace * inRealSpace;
}
std::cout << "rms offset from the real-space position along the line of sight, over " << compared
<< " halos: " << std::sqrt(before / (double)compared) << " Mpc/h before the correction, "
<< std::sqrt(after / (double)compared) << " Mpc/h after" << std::endl;
}
catch (const otswap::Error& e) { std::cerr << e.what() << std::endl; return 1; }
return 0;
}
Lightcone¶
Reconstructs the displacement field of a survey-like catalogue with lightcone geometry: sky coordinates, the mean particle separation measured as a function of redshift, a redshift cut that keeps a slice of the catalogue, and the survey’s HEALPix mask, with the displacements that cross unobserved pixels rejected. Before the reconstruction it measures the mean particle separation alone, from the mask and from the sky area; after it, it reads the file written back. It keeps the redshifts 0.90 to 1.08, in 30 bins, with the distance table of a flat ΛCDM cosmology with Ω_m = 0.286 and h = 0.7.
Reads:
Writes output/mps_lightcone.dat, with otswap.io.write_mps_profile();
output/displacement_lightcone.dat, with otswap.io.write_displacement_mean(), and its
twin files displacement_lightcone.mps.dat and displacement_lightcone.distances.dat, the mps(z)
profile and the distance table; their columns and keywords are on the file formats page.
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2026 by Simone Sartori, simone.sartori@inaf.it
# =======================================================================
# Example code: how to run the OT reconstruction with lightcone geometry
# =======================================================================
"""This example explains how to reconstruct the displacement field of a
survey catalogue with lightcone geometry. The lightcone geometry takes
observed coordinates (right ascension, declination, redshift), a mean
particle separation that changes with redshift, which otswap measures from
the tracers, and the survey's footprint, here a HEALPix mask.
The reconstruction matches the tracers to randoms by optimal transport: in
each realization every tracer is paired with one random, and its
displacement points from the tracer (the Eulerian, observed position) to
that random (the Lagrangian position). Independent realizations are then
averaged.
The example first measures the mean particle separation alone, the quick
way to choose its redshift bins, and at the end reads the file it wrote
back.
The randoms carry the survey's geometry and selection function, which
otswap does not model: use the survey's own random catalogue.
Usage: python lightcone.py [data_dir]. The catalogues are read from
data_dir, by default the examples' data folder; the output is written to the
folder output/ next to this file, created if missing.
"""
import sys
from pathlib import Path
import numpy as np
import otswap
def main():
# -------------------------------------------------------------
# ------------ Locate the input and output folders ------------
# -------------------------------------------------------------
# The data folder is the examples' one, next to this example's folder,
# unless a first command-line argument replaces it
here = Path(__file__).resolve().parent
data = Path(sys.argv[1]) if len(sys.argv) > 1 else here.parent / "data"
output = here / "output"
output.mkdir(parents=True, exist_ok=True)
# ---------------------------------------------------------------
# ------------ Read the tracer and random catalogues ------------
# ---------------------------------------------------------------
# otswap.io.read reads the listed columns of a table: for ASCII files
# 0-based indices, or the names of the "###" line of a file otswap
# wrote; for FITS files the column names. Table.values has shape (N, 3):
# right ascension and declination in degrees, and redshift. They are
# passed as they are, with angle_unit="deg"
tracers_sky = otswap.io.read(data / "lightcone_tracers.dat", [0, 1, 2]).values
randoms_sky = otswap.io.read(data / "lightcone_randoms.dat", [0, 1, 2]).values
print(f"Tracers read: {len(tracers_sky)}")
print(f"Randoms read: {len(randoms_sky)}, {len(randoms_sky) / len(tracers_sky):g} per tracer")
# ---------------------------------------
# ------------ Read the mask ------------
# ---------------------------------------
# A HEALPix map in RING or NESTED ordering, read from a FITS file: a
# pixel is observed when its value is greater than 0. A map already in
# memory can be passed to otswap.Mask.from_array instead. When a mask is
# available, give it to the reconstruction rather than a sky area:
# otswap then takes the area from it, and leaves out the objects on
# unobserved pixels
mask = otswap.Mask(str(data / "lightcone_mask.fits"))
print(f"Mask: NSIDE {mask.nside}, {mask.sky_area_deg2:g} deg^2")
# ----------------------------------------------------
# ------------ Set the cosmological model ------------
# ----------------------------------------------------
# The comoving distances, from Omega_m, h, w0 and wa of a flat
# cosmology, tabulated by default from z = 0 to 10. The table must cover
# the redshifts of tracers and randoms
distances = otswap.DistanceTable.flat(0.286, 0.7, w0=-1.0, wa=0.0)
# ------------------------------------------------------------------
# ------------ Set the parameters of the reconstruction ------------
# ------------------------------------------------------------------
# The first seven are the fields of an otswap.Config, the struct
# otswap::Config of C++, passed to the call as config; a field left out
# keeps its default. n_bins and redshift_cut are arguments of the call.
#
# n_realizations: independent realizations. Each one consumes as many
# randoms as there are tracers, disjoint from those of the others, so
# the randoms kept must number at least n_realizations times the
# tracers kept. The redshift cut below keeps 202,184 of the 242,548
# randoms and 24,708 of the 29,579 tracers (the mask keeps them all):
# enough for 8 realizations.
#
# convergence: the sweeps stop once the fraction of successful swaps in a
# sweep, swaps per tracer visited, no longer exceeds this threshold.
# Larger values are faster and less accurate; 1e-2 keeps the example
# fast. For an analysis, start from the defaults, 30 realizations and
# 1e-3: the guide's section "Choosing the parameters" advises on both.
#
# seed: a fixed seed makes the run reproducible; 0 draws a new seed at
# each run, and result.config.seed records the one drawn. The number
# of threads follows OMP_NUM_THREADS, and with a fixed seed the result
# is the same whatever the number of threads.
#
# cell_size: the grid cell, in units of the mean particle separation,
# affects the speed only, never the result; the default is 3.
#
# reject_crossings, max_unobserved_pixels_crossed: after the
# reconstruction, a displacement whose path on the sky (the great-circle
# arc from the tracer to its random) crosses more than this many
# unobserved pixels of the mask in a row is marked invalid. The count is
# of pixels, so the same threshold means a different angle at a
# different NSIDE. These are the defaults.
#
# verbosity: what the reconstruction prints. With "normal", the
# default, how many tracers and randoms the redshift cut and the mask
# left out, how many displacements the crossing filter rejected, and
# then the time of the call and the tracers left without a valid
# displacement. "detailed" adds the mps(z) profile, "silent" prints
# nothing; the counts stay in result.selection either way.
#
# n_bins: the mean particle separation is measured in n_bins redshift
# bins of equal width, over the redshifts of the tracers kept. Each bin
# needs at least 278 tracers: if one is refused, the message gives an
# upper bound on the number of bins the catalogue supports.
#
# redshift_cut: tracers and randoms outside this closed redshift range
# are left out of the reconstruction; the catalogue spans 0.885 to 1.10,
# and this range reconstructs a slice of it. The default, None, cuts
# nothing; a (min, max) pair is accepted too
config = otswap.Config(n_realizations=8, convergence=1e-2, seed=12345, cell_size=3.0,
reject_crossings=True, max_unobserved_pixels_crossed=0, verbosity="normal")
n_bins = 30
redshift_cut = otswap.RedshiftCut(0.90, 1.08)
# --------------------------------------------------------------
# ------------ Measure the mean particle separation ------------
# --------------------------------------------------------------
# measure_mps_profile measures mps(z) from the tracers alone, as the
# reconstruction does, from the same mask, bins, table and cut, and in a
# fraction of its time: the profile is Result.mps_profile of the
# reconstruction below, bit for bit. Use it to choose n_bins before a
# reconstruction. It reports the tracers the cut and the mask left out
profile = otswap.measure_mps_profile(tracers_sky, mask=mask, n_bins=n_bins, distances=distances,
redshift_cut=redshift_cut, angle_unit="deg")
print(f"mps(z): {len(profile.mps)} bins from z = {profile.redshift_min:g} to {profile.redshift_max:g}, "
f"mps from {profile.mps.min():g} to {profile.mps.max():g} Mpc/h")
# Without a mask, the keyword sky_area_deg2 gives the sky area, in square
# degrees: no object is then left out on the sky and no crossing is
# filtered, so the catalogues must lie within the footprint already.
# These do, so with the mask's area the profile is the same
from_area = otswap.measure_mps_profile(tracers_sky, sky_area_deg2=mask.sky_area_deg2, n_bins=n_bins,
distances=distances, redshift_cut=redshift_cut, angle_unit="deg",
verbosity="silent")
print(f"The same profile from the sky area: {'yes' if np.array_equal(from_area.mps, profile.mps) else 'no'}")
# One row per bin: its centre, its mps and its number of tracers, with
# the range and the representative mps as keywords
otswap.io.write_mps_profile(output / "mps_lightcone.dat", profile)
print("Written: output/mps_lightcone.dat")
# ------------------------------------------------
# ------------ Run the reconstruction ------------
# ------------------------------------------------
# Tracers left out by the cut or the mask keep their row in the result,
# flagged in outside_redshift_cut or outside_mask, with NaN
# displacements. The result also holds the tracers' Cartesian positions
# (tracers), their mean Lagrangian positions (lagrangian, and
# lagrangian_sky on the sky, in the angle unit of the call) and the
# measured mps(z) (mps_profile)
result = otswap.reconstruct_lightcone(tracers_sky, randoms_sky, mask=mask, n_bins=n_bins,
distances=distances, angle_unit="deg",
redshift_cut=redshift_cut, config=config)
# ----------------------------------------------
# ------------ Summarize the result ------------
# ----------------------------------------------
# valid holds, for each realization and tracer, whether the displacement
# survived the crossing filter; valid_realizations counts them per
# tracer, and mean_displacement averages the valid ones, NaN where there
# are none
n = len(tracers_sky)
for rec in range(result.n_realizations):
print(f"Realization {rec}: {np.count_nonzero(result.valid[rec])} valid displacements of {n}")
counts = np.bincount(result.valid_realizations, minlength=result.n_realizations + 1)
print("Tracers by number of valid realizations: " + ", ".join(f"{k}: {c}" for k, c in enumerate(counts)))
left_out = np.count_nonzero(result.outside_redshift_cut | result.outside_mask)
print(f"Tracers left out (redshift cut or mask): {left_out}")
mean = result.mean_displacement
no_mean = np.isnan(mean[:, 0])
print(f"Tracers with a NaN mean displacement: {np.count_nonzero(no_mean)}")
print(f"Mean length of the mean displacement: {np.linalg.norm(mean[~no_mean], axis=1).mean():g} Mpc/h")
# ------------------------------------------
# ------------ Write the output ------------
# ------------------------------------------
# One row per tracer, in the order of the input: its sky coordinates
# and those of its mean Lagrangian position, in degrees, its Cartesian
# position, its mean Lagrangian position and its mean displacement, in
# Mpc/h, its number of valid realizations and the two selection flags,
# with a header describing the columns (angles in degrees, lengths in
# coordinate units) and the parameters of the run, and, in two twin
# files, the mps(z) profile and the distance table, so that
# otswap.io.read_displacement_mean reads the file back whole. A tracer
# left out, or without a valid realization, has NaN Lagrangian
# coordinates and displacement. The writer is the C++ library's, so the
# files are the C++ example's, byte for byte.
# otswap.io.write_displacement_complete writes every realization instead,
# losslessly (see the box example)
otswap.io.write_displacement_mean(output / "displacement_lightcone.dat", result)
print("Written: output/displacement_lightcone.dat, "
"output/displacement_lightcone.mps.dat and "
"output/displacement_lightcone.distances.dat")
# --------------------------------------------
# ------------ Read the file back ------------
# --------------------------------------------
# read_displacement_mean reads the file and its twins into a Result whose
# only realization is the mean, with n_realizations_mean the number of
# realizations averaged, the profile and the distance table: the values
# as written, with 9 significant digits in ASCII, exactly in FITS. The
# angles of the Result read are in angle_unit, which is required
read_back = otswap.io.read_displacement_mean(output / "displacement_lightcone.dat", angle_unit="deg")
largest = np.nanmax(np.abs(read_back.mean_displacement - result.mean_displacement))
table = read_back.distances
print(f"Read back: the mean of {read_back.n_realizations_mean} realizations, a profile of "
f"{len(read_back.mps_profile.mps)} bins, a distance table from z = {table.min_redshift:g} to "
f"{table.max_redshift:g}; largest difference from the mean written: {largest:g} Mpc/h")
if __name__ == "__main__":
main()
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 by Simone Sartori, simone.sartori@inaf.it
// =======================================================================
// Example code: how to run the OT reconstruction with lightcone geometry
// =======================================================================
/*
This example explains how to reconstruct the displacement field of a
survey catalogue with lightcone geometry. The lightcone geometry takes
observed coordinates (right ascension, declination, redshift), a mean
particle separation that changes with redshift, which otswap measures
from the tracers, and the survey's footprint, here a HEALPix mask.
The reconstruction matches the tracers to randoms by optimal
transport: in each realization every tracer is paired with one
random, and its displacement points from the tracer (the Eulerian,
observed position) to that random (the Lagrangian position).
Independent realizations are then averaged.
The example first measures the mean particle separation alone, the
quick way to choose its redshift bins, and at the end reads the file
it wrote back.
The randoms carry the survey's geometry and selection function, which
otswap does not model: use the survey's own random catalogue.
Usage: lightcone [data_dir]. The catalogues are read from data_dir, by
default the examples' data folder; the output is written to the
folder output/ next to this file, created if missing.
*/
#include <algorithm>
#include <cmath>
#include <filesystem>
#include <iostream>
#include <string>
#include <vector>
#include "otswap/OT.h"
// ==========================================================================
int main (int argc, char** argv)
{
try {
// -------------------------------------------------------------
// ------------ Locate the input and output folders ------------
// -------------------------------------------------------------
// OTSWAP_EXAMPLES_DATA and OTSWAP_EXAMPLE_OUTPUT are set by this
// example's CMakeLists.txt to the data folder and to output/ next to
// this file. A first command-line argument replaces the data folder
const std::string data = (argc > 1) ? argv[1] : OTSWAP_EXAMPLES_DATA;
const std::string output = OTSWAP_EXAMPLE_OUTPUT;
std::filesystem::create_directories(output);
// ---------------------------------------------------------------
// ------------ Read the tracer and random catalogues ------------
// ---------------------------------------------------------------
// io::read reads the listed columns of a table: for ASCII files
// 0-based indices, or the names of the "###" line of a file otswap
// wrote; for FITS files (.fits, .fit, .fits.gz) the column names.
// Table::values holds the rows one after the other: right ascension,
// declination and redshift for each object, the flat layout every
// otswap function takes. The catalogues give the angles in degrees,
// and otswap takes radians: skyToRadians converts them with the factor
// that otswap's Python interface uses
const std::vector<double> tracersSky =
otswap::skyToRadians(otswap::io::read(data + "/lightcone_tracers.dat", {"0", "1", "2"}).values);
const std::vector<double> randomsSky =
otswap::skyToRadians(otswap::io::read(data + "/lightcone_randoms.dat", {"0", "1", "2"}).values);
const std::size_t nTracers = tracersSky.size() / 3;
const std::size_t nRandoms = randomsSky.size() / 3;
std::cout << "Tracers read: " << nTracers << std::endl;
std::cout << "Randoms read: " << nRandoms << ", " << (double)nRandoms / (double)nTracers << " per tracer" << std::endl;
// ---------------------------------------
// ------------ Read the mask ------------
// ---------------------------------------
// A HEALPix map in RING or NESTED ordering, read from a FITS file: a
// pixel is observed when its value is greater than 0. A map already in
// memory can be passed to the constructor taking an array instead.
// When a mask is available, give it to the reconstruction rather than
// a sky area: otswap then takes the area from it, and leaves out the
// objects on unobserved pixels
const otswap::Mask mask(data + "/lightcone_mask.fits");
std::cout << "Mask: NSIDE " << mask.nside() << ", " << mask.skyAreaDeg2() << " deg^2" << std::endl;
// ----------------------------------------------------
// ------------ Set the cosmological model ------------
// ----------------------------------------------------
// The comoving distances, from Omega_m, h, w0 and wa of a flat
// cosmology, tabulated by default from z = 0 to 10. The table must
// cover the redshifts of tracers and randoms
const otswap::DistanceTable distances(0.286, 0.7, -1., 0.);
// ------------------------------------------------------------------
// ------------ Set the parameters of the reconstruction ------------
// ------------------------------------------------------------------
otswap::Config config;
// Independent realizations. Each one consumes as many randoms as there
// are tracers, disjoint from those of the others, so the randoms kept
// must number at least nRealizations times the tracers kept. The
// redshift cut below keeps 202,184 of the 242,548 randoms and 24,708 of
// the 29,579 tracers (the mask keeps them all): enough for 8
// realizations
config.nRealizations = 8;
// The sweeps stop once the fraction of successful swaps in a sweep,
// swaps per tracer visited, no longer exceeds this threshold. Larger
// values are faster and less accurate; 1e-2 keeps the example fast.
// For an analysis, start from the defaults, 30 realizations and 1e-3:
// the guide's section "Choosing the parameters" advises on both
config.convergence = 1.e-2;
// A fixed seed makes the run reproducible; 0 draws a new seed at each
// run, and Result::config.seed records the one drawn. The number of
// threads follows OMP_NUM_THREADS, and with a fixed seed the result is
// the same whatever the number of threads
config.seed = 12345;
// The grid cell, in units of the mean particle separation, affects the
// speed only, never the result; the default is 3
config.cellSize = 3.;
// After the reconstruction, a displacement whose path on the sky (the
// great-circle arc from the tracer to its random) crosses more than
// maxUnobservedPixelsCrossed unobserved pixels of the mask in a row is
// marked invalid. The count is of pixels, so the same threshold means a
// different angle at a different NSIDE. These are the defaults
config.rejectCrossings = true;
config.maxUnobservedPixelsCrossed = 0;
// What the reconstruction reports: with Normal, the default, how many
// tracers and randoms the redshift cut and the mask left out, how many
// displacements the crossing filter rejected, and then the time of the
// call and the tracers left without a valid displacement. Detailed adds
// the mps(z) profile, Silent prints nothing; the counts stay in
// Result::selection either way. The report goes to std::clog by
// default; here to std::cout, in order with this program's own lines
config.verbosity = otswap::Verbosity::Normal;
config.log = &std::cout;
// The mean particle separation is measured in nBins redshift bins of
// equal width, over the redshifts of the tracers kept. Each bin needs
// at least 278 tracers: if one is refused, the message gives an upper
// bound on the number of bins the catalogue supports
const unsigned nBins = 30;
// Tracers and randoms outside this closed redshift range are left out
// of the reconstruction; the catalogue spans 0.885 to 1.10, and this
// range reconstructs a slice of it. The default, {}, cuts nothing
const otswap::RedshiftCut cut {0.90, 1.08};
// --------------------------------------------------------------
// ------------ Measure the mean particle separation ------------
// --------------------------------------------------------------
// measureMpsProfile measures mps(z) from the tracers alone, as the
// reconstruction does, from the same mask, bins, table and cut, and in
// a fraction of its time: the profile is Result::mpsProfile of the
// reconstruction below, bit for bit. Use it to choose nBins before a
// reconstruction. It reports the tracers the cut and the mask left out
const otswap::MpsProfile profile =
otswap::measureMpsProfile(tracersSky, mask, nBins, distances, cut, otswap::Verbosity::Normal, &std::cout);
std::cout << "mps(z): " << profile.mps.size() << " bins from z = " << profile.redshiftMin << " to "
<< profile.redshiftMax << ", mps from " << *std::min_element(profile.mps.begin(), profile.mps.end())
<< " to " << *std::max_element(profile.mps.begin(), profile.mps.end()) << " Mpc/h" << std::endl;
// Without a mask, the overloads that take the sky area, in square
// degrees, leave out no object on the sky and filter no crossing: the
// catalogues must then lie within the footprint already. These do, so
// with the mask's area the profile is the same
const otswap::MpsProfile fromArea =
otswap::measureMpsProfile(tracersSky, mask.skyAreaDeg2(), nBins, distances, cut, otswap::Verbosity::Silent);
std::cout << "The same profile from the sky area: " << (fromArea.mps == profile.mps ? "yes" : "no") << std::endl;
// One row per bin: its centre, its mps and its number of tracers, with
// the range and the representative mps as keywords
otswap::io::writeMpsProfile(output + "/mps_lightcone.dat", profile);
std::cout << "Written: output/mps_lightcone.dat" << std::endl;
// ------------------------------------------------
// ------------ Run the reconstruction ------------
// ------------------------------------------------
// Tracers left out by the cut or the mask keep their row in the
// result, flagged in outsideRedshiftCut or outsideMask, with NaN
// displacements. The result also holds the tracers' Cartesian
// positions (tracers), their mean Lagrangian positions (lagrangian, and
// lagrangianSky on the sky) and the measured mps(z) (mpsProfile)
const otswap::Result result = otswap::reconstructLightcone(tracersSky, randomsSky, mask, nBins,
distances, config, cut);
// ----------------------------------------------
// ------------ Summarize the result ------------
// ----------------------------------------------
// valid holds, for each realization and tracer, whether the
// displacement survived the crossing filter; validRealizations counts
// them per tracer, and meanDisplacement averages the valid ones, NaN
// where there are none
for (unsigned rec = 0; rec < result.nRealizations; ++rec) {
std::size_t n = 0;
for (std::size_t i = 0; i < nTracers; ++i) n += result.valid[rec * nTracers + i];
std::cout << "Realization " << rec << ": " << n << " valid displacements of " << nTracers << std::endl;
}
std::vector<std::size_t> byCount(result.nRealizations + 1, 0);
std::size_t leftOut = 0, noMean = 0;
double length = 0.;
for (std::size_t i = 0; i < nTracers; ++i) {
++byCount[result.validRealizations[i]];
leftOut += (result.outsideRedshiftCut[i] || result.outsideMask[i]) ? 1 : 0;
const double* d = &result.meanDisplacement[3*i];
if (std::isnan(d[0])) ++noMean;
else length += std::sqrt(d[0]*d[0] + d[1]*d[1] + d[2]*d[2]);
}
std::cout << "Tracers by number of valid realizations:";
for (std::size_t n = 0; n < byCount.size(); ++n)
std::cout << (n ? ", " : " ") << n << ": " << byCount[n];
std::cout << std::endl;
std::cout << "Tracers left out (redshift cut or mask): " << leftOut << std::endl;
std::cout << "Tracers with a NaN mean displacement: " << noMean << std::endl;
std::cout << "Mean length of the mean displacement: " << length / (double)(nTracers - noMean) << " Mpc/h" << std::endl;
// ------------------------------------------
// ------------ Write the output ------------
// ------------------------------------------
// One row per tracer, in the order of the input: its sky coordinates
// and those of its mean Lagrangian position, in degrees, its Cartesian
// position, its mean Lagrangian position and its mean displacement, in
// Mpc/h, its number of valid realizations and the two selection flags,
// with a header describing the columns (angles in degrees, lengths in
// coordinate units) and the parameters of the run, and, in two twin
// files, the mps(z) profile and the distance table, so that
// io::readDisplacementMean reads the file back whole. A tracer left
// out, or without a valid realization, has NaN Lagrangian coordinates
// and displacement. io::writeDisplacementComplete writes every
// realization instead, losslessly (see the box example)
otswap::io::writeDisplacementMean(output + "/displacement_lightcone.dat", result);
std::cout << "Written: output/displacement_lightcone.dat, "
"output/displacement_lightcone.mps.dat and "
"output/displacement_lightcone.distances.dat" << std::endl;
// --------------------------------------------
// ------------ Read the file back ------------
// --------------------------------------------
// readDisplacementMean reads the file and its twins into a Result whose
// only realization is the mean, with nRealizationsMean the number of
// realizations averaged, the profile and the distance table: the values
// as written, with 9 significant digits in ASCII, exactly in FITS
const otswap::Result readBack = otswap::io::readDisplacementMean(output + "/displacement_lightcone.dat");
double largest = 0.;
for (std::size_t k = 0; k < 3 * nTracers; ++k)
if (!std::isnan(result.meanDisplacement[k]))
largest = std::max(largest, std::fabs(readBack.meanDisplacement[k] - result.meanDisplacement[k]));
std::cout << "Read back: the mean of " << readBack.nRealizationsMean << " realizations, a profile of "
<< readBack.mpsProfile.mps.size() << " bins, a distance table from z = "
<< readBack.distances->minRedshift() << " to " << readBack.distances->maxRedshift()
<< "; largest difference from the mean written: " << largest << " Mpc/h" << std::endl;
}
catch (const otswap::Error& e) { std::cerr << e.what() << std::endl; return 1; }
return 0;
}
Lightcone in Cartesian coordinates¶
Reconstructs and corrects the lightcone of the two lightcone examples given
in comoving Cartesian coordinates, the observer at the origin: the mean
particle separation is measured in distance bins, a cut on the comoving
distance keeps a shell of the catalogue, and the mask acts on the angles of
the objects. It first finds the distance and the direction of each tracer
with otswap.point_to_sky(), and measures the mean particle separation
alone, from the mask and from the sky area. It then shows three variants: the
reconstruction with the distance table, which fills the redshifts; the same
without the table, which gives the same displacements with NaN redshifts; and
the correction, which needs the table for the growth rate and the bias at the
tracers’ redshifts. The cut keeps the distances 2200 to 2450 Mpc/h.
Reads:
Writes output/tracers_sky_lightcone_cartesian.dat, the distance, right ascension and declination of
each tracer, with otswap.io.write(); output/mps_lightcone_cartesian.dat, with
otswap.io.write_mps_profile(); output/displacement_lightcone_cartesian.dat, with
otswap.io.write_displacement_mean(), and its
twin files .mps.dat and .distances.dat, the mps(d) profile and the distance table;
output/displacement_lightcone_cartesian_no_table.dat, the result without the table, and its twin
.mps.dat; and output/reconstructed_catalogue_lightcone_cartesian.dat, with otswap.io.write_real_space_catalog(); their columns
and keywords are on the file formats page.
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2026 by Simone Sartori, simone.sartori@inaf.it
# ============================================================================
# Example code: how to run the OT reconstruction on a lightcone in Cartesian
# coordinates, and correct it for redshift-space distortions
# ============================================================================
"""This example explains how to reconstruct a survey catalogue that is given
in comoving Cartesian coordinates, with the observer at the origin, instead
of right ascension, declination and redshift. Its tracers and randoms are
those of the lightcone and full_recons_lightcone examples, converted to
Cartesian coordinates with the same cosmology, and it does what both do: it
measures the mean particle separation alone, to choose the bins, then runs
the reconstruction, here with a cut on the distance, and the correction. It
first finds the distance and the direction of each tracer, with point_to_sky,
which is where the cut and the mask act.
Without redshifts the mean particle separation is measured as a function of
the comoving distance from the origin, in uniform distance bins, and the mask
and the optional distance cut act on the angles and the distance of each
object. The distance table is optional for the reconstruction, and only fills
the redshifts of the result; it is needed here for the correction, which
takes the growth rate f and the bias b(z) at the tracers' redshifts. The
example runs the reconstruction a second time without it, to show that
nothing else changes.
Usage: python lightcone_cartesian.py [data_dir]. The catalogues are read from
data_dir, by default the examples' data folder; the output is written to the
folder output/ next to this file, created if missing.
"""
import sys
from pathlib import Path
import numpy as np
import otswap
def main():
# -------------------------------------------------------------
# ------------ Locate the input and output folders ------------
# -------------------------------------------------------------
# The data folder is the examples' one, next to this example's folder,
# unless a first command-line argument replaces it
here = Path(__file__).resolve().parent
data = Path(sys.argv[1]) if len(sys.argv) > 1 else here.parent / "data"
output = here / "output"
output.mkdir(parents=True, exist_ok=True)
# ---------------------------------------------------------------
# ------------ Read the tracer and random catalogues ------------
# ---------------------------------------------------------------
# x, y, z for each object, in Mpc/h, the observer at the origin
tracers = otswap.io.read(data / "lightcone_tracers_cartesian.dat", [0, 1, 2]).values
randoms = otswap.io.read(data / "lightcone_randoms_cartesian.dat", [0, 1, 2]).values
print(f"Tracers read: {len(tracers)}")
print(f"Randoms read: {len(randoms)}, {len(randoms) / len(tracers):g} per tracer")
# ---------------------------------------
# ------------ Read the mask ------------
# ---------------------------------------
mask = otswap.Mask(str(data / "lightcone_mask.fits"))
print(f"Mask: NSIDE {mask.nside}, {mask.sky_area_deg2:g} deg^2")
# ---------------------------------------------------------------
# ------------ Find the distances and the directions ------------
# ---------------------------------------------------------------
# point_to_sky gives, for each point, its distance from the origin, in
# coordinate units, and its right ascension and declination, here in
# degrees: the direction the mask is applied to, and the distance the
# distance cut and the mps bins are taken on. It needs no distance
# table. The range of the distances is where to choose the cut
tracers_sky = otswap.point_to_sky(tracers, angle_unit="deg")
print(f"Tracer distances: {tracers_sky[:, 0].min():g} to {tracers_sky[:, 0].max():g} Mpc/h")
# One row per tracer, in input order: distance, RA, Dec
otswap.io.write(output / "tracers_sky_lightcone_cartesian.dat",
[otswap.io.Column("distance", tracers_sky[:, 0], description="distance from the origin"),
otswap.io.Column("ra", tracers_sky[:, 1], description="right ascension", unit="deg"),
otswap.io.Column("dec", tracers_sky[:, 2], description="declination", unit="deg")])
print("Written: output/tracers_sky_lightcone_cartesian.dat")
# ----------------------------------------------------
# ------------ Set the cosmological model ------------
# ----------------------------------------------------
# The table gives the linear growth rate f(z) of the correction, and the
# redshifts of the result. Its distances are in Mpc/h, so the
# coordinates must be in Mpc/h too: the unit of the coordinates is that
# of any distance table used with them. It must cover the corrected
# distances too: the default range, z = 0 to 10, leaves room for that
distances = otswap.DistanceTable.flat(0.286, 0.7, w0=-1.0, wa=0.0)
# --------------------------------------------
# ------------ Set the parameters ------------
# --------------------------------------------
# A fixed seed, and the displacements crossing an unobserved pixel of the
# mask rejected. 8 realizations, which the example randoms are enough
# for, and a convergence threshold of 1e-2 keep the example fast; for an
# analysis, start from the defaults, 30 and 1e-3 (the guide's section
# "Choosing the parameters").
#
# The mean particle separation is measured in 30 distance bins of equal
# width, each with enough tracers, over the distances of the tracers
# kept.
#
# distance_cut: tracers and randoms whose comoving distance from the
# origin lies outside this closed range, in coordinate units, are left
# out of the reconstruction: the randoms are dropped, and the tracers
# keep their row, flagged in Result.outside_distance_cut. The catalogue
# spans 2126 to 2500 Mpc/h. The default, None, cuts nothing; a
# (d_min, d_max) pair is accepted too
config = otswap.Config(n_realizations=8, convergence=1e-2, seed=12345, reject_crossings=True,
max_unobserved_pixels_crossed=0, verbosity="normal")
n_bins = 30
distance_cut = otswap.DistanceCut(2200.0, 2450.0)
# --------------------------------------------------------------
# ------------ Measure the mean particle separation ------------
# --------------------------------------------------------------
# measure_mps_profile_cartesian measures mps(d) from the tracers alone,
# as the reconstruction does, from the same mask, bins and cut, and in a
# fraction of its time: the profile is Result.mps_profile of the
# reconstruction below, bit for bit. Use it to choose n_bins before a
# reconstruction. It needs no distance table
profile = otswap.measure_mps_profile_cartesian(tracers, mask=mask, n_bins=n_bins,
distance_cut=distance_cut)
print(f"mps(d): {len(profile.mps)} bins, mps from {profile.mps.min():g} to {profile.mps.max():g} Mpc/h")
# Without a mask, the keyword sky_area_deg2 gives the sky area, in square
# degrees: no object is then left out on the sky and no crossing is
# filtered, so the catalogues must lie within the footprint already.
# These do, so with the mask's area the profile is the same
from_area = otswap.measure_mps_profile_cartesian(tracers, sky_area_deg2=mask.sky_area_deg2, n_bins=n_bins,
distance_cut=distance_cut, verbosity="silent")
print(f"The same profile from the sky area: {'yes' if np.array_equal(from_area.mps, profile.mps) else 'no'}")
# One row per bin: its centre, in distance, its mps and its number of
# tracers, with the range and the representative mps as keywords
otswap.io.write_mps_profile(output / "mps_lightcone_cartesian.dat", profile)
print("Written: output/mps_lightcone_cartesian.dat")
# ------------------------------------------------
# ------------ Run the reconstruction ------------
# ------------------------------------------------
# distances fills the redshifts of the result. angle_unit is required:
# it is the unit of the angles in the result's sky coordinates
result = otswap.reconstruct_lightcone_cartesian(tracers, randoms, mask=mask, n_bins=n_bins,
distances=distances, angle_unit="deg",
distance_cut=distance_cut, config=config)
# The profile is in distance, in coordinate units (Mpc/h here): the one
# measured above
same_profile = np.array_equal(result.mps_profile.mps, profile.mps)
print(f"The profile of the result is the one measured: {'yes' if same_profile else 'no'}")
# ----------------------------------------------------------------
# ------------ Reconstruct without the distance table ------------
# ----------------------------------------------------------------
# Without a table, distances omitted, the reconstruction does the same
# work, from the same seed, and gives the same displacements, valid flags
# and profile, bit for bit; only the redshifts of the result are NaN, and
# its files hold no distance table. NaN counts as equal to NaN here: the
# tracers left out by the cut, and those without a valid realization,
# have NaN means
without_table = otswap.reconstruct_lightcone_cartesian(tracers, randoms, mask=mask, n_bins=n_bins,
angle_unit="deg", distance_cut=distance_cut,
config=config)
same = (np.array_equal(without_table.displacement, result.displacement, equal_nan=True)
and np.array_equal(without_table.valid, result.valid)
and np.array_equal(without_table.mps_profile.mps, result.mps_profile.mps))
print(f"Without the table: {'the same' if same else 'NOT the same'} displacements, valid flags and profile")
# ---------------------------------------------
# ------------ Read the bias table ------------
# ---------------------------------------------
bias = otswap.io.read_bias_table(data / "lightcone_bias.dat")
# ----------------------------------------------------------------
# ------------ Correct the redshift-space distortions ------------
# ----------------------------------------------------------------
# As in full_recons_lightcone: real_space_lightcone takes the result of
# either function. The distance table is required here, even for a
# result reconstructed without one: the growth rate f and the bias b(z)
# are taken at the tracers' redshifts, which the table gives from their
# distances.
#
# sigma, the width of the Gaussian average in coordinate units (Mpc/h
# here): 10 Mpc/h is a starting value, and the value must be calibrated
# on the sample (the guide's section "Choosing the parameters")
correction = otswap.CorrectionConfig(weight_by_realizations=False, verbosity="normal")
catalogue = otswap.real_space_lightcone(result, distances=distances, bias=bias, sigma=10.0,
correction=correction)
# ----------------------------------------------
# ------------ Summarize the result ------------
# ----------------------------------------------
mean = result.mean_displacement
length = np.linalg.norm(mean, axis=1)
length = length[~np.isnan(length)]
print(f"Mean length of the mean displacement over {len(length)} tracers: {length.mean():g} Mpc/h")
shift = catalogue.shift[~np.isnan(catalogue.shift)]
print(f"Shift along the line of sight over the {len(shift)} corrected tracers: mean {shift.mean():g}, "
f"rms {np.sqrt(np.mean(shift ** 2)):g} Mpc/h")
# ------------------------------------------
# ------------ Write the output ------------
# ------------------------------------------
# The mean displacement, with the mps(d) profile and the distance table
# in twin files, and the corrected catalogue; the columns are those of
# the lightcone and full_recons_lightcone examples, but the mean file
# adds the column outsideDistanceCut, and the profile is binned in
# distance: a column distance and the keywords DISTMIN and DISTMAX, in
# coordinate units, instead of the redshift ones. The file of the result
# without the table has NaN redshift columns (tracRed, lagrRed) and no
# distance table twin. The writers are the C++ library's, so the files
# are the C++ example's, byte for byte
otswap.io.write_displacement_mean(output / "displacement_lightcone_cartesian.dat", result)
otswap.io.write_displacement_mean(output / "displacement_lightcone_cartesian_no_table.dat", without_table)
otswap.io.write_real_space_catalog(output / "reconstructed_catalogue_lightcone_cartesian.dat", catalogue)
print("Written: output/displacement_lightcone_cartesian.dat")
print("Written: output/displacement_lightcone_cartesian_no_table.dat")
print("Written: output/reconstructed_catalogue_lightcone_cartesian.dat")
if __name__ == "__main__":
main()
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 by Simone Sartori, simone.sartori@inaf.it
// ============================================================================
// Example code: how to run the OT reconstruction on a lightcone in Cartesian
// coordinates, and correct it for redshift-space distortions
// ============================================================================
/*
This example explains how to reconstruct a survey catalogue that is
given in comoving Cartesian coordinates, with the observer at the
origin, instead of right ascension, declination and redshift. Its
tracers and randoms are those of the lightcone and
full_recons_lightcone examples, converted to Cartesian coordinates
with the same cosmology, and it does what both do: it measures the
mean particle separation alone, to choose the bins, then runs the
reconstruction, here with a cut on the distance, and the correction.
It first finds the distance and the direction of each tracer, with
pointToSky, which is where the cut and the mask act.
Without redshifts the mean particle separation is measured as a
function of the comoving distance from the origin, in uniform distance
bins, and the mask and the optional distance cut act on the angles and
the distance of each object. The distance table is optional for the
reconstruction, and only fills the redshifts of the result; it is
needed here for the correction, which takes the growth rate f and the
bias b(z) at the tracers' redshifts. The example runs the
reconstruction a second time without it, to show that nothing else
changes.
Usage: lightcone_cartesian [data_dir]. The catalogues are read from
data_dir, by default the examples' data folder; the output is written
to the folder output/ next to this file, created if missing.
*/
#include <algorithm>
#include <cmath>
#include <filesystem>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include "otswap/OT.h"
// ==========================================================================
int main (int argc, char** argv)
{
try {
// -------------------------------------------------------------
// ------------ Locate the input and output folders ------------
// -------------------------------------------------------------
// OTSWAP_EXAMPLES_DATA and OTSWAP_EXAMPLE_OUTPUT are set by this
// example's CMakeLists.txt to the data folder and to output/ next to
// this file. A first command-line argument replaces the data folder
const std::string data = (argc > 1) ? argv[1] : OTSWAP_EXAMPLES_DATA;
const std::string output = OTSWAP_EXAMPLE_OUTPUT;
std::filesystem::create_directories(output);
// ---------------------------------------------------------------
// ------------ Read the tracer and random catalogues ------------
// ---------------------------------------------------------------
// x, y, z for each object, in Mpc/h, the observer at the origin
const std::vector<double> tracers = otswap::io::read(data + "/lightcone_tracers_cartesian.dat", {"0", "1", "2"}).values;
const std::vector<double> randoms = otswap::io::read(data + "/lightcone_randoms_cartesian.dat", {"0", "1", "2"}).values;
const std::size_t nTracers = tracers.size() / 3;
const std::size_t nRandoms = randoms.size() / 3;
std::cout << "Tracers read: " << nTracers << std::endl;
std::cout << "Randoms read: " << nRandoms << ", " << (double)nRandoms / (double)nTracers << " per tracer" << std::endl;
// ---------------------------------------
// ------------ Read the mask ------------
// ---------------------------------------
const otswap::Mask mask(data + "/lightcone_mask.fits");
std::cout << "Mask: NSIDE " << mask.nside() << ", " << mask.skyAreaDeg2() << " deg^2" << std::endl;
// ---------------------------------------------------------------
// ------------ Find the distances and the directions ------------
// ---------------------------------------------------------------
// pointToSky gives, for one point, its distance from the origin, in
// coordinate units, and its right ascension and declination, in
// radians: the direction the mask is applied to, and the distance the
// distance cut and the mps bins are taken on. It needs no distance
// table. The range of the distances is where to choose the cut.
// otswap::skyToDegrees converts the angles of an array ordered right
// ascension, declination, then a third value left unchanged, here the
// distance: the degrees of Python's point_to_sky, bit for bit
std::vector<double> directions(3*nTracers);
std::vector<double> distance(nTracers);
for (std::size_t i = 0; i < nTracers; ++i) {
otswap::pointToSky(tracers[3*i], tracers[3*i+1], tracers[3*i+2],
distance[i], directions[3*i], directions[3*i+1]);
directions[3*i+2] = distance[i];
}
directions = otswap::skyToDegrees(std::move(directions));
std::vector<double> ra(nTracers), dec(nTracers);
for (std::size_t i = 0; i < nTracers; ++i) {
ra[i] = directions[3*i];
dec[i] = directions[3*i+1];
}
std::cout << "Tracer distances: " << *std::min_element(distance.begin(), distance.end()) << " to "
<< *std::max_element(distance.begin(), distance.end()) << " Mpc/h" << std::endl;
// One row per tracer, in input order: distance, RA, Dec
otswap::io::write(output + "/tracers_sky_lightcone_cartesian.dat",
{{"distance", 'D', "distance from the origin", "", distance, {}},
{"ra", 'D', "right ascension", "deg", ra, {}},
{"dec", 'D', "declination", "deg", dec, {}}});
std::cout << "Written: output/tracers_sky_lightcone_cartesian.dat" << std::endl;
// ----------------------------------------------------
// ------------ Set the cosmological model ------------
// ----------------------------------------------------
// The table gives the linear growth rate f(z) of the correction, and
// the redshifts of the result. Its distances are in Mpc/h, so the
// coordinates must be in Mpc/h too: the unit of the coordinates is
// that of any distance table used with them. It must cover the
// corrected distances too: the default range, z = 0 to 10, leaves room
// for that
const otswap::DistanceTable distances(0.286, 0.7, -1., 0.);
// --------------------------------------------
// ------------ Set the parameters ------------
// --------------------------------------------
// A fixed seed, and the displacements crossing an unobserved pixel of
// the mask rejected. 8 realizations, which the example randoms are
// enough for, and a convergence threshold of 1e-2 keep the example
// fast; for an analysis, start from the defaults, 30 and 1e-3 (the
// guide's section "Choosing the parameters"). The report goes to
// std::cout, in order with this program's lines
otswap::Config config;
config.nRealizations = 8;
config.convergence = 1.e-2;
config.seed = 12345;
config.rejectCrossings = true;
config.maxUnobservedPixelsCrossed = 0;
config.verbosity = otswap::Verbosity::Normal;
config.log = &std::cout;
// The mean particle separation is measured in 30 distance bins of
// equal width, each with enough tracers, over the distances of the
// tracers kept
const unsigned nBins = 30;
// Tracers and randoms whose comoving distance from the origin lies
// outside this closed range, in coordinate units, are left out of the
// reconstruction: the randoms are dropped, and the tracers keep their
// row, flagged in Result::outsideDistanceCut. The catalogue spans 2126
// to 2500 Mpc/h. The default, {}, cuts nothing
otswap::DistanceCut cut;
cut.min = 2200.;
cut.max = 2450.;
// --------------------------------------------------------------
// ------------ Measure the mean particle separation ------------
// --------------------------------------------------------------
// The Cartesian measureMpsProfile measures mps(d) from the tracers
// alone, as the reconstruction does, from the same mask, bins and cut,
// and in a fraction of its time: the profile is Result::mpsProfile of
// the reconstruction below, bit for bit. Use it to choose nBins before
// a reconstruction. It needs no distance table
const otswap::MpsProfile profile =
otswap::measureMpsProfile(tracers, mask, nBins, cut, otswap::Verbosity::Normal, &std::cout);
std::cout << "mps(d): " << profile.mps.size() << " bins, mps from "
<< *std::min_element(profile.mps.begin(), profile.mps.end()) << " to "
<< *std::max_element(profile.mps.begin(), profile.mps.end()) << " Mpc/h" << std::endl;
// Without a mask, the overloads that take the sky area, in square
// degrees, leave out no object on the sky and filter no crossing: the
// catalogues must then lie within the footprint already. These do, so
// with the mask's area the profile is the same
const otswap::MpsProfile fromArea =
otswap::measureMpsProfile(tracers, mask.skyAreaDeg2(), nBins, cut, otswap::Verbosity::Silent);
std::cout << "The same profile from the sky area: " << (fromArea.mps == profile.mps ? "yes" : "no") << std::endl;
// One row per bin: its centre, in distance, its mps and its number of
// tracers, with the range and the representative mps as keywords
otswap::io::writeMpsProfile(output + "/mps_lightcone_cartesian.dat", profile);
std::cout << "Written: output/mps_lightcone_cartesian.dat" << std::endl;
// ------------------------------------------------
// ------------ Run the reconstruction ------------
// ------------------------------------------------
// The table, given by pointer since it is optional, fills the
// redshifts of the result
const otswap::Result result = otswap::reconstructLightcone(tracers, randoms, mask, nBins, config, &distances, cut);
// The profile is in distance, in coordinate units (Mpc/h here): the
// one measured above
std::cout << "The profile of the result is the one measured: "
<< (result.mpsProfile.mps == profile.mps ? "yes" : "no") << std::endl;
// ----------------------------------------------------------------
// ------------ Reconstruct without the distance table ------------
// ----------------------------------------------------------------
// Without a table, a null pointer, the reconstruction does the same
// work, from the same seed, and gives the same displacements, valid
// flags and profile, bit for bit; only the redshifts of the result
// are NaN, and its files hold no distance table
const otswap::Result withoutTable = otswap::reconstructLightcone(tracers, randoms, mask, nBins, config,
nullptr, cut);
// Equal values, NaN counting as equal to NaN: the tracers left out by
// the cut, and those without a valid realization, have NaN means
auto sameValues = [] (const std::vector<double>& a, const std::vector<double>& b) {
if (a.size() != b.size()) return false;
for (std::size_t k = 0; k < a.size(); ++k)
if (!(a[k] == b[k] || (std::isnan(a[k]) && std::isnan(b[k])))) return false;
return true;
};
const bool same = sameValues(withoutTable.displacement, result.displacement) &&
withoutTable.valid == result.valid &&
withoutTable.mpsProfile.mps == result.mpsProfile.mps;
std::cout << "Without the table: " << (same ? "the same" : "NOT the same")
<< " displacements, valid flags and profile" << std::endl;
// ---------------------------------------------
// ------------ Read the bias table ------------
// ---------------------------------------------
const otswap::BiasTable bias = otswap::io::readBiasTable(data + "/lightcone_bias.dat");
// ----------------------------------------------------------------
// ------------ Correct the redshift-space distortions ------------
// ----------------------------------------------------------------
// As in full_recons_lightcone: realSpaceLightcone takes the result of
// either overload of reconstructLightcone. The distance table is
// required here, even for a result reconstructed without one: the
// growth rate f and the bias b(z) are taken at the tracers' redshifts,
// which the table gives from their distances.
//
// sigma, the width of the Gaussian average in coordinate units (Mpc/h
// here): 10 Mpc/h is a starting value, and the value must be
// calibrated on the sample (the guide's section "Choosing the
// parameters")
const double sigma = 10.;
otswap::CorrectionConfig correction;
correction.weightByRealizations = false;
correction.verbosity = otswap::Verbosity::Normal;
correction.log = &std::cout;
const otswap::RealSpaceCatalog catalogue = otswap::realSpaceLightcone(result, distances, bias, sigma, correction);
// ----------------------------------------------
// ------------ Summarize the result ------------
// ----------------------------------------------
double sum = 0., squares = 0., length = 0.;
std::size_t corrected = 0, withMean = 0;
for (std::size_t i = 0; i < nTracers; ++i) {
const double* d = &result.meanDisplacement[3*i];
if (!std::isnan(d[0])) {
++withMean;
length += std::sqrt(d[0]*d[0] + d[1]*d[1] + d[2]*d[2]);
}
if (std::isnan(catalogue.shift[i])) continue;
++corrected;
sum += catalogue.shift[i];
squares += catalogue.shift[i] * catalogue.shift[i];
}
std::cout << "Mean length of the mean displacement over " << withMean << " tracers: "
<< length / (double)withMean << " Mpc/h" << std::endl;
std::cout << "Shift along the line of sight over the " << corrected << " corrected tracers: mean "
<< sum / (double)corrected << ", rms " << std::sqrt(squares / (double)corrected) << " Mpc/h" << std::endl;
// ------------------------------------------
// ------------ Write the output ------------
// ------------------------------------------
// The mean displacement, with the mps(d) profile and the distance
// table in twin files, and the corrected catalogue; the columns are
// those of the lightcone and full_recons_lightcone examples, but the
// mean file adds the column outsideDistanceCut, and the profile is
// binned in distance: a column distance and the keywords DISTMIN and
// DISTMAX, in coordinate units, instead of the redshift ones. The
// file of the result without the table has NaN redshift columns
// (tracRed, lagrRed) and no distance table twin
otswap::io::writeDisplacementMean(output + "/displacement_lightcone_cartesian.dat", result);
otswap::io::writeDisplacementMean(output + "/displacement_lightcone_cartesian_no_table.dat", withoutTable);
otswap::io::writeRealSpaceCatalog(output + "/reconstructed_catalogue_lightcone_cartesian.dat", catalogue);
std::cout << "Written: output/displacement_lightcone_cartesian.dat" << std::endl;
std::cout << "Written: output/displacement_lightcone_cartesian_no_table.dat" << std::endl;
std::cout << "Written: output/reconstructed_catalogue_lightcone_cartesian.dat" << std::endl;
}
catch (const otswap::Error& e) { std::cerr << e.what() << std::endl; return 1; }
return 0;
}
Redshift-space correction in a box¶
Runs the box reconstruction, without box limits, on the same halos in redshift space, distorted along the y axis, then moves each halo along that axis to its real-space position with the factor f/(b + 3f/5). It reads the corrected catalogue back by column name and compares it with the halos in real space.
Reads:
examples/data/box_halos_real_space.dat, for the comparison
Writes output/reconstructed_catalogue_box.dat, with otswap.io.write_real_space_catalog(); its columns
and keywords are on the file formats page.
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2026 by Simone Sartori, simone.sartori@inaf.it
# =====================================================================
# Example code: how to move a box catalogue from redshift to real space
# =====================================================================
"""This example explains how to correct a catalogue in box geometry for
redshift-space distortions with the OT reconstruction. The tracers are given
in redshift space, distorted along the y axis (axis 1), the line of sight.
The example runs the reconstruction of the box example on them, then moves
each tracer along that axis to the position it would have in real space.
The correction of tracer i is a shift along the axis,
s_i = f(z) / (b + 3 f(z) / 5) * <Psi_axis>_i ,
with f the linear growth rate at the box's redshift z, b the tracers' linear
bias, and <Psi_axis>_i the component along the axis of the reconstructed
mean displacement, averaged with a Gaussian of width sigma over the tracers
around i.
Without the periodic option, the box is not periodic, here or in the
reconstruction: nothing flows through its faces, so modes on the scale of
the box itself are not reconstructed, and the corrected positions are not
wrapped. A box cut from a periodic simulation is treated as a plain
sub-volume; a whole simulation box with periodic boundary conditions is
reconstructed, and corrected, with the periodic option: see the
periodic_box example.
Usage: python full_recons_box.py [data_dir]. The catalogues are read from
data_dir, by default the examples' data folder; the output is written to the
folder output/ next to this file, created if missing.
"""
import sys
from pathlib import Path
import numpy as np
import otswap
def main():
# -------------------------------------------------------------
# ------------ Locate the input and output folders ------------
# -------------------------------------------------------------
# The data folder is the examples' one, next to this example's folder,
# unless a first command-line argument replaces it
here = Path(__file__).resolve().parent
data = Path(sys.argv[1]) if len(sys.argv) > 1 else here.parent / "data"
output = here / "output"
output.mkdir(parents=True, exist_ok=True)
# ---------------------------------------------------------------
# ------------ Read the tracer and random catalogues ------------
# ---------------------------------------------------------------
# Comoving Cartesian coordinates in Mpc/h, shape (N, 3). The tracers are
# in redshift space, with the line of sight along y; the randoms are
# uniform in the volume
tracers = otswap.io.read(data / "box_halos_redshift_space.dat", [0, 1, 2]).values
randoms = otswap.io.read(data / "box_randoms.dat", [0, 1, 2]).values
print(f"Tracers: {len(tracers)}")
print(f"Randoms: {len(randoms)}, {len(randoms) / len(tracers):g} per tracer")
# ------------------------------------------------
# ------------ Run the reconstruction ------------
# ------------------------------------------------
# As in the box example, but without box limits: a fixed seed, and the
# mean particle separation of the bounding box of the tracers and
# randoms, computed by otswap and printed with "detailed". 8
# realizations, which the example randoms are enough for, and a
# convergence threshold of 1e-2 keep the example fast; for an analysis,
# start from the defaults, 30 and 1e-3 (the guide's section "Choosing
# the parameters")
config = otswap.Config(n_realizations=8, convergence=1e-2, seed=12345, verbosity="detailed")
result = otswap.reconstruct_box(tracers, randoms, config=config)
# ----------------------------------------------------
# ------------ Set the cosmological model ------------
# ----------------------------------------------------
# Only the linear growth rate f at the box's redshift is needed. The
# table computes it from Omega_m, h, w0 and wa of a flat cosmology
distances = otswap.DistanceTable.flat(0.3186, 0.67, w0=-1.0, wa=0.0)
# ----------------------------------------------------------------
# ------------ Correct the redshift-space distortions ------------
# ----------------------------------------------------------------
# The box's redshift, the tracers' linear bias, and the line of sight:
# axis 0, 1 or 2 for x, y or z
redshift, bias, axis = 1.0, 1.91255, 1
# sigma, the width of the Gaussian average in Mpc/h: 10 Mpc/h is a
# starting value, and the value must be calibrated on the sample (the
# guide's section "Choosing the parameters"). The options are an
# otswap.CorrectionConfig: with weight_by_realizations=True, each
# neighbour would be weighted by its number of valid realizations.
#
# The correction reads the tracers from the result. In a box without
# limits every tracer is valid and counts among its own neighbours, so
# every one is corrected; catalogue.status records what was done with
# each
correction = otswap.CorrectionConfig(weight_by_realizations=False)
catalogue = otswap.real_space_box(result, axis=axis, redshift=redshift, distances=distances,
bias=bias, sigma=10.0, correction=correction)
# ----------------------------------------------
# ------------ Summarize the result ------------
# ----------------------------------------------
# The single factor f/(b + 3f/5) of the box, and the shift applied along
# the line of sight to each corrected tracer, both kept in the catalogue
print(f"RSD factor f/(b + 3f/5): {catalogue.factor[0]:g}")
shift = catalogue.shift[~np.isnan(catalogue.shift)]
print(f"Shift along the line of sight over the {len(shift)} corrected tracers: mean {shift.mean():g}, "
f"rms {np.sqrt(np.mean(shift ** 2)):g} Mpc/h")
# ------------------------------------------
# ------------ Write the output ------------
# ------------------------------------------
# One row per tracer, in the order of the input: the corrected position,
# NaN for an uncorrected tracer, then the number of valid realizations,
# the two diagnostics of the average and the status of the tracer. The
# writer is the C++ library's, so the file is the C++ example's, byte
# for byte
otswap.io.write_real_space_catalog(output / "reconstructed_catalogue_box.dat", catalogue)
print("Written: output/reconstructed_catalogue_box.dat")
# -----------------------------------------------------------
# ------------ Compare with the real-space halos ------------
# -----------------------------------------------------------
# The file holds the corrected position in the columns tracX, tracY and
# tracZ, which otswap.io.read finds by name in a file otswap wrote. The
# example data give the same halos in real space too, row by row, so the
# correction can be checked here, as survey data do not allow: along the
# line of sight, the offset of each halo from its real-space position,
# before and after the correction
corrected = otswap.io.read(output / "reconstructed_catalogue_box.dat", ["tracX", "tracY", "tracZ"]).values
real = otswap.io.read(data / "box_halos_real_space.dat", [0, 1, 2]).values
kept = ~np.isnan(corrected[:, axis])
before = tracers[kept, axis] - real[kept, axis]
after = corrected[kept, axis] - real[kept, axis]
print(f"rms offset from the real-space position along the line of sight, over {np.count_nonzero(kept)} "
f"halos: {np.sqrt(np.mean(before ** 2)):g} Mpc/h before the correction, "
f"{np.sqrt(np.mean(after ** 2)):g} Mpc/h after")
if __name__ == "__main__":
main()
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 by Simone Sartori, simone.sartori@inaf.it
// =====================================================================
// Example code: how to move a box catalogue from redshift to real space
// =====================================================================
/*
This example explains how to correct a catalogue in box geometry for
redshift-space distortions with the OT reconstruction. The tracers
are given in redshift space, distorted along the y axis (axis 1), the
line of sight. The example runs the reconstruction of the box example
on them, then moves each tracer along that axis to the position it
would have in real space.
The correction of tracer i is a shift along the axis,
s_i = f(z) / (b + 3 f(z) / 5) * <Psi_axis>_i ,
with f the linear growth rate at the box's redshift z, b the tracers'
linear bias, and <Psi_axis>_i the component along the axis of the
reconstructed mean displacement, averaged with a Gaussian of width
sigma over the tracers around i.
Without the periodic option, the box is not periodic, here or in the
reconstruction: nothing flows through its faces, so modes on the scale
of the box itself are not reconstructed, and the corrected positions
are not wrapped. A box cut from a periodic simulation is treated as a
plain sub-volume; a whole simulation box with periodic boundary
conditions is reconstructed, and corrected, with the periodic option:
see the periodic_box example.
Usage: full_recons_box [data_dir]. The catalogues are read from
data_dir, by default the examples' data folder; the output is written
to the folder output/ next to this file, created if missing.
*/
#include <cmath>
#include <filesystem>
#include <iostream>
#include <string>
#include <vector>
#include "otswap/OT.h"
// ==========================================================================
int main (int argc, char** argv)
{
try {
// -------------------------------------------------------------
// ------------ Locate the input and output folders ------------
// -------------------------------------------------------------
// OTSWAP_EXAMPLES_DATA and OTSWAP_EXAMPLE_OUTPUT are set by this
// example's CMakeLists.txt to the data folder and to output/ next to
// this file. A first command-line argument replaces the data folder
const std::string data = (argc > 1) ? argv[1] : OTSWAP_EXAMPLES_DATA;
const std::string output = OTSWAP_EXAMPLE_OUTPUT;
std::filesystem::create_directories(output);
// ---------------------------------------------------------------
// ------------ Read the tracer and random catalogues ------------
// ---------------------------------------------------------------
// Comoving Cartesian coordinates in Mpc/h, x, y, z for each object,
// one row after the other. The tracers are in redshift space, with
// the line of sight along y; the randoms are uniform in the volume
const std::vector<double> tracers = otswap::io::read(data + "/box_halos_redshift_space.dat", {"0", "1", "2"}).values;
const std::vector<double> randoms = otswap::io::read(data + "/box_randoms.dat", {"0", "1", "2"}).values;
const std::size_t nTracers = tracers.size() / 3;
const std::size_t nRandoms = randoms.size() / 3;
std::cout << "Tracers: " << nTracers << std::endl;
std::cout << "Randoms: " << nRandoms << ", " << (double)nRandoms / (double)nTracers << " per tracer" << std::endl;
// ------------------------------------------------
// ------------ Run the reconstruction ------------
// ------------------------------------------------
// As in the box example, but without box limits: a fixed seed, and the
// mean particle separation of the bounding box of the tracers and
// randoms, computed by otswap and reported with Detailed. 8
// realizations, which the example randoms are enough for, and a
// convergence threshold of 1e-2 keep the example fast; for an
// analysis, start from the defaults, 30 and 1e-3 (the guide's section
// "Choosing the parameters"). The report goes to std::cout, in order
// with this program's lines
otswap::Config config;
config.nRealizations = 8;
config.convergence = 1.e-2;
config.seed = 12345;
config.verbosity = otswap::Verbosity::Detailed;
config.log = &std::cout;
const otswap::Result result = otswap::reconstructBox(tracers, randoms, config);
// ----------------------------------------------------
// ------------ Set the cosmological model ------------
// ----------------------------------------------------
// Only the linear growth rate f at the box's redshift is needed. The
// table computes it from Omega_m, h, w0 and wa of a flat cosmology
const otswap::DistanceTable distances(0.3186, 0.67, -1., 0.);
// ----------------------------------------------------------------
// ------------ Correct the redshift-space distortions ------------
// ----------------------------------------------------------------
// The box's redshift, the tracers' linear bias, and the line of sight:
// axis 0, 1 or 2 for x, y or z
const double redshift = 1.;
const double bias = 1.91255;
const unsigned axis = 1;
// sigma, the width of the Gaussian average in Mpc/h: 10 Mpc/h is a
// starting value, and the value must be calibrated on the sample (the
// guide's section "Choosing the parameters"). With
// weightByRealizations, each neighbour would be weighted by its number
// of valid realizations.
//
// The correction reads the tracers from the result. In a box without
// limits every tracer is valid and counts among its own neighbours, so
// every one is corrected; RealSpaceCatalog::status records what was
// done with each
const double sigma = 10.;
otswap::CorrectionConfig correction;
correction.weightByRealizations = false;
correction.log = &std::cout;
const otswap::RealSpaceCatalog catalogue = otswap::realSpaceBox(result, axis, redshift, distances, bias,
sigma, correction);
// ----------------------------------------------
// ------------ Summarize the result ------------
// ----------------------------------------------
// The single factor f/(b + 3f/5) of the box, and the shift applied
// along the line of sight to each corrected tracer, both kept in the
// catalogue
std::cout << "RSD factor f/(b + 3f/5): " << catalogue.factor[0] << std::endl;
std::size_t corrected = 0;
double sum = 0., squares = 0.;
for (std::size_t i = 0; i < nTracers; ++i) {
if (std::isnan(catalogue.shift[i])) continue;
++corrected;
sum += catalogue.shift[i];
squares += catalogue.shift[i] * catalogue.shift[i];
}
std::cout << "Shift along the line of sight over the " << corrected << " corrected tracers: mean "
<< sum / (double)corrected << ", rms " << std::sqrt(squares / (double)corrected) << " Mpc/h" << std::endl;
// ------------------------------------------
// ------------ Write the output ------------
// ------------------------------------------
// One row per tracer, in the order of the input: the corrected
// position, NaN for an uncorrected tracer, then the number of valid
// realizations, the two diagnostics of the average and the status of
// the tracer
otswap::io::writeRealSpaceCatalog(output + "/reconstructed_catalogue_box.dat", catalogue);
std::cout << "Written: output/reconstructed_catalogue_box.dat" << std::endl;
// -----------------------------------------------------------
// ------------ Compare with the real-space halos ------------
// -----------------------------------------------------------
// The file holds the corrected position in the columns tracX, tracY
// and tracZ, which io::read finds by name in a file otswap wrote. The
// example data give the same halos in real space too, row by row, so
// the correction can be checked here, as survey data do not allow:
// along the line of sight, the offset of each halo from its real-space
// position, before and after the correction
const std::vector<double> moved =
otswap::io::read(output + "/reconstructed_catalogue_box.dat", {"tracX", "tracY", "tracZ"}).values;
const std::vector<double> real = otswap::io::read(data + "/box_halos_real_space.dat", {"0", "1", "2"}).values;
double before = 0., after = 0.;
std::size_t compared = 0;
for (std::size_t i = 0; i < nTracers; ++i) {
if (std::isnan(moved[3*i+axis])) continue;
++compared;
const double inRedshiftSpace = tracers[3*i+axis] - real[3*i+axis];
const double inRealSpace = moved[3*i+axis] - real[3*i+axis];
before += inRedshiftSpace * inRedshiftSpace;
after += inRealSpace * inRealSpace;
}
std::cout << "rms offset from the real-space position along the line of sight, over " << compared
<< " halos: " << std::sqrt(before / (double)compared) << " Mpc/h before the correction, "
<< std::sqrt(after / (double)compared) << " Mpc/h after" << std::endl;
}
catch (const otswap::Error& e) { std::cerr << e.what() << std::endl; return 1; }
return 0;
}
Redshift-space correction in a lightcone¶
Runs the lightcone reconstruction, without the redshift cut, then moves each tracer along its line of sight to its real-space position, with the growth rate from the distance table and the bias from a b(z) table.
Reads:
Writes output/reconstructed_catalogue_lightcone.dat, with otswap.io.write_real_space_catalog(); its columns
and keywords are on the file formats page.
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2026 by Simone Sartori, simone.sartori@inaf.it
# ===========================================================================
# Example code: how to move a lightcone catalogue from redshift to real space
# ===========================================================================
"""This example explains how to correct a survey catalogue for
redshift-space distortions with the OT reconstruction, in lightcone
geometry. It runs the reconstruction of the lightcone example, then moves
each tracer along its line of sight to the position it would have in real
space.
The correction of tracer i is a shift along its line of sight,
s_i = f(z_i) / (b(z_i) + 3 f(z_i) / 5) * <Psi . r_hat>_i ,
with f the linear growth rate, b the tracers' linear bias, and
<Psi . r_hat>_i the line-of-sight component of the reconstructed mean
displacement, averaged with a Gaussian of width sigma over the tracers
around i. The tracer keeps its right ascension and declination, and moves to
the redshift of comoving distance d(z_i) + s_i.
Usage: python full_recons_lightcone.py [data_dir]. The catalogues are read
from data_dir, by default the examples' data folder; the output is written to
the folder output/ next to this file, created if missing.
"""
import sys
from pathlib import Path
import numpy as np
import otswap
def main():
# -------------------------------------------------------------
# ------------ Locate the input and output folders ------------
# -------------------------------------------------------------
# The data folder is the examples' one, next to this example's folder,
# unless a first command-line argument replaces it
here = Path(__file__).resolve().parent
data = Path(sys.argv[1]) if len(sys.argv) > 1 else here.parent / "data"
output = here / "output"
output.mkdir(parents=True, exist_ok=True)
# ---------------------------------------------------------------
# ------------ Read the tracer and random catalogues ------------
# ---------------------------------------------------------------
# Right ascension and declination in degrees, and redshift; passed as
# they are, with angle_unit="deg"
tracers_sky = otswap.io.read(data / "lightcone_tracers.dat", [0, 1, 2]).values
randoms_sky = otswap.io.read(data / "lightcone_randoms.dat", [0, 1, 2]).values
print(f"Tracers read: {len(tracers_sky)}")
print(f"Randoms read: {len(randoms_sky)}, {len(randoms_sky) / len(tracers_sky):g} per tracer")
# ---------------------------------------
# ------------ Read the mask ------------
# ---------------------------------------
mask = otswap.Mask(str(data / "lightcone_mask.fits"))
print(f"Mask: NSIDE {mask.nside}, {mask.sky_area_deg2:g} deg^2")
# ----------------------------------------------------
# ------------ Set the cosmological model ------------
# ----------------------------------------------------
# The table gives the comoving distances and the linear growth rate f(z)
# of the correction, computed from Omega_m, h, w0 and wa. It must cover
# the corrected distances too, which can fall slightly outside the
# catalogue's redshift range: the default range, z = 0 to 10, leaves
# room for that
distances = otswap.DistanceTable.flat(0.286, 0.7, w0=-1.0, wa=0.0)
# ------------------------------------------------
# ------------ Run the reconstruction ------------
# ------------------------------------------------
# As in the lightcone example, without a redshift cut: a fixed seed, 30
# redshift bins for the mean particle separation, and the displacements
# crossing an unobserved pixel of the mask rejected. 8 realizations,
# which the example randoms are enough for, and a convergence threshold
# of 1e-2 keep the example fast; for an analysis, start from the
# defaults, 30 and 1e-3 (the guide's section "Choosing the parameters")
config = otswap.Config(n_realizations=8, convergence=1e-2, seed=12345, reject_crossings=True,
max_unobserved_pixels_crossed=0, verbosity="normal")
result = otswap.reconstruct_lightcone(tracers_sky, randoms_sky, mask=mask, n_bins=30,
distances=distances, angle_unit="deg", config=config)
# ---------------------------------------------
# ------------ Read the bias table ------------
# ---------------------------------------------
# The tracers' linear bias b(z), as nodes in redshift: b is interpolated
# linearly between them, and extrapolated linearly beyond the first and
# last, with an otswap.ExtrapolationWarning saying for how many tracers.
# This table covers the whole catalogue
bias = otswap.io.read_bias_table(data / "lightcone_bias.dat")
# ----------------------------------------------------------------
# ------------ Correct the redshift-space distortions ------------
# ----------------------------------------------------------------
# sigma, the width of the Gaussian average in Mpc/h: 10 Mpc/h is a
# starting value, and the value must be calibrated on the sample (the
# guide's section "Choosing the parameters"). The options are an
# otswap.CorrectionConfig: with weight_by_realizations=True, each
# neighbour would be weighted by its number of valid realizations.
# "detailed" prints, besides the line of the call, how many tracers
# moved with their neighbours' average and why the others were left
# uncorrected.
#
# The correction reads the tracers from the result. A tracer without a
# valid realization still receives the average of its neighbours; one
# with no valid neighbour within 3 sigma, or left out of the
# reconstruction by the mask, is left uncorrected, with NaN coordinates;
# catalogue.status says which
correction = otswap.CorrectionConfig(weight_by_realizations=False, verbosity="detailed")
catalogue = otswap.real_space_lightcone(result, distances=distances, bias=bias, sigma=10.0,
correction=correction)
# ----------------------------------------------
# ------------ Summarize the result ------------
# ----------------------------------------------
# The factor f/(b + 3f/5) at the redshifts of the tracers that took part
# in the reconstruction, and the shift applied along the line of sight
# to each corrected tracer, both kept in the catalogue
factor = catalogue.factor[~np.isnan(catalogue.factor)]
print(f"RSD factor f/(b + 3f/5): from {factor.min():g} to {factor.max():g}")
shift = catalogue.shift[~np.isnan(catalogue.shift)]
print(f"Shift along the line of sight over the {len(shift)} corrected tracers: mean {shift.mean():g}, "
f"rms {np.sqrt(np.mean(shift ** 2)):g} Mpc/h")
# ------------------------------------------
# ------------ Write the output ------------
# ------------------------------------------
# One row per tracer, in the order of the input: the right ascension and
# declination, unchanged within the rounding of the file, and the
# corrected redshift; the corrected Cartesian position; the number of
# valid realizations, the two diagnostics of the average and the status
# of the tracer; NaN positions for an uncorrected tracer. The writer is
# the C++ library's, so the file is the C++ example's, byte for byte
otswap.io.write_real_space_catalog(output / "reconstructed_catalogue_lightcone.dat", catalogue)
print("Written: output/reconstructed_catalogue_lightcone.dat")
if __name__ == "__main__":
main()
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 by Simone Sartori, simone.sartori@inaf.it
// ===========================================================================
// Example code: how to move a lightcone catalogue from redshift to real space
// ===========================================================================
/*
This example explains how to correct a survey catalogue for
redshift-space distortions with the OT reconstruction, in lightcone
geometry. It runs the reconstruction of the lightcone example, then
moves each tracer along its line of sight to the position it would
have in real space.
The correction of tracer i is a shift along its line of sight,
s_i = f(z_i) / (b(z_i) + 3 f(z_i) / 5) * <Psi . r_hat>_i ,
with f the linear growth rate, b the tracers' linear bias, and
<Psi . r_hat>_i the line-of-sight component of the reconstructed mean
displacement, averaged with a Gaussian of width sigma over the
tracers around i. The tracer keeps its right ascension and
declination, and moves to the redshift of comoving distance
d(z_i) + s_i.
Usage: full_recons_lightcone [data_dir]. The catalogues are read from
data_dir, by default the examples' data folder; the output is written
to the folder output/ next to this file, created if missing.
*/
#include <algorithm>
#include <cmath>
#include <filesystem>
#include <iostream>
#include <string>
#include <vector>
#include "otswap/OT.h"
// ==========================================================================
int main (int argc, char** argv)
{
try {
// -------------------------------------------------------------
// ------------ Locate the input and output folders ------------
// -------------------------------------------------------------
// OTSWAP_EXAMPLES_DATA and OTSWAP_EXAMPLE_OUTPUT are set by this
// example's CMakeLists.txt to the data folder and to output/ next to
// this file. A first command-line argument replaces the data folder
const std::string data = (argc > 1) ? argv[1] : OTSWAP_EXAMPLES_DATA;
const std::string output = OTSWAP_EXAMPLE_OUTPUT;
std::filesystem::create_directories(output);
// ---------------------------------------------------------------
// ------------ Read the tracer and random catalogues ------------
// ---------------------------------------------------------------
// Right ascension, declination and redshift for each object, one row
// after the other. The angles are read in degrees and converted to
// radians by skyToRadians, with the factor that otswap's Python
// interface uses
const std::vector<double> tracersSky =
otswap::skyToRadians(otswap::io::read(data + "/lightcone_tracers.dat", {"0", "1", "2"}).values);
const std::vector<double> randomsSky =
otswap::skyToRadians(otswap::io::read(data + "/lightcone_randoms.dat", {"0", "1", "2"}).values);
const std::size_t nTracers = tracersSky.size() / 3;
const std::size_t nRandoms = randomsSky.size() / 3;
std::cout << "Tracers read: " << nTracers << std::endl;
std::cout << "Randoms read: " << nRandoms << ", " << (double)nRandoms / (double)nTracers << " per tracer" << std::endl;
// ---------------------------------------
// ------------ Read the mask ------------
// ---------------------------------------
const otswap::Mask mask(data + "/lightcone_mask.fits");
std::cout << "Mask: NSIDE " << mask.nside() << ", " << mask.skyAreaDeg2() << " deg^2" << std::endl;
// ----------------------------------------------------
// ------------ Set the cosmological model ------------
// ----------------------------------------------------
// The table gives the comoving distances and the linear growth rate
// f(z) of the correction, computed from Omega_m, h, w0 and wa. It must
// cover the corrected distances too, which can fall slightly outside
// the catalogue's redshift range: the default range, z = 0 to 10,
// leaves room for that
const otswap::DistanceTable distances(0.286, 0.7, -1., 0.);
// ------------------------------------------------
// ------------ Run the reconstruction ------------
// ------------------------------------------------
// As in the lightcone example, without a redshift cut: a fixed seed,
// 30 redshift bins for the mean particle separation, and the
// displacements crossing an unobserved pixel of the mask rejected. 8
// realizations, which the example randoms are enough for, and a
// convergence threshold of 1e-2 keep the example fast; for an
// analysis, start from the defaults, 30 and 1e-3 (the guide's section
// "Choosing the parameters"). The report goes to std::cout, in order
// with this program's lines
otswap::Config config;
config.nRealizations = 8;
config.convergence = 1.e-2;
config.seed = 12345;
config.rejectCrossings = true;
config.maxUnobservedPixelsCrossed = 0;
config.verbosity = otswap::Verbosity::Normal;
config.log = &std::cout;
const otswap::Result result = otswap::reconstructLightcone(tracersSky, randomsSky, mask, 30, distances, config);
// ---------------------------------------------
// ------------ Read the bias table ------------
// ---------------------------------------------
// The tracers' linear bias b(z), as nodes in redshift: b is
// interpolated linearly between them, and extrapolated linearly beyond
// the first and last, which the correction reports and counts in
// RealSpaceCatalog::nExtrapolated. This table covers the whole
// catalogue
const otswap::BiasTable bias = otswap::io::readBiasTable(data + "/lightcone_bias.dat");
// ----------------------------------------------------------------
// ------------ Correct the redshift-space distortions ------------
// ----------------------------------------------------------------
// sigma, the width of the Gaussian average in Mpc/h: 10 Mpc/h is a
// starting value, and the value must be calibrated on the sample (the
// guide's section "Choosing the parameters"). With
// weightByRealizations, each neighbour would be weighted by its number
// of valid realizations. Detailed reports, besides the line of the
// call, how many tracers moved with their neighbours' average and why
// the others were left uncorrected.
//
// The correction reads the tracers from the result. A tracer without a
// valid realization still receives the average of its neighbours; one
// with no valid neighbour within 3 sigma, or left out of the
// reconstruction by the mask, is left uncorrected, with NaN
// coordinates; RealSpaceCatalog::status says which
const double sigma = 10.;
otswap::CorrectionConfig correction;
correction.weightByRealizations = false;
correction.verbosity = otswap::Verbosity::Detailed;
correction.log = &std::cout;
const otswap::RealSpaceCatalog catalogue = otswap::realSpaceLightcone(result, distances, bias, sigma, correction);
// ----------------------------------------------
// ------------ Summarize the result ------------
// ----------------------------------------------
// The factor f/(b + 3f/5) at the redshifts of the tracers that took
// part in the reconstruction, and the shift applied along the line of
// sight to each corrected tracer, both kept in the catalogue
double factorMin = INFINITY, factorMax = -INFINITY, sum = 0., squares = 0.;
std::size_t corrected = 0;
for (std::size_t i = 0; i < nTracers; ++i) {
if (!std::isnan(catalogue.factor[i])) {
factorMin = std::min(factorMin, catalogue.factor[i]);
factorMax = std::max(factorMax, catalogue.factor[i]);
}
if (std::isnan(catalogue.shift[i])) continue;
++corrected;
sum += catalogue.shift[i];
squares += catalogue.shift[i] * catalogue.shift[i];
}
std::cout << "RSD factor f/(b + 3f/5): from " << factorMin << " to " << factorMax << std::endl;
std::cout << "Shift along the line of sight over the " << corrected << " corrected tracers: mean "
<< sum / (double)corrected << ", rms " << std::sqrt(squares / (double)corrected) << " Mpc/h" << std::endl;
// ------------------------------------------
// ------------ Write the output ------------
// ------------------------------------------
// One row per tracer, in the order of the input: the right ascension
// and declination, unchanged within the rounding of the file, and the
// corrected redshift; the corrected Cartesian position; the number of
// valid realizations, the two diagnostics of the average and the
// status of the tracer; NaN positions for an uncorrected tracer
otswap::io::writeRealSpaceCatalog(output + "/reconstructed_catalogue_lightcone.dat", catalogue);
std::cout << "Written: output/reconstructed_catalogue_lightcone.dat" << std::endl;
}
catch (const otswap::Error& e) { std::cerr << e.what() << std::endl; return 1; }
return 0;
}