job

Contents

job#

Defines the Job and External job classes for accessing CryoSPARC jobs.

Use cs.find_job() or project.find_job() to get a JobController instance for an existing job.

Use cs.create_job() or project.create_job() to create a new job and get a JobController instance for it.

Classes:

ExternalJobController

Scripting output job with customizable input slots and output results.

JobController

Accessor class to a job in CryoSPARC with ability to load inputs and outputs, add to job log, download job files.

Data:

GROUP_NAME_PATTERN

Regular expression for job input and output names.

class ExternalJobController#

Scripting output job with customizable input slots and output results. Use External jobs to save data save cryo-EM data generated by a software package outside of CryoSPARC.

External jobs may be connected to any other CryoSPARC job result as input. Its outputs must be created manually and may be configured to passthrough inherited input fields, just as with regular CryoSPARC jobs.

Create a new External Job with project.create_external_job(). or workspace.create_external_job(). ExternalJobController is a subclass of JobController and inherits all its methods and attributes.

Examples

Import multiple exposure groups into a single job

>>> from cryosparc.tools import CryoSPARC
>>> cs = CryoSPARC("http://localhost:61000")
>>> project = cs.find_project("P3")
>>> job = project.create_external_job("W3", title="Import Image Sets")
>>> job.start()
>>> for i in range(3):
...     dset = job.add_output(
...         type="exposure",
...         name=f"images_{i}",
...         slots=["movie_blob", "mscope_params", "gain_ref_blob"],
...         alloc=10  # allocate a dataset for this output with 10 rows
...     )
...     dset['movie_blob/path'] = ...  # populate dataset
...     job.save_output(output_name, dset)
...
>>> job.stop()

Methods:

__init__(cs, job)

add_input(type[, name, min, max, slots, ...])

Add or replace an External Job input.

add_output()

Add an output to the current job.

alloc_output(name[, alloc, dtype_params])

Allocate an empty dataset for a job output.

connect(target_input, source_job_uid, ...[, ...])

Connect a job input to another job's output.

run()

Set the job to running status within a context block (with job.run(): ...) and stop the job with completed status when the context ends.

save_output(name, dataset, *[, version, ...])

Save output dataset to External Job.

set_output_image(name, image, *[, savefig_kw])

Set the output image for an output, visible from the job's Outputs tab.

set_tile_image(image, *[, name, savefig_kw])

Set the job tile image, visible when viewing the job from a workspace.

start([status])

Set External Job status to "running" or "waiting".

stop([error])

Set External Job status to "completed" or "failed" if there was an error.

__init__(cs: CryoSPARC, job: Tuple[str, str] | Job) → None#
add_input(type: Literal['exposure', 'particle', 'template', 'volume', 'volume_multi', 'mask', 'live', 'ml_model', 'symmetry_candidate', 'flex_mesh', 'flex_model', 'hyperparameter', 'denoise_model', 'annotation_model'], name: str | None = None, min: int = 0, max: int | Literal['inf'] = 'inf', slots: Sequence[str | Slot | Datafield] = [], title: str | None = None, desc: str | None = None)#

Add or replace an External Job input. Connect the resulting input to outputs from other jobs with connect(). Load connected inputs with load_input().

Use to place External Jobs in the workspace job tree in the context where they apply, and to merge multiple sets of results of the same type from different outputs or jobs.

This action is available while the job is building, running or waiting for results. Completed or failed External jobs cannot accept new inputs.

Parameters:
  • type (Datatype) – cryo-EM data type for this input, e.g., “particle”

  • name (str, optional) – Input name key, e.g., “picked_particles”. Same as type if not specified. Defaults to None.

  • min (int, optional) – Minimum number of required input connections. Defaults to 0.

  • max (int | Literal["inf"], optional) – Maximum number of input connections. Specify "inf" for unlimited connections. Defaults to “inf”.

  • slots (list[SlotSpec], optional) – List of slots that should be connected to this input, such as "location" or "blob". When connecting the input, if the source job output is missing these slots, the external job cannot start or accept outputs. Defaults to [].

  • title (str, optional) – Human-readable title for this input. Defaults to name.

  • desc (str, optional) – Human-readable description for this input. Defaults to None.

Raises:
  • APIError – General CryoSPARC network access error such as timeout, URL or HTTP

  • InvalidSlotsError – slots argument is invalid

Returns:

name of created input

Return type:

str

Examples

Create an external job that accepts micrographs as input:

>>> cs = CryoSPARC("http://localhost:61000")
>>> project = cs.find_project("P3")
>>> job = project.create_external_job("W1", title="Custom Picker")
>>> job.uid
"J3"
>>> job.add_input(
...     type="exposure",
...     name="input_micrographs",
...     min=1,
...     slots=["micrograph_blob", "ctf"],
...     title="Input micrographs for picking
... )
"input_micrographs"
>>> job.connect("input_micrographs", "J1", "exposures")
>>> job.connect("input_micrographs", "J2", "exposures")
>>> input_micrographs = job.load_input("input_micrographs")
>>> input_micrographs
Dataset([  # 5000 items, 11 fields
    ("uid": [...]),
    ("micrograph_blob/path", ["...", ...]),
    ...
])
add_output(type: Literal['exposure', 'particle', 'template', 'volume', 'volume_multi', 'mask', 'live', 'ml_model', 'symmetry_candidate', 'flex_mesh', 'flex_model', 'hyperparameter', 'denoise_model', 'annotation_model'], name: str | None = None, slots: Sequence[str | Slot | Datafield] = [], passthrough: str | None = None, title: str | None = None) → str#
add_output(type: Literal['exposure', 'particle', 'template', 'volume', 'volume_multi', 'mask', 'live', 'ml_model', 'symmetry_candidate', 'flex_mesh', 'flex_model', 'hyperparameter', 'denoise_model', 'annotation_model'], name: str | None = None, slots: Sequence[str | Slot | Datafield] = [], passthrough: str | None = None, title: str | None = None, *, alloc: int | Dataset) → Dataset

