Skip to content

Commit 804db95

Browse files
committed
fix: apply ruff auto-fixes to experanto source files
1 parent da7d491 commit 804db95

6 files changed

Lines changed: 58 additions & 60 deletions

File tree

experanto/dataloaders.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import logging
22
import warnings
3-
from typing import Dict, List, Optional, Union
3+
from typing import Optional
44

55
from omegaconf import DictConfig
66

@@ -16,8 +16,8 @@
1616

1717

1818
def get_multisession_dataloader(
19-
paths: List[str],
20-
configs: Optional[Union[DictConfig, Dict, List[Union[DictConfig, Dict]]]] = None,
19+
paths: list[str],
20+
configs: DictConfig | dict | list[DictConfig | dict] | None = None,
2121
shuffle_keys: bool = False,
2222
**kwargs,
2323
) -> LongCycler:
@@ -90,10 +90,10 @@ def get_multisession_dataloader(
9090

9191

9292
def get_multisession_concat_dataloader(
93-
paths: List[str],
94-
configs: Optional[Union[Dict, List[Dict]]] = None,
95-
seed: Optional[int] = 0,
96-
dataloader_config: Optional[Dict] = None,
93+
paths: list[str],
94+
configs: dict | list[dict] | None = None,
95+
seed: int | None = 0,
96+
dataloader_config: dict | None = None,
9797
**kwargs,
9898
) -> Optional["FastSessionDataLoader"]:
9999
"""Create a concatenated multi-session dataloader.

experanto/datasets.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import os
77
from collections.abc import Iterable
88
from pathlib import Path
9-
from typing import Any, Dict, List, Optional
9+
from typing import Any
1010

1111
import numpy as np
1212
import torch
@@ -212,15 +212,15 @@ class ChunkDataset(Dataset):
212212
def __init__(
213213
self,
214214
root_folder: str,
215-
global_sampling_rate: Optional[float] = None,
216-
global_chunk_size: Optional[int] = None,
215+
global_sampling_rate: float | None = None,
216+
global_chunk_size: int | None = None,
217217
add_behavior_as_channels: bool = False,
218218
replace_nans_with_means: bool = False,
219219
cache_data: bool = False,
220-
out_keys: Optional[Iterable] = None,
220+
out_keys: Iterable | None = None,
221221
normalize_timestamps: bool = True,
222222
modality_config: dict = DEFAULT_MODALITY_CONFIG,
223-
seed: Optional[int] = None,
223+
seed: int | None = None,
224224
safe_interval_threshold: float = 0.5,
225225
interpolate_precision: int = 5,
226226
) -> None:
@@ -362,8 +362,8 @@ def initialize_statistics(self) -> None:
362362
None, ...
363363
]
364364
elif mode == "screen_default":
365-
means = np.array((80))
366-
stds = np.array((60))
365+
means = np.array(80)
366+
stds = np.array(60)
367367

368368
self._statistics[device_name]["mean"] = means.reshape(
369369
1, -1
@@ -385,7 +385,7 @@ def initialize_transforms(self):
385385
for device_name in self.device_names:
386386
if device_name == "screen":
387387
add_channel = Lambda(self.add_channel_function)
388-
transform_list: List[Any] = []
388+
transform_list: list[Any] = []
389389

390390
for v in self.modality_config.screen.transforms.values(): # type: ignore[union-attr]
391391
if isinstance(v, dict): # config dict
@@ -395,7 +395,7 @@ def initialize_transforms(self):
395395

396396
transform_list.insert(0, add_channel)
397397
else:
398-
transform_list: List[Any] = [ToTensor()]
398+
transform_list: list[Any] = [ToTensor()]
399399

400400
# Normalization.
401401
if self.modality_config[device_name].transforms.get("normalization", False):
@@ -468,8 +468,8 @@ def _get_callable_filter(self, filter_config):
468468

469469
def get_valid_intervals_from_filters(
470470
self, visualize: bool = False
471-
) -> List[TimeInterval]:
472-
valid_intervals: Optional[List[TimeInterval]] = None
471+
) -> list[TimeInterval]:
472+
valid_intervals: list[TimeInterval] | None = None
473473
for modality in self.modality_config:
474474
if "filters" in self.modality_config[modality]:
475475
device = self._experiment.devices[modality]
@@ -478,7 +478,7 @@ def get_valid_intervals_from_filters(
478478
].items():
479479
# Get the final callable filter function
480480
filter_function = self._get_callable_filter(filter_config)
481-
valid_intervals_: List[TimeInterval] = filter_function(device_=device) # type: ignore[assignment]
481+
valid_intervals_: list[TimeInterval] = filter_function(device_=device) # type: ignore[assignment]
482482
if visualize:
483483
logger.info("modality: %s, filter: %s", modality, filter_name)
484484
visualization_string = get_stats_for_valid_interval(
@@ -495,7 +495,7 @@ def get_valid_intervals_from_filters(
495495
return valid_intervals if valid_intervals is not None else []
496496

497497
def get_condition_mask_from_meta_conditions(
498-
self, valid_conditions_sum_of_product: List[dict]
498+
self, valid_conditions_sum_of_product: list[dict]
499499
) -> np.ndarray:
500500
"""Create a boolean mask for trials satisfying given conditions.
501501
@@ -517,7 +517,7 @@ def get_condition_mask_from_meta_conditions(
517517
``[{'tier': 'train', 'stim_type': 'natural'}, {'tier': 'blank'}]``
518518
matches trials that are either (train AND natural) OR blank.
519519
"""
520-
all_conditions: Optional[np.ndarray] = None
520+
all_conditions: np.ndarray | None = None
521521
for valid_conditions_product in valid_conditions_sum_of_product:
522522
conditions_of_product = None
523523
for k, valid_condition in valid_conditions_product.items():
@@ -540,7 +540,7 @@ def get_condition_mask_from_meta_conditions(
540540
def get_screen_sample_mask_from_meta_conditions(
541541
self,
542542
satisfy_for_next: int,
543-
valid_conditions_sum_of_product: List[dict],
543+
valid_conditions_sum_of_product: list[dict],
544544
filter_for_valid_intervals: bool = True,
545545
) -> np.ndarray:
546546
"""Create a boolean mask for screen samples satisfying given conditions.
@@ -702,7 +702,7 @@ def get_data_key_from_root_folder(self, root_folder):
702702
# Check if the file exists before trying to open it
703703
if os.path.isfile(meta_file_path):
704704
try:
705-
with open(meta_file_path, "r") as file:
705+
with open(meta_file_path) as file:
706706
meta = json.load(file)
707707

708708
# Get data_key from meta if it exists
@@ -811,14 +811,14 @@ def __getitem__(self, idx: int) -> dict:
811811

812812
return final_out
813813

814-
def get_state(self) -> Dict[str, Any]:
814+
def get_state(self) -> dict[str, Any]:
815815
"""Return the current state of the dataset's RNG."""
816816
return {
817817
"rng_state": self._rng.get_state() if self.seed is not None else None,
818818
"valid_screen_times": self._valid_screen_times.copy(),
819819
}
820820

821-
def set_state(self, state: Dict[str, Any]) -> None:
821+
def set_state(self, state: dict[str, Any]) -> None:
822822
"""Restore the dataset's RNG state."""
823823
if state["rng_state"] is not None and self.seed is not None:
824824
self._rng.set_state(state["rng_state"])

experanto/experiment.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import logging
44
import warnings
55
from pathlib import Path
6-
from typing import Union
76

87
import numpy as np
98
from hydra.utils import instantiate
@@ -130,9 +129,9 @@ def device_names(self):
130129
def interpolate(
131130
self,
132131
times: np.ndarray,
133-
device: Union[str, Interpolator, None] = None,
132+
device: str | Interpolator | None = None,
134133
return_valid: bool = False,
135-
) -> Union[tuple[dict, dict], dict, tuple[np.ndarray, np.ndarray], np.ndarray]:
134+
) -> tuple[dict, dict] | dict | tuple[np.ndarray, np.ndarray] | np.ndarray:
136135
"""Interpolate data from one or all devices at specified time points.
137136
138137
Parameters
@@ -200,7 +199,7 @@ def interpolate(
200199
else:
201200
return values
202201
elif isinstance(device, str):
203-
assert device in self.devices, "Unknown device '{}'".format(device)
202+
assert device in self.devices, f"Unknown device '{device}'"
204203
res = self.devices[device].interpolate(times, return_valid=return_valid)
205204
return res
206205
else:

experanto/interpolators.py

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,10 @@
44
import logging
55
import os
66
import re
7-
import typing
87
import warnings
98
from abc import abstractmethod
109
from pathlib import Path
11-
from typing import Union, cast
10+
from typing import cast
1211

1312
import cv2
1413
import numpy as np
@@ -71,7 +70,7 @@ def load_meta(self):
7170
@abstractmethod
7271
def interpolate(
7372
self, times: np.ndarray, return_valid: bool = False
74-
) -> Union[tuple[np.ndarray, np.ndarray], np.ndarray]:
73+
) -> tuple[np.ndarray, np.ndarray] | np.ndarray:
7574
"""Map an array of time points to interpolated data values."""
7675
...
7776

@@ -85,7 +84,7 @@ def __exit__(self, *exc):
8584
self.close()
8685

8786
@staticmethod
88-
def create(root_folder: str, cache_data: bool = False, **kwargs) -> "Interpolator":
87+
def create(root_folder: str, cache_data: bool = False, **kwargs) -> Interpolator:
8988
"""Factory method to create the appropriate interpolator for a modality.
9089
9190
Reads the ``meta.yml`` file in the folder to determine the modality type
@@ -110,7 +109,7 @@ def create(root_folder: str, cache_data: bool = False, **kwargs) -> "Interpolato
110109
ValueError
111110
If the modality type is not supported.
112111
"""
113-
with open(Path(root_folder) / "meta.yml", "r") as file:
112+
with open(Path(root_folder) / "meta.yml") as file:
114113
meta_data = yaml.safe_load(file)
115114
modality = meta_data.get("modality")
116115

@@ -197,7 +196,7 @@ def __init__(
197196
interpolation_mode: str = "nearest_neighbor",
198197
normalize: bool = False,
199198
normalize_subtract_mean: bool = False,
200-
normalize_std_threshold: typing.Optional[float] = None, # or 0.01
199+
normalize_std_threshold: float | None = None, # or 0.01
201200
**kwargs,
202201
) -> None:
203202
super().__init__(root_folder)
@@ -262,7 +261,7 @@ def normalize_data(self, data):
262261

263262
def interpolate(
264263
self, times: np.ndarray, return_valid: bool = False
265-
) -> Union[tuple[np.ndarray, np.ndarray], np.ndarray]:
264+
) -> tuple[np.ndarray, np.ndarray] | np.ndarray:
266265
valid = self.valid_times(times)
267266
valid_times = times[valid]
268267

@@ -361,7 +360,7 @@ def __init__(
361360
interpolation_mode: str = "nearest_neighbor",
362361
normalize: bool = False,
363362
normalize_subtract_mean: bool = False,
364-
normalize_std_threshold: typing.Optional[float] = None, # or 0.01
363+
normalize_std_threshold: float | None = None, # or 0.01
365364
**kwargs,
366365
) -> None:
367366
super().__init__(
@@ -385,7 +384,7 @@ def __init__(
385384

386385
def interpolate(
387386
self, times: np.ndarray, return_valid: bool = False
388-
) -> Union[tuple[np.ndarray, np.ndarray], np.ndarray]:
387+
) -> tuple[np.ndarray, np.ndarray] | np.ndarray:
389388
valid = self.valid_times(times)
390389
valid_times = times[valid]
391390

@@ -500,7 +499,7 @@ def __init__(
500499
root_folder: str,
501500
cache_data: bool = False, # New parameter
502501
rescale: bool = False,
503-
rescale_size: typing.Optional[tuple[int, int]] = None,
502+
rescale_size: tuple[int, int] | None = None,
504503
normalize: bool = False,
505504
**kwargs,
506505
) -> None:
@@ -565,7 +564,7 @@ def is_numbered_yml(file_name):
565564

566565
# Read each YAML file and store under its filename
567566
for meta_file in meta_files:
568-
with open(meta_file, "r") as file:
567+
with open(meta_file) as file:
569568
file_base_name = meta_file.stem
570569
yaml_content = yaml.safe_load(file)
571570
all_data[file_base_name] = yaml_content
@@ -579,7 +578,7 @@ def read_combined_meta(self) -> tuple[list, list]:
579578
logger.info("Combining metadata files...")
580579
self._combine_metadatas()
581580

582-
with open(self.root_folder / "combined_meta.json", "r") as file:
581+
with open(self.root_folder / "combined_meta.json") as file:
583582
self.combined_meta = json.load(file)
584583

585584
metadatas = []
@@ -605,7 +604,7 @@ def _parse_trials(self) -> None:
605604

606605
def interpolate(
607606
self, times: np.ndarray, return_valid: bool = False
608-
) -> Union[tuple[np.ndarray, np.ndarray], np.ndarray]:
607+
) -> tuple[np.ndarray, np.ndarray] | np.ndarray:
609608
valid = self.valid_times(times)
610609
valid_times = times[valid]
611610
valid_times += 1e-4 # add small offset to avoid numerical issues
@@ -724,7 +723,7 @@ def __init__(self, root_folder: str, cache_data: bool = False, **kwargs):
724723

725724
def interpolate(
726725
self, times: np.ndarray, return_valid: bool = False
727-
) -> Union[tuple[np.ndarray, np.ndarray], np.ndarray]:
726+
) -> tuple[np.ndarray, np.ndarray] | np.ndarray:
728727
valid = self.valid_times(times)
729728
valid_times = times[valid]
730729

@@ -791,7 +790,7 @@ class ScreenTrial:
791790

792791
def __init__(
793792
self,
794-
data_file_name: Union[str, Path],
793+
data_file_name: str | Path,
795794
meta_data: dict,
796795
image_size: tuple,
797796
first_frame_idx: int,
@@ -811,10 +810,10 @@ def __init__(
811810

812811
@staticmethod
813812
def create(
814-
data_file_name: Union[str, Path],
813+
data_file_name: str | Path,
815814
meta_data: dict,
816815
cache_data: bool = False,
817-
) -> "ScreenTrial":
816+
) -> ScreenTrial:
818817
modality = meta_data.get("modality")
819818
assert modality is not None
820819
class_name = modality.lower().capitalize() + "Trial"
@@ -1050,7 +1049,7 @@ def __init__(
10501049

10511050
def interpolate(
10521051
self, times: np.ndarray, return_valid: bool = False
1053-
) -> Union[tuple[np.ndarray, np.ndarray], np.ndarray]:
1052+
) -> tuple[np.ndarray, np.ndarray] | np.ndarray:
10541053
# 1. Filter for valid times
10551054
valid = self.valid_times(times)
10561055
valid_times = times[valid]

0 commit comments

Comments
 (0)