
    ը	f                     t   d Z ddlZddlZddlmZ ddlZddlZddlm	Z	 ddl
mZ ddlmZ 	 ddlZ ej                   d       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#m$Z$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/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 	 ddl7m8c m9c m:Z; ddl=m8c m>Z? ddl'm@Z@ ddlAmBZBmCZCmDZDmEZE dZFg dZGdZHd ZId ZJ G d dej                        ZL G d d      ZMd ZN G d d eO      ZPy# e$ r"Z e ed	      j=                  e            dZ[ww xY w# e$ r ddl<m8c m:Z; Y w xY w)!ab  
@package frame

@brief Temporal Plot Tool

Classes:
 - frame::DataCursor
 - frame::TplotFrame
 - frame::LookUp

(C) 2012-2016 by the GRASS Development Team

This program is free software under the GNU General Public License
(>=v2). Read the file COPYING that comes with GRASS for details.

@author Luca Delucchi
@author start stvds support Matej Krejci
    N)cycle)Module)reduceWXAgg)Figure)FigureCanvasWxAggNavigationToolbar2WxAggz^The Temporal Plot Tool needs the "matplotlib" (python-matplotlib) package to be installed. {0})GMessageGError
GException
RunCommand)CoordinatesValidator)gselect)	globalvar)Point)	RasterRow)Region)OrderedDict)PIPE)	GNotebook)CheckBoxTextCtrlButton
StaticTextg      ?)bgrcmyk)gQ?g        g      ?c                      g }t         j                  j                  d      D ]  }	 t        |      }|j	                  |       ! |t        |       k  ryy# t
        $ r |j	                  d       Y Nw xY w)z-Checks if given version or newer is installed.r   FT)
matplotlib__version__splitintappend
ValueErrorlist)versionversionInstalledivs       ,/usr/lib/grass83/gui/wxpython/tplot/frame.pycheck_versionr0   N   sw    ##))#. '	'AA##A&' $w-'  	'##A&	's   AA10A1c                     	 | j                  |      t        |      z   }| j                  ||      }| || S # t        $ r Y yw xY w)N )rindexlenr)   )sfirstlaststartends        r/   findBetweenr:   ]   sK    #e*,hhtU#s| s   36 	AAc                       e Zd ZdZ ed      fdZd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd ZddZd Zd Zd Zd ZddZd Zd Zd Zd Zd Zy)
TplotFramez!The main frame of the applicationzTemporal Plot Toolc                    t         j                  j                  | |t         j                  |       t	        j
                  d       || _        d | _        d | _        d| _	        | j                          | j                          t	        j                         | _        | j                  j                          | j                  t         j                  | j                          t#               | _        y )N)idtitleTF)wxFrame__init__ID_ANYtgisinit_giface	datasetsV	datasetsR	overwrite_layoutSQLDatabaseInterfaceConnectiondbifconnectBind	EVT_CLOSEonCloser   region)selfparentgifacer?   s       r/   rB   zTplotFrame.__init__i   s    
$299EB		$ 			 779					",,-h    c                     t               | _        t               | _        d | _        d | _        g | _        g | _        g | _        d | _        d | _	        y N)
r   	timeDataR	timeDataVtemporalTypeunitlistWhereConditionsplotNameListRplotNameListVpoicsvpathrR   s    r/   rE   zTplotFrame.init|   sI    $$ 	#% rU   c                     | j                   j                  du r| j                   j                          t        j                          y)zbClose the database interface and stop the messenger and C-interface
        subprocesses.
        TN)rL   	connectedcloserD   stop_subprocessesra   s    r/   __del__zTplotFrame.__del__   s0     99$&IIOO rU   c                     | j                   j                         r4| j                  j                          | j                  j                          | j                          | j                          y rW   )rF   GetMapDisplaycoorvalOnClosecatsrf   Destroy)rR   evts     r/   rP   zTplotFrame.onClose   sD    <<%%'LL  "IIrU   c           
      6#   t        j                  |       | _        t        dd      | _        t        | j                  t         j                  | j                        | _        d| _        t        | j                        | _
        t        j                  t         j                        | _        | j                  j                  | j                  dt         j                  t         j                   z  t         j"                  z         | j                  j                  | j                  dt         j"                         t%        | j                  t&        j(                        | _        t        j                  | j*                  t         j                        | _        t/        | j,                  t         j                  t1        d	      
      | _        t5        j6                  | j,                  t         j                  t8        j:                  dd      | _        t/        | j,                  t         j                  t1        d      
      | _        	 | j@                  jC                          t5        jD                  | j,                  | j@                        | _#        | jF                  jO                  t1        d             tQ        | j,                  t         j                  t1        d      
      | _)        t        j                  t         j                        | _*        | jT                  j                  | j2                  t         j"                         | jT                  j                  | j<                  t         j"                         | jT                  j                  | j>                  t         j"                         | jT                  j                  | jF                  t         j"                         | jT                  j                  | jR                  t         j"                         | j,                  jW                  | jT                         | jT                  jY                  |        | j*                  j[                  | j,                  t1        d      d       t        j                  | j*                  t         j                        | _.        t/        | j\                  t         j                  t1        d      
      | _/        t5        j6                  | j\                  t         j                  t8        j:                  dd      | _0        | j`                  jc                  t         jd                  | jf                         t5        jh                  | j\                        | _5        t/        | j\                  t         j                  t1        d      
      | _6        	 | j@                  jC                          t5        jn                  | j\                  | j@                        | _8        t/        | j\                  t         j                  t1        d      
      | _9        tQ        | j\                  t         j                  t1        d      
      | _:        t        j                  t         j                        | _;        | jv                  j                  | j^                  t         j"                         | jv                  j                  | j`                  t         j"                         | jv                  j                  | jl                  t         j"                         | jv                  j                  | jj                  t         j"                         | jv                  j                  | jr                  t         j"                         | jv                  j                  | jp                  t         j"                         | jv                  j                  | jt                  t         j"                         | j\                  jW                  | jv                         | jv                  jY                  |        | j*                  j[                  | j\                  t1        d      d       t        j                  | j*                  t         j                        | _<        t/        | jx                  t         j                  t1        d      
      | _=        tI        | jx                  t         j                  t8        jJ                        | _>        t/        | jx                  t         j                  t1        d      
      | _?        tI        | jx                  t         j                  t8        jJ                        | _@        t/        | jx                  t         j                  t1        d      
      | _A        tI        | jx                  t         j                  t8        jJ                        | _B        t        j                  t         j                        | _C        | j                  j                  | jz                  t         j"                         | j                  j                  | j|                  t         j"                         | j                  j                  | j~                  t         j"                         | j                  j                  | j                  t         j"                         | j                  j                  | j                  t         j"                         | j                  j                  | j                  t         j"                         | jx                  jW                  | j                         | j                  jY                  |        | j*                  j[                  | jx                  t1        d       d        t        j                  | j*                  t         j                        | _D        t/        | j                  t         j                  t1        d!      
      | _E        t        j                  | j                  t         j                  t8        j:                  d"t1        d#      t1        d$      t        j                         t         j                  %      | _K        t/        | j                  t         j                  t1        d&      
      | _L        t        jP                  | j                  t         j                        | _M        t        j                  t         j                        | _O        | j                  j                  | j                         | j                  j                  | j                         t        j                  t         j                        | _P        | j                  j                  | j                         | j                  j                  | j                         | j                  j                  | j                         | j                  jW                  | j                         | j                  jY                  |        | j                  jY                  |        | j*                  j[                  | j                  t1        d'      d'       t        j                  | j                  t         j                  (      | _Q        t        j                  t         j                        | _R        t        | j                  t         j                  t1        d)      *      | _T        | j                  jc                  t         j                  | j                         t        | j                  t         j                  t1        d+      *      | _W        | j                  jc                  t         j                  | j                         | j                  j                  | j                         | j                  j                  | j                         | j                  jW                  | j                         | j                  jW                  | j                         | j                  j                  | j*                  t         j"                         | j                  j                  | j                  t         j"                         | j                  jY                  |        | j                  jY                          y#  tI        | j,                  t         j                  t8        jJ                  tM                     | _#        Y xY w#  tI        | j\                  t         j                  t8        jJ                        | _8        Y xY w),zCreates the main panel with all the controls on it:
        * mpl canvas
        * mpl navigation toolbar
        * Control panel for interaction
        )g      @g      @)   ro   ro   )	facecolorNro   r   )rS   style)rS   r>   z]Raster temporal dataset (strds)
