
    &v0hy%                         d dl Zd dlZd dlZd dlZd dlZd dlZ	d dl
mZ d dlZd dlmZ d dlZd dlmZ d Zd Zd Zd ZdS )    N)mappingc                    	 t          j        | d          }d|j        vs	d|j        vrt          d          |                    d                                          }t          d|j                                         d|j        	                                            |d         S # t          $ r t          d|  d	           Y d
S t          $ r}t          d|            Y d
}~d
S d
}~ww xY w)zLoads annual productivity data.	)sepAnoProdutividadez0CSV must have 'Ano' and 'Produtividade' columns.z!Productivity data loaded. Years: -zError: Productivity file 'z' not found.Nz!Error loading productivity data: )pdread_csvcolumns
ValueError	set_index
sort_indexprintindexminmaxFileNotFoundError	Exception)filepathdf_prodes      O/home/jovyan/Desktop/enandes_v2/modelo_produtividade/functions_produtividade.pycarregar_produtividader      s   +hD111''?'/+Q+QOPPP##E**5577]'-2C2C2E2E]]HYHYH[H[]]^^^''   A8AAABBBtt   5!55666ttttts   B(B+ +C1	C1C,,C1c                 $   	 t          j        |           }t          |          dk    r#t          d           |                                }t          d|j                    |S # t          $ r }t          d|  d|            Y d}~dS d}~ww xY w)z Loads the Mato Grosso shapefile.   z>Warning: Shapefile has multiple features. Dissolving into one.z'Mato Grosso mask loaded. Original CRS: zError loading shapefile 'z': N)gpd	read_filelenr   dissolvecrsr   )shapefile_pathgdf_mtr   s      r   carregar_mascara_mtr$   +   s    
~..v;;??RSSS__&&FD
DDEEE   @.@@Q@@AAAttttts   A"A% %
B/B

Bc                 
   t           j                            |d|  d          }t           j                            |          st	          d|  d|            dS 	 t          |d          5 }t          j        |          }ddd           n# 1 swxY w Y   t          |          t          k    r-t	          d|  dt          |           d	t           d
           dS g }d}t          |          D ]\  }}		 t          |	t          j                  rt          |	d          r|	}
nt          |	t          j                  r6t	          d| d|  d           |                    t          j                   n	 t'          j        |	d          }
t	          d| d|  d           n_# t*          $ rR}t	          d| d|  dt-          |	           d|            |                    t          j                   Y d}~	d}~ww xY w|
j        j        7t	          d| d|  d           |                    t          j                   T||
j        j        }t	          d|            |j        |k    r/t	          d|j         d|            |                    |          }|
j                            |j                            t:                    |j        dd          }|                    ||
j        j        k                                               !                                }t          j"        |          r6t	          d| d|  d            |                    t          j                   n|                    |           # t*          $ rB}t	          d!| d|  d|            |                    t          j                   Y d}~d}~ww xY wt          |          t          k    r-t	          d"t           d#|  d$t          |           d
           dS t          j#        |          }t          j"        |          $                                rt          j%        |          }t          j"        |          sVt	          d%t          j"        |          &                                 d&|  d'|d(d)           ||t          j"        |          <   nt	          d*|  d+           dS |'                                S # tP          $ r t	          d|  d|            Y dS t*          $ r }t	          d,|  d|            Y d}~dS d}~ww xY w)-a  
    Loads NDVI data for a year from a pickle file, masks it using the MT geometry,
    and calculates the mean NDVI for each of the 23 observations.

    **ASSUMES**:
    - Pickle file named 'ndvi_{ano}.pkl' exists in 'pasta_ndvi'.
    - Pickle contains a list/iterable of 23 items.
    - Each item is loadable by rioxarray (e.g., xarray.DataArray with spatial info)
      OR is a NumPy array that can be georeferenced (requires more complex handling).
    ndvi_z.tifz&Warning: NDVI file not found for year z: NrbzWarning: Year z has z NDVI observations, expected .riozError: NDVI item z	 in year z1 is NumPy array - requires manual georeferencing.T)maskedzInfo: Opened NDVI item z
 for year z using rioxarray directly.z"Error: Cannot interpret NDVI item z with rioxarray. Type: z. Details: zWarning: NDVI item z has no CRS defined. Skipping.z&Determined target CRS from NDVI data: zReprojecting mask from z to F)dropinvertz2Warning: Mean NDVI is NaN after clipping for item z, year z. Possibly no overlapping data.zError processing NDVI item zError: Could not process all z NDVI items for year z. Got zWarning: Filling z NaN NDVI values in year z with yearly mean (z.4f)z!Error: Cannot fill NaNs for year z as yearly mean is also NaN.z&Error processing pickle file for year ))ospathjoinexistsr   openpickleloadr   NDVI_POR_ANO	enumerate
