synapse_net.file_utils

  1import os
  2from typing import Dict, List, Optional, Tuple, Union
  3
  4import mrcfile
  5import numpy as np
  6import pooch
  7
  8try:
  9    import cryoet_data_portal as cdp
 10except ImportError:
 11    cdp = None
 12
 13try:
 14    import zarr
 15except ImportError:
 16    zarr = None
 17
 18try:
 19    import s3fs
 20except ImportError:
 21    s3fs = None
 22
 23
 24def get_cache_dir() -> str:
 25    """Get the cache directory of synapse net.
 26
 27    Returns:
 28        The cache directory.
 29    """
 30    cache_dir = os.path.expanduser(pooch.os_cache("synapse-net"))
 31    return cache_dir
 32
 33
 34def get_data_path(folder: str, n_tomograms: Optional[int] = 1) -> Union[str, List[str]]:
 35    """Get the path to all tomograms stored as .rec or .mrc files in a folder.
 36
 37    Args:
 38        folder: The folder with tomograms.
 39        n_tomograms: The expected number of tomograms.
 40
 41    Returns:
 42        The filepath or list of filepaths of the tomograms in the folder.
 43    """
 44    file_names = os.listdir(folder)
 45    tomograms = []
 46    for fname in file_names:
 47        ext = os.path.splitext(fname)[1]
 48        if ext in (".rec", ".mrc"):
 49            tomograms.append(os.path.join(folder, fname))
 50
 51    if n_tomograms is None:
 52        return tomograms
 53    assert len(tomograms) == n_tomograms, f"{folder}: {len(tomograms)}, {n_tomograms}"
 54    return tomograms[0] if n_tomograms == 1 else tomograms
 55
 56
 57def _parse_voxel_size(voxel_size):
 58    parsed_voxel_size = None
 59    try:
 60        # The voxel sizes are stored in Angsrrom in the MRC header, but we want them
 61        # in nanometer. Hence we divide by a factor of 10 here.
 62        parsed_voxel_size = {
 63            "x": voxel_size.x / 10,
 64            "y": voxel_size.y / 10,
 65            "z": voxel_size.z / 10,
 66        }
 67    except Exception as e:
 68        print(f"Failed to read voxel size: {e}")
 69    return parsed_voxel_size
 70
 71
 72def read_voxel_size(path: str) -> Dict[str, float] | None:
 73    """Read voxel size from mrc/rec file.
 74
 75    The original unit of voxel size is Angstrom and we convert it to nanometers by dividing it by ten.
 76
 77    Args:
 78        path: Path to mrc/rec file.
 79
 80    Returns:
 81        Mapping from the axis name to voxel size. None if the voxel size could not be read.
 82    """
 83    with mrcfile.open(path, permissive=True) as mrc:
 84        voxel_size = _parse_voxel_size(mrc.voxel_size)
 85    return voxel_size
 86
 87
 88def read_mrc(path: str) -> Tuple[np.ndarray, Dict[str, float]]:
 89    """Read data and voxel size from mrc/rec file.
 90
 91    Args:
 92        path: Path to mrc/rec file.
 93
 94    Returns:
 95        The data read from the file.
 96        The voxel size read from the file.
 97    """
 98    with mrcfile.open(path, permissive=True) as mrc:
 99        voxel_size = _parse_voxel_size(mrc.voxel_size)
