Examples
Worked end-to-end examples of building and running workflows with the pipeliner CLI and Python API
This page provides worked end-to-end examples for building and running cryoEM processing workflows with ccpem-pipeliner. Each example shows both the CLI and Python API approaches where applicable, covering the full cycle from project creation through job execution, scheduling, cleanup, and archiving.
Before running any example:
- Python ≥ 3.9 installed (CI-tested on 3.10)
- ccpem-pipeliner installed via pip:
pip install ccpem-pipeliner - Verify the installation:
pipeliner.check_setup - A working directory that will serve as your project root. All paths in pipeliner are relative to this directory.
- External programs (RELION, CTFFIND4, etc.) are optional for project and API operations but required at job execution time. Missing executables cause jobs to load with
jobinfo.is_available=False; they can still be scheduled but will fail at runtime. - For MPI jobs: an MPI runtime (e.g. OpenMPI) on
PATH. - For queue submission: a cluster scheduler (SLURM, SGE, etc.) and a configured qsub template.
The two main ways to drive pipeliner are:
- CLI — use the
pipelinercommand with flag-based syntax for interactive and scripted headless use. - Python API — import
PipelinerProjectandapi_utilsfunctions to build fully automated scripts.
Create a project
CLI:
cd /path/to/project_root
pipeliner --new_project
This writes default_pipeline.star in the current directory. The optional argument names the pipeline (default: default).
API:
import os
os.chdir("/path/to/project_root")
from pipeliner.api.manage_project import PipelinerProject
proj = PipelinerProject(make_new_project=True)
PipelinerProject operates on the current working directory. It does not accept a path argument.
Discover available job types
pipeliner --available_jobs
pipeliner --available_jobs relion.motioncorr
Generate a default parameter file
# run.job format (human-readable, label == value)
pipeliner --default_runjob relion.import.movies
# Produces: relion_import_movies_run.job
# job.star format (STAR, for use with edit_jobstar)
pipeliner --default_jobstar relion.import.movies
# Produces: relion_import_movies_job.star
Run a job
pipeliner --run_job relion_import_movies_run.job
Continue an existing job
# Edit the job's continue_job.star first if you need to change parameters
pipeliner --continue_job Import/job001/
Check job status
Job status is recorded by sentinel files inside each job directory:
PIPELINER_JOB_EXIT_SUCCESS— succeededPIPELINER_JOB_EXIT_FAILED— failedPIPELINER_JOB_EXIT_ABORTED— aborted
Scheduled and running jobs have no exit file.
Manually set job status
pipeliner --set_status MotionCorr/job002/ success
Valid status values: success, failed, aborted, scheduled, running.
Suppress pipeliner log output in library code
import logging
pipeliner_logger = logging.getLogger("pipeliner")
pipeliner_logger.propagate = False
Example 1 — Create a new project (CLI)
Run from the directory where you want the project to live.
mkdir my_spa_project && cd my_spa_project
pipeliner --new_project
This writes default_pipeline.star and .CCPEM_pipeliner_project in the current directory.
Example 2 — Create a new project (Python API)
import os
os.makedirs("/data/projects/my_spa", exist_ok=True)
os.chdir("/data/projects/my_spa")
from pipeliner.api.manage_project import PipelinerProject
proj = PipelinerProject(
project_name="My SPA project",
description="Single particle analysis of apoferritin",
make_new_project=True,
)
Example 3 — Run a job from a dict
The cleanest way to run a single job programmatically. Use _rlnJobTypeLabel as the job-type key and real option key names.
import os
os.chdir("/data/projects/my_spa")
from pipeliner.api.manage_project import PipelinerProject
proj = PipelinerProject()
import_job = proj.run_job(
{
"_rlnJobTypeLabel": "relion.import.movies",
"fn_in_raw": "Movies/*.tif",
"kV": "300",
"Cs": "2.7",
"Q0": "0.1",
"angpix": "1.06",
"optics_group_name": "opticsGroup1",
"is_multiframe": "Yes",
},
run_in_foreground=True,
)
print(import_job.output_dir) # Import/job001/
Note:
run_in_foreground=Trueblocks until the job finishes. Do not combine it withdo_queue=Yes— that raisesValueError('Cannot wait for completion when submitting jobs to a queue').
Example 4 — Run a job from a generated parameter file
Useful when you want to inspect or manually tweak values before running.
import os
os.chdir("/data/projects/my_spa")
from pipeliner.api.manage_project import PipelinerProject
from pipeliner.api.api_utils import write_default_jobstar, edit_jobstar
proj = PipelinerProject()
# Generate a default job.star template
tmpl = write_default_jobstar("relion.import.movies")
# tmpl == 'relion_import_movies_job.star'
# Edit specific parameters (fn_template must be a job.star file)
edit_jobstar(
tmpl,
{
"fn_in_raw": "Movies/*.tif",
"kV": "300",
"angpix": "1.06",
"Q0": "0.1",
},
tmpl, # write back to the same file
)
import_job = proj.run_job(tmpl, run_in_foreground=True)
Note:
edit_jobstarrequires a job.star file asfn_template. Passing arun.jobfile raisesValueError('File <name> is not a valid STAR file. ...'); a STAR file that is not a job.star raisesValueError('File does not appear to be a valid job.star file').
Example 5 — Chain jobs: import → motion correction → CTF estimation
This is the canonical preprocessing pipeline. Each job's output feeds into the next as an input.
import os
os.chdir("/data/projects/my_spa")
from pipeliner.api.manage_project import PipelinerProject
from pipeliner.api.api_utils import (
write_default_jobstar,
edit_jobstar,
job_default_parameters_dict,
)
proj = PipelinerProject()
# --- Step 1: Import movies ---
import_params = job_default_parameters_dict("relion.import.movies")
import_params["fn_in_raw"] = "Movies/*.tif"
import_params["kV"] = "300"
import_params["Cs"] = "2.7"
import_params["Q0"] = "0.1"
import_params["angpix"] = "1.06"
import_job = proj.run_job(import_params, run_in_foreground=True)
# --- Step 2: Motion correction ---
mocorr_tmpl = write_default_jobstar("relion.motioncorr.own")
edit_jobstar(
mocorr_tmpl,
{
"input_star_mics": import_job.output_dir + "movies.star",
"dose_per_frame": "1.2",
"do_dose_weighting": "Yes",
},
mocorr_tmpl,
)
mocorr_job = proj.run_job(mocorr_tmpl, run_in_foreground=True)
# --- Step 3: CTF estimation ---
ctf_tmpl = write_default_jobstar("relion.ctffind.ctffind4")
edit_jobstar(
ctf_tmpl,
{
"input_star_mics": mocorr_job.output_dir + "corrected_micrographs.star",
# relion.motioncorr.own writes float16 micrographs by default, so CTFFIND
# must use the power spectra calculated by the MotionCorr job
"use_given_ps": "Yes",
},
ctf_tmpl,
)
ctf_job = proj.run_job(ctf_tmpl, run_in_foreground=True)
print("CTF job output:", ctf_job.output_dir)
Example 6 — Continue an existing job (CLI)
When a job has finished and you want to run more iterations or import more data:
# 1. Inspect which options can be changed
cat Import/job001/continue_job.star
# 2. Edit continue_job.star with your updated values, then:
pipeliner --continue_job Import/job001/
continue_job.staris a STAR job file (notrun.jobformat). Edit it withedit_jobstarin Python or a text editor, keeping the_rlnJobOptionVariable/_rlnJobOptionValuecolumn structure intact.
Example 7 — Continue an existing job (Python API)
For optimiser-based jobs (Class2D, Class3D, Refine3D, etc.) you must populate fn_cont before calling continue_job. Use get_continuation_job to have this done automatically.
import os
os.chdir("/data/projects/my_spa")
from pipeliner.api.manage_project import PipelinerProject
proj = PipelinerProject()
# get_continuation_job auto-populates fn_cont for optimiser-based jobs
cont_job = proj.get_continuation_job("Class2D/job004/")
cont_job.joboptions["nr_iter_em"].value = 50 # extend training
proj.run_job(cont_job, run_in_foreground=True)
For
relion.import.movies(which supports continuation without an optimiser file), you can callproj.continue_job("Import/job001/")directly after editingcontinue_job.star.
Example 8 — Overwrite an existing job
Replace a job with new parameters (same job type only). Downstream jobs must not have consumed this job's outputs.
# CLI: regenerate Import/job001 with new input files
pipeliner --run_job relion_import_movies_run.job --overwrite Import/job001/
# Python API
import os
os.chdir("/data/projects/my_spa")
from pipeliner.api.manage_project import PipelinerProject
from pipeliner.api.api_utils import job_default_parameters_dict
proj = PipelinerProject()
new_params = job_default_parameters_dict("relion.import.movies")
new_params["fn_in_raw"] = "Movies2/*.tif"
new_params["kV"] = "300"
new_params["angpix"] = "1.06"
new_params["Q0"] = "0.1"
proj.run_job(new_params, overwrite="Import/job001/", run_in_foreground=True)
overwriterequires a full job name such as'Import/job001/'. Short forms like'job001'or'1'are not resolved byrun_joband result in a new job being created instead.
Example 9 — Build a repeating on-the-fly schedule
Scheduling lets you register jobs without running them immediately, then run the whole set repeatedly. Placeholder files are created for all output nodes so subsequent jobs can reference them.
import os
os.chdir("/data/projects/my_spa")
from pipeliner.api.manage_project import PipelinerProject
from pipeliner.api.api_utils import write_default_jobstar, edit_jobstar
proj = PipelinerProject()
# Schedule import
import_tmpl = write_default_jobstar("relion.import.movies")
edit_jobstar(
import_tmpl,
{"fn_in_raw": "Movies/*.tif", "kV": "300", "angpix": "1.06", "Q0": "0.1"},
import_tmpl,
)
import_job = proj.schedule_job(import_tmpl)
# Schedule motion correction — use the placeholder output node path
mocorr_tmpl = write_default_jobstar("relion.motioncorr.own")
edit_jobstar(
mocorr_tmpl,
{"input_star_mics": import_job.output_dir + "movies.star",
"dose_per_frame": "1.2"},
mocorr_tmpl,
)
mocorr_job = proj.schedule_job(mocorr_tmpl)
# Run both jobs 10 times, waiting 5 seconds between jobs in each cycle
proj.run_schedule(
fn_sched="otf_preprocessing",
job_ids=[import_job.output_dir, mocorr_job.output_dir],
nr_repeat=10,
minutes_wait=1,
seconds_wait_after=5,
)
Equivalent CLI:
pipeliner --schedule_job relion_import_movies_job.star
pipeliner --schedule_job relion_motioncorr_own_job.star
pipeliner --run_schedule --name otf_preprocessing --jobs job001 job002 --nr_repeats 10 --min_between 1 --wait_sec_after 5
Example 10 — Wait for a job and then act on results
import os
os.chdir("/data/projects/my_spa")
from pipeliner.api.manage_project import PipelinerProject
from pipeliner.api.api_utils import job_default_parameters_dict
proj = PipelinerProject()
# Launch a 2D classification job in the background
class2d_params = job_default_parameters_dict("relion.class2d.em")
class2d_params["fn_img"] = "Extract/job005/particles.star"
class2d_params["nr_classes"] = "50"
class2d_job = proj.run_job(class2d_params) # returns immediately
# Block until it finishes (or times out after 12 hours)
final_status = proj.wait_for_job_to_finish(
class2d_job.output_dir,
ping=10.0,
timeout=43200.0,
error_on_fail=True,
)
print(final_status) # 'Succeeded' or 'Aborted' (a failed job raises RuntimeError because error_on_fail=True)
Example 11 — Set a job alias and status
import os
os.chdir("/data/projects/my_spa")
from pipeliner.api.manage_project import PipelinerProject
proj = PipelinerProject()
# Assign a human-readable alias
proj.set_alias("Class2D/job004/", "class2d_initial_round")
# Mark a failed job as succeeded so it can be continued
proj.update_job_status("Class2D/job004/", "Succeeded")
CLI equivalents:
pipeliner --set_alias "Class2D/job004/" class2d_initial_round
pipeliner --set_status Class2D/job004/ success
update_job_statusaccepts capitalized strings:'Succeeded','Failed','Aborted','Running','Scheduled'. The CLI--set_statusflag accepts lowercase substrings:success,failed,aborted,scheduled,running.
Example 12 — Clean up intermediate files
Cleanup moves removable files into Trash/Cleanup/ to save disk space.
# Clean one job
pipeliner --cleanup MotionCorr/job002/
# Harsh cleanup (removes more files)
pipeliner --cleanup MotionCorr/job002/ --harsh
# Clean all jobs
pipeliner --cleanup ALL
# Restore cleaned files for a specific job
pipeliner --restore_cleaned_files MotionCorr/job002/
import os
os.chdir("/data/projects/my_spa")
from pipeliner.api.manage_project import PipelinerProject
proj = PipelinerProject()
# run_cleanup requires FULL job names
proj.run_cleanup(["MotionCorr/job002/", "CtfFind/job003/"], harsh=False)
# Restore
proj.restore_from_cleanup("MotionCorr/job002/")
# Clean all
proj.cleanup_all(harsh=False)
# Permanently empty the trash (staticmethod — no confirmation in Python)
PipelinerProject.empty_trash()
Example 13 — Delete, undelete, and empty trash
# Move a job to Trash
pipeliner --delete_job Class2D/job004/
# Restore it
pipeliner --undelete_job Class2D/job004/
# Permanently delete trash contents (prompts Y/N in the CLI)
pipeliner --empty_trash
import os
os.chdir("/data/projects/my_spa")
from pipeliner.api.manage_project import PipelinerProject
proj = PipelinerProject()
proj.delete_job("Class2D/job004/") # returns bool
proj.undelete_job("Class2D/job004/") # returns bool
PipelinerProject.empty_trash() # staticmethod, returns bool
Example 14 — Archive a project
# Simple archive (directory structure + parameter files + replay script)
pipeliner --simple_archive Refine3D/job010/
# Full archive (all job output directories for the upstream chain)
pipeliner --full_archive Refine3D/job010/
import os
os.chdir("/data/projects/my_spa")
from pipeliner.api.manage_project import PipelinerProject
proj = PipelinerProject()
# Simple archive (full=False is the default)
archive_file = proj.create_archive("Refine3D/job010/", full=False, tar=True)
print(archive_file) # ProjectArchives/<YYYYMMDDhhmmss>_project_archive.tar.gz
# Full archive
full_archive_file = proj.create_archive("Refine3D/job010/", full=True, tar=True)
Example 15 — Generate reference and metadata reports
# Literature reference report up to a terminal job
pipeliner --references_report Refine3D/job010/
# JSON metadata report up to a terminal job
pipeliner --metadata_report Refine3D/job010/
import os
os.chdir("/data/projects/my_spa")
from pipeliner.api.manage_project import PipelinerProject
proj = PipelinerProject()
# Reference report
ref_file, n_jobs = proj.create_reference_report("Refine3D/job010/")
print(ref_file) # ReferenceReports/<datetime>_reference_report.json
print(n_jobs)
# Metadata report
md_file, n_jobs = proj.prepare_metadata_report(jobname="Refine3D/job010/")
print(md_file) # MetadataReports/<datetime>_metadata_report.json
Example 16 — Prepare an EMPIAR deposition
# Include all data types by default
pipeliner --empiar_deposition Refine3D/job010/
# Include only movies and micrographs
pipeliner --empiar_deposition Refine3D/job010/ --empiar_movies --empiar_mics
import os
os.chdir("/data/projects/my_spa")
from pipeliner.api.manage_project import PipelinerProject
output_path = PipelinerProject.prepare_project_empiar_deposition(
terminal_job="Refine3D/job010/",
empiar_do_mov=True,
empiar_do_mics=True,
empiar_do_parts=True,
empiar_do_rparts=True,
)
print(output_path) # EMPIAR/<datetime>_EMPIAR.json
Submission to EMPIAR must be done separately via the EMPIAR web interface.
Example 17 — Prepare a OneDep deposition
pipeliner --onedep_deposition \
--primary_map PostProcess/job012/postprocess.mrc \
--model ModelAngelo/job015/output.cif \
--halfmaps Refine3D/job010/run_half1_class001_unfil.mrc \
Refine3D/job010/run_half2_class001_unfil.mrc
import os
os.chdir("/data/projects/my_spa")
from pipeliner.api.manage_project import PipelinerProject
out_file, errors = PipelinerProject.prepare_project_onedep_deposition(
model="ModelAngelo/job015/output.cif",
primary_map="PostProcess/job012/postprocess.mrc",
halfmaps=[
"Refine3D/job010/run_half1_class001_unfil.mrc",
"Refine3D/job010/run_half2_class001_unfil.mrc",
],
depo_id="deposition",
)
if errors:
for e in errors:
print("Validation error:", e)
else:
print("Deposition files ready at:", out_file)
Example 18 — Recover a corrupted project
# Restore default_pipeline.star from per-job backups
pipeliner.recover_project
# Skip the confirmation prompt
pipeliner.recover_project --assume-yes
recover_projectrequires thatdefault_pipeline.staralready exists. If it is completely missing, the tool exits immediately and manual restoration is required.
Example 19 — Inspect a job type and list all available types
# Full info including references
pipeliner --job_info relion.motioncorr.own
# List all registered types
pipeliner --available_jobs
# Filtered list
pipeliner --available_jobs cryolo
# Check availability (programs on PATH)
pipeliner --check_jobs
from pipeliner.job_factory import get_job_types, new_job_of_type
# List all registered job types
all_jobs = get_job_types()
for j in all_jobs:
print(j.PROCESS_NAME, "| available:", j.jobinfo.is_available)
# Get a specific job and inspect it
job = new_job_of_type("relion.import.movies")
print(job.jobinfo.short_desc)
print(job.jobinfo.is_available)
if not job.jobinfo.is_available:
print(job.jobinfo.unavailable_message)
Example 20 — Write a custom job plugin
Create a new job type, package it, and register it under the ccpem_pipeliner.jobs entry-point group so pipeliner discovers it automatically.
my_package/my_job.py
from pipeliner.pipeliner_job import PipelinerJob, PipelinerCommand
from pipeliner.job_options import StringJobOption, IntJobOption
from typing import List
class MyCustomJob(PipelinerJob):
PROCESS_NAME = "mypkg.my_custom_job"
OUT_DIR = "MyCustomJob"
def __init__(self):
super().__init__()
self.jobinfo.short_desc = "A demonstration custom job"
self.jobinfo.long_desc = "Runs my_tool on input data."
self.joboptions["input_file"] = StringJobOption(
label="Input file:",
default_value="",
is_required=True,
)
self.joboptions["n_iterations"] = IntJobOption(
label="Number of iterations:",
default_value=10,
hard_min=1,
)
self.get_runtab_options()
def create_output_nodes(self):
from pipeliner.data_structure import NODE_PROCESSDATA
self.add_output_node("result.txt", NODE_PROCESSDATA, [])
def get_commands(self) -> List[PipelinerCommand]:
cmd = [
"my_tool",
"--input", self.joboptions["input_file"].get_string(),
"--n", self.joboptions["n_iterations"].get_string(),
"--output", self.output_dir,
]
return [PipelinerCommand(cmd)]
pyproject.toml (plugin package)
[project.entry-points."ccpem_pipeliner.jobs"]
"mypkg.my_custom_job" = "my_package.my_job:MyCustomJob"
After pip install -e . in the plugin package, pipeliner discovers the job automatically:
pipeliner --available_jobs mypkg
pipeliner --job_info mypkg.my_custom_job
The entry-point key must equal
MyCustomJob.PROCESS_NAMEexactly (mypkg.my_custom_job). Discovery happens each timeget_job_types()ornew_job_of_type()is called — there is no persistent registry.
FileNotFoundError: Could not find a project to open in directory ...
Symptom: PipelinerProject() raises FileNotFoundError when it is created.
Cause: The current working directory does not contain a default_pipeline.star or .CCPEM_pipeliner_project file.
Fix: cd to your project root before constructing PipelinerProject, or pass make_new_project=True to create one:
os.chdir("/path/to/project")
proj = PipelinerProject() # opens existing project
# or
proj = PipelinerProject(make_new_project=True) # creates new project
ValueError: Job type '<type>' not found
Symptom: run_job or job_from_dict raises this error when passing a dict.
Cause: The _rlnJobTypeLabel value is not a registered entry-point name, or the plugin package is not installed.
Fix: Use the exact registered process name (e.g. relion.import.movies, not ImportMovies or import_movies). Verify with:
pipeliner --available_jobs
If it is a plugin, confirm pip install succeeded and the entry-point group is ccpem_pipeliner.jobs.
ValueError: Parameter <name> is not found in jobtype <type>
Symptom: run_job with a dict raises this error.
Cause: A key in the parameters dict does not match any registered job option name for that job type.
Fix: Check the exact option key names with:
from pipeliner.api.api_utils import job_default_parameters_dict
print(list(job_default_parameters_dict("relion.import.movies").keys()))
For relion.import.movies, the input key is fn_in_raw, not fn_in_other or input_files.
ValueError: File <name> is not a valid STAR file. ... from edit_jobstar
Symptom: edit_jobstar raises this when called with a run.job file as fn_template.
Cause: edit_jobstar parses its first argument as a STAR job file. The run.job format (label == value lines) is incompatible.
Fix: Use write_default_jobstar (produces a .star file) as the template for edit_jobstar. Use write_default_runjob only for direct CLI use or manual editing:
tmpl = write_default_jobstar("relion.motioncorr.own") # correct
edit_jobstar(tmpl, {"input_star_mics": "Import/job001/movies.star"}, tmpl)
A value in an edited run.job file is ignored
Symptom: A job run from a manually edited run.job file uses the default value for an option instead of the value you set, and a warning like <file>; no value for `<label>` using default value: <default> is logged.
Cause: run.job lines are matched to job options by their label text. The label text on a run.job line was changed, so the line no longer matches the job's registered option label exactly and is ignored; that option keeps its default value.
Fix: Regenerate the file with pipeliner --default_runjob <jobtype> and only change the values (the part after ==), not the label text. For example:
Raw input files: == Movies/*.tif
not
Input files: == Movies/*.tif
ValueError('Cannot wait for completion when submitting jobs to a queue')
Symptom: Raised when calling run_job(..., run_in_foreground=True) on a job with do_queue set to Yes.
Cause: run_in_foreground=True is incompatible with queue submission.
Fix: Either remove run_in_foreground=True, or set do_queue to No in the job parameters before calling run_job.
ValueError: Job cannot be run because: ... with queue submission
Symptom: run_job raises this error before the job is created, followed by a line such as File <path> not found. No job directory is made.
Cause: Queue submission is enabled (do_queue=Yes) but the qsub_template setting is empty or points to a missing file.
Fix: Set the qsub_template path in ~/.config/ccpem/pipeliner/ccpem-pipeliner-settings.json (on Linux; ~/Library/Application Support/ccpem/pipeliner/ccpem-pipeliner-settings.json on macOS) or via the environment variable PIPELINER_QSUB_TEMPLATE. See the Configuration page for template format details.
pipeliner console scripts not found after install
Symptom: pipeliner.check_setup or pipeliner command not found.
Cause: Entry points were not registered correctly during installation.
Fix:
pip install --force-reinstall ccpem-pipeliner
pipeliner.check_setup
ValueError: ERROR: Could not initialize a new project ...
Symptom: pipeliner --new_project fails with this message.
Cause: A default_pipeline.star (or <name>_pipeline.star) already exists in the current directory.
Fix: Either work from the existing project (PipelinerProject() without make_new_project) or change to an empty directory.
Job loads but is marked unavailable
Symptom: job.jobinfo.is_available is False; job.jobinfo.unavailable_message explains a missing executable.
Cause: The required program (e.g. ctffind, MotionCor2) is not on the process PATH at the time the job object was created.
Fix: Add the program's directory to PIPELINER_ADDITIONAL_PROGRAM_PATHS before importing pipeliner, or source the appropriate environment script via PIPELINER_PATH_TO_SOURCE_FILES. Both take effect at import time. Alternatively, add the directory directly to PATH before starting Python.
Jobs with
is_available=Falsecan still be scheduled but will fail at execution time when the command cannot be found.