Press ENTER after typing the name or select with the combobox)rS   r>   labelstrdsT)rS   r>   sizetypemultiplez'X and Y coordinates separated by comma:)rS   rT   )rS   r>   rt   	validatorzICoordinates can be obtained for example by right-clicking on Map Display.z"Show simple linear regression line)flagSTRDS)pagetextnamez]Vector temporal dataset (stvds)
Press ENTER after typing the name or select with the comboboxstvds)rS   zSelect attribute column)rS   r>   rt   zSelect category of vector(s)STVDSzSet title for the plotzSet label for X axiszSet label for Y axisLabelsz*Path for output CSV file with plotted datar2   zCVS pathBrowse)rS   r>   rt   	labelTextdialogTitle
buttonTextstartDirectoryfileModezDo you want the CSV header?Export)r>   Draw)r>   rr   Help)Yr@   Panel	mainPanelr   fig	FigCanvasrC   canvasaxes2dNavigationToolbartoolbarBoxSizerVERTICALvboxAddLEFTTOPEXPANDr   FN
FNB_NODRAGntbcontrolPanelRasterr   _datasetSelectLabelRr   Selectr   DIALOG_GSELECT_SIZEdatasetSelectRcoorrF   GetMapWindowCoordinatesSelectri   r   DIALOG_TEXTCTRL_SIZEr   
SetToolTipr   linRegRastercontrolPanelSizerRasterSetSizerFitAddPagecontrolPanelVectordatasetSelectLabelVdatasetSelectVrN   EVT_TEXTOnVectorSelectedColumnSelect	attributeattributeLabelVectorCategorySelectrk   	catsLabellinRegVectorcontrolPanelSizerVectorcontrolPanelLabels
titleLabelr?   xLabelxyLabelr    controlPanelSizerLabelscontrolPanelExportcsvLabel
filebrowseFileBrowseButtonosgetcwdFD_SAVE	csvButtonheaderLabelheaderCheck
HORIZONTALcontrolPanelSizerCheckcontrolPanelSizerExport
vButtPanel
vButtSizerr   
drawButton
EVT_BUTTONOnRedraw
helpButtonOnHelpra   s    r/   rJ   zTplotFrame._layout   s    $ *	:		488D )5 KK,			dkk1bgg&6&BC		dllAryy1 DNN"--H #%(($((ryy"I#-**yy%
$
  &nn**yy..
 **yy@A
	
	LL%%'"44..t||DL 	5	
 %**yy89
 (*{{2;;'?$ 	$$(()A)A		(R$$(()<)<299(M$$(((C$$((BII(F$$(():):(K(()E)EF$$((.d55AgJWU #%(($((ryy"I#-**yy%
$
  &nn**yy..
 	  d.C.CD --T5L5LM(**yy-.

	LL%%'44..t||DI $**yy23

 %**yy89
 (*{{2;;'?$ 	$$(()A)A		(R$$(()<)<299(M$$(()<)<299(M$$((bii(H$$((bii(H$$(((C$$(():):(K(()E)EF$$((.d55AgJWU #%(($((ryy"I$**yy,-

 **yy//


 !**yy*+

 **yy//

 !**yy*+

 **yy//

 (*{{2;;'?$$$((ryy(I$$(("))(D$$((299(E$$((bii(@$$((299(E$$((bii(@(()E)EF$$((.d55AhKhW #%(($((ryy"I"**yyCD

 $44**yy..*{99;ZZ	
 &**yy12

 ;;d.E.E"))T&(kk"--&@###''(8(89##''(8(89'){{2;;'?$$$((7$$((8$$(()D)DE(()E)EF##''-$$((.d55AhKhW ((4>>bii@++bmm4 RYYaiPR]]DMM: RYYaiPR]]DKK8DOO,DOO,  1		*		dhhRYY/		dooBII6		dM	#..9933.0	DLH	 ..9933DIs!   A
AD A
AE DAAEE;AFc                    | j                   st        | t        d      d       yd}d}dj                  g d      }|D ],  }|d   }|dz   |d	   z   }|d
   }t	        j
                  ||      }	|	j                  | j                        st        t        d      |z  |         y|	j                  | j                         |	j                  j                         }
| j                  j                  |       t               | j                  |<   || j                  |   d<   |	j                         | j                  |   d<   |	j!                         | j                  |   d<   || j                  |   d   }n-| j                  |   d   |k7  rt        | t        d              y|	j#                  | j                        }|	j%                  || j                        | j                  |   d<   d| j                  |   d<   | j                  |   d   dk(  rf|	j'                         \  }}| j                  |   d<   || j                  |   d   }n-| j                  |   d   |k7  rt        | t        d              y|	j)                  |dd| j                        }|D ]  }i | j                  |   |d   <   |d	   | j                  |   |d      d<   |d
   | j                  |   |d      d<   t+        |d         }|j-                          |j/                  | j                         }|j1                          |dk(  r||
k  rd| j                  |   |d      d<   || j                  |   |d      d<    / || _        || _        y)[Load data and read properties
        :param list timeseries: a list of timeseries
        Invalid input coordinatesFrS   messageshowTracebackN,)r|   
