
    wgP                     *   d Z ddlmZ ddlmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZmZmZ dd	lmZ dd
lm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 ddlm Z  ddl!mZ ddl"m#Z# ddl$m%Z% d Z&d Z'd Z(d Z)d Z*d Z+dddZ,d Z-d"dZ.ddd Z/y!)#zUtility functions for geometrical entities.

Contains
========
intersection
convex_hull
closest_points
farthest_points
are_coplanar
are_similar

    )deque)sqrt)	nsimplify   )GeometryEntity)GeometryError)PointPoint2DPoint3D)
OrderedSet)factor_terms)Function
expand_mul)Float)ordered)Symbol)S)cancel)is_sequence)prec_to_dpsc                     |j                   }|D cg c]&  }t        | t              r|j                  n|| k(  s%|( }}|st	        d| z        t        |      dk7  rt	        d| z        |d   S c c}w )a  
    Checks whether a Symbol matching ``x`` is present in ``equation``
    or not. If present, the matching symbol is returned, else a
    ValueError is raised. If ``x`` is a string the matching symbol
    will have the same name; if ``x`` is a Symbol then it will be
    returned if found.

    Examples
    ========

    >>> from sympy.geometry.util import find
    >>> from sympy import Dummy
    >>> from sympy.abc import x
    >>> find('x', x)
    x
    >>> find('x', Dummy('x'))
    _x

    The dummy symbol is returned since it has a matching name:

    >>> _.name == 'x'
    True
    >>> find(x, Dummy('x'))
    Traceback (most recent call last):
    ...
    ValueError: could not find x
    zcould not find %sr   zambiguous %sr   )free_symbols
isinstancestrname
ValueErrorlen)xequationfreeixss        X/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/geometry/util.pyfindr$   #   sv    :   D	H
1c(:affaG!	HB	H,q011
2w!|!+,,a5L 
Is
   &A/A/c                 0    t        t        | d             S )z?Return the tuple of points sorted numerically according to argsc                     | j                   S Nargsr   s    r#   <lambda>z!_ordered_points.<locals>.<lambda>K   s
         key)tuplesorted)ps    r#   _ordered_pointsr2   I   s    /011r,   c                  b   ddl m} ddlm} t	        |       } t        |       D ]5  t        |      s| j                         t        fd| D              c S  t        d | D              rt        |       dk  ry| j                         | j                         }}t        |       D ]+  t        j                  ||      s| j                         - | sy |||| j                               }| D ]  |vs y yg }| D ]  t        t              r|j                         %t        |      r|j                  j                         Mt        t               s^j                  D ]7  }t        |t"              s|j                  t        |j                  d	z           9  t%        | S )
a	   Returns True if the given entities are coplanar otherwise False

    Parameters
    ==========

    e: entities to be checked for being coplanar

    Returns
    =======

    Boolean

    Examples
    ========

    >>> from sympy import Point3D, Line3D
    >>> from sympy.geometry.util import are_coplanar
    >>> a = Line3D(Point3D(5, 0, 0), Point3D(1, -1, 1))
    >>> b = Line3D(Point3D(0, -2, 0), Point3D(3, 1, 1))
    >>> c = Line3D(Point3D(0, -1, 0), Point3D(5, -1, 9))
    >>> are_coplanar(a, b, c)
    False

    r   )LinearEntity3D)Planec              3   @   K   | ]  }|j                          y wr'   )is_coplanar).0r1   r!   s     r#   	<genexpr>zare_coplanar.<locals>.<genexpr>p   s     3Aq}}Q'3s   c              3   <   K   | ]  }t        |t                y wr'   )r   r   )r8   r!   s     r#   r9   zare_coplanar.<locals>.<genexpr>r   s     
-a:a!
-      FT)r   )liner4   planer5   setlistr   removeallr   popr   are_collinearappendextendr)   r   r	   are_coplanar)er4   r5   abr1   pt3dr!   s          @r#   rG   rG   N   s   2 % 	AA!W 4aHHQK33334
 