100        data = np.asarray(mrc.data[:])
101    assert data.ndim in (2, 3)
102
103    # Transpose the data to match python axis order.
104    data = np.flip(data, axis=1) if data.ndim == 3 else np.flip(data, axis=0)
105    return data, voxel_size
106
107
108def read_ome_zarr(uri: str, scale_level: int = 0, fs=None) -> Tuple[np.ndarray, Dict[str, float]]:
109    """Read data and voxel size from an ome.zarr file.
110
111    Args:
112        uri: Path or url to the ome.zarr file.
113        scale_level: The level of the multi-scale image pyramid to load.
114        fs: S3 filesystem to use for initializing the store.
115
116    Returns:
117        The data read from the file.
118        The voxel size read from the file.
119    """
120    if zarr is None:
121        raise RuntimeError("The zarr library is required to read ome.zarr files.")
122
123    def parse_s3_uri(uri):
124        return uri.removeprefix("s3://")
125
126    if (uri.startswith("s3") or fs is not None) and s3fs is None:
127        raise RuntimeError("The s3fs library is required to read ome.zarr files from s3.")
128
129    if uri.startswith("s3"):
130        if fs is None:
131            fs = s3fs.S3FileSystem(anon=True)
132        s3_uri = parse_s3_uri(uri)
133        store = s3fs.S3Map(root=s3_uri, s3=fs, check=False)
134    elif fs is not None:
135        s3_uri = parse_s3_uri(uri)
136        store = s3fs.S3Map(root=s3_uri, s3=fs, check=False)
137    else:
138        if not os.path.exists(uri):
139            raise ValueError(f"Cannot find the filepath at {uri}.")
140        store = uri
141
142    f = zarr.open(store, "r")
143    multiscales = f.attrs["multiscales"][0]
144
145    # Read the axis and transformation metadata for this dataset, to determine the voxel size.
146    axes = [axis["name"] for axis in multiscales["axes"]]
147    assert set(axes) == set("xyz")
148    units = [axis.get("unit", "angstrom") for axis in multiscales["axes"]]
149    assert all(unit in ("angstrom", "nanometer") for unit in units)
150
151    transformations = multiscales["datasets"][scale_level]["coordinateTransformations"]
152    scale_transformation = [trafo["scale"] for trafo in transformations if trafo["type"] == "scale"][0]
153
154    # Convert the given unit size to nanometer.
155    # (It is typically given in angstrom, and we have to divide by a factor of 10).
156    unit_factor = [10.0 if unit == "angstrom" else 1.0 for unit in units]
157    voxel_size = {axis: scale / factor for axis, scale, factor in zip(axes, scale_transformation, unit_factor)}
158
159    # Get the internale path for the given scale and load the data.
160    internal_path = multiscales["datasets"][scale_level]["path"]
161    data = f[internal_path][:]
162
163    return data, voxel_size
164
165
166def read_data_from_cryo_et_portal_run(
167    run_id: int,
168    output_path: Optional[str] = None,
169    use_zarr_format: bool = True,
170    processing_type: str = "denoised",
171    id_field: str = "run_id",
172    scale_level: Optional[int] = None,
173) -> Tuple[np.ndarray, Dict[str, float]]:
174    """Read data and voxel size from a CryoET Data Portal run.
175
176    Args:
177        run_id: The ID of the experiment run.
178        output_path: The path for saving the data. The data will be streamed if the path is not given.
179        use_zarr_format: Whether to use the data in zarr format instead of mrc.
180        processing_type: The processing type of the tomogram to download.
181        id_field: The name of the id field. One of 'id' or 'run_id'.
182            The 'id' references specific tomograms, whereas 'run_id' references a collection of experimental data.
183        scale_level: The scale level to read from the data. Only valid for zarr data.
184
185    Returns:
186        The data read from the run.
187        The voxel size read from the run.
188    """
189    assert id_field in ("id", "run_id")
190    if output_path is not None and os.path.exists(output_path):
191        return read_ome_zarr(output_path) if use_zarr_format else read_mrc(output_path)
192
193    if cdp is None:
194        raise RuntimeError("The CryoET data portal library is required to download data from the portal.")
195    if s3fs is None:
196        raise RuntimeError("The CryoET data portal download requires s3fs download.")
197
198    client = cdp.Client()
199
200    fs = s3fs.S3FileSystem(anon=True)
201    tomograms = cdp.Tomogram.find(
202        client, [getattr(cdp.Tomogram, id_field) == run_id, cdp.Tomogram.processing == processing_type]
203    )
204    if len(tomograms) == 0:
205        return None, None
206    if len(tomograms) > 1:
207        raise NotImplementedError
208    tomo = tomograms[0]
209
210    if use_zarr_format:
211        if output_path is None:
212            scale_level = 0 if scale_level is None else scale_level
213            data, voxel_size = read_ome_zarr(tomo.s3_omezarr_dir, scale_level=scale_level, fs=fs)
214        else:
215            # TODO: write the outuput to ome zarr, for all scale levels.
216            raise NotImplementedError
217    else:
218        if scale_level is not None:
219            raise ValueError
220        if output_path is None:
221            raise RuntimeError("You have to pass an output_path to download the data as mrc file.")
222        fs.get(tomo.s3_mrc_file, output_path)
223        data, voxel_size = read_mrc(output_path)
224
225    return data, voxel_size
def get_cache_dir() -> str:
25def get_cache_dir() -> str:
26    """Get the cache directory of synapse net.
27
28    Returns:
29        The cache directory.
30    """
31    cache_dir = os.path.expanduser(pooch.os_cache("synapse-net"))
32    return cache_dir

Get the cache directory of synapse net.

Returns:

The cache directory.

