jherzog commited on
Commit
97655a1
·
1 Parent(s): 9dbdf7e

Added docstrings to the custom classes.

Browse files
Files changed (2) hide show
  1. ben_txt_datamodule.py +116 -0
  2. example_data_loading.py +11 -11
ben_txt_datamodule.py CHANGED
@@ -188,6 +188,12 @@ class BENImageReader:
188
 
189
 
190
  class BENTxTDataset(Dataset):
 
 
 
 
 
 
191
  _expected_columns = {'s1_name', 'output', 'longitude', 'country', 'climate_zone', 'type', 'input', 'split', 'latitude', 'ID', 'patch_id', 'category', 'season'}
192
 
193
  def __init__(
@@ -208,7 +214,39 @@ class BENTxTDataset(Dataset):
208
  ref_token: Optional[str] = None,
209
  info_fn: Callable = lambda x: x,
210
  ):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
  super().__init__()
 
 
 
 
 
 
 
 
 
 
 
212
  self.image_reader = BENImageReader(lmdb_file, metadata_file, bands, img_size, upsample_mode, info_fn=info_fn)
213
 
214
  self.text_data = pd.read_parquet(metadata_file)
@@ -240,9 +278,24 @@ class BENTxTDataset(Dataset):
240
  assert len(self.ref_token) == 2, "Reference tokens must have length 2."
241
 
242
  def __len__(self):
 
243
  return len(self.text_data)
244
 
245
  def __getitem__(self, idx):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
  sample = self.text_data.iloc[idx]
247
  img_id = sample.patch_id
248
  img_data = self.image_reader[img_id]
@@ -265,6 +318,26 @@ class BENTxTDataset(Dataset):
265
 
266
 
267
  class BENTxTDataModule(pl.LightningDataModule):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
  train_ds = None
269
  val_ds = None
270
  test_ds = None
@@ -290,6 +363,33 @@ class BENTxTDataModule(pl.LightningDataModule):
290
  ref_token: Iterable[str] = None,
291
  info_fn: Optional[Callable] = lambda x: x,
292
  ):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
  super().__init__()
294
  self.num_workers_dataloader = num_workers_dataloader
295
  self.batch_size = batch_size
@@ -329,6 +429,18 @@ class BENTxTDataModule(pl.LightningDataModule):
329
  self.eval_transforms = image_transforms_eval if image_transforms_eval is not None else default_transform(img_size, mean=self.mean, std=self.std)
330
 
331
  def setup(self, stage: Optional[str] = None) -> None:
 
 
 
 
 
 
 
 
 
 
 
 
332
  if stage == "fit" or stage is None:
333
  self.train_ds = BENTxTDataset(
334
  **self.ds_kwargs,
@@ -356,13 +468,17 @@ class BENTxTDataModule(pl.LightningDataModule):
356
 
357
 
358
  def train_dataloader(self):
 
359
  return DataLoader(self.train_ds, batch_size=self.batch_size, num_workers=self.num_workers_dataloader, shuffle=True, pin_memory=self.pin_memory, collate_fn=collate_mixed)
360
 
361
  def val_dataloader(self):
 
362
  return DataLoader(self.val_ds, batch_size=self.batch_size, num_workers=self.num_workers_dataloader, shuffle=False, pin_memory=self.pin_memory, collate_fn=collate_mixed)
363
 
364
  def test_dataloader(self):
 
365
  return DataLoader(self.test_ds, batch_size=self.batch_size, num_workers=self.num_workers_dataloader, shuffle=False, pin_memory=self.pin_memory, collate_fn=collate_mixed)
366
 
367
  def bench_dataloader(self):
 
368
  return DataLoader(self.bench_ds, batch_size=self.batch_size, num_workers=self.num_workers_dataloader, shuffle=False, pin_memory=self.pin_memory, collate_fn=collate_mixed)
 
188
 
189
 
190
  class BENTxTDataset(Dataset):
191
+ """
192
+ PyTorch Dataset for BigEarthNet.txt.
193
+
194
+ This dataset class loads the textual annotations from BigEarthNet.txt toegther with the satellite imagery (Sentinel-1 and Sentinel-2) from the BigEarthNet-v2.0 dataset (converted to LMDB format).
195
+ It supports various filtering options to create custom dataset splits based on textual annotation metadata, such as type or category, or image metadata like country, season, and climate zone.
196
+ """
197
  _expected_columns = {'s1_name', 'output', 'longitude', 'country', 'climate_zone', 'type', 'input', 'split', 'latitude', 'ID', 'patch_id', 'category', 'season'}
198
 
199
  def __init__(
 
214
  ref_token: Optional[str] = None,
215
  info_fn: Callable = lambda x: x,
216
  ):
217
+ """
218
+ Initialize the BigEarthNet.txt Dataset.
219
+
220
+ Args:
221
+ lmdb_file: Path to the LMDB file containing the BigEarthNet-v2.0 image data.
222
+ metadata_file: Path to the BigEarthNet.txt Parquet file.
223
+ bands: Band names to load. Can be a predefined combination key ('RGB', 'S2-10m20m', 'S1S2-10m20m', 'all') or an iterable of band names, i.e., ('B04', 'B03', 'B02').
224
+ img_size: Target image size for interpolation (default: 120).
225
+ upsample_mode: Interpolation mode for resizing ('nearest', 'bilinear', 'bicubic', etc.).
226
+ Default: 'nearest'.
227
+ types: Optional filter for annotation types (e.g., 'binary', 'mcq', 'captioning', 'bounding box').
228
+ categories: Optional filter for annotation categories. See [here](TODO) for possible type-category combinations or retrieve them by yourself using some kind of database tool on the Parquet file.
229
+ countries: Optional filter for acquisition countries (e.g., 'Austria', 'Belgium', 'Finland', 'Ireland', 'Kosovo', 'Lithuania', 'Luxembourg', 'Portugal', 'Serbia', 'Switzerland').
230
+ seasons: Optional filter for seasons (e.g., 'Spring', 'Summer', 'Fall', 'Winter').
231
+ climate_zones: Optional filter for climate zones. See [here](TODO) for possible climate_zones values or retrieve them by yourself using some kind of database tool on the Parquet file.
232
+ transform: Optional torchvision transform to apply to images.
233
+ splits: Optional filter for dataset splits ('train', 'validation', 'test', 'bench').
234
+ point_token: Optional tuple of [start_token, end_token] to wrap <point> tags in text.
235
+ ref_token: Optional tuple of [start_token, end_token] to wrap <ref> tags in text.
236
+ info_fn: Optional callback function for logging information during initialization.
237
+ """
238
  super().__init__()
239
+
240
+ if isinstance(bands, str):
241
+ assert bands in _predefined_bandcombinations, f"{bands} not in predefined options: {_predefined_bandcombinations.keys()}"
242
+ bands = _predefined_bandcombinations[bands]
243
+ elif isinstance(bands, Iterable):
244
+ bands = list(bands)
245
+ elif bands is None:
246
+ bands = _predefined_bandcombinations['all']
247
+ else:
248
+ raise NotImplementedError(f"{bands} is not supported")
249
+
250
  self.image_reader = BENImageReader(lmdb_file, metadata_file, bands, img_size, upsample_mode, info_fn=info_fn)
251
 
252
  self.text_data = pd.read_parquet(metadata_file)
 
278
  assert len(self.ref_token) == 2, "Reference tokens must have length 2."
279
 
280
  def __len__(self):
281
+ """Return the number of samples in the dataset."""
282
  return len(self.text_data)
283
 
284
  def __getitem__(self, idx):
285
+ """
286
+ Get a sample from the dataset.
287
+
288
+ Args:
289
+ idx: Index of the sample to retrieve.
290
+
291
+ Returns:
292
+ dict: A dictionary containing:
293
+ - 'image_input': Tensor of shape (num_bands, img_size, img_size) containing normalized
294
+ satellite imagery.
295
+ - 'text_input': String containing the text query/caption with tokens replaced based on
296
+ point_token and ref_token settings.
297
+ - 'reference_output': The expected output/answer for the given input.
298
+ """
299
  sample = self.text_data.iloc[idx]
300
  img_id = sample.patch_id
301
  img_data = self.image_reader[img_id]
 
318
 
319
 
320
  class BENTxTDataModule(pl.LightningDataModule):
321
+ """
322
+ PyTorch Lightning DataModule for BigEarthNet.txt.
323
+
324
+ This DataModule provides a structured interface for loading and preprocessing BigEarthNet.txt
325
+ data for use with PyTorch Lightning training loops. It automatically handles train,
326
+ validation, test, and benchmark dataset splits, with proper train/eval transforms and
327
+ DataLoader configuration.
328
+
329
+ The module manages:
330
+ - Automatic dataset setup for different training stages
331
+ - Image preprocessing and normalization based on selected bands
332
+ - DataLoader creation with appropriate batch sizes and worker processes
333
+ - GPU pinning when CUDA is available
334
+
335
+ Attributes:
336
+ train_ds (BENTxTDataset): Training dataset instance.
337
+ val_ds (BENTxTDataset): Validation dataset instance.
338
+ test_ds (BENTxTDataset): Test dataset instance.
339
+ bench_ds (BENTxTDataset): Benchmark dataset instance.
340
+ """
341
  train_ds = None
342
  val_ds = None
343
  test_ds = None
 
363
  ref_token: Iterable[str] = None,
364
  info_fn: Optional[Callable] = lambda x: x,
365
  ):