start_timeend_timer   @ro      rL   +Dataset <%s> not found in temporal databaser   rS   temporalDataTyperZ   granularityRDatasets have different temporal type (absolute x relative), which is not allowed.)rS   r   )mapsrL   validTopologyr[   relative7Datasets have different time unit which is not allowed.r   )columnswhereorderrL   start_datetimeend_datetimei   value)r_   r   r   joinrD   dataset_factoryis_in_dbrL   selectmetadataget_min_minr]   r(   r   rX   get_temporal_typeget_granularityget_registered_maps_as_objectscheck_temporal_topologyget_relative_timeget_registered_mapsr   open	get_valuerd   r[   rZ   )rR   
timeseriesmoder[   r   seriesr|   fullnameetypespminminr   r8   r9   rowsrowr   vals                     r/   _getSTRDdatazTplotFrame._getSTRDdata  s    xxQ'B%CSX ((=>  G	@F!9DczF1I-H1IE%%eX6B;;DII;.NO!
 II499I%[[,,.F%%d+#.=DNN4 7<DNN4 !34353G3G3IDNN4 0242D2D2FDNN4 /|~~d+N;%n5=0  44$))4DD464N4N		 5O 5DNN4 1 ,0DNN4 (~~d#N3zA;=;O;O;Q8sDNN408<>>$/7D^^D)&1T9# !'! ))t<dii * D  @/1t$SV,ADQt$SV,-=>?B1vt$SV,^<c!f%kk$((+	+%#,<@DNN4(Q09<?DNN4(Q09@yG	@R 	 rU   c                    t        d|dt              }|j                  j                  }|j	                         D ]H  }|j                  d      }|d   j                  d      d   }t        |      t        |      k(  sC|d   c S  y)	z2find attribute key according to layer of input mapzv.db.connectr   )mapflagsstdout_|r   /r   N)r   r   outputsstdout
splitlinesr&   str)rR   mapplayerInpvdblinelsplitlayers          r/   _parseVDbConnzTplotFrame._parseVDbConn  sz    ^S$Gkk  NN$ 	!DZZ_F1IOOC(+E5zS]*ay 		!
 rU   c                     t        j                  d|d      }|j                         }|s|S |D ]H  }t        |      |vst	        t        d      j                  ||      |        |j                  |       J |S )z)Get a list of categories for a vector mapz
v.categoryprint)inputoptionz?Category {ca} is not on vector map {ma} and it will be not used)macar   )grassread_commandr  r  r
   r   formatremove)rR   r  rk   r  
categoriescats         r/   _getExistingCategoriesz!TplotFrame._getExistingCategories  s      T'J^^%
 		!C3xz)8 ff- C 		! rU   c                 l   d}d}d}| j                   j                         }| j                  j                         dk7  r)| j                  j                         j                  d      }|r!| j                  rt        t        d             |r|dk(  rt        | dt        d             ydj                  g d	      }|D ]e  }|d
   }|dz   |d   z   }	|d   }
