Skip to content

Integrate Hebog into a pipeline

This guide is for developers who call Hebog from a workflow such as a Prefect flow, a Dask graph or a batch script. It assumes no radio astronomy background. For the design behind these steps, read How Hebog distributes work.

Hebog is experimental. Pin an exact version and read capability and status before relying on it.

The contract in brief

result = hebog.find_sources(request, config, executor)
Argument or result What it is Safe to serialize
SourceFinderRequest Input path, output directory, run identifier yes
SourceFinderConfig Immutable scientific settings yes
executor Where work runs; owned by you no, create it in the calling process
SourceFinderResult Counts, timing, and a record of each product's path, size and SHA-256 yes

The call reads one FITS image, and an optional flat-noise companion, and publishes one directory of four files, or five with the companion's RMS. It holds no global state, starts no cluster and leaves no open files. Importing hebog does not import Dask.

1. Choose an executor

from hebog.executors import DaskExecutor, SerialExecutor, ThreadExecutor

# the reference, in one process
executor = SerialExecutor()
# one process, used as a context manager
executor = ThreadExecutor(thread_count=4)
# your existing dask.distributed client
executor = DaskExecutor(client, retry_limit=1)

All three produce the same products. Hebog never creates, resizes or closes your client. If find_sources is itself a task in your graph, give it a client through your framework's usual mechanism, or let that task start worker processes of its own (see below). Hebog's own tasks never start a cluster.

Optionally declare the budget Hebog may use. Without it, DaskExecutor reads the cluster's size again for each round, so workers that join while an analysis runs take its later rounds:

from hebog.executors import ExecutorCapacity

executor = DaskExecutor(
    client,
    capacity=ExecutorCapacity(
        worker_count=8,
        threads_per_worker=1,
        maximum_tasks_in_flight=16,
        memory_bytes_per_worker=32 * 1024**3,
    ),
)

The budget is also how many cores Hebog may use. Its task slots, workers times their threads but no more than maximum_tasks_in_flight, set the tiling and the batch sizes: when an image's 2,048-pixel tiles would leave a slot waiting, Hebog tiles it on 1,024-pixel cores instead, for images up to eleven such cores a side; wider images keep 2,048-pixel cores whatever the budget. The products do not change. State a budget smaller than the client's when other work holds some of its threads.

maximum_tasks_in_flight bounds how many tasks are submitted at once. Every Hebog task also declares the memory it holds, so Hebog narrows that bound until the tasks in flight fit memory_bytes_per_worker on worker_count workers, and refuses a task larger than one worker's memory before anything runs. A ThreadExecutor takes the same budget: ThreadExecutor(4, memory_bytes_per_worker=8 * 1024**3).

On a cluster, name Dask worker resources so that Dask itself keeps each worker within its memory:

dask worker tcp://scheduler:8786 --nthreads 4 --resources "memory=16e9,cores=4"
executor = DaskExecutor(client, memory_resource="memory", core_resource="cores")

Each task then requests its declared bytes of memory and its one thread of cores, and Dask starts it only on a worker with that much of both still free. The names are yours, so they can match resources your own tasks already request. Hebog reads the workers' amounts as its budget, and refuses to start when no worker declares them, since Dask would otherwise hold the tasks forever. Hebog does not pin tasks to workers.

Turn off Dask's own memory actions on the workers that run Hebog's tasks. By default Dask pauses a worker whose process holds more than 80% of its memory limit, counting memory the allocator keeps after a large task, and a paused worker starts no task, so the analysis can wait for good. Hebog's declared memory already keeps its tasks within the workers' limits, and its workers hold no data between tasks for Dask to spill. Set this before starting the workers:

export DASK_DISTRIBUTED__WORKER__MEMORY__TARGET=False
export DASK_DISTRIBUTED__WORKER__MEMORY__SPILL=False
export DASK_DISTRIBUTED__WORKER__MEMORY__PAUSE=False
export DASK_DISTRIBUTED__WORKER__MEMORY__TERMINATE=False

For a LocalCluster, set the same in dask.config before creating it:

import dask.config

dask.config.set(
    {
        f"distributed.worker.memory.{name}": False
        for name in ("target", "spill", "pause", "terminate")
    }
)

Reserve memory for the analysis itself too. In the process that calls it, find_sources holds Hebog's modules, the records every pass keeps for each source, budgeted at 44 KB each, and the background's noise grids, which grow with the pixels. hebog.analysis_memory_bytes states how much for the image's shape and an upper estimate of the source count, which hebog.expected_source_count makes from the image at your detection threshold, reading it in bounded blocks. A deconvolution model's component list is no such estimate: it holds many components for each source. When find_sources runs inside a Dask task, request it there:

from distributed import get_client

import hebog
from hebog.executors import DaskExecutor


def run_on_this_cluster(request, config):
    executor = DaskExecutor(
        get_client(), memory_resource="memory", core_resource="cores"
    )
    return hebog.find_sources(request, config, executor)


expected = hebog.expected_source_count(image_path, detection_threshold_sigma=5.0)
reserve = hebog.analysis_memory_bytes((20_000, 20_000), expected_sources=expected)
client.submit(
    run_on_this_cluster, request, config, resources={"memory": reserve, "cores": 1}
)

The analysis leaves its worker's thread pool while it waits on its tasks and rejoins it to continue, so several analyses cannot fill every thread and wait for good. Dask keeps a task's resources while it waits, so the analysis holds its one core and its tasks share the rest.

With a serial or thread executor the tasks run in the calling process, so reserve their admitted memory on top.

