Lightcone examples¶
Two examples, in the lightcone geometry, on the same survey-like catalogue: tracers between redshifts 0.885 and 1.10, a random catalogue with the same footprint and redshift distribution, about eight randoms per tracer, and the footprint as a HEALPix mask.
Each example is 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 folder in examples is a CMake project of its own, built against an installed bitvf.
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.
The mask, examples/data/lightcone_mask.fits.gz, is read as it is: otswap reads a gzip-compressed FITS file directly.
Building and running¶
For an example <name>, with bitvf installed under <prefix>:
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 catalogues give the angles in degrees. The C++ programs convert them to
radians, the unit of the C++ library; the Python scripts pass them as they
are, with angle_unit="deg".
Lightcone¶
Reconstructs the tracers, in real space, with otswap, then finds the voids
of that reconstruction with bitvf::findVoidsLightcone()
(bitvf.find_voids_lightcone()): two separate calls, so that the
reconstruction can be searched several times.
Reads examples/data/lightcone_tracers.dat, examples/data/lightcone_randoms.dat and examples/data/lightcone_mask.fits.gz.
Writes output/voids_lightcone.dat, output/overdense_basins_lightcone.dat
and output/galaxies_lightcone.dat; 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 find the voids of a lightcone reconstruction
# ===================================================================
"""This example explains how to find voids in lightcone geometry from an
optimal transport reconstruction. otswap reconstructs the displacement field
of tracers observed on a part of the sky, in real space; bitvf then computes
the divergence of that field on a grid of shells in comoving distance,
declination rings and right-ascension sectors, smooths it, and splits it by a
watershed into basins around its local minima. Basins whose minimum is below
0, where the reconstructed flow diverges, are the voids; the others are the
overdense basins.
The two steps are separate calls, so the reconstruction can be kept, written,
or searched several times with different parameters. The run_lightcone
pipeline of the full_recons_lightcone example does both in one call.
The survey is described by the randoms, which must carry its footprint and
redshift distribution, and by the mask, a HEALPix map of the observed sky. A
cell of the grid whose centre falls on an unobserved pixel is masked: it
holds no divergence and belongs to no basin.
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 otswap
import bitvf
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, shape (N, 3).
# They are passed as they are, with angle_unit="deg": the Python
# interface converts at its boundary
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, RING or NESTED, from a FITS file, here gzip-compressed:
# a pixel is observed when its value is greater than 0. Tracers on
# unobserved pixels keep their row in every per-tracer output, flagged,
# and take no part
mask = otswap.Mask(str(data / "lightcone_mask.fits.gz"))
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)
# ------------------------------------------------
# ------------ Run the reconstruction ------------
# ------------------------------------------------
# 8 realizations, a convergence threshold of 1e-2 and a fixed seed, so
# that the run can be repeated; displacements that cross an unobserved
# pixel of the mask are rejected. Each realization uses as many randoms
# as there are tracers, so at least 8 per tracer are needed: 30 per
# tracer, the minimum with otswap's default of 30 realizations, is a
# good start
ot_config = otswap.Config(n_realizations=8, convergence=1e-2, seed=12345, reject_crossings=True,
max_unobserved_pixels_crossed=0, verbosity="normal")
# The mean particle separation (mps) is measured in 30 redshift bins;
# each needs enough tracers, so use fewer bins for a small sample. The
# redshift cut spans the whole catalogue: narrow it to search a slice
reconstruction = otswap.reconstruct_lightcone(tracers_sky, randoms_sky, mask=mask, n_bins=30,
distances=distances, angle_unit="deg",
redshift_cut=otswap.RedshiftCut(0.885, 1.10),
config=ot_config)
# ---------------------------------------------
# ------------ Find the voids -----------------
# ---------------------------------------------
# The search reads everything it needs from the reconstruction: the
# tracers, their displacements in each realization, the mps(z) profile,
# the distance table and the redshift cut. The randoms are given again
# because the grid and the mean density of each cell are built on them.
#
# The two parameters that change the result:
# - the smoothing: a Gaussian of width sigma, here 1 mps, the default and
# a reasonable starting value; a larger sigma merges small basins into
# larger ones;
# - the cell size, left to its default: 1 mps up to 20 realizations,
# (20 / n_realizations)^(1/3) mps above, measured at the centre of each
# shell.
#
# keep_assignment keeps, for each tracer, the basin it ended up in, which
# the galaxies file records. "detailed" prints one line per step
config = bitvf.Config(smoothing=bitvf.Smoothing(sigma=1.0, unit=bitvf.LengthUnit.MPS),
keep_assignment=True, verbosity="detailed")
result = bitvf.find_voids_lightcone(reconstruction, randoms_sky, mask=mask, angle_unit="deg", config=config)
# ----------------------------------------------
# ------------ Summarize the result ------------
# ----------------------------------------------
# Each catalogue has one row per basin, in the order of its seed cell.
# radius is the radius of the sphere with the volume of the void's core,
# the part where the divergence is below 0, in Mpc/h; edge_flag is 0 for
# a void that does not touch the edges of the grid, where the flow is not
# known
voids = result.voids
inside = int((voids.edge_flag == 0).sum())
print(f"Tracers on unobserved pixels: {result.counts.tracers_outside_mask}")
print(f"Voids: {voids.n_basins}, {inside} not touching the edges of the grid")
print(f"Largest void radius: {voids.radius.max():g} Mpc/h")
print(f"Overdense basins: {result.overdense.n_basins}")
# ------------------------------------------
# ------------ Write the output ------------
# ------------------------------------------
# One file per product, ASCII from the extension: the voids and the
# overdense basins, one row per basin, and where each tracer ended up,
# one row per tracer. Angles are written in degrees. io.file_name gives
# the conventional names, voids_lightcone.dat,
# overdense_basins_lightcone.dat and galaxies_lightcone.dat. The writers
# are the C++ library's, so the files are the C++ example's, byte for
# byte
product = bitvf.io.Product
bitvf.io.write_voids(bitvf.io.file_name(product.VOIDS, output, "lightcone.dat", zspace=False), result)
bitvf.io.write_overdense(bitvf.io.file_name(product.OVERDENSE, output, "lightcone.dat", zspace=False), result)
bitvf.io.write_galaxies(bitvf.io.file_name(product.GALAXIES, output, "lightcone.dat", zspace=False), result)
print("Written: output/voids_lightcone.dat, output/overdense_basins_lightcone.dat, "
"output/galaxies_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 find the voids of a lightcone reconstruction
// ===================================================================
/*
This example explains how to find voids in lightcone geometry from an
optimal transport reconstruction. otswap reconstructs the displacement
field of tracers observed on a part of the sky, in real space; bitvf
then computes the divergence of that field on a grid of shells in
comoving distance, declination rings and right-ascension sectors,
smooths it, and splits it by a watershed into basins around its local
minima. Basins whose minimum is below 0, where the reconstructed flow
diverges, are the voids; the others are the overdense basins.
The two steps are separate calls, so the reconstruction can be kept,
written, or searched several times with different parameters. The
runLightcone pipeline of the full_recons_lightcone example does both
in one call.
The survey is described by the randoms, which must carry its footprint
and redshift distribution, and by the mask, a HEALPix map of the
observed sky. A cell of the grid whose centre falls on an unobserved
pixel is masked: it holds no divergence and belongs to no basin.
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 <filesystem>
#include <iostream>
#include <string>
#include <vector>
#include "bitvf/VoidFinder.h"
#include "bitvf/io.h"
// ==========================================================================
int main (int argc, char** argv)
{
try {
// -------------------------------------------------------------
// ------------ Locate the input and output folders ------------
// -------------------------------------------------------------
// BITVF_EXAMPLES_DATA and BITVF_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] : BITVF_EXAMPLES_DATA;
const std::string output = BITVF_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: the C++ library works in radians
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, RING or NESTED, from a FITS file, here gzip-compressed:
// a pixel is observed when its value is greater than 0. Tracers on
// unobserved pixels keep their row in every per-tracer output, flagged,
// and take no part
const otswap::Mask mask(data + "/lightcone_mask.fits.gz");
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.);
// ------------------------------------------------
// ------------ Run the reconstruction ------------
// ------------------------------------------------
// 8 realizations, a convergence threshold of 1e-2 and a fixed seed, so
// that the run can be repeated; displacements that cross an unobserved
// pixel of the mask are rejected. Each realization uses as many randoms
// as there are tracers, so at least 8 per tracer are needed: 30 per
// tracer, the minimum with otswap's default of 30 realizations, is a
// good start. The report goes to std::cout, in order with
// this program's lines
otswap::Config otConfig;
otConfig.nRealizations = 8;
otConfig.convergence = 1.e-2;
otConfig.seed = 12345;
otConfig.rejectCrossings = true;
otConfig.maxUnobservedPixelsCrossed = 0;
otConfig.verbosity = otswap::Verbosity::Normal;
otConfig.log = &std::cout;
// The mean particle separation (mps) is measured in 30 redshift bins;
// each needs enough tracers, so use fewer bins for a small sample. The
// redshift cut spans the whole catalogue: narrow it to search a slice
const unsigned nBins = 30;
const otswap::RedshiftCut cut{0.885, 1.10};
const otswap::Result reconstruction =
otswap::reconstructLightcone(tracersSky, randomsSky, mask, nBins, distances, otConfig, cut);
// ---------------------------------------------
// ------------ Find the voids -----------------
// ---------------------------------------------
// The search reads everything it needs from the reconstruction: the
// tracers, their displacements in each realization, the mps(z) profile,
// the distance table and the redshift cut. The randoms are given again
// because the grid and the mean density of each cell are built on them.
//
// The two parameters that change the result:
// - the smoothing: a Gaussian of width sigma, here 1 mps, the default
// and a reasonable starting value; a larger sigma merges small basins
// into larger ones;
// - the cell size, left to its default: 1 mps up to 20 realizations,
// (20 / nRealizations)^(1/3) mps above, measured at the centre of
// each shell.
//
// keepAssignment keeps, for each tracer, the basin it ended up in, which
// the galaxies file records. Detailed prints one line per step
bitvf::Config config;
config.smoothing.sigma = 1.;
config.smoothing.unit = bitvf::LengthUnit::Mps;
config.keepAssignment = true;
config.verbosity = otswap::Verbosity::Detailed;
config.log = &std::cout;
const bitvf::Result result = bitvf::findVoidsLightcone(reconstruction, randomsSky, mask, config);
// ----------------------------------------------
// ------------ Summarize the result ------------
// ----------------------------------------------
// Each catalogue has one row per basin, in the order of its seed cell.
// radius is the radius of the sphere with the volume of the void's
// core, the part where the divergence is below 0, in Mpc/h; edgeFlag is
// 0 for a void that does not touch the edges of the grid, where the
// flow is not known
const bitvf::BasinCatalog& voids = result.voids;
std::size_t inside = 0;
double largest = 0.;
for (std::size_t b = 0; b < voids.nBasins; ++b) {
if (voids.edgeFlag[b] == 0) ++inside;
largest = std::max(largest, voids.radius[b]);
}
std::cout << "Tracers on unobserved pixels: " << result.counts.tracersOutsideMask << std::endl;
std::cout << "Voids: " << voids.nBasins << ", " << inside << " not touching the edges of the grid" << std::endl;
std::cout << "Largest void radius: " << largest << " Mpc/h" << std::endl;
std::cout << "Overdense basins: " << result.overdense.nBasins << std::endl;
// ------------------------------------------
// ------------ Write the output ------------
// ------------------------------------------
// One file per product, ASCII from the extension: the voids and the
// overdense basins, one row per basin, and where each tracer ended up,
// one row per tracer. Angles are written in degrees. io::fileName gives
// the conventional names, voids_lightcone.dat,
// overdense_basins_lightcone.dat and galaxies_lightcone.dat
const std::string voidsFile = bitvf::io::fileName(bitvf::io::Product::Voids, output, "lightcone.dat", false);
const std::string overdenseFile = bitvf::io::fileName(bitvf::io::Product::Overdense, output, "lightcone.dat", false);
const std::string galaxiesFile = bitvf::io::fileName(bitvf::io::Product::Galaxies, output, "lightcone.dat", false);
bitvf::io::writeVoids(voidsFile, result);
bitvf::io::writeOverdense(overdenseFile, result);
bitvf::io::writeGalaxies(galaxiesFile, result);
std::cout << "Written: output/voids_lightcone.dat, output/overdense_basins_lightcone.dat, "
"output/galaxies_lightcone.dat" << std::endl;
}
catch (const otswap::Error& e) { std::cerr << e.what() << std::endl; return 1; }
catch (const bitvf::Error& e) { std::cerr << e.what() << std::endl; return 1; }
return 0;
}
Full reconstruction¶
Runs the whole pipeline on the same tracers taken as observed in redshift
space, in one call to bitvf::runLightcone()
(bitvf.run_lightcone()): the reconstruction, the correction of
redshift-space distortions with the bias of
examples/data/lightcone_bias.dat, a second reconstruction in
real space with resampled randoms, and the void search, also on the
redshift-space pass.
Reads the files of the previous example and examples/data/lightcone_bias.dat.
Writes output/voids_zspace_lightcone.dat,
output/divergence_zspace_lightcone.dat, output/voids_lightcone.dat and
output/divergence_lightcone.dat, each divergence file with its twin file
of the mps(z) profile, .mps.dat.
examples/executable/lightcone.ini runs the same pipeline with
the bitvf executable and writes the same files.
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2026 by Simone Sartori, simone.sartori@inaf.it
# ===========================================================================
# Example code: how to find real-space voids from a redshift-space lightcone
# ===========================================================================
"""This example explains how to run the whole BitVF pipeline on a survey
catalogue observed in redshift space, in lightcone geometry, in one call. The
redshift distortions displace each tracer along its line of sight, the
direction from the observer. The pipeline:
1. reconstructs the displacement field of the redshift-space tracers by
optimal transport (otswap);
2. moves each tracer along its line of sight to the position it would have in
real space, from the reconstructed displacements and linear theory
(otswap's correction of redshift-space distortions);
3. reconstructs the corrected tracers again, with randoms that follow the
redshift distribution of the corrected tracers;
4. finds the voids of that real-space reconstruction, on the grid of the
first one.
On request it also finds the voids of the first, redshift-space,
reconstruction, which this example compares with the real-space ones.
Tracers on unobserved pixels or outside the redshift cut keep their row in
every per-tracer output, flagged, and take no part. So do those the
correction leaves unmoved, or moves outside the grid or the cut, in the
second reconstruction.
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 otswap
import bitvf
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, shape (N, 3);
# 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)}")
# ---------------------------------------
# ------------ Read the mask ------------
# ---------------------------------------
# A HEALPix map from a FITS file, here gzip-compressed: a pixel is
# observed when its value is greater than 0
mask = otswap.Mask(str(data / "lightcone_mask.fits.gz"))
print(f"Mask: NSIDE {mask.nside}, {mask.sky_area_deg2:g} deg^2")
# --------------------------------------------------
# ------------ Configure the pipeline --------------
# --------------------------------------------------
# The reconstruction, for both passes: 8 realizations, a convergence
# threshold of 1e-2 and a fixed seed; displacements that cross an
# unobserved pixel of the mask are rejected. Each realization uses as
# many randoms as there are tracers, so at least 8 per tracer are needed:
# 30 per tracer, the minimum with otswap's default of 30 realizations, is
# a good start
ot_config = otswap.Config(n_realizations=8, convergence=1e-2, seed=12345, reject_crossings=True,
max_unobserved_pixels_crossed=0)
# The correction: the tracers' linear bias as nodes in redshift,
# interpolated linearly between them, and sigma, the width of the
# Gaussian average of the displacements around each tracer, in Mpc/h:
# 10 Mpc/h is a reasonable starting value, but the best value depends on
# the sample and should be checked in each analysis. RESAMPLE, the
# default, gives the randoms of the second reconstruction the redshift
# distribution of the corrected tracers; NONE would keep the observed
# one. zspace_voids also searches the redshift-space pass
rsd = bitvf.LightconeRsd(bias=otswap.io.read_bias_table(data / "lightcone_bias.dat"), sigma=10.0,
second_pass_randoms=bitvf.SecondPassRandoms.RESAMPLE, zspace_voids=True)
# The void search, on both passes: the default smoothing of 1 mps and the
# default cell size. The divergence grid is kept, with the field before
# and after smoothing, so that it can be written and searched again later
# without the reconstruction
voids = bitvf.Config(keep_divergence=True, verbosity="detailed")
# The mean particle separation (mps) is measured in 30 redshift bins on
# each pass; each needs enough tracers, so use fewer bins for a small
# sample. The redshift cut spans the whole catalogue: narrow it to search
# a slice
config = bitvf.LightconeConfig(ot=ot_config, n_bins=30, cut=otswap.RedshiftCut(0.885, 1.10), rsd=rsd,
voids=voids)
# The comoving distances and the linear growth rate f(z) of the
# correction, from Omega_m, h, w0 and wa of a flat cosmology. The table
# 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 pipeline ----------------
# ----------------------------------------------
run = bitvf.run_lightcone(tracers_sky, randoms_sky, mask=mask, distances=distances, angle_unit="deg",
config=config)
# ----------------------------------------------
# ------------ Summarize the result ------------
# ----------------------------------------------
# run.voids is the real-space search, whose per-tracer outputs keep one
# row per input tracer, and run.zspace_voids the redshift-space one.
# Redshift-space distortions stretch voids along the line of sight and
# change their number
real, zspace = run.voids, run.zspace_voids
print(f"Tracers left out of the second pass: {real.counts.tracers_uncorrected} uncorrected, "
f"{real.counts.tracers_outside_grid} moved outside the grid, "
f"{real.counts.tracers_outside_cut} moved outside the redshift cut")
print(f"Voids in redshift space: {zspace.voids.n_basins}")
print(f"Voids in real space: {real.voids.n_basins}")
# ------------------------------------------
# ------------ Write the output ------------
# ------------------------------------------
# The voids and the divergence grid of each pass, with the mps(z) profile
# of the grid in a twin file (.mps.dat). The redshift-space files have
# zspace_ in their names: voids_zspace_lightcone.dat and
# divergence_zspace_lightcone.dat, then voids_lightcone.dat and
# divergence_lightcone.dat. The writers are the C++ library's, so the
# files are the C++ example's, byte for byte
product = bitvf.io.Product
bitvf.io.write_voids(bitvf.io.file_name(product.VOIDS, output, "lightcone.dat", zspace=True), zspace)
bitvf.io.write_divergence(bitvf.io.file_name(product.DIVERGENCE, output, "lightcone.dat", zspace=True), zspace)
bitvf.io.write_voids(bitvf.io.file_name(product.VOIDS, output, "lightcone.dat", zspace=False), real)
bitvf.io.write_divergence(bitvf.io.file_name(product.DIVERGENCE, output, "lightcone.dat", zspace=False), real)
print("Written: output/voids_zspace_lightcone.dat, output/divergence_zspace_lightcone.dat, "
"output/voids_lightcone.dat, output/divergence_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 find real-space voids from a redshift-space lightcone
// ===========================================================================
/*
This example explains how to run the whole BitVF pipeline on a survey
catalogue observed in redshift space, in lightcone geometry, in one
call. The redshift distortions displace each tracer along its line of
sight, the direction from the observer. The pipeline:
1. reconstructs the displacement field of the redshift-space tracers
by optimal transport (otswap);
2. moves each tracer along its line of sight to the position it would
have in real space, from the reconstructed displacements and linear
theory (otswap's correction of redshift-space distortions);
3. reconstructs the corrected tracers again, with randoms that follow
the redshift distribution of the corrected tracers;
4. finds the voids of that real-space reconstruction, on the grid of
the first one.
On request it also finds the voids of the first, redshift-space,
reconstruction, which this example compares with the real-space ones.
Tracers on unobserved pixels or outside the redshift cut keep their row
in every per-tracer output, flagged, and take no part. So do those the
correction leaves unmoved, or moves outside the grid or the cut, in the
second reconstruction.
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 <filesystem>
#include <iostream>
#include <string>
#include <vector>
#include "bitvf/BitVF.h"
#include "bitvf/io.h"
// ==========================================================================
int main (int argc, char** argv)
{
try {
// -------------------------------------------------------------
// ------------ Locate the input and output folders ------------
// -------------------------------------------------------------
// BITVF_EXAMPLES_DATA and BITVF_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] : BITVF_EXAMPLES_DATA;
const std::string output = BITVF_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: the C++ library works in radians
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);
std::cout << "Tracers read: " << tracersSky.size() / 3 << std::endl;
std::cout << "Randoms read: " << randomsSky.size() / 3 << std::endl;
// ---------------------------------------
// ------------ Read the mask ------------
// ---------------------------------------
// A HEALPix map from a FITS file, here gzip-compressed: a pixel is
// observed when its value is greater than 0
const otswap::Mask mask(data + "/lightcone_mask.fits.gz");
std::cout << "Mask: NSIDE " << mask.nside() << ", " << mask.skyAreaDeg2() << " deg^2" << std::endl;
// --------------------------------------------------
// ------------ Configure the pipeline --------------
// --------------------------------------------------
// The reconstruction, for both passes: 8 realizations, a convergence
// threshold of 1e-2 and a fixed seed; displacements that cross an
// unobserved pixel of the mask are rejected. Each realization uses as
// many randoms as there are tracers, so at least 8 per tracer are
// needed: 30 per tracer, the minimum with otswap's default of 30
// realizations, is a good start
bitvf::LightconeConfig config;
config.ot.nRealizations = 8;
config.ot.convergence = 1.e-2;
config.ot.seed = 12345;
config.ot.rejectCrossings = true;
config.ot.maxUnobservedPixelsCrossed = 0;
config.ot.log = &std::cout;
// The mean particle separation (mps) is measured in 30 redshift bins on
// each pass; each needs enough tracers, so use fewer bins for a small
// sample. The redshift cut spans the whole catalogue: narrow it to
// search a slice
config.nBins = 30;
config.cut = otswap::RedshiftCut{0.885, 1.10};
// The correction: the tracers' linear bias as nodes in redshift,
// interpolated linearly between them, and sigma, the width of the
// Gaussian average of the displacements around each tracer, in Mpc/h:
// 10 Mpc/h is a reasonable starting value, but the best value depends
// on the sample and should be checked in each analysis. Resample, the
// default, gives the randoms of the second reconstruction the redshift
// distribution of the corrected tracers; None would keep the observed
// one. zspaceVoids also searches the redshift-space pass
bitvf::LightconeRsd rsd;
rsd.bias = otswap::io::readBiasTable(data + "/lightcone_bias.dat");
rsd.sigma = 10.;
rsd.correction.log = &std::cout;
rsd.secondPassRandoms = bitvf::SecondPassRandoms::Resample;
rsd.zspaceVoids = true;
config.rsd = rsd;
// The void search, on both passes: the default smoothing of 1 mps and
// the default cell size. The divergence grid is kept, with the field
// before and after smoothing, so that it can be written and searched
// again later without the reconstruction
config.voids.keepDivergence = true;
config.voids.verbosity = otswap::Verbosity::Detailed;
config.voids.log = &std::cout;
// The comoving distances and the linear growth rate f(z) of the
// correction, from Omega_m, h, w0 and wa of a flat cosmology. The table
// 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 pipeline ----------------
// ----------------------------------------------
const bitvf::BitVFResult run = bitvf::runLightcone(tracersSky, randomsSky, mask, distances, config);
// ----------------------------------------------
// ------------ Summarize the result ------------
// ----------------------------------------------
// run.voids is the real-space search, whose per-tracer outputs keep
// one row per input tracer, and run.zspaceVoids the redshift-space one.
// Redshift-space distortions stretch voids along the line of sight and
// change their number
const bitvf::Result& real = run.voids;
const bitvf::Result& zspace = *run.zspaceVoids;
std::cout << "Tracers left out of the second pass: " << real.counts.tracersUncorrected << " uncorrected, "
<< real.counts.tracersOutsideGrid << " moved outside the grid, "
<< real.counts.tracersOutsideCut << " moved outside the redshift cut" << std::endl;
std::cout << "Voids in redshift space: " << zspace.voids.nBasins << std::endl;
std::cout << "Voids in real space: " << real.voids.nBasins << std::endl;
// ------------------------------------------
// ------------ Write the output ------------
// ------------------------------------------
// The voids and the divergence grid of each pass, with the mps(z)
// profile of the grid in a twin file (.mps.dat). The redshift-space
// files have zspace_ in their names: voids_zspace_lightcone.dat and
// divergence_zspace_lightcone.dat, then voids_lightcone.dat and
// divergence_lightcone.dat
using bitvf::io::Product;
bitvf::io::writeVoids(bitvf::io::fileName(Product::Voids, output, "lightcone.dat", true), zspace);
bitvf::io::writeDivergence(bitvf::io::fileName(Product::Divergence, output, "lightcone.dat", true), zspace);
bitvf::io::writeVoids(bitvf::io::fileName(Product::Voids, output, "lightcone.dat", false), real);
bitvf::io::writeDivergence(bitvf::io::fileName(Product::Divergence, output, "lightcone.dat", false), real);
std::cout << "Written: output/voids_zspace_lightcone.dat, output/divergence_zspace_lightcone.dat, "
"output/voids_lightcone.dat, output/divergence_lightcone.dat" << std::endl;
}
catch (const otswap::Error& e) { std::cerr << e.what() << std::endl; return 1; }
catch (const bitvf::Error& e) { std::cerr << e.what() << std::endl; return 1; }
return 0;
}