Add an output to the current job. Optionally returns a corresponding empty dataset if alloc is specified.

Parameters:
  • type (Datatype) – cryo-EM datatype for this output, e.g., “particle”

  • name (str, optional) – Output name key, e.g., “selected_particles”. Same as type if not specified. Defaults to None.

  • slots (list[SlotSpec], optional) – List of slot expected to be created for this output, such as location or blob. Do not specify any slots that were passed through from an input unless those slots are modified in the output. Defaults to [].

  • passthrough (str, optional) – Indicates that this output inherits slots from an existing input with the specified name. The input must first be added with add_input(). Defaults to False.

  • title (str, optional) – Human-readable title for this input. Defaults to None.

  • alloc (int | Dataset, optional) – If specified, pre-allocate and return a dataset with the requested slots. Specify an integer to allocate a specific number of rows. Specify a Dataset from which to inherit unique row IDs (useful when adding passthrough outputs). Defaults to None.

Raises:
  • APIError – General CryoSPARC network access error such as timeout, URL or HTTP

  • InvalidSlotsError – slots argument is invalid

Returns:

Name of the created output. If alloc is

specified as an integer, instead returns blank dataset with the given size and random UIDs. If alloc is specified as a Dataset, returns blank dataset with the same UIDs.

Return type:

str | Dataset

Examples

Create and allocate an output for new particle picks

>>> cs = CryoSPARC("http://localhost:61000")
>>> project = cs.find_project("P3")
>>> job = project.find_external_job("J3")
>>> particles_dset = job.add_output(
...     type="particle",
...     name="picked_particles",
...     slots=["location", "pick_stats"],
...     alloc=10000
... )

Create an inheritied output for input micrographs

>>> job.add_output(
...     type="exposures",
...     name="picked_micrographs",
...     passthrough="input_micrographs",
...     title="Passthrough picked micrographs"
... )
"picked_micrographs"

Create an output with multiple slots of the same type

>>> job.add_output(
...     type="particle",
...     name="particle_alignments",
...     slots=[
...         {"name": "alignments_class_0", "dtype": "alignments3D", "required": True},
...         {"name": "alignments_class_1", "dtype": "alignments3D", "required": True},
...         {"name": "alignments_class_2", "dtype": "alignments3D", "required": True},
...     ]
... )
"particle_alignments"
alloc_output(name: str, alloc: int | ArrayLike | Dataset = 0, *, dtype_params: Dict[str, Any] = {}) → Dataset#

Allocate an empty dataset for a job output. Initialize with empty rows matching the given alloc argument. The result may be filled in and saved with save_output().

Parameters:
  • name (str) – Name of job output to allocate

  • size (int | ArrayLike | Dataset, optional) – Specify as one of the following: (A) integer to allocate a specific number of rows, (B) an array of numbers to use for uid column in the allocated dataset or (C) a dataset from which to inherit unique row IDs (useful for allocating passthrough outputs). Defaults to 0.

  • dtype_params (dict, optional) – Data type parameters when allocating results with dynamic column sizes such as particle -> alignments3D_multi. Defaults to {}.

Returns:

Empty dataset

Return type:

Dataset

Examples

Allocate a dataset of size 10,000 for an output for new particle picks

>>> cs = CryoSPARC("http://localhost:61000")
>>> project = cs.find_project("P3")
>>> job = project.find_external_job("J3")
>>> job.alloc_output("picked_particles", 10000)
Dataset([  # 10000 items, 11 fields
    ("uid": [...]),
    ("location/micrograph_path", ["", ...]),
    ...
])

Allocate a dataset from an existing input passthrough dataset

>>> input_micrographs = job.load_input("input_micrographs")
>>> job.alloc_output("picked_micrographs", input_micrographs)
Dataset([  # same "uid" field as input_micrographs
    ("uid": [...]),
])
connect(target_input: str, source_job_uid: str | JobController, source_output: str, *, slots: Sequence[str | Slot | Datafield] = [], title: str | None = None, desc: str | None = None, **kwargs) → bool#

Connect a job input to another job’s output. If the input does not exist, it is added with the provided slot specification (similar to calling add_input()).

Parameters:
  • target_input (str) – Input name to connect into. Will be created if does not already exist.

  • source_job_uid (str | JobController) – Job UID to connect from, e.g., “J42”

  • source_output (str) – Job output name to connect from , e.g., “particles”

  • slots (list[SlotSpec], optional) – List of input slots (e.g., “particle” or “blob”) to explicitly required for the created input. If the given source job is missing these slots, the external job cannot start or accept outputs. Defaults to [].

  • title (str, optional) – Human readable title for created input. Defaults to target input name.

  • desc (str, optional) – Human readable description for created input. Defaults to “”.

Raises:
  • APIError – General CryoSPARC network access error such as timeout, URL or HTTP

  • InvalidSlotsError – slots argument is invalid

Examples

Connect J3 to CTF-corrected micrographs from J2’s micrographs output.

>>> cs = CryoSPARC("http://localhost:61000")
>>> project = cs.find_project("P3")
>>> job = project.find_external_job("J3")
>>> job.connect("input_micrographs", "J2", "micrographs")
run()#

Set the job to running status within a context block (with job.run(): ...) and stop the job with completed status when the context ends. The job may accept outputs while within this block.

Errors raised within the block are added to the job’s Event log. The job is marked as failed if an error occurs.

Yields:

ExternalJob – self.

Examples

>>> with job.run():
...     job.save_output(...)
save_output(name: str, dataset: Dataset, *, version: int = 0, image: str | PurePath | IO[bytes] | Any | None = None, savefig_kw: dict = {'bbox_inches': 'tight', 'pad_inches': 0}, **kwargs)#

Save output dataset to External Job. Job must be running or waiting to accept outputs.

