a
    J5dg                     @   s*  d Z ddlmZ ddlZddlmZ ddlmZmZ ddl	m
Z
mZmZmZmZmZmZ ddlmZmZ ddlmZ dd	lmZ g d
ZG dd dZe ZejZejZejZejZej Z d&ddZ!d'ddZ"dd Z#dd Z$dd Z%dd Z&dd Z'G dd dZ(e(j)Z)d(dd Z*d!d" Z+d)d$d%ZdS )*z-Support for various GEOS geometry operations
    )warnN)	polylabel)GeometryTypeErrorShapelyDeprecationWarning)GeometryCollection
LineStringMultiLineString
MultiPointPointPolygonshape)BaseGeometryBaseMultipartGeometryorient)prep)cascaded_union	linemergeoperator
polygonizepolygonize_full	transformunary_uniontriangulatevoronoi_diagramsplitnearest_pointsvalidatesnapshared_pathsclip_by_rectr   	substringc                   @   s>   e Zd Zdd Zdd Zdd Zddd	Zd
d Zdd ZdS )CollectionOperatorc              	   C   s<   t |tr|S z
t|W S  ttfy6   t| Y S 0 d S N)
isinstancer   r   
ValueErrorAttributeErrorr   )selfob r)   G/var/www/html/django/DPS/env/lib/python3.9/site-packages/shapely/ops.pyshapeup,   s    

zCollectionOperator.shapeupc              	      sr   t |ddp|}z<zt|}W n ty6   |g}Y n0 W  fdd|D }n fdd|D }0 t|}|jS )zCreates polygons from a source of lines

        The source may be a MultiLineString, a sequence of LineString objects,
        or a sequence of objects than can be adapted to LineStrings.
        geomsNc                    s   g | ]}  |qS r)   r+   .0liner'   r)   r*   
<listcomp>A       z1CollectionOperator.polygonize.<locals>.<listcomp>)getattriter	TypeErrorshapelyr   r,   )r'   linessourceobs
collectionr)   r1   r*   r   5   s    (
zCollectionOperator.polygonizec              	      sl   t |ddp|}z<zt|}W n ty6   |g}Y n0 W  fdd|D }n fdd|D }0 t|S )a  Creates polygons from a source of lines, returning the polygons
        and leftover geometries.

        The source may be a MultiLineString, a sequence of LineString objects,
        or a sequence of objects than can be adapted to LineStrings.

        Returns a tuple of objects: (polygons, cut edges, dangles, invalid ring
        lines). Each are a geometry collection.

        Dangles are edges which have one or both ends which are not incident on
        another edge endpoint. Cut edges are connected at both ends but do not
        form part of polygon. Invalid ring lines form rings which are invalid
        (bowties, etc).
        r,   Nc                    s   g | ]}  |qS r)   r-   r.   r1   r)   r*   r2   Z   r3   z6CollectionOperator.polygonize_full.<locals>.<listcomp>)r4   r5   r6   r7   r   )r'   r8   r9   r:   r)   r1   r*   r   E   s    (z"CollectionOperator.polygonize_fullFc                 C   s   d}t |dddkr|}n\t|dr:tdd |jD }n<t|drvztdd |D }W n tyt   t|}Y n0 |du rtd	| tj||d
S )a  Merges all connected lines from a source

        The source may be a MultiLineString, a sequence of LineString objects,
        or a sequence of objects than can be adapted to LineStrings.  Returns a
        LineString or MultiLineString when lines are not contiguous.
        N	geom_typer   r,   c                 S   s   g | ]
}|j qS r)   coordsr/   Zlsr)   r)   r*   r2   i   r3   z0CollectionOperator.linemerge.<locals>.<listcomp>__iter__c                 S   s   g | ]
}|j qS r)   r=   r?   r)   r)   r*   r2   l   r3   zCannot linemerge )directed)r4   hasattrr   r,   r&   r%   r7   Z
line_merge)r'   r8   rA   r9   r)   r)   r*   r   ]   s    

zCollectionOperator.linemergec                 C   s   t dtdd tj|ddS )zReturns the union of a sequence of geometries

        .. deprecated:: 1.8
            This function was superseded by :meth:`unary_union`.
        zKThe 'cascaded_union()' function is deprecated. Use 'unary_union()' instead.   )