When find_sources runs as a task on a worker that holds a whole node's cores, as Rapthor's filter step does, that task can start worker processes for Hebog's tasks and close them when the finder returns. On four cores they took about half the time of a ThreadExecutor, whose threads share Python's interpreter lock, on every image measured, the smallest 2,048 pixels a side. Dask starts daemonic workers by default, and a daemonic process cannot start processes, so start the outer workers with DASK_DISTRIBUTED__WORKER__DAEMON=False, or with distributed.worker.daemon set to False in dask.config before creating a LocalCluster. Inside the task:

import dask.config
from distributed import Client, LocalCluster

import hebog
from hebog.executors import DaskExecutor


def run_finder(request, config, task_bytes, cores):
    """Analyse one image on worker processes this task starts."""
    share = task_bytes // cores
    memory_off = {
        f"distributed.worker.memory.{name}": False
        for name in ("target", "spill", "pause", "terminate")
    }
    with (
        dask.config.set(memory_off),
        LocalCluster(
            n_workers=cores,
            threads_per_worker=1,
            resources={"memory": share, "cores": 1},
            dashboard_address=None,
        ) as cluster,
        Client(cluster) as client,
    ):
        executor = DaskExecutor(
            client, memory_resource="memory", core_resource="cores"
        )
        return hebog.find_sources(request, config, executor)

Each worker process holds about 180 MiB of Python and Hebog's modules before it runs a task, which no task declares, so leave that out of task_bytes as well as the analysis reservation. Each worker's share must hold Hebog's largest task, up to about 1.7 GB on 2,048-pixel tile cores.

2. Put files where workers can reach them

Workers open the input image themselves and write intermediate Zarr planes beside the output directory. On a multi-node cluster, use absolute paths on storage that every worker can read and write. Set numerical-library thread counts (OMP_NUM_THREADS and similar) so that worker threads are not oversubscribed.

3. Treat the output directory as one atomic product

  • The output directory must not exist, unless it holds the finished products of the same request: the same run ID, inputs, configuration and Hebog science. Then find_sources returns them without analysing the image again, so a task retried after the finder returned resumes at once. For any other existing path Hebog raises SourceFinderOutputExistsError instead of overwriting.
  • Products are written to a private sibling directory, validated, and moved into place with one rename. A successful return, not the existence of the directory, means the products are ready.
  • After a failure the output directory is absent, so the same request can be retried. Use a new output_directory per attempt if your framework keeps failed attempts.
  • A failed run raises only once none of its tasks is still running, and leaves nothing beside the output. A killed process leaves its hidden staging directory; the next run to the same output removes it once that process has provably stopped, and reports every one it finds with a SourceFinderStagingWarning. A run to another output does not look, so if you retry under a new output_directory, remove a killed attempt's hidden directory yourself. Tasks a killed process left on your Dask cluster keep running; let them finish, or restart the workers, before retrying. See what a failed or killed run leaves.

4. Handle errors by type

Exception Meaning Typical response
InvalidSourceFinderInputError Missing, unreadable, truncated or malformed FITS input, including a header that lacks a unit, beam or frequency the request does not supply fix the file or supply the metadata, see the tutorial; do not retry unchanged
UnsupportedSourceFinderConfigurationError Readable file, but a unit other than Jy/beam, an unsupported coordinate frame, or a beam wider than 10 pixels convert or regrid the image; see the input header contract
SourceFinderImageTooLargeError Image exceeds a current size limit cut the image or wait for a later release
SourceFinderOutputExistsError Output directory exists and does not hold this request's finished products choose a new directory

All derive from SourceFinderError. An image with no detectable sources is not an error: it returns an empty catalogue.

5. Persist and verify results

Store the whole SourceFinderResult, not only the paths. Each product record carries its role, byte count, SHA-256 and schema version. Pass the record to a Hebog reader and it verifies these before parsing:

from hebog.io import read_catalogue_fits_product, read_diagnostics_product

catalogue = read_catalogue_fits_product(result.catalogue)
diagnostics = read_diagnostics_product(result.diagnostics)

Check scientific_status on each product. The RMS product is unavailable when the image had no usable noise estimate; downstream steps must not treat that as "no sources exist". See the integration checklist.

What Hebog does not do

Hebog analyses one image. Your pipeline remains responsible for:

  • scheduling, retries across tasks and resource admission;
  • combining several images, apart from a field's flat-noise image, whose RMS one run publishes beside the primary-beam-corrected image's products;
  • filtering or grouping an existing sky model with the mask; and
  • translating products into another tool's file names or column conventions.

For Rapthor, hebog.adapters.find_sector_sources writes Rapthor's file names and catalogue columns, and LSMTool's filter_sources filters and groups the sky model with the island mask; see the Rapthor source-finding contract. The guide to Rapthor's Hebog branch and its container show how to install and test source_finder = hebog on Rapthor's current single-task worker layout. On a step of several cores its Prefect task starts worker processes for Hebog's tasks, as above; it divides its memory with hebog.adapters.sector_memory and retains the PyBDSF fallback. Set hebog_dual_run = True to retain both filtered product sets and place their comparison in ordinary image diagnostics. The branch is not yet merged into Rapthor. The adapter and the branch's parset default to the continuum profile with a zero background, which passes the truth-based gate where compact does not; it is not a qualified Rapthor profile. Running Hebog's tasks on Rapthor's own client needs a later worker-layout change.

Versioning

Hebog makes no compatibility promise between 0.x releases. Output schemas are versioned and readers reject versions they do not support, so an upgrade fails loudly rather than misreading old files. Pin the version, read the release notes, and preserve quality flags you do not recognise.