Darioli commited on
Commit
34d7f57
·
verified ·
1 Parent(s): 084a69e

Updated Reader class.

Browse files
Files changed (1) hide show
  1. reader.py +94 -122
reader.py CHANGED
@@ -1,16 +1,12 @@
1
  import h5py
 
2
 
3
  class MicronsReader:
4
  def __init__(self, file_path):
5
- """
6
- Initialize the reader.
7
- Opening in read-only mode ('r') is faster and prevents accidental corruption.
8
- """
9
  self.file_path = file_path
10
  self.f = h5py.File(self.file_path, 'r')
11
 
12
  def close(self):
13
- """Close the file handle manually."""
14
  self.f.close()
15
 
16
  def __enter__(self):
@@ -19,179 +15,155 @@ class MicronsReader:
19
  def __exit__(self, exc_type, exc_val, exc_tb):
20
  self.close()
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  def get_full_data_by_hash(self, condition_hash, brain_area=None):
23
  """
24
- Returns a dictionary with the clip and all trials (responses, behavior,
25
- pupil, times) associated with a hash.
26
-
27
  Args:
28
  condition_hash (str): The identifier for the video.
29
  brain_area (str, optional): Filter for neural responses.
30
-
31
  Returns:
32
  dict: {
33
  'clip': np.array,
34
  'stim_type': str,
35
  'trials': [
36
- {'session': str, 'trial_idx': str, 'responses': np.array, ...}, ...
 
 
37
  ]
38
  }
39
  """
40
- # 1. Reuse get_video_data for stimulus info
41
  h_key = self._encode_hash(condition_hash)
42
- clip, stim_type = self.get_video_data(h_key)
43
  if clip is None:
44
  return None
45
 
46
- data_out = {
47
- 'clip': clip,
48
- 'stim_type': stim_type,
49
- 'trials': []
50
- }
51
-
52
- # 2. Access instances (links to trials)
53
- video_grp = self.f[f'videos/{h_key}']
54
- instances = video_grp['instances']
55
 
 
56
  for instance_name in instances:
57
- # SoftLink to the trial group
58
  trial_grp = instances[instance_name]
59
-
60
- # Identify parent session to look up brain area indices
61
  session_key = "_".join(instance_name.split('_')[:2])
62
-
63
- # 3. Handle Neural Responses
64
- if brain_area:
65
- area_path = f"sessions/{session_key}/meta/area_indices/{brain_area}"
66
- if area_path not in self.f:
67
- continue # Skip session if area not recorded
68
- indices = self.f[area_path][:]
69
- responses = trial_grp['responses'][indices, :]
70
- else:
71
- responses = trial_grp['responses'][:]
72
-
73
- # 4. Aggregate all datasets in the trial folder
74
- data_out['trials'].append({
75
- 'session': session_key,
76
- 'trial_idx': trial_grp.name.split('/')[-1],
77
- 'responses': responses,
78
- 'behavior': trial_grp['behavior'][:],
79
- 'pupil_center': trial_grp['pupil_center'][:],
80
- })
81
-
82
  return data_out
83
 
84
  def get_responses_by_hash(self, condition_hash, brain_area=None):
85
  """Retrieves only neural responses associated with a hash across sessions."""
86
- # Note: This is now essentially a subset of get_full_data_by_hash
87
  full_data = self.get_full_data_by_hash(condition_hash, brain_area=brain_area)
88
  if full_data is None:
89
  return []
90
-
91
  return [
92
  {
93
- 'session': t['session'],
94
- 'trial_idx': t['trial_idx'],
95
- 'responses': t['responses']
96
- }
97
  for t in full_data['trials']
98
  ]
99
 
100
- def _encode_hash(self, h):
101
- """Helper to convert a real hash into an HDF5-safe key."""
102
- return h.replace('/', '%2F')
103
-
104
- def _decode_hash(self, h):
105
- return h.replace('%2F', '/')
106
-
107
  def get_video_data(self, condition_hash):
108
  h_key = self._encode_hash(condition_hash)
109
  video_path = f"videos/{h_key}"
110
-
111
  if video_path not in self.f:
112
  return None, None
113
-
114
  vid_grp = self.f[video_path]
115
  clip = vid_grp['clip'][:]
116
  stim_type = vid_grp.attrs.get('type', 'Unknown')
117
  return clip, stim_type
118
 
119
  def get_hashes_by_session(self, session_key, return_unique=False):
120
- """Returns a unique list of condition hashes shown in a specific session."""
121
  if session_key not in self.f['sessions']:
122
  raise ValueError(f"Session {session_key} not found.")
123
  hashes = self.f[f'sessions/{session_key}/meta/condition_hashes'][:]
124
- return set([self._decode_hash(h.decode('utf-8')) for h in hashes]) if return_unique else [self._decode_hash(h.decode('utf-8')) for h in hashes]
 
125
 
126
  def get_hashes_by_type(self, stim_type):
127
- """Returns hashes belonging to a specific type (e.g., 'Monet2')."""
128
  if stim_type not in self.f['types']:
129
  return []
