fovi.utils package

fovi.utils.add_to_all(all)[source]

Decorator that adds a function or class name to an __all__ list.

Use this decorator to automatically register module exports.

Parameters:

all (list) – The __all__ list to append to.

Returns:

A decorator that appends the function/class name to all.

Return type:

callable

Example

>>> __all__ = []
>>> @add_to_all(__all__)
... def my_function():
...     pass
>>> 'my_function' in __all__
True
fovi.utils.get_random_name()[source]

generate a random 10-digit string of uppercase and lowercase letters, and digits

fovi.utils.get_model(model, distributed)[source]

Get the underlying model from a potentially distributed model wrapper.

In distributed training, models are wrapped in DistributedDataParallel, and the actual model is accessible via the .module attribute.

Parameters:
  • model (nn.Module) – The model, potentially wrapped in DDP.

  • distributed (bool) – Whether distributed training is enabled.

Returns:

The underlying model (unwrapped if distributed).

Return type:

nn.Module

fovi.utils.reproducible_results(seed=1)[source]

Set random seeds for reproducible experiments.

Configures PyTorch, NumPy, and CUDA random number generators for reproducibility. Also sets cuDNN to deterministic mode.

Parameters:

seed (int, optional) – Random seed value. If None, no seeding is done. Defaults to 1.

Note

Setting deterministic mode may reduce performance but ensures reproducibility across runs.

class fovi.utils.HiddenPrints(enabled=True)[source]

Bases: object

Context manager to suppress stdout output.

Temporarily redirects stdout to devnull to hide print statements from called functions.

Parameters:

enabled (bool, optional) – Whether to suppress prints. If False, acts as a no-op. Defaults to True.

Example

>>> with HiddenPrints():
...     print("This won't be shown")
>>> print("This will be shown")
This will be shown
__init__(enabled=True)[source]
fovi.utils.normalize(x, min=None, max=None, dim=None)[source]

Normalize values to [0, 1] range using min-max normalization.

Computes (x - min) / (max - min). If min/max are not provided, they are computed from the data.

Parameters:
  • x (torch.Tensor or np.ndarray) – Input values to normalize.

  • min (float or torch.Tensor, optional) – Minimum value for normalization. If None, computed from x. Defaults to None.

  • max (float or torch.Tensor, optional) – Maximum value for normalization. If None, computed from x. Defaults to None.

  • dim (int, optional) – Dimension along which to compute min/max. If None, uses global min/max. Defaults to None.

Returns:

Normalized values in [0, 1] range.

Returns same type as input.

Return type:

torch.Tensor or np.ndarray

fovi.utils.timeit(description='Code block')[source]

Context manager that times and prints the execution duration of a code block.

Parameters:

description (str, optional) – Label to print with the timing. Defaults to “Code block”.

Example

>>> with timeit("My operation"):
...     time.sleep(1)
My operation: 1.00... seconds
fovi.utils.load_pretrained(model, weights, progress)[source]

Load pretrained weights into a model.

Parameters:
  • model (nn.Module) – The model to load weights into.

  • weights – Pretrained weights object with a get_state_dict method (e.g., from torchvision.models).

  • progress (bool) – Whether to display a progress bar during download.

Returns:

The model with loaded weights.

Return type:

nn.Module

fovi.utils.analyze_rf(points, rf_center=None)[source]

Analyze receptive field (RF) for geometric properties.

Fits an ellipse to the RF boundary points and computes metrics describing the RF shape and position.

Parameters:
  • points (torch.Tensor or np.ndarray) – Array of shape (N, 2) containing the (x, y) coordinates of RF boundary points.

  • rf_center (tuple, optional) – (x, y) coordinates of the RF center. If None, uses the first point as the center. Defaults to None.

Returns:

A tuple (area, aspect_ratio, radial_displacement) where:
  • area (float): Area of the fitted ellipse (pi * a * b).

  • aspect_ratio (float): Ratio of semi-minor to semi-major axis (b/a).

  • radial_displacement (float): Normalized radial displacement of the center from the ellipse center, in range [0, 2].

Return type:

tuple

fovi.utils.normalize_imagenet(x)[source]

Normalize an image using ImageNet mean and standard deviation.

Applies the standard ImageNet normalization: (x - mean) / std.

Parameters:

x (np.ndarray) – Image array to normalize.

Returns:

Normalized image array.

Return type:

np.ndarray

fovi.utils.flatten_dict(d, prefix='', separator='.')[source]

Flatten a nested dictionary into a single-level dictionary.

Nested keys are joined with the separator to form compound keys.

Parameters:
  • d (dict) – The nested dictionary to flatten.

  • prefix (str, optional) – Prefix to prepend to all keys. Defaults to ‘’.

  • separator (str, optional) – String to join nested keys. Defaults to ‘.’.

Returns:

Flattened dictionary with compound keys.

Return type:

dict

Example

>>> flatten_dict({'a': {'b': 1, 'c': 2}, 'd': 3})
{'a.b': 1, 'a.c': 2, 'd': 3}
fovi.utils.unflatten_dict(d, separator='.')[source]

Unflatten a dictionary with compound keys into a nested dictionary.

Inverse operation of flatten_dict. Splits compound keys on the separator to reconstruct nested structure.

Parameters:
  • d (dict) – The flat dictionary to unflatten.

  • separator (str, optional) – String that separates nested keys. Defaults to ‘.’.

Returns:

Nested dictionary structure.

Return type:

dict

Example

>>> unflatten_dict({'a.b': 1, 'a.c': 2, 'd': 3})
{'a': {'b': 1, 'c': 2}, 'd': 3}

Modules