Post-Production Workflow Guide

This guide explains how to write and run a pycWB post-production workflow. Post-production starts after search jobs have produced catalog and progress Parquet files. A workflow YAML then selects analysis subsets, matches simulation triggers to injection truth, trains or applies ranking models, builds FAR products, computes simulation efficiency, and writes report artifacts.

The main command is:

pycwb post-process path/to/postprocess_workflow.yaml

To inspect the dependency graph without running any action:

pycwb post-process path/to/postprocess_workflow.yaml --diagram-only

The user-facing template examples/postproduction/standard_analysis_10pct_workflow.yaml is a good starting point for a complete background, simulation, FAR, efficiency, and HTML-report workflow.

Terminal progress and detailed logs

Install the optional terminal display dependency:

pip install 'pycwb[terminal]'

The native CLI automatically uses a Rich dashboard when stdout and stderr are attached to an interactive terminal and Rich is installed. The vertical workflow uses step names from the YAML, marks pending, running, completed, resumed, failed and interrupted steps, and shows elapsed time and counts of finished and pending stages. A recent-output panel shows action output and INFO/warning/error messages. DEBUG logging from PycWB goes to the detailed file without filling the recent-output panel.

pycwb post-process workflow.yaml --log-file logs/postproduction.log

--log-file appends a UTF-8 plain-text log with the complete step plan, timestamped step transitions, stdout/stderr, PycWB DEBUG diagnostics and failure tracebacks. Relative log paths are relative to the shell’s current directory; missing parent directories are created. Terminal control sequences are removed from the log. The dashboard itself is never written into it. Without this option, no detailed log file is created.

Action messages focus on progress, aggregate event counts, scientific results, selected compute resources, and output locations. Per-batch column mappings, ranking-hook confirmations, feature add/remove messages, and raw parameter dumps are omitted. Training configuration remains available in the saved training settings when dump_training_review is enabled. Warnings, errors, and failure tracebacks are retained; performance JSONL records are independent of the terminal display.

The dashboard refreshes twice per second and retains only a bounded recent output buffer. Long workflows show a window around the active step; small terminals stack the workflow and output panels. Stage counts are not estimates of remaining computation time. Individual actions still execute sequentially with their existing output and resume behavior.

Use ordinary line-based progress for a batch job or a readable terminal stream:

pycwb post-process workflow.yaml --progress plain --log-file logs/postproduction.log

--progress auto is the CLI default. It falls back to plain output when redirected, when TERM=dumb, or when Rich is unavailable. --progress live explicitly requests Rich, including when terminal detection is unavailable; it fails with installation instructions if Rich is missing. These execution options do not affect --diagram-only.

On normal POSIX CLI sessions, capture includes C/C++ output and output inherited by synchronous child processes. With embedded Python streams (such as StringIO) or on other platforms, capture covers Python streams only. Capture and temporary logging configuration are process-wide and restored on completion, failure or interruption; use separate processes for concurrent workflows. PycWB imports that happen before workflow execution, such as initial ROOT startup, are outside this log’s scope. Failed actions still raise their original exception and the CLI exits unsuccessfully.

Python callers retain plain output by default and may opt in with run_workflow(..., progress="auto", log_file="logs/postproduction.log").

Resuming completed actions

Resume is enabled by default, including for direct calls to supported Python actions. A single hidden status record is saved beside the first essential output: model.ubj uses .model.ubj.status.json. The record is atomically marked running before execution, then complete after the action returns successfully, all essential outputs exist, and its result can be serialized. It stores the action and argument fingerprints, input/output paths, returned counts and other serializable metadata. When the same action runs again with unchanged settings, code and input/output paths, and all essential output files exist, it logs a warning and restores that result without recomputing. Later @step.path references and output_alias values work as usual.

Supported products include saved selections/splits, models, matched and scored catalogs, and reports with a complete file inventory. An action returning DataFrames, Arrow tables or other transient objects executes normally; no complete status is written for that result. Selection requesting in-memory intervals or triggers therefore continues to run. Existing products without a status record run once to establish one. Missing essential outputs, changed input/output paths or arguments, or a failed/interrupted action prevent reuse. A running record means completion was not confirmed; it can remain after failure, interruption, missing required outputs or an unsuccessful status write. Such a step executes again even when all output filenames exist. Outputs are written directly to their normal paths; only the status record uses an atomic temporary-file rename.

Existing <output>.resume.json completion records are still accepted. On successful reuse they are migrated to the hidden complete record without recomputing. A hidden status record takes precedence over any legacy record, including when the hidden record is incomplete or invalid.

