Box examples

Three examples, in the box geometry.

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.

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 field example reads the output of full_recons_box, which is run first.

Box

Reconstructs halos in a cube, in real space, with otswap, then finds the voids of that reconstruction with bitvf::findVoidsBox() (bitvf.find_voids_box()): two separate calls, so that the reconstruction can be searched several times.

Reads examples/data/box_halos_real_space.dat.

Writes output/voids_box.dat, output/overdense_basins_box.dat and output/galaxies_box.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 box reconstruction
# ===============================================================

"""This example explains how to find voids in box geometry from an optimal
transport reconstruction. otswap reconstructs the displacement field of halos
in real space; bitvf then computes the divergence of that field on a grid of
cubic cells, 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_box pipeline of
the full_recons_box example does both in one call.

The box is not periodic: nothing flows through its faces, and the basins that
touch them are flagged (edge_flag), so that they can be left out of an
analysis.

Usage: python 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 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 catalogue -------------
    # ----------------------------------------------------

    # Comoving Cartesian coordinates in Mpc/h, shape (N, 3), in real space
    tracers = otswap.io.read(data / "box_halos_real_space.dat", [0, 1, 2]).values

    print(f"Tracers: {len(tracers)}")

    # ------------------------------------------------
    # ------------ Run the reconstruction ------------
    # ------------------------------------------------

    # The halos fill a cube of side 400 Mpc/h, [269, 669) on each axis.
    # Given as box limits, the cube is where otswap draws the randoms and
    # where bitvf builds its grid; the mean particle separation follows from
    # its volume and the halos inside it
    box = ((269.0, 269.0, 269.0), (669.0, 669.0, 669.0))

    # 8 realizations, a convergence threshold of 1e-2 and a fixed seed, so
    # that the run can be repeated. Without randoms, otswap draws 8 per halo,
    # uniformly in the box
    ot_config = otswap.Config(n_realizations=8, convergence=1e-2, seed=12345, verbosity="normal")
    reconstruction = otswap.reconstruct_box(tracers, box=box, config=ot_config)

    # ---------------------------------------------
    # ------------ Find the voids -----------------
    # ---------------------------------------------

    # The search reads everything it needs from the reconstruction: the
    # tracers, their displacements in each realization, the mean particle
    # separation (mps) and the box.
    #
    # 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 side, left to its default: 1 mps up to 20 realizations,
    #   (20 / n_realizations)^(1/3) mps above.
    #
    # keep_assignment keeps, for each halo, 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_box(reconstruction, 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; edge_flag is 0 for a void
    # that does not touch the faces of the grid
    voids = result.voids
    inside = int((voids.edge_flag == 0).sum())

    print(f"Mean particle separation: {result.mps:g} Mpc/h")
    print(f"Voids: {voids.n_basins}, {inside} not touching the faces 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 halo ended up, one
    # row per halo. io.file_name gives the conventional names, voids_box.dat,
    # overdense_basins_box.dat and galaxies_box.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, "box.dat", zspace=False), result)
    bitvf.io.write_overdense(bitvf.io.file_name(product.OVERDENSE, output, "box.dat", zspace=False), result)
    bitvf.io.write_galaxies(bitvf.io.file_name(product.GALAXIES, output, "box.dat", zspace=False), result)

    print("Written: output/voids_box.dat, output/overdense_basins_box.dat, output/galaxies_box.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 box reconstruction
// ===============================================================

/*
  This example explains how to find voids in box geometry from an
  optimal transport reconstruction. otswap reconstructs the displacement
  field of halos in real space; bitvf then computes the divergence of
  that field on a grid of cubic cells, 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
  runBox pipeline of the full_recons_box example does both in one call.

  The box is not periodic: nothing flows through its faces, and the
  basins that touch them are flagged (edgeFlag), so that they can be
  left out of an analysis.

  Usage: 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 <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 catalogue -------------
    // ----------------------------------------------------

    // Comoving Cartesian coordinates in Mpc/h, x, y, z for each halo, one
    // row after the other, in real space
    const std::vector<double> tracers = otswap::io::read(data + "/box_halos_real_space.dat", {"0", "1", "2"}).values;

    std::cout << "Tracers: " << tracers.size() / 3 << std::endl;


    // ------------------------------------------------
    // ------------ Run the reconstruction ------------
    // ------------------------------------------------

    // The halos fill a cube of side 400 Mpc/h, [269, 669) on each axis.
    // Given as box limits, the cube is where otswap draws the randoms and
    // where bitvf builds its grid; the mean particle separation follows
    // from its volume and the halos inside it
    const otswap::BoxLimits box{{269., 269., 269.}, {669., 669., 669.}};

    // 8 realizations, a convergence threshold of 1e-2 and a fixed seed, so
    // that the run can be repeated. Without randoms, otswap draws 8 per
    // halo, uniformly in the box. 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.verbosity = otswap::Verbosity::Normal;
    otConfig.log = &std::cout;

    const otswap::Result reconstruction = otswap::reconstructBox(tracers, {}, otConfig, box);


    // ---------------------------------------------
    // ------------ Find the voids -----------------
    // ---------------------------------------------

    // The search reads everything it needs from the reconstruction: the
    // tracers, their displacements in each realization, the mean particle
    // separation (mps) and the box.
    //
    // 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 side, left to its default: 1 mps up to 20 realizations,
    //   (20 / nRealizations)^(1/3) mps above.
    //
    // keepAssignment keeps, for each halo, 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::findVoidsBox(reconstruction, 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; edgeFlag is 0 for a
    // void that does not touch the faces of the grid
    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 << "Mean particle separation: " << result.mps << " Mpc/h" << std::endl;
    std::cout << "Voids: " << voids.nBasins << ", " << inside << " not touching the faces 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 halo ended up,
    // one row per halo. io::fileName gives the conventional names,
    // voids_box.dat, overdense_basins_box.dat and galaxies_box.dat
    const std::string voidsFile = bitvf::io::fileName(bitvf::io::Product::Voids, output, "box.dat", false);
    const std::string overdenseFile = bitvf::io::fileName(bitvf::io::Product::Overdense, output, "box.dat", false);
    const std::string galaxiesFile = bitvf::io::fileName(bitvf::io::Product::Galaxies, output, "box.dat", false);

    bitvf::io::writeVoids(voidsFile, result);
    bitvf::io::writeOverdense(overdenseFile, result);
    bitvf::io::writeGalaxies(galaxiesFile, result);

    std::cout << "Written: output/voids_box.dat, output/overdense_basins_box.dat, output/galaxies_box.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 halos observed in redshift space, in one call to bitvf::runBox() (bitvf.run_box()): the reconstruction, the correction of redshift-space distortions, a second reconstruction in real space and the void search, also on the redshift-space pass. The randoms are drawn by bitvf.

Reads examples/data/box_halos_redshift_space.dat.

Writes output/voids_zspace_box.dat, output/divergence_zspace_box.dat, output/voids_box.dat and output/divergence_box.dat. examples/executable/box.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 box
# =====================================================================

"""This example explains how to run the whole BitVF pipeline on a box
catalogue observed in redshift space, in one call. The tracers are distorted
along one Cartesian axis, the line of sight. The pipeline:

1. reconstructs the displacement field of the redshift-space tracers by
   optimal transport (otswap);
2. moves each tracer along the 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 the same randoms and seed;
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 the correction leaves unmoved, or moves outside the grid, keep their
row in every per-tracer output, flagged, and take no part in the second
reconstruction.

Usage: python full_recons_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. The field example reads
the divergence file it writes.
"""

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 catalogue -------------
    # ----------------------------------------------------

    # Comoving Cartesian coordinates in Mpc/h, shape (N, 3), in redshift
    # space with the line of sight along y
    tracers = otswap.io.read(data / "box_halos_redshift_space.dat", [0, 1, 2]).values

    print(f"Tracers: {len(tracers)}")

    # --------------------------------------------------
    # ------------ Configure the pipeline --------------
    # --------------------------------------------------

    # The reconstruction, for both passes: 8 realizations, a convergence
    # threshold of 1e-2 and a fixed seed. No randoms are given, so bitvf
    # draws 8 per halo, uniformly in the box, from a seed derived from this
    # one (Result.random_seed)
    ot_config = otswap.Config(n_realizations=8, convergence=1e-2, seed=12345)

    # The halos fill a cube of side 400 Mpc/h, [269, 669) on each axis
    box = ((269.0, 269.0, 269.0), (669.0, 669.0, 669.0))

    # The correction: the line of sight (axis 0, 1 or 2 for x, y or z), the
    # box's redshift, at which the growth rate is read from the distance
    # table below, and the tracers' linear bias. sigma is 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. zspace_voids also
    # searches the redshift-space pass
    rsd = bitvf.BoxRsd(axis=1, redshift=1.0, bias=1.91255, sigma=10.0, 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 (see the field example)
    voids = bitvf.Config(keep_divergence=True, verbosity="detailed")

    config = bitvf.BoxConfig(ot=ot_config, limits=box, rsd=rsd, voids=voids)

    # The correction needs only the linear growth rate f at the box's
    # redshift. 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)

    # ----------------------------------------------
    # ------------ Run the pipeline ----------------
    # ----------------------------------------------

    run = bitvf.run_box(tracers, config=config, distances=distances)

    # ----------------------------------------------
    # ------------ Summarize the result ------------
    # ----------------------------------------------

    # run.voids is the real-space search, whose per-halo outputs keep one
    # row per input halo, 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"Randoms drawn with seed {real.random_seed}")
    print(f"Halos left out of the second pass: {real.counts.tracers_uncorrected} uncorrected, "
          f"{real.counts.tracers_outside_grid} moved outside the grid")
    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. The redshift-space
    # files have zspace_ in their names: voids_zspace_box.dat and
    # divergence_zspace_box.dat, then voids_box.dat and divergence_box.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, "box.dat", zspace=True), zspace)
    bitvf.io.write_divergence(bitvf.io.file_name(product.DIVERGENCE, output, "box.dat", zspace=True), zspace)
    bitvf.io.write_voids(bitvf.io.file_name(product.VOIDS, output, "box.dat", zspace=False), real)
    bitvf.io.write_divergence(bitvf.io.file_name(product.DIVERGENCE, output, "box.dat", zspace=False), real)

    print("Written: output/voids_zspace_box.dat, output/divergence_zspace_box.dat, output/voids_box.dat, "
          "output/divergence_box.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 box
// =====================================================================

/*
  This example explains how to run the whole BitVF pipeline on a box
  catalogue observed in redshift space, in one call. The tracers are
  distorted along one Cartesian axis, the line of sight. The pipeline:

  1. reconstructs the displacement field of the redshift-space tracers
     by optimal transport (otswap);
  2. moves each tracer along the 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 the same randoms and
     seed;
  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 the correction leaves unmoved, or moves outside the grid, keep
  their row in every per-tracer output, flagged, and take no part in the
  second reconstruction.

  Usage: full_recons_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. The field
  example reads the divergence file it writes.
*/

#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 catalogue -------------
    // ----------------------------------------------------

    // Comoving Cartesian coordinates in Mpc/h, x, y, z for each halo, one
    // row after the other, in redshift space with the line of sight along y
    const std::vector<double> tracers = otswap::io::read(data + "/box_halos_redshift_space.dat",
                                                         {"0", "1", "2"}).values;

    std::cout << "Tracers: " << tracers.size() / 3 << std::endl;


    // --------------------------------------------------
    // ------------ Configure the pipeline --------------
    // --------------------------------------------------

    // The reconstruction, for both passes: 8 realizations, a convergence
    // threshold of 1e-2 and a fixed seed. No randoms are given, so bitvf
    // draws 8 per halo, uniformly in the box, from a seed derived from
    // this one (Result::randomSeed)
    bitvf::BoxConfig config;
    config.ot.nRealizations = 8;
    config.ot.convergence = 1.e-2;
    config.ot.seed = 12345;
    config.ot.log = &std::cout;

    // The halos fill a cube of side 400 Mpc/h, [269, 669) on each axis
    config.limits = otswap::BoxLimits{{269., 269., 269.}, {669., 669., 669.}};

    // The correction: the line of sight (axis 0, 1 or 2 for x, y or z),
    // the box's redshift, at which the growth rate is read from the
    // distance table below, and the tracers' linear bias. sigma is 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. zspaceVoids also searches the redshift-space pass
    bitvf::BoxRsd rsd;
    rsd.axis = 1;
    rsd.redshift = 1.;
    rsd.bias = 1.91255;
    rsd.sigma = 10.;
    rsd.correction.log = &std::cout;
    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 (see the field example)
    config.voids.keepDivergence = true;
    config.voids.verbosity = otswap::Verbosity::Detailed;
    config.voids.log = &std::cout;

    // The correction needs only the linear growth rate f at the box's
    // redshift. 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.);


    // ----------------------------------------------
    // ------------ Run the pipeline ----------------
    // ----------------------------------------------

    const bitvf::BitVFResult run = bitvf::runBox(tracers, {}, distances, config);


    // ----------------------------------------------
    // ------------ Summarize the result ------------
    // ----------------------------------------------

    // run.voids is the real-space search, whose per-halo outputs keep
    // one row per input halo, 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 << "Randoms drawn with seed " << *real.randomSeed << std::endl;
    std::cout << "Halos left out of the second pass: " << real.counts.tracersUncorrected << " uncorrected, "
              << real.counts.tracersOutsideGrid << " moved outside the grid" << 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. The redshift-space
    // files have zspace_ in their names: voids_zspace_box.dat and
    // divergence_zspace_box.dat, then voids_box.dat and divergence_box.dat
    using bitvf::io::Product;
    bitvf::io::writeVoids(bitvf::io::fileName(Product::Voids, output, "box.dat", true), zspace);
    bitvf::io::writeDivergence(bitvf::io::fileName(Product::Divergence, output, "box.dat", true), zspace);
    bitvf::io::writeVoids(bitvf::io::fileName(Product::Voids, output, "box.dat", false), real);
    bitvf::io::writeDivergence(bitvf::io::fileName(Product::Divergence, output, "box.dat", false), real);

    std::cout << "Written: output/voids_zspace_box.dat, output/divergence_zspace_box.dat, output/voids_box.dat, "
                 "output/divergence_box.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;
}

Field

Finds the voids of a field given at the centres of the cells of a box lattice, with no tracers, with bitvf::io::readField() and bitvf::findVoidsBoxFromField() (bitvf.io.read_field(), bitvf.find_voids_box_from_field()). The field is the divergence before smoothing, divergence, of the full reconstruction’s divergence file, smoothed more widely: the search smooths the field it reads, so the divergenceSmoothed column would be smoothed twice.

Reads examples/full_recons_box/output/divergence_box.dat, or the file given as argument in place of data_dir.

Writes output/voids_field.dat and output/overdense_basins_field.dat. examples/executable/field.ini runs the same search with the bitvf-field executable, on the divergence file of box.ini, 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 the voids of a field on a box lattice
# =================================================================

"""This example explains how to find voids in a field given at the centres of
the cells of a box lattice, with no tracers and no reconstruction: a density
contrast, a potential, or any field whose voids lie below 0. A field with
voids above 0 must be flipped first.