t        j                  |
|	      }|j                  | j                        st        t        d      |	z  | d        y|j                  | j                         |j                  | j                  d|d      }t               | j                   |<   |
| j                   |   d<   |j#                         | j                   |   d<   |j%                         | j                   |   d<   || j                   |   d   }n.| j                   |   d   |k7  rt        | dt        d              yd| j                   |   d<   | j                   |   d   dk(  rg|j'                         \  }}| j                   |   d<   || j                   |   d   }n.| j                   |   d   |k7  rt        t        d      | d        y| j                  r4| j(                  j+                  |       t-        j.                  d| j                  j1                         d      }t3        |      t3        |      k7  rt        | dt        d              yt5        t3        |            D ]  }||   }||   }t7        |d         t7        |d         k(  s+d j9                  |d!   |d   "      }i | j                   |   |<   |d   | j                   |   |   d#<   |d   | j                   |   |   d$<   |d%   |   | j                   |   |   d&<    d}| j;                  |d
   d!   |      }t3        |      }d}|D ]  }|dk(  r|dk7  r|d'j9                  |d()      z  }nS|dk(  r|dk(  r|d*j9                  |d()      z  }n2||k(  r|d+j9                  |d()      z  }n|d,j9                  |d()      z  }d-j9                  |.      }| j(                  j+                  d/j9                  ||0             t               | j                   |   |<   |dz  } |D ]D  }t=        |d         }| j?                  |d!   |      }|s.t        | dt        d1j9                  |d!   |2                     yt-        j@                  |d!   ||j9                  |3      |4      }d5j9                  |.      }|D ]  }d-j9                  |.      }|| j                   |   |   jC                         vri | j                   |   |   |<   |d   | j                   |   |   |   d#<   |d6   | j                   |   |   |   d$<   |d7   t=        |         d
   | j                   |   |   |   d&<    G h || _"        || _#        y)8r   Nr2   r   zvBoth coordinates and categories are set, coordinates will be used. The use categories remove text from coordinate form)r   FzCWith Vector temporal dataset you have to select an attribute columnrS   r   r   )r|   r   r   r>   r  r   r   ro   r   r   r   )r   rS   r   r   )rL   r   r   r   r   rZ   r   r   r[   r   r   
pois_srvdsl     _)r  coorddistancezJDifference number of vector layers and maps in the vector temporal datasetr  Layerz{map}_{layer}r|   )r  r  r   r   
Attributesr   z
{k}={c} orz{key})r   r!   z{k}={c}z {k}={c}z {k}={c} orzcat{num})numz
{na}+{cat})nar!  z6No connection between vector map {vmap} and layer {la})vmaplakey)r  r  r   r   zlay{num}r   values)$r   GetValuerk   r&   r_   r
   r   r   r   rD   r   r   rL   r   r   r   rY   r   r   r   r^   r(   r  vector_whatcoordsr4   ranger  r  r"  r'   r  vector_db_selectkeysr[   rZ   )rR   r   r   r[   rk   r   r   r   r|   r   r   r   r  r8   r9   outr-   r  r0  lay
wherequerytotcatncatr!  catncatkeyvalslayns                               r/   _getSTVDDatazTplotFrame._getSTVDData  s   
 NN++-	992%99%%'--c2DDHH7 IO#+ ((LM  E	F!9DczF1I-H1IE%%eX6B;;DII;.NO!"'	 II499I%))YYlG4 * D $/=DNN4 7<DNN4 !34353G3G3IDNN4 0242D2D2FDNN4 /|~~d+N;%n5="'F +/DNN4 (~~d#N3zA;=;O;O;Q8sDNN408<>>$/7D^^D)&1T9 !X!  $&+ xx""))$/ ''$((//+.
 s8s4y(#&+ !B! s4y) Aq'C VF3w<(Cw,@@-44 #F6'? 5  57t,S1FI,FWt,S12BCDGDUt,S1.A=CL=Q%>t,S1':  
22476?DIT CqyVq["l&9&9C7&9&KK
v{"i&6&6&6&HH
"j&7&7#&7&II
"m&:&:SG&:&LL
%,,,5D&&--l.A.ATt.A.TU1<DNN4(.AID    Cc'l+C!//FSAF!#'*/$%!117S[S1Q%  11K!(//F/; )	D &,,,5D# )00S09t~~d';D'A'F'F'HH?ADNN406t<MP(Nt,T2489IJ LO&Lt,T248H EINHEEt,T248A) KE	L 	 rU   c                    | j                   j                          | j                   j                  d       | j                  dk(  r_| j                   j	                          | j
                  j                          t        j                  | _	        t        j                  | _        nd | _	        | j                  | _        t        t              | _        g | _        g | _        g | _        | j$                  j'                         | _        | j*                  j'                         | _        | j.                  j'                         | _        | j2                  r&t5        | j6                  | j                        | _        n%t5        | j:                  | j                        | _        | j2                  r| j=                          | j>                  r9| j@                  r| jC                          n| jD                  r| jG                          | jH                  jK                          tM        | j"                  | j8                  tN        | j                         y)z)Draws or print 2D plot (temporal extents)Fabsolutec                     | S rW    r   s    r/   <lambda>z(TplotFrame._drawFigure.<locals>.<lambda>  s    Q rU   N)(r   cleargridrZ   
xaxis_dater   autofmt_xdatemdatesdate2numconvertnum2date
invconvertr   COLORScolorsyticksNames	yticksPosplotsr?   r1  	drawTitler   drawXr    drawYrH   LookUprX   lookUprY   drawRrG   r_   drawVrk   	drawVCatsr   draw
DataCursor
InfoFormatra   s    r/   _drawFigurezTplotFrame._drawFigure  sh   
*KK""$HH""$!??DL$ooDO&DL"llDOFm
,,.VV__&
VV__&
>> ADK ADK>>JJL>>xx

 4::t{{JErU   c                 z   | j                   dk7  r&| j                  j                  | j                          nh| j                  dk(  r(| j                  j                  t	        d|z               n1| j                  j                  t	        d      | j
                  z         | j                  dk7  r&| j                  j                  | j                         n4| j                  j                  dj                  | j                               | j                  dk7  r&| j                  j                  | j                         yy)z Function to set the right labelsr2   rB  zTemporal resolution: %sz	Time [%s]z, N)rV  r   
set_xlabelrZ   r   r[   rW  
set_ylabelr   rR  rU  	set_title)rR   r   s     r/   
_setLabelszTplotFrame._setLabels  s    ::KK""4::.  J.&&q)BQ)F'GH&&q~		'AB::KK""4::.KK""499T-=-=#>?>>RKK!!$..1  rU   c                    ddl }t        |d   t              rt        t        |g|       }nt        t        ||            }t	        | j
                  dd      5 }|j                  |      }| j                  r/dg}|j                  | j                         |j                  |       |j                  |       ddd       y# 1 sw Y   yxY w)z&Used to write CSV file of plotted datar   Nwr2   )newlineTime)csv
isinstancer*   zipr   r`   writerheaderextendrR  writerow	writerows)rR   r   r    rj  zippedfirm  heads           r/   	_writeCSVzTplotFrame._writeCSV  s    adD!#a*!*%F#a)_F$,,R0 	%BZZ^F{{xD,,-%V$	% 	% 	%s   ACCc                    fd}t        |      t        j                  ||z        z  t        j                  |      t        j                  |      z  z
  t        |      t        j                  ||z        z  t        j                  |      t        j                  |      z  z
  z  t        j                  |      t        j                  |      z  z
  t        |      z  |r|dj                        fS |S )ak  Calculate simple linear regression model
        y = a + b*x (y is dependent variable, a is intercept, b is slope,
        x is explanatory variable)

        param numpy.array x: explanatory variable
        param numpy.array y: dependent variable
        param returnFormula bool: return calculated simple linear
        regression formula too

        return tuple or function:

        tuple: (simple linear regression function model for dependent
        variable, calculated simple linear regression formula model)

        function: simple linear regression model function for dependent
        variable
        c                     | z  z   S rW   rD  )x1ar   s    r/   predictz-TplotFrame._calcSimpleLinReg.<locals>.predict  s    q2v:rU   zy = {a:.5f} + {b:.5f}*x)ry  r   )r4   npsumr  )rR   r   r    returnFormularz  ry  r   s        @@r/   _calcSimpleLinRegzTplotFrame._calcSimpleLinReg  s    &	 VbffQUm#bffQi"&&)&;;FRVVAE]"RVVAY%::
 VVAYRVVAY&#a&05<<qA<FFFrU   c                    | j                  t        j                  |      t        j                  |      d      \  }}dj                  t        j                  t        j                  |      t        j                  |            d   dz        }| j
                  j                  | j                  j                  | |t        j                  |            t        dj                  ||      	      d
          t        |       d
dl}|j                         dk(  r1t        dj                  dg|j                  d      dd z                yt        |       y)zDraw simple regression line

        :param list xdata: x axis data
        :param list xdata: y axis data

        return None
        T)r   r    r}  u   r² = {:.5f})r   ro   r   )rx  z{reg}, {r2})regr2)colorrr   r   NWindowsz =r  =ro   )r~  r{  arrayr  corrcoefrT  r(   r   plotLINEAR_REG_LINE_COLORr  platformsystemr   r&   )rR   xdataydatarz  
regFormular  r  s          r/   _drawSimpleLinRegLinez TplotFrame._drawSimpleLinRegLine!  s    #44hhuo% 5 
  &&KK%9$?1D
 	

KK288E?++#**zb*A	  
 	
 	j??	)$))TFRXXc]12%6678"IrU   c                    g }g }t        | j                        D ]  \  }}|d   }| j                  j                  |       | j                  j                  d       g }g }t        j                  | j                  |         D ]U  \  }}|dv r|j                  | j                  |d                |j                  |d          |j                  |d          W t        |      |j                  d       k(  rt        | dt        d              y | j                  j                  |||	       t        | j                         }	| j"                  j                  | j$                  j'                  ||d
|	| j(                  |         d          | j*                  j-                         r| j/                  ||       | j0                  s|j                  |        | j0                  r| j3                  ||       | j5                  | j                     d          | j$                  j7                         \  }
}| j$                  j9                  d       y )Nr   ro   rZ   r   r   r[   r   r   r   FzHProblem getting data from raster temporal dataset. Empty list of values.r$  yrangesxrangesdatasetNameomarkerr  rr   r  r  r   loc)	enumeraterH   rR  r(   rS  six	iteritemsrX   rM  r4   countr   r   rY  
AddDatasetnextrQ  rT  r   r  r]   r   	IsCheckedr  r`   ru  re  get_legend_handles_labelslegend)rR   ycsvxcsvr-   r|   r  r  r6  r0  r  handleslabelss               r/   rZ  zTplotFrame.drawRA  s    0 *	#GAt7D##D)NN!!!$EE #dnnT.B C 6f   T\\&1A*BCDVG_-F#3456 5zU[[.."': KK""5%T"R%EJJ  5EASASTUAV !    **,**e*D||E"U*	#X <<NN4&t,];<++??Aq!rU   c                 n   g }t        | j                        D ]  \  }}|j                  dd      }| j                  j	                  |       |j                  d      }|d   }| j                  j	                  d       g }g }g }t        j                  | j                  |d      |d            D ]o  \  }	}
|	dv r|j	                  | j                  |
d                |
d   dk(  r|j	                  d        n|j	                  |
d          |j	                  |
d          q t        |      |j                  d       k(  r<t        | d	t        d
j                  |d   j                  dd                         a| j                   j#                  |||       t%        | j&                        }| j(                  j	                  | j*                  j-                  ||d||      d          | j.                  j1                         r| j3                  ||       | j4                  s|j	                  |        | j4                  r| j7                  |       | j9                  | j                     d          | j*                  j;                         \  }}| j*                  j=                  d       g | _        y )N+ r   ro   r  r   r   r2   FzUProblem getting data from vector temporal dataset. Empty list of values for cat {ca}.r!  )r  r$  r  r  r  r  r   r  ) r  r^   replacerR  r(   r&   rS  r  r  rY   rM  r4   r  r   r   r  rY  r  r  rQ  rT  r   r  r   r  r  r`   ru  re  r  r  r\   )rR   r  r-   r|   	labelnamename_catr  r  r  r6  r0  r  r  r  s                 r/   r\  zTplotFrame.drawVCatsw  ss    !3!34 2	#GAtS#.I##I.zz#HA;DNN!!!$EED #dnnXa[.I(ST+.V W 6f   T\\&1A*BCD'?b(LL&LL1F#3456  5zU[[.."'  &(1+*=*=eR*H I KK""5%T"R%EJJ  5E !    **,**e*D||E"e2	#h <<NN4&t,];< ++??Aq!#% rU   c           
         g }t        | j                        D ]  \  }}| j                  j                  | j                  j                                | j                  j                  d       g }g }g }t        j                  | j                  |         D ]U  \  }}|dv r|j                  | j                  |d                |j                  |d          |j                  |d          W t        |      |j                  d       k(  rt        | dt        d              y | j                  j!                  |||       t#        | j$                        }	| j&                  j                  | j(                  j+                  ||d	|	|
      d          | j,                  j/                         r| j1                  ||       | j2                  s|j                  |        | j2                  r| j5                  |       | j7                  | j                     d          | j(                  j9                         \  }
}| j(                  j;                  d       g | _        y )Nr   r  r   r   FzHProblem getting data from vector temporal dataset. Empty list of values.r$  r  r  r  r  r   r  )r  r^   rR  r(   r   r1  rS  r  r  rY   rM  r4   r  r   r   rY  r  r  rQ  rT  r   r  r   r  r  r`   ru  re  r  r  r\   )rR   r  r-   r|   r  r  r  r6  r0  r  r  r  s               r/   r[  zTplotFrame.drawV  s    !3!34 )	#GAt##DNN$;$;$=>NN!!!$EED #dnnT.B C 6f   T\\&1A*BCDVG_-F#3456 5zU[[.."': KK""5%T"R%EJJ  cd STUV   **,**e*D||E"S)	#V <<NN4&t,];< ++??Aq!#% rU   Nc                    | j                          | j                  j                         | _        | j                  j                         | _        t        j                  j                  | j                        r| j                  st        j                  | t        dj                  | j                              t        d      t        j                  t        j                   z  t        j"                  z        }|j%                         t        j&                  k7  r(|j)                          t+        | dt        d             y|j)                          | j,                  j                         j/                         }| j0                  j                         j/                         }|s|sy	 | j2                  j4                  j                         }|r|dk7  r	 |j7                  d	      \  }}t9        |      t9        |      }}||g}|r	 t?        t9        |d         t9        |d               | _         | j@                  st+        | t        d      d       y| jD                  jG                         }	|	jI                  | j@                        st+        | t        d      d       y|rS|j7                  d	      }	 | jK                  |d      }|sy	 | j@                  st+        | t        d      d       y|| _&        |r/|j7                  d	      }	 | jK                  |d      }|sy	 || _'        | jQ                          y#  	 | j2                  j                         }n	#  d}Y nxY wY xY w# t:        t<        f$ ru 	 | j2                  j                         j7                  d	      \  }}t9        |      t9        |      }}n-# t:        t<        f$ r t+        | t        d
      d       Y Y yw xY wY w xY w# tB        $ r t+        | t        d      d       Y yw xY w# tB        $ r t+        | t        d      d       Y yw xY w# tB        $ r t+        | t        d      d       Y yw xY w)zRequired redrawing.z.{pa} already exists, do you want to overwrite?)pazFile existsFz)Please change name of output CSV file or r$  Nr2   r   z,Incorrect coordinates format, should be: x,yr   r   ro   r   z%Seed point outside the current regionrs   zInvalid input raster datasetr}   zInvalid input vector dataset))rE   r   r1  r`   r   r  rn  r   pathexistsrI   r@   MessageDialogr   r  OKCANCELICON_QUESTION	ShowModalID_OKrl   r   r   stripr   ri   coordsFieldr&   floatr)   AttributeErrorr   r_   r   rQ   get_bboxcontains_checkDatasetsrH   rG   _redraw)