Resume trusts pipeline artifacts at the same resolved paths: it ignores file contents, size, modification time, device and inode numbers, including metadata in older completion records. Input existence is not checked by the completion record; action-specific inventory resolvers may still inspect small manifests or catalog metadata to determine dependency paths. Use --no-resume when replacing data at an existing path and wanting to recompute its products.

The action’s module source is fingerprinted as well. This conservatively invalidates its actions after any edit to that module, but does not automatically track every imported helper or library version. Additional file dependencies are declared by each action’s resume contract; after changing an untracked dependency, force the affected actions to run again. INFO logs explain why a completion record was rejected (settings, implementation, inventory, file paths, or missing/invalid records and outputs).

import_cwb_root, process_background and compute_livetime retain their transient results and run normally. generate_waveform_report and training with dump: true also run normally because their complete output inventory depends on the data or executable configuration. Training with dump_training_review: true supports resume. Reports that intentionally produce no required plots, such as empty foreground reports or diagnostics for models without saved training history, run again.

To disable resume for a workflow or an individual step:

runtime:
  resume: false
steps:
  - id: split
    action: postprocess.selection.trigger_selection
    resume: true
    # inputs, args and outputs as usual

A step’s resume overrides runtime.resume; args.resume is also accepted when no step-level switch is supplied. To force the entire workflow to execute its actions, including steps with resume: true, use:

pycwb post-process workflow.yaml --no-resume

The equivalent Python switches are run_workflow(..., resume=False) and, for supported actions, action(..., resume=False). A successful forced run updates its completion record. Output collision protections still apply to merge actions; disabling resume does not authorize overwriting a merge label.

Catalog merging reuses its existing committed merge[.LABEL].json manifest instead of a new sidecar, validating the snapshot’s catalog, progress and simulation truth. A labeled partial merge is a frozen snapshot: it stays the same when workers produce more results. Use a new label to merge newer work. The original incomplete-run permission and metadata-checking requirements still apply when reusing a snapshot. Removing tmp:// outputs during cleanup also removes the ability to reuse those particular steps.

Standalone pycwb merge also accepts --no-resume. Merge resume reads the saved Parquet or HDF5 payloads to validate their integrity, so large merged products still incur sequential I/O without reprocessing worker fragments.

Performance for large catalogs

The waveform efficiency report counts inclusive background tails in Parquet batches for rare-event IFAR cuts, retaining only the values needed for the displayed threshold. It preserves ties and the injection denominator. Less restrictive cuts use the original single-column calculation. The background HTML summary retains compact numeric vectors for its global ranks and plots; event details are decoded only for the displayed rows. These report reductions still require memory proportional to the number of background events, but no longer retain every event ID and descriptive field.

Catalog selection writes bounded 65,536-row batches. For a training-only catalog, trigger_selection can take columns to read and write only explicitly required raw feature columns. Identity and physical-lag columns are retained automatically. Include every column required by downstream features, cuts and ranking hooks; projection is explicit and never inferred from a sample. Omit columns to retain the complete catalog schema. Projection requires trigger file outputs and cannot be combined with a trigger_filter expression. batch_size controls the row buffer, whose byte size depends on the catalog’s column types.

File-output interval splits automatically use DuckDB for supported plain progress schemas with integer membership keys. The split keeps the original source-order pandas exposure sums, seeded partition assignment, trigger order, Parquet payloads and catalog provenance. It reads compact numeric metadata and writes progress and trigger payloads in batches, avoiding a complete enriched progress DataFrame. Existing Python arguments, YAML settings and result fields are unchanged. Custom job filters, complex progress schemas and in-memory progress results use the existing selection path.

This path uses a private one-thread DuckDB connection with a 2 GB database memory limit. DuckDB may spill joins and sorts to a temporary directory on the trigger output filesystem; allow disk space there. The directory is removed when selection finishes or fails. Compact numeric metadata and other Python buffers still consume memory proportional to progress rows, so the database limit is not a limit on total process RAM.

For XGBoost training, read_batch_size: 65536 preprocesses projected raw columns in batches before concatenating compact float32 feature tables. It preserves file/row order, cleaning, caps, the configured random seed, balancing and the evaluation split. Cuts must be row-local: reductions such as rho0.mean() are rejected because computing them per batch changes the population. Clean matched simulations upstream when using this mode; the legacy matched_outer_file option uses the eager reader. Training still retains all compact features and the booster in memory; this is not out-of-core booster training. n_threads optionally sets the booster CPU allocation; verbose: 25 prints metrics every 25 rounds without changing the configured stopping rules or number of trees.

