
    0-Ph~                         d dl Z d dlmZ d dlZd dlmZ d dlmZm	Z	  ej
        d          Zd Zd Z G d d	          Z G d
 de          Z G d de          Z G d de          Zd Zdddej        d dddfdZdS )    N)warn)inv)optimizespatial   c                 d    | j         dk    s| j        d         |k    rt          d| d          d S )N   r   zInput data must have shape (N, z).ndimshape
ValueError)datadims     S/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/skimage/measure/fit.py_check_data_dimr      s?    yA~~A#--B3BBBCCC .-    c                 \    | j         dk     s| j        d         dk     rt          d          d S )Nr	   r   zInput data must be at least 2D.r
   )r   s    r   _check_data_atleast_2Dr      s4    y1}}
1)):;;; *)r   c                       e Zd Zd ZdS )	BaseModelc                     d | _         d S N)params)selfs    r   __init__zBaseModel.__init__   s    r   N)__name__
__module____qualname__r    r   r   r   r      s#            r   r   c                   8    e Zd ZdZd Zd	dZd
dZd	dZd	dZdS )LineModelNDau  Total least squares estimator for N-dimensional lines.

    In contrast to ordinary least squares line estimation, this estimator
    minimizes the orthogonal distances of points to the estimated line.

    Lines are defined by a point (origin) and a unit vector (direction)
    according to the following vector equation::

        X = origin + lambda * direction

    Attributes
    ----------
    params : tuple
        Line model parameters in the following order `origin`, `direction`.

    Examples
    --------
    >>> x = np.linspace(1, 2, 25)
    >>> y = 1.5 * x + 3
    >>> lm = LineModelND()
    >>> lm.estimate(np.stack([x, y], axis=-1))
    True
    >>> tuple(np.round(lm.params, 5))
    (array([1.5 , 5.25]), array([0.5547 , 0.83205]))
    >>> res = lm.residuals(np.stack([x, y], axis=-1))
    >>> np.abs(np.round(res, 9))
    array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
           0., 0., 0., 0., 0., 0., 0., 0.])
    >>> np.round(lm.predict_y(x[:5]), 3)
    array([4.5  , 4.562, 4.625, 4.688, 4.75 ])
    >>> np.round(lm.predict_x(y[:5]), 3)
    array([1.   , 1.042, 1.083, 1.125, 1.167])

    c                    t          |           |                    d          }||z
  }|j        d         dk    r<|d         |d         z
  }t          j                            |          }|dk    r||z  }nA|j        d         dk    r.t          j                            |d          \  }}}|d         }ndS ||f| _        dS )a  Estimate line model from data.

        This minimizes the sum of shortest (orthogonal) distances
        from the given data points to the estimated line.

        Parameters
        ----------
        data : (N, dim) array
            N points in a space of dimensionality dim >= 2.

        Returns
        -------
        success : bool
            True, if model estimation succeeds.
        r   axisr	   r   F)full_matricesT)r   meanr   nplinalgnormsvdr   )r   r   origin	directionr)   _vs          r   estimatezLineModelND.estimate?   s      	t$$$""f}:a=AQ$q')I9>>),,DqyyT!	Z]QimmDm>>GAq!!II5y)tr   Nc                 4   t          |           || j        t          d          | j        }t          |          dk    rt          d          |\  }}||z
  ||z
  |z  dt          j        f         |z  z
  }t          j                            |d          S )a  Determine residuals of data to model.

        For each point, the shortest (orthogonal) distance to the line is
        returned. It is obtained by projecting the data onto the line.

        Parameters
        ----------
        data : (N, dim) array
            N points in a space of dimension dim.
        params : (2,) array, optional
            Optional custom parameter set in the form (`origin`, `direction`).

        Returns
        -------
        residuals : (N,) array
            Residual for each data point.
        NParameters cannot be Noner	   !Parameters are defined by 2 sets..r   r#   )r   r   r   lenr'   newaxisr(   r)   )r   r   r   r+   r,   ress         r   	residualszLineModelND.residualsd   s    $ 	t$$$>{" !<===[Fv;;!@AAA"	f}$-9!<O!
