
    7fV                        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 dlmZ d dlmZ d dlZd dlmZ d dlZd dl d dl d dlmZmZmZmZma d dlZ	 d Z"d	 Z#d
 Z$ddZ%ddZ&ddZ'ddZ(ddZ)d Z*d Z+ddZ,y)    N)datetime)relativedelta)Line2D)interp2d)*)JSON_DOWNLOAD_URLJSON_VOLCANO
START_DATEEND_DATEELNINOSc                    | j                   }| j                   dz   t        z   }g }| j                  rt               }nd }| j                  rt        ||       | j                  rt        |       | j                  r\t        | j                  | j                  | j                        }|rt        ||| j                         nt        ||| j                         | j                   rpg }|g k(  r+t        | j                  | j                  | j                        }t#        |      | j$                  k  rd}t'        |      | j(                  rW| j*                  rKt-        | j(                  | j*                        \  | _        | _        d| j(                   d| j*                   }n| j.                  rt1        || j.                  d         \  }}}	t-        |d   |d         \  | _        | _        | j                   dk(  r| j(                  d   | j*                  d   g}
t3        | j(                        dz
  t5        | j(                        dz   g| _        t3        | j*                        dz
  t5        | j*                        dz   g| _        | j.                  d    d	| j(                   d| j*                   }nd
}t'        |      | j.                  r| j.                  d   }n3| j(                  r'| j*                  r| j(                   d| j*                   }t7        | j                  t8              s%t9        | j                        j;                  dd      n| j                  j;                  dd      }t7        | j                  t8              s%t9        | j                        j;                  dd      n| j                  j;                  dd      }| j<                   d d| d| d| j                    d
}| j                   dk(  rd}nd}| j                  r8|j?                         r|j?                         jA                         s
t               }tC        | j(                  | j*                  |||      }| j                   dk(  s| j                   dk(  s|dk(  rt9        | j$                        dz   }nK| j                   dk(  r,| jD                  rdt#        |       d}n dt#        |       d}nd| j                    d}||dd}| j                  dv s| jD                  r!tG        || j                  | jD                        }| j                   dk(  r&| jH                  rtK        || jH                        }tM        || j*                  | j(                  || jN                  | jP                  || jR                         | j.                  rGtU        jV                  
d   |
d   ddd | j.                  d   d!"       tU        jX                  d#dd$%       tU        jZ                         }tU        j\                         }| j^                  rtU        j`                  |       | jb                  rtU        jd                          ||fS tg        || j$                        }ti        | jj                        tm        | jj                        }| jn                  r1t7        | jn                  t              st        | jn                        n|}|g k7  rXtq        ||d&         }|D ci c]  }|| }}|d&   js                  |      |d'<   |jt                  jw                  tx              |d'<   | jj                  dkD  rJt{        | jj                        D cg c]+  }t}        j~                  |   |t9        |dz         z   (      - }}ng }|d)   j                  d*+      | jj                  z  t#        |      z  j                  t              j                  | jj                  dz
  ,      |d-<   |d-   js                  fd.      |d-<   t        |      }| j                   d/k(  rt        |||      \  }}nAd }|r$|j                  d)0      }|j                  d1      }t        ||| j                  ||      }| j                  r|st        |||      }| jn                  s|g k7  rt        ||||      }tU        jX                  |d2d#3       tU        j                          tU        jZ                         }tU        j\                         }| j^                  r!t        d4|       tU        j`                  |       | jb                  rtU        jd                          ||fS y5c c}w c c}w )6N/z;Error: The number of dates is less than the rolling window.z
Latitude: z, Longitude: r      map   z - Latitude: zfError: Please provide valid coordinates or volcano name.
 Try using --list to get a list of volcanoes._- z.pngstrengthTFdailybarz day precipitation (mm)zCumulative precipitation over z
 days (mm)zDaily precipitation over z days (mm/day) z precipitation (mm)zCumulative precipitation)titleylabely2label)WMYred^2      )colormarkerslabelzordersmallg333333?)fontsizeframeon