evaluate_far_rho supports an exact histogram accumulation path with batch_size: 65536, fixed vmin/vmax, positive bin_size and return_per_event: false. It scores bounded batches, streams the optional scored catalog, and sums integer bin counts. Bin edges, finite-value handling, prediction cuts, tail counts and exposure normalization follow the eager path. User ranking hooks must be row-local, as for score_catalog; hooks that normalize using the complete population must use the eager action. No complete-population sort is performed in histogram mode. Scored Parquet and JSON products are published after successful processing.

To record timings for each action, add:

runtime:
  profile_file: pp_logs/step_timings.jsonl

Each record contains elapsed seconds, completion/failure status and the process RSS at step exit. The RSS value is not a measurement of that step’s peak memory. Existing selected outputs do not imply workflow resumption; the runner still starts at the first action on each invocation.

For a compact multi-run study, see examples/postproduction/angle_error_comparison_workflow.yaml. It shows a generic three-action pattern: combine and reindex an array of catalogs, pass the combined data to interactive plot actions, then assemble every returned HTML plot in one generic report page. Each input needs only a generic name and catalog_file. The reader adds run_index and run_name columns and also reads scheduled injections from catalog job metadata, so an injection missed by the search is not lost from the denominator. Optional extra fields are retained as metadata, without prescribing which factor the study varies.

What The Workflow Consumes

A complete post-production workflow usually consumes these files:

Artifact

Typical path

Purpose

Background catalog

BKG/.../catalog/catalog.parquet

Trigger rows used for training, FAR holdout, and zero-lag scoring.

Background progress

BKG/.../catalog/progress.parquet

Job/livetime rows used for train/FAR splits and reports.

Simulation trigger catalog

SIM/.../catalog/catalog.parquet

Recovered simulation triggers.

Simulation progress

SIM/.../catalog/progress.parquet

Job metadata for selecting a simulation training subset.

Simulation summary

SIM/.../catalog/simulations.parquet

One row per injected signal, generated before post-production.

XGBoost config

XGB/.../xgb_config.py

Feature and ranking-statistic configuration.

Public alerts

public_alerts.txt

Optional known-event candidates for the background report.

For simulation studies, build simulations.parquet before running the workflow:

pycwb simulation-summary user_parameters.yaml \
  --work-dir /path/to/sim/run \
  --output /path/to/sim/run/catalog/simulations.parquet

You can also run matching as a standalone command, but complete workflows should prefer the explicit postprocess.matching.match_simulations action:

pycwb match-simulations catalog.parquet simulations.parquet \
  --how right --output matched_right.parquet

YAML Structure

A workflow has three top-level sections:

vars

User-editable values and reusable paths. Put run names, chunks, split fractions, output locations, and input file paths here.

runtime

Execution settings owned by the workflow runner, especially the temporary directory and cleanup policy.

steps

Ordered actions. Each step declares an id, human-readable name, action path, inputs, optional args, and outputs.

Minimal shape:

vars:
  work_dir: .
  paths:
    bkg_catalog: BKG/run/catalog/catalog.parquet

runtime:
  tmp_dir: ${work_dir}/tmp/postprod
  cleanup_tmp: never

steps:
  - id: example_step
    name: Example Step
    action: postprocess.selection.trigger_selection
    inputs:
      catalog_file: ${paths.bkg_catalog}
      progress_file: BKG/run/catalog/progress.parquet
    args:
      returns: [jobs, triggers, livetime]
    outputs:
      triggers_file: tmp://selected.parquet

Variables, References, And Temporary Files

Use ${...} to expand values from vars. Dotted paths are supported:

vars:
  work_dir: .
  chunks:
    train_bkg_1: K20
    train_bkg_2: K22
    target: K21
    tag: k20_k22_k21
  train_fraction_label: 10pct
  run:
    output_name: O4_${chunks.target}_run1
    analysis_slug: bkg_${chunks.tag}_${train_fraction_label}
  paths:
    output_dir: public/${run.output_name}
    model_file: ${paths.output_dir}/models/${run.analysis_slug}_xgb_model_blf.ubj

When an entire value is one variable reference, its YAML type is preserved. Use this to make structured action inputs explicit and reviewable rather than relying on values inherited implicitly from the workflow context:

vars:
  runs:
    - name: reference
      catalog_file: first/catalog.parquet
    - name: comparison
      catalog_file: second/catalog.parquet

steps:
  - id: read_runs
    action: postprocess.multi_run.read_catalog_runs
    inputs:
      runs: ${runs}  # remains a list, not a string

Use @step.path to read values returned by earlier steps:

catalog_file: "@k21_bkg_split.far.triggers_file"
livetime: "@k21_bkg_split.far.livetime.seconds"

Use tmp:// for intermediate files. The workflow runner resolves those paths under runtime.tmp_dir:

runtime:
  tmp_dir: ${work_dir}/tmp/${run.analysis_slug}

outputs:
  output_file: tmp://bkg_far_scored.parquet

Cleanup policies are:

never

Keep temporary files. This is best while developing or debugging.

on_success

Remove runtime.tmp_dir after a successful workflow.

always

Remove runtime.tmp_dir even if a later step fails.

Changing Chunks Or Fractions

For a chunk-swap workflow, keep the paths derived from a small set of values:

train_fraction_label: 10pct

chunks:
  train_bkg_1: K20
  train_bkg_2: K22
  target: K21
  tag: k20_k22_k21

run:
  output_name: O4_${chunks.target}_run1
  analysis_slug: bkg_${chunks.tag}_${train_fraction_label}

To use K23 instead of K22, update:

chunks:
  train_bkg_1: K20
  train_bkg_2: K23
  target: K21
  tag: k20_k23_k21

The derived catalog paths, temporary directory, model name, FAR JSON, plots, and report paths will update together.

If you change the training fraction, update all three values together:

k21_train_fraction: 0.3
k21_far_fraction: 0.7
train_fraction_label: 30pct

Common Actions

The actions below are the main building blocks used by the standard workflow. See Post-Production Action Reference for the complete registered-action catalog, exact signatures, and guidance on composing actions safely.

postprocess.selection.trigger_selection

Selects or splits trigger catalogs by jobs or intervals. Use it for BKG train/FAR splits, SIM training fractions, and full SIM evaluation selections.

postprocess.matching.match_simulations

Matches a trigger catalog to simulations.parquet. Use how: outer before SIM training filters and how: right for efficiency curves.

postprocess.selection.filter_real_simulation

Keeps recovered simulation triggers and optionally removes vetoed or across-segment injections.

postprocess.train_xgboost.train_xgboost

Trains the XGBoost ranking model from BKG and SIM catalog lists.

postprocess.evaluate.evaluate_far_rho

Scores the FAR holdout and writes the FAR-vs-ranking lookup.

postprocess.evaluate.score_catalog

Scores a catalog, commonly the target zero-lag background.

postprocess.evaluate.evaluate_efficiency

Scores simulation evaluation triggers and writes a scored catalog.

postprocess.plot_efficiency.compute_efficiency_vs_hrss_by_waveform

Builds waveform-level efficiency curves using a matched simulation table.

postprocess.report.standard_background_report

Writes the standard background plots, fake-open-box outputs, and zero-lag report products.

postprocess.evaluate.score_mdc_catalog

Scores MDC detections against a background IFAR threshold.

postprocess.report_builder.postproduction_report

Aggregates workflow artifacts into the final HTML and JSON report.

Validation And Debugging

Start with a diagram-only dry run:

pycwb post-process postprocess_workflow.yaml --diagram-only

Useful checks before a full run:

  • All ${...} variables resolve to the intended files.

  • Every @step.path reference points to an earlier step.

  • runtime.tmp_dir is unique for this analysis.

  • how: outer is used for SIM training matching.

  • how: right is used for SIM evaluation matching.

  • BKG selections use exclude_zero_lag: true.

  • SIM selections use exclude_zero_lag: false.

  • Report paths point to the same files produced by earlier steps.

Common failure modes:

Missing simulations.parquet

Run pycwb simulation-summary for the simulation production, then rerun post-production.

duckdb import error

Install the catalog matching dependency in the active environment.

Reference resolution error

Check that the producing step has an id and that the referenced key is returned by that action.

Unexpected train/FAR overlap

Use split.by: interval_livetime and make sure the input catalog carries job shift metadata.

Temporary file missing

Keep cleanup_tmp: never while debugging so intermediate parquet files remain inspectable.

Outputs To Expect

A complete workflow typically produces:

  • trained model under ${paths.output_dir}/models/;

  • XGBoost training settings and training output logs;

  • FAR JSON lookup table;

  • scored FAR and zero-lag background catalogs;

  • scored simulation evaluation catalog;

  • waveform efficiency plot and fit-parameter CSV;

  • background report plots;

  • optional MDC detection CSV;

  • final index.html and report_data.json.

