@@ -431,6 +431,66 @@ def _detect_clusters_numba(
431431
432432 return labels , sizes [:n_clusters ]
433433
434+
435+ @njit (cache = True )
436+ def _check_percolation (
437+ labels : np .ndarray ,
438+ sizes : np .ndarray ,
439+ direction : int ,
440+ ) -> Tuple [bool , int , int ]:
441+ """
442+ Check for percolating clusters.
443+
444+ Args:
445+ direction: 0=horizontal, 1=vertical, 2=both
446+
447+ Returns:
448+ percolates, perc_label, perc_size
449+ """
450+ rows , cols = labels .shape
451+ max_label = len (sizes )
452+
453+ touches_left = np .zeros (max_label + 1 , dtype = np .bool_ )
454+ touches_right = np .zeros (max_label + 1 , dtype = np .bool_ )
455+ touches_top = np .zeros (max_label + 1 , dtype = np .bool_ )
456+ touches_bottom = np .zeros (max_label + 1 , dtype = np .bool_ )
457+
458+ for i in range (rows ):
459+ if labels [i , 0 ] > 0 :
460+ touches_left [labels [i , 0 ]] = True
461+ if labels [i , cols - 1 ] > 0 :
462+ touches_right [labels [i , cols - 1 ]] = True
463+
464+ for j in range (cols ):
465+ if labels [0 , j ] > 0 :
466+ touches_top [labels [0 , j ]] = True
467+ if labels [rows - 1 , j ] > 0 :
468+ touches_bottom [labels [rows - 1 , j ]] = True
469+
470+ best_label = 0
471+ best_size = 0
472+
473+ for label in range (1 , max_label + 1 ):
474+ percolates_h = touches_left [label ] and touches_right [label ]
475+ percolates_v = touches_top [label ] and touches_bottom [label ]
476+
477+ is_percolating = False
478+ if direction == 0 :
479+ is_percolating = percolates_h
480+ elif direction == 1 :
481+ is_percolating = percolates_v
482+ else :
483+ is_percolating = percolates_h or percolates_v
484+
485+ if is_percolating :
486+ cluster_size = sizes [label - 1 ]
487+ if cluster_size > best_size :
488+ best_size = cluster_size
489+ best_label = label
490+
491+ return best_label > 0 , best_label , best_size
492+
493+
434494# ============================================================================
435495# PUBLIC API - CLUSTER DETECTION
436496# ============================================================================
0 commit comments