-1
--q6A: uuw1a 	A$$Q1-	  aAEEG$A !A: !  		?A!W%AA~.AFF#A~. ?A!!U+Gafftm$=>?		? T""r,   c                     | |k(  ryt        | dd      }|r ||      S t        |dd      }|r ||       S | j                  j                  }|j                  j                  }t        d|d|      )a  Are two geometrical entities similar.

    Can one geometrical entity be uniformly scaled to the other?

    Parameters
    ==========

    e1 : GeometryEntity
    e2 : GeometryEntity

    Returns
    =======

    are_similar : boolean

    Raises
    ======

    GeometryError
        When `e1` and `e2` cannot be compared.

    Notes
    =====

    If the two objects are equal then they are similar.

    See Also
    ========

    sympy.geometry.entity.GeometryEntity.is_similar

    Examples
    ========

    >>> from sympy import Point, Circle, Triangle, are_similar
    >>> c1, c2 = Circle(Point(0, 0), 4), Circle(Point(1, 4), 3)
    >>> t1 = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))
    >>> t2 = Triangle(Point(0, 0), Point(2, 0), Point(0, 2))
    >>> t3 = Triangle(Point(0, 0), Point(3, 0), Point(0, 1))
    >>> are_similar(t1, t2)
    True
    >>> are_similar(t1, t3)
    False

    T
is_similarNzCannot test similarity between z and )getattr	__class____name__r   )e1e2is_similar1is_similar2n1n2s         r#   are_similarrW      sx    \ 
Rx"lD1K2"lD1K2			B			B
68"=? ?r,   c                  J  	
 ddl m
 ddlm	 | rt	        d | D              r$t        dd      }| D ]  }||z  }	 t        |       }nt	        
fd| D              r;t        dd      }d}| D ]%  }|j                  }||j                  |z  z  }||z  }' |}nNt	        	fd| D              r:t        dd      }d}| D ]%  }|j                  }||j                  |z  z  }||z  }' |}z  } |j                  |j                  D cg c]  }|j                          c} S yc c}w )	a  Find the centroid (center of mass) of the collection containing only Points,
    Segments or Polygons. The centroid is the weighted average of the individual centroid
    where the weights are the lengths (of segments) or areas (of polygons).
    Overlapping regions will add to the weight of that region.

    If there are no objects (or a mixture of objects) then None is returned.

    See Also
    ========

    sympy.geometry.point.Point, sympy.geometry.line.Segment,
    sympy.geometry.polygon.Polygon

    Examples
    ========

    >>> from sympy import Point, Segment, Polygon
    >>> from sympy.geometry.util import centroid
    >>> p = Polygon((0, 0), (10, 0), (10, 10))
    >>> q = p.translate(0, 20)
    >>> p.centroid, q.centroid
    (Point2D(20/3, 10/3), Point2D(20/3, 70/3))
    >>> centroid(p, q)
    Point2D(20/3, 40/3)
    >>> p, q = Segment((0, 0), (2, 0)), Segment((0, 0), (2, 2))
    >>> centroid(p, q)
    Point2D(1, 2 - sqrt(2))
    >>> centroid(Point(0, 0), Point(2, 0))
    Point2D(1, 0)

    Stacking 3 polygons on top of each other effectively triples the
    weight of that polygon:

    >>> p = Polygon((0, 0), (1, 0), (1, 1), (0, 1))
    >>> q = Polygon((1, 0), (3, 0), (3, 1), (1, 1))
    >>> centroid(p, q)
    Point2D(3/2, 1/2)
    >>> centroid(p, p, p, q) # centroid x-coord shifts left
    Point2D(11/10, 1/2)

    Stacking the squares vertically above and below p has the same
    effect:

    >>> centroid(p, p.translate(0, 1), p.translate(0, -1), q)
    Point2D(11/10, 1/2)

    r   SegmentPolygonc              3   <   K   | ]  }t        |t                y wr'   )r   r	   )r8   gs     r#   r9   zcentroid.<locals>.<genexpr>  s     2z!U#2r;   r   c              3   6   K   | ]  }t        |        y wr'   r   )r8   r^   rZ   s     r#   r9   zcentroid.<locals>.<genexpr>       6AAw'6   c              3   6   K   | ]  }t        |        y wr'   r`   )r8   r^   r\   s     r#   r9   zcentroid.<locals>.<genexpr>  ra   rb   N)r=   rZ   polygonr\   rB   r	   r   lengthmidpointareacentroidfuncr)   simplify)r)   cr^   denLlArI   r!   r\   rZ   s            @@r#   rh   rh      s2   `  2T22aA Qd)C666aAA HHQZZ\!Q C666aAA FFQZZ\!Q C	Sqvvaff5

