
    1-PhT                        d Z ddlZddlmZmZ ddlmZ ddl	m
Z
 ddlmZ 	 ddlmZ ej        j        Zd	 Zeej        _         ej                    Zn# e$ r dZY nw xY w	 dd
lmZ dZn# e$ r dZY nw xY wddlmZ ddlmZmZ d Zd Zd Zd Zd Z d Z!d Z" ej#        d          	 	 	 	 	 	 ddddd            Z$dS )a  
Random walker segmentation algorithm

from *Random walks for image segmentation*, Leo Grady, IEEE Trans
Pattern Anal Mach Intell. 2006 Nov;28(11):1768-83.

Installing pyamg and using the 'cg_mg' mode of random_walker improves
significantly the performance.
    N)sparsendimage   )utils)warn)SCIPY_CG_TOL_PARAM_NAME)umfpackc                 H    	 t          |            d S # t          $ r Y d S w xY w)N)old_delAttributeError)selfs    o/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/skimage/segmentation/random_walker_segmentation.pynew_delr      s8    	DMMMMM 	 	 	DD	s    
!!)ruge_stuben_solverTF)img_as_float)cgspsolvec                 h   t          j        | |z  |z                                | ||f          }t          j        |dddf                                         |dddf                                         f          }t          j        |ddddf                                         |ddddf                                         f          }t          j        |dd                                         |dd                                         f          }t          j        |||f          }|S )a$  Returns a list of edges for a 3D image.

    Parameters
    ----------
    n_x : integer
        The size of the grid in the x direction.
    n_y : integer
        The size of the grid in the y direction
    n_z : integer
        The size of the grid in the z direction

    Returns
    -------
    edges : (2, N) ndarray
        with the total number of edges::

            N = n_x * n_y * (nz - 1) +
                n_x * (n_y - 1) * nz +
                (n_x - 1) * n_y * nz

        Graph edges with each column describing a node-id pair.
    .N   )nparangereshapevstackravelhstack)n_xn_yn_zvertices
edges_deepedges_right
edges_downedgess           r   _make_graph_edges_3dr%   4   s   . ysS))113S/BBHHS#2#X.4466abb8I8O8O8Q8QRSSJ)Xaaa"f-3355x1227L7L7N7NOPPKHSbSM//118ABB<3E3E3G3GHIIJIz;
;<<EL    c                     t          j         fddD             d          dz  }t          d j        d                   D ],|t          j         fddD             d          dz  z  }-| d	                                 z  z  }|r"|t          j         j        d                   z  }t          j        ||z            }||z  }| S )
Nc                     g | ]J}j         |         d k    t          j        d         |                                          |         z  KS )r   ).r   axisshaper   diffr   ).0axdataspacings     r   
<listcomp>z'_compute_weights_3d.<locals>.<listcomp>X   s\       :b>A%% V2...4466D%%%r&   )r   r   r   r   r)   r   r   r   c                     g | ]L}j         |         d k    t          j        df         |                                          |         z  MS )r   .r)   r+   )r.   r/   channelr0   r1   s     r   r2   z'_compute_weights_3d.<locals>.<listcomp>d   sa       z"~)) GDg.R888>>@@72;N)))r&   
   )r   concatenateranger,   stdsqrtexp)	r0   r1   betaepsmultichannel	gradientsscale_factorweightsr4   s	   ``      @r   _compute_weights_3drA   S   s<    	    #  
 	
 	
 	
 	  DJrN++ 
 
N     '  
    
	
		 5BO,L 0 	
