Skip to content

napari_cellseg3d.config

Module to store configuration parameters for napari_cellseg3d.

Classes:

Name Description
CRFConfig

Class to record params for CRF.

DeterministicConfig

Class to record deterministic config.

InferenceWorkerConfig

Class to record configuration for Inference job.

InfererConfig

Class to record params for Inferer plugin.

InstanceSegConfig

Class to record params for instance segmentation.

ModelInfo

Dataclass recording supervised models info.

PostProcessConfig

Class to record params for post processing.

ReviewConfig

Class to record params for Review plugin.

ReviewSession

Class to record params for Review session.

SlidingWindowConfig

Class to record params for sliding window inference.

SupervisedTrainingWorkerConfig

Class to record config for Trainer plugin.

Thresholding

Class to record params for thresholding.

TrainerConfig

Class to record trainer plugin config.

TrainingWorkerConfig

General class to record config for training.

WNetTrainingWorkerConfig

Class to record config for WNet worker.

WandBConfig

Class to record parameters for WandB.

WeightsInfo

Class to record params for weights.

Zoom

Class to record params for zoom.

Functions:

Name Description
__getattr__

Provides PRETRAINED_WEIGHTS_DIR, deprecated; use utils.get_pretrained_weights_dir().

CRFConfig dataclass

Class to record params for CRF.

Parameters:

Name Type Description Default
sa float

alpha standard deviation, the scale of the spatial part of the appearance/bilateral kernel.

10
sb float

beta standard deviation, the scale of the color part of the appearance/bilateral kernel.

5
sg float

gamma standard deviation, the scale of the smoothness/gaussian kernel.

1
w1 float

weight of the appearance/bilateral kernel.

10
w2 float

weight of the smoothness/gaussian kernel.

5
n_iter int

Number of iterations for the CRF post-processing step. Defaults to 5.

required
Source code in napari_cellseg3d/config.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
@dataclass
class CRFConfig:
    """Class to record params for CRF.

    Args:
        sa (float): alpha standard deviation, the scale of the spatial part of the appearance/bilateral kernel.
        sb (float): beta standard deviation, the scale of the color part of the appearance/bilateral kernel.
        sg (float): gamma standard deviation, the scale of the smoothness/gaussian kernel.
        w1 (float): weight of the appearance/bilateral kernel.
        w2 (float): weight of the smoothness/gaussian kernel.
        n_iter (int, optional): Number of iterations for the CRF post-processing step. Defaults to 5.
    """

    sa: float = 10
    sb: float = 5
    sg: float = 1
    w1: float = 10
    w2: float = 5
    n_iters: int = 5

DeterministicConfig dataclass

Class to record deterministic config.

Source code in napari_cellseg3d/config.py
303
304
305
306
307
308
@dataclass
class DeterministicConfig:
    """Class to record deterministic config."""

    enabled: bool = True
    seed: int = 34936339  # default seed from NP_MAX

InferenceWorkerConfig dataclass

Class to record configuration for Inference job.

Parameters:

Name Type Description Default
device str

device to use for inference

'cpu'
model_info ModelInfo

model info

ModelInfo()
weights_config WeightsInfo

weights info

WeightsInfo()
results_path str

path to save results

str(home() / 'cellseg3d' / 'inference')
filetype str

filetype to save results

'.tif'
keep_on_cpu bool

keep results on cpu

False
compute_stats bool

compute stats

False
post_process_config PostProcessConfig

post processing config

PostProcessConfig()
sliding_window_config SlidingWindowConfig

sliding window config

SlidingWindowConfig()
images_filepaths str

path to images to infer

None
layer Layer

napari layer to infer on

None
keep_channel Optional[int]

index of the single output channel to keep for multi-channel models (WNet3D); None keeps all channels

