Skip to content

napari_ndev.helpers #

Helper functions for file handling, image processing, and logging setup.

Functions:

  • get_directory_and_files : Get the directory and files in the specified directory.
  • get_channel_names : Get the channel names from an BioImage object.
  • get_squeezed_dim_order : Return a string containing the squeezed dimensions of the given BioImage object.
  • create_id_string : Create an ID string for the given image.
  • check_for_missing_files : Check if the given files are missing in the specified directories.
  • setup_logger : Set up a logger with the specified log location.

check_for_missing_files #

check_for_missing_files(files, *directories)

Check if the given files are missing in the specified directories.

Parameters:

  • files #

    (list of Path or list of str) –

    List of files to check.

  • directories #

    (tuple of Path or str, default: () ) –

    Tuple of directories to search for the files.

Returns:

  • list of tuple

    List of tuples containing the missing files and their corresponding directories.

Source code in src/napari_ndev/helpers.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
def check_for_missing_files(
    files: list[Path] | list[str], *directories: Path | str
) -> list[tuple]:
    """
    Check if the given files are missing in the specified directories.

    Parameters
    ----------
    files : list of Path or list of str
        List of files to check.
    directories : tuple of Path or str
        Tuple of directories to search for the files.

    Returns
    -------
    list of tuple
        List of tuples containing the missing files and their corresponding directories.

    """
    missing_files = []
    for file in files:
        for directory in directories:
            if isinstance(directory, str):
                directory = Path(directory)
            if isinstance(file, str):
                file = Path(file)

            file_loc = directory / file.name
            if not file_loc.exists():
                missing_files.append((file.name, directory.name))

    return missing_files

create_id_string #

create_id_string(img, identifier)

Create an ID string for the given image.

Parameters:

  • img #

    (BioImage) –

    The image object.

  • identifier #

    (str) –

    The identifier string.

Returns:

  • str

    The ID string.

Examples:

>>> create_id_string(img, 'test')
'test__0__Scene:0'
Source code in src/napari_ndev/helpers.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def create_id_string(img: nImage | BioImage, identifier: str) -> str:
    """
    Create an ID string for the given image.

    Parameters
    ----------
    img : BioImage
        The image object.
    identifier : str
        The identifier string.

    Returns
    -------
    str
        The ID string.

    Examples
    --------
    >>> create_id_string(img, 'test')
    'test__0__Scene:0'

    """
    scene_idx = img.current_scene_index
    # scene = img.current_scene
    # instead use ome_metadata.name because this gets saved with OmeTiffWriter
    try:
        if img.ome_metadata.images[scene_idx].name is None:
            scene = img.current_scene
        else:
            scene = img.ome_metadata.images[scene_idx].name
    except NotImplementedError:
        scene = img.current_scene  # not useful with OmeTiffReader, atm
    id_string = f'{identifier}__{scene_idx}__{scene}'
    return id_string

elide_string #

elide_string(input_string, max_length=15, location='middle')

Elide a string if it exceeds the specified length.

Parameters:

  • input_string #

    (str) –

    The input string.

  • max_length #

    (int, default: 15 ) –

    The maximum length of the string. Defaults to 15.

  • location #

    (str, default: 'middle' ) –

    The location to elide the string. Can be 'start', 'middle', or 'end'. Defaults to 'middle'.

Returns:

  • str

    The elided string.

Source code in src/napari_ndev/helpers.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
def elide_string(input_string, max_length=15, location='middle'):
    """
    Elide a string if it exceeds the specified length.

    Parameters
    ----------
    input_string : str
        The input string.
    max_length : int, optional
        The maximum length of the string. Defaults to 15.
    location : str, optional
        The location to elide the string. Can be 'start', 'middle', or 'end'.
        Defaults to 'middle'.

    Returns
    -------
    str
        The elided string.

    """
    # If the string is already shorter than the max length, return it
    if len(input_string) <= max_length:
        return input_string
    # If max_length is too small, just truncate
    if max_length <= 5:
        return input_string[:max_length]
    # Elide the string based on the location
    if location == 'start':
        return '...' + input_string[-(max_length - 3):]
    if location == 'end':
        return input_string[:max_length - 3] + '...'
    if location == 'middle':
        half_length = (max_length - 3) // 2
        return input_string[:half_length] + '...' + input_string[-half_length:]
    raise ValueError('Invalid location. Must be "start", "middle", or "end".')

get_channel_names #

get_channel_names(img)

Get the channel names from a BioImage object.

If the image has a dimension order that includes "S" (it is RGB), return the default channel names ["red", "green", "blue"]. Otherwise, return the channel names from the image.

Parameters:

  • img #

    (BioImage) –

    The BioImage object.

Returns:

  • list of str

    The channel names.

