CCPEM Pipeliner
Guide

Writing a Job Plugin

Writing a new job type as a PipelinerJob subclass and registering it as an entry point


Overview

This page explains how to write a new job type for ccpem-pipeliner by subclassing PipelinerJob, and how to register it so that pipeliner discovers it automatically at startup. A job plugin is a self-contained Python class that declares its input parameters, generates commands to run, declares its output nodes, and optionally provides results displays and cleanup logic. Once registered under the ccpem_pipeliner.jobs entry-point group, your job appears alongside built-in jobs in the CLI and in the Doppio GUI without any changes to the core package.


Prerequisites

Before writing a job plugin you need:

  • Python 3.9 or later
  • ccpem-pipeliner installed in your development environment:
    pip install ccpem-pipeliner
    
  • A Python package with a pyproject.toml (or setup.cfg) that you control, so you can add entry-point declarations
  • Familiarity with Python packaging (setuptools build backend setuptools.build_meta)
  • The external program(s) your job will call must be discoverable via shutil.which on the machine where the job runs (required for availability checks; missing executables do not prevent the job from loading, but set jobinfo.is_available = False)

Installation
  1. Add ccpem-pipeliner as a dependency of your package in pyproject.toml:

    [project]
    dependencies = [
        "ccpem-pipeliner",
    ]
    
  2. Declare your job class under the ccpem_pipeliner.jobs entry-point group. The key must equal the PROCESS_NAME class attribute of your job class:

    [project.entry-points."ccpem_pipeliner.jobs"]
    "mypackage.myjob" = "mypackage.jobs.my_job:MyJob"
    
  3. Install your package (editable mode is convenient during development):

    pip install -e .
    
  4. Verify that pipeliner discovers your job:

    pipeliner --available_jobs mypackage
    

    If the job does not appear, reinstall with:

    pip install --force-reinstall ccpem-pipeliner
    pip install --force-reinstall -e .
    

    Then run pipeliner.check_setup to confirm console scripts and job availability.


Usage

Class skeleton

Every job must subclass PipelinerJob and declare two class-level attributes:

  • PROCESS_NAME — the exact string used as the entry-point key in pyproject.toml.
  • OUT_DIR — the top-level directory name under which all jobNNN/ subdirectories are created (also used to group jobs in the GUI).
from pipeliner.pipeliner_job import PipelinerJob, PipelinerCommand, Ref
from pipeliner.external_program_utils import ExternalProgram
from pipeliner.job_options import (
    StringJobOption,
    FloatJobOption,
    IntJobOption,
    BooleanJobOption,
    InputNodeJobOption,
    FileDescription,
)
from pipeliner.data_structure import NODE_DENSITYMAP
from pipeliner.display_tools import create_results_display_object

class MySomethingJob(PipelinerJob):
    PROCESS_NAME = "mysoftware.do_something"
    OUT_DIR = "MySomething"

    def __init__(self):
        super().__init__()  # always call super first
        ...

__init__: describe the job and define options

Populate self.jobinfo and self.joboptions inside __init__. Job options are stored in self.joboptions (a plain dict); values are assigned via the .value property.

    def __init__(self):
        super().__init__()

        # --- Job metadata ---
        self.jobinfo.display_name = "My Something Job"
        self.jobinfo.version = "0.1"
        self.jobinfo.job_author = "Your Name"
        self.jobinfo.short_desc = "Run mysoftware on a density map"
        self.jobinfo.long_desc = (
            "Longer description of what mysoftware does and when to use it."
        )
        self.jobinfo.documentation = "https://example.com/mysoftware"

        # ExternalProgram entries drive the is_available check.
        # If any executable cannot be found with `which`, the job loads
        # normally but jobinfo.is_available is False.
        self.jobinfo.programs = [
            ExternalProgram(command="mysoftware"),
        ]

        self.jobinfo.references = [
            Ref(
                authors=["Smith A", "Jones B"],
                title="MySoftware: a tool for doing something",
                journal="J. Struct. Biol.",
                year="2024",
                doi="10.1234/example",
            )
        ]

        # --- Job options ---
        # InputNodeJobOption for files that are part of the project
        self.joboptions["input_map"] = InputNodeJobOption(
            label="Input density map:",
            node_type=NODE_DENSITYMAP,
            default_value="",
            pattern=FileDescription("3D map", [".mrc"]),
            is_required=True,
        )

        self.joboptions["resolution"] = FloatJobOption(
            label="Resolution (Angstrom):",
            default_value=3.0,
            help_text="Target resolution for processing.",
        )

        self.joboptions["n_iter"] = IntJobOption(
            label="Number of iterations:",
            default_value=10,
        )

        # Adds do_queue, queuename, qsub, qsubscript, min_dedicated.
        # Pass mpi=True to also add nr_mpi and mpi_command.
        # Pass threads=True to also add nr_threads.
        self.get_runtab_options(mpi=False, threads=True)

