
    (ph	5                     P    S r SSKrSSKrSSKJr  SSKJr  S/rS r	 " S S5      r
g)	z3
Spherical Voronoi Code

.. versionadded:: 0.18.0

    N   )_voronoi)cKDTreeSphericalVoronoic           	         [         R                  R                  U 5      nS[         R                  " SU SS2S4   U SS2S4   5      [         R                  " SU SS2S4   U SS2S4   5      -   [         R                  " SU SS2S4   U SS2S4   5      -   -   n[         R                  " S[         R
                  " X5      -  5      $ )zCalculates the solid angles of plane triangles. Implements the method of
Van Oosterom and Strackee [VanOosterom]_ with some modifications. Assumes
that input points have unit norm.r   ij,ij->iNr      )nplinalgdeteinsumabsarctan2)R	numeratordenominators      S/var/www/html/venv/lib/python3.13/site-packages/scipy/spatial/_spherical_voronoi.pycalculate_solid_anglesr      s     		a IryyQq!tWa1g>yyQq!tWa1g>?yyQq!tWa1g>? @K 66!bjj8899    c                   @    \ rS rSrSrSS jrS rS rS rS r	S	 r
S
rg)r   $   a  Voronoi diagrams on the surface of a sphere.

.. versionadded:: 0.18.0

Parameters
----------
points : ndarray of floats, shape (npoints, ndim)
    Coordinates of points from which to construct a spherical
    Voronoi diagram.
radius : float, optional
    Radius of the sphere (Default: 1)
center : ndarray of floats, shape (ndim,)
    Center of sphere (Default: origin)
threshold : float
    Threshold for detecting duplicate points and
    mismatches between points and sphere parameters.
    (Default: 1e-06)

Attributes
----------
points : double array of shape (npoints, ndim)
    the points in `ndim` dimensions to generate the Voronoi diagram from
radius : double
    radius of the sphere
center : double array of shape (ndim,)
    center of the sphere
vertices : double array of shape (nvertices, ndim)
    Voronoi vertices corresponding to points
regions : list of list of integers of shape (npoints, _ )
    the n-th entry is a list consisting of the indices
    of the vertices belonging to the n-th point in points

Methods
-------
calculate_areas
    Calculates the areas of the Voronoi regions. For 2D point sets, the
    regions are circular arcs. The sum of the areas is ``2 * pi * radius``.
    For 3D point sets, the regions are spherical polygons. The sum of the
    areas is ``4 * pi * radius**2``.

Raises
------
ValueError
    If there are duplicates in `points`.
    If the provided `radius` is not consistent with `points`.

Notes
-----
The spherical Voronoi diagram algorithm proceeds as follows. The Convex
Hull of the input points (generators) is calculated, and is equivalent to
their Delaunay triangulation on the surface of the sphere [Caroli]_.
The Convex Hull neighbour information is then used to
order the Voronoi region vertices around each generator. The latter
approach is substantially less sensitive to floating point issues than
angle-based methods of Voronoi region vertex sorting.

Empirical assessment of spherical Voronoi algorithm performance suggests
quadratic time complexity (loglinear is optimal, but algorithms are more
challenging to implement).

References
----------
.. [Caroli] Caroli et al. Robust and Efficient Delaunay triangulations of
            points on or close to a sphere. Research Report RR-7004, 2009.

.. [VanOosterom] Van Oosterom and Strackee. The solid angle of a plane
                 triangle. IEEE Transactions on Biomedical Engineering,
                 2, 1983, pp 125--126.

See Also
--------
Voronoi : Conventional Voronoi diagrams in N dimensions.

Examples
--------
Do some imports and take some points on a cube:

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from scipy.spatial import SphericalVoronoi, geometric_slerp
>>> from mpl_toolkits.mplot3d import proj3d
>>> # set input data
>>> points = np.array([[0, 0, 1], [0, 0, -1], [1, 0, 0],
...                    [0, 1, 0], [0, -1, 0], [-1, 0, 0], ])

Calculate the spherical Voronoi diagram:

>>> radius = 1
>>> center = np.array([0, 0, 0])
>>> sv = SphericalVoronoi(points, radius, center)

Generate plot:

>>> # sort vertices (optional, helpful for plotting)
>>> sv.sort_vertices_of_regions()
>>> t_vals = np.linspace(0, 1, 2000)
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111, projection='3d')
>>> # plot the unit sphere for reference (optional)
>>> u = np.linspace(0, 2 * np.pi, 100)
>>> v = np.linspace(0, np.pi, 100)
>>> x = np.outer(np.cos(u), np.sin(v))
>>> y = np.outer(np.sin(u), np.sin(v))
>>> z = np.outer(np.ones(np.size(u)), np.cos(v))
>>> ax.plot_surface(x, y, z, color='y', alpha=0.1)
>>> # plot generator points
>>> ax.scatter(points[:, 0], points[:, 1], points[:, 2], c='b')
>>> # plot Voronoi vertices
>>> ax.scatter(sv.vertices[:, 0], sv.vertices[:, 1], sv.vertices[:, 2],
...                    c='g')
>>> # indicate Voronoi regions (as Euclidean polygons)
>>> for region in sv.regions:
...    n = len(region)
...    for i in range(n):
...        start = sv.vertices[region][i]
...        end = sv.vertices[region][(i + 1) % n]
...        result = geometric_slerp(start, end, t_vals)
...        ax.plot(result[..., 0],
...                result[..., 1],
...                result[..., 2],
...                c='k')
>>> ax.azim = 10
>>> ax.elev = 40
>>> _ = ax.set_xticks([])
>>> _ = ax.set_yticks([])
>>> _ = ax.set_zticks([])
>>> fig.set_size_inches(4, 4)
>>> plt.show()