def get_data_path(folder: str, n_tomograms: Optional[int] = 1) -> Union[str, List[str]]:
35def get_data_path(folder: str, n_tomograms: Optional[int] = 1) -> Union[str, List[str]]:
36    """Get the path to all tomograms stored as .rec or .mrc files in a folder.
37
38    Args:
39        folder: The folder with tomograms.
40        n_tomograms: The expected number of tomograms.
41
42    Returns:
43        The filepath or list of filepaths of the tomograms in the folder.
44    """
45    file_names = os.listdir(folder)
46    tomograms = []
47    for fname in file_names:
48        ext = os.path.splitext(fname)[1]
49        if ext in (".rec", ".mrc"):
50            tomograms.append(os.path.join(folder, fname))
51
52    if n_tomograms is None:
53        return tomograms
54    assert len(tomograms) == n_tomograms, f"{folder}: {len(tomograms)}, {n_tomograms}"
55    return tomograms[0] if n_tomograms == 1 else tomograms

Get the path to all tomograms stored as .rec or .mrc files in a folder.

Arguments:
  • folder: The folder with tomograms.
  • n_tomograms: The expected number of tomograms.
Returns:

The filepath or list of filepaths of the tomograms in the folder.

def read_voxel_size(path: str) -> Optional[Dict[str, float]]:
73def read_voxel_size(path: str) -> Dict[str, float] | None:
74    """Read voxel size from mrc/rec file.
75
76    The original unit of voxel size is Angstrom and we convert it to nanometers by dividing it by ten.
77
78    Args:
79        path: Path to mrc/rec file.
80
81    Returns:
82        Mapping from the axis name to voxel size. None if the voxel size could not be read.
83    """
84    with mrcfile.open(path, permissive=True) as mrc:
85        voxel_size = _parse_voxel_size(mrc.voxel_size)
86    return voxel_size

Read voxel size from mrc/rec file.

The original unit of voxel size is Angstrom and we convert it to nanometers by dividing it by ten.

Arguments:
  • path: Path to mrc/rec file.
Returns:

Mapping from the axis name to voxel size. None if the voxel size could not be read.

def read_mrc(path: str) -> Tuple[numpy.ndarray, Dict[str, float]]:
 89def read_mrc(path: str) -> Tuple[np.ndarray, Dict[str, float]]:
 90    """Read data and voxel size from mrc/rec file.
 91
 92    Args:
 93        path: Path to mrc/rec file.
 94
 95    Returns:
 96        The data read from the file.
 97        The voxel size read from the file.
 98    """
 99    with mrcfile.open(path, permissive=True) as mrc:
100        voxel_size = _parse_voxel_size(mrc.voxel_size)
101        data = np.asarray(mrc.data[:])
102    assert data.ndim in (2, 3)
103
104    # Transpose the data to match python axis order.
105    data = np.flip(data, axis=1) if data.ndim == 3 else np.flip(data, axis=0)
106    return data, voxel_size

Read data and voxel size from mrc/rec file.

Arguments:
  • path: Path to mrc/rec file.
Returns:

The data read from the file. The voxel size read from the file.

def read_ome_zarr( uri: str, scale_level: int = 0, fs=None) -> Tuple[numpy.ndarray, Dict[str, float]]:
109def read_ome_zarr(uri: str, scale_level: int = 0, fs=None) -> Tuple[np.ndarray, Dict[str, float]]:
110    """Read data and voxel size from an ome.zarr file.
111
112    Args:
113        uri: Path or url to the ome.zarr file.
114        scale_level: The level of the multi-scale image pyramid to load.
115        fs: S3 filesystem to use for initializing the store.
116
117    Returns:
118        The data read from the file.
119        The voxel size read from the file.
120    """
121    if zarr is None:
122        raise RuntimeError("The zarr library is required to read ome.zarr files.")
123
124    def parse_s3_uri(uri):
125        return uri.removeprefix("s3://")
126
127    if (uri.startswith("s3") or fs is not None) and s3fs is None:
128        raise RuntimeError("The s3fs library is required to read ome.zarr files from s3.")
129
130    if uri.startswith("s3"):
131        if fs is None:
132            fs = s3fs.S3FileSystem(anon=True)
133        s3_uri = parse_s3_uri(uri)
134        store = s3fs.S3Map(root=s3_uri, s3=fs, check=False)
135    elif fs is not None:
136        s3_uri = parse_s3_uri(uri)
137        store = s3fs.S3Map(root=s3_uri, s3=fs, check=False)
138    else:
139        if not os.path.exists(uri):
140            raise ValueError(f"Cannot find the filepath at {uri}.")
141        store = uri
142
143    f = zarr.open(store, "r")
144    multiscales = f.attrs["multiscales"][0]
145
146    # Read the axis and transformation metadata for this dataset, to determine the voxel size.
147    axes = [axis["name"] for axis in multiscales["axes"]]
148    assert set(axes) == set("xyz")
149    units = [axis.get("unit", "angstrom") for axis in multiscales["axes"]]
150    assert all(unit in ("angstrom", "nanometer") for unit in units)
151
152    transformations = multiscales["datasets"][scale_level]["coordinateTransformations"]
153    scale_transformation = [trafo["scale"] for trafo in transformations if trafo["type"] == "scale"][0]
154
155    # Convert the given unit size to nanometer.
156    # (It is typically given in angstrom, and we have to divide by a factor of 10).
157    unit_factor = [10.0 if unit == "angstrom" else 1.0 for unit in units]
158    voxel_size = {axis: scale / factor for axis, scale, factor in zip(axes, scale_transformation, unit_factor)}
159
160    # Get the internale path for the given scale and load the data.
161    internal_path = multiscales["datasets"][scale_level]["path"]
162    data = f[internal_path][:]
163
164    return data, voxel_size