2///f\I-..GsNG8Or&   c                 .   | j         d d         \  }}}t          |||          }t          | ||d|          }	|2t          j        |dd df                                         |d d d df                                         |d d                                         g          }
t          j        |ddd f                                         |d d dd f                                         |dd                                          g          }t          j        |
|          }|d d |f         |	|         }	}t          j        |d          \  }}|                    |j                   }||z  |z  }|                                }|d d d                                         }t          j        |	|	f          } t          j
        | ||ff||f	          }|                    t          j        |                    d
                                |S )N   g|=)r;   r<   r=   .r   r   Treturn_inverser,   r   r)   )r,   r%   rA   r   r   r   logical_anduniquer   r   	csr_arraysetdiagsum)r0   r1   maskr;   r=   l_xl_yl_zr$   r@   mask0mask1ind_mask_inv_idxpixel_nb	i_indices	j_indiceslaps                      r   _build_laplacianrY   y   s   JrrNMCc c3//E!gDgL  G  	#ss(^!!##T!!!SbS&\%7%7%9%949??;L;LM
 
 	#qrr']  ""DABBK$5$5$7$7abb9I9IJ
 
 >%//qqq({+WX->w YuT:::
7,, Sy3HIddd!!##I9gw'((D

D9i"89(HAU
V
V
VCKK#''q'//***+++Jr&   c           
         ||                                 }n||         }t          j        |j                  }|dk    }||          }	||         }
t	          | ||||          }||	ddf         }|dd|	f         }|dd|
f          }||         t          j        t          j        fdt          d|dz             D                                 }||z  }||fS )z
    Build the matrix A and rhs B of the linear system to solve.
    A and B are two block of the laplacian of the image graph.
    Nr   )rL   r;   r=   c                 J    g | ]}t          j        |k              j         S  )r   