Parameters:
  • name (str) – Name of output on this job.

  • dataset (Dataset) – Value of output with only required fields.

  • version (int, optional) – Version number, when saving multiple intermediate iterations. Defaults to 0.

  • image (str | Path | IO | Figure, optional) – Optional image file or matplotlib Figure to set as the thumbnail for this output. Defaults to None.

  • savefig_kw (dict, optional) – Additional keyword arguments to pass to figure.savefig() when saving matplotlib Figures. Defaults to dict(bbox_inches="tight", pad_inches=0).

Examples

Save a previously-allocated output.

>>> cs = CryoSPARC("http://localhost:61000")
>>> project = cs.find_project("P3")
>>> job = project.find_external_job("J3")
>>> particles = job.alloc_output("picked_particles", 10000)
>>> job.save_output("picked_particles", particles)
set_output_image(name: str, image: str | PurePath | IO[bytes] | Any | GridFSAsset, *, savefig_kw: dict = {'bbox_inches': 'tight', 'pad_inches': 0})#

Set the output image for an output, visible from the job’s Outputs tab. Specify either an image file or matplotlib Figure.

Parameters:
  • name (str) – Name of output to set image for.

  • image (str | Path | IO | Figure) – Image file or matplotlib Figure.

set_tile_image(image: str | PurePath | IO[bytes] | Any | GridFSAsset, *, name: str = 'tile0', savefig_kw: dict = {'bbox_inches': 'tight', 'pad_inches': 0})#

Set the job tile image, visible when viewing the job from a workspace. Specify either an image file or a matplotlib Figure.

Parameters:

image (str | Path | IO | Figure) – Image file or matplotlib Figure.

start(status: Literal['running', 'waiting'] = 'waiting')#

Set External Job status to “running” or “waiting”. This allows the job to accept outputs.

Parameters:

status (str, optional) – “running” or “waiting”. Defaults to “waiting”.

stop(error: str = '')#

Set External Job status to “completed” or “failed” if there was an error. Jobs may no longer accept outputs after stopping.

Parameters:

error (str, optional) – Error message, will add to event log and set job to status to failed if specified. Defaults to “”.

FileOrFigure(*args, **kwargs)#

A file path, a file-like object, or a matplotlib figure.

alias of str | PurePath | IO[bytes] | Any

GROUP_NAME_PATTERN = '^[A-Za-z][0-9A-Za-z_]*$'#

Regular expression for job input and output names. May only contain Latin letters, numbers and underscores, and must start with a letter.

class JobController#

Accessor class to a job in CryoSPARC with ability to load inputs and outputs, add to job log, download job files. Should be initialized with cs.find_job() or project.find_job().

Parameters:

job (tuple[str, str] | Job) – either _(Project UID, Job UID)_ tuple or Job model, e.g. ("P3", "J42")

model#

All job data from the CryoSPARC database. Contents may change over time, use refresh() to update.

Type:

Job

Examples

Find an existing job.

>>> cs = CryoSPARC("http://localhost:61000")
>>> job = cs.find_job("P3", "J42")
>>> job.status
"building"

Queue a job.

>>> job.queue("worker_lane")
>>> job.status
"queued"

Create a 3-class ab-initio job connected to existing particles.

>>> job = cs.create_job("P3", "W1", "homo_abinit"
...     connections={"particles": ("J20", "particles_selected")}
...     params={"abinit_K": 3}
... )
>>> job.queue()
>>> job.status
"queued"

Attributes:

desc

Job description

dir

Full path to the job directory.

full_spec

The full specification for job inputs, outputs and parameters, as defined in the job register.

inputs

Input connection details.

outputs

Input result details.

params

Job parameter values object.

project_uid

Project unique ID, e.g., "P3"

status

Job scheduling status.

title

Job title

type

Job type key

uid

Job unique ID, e.g., "J42"

Methods:

__init__(cs, job)

clear(*[, descendants])

Clear the job's outputs and events to get it back to building status.

clear_param(param)

Reset a parameter to its default value.

clear_params()

Reset all job parameters.

clone([workspace])

Clone this job, creating a new building job with the same inputs and parameters but no outputs.

connect(target_input, source_job_uid, ...[, ...])

Connect a job input to another job's output.

connect_result(target_input, connection_idx, ...)

Connect a low-level input result slot to an output result from another (source) job.

cp(source_path[, target_path])

Copy a file or folder to the job directory.

delete(*[, wait])

Delete the job and all associated events and results.

disconnect(target_input[, connection_idx])

Disconnect a job input.

disconnect_result(target_input, ...)

Clear a job's low-level input result slot.

download(path)

Initiate a download request for a file in the job directory.

download_asset()

Download the job asset with the given ID from the database.

download_dataset(path)

Download a .cs dataset file from the job directory.

download_file()

Download file from the job directory to a target path or writeable file handle.

download_mrc(path)

Download a .mrc file from the job directory.

export()

Export the job to its project directory's exports subfolder.

find_events()

Find all events in the job log, optionally matching a type, pattern or checkpoint.

interact(action[, body, timeout, refresh])

Send a message to or perform an interactive action on a waiting interactive job.

kill()

Kill this job if running.

link_to_workspace(workspace)

Link the job to an additional workspace.

list_assets()

Find files available in the database for this job.

list_files([prefix, recursive])

List files in the job directory.

load_input(name[, slots])

Load the dataset connected to a job input.

load_output(name[, slots, version])

Load the dataset for a job output.

log()

Append to the job's event log.

log_checkpoint([meta])

Add a checkpoint to the job's event log.

log_plot(figure, text[, formats, raw_data, ...])

Add an event log with a figure.

mkdir(target_path[, parents, exist_ok])

Create a subfolder in the job directory.

move(from_workspace, to_workspace)

Move this job from one workspace to another.

print_input_spec()

Print a table of input keys, their title, type, connection requirements and details about their low-level required slots.

print_output_spec()

Print a table of output keys, their title, type and details about their low-level results.

print_param_spec()

Print a table of job-specific parameter keys, their title, type and default.

queue([lane, target, gpus, cluster_vars, ...])

Queue the job for execution.

refresh()

Reload this job from the CryoSPARC database.