isinstancexa	DataArrayhasattrnpndarrayappendnan	rioxarrayopen_rasterior   typer)   r!   to_crsclipgeometryapplyr   wherenodatameanitemisnanarrayanynanmeansumtolistr   )ano
pasta_ndvigdf_mt_maskr   fndvi_data_anualmean_ndvi_values
target_crsi	ndvi_itemrdsrio_exclipped_rdsmean_valitem_emean_ndvi_values_arr
valid_meanr   s                     r   processar_ndvi_anualr`   9   s|    w||J(9(9(9(9::H7>>(## HsHHhHHIIIth(D!! 	-Q$k!nnO	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- <//o3ooS-A-Aoo`loooppp 4
%o66 A	0 A	0LAy@0 i66 !79e;T;T !"33	2:66 ! oQoooooppp#**262222
! (5iMMMdddSdddeeee$ ! ! !  Q1  Q  QPS  Q  Qlpqzl{l{  Q  Q  IO  Q  Q  R  R  R(//777 ! 7;&```S```aaa$++BF333%!$JO:OOPPP ?j00UKOUUUUVVV"-"4"4Z"@"@K "gll;+?+E+Eg+N+NP[P_fjsxlyy
 ',,[CGN-JKKPPRRWWYY8H%% 6~PQ~~Z]~~~%,,RV4444$++H555 0 0 0PAPPPPPPQQQ ''////////0
   L00y<yyVYyyadeuavavyyyzzzD  "x(8998())--// 	$899J8J''   S"(3G*H*H*L*L*N*N  S  Sil  S  S  BL  S  S  S  S  T  T  TGQ$RX.B%C%CDD[#[[[\\\t#**,,,   HsHHhHHIIItt   AsAAaAABBBttttts   S; ,BS; BS; BAS; S; 7A=N5,F"!N"
G>,AG93N7S; 9G>>ANS; E NS; 
O7OS; OAS; CS; 'S; ;U	U&UUc                    g }t          |                     |          d          5 }t          j        |          }d d d            n# 1 swxY w Y   t          |                    |          d          5 }t          j        |          }d d d            n# 1 swxY w Y   t	          dd          D ]N}	||	         }
||	         }t          j        |
|fd          }|                    |           t          |	           Ot          j	        |          }t          t          j        |d                    |                    d          5 }t          j        ||           d d d            n# 1 swxY w Y   t          d          S )	Nr'   r      r   )axiszfiltered_{}.pklwbconcatenated)r2   formatr3   r4   ranger;   concatenater=   r   stackospr0   dump)data_p1data_p2directory_pathyearcombined_dff1data_1f2data_2rW   data_1_imagedata_2_imageresultresult_finalrS   s                  r   concatenate_pkl_areary      s   K	gnnT""D	)	) !RR! ! ! ! ! ! ! ! ! ! ! ! ! ! !	gnnT""D	)	) !RR! ! ! ! ! ! ! ! ! ! ! ! ! ! ! 1R[[  ayay| <1EEE6"""a8K((L	ch~'8'?'?'E'EFF	M	M %QRL!$$$% % % % % % % % % % % % % % %    s5   AAA5BBB
E,,E03E0)pandasr
   numpyr;   r3   	geopandasr   r?   xarrayr8   shapely.geometryr   r.   os.pathr/   rj   mathmatplotlib.pyplotpyplotpltr   r$   r`   ry        r   <module>r      s                         $ $ $ $ $ $ 				                   x x xt! ! ! ! !r   