KamitaniLab / bdpy

Python package for brain decoding analysis (BrainDecoderToolbox2 data format, machine learning analysis, functional MRI)
MIT License
33 stars 22 forks source link

Return type of FeatureExtractor.__call__() (or FeatureExtractor.run()) should be updated #83

Closed ganow closed 1 month ago

ganow commented 8 months ago

https://github.com/KamitaniLab/bdpy/blob/016d4aedb11585f302f9e96d927496438320b915/bdpy/dl/torch/torch.py#L59-L60

Type annotation of the return value should be Union[dict[str, np.ndarray], dict[str, torch.Tensor]] instead of dict[str, Union[np.ndarray, torch.Tensor]]. The latter annotation accepts the return value like:

{
  "a": np.array(...),
  "b": torch.Tensor(...),
}

but it is actually invalid.

Furthermore, the design itself, where the return type of a function can change dynamically depending on the detach flag passed at initialization, makes it difficult for the editor to benefit from type inference. One example is the following (in #81).

https://github.com/KamitaniLab/bdpy/blob/f67228e64c7b4fa8877234d2b9c4822fcb6ed069/bdpy/recon/torch/modules/encoder.py#L89-L103

The .encode() method of a BaseEncoder subclass must return the type dict[str, torch.Tensor] by design. SimpleEncoder initializes FeatureExtractor with detach=False at initialization time, so the type constraints of .encode() are satisfied at runtime, but that information is not determined at the type annotation level.

Screen Shot 2023-12-21 at 13 52 09

ShuntaroAoki commented 1 month ago

https://github.com/KamitaniLab/bdpy/commit/083369fda016129911e7abce31b096e1c0b99b1b