rR   eventdlgrH   rG   getcoorscoordxcoordycoorsbboxs
             r/   r   zTplotFrame.OnRedraw  s   		~~..0&&00277>>$,,'""$$*FdllF$; - 		!B$4$44C }}"((*"'IJ
 KKM''00288:	''00288:		 ||//88:H B!)!4!&vf V$E$U58_eE!HoFDH xx# !"= >&+
 {{++-}}TXX.# !"L M&+
 !,I
 //	7C	  ! 889:"'
 &DN !,I
 //	7C	  ! 'DNi	  <<002 
 / 
	%)\\%:%:%<%B%B3%GNFF%*6]E&MFF"N3 # !"P Q&+
  
 " # !"= >&+
 :  <="'
 .  <="'
 s   '$L5 *M" )O) 2P P5 5M8MMMM"O&2AN54O&5&OO&OO&%O&) PP P21P25 QQc                    | j                   r| j                  | j                          | j                  r| j                  | j                         | j                  s"| j
                  j                  ddd      | _        | j                          y)zXReadraw data.

        Decides if to draw also 3D and adjusts layout if needed.
        ro   N)rH   r  rG   r@  r   r   add_subplotr`  ra   s    r/   r  zTplotFrame._redrawb  se    
 >>dnn->>dnn- {{((..q!Q7DKrU   c                 ^   g }t        j                  |d| j                        }t        j                  |      D 	cg c]@  \  }}t        j                  |      D 	cg c]  \  }}|D 	cg c]  }	|	||f	 c}	 c}	}}B }
}}}}}	|
rWt        d t        d |
            }
t        j                         j                         t        |
fd      D cg c]  }| }
}|D ]  }t        d      |z  }|j                  d      d	k\  rE|j                  dd
      \  }}t        |
      D cg c]  \  }\  }}}||k(  r||k(  r| }}}}}n*t        |
      D cg c]  \  }\  }}}||k(  r| }}}}}t        |      d	k(  rt        |      t        |      dk\  rt        j                   | t        d|z        t        d      |D cg c]  }d|
|   d	   |
|   d
   |
|   d   dz   c}t        j"                  t        j$                  z        }|j'                         t        j(                  k(  r)|j+                         }|j-                  |
||             {}|j-                  |
|d	              |S c c}	w c c}	}}w c c}	}}}}w c c}w c c}}}}w c c}}}}w c c}w )zChecks and validates datasets.

        Reports also type of dataset (e.g. 'strds').

        :param list datasets: list of temporal dataset's name
        :return: (mapName, mapset, type)
        T)ru   
group_typerL   c                     | |z   S rW   rD  r   r    s     r/   rF  z+TplotFrame._checkDatasets.<locals>.<lambda>  s
    QU rU   c                     | |z   S rW   rD  r  s     r/   rF  z+TplotFrame._checkDatasets.<locals>.<lambda>  s
    A rU   c                 ,    j                  | d         S )Nro   )index)lmapsetss    r/   rF  z+TplotFrame._checkDatasets.<locals>.<lambda>  s    W]]1Q4=P rU   r.  z"Space time dataset <%s> not found.r   r   ro   r   z+Please specify the space time dataset <%s>.zAmbiguous dataset namez%(map)s@%(mapset)s: %(etype)s)r  mapsetr   )r   captionchoicesrq   )rD   tlist_groupedrL   r  r  r   get_tgis_c_library_interfaceavailable_mapsetssortedr   findr&   r  r4   r   r@   SingleChoiceDialogCHOICEDLG_STYLEr  r  r  GetSelectionr(   )rR   datasetstyp	validatedtDictr  
etypesDictr   r   r  allDatasetsr-   dataseterrorMsg	nameShortnmapName
mapsetNameindicesr  r  r  s                        @r/   r  zTplotFrame._checkDatasetsr  s    	""499M '*mmE&:
 

 #
 $'==#< E4 266##vu%6
 
  "F+={$KK 779KKMG!+3PQK    -	:G=>HH||C A%$+MM#q$9!	6 <E[;Q 77GZ G+
f0D   8A7M 33GVU')   7|q  **W"++KgU 67 ") ) (31~a'8*5a.*;)4Q): ,,ruu4%( ==?bhh.,,.E$$[%@A  WQZ!89[-	:^ } 7
sB   !J"J.J :J?J	J2J"J""J* JJc                      t        ddd       y)zFunction to show helpzg.manualTzg.gui.tplot)progquietentryN)r   )rR   r  s     r/   r   zTplotFrame.OnHelp  s    
$mDrU   c                    |s|r|s|sy	 |r| j                  |d      | _        |r| j                  |d      | _        | j                  s| j                  sy|r_	 t        t        |d         t        |d               | _        	 | j                  j                  j                  d
j                  |             | j                  r{d
j                  t        d | j                              }| j                  j                  |       |r| j                  j                  |       |r| j                   j                  |       | j                  r?| j"                  j                  d
j                  t        d | j                                     |r| j$                  j                  |       |r| j&                  j                  |       |r| j(                  j                  |       |	r|	| _        |
| _        || _        | j1                          y# t        $ r t	        | t        d      d       Y yw xY w# t        $ r t	        | t        d	      d       Y yw xY w#  | j                  j                  d
j                  |             Y xY w)aV  Set the data
        :param list rasters: a list of temporal raster dataset's name
        :param list vectors: a list of temporal vector dataset's name
        :param list coors: a list with x/y coordinates
        :param list cats: a list with incld. categories of vector
        :param str attr:  name of attribute of vectror data
        Nrs   r}   Invalid input temporal datasetFr   r   ro   r   r   c                     | d   dz   | d   z   S Nr   r   ro   rD  rE  s    r/   rF  z(TplotFrame.SetDatasets.<locals>.<lambda>  s    AaD3J1,= rU   c                     | d   dz   | d   z   S r  rD  rE  s    r/   rF  z(TplotFrame.SetDatasets.<locals>.<lambda>  s    qtczAaD'8 rU   )r  rH   rG   r   r   r   r   r  r_   ri   r  SetValuer   r  r   r   rk   r   r?   r   r    r`   rn  rI   r  )rR   rastersvectorsr  rk   attrr?   xlabelylabelcsvfilert  rI   vdatass                r/   SetDatasetszTplotFrame.SetDatasets  s   * 7ET	!%!4!4Wg!F!%!4!4Wg!FNNdnn  uQx%a/B7((11#((5/B >>XXc"=t~~NOF((0''-		""4(>>((8$..IJ JJ&FFOOF#FFOOF#"DL"U  	:;#
 	  9:"'
 7%%chhuo6s0   A
H )H. 4I  H+*H+. II,Jc                    | j                   j                         j                         }|j                  d      d   }t	        |j                  d            dkD  r|j                  d      d   nd}d}t        j                  d| j                        D ]/  }|j                  d      \  }}||k(  s|r||k7  r%|dz   |z   }d} n |ri	 t        j                  d	d
|d      }	t        t!        t#        |	j                                           }	|	D ]  }
| j                  j%                  |
d         y| j                  j                          y# t        $ r4 | j                  j                          t        | t        d      d       Y yw xY w)z&Update the controlbox related to stvdsr   r   ro   r2   Fr}   )ru   rL   Tzt.vect.listur|   )r  r  columnr  r   N)r   r1  r  r&   r4   rD   tlistrL   r  r  	Exceptionr   Clearr   r   r*   setr  InsertColumns)rR   r  r  r|   r  foundeach	each_nameeach_mapset	vect_listvecs              r/   r   zTplotFrame.OnVectorSelected  sn   %%..0668}}S!!$*-gmmC.@*AA*Es#A&2JJG$))< 	D%)ZZ_"I{y f3*{2	 !..!GF	 S	(9!:;<I  5,,S!45 NN  "  $$&>?"'
 s   E :FF)FrW   )__name__
