project#
Defines Project class for accessing and managing CryoSPARC projects.
Use cs.find_project() to get
a ProjectController instance.
Classes:
Accessor instance for CryoSPARC projects with ability to add workspaces, jobs and upload/download project files. |
- class ProjectController#
Accessor instance for CryoSPARC projects with ability to add workspaces, jobs and upload/download project files. Should be initialized with
cs.find_project().- Parameters:
project (str | Project) – either Project UID or Project model, e.g.
"P3"
- model#
All project data from the CryoSPARC database. Contents may change over time, use
refresh()to update.- Type:
Attributes:
Project description
Full path to project directory.
Project title
Project unique ID, e.g., "P3"
Methods:
__init__(cs, project)accept([path])Accept a failed attach for this project.
archive(*[, wait])Archive this project.
attach(*[, wait])Attach an existing project directory to this instance.
clear_default_param(param)Clear a default parameter value for this project.
cp(source_path[, target_path])Copy a file or directory to the project directory.
create_external_job(workspace_uid[, title, desc])Add a new External job to this project to save computed outputs to.
create_job(workspace_uid, type[, ...])Add a new job with the given type to a workspace in the project.
create_workspace(title[, desc])Create a new empty workspace in this project.
delete(*[, wait])Start project deletion task.
detach(*[, wait])Detach this project from this CryoSPARC instance, removing its lock file.
download(path)Open a file in the project for reading.
download_dataset(path)Download a .cs dataset file from the given relative path in the project directory.
Download a file from the project directory to a target path or writeable file handle.
download_mrc(path)Download a .mrc file from the project directory.
find_external_job(job_uid)Get external job in this project by its unique ID.
find_job(job_uid)Get a job in the project by its unique ID.
find_jobs([workspace_uid, order])Search for jobs in the project.
find_workspace(workspace_uid)Find a workspace in the project by its unique ID.
find_workspaces(*[, order])Search for workspaces in the project.
import_job(workspace_uid, path, *[, wait])Import a job into a project workspace from a location on disk.
list_files([prefix, recursive])List files in the project directory.
mkdir(target_path[, parents, exist_ok])Create a subfolder in the project directory.
move(path, *[, wait])Move the project directory to a new location on the file system.
refresh()Reload this project from the CryoSPARC database.
save_external_result(workspace_uid, dataset, ...)Save a result dataset to the project, via External Job.
set_default_param(param, value)Set a default parameter value for this project.
set_description(desc)Set project description.
set_title(title)Set project title.
symlink(source_path[, target_path])Create a symbolic link in a project directory.
unarchive(path)Revert an archive operation.
upload(target_path, source, *[, overwrite])Upload a file to the project directory.
upload_dataset(target_path, dset, *[, ...])Upload a dataset as a .cs file into the project directory.
upload_mrc(target_path, data, psize, *[, ...])Upload a numpy 2D or 3D array to the project directory as an MRC file.
- accept(path: str | PurePosixPath | None = None) None#
Accept a failed attach for this project. Some job or workspace data may be inaccessible or lost after a failed attach, so use with caution.
Accepting a failed project will not fix any underlying issues with the project directory, such as missing files or corrupted data. Please ensure that the project is valid and complete before accepting. Instead of accepting a failed attach, consider investigating why the attach failed, then detach the project, fix the issue and re-attach.
- Parameters:
path (str | Path, optional) – If the project was moved, set a new project directory. Defaults to None.
- archive(*, wait: bool = False)#
Archive this project. Archived projects are hidden from the web UI. They cannot be modified and their jobs cannot run. Once archived, an admin may safely move the project directory to a long-term storage location.
Restore an archived project with
unarchive().- Parameters:
wait (bool, optional) – If False, waits for the archive operation to complete before returning. Defaults to False.
- attach(*, wait: bool = False)#
Attach an existing project directory to this instance.
The directory may not already be attached to any other CryoSPARC instance. A lock file will be created in the project directory to prevent it from being attached to multiple instances at the same time.
Project will not be available to modify until the attach process completes, which may take some time depending on the size of the project. Set
wait=Trueto block until the project is fully attached and available.Once attach completes, the project will be visible and modifiable in the web UI. The project is assigned a new unique ID upon attach.
- Parameters:
wait (bool, optional) – If True, wait for the attach operation to complete before returning. Defaults to False.
- Raises:
APIError – Project cannot be attached, e.g., if path does not exist or is already attached to another instance.
ProjectError – If attachment successfully starts but does fully complete due to invalid or corrupted data.
- clear_default_param(param: str)#
Clear a default parameter value for this project.
- Parameters:
param (str) – Name of the parameter to clear the default value for, e.g., “compute_num_gpus”.
- cp(source_path: str | PurePosixPath, target_path: str | PurePosixPath = '') None#
Copy a file or directory to the project 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 project directory.
target_path (str | Path, optional) – Name or path in the project directory to copy into. If not specified, uses the same file name as the source. Defaults to “”.
- create_external_job(workspace_uid: str, title: str = '', desc: str = '') ExternalJobController#
Add a new External job to this project to save computed outputs to.
- Parameters:
workspace_uid (str) – Workspace UID to create job in, e.g., “W3”.
title (str, optional) – Title for external job (recommended). Defaults to “”.
desc (str, optional) – Markdown description for external job. Defaults to “”.
- Returns:
created external job instance
- Return type:
ExternalJob
- create_job(workspace_uid: str, type: str, connections: Dict[str, Tuple[str | JobController, str] | List[Tuple[str | JobController, str]]] = {}, params: Dict[str, Any] = {}, title: str = '', desc: str = '') JobController#
Add a new job with the given type to a workspace in the project.
All available job types and associated metadata are available from
cs.job_register.- Parameters:
project_uid (str) – Project UID to create job in, e.g., “P3”
workspace_uid (str) – Workspace UID to create job in, e.g., “W1”
type (str) – Job type identifier, e.g., “homo_abinit”
connections (dict[str, tuple[str | JobController, str] | list[tuple[str | JobController, str]]]) – Initial input connections. Each key is an input name and each value is a (job, output name) tuple. Defaults to {}
params (dict[str, Any], optional) – Specify parameter values. Defaults to {}.
title (str, optional) – Job title. Defaults to “”.
desc (str, optional) –
Job Markdown description. Defaults to “”.
- Returns:
created job accessor object.
- Return type:
- Raises:
APIError – Job cannot be created.
Examples
Create an Import Movies job.
>>> from cryosparc.tools import CryoSPARC >>> cs = CryoSPARC("http://localhost:61000") >>> project = cs.find_project("P3") >>> import_job = project.create_job("W1", "import_movies") >>> import_job.set_param("blob_paths", "/bulk/data/t20s/*.tif") True
Create a 3-class ab-initio job connected to existing particles.
>>> abinit_job = project.create_job("W1", "homo_abinit" ... connections={"particles": ("J20", "particles_selected")} ... params={"abinit_K": 3} ... )
- create_workspace(title: str, desc: str | None = None) WorkspaceController#
Create a new empty workspace in this project.
- delete(*, wait: bool = False)#
Start project deletion task. Will delete the project, its full directory, all associated workspaces, sessions, jobs and results. Kills any running jobs or active sessions in the project before deleting.
The directory for an archived or detached project will not be deleted, but the project and all associated jobs will be fully removed from the web UI.
- Parameters:
wait (bool, optional) – If True, wait for the delete operation to complete before returning. Defaults to False.
- Raises:
ProjectError – If project could not be deleted. See cryosparcm log api for details.
- property desc: str#
Project description
- detach(*, wait: bool = False)#
Detach this project from this CryoSPARC instance, removing its lock file. Detached projects are not accessible from the web UI and may be attached to other instances.
See
cs.attach_project()to re-attach.- Parameters:
wait (bool, optional) – If True, wait for the detach operation to complete before returning. Defaults to False.
- property dir: PurePosixPath#
Full path to project directory.
- download(path: str | PurePosixPath)#
Open a file in the project for reading. Use to get files from a remote CryoSPARC instance whose project directories are not available on the file system where this script runs.
- Parameters:
path (str | Path) – Name or path of file in project directory.
- Yields:
BinaryIteratorIO –
- Use a context manager to read the file from the
request body.
Examples
Download a project’s metadata
>>> cs = CryoSPARC("http://localhost:61000") >>> project = cs.find_project("P3") >>> with project.download("project.json") as res: >>> project_data = json.loads(res.read())
- download_dataset(path: str | PurePosixPath) Dataset#
Download a .cs dataset file from the given relative path in the project directory.
- Parameters:
path (str | Path) – Name or path to .cs file in project directory.
- Returns:
Loaded dataset instance
- Return type:
- 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 a file from the project directory to a target path or writeable file handle.
Use to get files from a remote CryoSPARC instance whose project directories are not available on the file system where this script runs.
- Parameters:
path (str | Path) – Name or path of file in project directory.
target (str | Path | IO, optional) – 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 project directory.
- Parameters:
path (str | Path) – Name or path to .mrc file in project directory.
- Returns:
MRC file header and data as a numpy array
- Return type:
tuple[Header, NDArray]
- find_external_job(job_uid: str) ExternalJobController#
Get external job in this project by its unique ID.
- Parameters:
job_uid (str) – Job unique ID, e.g,. “J42”
- Raises:
APIError – Job does not exist
TypeError – Job is not an external job
- Returns:
external job accessor object
- Return type:
- find_job(job_uid: str) JobController#
Get a job in the project by its unique ID.
- Parameters:
job_uid (str) – Job unique ID, e.g., “J42”
- Returns:
job accessor instance
- Return type:
- Raises:
APIError – Job does not exist.
- find_jobs(workspace_uid: str | List[str] | None = None, *, order: Literal[1, -1] = 1, **search: Unpack[JobSearch]) Iterable[JobController]#
Search for jobs in the project.
Example
>>> jobs = project.find_jobs("W3") >>> jobs = project.find_jobs(["W3", "W4"]) >>> jobs = project.find_jobs( ... type="homo_reconstruct", ... completed_at=(datetime(2025, 3, 1), datetime(2025, 3, 31)), ... order=-1, ... ) >>> for job in jobs: ... print(job.uid)
- Parameters:
workspace_uid (str | list[str] | None) – Workspace unique ID, e.g., “W1”. If not specified, returns jobs from all workspaces. Defaults to None.
order (int, optional) – Sort order for resulting jobs, 1 for ascending, -1 for descending. Defaults to 1.
**search (JobSearch) – Additional search parameters to filter jobs, specified as keyword arguments.
- Returns:
job accessor objects
- Return type:
Iterable[JobController]
- find_workspace(workspace_uid: str) WorkspaceController#
Find a workspace in the project by its unique ID.
- Parameters:
workspace_uid (str) – Workspace unique ID, e.g., “W1”
- Returns:
workspace accessor object
- Return type:
- Raises:
APIError – Workspace does not exist.
- find_workspaces(*, order: Literal[1, -1] = 1) Iterable[WorkspaceController]#
Search for workspaces in the project.
- Parameters:
order (int, optional) – Sort order for resulting workspaces, 1 for ascending, -1 for descending. Defaults to 1.
- Returns:
workspace accessor objects
- Return type:
Iterable[WorkspaceController]
- import_job(workspace_uid: str, path: str | PurePosixPath, *, wait: bool = False) JobController#
Import a job into a project workspace from a location on disk.
The exported job directory must be copied into the target project directory with all its symbolic links resolved. By convention, the exported job directory should be located in the project directory →
importssubfolder.The resulting job will be in an “importing” state until CryoSPARC verifies its contents and outputs. Set
wait=Trueto block until the job is ready to use.- Parameters:
workspace_uid (str) – Workspace UID to create job in, e.g., “W1”
path (str | Path) – Path to job directory, must be in the project directory. If the CryoSPARC instance is hosted remotely, this should be a path available on the server file system. e.g.,
"/projects/CS-project/imports/jobs/J134_homo_abinit"or"imports/jobs/J134_homo_abinit"wait (bool, optional) – If True, wait until job import is complete before returning. Defaults to False.
- Raises:
- list_files(prefix: str | PurePosixPath = '', recursive: bool = False) List[str]#
List files in the project directory.
Note that enabling
recursiveincludes both subdirectories and their files in the list.- Parameters:
prefix (str | Path, optional) – Subfolder inside project 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 project directory.
- Return type:
list[str]
- mkdir(target_path: str | PurePosixPath, parents: bool = False, exist_ok: bool = False)#
Create a subfolder in the project directory.
- Parameters:
target_path (str | Path) – Name or path of folder to create inside the project 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(path: str | PurePath, *, wait: bool = False)#
Move the project directory to a new location on the file system.
Provide either the new directory name or the full new directory path. If the given path is a directory that already exists, the project directory will be moved inside it with the same name.
May take a long time when moving projects between file systems.
- Parameters:
path (str | Path) – New file system path for the project directory.
wait (bool, optional) – If True, wait for the move operation to
False. (complete before returning. Defaults to)
- refresh()#
Reload this project from the CryoSPARC database.
- Returns:
self
- Return type:
- save_external_result(workspace_uid: str | None, dataset: Dataset[R], 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: List[str | Slot | Datafield] | None = None, passthrough: Tuple[str, str] | None = None, title: str = '', desc: str = '', image: str | PurePath | IO[bytes] | Any | None = None, savefig_kw: dict = {'bbox_inches': 'tight', 'pad_inches': 0}) str#
Save a result dataset to the project, via External Job. Specify at least the dataset to save and the type of data.
If neither
workspace_uidnorpassthroughare specified, saves result to the project’s newest workspace. Ifpassthroughis specified butworkspace_uidis not, saves to the passthrough job’s newest workspace.Examples
Save all particle data
>>> particles = Dataset() >>> project.save_external_result("W1", particles, 'particle') "J43"
Save new particle locations that inherit passthrough slots from a parent job
>>> particles = Dataset() >>> project.save_external_result( ... workspace_uid='W1', ... dataset=particles, ... type='particle', ... name='particles', ... slots=['location'], ... passthrough=('J42', 'selected_particles'), ... title='Re-centered particles' ... ) "J44"
Save a result with multiple slots of the same type.
>>> project.save_external_result( ... workspace_uid="W1", ... dataset=particles, ... type="particle", ... name="particle_alignments", ... slots=[ ... {"dtype": "alignments3D", "prefix": "alignments_class_0", "required": True}, ... {"dtype": "alignments3D", "prefix": "alignments_class_1", "required": True}, ... {"dtype": "alignments3D", "prefix": "alignments_class_2", "required": True}, ... ] ... ) "J45"
- Parameters:
workspace_uid (str | None) – Workspace UID to save results into. Specify
Noneto auto-select a workspace.dataset (Dataset) – Result dataset.
type (Datatype) – Type of output dataset.
name (str, optional) – Name of output on created External job. Same as type if unspecified. Defaults to None.
slots (list[SlotSpec], optional) – List of slots expected to be created for this output such as
locationorblob. Do not specify any slots that were passed through from an input unless those slots are modified in the output. Defaults to None.passthrough (tuple[str, str], optional) – Indicates that this output inherits slots from the specified output. e.g.,
("J1", "particles"). Defaults to None.title (str, optional) – Human-readable title for this output. Defaults to “”.
desc (str, optional) –
Markdown description for this output. Defaults to “”.
image (str | Path | IO | Figure, optional) – Optional image file or matplotlib Figure to set as the image for this output. Defaults to None.
savefig_kw (dict, optional) – Additional keyword arguments to pass to
figure.savefig()when saving matplotlib Figures. Defaults todict(bbox_inches="tight", pad_inches=0).
- Returns:
UID of created job where this output was saved
- Return type:
str
- set_default_param(param: str, value: Any)#
Set a default parameter value for this project. Default parameters are used to pre-populate parameter fields when creating new jobs in this project. This is useful for setting parameters that are commonly used across many jobs in the same project, such as file paths.
- Parameters:
param (str) – Name of the parameter to set a default value for, e.g., “compute_num_gpus”.
value (any) – Default value to set for the given parameter.
- set_description(desc: str)#
Set project description. May include Markdown formatting.
- Parameters:
desc (str) – New project description
- set_title(title: str)#
Set project title.
- Parameters:
title (str) – New project title
- symlink(source_path: str | PurePosixPath, target_path: str | PurePosixPath = '') None#
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 project directory.
target_path (str | Path) – Name or path of new symlink in the project directory. If not specified, creates link with the same file name as the source. Defaults to “”.
- property title: str#
Project title
- uid: str#
Project unique ID, e.g., “P3”
- unarchive(path: str | PurePath)#
Revert an archive operation. See
archive()for details.- Parameters:
path (str | Path) – Current file system path to the project directory.
- upload(target_path: str | PurePosixPath, source: str | PurePath | IO | Buffer | Stream, *, overwrite: bool = False) None#
Upload a file to the project directory.
- Parameters:
target_path (str | Path) – Name or path of file to write in the project 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. Raises error on existing files otherwise. 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 project directory.
- Parameters:
target_path (str | Path) – Name or path of dataset to save in the project directory. Should have a
.csextension.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 project directory as an MRC file.
- Parameters:
target_path (str | Path) – Name or path of MRC file to save in the project directory. Should have a
.mrcextension.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.