None
Source code in napari_cellseg3d/config.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
@dataclass
class InferenceWorkerConfig:
    """Class to record configuration for Inference job.

    Args:
        device (str): device to use for inference
        model_info (ModelInfo): model info
        weights_config (WeightsInfo): weights info
        results_path (str): path to save results
        filetype (str): filetype to save results
        keep_on_cpu (bool): keep results on cpu
        compute_stats (bool): compute stats
        post_process_config (PostProcessConfig): post processing config
        sliding_window_config (SlidingWindowConfig): sliding window config
        images_filepaths (str): path to images to infer
        layer (napari.layers.Layer): napari layer to infer on
        keep_channel (Optional[int]): index of the single output channel to keep for multi-channel models (WNet3D); None keeps all channels
    """

    device: str = "cpu"
    model_info: ModelInfo = field(default_factory=ModelInfo)
    weights_config: WeightsInfo = field(default_factory=WeightsInfo)
    results_path: str = str(Path.home() / "cellseg3d" / "inference")
    filetype: str = ".tif"
    keep_on_cpu: bool = False
    compute_stats: bool = False
    post_process_config: PostProcessConfig = field(default_factory=PostProcessConfig)
    sliding_window_config: SlidingWindowConfig = field(
        default_factory=SlidingWindowConfig
    )
    use_crf: bool = False
    crf_config: CRFConfig = field(default_factory=CRFConfig)

    images_filepaths: List[str] = None
    layer: napari.layers.Layer = None
    keep_channel: Optional[int] = None

InfererConfig dataclass

Class to record params for Inferer plugin.

Parameters:

Name Type Description Default
model_info ModelInfo

model info

None
show_results bool

show results in napari

False
show_results_count int

number of results to show

5
show_original bool

show original image in napari

True
anisotropy_resolution List[int]

anisotropy resolution

None
Source code in napari_cellseg3d/config.py
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
@dataclass
class InfererConfig:
    """Class to record params for Inferer plugin.

    Args:
        model_info (ModelInfo): model info
        show_results (bool): show results in napari
        show_results_count (int): number of results to show
        show_original (bool): show original image in napari
        anisotropy_resolution (List[int]): anisotropy resolution
    """

    model_info: ModelInfo = None
    show_results: bool = False
    show_results_count: int = 5
    show_original: bool = True
    anisotropy_resolution: List[int] = None

InstanceSegConfig dataclass

Class to record params for instance segmentation.

Source code in napari_cellseg3d/config.py
177
178
179
180
181
182
@dataclass
class InstanceSegConfig:
    """Class to record params for instance segmentation."""

    enabled: bool = False
    method: InstanceMethod = None

ModelInfo dataclass

Dataclass recording supervised models info.

Parameters:

Name Type Description Default
name str

name of the model

next(iter(MODEL_LIST))
model_input_size Optional[List[int]]

input size of the model

None
num_classes int

number of classes for the model.

2

Methods:

Name Description
get_model

Return model from model list.

get_model_name_list

Return list of model names.

Source code in napari_cellseg3d/config.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
@dataclass
class ModelInfo:
    """Dataclass recording supervised models info.

    Args:
        name (str): name of the model
        model_input_size (Optional[List[int]]): input size of the model
        num_classes (int): number of classes for the model.
    """

    name: str = next(iter(MODEL_LIST))
    model_input_size: Optional[List[int]] = None  # only used by SegResNet and SwinUNETR
    num_classes: int = 2  # only used by WNets

    def get_model(self):
        """Return model from model list."""
        try:
            return MODEL_LIST[self.name]
        except KeyError as e:
            msg = f"Model {self.name} is not defined"
            logger.warning(msg)
            logger.warning(msg)
            raise KeyError from e

    @staticmethod
    def get_model_name_list():
        """Return list of model names."""
        logger.info("Model list :")
        for model_name in MODEL_LIST:
            logger.info(f" * {model_name}")
        return MODEL_LIST.keys()

get_model

get_model()

Return model from model list.

Source code in napari_cellseg3d/config.py
118
119
120
121
122
123
124
125
126
def get_model(self):
    """Return model from model list."""
    try:
        return MODEL_LIST[self.name]
    except KeyError as e:
        msg = f"Model {self.name} is not defined"
        logger.warning(msg)
        logger.warning(msg)
        raise KeyError from e

get_model_name_list staticmethod

get_model_name_list()

Return list of model names.

Source code in napari_cellseg3d/config.py
128
129
130
131
132
133
134
@staticmethod
def get_model_name_list():
    """Return list of model names."""
    logger.info("Model list :")
    for model_name in MODEL_LIST:
        logger.info(f" * {model_name}")
    return MODEL_LIST.keys()