566/ . 6s   D c                     t        |       D cg c]  }t        |       }}t        |      dk  rt        d      	 |j	                  d        t        d |D              sd }ndd	lm} d
g} ||d   j                  |d   j                  z
  |d   j                  |d   j                  z
        }d}d}t        ddg      }|t        |      k  r||k  rC||   d   ||   d   z
  |kD  r/|j                          |dz  }||k  r||   d   ||   d   z
  |kD  r/|D ]l  } |||   j                  ||   j                  z
  ||   j                  ||   j                  z
        }	|	|k  r||fg}n|	|k(  r|j                  ||f       nk|	}n |j                  |       |dz  }|t        |      k  r|D 
ch c]  }
t        |
D cg c]  }||   	 c}        c}}
S c c}w # t
        $ r t        d      w xY wc c}w c c}}
w )a;  Return the subset of points from a set of points that were
    the closest to each other in the 2D plane.

    Parameters
    ==========

    args
        A collection of Points on 2D plane.

    Notes
    =====

    This can only be performed on a set of points whose coordinates can
    be ordered on the number line. If there are no ties then a single
    pair of Points will be in the set.

    Examples
    ========

    >>> from sympy import closest_points, Triangle
    >>> Triangle(sss=(3, 4, 5)).args
    (Point2D(0, 0), Point2D(3, 0), Point2D(3, 4))
    >>> closest_points(*_)
    {(Point2D(0, 0), Point2D(3, 0))}

    References
    ==========

    .. [1] https://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairPS.html

    .. [2] Sweep line algorithm
        https://en.wikipedia.org/wiki/Sweep_line_algorithm

       z)At least 2 distinct points must be given.c                     | j                   S r'   r(   r*   s    r#   r+   z closest_points.<locals>.<lambda>D  
    QVV r,   r-   The points could not be sorted.c              3   V   K   | ]!  }|j                   D ]  }|j                    # y wr'   r)   is_Rationalr8   jr!   s      r#   r9   z!closest_points.<locals>.<genexpr>H  $     88Aq}}8}8   ')c                 \    | | z  ||z  z   }|j                   rt        |      S t        |      S r'   rw   _sqrtr   r   yargs      r#   hypotzclosest_points.<locals>.hypotI  .    A#!)CSz!9r,   r   r   )r   r   r   )r?   r
   r   r   sort	TypeErrorrB   mathr   r   r   r   popleftrE   r/   )r)   r!   r1   r   rv	best_distleftboxry   dpairs              r#   closest_pointsr     s   F !Y''A'
1vzDEE<	#$ 8a88	 	
Badffqtvvoqtvv!7I	AD
A-C
c!f*Qh1Q47QtWQZ/);KKMAID Qh1Q47QtWQZ/);  	Aadffqtvvoqtvv!7A9}!fXi		1a&!I	 	

1	Q c!f*" 577DE&A1Q4&'77Q 	(  <:;;<D '7s(   GG 3G<G7	G<G47G<T)rd   c                 d   ddl m} ddlm} t	               }|D ]  }t        |t              s	 t        |      }t        |t              r|j                  |       At        ||      r|j                  |j                         it        ||      r|j                  |j                         t        dt        |      z         t!        d |D              rt        d      t#        |      }t%        |      dk(  r| r|d   S |d   d	fS t%        |      d
k(  r ||d   |d         }| r|S |d	fS d }g }g }		 |j'                  d        |D ]  }
t%        |      dkD  rE ||d   |d   |
      dk  r2|j+                          t%        |      dkD  r ||d   |d   |
      dk  r2t%        |	      dkD  rE ||	d   |	d   |
      dk\  r2|	j+                          t%        |	      dkD  r ||	d   |	d   |
      dk\  r2|j-                  |
       |	j-                  |
        |j/                          t1        |	|dd z         }t%        |      d