framealphaDate	Eruptionsr#   r&   rollfirst)method)upperr#   c                     |    S N )xcolorss    Q/home/exouser/operations/rsmas_insar/tools/Precip/src/precip/plotter_functions.py<lambda>z!prompt_subplots.<locals>.<lambda>   s    fQi     annualbydropz
upper left)handleslocr)   zSaving:)NN)Odirr	   use_sshconnect_jetstreamcheckcheck_nc4_fileslistvolcanoes_listdownloadgenerate_date_list
start_dateend_dateaveragedownload_jetstream_parallelparalleldload_site_list_parallelstylelenr/   
ValueErrorlatitude	longitudeadapt_coordinatesvolcano_nameextract_volcanoes_infominmax
isinstancestrreplaceoutdirget_transport	is_activesql_extract_precipitationcumulate#weekly_monthly_yearly_precipitationinterpolateinterpolate_mapmap_precipitationcolorbarisolinesvlimpltscatterlegendgcfgca	save_flagsavefig	show_flagshowvolcano_rain_framecolor_schemebinsquantile_name	add_eventadapt_eventsr   r-   applydate_to_decimal_yearrangempatchesPatchrankastypeintclipfrom_nested_to_floatannual_plottersort_valuesreset_indexbar_plotterlogelninoplot_elninosplot_eruptionstight_layoutprint)inpsgpm_dirvolcano_json_dir	date_listssheruption_datesmsgr   laloidvolcano_positionsaveNamestrStartstrEnd	save_pathr   precipitationr   labelsfigaxesquantiledateeruption_dictilegend_handlesaxsr7   s                              @r8   prompt_subplotsr      s3   hhGxx#~4I||! zz%yy'(}}&tt||T	'	3F %WiGzz?*4??DMM4<<XI y>TYY&OCS/!==T^^,=dmmT^^,\)DM4> }T^^<LME'=>NPTPaPabcPd'e$ND",=d1gtAw,O)DM4>zzU"$(MM!$4dnnQ6G#H !$T]]!3a!7T]]9Ka9O P"%dnn"5"93t~~;NQR;R!S ((+,M$--VZVdVdUefE |CS/! ,,Q/]]t~~--$..)9:H@J4??\_@`3t'//R8fjfufuf}f}  B  DF  gG<Ft}}VY<ZT]]#++C4`d`m`m`u`uvy{}`~{{m1XJaz6(!DJJ<tT	::#H H<<!2!2!49J9J9L9V9V9X#%C 2$--QZ\cehi:: DJJ%$78t;K^&??FZZ5 }}9#i.9IT 5S^4DNS $78F ! 57
 <<?*dmm?t||]a]j]jkM :: /t?O?O PmT^^T]]IW[WdWdfjfsfsu{  ~B  ~G  ~G  H  ,Q/1A!1DEZ]ackok|k|}~k  IJ  K

GTcJ'')C779D~~I&~~
9 +=$))Ddii( +
 >>9CDNNTX9YT$..1_mNR *.-:OPN 5CCDT4ZCMC *7v)>)B)B=)QM+& *7)@)@)F)FG[)\M+& 99q=bghlhqhqbrs]^hnn6!9HsSTUVSVxDWXsNs  N $1#8#=#=W#=#MPTPYPY#Y]`an]o"o!w!wx{!|  "B  "B  IM  IR  IR  ST  IT  "B  "Ug "/w!7!;!;<O!Pg -];::!"0PV"WNC C  - 9 9V 9 D - 9 9t 9 D )$((FTbcN;;x)-MN>>^r1+M>8UXYN

>|gNggiwwy>>I&;;y!>>HHJDyG D ts   -
e0ec                    	 t        j                  |      }|j                          |j                         }|S # t         j                  j
                  $ rq}t        d|       t        d       t        j                  j                  |       st        | t               t        |       }t        j                  |      }Y d }~|S d }~ww xY w)NzError: zLoading from local file)requestsgetraise_for_statusjson
exceptionsRequestExceptionr   ospathexistsdownload_volcano_jsonr   openload)jsonfileurlresponsedataerrfs         r8   get_volcano_jsonr      s    <<$!!#}} K // y'(ww~~h'!(,=>Nyy|Ks   59 CA&CCc                     t        | t              }g }|d   D ]$  }|d   d   |vs|j                  |d   d          & |D ]  }t        |        |S )z
    Retrieves a list of volcano names from a JSON file.

    Args:
        jsonfile (str): The path to the JSON file containing volcano data.

    Returns:
        None
    features