Nc                    Uc  [        S5      e[        U5      U l        [        R                  " U5      R                  [        R                  5      U l        U R                  R                  S   U l	        Uc&  [        R                  " U R                  5      U l        O[        R                  " U[        S9U l        [        R                  R                  U R                  U R                  S   -
  X@R                  -  S9U l        U R                  U R                  :  a  [        SU R                   35      e[        U R                  5      R!                  X@R                  -  5      (       a  [        S5      e[        R                  R#                  U R                  U R                  -
  SS9n[        R$                  " XPR                  -
  5      R'                  5       nXdU R                  -  :  a  [        S	5      eU R)                  5         g )
NzM`radius` is `None`. Please provide a floating point number (i.e. `radius=1`).r   )dtyper   )tolz&Rank of input points must be at least zDuplicate generators present.axisz$Radius inconsistent with generators.)
ValueErrorfloatradiusr
   arrayastypefloat64pointsshape_dimzeroscenterr   matrix_rank_rankr   query_pairsnormr   max_calc_vertices_regions)selfr#   r   r'   	thresholdradiimax_discrepancys          r   __init__SphericalVoronoi.__init__   s}   > 2 3 3 Fmhhv&--bjj9KK%%a(	>((499-DK((67DK YY**4;;Q+G/8;;/F + H
::		!Edii[QRR4;;++I,CDD<==		t{{T[[8qA&&!4599;$++55CDD##%r   c           
         [         R                  R                  U R                  5      nU R                  UR
                  SS2SS24   -  U R                  -   U l        UR                  U l	        [        R                  " [        U R                  5      5      n[        R                  " U/U R                  -  5      R                  5       nU R                  R                  5       n[        R                   " USS9nX5   R#                  [        R$                  5      n[        R&                  " [        R(                  " US-   5      5      n[+        [        U5      S-
  5       Vs/ s H  n[-        XgU   XxS-       5      PM     n	nXl        gs  snf )a
  
Calculates the Voronoi vertices and regions of the generators stored
in self.points. The vertices will be stored in self.vertices and the
regions in self.regions.

This algorithm was discussed at PyData London 2015 by
Tyler Reddy, Ross Hemsley and Nikolai Nowaczyk
N	mergesort)kindr   )scipyspatial
ConvexHullr#   r   	equationsr'   vertices	simplices
_simplicesr
   arangelencolumn_stackr%   ravelargsortr!   intpcumsumbincountrangelistregions)
r.   convsimplex_indicestri_indicespoint_indicesindicesflattened_groups	intervalsigroupss
             r   r-   'SphericalVoronoi._calc_vertices_regions   s5    }}''4 dnnQV&<<t{{J.. ))C$89oo&7$))&CDJJL--/**]=&/66rww?IIbkk-!*;<=	 !Y!!3464a '!Y1u5EFG4 	 66s    Fc                     U R                   S:w  a  [        S5      e[        R                  " U R                  U R
                  5        g)a{  Sort indices of the vertices to be (counter-)clockwise ordered.

Raises
------
TypeError
    If the points are not three-dimensional.

Notes
-----
For each region in regions, it sorts the indices of the Voronoi
vertices such that the resulting points are in a clockwise or
counterclockwise order around the generator point.

This is done as follows: Recall that the n-th region in regions
surrounds the n-th generator in points and that the k-th
Voronoi vertex in vertices is the circumcenter of the k-th triangle
in self._simplices.  For each region n, we choose the first triangle
(=Voronoi vertex) in self._simplices and a vertex of that triangle
not equal to the center n. These determine a unique neighbor of that
triangle, which is then chosen as the second triangle. The second
triangle will have a unique vertex not equal to the current vertex or
the center. This determines a unique neighbor of the second triangle,
which is then chosen as the third triangle and so forth. We proceed
through all the triangles (=Voronoi vertices) belonging to the
generator in points and obtain a sorted version of the vertices
of its surrounding region.
   z/Only supported for three-dimensional point setsN)r%   	TypeErrorr   sort_vertices_of_regionsr>   rI   r.   s    r   rW   )SphericalVoronoi.sort_vertices_of_regions   s3    8 99>MNN))$//4<<Hr   c                    U R                  5         U R                   Vs/ s H  n[        U5      PM     nn[        R                  " U5      nUS   n[        U5       VVVs/ s H  u  pV[        U5        H  nUPM     M     nnnn[        R                  " U R                   VV	s/ s H  o  H  oPM     M     sn	n5      n
[        R                  " U
S5      n[        R                  " US5      nSUS'   XS-
     X'   U R                  U R                  -
  U R                  -  nU R                  U R                  -
  U R                  -  n[        R                  " X   X   X   /5      R                  USS45      n[        U5      n[        R                  " U5      US-
     nUSS === US S -  sss& UU R                  S-  -  $ s  snf s  snnnf s  sn	nf )Nr5   r   r   rU   r	   )rW   rI   r@   r
   rE   	enumeraterG   r    rollr#   r'   r   r<   hstackreshaper   )r.   regionsizescsizesnum_regionsrQ   sizejrM   rnbrs1nbrs2rN   pnormalizedvnormalized	trianglestriangle_solid_anglessolid_angless                     r   _calculate_areas_3d$SphericalVoronoi._calculate_areas_3d  s   %%'+/<<8<V<85!Rj
 +4E*: /*:wq"'+Q "- *: / $,,G,1!!,GH q!''&!$
z* {{T[[0DKK?}}t{{2dkkA II{9*1*1! " #*';1*="> 	 !7y A yy!67
CQRL"-- dkk1n,,G 9/ Hs   G !G$G
c                 .   U R                   U R                     U R                  -
  n[        R                  " US S 2S4   US S 2S4   -
  S-  SS9n[        R
                  " SUSU R                  S-  -  -  -
  5      nU R                  U-  n[        R                  " [        R                  " SUS S 2S4   U R                  U R                  -
  5      5      n[        R                  " US:  5      nS[        R                  -  U R                  -  XF   -
  XF'   U$ )Nr   r   r	   r   r   )r#   r>   r'   r
   sumarccosr   signr   r<   wherepi)r.   arcsdthetaareassignsrN   s          r   _calculate_areas_2d$SphericalVoronoi._calculate_areas_2d.  s    {{4??+dkk9 FFDAJad+1:		!qA)9$:;<= e# 		*d1a4j.2mmdkk.IK L((519%RUUT[[05>Ar   c                     U R                   S:X  a  U R                  5       $ U R                   S:X  a  U R                  5       $ [        S5      e)an  Calculates the areas of the Voronoi regions.

For 2D point sets, the regions are circular arcs. The sum of the areas
is ``2 * pi * radius``.

For 3D point sets, the regions are spherical polygons. The sum of the
areas is ``4 * pi * radius**2``.

.. versionadded:: 1.5.0

Returns
-------
areas : double array of shape (npoints,)
    The areas of the Voronoi regions.
r	   rU   z'Only supported for 2D and 3D point sets)r%   rz   rm   rV   rX   s    r   calculate_areas SphericalVoronoi.calculate_areas@  sD      99>++--YY!^++--EFFr   )r%   r)   r>   r'   r#   r   rI   r<   )r   Ngư>)__name__
__module____qualname____firstlineno____doc__r2   r-   rW   rm   rz   r}   __static_attributes__ r   r   r   r   $   s,    AD&>BI@%-N$Gr   )r   numpyr
   r8    r   scipy.spatialr   __all__r   r   r   r   r   <module>r      s3       !
:qG qGr   