PostProcessConfig dataclass

Class to record params for post processing.

Parameters:

Name Type Description Default
zoom Zoom

zoom config

Zoom()
thresholding Thresholding

thresholding config

Thresholding()
instance InstanceSegConfig

instance segmentation config

InstanceSegConfig()
Source code in napari_cellseg3d/config.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
@dataclass
class PostProcessConfig:
    """Class to record params for post processing.

    Args:
        zoom (Zoom): zoom config
        thresholding (Thresholding): thresholding config
        instance (InstanceSegConfig): instance segmentation config
    """

    zoom: Zoom = field(default_factory=Zoom)
    thresholding: Thresholding = field(default_factory=Thresholding)
    instance: InstanceSegConfig = field(default_factory=InstanceSegConfig)
    artifact_removal: bool = False
    artifact_removal_size: int = 500

ReviewConfig dataclass

Class to record params for Review plugin.

Parameters:

Name Type Description Default
image array

image to review

None
labels array

labels to review

None
csv_path str

path to csv to save results

home() / 'cellseg3d' / 'review'
model_name str

name of the model (added to csv name)

''
new_csv bool

whether to create a new csv

True
filetype str

filetype to read & write review images

'.tif'
zoom_factor List[int]

zoom factor to apply to image & labels, if selected

None
Source code in napari_cellseg3d/config.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
@dataclass
class ReviewConfig:
    """Class to record params for Review plugin.

    Args:
        image (np.array): image to review
        labels (np.array): labels to review
        csv_path (str): path to csv to save results
        model_name (str): name of the model (added to csv name)
        new_csv (bool): whether to create a new csv
        filetype (str): filetype to read & write review images
        zoom_factor (List[int]): zoom factor to apply to image & labels, if selected
    """

    image: np.array = None
    labels: np.array = None
    csv_path: str = Path.home() / "cellseg3d" / "review"
    model_name: str = ""
    new_csv: bool = True
    filetype: str = ".tif"
    zoom_factor: List[int] = None

ReviewSession dataclass

Class to record params for Review session.

Parameters:

Name Type Description Default
project_name str

name of the project

required
image_path str

path to images

required
labels_path str

path to labels

required
csv_path str

path to csv

required
aniso_zoom List[int]

anisotropy zoom

required
time_taken timedelta

time taken to review

required
Source code in napari_cellseg3d/config.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
@dataclass  # TODO create custom reader for JSON to load project
class ReviewSession:
    """Class to record params for Review session.

    Args:
        project_name (str): name of the project
        image_path (str): path to images
        labels_path (str): path to labels
        csv_path (str): path to csv
        aniso_zoom (List[int]): anisotropy zoom
        time_taken (datetime.timedelta): time taken to review
    """

    project_name: str
    image_path: str
    labels_path: str
    csv_path: str
    aniso_zoom: List[int]
    time_taken: datetime.timedelta

SlidingWindowConfig dataclass

Class to record params for sliding window inference.

Methods:

Name Description
is_enabled

Return True if sliding window is enabled.

Source code in napari_cellseg3d/config.py
229
230
231
232
233
234
235
236
237
238
@dataclass
class SlidingWindowConfig:
    """Class to record params for sliding window inference."""

    window_size: int = None
    window_overlap: float = 0.25

    def is_enabled(self):
        """Return True if sliding window is enabled."""
        return self.window_size is not None

is_enabled

is_enabled()

Return True if sliding window is enabled.

Source code in napari_cellseg3d/config.py
236
237
238
def is_enabled(self):
    """Return True if sliding window is enabled."""
    return self.window_size is not None

SupervisedTrainingWorkerConfig dataclass

Bases: TrainingWorkerConfig

Class to record config for Trainer plugin.

Parameters:

Name Type Description Default
model_info ModelInfo

model info

None
loss_function callable

loss function

None
validation_percent float

validation percent

required
Source code in napari_cellseg3d/config.py
363
364
365
366
367
368
369
370
371
372
373
374
375
@dataclass
class SupervisedTrainingWorkerConfig(TrainingWorkerConfig):
    """Class to record config for Trainer plugin.

    Args:
        model_info (ModelInfo): model info
        loss_function (callable): loss function
        validation_percent (float): validation percent
    """

    model_info: ModelInfo = None
    loss_function: callable = None
    training_percent: float = 0.8