130
- encoded_keys = list(self.f[f'types/{stim_type}'].keys())
131
- return [self._decode_hash(k) for k in encoded_keys]
132
 
133
  def get_available_brain_areas(self, session_key=None):
134
- """Returns a list of brain areas available in the file or a specific session."""
135
  if session_key:
136
  return list(self.f[f'sessions/{session_key}/meta/area_indices'].keys())
137
  return list(self.f['brain_areas'].keys())
138
-
139
- def count_trials_per_hash(self):
140
- return {k: len(v['instances']) for k, v in self.f['videos'].items()}
141
 
142
- def print_structure(self, max_items=5, follow_links=False):
143
- """
144
- Prints a tree-like representation of the HDF5 database.
145
-
146
- Args:
147
- max_items (int): Max children to show per group.
148
- follow_links (bool): If True, recurses into SoftLinks (original behavior).
149
- If False, prints the link destination and stops.
150
- """
151
- print(f"\nStructure of: {self.file_path}")
152
- print("=" * 50)
153
-
154
- def _print_tree(name, obj, indent="", current_key=""):
155
- item_name = current_key if current_key else name
156
-
157
- # 1. Check if this specific key is a SoftLink
158
- # We need the parent object to check the link status of the child
159
- # For the root level, obj is self.f
160
- is_link = False
161
- link_path = ""
162
-
163
- # Dataset vs Group handling
164
- if isinstance(obj, h5py.Dataset):
165
- print(f"{indent}📄 {item_name:20} [Dataset: {obj.shape}, {obj.dtype}]")
166
- return
167
-
168
- # It's a Group
169
- attrs = dict(obj.attrs)
170
- attr_str = f" | Attributes: {attrs}" if attrs else ""
171
- print(f"{indent}📂 {item_name.upper()}/ {attr_str}")
172
-
173
- keys = sorted(obj.keys())
174
- num_keys = len(keys)
175
- display_keys = keys[:max_items]
176
-
177
- for key in display_keys:
178
- # Check link status without dereferencing
179
- link_obj = obj.get(key, getlink=True)
180
-
181
- if isinstance(link_obj, h5py.SoftLink):
182
- # It is a SoftLink!
183
- if follow_links:
184
- _print_tree(key, obj[key], indent + " ", current_key=key)
185
- else:
186
- print(f"{indent} 🔗 {key:18} -> {link_obj.path}")
187
- else:
188
- # It is a real Group or Dataset
189
- _print_tree(key, obj[key], indent + " ", current_key=key)
190
 
191
- if num_keys > max_items:
192
- print(f"{indent} ... and {num_keys - max_items} more items")
 
 
 
 
 
 
 
193
 
194
- # Start recursion
195
- for key in sorted(self.f.keys()):
196
- # We treat the root level keys as 'real' objects to start
197
- _print_tree(key, self.f[key], current_key=key)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import h5py
2
+ import numpy as np
3
 
4
  class MicronsReader:
5
  def __init__(self, file_path):
 
 
 
 
6
  self.file_path = file_path
7
  self.f = h5py.File(self.file_path, 'r')
8
 
9
  def close(self):
 
10
  self.f.close()
11
 
12
  def __enter__(self):
 
15
  def __exit__(self, exc_type, exc_val, exc_tb):
16
  self.close()
17
 
18
+ def _encode_hash(self, h):
19
+ return h.replace('/', '%2F')
20
+
21
+ def _decode_hash(self, h):
22
+ return h.replace('%2F', '/')
23
+
24
+ def _read_trial(self, trial_grp, session_key, brain_area=None):
25
+ """
26
+ Helper to extract all datasets from a trial group.
27
+ Centralizes field names so they only need updating in one place.
28
+ """
29
+ if brain_area:
30
+ area_path = f"sessions/{session_key}/meta/area_indices/{brain_area}"
31
+ if area_path not in self.f:
32
+ return None
33
+ indices = self.f[area_path][:]
34
+ responses = trial_grp['responses'][indices, :]
35
+ else:
36
+ responses = trial_grp['responses'][:]
37
+
38
+ return {
39
+ 'session': session_key,
40
+ 'trial_idx': trial_grp.name.split('/')[-1],
41
+ 'responses': responses,
42
+ 'treadmill': trial_grp['treadmill'][:],
43
+ 'pupil': trial_grp['pupil'][:],
44
+ 'stim_times': trial_grp['stim_times'][:],
45
+ }
46
+
47
  def get_full_data_by_hash(self, condition_hash, brain_area=None):
48
  """
49
+ Returns a dictionary with the clip and all trials (responses, treadmill,
50
+ pupil, stim_times) associated with a condition hash.
51
+
52
  Args:
53
  condition_hash (str): The identifier for the video.
54
  brain_area (str, optional): Filter for neural responses.
55
+
56
  Returns:
57
  dict: {
58
  'clip': np.array,
59
  'stim_type': str,
60
  'trials': [
61
+ {'session': str, 'trial_idx': str, 'responses': np.array,
62
+ 'treadmill': np.array, 'pupil': np.array, 'stim_times': np.array},
63
+ ...
64
  ]
65
  }
66
  """
 