Read data and voxel size from an ome.zarr file.

Arguments:
  • uri: Path or url to the ome.zarr file.
  • scale_level: The level of the multi-scale image pyramid to load.
  • fs: S3 filesystem to use for initializing the store.
Returns:

The data read from the file. The voxel size read from the file.

def read_data_from_cryo_et_portal_run( run_id: int, output_path: Optional[str] = None, use_zarr_format: bool = True, processing_type: str = 'denoised', id_field: str = 'run_id', scale_level: Optional[int] = None) -> Tuple[numpy.ndarray, Dict[str, float]]:
167def read_data_from_cryo_et_portal_run(
168    run_id: int,
169    output_path: Optional[str] = None,
170    use_zarr_format: bool = True,
171    processing_type: str = "denoised",
172    id_field: str = "run_id",
173    scale_level: Optional[int] = None,
174) -> Tuple[np.ndarray, Dict[str, float]]:
175    """Read data and voxel size from a CryoET Data Portal run.
176
177    Args:
178        run_id: The ID of the experiment run.
179        output_path: The path for saving the data. The data will be streamed if the path is not given.
180        use_zarr_format: Whether to use the data in zarr format instead of mrc.
181        processing_type: The processing type of the tomogram to download.
182        id_field: The name of the id field. One of 'id' or 'run_id'.
183            The 'id' references specific tomograms, whereas 'run_id' references a collection of experimental data.
184        scale_level: The scale level to read from the data. Only valid for zarr data.
185
186    Returns:
187        The data read from the run.
188        The voxel size read from the run.
189    """
190    assert id_field in ("id", "run_id")
191    if output_path is not None and os.path.exists(output_path):
192        return read_ome_zarr(output_path) if use_zarr_format else read_mrc(output_path)
193
194    if cdp is None:
195        raise RuntimeError("The CryoET data portal library is required to download data from the portal.")
196    if s3fs is None:
197        raise RuntimeError("The CryoET data portal download requires s3fs download.")
198
199    client = cdp.Client()
200
201    fs = s3fs.S3FileSystem(anon=True)
202    tomograms = cdp.Tomogram.find(
203        client, [getattr(cdp.Tomogram, id_field) == run_id, cdp.Tomogram.processing == processing_type]
204    )
205    if len(tomograms) == 0:
206        return None, None
207    if len(tomograms) > 1:
208        raise NotImplementedError
209    tomo = tomograms[0]
210
211    if use_zarr_format:
212        if output_path is None:
213            scale_level = 0 if scale_level is None else scale_level
214            data, voxel_size = read_ome_zarr(tomo.s3_omezarr_dir, scale_level=scale_level, fs=fs)
215        else:
216            # TODO: write the outuput to ome zarr, for all scale levels.
217            raise NotImplementedError
218    else:
219        if scale_level is not None:
220            raise ValueError
221        if output_path is None:
222            raise RuntimeError("You have to pass an output_path to download the data as mrc file.")
223        fs.get(tomo.s3_mrc_file, output_path)
224        data, voxel_size = read_mrc(output_path)
225
226    return data, voxel_size

Read data and voxel size from a CryoET Data Portal run.

Arguments:
  • run_id: The ID of the experiment run.
  • output_path: The path for saving the data. The data will be streamed if the path is not given.
  • use_zarr_format: Whether to use the data in zarr format instead of mrc.
  • processing_type: The processing type of the tomogram to download.
  • id_field: The name of the id field. One of 'id' or 'run_id'. The 'id' references specific tomograms, whereas 'run_id' references a collection of experimental data.
  • scale_level: The scale level to read from the data. Only valid for zarr data.
Returns:

The data read from the run. The voxel size read from the run.