Thresholding dataclass

Class to record params for thresholding.

Source code in napari_cellseg3d/config.py
161
162
163
164
165
166
@dataclass
class Thresholding:
    """Class to record params for thresholding."""

    enabled: bool = False
    threshold_value: float = 0.8

TrainerConfig dataclass

Class to record trainer plugin config.

Source code in napari_cellseg3d/config.py
311
312
313
314
315
@dataclass
class TrainerConfig:
    """Class to record trainer plugin config."""

    save_as_zip: bool = False

TrainingWorkerConfig dataclass

General class to record config for training.

Parameters:

Name Type Description Default
device str

device to use for training

'cpu'
max_epochs int

max number of epochs

50
learning_rate float64

learning rate

0.001
validation_interval int

validation interval

2
batch_size int

batch size

1
deterministic_config DeterministicConfig

deterministic config

DeterministicConfig()
scheduler_factor float

scheduler factor

0.5
scheduler_patience int

scheduler patience

10
weights_info WeightsInfo

weights info

WeightsInfo()
results_path_folder str

path to save results

str(home() / 'cellseg3d' / 'training')
sampling bool

whether to sample data into patches

False
num_samples int

number of patches

2
sample_size List[int]

patch size

None
do_augmentation bool

whether to do augmentation

True
num_workers int

number of workers

4
train_data_dict dict

dict of train data as {"image": np.array, "labels": np.array}

None
Source code in napari_cellseg3d/config.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
@dataclass
class TrainingWorkerConfig:
    """General class to record config for training.

    Args:
        device (str): device to use for training
        max_epochs (int): max number of epochs
        learning_rate (np.float64): learning rate
        validation_interval (int): validation interval
        batch_size (int): batch size
        deterministic_config (DeterministicConfig): deterministic config
        scheduler_factor (float): scheduler factor
        scheduler_patience (int): scheduler patience
        weights_info (WeightsInfo): weights info
        results_path_folder (str): path to save results
        sampling (bool): whether to sample data into patches
        num_samples (int): number of patches
        sample_size (List[int]): patch size
        do_augmentation (bool): whether to do augmentation
        num_workers (int): number of workers
        train_data_dict (dict): dict of train data as {"image": np.array, "labels": np.array}
    """

    # model params
    device: str = "cpu"
    max_epochs: int = 50
    learning_rate: np.float64 = 1e-3
    validation_interval: int = 2
    batch_size: int = 1
    deterministic_config: DeterministicConfig = field(
        default_factory=DeterministicConfig
    )
    scheduler_factor: float = 0.5
    scheduler_patience: int = 10
    weights_info: WeightsInfo = field(default_factory=WeightsInfo)
    # data params
    results_path_folder: str = str(Path.home() / "cellseg3d" / "training")
    sampling: bool = False
    num_samples: int = 2
    sample_size: List[int] = None
    do_augmentation: bool = True
    num_workers: int = 4
    train_data_dict: dict = None

WNetTrainingWorkerConfig dataclass

Bases: TrainingWorkerConfig

Class to record config for WNet worker.

Parameters:

Name Type Description Default
in_channels int

encoder input channels

1
out_channels int

decoder (reconstruction) output channels

1
num_classes int

encoder output channels

2
dropout float

dropout

0.65
learning_rate float64

learning rate

2e-05
use_clipping bool

use gradient clipping

False
clipping float

clipping value

1.0
weight_decay float

weight decay

0.01
intensity_sigma float

intensity sigma

1.0
spatial_sigma float

spatial sigma

4.0
radius int

pixel radius for loss computation; might be overriden depending on data shape

2
reconstruction_loss str

reconstruction loss (MSE or BCE)

'MSE'
n_cuts_weight float

weight for NCuts loss

0.5
rec_loss_weight float

weight for reconstruction loss. Must be adjusted depending on images; compare to NCuts loss value

0.5 / 1.0
train_data_dict dict

dict of train data as {"image": np.array, "labels": np.array}

None
eval_volume_dict str

dict of eval volume (optional)

