CCPEM Pipeliner
API reference

Python API (PipelinerProject)

Driving projects from Python with PipelinerProject: running, scheduling and managing jobs, cleanup, reports and depositions


Description

PipelinerProject is the primary Python API class for driving a cryoEM processing project programmatically. Import it from pipeliner.api.manage_project and instantiate it in the project's working directory to create, open, run, schedule, manage, clean up, and report on jobs without using the command line. Use PipelinerProject whenever you need to script or automate multi-step pipelines, integrate pipeliner into larger facility workflows, or control job execution from Python rather than the pipeliner CLI.


Parameters

PipelinerProject.__init__ parameters

ParameterTypeRequiredDefaultDescription
pipeline_namestrNo'default'Name of the pipeline. The pipeline STAR file will be <pipeline_name>_pipeline.star. There is no good reason to change this from the default.
project_namestrNoNoneA short human-readable label for the project. If provided, overwrites the stored project name each time the project is opened.
descriptionstrNoNoneA longer description of the project. If provided, overwrites the stored description each time the project is opened.
make_new_projectboolNoFalseWhen True, creates a new empty project in the current directory if none is found. When False, raises FileNotFoundError if no existing project is detected.

Important: PipelinerProject operates on the current working directory. It does not accept a project_path argument. Change into your project directory before instantiating. It is also not a context manager — do not use it in a with statement.


Returns

PipelinerProject.__init__ returns None; it initialises the instance in place. The table below summarises the return types of the key methods you will call on the instance.

MethodReturn typeNotes
run_job(jobinput, overwrite, alias, ignore_invalid_joboptions, run_in_foreground)PipelinerJobThe job that was created and started. Defaults to run_in_foreground=False — job runs asynchronously.
schedule_job(job_input, comment, alias)PipelinerJobRegisters a job without running it. The returned PipelinerJob has an output_dir attribute but no name attribute.
run_scheduled_job(job, run_in_foreground)PipelinerJobStarts a previously scheduled job. Accepts a PipelinerJob instance (not a dict or file path).
continue_job(job_to_continue, comment, run_in_foreground)PipelinerJobContinues an existing succeeded job in its original directory.
schedule_continue_job(job_to_continue, params_dict, comments)PipelinerJobSchedules a continuation without running it.
get_continuation_job(job_name)PipelinerJobReturns a job prepared for continuation with options updated in memory; does not write continue_job.star.
get_job(job_name)PipelinerJobRetrieves an existing job by full name or full alias.
abort_job(job_name)NoneAborts a running job.
wait_for_job_to_finish(job, ping, timeout, error_on_fail, error_on_abort)strFinal job status: 'Succeeded', 'Failed', or 'Aborted'.
run_cleanup(jobs, harsh)boolTrue on success, False if any job is not found.
cleanup_all(harsh)NoneRuns cleanup on all jobs.
restore_from_cleanup(job)NoneRestores files from Trash/Cleanup/ back to the job directory.
delete_job(job)boolTrue on success, False on failure.
undelete_job(job)boolTrue on success, False on failure.
empty_trash()boolStatic method. True on success, False if Trash is already empty.
create_archive(job, full, tar)strArchive filename (with .tar.gz if tar=True), or '' if the terminal job is not found.
create_reference_report(terminal_job)Tuple[str, int](output_file_path, njobs) where the path is under ReferenceReports/.
prepare_metadata_report(jobname)Tuple[str, int](output_file_path, njobs), or ('', 0) if the job is not found.
parse_procname(in_proc, search_trash)strFull process name (e.g. 'MotionCorr/job002/') resolved from a short or full input.
run_schedule(fn_sched, job_ids, nr_repeat, minutes_wait, minutes_wait_before, seconds_wait_after)strThe schedule name (fn_sched).
stop_schedule(schedule_name)boolTrue on success, False on failure.
update_job_status(job, new_status)NoneUpdates status sentinel files.
compare_job_parameters(jobs_list)dictMaps each parameter to a list of its values across the jobs.
find_job_by_comment(contains, not_contains, job_type, command)List[str]Job names matching the criteria.
add_missing_nodes_from_all_jobs()List[str]Names of newly added nodes.
prepare_project_onedep_deposition(model, primary_map, additional_maps, sequences, masks, halfmaps, depo_id)Tuple[str, List[ValidationError]]Static method. Path to the prepared deposition file and any validation errors.
prepare_project_empiar_deposition(...)—Static method. Prepares EMPIAR deposition data.
set_alias(job, new_alias)NoneSets or clears an alias (None or '' clears it).
edit_comment(job_name, comment, overwrite)NoneAppends (or overwrites when overwrite=True) a comment on a job.

