|
| 1 | +from SM_preprocess import * |
| 2 | +from surrogate_model import * |
| 3 | +from utlis import * |
| 4 | +from preprocessFIM import * |
| 5 | + |
| 6 | +def load_model(model): |
| 7 | + # Set up S3 access |
| 8 | + fs = s3fs.S3FileSystem(anon=True) |
| 9 | + bucket_path = "sdmlab/SM_dataset/trained_model/SM_trainedmodel.ckpt" |
| 10 | + |
| 11 | + # Download to a temporary file |
| 12 | + with fs.open(bucket_path, 'rb') as s3file: |
| 13 | + with tempfile.NamedTemporaryFile(suffix=".ckpt", delete=False) as tmp_ckpt: |
| 14 | + tmp_ckpt.write(s3file.read()) |
| 15 | + tmp_ckpt_path = tmp_ckpt.name |
| 16 | + |
| 17 | + # Load checkpoint |
| 18 | + checkpoint = torch.load(tmp_ckpt_path, map_location='cuda' if torch.cuda.is_available() else 'cpu') |
| 19 | + model.load_state_dict(checkpoint['state_dict']) |
| 20 | + |
| 21 | + # Move model to device |
| 22 | + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') |
| 23 | + model.to(device) |
| 24 | + model.eval() |
| 25 | + |
| 26 | + return model, device |
| 27 | + |
| 28 | +#WEIGHTED AVERAGE for patch |
| 29 | +def create_weight_map(M: int, N: int): |
| 30 | + weight_map = np.zeros((M, N), dtype=np.float32) |
| 31 | + center_x, center_y = M // 2, N // 2 |
| 32 | + for i in range(M): |
| 33 | + for j in range(N): |
| 34 | + dist_sq = (i - center_x)**2 + (j - center_y)**2 |
| 35 | + weight = np.exp(-dist_sq / (2 * (min(M, N) / 2)**2)) |
| 36 | + weight_map[i, j] = weight |
| 37 | + return torch.from_numpy(weight_map).float().unsqueeze(0).unsqueeze(0) # (1, 1, M, N) |
| 38 | + |
| 39 | +#If there is Stride |
| 40 | +def predict_on_area(dataset, model, shape: torch.Tensor, M: int = 256, N: int = 256, stride: int = 128, device=None): |
| 41 | + # Get row and col size |
| 42 | + shape_row = shape.size(1) |
| 43 | + shape_col = shape.size(2) |
| 44 | + |
| 45 | + # Pad if needed |
| 46 | + pad_h = (stride * ((shape_row - M) // stride + 1) + M - shape_row) |
| 47 | + pad_w = (stride * ((shape_col - N) // stride + 1) + N - shape_col) |
| 48 | + |
| 49 | + if pad_h > 0 or pad_w > 0: |
| 50 | + padding = (0, pad_w, 0, pad_h) |
| 51 | + shape = nn.functional.pad(shape, padding, mode='constant', value=0) |
| 52 | + |
| 53 | + # Update new shape after padding |
| 54 | + new_row = shape.size(1) |
| 55 | + new_col = shape.size(2) |
| 56 | + |
| 57 | + # Separate X and Y |
| 58 | + X = shape[dataset.x_feature_index] |
| 59 | + y = shape[dataset.y_feature_index] |
| 60 | + |
| 61 | + # Initialize weighted prediction sum and weight sum arrays |
| 62 | + weighted_prediction_sum = torch.zeros((1, new_row, new_col), device=device) |
| 63 | + weight_sum = torch.zeros((1, new_row, new_col), device=device) |
| 64 | + |
| 65 | + # Create the weight map |
| 66 | + weight_map = create_weight_map(M, N).to(device) |
| 67 | + |
| 68 | + # Loop over patches |
| 69 | + for start_i in range(0, new_row - M + 1, stride): |
| 70 | + for start_j in range(0, new_col - N + 1, stride): |
| 71 | + end_i = start_i + M |
| 72 | + end_j = start_j + N |
| 73 | + patch = X[:, start_i:end_i, start_j:end_j].unsqueeze(0).to(device) |
| 74 | + |
| 75 | + with torch.no_grad(): |
| 76 | + patch_prediction_raw = model(patch) |
| 77 | + |
| 78 | + weighted_prediction = patch_prediction_raw * weight_map |
| 79 | + weighted_prediction_sum[:, start_i:end_i, start_j:end_j] += weighted_prediction.squeeze(0) |
| 80 | + weight_sum[:, start_i:end_i, start_j:end_j] += weight_map.squeeze(0) |
| 81 | + |
| 82 | + epsilon = 1e-8 |
| 83 | + final_prediction = weighted_prediction_sum / (weight_sum + epsilon) |
| 84 | + final_prediction = (final_prediction > 0.01).float() |
| 85 | + |
| 86 | + # Crop back to original shape (before padding) |
| 87 | + final_prediction = final_prediction[:, :shape_row, :shape_col] |
| 88 | + y = y[:, :shape_row, :shape_col] |
| 89 | + lf = shape[[dataset.lf_index]][:, :shape_row, :shape_col] |
| 90 | + |
| 91 | + return final_prediction.cpu(), y.cpu(), lf.cpu() |
| 92 | + |
| 93 | +#Save the tif file |
| 94 | +def save_image(image: torch.Tensor, path: Path, reference_tif: str): |
| 95 | + """Save the image as a .tif file. |
| 96 | + |
| 97 | + Args: |
| 98 | + image (torch.Tensor): The image to save |
| 99 | + path (Path): The path to save the image |
| 100 | + """ |
| 101 | + image_np = image.squeeze().cpu().numpy().astype('float32') |
| 102 | + with rasterio.open(reference_tif) as ref: |
| 103 | + meta = ref.meta.copy() |
| 104 | + meta.update({ |
| 105 | + "driver": "GTiff", |
| 106 | + "height": image_np.shape[0], |
| 107 | + "width": image_np.shape[1], |
| 108 | + "count": 1, |
| 109 | + "dtype": 'float32' |
| 110 | + }) |
| 111 | + |
| 112 | + with rasterio.open(path, 'w', **meta) as dst: |
| 113 | + dst.write(image_np, 1) |
| 114 | + mask_with_PWB(path, path) |
| 115 | + |
| 116 | + with rasterio.open(path, 'r+') as dst: |
| 117 | + data = dst.read(1) |
| 118 | + binary_data = np.where(data > 0, 1, 0).astype(np.uint8) |
| 119 | + dst.write(binary_data, 1) |
| 120 | + |
| 121 | + compress_tif_lzw(path) |
| 122 | + |
| 123 | + |
| 124 | +#ENHANCE THE LOW-FIDELITY FLOOD MAP |
| 125 | +def Predict_FM(huc_id, patch_size=(256, 256)): |
| 126 | + |
| 127 | + data_dir = Path(f'./HUC{huc_id}_forcings/') |
| 128 | + model = AttentionUNet(channel=8) |
| 129 | + |
| 130 | + preprocessor = InferenceDataPreprocessor(data_dir=Path(data_dir), patch_size=patch_size, verbose=True) |
| 131 | + |
| 132 | + print("Loading model...") |
| 133 | + model, device = load_model(model) |
| 134 | + print("Model loaded.") |
| 135 | + |
| 136 | + |
| 137 | + lf_files = preprocessor.get_all_lf_maps(huc_id) |
| 138 | + for lf_path in lf_files: |
| 139 | + lf_filename = lf_path.name |
| 140 | + print(f"Predicting for: {lf_filename}\n") |
| 141 | + |
| 142 | + print(f"Loading static features for HUC {huc_id}...") |
| 143 | + static_stack = preprocessor.get_static_stack(huc_id) |
| 144 | + lf_tensor = preprocessor.tif_to_tensor(lf_path, feature_name='low_fidelity') |
| 145 | + |
| 146 | + # Combine and validate |
| 147 | + area_tensor = torch.cat([static_stack, lf_tensor], dim=0) |
| 148 | + if area_tensor.shape[0] != 8: |
| 149 | + raise ValueError(f"Expected 8 channels, got {area_tensor.shape[0]} — check missing static feature for HUC {huc_id}.") |
| 150 | + |
| 151 | + # Define dummy interface |
| 152 | + class Dummy: |
| 153 | + x_feature_index = list(range(area_tensor.shape[0])) |
| 154 | + y_feature_index = [area_tensor.shape[0] - 1] |
| 155 | + lf_index = area_tensor.shape[0] - 1 |
| 156 | + |
| 157 | + print(f"Static features loaded for {huc_id}.\n") |
| 158 | + |
| 159 | + # Predict |
| 160 | + print(f"Enhancing {lf_path}...") |
| 161 | + x, y, lf = predict_on_area(Dummy, model, area_tensor, M=patch_size[0], N=patch_size[1], stride=patch_size[0] // 2, device=device) |
| 162 | + |
| 163 | + # Save result |
| 164 | + pred_dir = Path(f"./Results/HUC{huc_id}/") |
| 165 | + pred_dir.mkdir(parents=True, exist_ok=True) |
| 166 | + pred_path = pred_dir / f"SMprediction_{lf_filename}" |
| 167 | + save_image(x, pred_path, lf_path) |
| 168 | + print(f"Enhancement completed for {lf_filename}.\n") |
| 169 | + |
| 170 | + |
0 commit comments