None
eval_batch_size int

eval batch size (optional)

1
Source code in napari_cellseg3d/config.py
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
@dataclass
class WNetTrainingWorkerConfig(TrainingWorkerConfig):
    """Class to record config for WNet worker.

    Args:
        in_channels (int): encoder input channels
        out_channels (int): decoder (reconstruction) output channels
        num_classes (int): encoder output channels
        dropout (float): dropout
        learning_rate (np.float64): learning rate
        use_clipping (bool): use gradient clipping
        clipping (float): clipping value
        weight_decay (float): weight decay
        intensity_sigma (float): intensity sigma
        spatial_sigma (float): spatial sigma
        radius (int): pixel radius for loss computation; might be overriden depending on data shape
        reconstruction_loss (str): reconstruction loss (MSE or BCE)
        n_cuts_weight (float): weight for NCuts loss
        rec_loss_weight (float): weight for reconstruction loss. Must be adjusted depending on images; compare to NCuts loss value
        train_data_dict (dict): dict of train data as {"image": np.array, "labels": np.array}
        eval_volume_dict (str): dict of eval volume (optional)
        eval_batch_size (int): eval batch size (optional)
    """

    # model params
    in_channels: int = 1
    out_channels: int = 1
    num_classes: int = 2
    dropout: float = 0.65
    learning_rate: np.float64 = 2e-5
    use_clipping: bool = False
    clipping: float = 1.0
    weight_decay: float = 0.01  # 1e-5
    # NCuts loss params
    intensity_sigma: float = 1.0
    spatial_sigma: float = 4.0
    radius: int = 2
    # reconstruction loss params
    reconstruction_loss: str = "MSE"  # or "BCE"
    # summed losses weights
    n_cuts_weight: float = 0.5
    rec_loss_weight: float = 0.5 / 1.0  # 0.5 / 100
    # normalization params
    # normalizing_function: callable = remap_image # FIXME: call directly in worker, not a param
    # data params
    train_data_dict: dict = None
    eval_volume_dict: str = None
    eval_batch_size: int = 1

WandBConfig dataclass

Class to record parameters for WandB.

Source code in napari_cellseg3d/config.py
431
432
433
434
435
436
@dataclass
class WandBConfig:
    """Class to record parameters for WandB."""

    mode: str = "online"  # disabled, online, offline
    save_model_artifact: bool = False

WeightsInfo dataclass

Class to record params for weights.

Parameters:

Name Type Description Default
path Optional[str]

path to weights

(lambda: str(get_pretrained_weights_dir()))()
use_custom Optional[bool]

whether to use custom weights

False
use_pretrained Optional[bool]

whether to use pretrained weights

False
Source code in napari_cellseg3d/config.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
@dataclass
class WeightsInfo:
    """Class to record params for weights.

    Args:
        path (Optional[str]): path to weights
        use_custom (Optional[bool]): whether to use custom weights
        use_pretrained (Optional[bool]): whether to use pretrained weights
    """

    path: Optional[str] = field(
        default_factory=lambda: str(get_pretrained_weights_dir())
    )
    use_pretrained: Optional[bool] = False
    use_custom: Optional[bool] = False

Zoom dataclass

Class to record params for zoom.

Source code in napari_cellseg3d/config.py
169
170
171
172
173
174
@dataclass
class Zoom:
    """Class to record params for zoom."""

    enabled: bool = False
    zoom_values: List[float] = None

__getattr__

__getattr__(name)

Provides PRETRAINED_WEIGHTS_DIR, deprecated; use utils.get_pretrained_weights_dir().

Source code in napari_cellseg3d/config.py
37
38
39
40
41
42
43
44
45
46
47
def __getattr__(name):
    """Provides `PRETRAINED_WEIGHTS_DIR`, deprecated; use `utils.get_pretrained_weights_dir()`."""
    if name == "PRETRAINED_WEIGHTS_DIR":
        warnings.warn(
            "napari_cellseg3d.config.PRETRAINED_WEIGHTS_DIR is deprecated, "
            "use napari_cellseg3d.utils.get_pretrained_weights_dir() instead",
            DeprecationWarning,
            stacklevel=2,
        )
        return str(get_pretrained_weights_dir())
    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")