restart()

Kill and clear a completed or partially-completed job, queue it with the same scheduler settings as its previous run.

set_description(desc)

Set job description.

set_final([final])

Mark or unmark the job as a final result.

set_param(name, value, **kwargs)

Set job parameter to a value.

set_params()

Update job parameters with the given values.

set_priority(priority)

Set job priority.

set_title(title)

Set job title.

subprocess(args, *[, mute, checkpoint, ...])

Launch a subprocess and write its text-based output and error to the event log.

symlink(source_path[, target_path])

Create a symbolic link in a project directory.

unlink_from_workspace(workspace)

Unlink the job from a workspace.

upload(target_path, source, *[, overwrite])

Upload a file to the job directory.

upload_dataset(target_path, dset, *[, ...])

Upload a dataset as a .cs file into the job directory.

upload_mrc(target_path, data, psize, *[, ...])

Upload a numpy 2D or 3D array to the job directory as an MRC file.

wait_for_done(*[, error_on_incomplete, timeout])

Wait until the job reaches status "completed", "killed" or "failed".

wait_for_status(status, *[, timeout])

Wait for the job's status to reach the specified value.

__init__(cs: CryoSPARC, job: Tuple[str, str] | Job) → None#
clear(*, descendants: bool = False)#

Clear the job’s outputs and events to get it back to building status. Launched, running or waiting jobs must be killed before clearing.

Retains input connections and parameter overrides.

Parameters:

descendants (bool, optional) – If True, also clear all descendant jobs. Defaults to False.

clear_param(param: str)#

Reset a parameter to its default value.

Parameters:

param (str) – Param name, a key in the job’s spec.params field.

Raises:

APIError – Invalid param name, or if job is not in “building” status.

clear_params()#

Reset all job parameters.

Raises:

APIError – If job is not in “building” status.

clone(workspace: str | WorkspaceController | None = None) → Self#

Clone this job, creating a new building job with the same inputs and parameters but no outputs. The new job may be queued with queue().

Parameters:

workspace (str | WorkspaceController, optional) – Target workspace to create the cloned job in. Can specify by name or UID, or with a WorkspaceController instance from project.find_workspace() or project.create_workspace(). If not specified, clones into the oldest workspace the original job is linked to. Defaults to None.

Returns:

Controller for the newly cloned job.

Return type:

JobController

connect(target_input: str, source_job_uid: str | JobController, source_output: str, *, connection_idx: int | None = None, **kwargs) → bool#

Connect a job input to another job’s output.

This action is available while the job is building. Only External jobs may be connected while running or waiting for results.

Parameters:
  • target_input (str) – Input name to connect into. Will be created if not specified.

  • source_job_uid (str | JobController) – Job to connect from, e.g., “J42”

  • source_output (str) – Job output name to connect from , e.g., “particles”

  • connection_idx (int, optional) – Replace the given connection index for this input, where 0 is the first connection, 1 is the second, etc. If not specified, appends a new connection. Defaults to None.

Returns:

False if the job encountered a build error.

Return type:

bool

Raises:

APIError – If job is not in “building” status.

Examples

Connect J3 to CTF-corrected micrographs from J2’s micrographs output.

>>> cs = CryoSPARC("http://localhost:61000")
>>> project = cs.find_project("P3")
>>> job = project.find_job("J3")
>>> job.connect("input_micrographs", "J2", "micrographs")
connect_result(target_input: str, connection_idx: int, slot: str, source_job_uid: str | JobController, source_output: str, source_result: str, source_version: int | Literal['F'] = 'F')#

Connect a low-level input result slot to an output result from another (source) job.

Parameters:
  • target_input (str) – Input name to connect into, e.g., “particles”

  • connection_idx (int) – Connection index to connect into, use 0 for the job’s first connection on that input, 1 for the second, etc.

  • slot (str) – Input slot name to connect into, e.g., “location”

  • source_job_uid (str | JobController) – Job to connect from, e.g., “J42”

  • source_output (str) – Job output name to connect from , e.g., “particles”

  • source_result (str) – Result name to connect from, e.g., “location”

Returns:

False if the job encountered a build error.

Return type:

bool

Examples