!  y~~c~***r   r   c                 *   || j         t          d          | j         }t          |          dk    rt          d          |\  }}||         dk    rt          d|           |||         z
  ||         z  }||dt          j        f         |z  z   }|S )al  Predict intersection of the estimated line model with a hyperplane
        orthogonal to a given axis.

        Parameters
        ----------
        x : (n, 1) array
            Coordinates along an axis.
        axis : int
            Axis orthogonal to the hyperplane intersecting the line.
        params : (2,) array, optional
            Optional custom parameter set in the form (`origin`, `direction`).

        Returns
        -------
        data : (n, m) array
            Predicted coordinates.

        Raises
        ------
        ValueError
            If the line is parallel to the given axis.
        Nr1   r	   r2   r   zLine parallel to axis .)r   r   r3   r'   r4   )r   xr$   r   r+   r,   lr   s           r   predictzLineModelND.predict   s    . >{" !<===[Fv;;!@AAA"	T?a<d<<===40#rz/*Y66r   c                 J    |                      |d|          dddf         }|S )a  Predict x-coordinates for 2D lines using the estimated model.

        Alias for::

            predict(y, axis=1)[:, 0]

        Parameters
        ----------
        y : array
            y-coordinates.
        params : (2,) array, optional
            Optional custom parameter set in the form (`origin`, `direction`).

        Returns
        -------
        x : array
            Predicted x-coordinates.

        r   r$   r   Nr   r:   )r   yr   r8   s       r   	predict_xzLineModelND.predict_x   -    ( LL6L22111a48r   c                 J    |                      |d|          dddf         }|S )a  Predict y-coordinates for 2D lines using the estimated model.

        Alias for::

            predict(x, axis=0)[:, 1]

        Parameters
        ----------
        x : array
            x-coordinates.
        params : (2,) array, optional
            Optional custom parameter set in the form (`origin`, `direction`).

        Returns
        -------
        y : array
            Predicted y-coordinates.

        r   r<   Nr   r=   )r   r8   r   r>   s       r   	predict_yzLineModelND.predict_y   r@   r   r   )r   N)	r   r   r   __doc__r/   r6   r:   r?   rB   r   r   r   r!   r!      s        ! !F# # #J+ + + +@& & & &P   .     r   r!   c                   &    e Zd ZdZd Zd ZddZdS )CircleModelaM  Total least squares estimator for 2D circles.

    The functional model of the circle is::

        r**2 = (x - xc)**2 + (y - yc)**2

    This estimator minimizes the squared distances from all points to the
    circle::

        min{ sum((r - sqrt((x_i - xc)**2 + (y_i - yc)**2))**2) }

    A minimum number of 3 points is required to solve for the parameters.

    Attributes
    ----------
    params : tuple
        Circle model parameters in the following order `xc`, `yc`, `r`.

    Notes
    -----
    The estimation is carried out using a 2D version of the spherical
    estimation given in [1]_.

    References
    ----------
    .. [1] Jekel, Charles F. Obtaining non-linear orthotropic material models
           for pvc-coated polyester via inverse bubble inflation.
           Thesis (MEng), Stellenbosch University, 2016. Appendix A, pp. 83-87.
           https://hdl.handle.net/10019.1/98627

    Examples
    --------
    >>> t = np.linspace(0, 2 * np.pi, 25)
    >>> xy = CircleModel().predict_xy(t, params=(2, 3, 4))
    >>> model = CircleModel()
    >>> model.estimate(xy)
    True
    >>> tuple(np.round(model.params, 5))
    (2.0, 3.0, 4.0)
    >>> res = model.residuals(xy)
    >>> np.abs(np.round(res, 9))
    array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
           0., 0., 0., 0., 0., 0., 0., 0.])
    c                 t   t          |d           t          j        |j        t          j                  }|                    |d          }|                    d          }||z
  }|                                }|t          j        |          j	        k     rt          dt          d           dS ||z  }t          j        |dz  t          j        |j        d         d	f|
          d	          }t          j        |dz  d	          }t          j                            ||d          \  }}}	}|	dk    rt          d           dS |dd         }
t%          j        |
|          }t          j        t          j        |dz                      }|
|z  }
||z  }|
|z  }
t+          |
          |fz   | _        dS )a/  Estimate circle model from data using total least squares.

        Parameters
        ----------
        data : (N, 2) array
            N points with ``(x, y)`` coordinates, respectively.

        Returns
        -------
        success : bool
            True, if model estimation succeeds.

        r	   r   Fcopyr   r#   zUStandard deviation of data is too small to estimate circle with meaningful precision.category