propertiesVolcanoName)r   r   appendr   )r   r   volcanoNamejvolcanos        r8   rH   rH     sr     H&78DK* ?\?=)<q}=>?  g r:   c           
         g d}t        | t              }g }g }t        j                  t        d      j                         }t        j                  t        d      j                         }|d   D ]  }	|	d   d   |k(  s|	d   d   }
|	d   d   }t        j                  |	d   d   d      j                         }|	d   d	   }|d
d
d   }	 t        j                  |	d   d   d      j                         }t        | d|
 d| d|        ||k\  r||k  r|j                  |       |s|	d   d   }|j                  ||||g        |rt        j                  ||      }|S |g k7  r?t        |      }t        d       t        d       t        d       |D ]  }t        d|        t        d       t        d       |
fS #  d}Y xY w)am  
    Extracts information about a specific volcano from a JSON file.

    Args:
        jsonfile (str): The path to the JSON file containing volcano data.
        volcanoName (str): The name of the volcano to extract information for.

    Returns:
        tuple: A tuple containing the start dates of eruptions, a date list, and the coordinates of the volcano.
    )VolcanoStartEndzMax Explosivityz%Y%m%dr   r   r   VolcanoNumber	StartDategeometrycoordinatesNEndDateNonez, id: z eruption started z and ended ExplosivityIndexMax)columnsz!---------------------------------zSorting eruptions by date...zExtracted eruption in date: r   )r   r   r   strptimer
   r   r   r   r   pd	DataFramesorted)r   r   r   column_namesr   start_dates
frame_data	first_daylast_dayr   r   namestartr   endstrendfds                     r8   rX   rX     s    BLH&78DKJ!!*h7<<>I  8499;H * =\?=)[8<1BlOM2D%%q{'ChOTTVEJ-6K%dd+K''<)ChOTTV
 TF&$6ug[NO 	!ex&7""5),(=>!!4U";<-=0 \\*l;	 b[)12,-12 	5A0!4	5 

-.	"IR''Ms   *F??Gc           
         |rv| d   D cg c]  }|dz  	 }}| d   D cg c]
  }|dz  dz    }}dt        | d   j                               z  }|j                  ||dd|d	      }|j                  |       |S |r!| | d   j	                            j
                  }	n| | d   j	                            d   }	|	D ]  }t        j                  |dd
dd        |t        dgdgdd
ddd      gz  }|S c c}w c c}w )Nr-   r         ?xW r,   blackvzVolcanic Events)r#   r$   r%   r&   dashed)	      )r6   r#   	linestyledashes	linewidthr   )r"   r   zVolcanic event)r#   r   r   r&   r   )	rR   uniquerk   r   notnaindexrj   axvliner   )
r   r   r   r   r   r6   yscatter_sizeeruption	eruptionss
             r8   r   r   i  s.   
)+67qQU77$1+$>?qa1f]??]6%:%A%A%C!DD;;q!73,Vg;hh'!-"<"B"B"DEKK	 "-"<"B"B"DEkR	 Waw(5TUVW vqcA3gSX`p}~  A  AN' 8?s
   C0C5c                    	 | j                  d      d   d   }t        j                  |j                  d         }t        j                  |j                  d         }t	        |||      }t        j
                  |j                         |j                         |j                  d   |z        }t        j
                  |j                         |j                         |j                  d   |z        } |||      }|S #  | d   }Y xY w)aO  
    Interpolates a precipitation map using scipy.interpolate.interp2d.

    Parameters:
    dataframe (pandas.DataFrame): The input dataframe containing the precipitation data.
    resolution (int): The resolution factor for the interpolated map. Default is 5.

    Returns:
    numpy.ndarray: The interpolated precipitation map.
    Precipitationr   r   )r   nparangeshaper   linspacerY   rZ   )		dataframe
resolutionvaluesr6   r   interpolatornew_xnew_y
new_valuess	            r8   re   re     s    /215
 			&,,q/"A
		&,,q/"AAq&)L KK&,,q/**DEEKK&,,q/**DEE eU+J1s   C; ;Dc                 ,   t         j                  j                  d|       }t        |t              st	        |d         }|j
                  }d||dk  <   ||d d  t        j                  ||d| d      }|dk7  rt        j                  ||d       t        S )	N01m)r   regionr   whiter   )levelsr7   extent