k(  r ||d   |d         }| r|S |d	fS | r || S |j/                          ||	fS # t        $ r t        dt        |      z        w xY w# t(        $ r t        d      w xY w)a  The convex hull surrounding the Points contained in the list of entities.

    Parameters
    ==========

    args : a collection of Points, Segments and/or Polygons

    Optional parameters
    ===================

    polygon : Boolean. If True, returns a Polygon, if false a tuple, see below.
              Default is True.

    Returns
    =======

    convex_hull : Polygon if ``polygon`` is True else as a tuple `(U, L)` where
                  ``L`` and ``U`` are the lower and upper hulls, respectively.

    Notes
    =====

    This can only be performed on a set of points whose coordinates can
    be ordered on the number line.

    See Also
    ========

    sympy.geometry.point.Point, sympy.geometry.polygon.Polygon

    Examples
    ========

    >>> from sympy import convex_hull
    >>> points = [(1, 1), (1, 2), (3, 1), (-5, 2), (15, 4)]
    >>> convex_hull(*points)
    Polygon(Point2D(-5, 2), Point2D(1, 1), Point2D(3, 1), Point2D(15, 4))
    >>> convex_hull(*points, **dict(polygon=False))
    ([Point2D(-5, 2), Point2D(15, 4)],
     [Point2D(-5, 2), Point2D(1, 1), Point2D(3, 1), Point2D(15, 4)])

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Graham_scan

    .. [2] Andrew's Monotone Chain Algorithm
      (A.M. Andrew,
      "Another Efficient Algorithm for Convex Hulls in Two Dimensions", 1979)
      https://web.archive.org/web/20210511015444/http://geomalgorithms.com/a10-_hull-1.html

    r   rY   r[   z8%s is not a GeometryEntity and cannot be made into Pointz#Convex hull for %s not implemented.c              3   8   K   | ]  }t        |      d k7    yw)rq   N)r   )r8   r   s     r#   r9   zconvex_hull.<locals>.<genexpr>  s     
"13q6Q;
"s   z2Can only compute the convex hull in two dimensionsr   Nrq   c                     |j                   | j                   z
  |j                  | j                  z
  z  |j                  | j                  z
  |j                   | j                   z
  z  z
  S )zNReturn positive if p-q-r are clockwise, neg if ccw, zero if
        collinear.)r   r   )r1   qrs      r#   _orientationz!convex_hull.<locals>._orientation  sI     acc	ACC!##I&!##)accACCi)@@@r,   c                     | j                   S r'   r(   r*   s    r#   r+   zconvex_hull.<locals>.<lambda>  rs   r,   r-   rt   )r=   rZ   rd   r\   r   r   r   r	   NotImplementedErrorr   r   addupdatepointsverticestypeanyr@   r   r   r   rC   rE   reverser/   )rd   r)   rZ   r\   r1   rH   sr   Urm   p_i
convexHulls               r#   convex_hullr   j  s   j  A A!^,f!H aEE!H7#HHQXX7#HHQZZ %5Q?A AA" 
"
""MNNQA
1v{qt0QqT4L0	Q1AaD!A$q*!T*A 	A
A<	#$  !fqj\!B%2<AEEG !fqj\!B%2<A!fqj\!B%2<AEEG !fqj\!B%2<A		 IIKq1Qr7{#J
:!JqM:a=1q*!T*
##			1vi ' f ![^abc^d!deefB  <:;;<s   I63J 6!JJ/c                     d }t        |       D cg c]  }t        |       }}t        d |D              sd }nddlm} g }d} ||       D ]n  }t        |      \  }}	 ||j                  |	j                  z
  |j                  |	j                  z
        }