Available JobOption subclasses:

TypePython typeGUI appearance
StringJobOptionstrText field
FloatJobOptionfloatNumber field
IntJobOptionintNumber field
BooleanJobOptionboolCheckbox
MultipleChoiceJobOptionstrDrop-down
InputNodeJobOptionstrFile browser (project files)
MultiInputNodeJobOptionList[str]Multi-file browser
ExternalFileJobOptionstrText field (external paths)
DirPathJobOptionstrDirectory path

create_output_nodes: declare expected outputs

This method is called before the job runs. Use self.add_output_node() to register each expected output file. Import node-type constants from pipeliner.data_structure.

    def create_output_nodes(self) -> None:
        self.add_output_node(
            "result.mrc",
            NODE_DENSITYMAP,
            ["mysoftware", "processed"],
        )

The file path passed to add_output_node is relative to self.output_dir — pipeliner prepends self.output_dir when registering the node in the pipeline graph.


get_commands: build the command list

get_commands is called in a separate process (and possibly on a different machine for queued jobs). It must:

  • Return quickly — no file I/O, no long computation.
  • Not write any files itself.
  • Reconstruct all state from self.joboptions alone.
  • Write output only inside self.output_dir.
    def get_commands(self) -> list:
        input_map = self.joboptions["input_map"].get_string()
        resolution = self.joboptions["resolution"].get_number()
        n_iter = self.joboptions["n_iter"].get_number()

        cmd = [
            "mysoftware",
            "--input", input_map,
            "--resolution", resolution,
            "--iterations", n_iter,
            "--output", self.output_dir,
        ]

        return [PipelinerCommand(cmd)]

Path rules:

  • All input and output paths must be relative to the project directory (the working directory when pipeliner runs jobs).
  • If your program insists on running from a specific directory, set self.working_dir = self.output_dir at the top of get_commands, then adjust all file paths with os.path.relpath(path, self.working_dir).
  • Absolute paths are permitted only for externally installed files (executables, queue templates, scratch disks) that are not tracked as pipeline nodes.

MPI: if you called get_runtab_options(mpi=True), prepend self.get_mpi_command() to your command list to actually run under MPI.


Optional: additional_joboption_validation

Return a list of JobOptionValidationResult objects to add cross-option validation beyond what individual JobOption objects check:

from pipeliner.job_options import JobOptionValidationResult

    def additional_joboption_validation(self) -> list:
        errors = []
        res = self.joboptions["resolution"].get_number()
        if res <= 0:
            errors.append(
                JobOptionValidationResult(
                    result_type="error",
                    raised_by=[self.joboptions["resolution"]],
                    message="Resolution must be greater than zero.",
                )
            )
        return errors

Optional: create_results_display

Return a list of ResultsDisplayObject instances. Use create_results_display_object(dobj_type, **kwargs) for safe construction — it returns a ResultsDisplayPending placeholder if anything goes wrong, preventing a failed display from crashing the job.

Valid dobj_type values include: 'mapmodel', 'image', 'graph', 'table', 'montage', 'histogram', 'html', 'pdffile', 'plotlyfigure', 'plotlyobj', 'plotlyhistogram', 'plotlyscatter', 'rvapi', 'text', 'textfile', 'json', 'gallery', 'carousel', and 'moorhen'.

from pipeliner.results_display_objects import ResultsDisplayObject

    def create_results_display(self) -> list:
        output_map = self.output_nodes[0].name  # first registered output
        display = create_results_display_object(
            "mapmodel",
            title="Result map",
            maps=[output_map],
            associated_data=[output_map],
        )
        return [display]

Optional: prepare_clean_up_lists

Return two lists — files to delete and directories to delete — for use by pipeliner --cleanup. Cleanup moves every listed path to Trash/Cleanup/ without checking that it exists, so a listed file or directory that is missing raises FileNotFoundError; only list paths that exist:

import os

    def prepare_clean_up_lists(
        self, do_harsh: bool = False
    ):
        files_to_delete = []
        dirs_to_delete = []

        # Always remove intermediate scratch files (if the job wrote any)
        scratch_file = os.path.join(self.output_dir, "scratch.tmp")
        if os.path.isfile(scratch_file):
            files_to_delete.append(scratch_file)

        if do_harsh:
            # Also remove large intermediates on harsh cleanup
            tmp_dir = os.path.join(self.output_dir, "tmp")
            if os.path.isdir(tmp_dir):
                dirs_to_delete.append(tmp_dir)

        return files_to_delete, dirs_to_delete

Supporting continuation

By default can_continue is False. To support continuation, set self.can_continue = True in __init__ and override continuation_joboption_updates() to modify job options for the continuation run.


Registering the entry point

The entry-point key in pyproject.toml must exactly equal PROCESS_NAME:

[project.entry-points."ccpem_pipeliner.jobs"]
"mysoftware.do_something" = "my_plugin.my_job:MySomethingJob"

After editing pyproject.toml, reinstall:

pip install -e ./my_plugin

Pipeliner performs entry-point lookup each time get_job_types() or new_job_of_type() is called — there is no persistent registry to flush.


Examples

Example 1 — Complete minimal job

A job that calls a hypothetical my_filter program, takes a density map as input, and writes a filtered map:

# mypackage/jobs/filter_job.py
import os
from typing import List

from pipeliner.pipeliner_job import PipelinerJob, PipelinerCommand, Ref
from pipeliner.external_program_utils import ExternalProgram
from pipeliner.job_options import InputNodeJobOption, FloatJobOption, FileDescription
from pipeliner.data_structure import NODE_DENSITYMAP

class MapFilterJob(PipelinerJob):
    PROCESS_NAME = "mypackage.filter_map"
    OUT_DIR = "MapFilter"

    def __init__(self):
        super().__init__()
        self.jobinfo.display_name = "Map filter"
        self.jobinfo.version = "0.1"
        self.jobinfo.short_desc = "Low-pass filter a density map"
        self.jobinfo.long_desc = "Applies a low-pass filter to an MRC density map."
        self.jobinfo.programs = [ExternalProgram(command="my_filter")]
        self.jobinfo.references = [
            Ref(
                authors=["Smith J"],
                title="A filtering method for cryo-EM maps",
                journal="J Struct Biol",
                year="2024",
                doi="10.0000/example",
            )
        ]

        self.joboptions["input_map"] = InputNodeJobOption(
            label="Input density map:",
            node_type=NODE_DENSITYMAP,
            default_value="",
            pattern=FileDescription("3D map", [".mrc"]),
            is_required=True,
        )
        self.joboptions["lowpass"] = FloatJobOption(
            label="Low-pass filter resolution (A):",
            default_value=10.0,
            help_text="Apply a low-pass filter at this resolution.",
        )
        self.get_runtab_options()

    def create_output_nodes(self) -> None:
        self.add_output_node("filtered_map.mrc", NODE_DENSITYMAP, ["filtered"])

    def get_commands(self) -> List[PipelinerCommand]:
        input_map = self.joboptions["input_map"].get_string()
        lowpass = self.joboptions["lowpass"].get_number()
        output_map = os.path.join(self.output_dir, "filtered_map.mrc")
        return [
            PipelinerCommand([
                "my_filter",
                "--input", input_map,
                "--lowpass", lowpass,
                "--output", output_map,
            ])
        ]

Example 2 — Entry-point registration in pyproject.toml

[build-system]
requires = ["setuptools>=61.0", "wheel"]
build-backend = "setuptools.build_meta"

[project]
name = "mypackage"
version = "0.1.0"
dependencies = ["ccpem-pipeliner"]

[project.entry-points."ccpem_pipeliner.jobs"]
"mypackage.filter_map" = "mypackage.jobs.filter_job:MapFilterJob"

After running pip install -e ., verify discovery:

pipeliner --available_jobs mypackage

Example 3 — Generate a default run.job file and inspect it

After installation, generate the default parameter file for your job:

pipeliner --default_runjob mypackage.filter_map

This writes mypackage_filter_map_run.job in the current directory (dots in the job type name are replaced with underscores, and _run.job is appended).


Example 4 — Checking availability from the Python API

from pipeliner.job_factory import new_job_of_type

job = new_job_of_type("mypackage.filter_map")
print(job.jobinfo.is_available)          # True if 'my_filter' is on PATH
print(job.jobinfo.unavailable_message)   # None if available

Example 5 — Running your job via the Python API

import os
from pipeliner.api.manage_project import PipelinerProject

os.chdir("/path/to/my/project")
proj = PipelinerProject(make_new_project=True)