stacklevelNZaxis)r   r   r7   	union_allr'   r,   r)   r)   r*   r   s   s    z!CollectionOperator.cascaded_unionc                 C   s   t j|ddS )zReturns the union of a sequence of geometries

        Usually used to convert a collection into the smallest set of polygons
        that cover the same area.
        NrE   )r7   rF   rG   r)   r)   r*   r      s    zCollectionOperator.unary_unionN)F)	__name__
__module____qualname__r+   r   r   r   r   r   r)   r)   r)   r*   r"   +   s   	
r"           Fc                 C   s    t j| ||d}dd |jD S )a  Creates the Delaunay triangulation and returns a list of geometries

    The source may be any geometry type. All vertices of the geometry will be
    used as the points of the triangulation.

    From the GEOS documentation:
    tolerance is the snapping tolerance used to improve the robustness of
    the triangulation computation. A tolerance of 0.0 specifies that no
    snapping will take place.

    If edges is False, a list of Polygons (triangles) will be returned.
    Otherwise the list of LineString edges is returned.

    )	tolerance
only_edgesc                 S   s   g | ]}|qS r)   r)   )r/   gr)   r)   r*   r2      r3   ztriangulate.<locals>.<listcomp>)r7   Zdelaunay_trianglesr,   )geomrL   edgesr;   r)   r)   r*   r      s    r   c              
   C   s   zt j| |||d}W nP t jyf } z6d}|d|d7 }|rH|d7 }t||W Y d}~n
d}~0 0 |jdkr|t|gS |S )aT  
    Constructs a Voronoi Diagram [1] from the given geometry.
    Returns a list of geometries.

    Parameters
    ----------
    geom: geometry
        the input geometry whose vertices will be used to calculate
        the final diagram.
    envelope: geometry, None
        clipping envelope for the returned diagram, automatically
        determined if None. The diagram will be clipped to the larger
        of this envelope or an envelope surrounding the sites.
    tolerance: float, 0.0
        sets the snapping tolerance used to improve the robustness
        of the computation. A tolerance of 0.0 specifies that no
        snapping will take place.
    edges: bool, False
        If False, return regions as polygons. Else, return only
        edges e.g. LineStrings.

    GEOS documentation can be found at [2]

    Returns
    -------
    GeometryCollection
        geometries representing the Voronoi regions.

    Notes
    -----
    The tolerance `argument` can be finicky and is known to cause the
    algorithm to fail in several cases. If you're using `tolerance`
    and getting a failure, try removing it. The test cases in
    tests/test_voronoi_diagram.py show more details.


    References
    ----------
    [1] https://en.wikipedia.org/wiki/Voronoi_diagram
    [2] https://geos.osgeo.org/doxygen/geos__c_8h_source.html  (line 730)
    )rL   Z	extend_torM   z;Could not create Voronoi Diagram with the specified inputs (z).z0 Try running again with default tolerance value.Nr   )r7   Zvoronoi_polygonsZGEOSExceptionr%   r<   r   )rO   enveloperL   rP   resulterrZerrstrr)   r)   r*   r      s    *
 

r   c                 C   s
   t | S r#   )r7   Zis_valid_reasonrO   r)   r)   r*   r      s    r   c                    st  |j r
|S |jdv r(zz|jdv r>t|t t|j   W S |jdkrt|jt t|jj   }t fdd|jD }t|||W S W n ty$   |jdv rt| fdd|jD  Y S |jdkr t|j fdd|jjD }t fd	d|jD }t||| Y S Y n0 nH|j	d
sB|jdkr^t| fdd|j
D S td|jddS )aq  Applies `func` to all coordinates of `geom` and returns a new
    geometry of the same type from the transformed coordinates.

    `func` maps x, y, and optionally z to output xp, yp, zp. The input
    parameters may iterable types like lists or arrays or single values.
    The output shall be of the same type. Scalars in, scalars out.
    Lists in, lists out.

    For example, here is an identity function applicable to both types
    of input.

      def id_func(x, y, z=None):
          return tuple(filter(None, [x, y, z]))

      g2 = transform(id_func, g1)

    Using pyproj >= 2.1, this example will accurately project Shapely geometries:

      import pyproj

      wgs84 = pyproj.CRS('EPSG:4326')
      utm = pyproj.CRS('EPSG:32618')

      project = pyproj.Transformer.from_crs(wgs84, utm, always_xy=True).transform

      g2 = transform(project, g1)

    Note that the always_xy kwarg is required here as Shapely geometries only support
    X,Y coordinate ordering.

    Lambda expressions such as the one in

      g2 = transform(lambda x, y, z=None: (x+1.0, y+1.0), g1)

    also satisfy the requirements for `func`.
    )r
   r   