366
+ """
367
+ Initialize the BigEarthNet.txt DataModule.
368
+
369
+ Args:
370
+ lmdb_file: Path to the LMDB file containing the BigEarthNet-v2.0 image data.
371
+ metadata_file: Path to the BigEarthNet.txt Parquet file.
372
+ bands: Band names to load. Can be a predefined combination key ('RGB', 'S2-10m20m', 'S1S2-10m20m', 'all') or an iterable of band names, i.e., ('B04', 'B03', 'B02').
373
+ img_size: Target image size for interpolation (default: 120).
374
+ upsample_mode: Interpolation mode for resizing ('nearest', 'bilinear', 'bicubic', etc.).
375
+ Default: 'nearest'.
376
+ types: Optional filter for annotation types (e.g., 'binary', 'mcq', 'captioning', 'bounding box').
377
+ categories: Optional filter for annotation categories. See [here](TODO) for possible type-category combinations or retrieve them by yourself using some kind of database tool on the Parquet file.
378
+ countries: Optional filter for acquisition countries (e.g., 'Austria', 'Belgium', 'Finland', 'Ireland', 'Kosovo', 'Lithuania', 'Luxembourg', 'Portugal', 'Serbia', 'Switzerland').
379
+ seasons: Optional filter for seasons (e.g., 'Spring', 'Summer', 'Fall', 'Winter').
380
+ climate_zones: Optional filter for climate zones. See [here](TODO) for possible climate_zones values or retrieve them by yourself using some kind of database tool on the Parquet file.
381
+ transform: Optional torchvision transform to apply to images.
382
+ num_workers_dataloader: Number of worker processes for DataLoaders (default: 4).
383
+ Set to 0 to disable multiprocessing.
384
+ batch_size: Batch size for DataLoaders (default: 16).
385
+ image_transforms_train: Custom image transforms for training. If None, uses default
386
+ augmentations (resize, flip, normalize).
387
+ image_transforms_eval: Custom image transforms for evaluation/validation. If None,
388
+ uses simple normalization.
389
+ point_token: Optional tuple of [start_token, end_token] to wrap <point> tags in text.
390
+ ref_token: Optional tuple of [start_token, end_token] to wrap <ref> tags in text.
391
+ info_fn: Optional callback function for logging during initialization.
392
+ """
393
  super().__init__()
394
  self.num_workers_dataloader = num_workers_dataloader
395
  self.batch_size = batch_size
 
429
  self.eval_transforms = image_transforms_eval if image_transforms_eval is not None else default_transform(img_size, mean=self.mean, std=self.std)
430
 
431
  def setup(self, stage: Optional[str] = None) -> None:
432
+ """
433
+ Create train/val/test/bench datasets based on the specified stage.
434
+
435
+ This method is called by PyTorch Lightning during trainer initialization.
436
+
437
+ Args:
438
+ stage: The training stage - one of 'fit', 'test', 'bench', or None. If None,
439
+ all datasets are created. Default: None.
440
+ - 'fit': Creates train and validation datasets
441
+ - 'test': Creates test dataset (includes both 'test' and 'bench' splits)
442
+ - 'bench': Creates benchmark dataset
443
+ """
444
  if stage == "fit" or stage is None:
445
  self.train_ds = BENTxTDataset(
446
  **self.ds_kwargs,
 
468
 
469
 
470
  def train_dataloader(self):
471
+ """Create and return the training DataLoader with shuffling and augmentations."""
472
  return DataLoader(self.train_ds, batch_size=self.batch_size, num_workers=self.num_workers_dataloader, shuffle=True, pin_memory=self.pin_memory, collate_fn=collate_mixed)
473
 
474
  def val_dataloader(self):
475
+ """Create and return the validation DataLoader without shuffling."""
476
  return DataLoader(self.val_ds, batch_size=self.batch_size, num_workers=self.num_workers_dataloader, shuffle=False, pin_memory=self.pin_memory, collate_fn=collate_mixed)
477
 
478
  def test_dataloader(self):
479
+ """Create and return the test DataLoader (includes both 'test' and 'bench' splits)."""
480
  return DataLoader(self.test_ds, batch_size=self.batch_size, num_workers=self.num_workers_dataloader, shuffle=False, pin_memory=self.pin_memory, collate_fn=collate_mixed)
481
 
482
  def bench_dataloader(self):
483
+ """Create and return the benchmark DataLoader."""
484
  return DataLoader(self.bench_ds, batch_size=self.batch_size, num_workers=self.num_workers_dataloader, shuffle=False, pin_memory=self.pin_memory, collate_fn=collate_mixed)
example_data_loading.py CHANGED
@@ -3,10 +3,10 @@ from ben_txt_datamodule import BENTxTDataset, BENTxTDataModule
3
  def create_dataset_example():
4
  # Datasets example using the Red (B04), Green (B03), and Blue (B02) band from the Sentinel-2 images.
5
  ds_rgb = BENTxTDataset(
6
- lmdb_file="Encoded-BigEarthNet/",
7
- metadata_file="BigEarthNet.txt.parquet",
8
- bands=("B04", "B03", "B02"),
9
- img_size=120
10
  )
11
 
12
  sample = ds_rgb[0]
@@ -18,19 +18,19 @@ def create_datamodule_example():
18
  # Lightning DataModule example using the 10m and 20m spatial resolution bands from Sentinel-1 and Sentinel-2 and multiple metadata filters.
19
  # The datamodule will create 4 dataloaders: train, val, test, and bench.
20
  dm = BENTxTDataModule(
21
- image_lmdb_file="Encoded-BigEarthNet/",
22
- metadata_file="BigEarthNet.txt.parquet",
23
- bands='S1S2-10m20m',
24
- img_size=120,
25
- batch_size=1,
26
- num_workers_dataloader=0,
27
  types = ['mcq'],
28
  categories = ['climate zone'],
29
  countries = ['Portugal', 'Finland'],
30
  seasons = ['Summer'],
31
  climate_zones = None,
32
  point_token = ['<point>', '</point>'],
33
- ref_token=['<ref>', '</ref>']
34
  )
35
  dm.setup()
36
 
 
3
  def create_dataset_example():
4
  # Datasets example using the Red (B04), Green (B03), and Blue (B02) band from the Sentinel-2 images.
5
  ds_rgb = BENTxTDataset(
6
+ lmdb_file = "Encoded-BigEarthNet/",
7
+ metadata_file = "BigEarthNet.txt.parquet",
8
+ bands = ("B04", "B03", "B02"),
9
+ img_size = 120
10
  )
11
 
12
  sample = ds_rgb[0]
 
18
  # Lightning DataModule example using the 10m and 20m spatial resolution bands from Sentinel-1 and Sentinel-2 and multiple metadata filters.
19
  # The datamodule will create 4 dataloaders: train, val, test, and bench.
20
  dm = BENTxTDataModule(
21
+ image_lmdb_file = "Encoded-BigEarthNet/",
22
+ metadata_file = "BigEarthNet.txt.parquet",
23
+ bands = 'S1S2-10m20m',
24
+ img_size = 120,
25
+ batch_size = 1,
26
+ num_workers_dataloader = 0,
27
  types = ['mcq'],
28
  categories = ['climate zone'],
29
  countries = ['Portugal', 'Finland'],
30
  seasons = ['Summer'],
31
  climate_zones = None,
32
  point_token = ['<point>', '</point>'],
33
+ ref_token = ['<ref>', '</ref>']
34
  )
35
  dm.setup()
36