Keep the workflow YAML with the report output. It records the exact inputs, fractions, seeds, matching modes, and artifact paths used for the analysis.

Reusable Report Presets

Page and figure defaults can live in YAML files alongside the workflow. A preset is expanded before workflow variables and action references are resolved; loading one never executes an action. For example, presets/background.yaml contains:

version: 1
parameters:
  frequency_column: central_freq_L1
  density_bins: [160, 120]
config:
  parameter_space:
    plots:
      rank_vs_frequency:
        x: ${preset.frequency_column}
        y: ${page.ranking_par}
        bins: ${preset.density_bins}

The corresponding report page supplies its campaign inputs:

- id: postproduction_report
  action: postprocess.report_builder.postproduction_report
  inputs:
    production_catalog_file: ${paths.target_bkg_catalog}
  args:
    bkg:
      preset: presets/background.yaml
      parameters:
        frequency_column: central_freq_H1
      scored_catalog: "@bkg_far_score.output_file"
      livetime: "@k21_bkg_split.far.livetime.seconds"
      ranking_par: rhor
      overrides:
        parameter_space:
          plots:
            rank_vs_frequency:
              bins: [200, 140]

parameters fills declared preset placeholders. A null default requires an explicit parameter. overrides changes the resulting configuration, including individual plots by name. Precedence is preset defaults, supplied parameters, explicit page fields, then overrides. Mappings merge recursively; lists replace whole lists. Whole-value substitutions retain their types. Normal ${...} workflow variables and @step.path references keep their existing meaning.

Named parameter_space.plots and parameter_plots mappings become ordered renderer lists. Plot groups and marginals may refer to the parameter-space plot names. Unknown parameter names, plot names and template references are errors. Presets use safe YAML and schema version 1. By default, preset paths are relative to the workflow’s real directory and must stay inside that directory. Multiple campaigns can instead share a preset directory using a top-level preset_root:

post-process/
  presets/
    background.yaml
  examples/
    O1_K01/
      workflow.yaml
    O2_K01/
      workflow.yaml

For either workflow in this layout:

preset_root: ../../presets
steps:
  - id: postproduction_report
    action: postprocess.report_builder.postproduction_report
    args:
      bkg:
        preset: background.yaml
        scored_catalog: "@bkg_far_score.output_file"
        ranking_par: rhor
        livetime: "@split.far.livetime.seconds"

preset_root must be a non-empty, literal relative path to an existing directory. It resolves from the workflow’s real directory regardless of the current working directory; workflow variables such as ${paths.presets} are not supported in this field. The declared root may be a sibling or ancestor directory outside the workflow directory. Every preset path must stay inside the selected root, including after resolving symbolic links. Absolute preset paths, paths escaping the root, recursive aliases and preset chains are rejected. Preset source records use paths relative to this root. Preserve the relative layout of the workflows, shared presets and any inputs/ maps when transferring them to another machine.

The runner supplies the current workflow_file to the final report when it is omitted. Reports package the original and expanded workflows, the exact loaded preset files and supplied waveform family maps under workflow_bundle/, with a SHA-256 manifest and download links. Preset input paths, expanded configuration and packaged output paths participate in report resume checks. Changes to expanded presentation arguments rebuild the affected reports while unchanged scientific actions retain their own resume records. Background selections, exposure and training results continue to flow through upstream actions; there is no saved-background configuration to fill in.

A complete K21 example, including background, training, standard-injection and optional CBC presets, is in examples/postproduction/k21_presets/. The CBC example plots injection coverage; it does not reinterpret HRSS curves as distance efficiencies.

Reusable configuration helpers

pycwb.post_production.presets.normalize_named_plots(config) converts named plot mappings and their group/marginal references into renderer lists. It works without preset files, modifies the supplied configuration in place, and returns that same mapping. Existing list-based layouts are unchanged.

Report code can reuse build_plot_card, plot_group_specs, build_plot_groups and validate_plot_columns from pycwb.modules.postprocess.report_context. They share artifact registration, layout validation and SVG download handling across report sections. pycwb.modules.postprocess.report_render.render_report_template renders bundled report templates with the same escaping and numerical-display filters.

pycwb.modules.postprocess.efficiency_metrics.parse_ifar_seconds is the shared parser for finite positive seconds or duration labels such as 100yr. Historical month presets remain 30 days.