stacklevelr   dtypeN)rcond   z6Input does not contain enough significant data points.T)r   r'   promote_typesrN   float32astyper&   stdfinfotinyr   RuntimeWarningappendonesr   sumr(   lstsqr   minkowski_distancesqrttupler   )r   r   
float_typer+   scaleAfCr-   rankcenter	distancesrs                r   r/   zCircleModel.estimate	  s    	!$$$$ %dj"*==
{{:E{22 ""f}

28J'',,,4'	    5
 IdQhA(:* M M MTUVVVF47###	1D991dA199IJJJ51Q3.vt<<	GBGIqL))** 	%	U
&Fmmqd*tr   c                     t          |d           | j        \  }}}|dddf         }|dddf         }|t          j        ||z
  dz  ||z
  dz  z             z
  S )ae  Determine residuals of data to model.

        For each point the shortest distance to the circle is returned.

        Parameters
        ----------
        data : (N, 2) array
            N points with ``(x, y)`` coordinates, respectively.

        Returns
        -------
        residuals : (N,) array
            Residual for each data point.

        r	   rG   Nr   r   )r   r   r'   r]   )r   r   xcycrg   r8   r>   s          r   r6   zCircleModel.residualsC  sp    " 	!$$$$K	BAJAJ27AFq=AFq=89999r   Nc                     || j         }|\  }}}||t          j        |          z  z   }||t          j        |          z  z   }t          j        |d         |d         f|j                  S )a  Predict x- and y-coordinates using the estimated model.

        Parameters
        ----------
        t : array
            Angles in circle in radians. Angles start to count from positive
            x-axis to positive y-axis in a right-handed system.
        params : (3,) array, optional
            Optional custom parameter set.

        Returns
        -------
        xy : (..., 2) array
            Predicted x- and y-coordinates.

        N.Nr#   )r   r'   cossinconcatenater   )r   tr   ri   rj   rg   r8   r>   s           r   
predict_xyzCircleModel.predict_xy]  sk    " >[F	BRVAYYRVAYY~q|Qy\:HHHHr   r   r   r   r   rC   r/   r6   rq   r   r   r   rE   rE      sX        + +Z8 8 8t: : :4I I I I I Ir   rE   c                   &    e Zd ZdZd Zd ZddZdS )EllipseModelaL  Total least squares estimator for 2D ellipses.

    The functional model of the ellipse is::

        xt = xc + a*cos(theta)*cos(t) - b*sin(theta)*sin(t)
        yt = yc + a*sin(theta)*cos(t) + b*cos(theta)*sin(t)
        d = sqrt((x - xt)**2 + (y - yt)**2)

    where ``(xt, yt)`` is the closest point on the ellipse to ``(x, y)``. Thus
    d is the shortest distance from the point to the ellipse.

    The estimator is based on a least squares minimization. The optimal
    solution is computed directly, no iterations are required. This leads
    to a simple, stable and robust fitting method.

    The ``params`` attribute contains the parameters in the following order::

        xc, yc, a, b, theta

    Attributes
    ----------
    params : tuple
        Ellipse model parameters in the following order `xc`, `yc`, `a`, `b`,
        `theta`.

    Examples
    --------

    >>> xy = EllipseModel().predict_xy(np.linspace(0, 2 * np.pi, 25),
    ...                                params=(10, 15, 8, 4, np.deg2rad(30)))
    >>> ellipse = EllipseModel()
    >>> ellipse.estimate(xy)
    True
    >>> np.round(ellipse.params, 2)
    array([10.  , 15.  ,  8.  ,  4.  ,  0.52])
    >>> np.round(abs(ellipse.residuals(xy)), 5)
    array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
           0., 0., 0., 0., 0., 0., 0., 0.])
    c                    t          |d           t          |          dk     rt          dt          d           dS t	          j        |j        t          j                  }|                    |d          }|	                    d	          }||z
  }|
                                }|t	          j        |          j        k     rt          d