atleast_2dT)r.   labseedss     r   r2   z(_build_linear_system.<locals>.<listcomp>   s*    RRRS2=#..0RRRr&   r   )	r   r   r   sizerY   r   	csc_arrayr   r7   )r0   r1   labelsnlabelsrL   r;   r=   indices
seeds_maskunlabeled_indicesseeds_indices
lap_sparserowsBrhsr`   s                  @r   _build_linear_systemrm      s   
 |i$$G!J,J'M!gDt,  J '*+Daaa**+J	aaa	A:E!
	RRRRE!Wq[<Q<QRRRSS J j.Cs?r&   c                 $   	
 |d}|dk    rt           st          dd           d}|dk    r)t                                                     j        }n7d 	|dk    rt
          t          dd           d n|dk    r= j        d	         }t          j        d
 	                                z  df||f          nQt           t          j        d          \   _         _        t           d          }|                    d          d	t"          |i
 	
fdt%          j        d                   D             }t          j        d |D                       rt          dd           t          j        d |D                       }|S )Ncg_jcg_mgz_"cg_mg" not available, it requires pyamg to be installed. The "cg_j" mode will be used instead.r   
stacklevelbfr   z"cg" mode may be slow because UMFPACK is not available. Consider building Scipy with UMFPACK or use a preconditioned version of CG ("cg_j" or "cg_mg" modes).r         ?r   rF   z-index values too large for int32 mode 'cg_mg'pinv)coarse_solverV)cycle   c           
      r    g | ]3}t          d d |gf                                         fi dd4S )Nr   )atolMmaxiter)r   toarray)r.   irk   r|   ri   r}   rtols     r   r2   z(_solve_linear_system.<locals>.<listcomp>   sd     
 
 
 z1QQQV9,,..UU$UQ!WUUUU
 
 
r&   r   c                      g | ]\  }}|d k    S r   r\   )r.   rS   infos      r   r2   z(_solve_linear_system.<locals>.<listcomp>   s     22244!8222r&   zsConjugate gradient convergence to tolerance not achieved. Consider decreasing beta to improve system conditionning.c                     g | ]\  }}|S r\   r\   )r.   xrS   s      r   r2   z(_solve_linear_system.<locals>.<listcomp>   s    ---da---r&   )
amg_loadedr   r   r~   r^   UmfpackContextr,   r   	dia_arraydiagonal_safe_downcast_indicesr   int32re   indptrr   aspreconditionerr   r7   anyasarray)ri   rk   tolmodeXnmlcg_outr|   r}   r   s   ``      @@@r   _solve_linear_systemr      s   |wz4	
 	
 	
 	

 t||J		,,.4<<%N  !	    AAV^^ $A #
(;(;(=(="=q!A!QPPPAA 5KBH&U5 51J
 1 $JfEEEB####..AG'-
 
 
 
 
 
 
 
171:&&
 
 
 622622233 	L   
 J--f---..Hr&   c                 h   t          j        |          j        }| j        d         |k    rt	          |          t          | j         |k    r,t          j        | j        |k              rt	          |          | j                            |d          }| j                            |d          }||fS )Nr   F)copy)	r   iinfomaxr   
ValueErrorr,   r   re   astype)Aitypemsg	max_valuere   r   s         r   r   r      s    #Ix|ioo
AG}y  6!)i'(( 	"S//!iu511GX__U_//FF?r&   c                    t          j        | d          \  }}t          |          dk    rt          d          |dk                                    st          dd           | d d d d fS | dk    }| dk    }| dk    }t          j        ||          }t          j        |t          j	        |                    }d	||<   |d         dk     st          j        |          rt          j        t          j	        t          j        ||                    |          }d
| |<   t          j
        ||                   rt          dd           | d d d d fS d	||<   t          j        |          }nd }t          j        |d          }t          j        |                    | j                  |z
            } ||dz   d          j        d         }	t          j        |          }
| |
         }| |	||
|fS )NTrD   r   zWNo seeds provided in label image: please ensure it contains at least one positive valuezRandom walker only segments unlabeled areas, where labels == 0. No zero valued areas in labels were found. Returning provided labels.r   rq   )rL   Fr   z_All unlabeled pixels are isolated, they could not be determined by the random walker algorithm.r   )r   rH   r   r   r   r   ndibinary_propagationrG   logical_notall
atleast_3dsearchsortedr   r,   nonzero)rc   label_valuesrT   	null_maskpos_maskrL   fillisolatedzero_idxrd   inds_isolated_seedsisolated_valuess               r   _preprocessr      s+   IfTBBBL'
<A6
 
 	

 A""$$ .0 		
 	
 	
 	
 tT4--
 !IzHQ;D!)$777D~ht(<(<==HHX AbfX..>N31(FFFGG
 
 x6(9%&& 	2=   
 4tT11X}T"" |Q//H]7??6<888CDDF8a<>>*03G*X..01O7D"5FFr&   )multichannel_output   ro   MbP?)prob_tolchannel_axisc          	      r   |dvrt          | d          | j        t          j        k    r!|                     t          j        d          } |t          j        d          }nct          |          j        k    r<t          |          dk    rt          j	        |df         }t          j
        |          }nt          d	          |	du}
|
sk| j        d
vrt          d          | j        j        k    rt          d          t          j        t          |                     dt          j        f         } nu| j        dvrt          d          | j        dd         j        k    rt          d          t          |           } | j        dk    r| ddddt          j        ddf         } j        }j        }|rt          j                  t!                    \  }}}}|8|r4t          j        fdt          j                  D             d          S S t'          | |||||
          \  }}t)          ||||          }|                                | k     s|                                d|z   k    rt/          d           ||<                       |          dk    }d||<   |rOt          j        |f|z             }t5          t7          ||          d          D ]\  }\  }}|||<   d||k    <   n3t          j        |d          dz   }                    |          }|||<   |S )a5  Random walker algorithm for segmentation from markers.

    Random walker algorithm is implemented for gray-level or multichannel
    images.

    Parameters
    ----------
    data : (M, N[, P][, C]) ndarray
        Image to be segmented in phases. Gray-level `data` can be two- or
        three-dimensional; multichannel data can be three- or four-
        dimensional with `channel_axis` specifying the dimension containing
        channels. Data spacing is assumed isotropic unless the `spacing`
        keyword argument is used.
    labels : (M, N[, P]) array of ints
        Array of seed markers labeled with different positive integers
        for different phases. Zero-labeled pixels are unlabeled pixels.
        Negative labels correspond to inactive pixels that are not taken
        into account (they are removed from the graph). If labels are not
        consecutive integers, the labels array will be transformed so that
        labels are consecutive. In the multichannel case, `labels` should have
        the same shape as a single channel of `data`, i.e. without the final
        dimension denoting channels.
    beta : float, optional
        Penalization coefficient for the random walker motion
        (the greater `beta`, the more difficult the diffusion).
    mode : string, available options {'cg', 'cg_j', 'cg_mg', 'bf'}
        Mode for solving the linear system in the random walker algorithm.

        - 'bf' (brute force): an LU factorization of the Laplacian is
          computed. This is fast for small images (<1024x1024), but very slow
          and memory-intensive for large images (e.g., 3-D volumes).
        - 'cg' (conjugate gradient): the linear system is solved iteratively
          using the Conjugate Gradient method from scipy.sparse.linalg. This is
          less memory-consuming than the brute force method for large images,
          but it is quite slow.
        - 'cg_j' (conjugate gradient with Jacobi preconditionner): the
          Jacobi preconditionner is applied during the Conjugate
          gradient method iterations. This may accelerate the
          convergence of the 'cg' method.
        - 'cg_mg' (conjugate gradient with multigrid preconditioner): a
          preconditioner is computed using a multigrid solver, then the
          solution is computed with the Conjugate Gradient method. This mode
          requires that the pyamg module is installed.
    tol : float, optional
        Tolerance to achieve when solving the linear system using
        the conjugate gradient based modes ('cg', 'cg_j' and 'cg_mg').
    copy : bool, optional
        If copy is False, the `labels` array will be overwritten with
        the result of the segmentation. Use copy=False if you want to
        save on memory.
    return_full_prob : bool, optional
        If True, the probability that a pixel belongs to each of the
        labels will be returned, instead of only the most likely
        label.
    spacing : iterable of floats, optional
        Spacing between voxels in each spatial dimension. If `None`, then
        the spacing between pixels/voxels in each dimension is assumed 1.
    prob_tol : float, optional
        Tolerance on the resulting probability to be in the interval [0, 1].
        If the tolerance is not satisfied, a warning is displayed.
    channel_axis : int or None, optional
        If None, the image is assumed to be a grayscale (single channel) image.
        Otherwise, this parameter indicates which axis of the array corresponds
        to channels.

        .. versionadded:: 0.19
           ``channel_axis`` was added in 0.19.

    Returns
    -------
    output : ndarray
        * If `return_full_prob` is False, array of ints of same shape
          and data type as `labels`, in which each pixel has been
          labeled according to the marker that reached the pixel first
          by anisotropic diffusion.
        * If `return_full_prob` is True, array of floats of shape
          `(nlabels, labels.shape)`. `output[label_nb, i, j]` is the
          probability that label `label_nb` reaches the pixel `(i, j)`
          first.

    See Also
    --------
    skimage.segmentation.watershed
        A segmentation algorithm based on mathematical morphology
        and "flooding" of regions from markers.

    Notes
    -----
    Multichannel inputs are scaled with all channel data combined. Ensure all
    channels are separately normalized prior to running this algorithm.

    The `spacing` argument is specifically for anisotropic datasets, where
    data points are spaced differently in one or more spatial dimensions.
    Anisotropic data is commonly encountered in medical imaging.

    The algorithm was first proposed in [1]_.

    The algorithm solves the diffusion equation at infinite times for
    sources placed on markers of each phase in turn. A pixel is labeled with
    the phase that has the greatest probability to diffuse first to the pixel.

    The diffusion equation is solved by minimizing x.T L x for each phase,
    where L is the Laplacian of the weighted graph of the image, and x is
    the probability that a marker of the given phase arrives first at a pixel
    by diffusion (x=1 on markers of the phase, x=0 on the other markers, and
    the other coefficients are looked for). Each pixel is attributed the label
    for which it has a maximal value of x. The Laplacian L of the image
    is defined as:

       - L_ii = d_i, the number of neighbors of pixel i (the degree of i)
       - L_ij = -w_ij if i and j are adjacent pixels

    The weight w_ij is a decreasing function of the norm of the local gradient.
    This ensures that diffusion is easier between pixels of similar values.

    When the Laplacian is decomposed into blocks of marked and unmarked
    pixels::

        L = M B.T
            B A

    with first indices corresponding to marked pixels, and then to unmarked
    pixels, minimizing x.T L x for one phase amount to solving::

        A x = - B x_m

    where x_m = 1 on markers of the given phase, and 0 on other markers.
    This linear system is solved in the algorithm using a direct method for
    small images, and an iterative method for larger images.

    References
    ----------
    .. [1] Leo Grady, Random walks for image segmentation, IEEE Trans Pattern
        Anal Mach Intell. 2006 Nov;28(11):1768-83.
        :DOI:`10.1109/TPAMI.2006.233`.

    Examples
    --------
    >>> rng = np.random.default_rng()
    >>> a = np.zeros((10, 10)) + 0.2 * rng.random((10, 10))
    >>> a[5:8, 5:8] += 1
    >>> b = np.zeros_like(a, dtype=np.int32)
    >>> b[3, 3] = 1  # Marker for first phase
    >>> b[6, 6] = 2  # Marker for second phase
    >>> random_walker(a, b)  # doctest: +SKIP
    array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
           [1, 1, 1, 1, 1, 2, 2, 2, 1, 1],
           [1, 1, 1, 1, 1, 2, 2, 2, 1, 1],
           [1, 1, 1, 1, 1, 2, 2, 2, 1, 1],
           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], dtype=int32)

    )rp   r   rs   ro   NzK is not a valid mode. Valid modes are 'cg_mg', 'cg', 'cg_j', 'bf', and Nonesafe)castingNrC   r   rt   z`Input argument `spacing` incorrect, should be an iterable with one number per spatial dimension.)r   rC   z=For non-multichannel input, data must be of dimension 2 or 3.z$Incompatible data and labels shapes..)rC      z9For multichannel input, data must have 3 or 4 dimensions.r   c                 L    g | ] }|d k    t          j        |k              !S r   )r   r   )r.   r_   rc   s     r   r2   z!random_walker.<locals>.<listcomp>)  s-    VVV#cTUggv}--gggr&   r)   r   z{The probability range is outside [0, 1] given the tolerance `prob_tol`. Consider decreasing `beta` and/or decreasing `tol`.r   F)start)r   dtyper   float16r   float32oneslenndimr_r   r,   r   r   newaxisr   r   r6   rH   rm   r   minr   r   r   zeros	enumeratezipargmax)r0   rc   r;   r   r   r   return_full_probr1   r   r   r=   labels_shapelabels_dtyperd   rL   r   r   ri   rk   r   outr_   