LinearRingr   )r
   r   rV   r   c                 3   s(   | ] }t |t t|j   V  qd S r#   )typezipr>   r/   ringfuncr)   r*   	<genexpr>  s   ztransform.<locals>.<genexpr>c                    s   g | ]} | qS r)   r)   r/   cr[   r)   r*   r2     r3   ztransform.<locals>.<listcomp>c                    s   g | ]} | qS r)   r)   r^   r[   r)   r*   r2   !  r3   c                 3   s*   | ]"}t | fd d|jD V  qdS )c                    s   g | ]} | qS r)   r)   r^   r[   r)   r*   r2   #  r3   z'transform.<locals>.<genexpr>.<listcomp>N)rW   r>   rY   r[   r)   r*   r]   "  s   ZMultir   c                    s   g | ]}t  |qS r)   )r   )r/   partr[   r)   r*   r2   )  r3   zType z not recognizedN)is_emptyr<   rW   rX   r>   ZexteriorlistZ	interiorsr6   
startswithr,   r   )r\   rO   shellZholesr)   r[   r*   r      s0    %


  r   c                 C   sL   t | |}|du r,| jr$tdntdt |d}t |d}||fS )zReturns the calculated nearest points in the input geometries

    The points are returned in the same order as the input geometries.
    Nz!The first input geometry is emptyz"The second input geometry is emptyr      )r7   Zshortest_linera   r%   Z	get_point)g1g2seqp1p2r)   r)   r*   r   .  s    
r   c                 C   s   t | ||S )a  Snap one geometry to another with a given tolerance

    Vertices of the first geometry are snapped to vertices of the second
    geometry. The resulting snapped geometry is returned. The input geometries
    are not modified.

    Parameters
    ----------
    g1 : geometry
        The first geometry
    g2 : geometry
        The second geometry
    tolerance : float
        The snapping tolerance

    Example
    -------
    >>> square = Polygon([(1,1), (2, 1), (2, 2), (1, 2), (1, 1)])
    >>> line = LineString([(0,0), (0.8, 0.8), (1.8, 0.95), (2.6, 0.5)])
    >>> result = snap(line, square, 0.5)
    >>> result.wkt
    'LINESTRING (0 0, 1 1, 2 1, 2.6 0.5)'
    )r7   r   )rf   rg   rL   r)   r)   r*   r   ?  s    r   c                 C   s0   t | tstdt |ts$tdt| |S )a  Find paths shared between the two given lineal geometries

    Returns a GeometryCollection with two elements:
     - First element is a MultiLineString containing shared paths with the
       same direction for both inputs.
     - Second element is a MultiLineString containing shared paths with the
       opposite direction for the two inputs.

    Parameters
    ----------
    g1 : geometry
        The first geometry
    g2 : geometry
        The second geometry
    z#First geometry must be a LineStringz$Second geometry must be a LineString)r$   r   r   r7   r   )rf   rg   r)   r)   r*   r   Z  s
    

r   c                   @   sH   e Zd Zedd Zedd Zedd Zedd Zed	d
 ZdS )SplitOpc                    sN   t  tstdt |ts$td j|}t   fddt|D S )z!Split a Polygon with a LineStringz First argument must be a Polygonz$Second argument must be a LineStringc                    s   g | ]}  | r|qS r)   )containsZrepresentative_point)r/   Zpgpolyr)   r*   r2     s   z4SplitOp._split_polygon_with_line.<locals>.<listcomp>)r$   r   r   r   boundaryunionr   r   )rn   splitterrp   r)   rm   r*   _split_polygon_with_liner  s    


z SplitOp._split_polygon_with_linec                 C   s   |j dv r|j}t| ts"tdt|ts>t|ts>td|| }|d dkr^tdn(|d dksv|d dkr| |S | gS d	S )
zCSplit a LineString with another (Multi)LineString or (Multi)Polygon)r   MultiPolygon#First argument must be a LineStringz@Second argument must be either a LineString or a MultiLineStringr   1z2Input geometry segment overlaps with the splitter.0   N)	r<   ro   r$   r   r   r   Zrelater%   
difference)r0   rq   Zrelationr)   r)   r*   _split_line_with_line  s     

	