t          d           dS ||z  }|dddf         }|dddf         }t	          j        |dz  ||z  |dz  g          j        }t	          j        ||t	          j        |          g          j        }|j        |z  }	|j        |z  }
|j        |z  }t	          j        g dg dg dg          }	 t#          |          |	|
t#          |          z  |
j        z  z
  z  }n# t          j        j        $ r Y dS w xY wt          j                            |          \  }}dt	          j        |dddf         |dddf                   z  t	          j        |dddf         d          z
  }|dd|dk    f         }d|j        v s%t          |                                          dk    rdS |                                \  }}}t#          |           |
j        z  |z  }|                                \  }}}|dz  }|dz  }|dz  }||z  ||z  z
  |dz  ||z  z
  z  }||z  ||z  z
  |dz  ||z  z
  z  }||dz  z  ||dz  z  z   ||dz  z  z   d|z  |z  |z  z
  ||z  |z  z
  }t	          j        ||z
  dz  d|dz  z  z             }|dz  ||z  z
  |||z   z
  z  }|dz  ||z  z
  | ||z   z
  z  }t	          j        d|z  |z            }t	          j        d|z  |z            } dt	          j        d|z  ||z
  z            z  }!||k    r|!dt          j        z  z  }!|| k     r| |} }|!t          j        dz  z  }!|!t          j        z  }!t	          j        |||| |!g          j        }"|"ddxx         |z  cc<   |"ddxx         |z  cc<   t=          d |"D                       | _        dS )ag  Estimate ellipse model from data using total least squares.

        Parameters
        ----------
        data : (N, 2) array
            N points with ``(x, y)`` coordinates, respectively.

        Returns
        -------
        success : bool
            True, if model estimation succeeds.


        References
        ----------
        .. [1] Halir, R.; Flusser, J. "Numerically stable direct least squares
               fitting of ellipses". In Proc. 6th International Conference in
               Central Europe on Computer Graphics and Visualization.
               WSCG (Vol. 98, pp. 125-132).

        r	   rG      z3Need at least 5 data points to estimate an ellipse.rJ   FrH   r   r#   zVStandard deviation of data is too small to estimate ellipse with meaningful precision.Nr   )        rw          @)rw   g      rw   )rx   rw   rw      rP   rx   g      ?c              3   4   K   | ]}t          |          V  d S r   )float).0ps     r   	<genexpr>z(EllipseModel.estimate.<locals>.<genexpr>$  s(      55E!HH555555r   T) r   r3   r   rW   r'   rQ   rN   rR   rS   r&   rT   rU   rV   vstackT	ones_likearrayr   r(   LinAlgErroreigmultiplypowerr   ravelr]   arctanpi
nan_to_numrealr^   r   )#r   r   r_   r+   r`   r8   r>   D1D2S1S2S3C1Meig_valseig_vecsconda1abca2drb   gx0y0	numeratortermdenominator1denominator2widthheightphir   s#                                      r   r/   zEllipseModel.estimate  s   0 	!$$$$t99q==E'   
 5 %dj"*==
{{:E{22 ""f}

28J'',,,5'	    5AJAJ Y1a!eQT*++-Y1bl1oo.//1 TBYTBYTBY X(8(8(8///JKK	B2SWWrt 334AAy$ 	 	 	55	
  Y]]1--( 2;x111~x111~>>>QTNAB
 B
 
 aaa$(m$==C

OOq005((**1a "ggX_r!((**1a 	
S	S	S !ea!em3Q/!ea!em3Q/ 1Hq1a4x'!ad(2QUQY]BQUQYN	wA!|a!Q$h.//1q1uQ81q1u$!a%9I455Y566 BIsQw1q51222q553;C
 6>>"E6E2519Cru Bvs;<<Arr


e


rr


f


55f55555ts   
-F8 8GGc                 F   t          |d           | j        \  }t          j        |          t          j        |          |dddf         }|dddf         }|j        d         }fd}t          j        |ft          j                  }t          j	        |z
  |z
            |z
  }t          |          D ]V}	||	         }
||	         }t          j        |||	         |
|f          \  }}t          j         |||
|                    ||	<   W|S )	af  Determine residuals of data to model.

        For each point the shortest distance to the ellipse is returned.

        Parameters
        ----------
        data : (N, 2) array
            N points with ``(x, y)`` coordinates, respectively.

        Returns
        -------
        residuals : (N,) array
            Residual for each data point.

        r	   rG   Nr   r   c                    t          j        t          j        |                     }t          j        t          j        |                     }	z  |z  z   