Source code in src/napari_ndev/helpers.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def get_channel_names(img: nImage | BioImage) -> list[str]:
    """
    Get the channel names from a BioImage object.

    If the image has a dimension order that includes "S" (it is RGB),
    return the default channel names ["red", "green", "blue"].
    Otherwise, return the channel names from the image.

    Parameters
    ----------
    img : BioImage
        The BioImage object.

    Returns
    -------
    list of str
        The channel names.

    """
    if 'S' in img.dims.order:
        return ['red', 'green', 'blue']
    return img.channel_names

get_directory_and_files #

get_directory_and_files(dir_path=None, pattern=None)

Get the directory and files in the specified directory.

Parameters:

  • dir_path #

    (str or Path or None, default: None ) –

    The directory path.

  • pattern #

    (list of str or str or None, default: None ) –

    The file pattern(s) to match. If a string is provided, it will be treated as a single pattern. If a list is provided, each element will be treated as a separate pattern. Defaults to ['tif', 'tiff', 'nd2', 'czi', 'lif', 'oib', 'png', 'jpg', 'jpeg', 'bmp', 'gif'].

Returns:

  • tuple of (Path, list of Path)

    A tuple containing the directory path and a list of file paths.

Source code in src/napari_ndev/helpers.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def get_directory_and_files(
    dir_path: str | Path | None = None,
    pattern: list[str] | str | None = None,
) -> tuple[Path, list[Path]]:
    """
    Get the directory and files in the specified directory.

    Parameters
    ----------
    dir_path : str or Path or None, optional
        The directory path.
    pattern : list of str or str or None, optional
        The file pattern(s) to match. If a string is provided, it will be treated as a single pattern.
        If a list is provided, each element will be treated as a separate pattern.
        Defaults to ['tif', 'tiff', 'nd2', 'czi', 'lif', 'oib', 'png', 'jpg', 'jpeg', 'bmp', 'gif'].

    Returns
    -------
    tuple of (Path, list of Path)
        A tuple containing the directory path and a list of file paths.

    """
    if pattern is None:
        pattern = [
            'tif',
            'tiff',
            'nd2',
            'czi',
            'lif',
            'oib',
            'png',
            'jpg',
            'jpeg',
            'bmp',
            'gif',
        ]
    if dir_path is None:
        return None, []

    directory = Path(dir_path)

    if dir_path is not None and not directory.exists():
        raise FileNotFoundError(f'Directory {dir_path} does not exist.')

    pattern = [pattern] if isinstance(pattern, str) else pattern
    # add *. to each pattern if it doesn't already have either
    pattern_glob = []
    for pat in pattern:
        if '.' not in pat:
            pat = f'*.{pat}'
        if '*' not in pat:
            pat = f'*{pat}'
        pattern_glob.append(pat)

    files = []
    for p_glob in pattern_glob:
        for file in directory.glob(p_glob):
            files.append(file)
    return directory, files

get_squeezed_dim_order #

get_squeezed_dim_order(img, skip_dims=None)

Return a string containing the squeezed dimensions of the given BioImage.

Parameters:

  • img #

    (BioImage) –

    The BioImage object.

  • skip_dims #

    (list of str or str or None, default: None ) –

    Dimensions to skip. Defaults to ["C", "S"].

Returns:

  • str

    A string containing the squeezed dimensions.

Source code in src/napari_ndev/helpers.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def get_squeezed_dim_order(
    img: nImage | BioImage,
    skip_dims: list[str] | str | None = None,
) -> str:
    """
    Return a string containing the squeezed dimensions of the given BioImage.

    Parameters
    ----------
    img : BioImage
        The BioImage object.
    skip_dims : list of str or str or None, optional
        Dimensions to skip. Defaults to ["C", "S"].

    Returns
    -------
    str
        A string containing the squeezed dimensions.

    """
    if skip_dims is None:
        skip_dims = ['C', 'S']
    return ''.join(
        {k: v for k, v in img.dims.items() if v > 1 and k not in skip_dims}
    )

setup_logger #

setup_logger(log_loc=Union[str, Path])

Set up a logger with the specified log location.

Parameters:

Returns:

  • logger ( Logger ) –

    The logger object.

  • handler ( FileHandler ) –

    The file handler object.

Source code in src/napari_ndev/helpers.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def setup_logger(log_loc=Union[str, Path]):
    """
    Set up a logger with the specified log location.

    Parameters
    ----------
    log_loc : str or Path
        The path to the log file.

    Returns
    -------
    logger : logging.Logger
        The logger object.
    handler : logging.FileHandler
        The file handler object.

    """
    logger = logging.getLogger(__name__ + str(time.time()))
    logger.setLevel(logging.INFO)
    handler = logging.FileHandler(log_loc)
    handler.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger, handler