zSplitOp._split_line_with_linec                 C   sV  t | tstdt |ts$td| |ds6| gS | jd |jd krP| gS | |}t| j}d}tt	|d D ]}|| }||d  }|d |d  }|d |d  }	|d |	d  d }
||
7 }||krt|d	|d  t||d d	 g  S ||k rxt|d	|d  |jd g t|jd g||d d	  g  S qx| gS )
zSplit a LineString with a Pointrt   zSecond argument must be a Pointz	0********r   rK   re   rC         ?N)
r$   r   r   r
   Zrelate_patternr>   projectrb   rangelen)r0   rq   Zdistance_on_liner>   current_positioniZpoint1Zpoint2ZdxZdysegment_lengthr)   r)   r*   _split_line_with_point  s2    




,
zSplitOp._split_line_with_pointc                 C   sh   t | tstdt |ts$td| g}|jD ]2}g }tdd |D ]}|t|| qF|}q0|S )z$Split a LineString with a MultiPointrt   z$Second argument must be a MultiPointc                 S   s   | j  S r#   )ra   )xr)   r)   r*   <lambda>  r3   z5SplitOp._split_line_with_multipoint.<locals>.<lambda>)	r$   r   r   r	   r,   filterextendrk   r   )r0   rq   chunksptZ
new_chunkschunkr)   r)   r*   _split_line_with_multipoint  s    


