@@ -236,7 +236,7 @@ def bbox_overlap(
236236) -> float :
237237 """
238238 Calculate the fraction of the source bounding box that overlaps with the target
239- bounding box.
239+ bounding box relative to the area of the source bounding box .
240240
241241 Args:
242242 source_bbox: (min_x, min_y, max_x, max_y)
@@ -245,19 +245,37 @@ def bbox_overlap(
245245 Returns:
246246 float in [0, 1]
247247 """
248- inter_min_x = max (source_bbox [0 ], target_bbox [0 ])
249- inter_min_y = max (source_bbox [1 ], target_bbox [1 ])
250- inter_max_x = min (source_bbox [2 ], target_bbox [2 ])
251- inter_max_y = min (source_bbox [3 ], target_bbox [3 ])
252-
253- inter_w = max (0 , inter_max_x - inter_min_x )
254- inter_h = max (0 , inter_max_y - inter_min_y )
255- inter_area = inter_w * inter_h
256- area_source = (source_bbox [2 ] - source_bbox [0 ]) * (source_bbox [3 ] - source_bbox [1 ])
248+ source_bboxes = _split_bbox_antimeridian (source_bbox )
249+ target_bboxes = _split_bbox_antimeridian (target_bbox )
250+
251+ inter_area = 0.0
252+ for source_bbox in source_bboxes :
253+ for target_bbox in target_bboxes :
254+ inter_min_x = max (source_bbox [0 ], target_bbox [0 ])
255+ inter_min_y = max (source_bbox [1 ], target_bbox [1 ])
256+ inter_max_x = min (source_bbox [2 ], target_bbox [2 ])
257+ inter_max_y = min (source_bbox [3 ], target_bbox [3 ])
258+
259+ inter_w = max (0 , inter_max_x - inter_min_x )
260+ inter_h = max (0 , inter_max_y - inter_min_y )
261+ inter_area += inter_w * inter_h
262+ area_source = 0.0
263+ for source_bbox in source_bboxes :
264+ area_source += (source_bbox [2 ] - source_bbox [0 ]) * (
265+ source_bbox [3 ] - source_bbox [1 ]
266+ )
257267
258268 return inter_area / area_source
259269
260270
271+ def _split_bbox_antimeridian (bbox : Sequence [FloatInt ]):
272+ min_x , min_y , max_x , max_y = bbox
273+
274+ if max_x < min_x :
275+ return [(min_x , min_y , 180 , max_y ), (- 180 , min_y , max_x , max_y )]
276+ return [bbox ]
277+
278+
261279def normalize_grid_mapping (ds : xr .Dataset , gm : GridMapping ) -> xr .Dataset :
262280 """
263281 Normalize the grid mapping of a dataset to use a standard "spatial_ref" coordinate.
0 commit comments