
    !\ia                        S r SSKJr  SSKrSSKrSSKrSSKrSSKrSSK	r	SSK	J
r
  SSKJr  SSKJrJrJrJr  SSKJr  SSKJrJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJrJ r   SSK!J"r"  \RF                  " \$5      r%\  SS j5       r&\SS\4S j5       r'\SS j5       r(\SSSSS\S\RR                  SSSSS4S j5       r*SS jr+      SS jr,S r-       SS jr.g) z8Functions for working with features in a raster dataset.    )	ExitStackN)warp)DatasetBase)_shapes_sieve
_rasterize_bounds)MergeAlg)
ensure_envGDALVersion)ShapeSkipWarning)DatasetWriter)coords)Affine)IDENTITYguard_transform)WindowFc           	      V    U(       a  SOSu  pV[        U UUUUUS9R                  S5      $ )a  Create a mask from shapes.

By default, mask is intended for use as a
numpy mask, where pixels that overlap shapes are False.

Parameters
----------
geometries : iterable over geometries (GeoJSON-like objects)
out_shape : tuple or list
    Shape of output :class:`numpy.ndarray`.
transform : Affine transformation object
    Transformation from pixel coordinates of `source` to the
    coordinate system of the input `shapes`. See the `transform`
    property of dataset objects.
all_touched : boolean, optional
    If True, all pixels touched by geometries will be burned in.  If
    False, only pixels whose center is within the polygon or that
    are selected by Bresenham's line algorithm will be burned in.
    False by default
invert: boolean, optional
    If True, mask will be True for pixels that overlap shapes.
    False by default.

Returns
-------
numpy.ndarray :
    Type is :class:`numpy.bool_`

Notes
-----
See rasterize() for performance notes.

)r      )r   r   )	out_shape	transformall_touchedfilldefault_valuebool)	rasterizeastype)
geometriesr   r   r   invertr   
mask_values          T/var/www/html/kml_chatgpt/mouzaenv/lib/python3.13/site-packages/rasterio/features.pygeometry_maskr"      s;    P "(vVD " #)&.1       c              #      #    [        U S5      (       a  Uc  U R                  ) nU R                  n [        U5      n[	        XX#5       Sh  vN   g N7f)a)  Get shapes and values of connected regions in a dataset or array.

Parameters
----------
source : numpy.ndarray, dataset object, Band, or tuple(dataset, bidx)
    Data type must be one of rasterio.int8, rasterio.int16, rasterio.int32,
    rasterio.uint8, rasterio.uint16, rasterio.float32, or rasterio.float64.
mask : numpy.ndarray or rasterio Band object, optional
    Must evaluate to bool (rasterio.bool_ or rasterio.uint8). Values
    of False or 0 will be excluded from feature generation.  Note
    well that this is the inverse sense from Numpy's, where a mask
    value of True indicates invalid data in an array. If `source` is
    a :class:`numpy.ma.MaskedArray` and `mask` is None, the source's mask will
    be inverted and used in place of `mask`.
connectivity : int, optional
    Use 4 or 8 pixel connectivity for grouping pixels into features
transform : Affine transformation, optional
    If not provided, feature coordinates will be generated based on
    pixel coordinates

Yields
-------
polygon, value
    A pair of (polygon, value) for each feature found in the image.
    Polygons are GeoJSON-like dicts and the values are the
    associated value from the image, in the data type of the image.
    Note: due to floating point precision issues, values returned
    from a floating point image may not exactly match the original
    values.

Notes
-----
The amount of memory used by this algorithm is proportional to the
number and complexity of polygons produced.  This algorithm is most
appropriate for simple thematic data.  Data with high pixel-to-pixel
variability, such as imagery, may produce one polygon per pixel and
consume large amounts of memory.

Because the low-level implementation uses either an int32 or float32
buffer, uint32 and float64 data cannot be operated on without
truncation issues.

maskN)hasattrr&   datar   r   )sourcer&   connectivityr   s       r!   shapesr+   N   sG     Z vv4<|	*Iv\===s   AA
AAc                     [        U [        5      (       a   [        R                  " X R                  5      n Uc+  [
        R                  " U R                  U R                  5      n[        XX#U5      $ )a)  Remove small polygon regions from a raster.

Polygons are found for each set of neighboring pixels of the same
value.

Parameters
----------
source : ndarray, dataset, or Band
    The source is a 2 or 3-D ndarray, a dataset opened in "r" mode,
    or a single or a multiple Rasterio Band object. Must be of type
    rasterio.int16, rasterio.int32, rasterio.uint8, rasterio.uint16,
    or rasterio.float32
size : int
    minimum polygon size (number of pixels) to retain.
out : numpy ndarray, optional
    Array of same shape and data type as `source` in which to store
    results.
mask : numpy ndarray or rasterio Band object, optional
    Values of False or 0 will be excluded from feature generation
    Must evaluate to bool (rasterio.bool_ or rasterio.uint8)
connectivity : int, optional
    Use 4 or 8 pixel connectivity for grouping pixels into features

Returns
-------
out : numpy.ndarray
    Result

Notes
-----
GDAL only supports values that can be cast to 32-bit integers for
this operation.

The amount of memory used by this algorithm is proportional to the
number and complexity of polygons found in the image.  This
algorithm is most appropriate for simple thematic data.  Data with
high pixel-to-pixel variability, such as imagery, may produce one
polygon per pixel and consume large amounts of memory.

)

isinstancer   rasteriobandindexesnpzerosshapedtyper   )r)   sizeoutr&   r*   s        r!   siever7      sP    T &+&&v~~6
{hhv||V\\2&<88r#   r   Tc                    Sn[         R                  " 5       R                  S5      (       a  US-  nUb  UR                  R                  n
O%U
b!  [
        R                  " U
5      R                  n
O U
b  X;  a  [        S5      e/ n/ n[        U 5       GH  u  nn[        U[        [        45      (       a  Uu  nnUc  UnOUnU	n[        USS5      =(       d    Un[        U5      (       a|  UR                  U5        US   nUS:X  a!  US	    H  nUR                  UU45        M     M  US
:X  a$  US    H  nUR                  SUS.U45        M     M  UR                  UU45        M  U(       a.  [        R                  " SR!                  UU5      ["        5        GM  [        S5      e   U
(       d  U(       a  [
        R$                  " U5      nUR                  R                  n
X;  a_  U
R'                  S5      (       aI  UR)                  5       UR+                  5       nnSU::  a	  US::  a  Sn
OSU::  a	  US::  a  Sn
O[        S5      e[-        5        nUb]  [        U[.        5      (       a  UnO[1        S#0 UD6nUb  UUS'   U
b  U
US'   [2        R4                  " US40 UD6nUR7                  U5        ORUb  ONUb@  [9        U5      S:w  a  [        S5      e[
        R:                  " XS9nUR=                  U5        O[        S5      e[)        UR>                  5      S:X  a  [        S5      e[A        U5      nU(       a  [C        XXgU5        [        U[
        RD                  5      (       aA  U(       a/  [G        US 5      (       d  [
        RH                  RK                  XSS!S"9nUsSSS5        $  SSS5        g! , (       d  f       g= f)$a  Return an image array with input geometries burned in.

Warnings will be raised for any invalid or empty geometries, and
an exception will be raised if there are no valid shapes
to rasterize.

Parameters
----------
shapes : iterable of (`geometry`, `value`) pairs or geometries
    The `geometry` can either be an object that implements the geo
    interface or GeoJSON-like object. If no `value` is provided
    the `default_value` will be used. If `value` is `None` the
    `fill` value will be used.
out_shape : tuple or list with 2 integers
    Shape of output :class:`numpy.ndarray`.
fill : int or float, optional
    Used as fill value for all areas not covered by input
    geometries.
nodata: float, optional
    nodata value to use in output file or masked array.
masked: bool, optional. Default: False.
    If True, return a masked array. Note: nodata is always set in
    the case of file output.
out : numpy.ndarray, optional
    Array in which to store results. If not provided, out_shape
    and dtype are required.
transform : Affine transformation object, optional
    Transformation from pixel coordinates of `source` to the
    coordinate system of the input `shapes`. See the `transform`
    property of dataset objects.
all_touched : boolean, optional
    If True, all pixels touched by geometries will be burned in.  If
    false, only pixels whose center is within the polygon or that
    are selected by Bresenham's line algorithm will be burned in.
merge_alg : MergeAlg, optional
    Merge algorithm to use. One of:
        MergeAlg.replace (default):
            the new value will overwrite the existing value.
        MergeAlg.add:
            the new value will be added to the existing raster.
default_value : int or float, optional
    Used as value for all geometries, if not provided in `shapes`.
dtype : rasterio or numpy.dtype, optional
    Used as data type for results, if `out` is not provided.
skip_invalid : bool, optional
    If True (default), invalid shapes will be skipped. If False,
    ValueError will be raised.
dst_path : str or PathLike, optional
    Path of output dataset
dst_kwds : dict, optional
    Dictionary of creation options and other parameters that will be
    overlaid on the profile of the output dataset.

Returns
-------
numpy.ndarray :
    If `out` was not None then `out` is returned, it will have been
    modified in-place. If `out` was None, this will be a new array.

Notes
-----
Valid data types for `fill`, `default_value`, `out`, `dtype` and
shape values are "int16", "int32", "uint8", "uint16", "uint32",
"float32", and "float64".

This function requires significant memory resources. The shapes
iterator will be materialized to a Python list and another C copy of
that list will be made. The `out` array will be copied and
additional temporary raster memory equal to 2x the smaller of `out`
data or GDAL's max cache size (controlled by GDAL_CACHEMAX, default
is 5% of the computer's physical memory) is required.

If GDAL max cache size is smaller than the output data, the array of
shapes will be iterated multiple times. Performance is thus a linear
function of buffer size. For maximum speed, ensure that
GDAL_CACHEMAX is larger than the size of `out` or `out_shape`.
)	int16int32int64uint8uint16uint32uint64float32float64z3.7)int8NzEData type specified by out array or dtype parameter is not supported.__geo_interface__typeGeometryCollectionr   MultiPolygoncoordinatesPolygon)rD   rG   z=Invalid or empty shape {} at index {} will not be rasterized.z,Invalid or empty shape cannot be rasterized.inti   ir:   r   l    r>   z2GDAL versions < 3.6 cannot rasterize int64 values.nodatar4   w   zInvalid out_shape, must be 2Dr4   z-Either an out_shape or image must be providedzwidth and height must be > 0r&   F)copy )&r   runtimeat_leastr4   namer1   
ValueError	enumerater-   tuplelistgetattris_valid_geomappendwarningswarnformatr   array
startswithminmaxr   r   dictr.   openenter_contextlenemptyr   r3   r   r   ndarrayr'   mamasked_equal)r+   r   r   rJ   maskedr6   r   r   	merge_algr   r4   skip_invaliddst_pathdst_kwdsvalid_dtypesvalid_shapesshape_valuesindexitemgeomvalue	geom_typepartpoly
values_arrlohi
exit_stackout_profiles                                r!   r   r      sz   |L %%e,,	! 				$$ 	U6S
 	
 LL (tdUDM**KD%}D!Et0$7?4&VI00 !.D ''u6 / n, /D '')D)QSX(YZ 0 ##T5M2 SZZe %	 !!OPPS )Z \XXl+
  %% $)9)9%)@)@^^%z~~'7Bb R:%5bR:-  !UVV	
(M22".X.%,2K)$+0K(mmHcA[A((-_"9~" !@AA((92CHHTN LMMsyy>Q;<<#I.	|))Lc2::&&gc622ee((5(AI 
B 'C 
s   EN//
N=c                     [        U SS5      =(       d    U n SU ;   a  [        U S   5      $ U R                  S5      =(       d    U nSU;   d  SU;   d  SU;   d  [        S5      e[	        X1US	9$ )
a>  Return a (left, bottom, right, top) bounding box.

From Fiona 1.4.8. Modified to return bbox from geometry if available.

Parameters
----------
geometry: GeoJSON-like feature (implements __geo_interface__),
          feature collection, or geometry.

Returns
-------
tuple
    Bounding box: (left, bottom, right, top)
rC   NbboxgeometryrG   r   featureszRgeometry must be a GeoJSON-like geometry, GeometryCollection, or FeatureCollection)north_upr   )rW   rU   getrS   r	   )r   r   r   rs   s       r!   boundsr     s|      x!4d;GxHXf%&&<<
#/xD T!\T%9Z4=O#
 	

 4i@@r#   c                 H   U Vs/ s H  n[        XR                  ) S9PM     n	nU	 V
VVVVs/ s H  u  ppX-
  X-   X-   X-
  4  H  nUPM     M      nnnnn
nU	 V
VVVVs/ s H  u  ppX-
  X-
  X-   X-   4  H  nUPM     M      nnnnn
n[        [        R                  " [        U5      5      5      [        [        R                  " [        U5      5      5      nn[        [        R                  " [        U5      5      5      [        [        R                  " [        U5      5      5      nn[        UU[        UU-
  S5      [        UU-
  S5      S9n[        SSU R                  U R                  5      nU(       d  UR                  U5      nU$ s  snf s  snnnnn
f s  snnnnn
f )a	  Calculate the window within the raster that fits the bounds of
the geometry plus optional padding.  The window is the outermost
pixel indices that contain the geometry (floor of offsets, ceiling
of width and height).

If shapes do not overlap raster, a WindowError is raised.

Parameters
----------
dataset : dataset object opened in 'r' mode
    Raster for which the mask will be created.
shapes : iterable over geometries.
    A geometry is a GeoJSON-like object or implements the geo
    interface.  Must be in same coordinate system as dataset.
pad_x : float
    Amount of padding (as fraction of raster's x pixel size) to add
    to left and right side of bounds.
pad_y : float
    Amount of padding (as fraction of raster's y pixel size) to add
    to top and bottom of bounds.
north_up : optional
    This parameter is ignored since version 1.2.1. A deprecation
    warning will be emitted in 1.3.0.
rotated : optional
    This parameter is ignored since version 1.2.1. A deprecation
    warning will be emitted in 1.3.0.
pixel_precision : int or float, optional
    Number of places of rounding precision or absolute precision for
    evaluating bounds of shapes.
boundless : bool, optional
    Whether to allow a boundless window or not.

Returns
-------
rasterio.windows.Window

)r   g        )col_offrow_offwidthheightr   )r   r   rI   mathfloorr_   ceilr`   r   r   r   intersection)datasetr+   pad_xpad_yr   rotatedpixel_precision	boundlessr3   
all_boundsleftbottomrighttopxcolsyrows	row_startrow_stop	col_startcol_stopwindowraster_windows                           r!   geometry_windowr     s   ` LRR6%&+<+<*<=6JR +5*4&T5,u}dlKA 	
K 	
*4 	  +5*4&T5+s{FNFNKA 	
K 	
*4 	  djjT34c$))CI:N6OxIdjjT34c$))CI:N6OxI(Y&,8i'-	F 1a?M$$]3M9 S
s   F%F %Fc                 T   1 Skn[        U SS5      =(       d    U n  U S   nX!R                  S15      ;  a  g X!;   Ga  SU ;  a  gU S   nUS:X  a  [	        U5      S	:  $ US
:X  a&  [	        U5      S:  =(       a    [	        US   5      S	:  $ US:X  a&  [	        U5      S	:  =(       a    [	        US   5      S	:  $ US:X  a&  [	        U5      S:  =(       a    [	        US   5      S	:  $ US:X  aA  [	        U5      S:  =(       a,    [	        US   5      S	:  =(       a    [	        US   S   5      S	:  $ US:X  aA  [	        U5      S:  =(       a,    [	        US   5      S:  =(       a    [	        US   S   5      S	:  $ US:X  a_  [	        U5      S:  =(       aJ    [	        US   5      S:  =(       a2    [	        US   S   5      S:  =(       a    [	        US   S   S   5      S	:  $ US:X  a8  SU ;  a  g[	        U S   5      S:  d  gU S    H  n[        U5      (       a  M    g   g! [        [        4 a     gf = f)a  
Checks to see if geometry is a valid GeoJSON geometry type or
GeometryCollection.  Geometry must be GeoJSON or implement the geo
interface.

Geometries must be non-empty, and have at least x, y coordinates.

Note: only the first coordinate is checked for validity.

Parameters
----------
geom: an object that implements the geo interface or GeoJSON-like object

Returns
-------
bool: True if object is a valid GeoJSON geometry type
>   PointrH   
LineString
LinearRing
MultiPointrF   MultiLineStringrC   NrD   rE   FrG   r   rL   r   r   r   r   r$   r   rH   rF   r   T)rW   unionKeyError	TypeErrorrd   rX   )rs   
geom_typesru   r   gs        r!   rX   rX      sb   &@J 4,d3;tDL	,,.B-CDD E $m$v;!##$v;?:s6!9~'::$ v;!#;F1I!(;;$ v;!#;F1I!(;;))K!O +F1I!(; +q	!%*, 	! K!O +F1I!(; +q	!%*, &K!O IF1I(: Iq	!%*I/26!9Q<?/Cq/HJ ((t#4%&* l#A ## $ q i  s   H H'&H'c           
   #   ~  #    Ub  XR                   :  a  [        S5      eSnSn	U R                  n
US:  a  [        [        R
                  " U R                  U-  5      5      [        [        R
                  " U R                  U-  5      5      4nU R                  US   -  nU R                  US   -  nU
[        R                  " U R                  U-  U R                  U-  5      -  n
U
[        R                  " X5      -  n
U(       a  U(       a  U(       d  U(       d  US:X  a  U R                  U5      n	OSWnUc&  [        R                  " U R                   4U-   S5      n	O[        R                  " US5      n	U R                  X5      n	Uc.  [        R                  R                  U	5      R!                  S5      n	U	nU(       ab  US:X  a  U R#                  USS9nOK[        R                  " WU R$                  U R&                  R)                  U5         S9nU R#                  XSS9nU(       a,  [        R*                  " US5      S	-  nSXS:H  '   UnU(       d  Un	S
U
0nU(       d  U	US'   [,        R.                  R1                  U R2                  5      n[5        [6        R8                  R:                  " U40 UD65       H  u  nu  nnU(       a"  [<        R>                  " U R@                  SUSUS9n[C        [E        U5      6 u  nnSU SU 3UUS.[G        U5      [G        U5      [I        U5      [I        U5      /US.v   M     g7f)aA  Yield GeoJSON features for the dataset

The geometries are polygons bounding contiguous regions of the same raster value.

Parameters
----------
src: Rasterio Dataset

bidx: int
    band index

sampling: int (DEFAULT: 1)
    Inverse of the sampling fraction; a value of 10 decimates

band: boolean (DEFAULT: True)
    extract features from a band (True) or a mask (False)

as_mask: boolean (DEFAULT: False)
    Interpret band as a mask and output only one class of valid data shapes?

with_nodata: boolean (DEFAULT: False)
    Include nodata regions?

geographic: str (DEFAULT: True)
    Output shapes in EPSG:4326? Otherwise use the native CRS.

precision: int (DEFAULT: -1)
    Decimal precision of coordinates. -1 for full float precision output

Yields
------
GeoJSON-like Feature dictionaries for shapes found in the given band
Nzbidx is out of range for rasterr   r   r<   F)ri   rM      r   r&   z	EPSG:4326T)antimeridian_cutting	precisionFeature:)valfilename)rD   id
propertiesr~   r   )%countrS   r   rI   r   r   r   r   r   translationscale
read_masksr1   r2   
logical_orreducer   readdtypesr0   rq   	ones_likeospathbasenamerR   rT   r.   r   r+   r   transform_geomcrszipr   r_   r`   )srcbidxsamplingr/   as_maskwith_nodata
geographicr   imgmskr   r3   
x_sampling
y_sampling	msk_shapetmpkwargssrc_basenameir   r   xsyss                          r!   dataset_featuresr   X  s    T D99,:;;
C
C I!|TYYszzH456TYYsyy83457 YYq)
ZZ%(*
 	V''II
"CJJ$;= 	=	 	V\\*99	
 Dq=..&CI|hhYYL9,g7 hhy'2..+C<--&&s+227;C  q=((4(.C((jj!2!24!89;C ((4U(3C ll3(3.1HC 9%Fv77##CHH-L !$$S3F358As##a%)Y@A fQiB!N!A3'"%<@Wc"gs2wB8
 	
5s   L;L=)FF)NNr$   )TN)r   r   NNNF)Nr   TFFT)/__doc__
contextlibr   loggingr   r   rZ   numpyr1   r.   r   rasterio._baser   rasterio._featuresr   r   r   r	   rasterio.enumsr
   rasterio.envr   r   rasterio.errorsr   rasterio.ior   rasterio.rio.helpersr   rasterio.transformr   r   r   rasterio.windowsr   	getLogger__name__logr"   r+   r7   replacer   r   r   rX   r   rO   r#   r!   <module>r      s+   >     	     & C C # 0 , % ' % 8 #! 
 /1 /1d 1 1> 1>h /9 /9d  	

V VrAH 
L^Ut B
r#   