__module____qualname____doc__r   rB   rE   rf   rP   rJ   r  r  r"  r@  r`  re  ru  r~  r  rZ  r\  r[  r   r  r  r   r  r   rD  rU   r/   r<   r<   f   s    +-./C-D &	!FPWr
$fP$FL2 % <@4"l=&~4&ltl KZEHT#rU   r<   c                   "    e Zd ZdZd Zd Zd Zy)rX  z.Helper class for searching info by coordinatesc                 .    i | _         || _        || _        y rW   )datatimeDatarM  )rR   r  rM  s      r/   rB   zLookUp.__init__2  s    	 rU   c                     t        |      t        |      k7  rt        | dt        d             y i | j                  |<   t	        t        |            D ]  }||   | j                  |   ||   <    y )NFz(Datasets have different number of valuesr$  )r4   r   r   r  r4  )rR   r  r  r  r-   s        r/   r  zLookUp.AddDataset7  so    w<3w<'#DE
 !#		+s7|$ 	<A18DIIk"71:.	<rU   c                     i }t        j                  | j                        D ]$  \  }}||   s| j                  |      ||   g||<   & t	        |      dk(  ry | j
                  |fS )Nr   )r  r  r  rM  r4   r  )rR   r   r0  r/  r   s        r/   GetInformationzLookUp.GetInformationC  sh    --		2 	:JCQx#||Aa9s	: v;!}}f$$rU   N)r  r  r  r  rB   r  r  rD  rU   r/   rX  rX  /  s    8