z  |z  z
  }
z  |z  z   	z  |z  z   }||z
  dz  ||z
  dz  z   S )Nr	   )mathrm   r'   squeezern   )rp   xiyictstxtytr   r   cthetasthetari   rj   s          r   funz#EllipseModel.residuals.<locals>.funE  s    "*Q--((B"*Q--((Ba&j2o%F
R7Ba&j2o%F
R7BG>R"WN22r   rM   )args)r   r   r   rm   rn   r   r'   emptyfloat64arctan2ranger   leastsqr]   )r   r   thetar8   r>   Nr   r6   t0ir   r   rp   r-   r   r   r   r   ri   rj   s                 @@@@@@r   r6   zEllipseModel.residuals(  sU   " 	!$$$$"kB1e%%AJAJJqM	3 	3 	3 	3 	3 	3 	3 	3 	3 	3$ HaT444	 ZBB''%/ q 	3 	3A1B1B#CAb"X>>>DAq733q"b>>22IaLLr   Nc                 f   || j         }|\  }}}}}t          j        |          }t          j        |          }	t	          j        |          }
t	          j        |          }|||
z  |z  z   ||z  |	z  z
  }|||z  |z  z   ||
z  |	z  z   }t          j        |d         |d         f|j                  S )a  Predict x- and y-coordinates using the estimated model.

        Parameters
        ----------
        t : array
            Angles in circle in radians. Angles start to count from positive
            x-axis to positive y-axis in a right-handed system.
        params : (5,) array, optional
            Optional custom parameter set.

        Returns
        -------
        xy : (..., 2) array
            Predicted x- and y-coordinates.

        Nrl   r#   )r   r'   rm   rn   r   ro   r   )r   rp   r   ri   rj   r   r   r   r   r   r   r   r8   r>   s                 r   rq   zEllipseModel.predict_xyf  s    $ >[F$B1eVAYYVAYY%%Vb 1v:?2Vb 1v:?2~q|Qy\:HHHHr   r   rr   r   r   r   rt   rt   x  s\        & &PE E EN< < <|I I I I I Ir   rt   c                 `   |dk    rdS | dk    rt           j        S | |z  }d|z
  }d||z  z
  }t          j        |t          dt          z
            }t          j        |t          dt          z
            }t          j        t          j        |          t          j        |          z            S )a  Determine number trials such that at least one outlier-free subset is
    sampled for the given inlier/outlier ratio.

    Parameters
    ----------
    n_inliers : int
        Number of inliers in the data.
    n_samples : int
        Total number of samples in the data.
    min_samples : int
        Minimum number of samples chosen randomly from original data.
    probability : float
        Probability (confidence) that one outlier-free sample is generated.

    Returns
    -------
    trials : int
        Number of trials.
    r   r   )a_mina_max)r'   infclip_EPSILONceillog)	n_inliers	n_samplesmin_samplesprobabilityinlier_rationomdenoms          r   _dynamic_max_trialsr     s    ( aqA~~vy(L
k/Ck))E '#XQ\
:
:
:CGEX>>>E726#;;.///r   d   c           	         d}t           j        }g |du}|du}t           j                            |
          }
t	          | t
          t          f          s| f} t          | d                   }d|cxk     r|k    sn t          d| d          |dk     rt          d          |dk     rt          d          d|	cxk    rdk    sn t          d          |6t          |          |k    r#t          d	t          |           d