Errors
ErrorWhen it occurs
FileNotFoundErrorNo project is found in the current directory and make_new_project=False.
ValueErrorThe project marker (.CCPEM_pipeliner_project) exists but the expected pipeline file is absent. Raised by run_job when a dict-input job type is not found ("Job type '<type>' not found"), or when a parameter key is unknown ('Parameter <name> is not found in jobtype <type>'). Raised by run_job(..., run_in_foreground=True) when the job's do_queue is Yes ('Cannot wait for completion when submitting jobs to a queue'). Raised by run_job and continue_job when a file named in the job's options does not exist ('Job cannot be run because: ...'); when do_queue is Yes this includes an empty or missing queue submission template (qsubscript), and no job is created. Raised by update_job_status for invalid status strings (matching is case-sensitive), when the new status is the job's current status, or when a Running job is set to Aborted. Raised by get_continuation_job if the parent job status is not Succeeded. Raised by abort_job if the job name is not found. Raised by run_schedule if a schedule with that name is already running. Raised by find_job_by_comment if neither contains nor not_contains is provided. Raised by compare_job_parameters if a job is not found or jobs are of different types. Raised by edit_comment if comment is None.
NotImplementedErrorget_continuation_job is called on a job type whose can_continue is False (e.g. all CCP-EM model-building jobs, all relion.select.* jobs, relion.import, relion.import.coordinates, all relion.joinstar.* jobs).
RuntimeErrorabort_job is called on a job that is not currently Running. run_scheduled_job starts an already-scheduled job with queue submission enabled and its submission template (qsubscript) can no longer be read — the job is marked Failed and RuntimeError('Error starting job <dir>') is raised with ValueError('Error reading template submission script in: <path>') as its cause. wait_for_job_to_finish raises on timeout, or when error_on_fail=True/error_on_abort=True and the job ends in the corresponding status.
TypeErrorrun_schedule receives unexpected keyword arguments name= or jobs=.

Examples

Open an existing project and inspect a job

import os
from pipeliner.api.manage_project import PipelinerProject

os.chdir('/path/to/my/project')
proj = PipelinerProject()  # opens the existing default_pipeline.star
job = proj.get_job('MotionCorr/job002/')
print(job.output_dir)
print(job.jobinfo.is_available)

Create a new project and run a movie-import job programmatically

import os
from pipeliner.api.manage_project import PipelinerProject
from pipeliner.api.api_utils import job_default_parameters_dict

os.chdir('/path/to/project/directory')
proj = PipelinerProject(make_new_project=True)

# Build a parameter dict for the import job
params = job_default_parameters_dict('relion.import.movies')
params['fn_in_raw'] = 'Movies/*.tif'
params['kV'] = '300'
params['Cs'] = '2.7'
params['Q0'] = '0.1'
params['angpix'] = '0.885'

# Run the job and wait for it to finish
import_job = proj.run_job(params, run_in_foreground=True)
print(import_job.output_dir)  # e.g. 'Import/job001/'

Schedule a pipeline of dependent jobs and run them as a schedule

import os
from pipeliner.api.manage_project import PipelinerProject
from pipeliner.api.api_utils import job_default_parameters_dict

os.chdir('/path/to/project')
proj = PipelinerProject()

# Schedule motion correction
mc_params = job_default_parameters_dict('relion.motioncorr.own')
mc_params['input_star_mics'] = 'Import/job001/movies.star'
mc_job = proj.schedule_job(mc_params)

# Schedule CTF estimation on the motion-corrected output
ctf_params = job_default_parameters_dict('relion.ctffind.ctffind4')
ctf_params['input_star_mics'] = f'{mc_job.output_dir}corrected_micrographs.star'
# relion.motioncorr.own writes float16 micrographs by default, so CTFFIND must use
# the power spectra it saved; without this, schedule_job raises ValueError
ctf_params['use_given_ps'] = 'Yes'
ctf_job = proj.schedule_job(ctf_params)

# Run both jobs as an automated schedule
schedule_name = proj.run_schedule(
    fn_sched='my_schedule',
    job_ids=[mc_job.output_dir, ctf_job.output_dir],
    nr_repeat=1,
    seconds_wait_after=5,
)
print(schedule_name)