The field is read from a table with one row per cell, in any order; the
lattice, its cell side and its extent are inferred from the centres. The
field is smoothed, split by the same watershed as the void finder, and
catalogued: centres, radii, contact with the faces of the grid, and the field
at each centre. Densities, which need tracers, are not computed.

The input here is the divergence file written by the full_recons_box example:
a divergence file of bitvf is a valid field, with the cell centres, the
divergence before smoothing and the tracer weight of each cell. Searched with
the smoothing of the search that wrote it, it gives back that search's
basins; this example smooths it with a Gaussian of 15 Mpc/h instead, wider
than the 1 mps of that search, so that small voids merge into larger ones.

Usage: python field.py [field_file]. The field is read from field_file, by
default the divergence file of the full_recons_box example, which must then
be run first; the output is written to the folder output/ next to this file,
created if missing.
"""

import sys
from pathlib import Path

import bitvf


def main():

    # -------------------------------------------------------------
    # ------------ Locate the input and output folders ------------
    # -------------------------------------------------------------

    # The input is the divergence file of the full_recons_box example,
    # unless a first command-line argument replaces it
    here = Path(__file__).resolve().parent
    default = here.parent / "full_recons_box" / "output" / "divergence_box.dat"
    field_file = Path(sys.argv[1]) if len(sys.argv) > 1 else default
    output = here / "output"
    output.mkdir(parents=True, exist_ok=True)

    # -------------------------------------
    # ------------ Read the field ---------
    # -------------------------------------

    # The columns of the cell centres, in Mpc/h, of the field and of the
    # weight of each cell in the smoothing. Without a weight column every
    # cell weighs the same. The field is the divergence column, before
    # smoothing, not divergenceSmoothed: the search smooths the field it
    # reads, so the smoothed divergence would be smoothed twice
    field = bitvf.io.read_field(field_file, centres=["cellX", "cellY", "cellZ"], value="divergence", weight="weight")

    print(f"Cells: {len(field.values)}")

    # ---------------------------------------------
    # ------------ Find the voids -----------------
    # ---------------------------------------------

    # No mean particle separation is given, so sigma is in coordinate units,
    # here Mpc/h. "normal" prints one line with the lattice found
    config = bitvf.Config(smoothing=bitvf.Smoothing(sigma=15.0, unit=bitvf.LengthUnit.COORDINATE),
                          verbosity="normal")
    result = bitvf.find_voids_box_from_field(field.centres, field.values, config=config, weights=field.weights)

    # ----------------------------------------------
    # ------------ Summarize the result ------------
    # ----------------------------------------------

    # field_centre is the smoothed field at each void's centre, so the
    # deepest void has the lowest value
    voids = result.voids

    print(f"Voids: {voids.n_basins}")
    print(f"Largest void radius: {voids.radius.max():g} Mpc/h")
    print(f"Lowest field at a void centre: {min(voids.field_centre.min(), 0.0):g}")
    print(f"Overdense basins: {result.overdense.n_basins}")

    # ------------------------------------------
    # ------------ Write the output ------------
    # ------------------------------------------

    # The voids and the overdense basins, voids_field.dat and
    # overdense_basins_field.dat, with the column fieldCentre in place of
    # the densities. 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, "field.dat", zspace=False), result)
    bitvf.io.write_overdense(bitvf.io.file_name(product.OVERDENSE, output, "field.dat", zspace=False), result)

    print("Written: output/voids_field.dat, output/overdense_basins_field.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 field on a box lattice
// =================================================================

/*
  This example explains how to find voids in a field given at the
  centres of the cells of a box lattice, with no tracers and no
  reconstruction: a density contrast, a potential, or any field whose
  voids lie below 0. A field with voids above 0 must be flipped first.

  The field is read from a table with one row per cell, in any order;
  the lattice, its cell side and its extent are inferred from the
  centres. The field is smoothed, split by the same watershed as the
  void finder, and catalogued: centres, radii, contact with the faces
  of the grid, and the field at each centre. Densities, which need
  tracers, are not computed.

  The input here is the divergence file written by the full_recons_box
  example: a divergence file of bitvf is a valid field, with the cell
  centres, the divergence before smoothing and the tracer weight of
  each cell. Searched with the smoothing of the search that wrote it,
  it gives back that search's basins; this example smooths it with a
  Gaussian of 15 Mpc/h instead, wider than the 1 mps of that search, so
  that small voids merge into larger ones.

  Usage: field [field_file]. The field is read from field_file, by
  default the divergence file of the full_recons_box example, which must
  then be run first; 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_EXAMPLE_FIELD and BITVF_EXAMPLE_OUTPUT are set by this
    // example's CMakeLists.txt to the divergence file of the
    // full_recons_box example and to output/ next to this file. A first
    // command-line argument replaces the input file
    const std::string input = (argc > 1) ? argv[1] : BITVF_EXAMPLE_FIELD;
    const std::string output = BITVF_EXAMPLE_OUTPUT;
    std::filesystem::create_directories(output);


    // -------------------------------------
    // ------------ Read the field ---------
    // -------------------------------------

    // The columns of the cell centres, in Mpc/h, of the field and of the
    // weight of each cell in the smoothing. Without a weight column every
    // cell weighs the same. The field is the divergence column, before
    // smoothing, not divergenceSmoothed: the search smooths the field it
    // reads, so the smoothed divergence would be smoothed twice
    const bitvf::io::Field field = bitvf::io::readField(input, {"cellX", "cellY", "cellZ"}, "divergence", "weight");

    std::cout << "Cells: " << field.values.size() << std::endl;


    // ---------------------------------------------
    // ------------ Find the voids -----------------
    // ---------------------------------------------

    // No mean particle separation is given, so sigma is in coordinate
    // units, here Mpc/h. Normal prints one line with the lattice found
    bitvf::Config config;
    config.smoothing.sigma = 15.;
    config.smoothing.unit = bitvf::LengthUnit::Coordinate;
    config.verbosity = otswap::Verbosity::Normal;
    config.log = &std::cout;

    const bitvf::Result result = bitvf::findVoidsBoxFromField(field.centres, field.values, config, field.weights);


    // ----------------------------------------------
    // ------------ Summarize the result ------------
    // ----------------------------------------------

    // fieldCentre is the smoothed field at each void's centre, so the
    // deepest void has the lowest value
    const bitvf::BasinCatalog& voids = result.voids;
    double largest = 0., deepest = 0.;
    for (std::size_t b = 0; b < voids.nBasins; ++b) {
      largest = std::max(largest, voids.radius[b]);
      deepest = std::min(deepest, voids.fieldCentre[b]);
    }

    std::cout << "Voids: " << voids.nBasins << std::endl;
    std::cout << "Largest void radius: " << largest << " Mpc/h" << std::endl;
    std::cout << "Lowest field at a void centre: " << deepest << std::endl;
    std::cout << "Overdense basins: " << result.overdense.nBasins << std::endl;


    // ------------------------------------------
    // ------------ Write the output ------------
    // ------------------------------------------

    // The voids and the overdense basins, voids_field.dat and
    // overdense_basins_field.dat, with the column fieldCentre in place of
    // the densities
    using bitvf::io::Product;
    bitvf::io::writeVoids(bitvf::io::fileName(Product::Voids, output, "field.dat", false), result);
    bitvf::io::writeOverdense(bitvf::io::fileName(Product::Overdense, output, "field.dat", false), result);

    std::cout << "Written: output/voids_field.dat, output/overdense_basins_field.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;
}