AymanAmeen commited on
Commit
7beec83
·
verified ·
1 Parent(s): 30edaed

Create eit_dataset_loader.py

Browse files
Files changed (1) hide show
  1. eit_dataset_loader.py +229 -0
eit_dataset_loader.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ HuggingFace Dataset Loader for SimEIT - Electrical Impedance Tomography Dataset
3
+
4
+ This loader supports loading EIT data from HDF5 files with train/validation/test splits.
5
+ The dataset contains voltage measurements and conductivity maps (images) at different resolutions.
6
+ """
7
+
8
+ import datasets
9
+ import h5py
10
+ import numpy as np
11
+ from pathlib import Path
12
+
13
+
14
+ class EITDatasetConfig(datasets.BuilderConfig):
15
+ """BuilderConfig for EIT Dataset."""
16
+
17
+ def __init__(self, subset="CirclesOnly", image_resolution="128_log", **kwargs):
18
+ """
19
+ Args:
20
+ subset: Which dataset subset to load ("CirclesOnly" or "FourObjects")
21
+ image_resolution: Image resolution to load ("32_log", "64_log", "128_log", or "256")
22
+ **kwargs: keyword arguments forwarded to super.
23
+ """
24
+ super(EITDatasetConfig, self).__init__(**kwargs)
25
+ self.subset = subset
26
+ self.image_resolution = image_resolution
27
+
28
+
29
+ class EITDataset(datasets.GeneratorBasedBuilder):
30
+ """A custom dataset loader for EIT (Electrical Impedance Tomography) .h5 files."""
31
+
32
+ BUILDER_CONFIGS = [
33
+ EITDatasetConfig(
34
+ name="circles_128",
35
+ version=datasets.Version("1.0.0"),
36
+ description="CirclesOnly dataset with 128x128 resolution (log scale)",
37
+ subset="CirclesOnly",
38
+ image_resolution="128_log"
39
+ ),
40
+ EITDatasetConfig(
41
+ name="circles_256",
42
+ version=datasets.Version("1.0.0"),
43
+ description="CirclesOnly dataset with 256x256 resolution",
44
+ subset="CirclesOnly",
45
+ image_resolution="256"
46
+ ),
47
+ EITDatasetConfig(
48
+ name="four_objects_128",
49
+ version=datasets.Version("1.0.0"),
50
+ description="FourObjects dataset with 128x128 resolution (log scale)",
51
+ subset="FourObjects",
52
+ image_resolution="128_log"
53
+ ),
54
+ EITDatasetConfig(
55
+ name="four_objects_256",
56
+ version=datasets.Version("1.0.0"),
57
+ description="FourObjects dataset with 256x256 resolution",
58
+ subset="FourObjects",
59
+ image_resolution="256"
60
+ ),
61
+ ]
62
+
63
+ DEFAULT_CONFIG_NAME = "circles_128"
64
+
65
+ def _info(self):
66
+ """Define the features (columns) of the dataset."""
67
+ # Determine image shape based on resolution
68
+ if self.config.image_resolution == "256":
69
+ image_shape = (256, 256)
70
+ elif self.config.image_resolution == "128_log":
71
+ image_shape = (128, 128)
72
+ elif self.config.image_resolution == "64_log":
73
+ image_shape = (64, 64)
74
+ elif self.config.image_resolution == "32_log":
75
+ image_shape = (32, 32)
76
+ else:
77
+ image_shape = (128, 128) # default
78
+
79
+ return datasets.DatasetInfo(
80
+ description=(
81
+ "SimEIT: A Scalable Simulation Framework for Generating Large-Scale "
82
+ "Electrical Impedance Tomography Datasets. This dataset contains "
83
+ "voltage measurements and corresponding conductivity maps for EIT imaging."
84
+ ),
85
+ features=datasets.Features({
86
+ "voltage_measurements": datasets.Sequence(datasets.Value("float32")),
87
+ "conductivity_map": datasets.Array2D(shape=image_shape, dtype="float32"),
88
+ "graph_representation": datasets.Sequence(datasets.Value("float32")),
89
+ "sample_id": datasets.Value("int32"),
90
+ }),
91
+ homepage="https://huggingface.co/datasets/your-dataset-repo",
92
+ license="apache-2.0",
93
+ citation="",
94
+ )
95
+
96
+ def _split_generators(self, dl_manager):
97
+ """Define data splits and their corresponding files."""
98
+ # Get the base path - assumes the script is in the dataset directory
99
+ # or you can modify this to point to your data location
100
+ base_path = Path(self.config.data_dir) if self.config.data_dir else Path(".")
101
+ subset_path = base_path / self.config.subset
102
+
103
+ # Path to the HDF5 file
104
+ h5_file = subset_path / "dataset.h5"
105
+
106
+ # Paths to split files
107
+ train_split_file = subset_path / "parameters" / "train.txt"
108
+ val_split_file = subset_path / "parameters" / "val.txt"
109
+ test_split_file = subset_path / "parameters" / "test.txt"
110
+
111
+ return [
112
+ datasets.SplitGenerator(
113
+ name=datasets.Split.TRAIN,
114
+ gen_kwargs={
115
+ "filepath": str(h5_file),
116
+ "split_file": str(train_split_file),
117
+ "image_resolution": self.config.image_resolution,
118
+ }
119
+ ),
120
+ datasets.SplitGenerator(
121
+ name=datasets.Split.VALIDATION,
122
+ gen_kwargs={
123
+ "filepath": str(h5_file),
124
+ "split_file": str(val_split_file),
125
+ "image_resolution": self.config.image_resolution,
126
+ }
127
+ ),
128
+ datasets.SplitGenerator(
129
+ name=datasets.Split.TEST,
130
+ gen_kwargs={
131
+ "filepath": str(h5_file),
132
+ "split_file": str(test_split_file),
133
+ "image_resolution": self.config.image_resolution,
134
+ }
135
+ ),
136
+ ]
137
+
138
+ def _generate_examples(self, filepath, split_file, image_resolution):
139
+ """
140
+ Read the .h5 file and yield examples based on the split file.
141
+
142
+ Args:
143
+ filepath: Path to the HDF5 file
144
+ split_file: Path to the text file containing sample indices for this split
145
+ image_resolution: Resolution of images to load
146
+ """
147
+ # Read the split indices
148
+ with open(split_file, 'r') as f:
149
+ indices = [int(line.strip()) for line in f if line.strip()]
150
+
151
+ # Open the HDF5 file and load data
152
+ with h5py.File(filepath, "r") as h5_file:
153
+ # Access the datasets
154
+ voltage_data = h5_file["volt"]["16"] # Shape: (256, 110000)
155
+ image_data = h5_file["image"][image_resolution] # Shape: (H, W, 110000)
156
+
157
+ # Check if graph data exists for this resolution
158
+ graph_key = image_resolution if image_resolution != "256" else "128_log"
159
+ if graph_key in h5_file["graph"]:
160
+ graph_data = h5_file["graph"][graph_key]
161
+ else:
162
+ graph_data = None
163
+
164
+ # Iterate over the indices for this split
165
+ for idx, sample_idx in enumerate(indices):
166
+ # Extract data for this sample
167
+ voltage_measurements = voltage_data[:, sample_idx].astype(np.float32)
168
+ conductivity_map = image_data[:, :, sample_idx].astype(np.float32)
169
+
170
+ # Prepare the example
171
+ example = {
172
+ "voltage_measurements": voltage_measurements.tolist(),
173
+ "conductivity_map": conductivity_map,
174
+ "sample_id": sample_idx,
175
+ }
176
+
177
+ # Add graph representation if available
178
+ if graph_data is not None:
179
+ graph_representation = graph_data[:, sample_idx].astype(np.float32)
180
+ example["graph_representation"] = graph_representation.tolist()
181
+ else:
182
+ # Provide empty list if graph data is not available
183
+ example["graph_representation"] = []
184
+
185
+ yield idx, example
186
+
187
+
188
+ # Example usage:
189
+ if __name__ == "__main__":
190
+ # Example 1: Load the dataset with default configuration
191
+ print("Loading CirclesOnly dataset with 128x128 resolution...")
192
+ dataset = datasets.load_dataset(
193
+ __file__,
194
+ name="circles_128",
195
+ data_dir="/mnt/f/MSS/EIT-Dataset/uploadedDataset",
196
+ trust_remote_code=True
197
+ )
198
+
199
+ print(f"Train split size: {len(dataset['train'])}")
200
+ print(f"Validation split size: {len(dataset['validation'])}")
201
+ print(f"Test split size: {len(dataset['test'])}")
202
+
203
+ # Access a single example
204
+ example = dataset['train'][0]
205
+ print("\nExample structure:")
206
+ print(f" Voltage measurements shape: {len(example['voltage_measurements'])}")
207
+ print(f" Conductivity map shape: {example['conductivity_map'].shape}")
208
+ print(f" Graph representation shape: {len(example['graph_representation'])}")
209
+ print(f" Sample ID: {example['sample_id']}")
210
+
211
+ # Example 2: Load FourObjects dataset
212
+ print("\n" + "="*50)
213
+ print("Loading FourObjects dataset with 256x256 resolution...")
214
+ dataset_4obj = datasets.load_dataset(
215
+ __file__,
216
+ name="four_objects_256",
217
+ data_dir="/mnt/f/MSS/EIT-Dataset/uploadedDataset",
218
+ trust_remote_code=True
219
+ )
220
+
221
+ print(f"Train split size: {len(dataset_4obj['train'])}")
222
+
223
+ # Example 3: Iterate through a few samples
224
+ print("\n" + "="*50)
225
+ print("Iterating through first 3 samples...")
226
+ for i, sample in enumerate(dataset['train'].select(range(3))):
227
+ print(f"Sample {i}: ID={sample['sample_id']}, "
228
+ f"Voltage shape={len(sample['voltage_measurements'])}, "
229
+ f"Image shape={sample['conductivity_map'].shape}")