Notes

Working directory requirement. PipelinerProject always operates on the current working directory. Call os.chdir() before instantiation if the project is not in your current directory.

Not a context manager. Do not use with PipelinerProject(...) as proj:. Instantiate with proj = PipelinerProject(...) and call methods directly.

Creating versus opening projects. When make_new_project=False (the default), the constructor raises FileNotFoundError if neither a .CCPEM_pipeliner_project file nor a pipeline file is found. Pass make_new_project=True only when you intend to create a blank project. If a project or a pipeline file already exists, make_new_project=True has no effect: the constructor opens the existing project instead of creating a new one. If .CCPEM_pipeliner_project exists but its pipeline file is missing, the constructor raises ValueError even with make_new_project=True.

Existing RELION projects. To work with a project originally created by RELION, cd into the project directory and call PipelinerProject() without make_new_project=True. The --new_project CLI flag is not needed and will fail if a pipeline file already exists.

Method name resolution. Most PipelinerProject methods require full job names such as 'MotionCorr/job002/'. The trailing slash is optional for some methods (such as get_job(), run_cleanup(), update_job_status() and run_job(overwrite=...)) but required by others (such as create_archive(), prepare_metadata_report(), abort_job() and restore_from_cleanup()). Short forms like 'job002' or '2' are not resolved automatically by methods such as run_cleanup(), get_job(), or run_job(overwrite=...). Call parse_procname() first to resolve a short form to a full name. The CLI resolves short forms automatically via parse_proclist, but the Python API does not.

run_job versus schedule_job. run_job() creates a new job with a sequential number and launches it immediately (by default without waiting). schedule_job() registers a job without running it and returns a PipelinerJob instance. Use run_scheduled_job(job_instance) to execute a previously scheduled job. Never pass a PipelinerJob object to schedule_job() — it accepts only a parameters dict or a file path.

run_in_foreground and queue submission. run_in_foreground=True runs the job locally and blocks until completion. If the job has do_queue set to Yes, passing run_in_foreground=True raises ValueError('Cannot wait for completion when submitting jobs to a queue'). To run locally, set do_queue to No in the job parameters before calling run_job().

Overwriting a job. Pass overwrite='MotionCorr/job002/' (full name) to run_job() to delete and replace an existing job. Short forms are not resolved here; an unresolved name causes a new job to be created rather than the existing one to be overwritten.

Continuation jobs. For optimiser-based jobs (Class2D, Class3D, InitialModel, Refine3D, Multibody), continue_job() requires that fn_cont be set in the job's continue_job.star file before calling it. Only get_continuation_job() populates fn_cont automatically, and only for Class2D, Class3D, InitialModel and Refine3D jobs (not Multibody). It sets fn_cont on the job object it returns, which you then run with run_job(); it does not edit continue_job.star. get_continuation_job() raises NotImplementedError if the job type has can_continue=False, and ValueError if the job is not in Succeeded status.

Job numbers are project-wide. Jobs receive sequential numbers across all types (Import/job001, MotionCorr/job002, CtfFind/job003, …), not per-type numbering.

update_job_status versus set_status. update_job_status(job, new_status) accepts capitalised status strings: 'Succeeded', 'Failed', 'Aborted', 'Running', or 'Scheduled'. The CLI --set_status flag accepts lowercase substrings. A Running job cannot be set to Aborted via update_job_status; use abort_job() instead.

Archive filename. create_archive() returns a path named from the date and time it was created, like ProjectArchives/<YYYYMMDDhhmmss>_project_archive.tar.gz (with tar=False it is the archive directory, without .tar.gz). It returns '' if the terminal job is not found.

Reference reports directory. create_reference_report() writes output to ReferenceReports/.

EMPIAR deposition parameters. prepare_project_empiar_deposition() uses empiar_do_mov, empiar_do_mics, empiar_do_parts, and empiar_do_rparts boolean parameters, all True by default.

OneDep deposition. prepare_project_onedep_deposition() takes explicit file path arguments (model, primary_map, etc.) and returns Tuple[str, List[ValidationError]].

Settings and environment variables. PIPELINER_PATH_TO_SOURCE_FILES and PIPELINER_ADDITIONAL_PROGRAM_PATHS take effect when pipeliner is imported. Other settings such as queue_name, qsub_template, and qsub_command are re-read from environment variables on each getter call and can be changed at runtime without restarting.