<	%rU   rX  c           
         g }t        j                  |      D ]  \  }}| |   d   }|dk(  r|j                  t        d      |z         nE|dk(  r|j                  t        d      |z         n"|dk(  r|j                  t        d      |z         |j                  t        dj	                  |d	   |d
                      |j                  d        |j                  t        d             dj                  |      S )z!Formats information about datasetr   rs   zSpace time raster dataset: %sr}   zSpace time vector dataset: %sstr3dsz Space time 3D raster dataset: %szValue for {date} is {val}r   ro   )dater  
zPress Del to dismiss.)r  r  r(   r   r  r   )r  r0  r{   r/  r  r   s         r/   r_  r_  O  s    DMM&) 
S01GKK9:S@AgKK9:S@AhKK<=CDA188c!f#a&8QRSD
 	KK)*+99T?rU   c                   0    e Zd ZdZ	 	 	 ddZd Zd Zd Zy)r^  zA simple data cursor widget that displays the x,y location of a
    matplotlib artist when it is selected.


    Source: http://stackoverflow.com/questions/4652439/
            is-there-a-matplotlib-equivalent-of-matlabs-datacursormode/4674445
    c                    || _         || _        || _        || _        t	        j
                  |      s|g}|| _        || _        t        t        d | j                  D                    | _
        t        t        d | j                  D                    | _        i | _        | j                  D ]   }| j                  |      | j                  |<   " | j                  D ]  }	|	j                  |        | j                  D ]D  }