z#SplitOp._split_line_with_multipointc                    s   | j dv r"t fdd| jD S | j dkrv j dv r>tj}q j dkrPtj}q j dkrbtj}qtd j  d	nB| j d
kr j dkrtj}qtd j  d	ntd| j  dt||  S )aS  
        Splits a geometry by another geometry and returns a collection of geometries. This function is the theoretical
        opposite of the union of the split geometry parts. If the splitter does not split the geometry, a collection
        with a single geometry equal to the input geometry is returned.
        The function supports:
          - Splitting a (Multi)LineString by a (Multi)Point or (Multi)LineString or (Multi)Polygon
          - Splitting a (Multi)Polygon by a LineString

        It may be convenient to snap the splitter with low tolerance to the geometry. For example in the case
        of splitting a line by a point, the point must be exactly on the line, for the line to be correctly split.
        When splitting a line by a polygon, the boundary of the polygon is used for the operation.
        When splitting a line by another line, a ValueError is raised if the two overlap at some segment.

        Parameters
        ----------
        geom : geometry
            The geometry to be split
        splitter : geometry
            The geometry that will split the input geom

        Example
        -------
        >>> pt = Point((1, 1))
        >>> line = LineString([(0,0), (2,2)])
        >>> result = split(line, pt)
        >>> result.wkt
        'GEOMETRYCOLLECTION (LINESTRING (0 0, 1 1), LINESTRING (1 1, 2 2))'
        )r   rs   c                    s$   g | ]}t | jD ]}|qqS r)   )rk   r   r,   )r/   r`   r   rq   r)   r*   r2     r3   z!SplitOp.split.<locals>.<listcomp>r   )r   r   r   rs   r
   r	   zSplitting a LineString with a z is not supportedr   zSplitting a Polygon with a z
Splitting z geometry is not supported)	r<   r   r,   rk   ry   r   r   r   rr   )rO   rq   Z
split_funcr)   r   r*   r     s0    






zSplitOp.splitN)	rH   rI   rJ   staticmethodrr   ry   r   r   r   r)   r)   r)   r*   rk   q  s   

 
)
rk   c                 C   s  t | tstd| j d||kr0| ||S |sV|| jkrV|| jkrV| | j|S |s~| | jkr~| | jkr~| d|S |r|dkr|dkr| d|S |r| dkr| dkr| d|S |r|| j9 }|| j9 }|d  k r|k rn nt|| | jkr| |S |d  k r*|k rLn nt|| | jkrL| |S | |}| |}|dk rt| j| }|dk r| j| }||k}|r|| }}|dk rd}|r|j|jfg}n|j|jfg}t	| j
}d}	t||dd D ]r\}
}||	  k r|k r"n n||
 n|	|kr2 qf|	|d |
d  d |d |
d  d  d 7 }	q|r||j|jf t|}n||j|jf t|S )a_  Return a line segment between specified distances along a LineString

    Negative distance values are taken as measured in the reverse
    direction from the end of the geometry. Out-of-range index
    values are handled by clamping them to the valid range of values.

    If the start distance equals the end distance, a Point is returned.

    If the start distance is actually beyond the end distance, then the
    reversed substring is returned such that the start distance is
    at the first coordinate.

    Parameters
    ----------
    geom : LineString
        The geometry to get a substring of.
    start_dist : float
        The distance along `geom` of the start of the substring.
    end_dist : float
        The distance along `geom` of the end of the substring.
    normalized : bool, False
        Whether the distance parameters are interpreted as a
        fraction of the geometry's length.

    Returns
    -------
    Union[Point, LineString]
        The substring between `start_dist` and `end_dist` or a Point
        if they are at the same location.

    Raises
    ------
    TypeError
        If `geom` is not a LineString.

    Examples
    --------
    >>> from shapely.geometry import LineString
    >>> from shapely.ops import substring
    >>> ls = LineString((i, 0) for i in range(6))
    >>> ls.wkt
    'LINESTRING (0 0, 1 0, 2 0, 3 0, 4 0, 5 0)'
    >>> substring(ls, start_dist=1, end_dist=3).wkt
    'LINESTRING (1 0, 2 0, 3 0)'
    >>> substring(ls, start_dist=3, end_dist=1).wkt
    'LINESTRING (3 0, 2 0, 1 0)'
    >>> substring(ls, start_dist=1, end_dist=-3).wkt
    'LINESTRING (1 0, 2 0)'
    >>> substring(ls, start_dist=0.2, end_dist=-0.6, normalized=True).wkt
    'LINESTRING (1 0, 2 0)'

    Returning a `Point` when `start_dist` and `end_dist` are at the
    same location.

    >>> substring(ls, 2.5, -2.5).wkt
    'POINT (2.5 0)'
    z;Can only calculate a substring of LineString geometries. A z was provided.r   re   NrC   rz   )r$   r   r   r<   Zinterpolatelengthabsr   yrb   r>   rX   appendreversed)rO   Z
start_distZend_dist
normalizedZstart_pointZ	end_pointreverseZvertex_listr>   Zcurrent_distanceri   rj   r)   r)   r*   r!   .  sd    ;


.
0










4
r!   c                 C   s   | j r
| S t| ||||S )a]  Returns the portion of a geometry within a rectangle

    The geometry is clipped in a fast but possibly dirty way. The output is
    not guaranteed to be valid. No exceptions will be raised for topological
    errors.

    Parameters
    ----------
    geom : geometry
        The geometry to be clipped
    xmin : float
        Minimum x value of the rectangle
    ymin : float
        Minimum y value of the rectangle
    xmax : float
        Maximum x value of the rectangle
    ymax : float
        Maximum y value of the rectangle

    Notes
    -----
    Requires GEOS >= 3.5.0
    New in 1.7.
    )ra   r7   r    )rO   ZxminZyminZxmaxZymaxr)   r)   r*   r      s    r          ?c                    sB   t | tr(| tt fdd| jS t | tfr>t|  S | S )a  A properly oriented copy of the given geometry.

    The signed area of the result will have the given sign. A sign of
    1.0 means that the coordinates of the product's exterior rings will
    be oriented counter-clockwise.

    Parameters
    ----------
    geom : Geometry
        The original geometry. May be a Polygon, MultiPolygon, or
        GeometryCollection.
    sign : float, optional.
        The sign of the result's signed area.

    Returns
    -------
    Geometry

    c                    s
   t |  S r#   r   rU   signr)   r*   r     r3   zorient.<locals>.<lambda>)r$   r   	__class__rb   mapr,   r   orient_)rO   r   r)   r   r*   r     s    


r   )rK   F)NrK   F)F)r   ),__doc__warningsr   r7   Zshapely.algorithms.polylabelr   Zshapely.errorsr   r   Zshapely.geometryr   r   r   r	   r
   r   r   Zshapely.geometry.baser   r   Zshapely.geometry.polygonr   r   Zshapely.preparedr   __all__r"   r   r   r   r   r   r   r   r   r   r   r   r   r   rk   r   r!   r    r)   r)   r)   r*   <module>   s:   $	_

:K ;