linewidths   )inliner)   )	pygmtdatasetsload_earth_reliefr[   r   r   rj   contourclabel)r   r  r  gridgrid_npconts         r8   add_isolinesr    s    >>++uV+LDfc"VAY kkG GGaK DG ;;tF76VYZDz

43Jr:   c                    g d}t        |       t        j                  k(  r| j                  d      d   d   }	n,t        |       t        k(  r| |d   j                  d         }	n| }	t        j                  |	j                         d      }	|sd}
|	j                         }n
|d   }
|d   }|d   |d   |d   |d   g}|st        |      }nt        ||d      } |j                  |	|
|||	        |j                  |d   |d           |j                  |d   |d           |j                         }|j                  |d
           |j                   |d          y)aj  
    Plot a map of precipitation.

    Args:
        precipitation_series (pd.DataFrame or dict or ndarray): The precipitation data.
            If a DataFrame, it should have a column named 'Precipitation' containing the precipitation values.
            If a dict, it should have keys representing dates in the format 'YYYY-MM-DD' and values as precipitation arrays.
            If an ndarray, it should be a 2D array of precipitation values.
        lo (list): The longitude range [lo_min, lo_max].
        la (list): The latitude range [la_min, la_max].
        date (list): The list of dates for which precipitation is plotted.
        colorbar (str): The colormap for the plot.
        levels (list): The contour levels for the isolines.
        vlim (tuple, optional): The minimum and maximum values for the colorbar. Defaults to None.

    Returns:
        None
    )            im  r   r   z%Y-%m-%d)axisr   T)r  )vminvmaxr  cmapr   r   N)typer   r   r   dictstrftimer   flip	transposerZ   r  imshowylimxlimrg   	set_labelr   )precipitation_serieslolar   rg   r  r   ri   m_yprecipr  r  r   rj   cbars                  r8   rf   rf     sZ   (  C !R\\1%))/:1=a@	"	#t	+%d1g&6&6z&BC &WWV%%'a0Fzz| AwAweRUBqE2a5)F 6" 66$7CJJvDtFJCHHRUBqECHHRUBqE 3<<>D 	NN6(#$CIIfWor:   c                 |   t        j                  d       |r;| j                  d      } | j                  d      } d}t	        t        |             }nd}| d	   }| d   }t        j                  |d
          |dk(  r,t        j                  d       t        j                  g d       |st        j                  d       t        j                  |d          t        | d   j                         dz  dz        }t        j                  ||| d   |d       |dk(  rt        | d	   j                         dz        }	t        | d	   j                         dz  dz         }
t        j                  t	        |
|	z
  dz  dz         D cg c]
  }|	d|z  z    c}t	        |
|	z
  dz  dz         D cg c]  }dt!        |	d|z  z         dd  z    c}       t        j"                         }|j                  | d	   | d   d|d       |j%                  ddd       |t'        j(                  d|d          gz  }|S c c}w c c}w )!N)
      )figsizer/   r<   Tr>   g?g{Gz?Decimalr   r   )g?r   r)  d   i  Yearr         ?r   r#   )r#   widthalphaFr   ')ticksr   cumsumgrayg?zCumulative precipitation (mm)i  r)  )rotationlabelpadr   r.   )rj   subplotsr   r   r{   rR   r   yscaleyticksxlabelr   r   rZ   r   rY   xticksr\   twinx
set_ylabelr|   r}   )r   r   r   r   r   r0  r6   r   r4  r   r   r   plot2s                r8   r   r     sZ   LL!%11V1<%11t1<#m$% )$fA JJvh 
d{

5

*+

6IIfWov&**,s2q89EGGAqg.e1E5M),002a78-	*..0A59:

u8Ja7O1PQA%1Q3-Q  CH  KN  QV  KV  [\  J\  `a  Ia  Cb  [c}~[^adejnopqnqerastvtwax[x  [c  	d				-	*M(,CF\akn	o83RTU8>>fY>OPQQ  R  [cs   H4*H9
c                    | d   j                         }| d   j                         }t        |dz        }t        |dz  dz         }t        j                  dddddgid      \  }}|d   }	|d   }
	 | d   dz  }| d   dz  }|	j                  ||| d   d	d
t        | d   j#                               z         g }t        ||dz         D ]0  }|j%                  | d   | d   dz  |k(     j'                                2 |
j)                  t        ||dz         |dd       |	j+                  t        |dz   |z
  dz        D cg c]
  }|d|z  z    c}t        |dz   |z
  dz        D cg c]  }t-        |d|z  z          c}       |	j/                  t        d      D cg c]
  }dd|z  z    c}g d       |	j1                  d       |	j3                  d       |	j5                  |d          |
j5                  d       |
j+                  t        |dz   |z
  dz        D cg c]
  }|d|z  z    c}t        |dz   |z
  dz        D cg c]  }t-        |d|z  z          c}       ||d   fS c c}w c c}w c c}w c c}w c c}w )Nr,  r   r   width_ratios   )      )gridspec_kwr+  r   r%   r   r,   )r#   r$   r%   r#   r   r   purple)heightr#      gUUUUUU?gUUUUUU?)010203040506070809101112Monthr.  r   z
Total (mm))rY   rZ   r   rj   r9  r{   color_count	by_season	volc_raincopyr   r   arrayrR   rk   r7   rainfallr   r   sumbarh
set_yticksr\   
set_xticks
set_xlabelr?  	set_title)r   r   r   
first_date	last_dater   r   r   r   ax0ax1r   r   rain_by_yearrain_jdates_jbin_sizer6   r   totalsyearks                         r8   r   r   +  s    y)--/Ji(,,.I
a E
i1nq 
!CQA/GQYZIC
q'C
q'C  	i 1$Ai A%AKK1M'236SQ^_eQfQmQmQoMpCpKr FeSU# cmO4]95MQR5RVZ5Z[__abc HHU5#a% &8HD
 NN537U?q2H+JKaEQqSMKjoruxyry  }B  sB  GH  rH  kJ  NKefcRW[\]^[^R_N`  NK  LNNuRy9!TT1H_9  <D  ENN7NN6MM&/"MM,NN537U?q2H+JKaEQqSMKjoruxyry  }B  sB  GH  rH  kJ  NKefcRW[\]^[^R_N`  NK  L47"" L  NK9
 L  NKs   >I*%I/
I4I9I>
c           	         t         j                  j                  } |d      dg |d      dgd}| d   j                         }t	        | d   j                         dz  d	z        }d
t        | d   j                               z  }dD ]E  }t        |   D ]5  \  }	}
|	|kD  rt        |
|      }
|rt        |	d	      \  }}	t        |
d	      \  }}
||k(  r'|j                  |	|
g|dz
  |dz
  g||   d   d|       nw|j                  |	dg|dz
  |dz
  g||   d   d|       |j                  d|
g|dz
  |dz
  g||   d   d|       n*t        j                  |	|
g|dz
  |dz
  g||   d   dd       ||   d	   |D cg c]  }|j                          c}vs|j                  t        j                  ||   d   ||   d	                8 H |S c c}w )N   u   Strong El Niñor"   u   Strong La Niña)zstrong ninozstrong ninar,  r5  r/  r   iU  r,   g(\?r   g      ?)r#   r1  r   g 	?g/nbg      ?r   r.   )rj   cmbwrrZ   r   rR   r   r   rY   divmodplot	get_labelr   r|   r}   )r   r   r   r  r7   r   r4  r   r   x1x2y1y2r   s                 r8   r   r   a  s    66::D"3i):;TRSWVgLhiF
	
"
&
&
(Cx(,,.4:;E]6299;<<I+ ^aj 	^FBCxRBABAB8HHb"XS"s(';6!9Q<WZfoHpHHb&\BHb3h+?vayQR|[^jsHtHHfb\BHb3h+?vayQR|[^jsHt"bEDL%$,#?vayQR|[^jklay|>#JaAKKM#JJ%%hnn6!9Q<vVWyYZ|&\]'	^^,  $Ks   :G
)F)FN)r*  )r   Fr4   )-r   r   r   sysdateutil.relativedeltar   pandasr   matplotlib.pyplotpyplotrj   matplotlib.patchespatchesr|   matplotlib.linesr   numpyr   scipy.interpolater   r  precip.helper_functionsprecip.download_functionsprecip.configr   r	   r
   r   r   r   r   reqr   textr   r   rH   rX   r   re   r  rf   r   r   r   r5   r:   r8   <module>r     s|    	   
 0   % #  &  % ' X X  	Up(0G(T0B0<~/d3#l r:   