|
j                  j!                  d|        |
j                  j!                  d| j"                         F y)aO  Create the data cursor and connect it to the relevant figure.
        "artists" is the matplotlib artist or sequence of artists that will be
            selected.
        "tolerance" is the radius (in points) that the mouse click must be
            within to select the artist.
        "offsets" is a tuple of (x,y) offsets in points from the selected
            point to the displayed annotation box
        "display_all" controls whether more than one annotation box will
            be shown if there are multiple axes.  Only one will be shown
            per-axis, regardless.
        c              3   4   K   | ]  }|j                     y wrW   )axes).0arts     r/   	<genexpr>z&DataCursor.__init__.<locals>.<genexpr>  s     ?3chh?   c              3   4   K   | ]  }|j                     y wrW   )figure)r  axs     r/   r   z&DataCursor.__init__.<locals>.<genexpr>  s      ?r ?r!  
pick_eventkey_press_eventN)rY  formatFunctionoffsetsdisplay_allr{  iterableartistsrM  tupler  r  figuresannotationsannotateset_pickradiusr   mpl_connect
keyPressed)rR   r+  rY  r'  rM  	tolerancer(  r)  r$  artistr   s              r/   rB   zDataCursor.__init__k  s   * ,&{{7#iG#?$,,??@	S ?TYY ??@)) 	5B#'==#4DR 	5ll 	-F!!),	-<< 	GCJJ""<6JJ""#4dooF	GrU   c                     |j                   dk7  ry| j                  D ]:  }| j                  |   j                  d       |j                  j                          < y)z3Key pressed - hide annotation if Delete was presseddeleteNF)r/  r  r.  set_visibler   r]  )rR   r  r$  s      r/   r2  zDataCursor.keyPressed  sM    99 )) 	 BR ,,U3LL	 rU   c                     |j                  | j                  dd| j                  ddt        ddd      t        d	d
      dd
      }|j	                  d       |S )z;Draws and hides the annotation box for the given axis "ax".)r   r   centerbottomzoffset pointszround,pad=0.5yellowgffffff?)boxstylefcalphaz->z
arc3,rad=0)
arrowstyleconnectionstyleFleft)	xyhaxytextva
textcoordsr  
arrowpropsannotation_clipmultialignment)r/  r'  r(  dictr7  )rR   r$  
annotations      r/   r/  zDataCursor.annotate  sc    [[<<&83Gt\J!! ! 

 	u%rU   c                    |j                   j                  |j                   j                  }}| j                  |j                  j
                     }|e| j                  s0| j                  j                         D ]  }|j                  d        dt        t        |j                              v rhg }|j                  j                         D ]%  }	 | j                  |      }|j                  |       ' |t        j                  t!        ||z
                 }| j"                  j%                  |      }	t'        t)        |	d   j                                d   }
|	sy|t+        |
      f|_         | j.                  |	 }|j1                  |       |j                  d       |j2                  j5                          yy#  |}Y xY w)z,Intended to be called through "mpl_connect".NFLine2Dro   T)
mouseeventr  r  r.  r4  r  r)  r0  r7  r  ru   	get_xdatarM  r(   r{  argminabsrY  r  r*   rl  maxrB  r'  set_textr   r]  )rR   r  r   r    rK  annxDatary  dinfoysr{   s               r/   __call__zDataCursor.__call__  s    %%u'7'7'='=1%%ell&7&78
=##++224 +COOE*+3tELL122//1 $A LLO LLO$ "))C	N34;;--a0Dc47>>+,-a0Bs2wJJM&4&&-D%""4(LL1 s   F99F?N)   )i   F)r  r  r  r  rB   r2  r/  rY  rD  rU   r/   r^  r^  b  s(     'GR $ rU   r^  )Qr  r   r  	itertoolsr   numpyr{  r@   grass.pygrass.modulesr   grass.scriptscriptr  	functoolsr   r$   usematplotlib.figurer   !matplotlib.backends.backend_wxaggr   r   r	   r   matplotlib.datesdatesrK  ImportErrorer   r  grass.temporaltemporalrD   	core.gcmdr
   r   r   r   gui_core.widgetsr   gui_corer   corer   grass.pygrass.vector.geometryr   grass.pygrass.rasterr   grass.pygrass.gis.regionr   collectionsr   
subprocessr   wx.lib.agw.flatnotebooklibagwflatnotebookr   wx.lib.flatnotebookwx.lib.filebrowsebuttonfilebrowsebuttonr   r   gui_core.wrapr   r   r   r   ALPHArP  r  r0   r:   rA   r<   rX  r_  objectr^  rD  rU   r/   <module>r~     s!  $ 
 
   	 (   JNN7( &  > > 1   / * + # %(( - , & @ @	,* F# F#R&% %@&j  j m)  
	?	
 &)	 ,  %$$%s)   *C< D& <D#DD#&D76D7