label_probprobs    `                      r   random_walkerr   <  s   X 666 , , ,
 
 	

 zRZ {{2:v{66 '!**	W	$	$w<<1eGSL)G*W%%>
 
 	
  t+L -9F""R   :%%CDDD}\$//00bjA9F""N   :crc?fl**CDDDD!!9>>111bj!!!+,D<L<L !DOPVDWDWAVWd/  	>VVVV69J9JVVV     )gvwdL MJ 	ZC66Auuww(aeeggH44	
 	
 	
 #2F^^L))FQ;D %D	 hzL011'0S!A'F'F'F 	* 	*#C#*d#Jt()Jv}%%	* Iaa   1$mmL))D	Jr&   )r   ro   r   TFN)%__doc__numpyr   scipyr   r   r   _sharedr   _shared.utilsr   _shared.compatr   #scipy.sparse.linalg.dsolve.linsolver	   r   __del__r   r   ImportErrorpyamgr   r   utilr   scipy.sparse.linalgr   r   r%   rA   rY   rm   r   r   r   channel_as_last_axisr   r\   r&   r   <module>r      s'        ( ( ( ( ( ( ( (                   4 4 4 4 4 4;;;;;;$,G   &-G"+W+--NN   NNN((((((JJ   JJJ        + + + + + + + +  ># # #L  @  @1 1 1h   <G <G <G~ 666 
		T T T T T 76T T Ts#   0A AA!A* *A43A4