Upload 2 files
Browse files- script/load_dataset.py +3 -49
- script/scenarios.py +88 -58
script/load_dataset.py
CHANGED
|
@@ -3,7 +3,7 @@
|
|
| 3 |
Utilities for loading and manipulating HDF5 dataset optimized for ML.
|
| 4 |
|
| 5 |
Features:
|
| 6 |
-
- Fast extraction by
|
| 7 |
- Create temporal sequences for LSTM/Transformer
|
| 8 |
- Automatic data normalization
|
| 9 |
- Filter by metadata (angle, resolution, etc.)
|
|
@@ -42,7 +42,6 @@ class MLDatasetLoader:
|
|
| 42 |
with h5py.File(self.hdf5_path, 'r') as f:
|
| 43 |
meta = f['metadata']
|
| 44 |
self.classes = json.loads(meta.attrs['classes'])
|
| 45 |
-
self.satellites = json.loads(meta.attrs['satellites'])
|
| 46 |
self.n_groups = meta.attrs['n_total_groups']
|
| 47 |
self.nodata = meta.attrs['nodata_value']
|
| 48 |
|
|
@@ -52,11 +51,6 @@ class MLDatasetLoader:
|
|
| 52 |
entries_json = f[f'index/by_class/{class_name}'].attrs['entries_json']
|
| 53 |
self.class_index[class_name] = json.loads(entries_json)
|
| 54 |
|
| 55 |
-
self.satellite_index = {}
|
| 56 |
-
for sat_name in f['index/by_satellite'].keys():
|
| 57 |
-
entries_json = f[f'index/by_satellite/{sat_name}'].attrs['entries_json']
|
| 58 |
-
self.satellite_index[sat_name] = json.loads(entries_json)
|
| 59 |
-
|
| 60 |
temp_ranges_json = f['index/temporal_ranges'].attrs['ranges_json']
|
| 61 |
self.temporal_ranges = json.loads(temp_ranges_json)
|
| 62 |
|
|
@@ -315,7 +309,7 @@ class MLDatasetLoader:
|
|
| 315 |
scale_type: 'intensity' (default), 'amplitude' (data**0.5), or 'log10' (log10 scale)
|
| 316 |
|
| 317 |
Returns:
|
| 318 |
-
Dict containing: images, masks, timestamps,
|
| 319 |
"""
|
| 320 |
with h5py.File(self.hdf5_path, 'r') as f:
|
| 321 |
# Support dual-pol
|
|
@@ -353,7 +347,6 @@ class MLDatasetLoader:
|
|
| 353 |
# Load data for common timestamps
|
| 354 |
images_list = []
|
| 355 |
masks_list = []
|
| 356 |
-
satellites_list = []
|
| 357 |
angles_list = []
|
| 358 |
|
| 359 |
# First, determine minimum dimensions
|
|
@@ -383,7 +376,6 @@ class MLDatasetLoader:
|
|
| 383 |
masks_list.append(mask_pol)
|
| 384 |
|
| 385 |
if pol == polarisation[0]: # Only once
|
| 386 |
-
satellites_list = data_pol['satellites'][:][indices]
|
| 387 |
angles_list = data_pol['angles_incidence'][:][indices]
|
| 388 |
|
| 389 |
# Stack in last dimension: (H, W, T, 2)
|
|
@@ -393,7 +385,6 @@ class MLDatasetLoader:
|
|
| 393 |
masks = np.maximum(masks_list[0], masks_list[1])
|
| 394 |
|
| 395 |
timestamps = common_ts
|
| 396 |
-
satellites = satellites_list
|
| 397 |
angles = angles_list
|
| 398 |
|
| 399 |
metadata = {
|
|
@@ -414,7 +405,6 @@ class MLDatasetLoader:
|
|
| 414 |
images = pol_data['images'][:]
|
| 415 |
masks = pol_data['masks'][:]
|
| 416 |
timestamps = pol_data['timestamps'][:]
|
| 417 |
-
satellites = pol_data['satellites'][:]
|
| 418 |
angles = pol_data['angles_incidence'][:]
|
| 419 |
|
| 420 |
# Filter by dates
|
|
@@ -431,7 +421,6 @@ class MLDatasetLoader:
|
|
| 431 |
images = images[:, :, mask_ts]
|
| 432 |
masks = masks[:, :, mask_ts]
|
| 433 |
timestamps = timestamps[mask_ts]
|
| 434 |
-
satellites = satellites[mask_ts]
|
| 435 |
angles = angles[mask_ts]
|
| 436 |
|
| 437 |
metadata = {
|
|
@@ -468,7 +457,6 @@ class MLDatasetLoader:
|
|
| 468 |
'images': images,
|
| 469 |
'masks': masks,
|
| 470 |
'timestamps': [t.decode('utf-8') for t in timestamps],
|
| 471 |
-
'satellites': [s.decode('utf-8') for s in satellites],
|
| 472 |
'angles_incidence': angles,
|
| 473 |
'metadata': metadata,
|
| 474 |
'group': group_name,
|
|
@@ -489,41 +477,13 @@ class MLDatasetLoader:
|
|
| 489 |
group_to_class[group] = class_name
|
| 490 |
return group_to_class
|
| 491 |
|
| 492 |
-
|
| 493 |
-
def get_samples_by_satellite(
|
| 494 |
-
self,
|
| 495 |
-
satellite: str,
|
| 496 |
-
class_filter: Optional[str] = None
|
| 497 |
-
) -> List[Dict]:
|
| 498 |
-
"""
|
| 499 |
-
Return samples from a specific satellite.
|
| 500 |
-
|
| 501 |
-
Args:
|
| 502 |
-
satellite: Satellite name ('PAZ', 'TerraSAR-X', 'TanDEM-X')
|
| 503 |
-
class_filter: Optional, filter by class
|
| 504 |
-
|
| 505 |
-
Returns:
|
| 506 |
-
List of dictionaries with path, timestamp, class, group
|
| 507 |
-
"""
|
| 508 |
-
if satellite not in self.satellite_index:
|
| 509 |
-
return []
|
| 510 |
-
|
| 511 |
-
samples = self.satellite_index[satellite]
|
| 512 |
-
|
| 513 |
-
if class_filter:
|
| 514 |
-
samples = [s for s in samples if s['class'] == class_filter]
|
| 515 |
-
|
| 516 |
-
return samples
|
| 517 |
-
|
| 518 |
def get_statistics_summary(self) -> Dict:
|
| 519 |
"""Return a summary of dataset statistics"""
|
| 520 |
stats = {
|
| 521 |
'by_class': {},
|
| 522 |
-
'by_satellite': {},
|
| 523 |
'global': {
|
| 524 |
'n_groups': self.n_groups,
|
| 525 |
'n_classes': len(self.classes),
|
| 526 |
-
'n_satellites': len(self.satellites)
|
| 527 |
}
|
| 528 |
}
|
| 529 |
|
|
@@ -534,12 +494,6 @@ class MLDatasetLoader:
|
|
| 534 |
'n_groups': len(groups),
|
| 535 |
'groups': groups
|
| 536 |
}
|
| 537 |
-
|
| 538 |
-
# Stats by satellite
|
| 539 |
-
for sat_name in self.satellites:
|
| 540 |
-
samples = self.get_samples_by_satellite(sat_name)
|
| 541 |
-
stats['by_satellite'][sat_name] = {
|
| 542 |
-
'n_samples': len(samples)
|
| 543 |
-
}
|
| 544 |
|
| 545 |
return stats
|
|
|
|
| 3 |
Utilities for loading and manipulating HDF5 dataset optimized for ML.
|
| 4 |
|
| 5 |
Features:
|
| 6 |
+
- Fast extraction by class, temporal period
|
| 7 |
- Create temporal sequences for LSTM/Transformer
|
| 8 |
- Automatic data normalization
|
| 9 |
- Filter by metadata (angle, resolution, etc.)
|
|
|
|
| 42 |
with h5py.File(self.hdf5_path, 'r') as f:
|
| 43 |
meta = f['metadata']
|
| 44 |
self.classes = json.loads(meta.attrs['classes'])
|
|
|
|
| 45 |
self.n_groups = meta.attrs['n_total_groups']
|
| 46 |
self.nodata = meta.attrs['nodata_value']
|
| 47 |
|
|
|
|
| 51 |
entries_json = f[f'index/by_class/{class_name}'].attrs['entries_json']
|
| 52 |
self.class_index[class_name] = json.loads(entries_json)
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
temp_ranges_json = f['index/temporal_ranges'].attrs['ranges_json']
|
| 55 |
self.temporal_ranges = json.loads(temp_ranges_json)
|
| 56 |
|
|
|
|
| 309 |
scale_type: 'intensity' (default), 'amplitude' (data**0.5), or 'log10' (log10 scale)
|
| 310 |
|
| 311 |
Returns:
|
| 312 |
+
Dict containing: images, masks, timestamps, metadata
|
| 313 |
"""
|
| 314 |
with h5py.File(self.hdf5_path, 'r') as f:
|
| 315 |
# Support dual-pol
|
|
|
|
| 347 |
# Load data for common timestamps
|
| 348 |
images_list = []
|
| 349 |
masks_list = []
|
|
|
|
| 350 |
angles_list = []
|
| 351 |
|
| 352 |
# First, determine minimum dimensions
|
|
|
|
| 376 |
masks_list.append(mask_pol)
|
| 377 |
|
| 378 |
if pol == polarisation[0]: # Only once
|
|
|
|
| 379 |
angles_list = data_pol['angles_incidence'][:][indices]
|
| 380 |
|
| 381 |
# Stack in last dimension: (H, W, T, 2)
|
|
|
|
| 385 |
masks = np.maximum(masks_list[0], masks_list[1])
|
| 386 |
|
| 387 |
timestamps = common_ts
|
|
|
|
| 388 |
angles = angles_list
|
| 389 |
|
| 390 |
metadata = {
|
|
|
|
| 405 |
images = pol_data['images'][:]
|
| 406 |
masks = pol_data['masks'][:]
|
| 407 |
timestamps = pol_data['timestamps'][:]
|
|
|
|
| 408 |
angles = pol_data['angles_incidence'][:]
|
| 409 |
|
| 410 |
# Filter by dates
|
|
|
|
| 421 |
images = images[:, :, mask_ts]
|
| 422 |
masks = masks[:, :, mask_ts]
|
| 423 |
timestamps = timestamps[mask_ts]
|
|
|
|
| 424 |
angles = angles[mask_ts]
|
| 425 |
|
| 426 |
metadata = {
|
|
|
|
| 457 |
'images': images,
|
| 458 |
'masks': masks,
|
| 459 |
'timestamps': [t.decode('utf-8') for t in timestamps],
|
|
|
|
| 460 |
'angles_incidence': angles,
|
| 461 |
'metadata': metadata,
|
| 462 |
'group': group_name,
|
|
|
|
| 477 |
group_to_class[group] = class_name
|
| 478 |
return group_to_class
|
| 479 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 480 |
def get_statistics_summary(self) -> Dict:
|
| 481 |
"""Return a summary of dataset statistics"""
|
| 482 |
stats = {
|
| 483 |
'by_class': {},
|
|
|
|
| 484 |
'global': {
|
| 485 |
'n_groups': self.n_groups,
|
| 486 |
'n_classes': len(self.classes),
|
|
|
|
| 487 |
}
|
| 488 |
}
|
| 489 |
|
|
|
|
| 494 |
'n_groups': len(groups),
|
| 495 |
'groups': groups
|
| 496 |
}
|
| 497 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 498 |
|
| 499 |
return stats
|
script/scenarios.py
CHANGED
|
@@ -671,18 +671,21 @@ def scenario_4_domain_adaptation_satellite(
|
|
| 671 |
max_mask_value: int = 1,
|
| 672 |
max_mask_percentage: float = 10.0,
|
| 673 |
min_valid_percentage: float = 50.0,
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
|
|
|
|
|
|
|
|
|
| 677 |
scale_type: str = 'intensity',
|
| 678 |
skip_optim_offset: bool = True,
|
| 679 |
verbose: bool = True
|
| 680 |
) -> Dict:
|
| 681 |
"""
|
| 682 |
-
SCENARIO 4: Domain Adaptation
|
| 683 |
|
| 684 |
-
Objective: Learn on
|
| 685 |
-
Source:
|
| 686 |
|
| 687 |
Args:
|
| 688 |
loader: Instance of MLDatasetLoader
|
|
@@ -690,32 +693,37 @@ def scenario_4_domain_adaptation_satellite(
|
|
| 690 |
max_mask_value: Max mask value
|
| 691 |
max_mask_percentage: Max % of pixels with mask > max_mask_value
|
| 692 |
min_valid_percentage: Min % of valid pixels
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 696 |
verbose: Display detailed information
|
| 697 |
|
| 698 |
Returns:
|
| 699 |
Dict with:
|
| 700 |
-
- X_source
|
| 701 |
-
- X_target
|
| 702 |
-
- y_source: Array (N_source,) - labels
|
| 703 |
-
-
|
| 704 |
-
-
|
|
|
|
| 705 |
- masks_source: Array (N_source, window_size, window_size)
|
| 706 |
- masks_target: Array (N_target, window_size, window_size)
|
| 707 |
-
-
|
|
|
|
| 708 |
"""
|
| 709 |
print(f"\n{'='*70}")
|
| 710 |
-
print("SCENARIO 4: Domain Adaptation
|
| 711 |
print(f"{'='*70}")
|
| 712 |
print(f"Parameters:")
|
| 713 |
print(f" - Windows: {window_size}x{window_size}")
|
| 714 |
-
print(f" -
|
| 715 |
-
print(f" -
|
| 716 |
-
print(f" -
|
| 717 |
-
print(f" - Orbit: {orbit}")
|
| 718 |
-
print(f" - Source: PAZ 2020 (labeled) -> Target: TerraSAR-X 2008 (unlabeled)")
|
| 719 |
print(f" - Mask max: {max_mask_value}, {max_mask_percentage}%\n")
|
| 720 |
|
| 721 |
learning_classes = [c for c in loader.classes if c != 'STUDY']
|
|
@@ -724,6 +732,7 @@ def scenario_4_domain_adaptation_satellite(
|
|
| 724 |
X_source_all = []
|
| 725 |
X_target_all = []
|
| 726 |
y_source_all = []
|
|
|
|
| 727 |
groups_source_all = []
|
| 728 |
groups_target_all = []
|
| 729 |
masks_source_all = []
|
|
@@ -744,23 +753,23 @@ def scenario_4_domain_adaptation_satellite(
|
|
| 744 |
for group in loader.get_groups_by_class(class_name):
|
| 745 |
group_to_class[group] = class_name
|
| 746 |
|
| 747 |
-
# SOURCE
|
| 748 |
print("=" * 70)
|
| 749 |
-
print("Loading SOURCE (
|
| 750 |
-
|
| 751 |
-
for group_name in
|
| 752 |
class_name = group_to_class[group_name]
|
| 753 |
|
| 754 |
# Update progress bar description with current group
|
| 755 |
if verbose:
|
| 756 |
-
|
| 757 |
|
| 758 |
try:
|
| 759 |
-
# Load
|
| 760 |
data = loader.load_data(
|
| 761 |
group_name=group_name,
|
| 762 |
-
orbit=
|
| 763 |
-
polarisation=
|
| 764 |
start_date=source_date,
|
| 765 |
end_date=source_date,
|
| 766 |
normalize=False,
|
|
@@ -780,7 +789,13 @@ def scenario_4_domain_adaptation_satellite(
|
|
| 780 |
|
| 781 |
# Take the first PAZ acquisition
|
| 782 |
idx = paz_indices[0]
|
| 783 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 784 |
mask = data['masks'][:, :, idx]
|
| 785 |
|
| 786 |
# Extract windows
|
|
@@ -801,32 +816,32 @@ def scenario_4_domain_adaptation_satellite(
|
|
| 801 |
n_windows = len(windows)
|
| 802 |
|
| 803 |
# Store individually
|
| 804 |
-
for
|
| 805 |
-
X_source_all.append(windows[
|
| 806 |
y_source_all.append(class_to_int[class_name])
|
| 807 |
groups_source_all.append(group_to_int[group_name])
|
| 808 |
-
masks_source_all.append(window_masks[
|
| 809 |
group_names_source_all.append(group_name)
|
| 810 |
|
| 811 |
except Exception as e:
|
| 812 |
continue
|
| 813 |
|
| 814 |
-
# TARGET
|
| 815 |
print("\n" + "=" * 70)
|
| 816 |
-
print("Loading TARGET (
|
| 817 |
-
|
| 818 |
-
for group_name in
|
| 819 |
class_name = group_to_class[group_name]
|
| 820 |
|
| 821 |
# Update progress bar description with current group
|
| 822 |
if verbose:
|
| 823 |
-
|
| 824 |
|
| 825 |
try:
|
| 826 |
data = loader.load_data(
|
| 827 |
group_name=group_name,
|
| 828 |
-
orbit=
|
| 829 |
-
polarisation=
|
| 830 |
start_date=target_date,
|
| 831 |
end_date=target_date,
|
| 832 |
normalize=False,
|
|
@@ -837,15 +852,21 @@ def scenario_4_domain_adaptation_satellite(
|
|
| 837 |
if data['images'].shape[2] == 0:
|
| 838 |
continue
|
| 839 |
|
| 840 |
-
# Filter by
|
| 841 |
satellites = np.array(data['satellites'])
|
| 842 |
-
|
| 843 |
|
| 844 |
-
if len(
|
| 845 |
continue
|
| 846 |
|
| 847 |
-
idx =
|
| 848 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 849 |
mask = data['masks'][:, :, idx]
|
| 850 |
|
| 851 |
windows, window_masks, positions = loader.extract_windows(
|
|
@@ -855,7 +876,8 @@ def scenario_4_domain_adaptation_satellite(
|
|
| 855 |
stride=window_size,
|
| 856 |
max_mask_value=max_mask_value,
|
| 857 |
max_mask_percentage=max_mask_percentage,
|
| 858 |
-
|
|
|
|
| 859 |
)
|
| 860 |
|
| 861 |
if windows is None:
|
|
@@ -866,6 +888,7 @@ def scenario_4_domain_adaptation_satellite(
|
|
| 866 |
# Store individually
|
| 867 |
for idx_win in range(n_windows):
|
| 868 |
X_target_all.append(windows[idx_win])
|
|
|
|
| 869 |
groups_target_all.append(group_to_int[group_name])
|
| 870 |
masks_target_all.append(window_masks[idx_win])
|
| 871 |
group_names_target_all.append(group_name)
|
|
@@ -874,11 +897,12 @@ def scenario_4_domain_adaptation_satellite(
|
|
| 874 |
continue
|
| 875 |
|
| 876 |
if len(X_source_all) == 0 or len(X_target_all) == 0:
|
| 877 |
-
raise ValueError("No source
|
| 878 |
|
| 879 |
X_source = np.array(X_source_all, dtype=np.float32)
|
| 880 |
X_target = np.array(X_target_all, dtype=np.float32)
|
| 881 |
y_source = np.array(y_source_all)
|
|
|
|
| 882 |
groups_source = np.array(groups_source_all)
|
| 883 |
groups_target = np.array(groups_target_all)
|
| 884 |
masks_source = np.array(masks_source_all)
|
|
@@ -887,14 +911,15 @@ def scenario_4_domain_adaptation_satellite(
|
|
| 887 |
if verbose:
|
| 888 |
print(f"\n{'='*70}")
|
| 889 |
print(f"Results:")
|
| 890 |
-
print(f" - SOURCE (
|
| 891 |
print(f" X_source.shape: {X_source.shape}")
|
| 892 |
print(f" y_source.shape: {y_source.shape}")
|
| 893 |
print(f" groups_source.shape: {groups_source.shape}")
|
| 894 |
print(f" Unique classes: {np.unique(y_source, return_counts=True)}")
|
| 895 |
print(f" Unique groups: {len(np.unique(groups_source))}")
|
| 896 |
-
print(f" - TARGET (
|
| 897 |
print(f" X_target.shape: {X_target.shape}")
|
|
|
|
| 898 |
print(f" groups_target.shape: {groups_target.shape}")
|
| 899 |
print(f" Unique groups: {len(np.unique(groups_target))}")
|
| 900 |
|
|
@@ -902,6 +927,7 @@ def scenario_4_domain_adaptation_satellite(
|
|
| 902 |
'X_source': X_source,
|
| 903 |
'X_target': X_target,
|
| 904 |
'y_source': y_source,
|
|
|
|
| 905 |
'groups_source': groups_source, # Array (N_source,) - encoded as int
|
| 906 |
'groups_target': groups_target, # Array (N_target,) - encoded as int
|
| 907 |
'masks_source': masks_source,
|
|
@@ -912,10 +938,11 @@ def scenario_4_domain_adaptation_satellite(
|
|
| 912 |
'window_size': window_size,
|
| 913 |
'source_date': source_date,
|
| 914 |
'target_date': target_date,
|
| 915 |
-
'
|
| 916 |
-
'
|
| 917 |
-
'
|
| 918 |
-
'
|
|
|
|
| 919 |
}
|
| 920 |
}
|
| 921 |
|
|
@@ -989,7 +1016,7 @@ def example_usage(selec: int = None):
|
|
| 989 |
)
|
| 990 |
|
| 991 |
# ==========================================================================
|
| 992 |
-
# SCENARIO 4: Domain Adaptation
|
| 993 |
# ==========================================================================
|
| 994 |
if selec == 4:
|
| 995 |
scenario4_data = scenario_4_domain_adaptation_satellite(
|
|
@@ -997,10 +1024,13 @@ def example_usage(selec: int = None):
|
|
| 997 |
window_size=32,
|
| 998 |
max_mask_value=1,
|
| 999 |
max_mask_percentage=10.0,
|
| 1000 |
-
min_valid_percentage=100.0,
|
| 1001 |
-
|
| 1002 |
-
|
| 1003 |
-
|
|
|
|
|
|
|
|
|
|
| 1004 |
scale_type='amplitude',
|
| 1005 |
skip_optim_offset=True
|
| 1006 |
)
|
|
|
|
| 671 |
max_mask_value: int = 1,
|
| 672 |
max_mask_percentage: float = 10.0,
|
| 673 |
min_valid_percentage: float = 50.0,
|
| 674 |
+
source_orbit: str = 'DSC',
|
| 675 |
+
target_orbit: str = 'ASC',
|
| 676 |
+
source_date: str = '20210127',
|
| 677 |
+
target_date: str = '20210214',
|
| 678 |
+
source_polarization: str = 'HH', # Can be 'HH', 'HV', or ['HH', 'HV']
|
| 679 |
+
target_polarization: str = 'HH', # Can be 'HH', 'HV', or ['HH', 'HV']
|
| 680 |
scale_type: str = 'intensity',
|
| 681 |
skip_optim_offset: bool = True,
|
| 682 |
verbose: bool = True
|
| 683 |
) -> Dict:
|
| 684 |
"""
|
| 685 |
+
SCENARIO 4: Domain Adaptation between different acquisition geometries.
|
| 686 |
|
| 687 |
+
Objective: Learn on source geometry (labeled) and adapt to target geometry (unlabeled).
|
| 688 |
+
Default: Source: PAZ DSC 2021-01-27 HH -> Target: PAZ ASC 2021-02-14 HH
|
| 689 |
|
| 690 |
Args:
|
| 691 |
loader: Instance of MLDatasetLoader
|
|
|
|
| 693 |
max_mask_value: Max mask value
|
| 694 |
max_mask_percentage: Max % of pixels with mask > max_mask_value
|
| 695 |
min_valid_percentage: Min % of valid pixels
|
| 696 |
+
source_orbit: Source orbit ('ASC' or 'DSC')
|
| 697 |
+
target_orbit: Target orbit ('ASC' or 'DSC')
|
| 698 |
+
source_date: Source acquisition date ('YYYYMMDD')
|
| 699 |
+
target_date: Target acquisition date ('YYYYMMDD')
|
| 700 |
+
source_polarization: Source polarization ('HH', 'HV', or ['HH', 'HV'])
|
| 701 |
+
target_polarization: Target polarization ('HH', 'HV', or ['HH', 'HV'])
|
| 702 |
+
scale_type: 'intensity' (default), 'amplitude', or 'log10'
|
| 703 |
+
skip_optim_offset: Skip window offset optimization
|
| 704 |
verbose: Display detailed information
|
| 705 |
|
| 706 |
Returns:
|
| 707 |
Dict with:
|
| 708 |
+
- X_source: Array (N_source, window_size, window_size, n_pol_source)
|
| 709 |
+
- X_target: Array (N_target, window_size, window_size, n_pol_target)
|
| 710 |
+
- y_source: Array (N_source,) - labels source
|
| 711 |
+
- y_target: Array (N_target,) - labels target (for analysis only)
|
| 712 |
+
- groups_source: Array (N_source,) - group identifiers for source
|
| 713 |
+
- groups_target: Array (N_target,) - group identifiers for target
|
| 714 |
- masks_source: Array (N_source, window_size, window_size)
|
| 715 |
- masks_target: Array (N_target, window_size, window_size)
|
| 716 |
+
- class_names: Dict - mapping int -> class name
|
| 717 |
+
- group_names: Dict - mapping int -> group name
|
| 718 |
"""
|
| 719 |
print(f"\n{'='*70}")
|
| 720 |
+
print("SCENARIO 4: Domain Adaptation - Different Acquisition Geometries")
|
| 721 |
print(f"{'='*70}")
|
| 722 |
print(f"Parameters:")
|
| 723 |
print(f" - Windows: {window_size}x{window_size}")
|
| 724 |
+
print(f" - Source: PAZ {source_orbit} {source_date} {source_polarization}")
|
| 725 |
+
print(f" - Target: PAZ {target_orbit} {target_date} {target_polarization}")
|
| 726 |
+
print(f" - Scale type: {scale_type}")
|
|
|
|
|
|
|
| 727 |
print(f" - Mask max: {max_mask_value}, {max_mask_percentage}%\n")
|
| 728 |
|
| 729 |
learning_classes = [c for c in loader.classes if c != 'STUDY']
|
|
|
|
| 732 |
X_source_all = []
|
| 733 |
X_target_all = []
|
| 734 |
y_source_all = []
|
| 735 |
+
y_target_all = []
|
| 736 |
groups_source_all = []
|
| 737 |
groups_target_all = []
|
| 738 |
masks_source_all = []
|
|
|
|
| 753 |
for group in loader.get_groups_by_class(class_name):
|
| 754 |
group_to_class[group] = class_name
|
| 755 |
|
| 756 |
+
# SOURCE
|
| 757 |
print("=" * 70)
|
| 758 |
+
print(f"Loading SOURCE ({source_orbit} {source_date} {source_polarization})...")
|
| 759 |
+
pbar_source = tqdm(unique_groups, desc="Source Groups", unit="grp")
|
| 760 |
+
for group_name in pbar_source:
|
| 761 |
class_name = group_to_class[group_name]
|
| 762 |
|
| 763 |
# Update progress bar description with current group
|
| 764 |
if verbose:
|
| 765 |
+
pbar_source.set_postfix_str(f"{group_name} ({class_name})")
|
| 766 |
|
| 767 |
try:
|
| 768 |
+
# Load source data
|
| 769 |
data = loader.load_data(
|
| 770 |
group_name=group_name,
|
| 771 |
+
orbit=source_orbit,
|
| 772 |
+
polarisation=source_polarization,
|
| 773 |
start_date=source_date,
|
| 774 |
end_date=source_date,
|
| 775 |
normalize=False,
|
|
|
|
| 789 |
|
| 790 |
# Take the first PAZ acquisition
|
| 791 |
idx = paz_indices[0]
|
| 792 |
+
|
| 793 |
+
# Handle both single-pol and dual-pol
|
| 794 |
+
if len(data['images'].shape) == 4: # Dual-pol: (H, W, T, 2)
|
| 795 |
+
img = data['images'][:, :, idx, :] # (H, W, 2)
|
| 796 |
+
else: # Single-pol: (H, W, T)
|
| 797 |
+
img = data['images'][:, :, idx] # (H, W)
|
| 798 |
+
|
| 799 |
mask = data['masks'][:, :, idx]
|
| 800 |
|
| 801 |
# Extract windows
|
|
|
|
| 816 |
n_windows = len(windows)
|
| 817 |
|
| 818 |
# Store individually
|
| 819 |
+
for idx_win in range(n_windows):
|
| 820 |
+
X_source_all.append(windows[idx_win])
|
| 821 |
y_source_all.append(class_to_int[class_name])
|
| 822 |
groups_source_all.append(group_to_int[group_name])
|
| 823 |
+
masks_source_all.append(window_masks[idx_win])
|
| 824 |
group_names_source_all.append(group_name)
|
| 825 |
|
| 826 |
except Exception as e:
|
| 827 |
continue
|
| 828 |
|
| 829 |
+
# TARGET
|
| 830 |
print("\n" + "=" * 70)
|
| 831 |
+
print(f"Loading TARGET ({target_orbit} {target_date} {target_polarization})...")
|
| 832 |
+
pbar_target = tqdm(unique_groups, desc="Target Groups", unit="grp")
|
| 833 |
+
for group_name in pbar_target:
|
| 834 |
class_name = group_to_class[group_name]
|
| 835 |
|
| 836 |
# Update progress bar description with current group
|
| 837 |
if verbose:
|
| 838 |
+
pbar_target.set_postfix_str(f"{group_name} ({class_name})")
|
| 839 |
|
| 840 |
try:
|
| 841 |
data = loader.load_data(
|
| 842 |
group_name=group_name,
|
| 843 |
+
orbit=target_orbit,
|
| 844 |
+
polarisation=target_polarization,
|
| 845 |
start_date=target_date,
|
| 846 |
end_date=target_date,
|
| 847 |
normalize=False,
|
|
|
|
| 852 |
if data['images'].shape[2] == 0:
|
| 853 |
continue
|
| 854 |
|
| 855 |
+
# Filter by PAZ satellite
|
| 856 |
satellites = np.array(data['satellites'])
|
| 857 |
+
paz_indices = np.where(satellites == 'PAZ')[0]
|
| 858 |
|
| 859 |
+
if len(paz_indices) == 0:
|
| 860 |
continue
|
| 861 |
|
| 862 |
+
idx = paz_indices[0]
|
| 863 |
+
|
| 864 |
+
# Handle both single-pol and dual-pol
|
| 865 |
+
if len(data['images'].shape) == 4: # Dual-pol: (H, W, T, 2)
|
| 866 |
+
img = data['images'][:, :, idx, :] # (H, W, 2)
|
| 867 |
+
else: # Single-pol: (H, W, T)
|
| 868 |
+
img = data['images'][:, :, idx] # (H, W)
|
| 869 |
+
|
| 870 |
mask = data['masks'][:, :, idx]
|
| 871 |
|
| 872 |
windows, window_masks, positions = loader.extract_windows(
|
|
|
|
| 876 |
stride=window_size,
|
| 877 |
max_mask_value=max_mask_value,
|
| 878 |
max_mask_percentage=max_mask_percentage,
|
| 879 |
+
min_valid_percentage=min_valid_percentage,
|
| 880 |
+
skip_optim_offset=skip_optim_offset
|
| 881 |
)
|
| 882 |
|
| 883 |
if windows is None:
|
|
|
|
| 888 |
# Store individually
|
| 889 |
for idx_win in range(n_windows):
|
| 890 |
X_target_all.append(windows[idx_win])
|
| 891 |
+
y_target_all.append(class_to_int[class_name]) # For analysis only
|
| 892 |
groups_target_all.append(group_to_int[group_name])
|
| 893 |
masks_target_all.append(window_masks[idx_win])
|
| 894 |
group_names_target_all.append(group_name)
|
|
|
|
| 897 |
continue
|
| 898 |
|
| 899 |
if len(X_source_all) == 0 or len(X_target_all) == 0:
|
| 900 |
+
raise ValueError("No source or target data found")
|
| 901 |
|
| 902 |
X_source = np.array(X_source_all, dtype=np.float32)
|
| 903 |
X_target = np.array(X_target_all, dtype=np.float32)
|
| 904 |
y_source = np.array(y_source_all)
|
| 905 |
+
y_target = np.array(y_target_all)
|
| 906 |
groups_source = np.array(groups_source_all)
|
| 907 |
groups_target = np.array(groups_target_all)
|
| 908 |
masks_source = np.array(masks_source_all)
|
|
|
|
| 911 |
if verbose:
|
| 912 |
print(f"\n{'='*70}")
|
| 913 |
print(f"Results:")
|
| 914 |
+
print(f" - SOURCE ({source_orbit} {source_date} {source_polarization}):")
|
| 915 |
print(f" X_source.shape: {X_source.shape}")
|
| 916 |
print(f" y_source.shape: {y_source.shape}")
|
| 917 |
print(f" groups_source.shape: {groups_source.shape}")
|
| 918 |
print(f" Unique classes: {np.unique(y_source, return_counts=True)}")
|
| 919 |
print(f" Unique groups: {len(np.unique(groups_source))}")
|
| 920 |
+
print(f" - TARGET ({target_orbit} {target_date} {target_polarization}):")
|
| 921 |
print(f" X_target.shape: {X_target.shape}")
|
| 922 |
+
print(f" y_target.shape: {y_target.shape}")
|
| 923 |
print(f" groups_target.shape: {groups_target.shape}")
|
| 924 |
print(f" Unique groups: {len(np.unique(groups_target))}")
|
| 925 |
|
|
|
|
| 927 |
'X_source': X_source,
|
| 928 |
'X_target': X_target,
|
| 929 |
'y_source': y_source,
|
| 930 |
+
'y_target': y_target,
|
| 931 |
'groups_source': groups_source, # Array (N_source,) - encoded as int
|
| 932 |
'groups_target': groups_target, # Array (N_target,) - encoded as int
|
| 933 |
'masks_source': masks_source,
|
|
|
|
| 938 |
'window_size': window_size,
|
| 939 |
'source_date': source_date,
|
| 940 |
'target_date': target_date,
|
| 941 |
+
'source_orbit': source_orbit,
|
| 942 |
+
'target_orbit': target_orbit,
|
| 943 |
+
'source_polarization': source_polarization,
|
| 944 |
+
'target_polarization': target_polarization,
|
| 945 |
+
'satellite': 'PAZ'
|
| 946 |
}
|
| 947 |
}
|
| 948 |
|
|
|
|
| 1016 |
)
|
| 1017 |
|
| 1018 |
# ==========================================================================
|
| 1019 |
+
# SCENARIO 4: Domain Adaptation Different Geometries
|
| 1020 |
# ==========================================================================
|
| 1021 |
if selec == 4:
|
| 1022 |
scenario4_data = scenario_4_domain_adaptation_satellite(
|
|
|
|
| 1024 |
window_size=32,
|
| 1025 |
max_mask_value=1,
|
| 1026 |
max_mask_percentage=10.0,
|
| 1027 |
+
min_valid_percentage=100.0,
|
| 1028 |
+
source_orbit='DSC',
|
| 1029 |
+
target_orbit='ASC',
|
| 1030 |
+
source_date='20210127',
|
| 1031 |
+
target_date='20210214',
|
| 1032 |
+
source_polarization='HH',
|
| 1033 |
+
target_polarization='HH',
|
| 1034 |
scale_type='amplitude',
|
| 1035 |
skip_optim_offset=True
|
| 1036 |
)
|