67
  h_key = self._encode_hash(condition_hash)
68
+ clip, stim_type = self.get_video_data(condition_hash)
69
  if clip is None:
70
  return None
71
 
72
+ data_out = {'clip': clip, 'stim_type': stim_type, 'trials': []}
 
 
 
 
 
 
 
 
73
 
74
+ instances = self.f[f'videos/{h_key}/instances']
75
  for instance_name in instances:
 
76
  trial_grp = instances[instance_name]
 
 
77
  session_key = "_".join(instance_name.split('_')[:2])
78
+ trial = self._read_trial(trial_grp, session_key, brain_area)
79
+ if trial is not None:
80
+ data_out['trials'].append(trial)
81
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  return data_out
83
 
84
  def get_responses_by_hash(self, condition_hash, brain_area=None):
85
  """Retrieves only neural responses associated with a hash across sessions."""
 
86
  full_data = self.get_full_data_by_hash(condition_hash, brain_area=brain_area)
87
  if full_data is None:
88
  return []
 
89
  return [
90
  {
91
+ 'session': t['session'],
92
+ 'trial_idx': t['trial_idx'],
93
+ 'responses': t['responses'],
94
+ }
95
  for t in full_data['trials']
96
  ]
97
 
 
 
 
 
 
 
 
98
  def get_video_data(self, condition_hash):
99
  h_key = self._encode_hash(condition_hash)
100
  video_path = f"videos/{h_key}"
 
101
  if video_path not in self.f:
102
  return None, None
 
103
  vid_grp = self.f[video_path]
104
  clip = vid_grp['clip'][:]
105
  stim_type = vid_grp.attrs.get('type', 'Unknown')
106
  return clip, stim_type
107
 
108
  def get_hashes_by_session(self, session_key, return_unique=False):
109
+ """Returns condition hashes shown in a specific session."""
110
  if session_key not in self.f['sessions']:
111
  raise ValueError(f"Session {session_key} not found.")
112
  hashes = self.f[f'sessions/{session_key}/meta/condition_hashes'][:]
113
+ decoded = [self._decode_hash(h.decode('utf-8')) for h in hashes]
114
+ return set(decoded) if return_unique else decoded
115
 
116
  def get_hashes_by_type(self, stim_type):
117
+ """Returns hashes belonging to a specific stimulus type (e.g., 'Monet2')."""
118
  if stim_type not in self.f['types']:
119
  return []
120
+ return [self._decode_hash(k) for k in self.f[f'types/{stim_type}'].keys()]
 
121
 
122
  def get_available_brain_areas(self, session_key=None):
123
+ """Returns brain areas available in the file or a specific session."""
124
  if session_key:
125
  return list(self.f[f'sessions/{session_key}/meta/area_indices'].keys())
126
  return list(self.f['brain_areas'].keys())
 
 
 
127
 
128
+ def get_trial(self, session_key, trial_idx, brain_area=None):
129
+ """
130
+ Direct access to a single trial by session and trial index.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
+ Args:
133
+ session_key (str): e.g. '4_1'
134
+ trial_idx (int or str): trial index
135
+ brain_area (str, optional): filter responses by area
136
+ """
137
+ trial_path = f"sessions/{session_key}/trials/{trial_idx}"
138
+ if trial_path not in self.f:
139
+ raise ValueError(f"Trial {trial_idx} not found in session {session_key}.")
140
+ return self._read_trial(self.f[trial_path], session_key, brain_area)
141
 
142
+ def print_structure(self, max_items=5, follow_links=False):
143
+ """Prints a tree-like representation of the HDF5 database."""
144
+ print(f"\nStructure of: {self.file_path}")
145
+ print("=" * 50)
146
+
147
+ def _print_tree(name, obj, indent="", current_key=""):
148
+ item_name = current_key if current_key else name
149
+ if isinstance(obj, h5py.Dataset):
150
+ print(f"{indent}📄 {item_name:20} [Dataset: {obj.shape}, {obj.dtype}]")
151
+ return
152
+ attrs = dict(obj.attrs)
153
+ attr_str = f" | Attributes: {attrs}" if attrs else ""
154
+ print(f"{indent}📂 {item_name.upper()}/ {attr_str}")
155
+ keys = sorted(obj.keys())
156
+ for key in keys[:max_items]:
157
+ link_obj = obj.get(key, getlink=True)
158
+ if isinstance(link_obj, h5py.SoftLink):
159
+ if follow_links:
160
+ _print_tree(key, obj[key], indent + " ", current_key=key)
161
+ else:
162
+ print(f"{indent} 🔗 {key:18} -> {link_obj.path}")
163
+ else:
164
+ _print_tree(key, obj[key], indent + " ", current_key=key)
165
+ if len(keys) > max_items:
166
+ print(f"{indent} ... and {len(keys) - max_items} more items")
167
+
168
+ for key in sorted(self.f.keys()):
169
+ _print_tree(key, self.f[key], current_key=key)