|
|kD  r||	fg}n|
|k(  r|j                  ||	f       nm|
}p t        |      S c c}w )al  Return the subset of points from a set of points that were
    the furthest apart from each other in the 2D plane.

    Parameters
    ==========

    args
        A collection of Points on 2D plane.

    Notes
    =====

    This can only be performed on a set of points whose coordinates can
    be ordered on the number line. If there are no ties then a single
    pair of Points will be in the set.

    Examples
    ========

    >>> from sympy.geometry import farthest_points, Triangle
    >>> Triangle(sss=(3, 4, 5)).args
    (Point2D(0, 0), Point2D(3, 0), Point2D(3, 4))
    >>> farthest_points(*_)
    {(Point2D(0, 0), Point2D(3, 4))}

    References
    ==========

    .. [1] https://code.activestate.com/recipes/117225-convex-hull-and-diameter-of-2d-point-sets/

    .. [2] Rotating Callipers Technique
        https://en.wikipedia.org/wiki/Rotating_calipers

    c              3     K   t        | i ddi\  }}|*t        |t              rt        d      |j                   y d}t        |      dz
  }|t        |      dz
  k  s|dkD  r||   ||   f |t        |      dz
  k(  r|dz  }n|dk(  r|dz  }n||dz      j                  ||   j                  z
  ||   j                  ||dz
     j                  z
  z  ||   j                  ||dz
     j                  z
  ||dz      j                  ||   j                  z
  z  kD  r|dz  }n|dz  }|t        |      dz
  k  r|dkD  ry y w)Nrd   Fz+At least two distinct points must be given.r   r   )r   r   r	   r   r)   r   r   r   )Pointsr   rm   r!   ry   s        r#   rotatingCalipersz)farthest_points.<locals>.rotatingCalipers   sH    F9y%&8919!U# !NOO&&LAA
Ac!fqj.AEdAaDj A
?FA!VFA !fhh1'AaDFFQqsVXX,=>1!AaC&((*q1vxx!A$&&/@ABFAFA c!fqj.AEs   D8E;EEc              3   V   K   | ]!  }|j                   D ]  }|j                    # y wr'   rv   rx   s      r#   r9   z"farthest_points.<locals>.<genexpr>  rz   r{   c                 \    | | z  ||z  z   }|j                   rt        |      S t        |      S r'   r}   r   s      r#   r   zfarthest_points.<locals>.hypot  r   r,   r   r   )	r?   r
   rB   r   r   r2   r   r   rE   )r)   r   r!   r1   r   r   diamr   hr   r   s              r#   farthest_pointsr     s    H2 !Y''A'8a88	 		BD & 	t$1!##)QSS133Y't8a&B$YIIq!f	 r7N1 	(s   C	c           
         t        |      rt        |      }|d   }n3t        |t              r|h}nt        |t              rnt        d|z        | j                  D ci c]'  }||k7  r |v r| t	        |j                        |      ) }}t        |t              r+ t	        |j                        |      j                  |      }n|j                  |      }| j                  |      } i }t        |      D ]  }	| j                  |      }
|
j                  |t        j                  i      }|
|z
  j                  |t        j                  i      }t        t!        t#        | |z  j                  |            d            }|	|dz
  k(  r6|j                  |j%                         D cg c]	  \  }}||f c}}      c S |||<   ||z
  } |j                  |      } yc c}w c c}}w )a  Return ``dy/dx`` assuming that ``eq == 0``.

    Parameters
    ==========

    y : the dependent variable or a list of dependent variables (with y first)
    x : the variable that the derivative is being taken with respect to
    n : the order of the derivative (default is 1)

    Examples
    ========

    >>> from sympy.abc import x, y, a
    >>> from sympy.geometry.util import idiff

    >>> circ = x**2 + y**2 - 4
    >>> idiff(circ, y, x)
    -x/y
    >>> idiff(circ, y, x, 2).simplify()
    (-x**2 - y**2)/y**3

    Here, ``a`` is assumed to be independent of ``x``:

    >>> idiff(x + a + y, y, x)
    -1

    Now the x-dependence of ``a`` is made explicit by listing ``a`` after
    ``y`` in a list.

    >>> idiff(x + a + y, [y, a], x)
    -Derivative(a, x) - 1

    See Also
    ========

    sympy.core.function.Derivative: represents unevaluated derivatives
    sympy.core.function.diff: explicitly differentiates wrt symbols

    r   z:expecting x-dependent symbol(s) or function(s) but got: %sF)deepr   N)r   r?   r   r   r   r   r   r   diffsubsrangexreplacer   ZeroOner   r   r   items)eqr   r   ndepr   fdydxderivsr!   deqrJ   rI   ypkvs                   r#   idiffr   4  s   P 1~!faD	Av	c	Ax	 UXYYZZ)+ 	 A6a3h 