job = proj.run_job(
    {
        "_rlnJobTypeLabel": "mypackage.filter_map",
        "input_map": "Import/job001/my_map.mrc",
        "lowpass": "8.0",
    },
    run_in_foreground=True,
)
print(job.output_dir)   # e.g. MapFilter/job002/

Note: job_from_dict() / run_job() parameter dicts are keyed by job option key (e.g. "lowpass"), not by the label string (e.g. "Low-pass filter resolution (A):"). All values must be strings.


Troubleshooting

Job does not appear in pipeliner --available_jobs

Symptom: Running pipeliner --available_jobs myorg returns no results.

Likely causes and fixes:

  • The plugin package was not installed (or was installed without the entry point). Run pip install -e . from your package root, then verify with pip show myplugin.
  • The entry-point group name is wrong. It must be exactly ccpem_pipeliner.jobs — check your pyproject.toml.
  • The entry-point key does not match PROCESS_NAME. Both must be identical strings (e.g., "myorg.myjob").
  • The console scripts for pipeliner itself were lost. Reinstall: pip install --force-reinstall ccpem-pipeliner, then pip install --force-reinstall -e ..

UnavailableJob appears instead of your class

Symptom: pipeliner --check_jobs myorg lists your job under the "Unavailable jobs" header by name only — an UnavailableJob has no programs, so the listing shows no reason (the logged traceback is printed above it) — or get_job_types() returns an UnavailableJob instance.

Likely cause: An exception was raised when Python imported your module or instantiated your class (e.g., an import error, a syntax error, or an exception in __init__). The exception is logged as Error loading job type '<name>', and its text is available as job.jobinfo.unavailable_message on the UnavailableJob returned by get_job_types().

Fix: Run python -c "from myplugin.jobs import MyJob; MyJob()" to see the traceback. Fix the import or initialisation error, then reinstall.

Note: if the job loads successfully but a required executable is missing from PATH, the job loads normally with jobinfo.is_available = False — it does not become an UnavailableJob.


An edited value in a run.job file is ignored

Symptom: pipeliner --run_job myorg_myjob_run.job runs, but a value you edited is not used and the option keeps its default.

Likely cause: You edited the run.job file and changed an option label. Lines are matched to options by label, and labels in run.job files must match the label= argument passed to each JobOption constructor exactly (including capitalisation, spaces, and trailing colon if present). A line whose label doesn't match is silently ignored: no error is raised, and a no value for ... using default value warning is logged for the option.

Fix: Regenerate the default file with pipeliner --default_runjob myorg.myjob and use those labels verbatim.


ValueError('Parameter <name> is not found in jobtype myorg.myjob') from the Python API

Symptom: proj.run_job({"_rlnJobTypeLabel": "myorg.myjob", "bad_key": 1}) raises this error.

Likely cause: The dict key does not match the key used in self.joboptions[...] inside __init__.

Fix: Use the exact string you passed as the dict key to self.joboptions (e.g., "input_map", not "Input map file:"). The label is for human display; the key is for programmatic access.


Job runs but writes files outside output_dir

Symptom: Output files appear in the project root or elsewhere, not in MyJob/jobNNN/.

Likely cause: Commands in get_commands use bare filenames without prefixing self.output_dir, or the working directory is unintentionally changed.

Fix: Prefix every output path with os.path.join(self.output_dir, "filename"). If the program cannot be redirected, set self.working_dir = self.output_dir at the start of get_commands and use os.path.relpath(input_path, self.working_dir) for input arguments.


get_commands is called but state set before schedule_job is lost

Symptom: Attributes set on the job object before scheduling are None or default-valued when commands run.

Cause: get_commands runs in a separate process (and possibly on a different machine for queued jobs). Instance state is not preserved across the process boundary.

Fix: Make get_commands reconstruct everything it needs from self.joboptions values alone. Never rely on attributes set after __init__.


Queue submission fails with Job cannot be run because: File <path> not found

Symptom: With queue submission enabled, run_job (or pipeliner --run_job) raises ValueError with this message and no job is created.

Likely cause: The qsubscript job option is empty or points to a queue template file that does not exist. Input files, including the template, are checked before the job is created.

Fix: Provide a valid queue submission template. If the template can no longer be read when an already-scheduled job is started with run_scheduled_job(), writing the submission script raises ValueError('Error reading template submission script in: <path>'); that job is marked Failed before any runner starts, and the caller receives RuntimeError('Error starting job <dir>') with that ValueError as its cause.