Connect J3 to the first connection of J2’s particles input. >>> cs = CryoSPARC(”http://localhost:61000”) >>> project = cs.find_project(“P3”) >>> job = project.find_job(“J3”) >>> job.connect_result(“particles”, 0, “location”, “J2”, “particles_selected”, “location”)

cp(source_path: str | PurePosixPath, target_path: str | PurePosixPath = '') → None#

Copy a file or folder to the job directory. May only copy files within the project directory or from paths the user is authorized to access by an administrator.

If copying to a remote CryoSPARC instance, the source path must be accessible on the server file system. If the source path is only available locally, use upload() instead.

Parameters:
  • source_path (str | Path) – Relative or absolute path of source file or folder to copy. If relative, assumed to be within the job directory.

  • target_path (str | Path, optional) – Name or path in the job directory to copy into. If not specified, uses the same file name as the source. Defaults to “”.

delete(*, wait: bool = False)#

Delete the job and all associated events and results.

A job cannot be deleted if it is in any of the following states:

  • Active (running or waiting); please kill the job first

  • Marked as final

  • Ancestor of a job marked as final

  • Has connected child jobs that are running, waiting, completed, killed or failed; please clear or delete all connected jobs first

Parameters:

wait (bool, optional) – If True, wait for the delete operations to complete before returning. Defaults to False.

Raises:
  • APIError – If the job fails to pass pre-delete checks, e.g., if it has active descendants

  • JobError – If the delete operation fails after waiting.

property desc: str#

Job description

property dir: PurePosixPath#

Full path to the job directory.

disconnect(target_input: str, connection_idx: int | None = None, **kwargs)#

Disconnect a job input.

Parameters:
  • target_input (str) – Name of input to disconnect

  • connection_idx (int, optional) – Connection index to clear. Set to 0 to remove the first connection, 1 for the second, etc. Set to -1 to remove the last connection, -2 for the second-last, etc. If unspecified, clears all input connections. Defaults to None.

disconnect_result(target_input: str, connection_idx: int, slot: str)#

Clear a job’s low-level input result slot.

Parameters:
  • target_input (str) – Name of input to disconnect

  • connection_idx (int) – Connection index to modify. Set to 0 to remove the first connection, 1 for the second, etc. Set to -1 to remove the last connection, -2 for the second-last, etc.

  • slot (str) – Input slot name to disconnect, e.g., “location”

Returns:

False if the job encountered a build error.

Return type:

bool

download(path: str | PurePosixPath)#

Initiate a download request for a file in the job directory. Use to get files from a remote CryoSPARC instance whose job directories are not available on the file system where this script runs.

Parameters:

path (str | Path) – Name or path of file in job directory.

Yields:

BinaryIteratorIO –

Use a context manager to read the file from the

request body.

Examples

Download a job’s metadata

>>> cs = CryoSPARC("http://localhost:61000")
>>> job = cs.find_job("P3", "J42")
>>> with job.download("job.json") as res:
>>>     job_data = json.loads(res.read())
download_asset(fileid: str, target: str | PurePath) → Path#
download_asset(fileid: str, target: IO[bytes]) → IO[bytes]

Download the job asset with the given ID from the database.

Parameters:
  • fileid (str) – GridFS file object ID

  • target (str | Path | IO) – Local file path or writeable file handle to write response data.

Returns:

resulting target path or file handle.

Return type:

Path | IO

download_dataset(path: str | PurePosixPath) → Dataset#

Download a .cs dataset file from the job directory.

Parameters:

path (str | Path) – Name or path of .cs file in job directory.

Returns:

Loaded dataset instance

Return type:

Dataset

download_file(path: str | PurePosixPath) → Path#
download_file(path: str | PurePosixPath, target: str | PurePath) → Path
download_file(path: str | PurePosixPath, target: IO[bytes]) → IO[bytes]

Download file from the job directory to a target path or writeable file handle.

Use to get files from a remote CryoSPARC instance whose job directories are not available on the file system where this script runs.

Parameters:
  • path (str | Path) – Name or path of file in job directory.

  • target (str | Path | IO) – Local file path, directory path or writeable file handle to write response data. If not specified, downloads to current working directory with a similar file name. Defaults to “”.

Returns:

resulting target path or file handle.

Return type:

Path | IO

download_mrc(path: str | PurePosixPath) → Tuple[mrc.Header, NDArray]#

Download a .mrc file from the job directory.

Parameters:

path (str | Path) – Name or path of .mrc file in job directory.

Returns:

MRC file header and data as a numpy array

Return type:

tuple[Header, NDArray]

export() → None#
export(*, wait: Literal[True], timeout: float = 300) → PurePosixPath

Export the job to its project directory’s exports subfolder.

Parameters:
  • wait (bool, optional) – If True, wait for the export to complete before returning. Defaults to False.

  • timeout (float, optional) – Maximum time to wait for the export to complete, in seconds. Only applies if wait is True. Defaults to 300.

Returns:

If waited, path to the exported job directory.

None if not waited. Path may be moved to another project for import.

Return type:

PurePosixPath | None

Raises:
  • JobError – If the job export could not be completed.

  • TimeoutError – If wait is True and the export does not complete within the specified timeout.

find_events(*, pattern: str | Pattern[str] | None = None, checkpoint: int | None = None) → Iterator[TextEvent | ImageEvent | InteractiveEvent]#
find_events(*, type: Literal['text', 'warning', 'error'], pattern: str | Pattern[str] | None = None, checkpoint: int | None = None) → Iterator[TextEvent]
find_events(*, type: Literal['image'], pattern: str | Pattern[str] | None = None, checkpoint: int | None = None) → Iterator[ImageEvent]
find_events(*, type: Literal['interactive'], pattern: str | Pattern[str] | None = None, checkpoint: int | None = None) → Iterator[InteractiveEvent]

Find all events in the job log, optionally matching a type, pattern or checkpoint.

Parameters:
  • pattern (str | Pattern, optional) – Regular expression to match against event text. If not specified, shows all events. Defaults to None.

  • type (Literal["text", "warning", "error", "image", "interactive"], optional) – If specified, only return events with the given log level. Defaults to None.

  • checkpoint (int, optional) – If specified, only return events logged after the given checkpoint. Specify 0 to show initial logs before the first checkpoint. Specify -1 to show logs after the last checkpoint. Defaults to None.

Yields:

TextEvent | ImageEvent | InteractiveEvent – Matching event log entry

property full_spec: JobRegisterJobSpec#

The full specification for job inputs, outputs and parameters, as defined in the job register.

property inputs: Dict[str, Input]#

Input connection details.

interact(action: str, body: Any = {}, *, timeout: int = 10, refresh: bool = False) → Any#

Send a message to or perform an interactive action on a waiting interactive job. Possible actions and expected body depend on the job type. See Custom Workflow.

Parameters:
  • action (str) – Interactive endpoint to call.

  • body (any) – Data to send to the interactive job endpoint. Must be JSON-encodable.

  • timeout (int, optional) – Maximum time to wait for action to complete, in seconds. Defaults to 10.

  • refresh (bool, optional) – If True, refresh the job model after posting. Defaults to False.

Returns:

Response from the interactive endpoint.

Return type:

any

kill()#

Kill this job if running.

Note

This function is not available for External Jobs. use job.stop() instead.

Link the job to an additional workspace.

Parameters:

workspace (str | WorkspaceController) – Target workspace to link this job to. Can specify by UID, or with a WorkspaceController instance from project.find_workspace() or project.create_workspace().

list_assets() → List[GridFSFile]#

Find files available in the database for this job. Returns a list with details about the assets.

Each entry is an object with an id key. Use id to download the file with download_asset().

Returns:

Asset details

Return type:

list[GridFSFile]

list_files(prefix: str | PurePosixPath = '', recursive: bool = False) → List[str]#

List files in the job directory.

Note that enabling recursive includes both subdirectories and their files in the list.

Parameters:
  • prefix (str | Path, optional) – Subfolder inside job to list. Defaults to “”.

  • recursive (bool, optional) – If True, include files in all subfolders. Defaults to False.

Returns:

List of file paths relative to the job directory.

Return type:

list[str]

load_input(name: str, slots: Literal['default', 'passthrough', 'all'] | List[str] = 'all')#

Load the dataset connected to a job input.

Parameters:
  • name (str) – Input name to load

  • slots (Literal["default", "passthrough", "all"] | list[str], optional) – List of specific slots to load, such as movie_blob or locations, or all slots if not specified (including passthrough). May also specify as keyword. Defaults to “all”.

Raises:

APIError – If the job doesn’t have the given input or the dataset cannot be loaded.

Returns:

Loaded dataset

Return type:

Dataset

load_output(name: str, slots: Literal['default', 'passthrough', 'all'] | List[str] = 'all', version: int | Literal['F'] = 'F')#

Load the dataset for a job output.

Parameters:
  • name (str) – Output name to load

  • slots (Literal["default", "passthrough", "all"] | list[str], optional) – List of specific slots to load, such as movie_blob or locations, or all slots if not specified (including passthrough). May also specify as keyword. Defaults to “all”.

  • version (int | Literal["F"], optional) – Specific output version to load. Use this to load the output at different stages of processing. Leave unspecified to load final verion. Defaults to “F”

Raises:

APIError – If job does not have any results for the given output, or the dataset cannot be loaded.

Returns:

Loaded dataset

Return type:

Dataset

log(text: str, *, level: Literal['text', 'warning', 'error'] = 'text') → str#
log(text: str, *, level: Literal['text', 'warning', 'error'] = 'text', name: str) → str
log(text: str, *, level: Literal['text', 'warning', 'error'] = 'text', id: str) → str

Append to the job’s event log. Update an existing log by providing a name or ID.

Parameters:
  • text (str) – Text to log

  • level (str, optional) – Log level (“text”, “warning” or “error”). Defaults to “text”.

  • name (str, optional) – Event name. If called multiple times with the same name, updates that event instead of creating a new one. Named events are reset when logging a checkpoint. Cannot be provided with id. Defaults to None.

  • id (str, optional) – Update a previously-created event log by its ID. Cannot be provided with name. Defaults to None.

Example

Log a warning message to the job log. >>> job.log(“This is a warning”, level=”warning”)

Show a live progress bar in the job log. >>> for pct in range(1, 10): … # example log: “Progress: [#####—–] 50%” … job.log(f”Progress: [{‘#’ * pct}{‘-’ * (10 - pct)}] {pct * 10}%”, name=”progress”) … sleep(1) … >>> job.log(“Done!”)

Update an existing log event by ID. >>> event_id = job.log(“Starting job processing…”) >>> # do some processing… >>> job.log(“Finished processing”, id=event_id)

Returns:

Created log event ID

Return type:

str

log_checkpoint(meta: dict = {})#

Add a checkpoint to the job’s event log. Also resets named events.

Parameters:

meta (dict, optional) – Additional meta information. Defaults to {}.

Returns:

Created checkpoint event ID

Return type:

str

log_plot(figure: str | PurePath | IO[bytes] | Any, text: str, formats: Iterable[Literal['pdf', 'gif', 'jpg', 'jpeg', 'png', 'svg']] = ['png', 'pdf'], raw_data: str | bytes | None = None, raw_data_file: str | PurePath | IO[bytes] | None = None, raw_data_format: Literal['txt', 'csv', 'html', 'json', 'xml', 'bild', 'bld', 'log'] | None = None, flags: List[str] = ['plots'], savefig_kw: dict = {'bbox_inches': 'tight', 'pad_inches': 0})#

Add an event log with a figure.

figure must be one of the following

  • Path to an existing image file in PNG, JPEG, GIF, SVG or PDF format

  • A file handle-like object with the binary data of an image

  • A matplotlib plot

If a matplotlib figure is specified, uploads the plots in png and pdf formats. Override the formats argument with formats=['<format1>', '<format2>', ...] to save in different image formats.

If a text-version of the given plot is available (e.g., in csv format), specify raw_data with the full contents or raw_data_file with a path or binary file handle pointing to the contents. Assumes file format from extension or raw_data_format. Defaults to "txt" if cannot be determined.

Parameters:
  • figure (str | Path | IO | Figure) – Image file path, file handle or matplotlib figure instance.

  • text (str) – Associated description for the figure

  • formats (list[ImageFormat], optional) – Image formats to save plot into. If a figure is a file handle, specify formats=['<format>'], where <format> is a valid image extension such as png or pdf. Assumes png if not specified. Defaults to [“png”, “pdf”].

  • raw_data (str | bytes, optional) – Raw text data for associated plot, generally in CSV, XML or JSON format. Cannot be specified with raw_data_file. Defaults to None.

  • raw_data_file (str | Path | IO, optional) – Path to raw text data. Cannot be specified with raw_data. Defaults to None.

  • raw_data_format (TextFormat, optional) – Format for raw text data. Defaults to None.

  • flags (list[str], optional) – Flags to use for UI rendering. Generally should not be specified. Defaults to [“plots”].

  • savefig_kw (dict, optional) – If a matplotlib figure is specified optionally specify keyword arguments for the savefig method. Defaults to dict(bbox_inches=”tight”, pad_inches=0).

Returns:

Created log event ID

Return type:

str

mkdir(target_path: str | PurePosixPath, parents: bool = False, exist_ok: bool = False) → None#

Create a subfolder in the job directory.

Parameters:
  • target_path (str | Path) – Name or path of folder to create inside the job directory.

  • parents (bool, optional) – If True, any missing parents are created as needed. Defaults to False.

  • exist_ok (bool, optional) – If True, does not raise an error for existing directories. Still raises if the target path is not a directory. Defaults to False.

move(from_workspace: str | WorkspaceController, to_workspace: str | WorkspaceController)#

Move this job from one workspace to another. Equivalent to linking to the new workspace and unlinking from the old one.

Parameters:
Raises:

APIError – If job cannot be moved.

property outputs: Dict[str, Output]#

Input result details.

property params: Params#

Job parameter values object.

Example

>>> cs = CryoSPARC(...)
>>> job = cs.find_job("P3", "J42")
>>> print(job.type)
"homo_abinit"
>>> print(job.params.abinit_K)
3
print_input_spec()#

Print a table of input keys, their title, type, connection requirements and details about their low-level required slots.

The “Required?” heading also shows the number of outputs that must be connected to the input for this job to run.

Examples

>>> cs = CryoSPARC("http://localhost:61000")
>>> job = cs.find_job("P3", "J42")
>>> job.type
'extract_micrographs_multi'
>>> job.print_output_spec()
Input       | Title       | Type     | Required? | Input Slots     | Slot Types      | Slot Required?
=====================================================================================================
micrographs | Micrographs | exposure | ✓ (1+)    | micrograph_blob | micrograph_blob | ✓
            |             |          |           | mscope_params   | mscope_params   | ✓
            |             |          |           | background_blob | stat_blob       | ✕
            |             |          |           | ctf             | ctf             | ✕
particles   | Particles   | particle | ✕ (0+)    | location        | location        | ✓
            |             |          |           | alignments2D    | alignments2D    | ✕
            |             |          |           | alignments3D    | alignments3D    | ✕
print_output_spec()#

Print a table of output keys, their title, type and details about their low-level results.

Examples

>>> cs = CryoSPARC("http://localhost:61000")
>>> job = cs.find_job("P3", "J42")
>>> job.type
'extract_micrographs_multi'
>>> job.print_output_spec()
Output                 | Title       | Type     | Result Slots           | Result Types    | Passthrough?
=========================================================================================================
micrographs            | Micrographs | exposure | micrograph_blob        | micrograph_blob | ✕
                       |             |          | micrograph_blob_non_dw | micrograph_blob | ✓
                       |             |          | background_blob        | stat_blob       | ✓
                       |             |          | ctf                    | ctf             | ✓
                       |             |          | ctf_stats              | ctf_stats       | ✓
                       |             |          | mscope_params          | mscope_params   | ✓
particles              | Particles   | particle | blob                   | blob            | ✕
                       |             |          | ctf                    | ctf             | ✕
print_param_spec()#

Print a table of job-specific parameter keys, their title, type and default.

Examples

>>> cs = CryoSPARC("http://localhost:61000")
>>> job = cs.find_job("P3", "J42")
>>> job.type
'extract_micrographs_multi'
>>> job.print_param_spec()
Param                       | Title                 | Type    | Default
=======================================================================
box_size_pix                | Extraction box size   | integer  | 256
bin_size_pix                | Fourier crop box size | integer  | None
compute_num_gpus            | Number of GPUs        | integer  | 1
...
project_uid: str#

Project unique ID, e.g., “P3”

queue(lane: str | None = None, target: str | None = None, gpus: List[int] = [], *, cluster_vars: Dict[str, Any] = {}, check_inputs_ready: bool = True, oversubscribe_gpus: bool = False, hostname: str | None = None)#

Queue the job for execution. Specify either lane or target, but exclude both for interactive jobs. One or more gpus options may be specified with target.

Queued jobs will launch when

  • all connected input jobs are completed

  • enough CPU/GPU/RAM is available on the lane or target

  • enough license tokens are available

Find available lanes with cs.get_lanes().

Find available targets with cs.get_targets().

Note

This function is not available for External Jobs. use job.start() / job.stop() or with job.run() instead.

Parameters:
  • lane (str, optional) – Connected scheduler lane to queue to. Defaults to None.

  • target (str, optional) – Specific worker hostname in compute lane, if more than one is available. Defaults to None.

  • gpus (list[int], optional) – GPU(s) to queue to. If specified, must have as many GPUs as required by job parameters. Leave unspecified to use first available GPU(s). Defaults to [].

  • cluster_vars (dict[str, Any], optional) – Specify custom cluster variables when queuing to a cluster. Keys are variable names. Defaults to {}.

  • check_inputs_ready (bool, optional) – If False, launch job without waiting for parent jobs to complete. Defaults to True.

  • oversubscribe_gpus (bool, optional) – If True, launch job even if target GPU(s) are already in use by another job. Defaults to False.

Examples

Queue a job to lane named “worker”:

>>> cs = CryoSPARC("http://localhost:61000")
>>> job = cs.find_job("P3", "J42")
>>> job.status
"building"
>>> job.queue("worker")
>>> job.status
"queued"
refresh()#

Reload this job from the CryoSPARC database.

Returns:

self

Return type:

JobController

restart()#

Kill and clear a completed or partially-completed job, queue it with the same scheduler settings as its previous run.

Retains input connections and parameter overrides.

set_description(desc: str)#

Set job description. May include Markdown formatting.

Parameters:

desc (str) – New job description

set_final(final: bool = True)#

Mark or unmark the job as a final result. Final jobs and their connected ancestors cannot be modified or deleted, and are protected during data cleanup.

Parameters:

final (bool, optional) – Set job’s final status. Defaults to True.

set_param(name: str, value: Any, **kwargs) → bool#

Set job parameter to a value.

Parameters:
  • name (str) – Param name, a key in the job’s spec.params field.

  • value (any) – Target parameter value.

Returns:

False if the job encountered a build error.

Return type:

bool

Raises:

APIError – Invalid param name or value, or if job is not in “building” status.

Examples

Set the number of GPUs used by a supported job

>>> cs = CryoSPARC("http://localhost:61000")
>>> job = cs.find_job("P3", "J42")
>>> job.set_param("compute_num_gpus", 4)
True
set_params(params: Dict[str, Any], /) → None#
set_params(**params: Any) → None

Update job parameters with the given values. Only parameters that are valid for the job type are updated.

Parameters:

params (dict[str, Any]) – Dictionary of param names and target values. May be specified as keyword arguments.

Raises:

APIError – Invalid param name or value, or if job is not in “building” status.

Examples

Set multiple parameters at once.

>>> cs = CryoSPARC("http://localhost:61000")
>>> job = cs.find_job("P3", "J42")
>>> job.set_params(compute_num_gpus=4, abinit_K=3)
>>> # or
>>> job.set_params({"compute_num_gpus": 4, "abinit_K": 3})
set_priority(priority: int)#

Set job priority. Once queued, higher priority jobs are scheduled before lower priority ones.

Parameters:

priority (int) – Larger number indicates higher priority.

set_title(title: str)#

Set job title.

Parameters:

title (str) – New job title

property status: Literal['building', 'queued', 'launched', 'started', 'running', 'waiting', 'completed', 'killed', 'failed']#

Job scheduling status.

subprocess(args: str | list, *, mute: bool = False, checkpoint: bool = False, checkpoint_line_pattern: str | Pattern[str] | None = None, **kwargs) → None#

Launch a subprocess and write its text-based output and error to the event log.

Parameters:
  • args (str | list) – Process arguments to run

  • mute (bool, optional) – If True, does not also forward process output to standard output. Defaults to False.

  • checkpoint (bool, optional) – If True, creates a checkpoint in the job event log just before process output begins. Defaults to False.

  • checkpoint_line_pattern (str | Pattern[str], optional) – Regular expression to match checkpoint lines for processes with a lot of output. If a process outputs a line that matches this pattern, a checkpoint is created in the event log before this line is forwarded. Defaults to None.

  • **kwargs – Additional keyword arguments for subprocess.Popen.

Raises:
  • TypeError – For invalid arguments

  • RuntimeError – If process exists with non-zero status code

Create a symbolic link in a project directory. May only create links to files or folders the user is authorized to access by an administrator.

Parameters:
  • source_path (str | Path) – Relative or absolute path of source file or folder to create a link to. If relative, assumed to be within the job directory.

  • target_path (str | Path) – Name or path of new symlink in the job directory. If not specified, creates link with the same file name as the source. Defaults to “”.

property title: str#

Job title

property type: str#

Job type key

uid: str#

Job unique ID, e.g., “J42”

Unlink the job from a workspace.

Parameters:

workspace (str | WorkspaceController) – Target workspace to unlink this job from. Can specify by UID, or with a WorkspaceController instance from project.find_workspace().

Raises:

APIError – If the job is not linked to the workspace, or if this is the only workspace the job is linked to.

upload(target_path: str | PurePosixPath, source: str | PurePath | IO | Buffer | Stream, *, overwrite: bool = False) → None#

Upload a file to the job directory.

Parameters:
  • target_path (str | Path) – Name or path of file to write in the job directory.

  • source (str | bytes | Path | IO) – Local path or file handle to upload. May also specified as raw bytes.

  • overwrite (bool, optional) – If True, overwrite existing files. If False, raises error on existing files. Defaults to False.

upload_dataset(target_path: str | PurePosixPath, dset: Dataset, *, format: int = 1, overwrite: bool = False) → None#

Upload a dataset as a .cs file into the job directory.

Parameters:
  • target_path (str | Path) – Name or path of dataset to save in the job directory. Should have a .cs extension.

  • dset (Dataset) – Dataset to save.

  • format (int) – Format to save in from cryosparc.dataset.*_FORMAT, defaults to NUMPY_FORMAT)

  • overwrite (bool, optional) – If True, overwrite existing files. If False, raises error on existing files. Defaults to False.