HQVVQ	 	 A 	  !Vx"''*vvay	BF1X 
ggajLL$(1Waee}-*VaRTKK,?%@uMNA:77qwwy9tq!QF9::tBYyy|
	 " :s   ,G'G"F)pairwisec           	      h   t        |      dk  rg S t        |      }d}t        |      D ]  \  }}t        |t              st        |      }i }|j                  t              D ]C  }||j                  nt        |j                  |      }|j                  |t        |d             E |j                  |      ||<    | sM|d   j                  |d         }|dd D ]-  }	g }
|D ]"  }|
j                  |j                  |	             $ |
}/ nvg }t        t        |            D ]@  }t        |dz   t        |            D ]#  }|j                  t        ||   ||                % B t        t!        t#        |                  }|)t%        |      }|D cg c]  }|j'                  |       }}|S c c}w )a   The intersection of a collection of GeometryEntity instances.

    Parameters
    ==========
    entities : sequence of GeometryEntity
    pairwise (keyword argument) : Can be either True or False

    Returns
    =======
    intersection : list of GeometryEntity

    Raises
    ======
    NotImplementedError
        When unable to calculate intersection.

    Notes
    =====
    The intersection of any geometrical entity with itself should return
    a list with one item: the entity in question.
    An intersection requires two or more entities. If only a single
    entity is given then the function will return an empty list.
    It is possible for `intersection` to miss intersections that one
    knows exists because the required quantities were not fully
    simplified internally.
    Reals should be converted to Rationals, e.g. Rational(str(real_num))
    or else failures due to floating point issues may result.

    Case 1: When the keyword argument 'pairwise' is False (default value):
    In this case, the function returns a list of intersections common to
    all entities.

    Case 2: When the keyword argument 'pairwise' is True:
    In this case, the functions returns a list intersections that occur
    between any pair of entities.

    See Also
    ========

    sympy.geometry.entity.GeometryEntity.intersection

    Examples
    ========

    >>> from sympy import Ray, Circle, intersection
    >>> c = Circle((0, 1), 1)
    >>> intersection(c, c.center)
    []
    >>> right = Ray((0, 0), (1, 0))
    >>> up = Ray((0, 0), (0, 1))
    >>> intersection(c, right, up)
    [Point2D(0, 0)]
    >>> intersection(c, right, up, pairwise=True)
    [Point2D(0, 0), Point2D(0, 2)]
    >>> left = Ray((1, 0), (0, 0))
    >>> intersection(right, left)
    [Segment2D(Point2D(0, 0), Point2D(1, 0))]

    r   NT)rationalr   rq   )r   r@   	enumerater   r   r	   atomsr   _precmin
setdefaultr   r   intersectionrF   r   r   r?   r   r   )r   entitieskwargsprecr!   rH   r   r   resentitynewresr   ansry   r   r1   s                   r#   r   r   }  s   x 8}	H~HD(# 	$1!^,aA 	9A"l177AGGT0BDLLIa$78	9 jjm	$ qk&&x{3qrl 	FF 6annV456C		 s8}% 	CA1q5#h-0 C

<Xa[ABC	C 73s8$% "#!qss1v##J $s   F/N)r   )0__doc__collectionsr   r   r   r~   sympyr   r   r   
exceptionsr   pointr	   r
   r   sympy.core.containersr   sympy.core.exprtoolsr   sympy.core.functionr   r   sympy.core.numbersr   sympy.core.sortingr   sympy.core.symbolr   sympy.core.singletonr   sympy.polys.polytoolsr   (sympy.functions.elementary.miscellaneoussympy.utilities.iterablesr   mpmath.libmp.libmpfr   r$   r2   rG   rW   rh   r   r   r   r   r    r,   r#   <module>r      s       " % * * , - 4 $ & $ " ( 9 1 +#L2
C#L9?xI7XK8\  $ pdUpFR &+ `r,   