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+
This loader provides direct access to the EIT dataset stored in HDF5 format.
|
| 5 |
+
Can be used standalone or wrapped for HuggingFace datasets compatibility.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import h5py
|
| 9 |
+
import numpy as np
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Dict, List, Tuple, Optional
|
| 12 |
+
import torch
|
| 13 |
+
from torch.utils.data import Dataset
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class EITDataset(Dataset):
|
| 17 |
+
"""
|
| 18 |
+
PyTorch Dataset for EIT (Electrical Impedance Tomography) data.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
data_dir: Base directory containing the dataset
|
| 22 |
+
subset: Which dataset to load ("CirclesOnly" or "FourObjects")
|
| 23 |
+
split: Which split to load ("train", "val", or "test")
|
| 24 |
+
image_resolution: Image resolution ("32_log", "64_log", "128_log", or "256")
|
| 25 |
+
load_to_memory: If True, load all data to RAM (faster but memory intensive)
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
data_dir: str,
|
| 31 |
+
subset: str = "CirclesOnly",
|
| 32 |
+
split: str = "train",
|
| 33 |
+
image_resolution: str = "128_log",
|
| 34 |
+
load_to_memory: bool = False
|
| 35 |
+
):
|
| 36 |
+
self.data_dir = Path(data_dir)
|
| 37 |
+
self.subset = subset
|
| 38 |
+
self.split = split
|
| 39 |
+
self.image_resolution = image_resolution
|
| 40 |
+
self.load_to_memory = load_to_memory
|
| 41 |
+
|
| 42 |
+
# Paths
|
| 43 |
+
self.subset_path = self.data_dir / subset
|
| 44 |
+
self.h5_path = self.subset_path / "dataset.h5"
|
| 45 |
+
|
| 46 |
+
# Map split name to file name
|
| 47 |
+
split_map = {"train": "train.txt", "val": "val.txt", "test": "test.txt"}
|
| 48 |
+
self.split_file = self.subset_path / "parameters" / split_map[split]
|
| 49 |
+
|
| 50 |
+
# Load split indices
|
| 51 |
+
self._load_split_indices()
|
| 52 |
+
|
| 53 |
+
# Load data to memory if requested
|
| 54 |
+
if self.load_to_memory:
|
| 55 |
+
self._load_to_memory()
|
| 56 |
+
else:
|
| 57 |
+
self.cached_data = None
|
| 58 |
+
|
| 59 |
+
def _load_split_indices(self):
|
| 60 |
+
"""Load the indices for this split."""
|
| 61 |
+
with open(self.split_file, 'r') as f:
|
| 62 |
+
self.indices = [int(line.strip()) for line in f if line.strip()]
|
| 63 |
+
|
| 64 |
+
def _load_to_memory(self):
|
| 65 |
+
"""Load all data for this split into memory."""
|
| 66 |
+
print(f"Loading {len(self.indices)} samples to memory...")
|
| 67 |
+
self.cached_data = []
|
| 68 |
+
|
| 69 |
+
with h5py.File(self.h5_path, "r") as h5_file:
|
| 70 |
+
voltage_data = h5_file["volt"]["16"]
|
| 71 |
+
image_data = h5_file["image"][self.image_resolution]
|
| 72 |
+
|
| 73 |
+
# Determine graph key
|
| 74 |
+
graph_key = self.image_resolution if self.image_resolution != "256" else "128_log"
|
| 75 |
+
has_graph = graph_key in h5_file["graph"]
|
| 76 |
+
|
| 77 |
+
for sample_idx in self.indices:
|
| 78 |
+
voltage = voltage_data[:, sample_idx].astype(np.float32)
|
| 79 |
+
image = image_data[:, :, sample_idx].astype(np.float32)
|
| 80 |
+
|
| 81 |
+
sample = {
|
| 82 |
+
'voltage_measurements': voltage,
|
| 83 |
+
'conductivity_map': image,
|
| 84 |
+
'sample_id': sample_idx
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
if has_graph:
|
| 88 |
+
graph = h5_file["graph"][graph_key][:, sample_idx].astype(np.float32)
|
| 89 |
+
sample['graph_representation'] = graph
|
| 90 |
+
|
| 91 |
+
self.cached_data.append(sample)
|
| 92 |
+
|
| 93 |
+
print("Data loaded to memory!")
|
| 94 |
+
|
| 95 |
+
def __len__(self) -> int:
|
| 96 |
+
return len(self.indices)
|
| 97 |
+
|
| 98 |
+
def __getitem__(self, idx: int) -> Dict[str, np.ndarray]:
|
| 99 |
+
"""Get a single sample."""
|
| 100 |
+
if self.cached_data is not None:
|
| 101 |
+
# Return from cached data
|
| 102 |
+
return self.cached_data[idx]
|
| 103 |
+
|
| 104 |
+
# Read from HDF5 file on-the-fly
|
| 105 |
+
sample_idx = self.indices[idx]
|
| 106 |
+
|
| 107 |
+
with h5py.File(self.h5_path, "r") as h5_file:
|
| 108 |
+
voltage = h5_file["volt"]["16"][:, sample_idx].astype(np.float32)
|
| 109 |
+
image = h5_file["image"][self.image_resolution][:, :, sample_idx].astype(np.float32)
|
| 110 |
+
|
| 111 |
+
sample = {
|
| 112 |
+
'voltage_measurements': voltage,
|
| 113 |
+
'conductivity_map': image,
|
| 114 |
+
'sample_id': sample_idx
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
# Add graph representation if available
|
| 118 |
+
graph_key = self.image_resolution if self.image_resolution != "256" else "128_log"
|
| 119 |
+
if graph_key in h5_file["graph"]:
|
| 120 |
+
graph = h5_file["graph"][graph_key][:, sample_idx].astype(np.float32)
|
| 121 |
+
sample['graph_representation'] = graph
|
| 122 |
+
|
| 123 |
+
return sample
|
| 124 |
+
|
| 125 |
+
def get_image_shape(self) -> Tuple[int, int]:
|
| 126 |
+
"""Get the shape of conductivity maps."""
|
| 127 |
+
resolution_map = {
|
| 128 |
+
"32_log": (32, 32),
|
| 129 |
+
"64_log": (64, 64),
|
| 130 |
+
"128_log": (128, 128),
|
| 131 |
+
"256": (256, 256)
|
| 132 |
+
}
|
| 133 |
+
return resolution_map.get(self.image_resolution, (128, 128))
|
| 134 |
+
|
| 135 |
+
def get_statistics(self) -> Dict:
|
| 136 |
+
"""Calculate dataset statistics."""
|
| 137 |
+
print("Calculating statistics...")
|
| 138 |
+
voltage_sum = np.zeros(256, dtype=np.float64)
|
| 139 |
+
voltage_sq_sum = np.zeros(256, dtype=np.float64)
|
| 140 |
+
image_sum = 0.0
|
| 141 |
+
image_sq_sum = 0.0
|
| 142 |
+
n_samples = len(self)
|
| 143 |
+
|
| 144 |
+
with h5py.File(self.h5_path, "r") as h5_file:
|
| 145 |
+
voltage_data = h5_file["volt"]["16"]
|
| 146 |
+
image_data = h5_file["image"][self.image_resolution]
|
| 147 |
+
|
| 148 |
+
for sample_idx in self.indices:
|
| 149 |
+
voltage = voltage_data[:, sample_idx]
|
| 150 |
+
image = image_data[:, :, sample_idx]
|
| 151 |
+
|
| 152 |
+
voltage_sum += voltage
|
| 153 |
+
voltage_sq_sum += voltage ** 2
|
| 154 |
+
image_sum += np.sum(image)
|
| 155 |
+
image_sq_sum += np.sum(image ** 2)
|
| 156 |
+
|
| 157 |
+
n_pixels = n_samples * self.get_image_shape()[0] * self.get_image_shape()[1]
|
| 158 |
+
|
| 159 |
+
stats = {
|
| 160 |
+
'voltage_mean': voltage_sum / n_samples,
|
| 161 |
+
'voltage_std': np.sqrt(voltage_sq_sum / n_samples - (voltage_sum / n_samples) ** 2),
|
| 162 |
+
'image_mean': image_sum / n_pixels,
|
| 163 |
+
'image_std': np.sqrt(image_sq_sum / n_pixels - (image_sum / n_pixels) ** 2),
|
| 164 |
+
'n_samples': n_samples
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
return stats
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
class EITDataModule:
|
| 171 |
+
"""
|
| 172 |
+
Convenience class to manage all splits of the EIT dataset.
|
| 173 |
+
|
| 174 |
+
Args:
|
| 175 |
+
data_dir: Base directory containing the dataset
|
| 176 |
+
subset: Which dataset to load ("CirclesOnly" or "FourObjects")
|
| 177 |
+
image_resolution: Image resolution ("32_log", "64_log", "128_log", or "256")
|
| 178 |
+
batch_size: Batch size for DataLoaders
|
| 179 |
+
num_workers: Number of workers for DataLoaders
|
| 180 |
+
load_to_memory: If True, load all data to RAM
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
def __init__(
|
| 184 |
+
self,
|
| 185 |
+
data_dir: str,
|
| 186 |
+
subset: str = "CirclesOnly",
|
| 187 |
+
image_resolution: str = "128_log",
|
| 188 |
+
batch_size: int = 32,
|
| 189 |
+
num_workers: int = 4,
|
| 190 |
+
load_to_memory: bool = False
|
| 191 |
+
):
|
| 192 |
+
self.data_dir = data_dir
|
| 193 |
+
self.subset = subset
|
| 194 |
+
self.image_resolution = image_resolution
|
| 195 |
+
self.batch_size = batch_size
|
| 196 |
+
self.num_workers = num_workers
|
| 197 |
+
self.load_to_memory = load_to_memory
|
| 198 |
+
|
| 199 |
+
# Create datasets
|
| 200 |
+
self.train_dataset = EITDataset(
|
| 201 |
+
data_dir, subset, "train", image_resolution, load_to_memory
|
| 202 |
+
)
|
| 203 |
+
self.val_dataset = EITDataset(
|
| 204 |
+
data_dir, subset, "val", image_resolution, load_to_memory
|
| 205 |
+
)
|
| 206 |
+
self.test_dataset = EITDataset(
|
| 207 |
+
data_dir, subset, "test", image_resolution, load_to_memory
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
def train_dataloader(self, **kwargs):
|
| 211 |
+
"""Get training DataLoader."""
|
| 212 |
+
from torch.utils.data import DataLoader
|
| 213 |
+
return DataLoader(
|
| 214 |
+
self.train_dataset,
|
| 215 |
+
batch_size=kwargs.get('batch_size', self.batch_size),
|
| 216 |
+
shuffle=True,
|
| 217 |
+
num_workers=kwargs.get('num_workers', self.num_workers),
|
| 218 |
+
pin_memory=True
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
def val_dataloader(self, **kwargs):
|
| 222 |
+
"""Get validation DataLoader."""
|
| 223 |
+
from torch.utils.data import DataLoader
|
| 224 |
+
return DataLoader(
|
| 225 |
+
self.val_dataset,
|
| 226 |
+
batch_size=kwargs.get('batch_size', self.batch_size),
|
| 227 |
+
shuffle=False,
|
| 228 |
+
num_workers=kwargs.get('num_workers', self.num_workers),
|
| 229 |
+
pin_memory=True
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
def test_dataloader(self, **kwargs):
|
| 233 |
+
"""Get test DataLoader."""
|
| 234 |
+
from torch.utils.data import DataLoader
|
| 235 |
+
return DataLoader(
|
| 236 |
+
self.test_dataset,
|
| 237 |
+
batch_size=kwargs.get('batch_size', self.batch_size),
|
| 238 |
+
shuffle=False,
|
| 239 |
+
num_workers=kwargs.get('num_workers', self.num_workers),
|
| 240 |
+
pin_memory=True
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
def get_statistics(self):
|
| 244 |
+
"""Get statistics for all splits."""
|
| 245 |
+
return {
|
| 246 |
+
'train': self.train_dataset.get_statistics(),
|
| 247 |
+
'val': self.val_dataset.get_statistics(),
|
| 248 |
+
'test': self.test_dataset.get_statistics()
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
# Example usage
|
| 253 |
+
if __name__ == "__main__":
|
| 254 |
+
print("="*60)
|
| 255 |
+
print("EIT Dataset Loader - Example Usage")
|
| 256 |
+
print("="*60)
|
| 257 |
+
|
| 258 |
+
# Create dataset
|
| 259 |
+
data_dir = "/mnt/f/MSS/EIT-Dataset/uploadedDataset"
|
| 260 |
+
|
| 261 |
+
print("\n1. Creating datasets...")
|
| 262 |
+
train_dataset = EITDataset(
|
| 263 |
+
data_dir=data_dir,
|
| 264 |
+
subset="CirclesOnly",
|
| 265 |
+
split="train",
|
| 266 |
+
image_resolution="128_log",
|
| 267 |
+
load_to_memory=False
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
print(f" Train dataset size: {len(train_dataset)}")
|
| 271 |
+
print(f" Image shape: {train_dataset.get_image_shape()}")
|
| 272 |
+
|
| 273 |
+
# Get a sample
|
| 274 |
+
print("\n2. Loading a sample...")
|
| 275 |
+
sample = train_dataset[0]
|
| 276 |
+
print(f" Keys: {list(sample.keys())}")
|
| 277 |
+
print(f" Voltage measurements shape: {sample['voltage_measurements'].shape}")
|
| 278 |
+
print(f" Conductivity map shape: {sample['conductivity_map'].shape}")
|
| 279 |
+
if 'graph_representation' in sample:
|
| 280 |
+
print(f" Graph representation shape: {sample['graph_representation'].shape}")
|
| 281 |
+
print(f" Sample ID: {sample['sample_id']}")
|
| 282 |
+
|
| 283 |
+
# Create DataModule
|
| 284 |
+
print("\n3. Creating EITDataModule...")
|
| 285 |
+
data_module = EITDataModule(
|
| 286 |
+
data_dir=data_dir,
|
| 287 |
+
subset="CirclesOnly",
|
| 288 |
+
image_resolution="128_log",
|
| 289 |
+
batch_size=4,
|
| 290 |
+
num_workers=0 # Set to 0 for testing, increase for training
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
print(f" Train samples: {len(data_module.train_dataset)}")
|
| 294 |
+
print(f" Val samples: {len(data_module.val_dataset)}")
|
| 295 |
+
print(f" Test samples: {len(data_module.test_dataset)}")
|
| 296 |
+
|
| 297 |
+
# Create DataLoader
|
| 298 |
+
print("\n4. Creating DataLoader and getting a batch...")
|
| 299 |
+
train_loader = data_module.train_dataloader()
|
| 300 |
+
batch = next(iter(train_loader))
|
| 301 |
+
print(f" Batch voltage shape: {batch['voltage_measurements'].shape}")
|
| 302 |
+
print(f" Batch image shape: {batch['conductivity_map'].shape}")
|
| 303 |
+
print(f" Batch IDs: {batch['sample_id'].tolist()}")
|
| 304 |
+
|
| 305 |
+
# Test different configurations
|
| 306 |
+
print("\n5. Testing different resolutions...")
|
| 307 |
+
for resolution in ["32_log", "64_log", "128_log", "256"]:
|
| 308 |
+
try:
|
| 309 |
+
ds = EITDataset(data_dir, "CirclesOnly", "train", resolution)
|
| 310 |
+
print(f" {resolution}: {len(ds)} samples, shape: {ds.get_image_shape()}")
|
| 311 |
+
except Exception as e:
|
| 312 |
+
print(f" {resolution}: Error - {e}")
|
| 313 |
+
|
| 314 |
+
print("\n" + "="*60)
|
| 315 |
+
print("All tests completed successfully!")
|
| 316 |
+
print("="*60)
|