upload_mrc(target_path: str | PurePosixPath, data: NDArray, psize: float, *, overwrite: bool = False) → None#

Upload a numpy 2D or 3D array to the job directory as an MRC file.

Parameters:
  • target_path (str | Path) – Name or path of MRC file to save in the job directory. Should have a .mrc extension.

  • data (NDArray) – Numpy array with MRC file data.

  • psize (float) – Pixel size to include in MRC header.

  • overwrite (bool, optional) – If True, overwrite existing files. If False, raises error on existing files. Defaults to False.

wait_for_done(*, error_on_incomplete: bool = False, timeout: int | None = None) → str#

Wait until the job reaches status “completed”, “killed” or “failed”.

Parameters:
  • error_on_incomplete (bool, optional) – If True, raises an assertion error when job finishes with status other than “completed” or timeout is reached. Defaults to False.

  • timeout (int, optional) – If specified, wait at most this many seconds. Once timeout is reached, returns current status or fails if error_on_incomplete is True. Defaults to None.

wait_for_status(status: Literal['building', 'queued', 'launched', 'started', 'running', 'waiting', 'completed', 'killed', 'failed'] | Iterable[Literal['building', 'queued', 'launched', 'started', 'running', 'waiting', 'completed', 'killed', 'failed']], *, timeout: int | None = None) → str#

Wait for the job’s status to reach the specified value. Must be one of the following:

  • ‘building’

  • ‘queued’

  • ‘launched’

  • ‘started’

  • ‘running’

  • ‘waiting’

  • ‘completed’

  • ‘killed’

  • ‘failed’

Parameters:
  • status (str | set[str]) – Specific status or set of statuses to wait for. If a set of statuses is specified, waits util job reaches any of the specified statuses.

  • timeout (int, optional) – If specified, wait at most this many seconds. Once timeout is reached, returns current status. Defaults to None.

Returns:

current job status

Return type:

str

JobOutput(*args, **kwargs)#

Job output type alias for connecting jobs. Tuple of (job, output_name).

alias of Tuple[str | JobController, str]

LogLevel(*args, **kwargs)#

Severity level for job event logs.

alias of Literal[‘text’, ‘warning’, ‘error’]

OptPattern(*args, **kwargs)#

Optional pattern type alias for matching strings.

alias of str | Pattern[str] | None