| d          ||n|
	                    ||d           |            }d}||k     r|dz  }fd| D             }|
	                    ||d          |r || s9 |j
        | }||sH|r
 ||g|R  sTt          j         |j        |            }||k     }|                    |          }t          j        |          }||k    s||k    r9||k     r3|}|}|t          |t!          ||||	                    }||k    s||k    rn||k     t#                    r3fd| D             } |j
        |  |r ||g|R  st%          d           nd}dt%          d           |fS )a  Fit a model to data with the RANSAC (random sample consensus) algorithm.

    RANSAC is an iterative algorithm for the robust estimation of parameters
    from a subset of inliers from the complete data set. Each iteration
    performs the following tasks:

    1. Select `min_samples` random samples from the original data and check
       whether the set of data is valid (see `is_data_valid`).
    2. Estimate a model to the random subset
       (`model_cls.estimate(*data[random_subset]`) and check whether the
       estimated model is valid (see `is_model_valid`).
    3. Classify all data as inliers or outliers by calculating the residuals
       to the estimated model (`model_cls.residuals(*data)`) - all data samples
       with residuals smaller than the `residual_threshold` are considered as
       inliers.
    4. Save estimated model as best model if number of inlier samples is
       maximal. In case the current estimated model has the same number of
       inliers, it is only considered as the best model if it has less sum of
       residuals.

    These steps are performed either a maximum number of times or until one of
    the special stop criteria are met. The final model is estimated using all
    inlier samples of the previously determined best model.

    Parameters
    ----------
    data : [list, tuple of] (N, ...) array
        Data set to which the model is fitted, where N is the number of data
        points and the remaining dimension are depending on model requirements.
        If the model class requires multiple input data arrays (e.g. source and
        destination coordinates of  ``skimage.transform.AffineTransform``),
        they can be optionally passed as tuple or list. Note, that in this case
        the functions ``estimate(*data)``, ``residuals(*data)``,
        ``is_model_valid(model, *random_data)`` and
        ``is_data_valid(*random_data)`` must all take each data array as
        separate arguments.
    model_class : object
        Object with the following object methods:

         * ``success = estimate(*data)``
         * ``residuals(*data)``

        where `success` indicates whether the model estimation succeeded
        (`True` or `None` for success, `False` for failure).
    min_samples : int in range (0, N)
        The minimum number of data points to fit a model to.
    residual_threshold : float larger than 0
        Maximum distance for a data point to be classified as an inlier.
    is_data_valid : function, optional
        This function is called with the randomly selected data before the
        model is fitted to it: `is_data_valid(*random_data)`.
    is_model_valid : function, optional
        This function is called with the estimated model and the randomly
        selected data: `is_model_valid(model, *random_data)`, .
    max_trials : int, optional
        Maximum number of iterations for random sample selection.
    stop_sample_num : int, optional
        Stop iteration if at least this number of inliers are found.
    stop_residuals_sum : float, optional
        Stop iteration if sum of residuals is less than or equal to this
        threshold.
    stop_probability : float in range [0, 1], optional
        RANSAC iteration stops if at least one outlier-free set of the
        training data is sampled with ``probability >= stop_probability``,
        depending on the current best model's inlier ratio and the number
        of trials. This requires to generate at least N samples (trials):

            N >= log(1 - probability) / log(1 - e**m)

        where the probability (confidence) is typically set to a high value
        such as 0.99, e is the current fraction of inliers w.r.t. the
        total number of samples, and m is the min_samples value.
    rng : {`numpy.random.Generator`, int}, optional
        Pseudo-random number generator.
        By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`).
        If `rng` is an int, it is used to seed the generator.
    initial_inliers : array-like of bool, shape (N,), optional
        Initial samples selection for model estimation


    Returns
    -------
    model : object
        Best model with largest consensus set.
    inliers : (N,) array
        Boolean mask of inliers classified as ``True``.

    References
    ----------
    .. [1] "RANSAC", Wikipedia, https://en.wikipedia.org/wiki/RANSAC

    Examples
    --------

    Generate ellipse data without tilt and add noise:

    >>> t = np.linspace(0, 2 * np.pi, 50)
    >>> xc, yc = 20, 30
    >>> a, b = 5, 10
    >>> x = xc + a * np.cos(t)
    >>> y = yc + b * np.sin(t)
    >>> data = np.column_stack([x, y])
    >>> rng = np.random.default_rng(203560)  # do not copy this value
    >>> data += rng.normal(size=data.shape)

    Add some faulty data:

    >>> data[0] = (100, 100)
    >>> data[1] = (110, 120)
    >>> data[2] = (120, 130)
    >>> data[3] = (140, 130)

    Estimate ellipse model using all available data:

    >>> model = EllipseModel()
    >>> model.estimate(data)
    True
    >>> np.round(model.params)  # doctest: +SKIP
    array([ 72.,  75.,  77.,  14.,   1.])

    Estimate ellipse model using RANSAC:

    >>> ransac_model, inliers = ransac(data, EllipseModel, 20, 3, max_trials=50)
    >>> abs(np.round(ransac_model.params))  # doctest: +SKIP
    array([20., 30., 10.,  6.,  2.])
    >>> inliers  # doctest: +SKIP
    array([False, False, False, False,  True,  True,  True,  True,  True,
            True,  True,  True,  True,  True,  True,  True,  True,  True,
            True,  True,  True,  True,  True,  True,  True,  True,  True,
            True,  True,  True,  True,  True,  True,  True,  True,  True,
            True,  True,  True,  True,  True,  True,  True,  True,  True,
            True,  True,  True,  True,  True], dtype=bool)
    >>> sum(inliers) > 40
    True

    RANSAC can be used to robustly estimate a geometric
    transformation. In this section, we also show how to use a
    proportion of the total samples, rather than an absolute number.

    >>> from skimage.transform import SimilarityTransform
    >>> rng = np.random.default_rng()
    >>> src = 100 * rng.random((50, 2))
    >>> model0 = SimilarityTransform(scale=0.5, rotation=1,
    ...                              translation=(10, 20))
    >>> dst = model0(src)
    >>> dst[0] = (10000, 10000)
    >>> dst[1] = (-100, 100)
    >>> dst[2] = (50, 50)
    >>> ratio = 0.5  # use half of the samples
    >>> min_samples = int(ratio * len(src))
    >>> model, inliers = ransac(
    ...     (src, dst),
    ...     SimilarityTransform,
    ...     min_samples,
    ...     10,
    ...     initial_inliers=np.ones(len(src), dtype=bool),
    ... )  # doctest: +SKIP
    >>> inliers  # doctest: +SKIP
    array([False, False, False,  True,  True,  True,  True,  True,  True,
            True,  True,  True,  True,  True,  True,  True,  True,  True,
            True,  True,  True,  True,  True,  True,  True,  True,  True,
            True,  True,  True,  True,  True,  True,  True,  True,  True,
            True,  True,  True,  True,  True,  True,  True,  True,  True,
            True,  True,  True,  True,  True])

    r   Nz#`min_samples` must be in range (0, ]z.`residual_threshold` must be greater than zeroz&`max_trials` must be greater than zeror   z*`stop_probability` must be in range [0, 1]z4RANSAC received a vector of initial inliers (length z+) that didn't match the number of samples (z). The vector of initial inliers should have the same length as the number of samples and contain only True (this sample is an initial inlier) and False (this one isn't) values.F)replacec                      g | ]
}|         S r   r   )r|   r   spl_idxss     r   
<listcomp>zransac.<locals>.<listcomp>  s    ---11X;---r   c                      g | ]
}|         S r   r   )r|   r   best_inlierss     r   r   zransac.<locals>.<listcomp>  s    666A,666r   z8Estimated model is not valid. Try increasing max_trials.z"No inliers found. Model not fitted)r'   r   randomdefault_rng
isinstancer^   listr3   r   choicer/   absr6   dotcount_nonzerominr   anyr   )r   model_classr   residual_thresholdis_data_validis_model_valid
max_trialsstop_sample_numstop_residuals_sumstop_probabilityrnginitial_inliersbest_inlier_numbest_inlier_residuals_sumvalidate_modelvalidate_datanum_samplesmodel
num_trialssamplessuccessr6   inliersresiduals_suminliers_countdata_inliersr   r   s                             @@r   ransacr     s   j O "L#4/N!-M
)


$
$C dUDM** wd1g,,K****{****M{MMMNNNAIJJJA~~ABBB!&&&&Q&&&&EFFF"s?';';{'J'J?## #  
 
 	
 & 	ZZ[%Z@@  KMMEJ
z
!
!a
 .------ ::k;:FF  	!8 	 %.'*w  	.."A"A"A"A 	F?5?D122	00!i00 (11 O++ 00!$=== ,O(5%"L##[+?O  J  ?22,0BBBi z
!
!n < 	36666666%% 	M.."F"F"F"F 	MKLLL1222,r   )r   warningsr   numpyr'   numpy.linalgr   scipyr   r   spacingr   r   r   r   r!   rE   rt   r   r   r   r   r   r   <module>r      s                    # # # # # # # # 2:a==D D D
< < <
       
} } } } }) } } }@ZI ZI ZI ZI ZI) ZI ZI ZIzMI MI MI MI MI9 MI MI MI` 0  0  0P Ff f f f f fr   