[GRASS-SVN] r62594 - in grass/trunk/lib/python/temporal: . testsuite

svn_grass at osgeo.org svn_grass at osgeo.org
Tue Nov 4 07:45:52 PST 2014


Author: huhabla
Date: 2014-11-04 07:45:52 -0800 (Tue, 04 Nov 2014)
New Revision: 62594

Added:
   grass/trunk/lib/python/temporal/temporal_operator.py
   grass/trunk/lib/python/temporal/testsuite/unittests_temporal_algebra.py
   grass/trunk/lib/python/temporal/testsuite/unittests_temporal_conditionals.py
   grass/trunk/lib/python/temporal/testsuite/unittests_temporal_raster3d_algebra.py
   grass/trunk/lib/python/temporal/testsuite/unittests_temporal_raster_algebra.py
   grass/trunk/lib/python/temporal/testsuite/unittests_temporal_raster_conditionals.py
   grass/trunk/lib/python/temporal/testsuite/unittests_temporal_vector_algebra.py
Removed:
   grass/trunk/lib/python/temporal/temporal_raster_operator.py
   grass/trunk/lib/python/temporal/temporal_vector_operator.py
   grass/trunk/lib/python/temporal/testsuite/test_temporal_raster3d_algebra.py
   grass/trunk/lib/python/temporal/testsuite/test_temporal_raster_algebra.py
Modified:
   grass/trunk/lib/python/temporal/Makefile
   grass/trunk/lib/python/temporal/__init__.py
   grass/trunk/lib/python/temporal/temporal_algebra.py
   grass/trunk/lib/python/temporal/temporal_raster3d_algebra.py
   grass/trunk/lib/python/temporal/temporal_raster_algebra.py
   grass/trunk/lib/python/temporal/temporal_raster_base_algebra.py
   grass/trunk/lib/python/temporal/temporal_vector_algebra.py
   grass/trunk/lib/python/temporal/testsuite/test_doctests.py
   grass/trunk/lib/python/temporal/testsuite/test_register_function.py
Log:
temporal framework: New temporal algebra approach implemented by Thomas Leppelt. Additional algebra tests implemented.

Modified: grass/trunk/lib/python/temporal/Makefile
===================================================================
--- grass/trunk/lib/python/temporal/Makefile	2014-11-04 15:04:13 UTC (rev 62593)
+++ grass/trunk/lib/python/temporal/Makefile	2014-11-04 15:45:52 UTC (rev 62594)
@@ -2,12 +2,13 @@
 
 include $(MODULE_TOPDIR)/include/Make/Other.make
 include $(MODULE_TOPDIR)/include/Make/Python.make
+include $(MODULE_TOPDIR)/include/Make/Doxygen.make
 
 PYDIR = $(ETC)/python
 GDIR = $(PYDIR)/grass
 DSTDIR = $(GDIR)/temporal
 
-MODULES = base core abstract_dataset abstract_map_dataset abstract_space_time_dataset space_time_datasets open_stds factory gui_support list_stds register sampling metadata spatial_extent temporal_extent datetime_math temporal_granularity spatio_temporal_relationships unit_tests aggregation stds_export stds_import extract mapcalc univar_statistics temporal_topology_dataset_connector spatial_topology_dataset_connector c_libraries_interface temporal_algebra temporal_vector_algebra temporal_vector_operator temporal_raster_operator temporal_raster_base_algebra temporal_raster_algebra temporal_raster3d_algebra
+MODULES = base core abstract_dataset abstract_map_dataset abstract_space_time_dataset space_time_datasets open_stds factory gui_support list_stds register sampling metadata spatial_extent temporal_extent datetime_math temporal_granularity spatio_temporal_relationships unit_tests aggregation stds_export stds_import extract mapcalc univar_statistics temporal_topology_dataset_connector spatial_topology_dataset_connector c_libraries_interface temporal_algebra temporal_vector_algebra temporal_raster_base_algebra temporal_raster_algebra temporal_raster3d_algebra temporal_operator
 
 PYFILES := $(patsubst %,$(DSTDIR)/%.py,$(MODULES) __init__)
 PYCFILES := $(patsubst %,$(DSTDIR)/%.pyc,$(MODULES) __init__)
@@ -25,3 +26,6 @@
 
 $(DSTDIR)/%: % | $(DSTDIR)
 	$(INSTALL_DATA) $< $@
+
+#doxygen:
+DOXNAME = pythontemporal

Modified: grass/trunk/lib/python/temporal/__init__.py
===================================================================
--- grass/trunk/lib/python/temporal/__init__.py	2014-11-04 15:04:13 UTC (rev 62593)
+++ grass/trunk/lib/python/temporal/__init__.py	2014-11-04 15:45:52 UTC (rev 62594)
@@ -1,17 +1,12 @@
 from core import *
 from base import *
-from temporal_extent import *
 from spatial_extent import *
 from metadata import *
-from temporal_topology_dataset_connector import *
-from spatial_topology_dataset_connector import *
 from abstract_dataset import *
 from abstract_map_dataset import *
 from abstract_space_time_dataset import *
 from space_time_datasets import *
 from datetime_math import *
-from temporal_granularity import *
-from spatio_temporal_relationships import *
 from open_stds import *
 from factory import *
 from gui_support import *
@@ -25,10 +20,14 @@
 from mapcalc import *
 from univar_statistics import *
 from c_libraries_interface import *
+from spatio_temporal_relationships import *
+from spatial_topology_dataset_connector import *
+from temporal_extent import *
+from temporal_topology_dataset_connector import *
+from temporal_granularity import *
 from temporal_algebra import *
 from temporal_vector_algebra import *
-from temporal_vector_operator import *
-from temporal_raster_operator import *
 from temporal_raster_base_algebra import *
 from temporal_raster_algebra import *
 from temporal_raster3d_algebra import *
+from temporal_operator import *

Modified: grass/trunk/lib/python/temporal/temporal_algebra.py
===================================================================
--- grass/trunk/lib/python/temporal/temporal_algebra.py	2014-11-04 15:04:13 UTC (rev 62593)
+++ grass/trunk/lib/python/temporal/temporal_algebra.py	2014-11-04 15:45:52 UTC (rev 62594)
@@ -1,4 +1,5 @@
-"""
+"""@package grass.temporal
+
 Temporal algebra parser class
 
 (C) 2014 by the GRASS Development Team
@@ -31,21 +32,21 @@
     LexToken(NAME,'test1',1,4)
     LexToken(T_NOT_SELECT,'!:',1,10)
     LexToken(NAME,'test2',1,13)
-    >>> expression =  "C = test1 {equal,:} test2"
+    >>> expression =  "C = test1 {:,equal} test2"
     >>> p.test(expression)
-    C = test1 {equal,:} test2
+    C = test1 {:,equal} test2
     LexToken(NAME,'C',1,0)
     LexToken(EQUALS,'=',1,2)
     LexToken(NAME,'test1',1,4)
-    LexToken(T_SELECT_OPERATOR,'{equal,:}',1,10)
+    LexToken(T_SELECT_OPERATOR,'{:,equal}',1,10)
     LexToken(NAME,'test2',1,20)
-    >>> expression =  "C = test1 {equal,!:} test2"
+    >>> expression =  "C = test1 {!:,equal} test2"
     >>> p.test(expression)
-    C = test1 {equal,!:} test2
+    C = test1 {!:,equal} test2
     LexToken(NAME,'C',1,0)
     LexToken(EQUALS,'=',1,2)
     LexToken(NAME,'test1',1,4)
-    LexToken(T_SELECT_OPERATOR,'{equal,!:}',1,10)
+    LexToken(T_SELECT_OPERATOR,'{!:,equal}',1,10)
     LexToken(NAME,'test2',1,21)
     >>> expression =  "C = test1 # test2"
     >>> p.test(expression)
@@ -63,21 +64,21 @@
     LexToken(NAME,'test1',1,4)
     LexToken(T_HASH_OPERATOR,'{#}',1,10)
     LexToken(NAME,'test2',1,14)
-    >>> expression =  "C = test1 {equal,#} test2"
+    >>> expression =  "C = test1 {#,equal} test2"
     >>> p.test(expression)
-    C = test1 {equal,#} test2
+    C = test1 {#,equal} test2
     LexToken(NAME,'C',1,0)
     LexToken(EQUALS,'=',1,2)
     LexToken(NAME,'test1',1,4)
-    LexToken(T_HASH_OPERATOR,'{equal,#}',1,10)
+    LexToken(T_HASH_OPERATOR,'{#,equal}',1,10)
     LexToken(NAME,'test2',1,20)
-    >>> expression =  "C = test1 {equal|during,#} test2"
+    >>> expression =  "C = test1 {#,equal|during} test2"
     >>> p.test(expression)
-    C = test1 {equal|during,#} test2
+    C = test1 {#,equal|during} test2
     LexToken(NAME,'C',1,0)
     LexToken(EQUALS,'=',1,2)
     LexToken(NAME,'test1',1,4)
-    LexToken(T_HASH_OPERATOR,'{equal|during,#}',1,10)
+    LexToken(T_HASH_OPERATOR,'{#,equal|during}',1,10)
     LexToken(NAME,'test2',1,27)
     >>> expression =  "E = test1 : test2 !: test1"
     >>> p.test(expression)
@@ -112,15 +113,15 @@
     LexToken(LPAREN,'(',1,9)
     LexToken(NAME,'test1',1,10)
     LexToken(RPAREN,')',1,15)
-    >>> expression =  'H = tsnap(test2 {during,:} buff_t(test1, "1 days"))'
+    >>> expression =  'H = tsnap(test2 {:,during} buff_t(test1, "1 days"))'
     >>> p.test(expression)
-    H = tsnap(test2 {during,:} buff_t(test1, "1 days"))
+    H = tsnap(test2 {:,during} buff_t(test1, "1 days"))
     LexToken(NAME,'H',1,0)
     LexToken(EQUALS,'=',1,2)
     LexToken(TSNAP,'tsnap',1,4)
     LexToken(LPAREN,'(',1,9)
     LexToken(NAME,'test2',1,10)
-    LexToken(T_SELECT_OPERATOR,'{during,:}',1,16)
+    LexToken(T_SELECT_OPERATOR,'{:,during}',1,16)
     LexToken(BUFF_T,'buff_t',1,27)
     LexToken(LPAREN,'(',1,33)
     LexToken(NAME,'test1',1,34)
@@ -131,15 +132,15 @@
     LexToken(QUOTE,'"',1,48)
     LexToken(RPAREN,')',1,49)
     LexToken(RPAREN,')',1,50)
-    >>> expression =  'H = tshift(test2 {during,:} buff_t(test1, "1 days"), "1 months")'
+    >>> expression =  'H = tshift(test2 {:,during} buff_t(test1, "1 days"), "1 months")'
     >>> p.test(expression)
-    H = tshift(test2 {during,:} buff_t(test1, "1 days"), "1 months")
+    H = tshift(test2 {:,during} buff_t(test1, "1 days"), "1 months")
     LexToken(NAME,'H',1,0)
     LexToken(EQUALS,'=',1,2)
     LexToken(TSHIFT,'tshift',1,4)
     LexToken(LPAREN,'(',1,10)
     LexToken(NAME,'test2',1,11)
-    LexToken(T_SELECT_OPERATOR,'{during,:}',1,17)
+    LexToken(T_SELECT_OPERATOR,'{:,during}',1,17)
     LexToken(BUFF_T,'buff_t',1,28)
     LexToken(LPAREN,'(',1,34)
     LexToken(NAME,'test1',1,35)
@@ -200,9 +201,9 @@
     LexToken(COMMA,',',1,20)
     LexToken(NAME,'B',1,22)
     LexToken(RPAREN,')',1,23)
-    >>> expression =  'I = if(equals,td(A) > 10 {equals,||} td(B) < 10, A)'
+    >>> expression =  'I = if(equals,td(A) > 10 {||,equals} td(B) < 10, A)'
     >>> p.test(expression)
-    I = if(equals,td(A) > 10 {equals,||} td(B) < 10, A)
+    I = if(equals,td(A) > 10 {||,equals} td(B) < 10, A)
     LexToken(NAME,'I',1,0)
     LexToken(EQUALS,'=',1,2)
     LexToken(IF,'if',1,4)
@@ -215,7 +216,7 @@
     LexToken(RPAREN,')',1,18)
     LexToken(GREATER,'>',1,20)
     LexToken(INT,10,1,22)
-    LexToken(T_COMP_OPERATOR,'{equals,||}',1,25)
+    LexToken(T_COMP_OPERATOR,'{||,equals}',1,25)
     LexToken(TD,'td',1,37)
     LexToken(LPAREN,'(',1,39)
     LexToken(NAME,'B',1,40)
@@ -250,9 +251,9 @@
     LexToken(COMMA,',',1,44)
     LexToken(NAME,'A',1,46)
     LexToken(RPAREN,')',1,47)
-    >>> expression =  'E = if({equals},td(A) >= 4 {contain,&&} td(B) == 2, C : D)'
+    >>> expression =  'E = if({equals},td(A) >= 4 {&&,contain} td(B) == 2, C : D)'
     >>> p.test(expression)
-    E = if({equals},td(A) >= 4 {contain,&&} td(B) == 2, C : D)
+    E = if({equals},td(A) >= 4 {&&,contain} td(B) == 2, C : D)
     LexToken(NAME,'E',1,0)
     LexToken(EQUALS,'=',1,2)
     LexToken(IF,'if',1,4)
@@ -265,7 +266,7 @@
     LexToken(RPAREN,')',1,20)
     LexToken(GREATER_EQUALS,'>=',1,22)
     LexToken(INT,4,1,25)
-    LexToken(T_COMP_OPERATOR,'{contain,&&}',1,27)
+    LexToken(T_COMP_OPERATOR,'{&&,contain}',1,27)
     LexToken(TD,'td',1,40)
     LexToken(LPAREN,'(',1,42)
     LexToken(NAME,'B',1,43)
@@ -277,9 +278,9 @@
     LexToken(T_SELECT,':',1,54)
     LexToken(NAME,'D',1,56)
     LexToken(RPAREN,')',1,57)
-    >>> expression =  'F = if({equals},A {equal,#}, B, C : D)'
+    >>> expression =  'F = if({equals},A {#,equal}, B, C : D)'
     >>> p.test(expression)
-    F = if({equals},A {equal,#}, B, C : D)
+    F = if({equals},A {#,equal}, B, C : D)
     LexToken(NAME,'F',1,0)
     LexToken(EQUALS,'=',1,2)
     LexToken(IF,'if',1,4)
@@ -287,7 +288,7 @@
     LexToken(T_REL_OPERATOR,'{equals}',1,7)
     LexToken(COMMA,',',1,15)
     LexToken(NAME,'A',1,16)
-    LexToken(T_HASH_OPERATOR,'{equal,#}',1,18)
+    LexToken(T_HASH_OPERATOR,'{#,equal}',1,18)
     LexToken(COMMA,',',1,27)
     LexToken(NAME,'B',1,29)
     LexToken(COMMA,',',1,30)
@@ -298,33 +299,20 @@
     >>> p = tgis.TemporalAlgebraParser()
     >>> p.run = False
     >>> p.debug = True
-    >>> expression =  "D = A : (B !: C)"
-    >>> p.parse(expression)
-    B* =  B !: C
-    A* =  A : B*
-    D = A*
-    >>> expression =  "D = A {!:} B {during,:} C"
+    >>> expression =  "D = A {!:} B {:,during} C"
     >>> print(expression)
-    D = A {!:} B {during,:} C
+    D = A {!:} B {:,during} C
     >>> p.parse(expression)
     A* =  A {!:} B
-    A** =  A* {during,:} C
+    A** =  A* {:,during} C
     D = A**
-    >>> expression =  "D = A {:} B {during,!:} C"
+    >>> expression =  "D = A {:} B {!:,during} C"
     >>> print(expression)
-    D = A {:} B {during,!:} C
+    D = A {:} B {!:,during} C
     >>> p.parse(expression)
     A* =  A {:} B
-    A** =  A* {during,!:} C
+    A** =  A* {!:,during} C
     D = A**
-    >>> expression =  "D = A {:} (B {during,!:} (C : E))"
-    >>> print(expression)
-    D = A {:} (B {during,!:} (C : E))
-    >>> p.parse(expression)
-    C* =  C : E
-    B* =  B {during,!:} C*
-    A* =  A {:} B*
-    D = A*
     >>> p.run = False
     >>> p.debug = False
     >>> expression =  "C = test1 : test2"
@@ -335,24 +323,24 @@
     >>> print(expression)
     D = buff_t(test1,"10 months")
     >>> p.parse(expression, 'stvds')
-    >>> expression =  'E = test2 {during,:} buff_t(test1,"1 days")'
+    >>> expression =  'E = test2 {:,during} buff_t(test1,"1 days")'
     >>> print(expression)
-    E = test2 {during,:} buff_t(test1,"1 days")
+    E = test2 {:,during} buff_t(test1,"1 days")
     >>> p.parse(expression, 'stvds')
-    >>> expression =  'F = test2 {equal,:} buff_t(test1,"1 days")'
+    >>> expression =  'F = test2 {:,equal} buff_t(test1,"1 days")'
     >>> print(expression)
-    F = test2 {equal,:} buff_t(test1,"1 days")
+    F = test2 {:,equal} buff_t(test1,"1 days")
     >>> p.parse(expression, 'stvds')
     >>> p.debug = True
-    >>> expression =  'H = tsnap(test2 {during,:} buff_t(test1, "1 days"))'
+    >>> expression =  'H = tsnap(test2 {:,during} buff_t(test1, "1 days"))'
     >>> p.parse(expression, 'stvds')
     test1* = buff_t( test1 , " 1 days " )
-    test2* =  test2 {during,:} test1*
+    test2* =  test2 {:,during} test1*
     test2** = tsnap( test2* )
     H = test2**
-    >>> expression =  'H = tshift(test2 {during,:} test1, "1 days")'
+    >>> expression =  'H = tshift(test2 {:,during} test1, "1 days")'
     >>> p.parse(expression, 'stvds')
-    test2* =  test2 {during,:} test1
+    test2* =  test2 {:,during} test1
     test2** = tshift( test2* , " 1 days " )
     H = test2**
     >>> expression =  'H = tshift(H, 3)'
@@ -363,21 +351,21 @@
     >>> p.parse(expression, 'stvds')
     td(A)
     td(A) == 2
-    A* =  if condition True  then  A
+    A* =  if condition None  then  A
     C = A*
     >>> expression =  'C = if(td(A) == 5, A, B)'
     >>> p.parse(expression, 'stvds')
     td(A)
     td(A) == 5
-    A* =  if condition True  then  A  else  B
+    A* =  if condition None  then  A  else  B
     C = A*
-    >>> expression =  'C = if(td(A) == 5 || start_date() > "2010-01-01", A, B)'
+    >>> expression =  'C = if(td(A) == 5 || start_date(A) > "2010-01-01", A, B)'
     >>> p.parse(expression, 'stvds')
     td(A)
     td(A) == 5
-    start_date > "2010-01-01"
-    True || True
-    A* =  if condition True  then  A  else  B
+    start_date A > "2010-01-01"
+    None || None
+    A* =  if condition None  then  A  else  B
     C = A*
 
 """
@@ -389,34 +377,36 @@
     pass
 
 import os
+import copy
+import grass.pygrass.modules as pymod
 from space_time_datasets import *
 from factory import *
 from open_stds import *
+from temporal_operator import *
 
-from grass.exceptions import FatalError
-
 ##############################################################################
 
-
 class TemporalAlgebraLexer(object):
     """Lexical analyzer for the GRASS GIS temporal algebra"""
 
-    # Functions that defines an if condition, temporal buffering and snapping
+    # Functions that defines an if condition, temporal buffering, snapping and 
+    # selection of maps with temporal extent.
     conditional_functions = {
-        'if': 'IF',
+        'if'    : 'IF',
         'buff_t': 'BUFF_T',
-        'tsnap': 'TSNAP',
-        'tshift': 'TSHIFT',
+        'tsnap'  : 'TSNAP',
+        'tshift' : 'TSHIFT',
+        'tmap' : 'TMAP',
     }
-
+    
     # Variables with date and time strings
     datetime_functions = {
-        'start_time': 'START_TIME',     # start time as HH::MM:SS
-        'start_date': 'START_DATE',     # start date as yyyy-mm-DD
-        'start_datetime': 'START_DATETIME',  # start datetime as yyyy-mm-DD HH:MM:SS
-        'end_time': 'END_TIME',       # end time as HH:MM:SS
-        'end_date': 'END_DATE',       # end date as yyyy-mm-DD
-        'end_datetime': 'END_DATETIME',  # end datetime as  yyyy-mm-DD HH:MM:SS
+        'start_time'     : 'START_TIME',     # start time as HH::MM:SS
+        'start_date'     : 'START_DATE',     # start date as yyyy-mm-DD
+        'start_datetime' : 'START_DATETIME', # start datetime as yyyy-mm-DD HH:MM:SS
+        'end_time'       : 'END_TIME',       # end time as HH:MM:SS
+        'end_date'       : 'END_DATE',       # end date as yyyy-mm-DD
+        'end_datetime'   : 'END_DATETIME',   # end datetime as  yyyy-mm-DD HH:MM:SS
     }
 
     # Time functions
@@ -496,13 +486,13 @@
                     + tuple(conditional_functions.values())
 
     # Regular expression rules for simple tokens
-    t_T_SELECT_OPERATOR  = r'\{([a-zA-Z\| ]+[,])?([\|&+=]?[!]?[:])\}'
-    t_T_HASH_OPERATOR    = r'\{([a-zA-Z\| ]+[,])?[#]\}'
-    t_T_COMP_OPERATOR    = r'\{([a-zA-Z\| ]+[,])?(\|\||&&)\}'
+    t_T_SELECT_OPERATOR   = r'\{[!]?[:][,]?[a-zA-Z\| ]*([,])?([lrudi]|left|right|union|disjoint|intersect)?\}'
+    t_T_HASH_OPERATOR   = r'\{[#][,]?[a-zA-Z\| ]*([,])?([lrudi]|left|right|union|disjoint|intersect)?\}'
+    t_T_COMP_OPERATOR   = r'\{(\|\||&&)[,][a-zA-Z\| ]*[,]?[\|&]?([,])?([lrudi]|left|right|union|disjoint|intersect)?\}'
     t_T_REL_OPERATOR     = r'\{([a-zA-Z\| ])+\}'
     t_T_SELECT           = r':'
     t_T_NOT_SELECT       = r'!:'
-    t_LPAREN             = r'\('
+    t_LPAREN             = r'\('    
     t_RPAREN             = r'\)'
     t_COMMA              = r','
     t_CEQUALS            = r'=='
@@ -526,6 +516,7 @@
         # t.value = int(t.value)
         return t
 
+
     # Read date string and convert it into a date object
     def t_DATE(self, t):
         r'"\d\d\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])"'
@@ -549,9 +540,8 @@
         r'-?\d+'
         t.value = int(t.value)
         return t
-
     # Read in a list of maps.
-    def t_LIST(self, t):
+    def  t_LIST(self, t):
         r'[\[][.]*[\]]'
         t.value = list(t.value)
         return t
@@ -587,52 +577,49 @@
     # Handle errors.
     def t_error(self, t):
         raise SyntaxError("syntax error on line %d near '%s'" %
-                          (t.lineno, t.value))
+            (t.lineno, t.value))
 
     # Build the lexer
-    def build(self, **kwargs):
-        self.lexer = lex.lex(module=self, optimize=False, debug=False,
-                             **kwargs)
+    def build(self,**kwargs):
+        self.lexer = lex.lex(module=self, optimize=False, debug=False, **kwargs)
 
     # Just for testing
-    def test(self, data):
+    def test(self,data):
         self.name_list = {}
         print(data)
         self.lexer.input(data)
         while True:
-            tok = self.lexer.token()
-            if not tok: break
-            print tok
+             tok = self.lexer.token()
+             if not tok: break
+             print tok
 
 ###############################################################################
 
-
 class GlobalTemporalVar(object):
     """ This class handles global temporal variable conditional expressions,
         like start_doy() == 3.
         The three parts of the statement are stored separately in
         tfunc (START_DOY), compop (==) and value (3).
-        But also boolean values, time differences and relation operators for
-        comparison in if-statements can be stored in this class.
+        But also boolean values, time differences and relation operators for comparison in
+        if-statements can be stored in this class.
     """
     def __init__(self):
-        self.tfunc = None
-        self.compop = None
-        self.value = None
-        self.boolean = None
-        self.relationop = None
-        self.topology = []
-        self.td = None
+        self.tfunc        = None
+        self.compop       = None
+        self.value        = None
+        self.boolean      = None
+        self.relationop   = None
+        self.topology     = []
+        self.td           = None
 
     def get_type(self):
-        if self.tfunc is not None and self.compop is not None and \
-           self.value is not None:
+        if self.tfunc != None and self.compop != None and self.value != None:
             return("global")
-        elif self.boolean is not None:
+        elif self.boolean != None:
             return("boolean")
-        elif self.relationop is not None and self.topology is not []:
+        elif self.relationop != None and self.topology != []:
             return("operator")
-        elif self.td is not None:
+        elif self.td != None:
             return("timediff")
 
     def get_type_value(self):
@@ -653,10 +640,17 @@
     def __str__(self):
         return str(self.tfunc) + str(self.compop) + str(self.value)
 
+###############################################################################
 
+class FatalError(Exception):
+    def __init__(self, msg):
+        self.value = msg
+
+    def __str__(self):
+        return self.value
+
 ###############################################################################
 
-
 class TemporalAlgebraParser(object):
     """The temporal algebra class"""
 
@@ -665,12 +659,12 @@
 
     # Setting equal precedence level for select and hash operations.
     precedence = (
-        ('left', 'T_SELECT_OPERATOR', 'T_SELECT', 'T_NOT_SELECT'),  # 1
-        ('left', 'AND', 'OR', 'T_COMP_OPERATOR'),  # 2
+        ('left', 'T_SELECT_OPERATOR', 'T_SELECT', 'T_NOT_SELECT'), # 1
+        ('left', 'AND', 'OR', 'T_COMP_OPERATOR'), #2
         )
 
-    def __init__(self, pid=None, run=True, debug=False, spatial=False,
-                 null=False):
+    def __init__(self, pid=None, run = True, debug = False, spatial = False, 
+                        null = False, register_null = False,  nprocs = 1):
         self.run = run
         self.debug = debug
         self.pid = pid
@@ -684,13 +678,17 @@
         self.msgr = get_tgis_message_interface()
         self.dbif = SQLDatabaseInterfaceConnection()
         self.dbif.connect()
+        self.register_null = register_null
+        self.empty_maps = {}
+        self.m_mremove = pymod.Module('g.remove')
+        self.m_copy = pymod.Module('g.copy')
+        self.nprocs = nprocs
 
     def __del__(self):
         if self.dbif.connected:
             self.dbif.close()
 
-    def parse(self, expression, stdstype='strds', basename=None,
-              overwrite=False):
+    def parse(self, expression, stdstype = 'strds', maptype = 'rast',  mapclass = RasterDataset, basename = None, overwrite=False):
         self.lexer = TemporalAlgebraLexer()
         self.lexer.build()
         self.parser = yacc.yacc(module=self, debug=self.debug)
@@ -698,6 +696,8 @@
         self.overwrite = overwrite
         self.count = 0
         self.stdstype = stdstype
+        self.maptype = maptype
+        self.mapclass = mapclass
         self.basename = basename
         self.expression = expression
         self.parser.parse(expression)
@@ -710,18 +710,25 @@
             same object for map name generation in multiple threads.
         """
         self.count += 1
-        if self.pid is not None:
+        if self.pid != None:
             pid = self.pid
         else:
             pid = os.getpid()
-        name = "tmp_map_name_%i_%i" % (pid, self.count)
+        name = "tmp_map_name_%i_%i"%(pid, self.count)
         self.names[name] = name
         return name
 
-    def generate_new_map(self, base_map, bool_op='and', copy=True):
+    def generate_new_map(self, base_map, bool_op = 'and', copy = True,  rename = True):
         """Generate a new map using the spatio-temporal extent of the base map
 
-           :param base_map This map is used to create the new map
+           :param base_map: This map is used to create the new map
+           :param bool_op: The boolean operator specifying the spatial extent
+                  operation (intersection, union, disjoint union)
+           :param copy: Specifies if the temporal extent of mapB should be
+                  copied to mapA
+           :param rename: Specifies if the generated map get a random name or get
+                  the id from the base map.
+           :return: Map object
         """
         # Generate an intermediate name for the result map list.
         name = self.generate_map_name()
@@ -730,12 +737,14 @@
         # Create new map based on the related map list.
         map_new = base_map.get_new_instance(mapname)
         # Set initial map extend of new vector map.
-        self.overlay_map_extent(map_new, base_map, bool_op=bool_op, copy=copy)
-
+        self.overlay_map_extent(map_new, base_map, bool_op = bool_op, copy = copy)
+        if not rename:
+            name = base_map.get_id()
+            map_new.set_id(name)
         return map_new
 
-    def overlay_map_extent(self, mapA, mapB, bool_op=None, temp_op='=',
-                           copy=False):
+    def overlay_map_extent(self, mapA, mapB, bool_op = None, temp_op = 'l',
+                            copy = False):
         """Compute the spatio-temporal extent of two topological related maps
 
            :param mapA: The first map
@@ -743,7 +752,8 @@
            :param bool_op: The boolean operator specifying the spatial extent
                   operation (intersection, union, disjoint union)
            :param temp_op: The temporal operator specifying the temporal
-                  extent operation (intersection, union, disjoint union)
+                  extent operation (intersection, union, disjoint union, right reference)
+                  Left reference is the default temporal extent behaviour.
            :param copy: Specifies if the temporal extent of mapB should be
                   copied to mapA
            :return: 0 if there is no overlay
@@ -757,62 +767,128 @@
             mapA.set_temporal_extent(map_extent_temporal)
             if "cmd_list" in dir(mapB):
                 mapA.cmd_list = mapB.cmd_list
+            if "condition_value" in dir(mapB):
+                mapA.condition_value = mapB.condition_value
         else:
             # Calculate spatial extent for different overlay operations.
             if bool_op == 'and':
                 overlay_ext = mapA.spatial_intersection(mapB)
-                if overlay_ext is not None:
+                if overlay_ext != None:
                     mapA.set_spatial_extent(overlay_ext)
                 else:
                     returncode = 0
             elif bool_op in ['or', 'xor']:
                 overlay_ext = mapA.spatial_union(mapB)
-                if overlay_ext is not None:
+                if overlay_ext != None:
                     mapA.set_spatial_extent(overlay_ext)
                 else:
                     returncode = 0
             elif bool_op == 'disor':
                 overlay_ext = mapA.spatial_disjoint_union(mapB)
-                if overlay_ext is not None:
+                if overlay_ext != None:
                     mapA.set_spatial_extent(overlay_ext)
                 else:
                     returncode = 0
 
             # Calculate temporal extent for different temporal operators.
-            if temp_op == '&':
+            if temp_op == 'i':
                 temp_ext = mapA.temporal_intersection(mapB)
-                if temp_ext is not None:
+                if temp_ext != None:
                     mapA.set_temporal_extent(temp_ext)
                 else:
                     returncode = 0
-            elif temp_op == '|':
+            elif temp_op == 'u':
                 temp_ext = mapA.temporal_union(mapB)
-                if temp_ext is not None:
+                if temp_ext != None:
                     mapA.set_temporal_extent(temp_ext)
                 else:
-                    returncode = 0
-            elif temp_op == '+':
+                    returncode = 0                   
+            elif temp_op == 'd':
                 temp_ext = mapA.temporal_disjoint_union(mapB)
-                if temp_ext is not None:
+                if temp_ext != None:
                     mapA.set_temporal_extent(temp_ext)
                 else:
                     returncode = 0
-
+            elif temp_op == 'r':
+                temp_ext = mapB.get_temporal_extent()
+                if temp_ext != None:
+                    mapA.set_temporal_extent(temp_ext)
+                else:
+                    returncode = 0 
         return(returncode)
 
+    def set_temporal_extent_list(self, maplist, topolist = ["EQUAL"], temporal = 'l' ):
+        """ Change temporal extent of map list based on temporal relations to 
+                other map list and given temporal operator.
+
+            :param maplist: List of map objects for which relations has been build 
+                                        correctely.
+            :param topolist: List of strings of temporal relations.
+            :param temporal: The temporal operator specifying the temporal
+                                            extent operation (intersection, union, disjoint 
+                                            union, right reference, left reference).
+
+            :return: Map list with specified temporal extent.
+        """
+        resultdict = {}
+        
+        for map_i in maplist:
+            # Loop over temporal related maps and create overlay modules.
+            tbrelations = map_i.get_temporal_relations()
+            # Generate an intermediate map for the result map list.
+            map_new = self.generate_new_map(base_map=map_i, bool_op = 'and', 
+                                                                        copy = True,  rename = True)
+            # Combine temporal and spatial extents of intermediate map with related maps.
+            for topo in topolist:
+                if topo in tbrelations.keys():
+                    for map_j in (tbrelations[topo]):
+                        if temporal == 'r':
+                            # Generate an intermediate map for the result map list.
+                            map_new = self.generate_new_map(base_map=map_i, bool_op = 'and', 
+                                                                                        copy = True,  rename = True)
+                        # Create overlayed map extent.
+                        returncode = self.overlay_map_extent(map_new, map_j, 'and', \
+                                                                temp_op = temporal)
+                        # Stop the loop if no temporal or spatial relationship exist.
+                        if returncode == 0:
+                            break
+                        # Append map to result map list.
+                        elif returncode == 1:
+                            print(map_new.get_id() + " " + str(map_new.get_temporal_extent_as_tuple()))
+                            print(map_new.condition_value)
+                            # print(map_new.cmd_list)
+                            # resultlist.append(map_new)
+                            resultdict[map_new.get_id()] = map_new
+        
+                        # Create r.mapcalc expression string for the operation.
+                        #cmdstring = self.build_command_string(s_expr_a = map_new,  
+                        #                                                                s_expr_b = map_j,  
+                        #                                                                operator = function)
+                        # Conditional append of module command.
+                        #map_new.cmd_list = cmdstring
+                    if returncode == 0:
+                        break
+            # Append map to result map list.
+            #if returncode == 1:
+            #    resultlist.append(map_new)
+        # Get sorted map objects as values from result dictionoary.
+        resultlist = resultdict.values()
+        resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
+        
+        return(resultlist)
+    
     ######################### Temporal functions ##############################
 
-    def check_stds(self, input, clear=False):
-        """Check if input space time dataset exist in database and return its
-           map list.
+    def check_stds(self, input, clear = False):
+        """ Check if input space time dataset exist in database and return its map list.
 
-           :param input: Name of space time data set as string or list of maps.
-           :param clear: Reset the stored conditional values to empty list.
+            :param input: Name of space time data set as string or list of maps.
+            :param clear: Reset the stored conditional values to empty list.
 
-           :return: List of maps.
+            :return: List of maps.
 
         """
-        if not isinstance(input, list):
+        if isinstance(input, str):
             # Check for mapset in given stds input.
             if input.find("@") >= 0:
                 id_input = input
@@ -821,10 +897,9 @@
             # Create empty spacetime dataset.
             stds = dataset_factory(self.stdstype, id_input)
             # Check for occurence of space time dataset.
-            if stds.is_in_db(dbif=self.dbif) is False:
+            if stds.is_in_db(dbif=self.dbif) == False:
                 raise FatalError(_("Space time %s dataset <%s> not found") %
-                                 (stds.get_new_map_instance(None).get_type(),
-                                  id_input))
+                    (stds.get_new_map_instance(None).get_type(), id_input))
             else:
                 # Select temporal dataset entry from database.
                 stds.select(dbif=self.dbif)
@@ -836,20 +911,23 @@
                     if "condition_value" not in dir(map_i):
                         map_i.condition_value = []
                     # Set and check global temporal type variable and map.
-                    if map_i.is_time_absolute() and self.temporaltype is None:
+                    if map_i.is_time_absolute() and self.temporaltype == None:
                         self.temporaltype = 'absolute'
-                    elif map_i.is_time_relative() and self.temporaltype is None:
+                    elif map_i.is_time_relative() and self.temporaltype == None:
                         self.temporaltype = 'relative'
                     elif map_i.is_time_absolute() and self.temporaltype == 'relative':
-                        self.msgr.fatal(_("Wrong temporal type of space time"
-                                          " dataset <%s> <%s> time is required") %
-                                        (id_input, self.temporaltype))
+                        self.msgr.fatal(_("Wrong temporal type of space time dataset <%s> \
+                                      <%s> time is required") %
+                                     (id_input, self.temporaltype))
                     elif map_i.is_time_relative() and self.temporaltype == 'absolute':
-                        self.msgr.fatal(_("Wrong temporal type of space time"
-                                          " dataset <%s> <%s> time is required") %
-                                        (id_input, self.temporaltype))
-
-        else:
+                        self.msgr.fatal(_("Wrong temporal type of space time dataset <%s> \
+                                      <%s> time is required") %
+                                     (id_input, self.temporaltype))
+        elif isinstance(input,  self.mapclass):
+            # Check if the input is a single map and return it as list with one entry.
+            maplist = [input]
+        
+        elif isinstance(input,  list):
             maplist = input
             # Create map_value as empty list item.
             for map_i in maplist:
@@ -861,25 +939,31 @@
                     map_i.condition_value = []
                 elif clear:
                     map_i.condition_value = []
-
+        else:
+            self.msgr.fatal(_("Wrong type of input"))
+        
         return(maplist)
 
-    def get_temporal_topo_list(self, maplistA, maplistB=None,
-                               topolist=["EQUAL"], assign_val=False,
-                               count_map=False):
+    def get_temporal_topo_list(self, maplistA, maplistB = None, topolist = ["EQUAL"],
+                               assign_val = False, count_map = False, compare_bool = False,  
+                               compop = None, aggregate = None):
         """Build temporal topology for two space time data sets, copy map objects
           for given relation into map list.
-
           :param maplistA: List of maps.
           :param maplistB: List of maps.
           :param topolist: List of strings of temporal relations.
           :param assign_val: Boolean for assigning a boolean map value based on
-                             the map_values from the compared map list by
-                             topological relationships.
+                            the map_values from the compared map list by
+                            topological relationships.
           :param count_map: Boolean if the number of topological related maps
-                            should be returned.
-          :return: List of maps from maplistA that fulfil the topological
-                   relationships to maplistB specified in topolist.
+                           should be returned.
+          :param compare_bool: Boolean for comparing boolean map values based on
+                            related map list and compariosn operator.
+          :param compop: Comparison operator, && or ||.
+          :param aggregate: Aggregation operator for relation map list, & or |.
+          
+          :return: List of maps from maplistA that fulfil the topological relationships
+                  to maplistB specified in topolist.
 
           .. code-block:: python
 
@@ -1003,55 +1087,40 @@
               ...     print(map.get_id())
 
         """
-        topologylist = ["EQUAL", "FOLLOWS", "PRECEDES", "OVERLAPS",
-                        "OVERLAPPED", "DURING", "STARTS", "FINISHES",
-                        "CONTAINS", "STARTED", "FINISHED"]
-        complementdict = {"EQUAL": "EQUAL", "FOLLOWS": "PRECEDES",
-                          "PRECEDES": "FOLLOWS", "OVERLAPS": "OVERLAPPED",
-                          "OVERLAPPED": "OVERLAPS", "DURING": "CONTAINS",
-                          "CONTAINS": "DURING", "STARTS": "STARTED",
-                          "STARTED": "STARTS", "FINISHES": "FINISHED",
-                          "FINISHED": "FINISHES"}
+        topologylist = ["EQUAL", "FOLLOWS", "PRECEDES", "OVERLAPS", "OVERLAPPED", \
+                        "DURING", "STARTS", "FINISHES", "CONTAINS", "STARTED", \
+                        "FINISHED"]
+        complementdict = {"EQUAL": "EQUAL", "FOLLOWS" : "PRECEDES",
+                          "PRECEDES" : "FOLLOWS", "OVERLAPS" : "OVERLAPPED",
+                          "OVERLAPPED" : "OVERLAPS", "DURING" : "CONTAINS",
+                          "CONTAINS" : "DURING", "STARTS" : "STARTED",
+                          "STARTED" : "STARTS", "FINISHES" : "FINISHED",
+                          "FINISHED" : "FINISHES"}
         resultdict = {}
         # Check if given temporal relation are valid.
         for topo in topolist:
-            if topo.upper() not in topologylist:
-                raise SyntaxError("Unpermitted temporal relation name '" +
-                                  topo + "'")
+          if topo.upper() not in topologylist:
+              raise SyntaxError("Unpermitted temporal relation name '" + topo + "'")
 
         # Create temporal topology for maplistA to maplistB.
         tb = SpatioTemporalTopologyBuilder()
-        # Dictionary with different spatial variables used for topology builder
-        spatialdict = {'strds': '2D', 'stvds': '2D', 'str3ds': '3D'}
+        # Dictionary with different spatial variables used for topology builder.
+        spatialdict = {'strds' : '2D', 'stvds' : '2D', 'str3ds' : '3D'}
         # Build spatial temporal topology
         if self.spatial:
-            tb.build(maplistA, maplistB, spatial=spatialdict[self.stdstype])
+            tb.build(maplistA, maplistB, spatial = spatialdict[self.stdstype])
         else:
             tb.build(maplistA, maplistB)
         # Iterate through maps in maplistA and search for relationships given
         # in topolist.
-        # TODO: Better implementation with less nesting
         for map_i in maplistA:
             tbrelations = map_i.get_temporal_relations()
+            if assign_val:
+                self.assign_bool_value(map_i,  tbrelations,  topolist)
+            elif compare_bool:
+                self.compare_bool_value(map_i,  tbrelations, compop, aggregate, topolist)
             for topo in topolist:
                 if topo.upper() in tbrelations.keys():
-                    if assign_val:
-                        mapvaluelist = []
-                        if complementdict[topo.upper()] in tbrelations:
-                            relationmaplist = tbrelations[complementdict[topo.upper()]]
-                            for relationmap in relationmaplist:
-                                if "map_value" in dir(relationmap):
-                                    for element in relationmap.map_value:
-                                        if isinstance(element, GlobalTemporalVar):
-                                            if element.get_type() == "boolean":
-                                                mapvaluelist.append(element.boolean)
-                        if all(mapvaluelist):
-                            resultbool = True
-                        else:
-                            resultbool = False
-                        if "condition_value" in dir(map_i):
-                            if isinstance(map_i.condition_value, list):
-                                map_i.condition_value.append(resultbool)
                     if count_map:
                         relationmaplist = tbrelations[topo.upper()]
                         gvar = GlobalTemporalVar()
@@ -1062,137 +1131,129 @@
                             map_i.map_value = gvar
                     resultdict[map_i.get_id()] = map_i
         resultlist = resultdict.values()
-
+        
         # Sort list of maps chronological.
-        resultlist = sorted(resultlist,
-                            key=AbstractDatasetComparisonKeyStartTime)
-
+        resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
+        
         return(resultlist)
+    
+    def assign_bool_value(self,  map_i, tbrelations, topolist = ["EQUAL"]):
+        """ Function to assign boolean map value based on the map_values from the 
+                compared map list by topological relationships.
+          :param map_i: Map object with temporal extent.
+          :param tbrelations: List of temporal relation to map_i.
+          :param topolist: List of strings for given temporal relations.
+          
+          :return: Map object with conditional value that has been assigned by 
+                        relation maps that fulfil the topological relationships to 
+                        maplistB specified in topolist.
+        """
+        condition_value_list = []
+        for topo in topolist:
+            if topo.upper() in tbrelations.keys():
+                #relationmaplist = tbrelations[complementdict[topo.upper()]]
+                relationmaplist = tbrelations[topo.upper()]
+                for relationmap in relationmaplist:
+                    for boolean in relationmap.condition_value:
+                        if isinstance(boolean, bool):
+                            condition_value_list.append(boolean)
+                    print(str(relationmap.get_temporal_extent_as_tuple()) + str(boolean))
+        if all(condition_value_list):
+            resultbool = True
+        else:
+            resultbool = False
+        map_i.condition_value = [resultbool]
+        
+        return(resultbool)
 
-    def eval_toperator(self, operator):
+    def compare_bool_value(self,  map_i, tbrelations, compop, aggregate,  topolist = ["EQUAL"]):
+        """ Function to evaluate two map lists with boolean values by boolean 
+            comparison operator. 
+          :param map_i: Map object with temporal extent.
+          :param tbrelations: List of temporal relation to map_i.
+          :param topolist: List of strings for given temporal relations.
+          :param compop: Comparison operator, && or ||.
+          :param aggregate: Aggregation operator for relation map list, & or |.
+          
+          :return: Map object with conditional value that has been evaluated by
+                        comparison operators.
+        """
+        # Build conditional list with elements from related maps and given relation operator.
+        leftbool = map_i.condition_value[0]
+        condition_value_list = [leftbool]
+        count = 0
+        for topo in topolist:
+            if topo.upper() in tbrelations.keys():
+                relationmaplist = tbrelations[topo.upper()]
+                if count == 0:
+                    condition_value_list.append(compop[0])
+                    condition_value_list.append('(')
+                for relationmap in relationmaplist:
+                    for boolean in relationmap.condition_value:
+                        if isinstance(boolean, bool):
+                            if count > 0:
+                                condition_value_list.append(aggregate)
+                            condition_value_list.append(boolean)
+                            count = count + 1
+        if count > 0:
+            condition_value_list.append(')')
+        # Convert conditional list to concatenated string and evaluate booleans.
+        condition_value_str = ''.join(map(str, condition_value_list))
+        print(condition_value_str)
+        resultbool = eval(condition_value_str)
+        print(resultbool)
+        # Add boolean value to result list.
+        map_i.condition_value = [resultbool]
+        
+        return(resultbool)
+    
+    def eval_toperator(self, operator, optype = 'relation'):
         """This function evaluates a string containing temporal operations.
 
-          :param operator: String of temporal operations, e.g. {equal|during,=!:}.
+         :param operator: String of temporal operations, e.g. {!=,equal|during,l}.
+         :param optype: String to define operator type.
+         
+         :return :List of temporal relations (equal, during), the given function
+          (!:) and the interval/instances (l).
+          
+        .. code-block:: python
+        
+             >>> import grass.temporal as tgis
+             >>> tgis.init()
+             >>> p = tgis.TemporalOperatorParser()
+             >>> operator = "{+, during}"
+             >>> p.parse(operator, optype = 'raster')
+             >>> print(p.relations, p.temporal, p.function)
+             (['during'], 'l', '+')
 
-          :return: List of temporal relations (equal, during), the given
-                   function (!:) and the interval/instances (=).
 
-          .. code-block:: python
-
-              >>> import grass.temporal as tgis
-              >>> tgis.init()
-              >>> p = tgis.TemporalAlgebraParser()
-              >>> operator = "{equal,:}"
-              >>> p.eval_toperator(operator)
-              (['equal'], '=', ':')
-              >>> operator = "{equal|during,:}"
-              >>> p.eval_toperator(operator)
-              (['equal', 'during'], '=', ':')
-              >>> operator = "{equal,!:}"
-              >>> p.eval_toperator(operator)
-              (['equal'], '=', '!:')
-              >>> operator = "{equal|during,!:}"
-              >>> p.eval_toperator(operator)
-              (['equal', 'during'], '=', '!:')
-              >>> operator = "{equal|during,=!:}"
-              >>> p.eval_toperator(operator)
-              (['equal', 'during'], '=', '!:')
-              >>> operator = "{equal|during|starts,#}"
-              >>> p.eval_toperator(operator)
-              (['equal', 'during', 'starts'], '=', '#')
-              >>> operator = "{!:}"
-              >>> p.eval_toperator(operator)
-              (['equal'], '=', '!:')
-              >>> operator = "{=:}"
-              >>> p.eval_toperator(operator)
-              (['equal'], '=', ':')
-              >>> operator = "{#}"
-              >>> p.eval_toperator(operator)
-              (['equal'], '=', '#')
-              >>> operator = "{equal|during}"
-              >>> p.eval_toperator(operator)
-              (['equal', 'during'], '=', '')
-              >>> operator = "{equal}"
-              >>> p.eval_toperator(operator)
-              (['equal'], '=', '')
-              >>> operator = "{equal,||}"
-              >>> p.eval_toperator(operator)
-              (['equal'], '=', '||')
-              >>> operator = "{equal|during,&&}"
-              >>> p.eval_toperator(operator)
-              (['equal', 'during'], '=', '&&')
-
         """
-        topologylist = ["EQUAL", "FOLLOWS", "PRECEDES", "OVERLAPS",
-                        "OVERLAPPED", "DURING", "STARTS", "FINISHES",
-                        "CONTAINS", "STARTED", "FINISHED"]
-        functionlist = [":", "!:", "#"]
-        intervallist = ["=", "|", "&", "+"]
-        comparelist = ["||", "&&"]
-        relations = []
-        interval = '='
-        function = ''
-        op = operator.strip('{}')
-        oplist = op.split(',')
-        if len(oplist) > 1:
-            relationlist = oplist[0].split('|')
-            for relation in relationlist:
-                if relation.upper() in topologylist and relation not in relations:
-                    relations.append(relation)
-                else:
-                    raise SyntaxError("invalid syntax")
-            opright = oplist[1]
-            if opright in comparelist:
-                function = opright
-            elif opright[0] in intervallist:
-                interval = opright[0]
-                if opright[1:] in functionlist:
-                    function = opright[1:]
-                else:
-                    raise SyntaxError("invalid syntax")
-            elif opright in functionlist:
-                function = opright
-            else:
-                raise SyntaxError("invalid syntax")
-        elif all([rel.upper() in topologylist for rel in oplist[0].split('|')]):
-            relations = oplist[0].split('|')
-        else:
-            relations = ['equal']
-            opstr = str(oplist[0])
-            if opstr[0] in intervallist:
-                interval = opstr[0]
-                if opstr[1:] in functionlist:
-                    function = opstr[1:]
-                else:
-                    raise SyntaxError("invalid syntax")
-            elif opstr in functionlist:
-                function = opstr
-            #else:
-                #raise SyntaxError("invalid syntax")
+        p = TemporalOperatorParser()
+        p.parse(operator, optype)
+        p.relations = [rel.upper() for rel in p.relations]
+        
+        return(p.relations, p.temporal, p.function,  p.aggregate)
 
-        return(relations, interval, function)
-
-    def perform_temporal_selection(self, maplistA, maplistB,
-                                   topolist=["EQUAL"],
-                                   inverse=False, assign_val=False):
+    def perform_temporal_selection(self, maplistA, maplistB, topolist = ["EQUAL"],
+                                   inverse = False, assign_val = False):
         """This function performs temporal selection operation.
 
-          :param maplistA: List of maps representing the left side of a
-                           temporal expression.
-          :param maplistB: List of maps representing the right side of a
-                           temporal expression.
+          :param maplistA:   List of maps representing the left side of a temporal
+                             expression.
+          :param maplistB:   List of maps representing the right side of a temporal
+                             expression.
           :param topolist: List of strings of temporal relations.
-          :param inverse: Boolean value that specifies if the selection
-                          should be inverted.
+          :param inverse: Boolean value that specifies if the selection should be
+                             inverted.
           :param assign_val: Boolean for assigning a boolean map value based on
-                             the map_values from the compared map list by
-                             topological relationships.
+                            the map_values from the compared map list by
+                            topological relationships.
 
           :return: List of selected maps from maplistA.
 
           .. code-block:: python
 
-          >>> import grass.temporal as tgis
+              >>> import grass.temporal as tgis
               >>> tgis.init()
               >>> l = tgis.TemporalAlgebraParser()
               >>> # Example with two lists of maps
@@ -1233,127 +1294,133 @@
 
         """
         if not inverse:
-            topolist = self.get_temporal_topo_list(maplistA, maplistB,
-                                                   topolist,
-                                                   assign_val=assign_val)
+            topolist = self.get_temporal_topo_list(maplistA, maplistB, topolist,
+                                                    assign_val = assign_val)
             resultlist = topolist
 
         else:
-            topolist = self.get_temporal_topo_list(maplistA, maplistB,
-                                                   topolist, assign_val=False)
+            topolist = self.get_temporal_topo_list(maplistA, maplistB, topolist,
+                                                    assign_val = assign_val)
             resultlist = []
-
             for map_i in maplistA:
                 if map_i not in topolist:
                     resultlist.append(map_i)
-                    if assign_val:
-                        if "condition_value" in dir(map_i):
-                            map_i.condition_value.append(False)
+                    #if assign_val:
+                    #   if "condition_value" in dir(map_i):
+                    #        map_i.condition_value.append(False)
 
         # Sort list of maps chronological.
-        resultlist = sorted(resultlist,
-                            key=AbstractDatasetComparisonKeyStartTime)
-
+        resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
         return(resultlist)
 
-    def set_granularity(self, maplistA, maplistB, toperator='=',
-                        topolist=["EQUAL"]):
+    def set_granularity(self, maplistA, maplistB, toperator = 'l', topolist = ["EQUAL"]):
         """This function sets the temporal extends of a list of maps based on
-        another map list.
+             another map list.
 
-        :param maplistB: List of maps.
-        :param maplistB: List of maps.
-        :param toperator: String containing the temporal operator: =, +, &, \|.
-        :param topolist: List of topological relations.
+          :param maplistB: List of maps.
+          :param maplistB: List of maps.
+          :param toperator: String containing the temporal operator: l, r, d, i, u.
+          :param topolist: List of topological relations.
 
-        :return: List of maps with the new temporal extends.
+          :return: List of maps with the new temporal extends.
 
-        .. code-block:: python
+          .. code-block:: python
 
-            >>> import grass.temporal as tgis
-            >>> tgis.init()
-            >>> p = tgis.TemporalAlgebraParser()
-            >>> # Create two list of maps with equal time stamps
-            >>> mapsA = []
-            >>> mapsB = []
-            >>> for i in range(10):
-            ...     idA = "a%i at B"%(i)
-            ...     mapA = tgis.RasterDataset(idA)
-            ...     idB = "b%i at B"%(i)
-            ...     mapB = tgis.RasterDataset(idB)
-            ...     check = mapA.set_relative_time(i, i + 1, "months")
-            ...     check = mapB.set_relative_time(i*2, i*2 + 2, "months")
-            ...     mapsA.append(mapA)
-            ...     mapsB.append(mapB)
-            >>> resultlist = p.set_granularity(mapsA, mapsB, toperator = "|", topolist = ["during"])
-            >>> for map in resultlist:
-            ...     start,end,unit = map.get_relative_time()
-            ...     print(map.get_id() + ' - start: ' + str(start) + ' end: ' + str(end))
-            a1 at B - start: 0 end: 2
-            a0 at B - start: 0 end: 2
-            a3 at B - start: 2 end: 4
-            a2 at B - start: 2 end: 4
-            a5 at B - start: 4 end: 6
-            a4 at B - start: 4 end: 6
-            a7 at B - start: 6 end: 8
-            a6 at B - start: 6 end: 8
-            a9 at B - start: 8 end: 10
-            a8 at B - start: 8 end: 10
+              >>> import grass.temporal as tgis
+              >>> tgis.init()
+              >>> p = tgis.TemporalAlgebraParser()
+              >>> # Create two list of maps with equal time stamps
+              >>> mapsA = []
+              >>> mapsB = []
+              >>> for i in range(10):
+              ...     idA = "a%i at B"%(i)
+              ...     mapA = tgis.RasterDataset(idA)
+              ...     idB = "b%i at B"%(i)
+              ...     mapB = tgis.RasterDataset(idB)
+              ...     check = mapA.set_relative_time(i, i + 1, "months")
+              ...     check = mapB.set_relative_time(i*2, i*2 + 2, "months")
+              ...     mapsA.append(mapA)
+              ...     mapsB.append(mapB)
+              >>> resultlist = p.set_granularity(mapsA, mapsB, toperator = "u", topolist = ["during"])
+              >>> for map in resultlist:
+              ...     start,end,unit = map.get_relative_time()
+              ...     print(map.get_id() + ' - start: ' + str(start) + ' end: ' + str(end))
+              a1 at B - start: 0 end: 2
+              a0 at B - start: 0 end: 2
+              a3 at B - start: 2 end: 4
+              a2 at B - start: 2 end: 4
+              a5 at B - start: 4 end: 6
+              a4 at B - start: 4 end: 6
+              a7 at B - start: 6 end: 8
+              a6 at B - start: 6 end: 8
+              a9 at B - start: 8 end: 10
+              a8 at B - start: 8 end: 10
 
         """
-        topologylist = ["EQUAL", "FOLLOWS", "PRECEDES", "OVERLAPS",
-                        "OVERLAPPED", "DURING", "STARTS", "FINISHES",
-                        "CONTAINS", "STARTED", "FINISHED"]
+        topologylist = ["EQUAL", "FOLLOWS", "PRECEDES", "OVERLAPS", "OVERLAPPED", \
+                        "DURING", "STARTS", "FINISHES", "CONTAINS", "STARTED", \
+                        "FINISHED"]
 
         for topo in topolist:
-            if topo.upper() not in topologylist:
-                raise SyntaxError("Unpermitted temporal relation name '" +
-                                  topo + "'")
+          if topo.upper() not in topologylist:
+              raise SyntaxError("Unpermitted temporal relation name '" + topo + "'")
 
         # Create temporal topology for maplistA to maplistB.
         tb = SpatioTemporalTopologyBuilder()
-        # Dictionary with different spatial variables used for topology builder
-        spatialdict = {'strds': '2D', 'stvds': '2D', 'str3ds': '3D'}
+        # Dictionary with different spatial variables used for topology builder.
+        spatialdict = {'strds' : '2D', 'stvds' : '2D', 'str3ds' : '3D'}
         # Build spatial temporal topology for maplistB to maplistB.
         if self.spatial:
-            tb.build(maplistA, maplistB, spatial=spatialdict[self.stdstype])
+            tb.build(maplistA, maplistB, spatial = spatialdict[self.stdstype])
         else:
             tb.build(maplistA, maplistB)
         resultdict = {}
+
         # Iterate through maps in maplistA and search for relationships given
         # in topolist.
         for map_i in maplistA:
             tbrelations = map_i.get_temporal_relations()
+            map_extent = map_i.get_temporal_extent()
+            map_start = map_extent.get_start_time()
+            map_end = map_extent.get_end_time()
+            unchanged = True
             for topo in topolist:
                 if topo.upper() in tbrelations.keys():
                     relationmaplist = tbrelations[topo.upper()]
                     for relationmap in relationmaplist:
-                        newextend = None
-                        if toperator == "&":
-                            newextend = map_i.temporal_intersection(relationmap)
-                        elif toperator == "|":
-                            newextend = map_i.temporal_union(relationmap)
-                        elif toperator == "+":
-                            newextend = map_i.temporal_disjoint_union(relationmap)
-                        elif toperator == "=":
-                            resultdict[map_i.get_id()] = map_i
-
-                        if newextend is not None:
-                            start = newextend.get_start_time()
-                            end = newextend.get_end_time()
+                        newextent = None
+                        if toperator == "i":
+                            newextent = map_i.temporal_intersection(relationmap)
+                        elif toperator == "u":
+                            newextent = map_i.temporal_union(relationmap)
+                        elif toperator == "d":
+                            newextent = map_i.temporal_disjoint_union(relationmap)
+                        elif toperator == "l":
+                            newextent = map_i.get_temporal_extent()
+                        elif toperator == "r":
+                            newextent = relationmap.get_temporal_extent()
+                        if newextent != None:
+                            start = newextent.get_start_time()
+                            end = newextent.get_end_time()
                             #print(map_i.get_id() + ' - start: ' + str(start) + ' end: ' + str(end))
+                            # Track changes in temporal extents of maps.
+                            if map_start != start or map_end != end :
+                                unchanged = False
                             if map_i.is_time_absolute():
                                 map_i.set_absolute_time(start, end)
                             else:
                                 relunit = map_i.get_relative_time_unit()
-                                map_i.set_relative_time(int(start), int(end),
-                                                        relunit)
+                                map_i.set_relative_time(int(start), int(end), relunit)
                             resultdict[map_i.get_id()] = map_i
-
+                else:
+                    print('Topologic relation: ' + topo.upper() + ' not found.')
+                    resultdict[map_i.get_id()] = map_i
+            if unchanged == True:
+                print('Leave temporal extend of result map: ' +  map_i.get_map_id() + ' unchanged.')
+        
         resultlist = resultdict.values()
         # Sort list of maps chronological.
-        resultlist = sorted(resultlist,
-                            key=AbstractDatasetComparisonKeyStartTime)
+        resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
         # Get relations to maplistB per map in A.
         # Loop over all relations from list
         # temporal extent = map.temporal_intersection(map)
@@ -1363,14 +1430,14 @@
 
     def get_temporal_func_dict(self, map):
         """ This function creates a dictionary containing temporal functions for a
-          map dataset with time stamp.
+             map dataset with time stamp.
 
           :param map: Map object with time stamps.
 
           :return: Dictionary with temporal functions for given input map.
 
           .. code-block:: python
-
+          
               >>> import grass.temporal as tgis
               >>> import datetime
               >>> tgis.init()
@@ -1392,17 +1459,15 @@
               >>> print(tfuncdict["START_DATETIME"])
               2000-01-01 00:00:00
 
-
         """
-        tvardict = {"START_DOY": None, "START_DOW": None, "START_YEAR": None,
-                    "START_MONTH": None, "START_WEEK": None, "START_DAY": None,
-                    "START_HOUR": None, "START_MINUTE": None,
-                    "START_SECOND": None, "END_DOY": None, "END_DOW": None,
-                    "END_YEAR": None, "END_MONTH": None, "END_WEEK": None,
-                    "END_DAY": None, "END_HOUR": None, "END_MINUTE": None,
-                    "END_SECOND": None, "START_DATE": None,
-                    "START_DATETIME": None, "START_TIME": None,
-                    "END_DATE": None, "END_DATETIME": None, "END_TIME": None}
+        tvardict = {"START_DOY" : None, "START_DOW" : None, "START_YEAR" : None,
+            "START_MONTH" : None, "START_WEEK" : None, "START_DAY" : None,
+            "START_HOUR" : None, "START_MINUTE" : None, "START_SECOND" : None,
+            "END_DOY" : None, "END_DOW" : None, "END_YEAR" : None,
+            "END_MONTH" : None, "END_WEEK" : None, "END_DAY" : None,
+            "END_HOUR" : None, "END_MINUTE" : None, "END_SECOND" : None,
+            "START_DATE" : None, "START_DATETIME" : None, "START_TIME" : None,
+            "END_DATE" : None, "END_DATETIME" : None, "END_TIME" : None}
 
         # Compute temporal function only for maps with absolute time reference.
         if map.is_time_absolute:
@@ -1447,7 +1512,8 @@
             tvardict["END_DATE"]       = end.date()
             tvardict["END_DATETIME"]   = end
             tvardict["END_TIME"]       = end.time()
-
+            #core.fatal(_("The temporal functions for map <%s> only supported for absolute"\
+                #          "time." % (str(map.get_id()))))
         return(tvardict)
 
     def eval_datetime_str(self, tfuncval, comp, value):
@@ -1471,12 +1537,12 @@
         """ This function evaluates a global variable expression for a map list.
              For example: start_day() > 5 , end_month() == 2.
 
-          :param gvar:    Object of type GlobalTemporalVar containing temporal.
+          :param gvar: Object of type GlobalTemporalVar containing temporal.
           :param maplist: List of map objects.
 
-          :return: List of maps from maplist with added conditional boolean
-                   values.
+          :return: List of maps from maplist with added conditional boolean values.
         """
+        boollist = []
         # Loop over maps of input map list.
         for map_i in maplist:
             # Get dictionary with temporal variables for the map.
@@ -1491,18 +1557,15 @@
             tfuncval = tfuncdict[tfunc]
             # Check if value has to be transfered to datetime object for comparison.
             if tfunc in ["START_DATE", "END_DATE"]:
-                timeobj = datetime.strptime(value.replace("\"", ""),
-                                            '%Y-%m-%d')
+                timeobj = datetime.strptime(value.replace("\"",""), '%Y-%m-%d')
                 value = timeobj.date()
                 boolname = self.eval_datetime_str(tfuncval, comp_op, value)
             elif tfunc in ["START_TIME", "END_TIME"]:
-                timeobj = datetime.strptime(value.replace("\"", ""),
-                                            '%H:%M:%S')
+                timeobj = datetime.strptime(value.replace("\"",""), '%H:%M:%S')
                 value = timeobj.time()
                 boolname = self.eval_datetime_str(tfuncval, comp_op, value)
             elif tfunc in ["START_DATETIME", "END_DATETIME"]:
-                timeobj = datetime.strptime(value.replace("\"", ""),
-                                            '%Y-%m-%d %H:%M:%S')
+                timeobj = datetime.strptime(value.replace("\"",""), '%Y-%m-%d %H:%M:%S')
                 value = timeobj
                 boolname = self.eval_datetime_str(tfuncval, comp_op, value)
             else:
@@ -1512,150 +1575,103 @@
                 map_i.condition_value.append(boolname)
             else:
                 map_i.condition_value = boolname
-
         return(maplist)
 
-    def eval_map_list(self, maplist, thenlist, topolist=["EQUAL"]):
+    def eval_map_list(self, maplist ,thenlist, topolist = ["EQUAL"]):
         """ This function transfers boolean values from temporal expression
-            from one map list to another by their topology. These boolean
-            values are added to the maps as condition_value.
+             from one map list to another by their topology. These boolean
+             values are added to the maps as condition_value.
 
-            :param maplist:  List of map objects containing boolean map values.
-            :param thenlist: List of map objects where the boolean values
-                      should be added.
+          :param maplist:  List of map objects containing boolean map values.
+          :param thenlist: List of map objects where the boolean values
+                          should be added.
 
-            :return: List of maps from thenlist with added conditional boolean
-                     values.
+          :return: List of maps from thenlist with added conditional boolean values.
         """
-        # Get topology of then statement map list in relation to the other
-        # maplist and assign boolean values of the maplist to the thenlist.
+        # Get topology of then statement map list in relation to the other maplist
+        # and assign boolean values of the maplist to the thenlist.
         containlist = self.perform_temporal_selection(thenlist, maplist,
-                                                      assign_val=True,
-                                                      topolist=topolist)
+                                                        assign_val = True,
+                                                        topolist = topolist)
         # Inverse selection of maps from thenlist and assigning False values.
-        excludelist = self.perform_temporal_selection(thenlist, maplist,
-                                                      assign_val=True,
-                                                      inverse=True,
-                                                      topolist=topolist)
+        #excludelist = self.perform_temporal_selection(thenlist, maplist,
+         #                                               assign_val = True,
+          #                                              inverse = True,
+          #                                              topolist = topolist)
         # Combining the selection and inverse selection list.
-        resultlist = containlist + excludelist
+        resultlist = containlist# + excludelist
 
         return(resultlist)
 
-    def build_condition_list(self, tvarexpr, thenlist, topolist=["EQUAL"]):
-        """This function evaluates temporal variable expressions of a
-           conditional expression related to the map list of the then statement.
-           Global variables or map lists with booleans are compared to the
-           topology of the conclusion map list and a conditional list will be
-           appended to every map. It contain the boolean expressions from
-           these comparisons and optional operators to combine several
-           temporal expressions, like "&&" or "||".
+    def build_condition_list(self, tvarexpr, thenlist,  topolist = ["EQUAL"]):
+        """ This function evaluates temporal variable expressions of a conditional
+             expression in two steps.
+             At first it combines stepwise the single conditions by their relations with LALR.
+             In this prossess sub condition map lists will be created which will include 
+             information of the underlying single conditions. Important: The temporal 
+             relations between conditions are evaluated by implicit aggregation. 
+             In the second step the aggregated condition map list will be compared with the 
+             map list of conclusion statements by the given temporal relation.
+             
+             The result is writen as 'condition_value' attribute to the resulting map objects. 
+             These attribute consists of boolean expressions and operators which can be 
+             evaluated with the eval_condition_list function.
+             [True,  '||', False, '&&', True]
 
-           For example: td(A) == 1 && start_day() > 5 --> [True || False]
+             For example: td(A) == 1 && start_day() > 5 --> [True || False]
                           (for one map.condition_value in a then map list)
 
-           :param tvarexpr: List of GlobalTemporalVar objects and map lists.
-                            The list is constructed by the TemporalAlgebraParser
-                            in order of expression evaluation in the parser.
+             :param tvarexpr List of GlobalTemporalVar objects and map lists.
+                         The list is constructed by the TemporalAlgebraParser
+                         in order of expression evaluation in the parser.
 
-           :param thenlist: Map list object of the conclusion statement.
-                            It will be compared and evaluated by the conditions.
+             :param thenlist Map list object of the conclusion statement.
+                         It will be compared and evaluated by the conditions.
+          
+             :param topolist List of temporal relations between the conditions and the 
+                         conclusions.
+                          
+             :return: Map list with conditional values for all temporal expressions.
 
-           :return: Map list with conditional values for all temporal expressions.
-
-           .. code-block:: python
-
-               >>> import grass.temporal as tgis
-               >>> tgis.init()
-               >>> p = tgis.TemporalAlgebraParser()
-               >>> # Example with two lists of maps
-               >>> # Create two list of maps with equal time stamps
-               >>> mapsA = []
-               >>> mapsB = []
-               >>> for i in range(10):
-               ...     idA = "a%i at B"%(i)
-               ...     mapA = tgis.RasterDataset(idA)
-               ...     idB = "b%i at B"%(i)
-               ...     mapB = tgis.RasterDataset(idB)
-               ...     check = mapA.set_absolute_time(datetime(2000,1,i + 1),
-               ...             datetime(2000,1,i + 2))
-               ...     check = mapB.set_absolute_time(datetime(2000,1,i + 6),
-               ...             datetime(2000,1,i + 7))
-               ...     mapsA.append(mapA)
-               ...     mapsB.append(mapB)
-               >>> mapsA = p.check_stds(mapsA)
-               >>> mapsB = p.check_stds(mapsB)
-               >>> # Create global expression object.
-               >>> gvarA = tgis.GlobalTemporalVar()
-               >>> gvarA.tfunc = "start_day"
-               >>> gvarA.compop = ">"
-               >>> gvarA.value = 5
-               >>> gvarB = tgis.GlobalTemporalVar()
-               >>> gvarB.tfunc = "start_day"
-               >>> gvarB.compop = "<="
-               >>> gvarB.value = 8
-               >>> gvarOP = tgis.GlobalTemporalVar()
-               >>> gvarOP.relationop = "&&"
-               >>> gvarOP.topology.append("EQUAL")
-               >>> tvarexpr = gvarA
-               >>> result = p.build_condition_list(tvarexpr, mapsA)
-               >>> for map_i in result:
-               ...     print(map_i.get_map_id() + ' ' + str(map_i.condition_value))
-               a0 at B [False]
-               a1 at B [False]
-               a2 at B [False]
-               a3 at B [False]
-               a4 at B [False]
-               a5 at B [True]
-               a6 at B [True]
-               a7 at B [True]
-               a8 at B [True]
-               a9 at B [True]
-               >>> tvarexpr = [gvarA, gvarOP, gvarB]
-               >>> result = p.build_condition_list(tvarexpr, mapsB)
-               >>> for map_i in result:
-               ...     print(map_i.get_map_id() + ' ' + str(map_i.condition_value))
-               b0 at B [True, ['EQUAL'], '&&', True]
-               b1 at B [True, ['EQUAL'], '&&', True]
-               b2 at B [True, ['EQUAL'], '&&', True]
-               b3 at B [True, ['EQUAL'], '&&', False]
-               b4 at B [True, ['EQUAL'], '&&', False]
-               b5 at B [True, ['EQUAL'], '&&', False]
-               b6 at B [True, ['EQUAL'], '&&', False]
-               b7 at B [True, ['EQUAL'], '&&', False]
-               b8 at B [True, ['EQUAL'], '&&', False]
-               b9 at B [True, ['EQUAL'], '&&', False]
-
         """
-
+        
+        # Evaluate the temporal variable expression and compute the temporal combination 
+        # of conditions.
+        
         # Check if the input expression is a valid single global variable.
-        if not isinstance(tvarexpr, list):
-            if isinstance(tvarexpr, GlobalTemporalVar):
-                if tvarexpr.get_type() == "global":
-                    # Use method eval_global_var to evaluate expression.
-                    resultlist = self.eval_global_var(tvarexpr, thenlist)
-        else:
-            # Check if a given list is a list of maps.
-            if all([issubclass(type(ele), AbstractMapDataset) for ele in tvarexpr]):
-                # Use method eval_map_list to evaluate map_list in comparison
-                # to thenlist.
-                resultlist = self.eval_map_list(tvarexpr, thenlist, topolist)
-
+        if isinstance(tvarexpr, GlobalTemporalVar) and tvarexpr.get_type() == "global" :
+            # Use method eval_global_var to evaluate expression.
+            resultlist = self.eval_global_var(tvarexpr, thenlist)
+        # Check if a given list is a list of maps.
+        elif all([issubclass(type(ele), AbstractMapDataset) for ele in tvarexpr]):
+            # Use method eval_map_list to evaluate map_list in comparison to thenlist.
+            resultlist = self.eval_map_list(tvarexpr, thenlist, topolist)
+        elif len(tvarexpr) % 2 != 0:
+            # Define variables for map list comparisons.
+            left_obj = []
+            operator = []
+            right_obj =[]
+            count = 0
+            #self.msgr.fatal("Condition list is not complete. Elements missing")
+            for iter in range(len(tvarexpr)):
+                expr = tvarexpr[iter]
+                operator = tvarexpr[iter +1]
+                relexpr = tvarexpr[iter +2]
+                if all([issubclass(type(ele), list) for ele in [expr,  relexpr]]):
+                    resultlist = self.get_temporal_topo_list(expr,  relexpr)
             # Loop through the list, search for map lists or global variables.
             for expr in tvarexpr:
                 if isinstance(expr, list):
                     if all([issubclass(type(ele), AbstractMapDataset) for ele in expr]):
+
                         # Use method eval_map_list to evaluate map_list
-                        resultlist = self.eval_map_list(expr, thenlist,
-                                                        topolist)
+                        resultlist = self.eval_map_list(expr, thenlist, topolist)
                     else:
-                        # Recursive function call to look into nested list
-                        # elements.
+                        # Recursive function call to look into nested list elements.
                         self.build_condition_list(expr, thenlist)
 
                 elif isinstance(expr, GlobalTemporalVar):
-                    # Use according functions for different global variable
-                    # types.
+                    # Use according functions for different global variable types.
                     if expr.get_type() == "operator":
                         if all(["condition_value" in dir(map_i) for map_i in thenlist]):
                             # Add operator string to the condition list.
@@ -1665,15 +1681,14 @@
                         resultlist = self.eval_global_var(expr, thenlist)
 
         # Sort resulting list of maps chronological.
-        resultlist = sorted(resultlist,
-                            key=AbstractDatasetComparisonKeyStartTime)
+        resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
 
         return(resultlist)
-
-    def eval_condition_list(self, maplist, inverse=False):
+        
+    def eval_condition_list(self, maplist, inverse = False):
         """ This function evaluates conditional values of a map list.
-            A recursive function is used to evaluate comparison statements
-            from left to right in the given conditional list.
+             A recursive function is used to evaluate comparison statements
+             from left to right in the given conditional list.
 
             For example: [True,  '||', False, '&&', True]  -> True
                           [True,  '||', False, '&&', False] -> False
@@ -1685,56 +1700,19 @@
                           [True,  '&&', False]              -> False
                           [False, '||', True]               -> True
 
-            :param tvarexpr: List of GlobalTemporalVar objects and map lists.
+             :param tvarexpr: List of GlobalTemporalVar objects and map lists.
                           The list is constructed by the TemporalAlgebraParser
                           in order of expression evaluation in the parser.
 
-            :return: Map list with conditional values for all temporal expressions.
-
-            .. code-block:: python
-
-                >>> import grass.temporal as tgis
-                >>> tgis.init()
-                >>> p = tgis.TemporalAlgebraParser()
-                >>> # Example with two lists of maps
-                >>> # Create two list of maps with equal time stamps
-                >>> mapsA = []
-                >>> mapsB = []
-                >>> for i in range(10):
-                ...     idA = "a%i at B"%(i)
-                ...     mapA = tgis.RasterDataset(idA)
-                ...     idB = "b%i at B"%(i)
-                ...     mapB = tgis.RasterDataset(idB)
-                ...     check = mapA.set_absolute_time(datetime(2000,1,i + 1),
-                ...             datetime(2000,1,i + 2))
-                ...     check = mapB.set_absolute_time(datetime(2000,1,i + 6),
-                ...             datetime(2000,1,i + 7))
-                ...     mapsA.append(mapA)
-                ...     mapsB.append(mapB)
-                >>> mapsA = p.check_stds(mapsA)
-                >>> mapsB = p.check_stds(mapsB)
-                >>> # Create global expression object.
-                >>> gvarA = tgis.GlobalTemporalVar()
-                >>> gvarA.tfunc = "start_day"
-                >>> gvarA.compop = ">"
-                >>> gvarA.value = 5
-                >>> gvarB = tgis.GlobalTemporalVar()
-                >>> gvarB.tfunc = "start_day"
-                >>> gvarB.compop = "<="
-                >>> gvarB.value = 8
-                >>> gvarOP = tgis.GlobalTemporalVar()
-                >>> gvarOP.relationop = "&&"
-                >>> gvarOP.topology.append("EQUAL")
-                >>> tvarexpr = [mapsA, gvarOP,gvarA]
-
+             :return: Map list with conditional values for all temporal expressions.
         """
         def recurse_compare(conditionlist):
             for ele in conditionlist:
                 if ele == '||':
                     ele_index = conditionlist.index(ele)
-                    topolist = conditionlist.pop(ele_index - 1)
+                    topolist = conditionlist.pop(ele_index -1)
                     right = conditionlist.pop(ele_index)
-                    left = conditionlist.pop(ele_index - 2)
+                    left  = conditionlist.pop(ele_index - 2)
                     if any([left, right]):
                         result = True
                     else:
@@ -1743,9 +1721,9 @@
                     recurse_compare(conditionlist)
                 if ele == '&&':
                     ele_index = conditionlist.index(ele)
-                    topolist = conditionlist.pop(ele_index - 1)
+                    topolist = conditionlist.pop(ele_index -1)
                     right = conditionlist.pop(ele_index)
-                    left = conditionlist.pop(ele_index - 2)
+                    left  = conditionlist.pop(ele_index - 2)
                     if all([left, right]):
                         result = True
                     else:
@@ -1756,13 +1734,14 @@
 
             return(resultlist)
 
-        resultlist = []
+        resultlist  = []
         inverselist = []
+
+        # Loop through map list and evaluate conditional values.
         for map_i in maplist:
             if "condition_value" in dir(map_i):
                 # Get condition values from map object.
                 conditionlist = map_i.condition_value
-                #print(map_i.get_map_id() + ' ' + str(map_i.condition_value))
                 # Evaluate conditions in list with recursive function.
                 resultbool = recurse_compare(conditionlist)
                 # Set conditional value of map to resulting boolean.
@@ -1770,9 +1749,9 @@
                 # Add all maps that fulfill the conditions to result list.
                 if resultbool[0]:
                     resultlist.append(map_i)
+                    print(map_i.get_map_id() + ' ' + str(map_i.condition_value))
                 else:
                     inverselist.append(map_i)
-                #print(map_i.get_map_id() + ' ' + str(map_i.condition_value))
         if inverse:
             return(inverselist)
         else:
@@ -1787,25 +1766,99 @@
 
         """
         if self.run:
-            resultstds = open_new_stds(t[1], self.stdstype, self.temporaltype,
-                                       "", "", 'mean', dbif=self.dbif,
-                                       overwrite=self.overwrite)
             if isinstance(t[3], list):
                 num = len(t[3])
                 count = 0
+                changeflag = False
+                register_list = []                
                 if num > 0:
-                    dbif, connected = init_dbif(None)
-                    for map in t[3]:
-                        map.select(dbif=dbif)
-                        # map.update()
-                        resultstds.register_map(map, dbif=dbif)
-                        count += 1
-                        if count % 10 == 0:
-                            self.msgr.percent(count, num, 1)
-
-                    resultstds.update_from_registered_maps(dbif=dbif)
-                    if connected:
-                        dbif.close()
+                    for map_i in t[3]:
+                        # Test if temporal extents have been changed by temporal 
+                        # relation oeprators (&|+). 
+                        map_i_extent = map_i.get_temporal_extent_as_tuple()
+                        map_test = map_i.get_new_instance(map_i.get_id())
+                        map_test.select()
+                        map_test_extent = map_test.get_temporal_extent_as_tuple()
+                        if map_test_extent != map_i_extent:
+                            changeflag = True
+                    for map_i in t[3]:
+                        if changeflag:
+                            # Check if resultmap names exist in GRASS database.
+                            mapname = self.basename + "_" + str(count) + "@" + self.mapset
+                            process_queue = pymod.ParallelModuleQueue(int(self.nprocs))
+                            if self.stdstype == 'strds':
+                                map_test = RasterDataset(mapname)
+                            elif self.stdstype == 'stvds':
+                                map_test = VectorDataset(mapname)
+                            if map_test.map_exists() and self.overwrite == False:
+                                self.msgr.fatal("Error raster maps with basename %s exist. Use --o flag to overwrite existing file" \
+                                                    %(mapname))
+                            # Create new maps with basename.
+                            newident = self.basename + "_" + str(count)
+                            map_result = map_i.get_new_instance(newident + "@" + self.mapset)
+                            map_result.set_temporal_extent(map_i.get_temporal_extent())
+                            map_result.set_spatial_extent(map_i.get_spatial_extent())
+                            register_list.append(map_result)
+                            if self.stdstype == 'strds':
+                                m = copy.deepcopy(self.m_copy)
+                                m.inputs["rast"].value = map_i.get_id(),  newident
+                                m.flags["overwrite"].value = self.overwrite
+                                process_queue.put(m)
+                            elif self.stdstype == 'stvds':
+                                m = copy.deepcopy(self.m_copy)
+                                m.inputs["vect"].value = map_i.get_id(),  newident
+                                m.flags["overwrite"].value = self.overwrite
+                                process_queue.put(m)
+                        else:
+                            register_list.append(map_i)
+                        count  += 1
+                    if changeflag:
+                        process_queue.wait()
+                    
+                    # Open connection to temporal database.
+                    dbif, connect = init_dbif(self.dbif)
+                    # Create result space time dataset.                        
+                    resultstds = open_new_stds(t[1], self.stdstype, \
+                                                             'absolute', t[1], t[1], \
+                                                             'mean', self.dbif, \
+                                                             overwrite = self.overwrite)                            
+                    for map_i in register_list:                
+                        # Get meta data from grass database.
+                        map_i.load()
+                        # Check if temporal extents have changed.
+                        if changeflag:
+                            # Do not register empty maps if not required
+                            # In case of a null map continue, do not register null maps
+                            if map_i.metadata.get_min() is None and \
+                               map_i.metadata.get_max() is None:
+                                if not self.register_null:
+                                    self.empty_maps[map_i.get_name()] = map_i.get_name()
+                                    continue
+                            if map_i.is_in_db(dbif) and self.overwrite:
+                                # Update map in temporal database.
+                                map_i.update_all(dbif)
+                            elif map_i.is_in_db(dbif) and self.overwrite == False:
+                                # Raise error if map exists and no overwrite flag is given.
+                                self.msgr.fatal("Error vector map %s exist in temporal database. Use overwrite flag.  : \n%s" \
+                                                    %(map_i.get_map_id(), cmd.popen.stderr))
+                            else:
+                                # Insert map into temporal database.
+                                map_i.insert(dbif)
+                        # Register map in result space time dataset.
+                        success = resultstds.register_map(map_i, dbif)
+                    resultstds.update_from_registered_maps(dbif)
+                    dbif.close()
+                elif num == 0:
+                    self.msgr.warning('Empty result space time dataset. No map has \
+been registered in %s'  %(t[1] ))
+                    # Open connection to temporal database.
+                    dbif, connect = init_dbif(self.dbif)
+                    # Create result space time dataset.                        
+                    resultstds = open_new_stds(t[1], self.stdstype, \
+                                                             'absolute', t[1], t[1], \
+                                                             'mean', self.dbif, \
+                                                             overwrite = self.overwrite)
+                    dbif.close()
             t[0] = t[3]
 
         else:
@@ -1825,44 +1878,73 @@
         """ expr : LPAREN expr RPAREN"""
         t[0] = t[2]
 
-    def p_number(self, t):
+    def p_number(self,t):
         """number : INT
                   | FLOAT
         """
         t[0] = t[1]
 
-    def p_t_hash(self, t):
+    def p_expr_tmap_function(self, t):
+        # Add a single map.
+        # Only the spatial extent of the map is evaluated. 
+        # Temporal extent is not existing.
+        # Examples:
+        #    R = tmap(A) 
         """
+        expr : TMAP LPAREN stds RPAREN
+        """
+        if self.run:
+            # Check input map.
+            input = t[3]
+            if not isinstance(input, list):
+                # Check for mapset in given stds input.
+                if input.find("@") >= 0:
+                    id_input = input
+                else:
+                    id_input = input + "@" + self.mapset
+                # Create empty map dataset.
+                map_i = dataset_factory(self.maptype, id_input)
+                # Check for occurence of space time dataset.
+                if map_i.map_exists() == False:
+                    raise FatalError(_("%s map <%s> not found in GRASS spatial database") %
+                        (map_i.get_type(), id_input))
+                else:
+                    # Select dataset entry from database.
+                    map_i.select(dbif=self.dbif)
+            else:
+                raise FatalError(_("Wrong map type <%s> . TMAP only supports single maps that are registered in the temporal GRASS database") %
+                        (map_i.get_type()))
+            # Return map object.
+            t[0] = [map_i]
+        else:
+            t[0] = "tmap(",  t[3] , ")"
+
+        if self.debug:
+            print "tmap(", t[3] , ")"
+
+    def p_t_hash(self,t):
+        """
         t_hash_var : stds HASH stds
-                   | stds HASH expr
-                   | expr HASH stds
-                   | expr HASH expr
         """
 
         if self.run:
-            maplistA = self.check_stds(t[1])
-            maplistB = self.check_stds(t[3])
+            maplistA   = self.check_stds(t[1])
+            maplistB   = self.check_stds(t[3])
             resultlist = self.get_temporal_topo_list(maplistA, maplistB,
-                                                     count_map=True)
-
+                                                        count_map = True)
             t[0] = resultlist
 
-    def p_t_hash2(self, t):
+    def p_t_hash2(self,t):
         """
         t_hash_var : stds T_HASH_OPERATOR stds
-                   | stds T_HASH_OPERATOR expr
-                   | expr T_HASH_OPERATOR stds
-                   | expr T_HASH_OPERATOR expr
         """
 
         if self.run:
-            maplistA = self.check_stds(t[1])
-            maplistB = self.check_stds(t[3])
-            topolist = self.eval_toperator(t[2])[0]
-            resultlist = self.get_temporal_topo_list(maplistA, maplistB,
-                                                     topolist,
-                                                     count_map=True)
-
+            maplistA   = self.check_stds(t[1])
+            maplistB   = self.check_stds(t[3])
+            topolist   = self.eval_toperator(t[2],  optype = 'hash')[0]
+            resultlist = self.get_temporal_topo_list(maplistA, maplistB, topolist,
+                                                     count_map = True)
             t[0] = resultlist
 
     def p_t_td_var(self, t):
@@ -1875,11 +1957,11 @@
             for map_i in maplist:
                 if map_i.is_time_absolute:
                     start, end = map_i.get_absolute_time()
-                    if end is not None:
+                    if end != None:
                         td = time_delta_to_relative_time(end - start)
                 else:
                     start, end, unit = current.get_relative_time()
-                    if end is not None:
+                    if end != None:
                         td = end - start
                 if "map_value" in dir(map_i):
                     gvar = GlobalTemporalVar()
@@ -1895,6 +1977,7 @@
         if self.debug:
             print "td(" + str(t[3]) + ")"
 
+
     def p_t_time_var(self, t):
         # Temporal variables that return a double or integer value
         """
@@ -1932,102 +2015,102 @@
         """
         t[0] = t[1]
 
-    def p_t_var_expr(self, t):
+    def p_t_var_expr_td_hash(self, t):
         # Examples:
-        #    start_month() > 2
-        #    start_day() < 14
-        #    start_day() < start_month()
-        #    td() < 31
+        #    A # B == 2
+        #    td(A) < 31
         """
-        t_var_expr : t_var LPAREN RPAREN comp_op number
-                   | t_var LPAREN RPAREN comp_op t_var
-                   | t_td_var comp_op number
-                   | t_td_var comp_op t_var
-                   | t_hash_var comp_op number
-                   | t_hash_var comp_op t_var
+        t_var_expr :  t_td_var comp_op number
+                | t_hash_var comp_op number
         """
         if self.run:
-            if len(t) == 4:
-                maplist = self.check_stds(t[1])
-                comp_op = t[2]
-                for map_i in maplist:
-                    for obj in map_i.map_value:
-                        if isinstance(obj, GlobalTemporalVar):
-                            td = obj.td
-                            boolnum = eval(str(td) + comp_op + str(t[3]))
-                            gvar = GlobalTemporalVar()
-                            gvar.boolean = boolnum
-                            if obj.get_type() == "timediff":
-                                index = map_i.map_value.index(obj)
-                                map_i.map_value[index] = gvar
-
-                t[0] = maplist
-
-            if len(t) == 6:
-                if isinstance(t[1], GlobalTemporalVar):
-                    pass
-                gvar = GlobalTemporalVar()
-                gvar.tfunc = t[1]
-                gvar.compop = t[4]
-                gvar.value = t[5]
-                t[0] = gvar
-        else:
-            t[0] = True
-
+            maplist = self.check_stds(t[1])
+            comp_op = t[2]
+            value  = str(t[3])
+            for map_i in maplist:
+                # Evaluate time diferences and hash operator statements for each map.
+                try:
+                    td = map_i.map_value[0].td
+                    boolname = eval(str(td) + comp_op + value)
+                    # Add conditional boolean value to the map.
+                    if "condition_value" in dir(map_i):
+                        map_i.condition_value.append(boolname)
+                    else:
+                        map_i.condition_value = boolname
+                except:
+                    self.msgr.fatal("Error: the given expression does not contain a correct time difference object.")
+            
+            t[0] = maplist
+            
         if self.debug:
-            if len(t) == 6:
-                print t[1], t[4], t[5]
-            if len(t) == 4:
-                print t[1], t[2], t[3]
+            print t[1], t[2], t[3]
 
-    def p_t_var_expr_time1(self, t):
+    def p_t_var_expr_number(self, t):
         # Examples:
-        #   start_time() == "12:30:00"
-        #   start_date() <= "2001-01-01"
-        #   start_datetime() > "2001-01-01 12:30:00"
+        #    start_month(A) > 2
+        #    start_day(B) < 14
+        #    start_day(B) < start_month(A)
         """
-        t_var_expr : START_TIME LPAREN RPAREN comp_op TIME
-                   | START_DATE LPAREN RPAREN comp_op DATE
-                   | START_DATETIME LPAREN RPAREN comp_op DATETIME
-                   | END_TIME LPAREN RPAREN comp_op TIME
-                   | END_DATE LPAREN RPAREN comp_op DATE
-                   | END_DATETIME LPAREN RPAREN comp_op DATETIME
+        t_var_expr : t_var LPAREN stds RPAREN comp_op number
+                | t_var LPAREN expr RPAREN comp_op number      
         """
+        # TODO:  Implement comparison operator for map lists.
+        #| t_var LPAREN stds RPAREN comp_op t_var LPAREN stds RPAREN
+        #| t_var LPAREN stds RPAREN comp_op t_var LPAREN expr RPAREN
+        #| t_var LPAREN expr RPAREN comp_op t_var LPAREN expr RPAREN
+        #| t_var LPAREN expr RPAREN comp_op t_var LPAREN stds RPAREN
+        # TODO:  Implement statement in backward direction:
+        # number comp_op t_var LPAREN stds RPAREN
         if self.run:
+            maplist = self.check_stds(t[3])
             gvar = GlobalTemporalVar()
-            gvar.tfunc = t[1]
-            gvar.compop = t[4]
-            gvar.value = t[5]
-            t[0] = gvar
-        else:
-            t[0] = True
+            gvar.tfunc  = t[1]
+            gvar.compop = t[5]
+            gvar.value  = t[6]
+            # Evaluate temporal variable for given maplist.
+            resultlist = self.eval_global_var(gvar, maplist)
+            t[0] = resultlist
 
         if self.debug:
-            print t[1], t[4], t[5]
+                print t[1], t[3], t[5], t[6]
 
-    def p_t_var_expr_time2(self, t):
+    def p_t_var_expr_time(self, t):
+        # Examples:
+        #   start_time(A) == "12:30:00"
+        #   start_date(B) <= "2001-01-01"
+        #   start_datetime(C) > "2001-01-01 12:30:00"
+        # TODO:  Implement statement in backward direction:
+        # TIME comp_op START_TIME LPAREN stds RPAREN
         """
-        t_var_expr : TIME     comp_op START_TIME LPAREN RPAREN
-                   | DATE     comp_op START_DATE LPAREN RPAREN
-                   | DATETIME comp_op START_DATETIME LPAREN RPAREN
-                   | TIME     comp_op END_TIME LPAREN RPAREN
-                   | DATE     comp_op END_DATE LPAREN RPAREN
-                   | DATETIME comp_op END_DATETIME LPAREN RPAREN
+        t_var_expr : START_TIME LPAREN stds RPAREN comp_op TIME
+                   | START_DATE LPAREN stds RPAREN comp_op DATE
+                   | START_DATETIME LPAREN stds RPAREN comp_op DATETIME
+                   | END_TIME LPAREN stds RPAREN comp_op TIME
+                   | END_DATE LPAREN stds RPAREN comp_op DATE
+                   | END_DATETIME LPAREN stds RPAREN comp_op DATETIME
+                   | START_TIME LPAREN expr RPAREN comp_op TIME
+                   | START_DATE LPAREN expr RPAREN comp_op DATE
+                   | START_DATETIME LPAREN expr RPAREN comp_op DATETIME
+                   | END_TIME LPAREN expr RPAREN comp_op TIME
+                   | END_DATE LPAREN expr RPAREN comp_op DATE
+                   | END_DATETIME LPAREN expr RPAREN comp_op DATETIME
         """
         if self.run:
-            reverseop = {"<": ">", ">": "<", "<=": ">=", ">=": "<=",
-                         "==": "==", "!=": "!="}
+            # Check input maplist.
+            maplist = self.check_stds(t[3])
+            # Build global temporal variable.
             gvar = GlobalTemporalVar()
-            gvar.tfunc = t[3]
-            gvar.compop = reverseop[t[2]]
-            gvar.value = t[1]
-            t[0] = gvar
-        else:
-            t[0] = True
+            gvar.tfunc  = t[1]
+            gvar.compop = t[5]
+            gvar.value  = t[6]
+            # Evaluate temporal variable for given maplist.
+            resultlist = self.eval_global_var(gvar, maplist)
+            
+            t[0] = resultlist
 
+
         if self.debug:
-            print(t[4])
-            print t[1], t[4], t[5]
+            print t[1], t[3],  t[5], t[6]
 
     def p_t_var_expr_comp(self, t):
         """
@@ -2035,19 +2118,21 @@
                    | t_var_expr OR OR t_var_expr
         """
         if self.run:
-            tvarexprA = t[1]
-            tvarexprB = t[4]
-            operator = GlobalTemporalVar()
-            operator.relationop = t[2] + t[3]
-            operator.topology.append("EQUAL")
-            resultlist = []
-            resultlist.append(tvarexprA)
-            resultlist.append(operator)
-            resultlist.append(tvarexprB)
-
+            # Check input maplists and operators.
+            tvarexprA  = t[1]
+            tvarexprB  = t[4]
+            relations = ["EQUAL"]
+            temporal = "l"
+            function = t[2] + t[3]
+            aggregate = t[2] 
+            # Build conditional values based on topological relationships.            
+            complist = self.get_temporal_topo_list(tvarexprA, tvarexprB, topolist = relations,
+                               compare_bool = True, compop = function[0], aggregate = aggregate)
+            # Set temporal extent based on topological relationships.
+            resultlist = self.set_temporal_extent_list(complist, topolist = relations, 
+                                temporal = temporal)
+            
             t[0] = resultlist
-        else:
-            t[0] = True
 
         if self.debug:
             print t[1], t[2] + t[3], t[4]
@@ -2057,22 +2142,18 @@
         t_var_expr : t_var_expr T_COMP_OPERATOR t_var_expr
         """
         if self.run:
-            tvarexprA = t[1]
-            tvarexprB = t[3]
-            operator = GlobalTemporalVar()
-            toperator = self.eval_toperator(t[2])[0]
-            relationop = toperator[2]
-            relations = toperator[0]
-            operator.relationop = relationop
-            operator.topology.extend(relations)
-            resultlist = []
-            resultlist.append(tvarexprA)
-            resultlist.append(operator)
-            resultlist.append(tvarexprB)
+            tvarexprA  = t[1]
+            tvarexprB  = t[3]
+            # Evaluate temporal comparison operator.
+            relations, temporal, function, aggregate  = self.eval_toperator(t[2],  optype = 'boolean')
+            # Build conditional values based on topological relationships.
+            complist = self.get_temporal_topo_list(tvarexprA, tvarexprB, topolist = relations,
+                               compare_bool = True, compop = function[0], aggregate = aggregate)
+            # Set temporal extent based on topological relationships.
+            resultlist = self.set_temporal_extent_list(complist, topolist = relations, 
+                                temporal = temporal)
 
             t[0] = resultlist
-        else:
-            t[0] = True
 
         if self.debug:
             print t[1], t[2], t[3]
@@ -2092,17 +2173,17 @@
             # Setup database connection.
 
             # Check input stds.
-            maplistA = self.check_stds(t[1])
-            maplistB = self.check_stds(t[3])
+            maplistA     = self.check_stds(t[1])
+            maplistB     = self.check_stds(t[3])
             # Perform selection.
             selectlist = self.perform_temporal_selection(maplistA, maplistB)
             # Return map list.
             t[0] = selectlist
         else:
-            t[0] = t[1] + "*"
+            t[0] = t[1] , "*"
 
         if self.debug:
-            print t[1] + "* = ", t[1], t[2], t[3]
+            print str(t[1]),  "* = ", t[1], t[2], t[3]
 
     def p_expr_t_not_select(self, t):
         # Temporal equal selection
@@ -2117,11 +2198,11 @@
         """
         if self.run:
             # Check input stds.
-            maplistA = self.check_stds(t[1])
-            maplistB = self.check_stds(t[3])
+            maplistA     = self.check_stds(t[1])
+            maplistB     = self.check_stds(t[3])
             # Perform negative selection.
             selectlist = self.perform_temporal_selection(maplistA, maplistB,
-                                                         inverse=True)
+                                                         inverse = True)
             # Return map list.
             t[0] = selectlist
         else:
@@ -2130,6 +2211,7 @@
         if self.debug:
             print t[1] + "* = ", t[1], t[2], t[3]
 
+
     def p_expr_t_select_operator(self, t):
         # Temporal equal selection
         # The temporal topology relation equals is implicit
@@ -2148,10 +2230,10 @@
         """
         if self.run:
             # Check input stds.
-            maplistA = self.check_stds(t[1])
-            maplistB = self.check_stds(t[3])
+            maplistA     = self.check_stds(t[1])
+            maplistB     = self.check_stds(t[3])
             # Evaluate temporal operator.
-            operators = self.eval_toperator(t[2])
+            operators  = self.eval_toperator(t[2],  optype = 'select')
             # Check for negative selection.
             if operators[2] == "!:":
                 negation = True
@@ -2159,11 +2241,9 @@
                 negation = False
             # Perform selection.
             selectlist = self.perform_temporal_selection(maplistA, maplistB,
-                                                         topolist=operators[0],
-                                                         inverse=negation)
-            selectlist = self.set_granularity(selectlist, maplistB,
-                                              operators[1], operators[0])
-
+                         topolist = operators[0], inverse = negation)
+            selectlist = self.set_granularity(selectlist, maplistB, operators[1], 
+                operators[0])
             # Return map list.
             t[0] = selectlist
         else:
@@ -2172,6 +2252,7 @@
         if self.debug:
             print t[1] + "* = ", t[1], t[2], t[3]
 
+
     def p_expr_condition_if(self, t):
         # Examples
         # if( start_date() < "2005-06-01", A:B)
@@ -2181,13 +2262,13 @@
         """
         if self.run:
             # Get stds/map list of then statement.
-            thenlist = self.check_stds(t[5])
+            thenlist     = self.check_stds(t[5])
             # Get temporal conditional statement.
-            tvarexpr = t[3]
-            thencond = self.build_condition_list(tvarexpr, thenlist)
-            thenresult = self.eval_condition_list(thencond)
+            tvarexpr     = t[3]
+            thencond     = self.build_condition_list(tvarexpr, thenlist)      
+            thenresult   = self.eval_condition_list(thencond)
             # Clear the map and conditional values of the map list.
-            resultlist = self.check_stds(thenresult, clear=True)
+            resultlist   = self.check_stds(thenresult, clear = True)
             # Return resulting map list.
             t[0] = resultlist
         else:
@@ -2205,14 +2286,14 @@
         """
         if self.run:
             # Get stds/map list of then statement.
-            thenlist = self.check_stds(t[7])
+            thenlist     = self.check_stds(t[7])
             # Get temporal conditional statement.
-            tvarexpr = t[5]
-            topolist = self.eval_toperator(t[3])[0]
-            thencond = self.build_condition_list(tvarexpr, thenlist, topolist)
-            thenresult = self.eval_condition_list(thencond)
+            tvarexpr     = t[5]
+            topolist     = self.eval_toperator(t[3],  optype = 'relation')[0]
+            thencond     = self.build_condition_list(tvarexpr, thenlist, topolist)            
+            thenresult   = self.eval_condition_list(thencond)          
             # Clear the map and conditional values of the map list.
-            resultlist = self.check_stds(thenresult, clear=True)
+            resultlist   = self.check_stds(thenresult, clear = True)
             # Return resulting map list.
             t[0] = resultlist
         else:
@@ -2232,21 +2313,20 @@
         """
         if self.run:
             # Get stds/map list of then statement.
-            thenlist = self.check_stds(t[5])
-            elselist = self.check_stds(t[7])
+            thenlist     = self.check_stds(t[5])
+            elselist     = self.check_stds(t[7])
             # Get temporal conditional statement for then and else expressions.
-            tvarexpr = t[3]
-            thencond = self.build_condition_list(tvarexpr, thenlist)
-            thenresult = self.eval_condition_list(thencond)
-            elsecond = self.build_condition_list(tvarexpr, elselist)
-            elseresult = self.eval_condition_list(elsecond, inverse=True)
+            tvarexpr     = t[3]
+            thencond     = self.build_condition_list(tvarexpr, thenlist)
+            thenresult   = self.eval_condition_list(thencond)
+            elsecond     = self.build_condition_list(tvarexpr, elselist)
+            elseresult   = self.eval_condition_list(elsecond, inverse = True)
 
             # Combine and sort else and then statement to result map list.
             combilist = thenresult + elseresult
-            resultlist = sorted(combilist,
-                                key=AbstractDatasetComparisonKeyStartTime)
+            resultlist = sorted(combilist, key = AbstractDatasetComparisonKeyStartTime)
             # Clear the map and conditional values of the map list.
-            resultlist = self.check_stds(resultlist, clear=True)
+            resultlist   = self.check_stds(resultlist, clear = True)
             # Return resulting map list.
             t[0] = resultlist
         else:
@@ -2268,22 +2348,21 @@
         """
         if self.run:
             # Get stds/map list of then statement.
-            thenlist = self.check_stds(t[7])
-            elselist = self.check_stds(t[9])
+            thenlist     = self.check_stds(t[7])
+            elselist     = self.check_stds(t[9])
             # Get temporal conditional statement.
-            tvarexpr = t[5]
-            topolist = self.eval_toperator(t[3])[0]
-            thencond = self.build_condition_list(tvarexpr, thenlist, topolist)
-            thenresult = self.eval_condition_list(thencond)
-            elsecond = self.build_condition_list(tvarexpr, elselist, topolist)
-            elseresult = self.eval_condition_list(elsecond, inverse=True)
+            tvarexpr     = t[5]
+            topolist     = self.eval_toperator(t[3],  optype = 'relation')[0]
+            thencond     = self.build_condition_list(tvarexpr, thenlist, topolist)
+            thenresult   = self.eval_condition_list(thencond)
+            elsecond     = self.build_condition_list(tvarexpr, elselist, topolist)
+            elseresult   = self.eval_condition_list(elsecond, inverse = True)
 
             # Combine and sort else and then statement to result map list.
             combilist = thenresult + elseresult
-            resultlist = sorted(combilist,
-                                key=AbstractDatasetComparisonKeyStartTime)
+            resultlist = sorted(combilist, key = AbstractDatasetComparisonKeyStartTime)
             # Clear the map and conditional values of the map list.
-            resultlist = self.check_stds(resultlist, clear=True)
+            resultlist   = self.check_stds(resultlist, clear = True)
             # Return resulting map list.
             t[0] = resultlist
         else:
@@ -2310,7 +2389,7 @@
         """
         if self.run:
             # Check input stds.
-            bufflist = self.check_stds(t[3])
+            bufflist     = self.check_stds(t[3])
             for map in bufflist:
                 # Get increment format.
                 if len(t) == 10:
@@ -2338,7 +2417,7 @@
         """
         if self.run:
             # Check input stds.
-            maplist = self.check_stds(t[3])
+            maplist     = self.check_stds(t[3])
             # Perform snapping.
             snaplist = AbstractSpaceTimeDataset.snap_map_list(maplist)
             t[0] = snaplist
@@ -2360,15 +2439,14 @@
         """
         if self.run:
             # Check input stds.
-            maplist = self.check_stds(t[3])
+            maplist     = self.check_stds(t[3])
             # Get increment format.
             if len(t) == 10:
                 increment = str(t[6]) + " " + t[7]
             elif len(t) == 7:
                 increment = str(t[5])
             # Perform shifting.
-            shiftlist = AbstractSpaceTimeDataset.shift_map_list(maplist,
-                                                                increment)
+            shiftlist = AbstractSpaceTimeDataset.shift_map_list(maplist, increment)
             t[0] = shiftlist
         else:
             t[0] = t[3] + "*"
@@ -2382,9 +2460,8 @@
     # Handle errors.
     def p_error(self, t):
         if t:
-            raise SyntaxError("syntax error on line %d, token %s near '%s'"
-                              " expression '%s'" % (t.lineno, t.type, t.value,
-                                                    self.expression))
+            raise SyntaxError("syntax error on line %d, token %s near '%s' expression '%s'" %
+                             (t.lineno, t.type, t.value, self.expression))
         else:
             raise SyntaxError("Unexpected syntax error")
 

Added: grass/trunk/lib/python/temporal/temporal_operator.py
===================================================================
--- grass/trunk/lib/python/temporal/temporal_operator.py	                        (rev 0)
+++ grass/trunk/lib/python/temporal/temporal_operator.py	2014-11-04 15:45:52 UTC (rev 62594)
@@ -0,0 +1,615 @@
+"""!@package grass.temporal
+
+Temporal operator evaluation with PLY
+
+(C) 2013 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.
+
+ at author Thomas Leppelt and Soeren Gebbert
+
+ at code
+    >>> p = TemporalOperatorParser()
+    >>> expression =  "{equal| during}"
+    >>> p.parse(expression, optype = 'relation')
+    >>> print(p.relations, p.temporal, p.function)
+    (['equal', 'during'], None, None)
+    >>> p = TemporalOperatorParser()    
+    >>> expression =  "{contains | starts}"
+    >>> p.parse(expression)
+    >>> print(p.relations, p.temporal, p.function)
+    (['contains', 'starts'], None, None)
+    >>> p = TemporalOperatorParser()    
+    >>> expression =  "{&&, during}"
+    >>> p.parse(expression, optype = 'boolean')
+    >>> print(p.relations, p.temporal, p.function,p.aggregate)
+    (['during'], 'l', '&&', '&')
+    >>> p = TemporalOperatorParser()    
+    >>> expression =  "{||, equal | during}"
+    >>> p.parse(expression, optype = 'boolean')
+    >>> print(p.relations, p.temporal, p.function,p.aggregate)
+    (['equal', 'during'], 'l', '||', '|')
+    >>> p = TemporalOperatorParser()    
+    >>> expression =  "{||, equal | during, &}"
+    >>> p.parse(expression, optype = 'boolean')
+    >>> print(p.relations, p.temporal, p.function,p.aggregate)
+    (['equal', 'during'], 'l', '||', '&')
+    >>> p = TemporalOperatorParser()    
+    >>> expression =  "{&&, during, |}"
+    >>> p.parse(expression, optype = 'boolean')
+    >>> print(p.relations, p.temporal, p.function,p.aggregate)
+    (['during'], 'l', '&&', '|')
+    >>> p = TemporalOperatorParser()    
+    >>> expression =  "{&&, during, |, r}"
+    >>> p.parse(expression, optype = 'boolean')
+    >>> print(p.relations, p.temporal, p.function,p.aggregate)
+    (['during'], 'r', '&&', '|')
+    >>> p = TemporalOperatorParser()    
+    >>> expression =  "{&&, during, u}"
+    >>> p.parse(expression, optype = 'boolean')
+    >>> print(p.relations, p.temporal, p.function,p.aggregate)
+    (['during'], 'u', '&&', '&')
+    >>> p = TemporalOperatorParser()    
+    >>> expression =  "{:, during, r}"
+    >>> p.parse(expression, optype = 'select')
+    >>> print(p.relations, p.temporal, p.function)
+    (['during'], 'r', ':')
+    >>> p = TemporalOperatorParser()    
+    >>> expression =  "{!:, equal | contains, d}"
+    >>> p.parse(expression, optype = 'select')
+    >>> print(p.relations, p.temporal, p.function)
+    (['equal', 'contains'], 'd', '!:')
+    >>> p = TemporalOperatorParser()    
+    >>> expression =  "{#, during, r}"
+    >>> p.parse(expression, optype = 'hash')
+    >>> print(p.relations, p.temporal, p.function)
+    (['during'], 'r', '#')
+    >>> p = TemporalOperatorParser()    
+    >>> expression =  "{#, equal | contains}"
+    >>> p.parse(expression, optype = 'hash')
+    >>> print(p.relations, p.temporal, p.function)
+    (['equal', 'contains'], 'l', '#')
+    >>> p = TemporalOperatorParser()    
+    >>> expression =  "{+, during, r}"
+    >>> p.parse(expression, optype = 'raster')
+    >>> print(p.relations, p.temporal, p.function)
+    (['during'], 'r', '+')
+    >>> p = TemporalOperatorParser()    
+    >>> expression =  "{/, equal | contains}"
+    >>> p.parse(expression, optype = 'raster')
+    >>> print(p.relations, p.temporal, p.function)
+    (['equal', 'contains'], 'l', '/')
+    >>> p = TemporalOperatorParser()    
+    >>> expression =  "{+, equal | contains,intersect}"
+    >>> p.parse(expression, optype = 'raster')
+    >>> print(p.relations, p.temporal, p.function)
+    (['equal', 'contains'], 'i', '+')
+    >>> p = TemporalOperatorParser()    
+    >>> expression =  "{*, contains,disjoint}"
+    >>> p.parse(expression, optype = 'raster')
+    >>> print(p.relations, p.temporal, p.function)
+    (['contains'], 'd', '*')
+    >>> p = TemporalOperatorParser()    
+    >>> expression =  "{~, equal,left}"
+    >>> p.parse(expression, optype = 'overlay')
+    >>> print(p.relations, p.temporal, p.function)
+    (['equal'], 'l', '~')
+    >>> p = TemporalOperatorParser()    
+    >>> expression =  "{^, over,right}"
+    >>> p.parse(expression, optype = 'overlay')
+    >>> print(p.relations, p.temporal, p.function)
+    (['overlaps', 'overlapped'], 'r', '^')
+    
+ at endcode
+"""
+
+try:
+    import ply.lex as lex
+    import ply.yacc as yacc
+except:
+    pass
+
+class TemporalOperatorLexer(object):
+    """!Lexical analyzer for the GRASS GIS temporal operator"""
+
+    # Functions that defines topological relations.
+    relations = {
+        'equal'      : "EQUAL",
+        'follows'    : "FOLLOWS",
+        'precedes'   : "PRECEDES",
+        'overlaps'   : "OVERLAPS",
+        'overlapped' : "OVERLAPPED",
+        'during'     : "DURING",
+        'starts'     : "STARTS",
+        'finishes'   : "FINISHES",
+        'contains'   : "CONTAINS",
+        'started'    : "STARTED",
+        'finished'   : "FINISHED",
+        'over'       : "OVER"
+        }
+
+    # This is the list of token names.
+    tokens = (
+        'COMMA',
+        'LEFTREF',
+        'RIGHTREF',
+        'UNION', 
+        'DISJOINT',
+        'INTERSECT',
+        'HASH',
+        'OR',
+        'AND',
+        'DISOR',
+        'XOR',
+        'NOT',        
+        'MOD',
+        'DIV',
+        'MULT',
+        'ADD',      
+        'SUB',
+        'T_SELECT',
+        'T_NOT_SELECT',
+        'CLPAREN',
+        'CRPAREN',
+    )
+
+    # Build the token list
+    tokens = tokens + tuple(relations.values())
+
+    # Regular expression rules for simple tokens
+    t_T_SELECT                = r':'
+    t_T_NOT_SELECT        = r'!:'
+    t_COMMA                    = r','
+    t_LEFTREF                  = '^[l|left]'
+    t_RIGHTREF                ='^[r|right]'
+    t_UNION                     = '^[u|union]'
+    t_DISJOINT                 = '^[d|disjoint]'
+    t_INTERSECT             = '^[i|intersect]'
+    t_HASH                      = r'\#'
+    t_OR                          = r'[\|]'
+    t_AND                        = r'[&]'
+    t_DISOR                     = r'\+'
+    t_XOR                         = r'\^'
+    t_NOT                         = r'\~'    
+    t_MOD                       = r'[\%]'
+    t_DIV                         = r'[\/]'
+    t_MULT                      = r'[\*]'
+    t_ADD                       = r'[\+]'
+    t_SUB                        = r'[-]'
+    t_CLPAREN                = r'\{'
+    t_CRPAREN                = r'\}'
+
+    # These are the things that should be ignored.
+    t_ignore = ' \t'
+
+    # Track line numbers.
+    def t_newline(self, t):
+        r'\n+'
+        t.lineno += len(t.value)
+
+    def t_NAME(self, t):
+        r'[a-zA-Z_][a-zA-Z_0-9]*'
+        self.temporal_symbol(t)
+        return t
+
+    # Parse symbols
+    def temporal_symbol(self, t):
+        # Check for reserved words
+        if t.value in TemporalOperatorLexer.relations.keys():
+            t.type = TemporalOperatorLexer.relations.get(t.value)
+        elif t.value == 'l' or t.value == 'left':
+            t.value = 'l'
+            t.type = 'LEFTREF'
+        elif t.value == 'r' or t.value == 'right':
+            t.value = 'r'
+            t.type = 'RIGHTREF'
+        elif t.value == 'u' or t.value == 'union':
+            t.value = 'u'
+            t.type = 'UNION'
+        elif t.value == 'd' or t.value == 'disjoint':
+            t.value = 'd'
+            t.type = 'DISJOINT'
+        elif t.value == 'i' or t.value == 'intersect':
+            t.value = 'i'
+            t.type = 'INTERSECT'
+        #else:
+        #    t.type = 'NAME'
+        return(t)
+
+    # Handle errors.
+    def t_error(self, t):
+        raise SyntaxError("syntax error on line %d near '%s'" %
+            (t.lineno, t.value))
+
+    # Build the lexer
+    def build(self,**kwargs):
+        self.lexer = lex.lex(module=self, **kwargs)
+
+    # Just for testing
+    def test(self,data):
+        self.name_list = {}
+        print(data)
+        self.lexer.input(data)
+        while True:
+             tok = self.lexer.token()
+             if not tok: break
+             print tok
+
+###############################################################################
+
+class TemporalOperatorParser(object):
+    """The temporal operator class"""
+
+    def __init__(self):
+        self.lexer = TemporalOperatorLexer()
+        self.lexer.build()
+        self.parser = yacc.yacc(module=self)
+        self.relations = None
+        self.temporal  = None
+        self.function  = None
+        self.aggregate = None
+
+    def parse(self, expression,  optype = 'relation'):
+        self.optype = optype        
+        self.parser.parse(expression)
+        # The paramter optype can be of type: select {:, during, r}, boolean{&&, contains, |}, 
+        #                                                            raster{*, equal, |}, vector {|, starts, &},
+        #                                                            hash{#, during, l} or relation {during}.
+    
+    # Error rule for syntax errors.
+    def p_error(self, t):
+        raise SyntaxError("Unexpected syntax error")
+
+    # Get the tokens from the lexer class
+    tokens = TemporalOperatorLexer.tokens
+ 
+    def p_relation_operator(self, t):
+        # The expression should always return a list of maps.
+        """
+        operator : CLPAREN relation CRPAREN
+                 | CLPAREN relationlist CRPAREN
+        """
+        # Check for correct type.
+        if not self.optype == 'relation':
+            raise SyntaxError("invalid syntax")
+        else:
+            # Set three operator components.
+            if isinstance(t[2], list):
+                self.relations = t[2]
+            else:
+                self.relations = [t[2]]
+            self.temporal  = None
+            self.function  = None
+
+            t[0] = t[2]
+
+    def p_relation_bool_operator(self, t):
+        # The expression should always return a list of maps.
+        """
+        operator : CLPAREN OR OR COMMA relation CRPAREN
+                | CLPAREN AND AND COMMA relation CRPAREN
+                | CLPAREN OR OR COMMA relationlist CRPAREN
+                | CLPAREN AND AND COMMA relationlist CRPAREN
+        """
+        if not self.optype == 'boolean':
+            raise SyntaxError("invalid syntax")
+        else:        
+            # Set three operator components.
+            if isinstance(t[5], list):
+                self.relations = t[5]
+            else:
+                self.relations = [t[5]]
+            self.temporal  = "l"
+            self.function  = t[2] + t[3]
+            self.aggregate = t[2]
+            
+            t[0] = t[2]
+
+    def p_relation_bool_combi_operator(self, t):
+        # The expression should always return a list of maps.
+        """
+        operator : CLPAREN OR OR COMMA relation COMMA OR CRPAREN
+                | CLPAREN OR OR COMMA relation COMMA AND CRPAREN
+                | CLPAREN AND AND COMMA relation COMMA OR CRPAREN
+                | CLPAREN AND AND COMMA relation COMMA AND CRPAREN
+                | CLPAREN OR OR COMMA relationlist COMMA OR CRPAREN
+                | CLPAREN OR OR COMMA relationlist COMMA AND CRPAREN
+                | CLPAREN AND AND COMMA relationlist COMMA OR CRPAREN
+                | CLPAREN AND AND COMMA relationlist COMMA AND CRPAREN
+        """
+        if not self.optype == 'boolean':
+            raise SyntaxError("invalid syntax")
+        else:        
+            # Set three operator components.
+            if isinstance(t[5], list):
+                self.relations = t[5]
+            else:
+                self.relations = [t[5]]
+            self.temporal  = "l"
+            self.function  = t[2] + t[3]
+            self.aggregate = t[7]
+            
+            t[0] = t[2]
+
+    def p_relation_bool_combi_operator2(self, t):
+        # The expression should always return a list of maps.
+        """
+        operator : CLPAREN OR OR COMMA relation COMMA temporal CRPAREN
+                | CLPAREN AND AND COMMA relation COMMA temporal CRPAREN
+                | CLPAREN OR OR COMMA relationlist COMMA temporal CRPAREN
+                | CLPAREN AND AND COMMA relationlist COMMA temporal CRPAREN
+        """
+        if not self.optype == 'boolean':
+            raise SyntaxError("invalid syntax")
+        else:        
+            # Set three operator components.
+            if isinstance(t[5], list):
+                self.relations = t[5]
+            else:
+                self.relations = [t[5]]
+            self.temporal  = t[7]
+            self.function  = t[2] + t[3]
+            self.aggregate = t[2]
+            
+            t[0] = t[2]
+    
+    def p_relation_bool_combi_operator3(self, t):
+        # The expression should always return a list of maps.
+        """
+        operator : CLPAREN OR OR COMMA relation COMMA OR COMMA temporal CRPAREN
+                | CLPAREN OR OR COMMA relation COMMA AND COMMA temporal CRPAREN
+                | CLPAREN AND AND COMMA relation COMMA OR COMMA temporal CRPAREN
+                | CLPAREN AND AND COMMA relation COMMA AND COMMA temporal CRPAREN
+                | CLPAREN OR OR COMMA relationlist COMMA OR COMMA temporal CRPAREN
+                | CLPAREN OR OR COMMA relationlist COMMA AND COMMA temporal CRPAREN
+                | CLPAREN AND AND COMMA relationlist COMMA OR COMMA temporal CRPAREN
+                | CLPAREN AND AND COMMA relationlist COMMA AND COMMA temporal CRPAREN
+        """
+        if not self.optype == 'boolean':
+            raise SyntaxError("invalid syntax")
+        else:        
+            # Set three operator components.
+            if isinstance(t[5], list):
+                self.relations = t[5]
+            else:
+                self.relations = [t[5]]
+            self.temporal  = t[9]
+            self.function  = t[2] + t[3]
+            self.aggregate = t[7]
+            
+            t[0] = t[2]
+    
+    def p_select_relation_operator(self, t):
+        # The expression should always return a list of maps.
+        """
+        operator : CLPAREN select CRPAREN
+                    | CLPAREN select COMMA relation CRPAREN
+                    | CLPAREN select COMMA relationlist CRPAREN
+                    | CLPAREN select COMMA relation COMMA temporal CRPAREN
+                    | CLPAREN select COMMA relationlist COMMA temporal CRPAREN
+        """
+        if not self.optype == 'select':
+            raise SyntaxError("invalid syntax")
+        else:
+            if len(t) == 4:
+                # Set three operator components.
+                self.relations = ['equal']
+                self.temporal  = "l"
+                self.function  = t[2]
+            elif len(t) == 5:
+                self.relations = ['equal']
+                self.temporal  = t[3]
+                self.function  = t[2]
+            elif len(t) == 6:
+                if isinstance(t[4], list):
+                    self.relations = t[4]
+                else:
+                    self.relations = [t[4]]
+                self.temporal  = "l"
+                self.function  = t[2]
+            elif len(t) == 8:
+                if isinstance(t[4], list):
+                    self.relations = t[4]
+                else:
+                    self.relations = [t[4]]
+                self.temporal  = t[6]
+                self.function  = t[2]
+            t[0] = t[2]
+
+    def p_hash_relation_operator(self, t):
+        # The expression should always return a list of maps.
+        """
+        operator : CLPAREN HASH CRPAREN
+                    | CLPAREN HASH COMMA relation CRPAREN
+                    | CLPAREN HASH COMMA relationlist CRPAREN
+                    | CLPAREN HASH COMMA relation COMMA temporal CRPAREN
+                    | CLPAREN HASH COMMA relationlist COMMA temporal CRPAREN
+        """
+        if not self.optype == 'hash':
+            raise SyntaxError("invalid syntax")
+        else:
+            if len(t) == 4:
+                # Set three operator components.
+                self.relations = ['equal']
+                self.temporal  = "l"
+                self.function  = t[2]
+            elif len(t) == 5:
+                self.relations = ['equal']
+                self.temporal  = t[3]
+                self.function  = t[2]
+            elif len(t) == 6:
+                if isinstance(t[4], list):
+                    self.relations = t[4]
+                else:
+                    self.relations = [t[4]]
+                self.temporal  = "l"
+                self.function  = t[2]
+            elif len(t) == 8:
+                if isinstance(t[4], list):
+                    self.relations = t[4]
+                else:
+                    self.relations = [t[4]]
+                self.temporal  = t[6]
+                self.function  = t[2]
+            t[0] = t[2]
+
+    def p_raster_relation_operator(self, t):
+        # The expression should always return a list of maps.
+        """
+        operator : CLPAREN arithmetic CRPAREN
+                    | CLPAREN arithmetic COMMA relation CRPAREN
+                    | CLPAREN arithmetic COMMA relationlist CRPAREN
+                    | CLPAREN arithmetic COMMA relation COMMA temporal CRPAREN
+                    | CLPAREN arithmetic COMMA relationlist COMMA temporal CRPAREN
+        """
+        if not self.optype == 'raster':
+            raise SyntaxError("invalid syntax")
+        else:
+            if len(t) == 4:
+                # Set three operator components.
+                self.relations = ['equal']
+                self.temporal  = "l"
+                self.function  = t[2]
+            elif len(t) == 5:
+                self.relations = ['equal']
+                self.temporal  = t[3]
+                self.function  = t[2]
+            elif len(t) == 6:
+                if isinstance(t[4], list):
+                    self.relations = t[4]
+                else:
+                    self.relations = [t[4]]
+                self.temporal  = "l"
+                self.function  = t[2]
+            elif len(t) == 8:
+                if isinstance(t[4], list):
+                    self.relations = t[4]
+                else:
+                    self.relations = [t[4]]
+                self.temporal  = t[6]
+                self.function  = t[2]
+            t[0] = t[2]
+
+    def p_overlay_relation_operator(self, t):
+        # The expression should always return a list of maps.
+        """
+        operator : CLPAREN overlay CRPAREN
+                    | CLPAREN overlay COMMA relation CRPAREN
+                    | CLPAREN overlay COMMA relationlist CRPAREN
+                    | CLPAREN overlay COMMA relation COMMA temporal CRPAREN
+                    | CLPAREN overlay COMMA relationlist COMMA temporal CRPAREN
+        """
+        if not self.optype == 'overlay':
+            raise SyntaxError("invalid syntax")
+        else:
+            if len(t) == 4:
+                # Set three operator components.
+                self.relations = ['equal']
+                self.temporal  = "l"
+                self.function  = t[2]
+            elif len(t) == 5:
+                self.relations = ['equal']
+                self.temporal  = t[3]
+                self.function  = t[2]
+            elif len(t) == 6:
+                if isinstance(t[4], list):
+                    self.relations = t[4]
+                else:
+                    self.relations = [t[4]]
+                self.temporal  = "l"
+                self.function  = t[2]
+            elif len(t) == 8:
+                if isinstance(t[4], list):
+                    self.relations = t[4]
+                else:
+                    self.relations = [t[4]]
+                self.temporal  = t[6]
+                self.function  = t[2]
+            t[0] = t[2]
+
+    def p_relation(self, t):
+        # The list of relations.
+        """
+        relation : EQUAL
+                 | FOLLOWS
+                 | PRECEDES
+                 | OVERLAPS
+                 | OVERLAPPED
+                 | DURING
+                 | STARTS
+                 | FINISHES
+                 | CONTAINS
+                 | STARTED
+                 | FINISHED
+        """
+        t[0] = t[1]
+
+    def p_over(self, t):
+        # The list of relations.
+        """
+        relation : OVER
+        """
+        over_list = ["overlaps", "overlapped"]
+        t[0] = over_list
+
+    def p_relationlist(self, t):
+        # The list of relations.
+        """
+        relationlist : relation OR relation
+                     | relation OR relationlist
+        """
+        rel_list = []
+        rel_list.append(t[1])
+        if isinstance(t[3], list):
+            rel_list = rel_list + t[3]
+        else:
+            rel_list.append(t[3])
+        t[0] =  rel_list
+
+    def p_temporal_operator(self, t):
+        # The list of relations.
+        """
+        temporal : LEFTREF
+                | RIGHTREF
+                | UNION
+                | DISJOINT
+                | INTERSECT
+        """
+        t[0] = t[1]
+
+    def p_select_operator(self, t):
+        # The list of relations.
+        """
+        select : T_SELECT
+               | T_NOT_SELECT
+        """
+        t[0] = t[1]
+
+    def p_arithmetic_operator(self, t):
+        # The list of relations.
+        """
+        arithmetic : MOD
+                   | DIV
+                   | MULT
+                   | ADD
+                   | SUB
+        """
+        t[0] = t[1]
+
+    def p_overlay_operator(self, t):
+        # The list of relations.
+        """
+        overlay : AND
+                   | OR
+                   | XOR
+                   | DISOR
+                   | NOT
+        """
+        t[0] = t[1]
+###############################################################################
+
+if __name__ == "__main__":
+    import doctest
+    doctest.testmod()
+

Modified: grass/trunk/lib/python/temporal/temporal_raster3d_algebra.py
===================================================================
--- grass/trunk/lib/python/temporal/temporal_raster3d_algebra.py	2014-11-04 15:04:13 UTC (rev 62593)
+++ grass/trunk/lib/python/temporal/temporal_raster3d_algebra.py	2014-11-04 15:45:52 UTC (rev 62594)
@@ -1,6 +1,7 @@
-"""
-Temporal 3d raster algebra
+"""!@package grass.temporal
 
+Temporal raster algebra
+
 (C) 2013 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
@@ -10,24 +11,21 @@
 
 """
 
+import grass.pygrass.modules as pygrass
 from temporal_raster_base_algebra import *
 
 ###############################################################################
 
-
 class TemporalRaster3DAlgebraParser(TemporalRasterBaseAlgebraParser):
     """The temporal raster algebra class"""
 
-    def __init__(self, pid=None, run=False, debug=True, spatial=False,
-                 nprocs=1, register_null=False):
-        TemporalRasterBaseAlgebraParser.__init__(self, pid, run, debug,
-                                                 spatial, nprocs,
-                                                 register_null)
+    def __init__(self, pid=None, run=False, debug=True, spatial = False, nprocs = 1, register_null = False):
+        TemporalRasterBaseAlgebraParser.__init__(self, pid, run, debug, spatial, nprocs, register_null)
 
         self.m_mapcalc = pymod.Module('r3.mapcalc')
-        self.m_remove = pymod.Module('g.remove')
+        self.m_mremove = pymod.Module('g.remove')
 
-    def parse(self, expression, basename=None, overwrite=False):
+    def parse(self, expression, basename = None, overwrite=False):
         self.lexer = TemporalRasterAlgebraLexer()
         self.lexer.build()
         self.parser = yacc.yacc(module=self, debug=self.debug)
@@ -35,6 +33,8 @@
         self.overwrite = overwrite
         self.count = 0
         self.stdstype = "str3ds"
+        self.maptype = "rast3d"
+        self.mapclass = Raster3DDataset
         self.basename = basename
         self.expression = expression
         self.parser.parse(expression)
@@ -51,9 +51,9 @@
                 stringlist = ",".join(chunk)
 
                 if self.run:
-                    m = copy.deepcopy(self.m_remove)
+                    m = copy.deepcopy(self.m_mremove)
                     m.inputs["type"].value = "rast3d"
-                    m.inputs["name"].value = stringlist
+                    m.inputs["names"].value = stringlist
                     m.flags["f"].value = True
                     m.run()
 
@@ -105,24 +105,17 @@
                     # Get neighboring map and set temporal extent.
                     map_n = maplist[new_index]
                     # Generate an intermediate map for the result map list.
-                    map_new = self.generate_new_map(map_n, bool_op='and',
-                                                    copy=True)
+                    map_new = self.generate_new_map(map_n, bool_op = 'and', copy = True)
                     map_new.set_temporal_extent(map_i_t_extent)
                     # Create r.mapcalc expression string for the operation.
                     if "cmd_list" in dir(map_new) and len(t) == 5:
-                        cmdstring = "%s" % (map_new.cmd_list)
+                        cmdstring = "%s" %(map_new.cmd_list)
                     elif "cmd_list" not in dir(map_new) and len(t) == 5:
-                        cmdstring = "%s" % (map_n.get_id())
-                    elif "cmd_list" in dir(map_new) and len(t) in (9, 11):
-                        cmdstring = "%s[%s,%s,%s]" % (map_new.cmd_list,
-                                                      row_neighbor,
-                                                      col_neighbor,
-                                                      depth_neighbor)
-                    elif "cmd_list" not in dir(map_new) and len(t) in (9, 11):
-                        cmdstring = "%s[%s,%s,%s]" % (map_n.get_id(),
-                                                      row_neighbor,
-                                                      col_neighbor,
-                                                      depth_neighbor)
+                        cmdstring = "%s" %(map_n.get_id())
+                    elif "cmd_list" in dir(map_new) and len(t) in (9,11):
+                        cmdstring = "%s[%s,%s,%s]" %(map_new.cmd_list, row_neighbor, col_neighbor, depth_neighbor)
+                    elif "cmd_list" not in dir(map_new) and len(t) in (9,11):
+                        cmdstring = "%s[%s,%s,%s]" %(map_n.get_id(), row_neighbor, col_neighbor, depth_neighbor)
                     # Set new command list for map.
                     map_new.cmd_list = cmdstring
                     # Append map with updated command list to result list.
@@ -135,3 +128,5 @@
 if __name__ == "__main__":
     import doctest
     doctest.testmod()
+
+

Modified: grass/trunk/lib/python/temporal/temporal_raster_algebra.py
===================================================================
--- grass/trunk/lib/python/temporal/temporal_raster_algebra.py	2014-11-04 15:04:13 UTC (rev 62593)
+++ grass/trunk/lib/python/temporal/temporal_raster_algebra.py	2014-11-04 15:45:52 UTC (rev 62594)
@@ -1,4 +1,5 @@
-"""
+"""!@package grass.temporal
+
 Temporal raster algebra
 
 (C) 2013 by the GRASS Development Team
@@ -55,20 +56,16 @@
 
 ###############################################################################
 
-
 class TemporalRasterAlgebraParser(TemporalRasterBaseAlgebraParser):
     """The temporal raster algebra class"""
 
-    def __init__(self, pid=None, run=False, debug=True, spatial=False,
-                 nprocs=1, register_null=False):
-        TemporalRasterBaseAlgebraParser.__init__(self, pid, run, debug,
-                                                 spatial, nprocs,
-                                                 register_null)
+    def __init__(self, pid=None, run=False, debug=True, spatial = False, nprocs = 1, register_null = False):
+        TemporalRasterBaseAlgebraParser.__init__(self, pid, run, debug, spatial, nprocs, register_null)
 
-        self.m_mapcalc = pymod.Module('r.mapcalc', run_=False, finish_=False)
-        self.m_remove = pymod.Module('g.remove')
+        self.m_mapcalc = pymod.Module('r.mapcalc')
+        self.m_mremove = pymod.Module('g.remove')
 
-    def parse(self, expression, basename=None, overwrite=False):
+    def parse(self, expression, basename = None, overwrite=False):
         self.lexer = TemporalRasterAlgebraLexer()
         self.lexer.build()
         self.parser = yacc.yacc(module=self, debug=self.debug)
@@ -76,12 +73,14 @@
         self.overwrite = overwrite
         self.count = 0
         self.stdstype = "strds"
+        self.maptype = "rast"
+        self.mapclass = RasterDataset
         self.basename = basename
         self.expression = expression
         self.parser.parse(expression)
 
     def remove_empty_maps(self):
-        """! Removes the intermediate vector maps.
+        """! Removes the intermediate raster maps.
         """
         if self.empty_maps:
             self.msgr.message(_("Removing empty raster maps"))
@@ -92,7 +91,7 @@
                 stringlist = ",".join(chunk)
 
                 if self.run:
-                    m = copy.deepcopy(self.m_remove)
+                    m = copy.deepcopy(self.m_mremove)
                     m.inputs["type"].value = "rast"
                     m.inputs["name"].value = stringlist
                     m.flags["f"].value = True
@@ -143,20 +142,17 @@
                     # Get neighbouring map and set temporal extent.
                     map_n = maplist[new_index]
                     # Generate an intermediate map for the result map list.
-                    map_new = self.generate_new_map(map_n, bool_op='and',
-                                                    copy=True)
+                    map_new = self.generate_new_map(map_n, bool_op = 'and', copy = True)
                     map_new.set_temporal_extent(map_i_t_extent)
                     # Create r.mapcalc expression string for the operation.
                     if "cmd_list" in dir(map_new) and len(t) == 5:
-                        cmdstring = "%s" % (map_new.cmd_list)
+                        cmdstring = "%s" %(map_new.cmd_list)
                     elif "cmd_list" not in dir(map_new) and len(t) == 5:
-                        cmdstring = "%s" % (map_n.get_id())
+                        cmdstring = "%s" %(map_n.get_id())
                     elif "cmd_list" in dir(map_new) and len(t) in (7, 9):
-                        cmdstring = "%s[%s,%s]" % (map_new.cmd_list,
-                                                   row_neigbour, col_neigbour)
+                        cmdstring = "%s[%s,%s]" %(map_new.cmd_list, row_neigbour, col_neigbour)
                     elif "cmd_list" not in dir(map_new) and len(t) in (7, 9):
-                        cmdstring = "%s[%s,%s]" % (map_n.get_id(),
-                                                   row_neigbour, col_neigbour)
+                        cmdstring = "%s[%s,%s]" %(map_n.get_id(), row_neigbour, col_neigbour)
                     # Set new command list for map.
                     map_new.cmd_list = cmdstring
                     # Append map with updated command list to result list.
@@ -169,3 +165,5 @@
 if __name__ == "__main__":
     import doctest
     doctest.testmod()
+
+

Modified: grass/trunk/lib/python/temporal/temporal_raster_base_algebra.py
===================================================================
--- grass/trunk/lib/python/temporal/temporal_raster_base_algebra.py	2014-11-04 15:04:13 UTC (rev 62593)
+++ grass/trunk/lib/python/temporal/temporal_raster_base_algebra.py	2014-11-04 15:45:52 UTC (rev 62594)
@@ -1,6 +1,7 @@
-"""
-Temporal raster algebra base class
+"""@package grass.temporal
 
+Temporal raster algebra
+
 (C) 2013 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
@@ -13,94 +14,39 @@
     >>> p = TemporalRasterAlgebraLexer()
     >>> p.build()
     >>> p.debug = True
-    >>> expression =  'R = A / B * 20 + C - 2.45'
+    >>> expression =  'R = A {+,equal,l} B '
     >>> p.test(expression)
-    R = A / B * 20 + C - 2.45
+    R = A {+,equal,l} B 
     LexToken(NAME,'R',1,0)
     LexToken(EQUALS,'=',1,2)
     LexToken(NAME,'A',1,4)
-    LexToken(DIV,'/',1,6)
-    LexToken(NAME,'B',1,8)
-    LexToken(MULT,'*',1,10)
-    LexToken(INT,20,1,12)
-    LexToken(ADD,'+',1,15)
-    LexToken(NAME,'C',1,17)
-    LexToken(SUB,'-',1,19)
-    LexToken(FLOAT,2.45,1,21)
-    >>> expression =  'R = A {equal,|/} B'
+    LexToken(T_ARITH2_OPERATOR,'{+,equal,l}',1,6)
+    LexToken(NAME,'B',1,18)
+    >>> expression =  'R = A {*,equal|during,r} B '
     >>> p.test(expression)
-    R = A {equal,|/} B
+    R = A {*,equal|during,r} B 
     LexToken(NAME,'R',1,0)
     LexToken(EQUALS,'=',1,2)
     LexToken(NAME,'A',1,4)
-    LexToken(T_ARITH1_OPERATOR,'{equal,|/}',1,6)
-    LexToken(NAME,'B',1,17)
-    >>> expression =  'R = A {equal,||} B'
+    LexToken(T_ARITH1_OPERATOR,'{*,equal|during,r}',1,6)
+    LexToken(NAME,'B',1,25)
+    >>> expression =  'R = A {+,equal|during} B '
     >>> p.test(expression)
-    R = A {equal,||} B
+    R = A {+,equal|during} B 
     LexToken(NAME,'R',1,0)
     LexToken(EQUALS,'=',1,2)
     LexToken(NAME,'A',1,4)
-    LexToken(T_COMP_OPERATOR,'{equal,||}',1,6)
-    LexToken(NAME,'B',1,17)
-    >>> expression =  'R = A {equal,&&} B'
-    >>> p.test(expression)
-    R = A {equal,&&} B
-    LexToken(NAME,'R',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(NAME,'A',1,4)
-    LexToken(T_COMP_OPERATOR,'{equal,&&}',1,6)
-    LexToken(NAME,'B',1,17)
-    >>> expression =  'R = A {equal | during,+*} B'
-    >>> p.test(expression)
-    R = A {equal | during,+*} B
-    LexToken(NAME,'R',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(NAME,'A',1,4)
-    LexToken(T_ARITH1_OPERATOR,'{equal | during,+*}',1,6)
-    LexToken(NAME,'B',1,26)
-    >>> expression =  'R = A {equal | during,+:} B'
-    >>> p.test(expression)
-    R = A {equal | during,+:} B
-    LexToken(NAME,'R',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(NAME,'A',1,4)
-    LexToken(T_SELECT_OPERATOR,'{equal | during,+:}',1,6)
-    LexToken(NAME,'B',1,26)
-    >>> expression =  'R = abs(A) {equal,+:} exp(B) / sqrt(C) - log(D)'
-    >>> p.test(expression)
-    R = abs(A) {equal,+:} exp(B) / sqrt(C) - log(D)
-    LexToken(NAME,'R',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(ABS,'abs',1,4)
-    LexToken(LPAREN,'(',1,7)
-    LexToken(NAME,'A',1,8)
-    LexToken(RPAREN,')',1,9)
-    LexToken(T_SELECT_OPERATOR,'{equal,+:}',1,11)
-    LexToken(EXP,'exp',1,22)
-    LexToken(LPAREN,'(',1,25)
-    LexToken(NAME,'B',1,26)
-    LexToken(RPAREN,')',1,27)
-    LexToken(DIV,'/',1,29)
-    LexToken(SQRT,'sqrt',1,31)
-    LexToken(LPAREN,'(',1,35)
-    LexToken(NAME,'C',1,36)
-    LexToken(RPAREN,')',1,37)
-    LexToken(SUB,'-',1,39)
-    LexToken(LOG,'log',1,41)
-    LexToken(LPAREN,'(',1,44)
-    LexToken(NAME,'D',1,45)
-    LexToken(RPAREN,')',1,46)
+    LexToken(T_ARITH2_OPERATOR,'{+,equal|during}',1,6)
+    LexToken(NAME,'B',1,23)
 
 """
 
 import grass.pygrass.modules as pymod
-from temporal_raster_operator import *
+from temporal_operator import *
 from temporal_algebra import *
 
 ##############################################################################
 
-
 class TemporalRasterAlgebraLexer(TemporalAlgebraLexer):
     """Lexical analyzer for the GRASS GIS temporal algebra"""
 
@@ -109,24 +55,27 @@
 
     # Supported r.mapcalc functions.
     mapcalc_functions = {
-        'exp': 'EXP',
-        'log': 'LOG',
-        'sqrt': 'SQRT',
-        'abs': 'ABS',
-        'cos': 'COS',
-        'acos': 'ACOS',
-        'sin': 'SIN',
-        'asin': 'ASIN',
-        'tan': 'TAN',
-        'double': 'DOUBLE',
-        'float': 'FLOATEXP',
-        'int': 'INTEXP',
-        'isnull': 'ISNULL',
+        'exp'     : 'EXP',
+        'log'     : 'LOG',
+        'sqrt'    : 'SQRT',
+        'abs'     : 'ABS',
+        'cos'     : 'COS',
+        'acos'    : 'ACOS',
+        'sin'     : 'SIN',
+        'asin'    : 'ASIN',
+        'tan'     : 'TAN',
+        'double'  : 'DOUBLE',
+        'float'   : 'FLOATEXP',
+        'int'     : 'INTEXP',
+        'isnull'  : 'ISNULL',
         'isntnull': 'ISNTNULL',
-        'null': 'NULL',
-        'exist': 'EXIST',
+        'null'    : 'NULL',
+        'exist'   : 'EXIST',   
     }
-
+    
+    # Functions that defines single maps with time stamp and without temporal extent.
+    map_functions = {'map' : 'MAP'}
+    
     # This is the list of token names.
     raster_tokens = (
         'MOD',
@@ -141,19 +90,21 @@
     )
 
     # Build the token list
-    tokens = TemporalAlgebraLexer.tokens + raster_tokens \
-             + tuple(mapcalc_functions.values())
+    tokens = TemporalAlgebraLexer.tokens \
+                    + raster_tokens \
+                    + tuple(mapcalc_functions.values()) \
+                    + tuple(map_functions.values())
 
     # Regular expression rules for simple tokens
-    t_MOD = r'[\%]'
-    t_DIV = r'[\/]'
-    t_MULT = r'[\*]'
-    t_ADD = r'[\+]'
-    t_SUB = r'[-]'
-    t_T_ARITH1_OPERATOR = r'\{([a-zA-Z\| ]+[,])?([\|&+=]?[\%\*\/])\}'
-    t_T_ARITH2_OPERATOR = r'\{([a-zA-Z\| ]+[,])?([\|&+=]?[+-])\}'
-    t_L_SPAREN = r'\['
-    t_R_SPAREN = r'\]'
+    t_MOD                 = r'[\%]'
+    t_DIV                 = r'[\/]'
+    t_MULT                = r'[\*]'
+    t_ADD                 = r'[\+]'
+    t_SUB                 = r'[-]'
+    t_T_ARITH1_OPERATOR   = r'\{[\%\*\/][,]?[a-zA-Z\| ]*([,])?([lrudi]|left|right|union|disjoint|intersect)?\}'
+    t_T_ARITH2_OPERATOR   = r'\{[+-][,]?[a-zA-Z\| ]*([,])?([lrudi]|left|right|union|disjoint|intersect)?\}'
+    t_L_SPAREN            = r'\['
+    t_R_SPAREN            = r'\]'
 
     # Parse symbols
     def temporal_symbol(self, t):
@@ -166,14 +117,14 @@
             t.type = TemporalRasterAlgebraLexer.conditional_functions.get(t.value)
         elif t.value in TemporalRasterAlgebraLexer.mapcalc_functions.keys():
             t.type = TemporalRasterAlgebraLexer.mapcalc_functions.get(t.value)
+        elif t.value in TemporalRasterAlgebraLexer.map_functions.keys():
+            t.type = TemporalRasterAlgebraLexer.map_functions.get(t.value)
         else:
             t.type = 'NAME'
         return t
 
-#########
-#####################################################################
+##############################################################################
 
-
 class TemporalRasterBaseAlgebraParser(TemporalAlgebraParser):
     """The temporal algebra class"""
 
@@ -182,13 +133,13 @@
 
     # Setting equal precedence level for select and hash operations.
     precedence = (
-        ('left', 'T_SELECT_OPERATOR', 'T_SELECT', 'T_NOT_SELECT'),  # 1
-        ('left', 'ADD', 'SUB', 'T_ARITH2_OPERATOR'),  #2
+        ('left', 'T_SELECT_OPERATOR', 'T_SELECT', 'T_NOT_SELECT'), # 1
+        ('left', 'ADD', 'SUB', 'T_ARITH2_OPERATOR'), #2
         ('left', 'AND', 'OR', 'T_COMP_OPERATOR', 'MOD', 'DIV', 'MULT',
          'T_ARITH1_OPERATOR'))
 
-    def __init__(self, pid=None, run=True, debug=False, spatial=False,
-                 nprocs=1, register_null=False):
+    def __init__(self, pid=None, run = True, debug = False, spatial = False, \
+                  nprocs = 1, register_null = False):
         TemporalAlgebraParser.__init__(self, pid, run, debug, spatial)
         self.nprocs = nprocs
         self.empty_maps = {}
@@ -202,73 +153,384 @@
             return "null()"
 
     ######################### Temporal functions ##############################
+    def get_temporal_topo_list(self, maplistA, maplistB = None, topolist = ["EQUAL"],
+                               assign_val = False, count_map = False, compare_bool = False,  
+                               compare_cmd = False,  compop = None, aggregate = None,  
+                               new = False,  convert = False,  operator_cmd = False):
+        """Build temporal topology for two space time data sets, copy map objects
+          for given relation into map list.
+          
+          :param maplistA: List of maps.
+          :param maplistB: List of maps.
+          :param topolist: List of strings of temporal relations.
+          :param assign_val: Boolean for assigning a boolean map value based on
+                            the map_values from the compared map list by
+                            topological relationships.
+          :param count_map: Boolean if the number of topological related maps
+                           should be returned.
+          :param compare_bool: Boolean for comparing boolean map values based on
+                            related map list and compariosn operator.
+          :param compare_cmd: Boolean for comparing command list values based on
+                            related map list and compariosn operator.
+          :param compop: Comparison operator, && or ||.
+          :param aggregate: Aggregation operator for relation map list, & or |.
+          :param new: Boolean if new temporary maps should be created.
+          :param convert: Boolean if conditional values should be converted to 
+                        r.mapcalc command strings.
+          :param operator_cmd: Boolean for aggregate arithmetic operators implicitly 
+                        in command list values based on related map lists.
+                    
+          :return: List of maps from maplistA that fulfil the topological relationships
+                  to maplistB specified in topolist.
+        """
+        topologylist = ["EQUAL", "FOLLOWS", "PRECEDES", "OVERLAPS", "OVERLAPPED", \
+                        "DURING", "STARTS", "FINISHES", "CONTAINS", "STARTED", \
+                        "FINISHED"]
+        complementdict = {"EQUAL": "EQUAL", "FOLLOWS" : "PRECEDES",
+                          "PRECEDES" : "FOLLOWS", "OVERLAPS" : "OVERLAPPED",
+                          "OVERLAPPED" : "OVERLAPS", "DURING" : "CONTAINS",
+                          "CONTAINS" : "DURING", "STARTS" : "STARTED",
+                          "STARTED" : "STARTS", "FINISHES" : "FINISHED",
+                          "FINISHED" : "FINISHES"}
+        resultdict = {}
+        # Check if given temporal relation are valid.
+        for topo in topolist:
+          if topo.upper() not in topologylist:
+              raise SyntaxError("Unpermitted temporal relation name '" + topo + "'")
 
-    def eval_toperator(self, operator, comparison=False):
-        """This function evaluates a string containing temporal operations.
+        # Create temporal topology for maplistA to maplistB.
+        tb = SpatioTemporalTopologyBuilder()
+        # Dictionary with different spatial variables used for topology builder.
+        spatialdict = {'strds' : '2D', 'stvds' : '2D', 'str3ds' : '3D'}
+        # Build spatial temporal topology
+        if self.spatial:
+            tb.build(maplistA, maplistB, spatial = spatialdict[self.stdstype])
+        else:
+            tb.build(maplistA, maplistB)
+        # Iterate through maps in maplistA and search for relationships given
+        # in topolist.
+        for map_i in maplistA:
+            tbrelations = map_i.get_temporal_relations()
+            # Check for boolean parameters for further calculations.
+            if assign_val:
+                self.assign_bool_value(map_i,  tbrelations,  topolist)
+            elif compare_bool:
+                self.compare_bool_value(map_i,  tbrelations, compop, aggregate, topolist)
+            elif compare_cmd:
+                self.compare_cmd_value(map_i,  tbrelations, compop, aggregate, topolist, convert)
+            elif operator_cmd:
+                self.operator_cmd_value(map_i,  tbrelations, compop, topolist)
+                
+            for topo in topolist:
+                if topo.upper() in tbrelations.keys():
+                    if count_map:
+                        relationmaplist = tbrelations[topo.upper()]
+                        gvar = GlobalTemporalVar()
+                        gvar.td = len(relationmaplist)
+                        if "map_value" in dir(map_i):
+                            map_i.map_value.append(gvar)
+                        else:
+                            map_i.map_value = gvar
+                    resultdict[map_i.get_id()] = map_i
+        resultlist = resultdict.values()
+        
+        # Sort list of maps chronological.
+        resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
+        
+        return(resultlist)    
+    
+    def build_command_string(self, map_i,  relmap, operator = None, cmd_type = None):
+        """This function build the r.mapcalc command string for conditionals, 
+            spatial variable combinations and boolean comparisons.
+            
+            For Example: 'if(a1 == 1, b1, c2)' or 'exist(a1) && sin(b1)'
+            
+            :param map_i: map object with temporal extent and built relations.
+            :param relmap: map object with defined temporal relation to map_i.
+            :param operator: String representing operator between two spatial variables 
+                            (&&,||,+,-,*,/).
+            :param cmd_type: map object with defined temporal relation to map_i:
+                            condition, conclusion or operator.
+            
+            :return: the resulting command string for conditionals or spatial variable 
+                combinations
+        """    
+        def sub_cmdstring(map_i):
+            """This function search for command string in a map object and 
+            return substitute string (contained commandstring or map name)"""
+            if "cmd_list" in dir(map_i):
+                map_sub = map_i.cmd_list
+            elif "map_value" in dir(map_i) and len(map_i.map_value) > 0 and map_i.map_value[0].get_type() == "timediff":
+                map_sub = map_i.map_value[0].get_type_value()[0]
+            else:
+                try:
+                    map_sub = map_i.get_id()
+                except:
+                    map_sub = map_i
+            return(map_sub)
+        
+        # Check  for type of operation, conditional or spatial variable combination 
+        # and Create r.mapcalc expression string for the operation.
+        cmdstring = ""
+        if cmd_type == 'condition':
+            conditionsub = sub_cmdstring(map_i)
+            conclusionsub = sub_cmdstring(relmap)
+            cmdstring = "if(%s, %s)" %(conditionsub, conclusionsub)
+        elif cmd_type == 'conclusion':
+            thensub = sub_cmdstring(map_i)
+            elsesub = sub_cmdstring(relmap)
+            cmdstring = "%s, %s" %(thensub, elsesub)
+        elif cmd_type == 'operator':
+            leftsub = sub_cmdstring(map_i)
+            rightsub = sub_cmdstring(relmap)
+            if operator == None:
+                self.msgr.fatal("Error: Can't build command string for map %s, operator is missing" \
+                    %(map_i.get_map_id()))
+            cmdstring = "(%s %s %s)" %(leftsub, operator,  rightsub)
+        return(cmdstring)
 
-         :param operator: String of temporal operations, e.g. {equal|during,=!:}.
+    def compare_cmd_value(self,  map_i, tbrelations, compop, aggregate,  
+                                                topolist = ["EQUAL"],  convert = False):
+        """ Function to evaluate two map lists with boolean values by boolean 
+            comparison operator. Extended temporal algebra version with command 
+            list builder for temporal raster algebra.
+            
+            :param map_i: Map object with temporal extent.
+            :param tbrelations: List of temporal relation to map_i.
+            :param topolist: List of strings for given temporal relations.
+            :param compop: Comparison operator, && or ||.
+            :param aggregate: Aggregation operator for relation map list, & or |.
+            :param convert: Boolean if conditional values should be converted to 
+                        r.mapcalc command strings.
 
-         :return: List of temporal relations (equal, during), the given
-                  function (!:) and the interval/instances (=).
+            :return: Map object with conditional value that has been evaluated by
+                        comparison operators.
+        """
+        # Build comandlist list with elements from related maps and given relation operator.
+        if convert and "condition_value" in dir(map_i):
+            if map_i.condition_value != []:
+                cmdstring = str(int(map_i.condition_value[0]))
+                map_i.cmd_list = cmdstring
+        if "cmd_list" in dir(map_i):
+            leftcmd = map_i.cmd_list
+            cmd_value_list = [leftcmd]
+        count = 0
+        
+        for topo in topolist:
+            if topo.upper() in tbrelations.keys():
+                relationmaplist = tbrelations[topo.upper()]
+                if count == 0 and "cmd_list" in dir(map_i):
+                    cmd_value_list.append(compop)
+                    cmd_value_list.append('(')
+                for relationmap in relationmaplist:
+                    if convert and "condition_value" in dir(relationmap):
+                        if relationmap.condition_value != []:
+                            cmdstring = str(int(relationmap.condition_value[0]))
+                            relationmap.cmd_list = cmdstring
+                    if "cmd_list" in dir(relationmap):
+                        if count > 0:
+                            cmd_value_list.append(aggregate + aggregate)
+                        cmd_value_list.append(relationmap.cmd_list)
+                        count = count + 1
+        if count > 0:
+            cmd_value_list.append(')')
+            cmd_value_str = ''.join(map(str, cmd_value_list))
+            # Add command list to result map.
+            map_i.cmd_list = cmd_value_str
+        
+            return(cmd_value_str)
 
-        .. code-block:: python
+    def operator_cmd_value(self,  map_i, tbrelations, operator, topolist = ["EQUAL"]):
+        """ Function to evaluate two map lists by given arithmetic operator.
+        
+            :param map_i: Map object with temporal extent.
+            :param tbrelations: List of temporal relation to map_i.
+            :param topolist: List of strings for given temporal relations.
+            :param operator: Arithmetic operator, +-*/%.
 
-             >>> init(True)
-             >>> p = TemporalRasterBaseAlgebraParser()
-             >>> operator = "{equal,:}"
-             >>> p.eval_toperator(operator)
-             (['EQUAL'], '=', ':')
-             >>> operator = "{equal|during,:}"
-             >>> p.eval_toperator(operator)
-             (['EQUAL', 'DURING'], '=', ':')
-             >>> operator = "{equal,!:}"
-             >>> p.eval_toperator(operator)
-             (['EQUAL'], '=', '!:')
-             >>> operator = "{equal|during,!:}"
-             >>> p.eval_toperator(operator)
-             (['EQUAL', 'DURING'], '=', '!:')
-             >>> operator = "{equal|during,=!:}"
-             >>> p.eval_toperator(operator)
-             (['EQUAL', 'DURING'], '=', '!:')
-             >>> operator = "{equal|during|starts,#}"
-             >>> p.eval_toperator(operator)
-             (['EQUAL', 'DURING', 'STARTS'], '=', '#')
-             >>> operator = "{!:}"
-             >>> p.eval_toperator(operator)
-             (['EQUAL'], '=', '!:')
-             >>> operator = "{=:}"
-             >>> p.eval_toperator(operator)
-             (['EQUAL'], '=', ':')
-             >>> operator = "{#}"
-             >>> p.eval_toperator(operator)
-             (['EQUAL'], '=', '#')
-             >>> operator = "{equal|during}"
-             >>> p.eval_toperator(operator)
-             (['EQUAL', 'DURING'], None, None)
-             >>> operator = "{equal}"
-             >>> p.eval_toperator(operator)
-             (['EQUAL'], None, None)
-             >>> operator = "{equal,||}"
-             >>> p.eval_toperator(operator, True)
-             (['EQUAL'], '=', '||')
-             >>> operator = "{equal|during,&&}"
-             >>> p.eval_toperator(operator, True)
-             (['EQUAL', 'DURING'], '=', '&&')
+            :return: Map object with command list with  operators that has been 
+                        evaluated by implicit aggregration.
+        """
+        # Build comandlist list with elements from related maps and given relation operator.
+        leftcmd = map_i
+        cmdstring = ""
+        for topo in topolist:
+            if topo.upper() in tbrelations.keys():
+                relationmaplist = tbrelations[topo.upper()]
+                for relationmap in relationmaplist:
+                    # Create r.mapcalc expression string for the operation.
+                    cmdstring = self.build_command_string(leftcmd,  
+                                                                                        relationmap, 
+                                                                                        operator = operator, 
+                                                                                        cmd_type = "operator")
+                    leftcmd = cmdstring
+        # Add command list to result map.
+        map_i.cmd_list = cmdstring
+        
+        return(cmdstring)
+    
+    def set_temporal_extent_list(self, maplist, topolist = ["EQUAL"], temporal = 'l' , 
+                                                        cmd_bool = False, cmd_type = None,  operator = None):
+        """ Change temporal extent of map list based on temporal relations to 
+                other map list and given temporal operator.
 
+            :param maplist: List of map objects for which relations has been build 
+                                        correctely.
+            :param topolist: List of strings of temporal relations.
+            :param temporal: The temporal operator specifying the temporal
+                                            extent operation (intersection, union, disjoint 
+                                            union, right reference, left reference).
+            :param cmd_bool: Boolean if command string should be merged for related maps.
+            :param cmd_type: map object with defined temporal relation to map_i:
+                            condition, conclusion or operator.
+            :param operator: String defining the type of operator.
+
+            :return: Map list with specified temporal extent and optional command string.
         """
-        p = TemporalRasterOperatorParser()
-        p.parse(operator, comparison)
-        p.relations = [rel.upper() for rel in p.relations]
+        resultdict = {}
+        
+        for map_i in maplist:
+            # Loop over temporal related maps and create overlay modules.
+            tbrelations = map_i.get_temporal_relations()
+            # Generate an intermediate map for the result map list.
+            map_new = self.generate_new_map(base_map=map_i, bool_op = 'and', 
+                                                                        copy = True,  rename = True)
+            # Combine temporal and spatial extents of intermediate map with related maps.
+            for topo in topolist:
+                if topo in tbrelations.keys():
+                    for map_j in (tbrelations[topo]):
+                        if temporal == 'r':
+                            # Generate an intermediate map for the result map list.
+                            map_new = self.generate_new_map(base_map=map_i, bool_op = 'and', 
+                                                                                        copy = True,  rename = True)
+                        # Create overlayed map extent.
+                        returncode = self.overlay_map_extent(map_new, map_j, 'and', \
+                                                                temp_op = temporal)
+                        # Stop the loop if no temporal or spatial relationship exist.
+                        if returncode == 0:
+                            break
+                        # Append map to result map list.
+                        elif returncode == 1:
+                            # print(map_new.cmd_list)
+                            # resultlist.append(map_new)
+                            if cmd_bool:
+                                # Create r.mapcalc expression string for the operation.
+                                cmdstring = self.build_command_string(map_i,  
+                                                                                                    map_j, 
+                                                                                                    operator = operator, 
+                                                                                                    cmd_type = cmd_type)
+                                # Conditional append of module command.
+                                map_new.cmd_list = cmdstring
+                            # Write map object to result dictionary.
+                            resultdict[map_new.get_id()] = map_new
+                    if returncode == 0:
+                        break
+            # Append map to result map list.
+            #if returncode == 1:
+            #    resultlist.append(map_new)
+        # Get sorted map objects as values from result dictionoary.
+        resultlist = resultdict.values()
+        resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
+        
+        return(resultlist)
+    
+    def build_condition_cmd_list(self, iflist, thenlist,  elselist = None,  
+                                                        condition_topolist = ["EQUAL"], 
+                                                        conclusion_topolist = ["EQUAL"], 
+                                                        temporal = 'l', null = False):
+        """This function build the r.mapcalc command strings for spatial conditionals.
+            For Example: 'if(a1 == 1, b1, c2)'
 
-        return(p.relations, p.temporal, p.function)
+            :param iflist: Map list with temporal extents and command list.
+            :param thenlist: Map list with temporal extents and command list or numeric string.
+            :param elselist: Map list with temporal extents and command list or numeric string.
+            :param condition_topolist: List of strings for given temporal relations between 
+                            conditions and conclusions.
+            :param conclusion_topolist: List of strings for given temporal relations between 
+                            conditions (then and else).
+            :param temporal: The temporal operator specifying the temporal
+                                            extent operation (intersection, union, disjoint 
+                                            union, right reference, left reference).
+            :param null: Boolean if null map support should be activated.
 
+            :return: map list with resulting command string for given condition type.
+        """    
+        resultlist = []
+        # First merge conclusion command maplists or strings.
+        # Check if alternative conclusion map list is given.
+        if all([isinstance(thenlist, list), isinstance(elselist, list)]):
+            # Build conclusion command map list.
+            conclusiontopolist = self.get_temporal_topo_list(thenlist, elselist,  conclusion_topolist)
+            conclusionlist = self.set_temporal_extent_list(conclusiontopolist, 
+                                                                                    topolist = conclusion_topolist, 
+                                                                                    temporal = temporal , 
+                                                                                    cmd_bool = True, 
+                                                                                    cmd_type = "conclusion")
+        # Check if any conclusion is a numeric statements.
+        elif any([isinstance(thenlist, str), isinstance(elselist, str)]):
+            conclusionlist = []            
+            # Check if only alternative conclusion is a numeric statements.
+            if all([isinstance(thenlist, list), isinstance(elselist, str)]):
+                listinput = thenlist
+                numinput = elselist
+                for map_i in listinput:
+                    # Create r.mapcalc expression string for the operation.
+                    cmdstring = self.build_command_string( map_i,  
+                                                                                            numinput, 
+                                                                                            cmd_type = 'conclusion')
+                    # Conditional append of module command.
+                    map_i.cmd_list = cmdstring
+                    # Append map to result map list.
+                    conclusionlist.append(map_i)
+            # Check if only direct conclusion is a numeric statements.
+            elif all([isinstance(thenlist, str), isinstance(elselist, list)]):                
+                listinput = elselist
+                numinput =  thenlist
+                for map_i in listinput:
+                    # Create r.mapcalc expression string for the operation.
+                    cmdstring = self.build_command_string(numinput,  
+                                                                                            map_i,  
+                                                                                            cmd_type = 'conclusion')
+                    # Conditional append of module command.
+                    map_i.cmd_list = cmdstring
+                    # Append map to result map list.
+                    conclusionlist.append(map_i)
+            elif all([isinstance(thenlist, str), isinstance(elselist, str)]):
+                conclusionlist = thenlist + ',' + elselist
+        else:
+            # The direct conclusion is used.
+            conclusionlist = thenlist
+        # Use the conclusion map or string to merge it with the condition and 
+        # return maplist.
+        if isinstance(conclusionlist,  str):
+            resultlist = []
+            for map_i in iflist:
+                # Create r.mapcalc expression string for the operation.
+                cmdstring = self.build_command_string(map_i,  
+                                                                                        conclusionlist,  
+                                                                                        cmd_type = 'condition')
+                # Conditional append of module command.
+                map_i.cmd_list = cmdstring
+                # Append map to result map list.
+                resultlist.append(map_i)
+            return(resultlist)
+        elif isinstance(conclusionlist,  list):
+            # Build result command map list between conditions and conclusions.
+            conditiontopolist = self.get_temporal_topo_list(iflist, conclusionlist,  
+                                                                                        topolist = condition_topolist)
+            resultlist = self.set_temporal_extent_list(conditiontopolist, 
+                                                                            topolist = condition_topolist, 
+                                                                            temporal = 'r' , 
+                                                                            cmd_bool = True, 
+                                                                            cmd_type = "condition")
+            return(resultlist)
+
     ###########################################################################
 
     def p_statement_assign(self, t):
         # The expression should always return a list of maps.
         """
         statement : stds EQUALS expr
-
         """
         if self.run:
             # Create the process queue for parallel mapcalc processing
@@ -276,20 +538,19 @@
             if isinstance(t[3], list):
                 num = len(t[3])
                 count = 0
+                returncode = 0
                 register_list = []
                 for i in range(num):
                     # Check if resultmap names exist in GRASS database.
                     rastername = self.basename + "_" + str(i) + "@" + self.mapset
                     rastermap = RasterDataset(rastername)
-                    if rastermap.map_exists() and self.overwrite is False:
-                        self.msgr.fatal("Error raster maps with basename %s "
-                                        "exist. Use --o flag to overwrite "
-                                        "existing file" % (rastername))
+                    if rastermap.map_exists() and self.overwrite == False:
+                        self.msgr.fatal("Error raster maps with basename %s exist. Use --o flag to overwrite existing file" \
+                                            %(rastername))
                 map_test_list = []
                 for map_i in t[3]:
                     newident = self.basename + "_" + str(count)
                     if "cmd_list" in dir(map_i):
-                        print(newident + ' = ' + map_i.cmd_list)
                         # Build r.mapcalc module and execute expression.
                         # Change map name to given basename.
                         # Create deepcopy of r.mapcalc module.
@@ -304,31 +565,39 @@
                         m.inputs["expression"].value = str(m_expression)
                         m.flags["overwrite"].value = self.overwrite
                         process_queue.put(m)
+                    
+                    elif map_i.map_exists():
+                        map_test = map_i.get_new_instance(newident + "@" + self.mapset)
+                        map_test.set_temporal_extent(map_i.get_temporal_extent())
+                        map_test.set_spatial_extent(map_i.get_spatial_extent())
+                        map_test_list.append(map_test)
+                        
+                        m = copy.deepcopy(self.m_mapcalc)
+                        m_expression = newident + "=" + map_i.get_map_id()
+                        m.inputs["expression"].value = str(m_expression)
+                        m.flags["overwrite"].value = self.overwrite
+                        process_queue.put(m)
+                        
                     else:
-                        map_i.set_id(newident + "@" + self.mapset)
-                        map_test_list.append(map_i)
-                    count += 1
+                        self.msgr.error(_("Error computing map <%s>"%(map_i.get_id()) ))
+                    count  += 1
 
                 process_queue.wait()
 
                 for map_i in map_test_list:
-                    if not map_test.map_exists():
-                        self.msgr.error(_("Error computing map <%s>" %
-                                          (map_i.get_id())))
-                    else:
-                        register_list.append(map_i)
+                    register_list.append(map_i)
 
                 # Open connection to temporal database.
                 dbif, connect = init_dbif(self.dbif)
                 # Create result space time dataset.
-                resultstds = open_new_stds(t[1], self.stdstype, 'absolute',
-                                           t[1], t[1], 'mean', self.dbif,
-                                           overwrite=self.overwrite)
+                resultstds = open_new_stds(t[1], self.stdstype, \
+                                                         'absolute', t[1], t[1], \
+                                                         'mean', self.dbif, \
+                                                         overwrite = self.overwrite)
                 for map_i in register_list:
                     # Get meta data from grass database.
                     map_i.load()
                     # Do not register empty maps if not required
-
                     # In case of a null map continue, do not register null maps
                     if map_i.metadata.get_min() is None and \
                        map_i.metadata.get_max() is None:
@@ -339,12 +608,10 @@
                     if map_i.is_in_db(dbif) and self.overwrite:
                         # Update map in temporal database.
                         map_i.update_all(dbif)
-                    elif map_i.is_in_db(dbif) and self.overwrite is False:
+                    elif map_i.is_in_db(dbif) and self.overwrite == False:
                         # Raise error if map exists and no overwrite flag is given.
-                        self.msgr.fatal("Error vector map %s exist in temporal"
-                                        " database. Use overwrite flag.  : "
-                                        "\n%s" % (map_i.get_map_id(),
-                                                  cmd.popen.stderr))
+                        self.msgr.fatal("Error raster map %s exist in temporal database. Use overwrite flag.  : \n%s" \
+                                            %(map_i.get_map_id(), cmd.popen.stderr))
                     else:
                         # Insert map into temporal database.
                         map_i.insert(dbif)
@@ -355,7 +622,45 @@
                 t[0] = register_list
 
                 self.remove_empty_maps()
+    
+    def p_expr_spmap_function(self, t):
+        # Add a single map.
+        # Only the spatial extent of the map is evaluated. 
+        # Temporal extent is not existing.
+        # Examples:
+        #    R = map(A) 
+        """
+        mapexpr : MAP LPAREN stds RPAREN
+        """
+        if self.run:
+            # Check input map.
+            input = t[3]
+            if not isinstance(input, list):
+                # Check for mapset in given stds input.
+                if input.find("@") >= 0:
+                    id_input = input
+                else:
+                    id_input = input + "@" + self.mapset
+                # Create empty map dataset.
+                map_i = dataset_factory(self.maptype, id_input)
+                # Check for occurence of space time dataset.
+                if map_i.map_exists() == False:
+                    raise FatalError(_("%s map <%s> not found in GRASS spatial database") %
+                        (map_i.get_type(), id_input))
+                else:
+                    # Select dataset entry from database.
+                    map_i.select(dbif=self.dbif)
+                    # Create command list for map object.
+                    cmdstring = "(%s)" %(map_i.get_map_id())
+                    map_i.cmd_list = cmdstring
+            # Return map object.
+            t[0] = cmdstring
+        else:
+            t[0] = "map(" + t[3] + ")"
 
+        if self.debug:
+            print "map(" + t[3] + ")"
+
     def p_arith1_operation(self, t):
         """
         expr : stds MOD stds
@@ -380,23 +685,21 @@
         # Check input stds.
         maplistA = self.check_stds(t[1])
         maplistB = self.check_stds(t[3])
+        
         topolist = self.get_temporal_topo_list(maplistA, maplistB)
 
         if self.run:
             resultlist = []
             for map_i in topolist:
                 # Generate an intermediate map for the result map list.
-                map_new = self.generate_new_map(base_map=map_i, bool_op='and',
-                                                copy=True)
-                # Set first input for overlay module.
-                mapainput = map_i.get_id()
+                map_new = self.generate_new_map(base_map=map_i, bool_op = 'and', copy = True)
                 # Loop over temporal related maps and create overlay modules.
                 tbrelations = map_i.get_temporal_relations()
                 count = 0
                 for map_j in (tbrelations['EQUAL']):
                     # Create overlayed map extent.
-                    returncode = self.overlay_map_extent(map_new, map_j, 'and',
-                                                         temp_op='=')
+                    returncode = self.overlay_map_extent(map_new, map_j, 'and', \
+                                                            temp_op = 'l')
                     # Stop the loop if no temporal or spatial relationship exist.
                     if returncode == 0:
                         break
@@ -407,28 +710,12 @@
                         # Generate an intermediate map
                         name = self.generate_map_name()
 
-                    if "map_value" in dir(map_j) and len(map_j.map_value) > 0 and map_j.map_value[0].get_type() == "timediff":
-                        mapbinput = map_j.map_value[0].get_type_value()[0]
-                    else:
-                        # Set first input for overlay module.
-                        mapbinput = map_j.get_id()
-
                     # Create r.mapcalc expression string for the operation.
-                    if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_j):
-                        cmdstring = "(%s %s %s)" % (map_new.cmd_list, t[2],
-                                                    mapbinput)
-                    elif "cmd_list" in dir(map_j) and "cmd_list" not in dir(map_new):
-                        cmdstring = "(%s %s %s)" % (mapainput, t[2],
-                                                    map_j.cmd_list)
-                    elif "cmd_list" in dir(map_j) and "cmd_list" in dir(map_new):
-                        cmdstring = "(%s %s %s)" % (map_new.cmd_list, t[2],
-                                                    map_j.cmd_list)
-                    else:
-                        cmdstring = "(%s %s %s)" % (mapainput, t[2], mapbinput)
+                    cmdstring = self.build_command_string(map_i, map_j,  
+                                                                                    operator = t[2], 
+                                                                                    cmd_type = "operator")
                     # Conditional append of module command.
                     map_new.cmd_list = cmdstring
-                    # Set new map name to temporary map name.
-                    mapainput = name
                     count += 1
                 # Append map to result map list.
                 if returncode == 1:
@@ -443,11 +730,23 @@
     def p_arith1_operation_numeric1(self, t):
         """
         expr : stds MOD number
-             | expr MOD number
-             | stds DIV number
-             | expr DIV number
-             | stds MULT number
-             | expr MULT number
+            | expr MOD number
+            | stds DIV number
+            | expr DIV number
+            | stds MULT number
+            | expr MULT number
+            | stds MOD numberstr
+            | expr MOD numberstr
+            | stds DIV numberstr
+            | expr DIV numberstr
+            | stds MULT numberstr
+            | expr MULT numberstr            
+            | stds MOD mapexpr
+            | expr MOD mapexpr
+            | stds DIV mapexpr
+            | expr DIV mapexpr
+            | stds MULT mapexpr
+            | expr MULT mapexpr            
         """
         # Check input stds.
         maplist = self.check_stds(t[1])
@@ -458,9 +757,9 @@
                 mapinput = map_i.get_id()
                 # Create r.mapcalc expression string for the operation.
                 if "cmd_list" in dir(map_i):
-                    cmdstring = "(%s %s %s)" % (map_i.cmd_list, t[2], t[3])
+                    cmdstring = "(%s %s %s)" %(map_i.cmd_list, t[2], t[3])
                 else:
-                    cmdstring = "(%s %s %s)" % (mapinput, t[2], t[3])
+                    cmdstring = "(%s %s %s)" %(mapinput, t[2], t[3])
                 # Conditional append of module command.
                 map_i.cmd_list = cmdstring
                 # Append map to result map list.
@@ -472,14 +771,27 @@
             for map in resultlist:
                 print map.cmd_list
 
+
     def p_arith1_operation_numeric2(self, t):
         """
         expr : number MOD stds
-             | number MOD expr
-             | number DIV stds
-             | number DIV expr
-             | number MULT stds
-             | number MULT expr
+            | number MOD expr
+            | number DIV stds
+            | number DIV expr
+            | number MULT stds
+            | number MULT expr
+            | numberstr MOD stds
+            | numberstr MOD expr
+            | numberstr DIV stds
+            | numberstr DIV expr
+            | numberstr MULT stds
+            | numberstr MULT expr            
+            | mapexpr MOD stds
+            | mapexpr MOD expr
+            | mapexpr DIV stds
+            | mapexpr DIV expr
+            | mapexpr MULT stds
+            | mapexpr MULT expr             
         """
         # Check input stds.
         maplist = self.check_stds(t[3])
@@ -490,9 +802,9 @@
                 mapinput = map_i.get_id()
                 # Create r.mapcalc expression string for the operation.
                 if "cmd_list" in dir(map_i):
-                    cmdstring = "(%s %s %s)" % (t[1], t[2], map_i.cmd_list)
+                    cmdstring = "(%s %s %s)" %(t[1], t[2], map_i.cmd_list)
                 else:
-                    cmdstring = "(%s %s %s)" % (t[1], t[2], mapinput)
+                    cmdstring = "(%s %s %s)" %(t[1], t[2], mapinput)
                 # Conditional append of module command.
                 map_i.cmd_list = cmdstring
                 # Append map to result map list.
@@ -504,6 +816,7 @@
             for map in resultlist:
                 print map.cmd_list
 
+
     def p_arith2_operation(self, t):
         """
         expr : stds ADD stds
@@ -529,17 +842,15 @@
             resultlist = []
             for map_i in topolist:
                 # Generate an intermediate map for the result map list.
-                map_new = self.generate_new_map(base_map=map_i, bool_op='and',
-                                                copy=True)
-                # Set first input for overlay module.
-                mapainput = map_i.get_id()
+                map_new = self.generate_new_map(base_map=map_i, bool_op = 'and', copy = True)
+
                 # Loop over temporal related maps and create overlay modules.
                 tbrelations = map_i.get_temporal_relations()
                 count = 0
                 for map_j in (tbrelations['EQUAL']):
                     # Create overlayed map extent.
-                    returncode = self.overlay_map_extent(map_new, map_j, 'and',
-                                                         temp_op='=')
+                    returncode = self.overlay_map_extent(map_new, map_j, 'and', \
+                                                            temp_op = 'l')
                     # Stop the loop if no temporal or spatial relationship exist.
                     if returncode == 0:
                         break
@@ -549,29 +860,13 @@
                     else:
                         # Generate an intermediate map
                         name = self.generate_map_name()
-
-                    if "map_value" in dir(map_j) and len(map_j.map_value) > 0 and map_j.map_value[0].get_type() == "timediff":
-                        mapbinput = map_j.map_value[0].get_type_value()[0]
-                    else:
-                        # Set first input for overlay module.
-                        mapbinput = map_j.get_id()
-
+                    
                     # Create r.mapcalc expression string for the operation.
-                    if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_j):
-                        cmdstring = "(%s %s %s)" % (map_new.cmd_list, t[2],
-                                                    mapbinput)
-                    elif "cmd_list" in dir(map_j) and "cmd_list" not in dir(map_new):
-                        cmdstring = "(%s %s %s)" % (mapainput, t[2],
-                                                    map_j.cmd_list)
-                    elif "cmd_list" in dir(map_j) and "cmd_list" in dir(map_new):
-                        cmdstring = "(%s %s %s)" % (map_new.cmd_list, t[2],
-                                                    map_j.cmd_list)
-                    else:
-                        cmdstring = "(%s %s %s)" % (mapainput, t[2], mapbinput)
+                    cmdstring = self.build_command_string(map_i, map_j,  
+                                                                                    operator = t[2], 
+                                                                                    cmd_type = "operator")
                     # Conditional append of module command.
                     map_new.cmd_list = cmdstring
-                    # Set new map name to temporary map name.
-                    mapainput = name
                     count += 1
 
                 # Append map to result map list.
@@ -587,9 +882,17 @@
     def p_arith2_operation_numeric1(self, t):
         """
         expr : stds ADD number
-             | expr ADD number
-             | stds SUB number
-             | expr SUB number
+            | expr ADD number
+            | stds SUB number
+            | expr SUB number
+            | stds ADD numberstr
+            | expr ADD numberstr
+            | stds SUB numberstr
+            | expr SUB numberstr            
+            | stds ADD mapexpr
+            | expr ADD mapexpr
+            | stds SUB mapexpr
+            | expr SUB mapexpr
         """
         # Check input stds.
         maplist = self.check_stds(t[1])
@@ -600,9 +903,9 @@
                 mapinput = map_i.get_id()
                 # Create r.mapcalc expression string for the operation.
                 if "cmd_list" in dir(map_i):
-                    cmdstring = "(%s %s %s)" % (map_i.cmd_list, t[2], t[3])
+                    cmdstring = "(%s %s %s)" %(map_i.cmd_list, t[2], t[3])
                 else:
-                    cmdstring = "(%s %s %s)" % (mapinput, t[2], t[3])
+                    cmdstring = "(%s %s %s)" %(mapinput, t[2], t[3])
                 # Conditional append of module command.
                 map_i.cmd_list = cmdstring
                 # Append map to result map list.
@@ -617,9 +920,17 @@
     def p_arith2_operation_numeric2(self, t):
         """
         expr : number ADD stds
-             | number ADD expr
-             | number SUB stds
-             | number SUB expr
+            | number ADD expr
+            | number SUB stds
+            | number SUB expr
+            | numberstr ADD stds
+            | numberstr ADD expr
+            | numberstr SUB stds            
+            | numberstr SUB expr     
+            | mapexpr ADD stds
+            | mapexpr ADD expr
+            | mapexpr SUB stds
+            | mapexpr SUB expr   
         """
         # Check input stds.
         maplist = self.check_stds(t[3])
@@ -630,9 +941,9 @@
                 mapinput = map_i.get_id()
                 # Create r.mapcalc expression string for the operation.
                 if "cmd_list" in dir(map_i):
-                    cmdstring = "(%s %s %s)" % (t[1], t[2], map_i.cmd_list)
+                    cmdstring = "(%s %s %s)" %(t[1], t[2], map_i.cmd_list)
                 else:
-                    cmdstring = "(%s %s %s)" % (t[1], t[2], mapinput)
+                    cmdstring = "(%s %s %s)" %(t[1], t[2], mapinput)
                 # Conditional append of module command.
                 map_i.cmd_list = cmdstring
                 # Append map to result map list.
@@ -653,85 +964,20 @@
              | stds T_ARITH1_OPERATOR t_td_var
              | expr T_ARITH1_OPERATOR t_td_var
         """
-        # Check input stds.
-        maplistA = self.check_stds(t[1])
-        maplistB = self.check_stds(t[3])
-        relations, temporal, function = self.eval_toperator(t[2])
-        topolist = self.get_temporal_topo_list(maplistA, maplistB,
-                                               topolist=relations)
+        if self.run:        
+            # Check input stds.
+            maplistA = self.check_stds(t[1])
+            maplistB = self.check_stds(t[3])
+            relations, temporal, function, aggregate = self.eval_toperator(t[2],  optype = 'raster')
+            # Build conditional values based on topological relationships.
+            complist = self.get_temporal_topo_list(maplistA, maplistB, topolist = relations,
+                               operator_cmd = True, compop = function)
+            # Set temporal extent based on topological relationships.
+            resultlist = self.set_temporal_extent_list(complist, topolist = relations, 
+                                temporal = temporal)
+        
+        t[0] = resultlist   
 
-        if self.run:
-            resultlist = []
-            for map_i in topolist:
-                # Generate an intermediate map for the result map list.
-                map_new = self.generate_new_map(base_map=map_i, bool_op='and',
-                                                copy=True)
-                # Set first input for overlay module.
-                mapainput = map_i.get_id()
-                # Loop over temporal related maps and create overlay modules.
-                tbrelations = map_i.get_temporal_relations()
-                count = 0
-                for topo in relations:
-                    if topo in tbrelations.keys():
-                        for map_j in (tbrelations[topo]):
-                            # Create overlayed map extent.
-                            returncode = self.overlay_map_extent(map_new,
-                                                                 map_j, 'and',
-                                                                 temp_op=temporal)
-                            print(returncode)
-                            # Stop the loop if no temporal or spatial
-                            # relationship exist.
-                            if returncode == 0:
-                                break
-                            if count == 0:
-                                # Set map name.
-                                name = map_new.get_id()
-                            else:
-                                # Generate an intermediate map
-                                name = self.generate_map_name()
-                                map_new.set_id(name + "@" + mapset)
-                            # Set second input for overlay module.
-
-                            if "map_value" in dir(map_j) and len(map_j.map_value) > 0 and map_j.map_value[0].get_type() == "timediff":
-                                mapbinput = map_j.map_value[0].get_type_value()[0]
-                            else:
-                                # Set first input for overlay module.
-                                mapbinput = map_j.get_id()
-
-                            # Create r.mapcalc expression string for the operation.
-                            if "cmd_list" in dir(map_new):
-                                cmdstring = "(%s %s %s)" % (map_new.cmd_list,
-                                                            function,
-                                                            mapbinput)
-                                print('with cmd in a: ' + map_j.get_id())
-                            elif "cmd_list" in dir(map_j):
-                                cmdstring = "(%s %s %s)" % (mapainput,
-                                                            function,
-                                                            map_j.cmd_list)
-                                print('with cmd in b')
-                            elif "cmd_list" in dir(map_j) and "cmd_list" in dir(map_new):
-                                cmdstring = "(%s %s %s)" % (map_new.cmd_list,
-                                                            function,
-                                                            map_j.cmd_list)
-                                print('with cmd in b')
-                            else:
-                                cmdstring = "(%s %s %s)" % (mapainput,
-                                                            function,
-                                                            mapbinput)
-                            print(cmdstring)
-                            # Conditional append of module command.
-                            map_new.cmd_list = cmdstring
-                            # Set new map name to temporary map name.
-                            mapainput = name
-                            count += 1
-                        if returncode == 0:
-                            break
-                # Append map to result map list.
-                if returncode == 1:
-                    resultlist.append(map_new)
-
-            t[0] = resultlist
-
         if self.debug:
             for map in resultlist:
                 print map.cmd_list
@@ -745,84 +991,39 @@
              | stds T_ARITH2_OPERATOR t_td_var
              | expr T_ARITH2_OPERATOR t_td_var
         """
-        # Check input stds.
-        maplistA = self.check_stds(t[1])
-        maplistB = self.check_stds(t[3])
-        relations, temporal, function = self.eval_toperator(t[2])
-        topolist = self.get_temporal_topo_list(maplistA, maplistB,
-                                               topolist=relations)
-
-        if self.run:
-            resultlist = []
-            for map_i in topolist:
-                # Generate an intermediate map for the result map list.
-                map_new = self.generate_new_map(base_map=map_i, bool_op='and',
-                                                copy=True)
-                # Set first input for overlay module.
-                mapainput = map_i.get_id()
-                # Loop over temporal related maps and create overlay modules.
-                tbrelations = map_i.get_temporal_relations()
-                count = 0
-                for topo in relations:
-                    if topo in tbrelations.keys():
-                        for map_j in (tbrelations[topo]):
-                            # Create overlayed map extent.
-                            returncode = self.overlay_map_extent(map_new,
-                                                                 map_j, 'and',
-                                                                 temp_op=temporal)
-                            # Stop the loop if no temporal or spatial
-                            # relationship exist.
-                            if returncode == 0:
-                                break
-                            if count == 0:
-                                # Set map name.
-                                name = map_new.get_id()
-                            else:
-                                # Generate an intermediate map
-                                name = self.generate_map_name()
-                                map_new.set_id(name + "@" + self.mapset)
-                            # Set second input for overlay module.
-
-                            if "map_value" in dir(map_j) and len(map_j.map_value) > 0 and map_j.map_value[0].get_type() == "timediff":
-                                mapbinput = map_j.map_value[0].get_type_value()[0]
-                            else:
-                            # Set first input for overlay module.
-                                mapbinput = map_j.get_id()
-
-                            # Create r.mapcalc expression string for the operation.
-                            if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_j):
-                                cmdstring = "(%s %s %s)" % (map_new.cmd_list,
-                                                            function,
-                                                            mapbinput)
-                            elif "cmd_list" in dir(map_j) and "cmd_list" not in dir(map_new):
-                                cmdstring = "(%s %s %s)" % (mapainput,
-                                                            function,
-                                                            map_j.cmd_list)
-                            elif "cmd_list" in dir(map_j) and "cmd_list" in dir(map_new):
-                                cmdstring = "(%s %s %s)" % (map_new.cmd_list,
-                                                            function,
-                                                            map_j.cmd_list)
-                            else:
-                                cmdstring = "(%s %s %s)" % (mapainput,
-                                                            function,
-                                                            mapbinput)
-                            # Conditional append of module command.
-                            map_new.cmd_list = cmdstring
-                            # Set new map name to temporary map name.
-                            mapainput = name
-                            count += 1
-                        if returncode == 0:
-                            break
-                # Append map to result map list.
-                if returncode == 1:
-                    resultlist.append(map_new)
-
-            t[0] = resultlist
-
+        if self.run:        
+            # Check input stds.
+            maplistA = self.check_stds(t[1])
+            maplistB = self.check_stds(t[3])
+            relations, temporal, function, aggregate = self.eval_toperator(t[2],  optype = 'raster')
+            # Build conditional values based on topological relationships.
+            complist = self.get_temporal_topo_list(maplistA, maplistB, topolist = relations,
+                               operator_cmd = True, compop = function)
+            # Set temporal extent based on topological relationships.
+            resultlist = self.set_temporal_extent_list(complist, topolist = relations, 
+                                temporal = temporal)
+        
+        t[0] = resultlist
+  
         if self.debug:
             for map in resultlist:
                 print map.cmd_list
 
+    def p_arith_operation_numeric_string(self, t):
+        """
+        numberstr : number ADD number
+            | number SUB number
+            | number DIV number
+            | number MULT number
+            | number MOD number
+        """
+        numstring = "(%s %s %s)" %(t[1], t[2], t[3])
+
+        t[0] = numstring
+
+        if self.debug:
+            print(numstring)
+    
     def p_mapcalc_function(self, t):
         # Supported mapcalc functions.
         """
@@ -845,7 +1046,8 @@
             for map in resultlist:
                 print map.cmd_list
 
-    def p_mapcalc_operation(self, t):
+
+    def p_mapcalc_operation1(self, t):
         # Examples:
         # sin(A)
         # log(B)
@@ -861,9 +1063,9 @@
             for map_i in maplist:
                 # Create r.mapcalc expression string for the operation.
                 if "cmd_list" in dir(map_i):
-                    cmdstring = "%s(%s)" % (t[1].lower(), map_i.cmd_list)
+                    cmdstring = "%s(%s)" %(t[1].lower(), map_i.cmd_list)
                 else:
-                    cmdstring = "%s(%s)" % (t[1].lower(), map_i.get_id())
+                    cmdstring = "%s(%s)" %(t[1].lower(), map_i.get_id())
                 # Set new command list for map.
                 map_i.cmd_list = cmdstring
                 # Append map with updated command list to result list.
@@ -875,8 +1077,25 @@
             for map in resultlist:
                 print map.cmd_list
 
-    def p_s_var_expr(self, t):
+    def p_mapexpr_operation(self, t):
         # Examples:
+        # sin(map(a))
+        """
+        mapexpr : mapcalc_arith LPAREN mapexpr RPAREN
+        """
+        # Check input stds.
+        mapstring = t[3]
+
+        if self.run:
+            cmdstring = "%s(%s)" %(t[1].lower(), mapstring)
+
+            t[0] = cmdstring
+
+        if self.debug:
+            print mapstring
+
+    def p_s_var_expr_1(self, t):
+        # Examples:
         #   isnull(A)
         """
         s_var_expr : ISNULL LPAREN stds RPAREN
@@ -890,9 +1109,9 @@
             for map_i in maplist:
                 # Create r.mapcalc expression string for the operation.
                 if "cmd_list" in dir(map_i):
-                    cmdstring = "%s(%s)" % (t[1].lower(), map_i.cmd_list)
+                    cmdstring = "%s(%s)" %(t[1].lower(), map_i.cmd_list)
                 else:
-                    cmdstring = "%s(%s)" % (t[1].lower(), map_i.get_id())
+                    cmdstring = "%s(%s)" %(t[1].lower(), map_i.get_id())
                 # Set new command list for map.
                 map_i.cmd_list = cmdstring
                 # Append map with updated command list to result list.
@@ -904,7 +1123,7 @@
             for map in resultlist:
                 print map.cmd_list
 
-    def p_s_var_expr_1(self, t):
+    def p_s_var_expr_2(self, t):
         # Examples:
         #   isntnull(A)
         """
@@ -919,9 +1138,9 @@
             for map_i in maplist:
                 # Create r.mapcalc expression string for the operation.
                 if "cmd_list" in dir(map_i):
-                    cmdstring = "!isnull(%s)" % (map_i.cmd_list)
+                    cmdstring = "!isnull(%s)" %(map_i.cmd_list)
                 else:
-                    cmdstring = "!isnull(%s)" % (map_i.get_id())
+                    cmdstring = "!isnull(%s)" %(map_i.get_id())
                 # Set new command list for map.
                 map_i.cmd_list = cmdstring
                 # Append map with updated command list to result list.
@@ -933,7 +1152,7 @@
             for map in resultlist:
                 print map.cmd_list
 
-    def p_s_var_expr2(self, t):
+    def p_s_var_expr_3(self, t):
         # Examples:
         #   A <= 2
         """
@@ -948,9 +1167,9 @@
             for map_i in maplist:
                 # Create r.mapcalc expression string for the operation.
                 if "cmd_list" in dir(map_i):
-                    cmdstring = "%s %s %s" % (map_i.cmd_list, t[2], t[3])
+                    cmdstring = "%s %s %s" %(map_i.cmd_list, t[2], t[3])
                 else:
-                    cmdstring = "%s %s %s" % (map_i.get_id(), t[2], t[3])
+                    cmdstring = "%s %s %s" %(map_i.get_id(), t[2], t[3])
                 # Set new command list for map.
                 map_i.cmd_list = cmdstring
                 # Append map with updated command list to result list.
@@ -962,75 +1181,8 @@
             for map in resultlist:
                 print map.cmd_list
 
-    def p_s_var_expr3(self, t):
+    def p_s_var_expr_4(self, t):
         # Examples:
-        #   A <= 2 || B == 10
-        #   A < 3 && A > 1
-        """
-        s_var_expr : s_var_expr AND AND s_var_expr
-                   | s_var_expr OR OR s_var_expr
-        """
-        # Check input stds.
-        maplistA = self.check_stds(t[1])
-        maplistB = self.check_stds(t[4])
-        topolist = self.get_temporal_topo_list(maplistA, maplistB)
-
-        if self.run:
-            resultlist = []
-            for map_i in topolist:
-                # Loop over temporal related maps and create overlay modules.
-                tbrelations = map_i.get_temporal_relations()
-                count = 0
-                for map_j in (tbrelations['EQUAL']):
-                    # Generate an intermediate map for the result map list.
-                    map_new = self.generate_new_map(base_map=map_i,
-                                                    bool_op='and', copy=True)
-                    # Set first input for overlay module.
-                    mapainput = map_i.get_id()
-                    # Create overlayed map extent.
-                    returncode = self.overlay_map_extent(map_new, map_j, 'and',
-                                                         temp_op='=')
-                    # Stop the loop if no temporal or spatial relationship exist.
-                    if returncode == 0:
-                        break
-                    if count == 0:
-                        # Set map name.
-                        name = map_new.get_id()
-                    else:
-                        # Generate an intermediate map
-                        name = self.generate_map_name()
-
-                    # Set first input for overlay module.
-                    mapbinput = map_j.get_id()
-                    # Create r.mapcalc expression string for the operation.
-                    if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_j):
-                        cmdstring = "%s %s %s" % (map_new.cmd_list,
-                                                  t[2] + t[3], mapbinput)
-                    elif "cmd_list" in dir(map_j) and "cmd_list" not in dir(map_new):
-                        cmdstring = "%s %s %s" % (mapainput, t[2] + t[3],
-                                                  map_j.cmd_list)
-                    elif "cmd_list" in dir(map_j) and "cmd_list" in dir(map_new):
-                        cmdstring = "%s %s %s" % (map_new.cmd_list,
-                                                  t[2] + t[3], map_j.cmd_list)
-                    else:
-                        cmdstring = "%s %s %s" % (mapainput, t[2] + t[3],
-                                                  mapbinput)
-                    # Conditional append of module command.
-                    map_new.cmd_list = cmdstring
-                    # Set new map name to temporary map name.
-                    #mapainput = name
-                    count += 1
-                    # Append map to result map list.
-                    if returncode == 1:
-                        resultlist.append(map_new)
-            t[0] = resultlist
-
-        if self.debug:
-            for map in resultlist:
-                print map.cmd_list
-
-    def p_s_var_expr4(self, t):
-        # Examples:
         #   exist(B)
         """
         s_var_expr : EXIST LPAREN stds RPAREN
@@ -1044,9 +1196,9 @@
             for map_i in maplist:
                 # Create r.mapcalc expression string for the operation.
                 if "cmd_list" in dir(map_i):
-                    cmdstring = "%s" % (map_i.cmd_list)
+                    cmdstring = "%s" %(map_i.cmd_list)
                 else:
-                    cmdstring = "%s" % (map_i.get_id())
+                    cmdstring = "%s" %(map_i.get_id())
                 # Set new command list for map.
                 map_i.cmd_list = cmdstring
                 # Append map with updated command list to result list.
@@ -1057,7 +1209,62 @@
         if self.debug:
             for map in resultlist:
                 print map.cmd_list
+    
+    def p_s_var_expr_comp(self, t):
+        # Examples:
+        #   A <= 2 || B == 10
+        #   A < 3 && A > 1
+        """
+        s_var_expr : s_var_expr AND AND s_var_expr
+                   | s_var_expr OR OR s_var_expr
+        """        
+        if self.run:
+            # Check input stds.
+            s_var_exprA = self.check_stds(t[1])
+            s_var_exprB = self.check_stds(t[4])
+            relations = ["EQUAL"]
+            temporal = "l"
+            function = t[2] + t[3]
+            aggregate = t[2]
+            # Build conditional values based on topological relationships.            
+            complist = self.get_temporal_topo_list(s_var_exprA, s_var_exprB, topolist = relations,
+                               compare_cmd = True, compop = function, aggregate = aggregate)
+            # Set temporal extent based on topological relationships.
+            resultlist = self.set_temporal_extent_list(complist, topolist = relations, 
+                                temporal = temporal)
+                                
+            t[0] = resultlist
 
+        if self.debug:
+            for map in resultlist:
+                print map.cmd_list
+
+    def p_s_var_expr_comp_op(self, t):
+        # Examples:
+        #   A <= 2 {||} B == 10
+        #   A < 3 {&&, equal} A > 1
+        """
+        s_var_expr : s_var_expr T_COMP_OPERATOR s_var_expr
+        """
+        if self.run:
+            # Check input stds.
+            s_var_exprA = self.check_stds(t[1])
+            s_var_exprB = self.check_stds(t[3])
+            # Evaluate temporal comparison operator.
+            relations, temporal, function, aggregate  = self.eval_toperator(t[2],  optype = 'boolean')
+            # Build conditional values based on topological relationships.
+            complist = self.get_temporal_topo_list(s_var_exprA, s_var_exprB, topolist = relations,
+                               compare_cmd = True, compop = function, aggregate = aggregate)
+            # Set temporal extent based on topological relationships.
+            resultlist = self.set_temporal_extent_list(complist, topolist = relations, 
+                                temporal = temporal)
+            
+            t[0] = resultlist
+
+        if self.debug:
+            for map in resultlist:
+                print map.cmd_list
+
     def p_s_expr_condition_if(self, t):
         # Examples:
         #   if(s_var_expr, B)
@@ -1065,57 +1272,16 @@
         """
         expr : IF LPAREN s_var_expr COMMA stds RPAREN
              | IF LPAREN s_var_expr COMMA expr RPAREN
+             | IF LPAREN ts_var_expr COMMA stds RPAREN
+             | IF LPAREN ts_var_expr COMMA expr RPAREN
         """
-
         ifmaplist = self.check_stds(t[3])
         thenmaplist = self.check_stds(t[5])
-        topolist = self.get_temporal_topo_list(ifmaplist, thenmaplist)
-        resultlist = []
-        for map_i in topolist:
-            #print(map_i.get_id())
-            # Loop over temporal related maps and create overlay modules.
-            tbrelations = map_i.get_temporal_relations()
-            count = 0
-            for map_j in (tbrelations['EQUAL']):
-                # Generate an intermediate map for the result map list.
-                map_new = self.generate_new_map(base_map=map_i, bool_op='and',
-                                                copy=True)
-                # Set first input for overlay module.
-                mapainput = map_i.get_id()
-                # Create overlayed map extent.
-                returncode = self.overlay_map_extent(map_new, map_j, 'and',
-                                                     temp_op='=')
-                # Stop the loop if no temporal or spatial relationship exist.
-                if returncode == 0:
-                    break
-                if count == 0:
-                    # Set map name.
-                    name = map_new.get_id()
-                else:
-                    # Generate an intermediate map
-                    name = self.generate_map_name()
-
-                # Set first input for overlay module.
-                mapbinput = map_j.get_id()
-                # Create r.mapcalc expression string for the operation.
-                if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_j):
-                    cmdstring = "if(%s,%s)" % (map_new.cmd_list, mapbinput)
-                elif "cmd_list" in dir(map_j) and "cmd_list" not in dir(map_new):
-                    cmdstring = "if(%s,%s)" % (mapainput, map_j.cmd_list)
-                elif "cmd_list" in dir(map_j) and "cmd_list" in dir(map_new):
-                    cmdstring = "if(%s,%s)" % (map_new.cmd_list,
-                                               map_j.cmd_list)
-                else:
-                    cmdstring = "if(%s,%s)" % (mapainput, mapbinput)
-                # Conditional append of module command.
-                map_new.cmd_list = cmdstring
-                # Set new map name to temporary map name.
-                #mapainput = name
-                count += 1
-                # Append map to result map list.
-                if returncode == 1:
-                    resultlist.append(map_new)
-
+        resultlist = self.build_condition_cmd_list(ifmaplist, thenmaplist,  
+                                                                            elselist = None, 
+                                                                            condition_topolist = ["EQUAL"], 
+                                                                            conclusion_topolist = ["EQUAL"], 
+                                                                            temporal = 'r', null = False)
         t[0] = resultlist
 
         if self.debug:
@@ -1129,23 +1295,20 @@
         """
         expr : IF LPAREN s_var_expr COMMA number RPAREN
              | IF LPAREN s_var_expr COMMA NULL LPAREN RPAREN RPAREN
+             | IF LPAREN ts_var_expr COMMA number RPAREN
+             | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN RPAREN
         """
         ifmaplist = self.check_stds(t[3])
         resultlist = []
         # Select input for r.mapcalc expression based on length of PLY object.
         if len(t) == 7:
-            numinput = t[5]
+            numinput = str(t[5])
         elif len(t) == 9:
-            numinput = self.check_null(t[5])
-
+            numinput = str(t[5] + t[6] + t[7])
         # Iterate over condition map list.
         for map_i in ifmaplist:
-            mapinput = map_i.get_id()
             # Create r.mapcalc expression string for the operation.
-            if "cmd_list" in dir(map_i):
-                cmdstring = "if(%s,%s)" % (map_i.cmd_list, numinput)
-            else:
-                cmdstring = "if(%s,%s)" % (mapinput, numinput)
+            cmdstring = self.build_command_string(map_i, numinput, cmd_type = 'condition')
             # Conditional append of module command.
             map_i.cmd_list = cmdstring
             # Append map to result map list.
@@ -1163,65 +1326,18 @@
         """
         expr : IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA stds RPAREN
              | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA expr RPAREN
+             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds RPAREN
+             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr RPAREN
         """
-        relations, temporal, function = self.eval_toperator(t[3])
+        relations, temporal, function,  aggregation = self.eval_toperator(t[3],  
+                                                                                        optype = 'relation')
         ifmaplist = self.check_stds(t[5])
         thenmaplist = self.check_stds(t[7])
-        topolist = self.get_temporal_topo_list(ifmaplist, thenmaplist,
-                                               topolist=relations)
-        resultlist = []
-        for map_i in topolist:
-            #print(map_i.get_id())
-            # Loop over temporal related maps.
-            tbrelations = map_i.get_temporal_relations()
-            count = 0
-            for topo in relations:
-                if topo in tbrelations.keys():
-                    for map_j in (tbrelations[topo]):
-                        # Generate an intermediate map for the result map list.
-                        map_new = self.generate_new_map(base_map=map_i,
-                                                        bool_op='and',
-                                                        copy=True)
-                        # Set first input for overlay module.
-                        mapainput = map_i.get_id()
-                        # Create overlayed map extent.
-                        returncode = self.overlay_map_extent(map_new, map_j,
-                                                             'and',
-                                                             temp_op='=')
-                        # Stop the loop if no temporal or spatial relationship exist.
-                        if returncode == 0:
-                            break
-                        if count == 0:
-                            # Set map name.
-                            name = map_new.get_id()
-                        else:
-                            # Generate an intermediate map
-                            name = self.generate_map_name()
-
-                        # Set first input for overlay module.
-                        mapbinput = map_j.get_id()
-                        #print(mapbinput)
-                        #mapbinput = mapbinput.split('@')[0]
-                        # Create r.mapcalc expression string for the operation.
-                        if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_j):
-                            cmdstring = "if(%s,%s)" % (map_new.cmd_list,
-                                                       mapbinput)
-                        elif "cmd_list" in dir(map_j) and "cmd_list" not in dir(map_new):
-                            cmdstring = "if(%s,%s)" % (mapainput,
-                                                       map_j.cmd_list)
-                        elif "cmd_list" in dir(map_j) and "cmd_list" in dir(map_new):
-                            cmdstring = "if(%s,%s)" % (map_new.cmd_list,
-                                                       map_j.cmd_list)
-                        else:
-                            cmdstring = "if(%s,%s)" % (mapainput, mapbinput)
-                        # Conditional append of module command.
-                        map_new.cmd_list = cmdstring
-                        # Set new map name to temporary map name.
-                        #mapainput = name
-                        count += 1
-                        # Append map to result map list.
-                        if returncode == 1:
-                            resultlist.append(map_new)
+        resultlist = self.build_condition_cmd_list(ifmaplist, thenmaplist,  
+                                                                            elselist = None, 
+                                                                            condition_topolist = relations, 
+                                                                            conclusion_topolist = ["EQUAL"], 
+                                                                            temporal = 'r', null = False)
         t[0] = resultlist
 
         if self.debug:
@@ -1236,136 +1352,22 @@
              | IF LPAREN s_var_expr COMMA stds COMMA expr RPAREN
              | IF LPAREN s_var_expr COMMA expr COMMA stds RPAREN
              | IF LPAREN s_var_expr COMMA expr COMMA expr RPAREN
+             | IF LPAREN ts_var_expr COMMA stds COMMA stds RPAREN
+             | IF LPAREN ts_var_expr COMMA stds COMMA expr RPAREN
+             | IF LPAREN ts_var_expr COMMA expr COMMA stds RPAREN
+             | IF LPAREN ts_var_expr COMMA expr COMMA expr RPAREN
         """
+        # Check map list inputs.
         ifmaplist = self.check_stds(t[3])
         thenmaplist = self.check_stds(t[5])
         elsemaplist = self.check_stds(t[7])
-        resultlist = []
-        thendict = {}
-        elsedict = {}
-        # Get topologies for the appropriate conclusion term.
-        thentopolist = self.get_temporal_topo_list(ifmaplist, thenmaplist)
-        # Fill dictionaries with related maps for both conclusion terms.
-        for map_i in thentopolist:
-            thenrelations = map_i.get_temporal_relations()
-            relationmaps = thenrelations['EQUAL']
-            thendict[map_i.get_id()] = relationmaps
-        # Get topologies for the alternative conclusion term.
-        elsetopolist = self.get_temporal_topo_list(ifmaplist, elsemaplist)
-        for map_i in elsetopolist:
-            elserelations = map_i.get_temporal_relations()
-            relationmaps = elserelations['EQUAL']
-            elsedict[map_i.get_id()] = relationmaps
-        # Loop through conditional map list.
-        for map_i in ifmaplist:
-            if map_i.get_id() in thendict.keys():
-                thenlist = thendict[map_i.get_id()]
-            else:
-                thenlist = []
-            if map_i.get_id() in elsedict.keys():
-                elselist = elsedict[map_i.get_id()]
-            else:
-                elselist = []
-            # Set iteration amount to maximal or minimum number of related
-            # conclusion maps, depending on null map creation flag.
-            if self.null:
-                iternum = max(len(thenlist), len(elselist))
-            else:
-                iternum = min(len(thenlist), len(elselist))
-            # Calculate difference in conclusion lengths.
-            iterthen = iternum - len(thenlist)
-            iterelse = iternum - len(elselist)
-            # Extend null maps to the list to get conclusions with same length.
-            if iterthen != 0:
-                for i in range(iterthen):
-                    thenlist.extend(['null()'])
-            if iterelse != 0:
-                for i in range(iterelse):
-                    elselist.extend(['null()'])
+        # Create conditional command map list.
+        resultlist = self.build_condition_cmd_list(ifmaplist, thenmaplist,  
+                                                                            elselist = elsemaplist, 
+                                                                            condition_topolist = ["EQUAL"], 
+                                                                            conclusion_topolist = ["EQUAL"], 
+                                                                            temporal = 'r', null = False)
 
-            # Combine the conclusions in a paired list.
-            conclusionlist = zip(thenlist, elselist)
-            for i in range(iternum):
-                conclusionmaps = conclusionlist[i]
-                # Generate an intermediate map for the result map list.
-                map_new = self.generate_new_map(base_map=map_i, bool_op='and',
-                                                copy=True)
-                # Set first input for overlay module.
-                mapifinput = map_i.get_id()
-                # Get conclusion maps.
-                map_then = conclusionmaps[0]
-                map_else = conclusionmaps[1]
-
-                # Check if conclusions are map objects.
-                if map_then != 'null()':
-                    # Create overlayed map extent.
-                    returncode = self.overlay_map_extent(map_new, map_then,
-                                                         'and', temp_op='=')
-                    maptheninput = map_then.get_id()
-                    # Continue the loop if no temporal or spatial relationship exist.
-                    if returncode == 0:
-                        continue
-                else:
-                    maptheninput = 'null()'
-                # Check if conclusions are map objects.
-                if map_else != 'null()':
-                    # Create overlayed map extent.
-                    returncode = self.overlay_map_extent(map_new, map_else,
-                                                         'and', temp_op='=')
-                    mapelseinput = map_else.get_id()
-                    # Continue the loop if no temporal or spatial relationship exist.
-                    if returncode == 0:
-                        continue
-                else:
-                    mapelseinput = 'null()'
-
-                #if map_then != 'null()' and map_else != 'null()':
-                # Create r.mapcalc expression string for the operation.
-                if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_then) \
-                    and "cmd_list" not in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (map_new.cmd_list,
-                                                    maptheninput,
-                                                    mapelseinput)
-                elif "cmd_list" in dir(map_new) and "cmd_list" in dir(map_then) \
-                    and "cmd_list" not in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (map_new.cmd_list,
-                                                    map_then.cmd_list,
-                                                    mapelseinput)
-                elif "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_then) \
-                    and "cmd_list" in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (map_new.cmd_list,
-                                                    maptheninput,
-                                                    map_else.cmd_list)
-                elif "cmd_list" in dir(map_new) and "cmd_list" in dir(map_then) \
-                    and "cmd_list" in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (map_new.cmd_list,
-                                                    map_then.cmd_list,
-                                                    map_else.cmd_list)
-                elif "cmd_list" not in dir(map_new) and "cmd_list" in dir(map_then) \
-                    and "cmd_list" not in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (mapifinput,
-                                                    map_then.cmd_list,
-                                                    mapelseinput)
-                elif "cmd_list" not in dir(map_new) and "cmd_list" not in dir(map_then) \
-                    and "cmd_list" in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (mapifinput,
-                                                    maptheninput,
-                                                    map_else.cmd_list)
-                elif "cmd_list" not in dir(map_new) and "cmd_list" in dir(map_then) \
-                    and "cmd_list" in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (mapifinput,
-                                                    map_then.cmd_list,
-                                                    map_else.cmd_list)
-                else:
-                    cmdstring = "if(%s, %s, %s)" % (mapifinput,
-                                                    maptheninput,
-                                                    mapelseinput)
-                # Conditional append of module command.
-                map_new.cmd_list = cmdstring
-                # Append map to result map list.
-                if returncode == 1:
-                    resultlist.append(map_new)
-
         t[0] = resultlist
 
         if self.debug:
@@ -1381,6 +1383,10 @@
              | IF LPAREN s_var_expr COMMA NULL LPAREN RPAREN COMMA number RPAREN
              | IF LPAREN s_var_expr COMMA number COMMA NULL LPAREN RPAREN RPAREN
              | IF LPAREN s_var_expr COMMA NULL LPAREN RPAREN COMMA NULL LPAREN RPAREN RPAREN
+             | IF LPAREN ts_var_expr COMMA number COMMA number RPAREN
+             | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA number RPAREN
+             | IF LPAREN ts_var_expr COMMA number COMMA NULL LPAREN RPAREN RPAREN
+             | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA NULL LPAREN RPAREN RPAREN             
         """
         ifmaplist = self.check_stds(t[3])
         resultlist = []
@@ -1397,19 +1403,14 @@
         elif len(t) == 13:
             numthen = t[5] + t[6] + t[7]
             numelse = t[9] + t[10] + t[11]
-        # Iterate over condition map list.
-        for map_i in ifmaplist:
-            mapinput = map_i.get_id()
-            # Create r.mapcalc expression string for the operation.
-            if "cmd_list" in dir(map_i):
-                cmdstring = "if(%s, %s, %s)" % (map_i.cmd_list, numthen,
-                                                numelse)
-            else:
-                cmdstring = "if(%s, %s, %s)" % (mapinput, numthen, numelse)
-            # Conditional append of module command.
-            map_i.cmd_list = cmdstring
-            # Append map to result map list.
-            resultlist.append(map_i)
+        numthen = str(numthen)
+        numelse = str(numelse)
+        print(numthen + " " +numelse )
+        # Create conditional command map list.
+        resultlist = self.build_condition_cmd_list(ifmaplist, numthen,  numelse,  
+                                                        condition_topolist = ["EQUAL"], 
+                                                        conclusion_topolist = ["EQUAL"], 
+                                                        temporal = 'r', null = False)
 
         t[0] = resultlist
 
@@ -1430,110 +1431,39 @@
              | IF LPAREN s_var_expr COMMA stds COMMA NULL LPAREN RPAREN RPAREN
              | IF LPAREN s_var_expr COMMA expr COMMA number RPAREN
              | IF LPAREN s_var_expr COMMA expr COMMA NULL LPAREN RPAREN RPAREN
+             | IF LPAREN ts_var_expr COMMA number COMMA stds RPAREN
+             | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA stds RPAREN
+             | IF LPAREN ts_var_expr COMMA number COMMA expr RPAREN
+             | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA expr RPAREN
+             | IF LPAREN ts_var_expr COMMA stds COMMA number RPAREN
+             | IF LPAREN ts_var_expr COMMA stds COMMA NULL LPAREN RPAREN RPAREN
+             | IF LPAREN ts_var_expr COMMA expr COMMA number RPAREN
+             | IF LPAREN ts_var_expr COMMA expr COMMA NULL LPAREN RPAREN RPAREN             
         """
         ifmaplist = self.check_stds(t[3])
-        resultlist = []
-        thenmaplist = []
-        numthen = ''
-        elsemaplist = []
-        numelse = ''
         # Select input for r.mapcalc expression based on length of PLY object.
         if len(t) == 9:
-            try:
-                thenmaplist = self.check_stds(t[5])
-            except:
-                numthen = self.check_null(t[5])
-            try:
-                elsemaplist = self.check_stds(t[7])
-            except:
-                numelse = self.check_null(t[7])
+            if isinstance(t[5],  int):
+                theninput = str(t[5])
+                elseinput = self.check_stds(t[7])
+            elif isinstance(t[7],  int):
+                theninput = self.check_stds(t[5])
+                elseinput = str(t[7])
         elif len(t) == 11:
-            try:
-                thenmaplist = self.check_stds(t[5])
-            except:
-                numthen = self.check_null(t[5])
-            try:
-                elsemaplist = self.check_stds(t[9])
-            except:
-                numelse = self.check_null(t[7])
+            if t[5] == 'null':
+                theninput = str(t[5] + t[6] + t[7])
+                elseinput = self.check_stds(t[9])
+            elif t[7] == 'null':
+                theninput = self.check_stds(t[5])
+                elseinput = str(t[7] + t[8] + t[9])
+        print(theninput)
+        print(elseinput)
+        # Create conditional command map list.
+        resultlist = self.build_condition_cmd_list(ifmaplist, theninput,  elseinput,  
+                                                        condition_topolist = ["EQUAL"], 
+                                                        conclusion_topolist = ["EQUAL"], 
+                                                        temporal = 'r', null = False)
 
-        if thenmaplist != []:
-            topolist = self.get_temporal_topo_list(ifmaplist, thenmaplist)
-        elif elsemaplist != []:
-            topolist = self.get_temporal_topo_list(ifmaplist, elsemaplist)
-        if numthen != '':
-            numinput = numthen
-        elif numelse != '':
-            numinput = numelse
-
-        # Iterate over condition map lists with temporal relations.
-        for map_i in topolist:
-            # Loop over temporal related maps and create overlay modules.
-            tbrelations = map_i.get_temporal_relations()
-            count = 0
-            for map_j in (tbrelations['EQUAL']):
-                # Generate an intermediate map for the result map list.
-                map_new = self.generate_new_map(base_map=map_i, bool_op='and',
-                                                copy=True)
-                # Set first input for overlay module.
-                mapainput = map_i.get_id()
-                # Create overlayed map extent.
-                returncode = self.overlay_map_extent(map_new, map_j, 'and',
-                                                     temp_op='=')
-                # Stop the loop if no temporal or spatial relationship exist.
-                if returncode == 0:
-                    break
-                if count == 0:
-                    # Set map name.
-                    name = map_new.get_id()
-                else:
-                    # Generate an intermediate map
-                    name = self.generate_map_name()
-
-                # Set first input for overlay module.
-                mapbinput = map_j.get_id()
-                # Create r.mapcalc expression string for the operation.
-                if thenmaplist != []:
-                    if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_j):
-                        cmdstring = "if(%s,%s,%s)" % (map_new.cmd_list,
-                                                      mapbinput,
-                                                      numinput)
-                    elif "cmd_list" in dir(map_j) and "cmd_list" not in dir(map_new):
-                        cmdstring = "if(%s,%s,%s)" % (mapainput,
-                                                      map_j.cmd_list,
-                                                      numinput)
-                    elif "cmd_list" in dir(map_j) and "cmd_list" in dir(map_new):
-                        cmdstring = "if(%s,%s,%s)" % (map_new.cmd_list,
-                                                      map_j.cmd_list,
-                                                      numinput)
-                    else:
-                        cmdstring = "if(%s,%s,%s)" % (mapainput,
-                                                      mapbinput, numinput)
-                if elsemaplist != []:
-                    if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_j):
-                        cmdstring = "if(%s,%s,%s)" % (map_new.cmd_list,
-                                                      numinput,
-                                                      mapbinput)
-                    elif "cmd_list" in dir(map_j) and "cmd_list" not in dir(map_new):
-                        cmdstring = "if(%s,%s,%s)" % (mapainput,
-                                                      numinput,
-                                                      map_j.cmd_list)
-                    elif "cmd_list" in dir(map_j) and "cmd_list" in dir(map_new):
-                        cmdstring = "if(%s,%s,%s)" % (map_new.cmd_list,
-                                                      numinput,
-                                                      map_j.cmd_list)
-                    else:
-                        cmdstring = "if(%s,%s,%s)" % (mapainput, numinput,
-                                                      mapbinput)
-                # Conditional append of module command.
-                map_new.cmd_list = cmdstring
-                # Set new map name to temporary map name.
-                #mapainput = name
-                count += 1
-                # Append map to result map list.
-                if returncode == 1:
-                    resultlist.append(map_new)
-
         t[0] = resultlist
 
         if self.debug:
@@ -1553,125 +1483,46 @@
              | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA stds COMMA NULL LPAREN RPAREN RPAREN
              | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA expr COMMA number RPAREN
              | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA expr COMMA NULL LPAREN RPAREN RPAREN
+             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA number COMMA stds RPAREN
+             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA NULL LPAREN RPAREN COMMA stds RPAREN
+             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA number COMMA expr RPAREN
+             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA NULL LPAREN RPAREN COMMA expr RPAREN
+             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds COMMA number RPAREN
+             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds COMMA NULL LPAREN RPAREN RPAREN
+             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA number RPAREN
+             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA NULL LPAREN RPAREN RPAREN             
         """
-        relations, temporal, function = self.eval_toperator(t[3])
+        relations, temporal, function,  aggregation = self.eval_toperator(t[3],  optype = 'relation')
         ifmaplist = self.check_stds(t[5])
-        resultlist = []
-        thenmaplist = []
-        numthen = ''
-        elsemaplist = []
-        numelse = ''
         # Select input for r.mapcalc expression based on length of PLY object.
         if len(t) == 11:
-            try:
-                thenmaplist = self.check_stds(t[7])
-            except:
-                numthen = self.check_null(t[7])
-            try:
-                elsemaplist = self.check_stds(t[9])
-            except:
-                numelse = self.check_null(t[9])
+            if isinstance(t[7],  int):
+                theninput = str(t[7])
+                elseinput = self.check_stds(t[9])
+            elif isinstance(t[9],  int):
+                theninput = self.check_stds(t[7])
+                elseinput = str(t[9])
         elif len(t) == 13:
-            try:
-                thenmaplist = self.check_stds(t[7])
-            except:
-                numthen = self.check_null(t[7])
-            try:
-                elsemaplist = self.check_stds(t[11])
-            except:
-                numelse = self.check_null(t[9])
+            if isinstance(t[7],  int):
+                theninput = str(t[7] + t[8] + t[9])
+                elseinput = self.check_stds(t[11])
+            elif isinstance(t[9],  int):
+                theninput = self.check_stds(t[7])
+                elseinput = str(t[9] + t[10] + t[11])
 
-        if thenmaplist != []:
-            topolist = self.get_temporal_topo_list(ifmaplist, thenmaplist,
-                                                   topolist=relations)
-        elif elsemaplist != []:
-            topolist = self.get_temporal_topo_list(ifmaplist, elsemaplist,
-                                                   topolist=relations)
-        if numthen != '':
-            numinput = numthen
-        elif numelse != '':
-            numinput = numelse
+        # Create conditional command map list.
+        resultlist = self.build_condition_cmd_list(ifmaplist, theninput,  elseinput,  
+                                                        condition_topolist = relations, 
+                                                        conclusion_topolist = ["EQUAL"], 
+                                                        temporal = 'r', null = False)
 
-        # Iterate over condition map lists with temporal relations.
-        for map_i in topolist:
-            # Loop over temporal related maps and create overlay modules.
-            tbrelations = map_i.get_temporal_relations()
-            count = 0
-            for topo in relations:
-                if topo in tbrelations.keys():
-                    for map_j in (tbrelations[topo]):
-                        # Generate an intermediate map for the result map list.
-                        map_new = self.generate_new_map(base_map=map_i,
-                                                        bool_op='and',
-                                                        copy=True)
-                        # Set first input for overlay module.
-                        mapainput = map_i.get_id()
-                        # Create overlayed map extent.
-                        returncode = self.overlay_map_extent(map_new, map_j,
-                                                             'and',
-                                                             temp_op='=')
-                        # Stop the loop if no temporal or spatial relationship exist.
-                        if returncode == 0:
-                            break
-                        if count == 0:
-                            # Set map name.
-                            name = map_new.get_id()
-                        else:
-                            # Generate an intermediate map
-                            name = self.generate_map_name()
-
-                        # Set first input for overlay module.
-                        mapbinput = map_j.get_id()
-                        # Create r.mapcalc expression string for the operation.
-                        if thenmaplist != []:
-                            if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_j):
-                                cmdstring = "if(%s,%s,%s)" % (map_new.cmd_list,
-                                                              mapbinput,
-                                                              numinput)
-                            elif "cmd_list" in dir(map_j) and "cmd_list" not in dir(map_new):
-                                cmdstring = "if(%s,%s,%s)" % (mapainput,
-                                                              map_j.cmd_list,
-                                                              numinput)
-                            elif "cmd_list" in dir(map_j) and "cmd_list" in dir(map_new):
-                                cmdstring = "if(%s,%s,%s)" % (map_new.cmd_list,
-                                                              map_j.cmd_list,
-                                                              numinput)
-                            else:
-                                cmdstring = "if(%s,%s,%s)" % (mapainput,
-                                                              mapbinput,
-                                                              numinput)
-                        if elsemaplist != []:
-                            if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_j):
-                                cmdstring = "if(%s,%s,%s)" % (map_new.cmd_list,
-                                                              numinput,
-                                                              mapbinput)
-                            elif "cmd_list" in dir(map_j) and "cmd_list" not in dir(map_new):
-                                cmdstring = "if(%s,%s,%s)" % (mapainput,
-                                                              numinput,
-                                                              map_j.cmd_list)
-                            elif "cmd_list" in dir(map_j) and "cmd_list" in dir(map_new):
-                                cmdstring = "if(%s,%s,%s)" % (map_new.cmd_list,
-                                                              numinput,
-                                                              map_j.cmd_list)
-                            else:
-                                cmdstring = "if(%s,%s,%s)" % (mapainput,
-                                                              numinput,
-                                                              mapbinput)
-                        # Conditional append of module command.
-                        map_new.cmd_list = cmdstring
-                        # Set new map name to temporary map name.
-                        #mapainput = name
-                        count += 1
-                        # Append map to result map list.
-                        if returncode == 1:
-                            resultlist.append(map_new)
-
         t[0] = resultlist
 
         if self.debug:
             for map in resultlist:
                 print map.cmd_list
 
+
     def p_s_expr_condition_elif_relation(self, t):
         # Examples:
         #   if({equal||during}, s_var_expr, A, B)
@@ -1680,145 +1531,22 @@
              | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA stds COMMA expr RPAREN
              | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA expr COMMA stds RPAREN
              | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA expr COMMA expr RPAREN
+             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds COMMA stds RPAREN
+             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds COMMA expr RPAREN
+             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA stds RPAREN
+             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA expr RPAREN
         """
-        relations, temporal, function = self.eval_toperator(t[3])
+        relations, temporal, function, aggregation = self.eval_toperator(t[3],  optype = 'relation')
         ifmaplist = self.check_stds(t[5])
         thenmaplist = self.check_stds(t[7])
         elsemaplist = self.check_stds(t[9])
-        resultlist = []
-        thendict = {}
-        elsedict = {}
-        # Get topologies for the appropriate conclusion term.
-        thentopolist = self.get_temporal_topo_list(ifmaplist, thenmaplist,
-                                                   topolist=relations)
-        # Fill dictionaries with related maps for both conclusion terms.
-        for map_i in thentopolist:
-            thenrelations = map_i.get_temporal_relations()
-            relationmaps = []
-            for topo in relations:
-                if topo in thenrelations.keys():
-                    relationmaps = relationmaps + thenrelations[topo]
-            thendict[map_i.get_id()] = relationmaps
-        # Get topologies for the alternative conclusion term.
-        elsetopolist = self.get_temporal_topo_list(ifmaplist, elsemaplist,
-                                                   topolist=relations)
-        for map_i in elsetopolist:
-            elserelations = map_i.get_temporal_relations()
-            relationmaps = []
-            for topo in relations:
-                if topo in elserelations.keys():
-                    relationmaps = relationmaps + elserelations[topo]
-            elsedict[map_i.get_id()] = relationmaps
-        # Loop trough conditional map list.
-        for map_i in ifmaplist:
-            if map_i.get_id() in thendict.keys():
-                thenlist = thendict[map_i.get_id()]
-            else:
-                thenlist = []
-            if map_i.get_id() in elsedict.keys():
-                elselist = elsedict[map_i.get_id()]
-            else:
-                elselist = []
-            # Set iteration amount to maximal or minimum number of related
-            # conclusion maps, depending on null map creation flag.
-            if self.null:
-                iternum = max(len(thenlist), len(elselist))
-            else:
-                iternum = min(len(thenlist), len(elselist))
-            # Calculate difference in conclusion lengths.
-            iterthen = iternum - len(thenlist)
-            iterelse = iternum - len(elselist)
-            # Extend null maps to the list to get conclusions with same length.
-            if iterthen != 0:
-                for i in range(iterthen):
-                    thenlist.extend(['null()'])
-            if iterelse != 0:
-                for i in range(iterelse):
-                    elselist.extend(['null()'])
+        
+        # Create conditional command map list.
+        resultlist = self.build_condition_cmd_list(ifmaplist, thenmaplist,  elsemaplist,  
+                                                        condition_topolist = relations, 
+                                                        conclusion_topolist = ["EQUAL"], 
+                                                        temporal = 'r', null = False)
 
-            # Combine the conclusions in a paired list.
-            conclusionlist = zip(thenlist, elselist)
-            for i in range(iternum):
-                conclusionmaps = conclusionlist[i]
-                # Generate an intermediate map for the result map list.
-                map_new = self.generate_new_map(base_map=map_i, bool_op='and',
-                                                copy=True)
-                # Set first input for overlay module.
-                mapifinput = map_i.get_id()
-                # Get conclusion maps.
-                map_then = conclusionmaps[0]
-                map_else = conclusionmaps[1]
-
-                # Check if conclusions are map objects.
-                if map_then != 'null()':
-                    # Create overlayed map extent.
-                    returncode = self.overlay_map_extent(map_new, map_then,
-                                                         'and', temp_op='=')
-                    maptheninput = map_then.get_id()
-                    # Continue the loop if no temporal or spatial relationship exist.
-                    if returncode == 0:
-                        continue
-                else:
-                    maptheninput = 'null()'
-                # Check if conclusions are map objects.
-                if map_else != 'null()':
-                    # Create overlayed map extent.
-                    returncode = self.overlay_map_extent(map_new, map_else,
-                                                         'and', temp_op='=')
-                    mapelseinput = map_else.get_id()
-                    # Continue the loop if no temporal or spatial relationship exist.
-                    if returncode == 0:
-                        continue
-                else:
-                    mapelseinput = 'null()'
-
-                #if map_then != 'null()' and map_else != 'null()':
-                # Create r.mapcalc expression string for the operation.
-                if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_then) \
-                    and "cmd_list" not in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (map_new.cmd_list,
-                                                    maptheninput,
-                                                    mapelseinput)
-                elif "cmd_list" in dir(map_new) and "cmd_list" in dir(map_then) \
-                    and "cmd_list" not in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (map_new.cmd_list,
-                                                    map_then.cmd_list,
-                                                    mapelseinput)
-                elif "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_then) \
-                    and "cmd_list" in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (map_new.cmd_list,
-                                                    maptheninput,
-                                                    map_else.cmd_list)
-                elif "cmd_list" in dir(map_new) and "cmd_list" in dir(map_then) \
-                    and "cmd_list" in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (map_new.cmd_list,
-                                                    map_then.cmd_list,
-                                                    map_else.cmd_list)
-                elif "cmd_list" not in dir(map_new) and "cmd_list" in dir(map_then) \
-                    and "cmd_list" not in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (mapifinput,
-                                                    map_then.cmd_list,
-                                                    mapelseinput)
-                elif "cmd_list" not in dir(map_new) and "cmd_list" not in dir(map_then) \
-                    and "cmd_list" in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (mapifinput,
-                                                    maptheninput,
-                                                    map_else.cmd_list)
-                elif "cmd_list" not in dir(map_new) and "cmd_list" in dir(map_then) \
-                    and "cmd_list" in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (mapifinput,
-                                                    map_then.cmd_list,
-                                                    map_else.cmd_list)
-                else:
-                    cmdstring = "if(%s, %s, %s)" % (mapifinput,
-                                                    maptheninput,
-                                                    mapelseinput)
-                # Conditional append of module command.
-                map_new.cmd_list = cmdstring
-                # Append map to result map list.
-                if returncode == 1:
-                    resultlist.append(map_new)
-
         t[0] = resultlist
 
         if self.debug:
@@ -1846,963 +1574,56 @@
                     | s_var_expr OR OR ts_var_expr
                     | t_var_expr OR OR ts_var_expr
         """
-        # Check whether inputs are map lists or global temporal variables and
-        # store each in separate lists.
-        ts_var_dict = {"temporal": [], "spatial": []}
-        temporal_list = []
-        spatial_list = []
-        operator = t[2] + t[3]
-        temporalop = GlobalTemporalVar()
-        temporalop.relationop = operator
-        temporalop.topology.append("EQUAL")
+        if self.run:
+            # Check input stds.
+            s_var_exprA = self.check_stds(t[1])
+            s_var_exprB = self.check_stds(t[4])
+            relations = ["EQUAL"]
+            temporal = "l"
+            function = t[2] + t[3]
+            aggregate = t[2]
+            # Build conditional values based on topological relationships.            
+            complist = self.get_temporal_topo_list(s_var_exprA, s_var_exprB, 
+                                                                            topolist = relations, compare_cmd = True, 
+                                                                            compop = function, aggregate = aggregate,  
+                                                                            convert = True)
+            # Set temporal extent based on topological relationships.
+            resultlist = self.set_temporal_extent_list(complist, topolist = relations, 
+                                temporal = temporal)
 
-        if isinstance(t[1], dict) and "spatial" in t[1]:
-            temporal_list = temporal_list + t[1]["temporal"]
-            spatial_list.append(t[1]["spatial"])
-        elif isinstance(t[1], list):
-            if all([isinstance(i, ta.GlobalTemporalVar) for i in t[1]]):
-                temporal_list = temporal_list + t[1]
-            else:
-                tsexprA = self.check_stds(t[1])
-                spatial_list.append(tsexprA)
-        elif isinstance(t[1], ta.GlobalTemporalVar):
-            temporal_list.append(t[1])
-        if temporal_list != [] and isinstance(t[4], ta.GlobalTemporalVar):
-            temporal_list.append(temporalop)
-        if temporal_list != [] and \
-            isinstance(t[4], list) and \
-            all([isinstance(i, ta.GlobalTemporalVar) for i in t[4]]):
-            temporal_list.append(temporalop)
-        if isinstance(t[4], dict) and "spatial" in t[4]:
-            temporal_list = temporal_list + t[4]["temporal"]
-            spatial_list.append(t[4]["spatial"])
-        elif isinstance(t[4], list):
-            if all([isinstance(i, ta.GlobalTemporalVar) for i in t[4]]):
-                temporal_list = temporal_list + t[4]
-            else:
-                tsexprB = self.check_stds(t[4])
-                spatial_list.append(tsexprB)
-        elif isinstance(t[4], ta.GlobalTemporalVar):
-            temporal_list.append(t[4])
-
-        ts_var_dict["temporal"] = temporal_list
-        # Condition for two map lists in spatio temporal expression.
-        if len(spatial_list) == 2:
-            # Build topology for both map lists in spatio temporal expression.
-            topolist = self.get_temporal_topo_list(spatial_list[0],
-                                                   spatial_list[1])
-            resultlist = []
-            for map_i in topolist:
-                # Loop over temporal related maps and create overlay modules.
-                tbrelations = map_i.get_temporal_relations()
-                count = 0
-                for map_j in (tbrelations['EQUAL']):
-                    # Generate an intermediate map for the result map list.
-                    map_new = self.generate_new_map(base_map=map_i,
-                                                    bool_op='and', copy=True)
-                    # Set first input for overlay module.
-                    mapainput = map_i.get_id()
-                    # Create overlayed map extent.
-                    returncode = self.overlay_map_extent(map_new, map_j,
-                                                         'and', temp_op='=')
-                    # Stop the loop if no temporal or spatial relationship exist.
-                    if returncode == 0:
-                        break
-                    if count == 0:
-                        # Set map name.
-                        name = map_new.get_id()
-                    else:
-                        # Generate an intermediate map
-                        name = self.generate_map_name()
-
-                    # Set first input for overlay module.
-                    mapbinput = map_j.get_id()
-                    # Create r.mapcalc expression string for the operation.
-                    if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_j):
-                        cmdstring = "%s %s %s" % (map_new.cmd_list, operator,
-                                                  mapbinput)
-                    elif "cmd_list" in dir(map_j) and "cmd_list" not in dir(map_new):
-                        cmdstring = "%s %s %s" % (mapainput, operator,
-                                                  map_j.cmd_list)
-                    elif "cmd_list" in dir(map_j) and "cmd_list" in dir(map_new):
-                        cmdstring = "%s %s %s" % (map_new.cmd_list, operator,
-                                                  map_j.cmd_list)
-                    else:
-                        cmdstring = "%s %s %s" % (mapainput, operator,
-                                                  mapbinput)
-                    # Conditional append of module command.
-                    map_new.cmd_list = cmdstring
-                    # Set new map name to temporary map name.
-                    #mapainput = name
-                    count += 1
-                    # Append map to result map list.
-                    if returncode == 1:
-                        resultlist.append(map_new)
-                    # Return dictionary with spatial map list of temporal
-                    # intersected maps and temporal expression in list form.
-                    ts_var_dict["spatial"] = resultlist
-        # Condition for only one map list in spatio temporal expression.
-        elif len(spatial_list) == 1:
-            ts_var_dict["spatial"] = spatial_list[0]
-
-        t[0] = ts_var_dict
-
-    def p_ts_expr_condition_if(self, t):
-        # Examples:
-        #   if(ts_var_expr, A)
-        #   if(start_year == 2013 || B != 5, A)
-        """
-        expr : IF LPAREN ts_var_expr COMMA stds RPAREN
-             | IF LPAREN ts_var_expr COMMA expr RPAREN
-        """
-        ts_var_dict = t[3]
-        spatialcond = ts_var_dict["spatial"]
-        # Extract spatial map list from condition.
-        ifmaplist = self.check_stds(spatialcond)
-        thenmaplist = self.check_stds(t[5])
-        topolist = self.get_temporal_topo_list(ifmaplist, thenmaplist)
-        resultlist = []
-        resultspatial = []
-        for map_i in topolist:
-            #print(map_i.get_id())
-            # Loop over temporal related maps and create overlay modules.
-            tbrelations = map_i.get_temporal_relations()
-            count = 0
-            for map_j in (tbrelations['EQUAL']):
-                # Generate an intermediate map for the result map list.
-                map_new = self.generate_new_map(base_map=map_i, bool_op='and',
-                                                copy=True)
-                # Set first input for overlay module.
-                mapainput = map_i.get_id()
-                # Create overlayed map extent.
-                returncode = self.overlay_map_extent(map_new, map_j, 'and',
-                                                     temp_op='=')
-                # Stop the loop if no temporal or spatial relationship exist.
-                if returncode == 0:
-                    break
-                if count == 0:
-                    # Set map name.
-                    name = map_new.get_id()
-                else:
-                    # Generate an intermediate map
-                    name = self.generate_map_name()
-
-                # Set first input for overlay module.
-                mapbinput = map_j.get_id()
-                # Create r.mapcalc expression string for the operation.
-                if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_j):
-                    cmdstring = "if(%s,%s)" % (map_new.cmd_list, mapbinput)
-                elif "cmd_list" in dir(map_j) and "cmd_list" not in dir(map_new):
-                    cmdstring = "if(%s,%s)" % (mapainput, map_j.cmd_list)
-                elif "cmd_list" in dir(map_j) and "cmd_list" in dir(map_new):
-                    cmdstring = "if(%s,%s)" % (map_new.cmd_list,
-                                               map_j.cmd_list)
-                else:
-                    cmdstring = "if(%s,%s)" % (mapainput, mapbinput)
-                # Conditional append of module command.
-                map_new.cmd_list = cmdstring
-                # Set new map name to temporary map name.
-                #mapainput = name
-                count += 1
-                # Append map to result map list.
-                if returncode == 1:
-                    resultspatial.append(map_new)
-        # Evaluate temporal statements in spatio temporal condition.
-
-        #if len(ts_var_dict["temporal"]) == 1:
-            #temporalcond = ts_var_dict["temporal"][0]
-        #else:
-        temporalcond = ts_var_dict["temporal"]
-        resultspatial = self.check_stds(resultspatial)
-        thencond = self.build_condition_list(temporalcond, resultspatial)
-        thenresult = self.eval_condition_list(thencond)
-        # Clear the map list.
-        resultlist = self.check_stds(thenresult, clear=True)
-
         t[0] = resultlist
-
-        if self.debug:
-            for map in resultlist:
-                print map.cmd_list
-
-    def p_ts_expr_condition_if_relation(self, t):
-        # Examples:
-        #   if({equal||during}, ts_var_expr, A)
-        #   if({starts||during}, B > 2 || end_month() == 4, A)
+    
+    def p_hash_operation(self, t):
+        # Calculate the number of maps within an interval of another map from a 
+        # second space time dataset.
+        # A # B
+        # A {equal,r#} B
         """
-        expr : IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds RPAREN
-             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr RPAREN
+        expr : t_hash_var
         """
-        relations, temporal, function = self.eval_toperator(t[3])
-        ts_var_dict = t[5]
-        spatialcond = ts_var_dict["spatial"]
-        # Extract spatial map list from condition.
-        ifmaplist = self.check_stds(spatialcond)
-        thenmaplist = self.check_stds(t[7])
-        topolist = self.get_temporal_topo_list(ifmaplist, thenmaplist,
-                                               topolist=relations)
-        resultspatial = []
-        for map_i in topolist:
-            #print(map_i.get_id())
-            # Loop over temporal related maps and create overlay modules.
-            tbrelations = map_i.get_temporal_relations()
-            count = 0
-            for topo in relations:
-                if topo in tbrelations.keys():
-                    for map_j in (tbrelations[topo]):
-                        # Generate an intermediate map for the result map list.
-                        map_new = self.generate_new_map(base_map=map_i,
-                                                        bool_op='and',
-                                                        copy=True)
-                        # Set first input for overlay module.
-                        mapainput = map_i.get_id()
-                        # Create overlayed map extent.
-                        returncode = self.overlay_map_extent(map_new, map_j,
-                                                             'and',
-                                                             temp_op='=')
-                        # Stop the loop if no temporal or spatial relationship exist.
-                        if returncode == 0:
-                            break
-                        if count == 0:
-                            # Set map name.
-                            name = map_new.get_id()
-                        else:
-                            # Generate an intermediate map
-                            name = self.generate_map_name()
+        # Check input stds.
+        maplist = self.check_stds(t[1])
 
-                        # Set first input for overlay module.
-                        mapbinput = map_j.get_id()
-                        # Create r.mapcalc expression string for the operation.
-                        if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_j):
-                            cmdstring = "if(%s,%s)" % (map_new.cmd_list,
-                                                       mapbinput)
-                        elif "cmd_list" in dir(map_j) and "cmd_list" not in dir(map_new):
-                            cmdstring = "if(%s,%s)" % (mapainput,
-                                                       map_j.cmd_list)
-                        elif "cmd_list" in dir(map_j) and "cmd_list" in dir(map_new):
-                            cmdstring = "if(%s,%s)" % (map_new.cmd_list,
-                                                       map_j.cmd_list)
-                        else:
-                            cmdstring = "if(%s,%s)" % (mapainput, mapbinput)
-                        # Conditional append of module command.
-                        map_new.cmd_list = cmdstring
-                        # Set new map name to temporary map name.
-                        #mapainput = name
-                        count += 1
-                        # Append map to result map list.
-                        if returncode == 1:
-                            resultspatial.append(map_new)
-        # Evaluate temporal statements in spatio temporal condition.
-
-        #if len(ts_var_dict["temporal"]) == 1:
-            #temporalcond = ts_var_dict["temporal"][0]
-        #else:
-        temporalcond = ts_var_dict["temporal"]
-        resultspatial = self.check_stds(resultspatial)
-        thencond = self.build_condition_list(temporalcond, resultspatial,
-                                             relations)
-        thenresult = self.eval_condition_list(thencond)
-        # Clear the map list.
-        resultlist = self.check_stds(thenresult, clear=True)
-
-        t[0] = resultlist
-
-        if self.debug:
-            for map in resultlist:
-                print map.cmd_list
-
-    def p_ts_numeric_condition_if(self, t):
-        # Examples:
-        #   if(ts_var_expr, 1)
-        #   if(A == 5 && start_day() > 5, 10)
-        """
-        expr : IF LPAREN ts_var_expr COMMA number RPAREN
-             | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN RPAREN
-        """
-        ts_var_dict = t[3]
-        spatialcond = ts_var_dict["spatial"]
-        ifmaplist = self.check_stds(spatialcond)
-        resultspatial = []
-        # Select input for r.mapcalc expression based on length of PLY object.
-        if len(t) == 7:
-            numinput = t[5]
-        elif len(t) == 9:
-            numinput = t[5] + t[6] + t[7]
-        # Iterate over condition map list.
-        for map_i in ifmaplist:
-            mapinput = map_i.get_id()
-            # Create r.mapcalc expression string for the operation.
-            if "cmd_list" in dir(map_i):
-                cmdstring = "if(%s,%s)" % (map_i.cmd_list, numinput)
-            else:
-                cmdstring = "if(%s,%s)" % (mapinput, numinput)
-            # Conditional append of module command.
-            map_i.cmd_list = cmdstring
-            # Append map to result map list.
-            resultspatial.append(map_i)
-
-        temporalcond = ts_var_dict["temporal"]
-        resultspatial = self.check_stds(resultspatial)
-        thencond = self.build_condition_list(temporalcond, resultspatial)
-        thenresult = self.eval_condition_list(thencond)
-        # Clear the map list.
-        resultlist = self.check_stds(thenresult, clear=True)
-
-        t[0] = resultlist
-
-        if self.debug:
-            for map in resultlist:
-                print map.cmd_list
-
-    def p_ts_expr_condition_elif(self, t):
-        # Examples:
-        #   if(s_var_expr, A, B)
-        #   if(start_day() < 20 && B > 2, A, B)
-        """
-        expr : IF LPAREN ts_var_expr COMMA stds COMMA stds RPAREN
-             | IF LPAREN ts_var_expr COMMA stds COMMA expr RPAREN
-             | IF LPAREN ts_var_expr COMMA expr COMMA stds RPAREN
-             | IF LPAREN ts_var_expr COMMA expr COMMA expr RPAREN
-        """
-        ts_var_dict = t[3]
-        spatialcond = ts_var_dict["spatial"]
-        ifmaplist = self.check_stds(spatialcond)
-        thenmaplist = self.check_stds(t[5])
-        elsemaplist = self.check_stds(t[7])
-        resultspatial = []
-        thendict = {}
-        elsedict = {}
-        # Get topologies for the appropriate conclusion term.
-        thentopolist = self.get_temporal_topo_list(ifmaplist, thenmaplist)
-        # Fill dictionaries with related maps for both conclusion terms.
-        for map_i in thentopolist:
-            thenrelations = map_i.get_temporal_relations()
-            relationmaps = thenrelations['EQUAL']
-            thendict[map_i.get_id()] = relationmaps
-        # Get topologies for the alternative conclusion term.
-        elsetopolist = self.get_temporal_topo_list(ifmaplist, elsemaplist)
-        for map_i in elsetopolist:
-            elserelations = map_i.get_temporal_relations()
-            relationmaps = elserelations['EQUAL']
-            elsedict[map_i.get_id()] = relationmaps
-        # Loop through conditional map list.
-        for map_i in ifmaplist:
-            if map_i.get_id() in thendict.keys():
-                thenlist = thendict[map_i.get_id()]
-            else:
-                thenlist = []
-            if map_i.get_id() in elsedict.keys():
-                elselist = elsedict[map_i.get_id()]
-            else:
-                elselist = []
-            # Set iteration amount to maximal or minimum number of related
-            # conclusion maps, depending on null map creation flag.
-            if self.null:
-                iternum = max(len(thenlist), len(elselist))
-            else:
-                iternum = min(len(thenlist), len(elselist))
-            # Calculate difference in conclusion lengths.
-            iterthen = iternum - len(thenlist)
-            iterelse = iternum - len(elselist)
-            # Extend null maps to the list to get conclusions with same length.
-            if iterthen != 0:
-                for i in range(iterthen):
-                    thenlist.extend(['null()'])
-            if iterelse != 0:
-                for i in range(iterelse):
-                    elselist.extend(['null()'])
-            # Combine the conclusions in a paired list.
-            conclusionlist = zip(thenlist, elselist)
-            for i in range(iternum):
-                conclusionmaps = conclusionlist[i]
-                # Generate an intermediate map for the result map list.
-                map_new = self.generate_new_map(base_map=map_i,
-                                                bool_op='and', copy=True)
-                # Set first input for overlay module.
-                mapifinput = map_i.get_id()
-                # Get conclusion maps.
-                map_then = conclusionmaps[0]
-                map_else = conclusionmaps[1]
-
-                # Check if conclusions are map objects.
-                if map_then != 'null()':
-                    # Create overlayed map extent.
-                    returncode = self.overlay_map_extent(map_new, map_then,
-                                                         'and', temp_op='=')
-                    maptheninput = map_then.get_id()
-                    # Continue the loop if no temporal or spatial relationship exist.
-                    if returncode == 0:
-                        continue
-                else:
-                    maptheninput = 'null()'
-                # Check if conclusions are map objects.
-                if map_else != 'null()':
-                    # Create overlayed map extent.
-                    returncode = self.overlay_map_extent(map_new, map_else,
-                                                         'and', temp_op='=')
-                    mapelseinput = map_else.get_id()
-                    # Continue the loop if no temporal or spatial relationship exist.
-                    if returncode == 0:
-                        continue
-                else:
-                    mapelseinput = 'null()'
-
-                #if map_then != 'null()' and map_else != 'null()':
+        if self.run:
+            resultlist = []
+            for map_i in maplist:
+                for obj in map_i.map_value:
+                    if isinstance(obj, GlobalTemporalVar):
+                        n_maps = obj.td
+                mapinput = map_i.get_id()
                 # Create r.mapcalc expression string for the operation.
-                if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_then) \
-                    and "cmd_list" not in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (map_new.cmd_list,
-                                                    maptheninput,
-                                                    mapelseinput)
-                elif "cmd_list" in dir(map_new) and "cmd_list" in dir(map_then) \
-                    and "cmd_list" not in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (map_new.cmd_list,
-                                                    map_then.cmd_list,
-                                                    mapelseinput)
-                elif "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_then) \
-                    and "cmd_list" in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (map_new.cmd_list,
-                                                    maptheninput,
-                                                    map_else.cmd_list)
-                elif "cmd_list" in dir(map_new) and "cmd_list" in dir(map_then) \
-                    and "cmd_list" in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (map_new.cmd_list,
-                                                    map_then.cmd_list,
-                                                    map_else.cmd_list)
-                elif "cmd_list" not in dir(map_new) and "cmd_list" in dir(map_then) \
-                    and "cmd_list" not in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (mapifinput,
-                                                    map_then.cmd_list,
-                                                    mapelseinput)
-                elif "cmd_list" not in dir(map_new) and "cmd_list" not in dir(map_then) \
-                    and "cmd_list" in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (mapifinput,
-                                                    maptheninput,
-                                                    map_else.cmd_list)
-                elif "cmd_list" not in dir(map_new) and "cmd_list" in dir(map_then) \
-                    and "cmd_list" in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (mapifinput,
-                                                    map_then.cmd_list,
-                                                    map_else.cmd_list)
-                else:
-                    cmdstring = "if(%s, %s, %s)" % (mapifinput,
-                                                    maptheninput,
-                                                    mapelseinput)
-                # Conditional append of module command.
-                map_new.cmd_list = cmdstring
+                cmdstring = "(%s)" %(n_maps)
+                 # Append module command.
+                map_i.cmd_list = cmdstring
                 # Append map to result map list.
-                if returncode == 1:
-                    resultspatial.append(map_new)
+                resultlist.append(map_i)
 
-        temporalcond = ts_var_dict["temporal"]
-        resultspatial = self.check_stds(resultspatial)
-        thencond = self.build_condition_list(temporalcond, resultspatial)
-        thenresult = self.eval_condition_list(thencond)
-        #elseresult = self.eval_condition_list(thencond, inverse = True)
-        # Combine and sort else and then statement to result map list.
-        #combilist = thenresult + elseresult
-        #resultlist = sorted(combilist, key = AbstractDatasetComparisonKeyStartTime)
-        # Clear the map list.
-        #resultlist = self.check_stds(resultlist, clear = True)
-        resultlist = self.check_stds(thenresult, clear=True)
+            t[0] = resultlist
 
-        t[0] = resultlist
-
         if self.debug:
             for map in resultlist:
                 print map.cmd_list
 
-    def p_ts_expr_condition_elif_relation(self, t):
-        # Examples:
-        #   if({equal||during}, s_var_expr, A, B)
-        #   if({contains}, start_day() == 3 || C != 2, A, B)
-        """
-        expr : IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds COMMA stds RPAREN
-             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds COMMA expr RPAREN
-             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA stds RPAREN
-             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA expr RPAREN
-        """
-        relations, temporal, function = self.eval_toperator(t[3])
-        ts_var_dict = t[5]
-        spatialcond = ts_var_dict["spatial"]
-        # Extract spatial map list from condition.
-        ifmaplist = self.check_stds(spatialcond)
-        thenmaplist = self.check_stds(t[7])
-        elsemaplist = self.check_stds(t[9])
-        resultspatial = []
-        thendict = {}
-        elsedict = {}
-        # Get topologies for the appropriate conclusion term.
-        thentopolist = self.get_temporal_topo_list(ifmaplist, thenmaplist,
-                                                   topolist=relations)
-        # Fill dictionaries with related maps for both conclusion terms.
-        for map_i in thentopolist:
-            thenrelations = map_i.get_temporal_relations()
-            relationmaps = []
-            for topo in relations:
-                if topo in thenrelations.keys():
-                    relationmaps = relationmaps + thenrelations[topo]
-            thendict[map_i.get_id()] = relationmaps
-        # Get topologies for the alternative conclusion term.
-        elsetopolist = self.get_temporal_topo_list(ifmaplist, elsemaplist,
-                                                   topolist=relations)
-        for map_i in elsetopolist:
-            elserelations = map_i.get_temporal_relations()
-            relationmaps = []
-            for topo in relations:
-                if topo in elserelations.keys():
-                    relationmaps = relationmaps + elserelations[topo]
-            elsedict[map_i.get_id()] = relationmaps
-        # Loop trough conditional map list.
-        for map_i in ifmaplist:
-            if map_i.get_id() in thendict.keys():
-                thenlist = thendict[map_i.get_id()]
-            else:
-                thenlist = []
-            if map_i.get_id() in elsedict.keys():
-                elselist = elsedict[map_i.get_id()]
-            else:
-                elselist = []
-            # Set iteration amount to maximal or minimum number of related
-            # conclusion maps, depending on null map creation flag.
-            if self.null:
-                iternum = max(len(thenlist), len(elselist))
-            else:
-                iternum = min(len(thenlist), len(elselist))
-            # Calculate difference in conclusion lengths.
-            iterthen = iternum - len(thenlist)
-            iterelse = iternum - len(elselist)
-            # Extend null maps to the list to get conclusions with same length.
-            if iterthen != 0:
-                for i in range(iterthen):
-                    thenlist.extend(['null()'])
-            if iterelse != 0:
-                for i in range(iterelse):
-                    elselist.extend(['null()'])
-
-            # Combine the conclusions in a paired list.
-            conclusionlist = zip(thenlist, elselist)
-            for i in range(iternum):
-                conclusionmaps = conclusionlist[i]
-                # Generate an intermediate map for the result map list.
-                map_new = self.generate_new_map(base_map=map_i, bool_op='and',
-                                                copy=True)
-                # Set first input for overlay module.
-                mapifinput = map_i.get_id()
-                # Get conclusion maps.
-                map_then = conclusionmaps[0]
-                map_else = conclusionmaps[1]
-
-                # Check if conclusions are map objects.
-                if map_then != 'null()':
-                    # Create overlayed map extent.
-                    returncode = self.overlay_map_extent(map_new, map_then,
-                                                         'and', temp_op='=')
-                    maptheninput = map_then.get_id()
-                    # Continue the loop if no temporal or spatial relationship exist.
-                    if returncode == 0:
-                        continue
-                else:
-                    maptheninput = 'null()'
-                # Check if conclusions are map objects.
-                if map_else != 'null()':
-                    # Create overlayed map extent.
-                    returncode = self.overlay_map_extent(map_new, map_else,
-                                                         'and', temp_op='=')
-                    mapelseinput = map_else.get_id()
-                    # Continue the loop if no temporal or spatial relationship exist.
-                    if returncode == 0:
-                        continue
-                else:
-                    mapelseinput = 'null()'
-
-                #if map_then != 'null()' and map_else != 'null()':
-                # Create r.mapcalc expression string for the operation.
-                if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_then) \
-                    and "cmd_list" not in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (map_new.cmd_list,
-                                                    maptheninput,
-                                                    mapelseinput)
-                elif "cmd_list" in dir(map_new) and "cmd_list" in dir(map_then) \
-                    and "cmd_list" not in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (map_new.cmd_list,
-                                                    map_then.cmd_list,
-                                                    mapelseinput)
-                elif "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_then) \
-                    and "cmd_list" in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (map_new.cmd_list,
-                                                    maptheninput,
-                                                    map_else.cmd_list)
-                elif "cmd_list" in dir(map_new) and "cmd_list" in dir(map_then) \
-                    and "cmd_list" in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (map_new.cmd_list,
-                                                    map_then.cmd_list,
-                                                    map_else.cmd_list)
-                elif "cmd_list" not in dir(map_new) and "cmd_list" in dir(map_then) \
-                    and "cmd_list" not in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (mapifinput,
-                                                    map_then.cmd_list,
-                                                    mapelseinput)
-                elif "cmd_list" not in dir(map_new) and "cmd_list" not in dir(map_then) \
-                    and "cmd_list" in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (mapifinput, maptheninput,
-                                                    map_else.cmd_list)
-                elif "cmd_list" not in dir(map_new) and "cmd_list" in dir(map_then) \
-                    and "cmd_list" in dir(map_else):
-                    cmdstring = "if(%s, %s, %s)" % (mapifinput,
-                                                    map_then.cmd_list,
-                                                    map_else.cmd_list)
-                else:
-                    cmdstring = "if(%s, %s, %s)" % (mapifinput, maptheninput,
-                                                    mapelseinput)
-                # Conditional append of module command.
-                map_new.cmd_list = cmdstring
-                # Append map to result map list.
-                if returncode == 1:
-                    resultspatial.append(map_new)
-
-        temporalcond = ts_var_dict["temporal"]
-        resultspatial = self.check_stds(resultspatial)
-        thencond = self.build_condition_list(temporalcond, resultspatial,
-                                             relations)
-        thenresult = self.eval_condition_list(thencond)
-        #elseresult = self.eval_condition_list(thencond, inverse = True)
-        # Combine and sort else and then statement to result map list.
-        #combilist = thenresult + elseresult
-        #resultlist = sorted(combilist, key = AbstractDatasetComparisonKeyStartTime)
-        # Clear the map list.
-        resultlist = self.check_stds(thenresult, clear=True)
-
-        t[0] = resultlist
-
-        if self.debug:
-            for map in resultlist:
-                print map.cmd_list
-
-    def p_ts_numeric_condition_elif(self, t):
-        # Examples:
-        #   if(ts_var_expr, 1, 2)
-        #   if(A == 1 || end_year == 2013, 10, null())
-        """
-        expr : IF LPAREN ts_var_expr COMMA number COMMA number RPAREN
-             | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA number RPAREN
-             | IF LPAREN ts_var_expr COMMA number COMMA NULL LPAREN RPAREN RPAREN
-             | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA NULL LPAREN RPAREN RPAREN
-        """
-        ts_var_dict = t[3]
-        spatialcond = ts_var_dict["spatial"]
-        # Extract spatial map list from condition.
-        ifmaplist = self.check_stds(spatialcond)
-        resultspatial = []
-        # Select input for r.mapcalc expression based on length of PLY object.
-        if len(t) == 9:
-            numthen = t[5]
-            numelse = t[7]
-        elif len(t) == 11:
-            numthen = self.check_null(t[5])
-            numelse = self.check_null(t[7])
-        elif len(t) == 13:
-            numthen = self.check_null(t[5])
-            numelse = self.check_null(t[9])
-
-        # Iterate over condition map list.
-        for map_i in ifmaplist:
-            mapinput = map_i.get_id()
-            # Create r.mapcalc expression string for the operation.
-            if "cmd_list" in dir(map_i):
-                cmdstring = "if(%s, %s, %s)" % (map_i.cmd_list, numthen,
-                                                numelse)
-            else:
-                cmdstring = "if(%s, %s, %s)" % (mapinput, numthen, numelse)
-            # Conditional append of module command.
-            map_i.cmd_list = cmdstring
-            # Append map to result map list.
-            resultspatial.append(map_i)
-
-        temporalcond = ts_var_dict["temporal"]
-        resultspatial = self.check_stds(resultspatial)
-        thencond = self.build_condition_list(temporalcond, resultspatial)
-        thenresult = self.eval_condition_list(thencond)
-        #elseresult = self.eval_condition_list(thencond, inverse = True)
-        # Combine and sort else and then statement to result map list.
-        #combilist = thenresult + elseresult
-        #resultlist = sorted(combilist, key = AbstractDatasetComparisonKeyStartTime)
-        # Clear the map list.
-        #resultlist = self.check_stds(resultlist, clear = True)
-        resultlist = self.check_stds(thenresult, clear=True)
-
-        t[0] = resultlist
-
-    def p_ts_numeric_expr_condition_elif(self, t):
-        # Examples:
-        #   if(ts_var_expr, 1, A)
-        #   if(A == 5 && start_day() > 5, A, null())
-        """
-        expr : IF LPAREN ts_var_expr COMMA number COMMA stds RPAREN
-             | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA stds RPAREN
-             | IF LPAREN ts_var_expr COMMA number COMMA expr RPAREN
-             | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA expr RPAREN
-             | IF LPAREN ts_var_expr COMMA stds COMMA number RPAREN
-             | IF LPAREN ts_var_expr COMMA stds COMMA NULL LPAREN RPAREN RPAREN
-             | IF LPAREN ts_var_expr COMMA expr COMMA number RPAREN
-             | IF LPAREN ts_var_expr COMMA expr COMMA NULL LPAREN RPAREN RPAREN
-        """
-        ts_var_dict = t[3]
-        spatialcond = ts_var_dict["spatial"]
-        ifmaplist = self.check_stds(spatialcond)
-        resultspatial = []
-        thenmaplist = []
-        numthen = ''
-        elsemaplist = []
-        numelse = ''
-        # Select input for r.mapcalc expression based on length of PLY object.
-        if len(t) == 9:
-            try:
-                thenmaplist = self.check_stds(t[5])
-            except:
-                numthen = t[5]
-            try:
-                elsemaplist = self.check_stds(t[7])
-            except:
-                numelse = t[7]
-        elif len(t) == 11:
-            try:
-                thenmaplist = self.check_stds(t[5])
-            except:
-                numthen = t[5] + t[6] + t[7]
-            try:
-                elsemaplist = self.check_stds(t[9])
-            except:
-                numelse = t[7] + t[8] + t[9]
-        if thenmaplist != []:
-            topolist = self.get_temporal_topo_list(ifmaplist, thenmaplist)
-        elif elsemaplist != []:
-            topolist = self.get_temporal_topo_list(ifmaplist, elsemaplist)
-        if numthen != '':
-            numinput = numthen
-        elif numelse != '':
-            numinput = numelse
-
-        # Iterate over condition map lists with temporal relations.
-        for map_i in topolist:
-            # Loop over temporal related maps and create overlay modules.
-            tbrelations = map_i.get_temporal_relations()
-            count = 0
-            for map_j in (tbrelations['EQUAL']):
-                # Generate an intermediate map for the result map list.
-                map_new = self.generate_new_map(base_map=map_i, bool_op='and',
-                                                copy=True)
-                # Set first input for overlay module.
-                mapainput = map_i.get_id()
-                # Create overlayed map extent.
-                returncode = self.overlay_map_extent(map_new, map_j, 'and',
-                                                     temp_op='=')
-                # Stop the loop if no temporal or spatial relationship exist.
-                if returncode == 0:
-                    break
-                if count == 0:
-                    # Set map name.
-                    name = map_new.get_id()
-                else:
-                    # Generate an intermediate map
-                    name = self.generate_map_name()
-
-                # Set first input for overlay module.
-                mapbinput = map_j.get_id()
-                # Create r.mapcalc expression string for the operation.
-                if thenmaplist != []:
-                    if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_j):
-                        cmdstring = "if(%s,%s,%s)" % (map_new.cmd_list,
-                                                      mapbinput,
-                                                      numinput)
-                    elif "cmd_list" in dir(map_j) and "cmd_list" not in dir(map_new):
-                        cmdstring = "if(%s,%s,%s)" % (mapainput,
-                                                      map_j.cmd_list,
-                                                      numinput)
-                    elif "cmd_list" in dir(map_j) and "cmd_list" in dir(map_new):
-                        cmdstring = "if(%s,%s,%s)" % (map_new.cmd_list,
-                                                      map_j.cmd_list,
-                                                      numinput)
-                    else:
-                        cmdstring = "if(%s,%s,%s)" % (mapainput, mapbinput,
-                                                      numinput)
-                if elsemaplist != []:
-                    if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_j):
-                        cmdstring = "if(%s,%s,%s)" % (map_new.cmd_list,
-                                                      numinput,
-                                                      mapbinput)
-                    elif "cmd_list" in dir(map_j) and "cmd_list" not in dir(map_new):
-                        cmdstring = "if(%s,%s,%s)" % (mapainput, numinput,
-                                                      map_j.cmd_list)
-                    elif "cmd_list" in dir(map_j) and "cmd_list" in dir(map_new):
-                        cmdstring = "if(%s,%s,%s)" % (map_new.cmd_list,
-                                                      numinput, map_j.cmd_list)
-                    else:
-                        cmdstring = "if(%s,%s,%s)" % (mapainput, numinput,
-                                                      mapbinput)
-                # Conditional append of module command.
-                map_new.cmd_list = cmdstring
-                # Set new map name to temporary map name.
-                #mapainput = name
-                count += 1
-                # Append map to result map list.
-                if returncode == 1:
-                    resultspatial.append(map_new)
-
-        temporalcond = ts_var_dict["temporal"]
-        resultspatial = self.check_stds(resultspatial)
-        thencond = self.build_condition_list(temporalcond, resultspatial)
-        thenresult = self.eval_condition_list(thencond)
-        # Clear the map list.
-        resultlist = self.check_stds(thenresult, clear=True)
-
-        t[0] = resultlist
-
-        if self.debug:
-            for map in resultlist:
-                print map.cmd_list
-
-    def p_ts_numeric_expr_condition_elif_relation(self, t):
-        # Examples:
-        #   if({during},ts_var_expr, 1, A)
-        #   if({during}, A == 5 && start_day() > 5, A, null())
-        """
-        expr : IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA number COMMA stds RPAREN
-             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA NULL LPAREN RPAREN COMMA stds RPAREN
-             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA number COMMA expr RPAREN
-             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA NULL LPAREN RPAREN COMMA expr RPAREN
-             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds COMMA number RPAREN
-             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds COMMA NULL LPAREN RPAREN RPAREN
-             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA number RPAREN
-             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA NULL LPAREN RPAREN RPAREN
-        """
-        relations, temporal, function = self.eval_toperator(t[3])
-        ts_var_dict = t[5]
-        spatialcond = ts_var_dict["spatial"]
-        ifmaplist = self.check_stds(spatialcond)
-        resultspatial = []
-        thenmaplist = []
-        numthen = ''
-        elsemaplist = []
-        numelse = ''
-        # Select input for r.mapcalc expression based on length of PLY object.
-        if len(t) == 11:
-            try:
-                thenmaplist = self.check_stds(t[7])
-            except:
-                numthen = t[7]
-            try:
-                elsemaplist = self.check_stds(t[9])
-            except:
-                numelse = t[9]
-        elif len(t) == 13:
-            try:
-                thenmaplist = self.check_stds(t[7])
-            except:
-                numthen = t[9] + t[10] + t[11]
-            try:
-                elsemaplist = self.check_stds(t[11])
-            except:
-                numelse = t[9] + t[10] + t[11]
-        if thenmaplist != []:
-            topolist = self.get_temporal_topo_list(ifmaplist, thenmaplist,
-                                                   topolist=relations)
-        elif elsemaplist != []:
-            topolist = self.get_temporal_topo_list(ifmaplist, elsemaplist,
-                                                   topolist=relations)
-        if numthen != '':
-            numinput = numthen
-        elif numelse != '':
-            numinput = numelse
-
-        # Iterate over condition map lists with temporal relations.
-        for map_i in topolist:
-            # Loop over temporal related maps and create overlay modules.
-            tbrelations = map_i.get_temporal_relations()
-            count = 0
-            for topo in relations:
-                if topo in tbrelations.keys():
-                    for map_j in (tbrelations[topo]):
-                        # Generate an intermediate map for the result map list.
-                        map_new = self.generate_new_map(base_map=map_i,
-                                                        bool_op='and',
-                                                        copy=True)
-                        # Set first input for overlay module.
-                        mapainput = map_i.get_id()
-                        # Create overlayed map extent.
-                        returncode = self.overlay_map_extent(map_new, map_j,
-                                                             'and',
-                                                             temp_op='=')
-                        # Stop the loop if no temporal or spatial relationship exist.
-                        if returncode == 0:
-                            break
-                        if count == 0:
-                            # Set map name.
-                            name = map_new.get_id()
-                        else:
-                            # Generate an intermediate map
-                            name = self.generate_map_name()
-
-                        # Set first input for overlay module.
-                        mapbinput = map_j.get_id()
-                        # Create r.mapcalc expression string for the operation.
-                        if thenmaplist != []:
-                            if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_j):
-                                cmdstring = "if(%s,%s,%s)" % (map_new.cmd_list,
-                                                              mapbinput,
-                                                              numinput)
-                            elif "cmd_list" in dir(map_j) and "cmd_list" not in dir(map_new):
-                                cmdstring = "if(%s,%s,%s)" % (mapainput,
-                                                              map_j.cmd_list,
-                                                              numinput)
-                            elif "cmd_list" in dir(map_j) and "cmd_list" in dir(map_new):
-                                cmdstring = "if(%s,%s,%s)" % (map_new.cmd_list,
-                                                              map_j.cmd_list,
-                                                              numinput)
-                            else:
-                                cmdstring = "if(%s,%s,%s)" % (mapainput,
-                                                              mapbinput,
-                                                              numinput)
-                        if elsemaplist != []:
-                            if "cmd_list" in dir(map_new) and "cmd_list" not in dir(map_j):
-                                cmdstring = "if(%s,%s,%s)" % (map_new.cmd_list,
-                                                              numinput,
-                                                              mapbinput)
-                            elif "cmd_list" in dir(map_j) and "cmd_list" not in dir(map_new):
-                                cmdstring = "if(%s,%s,%s)" % (mapainput,
-                                                              numinput,
-                                                              map_j.cmd_list)
-                            elif "cmd_list" in dir(map_j) and "cmd_list" in dir(map_new):
-                                cmdstring = "if(%s,%s,%s)" % (map_new.cmd_list,
-                                                              numinput,
-                                                              map_j.cmd_list)
-                            else:
-                                cmdstring = "if(%s,%s,%s)" % (mapainput,
-                                                              numinput,
-                                                              mapbinput)
-                        # Conditional append of module command.
-                        map_new.cmd_list = cmdstring
-                        # Set new map name to temporary map name.
-                        #mapainput = name
-                        count += 1
-                        # Append map to result map list.
-                        if returncode == 1:
-                            resultspatial.append(map_new)
-
-        temporalcond = ts_var_dict["temporal"]
-        resultspatial = self.check_stds(resultspatial)
-        thencond = self.build_condition_list(temporalcond, resultspatial)
-        thenresult = self.eval_condition_list(thencond)
-        # Clear the map list.
-        resultlist = self.check_stds(thenresult, clear=True)
-
-        t[0] = resultlist
-
-        if self.debug:
-            for map in resultlist:
-                print map.cmd_list
-
-
 ###############################################################################
 
 if __name__ == "__main__":

Deleted: grass/trunk/lib/python/temporal/temporal_raster_operator.py
===================================================================
--- grass/trunk/lib/python/temporal/temporal_raster_operator.py	2014-11-04 15:04:13 UTC (rev 62593)
+++ grass/trunk/lib/python/temporal/temporal_raster_operator.py	2014-11-04 15:45:52 UTC (rev 62594)
@@ -1,389 +0,0 @@
-"""
-Temporal operator evaluation with PLY
-
-(C) 2013 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.
-
-:authors: Thomas Leppelt and Soeren Gebbert
-
-.. code-block:: python
-
-    >>> p = TemporalRasterOperatorParser()
-    >>> expression =  "{equal| during | follows,+!:}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal', 'during', 'follows'], '+', '!:')
-    >>> expression =  "{equal| during,!:}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal', 'during'], '=', '!:')
-    >>> expression =  "{!:}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal'], '=', '!:')
-    >>> expression =  "{|#}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal'], '|', '#')
-    >>> expression =  "{equal|during,=!:}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal', 'during'], '=', '!:')
-    >>> expression =  "{equal|during|starts}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal', 'during', 'starts'], None, None)
-    >>> expression =  "{equal,++}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal'], '+', '+')
-    >>> expression =  "{equal | during,|%}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal', 'during'], '|', '%')
-    >>> expression =  "{||}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal'], '=', '||')
-    >>> expression =  "{equal,||}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal'], '=', '||')
-    >>> expression =  "{equal | during | contains,&&}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal', 'during', 'contains'], '=', '&&')
-    >>> expression =  "{equal | during | contains,/}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal', 'during', 'contains'], '=', '/')
-    >>> expression =  "{equal | during | contains,|*}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal', 'during', 'contains'], '|', '*')
-
-"""
-
-try:
-    import ply.lex as lex
-    import ply.yacc as yacc
-except:
-    pass
-
-
-class TemporalRasterOperatorLexer(object):
-    """Lexical analyzer for the GRASS GIS temporal operator"""
-
-    # Functions that defines topological relations.
-    relations = {
-        'equal': "EQUAL",
-        'follows': "FOLLOWS",
-        'precedes': "PRECEDES",
-        'overlaps': "OVERLAPS",
-        'overlapped': "OVERLAPPED",
-        'during': "DURING",
-        'starts': "STARTS",
-        'finishes': "FINISHES",
-        'contains': "CONTAINS",
-        'started': "STARTED",
-        'finished': "FINISHED",
-        'over': "OVER"
-        }
-
-    # This is the list of token names.
-    tokens = (
-        'COMMA',
-        'LEFTREF',
-        'HASH',
-        'OR',
-        'AND',
-        'MOD',
-        'DIV',
-        'MULT',
-        'ADD',
-        'SUB',
-        'T_SELECT',
-        'T_NOT_SELECT',
-        'CLPAREN',
-        'CRPAREN',
-    )
-
-    # Build the token list
-    tokens = tokens + tuple(relations.values())
-
-    # Regular expression rules for simple tokens
-    t_T_SELECT = r':'
-    t_T_NOT_SELECT = r'!:'
-    t_COMMA = r','
-    t_LEFTREF = r'='
-    t_HASH = r'\#'
-    t_OR = r'[\|]'
-    t_AND = r'[&]'
-    t_MOD = r'[\%]'
-    t_DIV = r'[\/]'
-    t_MULT = r'[\*]'
-    t_ADD = r'[\+]'
-    t_SUB = r'[-]'
-    t_CLPAREN = r'\{'
-    t_CRPAREN = r'\}'
-
-    # These are the things that should be ignored.
-    t_ignore = ' \t'
-
-    # Track line numbers.
-    def t_newline(self, t):
-        r'\n+'
-        t.lineno += len(t.value)
-
-    def t_NAME(self, t):
-        r'[a-zA-Z_][a-zA-Z_0-9]*'
-        self.temporal_symbol(t)
-        return t
-
-    # Parse symbols
-    def temporal_symbol(self, t):
-        # Check for reserved words
-        if t.value in TemporalRasterOperatorLexer.relations.keys():
-            t.type = TemporalRasterOperatorLexer.relations.get(t.value)
-        #else:
-        #    t.type = 'NAME'
-        return(t)
-
-    # Handle errors.
-    def t_error(self, t):
-        raise SyntaxError("syntax error on line %d near '%s'" %
-                          (t.lineno, t.value))
-
-    # Build the lexer
-    def build(self, **kwargs):
-        self.lexer = lex.lex(module=self, **kwargs)
-
-    # Just for testing
-    def test(self, data):
-        self.name_list = {}
-        print(data)
-        self.lexer.input(data)
-        while True:
-            tok = self.lexer.token()
-            if not tok: break
-            print tok
-
-###############################################################################
-
-
-class TemporalRasterOperatorParser(object):
-    """The temporal algebra class"""
-
-    def __init__(self):
-        self.lexer = TemporalRasterOperatorLexer()
-        self.lexer.build()
-        self.parser = yacc.yacc(module=self)
-
-    def parse(self, expression, comparison=False):
-        self.comparison = comparison
-        self.parser.parse(expression)
-
-    # Error rule for syntax errors.
-    def p_error(self, t):
-        raise SyntaxError("invalid syntax")
-
-    # Get the tokens from the lexer class
-    tokens = TemporalRasterOperatorLexer.tokens
-
-    def p_relation_only(self, t):
-        # The expression should always return a list of maps.
-        """
-        operator : CLPAREN relation CRPAREN
-                 | CLPAREN relationlist CRPAREN
-        """
-        # Set three operator components.
-        if isinstance(t[2], list):
-            self.relations = t[2]
-        else:
-            self.relations = [t[2]]
-        self.temporal = None
-        self.function = None
-
-        t[0] = t[2]
-
-    def p_operator(self, t):
-        # The expression should always return a list of maps.
-        """
-        operator : CLPAREN select CRPAREN
-                 | CLPAREN HASH CRPAREN
-                 | CLPAREN arithmetic CRPAREN
-        """
-        # Set three operator components.
-        self.relations = ['equal']
-        self.temporal = "="
-        self.function = t[2]
-
-        t[0] = t[2]
-
-    def p_comparison(self, t):
-        # The expression should always return a list of maps.
-        """
-        operator : CLPAREN temporal AND CRPAREN
-                 | CLPAREN temporal OR CRPAREN
-        """
-        # Set three operator components.
-        self.relations = ['equal']
-        self.temporal = "="
-        if t[2] == t[3]:
-            self.function = t[2] + t[3]
-        else:
-            raise SyntaxError("syntax error on line %d near '%s'" %
-                              (t.lineno, t.value))
-
-        t[0] = t[2]
-
-    def p_operator_temporal(self, t):
-        # The expression should always return a list of maps.
-        """
-        operator : CLPAREN temporal select CRPAREN
-                 | CLPAREN temporal HASH CRPAREN
-                 | CLPAREN temporal arithmetic CRPAREN
-        """
-        # Set three operator components.
-        self.relations = ['equal']
-        self.temporal = t[2]
-        self.function = t[3]
-
-        t[0] = t[3]
-
-    def p_operator_relation(self, t):
-        # The expression should always return a list of maps.
-        """
-        operator : CLPAREN relation COMMA select CRPAREN
-                 | CLPAREN relationlist COMMA select CRPAREN
-                 | CLPAREN relation COMMA HASH CRPAREN
-                 | CLPAREN relationlist COMMA HASH CRPAREN
-                 | CLPAREN relation COMMA arithmetic CRPAREN
-                 | CLPAREN relationlist COMMA arithmetic CRPAREN
-        """
-        # Set three operator components.
-        if isinstance(t[2], list):
-            self.relations = t[2]
-        else:
-            self.relations = [t[2]]
-        self.temporal = "="
-        self.function = t[4]
-
-        t[0] = t[4]
-
-    def p_comparison_relation(self, t):
-        # The expression should always return a list of maps.
-        """
-        operator : CLPAREN relation COMMA temporal AND CRPAREN
-                 | CLPAREN relation COMMA temporal OR CRPAREN
-                 | CLPAREN relationlist COMMA temporal AND CRPAREN
-                 | CLPAREN relationlist COMMA temporal OR CRPAREN
-        """
-        # Set three operator components.
-        if isinstance(t[2], list):
-            self.relations = t[2]
-        else:
-            self.relations = [t[2]]
-        self.temporal = "="
-        if t[4] == t[5]:
-            self.function = t[4] + t[5]
-        else:
-            raise SyntaxError("syntax error on line %d near '%s'" %
-                              (t.lineno, t.value))
-
-        t[0] = t[4]
-
-    def p_operator_relation_temporal(self, t):
-        # The expression should always return a list of maps.
-        """
-        operator : CLPAREN relation COMMA temporal select CRPAREN
-                 | CLPAREN relationlist COMMA temporal select CRPAREN
-                 | CLPAREN relation COMMA temporal HASH CRPAREN
-                 | CLPAREN relationlist COMMA temporal HASH CRPAREN
-                 | CLPAREN relation COMMA temporal arithmetic CRPAREN
-                 | CLPAREN relationlist COMMA temporal arithmetic CRPAREN
-        """
-        # Set three operator components.
-        if isinstance(t[2], list):
-            self.relations = t[2]
-        else:
-            self.relations = [t[2]]
-        self.temporal = t[4]
-        self.function = t[5]
-        t[0] = t[5]
-
-    def p_relation(self, t):
-        # The list of relations.
-        """
-        relation : EQUAL
-                 | FOLLOWS
-                 | PRECEDES
-                 | OVERLAPS
-                 | OVERLAPPED
-                 | DURING
-                 | STARTS
-                 | FINISHES
-                 | CONTAINS
-                 | STARTED
-                 | FINISHED
-        """
-        t[0] = t[1]
-
-    def p_over(self, t):
-        # The list of relations.
-        """
-        relation : OVER
-        """
-        over_list = ["overlaps", "overlapped"]
-        t[0] = over_list
-
-    def p_relationlist(self, t):
-        # The list of relations.
-        """
-        relationlist : relation OR relation
-                     | relation OR relationlist
-        """
-        rel_list = []
-        rel_list.append(t[1])
-        if isinstance(t[3], list):
-            rel_list = rel_list + t[3]
-        else:
-            rel_list.append(t[3])
-        t[0] = rel_list
-
-    def p_temporal_operator(self, t):
-        # The list of relations.
-        """
-        temporal : LEFTREF
-                 | OR
-                 | AND
-                 | ADD
-        """
-        t[0] = t[1]
-
-    def p_select_operator(self, t):
-        # The list of relations.
-        """
-        select : T_SELECT
-               | T_NOT_SELECT
-        """
-        t[0] = t[1]
-
-    def p_arithmetic_operator(self, t):
-        # The list of relations.
-        """
-        arithmetic : MOD
-                   | DIV
-                   | MULT
-                   | ADD
-                   | SUB
-        """
-        t[0] = t[1]
-
-###############################################################################
-
-if __name__ == "__main__":
-    import doctest
-    doctest.testmod()

Modified: grass/trunk/lib/python/temporal/temporal_vector_algebra.py
===================================================================
--- grass/trunk/lib/python/temporal/temporal_vector_algebra.py	2014-11-04 15:04:13 UTC (rev 62593)
+++ grass/trunk/lib/python/temporal/temporal_vector_algebra.py	2014-11-04 15:45:52 UTC (rev 62594)
@@ -1,4 +1,5 @@
-"""
+"""@package grass.temporal
+
 Temporal vector algebra
 
 (C) 2014 by the GRASS Development Team
@@ -15,286 +16,6 @@
     >>> p = tgis.TemporalVectorAlgebraLexer()
     >>> p.build()
     >>> p.debug = True
-    >>> expression =  "C = A : B"
-    >>> p.test(expression)
-    C = A : B
-    LexToken(NAME,'C',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(NAME,'A',1,4)
-    LexToken(T_SELECT,':',1,6)
-    LexToken(NAME,'B',1,8)
-    >>> expression =  "C = test1 !: test2"
-    >>> p.test(expression)
-    C = test1 !: test2
-    LexToken(NAME,'C',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(NAME,'test1',1,4)
-    LexToken(T_NOT_SELECT,'!:',1,10)
-    LexToken(NAME,'test2',1,13)
-    >>> expression =  "C = test1 {equal,:} test2"
-    >>> p.test(expression)
-    C = test1 {equal,:} test2
-    LexToken(NAME,'C',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(NAME,'test1',1,4)
-    LexToken(T_SELECT_OPERATOR,'{equal,:}',1,10)
-    LexToken(NAME,'test2',1,20)
-    >>> expression =  "C = test1 {equal,!:} test2"
-    >>> p.test(expression)
-    C = test1 {equal,!:} test2
-    LexToken(NAME,'C',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(NAME,'test1',1,4)
-    LexToken(T_SELECT_OPERATOR,'{equal,!:}',1,10)
-    LexToken(NAME,'test2',1,21)
-    >>> expression =  "C = test1 # test2"
-    >>> p.test(expression)
-    C = test1 # test2
-    LexToken(NAME,'C',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(NAME,'test1',1,4)
-    LexToken(HASH,'#',1,10)
-    LexToken(NAME,'test2',1,12)
-    >>> expression =  "C = test1 {#} test2"
-    >>> p.test(expression)
-    C = test1 {#} test2
-    LexToken(NAME,'C',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(NAME,'test1',1,4)
-    LexToken(T_HASH_OPERATOR,'{#}',1,10)
-    LexToken(NAME,'test2',1,14)
-    >>> expression =  "C = test1 {equal,#} test2"
-    >>> p.test(expression)
-    C = test1 {equal,#} test2
-    LexToken(NAME,'C',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(NAME,'test1',1,4)
-    LexToken(T_HASH_OPERATOR,'{equal,#}',1,10)
-    LexToken(NAME,'test2',1,20)
-    >>> expression =  "C = test1 {equal|during,#} test2"
-    >>> p.test(expression)
-    C = test1 {equal|during,#} test2
-    LexToken(NAME,'C',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(NAME,'test1',1,4)
-    LexToken(T_HASH_OPERATOR,'{equal|during,#}',1,10)
-    LexToken(NAME,'test2',1,27)
-    >>> expression =  "E = test1 : test2 !: test1"
-    >>> p.test(expression)
-    E = test1 : test2 !: test1
-    LexToken(NAME,'E',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(NAME,'test1',1,4)
-    LexToken(T_SELECT,':',1,10)
-    LexToken(NAME,'test2',1,12)
-    LexToken(T_NOT_SELECT,'!:',1,18)
-    LexToken(NAME,'test1',1,21)
-    >>> expression =  'D = buff_t(test1,"10 months")'
-    >>> p.test(expression)
-    D = buff_t(test1,"10 months")
-    LexToken(NAME,'D',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(BUFF_T,'buff_t',1,4)
-    LexToken(LPAREN,'(',1,10)
-    LexToken(NAME,'test1',1,11)
-    LexToken(COMMA,',',1,16)
-    LexToken(QUOTE,'"',1,17)
-    LexToken(INT,10,1,18)
-    LexToken(NAME,'months',1,21)
-    LexToken(QUOTE,'"',1,27)
-    LexToken(RPAREN,')',1,28)
-    >>> expression =  'H = tsnap(test1)'
-    >>> p.test(expression)
-    H = tsnap(test1)
-    LexToken(NAME,'H',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(TSNAP,'tsnap',1,4)
-    LexToken(LPAREN,'(',1,9)
-    LexToken(NAME,'test1',1,10)
-    LexToken(RPAREN,')',1,15)
-    >>> expression =  'H = tsnap(test2 {during,:} buff_t(test1, "1 days"))'
-    >>> p.test(expression)
-    H = tsnap(test2 {during,:} buff_t(test1, "1 days"))
-    LexToken(NAME,'H',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(TSNAP,'tsnap',1,4)
-    LexToken(LPAREN,'(',1,9)
-    LexToken(NAME,'test2',1,10)
-    LexToken(T_SELECT_OPERATOR,'{during,:}',1,16)
-    LexToken(BUFF_T,'buff_t',1,27)
-    LexToken(LPAREN,'(',1,33)
-    LexToken(NAME,'test1',1,34)
-    LexToken(COMMA,',',1,39)
-    LexToken(QUOTE,'"',1,41)
-    LexToken(INT,1,1,42)
-    LexToken(NAME,'days',1,44)
-    LexToken(QUOTE,'"',1,48)
-    LexToken(RPAREN,')',1,49)
-    LexToken(RPAREN,')',1,50)
-    >>> expression =  'H = tshift(test2 {during,:} buff_t(test1, "1 days"), "1 months")'
-    >>> p.test(expression)
-    H = tshift(test2 {during,:} buff_t(test1, "1 days"), "1 months")
-    LexToken(NAME,'H',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(TSHIFT,'tshift',1,4)
-    LexToken(LPAREN,'(',1,10)
-    LexToken(NAME,'test2',1,11)
-    LexToken(T_SELECT_OPERATOR,'{during,:}',1,17)
-    LexToken(BUFF_T,'buff_t',1,28)
-    LexToken(LPAREN,'(',1,34)
-    LexToken(NAME,'test1',1,35)
-    LexToken(COMMA,',',1,40)
-    LexToken(QUOTE,'"',1,42)
-    LexToken(INT,1,1,43)
-    LexToken(NAME,'days',1,45)
-    LexToken(QUOTE,'"',1,49)
-    LexToken(RPAREN,')',1,50)
-    LexToken(COMMA,',',1,51)
-    LexToken(QUOTE,'"',1,53)
-    LexToken(INT,1,1,54)
-    LexToken(NAME,'months',1,56)
-    LexToken(QUOTE,'"',1,62)
-    LexToken(RPAREN,')',1,63)
-    >>> expression =  'H = tshift(A , 10)'
-    >>> p.test(expression)
-    H = tshift(A , 10)
-    LexToken(NAME,'H',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(TSHIFT,'tshift',1,4)
-    LexToken(LPAREN,'(',1,10)
-    LexToken(NAME,'A',1,11)
-    LexToken(COMMA,',',1,13)
-    LexToken(INT,10,1,15)
-    LexToken(RPAREN,')',1,17)
-    >>> expression =  'H = if(td(A) > 10, A)'
-    >>> p.test(expression)
-    H = if(td(A) > 10, A)
-    LexToken(NAME,'H',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(IF,'if',1,4)
-    LexToken(LPAREN,'(',1,6)
-    LexToken(TD,'td',1,7)
-    LexToken(LPAREN,'(',1,9)
-    LexToken(NAME,'A',1,10)
-    LexToken(RPAREN,')',1,11)
-    LexToken(GREATER,'>',1,13)
-    LexToken(INT,10,1,15)
-    LexToken(COMMA,',',1,17)
-    LexToken(NAME,'A',1,19)
-    LexToken(RPAREN,')',1,20)
-    >>> expression =  'H = if(td(A) > 10, A, B)'
-    >>> p.test(expression)
-    H = if(td(A) > 10, A, B)
-    LexToken(NAME,'H',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(IF,'if',1,4)
-    LexToken(LPAREN,'(',1,6)
-    LexToken(TD,'td',1,7)
-    LexToken(LPAREN,'(',1,9)
-    LexToken(NAME,'A',1,10)
-    LexToken(RPAREN,')',1,11)
-    LexToken(GREATER,'>',1,13)
-    LexToken(INT,10,1,15)
-    LexToken(COMMA,',',1,17)
-    LexToken(NAME,'A',1,19)
-    LexToken(COMMA,',',1,20)
-    LexToken(NAME,'B',1,22)
-    LexToken(RPAREN,')',1,23)
-    >>> expression =  'I = if(equals,td(A) > 10 {equals,||} td(B) < 10, A)'
-    >>> p.test(expression)
-    I = if(equals,td(A) > 10 {equals,||} td(B) < 10, A)
-    LexToken(NAME,'I',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(IF,'if',1,4)
-    LexToken(LPAREN,'(',1,6)
-    LexToken(NAME,'equals',1,7)
-    LexToken(COMMA,',',1,13)
-    LexToken(TD,'td',1,14)
-    LexToken(LPAREN,'(',1,16)
-    LexToken(NAME,'A',1,17)
-    LexToken(RPAREN,')',1,18)
-    LexToken(GREATER,'>',1,20)
-    LexToken(INT,10,1,22)
-    LexToken(T_OVERLAY_OPERATOR,'{equals,||}',1,25)
-    LexToken(TD,'td',1,37)
-    LexToken(LPAREN,'(',1,39)
-    LexToken(NAME,'B',1,40)
-    LexToken(RPAREN,')',1,41)
-    LexToken(LOWER,'<',1,43)
-    LexToken(INT,10,1,45)
-    LexToken(COMMA,',',1,47)
-    LexToken(NAME,'A',1,49)
-    LexToken(RPAREN,')',1,50)
-    >>> expression =  'I = if(equals,td(A) > 10 || start_day() < 10, A)'
-    >>> p.test(expression)
-    I = if(equals,td(A) > 10 || start_day() < 10, A)
-    LexToken(NAME,'I',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(IF,'if',1,4)
-    LexToken(LPAREN,'(',1,6)
-    LexToken(NAME,'equals',1,7)
-    LexToken(COMMA,',',1,13)
-    LexToken(TD,'td',1,14)
-    LexToken(LPAREN,'(',1,16)
-    LexToken(NAME,'A',1,17)
-    LexToken(RPAREN,')',1,18)
-    LexToken(GREATER,'>',1,20)
-    LexToken(INT,10,1,22)
-    LexToken(OR,'|',1,25)
-    LexToken(OR,'|',1,26)
-    LexToken(START_DAY,'start_day',1,28)
-    LexToken(LPAREN,'(',1,37)
-    LexToken(RPAREN,')',1,38)
-    LexToken(LOWER,'<',1,40)
-    LexToken(INT,10,1,42)
-    LexToken(COMMA,',',1,44)
-    LexToken(NAME,'A',1,46)
-    LexToken(RPAREN,')',1,47)
-    >>> expression =  'E = if({equals},td(A) >= 4 {contain,&&} td(B) == 2, C : D)'
-    >>> p.test(expression)
-    E = if({equals},td(A) >= 4 {contain,&&} td(B) == 2, C : D)
-    LexToken(NAME,'E',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(IF,'if',1,4)
-    LexToken(LPAREN,'(',1,6)
-    LexToken(T_REL_OPERATOR,'{equals}',1,7)
-    LexToken(COMMA,',',1,15)
-    LexToken(TD,'td',1,16)
-    LexToken(LPAREN,'(',1,18)
-    LexToken(NAME,'A',1,19)
-    LexToken(RPAREN,')',1,20)
-    LexToken(GREATER_EQUALS,'>=',1,22)
-    LexToken(INT,4,1,25)
-    LexToken(T_OVERLAY_OPERATOR,'{contain,&&}',1,27)
-    LexToken(TD,'td',1,40)
-    LexToken(LPAREN,'(',1,42)
-    LexToken(NAME,'B',1,43)
-    LexToken(RPAREN,')',1,44)
-    LexToken(CEQUALS,'==',1,46)
-    LexToken(INT,2,1,49)
-    LexToken(COMMA,',',1,50)
-    LexToken(NAME,'C',1,52)
-    LexToken(T_SELECT,':',1,54)
-    LexToken(NAME,'D',1,56)
-    LexToken(RPAREN,')',1,57)
-    >>> expression =  'F = if({equals},A {equal,#}, B, C : D)'
-    >>> p.test(expression)
-    F = if({equals},A {equal,#}, B, C : D)
-    LexToken(NAME,'F',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(IF,'if',1,4)
-    LexToken(LPAREN,'(',1,6)
-    LexToken(T_REL_OPERATOR,'{equals}',1,7)
-    LexToken(COMMA,',',1,15)
-    LexToken(NAME,'A',1,16)
-    LexToken(T_HASH_OPERATOR,'{equal,#}',1,18)
-    LexToken(COMMA,',',1,27)
-    LexToken(NAME,'B',1,29)
-    LexToken(COMMA,',',1,30)
-    LexToken(NAME,'C',1,32)
-    LexToken(T_SELECT,':',1,34)
-    LexToken(NAME,'D',1,36)
-    LexToken(RPAREN,')',1,37)
     >>> expression =  'E = A : B ^ C : D'
     >>> p.test(expression)
     E = A : B ^ C : D
@@ -307,18 +28,6 @@
     LexToken(NAME,'C',1,12)
     LexToken(T_SELECT,':',1,14)
     LexToken(NAME,'D',1,16)
-    >>> expression =  'E = A : B {|^} C : D'
-    >>> p.test(expression)
-    E = A : B {|^} C : D
-    LexToken(NAME,'E',1,0)
-    LexToken(EQUALS,'=',1,2)
-    LexToken(NAME,'A',1,4)
-    LexToken(T_SELECT,':',1,6)
-    LexToken(NAME,'B',1,8)
-    LexToken(T_OVERLAY_OPERATOR,'{|^}',1,10)
-    LexToken(NAME,'C',1,15)
-    LexToken(T_SELECT,':',1,17)
-    LexToken(NAME,'D',1,19)
     >>> expression =  'E = buff_a(A, 10)'
     >>> p.test(expression)
     E = buff_a(A, 10)
@@ -330,100 +39,15 @@
     LexToken(COMMA,',',1,12)
     LexToken(INT,10,1,14)
     LexToken(RPAREN,')',1,16)
-    >>> p = tgis.TemporalVectorAlgebraParser()
-    >>> p.run = False
-    >>> p.debug = True
-    >>> expression =  "D = A : (B !: C)"
-    >>> p.parse(expression)
-    B* =  B !: C
-    A* =  A : B*
-    D = A*
-    >>> expression =  "D = A {!:} B {during,:} C"
-    >>> print(expression)
-    D = A {!:} B {during,:} C
-    >>> p.parse(expression)
-    A* =  A {!:} B
-    A** =  A* {during,:} C
-    D = A**
-    >>> expression =  "D = A {:} B {during,!:} C"
-    >>> print(expression)
-    D = A {:} B {during,!:} C
-    >>> p.parse(expression)
-    A* =  A {:} B
-    A** =  A* {during,!:} C
-    D = A**
-    >>> expression =  "D = A {:} (B {during,!:} (C : E))"
-    >>> print(expression)
-    D = A {:} (B {during,!:} (C : E))
-    >>> p.parse(expression)
-    C* =  C : E
-    B* =  B {during,!:} C*
-    A* =  A {:} B*
-    D = A*
-    >>> p.run = False
-    >>> p.debug = False
-    >>> expression =  "C = test1 : test2"
-    >>> print(expression)
-    C = test1 : test2
-    >>> p.parse(expression, 'stvds')
-    >>> expression =  'D = buff_t(test1,"10 months")'
-    >>> print(expression)
-    D = buff_t(test1,"10 months")
-    >>> p.parse(expression, 'stvds')
-    >>> expression =  'E = test2 {during,:} buff_t(test1,"1 days")'
-    >>> print(expression)
-    E = test2 {during,:} buff_t(test1,"1 days")
-    >>> p.parse(expression, 'stvds')
-    >>> expression =  'F = test2 {equal,:} buff_t(test1,"1 days")'
-    >>> print(expression)
-    F = test2 {equal,:} buff_t(test1,"1 days")
-    >>> p.parse(expression, 'stvds')
-    >>> p.debug = True
-    >>> expression =  'H = tsnap(test2 {during,:} buff_t(test1, "1 days"))'
-    >>> p.parse(expression, 'stvds')
-    test1* = buff_t( test1 , " 1 days " )
-    test2* =  test2 {during,:} test1*
-    test2** = tsnap( test2* )
-    H = test2**
-    >>> expression =  'H = tshift(test2 {during,:} test1, "1 days")'
-    >>> p.parse(expression, 'stvds')
-    test2* =  test2 {during,:} test1
-    test2** = tshift( test2* , " 1 days " )
-    H = test2**
-    >>> expression =  'H = tshift(H, 3)'
-    >>> p.parse(expression, 'stvds')
-    H* = tshift( H , 3 )
-    H = H*
-    >>> expression =  'C = if(td(A) == 2, A)'
-    >>> p.parse(expression, 'stvds')
-    td(A)
-    td(A) == 2
-    A* =  if condition True  then  A
-    C = A*
-    >>> expression =  'C = if(td(A) == 5 || start_date() >= "2010-01-01", A, B)'
-    >>> p.parse(expression, 'stvds')
-    td(A)
-    td(A) == 5
-    start_date >= "2010-01-01"
-    True || True
-    A* =  if condition True  then  A  else  B
-    C = A*
-    >>> expression =  'C = if(td(A) == 5, A, B)'
-    >>> p.parse(expression, 'stvds')
-    td(A)
-    td(A) == 5
-    A* =  if condition True  then  A  else  B
-    C = A*
 
 """
 
 import grass.pygrass.modules as pygrass
-from temporal_vector_operator import *
+from temporal_operator import *
 from temporal_algebra import *
 
 ##############################################################################
 
-
 class TemporalVectorAlgebraLexer(TemporalAlgebraLexer):
     """Lexical analyzer for the GRASS GIS temporal vector algebra"""
 
@@ -432,9 +56,9 @@
 
     # Buffer functions from v.buffer
     vector_buff_functions = {
-       'buff_p': 'BUFF_POINT',
-       'buff_l': 'BUFF_LINE',
-       'buff_a': 'BUFF_AREA',
+       'buff_p'  : 'BUFF_POINT',
+       'buff_l'   : 'BUFF_LINE',
+       'buff_a'   : 'BUFF_AREA',
        }
 
     # This is the list of token names.
@@ -446,14 +70,16 @@
     )
 
     # Build the token list
-    tokens = TemporalAlgebraLexer.tokens + vector_tokens \
-             + tuple(vector_buff_functions.values())
+    tokens = TemporalAlgebraLexer.tokens \
+                    + vector_tokens \
+                    + tuple(vector_buff_functions.values())
 
     # Regular expression rules for simple tokens
-    t_DISOR = r'\+'
-    t_XOR = r'\^'
-    t_NOT = r'\~'
-    t_T_OVERLAY_OPERATOR = r'\{([a-zA-Z\|]+[,])?([\|&+=]?[\|&+=\^\~])\}'
+    t_DISOR              = r'\+'
+    t_XOR                = r'\^'
+    t_NOT                = r'\~'
+    #t_T_OVERLAY_OPERATOR = r'\{([a-zA-Z\|]+[,])?([\|&+=]?[\|&+=\^\~])\}'
+    t_T_OVERLAY_OPERATOR = r'\{[\|&+\^\~][,]?[a-zA-Z\| ]*([,])?([lrudi]|left|right|union|disjoint|intersect)?\}'
 
     # Parse symbols
     def temporal_symbol(self, t):
@@ -472,7 +98,6 @@
 
 ##############################################################################
 
-
 class TemporalVectorAlgebraParser(TemporalAlgebraParser):
     """The temporal algebra class"""
 
@@ -481,21 +106,21 @@
 
     # Setting equal precedence level for select and hash operations.
     precedence = (
-        ('left', 'T_SELECT_OPERATOR', 'T_SELECT', 'T_NOT_SELECT'),  # 1
-        ('left', 'AND', 'OR', 'T_COMP_OPERATOR', 'T_OVERLAY_OPERATOR', 'DISOR',
-         'NOT', 'XOR'),  # 2
+        ('left', 'T_SELECT_OPERATOR', 'T_SELECT', 'T_NOT_SELECT'), # 1
+        ('left', 'AND', 'OR', 'T_COMP_OPERATOR', 'T_OVERLAY_OPERATOR', 'DISOR', \
+          'NOT', 'XOR'), #2
         )
 
-    def __init__(self, pid=None, run=False, debug=True, spatial=False):
+    def __init__(self, pid=None, run=False, debug=True, spatial = False):
         TemporalAlgebraParser.__init__(self, pid, run, debug, spatial)
 
         self.m_overlay = pygrass.Module('v.overlay', quiet=True, run_=False)
         self.m_rename = pygrass.Module('g.rename', quiet=True, run_=False)
         self.m_patch = pygrass.Module('v.patch', quiet=True, run_=False)
-        self.m_remove = pygrass.Module('g.remove', quiet=True, run_=False)
+        self.m_mremove = pygrass.Module('g.remove', quiet=True, run_=False)
         self.m_buffer = pygrass.Module('v.buffer', quiet=True, run_=False)
 
-    def parse(self, expression, basename=None, overwrite=False):
+    def parse(self, expression, basename = None, overwrite = False):
         self.lexer = TemporalVectorAlgebraLexer()
         self.lexer.build()
         self.parser = yacc.yacc(module=self, debug=self.debug)
@@ -503,6 +128,8 @@
         self.overwrite = overwrite
         self.count = 0
         self.stdstype = "stvds"
+        self.maptype = "vect"
+        self.mapclass = VectorDataset
         self.basename = basename
         self.expression = expression
         self.parser.parse(expression)
@@ -519,105 +146,207 @@
             for chunk in chunklist:
                 stringlist = ",".join(chunk)
                 if self.debug:
-                    print "g.remove type=vect name=%s" % (stringlist)
+                    print "g.remove type=vect name=%s"%(stringlist)
 
                 if self.run:
-                    m = copy.deepcopy(self.m_remove)
+                    m = copy.deepcopy(self.m_mremove)
                     m.inputs["type"].value = "vect"
                     m.inputs["name"].value = stringlist
                     m.flags["f"].value = True
                     m.run()
 
-    def eval_toperator(self, operator, comparison=False):
-        """This function evaluates a string containing temporal operations.
+    def get_temporal_topo_list(self, maplistA, maplistB = None, topolist = ["EQUAL"],
+                               assign_val = False, count_map = False, compare_bool = False,  
+                               compare_cmd = False,  compop = None, aggregate = None,  
+                               new = False,  convert = False,  overlay_cmd = False):
+        """Build temporal topology for two space time data sets, copy map objects
+          for given relation into map list.
+          :param maplistA List of maps.
+          :param maplistB List of maps.
+          :param topolist List of strings of temporal relations.
+          :param assign_val Boolean for assigning a boolean map value based on
+                            the map_values from the compared map list by
+                            topological relationships.
+          :param count_map Boolean if the number of topological related maps
+                           should be returned.
+          :param compare_bool Boolean for comparing boolean map values based on
+                            related map list and compariosn operator.
+          :param compare_cmd Boolean for comparing command list values based on
+                            related map list and compariosn operator.
+          :param compop Comparison operator, && or ||.
+          :param aggregate Aggregation operator for relation map list, & or |.
+          :param new Boolean if new temporary maps should be created.
+          :param convert Boolean if conditional values should be converted to 
+                        r.mapcalc command strings.
+          :param overlay_cmd Boolean for aggregate overlay operators implicitly 
+                        in command list values based on related map lists.
+                    
+          :return: List of maps from maplistA that fulfil the topological relationships
+                  to maplistB specified in topolist.
+        """
+        topologylist = ["EQUAL", "FOLLOWS", "PRECEDES", "OVERLAPS", "OVERLAPPED", \
+                        "DURING", "STARTS", "FINISHES", "CONTAINS", "STARTED", \
+                        "FINISHED"]
+        complementdict = {"EQUAL": "EQUAL", "FOLLOWS" : "PRECEDES",
+                          "PRECEDES" : "FOLLOWS", "OVERLAPS" : "OVERLAPPED",
+                          "OVERLAPPED" : "OVERLAPS", "DURING" : "CONTAINS",
+                          "CONTAINS" : "DURING", "STARTS" : "STARTED",
+                          "STARTED" : "STARTS", "FINISHES" : "FINISHED",
+                          "FINISHED" : "FINISHES"}
+        resultdict = {}
+        # Check if given temporal relation are valid.
+        for topo in topolist:
+          if topo.upper() not in topologylist:
+              raise SyntaxError("Unpermitted temporal relation name '" + topo + "'")
 
-          :param operator: String of temporal operations, e.g.
-                           {equal|during,=!:}.
+        # Create temporal topology for maplistA to maplistB.
+        tb = SpatioTemporalTopologyBuilder()
+        # Dictionary with different spatial variables used for topology builder.
+        spatialdict = {'strds' : '2D', 'stvds' : '2D', 'str3ds' : '3D'}
+        # Build spatial temporal topology
+        if self.spatial:
+            tb.build(maplistA, maplistB, spatial = spatialdict[self.stdstype])
+        else:
+            tb.build(maplistA, maplistB)
+        # Iterate through maps in maplistA and search for relationships given
+        # in topolist.
+        for map_i in maplistA:
+            tbrelations = map_i.get_temporal_relations()
+            # Check for boolean parameters for further calculations.
+            if assign_val:
+                self.assign_bool_value(map_i,  tbrelations,  topolist)
+            elif compare_bool:
+                self.compare_bool_value(map_i,  tbrelations, compop, aggregate, topolist)
+            elif compare_cmd:
+                self.compare_cmd_value(map_i,  tbrelations, compop, aggregate, topolist, convert)
+            elif overlay_cmd:
+                self.overlay_cmd_value(map_i,  tbrelations, compop, topolist)
+                
+            for topo in topolist:
+                if topo.upper() in tbrelations.keys():
+                    if count_map:
+                        relationmaplist = tbrelations[topo.upper()]
+                        gvar = GlobalTemporalVar()
+                        gvar.td = len(relationmaplist)
+                        if "map_value" in dir(map_i):
+                            map_i.map_value.append(gvar)
+                        else:
+                            map_i.map_value = gvar
+                    resultdict[map_i.get_id()] = map_i
+        resultlist = resultdict.values()
+        
+        # Sort list of maps chronological.
+        resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
+        
+        return(resultlist)
 
-          :return: List of temporal relations (equal, during), the given
-                   function (!:) and the interval/instances (=).
-
-          .. code-block:: python
-
-              >>> import grass.temporal as tgis
-              >>> tgis.init(True)
-              >>> p = tgis.TemporalVectorAlgebraParser()
-              >>> operator = "{equal,:}"
-              >>> p.eval_toperator(operator)
-              (['EQUAL'], '=', ':')
-              >>> operator = "{equal|during,:}"
-              >>> p.eval_toperator(operator)
-              (['EQUAL', 'DURING'], '=', ':')
-              >>> operator = "{equal,!:}"
-              >>> p.eval_toperator(operator)
-              (['EQUAL'], '=', '!:')
-              >>> operator = "{equal|during,!:}"
-              >>> p.eval_toperator(operator)
-              (['EQUAL', 'DURING'], '=', '!:')
-              >>> operator = "{equal|during,=!:}"
-              >>> p.eval_toperator(operator)
-              (['EQUAL', 'DURING'], '=', '!:')
-              >>> operator = "{equal|during|starts,#}"
-              >>> p.eval_toperator(operator)
-              (['EQUAL', 'DURING', 'STARTS'], '=', '#')
-              >>> operator = "{!:}"
-              >>> p.eval_toperator(operator)
-              (['EQUAL'], '=', '!:')
-              >>> operator = "{=:}"
-              >>> p.eval_toperator(operator)
-              (['EQUAL'], '=', ':')
-              >>> operator = "{#}"
-              >>> p.eval_toperator(operator)
-              (['EQUAL'], '=', '#')
-              >>> operator = "{equal|during}"
-              >>> p.eval_toperator(operator)
-              (['EQUAL', 'DURING'], None, None)
-              >>> operator = "{equal}"
-              >>> p.eval_toperator(operator)
-              (['EQUAL'], None, None)
-              >>> operator = "{equal,||}"
-              >>> p.eval_toperator(operator, True)
-              (['EQUAL'], '=', '||')
-              >>> operator = "{equal|during,&&}"
-              >>> p.eval_toperator(operator, True)
-              (['EQUAL', 'DURING'], '=', '&&')
-              >>> operator = "{&}"
-              >>> p.eval_toperator(operator)
-              (['EQUAL'], '=', '&')
-
+    def overlay_cmd_value(self,  map_i, tbrelations, function, topolist = ["EQUAL"]):
+        """ Function to evaluate two map lists by given overlay operator.
+          :param map_i Map object with temporal extent.
+          :param tbrelations List of temporal relation to map_i.
+          :param topolist List of strings for given temporal relations.
+          :param function Overlay operator, &|+^~.
+          
+          :return: Map object with command list with  operators that has been 
+                        evaluated by implicit aggregration.
         """
+        # Build comandlist list with elements from related maps and given relation operator.
+        resultlist = []
+        # Define overlay operation dictionary.
+        overlaydict = {"&":"and",  "|":"or",  "^":"xor",  "~":"not", "+":"disor"}
+        operator = overlaydict[function]
+        # Set first input for overlay module.
+        mapainput = map_i.get_id()
+        # Append command list of given map to result command list.
+        if "cmd_list" in dir(map_i):
+            resultlist = resultlist + map_i.cmd_list
+        for topo in topolist:
+            if topo.upper() in tbrelations.keys():
+                relationmaplist = tbrelations[topo.upper()]
+                for relationmap in relationmaplist:
+                    # Append command list of given map to result command list.
+                    if "cmd_list" in dir(relationmap):
+                        resultlist = resultlist + relationmap.cmd_list
+                    # Generate an intermediate name
+                    name = self.generate_map_name()
+                    map_i.set_id(name + "@" + self.mapset)
+                    # Set second input for overlay module.
+                    mapbinput = relationmap.get_id()
+                    # Create module command in PyGRASS for v.overlay and v.patch.
+                    if operator != "disor":
+                        m = copy.deepcopy(self.m_overlay)
+                        m.run_ = False
+                        m.inputs["operator"].value = operator
+                        m.inputs["ainput"].value = str(mapainput)
+                        m.inputs["binput"].value = str(mapbinput)
+                        m.outputs["output"].value = name
+                        m.flags["overwrite"].value = self.overwrite
+                    else:
+                        patchinput = str(mapainput) + ',' + str(mapbinput)
+                        m = copy.deepcopy(self.m_patch)
+                        m.run_ = False
+                        m.inputs["input"].value = patchinput
+                        m.outputs["output"].value = name
+                        m.flags["overwrite"].value = self.overwrite
+                    # Conditional append of module command.
+                    resultlist.append(m)
+                    # Set new map name to temporary map name.
+                    mapainput = name
+        # Add command list to result map.
+        map_i.cmd_list = resultlist
+        
+        return(resultlist)
 
-        p = TemporalVectorOperatorParser()
-        p.parse(operator, comparison)
-        p.relations = [rel.upper() for rel in p.relations]
+    def set_temporal_extent_list(self, maplist, topolist = ["EQUAL"], temporal = 'l' ):
+        """ Change temporal extent of map list based on temporal relations to 
+                other map list and given temporal operator.
 
-        return(p.relations, p.temporal, p.function)
+            :param maplist List of map objects for which relations has been build 
+                                        correctely.
+            :param topolist List of strings of temporal relations.
+            :param temporal The temporal operator specifying the temporal
+                                            extent operation (intersection, union, disjoint 
+                                            union, right reference, left reference).
 
-    def overlay_map_extent(self, mapA, mapB, bool_op=None, temp_op='=',
-                           copy=False):
-        """Compute the spatio-temporal extent of two topological related maps
-
-           :param mapA: The first map
-           :param mapB: The second maps
-           :param bool_op: The boolean operator specifying the spatial extent
-                  operation (intersection, union, disjoint union)
-           :param temp_op: The temporal operator specifying the temporal
-                  exntent operation (intersection, union, disjoint union)
-           :param copy: Specifies if the temporal extent of mapB should be
-                  copied to mapA
+            :return: Map list with specified temporal extent.
         """
-        returncode = TemporalAlgebraParser.overlay_map_extent(self, mapA, mapB,
-                                                              bool_op, temp_op,
-                                                              copy)
-        if not copy and returncode == 1:
-            # Conditional append of command list.
-            if "cmd_list" in dir(mapA) and "cmd_list" in dir(mapB):
-                mapA.cmd_list = mapA.cmd_list + mapB.cmd_list
-            elif "cmd_list" not in dir(mapA) and "cmd_list" in dir(mapB):
-                mapA.cmd_list = mapB.cmd_list
-
-        return(returncode)
-
+        resultdict = {}
+        
+        for map_i in maplist:
+            # Loop over temporal related maps and create overlay modules.
+            tbrelations = map_i.get_temporal_relations()
+            # Generate an intermediate map for the result map list.
+            map_new = self.generate_new_map(base_map=map_i, bool_op = 'and', 
+                                                                        copy = True,  rename = False)
+            # Combine temporal and spatial extents of intermediate map with related maps.
+            for topo in topolist:
+                if topo in tbrelations.keys():
+                    for map_j in (tbrelations[topo]):
+                        if temporal == 'r':
+                            # Generate an intermediate map for the result map list.
+                            map_new = self.generate_new_map(base_map=map_i, bool_op = 'and', 
+                                                                                        copy = True,  rename = False)
+                        # Create overlayed map extent.
+                        returncode = self.overlay_map_extent(map_new, map_j, 'and', \
+                                                                temp_op = temporal)
+                        # Stop the loop if no temporal or spatial relationship exist.
+                        if returncode == 0:
+                            break
+                        # Append map to result map list.
+                        elif returncode == 1:
+                            # resultlist.append(map_new)
+                            resultdict[map_new.get_id()] = map_new
+                    if returncode == 0:
+                        break
+            # Append map to result map list.
+            #if returncode == 1:
+            #    resultlist.append(map_new)
+        # Get sorted map objects as values from result dictionoary.
+        resultlist = resultdict.values()
+        resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
+        
+        return(resultlist)
+    
     ###########################################################################
 
     def p_statement_assign(self, t):
@@ -636,20 +365,18 @@
                 for i in range(num):
                     # Check if resultmap names exist in GRASS database.
                     vectorname = self.basename + "_" + str(i)
-                    vectormap = VectorDataset(vectorname + "@" +
-                                              get_current_mapset())
-                    if vectormap.map_exists() and self.overwrite is False:
-                        self.msgr.fatal(_("Error vector maps with basename %s"
-                                          " exist. Use --o flag to overwrite"
-                                          " existing file") % (vectorname))
+                    vectormap = VectorDataset(vectorname + "@" + get_current_mapset())
+                    if vectormap.map_exists() and self.overwrite == False:
+                        self.msgr.fatal(_("Error vector maps with basename %s exist. "
+                                      "Use --o flag to overwrite existing file") \
+                                      %(vectorname))
                 for map_i in t[3]:
                     if "cmd_list" in dir(map_i):
                         # Execute command list.
                         for cmd in map_i.cmd_list:
                             try:
-                                # We need to check if the input maps have
-                                # areas in case of v.overlay otherwise
-                                # v.overlay will break
+                                # We need to check if the input maps have areas in case of v.overlay
+                                # otherwise v.overlay will break
                                 if cmd.name == "v.overlay":
                                     for name in (cmd.inputs["ainput"].value,
                                                     cmd.inputs["binput"].value):
@@ -672,16 +399,14 @@
                             self.msgr.message("Run command:\n" + cmd.get_bash())
                             cmd.run()
                             if cmd.popen.returncode != 0:
-                                self.msgr.fatal(_("Error starting %s : \n%s")
-                                                % (cmd.get_bash(),
-                                                   cmd.popen.stderr))
+                                self.msgr.fatal(_("Error starting %s : \n%s") \
+                                                    %(cmd.get_bash(), \
+                                                    cmd.popen.stderr))
                             mapname = cmd.outputs['output'].value
                             if mapname.find("@") >= 0:
                                 map_test = map_i.get_new_instance(mapname)
                             else:
-                                map_test = map_i.get_new_instance(mapname +
-                                                                  "@" +
-                                                                  self.mapset)
+                                map_test = map_i.get_new_instance(mapname + "@" + self.mapset)
                             if not map_test.map_exists():
                                 returncode = 1
                                 break
@@ -693,8 +418,7 @@
                             # Change map name to given basename.
                             newident = self.basename + "_" + str(count)
                             m = copy.deepcopy(self.m_rename)
-                            m.inputs["vect"].value = (map_i.get_name(),
-                                                      newident)
+                            m.inputs["vect"].value = (map_i.get_name(),newident)
                             m.flags["overwrite"].value = self.overwrite
                             m.run()
                             #m(vect = (map_i.get_name(),newident), \
@@ -707,45 +431,41 @@
 
                 if len(register_list) > 0:
                     # Open connection to temporal database.
-                    dbif, connected = init_dbif(dbif=self.dbif)
+                    dbif, connect = init_dbif(dbif=self.dbif)
                     # Create result space time dataset.
-                    resultstds = open_new_stds(t[1], self.stdstype, 'absolute',
-                                               t[1], t[1],
-                                               "temporal vector algebra",
-                                               dbif=dbif,
-                                               overwrite=self.overwrite)
+                    resultstds = open_new_stds(t[1], self.stdstype, \
+                                                                'absolute', t[1], t[1], \
+                                                                "temporal vector algebra", self.dbif,
+                                                                overwrite = self.overwrite)
                     for map_i in register_list:
-                        # Check if modules should be executed from command list
+                        # Check if modules should be executed from command list.
                         if "cmd_list" in dir(map_i):
                             # Get meta data from grass database.
                             map_i.load()
                             if map_i.is_in_db(dbif=dbif) and self.overwrite:
                                 # Update map in temporal database.
                                 map_i.update_all(dbif=dbif)
-                            elif map_i.is_in_db(dbif=dbif) and self.overwrite is False:
-                                # Raise error if map exists and no overwrite
-                                # flag is given.
-                                self.msgr.fatal(_("Error vector map %s exist"
-                                                  " in temporal database. Use "
-                                                  "overwrite flag.  : \n%s") %
-                                                (map_i.get_map_id(),
-                                                 cmd.popen.stderr))
+                            elif map_i.is_in_db(dbif=dbif) and self.overwrite == False:
+                                # Raise error if map exists and no overwrite flag is given.
+                                self.msgr.fatal(_("Error vector map %s exist in temporal database. "
+                                                  "Use overwrite flag.  : \n%s") \
+                                                  %(map_i.get_map_id(), cmd.popen.stderr))
                             else:
                                 # Insert map into temporal database.
                                 map_i.insert(dbif=dbif)
                         else:
-                            # Get metadata from temporal database.
-                            map_i.select(dbif=dbif)
+                            #Get metadata from temporal database.                          
+                            #map_i.select(dbif=dbif)
+                            map_i.load()
                         # Register map in result space time dataset.
-                        resultstds.register_map(map_i, dbif=dbif)
+                        success = resultstds.register_map(map_i, dbif=dbif)
                         #count += 1
                         #if count % 10 == 0:
                         #    grass.percent(count, num, 1)
-                    resultstds.update_from_registered_maps(dbif=dbif)
-                    if connected:
-                        dbif.close()
+                    resultstds.update_from_registered_maps(dbif)
+                    dbif.close()
                 self.remove_intermediate_vector_maps()
-            t[0] = register_list
+            t[0] = t[3]
 
     def p_overlay_operation(self, t):
         """
@@ -770,16 +490,24 @@
              | stds DISOR expr
              | expr DISOR expr
         """
-        # Check input stds.
-        maplistA = self.check_stds(t[1])
-        maplistB = self.check_stds(t[3])
-
         if self.run:
-            t[0] = self.create_overlay_operations(maplistA, maplistB,
-                                                  ("EQUAL",), "=", t[2])
-        else:
-            t[0] = t[1]
+            # Check input stds and operator.
+            maplistA = self.check_stds(t[1])
+            maplistB = self.check_stds(t[3])
+            relations = ["EQUAL"]
+            temporal = 'l' 
+            function = t[2] 
+            # Build commmand list for related maps.
+            complist = self.get_temporal_topo_list(maplistA, maplistB, topolist = relations,
+                                                                    compop = function, overlay_cmd = True)
+            # Set temporal extent based on topological relationships.
+            resultlist = self.set_temporal_extent_list(complist, topolist = relations, 
+                                temporal = temporal)
 
+            t[0] = resultlist
+        if self.debug:
+            str(t[1]) + t[2] + str(t[3])
+
     def p_overlay_operation_relation(self, t):
         """
         expr : stds T_OVERLAY_OPERATOR stds
@@ -787,113 +515,24 @@
              | stds T_OVERLAY_OPERATOR expr
              | expr T_OVERLAY_OPERATOR expr
         """
-        # Check input stds.
-        maplistA = self.check_stds(t[1])
-        maplistB = self.check_stds(t[3])
-        relations, temporal, function = self.eval_toperator(t[2])
-
         if self.run:
-            t[0] = self.create_overlay_operations(maplistA, maplistB,
-                                                  relations, temporal,
-                                                  function)
-        else:
-            t[0] = t[1]
+            # Check input stds and operator.
+            maplistA = self.check_stds(t[1])
+            maplistB = self.check_stds(t[3])
+            relations, temporal, function,  aggregate = self.eval_toperator(t[2],  optype = 'overlay')
+            # Build commmand list for related maps.
+            complist = self.get_temporal_topo_list(maplistA, maplistB, topolist = relations,
+                                                                    compop = function, overlay_cmd = True)
+            # Set temporal extent based on topological relationships.
+            resultlist = self.set_temporal_extent_list(complist, topolist = relations, 
+                                temporal = temporal)
+          
+            t[0] = resultlist
+        if self.debug:
+            str(t[1]) + t[2] + str(t[3])
 
-    def create_overlay_operations(self, maplistA, maplistB, relations,
-                                  temporal, function):
-        """Create the spatial overlay operation commad list
-
-           :param maplistA: A list of map objects
-           :param maplistB: A list of map objects
-           :param relations: The temporal relationships that must be
-                             fullfilled as list of strings("EQUAL", "DURING",
-                             ...)
-           :param temporal: The temporal operator as string "=" or "&", ...
-           :param function: The spatial overlay operations as string "&", "|",
-                            ...
-           :return: Return the list of maps with overlay commands
+    def p_buffer_operation(self,t):
         """
-        topolist = self.get_temporal_topo_list(maplistA, maplistB,
-                                               topolist=relations)
-
-        # Select operation name.
-        if function == "&":
-            opname = "and"
-        elif function == "|":
-            opname = "or"
-        elif function == "^":
-            opname = "xor"
-        elif function == "~":
-            opname = "not"
-        elif function == "+":
-            opname = "disor"
-
-        if self.run:
-            resultlist = []
-            for map_i in topolist:
-                # Generate an intermediate name for the result map list.
-                map_new = self.generate_new_map(base_map=map_i, bool_op=opname,
-                                                copy=True)
-                # Set first input for overlay module.
-                mapainput = map_i.get_id()
-                # Loop over temporal related maps and create overlay modules.
-                tbrelations = map_i.get_temporal_relations()
-                count = 0
-                for topo in relations:
-                    if topo in tbrelations.keys():
-                        for map_j in (tbrelations[topo]):
-                            # Create overlayed map extent.
-                            returncode = self.overlay_map_extent(map_new,
-                                                                 map_j, opname,
-                                                                 temp_op=temporal)
-                            # Stop the loop if no temporal or spatial
-                            # relationship exist.
-                            if returncode == 0:
-                                break
-                            if count == 0:
-                                # Set map name.
-                                name = map_new.get_id()
-                            else:
-                                # Generate an intermediate name
-                                name = self.generate_map_name()
-                                map_new.set_id(name + "@" + mapset)
-                            # Set second input for overlay module.
-                            mapbinput = map_j.get_id()
-                            # Create module command in PyGRASS for v.overlay
-                            # and v.patch.
-                            if opname != "disor":
-                                m = copy.deepcopy(self.m_overlay)
-                                m.run_ = False
-                                m.inputs["operator"].value = opname
-                                m.inputs["ainput"].value = str(mapainput)
-                                m.inputs["binput"].value = str(mapbinput)
-                                m.outputs["output"].value = name
-                                m.flags["overwrite"].value = self.overwrite
-                            else:
-                                patchinput = str(mapainput) + ',' + str(mapbinput)
-                                m = copy.deepcopy(self.m_patch)
-                                m.run_ = False
-                                m.inputs["input"].value = patchinput
-                                m.outputs["output"].value = name
-                                m.flags["overwrite"].value = self.overwrite
-                            # Conditional append of module command.
-                            if "cmd_list" in dir(map_new):
-                                map_new.cmd_list.append(m)
-                            else:
-                                map_new.cmd_list = [m]
-                            # Set new map name to temporary map name.
-                            mapainput = name
-                            count += 1
-                        if returncode == 0:
-                            break
-                # Append map to result map list.
-                if returncode == 1:
-                    resultlist.append(map_new)
-
-            return resultlist
-
-    def p_buffer_operation(self, t):
-        """
         expr : buff_function LPAREN stds COMMA number RPAREN
              | buff_function LPAREN expr COMMA number RPAREN
         """
@@ -944,7 +583,7 @@
     # Handle errors.
     def p_error(self, t):
         raise SyntaxError("syntax error on line %d near '%s' expression '%s'" %
-                          (t.lineno, t.value, self.expression))
+            (t.lineno, t.value, self.expression))
 
 ###############################################################################
 

Deleted: grass/trunk/lib/python/temporal/temporal_vector_operator.py
===================================================================
--- grass/trunk/lib/python/temporal/temporal_vector_operator.py	2014-11-04 15:04:13 UTC (rev 62593)
+++ grass/trunk/lib/python/temporal/temporal_vector_operator.py	2014-11-04 15:45:52 UTC (rev 62594)
@@ -1,348 +0,0 @@
-"""
-Temporal vector operator evaluation with PLY
-
-(C) 2014 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.
-
-:authors: Thomas Leppelt and Soeren Gebbert
-
-.. code-block:: python
-
-    >>> import grass.temporal as tgis
-    >>> tgis.init(True)
-    >>> p = tgis.TemporalVectorOperatorParser()
-    >>> expression =  "{equal| during,&&}"
-    >>> p.parse(expression, True)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal', 'during'], '=', '&&')
-    >>> expression =  "{equal| during | follows,&&}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal', 'during', 'follows'], '&', '&')
-    >>> expression =  "{equal| during | follows,+!:}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal', 'during', 'follows'], '+', '!:')
-    >>> expression =  "{equal| during,!:}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal', 'during'], '=', '!:')
-    >>> expression =  "{!:}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal'], '=', '!:')
-    >>> expression =  "{&&}"
-    >>> p.parse(expression, True)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal'], '=', '&&')
-    >>> expression =  "{&&}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal'], '&', '&')
-    >>> expression =  "{|#}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal'], '|', '#')
-    >>> expression =  "{equal,||}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal'], '|', '|')
-    >>> expression =  "{equal|during,=!:}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal', 'during'], '=', '!:')
-    >>> expression =  "{equal|during|starts}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    (['equal', 'during', 'starts'], None, None)
-    >>> expression =  "{over| equal,||}"
-    >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
-    ([['overlaps', 'overlapped'], 'equal'], '|', '|')
-
-"""
-try:
-    import ply.lex as lex
-    import ply.yacc as yacc
-except:
-    pass
-
-
-class TemporalVectorOperatorLexer(object):
-    """Lexical analyzer for the GRASS GIS temporal vector operators"""
-
-    # Functions that defines topological relations.
-    relations = {
-        'equal': "EQUAL",
-        'follows': "FOLLOWS",
-        'precedes': "PRECEDES",
-        'overlaps': "OVERLAPS",
-        'overlapped': "OVERLAPPED",
-        'during': "DURING",
-        'starts': "STARTS",
-        'finishes': "FINISHES",
-        'contains': "CONTAINS",
-        'started': "STARTED",
-        'finished': "FINISHED",
-        'over': "OVER"
-        }
-
-    # This is the list of token names.
-    tokens = (
-        'COMMA',
-        'LEFTREF',
-        'HASH',
-        'OR',
-        'AND',
-        'DISOR',
-        'XOR',
-        'NOT',
-        'T_SELECT',
-        'T_NOT_SELECT',
-        'CLPAREN',
-        'CRPAREN',
-    )
-
-    # Build the token list
-    tokens = tokens + tuple(relations.values())
-
-    # Regular expression rules for simple tokens
-    t_T_SELECT = r':'
-    t_T_NOT_SELECT = r'!:'
-    t_COMMA = r','
-    t_LEFTREF = r'='
-    t_HASH = r'\#'
-    t_OR = r'[\|]'
-    t_AND = r'[&]'
-    t_DISOR = r'\+'
-    t_XOR = r'\^'
-    t_NOT = r'\~'
-    t_CLPAREN = r'\{'
-    t_CRPAREN = r'\}'
-
-    # These are the things that should be ignored.
-    t_ignore = ' \t'
-
-    # Track line numbers.
-    def t_newline(self, t):
-        r'\n+'
-        t.lineno += len(t.value)
-
-    def t_NAME(self, t):
-        r'[a-zA-Z_][a-zA-Z_0-9]*'
-        self.temporal_symbol(t)
-        return t
-
-    # Parse symbols
-    def temporal_symbol(self, t):
-        # Check for reserved words
-        if t.value in TemporalVectorOperatorLexer.relations.keys():
-            t.type = TemporalVectorOperatorLexer.relations.get(t.value)
-        #else:
-        #    t.type = 'NAME'
-        return(t)
-
-    # Handle errors.
-    def t_error(self, t):
-        raise SyntaxError("syntax error on line %d near '%s'" %
-                          (t.lineno, t.value))
-
-    # Build the lexer
-    def build(self, **kwargs):
-        self.lexer = lex.lex(module=self, **kwargs)
-
-    # Just for testing
-    def test(self, data):
-        self.name_list = {}
-        print(data)
-        self.lexer.input(data)
-        while True:
-            tok = self.lexer.token()
-            if not tok: break
-            print tok
-
-
-class TemporalVectorOperatorParser(object):
-    """The parser for the GRASS GIS temporal vector operators"""
-
-    def __init__(self):
-        self.lexer = TemporalVectorOperatorLexer()
-        self.lexer.build()
-        self.parser = yacc.yacc(module=self)
-
-    def parse(self, expression, comparison=False):
-        self.comparison = comparison
-        self.parser.parse(expression)
-
-    # Error rule for syntax errors.
-    def p_error(self, t):
-        raise SyntaxError("invalid syntax")
-
-    # Get the tokens from the lexer class
-    tokens = TemporalVectorOperatorLexer.tokens
-
-    def p_relation_only(self, t):
-        # The expression should always return a list of maps.
-        """
-        operator : CLPAREN relation CRPAREN
-                 | CLPAREN relationlist CRPAREN
-        """
-        # Set three operator components.
-        if isinstance(t[2], list):
-            self.relations = t[2]
-        else:
-            self.relations = [t[2]]
-        self.temporal = None
-        self.function = None
-
-        t[0] = t[2]
-
-    def p_operator(self, t):
-        # The expression should always return a list of maps.
-        """
-        operator : CLPAREN select CRPAREN
-                 | CLPAREN HASH CRPAREN
-                 | CLPAREN overlay CRPAREN
-        """
-        # Set three operator components.
-        self.relations = ['equal']
-        self.temporal = "="
-        self.function = t[2]
-
-        t[0] = t[2]
-
-    def p_operator_temporal(self, t):
-        # The expression should always return a list of maps.
-        """
-        operator : CLPAREN temporal select CRPAREN
-                 | CLPAREN temporal HASH CRPAREN
-                 | CLPAREN temporal overlay CRPAREN
-        """
-        # Set three operator components.
-        self.relations = ['equal']
-        if self.comparison:
-            self.temporal = "="
-            self.function = t[2] + t[3]
-        else:
-            self.temporal = t[2]
-            self.function = t[3]
-
-        t[0] = t[3]
-
-    def p_operator_relation(self, t):
-        # The expression should always return a list of maps.
-        """
-        operator : CLPAREN relation COMMA select CRPAREN
-                 | CLPAREN relationlist COMMA select CRPAREN
-                 | CLPAREN relation COMMA HASH CRPAREN
-                 | CLPAREN relationlist COMMA HASH CRPAREN
-                 | CLPAREN relation COMMA overlay CRPAREN
-                 | CLPAREN relationlist COMMA overlay CRPAREN
-        """
-        # Set three operator components.
-        if isinstance(t[2], list):
-            self.relations = t[2]
-        else:
-            self.relations = [t[2]]
-        self.temporal = "="
-        self.function = t[4]
-
-        t[0] = t[4]
-
-    def p_operator_relation_temporal(self, t):
-        # The expression should always return a list of maps.
-        """
-        operator : CLPAREN relation COMMA temporal select CRPAREN
-                 | CLPAREN relationlist COMMA temporal select CRPAREN
-                 | CLPAREN relation COMMA temporal HASH CRPAREN
-                 | CLPAREN relationlist COMMA temporal HASH CRPAREN
-                 | CLPAREN relation COMMA temporal overlay CRPAREN
-                 | CLPAREN relationlist COMMA temporal overlay CRPAREN
-        """
-        # Set three operator components.
-        if isinstance(t[2], list):
-            self.relations = t[2]
-        else:
-            self.relations = [t[2]]
-        if self.comparison:
-            self.temporal = "="
-            self.function = t[4] + t[5]
-        else:
-            self.temporal = t[4]
-            self.function = t[5]
-        t[0] = t[5]
-
-    def p_relation(self, t):
-        # The list of relations.
-        """
-        relation : EQUAL
-                 | FOLLOWS
-                 | PRECEDES
-                 | OVERLAPS
-                 | OVERLAPPED
-                 | DURING
-                 | STARTS
-                 | FINISHES
-                 | CONTAINS
-                 | STARTED
-                 | FINISHED
-        """
-        t[0] = t[1]
-
-    def p_over(self, t):
-        # The list of relations.
-        """
-        relation : OVER
-        """
-        over_list = ["overlaps", "overlapped"]
-        t[0] = over_list
-
-    def p_relationlist(self, t):
-        # The list of relations.
-        """
-        relationlist : relation OR relation
-                     | relation OR relationlist
-        """
-        rel_list = []
-        rel_list.append(t[1])
-        if isinstance(t[3], list):
-            rel_list = rel_list + t[3]
-        else:
-            rel_list.append(t[3])
-        t[0] = rel_list
-
-    def p_temporal_operator(self, t):
-        # The list of relations.
-        """
-        temporal : LEFTREF
-                 | OR
-                 | AND
-                 | DISOR
-        """
-        t[0] = t[1]
-
-    def p_select_operator(self, t):
-        # The list of relations.
-        """
-        select : T_SELECT
-               | T_NOT_SELECT
-        """
-        t[0] = t[1]
-
-    def p_overlay_operator(self, t):
-        # The list of relations.
-        """
-        overlay : OR
-                | AND
-                | DISOR
-                | XOR
-                | NOT
-        """
-        t[0] = t[1]
-###############################################################################
-
-if __name__ == "__main__":
-    import doctest
-    doctest.testmod()

Modified: grass/trunk/lib/python/temporal/testsuite/test_doctests.py
===================================================================
--- grass/trunk/lib/python/temporal/testsuite/test_doctests.py	2014-11-04 15:04:13 UTC (rev 62593)
+++ grass/trunk/lib/python/temporal/testsuite/test_doctests.py	2014-11-04 15:45:52 UTC (rev 62594)
@@ -42,10 +42,8 @@
     tests.addTests(doctest.DocTestSuite(grass.temporal.temporal_raster3d_algebra))
     tests.addTests(doctest.DocTestSuite(grass.temporal.temporal_raster_algebra))
     tests.addTests(doctest.DocTestSuite(grass.temporal.temporal_raster_base_algebra))
-    tests.addTests(doctest.DocTestSuite(grass.temporal.temporal_raster_operator))
-    # TODO: Fix tests
-    #tests.addTests(doctest.DocTestSuite(grass.temporal.temporal_vector_algebra))
-    tests.addTests(doctest.DocTestSuite(grass.temporal.temporal_vector_operator))
+    tests.addTests(doctest.DocTestSuite(grass.temporal.temporal_operator))
+    tests.addTests(doctest.DocTestSuite(grass.temporal.temporal_vector_algebra))
     return tests
 
 if __name__ == '__main__':

Modified: grass/trunk/lib/python/temporal/testsuite/test_register_function.py
===================================================================
--- grass/trunk/lib/python/temporal/testsuite/test_register_function.py	2014-11-04 15:04:13 UTC (rev 62593)
+++ grass/trunk/lib/python/temporal/testsuite/test_register_function.py	2014-11-04 15:45:52 UTC (rev 62594)
@@ -1,4 +1,4 @@
-"""!Unit test to register raster maps with absolute and relative
+"""Unit test to register raster maps with absolute and relative
    time using tgis.register_maps_in_space_time_dataset()
 
 (C) 2013 by the GRASS Development Team
@@ -6,7 +6,7 @@
 License (>=v2). Read the file COPYING that comes with GRASS
 for details.
 
- at author Soeren Gebbert
+:authors: Soeren Gebbert
 """
 
 import grass.temporal as tgis
@@ -14,12 +14,11 @@
 import datetime
 import os
 
-
 class TestRegisterFunctions(grass.gunittest.TestCase):
 
     @classmethod
     def setUpClass(cls):
-        """!Initiate the temporal GIS and set the region
+        """Initiate the temporal GIS and set the region
         """
         os.putenv("GRASS_OVERWRITE", "1")
         # Use always the current mapset as temporal database
@@ -31,12 +30,12 @@
 
     @classmethod
     def tearDownClass(cls):
-        """!Remove the temporary region
+        """Remove the temporary region
         """
         cls.del_temp_region()
 
     def setUp(self):
-        """!Create the test maps and the space time raster datasets
+        """Create the test maps and the space time raster datasets
         """
         self.runModule("r.mapcalc", overwrite=True, quiet=True,
                        expression="register_map_1 = 1")
@@ -49,7 +48,7 @@
                                             title="Test strds", descr="Test strds", semantic="field")
 
     def tearDown(self):
-        """!Remove maps from temporal database
+        """Remove maps from temporal database
         """
         self.runModule("t.unregister", maps="register_map_1,register_map_2", quiet=True)
         self.runModule("g.remove", flags='f', type="rast", name="register_map_1,register_map_2", quiet=True)
@@ -57,7 +56,7 @@
         self.strds_rel.delete()
 
     def test_absolute_time_strds_1(self):
-        """!Test the registration of maps with absolute time in a
+        """Test the registration of maps with absolute time in a
            space time raster dataset
         """
         tgis.register_maps_in_space_time_dataset(type="rast", name=self.strds_abs.get_name(),
@@ -82,7 +81,7 @@
         self.assertEqual(end, datetime.datetime(2001, 1, 3))
 
     def test_absolute_time_strds_2(self):
-        """!Test the registration of maps with absolute time in a
+        """Test the registration of maps with absolute time in a
            space time raster dataset.
            The timestamps are set using the C-Interface beforehand, so that the register function needs
            to read the timetsamp from the map metadata.
@@ -113,7 +112,7 @@
         self.assertEqual(end, datetime.datetime(2001, 1, 3))
 
     def test_absolute_time_1(self):
-        """!Test the registration of maps with absolute time
+        """Test the registration of maps with absolute time
         """
         tgis.register_maps_in_space_time_dataset(type="rast", name=None,
                  maps="register_map_1,register_map_2",
@@ -132,7 +131,7 @@
         self.assertEqual(end, datetime.datetime(2001, 1, 3))
 
     def test_absolute_time_2(self):
-        """!Test the registration of maps with absolute time
+        """Test the registration of maps with absolute time
         """
         tgis.register_maps_in_space_time_dataset(type="rast", name=None,
                  maps="register_map_1,register_map_2",
@@ -149,7 +148,7 @@
         self.assertEqual(start, datetime.datetime(2001, 1, 1, 18, 30, 1))
 
     def test_absolute_time_3(self):
-        """!Test the registration of maps with absolute time.
+        """Test the registration of maps with absolute time.
            The timestamps are set using the C-Interface beforehand, so that the register function needs
            to read the timetsamp from the map metadata.
         """
@@ -172,7 +171,7 @@
         self.assertEqual(start, datetime.datetime(2001, 1, 1, 18, 30, 1))
 
     def test_relative_time_strds_1(self):
-        """!Test the registration of maps with relative time in a
+        """Test the registration of maps with relative time in a
            space time raster dataset
         """
 
@@ -201,7 +200,7 @@
         self.assertEqual(unit, "day")
 
     def test_relative_time_strds_2(self):
-        """!Test the registration of maps with relative time in a
+        """Test the registration of maps with relative time in a
            space time raster dataset. The timetsamps are set for the maps using the
            C-interface before registration.
         """
@@ -233,7 +232,7 @@
         self.assertEqual(unit, "seconds")
 
     def test_relative_time_1(self):
-        """!Test the registration of maps with relative time
+        """Test the registration of maps with relative time
         """
         tgis.register_maps_in_space_time_dataset(type="rast", name=None,
                  maps="register_map_1,register_map_2",
@@ -254,7 +253,7 @@
         self.assertEqual(unit, "day")
 
     def test_relative_time_2(self):
-        """!Test the registration of maps with relative time
+        """Test the registration of maps with relative time
         """
         tgis.register_maps_in_space_time_dataset(type="rast", name=None,
                  maps="register_map_1,register_map_2",
@@ -275,7 +274,7 @@
         self.assertEqual(unit, "seconds")
 
     def test_relative_time_3(self):
-        """!Test the registration of maps with relative time. The timetsamps are set beforhand using
+        """Test the registration of maps with relative time. The timetsamps are set beforhand using
            the C-interface.
         """
         ciface = tgis.get_tgis_c_library_interface()

Deleted: grass/trunk/lib/python/temporal/testsuite/test_temporal_raster3d_algebra.py
===================================================================
--- grass/trunk/lib/python/temporal/testsuite/test_temporal_raster3d_algebra.py	2014-11-04 15:04:13 UTC (rev 62593)
+++ grass/trunk/lib/python/temporal/testsuite/test_temporal_raster3d_algebra.py	2014-11-04 15:45:52 UTC (rev 62594)
@@ -1,84 +0,0 @@
-"""!Unit test to register raster maps with absolute and relative
-   time using tgis.register_maps_in_space_time_dataset()
-
-(C) 2013 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.
-
- at author Soeren Gebbert
-"""
-
-import grass.script
-import grass.temporal as tgis
-import grass.gunittest as gunittest
-import datetime
-import os
-
-
-class TestRegisterFunctions(gunittest.TestCase):
-
-    @classmethod
-    def setUpClass(cls):
-        """!Initiate the temporal GIS and set the region
-        """
-        os.putenv("GRASS_OVERWRITE", "1")
-        tgis.init(True) # Raise on error instead of exit(1)
-        grass.script.use_temp_region()
-        ret = grass.script.run_command("g.region", n=80.0, s=0.0, e=120.0,
-                                       w=0.0, t=100.0, b=0.0, res=10.0)
-
-        ret += grass.script.run_command("r3.mapcalc", overwrite=True, quiet=True, expression="a1 = 1")
-        ret += grass.script.run_command("r3.mapcalc", overwrite=True, quiet=True, expression="a2 = 2")
-        ret += grass.script.run_command("r3.mapcalc", overwrite=True, quiet=True, expression="a3 = 3")
-        ret += grass.script.run_command("r3.mapcalc", overwrite=True, quiet=True, expression="a4 = 4")
-
-
-        tgis.open_new_stds(name="A", type="str3ds", temporaltype="absolute",
-                                         title="A", descr="A", semantic="field", overwrite=True)
-
-        tgis.register_maps_in_space_time_dataset(type="rast3d", name="A", maps="a1,a2,a3,a4",
-                                                 start="2001-01-01", increment="1 day", interval=True)
-
-    def test_temporal_neighbors_1(self):
-        """Simple temporal neighborhood computation test"""
-        tra = tgis.TemporalRaster3DAlgebraParser(run = True, debug = True)
-        tra.parse(expression='D = A[-1] + A[1]',
-                  basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="str3ds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 2)
-        self.assertEqual(D.metadata.get_min_min(), 4)  # 1 + 3
-        self.assertEqual(D.metadata.get_max_max(), 6) # 2 + 4
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 2))
-        self.assertEqual(end, datetime.datetime(2001, 1, 4))
-
-    def test_temporal_neighbors_2(self):
-        """Simple temporal neighborhood computation test"""
-        tra = tgis.TemporalRaster3DAlgebraParser(run = True, debug = True)
-        tra.parse(expression='D = A[0,0,0,-1] + A[0,0,0,1]',
-                  basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="str3ds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 2)
-        self.assertEqual(D.metadata.get_min_min(), 4)  # 1 + 3
-        self.assertEqual(D.metadata.get_max_max(), 6) # 2 + 4
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 2))
-        self.assertEqual(end, datetime.datetime(2001, 1, 4))
-
-    def tearDown(self):
-        ret = grass.script.run_command("t.remove", type="str3ds", flags="rf", input="D", quiet=True)
-
-    @classmethod
-    def tearDownClass(cls):
-        """!Remove the temporary region
-        """
-        ret = grass.script.run_command("t.remove", type="str3ds", flags="rf", input="A", quiet=True)
-        grass.script.del_temp_region()
-
-if __name__ == '__main__':
-    gunittest.test()

Deleted: grass/trunk/lib/python/temporal/testsuite/test_temporal_raster_algebra.py
===================================================================
--- grass/trunk/lib/python/temporal/testsuite/test_temporal_raster_algebra.py	2014-11-04 15:04:13 UTC (rev 62593)
+++ grass/trunk/lib/python/temporal/testsuite/test_temporal_raster_algebra.py	2014-11-04 15:45:52 UTC (rev 62594)
@@ -1,375 +0,0 @@
-"""!Unit test to register raster maps with absolute and relative
-   time using tgis.register_maps_in_space_time_dataset()
-
-(C) 2013 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.
-
- at author Soeren Gebbert
-"""
-
-import grass.script
-import grass.temporal as tgis
-import grass.gunittest as gunittest
-import datetime
-import os
-
-
-class TestRegisterFunctions(gunittest.TestCase):
-
-    @classmethod
-    def setUpClass(cls):
-        """!Initiate the temporal GIS and set the region
-        """
-        os.putenv("GRASS_OVERWRITE", "1")
-        tgis.init(True) # Raise on error instead of exit(1)
-        grass.script.use_temp_region()
-        ret = grass.script.run_command("g.region", n=80.0, s=0.0, e=120.0,
-                                       w=0.0, t=1.0, b=0.0, res=10.0)
-
-        ret += grass.script.run_command("r.mapcalc", overwrite=True, quiet=True, expression="a1 = 1")
-        ret += grass.script.run_command("r.mapcalc", overwrite=True, quiet=True, expression="a2 = 2")
-        ret += grass.script.run_command("r.mapcalc", overwrite=True, quiet=True, expression="a3 = 3")
-        ret += grass.script.run_command("r.mapcalc", overwrite=True, quiet=True, expression="a4 = 4")
-        ret += grass.script.run_command("r.mapcalc", overwrite=True, quiet=True, expression="b1 = 5")
-        ret += grass.script.run_command("r.mapcalc", overwrite=True, quiet=True, expression="b2 = 6")
-        ret += grass.script.run_command("r.mapcalc", overwrite=True, quiet=True, expression="c1 = 7")
-
-
-        tgis.open_new_stds(name="A", type="strds", temporaltype="absolute",
-                                         title="A", descr="A", semantic="field", overwrite=True)
-        tgis.open_new_stds(name="B", type="strds", temporaltype="absolute",
-                                         title="B", descr="B", semantic="field", overwrite=True)
-        tgis.open_new_stds(name="C", type="strds", temporaltype="absolute",
-                                         title="B", descr="C", semantic="field", overwrite=True)
-
-        tgis.register_maps_in_space_time_dataset(type="rast", name="A", maps="a1,a2,a3,a4",
-                                                 start="2001-01-01", increment="1 day", interval=True)
-        tgis.register_maps_in_space_time_dataset(type="rast", name="B", maps="b1,b2",
-                                                 start="2001-01-01", increment="2 day", interval=True)
-
-        tgis.register_maps_in_space_time_dataset(type="rast", name="C", maps="c1",
-                                                 start="2001-01-02", increment="2 day", interval=True)
-
-
-    def test_temporal_conditional_time_dimension_bug(self):
-        """Testing the conditional time dimension bug, that uses the time 
-            dimension of the conditional statement instead the time dimension 
-            of the then/else statement."""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression="D = if({contains}, B == 5,  A - 1,  A + 1)", basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 4)
-        self.assertEqual(D.metadata.get_min_min(), 0) # 1 - 1
-        self.assertEqual(D.metadata.get_max_max(), 5) # 4 + 1
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 1))
-        self.assertEqual(end, datetime.datetime(2001, 1, 5))
-        self.assertEqual( D.check_temporal_topology(),  True)
-        self.assertEqual(D.get_granularity(),  u'1 day')
-
-    def test_simple_arith_hash_1(self):
-        """Simple arithmetic test including the hash operator"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression='D = A + A{equal,=#}A', basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 4)
-        self.assertEqual(D.metadata.get_min_min(), 2)
-        self.assertEqual(D.metadata.get_max_max(), 5)
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 1))
-        self.assertEqual(end, datetime.datetime(2001, 1, 5))
-
-
-    def test_simple_arith_td_1(self):
-        """Simple arithmetic test"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression='D = A + td(A)', basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 4)
-        self.assertEqual(D.metadata.get_min_min(), 2)
-        self.assertEqual(D.metadata.get_max_max(), 5)
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 1))
-        self.assertEqual(end, datetime.datetime(2001, 1, 5))
-
-    def test_simple_arith_td_2(self):
-        """Simple arithmetic test"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression='D = A / td(A)', basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 4)
-        self.assertEqual(D.metadata.get_min_min(), 1)
-        self.assertEqual(D.metadata.get_max_max(), 4)
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 1))
-        self.assertEqual(end, datetime.datetime(2001, 1, 5))
-
-    def test_simple_arith_td_3(self):
-        """Simple arithmetic test"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression='D = A {equal,+} td(A)', basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 4)
-        self.assertEqual(D.metadata.get_min_min(), 2)
-        self.assertEqual(D.metadata.get_max_max(), 5)
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 1))
-        self.assertEqual(end, datetime.datetime(2001, 1, 5))
-
-
-    def test_simple_arith_td_4(self):
-        """Simple arithmetic test"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression='D = A {equal,/} td(A)', basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 4)
-        self.assertEqual(D.metadata.get_min_min(), 1)
-        self.assertEqual(D.metadata.get_max_max(), 4)
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 1))
-        self.assertEqual(end, datetime.datetime(2001, 1, 5))
-
-
-    def test_simple_arith_if_1(self):
-        """Simple arithmetic test with if condition"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression='D = if({equal}, start_date() >= "2001-01-02", A + A)', basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 3)
-        self.assertEqual(D.metadata.get_min_min(), 4)
-        self.assertEqual(D.metadata.get_max_max(), 8)
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 2))
-        self.assertEqual(end, datetime.datetime(2001, 1, 5))
-
-    def test_simple_arith_if_2(self):
-        """Simple arithmetic test with if condition"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression='D = if({equal}, A#A == 1, A - A)', basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 4)
-        self.assertEqual(D.metadata.get_min_min(), 0)
-        self.assertEqual(D.metadata.get_max_max(), 0)
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 1))
-        self.assertEqual(end, datetime.datetime(2001, 1, 5))
-
-    def test_complex_arith_if_1(self):
-        """Complex arithmetic test with if condition"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression='D = if(start_date() < "2001-01-03" && A#A == 1, A{starts,=+}C, A{finishes,=+}C)', \
-                  basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 2)
-        self.assertEqual(D.metadata.get_min_min(), 9)  # 2 + 7 a2 + c1
-        self.assertEqual(D.metadata.get_max_max(), 10) # 3 + 7 a3 + c1
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 2))
-        self.assertEqual(end, datetime.datetime(2001, 1, 4))
-
-    def test_simple_arith_1(self):
-        """Simple arithmetic test"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression="D = A {equal,*} A {equal,+} A", basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 4)
-        self.assertEqual(D.metadata.get_min_min(), 2)  # 1*1 + 1
-        self.assertEqual(D.metadata.get_max_max(), 20) # 4*4 + 4
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 1))
-        self.assertEqual(end, datetime.datetime(2001, 1, 5))
-
-    def test_simple_arith_2(self):
-        """Simple arithmetic test that creates an empty strds"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression="D = A {during,*} A {during,+} A", basename="d", overwrite=True)
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 0)
-
-    def test_simple_arith_3(self):
-        """Simple arithmetic test"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression="D = A / A + A*A/A", basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 4)
-        self.assertEqual(D.metadata.get_min_min(), 2) # 1/1 + 1*1/1
-        self.assertEqual(D.metadata.get_max_max(), 5) # 4/4 + 4*4/4
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 1))
-        self.assertEqual(end, datetime.datetime(2001, 1, 5))
-        
-    def test_temporal_intersection_1(self):
-        """Simple temporal intersection test"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression="D = A {equal,&+} B", basename="d", overwrite=True)
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 0)
-
-    def test_temporal_intersection_2(self):
-        """Simple temporal intersection test"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression="D = A {during,&+} B", basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 4)
-        self.assertEqual(D.metadata.get_min_min(), 6) # 1 + 5
-        self.assertEqual(D.metadata.get_max_max(), 10) # 4 + 6
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 1))
-        self.assertEqual(end, datetime.datetime(2001, 1, 5))
-
-    def test_temporal_intersection_3(self):
-        """Simple temporal intersection test"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression="D = A {starts,&+} B", basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 2)
-        self.assertEqual(D.metadata.get_min_min(), 6) # 1 + 5
-        self.assertEqual(D.metadata.get_max_max(), 9) # 3 + 6
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 1))
-        self.assertEqual(end, datetime.datetime(2001, 1, 4))
-
-    def test_temporal_intersection_4(self):
-        """Simple temporal intersection test"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression="D = A {finishes,&+} B", basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 2)
-        self.assertEqual(D.metadata.get_min_min(), 7)  # 2 + 5
-        self.assertEqual(D.metadata.get_max_max(), 10) # 4 + 6
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 2))
-        self.assertEqual(end, datetime.datetime(2001, 1, 5))
-
-    def test_temporal_intersection_5(self):
-        """Simple temporal intersection test"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression="D = A {starts|finishes,&+} B", basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 4)
-        self.assertEqual(D.metadata.get_min_min(), 6)  # 1 + 5
-        self.assertEqual(D.metadata.get_max_max(), 10) # 4 + 6
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 1))
-        self.assertEqual(end, datetime.datetime(2001, 1, 5))
-
-    def test_temporal_intersection_6(self):
-        """Simple temporal intersection test"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression="D = B {overlaps,|+} C", basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 1)
-        self.assertEqual(D.metadata.get_min_min(), 12) # 5 + 7
-        self.assertEqual(D.metadata.get_max_max(), 12) # 5 + 7
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 1))
-        self.assertEqual(end, datetime.datetime(2001, 1, 4))
-
-    def test_temporal_intersection_7(self):
-        """Simple temporal intersection test"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression="D = B {overlapped,|+} C", basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 1)
-        self.assertEqual(D.metadata.get_min_min(), 13) # 6 + 7
-        self.assertEqual(D.metadata.get_max_max(), 13) # 6 + 7
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 2))
-        self.assertEqual(end, datetime.datetime(2001, 1, 5))
-
-    def test_temporal_intersection_8(self):
-        """Simple temporal intersection test"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression='D = A {during,=+} buff_t(C, "1 day") ',
-                  basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 4)
-        self.assertEqual(D.metadata.get_min_min(), 8)  # 1 + 7  a1 + c1
-        self.assertEqual(D.metadata.get_max_max(), 11) # 4 + 7  a4 + c1
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 1))
-        self.assertEqual(end, datetime.datetime(2001, 1, 5))
-
-    def test_temporal_neighbors_1(self):
-        """Simple temporal neighborhood computation test"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression='D = A[-1] + A[1]',
-                  basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 2)
-        self.assertEqual(D.metadata.get_min_min(), 4)  # 1 + 3
-        self.assertEqual(D.metadata.get_max_max(), 6) # 2 + 4
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 2))
-        self.assertEqual(end, datetime.datetime(2001, 1, 4))
-
-    def test_temporal_neighbors_2(self):
-        """Simple temporal neighborhood computation test"""
-        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
-        tra.parse(expression='D = A[0,0,-1] + A[0,0,1]',
-                  basename="d", overwrite=True)
-
-        D = tgis.open_old_stds("D", type="strds")
-        D.select()
-        self.assertEqual(D.metadata.get_number_of_maps(), 2)
-        self.assertEqual(D.metadata.get_min_min(), 4)  # 1 + 3
-        self.assertEqual(D.metadata.get_max_max(), 6) # 2 + 4
-        start, end = D.get_absolute_time()
-        self.assertEqual(start, datetime.datetime(2001, 1, 2))
-        self.assertEqual(end, datetime.datetime(2001, 1, 4))
-
-    def tearDown(self):
-        ret = grass.script.run_command("t.remove", flags="rf", input="D", quiet=True)
-
-    @classmethod
-    def tearDownClass(cls):
-        """!Remove the temporary region
-        """
-        ret = grass.script.run_command("t.remove", flags="rf", input="A,B,C", quiet=True)
-        grass.script.del_temp_region()
-
-
-if __name__ == '__main__':
-    gunittest.test()

Added: grass/trunk/lib/python/temporal/testsuite/unittests_temporal_algebra.py
===================================================================
--- grass/trunk/lib/python/temporal/testsuite/unittests_temporal_algebra.py	                        (rev 0)
+++ grass/trunk/lib/python/temporal/testsuite/unittests_temporal_algebra.py	2014-11-04 15:45:52 UTC (rev 62594)
@@ -0,0 +1,352 @@
+"""
+(C) 2013 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.
+
+:authors: Soeren Gebbert and Thomas Leppelt
+"""
+
+import grass.script
+import grass.temporal as tgis
+import grass.gunittest
+import datetime
+import os
+
+class TestTemporalAlgebra(grass.gunittest.TestCase):
+
+    @classmethod
+    def setUpClass(cls):
+        """Initiate the temporal GIS and set the region
+        """
+        tgis.init(True) # Raise on error instead of exit(1)
+        cls.use_temp_region()
+        cls.runModule("g.region", n=80.0, s=0.0, e=120.0,
+                                       w=0.0, t=1.0, b=0.0, res=10.0)
+
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="a1 = 1")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="a2 = 2")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="a3 = 3")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="a4 = 4")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="b1 = 5")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="b2 = 6")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="c1 = 7")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="d1 = 8")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="d2 = 9")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="d3 = 10")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="singletmap = 99")
+
+
+        tgis.open_new_stds(name="A", type="strds", temporaltype="absolute",
+                                         title="A", descr="A", semantic="field", overwrite=True)
+        tgis.open_new_stds(name="B", type="strds", temporaltype="absolute",
+                                         title="B", descr="B", semantic="field", overwrite=True)
+        tgis.open_new_stds(name="C", type="strds", temporaltype="absolute",
+                                         title="C", descr="C", semantic="field", overwrite=True)
+        tgis.open_new_stds(name="D", type="strds", temporaltype="absolute",
+                                         title="D", descr="D", semantic="field", overwrite=True)
+
+        tgis.register_maps_in_space_time_dataset(type="rast", name="A", maps="a1,a2,a3,a4",
+                                                 start="2001-01-01", increment="1 day", interval=True)
+        tgis.register_maps_in_space_time_dataset(type="rast", name="B", maps="b1,b2",
+                                                 start="2001-01-01", increment="2 day", interval=True)
+        tgis.register_maps_in_space_time_dataset(type="rast", name="C", maps="c1",
+                                                 start="2001-01-02", increment="2 day", interval=True)
+        tgis.register_maps_in_space_time_dataset(type="rast", name="D", maps="d1,d2,d3",
+                                                 start="2001-01-03", increment="1 day", interval=True)
+        tgis.register_maps_in_space_time_dataset(type="rast", name=None,  maps="singletmap", 
+                                                start="2001-01-03", end="2001-01-04", interval=True)
+
+    def tearDown(self):
+        self.runModule("t.remove", inputs="R", quiet=True)
+
+    @classmethod
+    def tearDownClass(cls):
+        """Remove the temporary region
+        """
+        cls.runModule("t.remove", flags="rf", inputs="A,B,C,D", quiet=True)
+        cls.del_temp_region()
+
+    def test_temporal_select1(self):
+        """Testing the temporal select operator with equal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression="R = A : A", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 1) 
+        self.assertEqual(D.metadata.get_max_max(), 4) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_select2(self):
+        """Testing the temporal select operator with equal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression="R = A : D", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 3) 
+        self.assertEqual(D.metadata.get_max_max(), 4) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_select3(self):
+        """Testing the temporal select operator with equal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression="R = A !: D", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 1) 
+        self.assertEqual(D.metadata.get_max_max(), 2) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 3))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_select_operators1(self):
+        """Testing the temporal select operator. Including temporal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression="R = A {:,during} C", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 2) 
+        self.assertEqual(D.metadata.get_max_max(), 3) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_select_operators2(self):
+        """Testing the temporal select operator. Including temporal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression="R = A {:,equal|during} C", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 2) 
+        self.assertEqual(D.metadata.get_max_max(), 3) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_select_operators3(self):
+        """Testing the temporal select operator. Including temporal relations 
+            and negation operation. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression="R = A {!:,during} C", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 1) 
+        self.assertEqual(D.metadata.get_max_max(), 4) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_select_operators4(self):
+        """Testing the temporal select operator. Including temporal relations and 
+            temporal operators. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression="R = A {:,during,d} C", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        maplist = D.get_registered_maps_as_objects()
+        for map_i in maplist:
+            start_map, end_map = map_i.get_absolute_time()
+            self.assertEqual(start_map, datetime.datetime(2001, 1, 2))
+            self.assertEqual(end_map, datetime.datetime(2001, 1, 4))
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 2) 
+        self.assertEqual(D.metadata.get_max_max(), 3) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  False)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+
+    def test_temporal_select_operators5(self):
+        """Testing the temporal select operator. Including temporal relations and 
+            temporal operators. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression="R = C {:,contains} A", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        maplist = D.get_registered_maps_as_objects()
+        for map_i in maplist:
+            start_map, end_map = map_i.get_absolute_time()
+            self.assertEqual(start_map, datetime.datetime(2001, 1, 2))
+            self.assertEqual(end_map, datetime.datetime(2001, 1, 4))
+        self.assertEqual(D.metadata.get_number_of_maps(), 1)
+        self.assertEqual(D.metadata.get_min_min(), 7) 
+        self.assertEqual(D.metadata.get_max_max(), 7) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+
+    def test_temporal_extent1(self):
+        """Testing the temporal extent operators. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression="R = A {:,during,r} C", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        maplist = D.get_registered_maps_as_objects()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 2) 
+        self.assertEqual(D.metadata.get_max_max(), 3) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  False)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+
+    def test_temporal_extent2(self):
+        """Testing the temporal extent operators. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression="R = A {:,during,d} C", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        maplist = D.get_registered_maps_as_objects()    
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 2) 
+        self.assertEqual(D.metadata.get_max_max(), 3) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  False)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+
+    def test_temporal_extent3(self):
+        """Testing the temporal extent operators. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression="R = A {:,during,u} C", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        maplist = D.get_registered_maps_as_objects()
+        for map_i in maplist:
+            start_map, end_map = map_i.get_absolute_time()
+            self.assertEqual(start_map, datetime.datetime(2001, 1, 2))
+            self.assertEqual(end_map, datetime.datetime(2001, 1, 4))            
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 2) 
+        self.assertEqual(D.metadata.get_max_max(), 3) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  False)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+
+    def test_temporal_hash1(self):
+        """Testing the hash function in conditional statement. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression="R = if(A # D == 1, A)", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        maplist = D.get_registered_maps_as_objects()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 3) 
+        self.assertEqual(D.metadata.get_max_max(), 4) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_hash_operator1(self):
+        """Testing the hash operator function in conditional statement. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression="R = if(A {#,during} C == 1, A)", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        maplist = D.get_registered_maps_as_objects()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 2) 
+        self.assertEqual(D.metadata.get_max_max(), 3) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_hash_operator2(self):
+        """Testing the hash operator function in conditional statement. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression="R = if({during}, C {#,contains} A == 2, A)", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        maplist = D.get_registered_maps_as_objects()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 2) 
+        self.assertEqual(D.metadata.get_max_max(), 3) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+    
+    def test_tmap_function1(self):
+        """Testing the tmap function. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression='R = tmap(singletmap)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        maplist = D.get_registered_maps_as_objects()
+        self.assertEqual(D.metadata.get_number_of_maps(), 1)
+        self.assertEqual(D.metadata.get_min_min(), 99) 
+        self.assertEqual(D.metadata.get_max_max(), 99) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_tmap_function2(self):
+        """Testing the tmap function. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression='R = A : tmap(singletmap)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        maplist = D.get_registered_maps_as_objects()
+        self.assertEqual(D.metadata.get_number_of_maps(), 1)
+        self.assertEqual(D.metadata.get_min_min(), 3) 
+        self.assertEqual(D.metadata.get_max_max(), 3) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+if __name__ == '__main__':
+    grass.gunittest.test()

Added: grass/trunk/lib/python/temporal/testsuite/unittests_temporal_conditionals.py
===================================================================
--- grass/trunk/lib/python/temporal/testsuite/unittests_temporal_conditionals.py	                        (rev 0)
+++ grass/trunk/lib/python/temporal/testsuite/unittests_temporal_conditionals.py	2014-11-04 15:45:52 UTC (rev 62594)
@@ -0,0 +1,356 @@
+"""
+(C) 2014 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.
+
+:authors: Thomas leppelt and Soeren Gebbert
+"""
+
+import grass.script
+import grass.temporal as tgis
+import grass.gunittest
+import datetime
+import os
+
+class TestTemporalConditionals(grass.gunittest.TestCase):
+
+    @classmethod
+    def setUpClass(cls):
+        """Initiate the temporal GIS and set the region
+        """
+        tgis.init(True) # Raise on error instead of exit(1)
+        cls.use_temp_region()
+        cls.runModule("g.region", n=80.0, s=0.0, e=120.0,
+                                       w=0.0, t=1.0, b=0.0, res=10.0)
+
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="a1 = 1")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="a2 = 2")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="a3 = 3")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="a4 = 4")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="b1 = 5")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="b2 = 6")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="c1 = 7")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="d1 = 8")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="d2 = 9")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="d3 = 10")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="e1 = 11")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="e2 = 12")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="e3 = 13")
+        
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="singletmap = 99")
+
+        tgis.open_new_stds(name="A", type="strds", temporaltype="absolute",
+                                         title="A", descr="A", semantic="field", overwrite=True)
+        tgis.open_new_stds(name="B", type="strds", temporaltype="absolute",
+                                         title="B", descr="B", semantic="field", overwrite=True)
+        tgis.open_new_stds(name="C", type="strds", temporaltype="absolute",
+                                         title="C", descr="C", semantic="field", overwrite=True)
+        tgis.open_new_stds(name="D", type="strds", temporaltype="absolute",
+                                         title="D", descr="D", semantic="field", overwrite=True)
+        tgis.open_new_stds(name="E", type="strds", temporaltype="absolute",
+                                         title="E", descr="E", semantic="field", overwrite=True)
+                                         
+        tgis.register_maps_in_space_time_dataset(type="rast", name="A", maps="a1,a2,a3,a4",
+                                                 start="2001-01-01", increment="1 day", interval=True)
+        tgis.register_maps_in_space_time_dataset(type="rast", name="B", maps="b1,b2",
+                                                 start="2001-01-01", increment="2 day", interval=True)
+        tgis.register_maps_in_space_time_dataset(type="rast", name="C", maps="c1",
+                                                 start="2001-01-02", increment="2 day", interval=True)
+        tgis.register_maps_in_space_time_dataset(type="rast", name="D", maps="d1,d2,d3",
+                                                 start="2001-01-03", increment="1 day", interval=True)
+        tgis.register_maps_in_space_time_dataset(type="rast", name="E", maps="e1,e2,e3",
+                                                 start="2000-12-31", increment="2 day", interval=True)
+        tgis.register_maps_in_space_time_dataset(type="rast", name=None,  maps="singletmap", 
+                                                start="2001-01-03", end="2001-01-04", interval=True)
+
+    def tearDown(self):
+        self.runModule("t.remove", inputs="R", quiet=True)
+
+    @classmethod
+    def tearDownClass(cls):
+        """Remove the temporary region
+        """
+        cls.runModule("t.remove", flags="rf", inputs="A,B,C,D,E", quiet=True)
+        cls.del_temp_region()
+
+    def test_temporal_condition_1(self):
+        """Testing the temporal select operator with equal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression='R = if(start_date(A) >= "2001-01-03", A)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 3) 
+        self.assertEqual(D.metadata.get_max_max(), 4) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_condition_2(self):
+        """Testing the temporal select operator with equal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression='R = if(td(A) == 1, A)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 1) 
+        self.assertEqual(D.metadata.get_max_max(), 4) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+    
+    def test_temporal_condition_3(self):
+        """Testing the temporal select operator with equal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression='R = if(td(A) == 1 || start_date(A) >= "2001-01-03", A)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 1) 
+        self.assertEqual(D.metadata.get_max_max(), 4) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+    
+    def test_temporal_condition_4(self):
+        """Testing the temporal select operator with equal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression='R = if(start_date(A) >= "2001-01-03", A)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 3) 
+        self.assertEqual(D.metadata.get_max_max(), 4) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_condition_5(self):
+        """Testing the temporal select operator with equal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression='R = if(start_day(A) <= 2, A)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 1) 
+        self.assertEqual(D.metadata.get_max_max(), 2) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 3))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+    
+    def test_temporal_condition_6(self):
+        """Testing the temporal select operator with equal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression='R = if(td(A) == 1 {||,during} start_date(C) < "2001-01-02", A)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 2) 
+        self.assertEqual(D.metadata.get_max_max(), 3) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_condition_7(self):
+        """Testing the temporal select operator with equal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression='R = if({over},start_date(C) == "2001-01-02" {&&,contains} td(A) == 1, B)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 5) 
+        self.assertEqual(D.metadata.get_max_max(), 6) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+
+    def test_temporal_condition_8(self):
+        """Testing the temporal select operator with equal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression='R = if(start_date(B) <= "2001-01-01" {||,over,|} td(E) == 2, B)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 5) 
+        self.assertEqual(D.metadata.get_max_max(), 6) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+
+    def test_temporal_condition_9(self):
+        """Testing the temporal select operator with equal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression='R = if(start_date(B) <= "2001-01-01" {&&,over,&} td(E) == 2, B)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 1)
+        self.assertEqual(D.metadata.get_min_min(), 5) 
+        self.assertEqual(D.metadata.get_max_max(), 5) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 3))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+
+    def test_temporal_condition_10(self):
+        """Testing the temporal select operator with equal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression='R = if(start_date(B) <= "2001-01-01" {||,over,|,r} td(E) == 2, E)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 3)
+        self.assertEqual(D.metadata.get_min_min(), 11) 
+        self.assertEqual(D.metadata.get_max_max(), 13) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2000, 12, 31))
+        self.assertEqual(end, datetime.datetime(2001, 1, 6))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+ 
+    def test_temporal_condition_11(self):
+        """Testing the temporal select operator with equal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression='R = if(start_date(B) <= "2001-01-01" {&&,over,r} td(E) == 2, E)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 1)
+        self.assertEqual(D.metadata.get_min_min(), 11) 
+        self.assertEqual(D.metadata.get_max_max(), 11) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2000, 12, 31))
+        self.assertEqual(end, datetime.datetime(2001, 1, 2))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+
+    def test_temporal_condition_12(self):
+        """Testing the temporal select operator with equal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression='R = if(start_date(B) <= "2001-01-01" {&&,over,|,r} td(E) == 2, E)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 1)
+        self.assertEqual(D.metadata.get_min_min(), 11) 
+        self.assertEqual(D.metadata.get_max_max(), 11) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2000, 12, 31))
+        self.assertEqual(end, datetime.datetime(2001, 1, 2))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+    
+    def test_temporal_conditional_13(self):
+        """Testing the hash operator function in conditional statement. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression='R = if({equal|during},td(B) == 2 {&&,contains} td(A) == 1, A)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        maplist = D.get_registered_maps_as_objects()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 1) 
+        self.assertEqual(D.metadata.get_max_max(), 4) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+ 
+    def test_temporal_condition_else_1(self):
+        """Testing the temporal select operator with equal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression='R = if(start_date(A) <= "2001-01-03", A, D)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 1) 
+        self.assertEqual(D.metadata.get_max_max(), 9) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+    
+    def test_temporal_condition_else_2(self):
+        """Testing the temporal select operator with equal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression='R = if(td(D) == 1 && start_date(A) >= "2001-01-04", A, D)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 4) 
+        self.assertEqual(D.metadata.get_max_max(), 8) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_condition_else_3(self):
+        """Testing the temporal select operator with equal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression='R = if({during},td(B) == 2 {&&,contains} start_date(D) >= "2001-01-04", A, D)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 8) 
+        self.assertEqual(D.metadata.get_max_max(), 9) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_condition_else_4(self):
+        """Testing the temporal select operator with equal relations. """
+        ta = tgis.TemporalAlgebraParser(run = True, debug = True)
+        ta.parse(expression='R = if({equal|over},start_date(B) <= "2001-01-01" {&&,over,|,r} td(E) == 2, E, B)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        for map in D.get_registered_maps_as_objects():
+            print(map.get_map_id())
+        self.assertEqual(D.metadata.get_number_of_maps(), 3)
+        self.assertEqual(D.metadata.get_min_min(), 5) 
+        self.assertEqual(D.metadata.get_max_max(), 11) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2000, 12, 31))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  False)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+
+if __name__ == '__main__':
+    grass.gunittest.test()
+
+
+

Added: grass/trunk/lib/python/temporal/testsuite/unittests_temporal_raster3d_algebra.py
===================================================================
--- grass/trunk/lib/python/temporal/testsuite/unittests_temporal_raster3d_algebra.py	                        (rev 0)
+++ grass/trunk/lib/python/temporal/testsuite/unittests_temporal_raster3d_algebra.py	2014-11-04 15:45:52 UTC (rev 62594)
@@ -0,0 +1,83 @@
+"""
+(C) 2014 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.
+
+:authors: Soeren Gebbert and Thomas Leppelt
+"""
+
+
+import grass.script
+import grass.temporal as tgis
+import grass.gunittest as gunittest
+import datetime
+import os
+
+class TestTemporalRaster3dAlgebra(gunittest.TestCase):
+
+    @classmethod
+    def setUpClass(cls):
+        """Initiate the temporal GIS and set the region
+        """
+        tgis.init(True) # Raise on error instead of exit(1)
+        cls.use_temp_region()
+        ret = grass.script.run_command("g.region", n=80.0, s=0.0, e=120.0,
+                                       w=0.0, t=100.0, b=0.0, res=10.0)
+
+        cls.runModule("r3.mapcalc", overwrite=True, quiet=True, expression="a1 = 1")
+        cls.runModule("r3.mapcalc", overwrite=True, quiet=True, expression="a2 = 2")
+        cls.runModule("r3.mapcalc", overwrite=True, quiet=True, expression="a3 = 3")
+        cls.runModule("r3.mapcalc", overwrite=True, quiet=True, expression="a4 = 4")
+
+        tgis.open_new_stds(name="A", type="str3ds", temporaltype="absolute",
+                                         title="A", descr="A", semantic="field", overwrite=True)
+
+        tgis.register_maps_in_space_time_dataset(type="rast3d", name="A", maps="a1,a2,a3,a4",
+                                                 start="2001-01-01", increment="1 day", interval=True)
+
+    def tearDown(self):
+        self.runModule("t.remove", type="str3ds", flags="rf", inputs="D", quiet=True)
+
+    @classmethod
+    def tearDownClass(cls):
+        """Remove the temporary region
+        """
+        cls.runModule("t.remove", type="str3ds", flags="rf", inputs="A", quiet=True)
+        cls.del_temp_region()
+
+    def test_temporal_neighbors_1(self):
+        """Simple temporal neighborhood computation test"""
+        tra = tgis.TemporalRaster3DAlgebraParser(run = True, debug = True)
+        tra.parse(expression='D = A[-1] + A[1]',
+                  basename="d", overwrite=True)
+
+        D = tgis.open_old_stds("D", type="str3ds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 4)  # 1 + 3
+        self.assertEqual(D.metadata.get_max_max(), 6) # 2 + 4
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+
+    def test_temporal_neighbors_2(self):
+        """Simple temporal neighborhood computation test"""
+        tra = tgis.TemporalRaster3DAlgebraParser(run = True, debug = True)
+        tra.parse(expression='D = A[0,0,0,-1] + A[0,0,0,1]',
+                  basename="d", overwrite=True)
+
+        D = tgis.open_old_stds("D", type="str3ds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 4)  # 1 + 3
+        self.assertEqual(D.metadata.get_max_max(), 6) # 2 + 4
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+
+if __name__ == '__main__':
+    grass.gunittest.test()
+
+
+

Added: grass/trunk/lib/python/temporal/testsuite/unittests_temporal_raster_algebra.py
===================================================================
--- grass/trunk/lib/python/temporal/testsuite/unittests_temporal_raster_algebra.py	                        (rev 0)
+++ grass/trunk/lib/python/temporal/testsuite/unittests_temporal_raster_algebra.py	2014-11-04 15:45:52 UTC (rev 62594)
@@ -0,0 +1,696 @@
+"""Unit test to register raster maps with absolute and relative
+   time using tgis.register_maps_in_space_time_dataset()
+
+(C) 2013 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.
+
+ at author Soeren Gebbert
+"""
+
+import datetime
+import os
+import grass.script
+import grass.temporal as tgis
+import grass.gunittest as gunittest
+
+class TestTemporalRasterAlgebra(gunittest.TestCase):
+
+    @classmethod
+    def setUpClass(cls):
+        """Initiate the temporal GIS and set the region
+        """
+        tgis.init(True) # Raise on error instead of exit(1)
+        cls.use_temp_region()
+        cls.runModule("g.region", n=80.0, s=0.0, e=120.0,
+                                       w=0.0, t=1.0, b=0.0, res=10.0)
+
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="a1 = 1")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="a2 = 2")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="a3 = 3")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="a4 = 4")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="b1 = 5")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="b2 = 6")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="c1 = 7")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="d1 = 8")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="d2 = 9")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="d3 = 10")        
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="singletmap = 99")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="singlemap = 100")
+
+        tgis.open_new_stds(name="A", type="strds", temporaltype="absolute",
+                                         title="A", descr="A", semantic="field", overwrite=True)
+        tgis.open_new_stds(name="B", type="strds", temporaltype="absolute",
+                                         title="B", descr="B", semantic="field", overwrite=True)
+        tgis.open_new_stds(name="C", type="strds", temporaltype="absolute",
+                                         title="B", descr="C", semantic="field", overwrite=True)
+        tgis.open_new_stds(name="D", type="strds", temporaltype="absolute",
+                                         title="D", descr="D", semantic="field", overwrite=True)
+
+        tgis.register_maps_in_space_time_dataset(type="rast", name="A", maps="a1,a2,a3,a4",
+                                                 start="2001-01-01", increment="1 day", interval=True)
+        tgis.register_maps_in_space_time_dataset(type="rast", name="B", maps="b1,b2",
+                                                 start="2001-01-01", increment="2 day", interval=True)
+        tgis.register_maps_in_space_time_dataset(type="rast", name="C", maps="c1",
+                                                 start="2001-01-02", increment="2 day", interval=True)
+        tgis.register_maps_in_space_time_dataset(type="rast", name="D", maps="d1,d2,d3",
+                                                 start="2001-01-03", increment="1 day", interval=True)                                                 
+        tgis.register_maps_in_space_time_dataset(type="rast", name=None,  maps="singletmap", 
+                                                start="2001-01-03", end="2001-01-04", interval=True)
+        
+    def tearDown(self):
+        self.runModule("t.remove", flags="rf", inputs="R", quiet=True)
+
+    @classmethod
+    def tearDownClass(cls):
+        """Remove the temporary region 
+        """
+        cls.runModule("t.remove", flags="rf", inputs="A,B,C,D", quiet=True)
+        cls.runModule("t.unregister", maps="singletmap", quiet=True)
+        cls.del_temp_region()
+
+    def test_temporal_conditional_time_dimension_bug(self):
+        """Testing the conditional time dimension bug, that uses the time 
+            dimension of the conditional statement instead the time dimension 
+            of the then/else statement."""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = if({contains}, B == 5,  A - 1,  A + 1)", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 0) # 1 - 1
+        self.assertEqual(D.metadata.get_max_max(), 5) # 4 + 1
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_simple_arith_hash_1(self):
+        """Simple arithmetic test including the hash operator"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = A + A {#, equal,l} A', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 2)
+        self.assertEqual(D.metadata.get_max_max(), 5)
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+
+
+    def test_simple_arith_td_1(self):
+        """Simple arithmetic test"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = A + td(A)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 2)
+        self.assertEqual(D.metadata.get_max_max(), 5)
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+
+    def test_simple_arith_td_2(self):
+        """Simple arithmetic test"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = A / td(A)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 1)
+        self.assertEqual(D.metadata.get_max_max(), 4)
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+
+    def test_simple_arith_td_3(self):
+        """Simple arithmetic test"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = A {+,equal} td(A)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 2)
+        self.assertEqual(D.metadata.get_max_max(), 5)
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+
+
+    def test_simple_arith_td_4(self):
+        """Simple arithmetic test"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = A {/, equal} td(A)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 1)
+        self.assertEqual(D.metadata.get_max_max(), 4)
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+
+
+    def test_simple_arith_if_1(self):
+        """Simple arithmetic test with if condition"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if({equal}, start_date(A) >= "2001-01-02", A + A)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 3)
+        self.assertEqual(D.metadata.get_min_min(), 4)
+        self.assertEqual(D.metadata.get_max_max(), 8)
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+
+    def test_simple_arith_if_2(self):
+        """Simple arithmetic test with if condition"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if({equal}, A#A == 1, A - A)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 0)
+        self.assertEqual(D.metadata.get_max_max(), 0)
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+
+    def test_complex_arith_if_1(self):
+        """Complex arithmetic test with if condition"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if(start_date(A) < "2001-01-03" && A#A == 1, A{+, starts,l}C, A{+, finishes,l}C)', \
+                  basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 9)  # 2 + 7 a2 + c1
+        self.assertEqual(D.metadata.get_max_max(), 10) # 3 + 7 a3 + c1
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+
+    def test_simple_arith_1(self):
+        """Simple arithmetic test"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = A {*, equal} A {+, equal} A", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 2)  # 1*1 + 1
+        self.assertEqual(D.metadata.get_max_max(), 20) # 4*4 + 4
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+
+    def test_simple_arith_2(self):
+        """Simple arithmetic test that creates an empty strds"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = A {*, during} A {+, during} A", basename="r", overwrite=True)
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 0)
+
+    def test_simple_arith_3(self):
+        """Simple arithmetic test"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = A / A + A*A/A", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 2) # 1/1 + 1*1/1
+        self.assertEqual(D.metadata.get_max_max(), 5) # 4/4 + 4*4/4
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        
+    def test_temporal_intersection_1(self):
+        """Simple temporal intersection test"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = A {+,equal,i} B", basename="r", overwrite=True)
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 0)
+
+    def test_temporal_intersection_2(self):
+        """Simple temporal intersection test"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = A {+,during,i} B", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 6) # 1 + 5
+        self.assertEqual(D.metadata.get_max_max(), 10) # 4 + 6
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+
+    def test_temporal_intersection_3(self):
+        """Simple temporal intersection test"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = A {+,starts,i} B", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 6) # 1 + 5
+        self.assertEqual(D.metadata.get_max_max(), 9) # 3 + 6
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+
+    def test_temporal_intersection_4(self):
+        """Simple temporal intersection test"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = A {+,finishes,intersect} B", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 7)  # 2 + 5
+        self.assertEqual(D.metadata.get_max_max(), 10) # 4 + 6
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+
+    def test_temporal_intersection_5(self):
+        """Simple temporal intersection test"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = A {+,starts|finishes,i} B", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 6)  # 1 + 5
+        self.assertEqual(D.metadata.get_max_max(), 10) # 4 + 6
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+
+    def test_temporal_intersection_6(self):
+        """Simple temporal intersection test"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = B {+,overlaps,u} C", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 1)
+        self.assertEqual(D.metadata.get_min_min(), 12) # 5 + 7
+        self.assertEqual(D.metadata.get_max_max(), 12) # 5 + 7
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+
+    def test_temporal_intersection_7(self):
+        """Simple temporal intersection test"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = B {+,overlapped,u} C", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 1)
+        self.assertEqual(D.metadata.get_min_min(), 13) # 6 + 7
+        self.assertEqual(D.metadata.get_max_max(), 13) # 6 + 7
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+
+    def test_temporal_intersection_8(self):
+        """Simple temporal intersection test"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = A {+,during,l} buff_t(C, "1 day") ',
+                  basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 8)  # 1 + 7  a1 + c1
+        self.assertEqual(D.metadata.get_max_max(), 11) # 4 + 7  a4 + c1
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+
+    def test_temporal_neighbors_1(self):
+        """Simple temporal neighborhood computation test"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = A[-1] + A[1]',
+                  basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 4)  # 1 + 3
+        self.assertEqual(D.metadata.get_max_max(), 6) # 2 + 4
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+
+    def test_temporal_neighbors_2(self):
+        """Simple temporal neighborhood computation test"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = A[0,0,-1] + A[0,0,1]',
+                  basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 4)  # 1 + 3
+        self.assertEqual(D.metadata.get_max_max(), 6) # 2 + 4
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+
+    def test_tmap_function1(self):
+        """Testing the tmap function. """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = tmap(singletmap)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        maplist = D.get_registered_maps_as_objects()
+        self.assertEqual(D.metadata.get_number_of_maps(), 1)
+        self.assertEqual(D.metadata.get_min_min(), 99) 
+        self.assertEqual(D.metadata.get_max_max(), 99) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_tmap_function2(self):
+        """Testing the tmap function. """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = tmap(singletmap) + 1', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        maplist = D.get_registered_maps_as_objects()
+        self.assertEqual(D.metadata.get_number_of_maps(), 1)
+        self.assertEqual(D.metadata.get_min_min(), 100) 
+        self.assertEqual(D.metadata.get_max_max(), 100) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_map_function1(self):
+        """Testing the map function. """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = map(singlemap) + A', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        maplist = D.get_registered_maps_as_objects()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 101) 
+        self.assertEqual(D.metadata.get_max_max(), 104) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_map_function2(self):
+        """Testing the map function. """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R =  A * map(singlemap)', basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        maplist = D.get_registered_maps_as_objects()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 100) 
+        self.assertEqual(D.metadata.get_max_max(), 400) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_select(self):
+        """Testing the temporal select operator. """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = A : A", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 1) 
+        self.assertEqual(D.metadata.get_max_max(), 4) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_select(self):
+        """Testing the temporal select operator. """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = A : D", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 3) 
+        self.assertEqual(D.metadata.get_max_max(), 4) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_select_operators1(self):
+        """Testing the temporal select operator. Including temporal relations. """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = A : D", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 3) 
+        self.assertEqual(D.metadata.get_max_max(), 4) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_select_operators2(self):
+        """Testing the temporal select operator. Including temporal relations. """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = A {!:,during} C", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 1) 
+        self.assertEqual(D.metadata.get_max_max(), 4) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_select_operators3(self):
+        """Testing the temporal select operator. Including temporal relations and 
+            different temporal operators (lr|+&)"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = A {:,during,d} B", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_min_min(), 1) 
+        self.assertEqual(D.metadata.get_max_max(), 4) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  False)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+
+    def test_temporal_select_operators4(self):
+        """Testing the temporal select operator. Including temporal relations and 
+            different temporal operators (lr|+&)"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = A {:,equal|during,r} C", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        maplist = D.get_registered_maps_as_objects()
+        for map_i in maplist:
+            start_map, end_map = map_i.get_absolute_time()
+            self.assertEqual(start_map, datetime.datetime(2001, 1, 2))
+            self.assertEqual(end_map, datetime.datetime(2001, 1, 4))
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 2)
+        self.assertEqual(D.metadata.get_max_max(), 3)
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  False)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+
+    def test_temporal_hash_operator1(self):
+        """Testing the temporal hash operator in the raster algebra. """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = if(A # D == 1, A)", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 3) 
+        self.assertEqual(D.metadata.get_max_max(), 4) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_hash_operator2(self):
+        """Testing the temporal hash operator in the raster algebra. """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = A # D", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 1) 
+        self.assertEqual(D.metadata.get_max_max(), 1) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_hash_operator3(self):
+        """Testing the temporal hash operator in the raster algebra. """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = C {#,contains} A", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 1)
+        self.assertEqual(D.metadata.get_min_min(), 2) 
+        self.assertEqual(D.metadata.get_max_max(), 2) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+
+    def test_temporal_hash_operator4(self):
+        """Testing the temporal hash operator in the raster algebra. """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = if({contains},A # D == 1, C {#,contains} A)", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 1)
+        self.assertEqual(D.metadata.get_min_min(), 2) 
+        self.assertEqual(D.metadata.get_max_max(), 2) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+ 
+    def test_raster_arithmetic_relation_1(self):
+        """Arithmetic test with temporal intersection"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = B {+,contains,l} A ", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 8) 
+        self.assertEqual(D.metadata.get_max_max(), 13) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+
+    def test_raster_arithmetic_relation_2(self):
+        """Arithmetic test with temporal intersection"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = B {*,contains,l} A ", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 10) 
+        self.assertEqual(D.metadata.get_max_max(), 72) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+
+    def test_raster_arithmetic_relation_3(self):
+        """Arithmetic test with temporal intersection"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = B {+,contains,l} A ", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_min_min(), 8) 
+        self.assertEqual(D.metadata.get_max_max(), 13) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+    
+    def test_raster_arithmetic_relation_4(self):
+        """Arithmetic test with temporal intersection"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = B {+,contains,r} A ", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(),4)
+        self.assertEqual(D.metadata.get_min_min(), 8) 
+        self.assertEqual(D.metadata.get_max_max(), 13) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+    
+    def test_raster_arithmetic_relation_5(self):
+        """Complex arithmetic test with temporal intersection"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression="R = tmap(singletmap) {+,equal| precedes| follows,l} A + map(singlemap)", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="strds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(),1)
+        self.assertEqual(D.metadata.get_min_min(), 208) 
+        self.assertEqual(D.metadata.get_max_max(), 208)
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+if __name__ == '__main__':
+    gunittest.test()

Added: grass/trunk/lib/python/temporal/testsuite/unittests_temporal_raster_conditionals.py
===================================================================
--- grass/trunk/lib/python/temporal/testsuite/unittests_temporal_raster_conditionals.py	                        (rev 0)
+++ grass/trunk/lib/python/temporal/testsuite/unittests_temporal_raster_conditionals.py	2014-11-04 15:45:52 UTC (rev 62594)
@@ -0,0 +1,498 @@
+"""
+(C) 2014 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.
+
+:authors: Thomas Leppelt
+"""
+
+import datetime
+import os
+import grass.script
+import grass.temporal as tgis
+import grass.gunittest as gunittest
+
+class TestTemporalRasterAlgebraConditionals(gunittest.TestCase):
+
+    @classmethod
+    def setUpClass(cls):
+        """Initiate the temporal GIS and set the region
+        """
+        tgis.init(True) # Raise on error instead of exit(1)
+        cls.use_temp_region()
+        cls.runModule("g.region", n=80.0, s=0.0, e=120.0,
+                                       w=0.0, t=1.0, b=0.0, res=10.0)
+
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="a1 = 1")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="a2 = 2")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="a3 = 3")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="a4 = 4")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="b1 = 5")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="b2 = 6")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="c1 = 7")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="d1 = 8")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="d2 = 9")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="d3 = 10")
+        cls.runModule("r.mapcalc", overwrite=True, quiet=True, expression="d4 = 11")
+
+        tgis.open_new_stds(name="A", type="strds", temporaltype="absolute",
+                                         title="A", descr="A", semantic="field", overwrite=True)
+        tgis.open_new_stds(name="B", type="strds", temporaltype="absolute",
+                                         title="B", descr="B", semantic="field", overwrite=True)
+        tgis.open_new_stds(name="C", type="strds", temporaltype="absolute",
+                                         title="C", descr="C", semantic="field", overwrite=True)
+        tgis.open_new_stds(name="D", type="strds", temporaltype="absolute",
+                                         title="D", descr="D", semantic="field", overwrite=True)
+ 
+        tgis.register_maps_in_space_time_dataset(type="rast", name="A", maps="a1,a2,a3,a4",
+                                                 start="2001-01-01", increment="1 day", interval=True)
+        tgis.register_maps_in_space_time_dataset(type="rast", name="B", maps="b1,b2",
+                                                 start="2001-01-01", increment="2 day", interval=True)
+        tgis.register_maps_in_space_time_dataset(type="rast", name="C", maps="c1",
+                                                 start="2001-01-02", increment="2 day", interval=True)
+        tgis.register_maps_in_space_time_dataset(type="rast", name="D", maps="d1,d2,d3,d4",
+                                                 start="2001-01-03", increment="1 day", interval=True)
+        
+    def tearDown(self):
+        self.runModule("t.remove", flags="rf", inputs="R", quiet=True)
+
+    @classmethod
+    def tearDownClass(cls):
+        """Remove the temporary region
+        """
+        cls.runModule("t.remove", flags="rf", inputs="A,B,C,D", quiet=True)
+        cls.del_temp_region()
+
+    def test_temporal_conditional_time_dimension_bug(self):
+        """Testing the conditional time dimension bug, that uses the time 
+            dimension of the conditional statement instead the time dimension 
+            of the then/else statement."""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if({contains}, B == 5,  A - 1,  A + 1)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 4)
+        self.assertEqual(R.metadata.get_min_min(), 0) # 1 - 1
+        self.assertEqual(R.metadata.get_max_max(), 5) # 4 + 1
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+    def test_temporal_conditional_1(self):
+        """Testing the conditional time dimension bug, that uses the time 
+            dimension of the conditional statement instead the time dimension 
+            of the then/else statement."""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if(td(A) == 1,  D * 2, D)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 2)
+        self.assertEqual(R.metadata.get_min_min(), 16)
+        self.assertEqual(R.metadata.get_max_max(), 18)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1,  3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+    def test_temporal_conditional_relation_1(self):
+        """Testing the conditional time dimension bug, that uses the time 
+            dimension of the conditional statement instead the time dimension 
+            of the then/else statement."""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if({during},exist(A),  B - 1,  B + 1)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 4)
+        self.assertEqual(R.metadata.get_min_min(), 4)
+        self.assertEqual(R.metadata.get_max_max(), 5)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  False)
+        self.assertEqual(R.get_granularity(),  u'2 days')
+
+    def test_spatial_conditional_1(self):
+        """Testing the spatial conditionals combined by AND/OR operators. 
+            Evaluation  """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if(A > 1 && A < 4 && isntnull(A), A)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 4)
+        self.assertEqual(R.metadata.get_min_min(), 0)
+        self.assertEqual(R.metadata.get_max_max(), 3)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+    def test_spatial_conditional_2(self):
+        """Testing the spatial conditionals combined by AND/OR operators. 
+            Evaluation  """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if(A > 1 && A < 4 && isntnull(A), A, null())', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 2)
+        self.assertEqual(R.metadata.get_min_min(), 2)
+        self.assertEqual(R.metadata.get_max_max(), 3)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+    def test_spatial_conditional_3(self):
+        """Testing the spatial conditionals combined by AND/OR operators. 
+            Evaluation  """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if(A > 1, A, D)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 2)
+        self.assertEqual(R.metadata.get_min_min(), 3)
+        self.assertEqual(R.metadata.get_max_max(), 4)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+    def test_spatial_conditional_4(self):
+        """Testing the spatial conditionals combined by AND/OR operators. 
+            Evaluation  """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if(A > 0, A)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 4)
+        self.assertEqual(R.metadata.get_min_min(), 1)
+        self.assertEqual(R.metadata.get_max_max(), 4)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+    def test_spatial_conditional_5(self):
+        """Testing the spatial conditionals combined by AND/OR operators. 
+            Evaluation  """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if(B > 5 {&&,contains,l} A < 5, B)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 2)
+        self.assertEqual(R.metadata.get_min_min(), 0)
+        self.assertEqual(R.metadata.get_max_max(), 6)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'2 days')
+    
+    def test_spatial_conditional_relation_1(self):
+        """Testing the spatial conditionals combined by AND/OR operators. 
+            Evaluation  """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if({contains},B > 5, D)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 2)
+        self.assertEqual(R.metadata.get_min_min(), 8)
+        self.assertEqual(R.metadata.get_max_max(), 9)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+    def test_spatial_conditional_relation_2(self):
+        """Testing the spatial conditionals with numeric conclusions"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if({contains}, B <= 5, A, A * 2)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 4)
+        self.assertEqual(R.metadata.get_min_min(), 1)
+        self.assertEqual(R.metadata.get_max_max(), 8)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+    def test_spatial_conditional_numeric_relation_1(self):
+        """Testing the spatial conditionals with numeric conclusions"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if({contains}, B > 5, A, 10)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 4)
+        self.assertEqual(R.metadata.get_min_min(), 3)
+        self.assertEqual(R.metadata.get_max_max(), 10)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+    
+    def test_spatial_conditional_numeric_relation_2(self):
+        """Testing the spatial conditionals combined by AND/OR operators. 
+            Evaluation  """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if({contains},B > 5, A + 2 / 4.0)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 4)
+        self.assertEqual(R.metadata.get_min_min(), 0)
+        self.assertEqual(R.metadata.get_max_max(), 4.5)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+    
+    def test_spatial_conditional_numeric_1(self):
+        """Testing the spatial conditionals with numeric conclusions"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if(A > 2, 0, A)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 4)
+        self.assertEqual(R.metadata.get_min_min(), 0)
+        self.assertEqual(R.metadata.get_max_max(), 2)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+    def test_spatial_conditional_numeric_2(self):
+        """Testing the spatial conditionals with numeric conclusions"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if(A > 2, A, 8)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 4)
+        self.assertEqual(R.metadata.get_min_min(), 3)
+        self.assertEqual(R.metadata.get_max_max(), 8)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+    def test_spatial_conditional_numeric_3(self):
+        """Testing the spatial conditionals with numeric conclusions"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if(A > 2, 1, 0)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 4)
+        self.assertEqual(R.metadata.get_min_min(), 0)
+        self.assertEqual(R.metadata.get_max_max(), 1)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+    def test_spatial_conditional_numeric_4(self):
+        """Testing the spatial conditionals with numeric conclusions"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if(A > 2, null())', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 2)
+        self.assertEqual(R.metadata.get_min_min(), 0)
+        self.assertEqual(R.metadata.get_max_max(), 0)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 3))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+    def test_spatiotemporal_conditional_1(self):
+        """Testing the spatial conditionals with numeric conclusions"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if(A < 2 && start_date(A) < "2001-01-03", A)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 4)
+        self.assertEqual(R.metadata.get_min_min(), 0)
+        self.assertEqual(R.metadata.get_max_max(), 1)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+    def test_spatiotemporal_conditional_2(self):
+        """Testing the spatial conditionals with numeric conclusions"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if(A < 3 || start_date(A) < "2001-01-04", A + 1, A - 1)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 4)
+        self.assertEqual(R.metadata.get_min_min(),2)
+        self.assertEqual(R.metadata.get_max_max(),4)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+    def test_spatiotemporal_conditional_relation_1(self):
+        """Testing the spatial conditionals with numeric conclusions"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if({contains},B > 5 && start_day(B) < 3, D)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 2)
+        self.assertEqual(R.metadata.get_min_min(),0)
+        self.assertEqual(R.metadata.get_max_max(),0)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+    def test_spatiotemporal_conditional_relation_2(self):
+        """Testing the spatial conditionals with numeric conclusions"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if({contains}, start_date(B) < "2001-01-03" || B <= 5, A, A * 2)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 4)
+        self.assertEqual(R.metadata.get_min_min(), 1)
+        self.assertEqual(R.metadata.get_max_max(), 8)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+    def test_spatiotemporal_conditional_numeric_relation_1(self):
+        """Testing the spatial conditionals with numeric conclusions"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if({contains}, start_date(B) >= "2001-01-03" && B > 5, A, 10)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 4)
+        self.assertEqual(R.metadata.get_min_min(), 3)
+        self.assertEqual(R.metadata.get_max_max(), 10)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+    
+    def test_spatiotemporal_conditional_numeric_relation_2(self):
+        """Testing the spatial conditionals combined by AND/OR operators. 
+            Evaluation  """
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if({contains},td(B) == 2 && start_date(B) == "2001-01-03" && B > 5 , A + 2 / 4.0)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 4)
+        self.assertEqual(R.metadata.get_min_min(), 0)
+        self.assertEqual(R.metadata.get_max_max(), 4.5)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+ 
+    def test_spatiotemporal_conditional_numeric_1(self):
+        """Testing the spatial conditionals with numeric conclusions"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if(start_date(A) < "2001-01-04" && A > 2, 0, A)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 4)
+        self.assertEqual(R.metadata.get_min_min(), 0)
+        self.assertEqual(R.metadata.get_max_max(), 4)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+    def test_spatiotemporal_conditional_numeric_2(self):
+        """Testing the spatial conditionals with numeric conclusions"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if(A > 2 || start_date(A) > "2001-01-01" && start_date(A) < "2001-01-04", A, 8)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 4)
+        self.assertEqual(R.metadata.get_min_min(), 2)
+        self.assertEqual(R.metadata.get_max_max(), 8)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+    def test_spatiotemporal_conditional_numeric_3(self):
+        """Testing the spatial conditionals with numeric conclusions"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if(start_date(A) < "2001-01-04" && A > 2, 1, 0)', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 4)
+        self.assertEqual(R.metadata.get_min_min(), 0)
+        self.assertEqual(R.metadata.get_max_max(), 1)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+    def test_spatiotemporal_conditional_numeric_4(self):
+        """Testing the spatial conditionals with numeric conclusions"""
+        tra = tgis.TemporalRasterAlgebraParser(run = True, debug = True)
+        tra.parse(expression='R = if(A > 2 || start_date(A) > "2001-01-01", null())', basename="r", overwrite=True)
+
+        R = tgis.open_old_stds("R", type="strds")
+        R.select()
+        self.assertEqual(R.metadata.get_number_of_maps(), 1)
+        self.assertEqual(R.metadata.get_min_min(), 0)
+        self.assertEqual(R.metadata.get_max_max(), 0)
+        start, end = R.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 2))
+        self.assertEqual( R.check_temporal_topology(),  True)
+        self.assertEqual(R.get_granularity(),  u'1 day')
+
+if __name__ == '__main__':
+    gunittest.test()

Added: grass/trunk/lib/python/temporal/testsuite/unittests_temporal_vector_algebra.py
===================================================================
--- grass/trunk/lib/python/temporal/testsuite/unittests_temporal_vector_algebra.py	                        (rev 0)
+++ grass/trunk/lib/python/temporal/testsuite/unittests_temporal_vector_algebra.py	2014-11-04 15:45:52 UTC (rev 62594)
@@ -0,0 +1,193 @@
+"""
+(C) 2014 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.
+
+:authors: Soeren Gebbert and Thomas Leppelt
+"""
+
+import datetime
+import os
+import grass.script
+import grass.temporal as tgis
+import grass.gunittest as gunittest
+
+class TestTemporalVectorAlgebra(gunittest.TestCase):
+
+    @classmethod
+    def setUpClass(cls):
+        """Initiate the temporal GIS and set the region
+        """
+        tgis.init(True) # Raise on error instead of exit(1)
+        cls.use_temp_region()
+        cls.runModule("g.region", n=80.0, s=0.0, e=120.0,
+                                       w=0.0, t=1.0, b=0.0, res=10.0)
+
+        cls.runModule("v.random", overwrite=True, quiet=True, n=20, seed=1,  output='a1')
+        cls.runModule("v.random", overwrite=True, quiet=True, n=20, seed=1,  output='a2')
+        cls.runModule("v.random", overwrite=True, quiet=True, n=20, seed=1,  output='a3')
+        cls.runModule("v.random", overwrite=True, quiet=True, n=20, seed=1,  output='a4')
+        cls.runModule("v.random", overwrite=True, quiet=True, n=20, seed=2,  output='b1')
+        cls.runModule("v.random", overwrite=True, quiet=True, n=20, seed=2,  output='b2')
+        cls.runModule("v.random", overwrite=True, quiet=True, n=20, seed=3,  output='c1')
+        cls.runModule("v.random", overwrite=True, quiet=True, n=20, seed=4,  output='d1')
+        cls.runModule("v.random", overwrite=True, quiet=True, n=20, seed=4,  output='d2')
+        cls.runModule("v.random", overwrite=True, quiet=True, n=20, seed=4,  output='d3')
+        cls.runModule("v.random", overwrite=True, quiet=True, n=20, seed=5,  output='singletmap')
+        cls.runModule("v.random", overwrite=True, quiet=True, n=20, seed=6,  output='singlemap')        
+
+        tgis.open_new_stds(name="A", type="stvds", temporaltype="absolute",
+                                         title="A", descr="A", semantic="field", overwrite=True)
+        tgis.open_new_stds(name="B", type="stvds", temporaltype="absolute",
+                                         title="B", descr="B", semantic="field", overwrite=True)
+        tgis.open_new_stds(name="C", type="stvds", temporaltype="absolute",
+                                         title="B", descr="C", semantic="field", overwrite=True)
+        tgis.open_new_stds(name="D", type="stvds", temporaltype="absolute",
+                                         title="D", descr="D", semantic="field", overwrite=True)
+
+        tgis.register_maps_in_space_time_dataset(type="vect", name="A", maps="a1,a2,a3,a4",
+                                                 start="2001-01-01", increment="1 day", interval=True)
+        tgis.register_maps_in_space_time_dataset(type="vect", name="B", maps="b1,b2",
+                                                 start="2001-01-01", increment="2 day", interval=True)
+        tgis.register_maps_in_space_time_dataset(type="vect", name="C", maps="c1",
+                                                 start="2001-01-02", increment="2 day", interval=True)
+        tgis.register_maps_in_space_time_dataset(type="vect", name="D", maps="d1,d2,d3",
+                                                 start="2001-01-03", increment="1 day", interval=True)
+        tgis.register_maps_in_space_time_dataset(type="vect", name=None,  maps="singletmap", 
+                                                start="2001-01-03", end="2001-01-04", interval=True)
+    
+    def tearDown(self):
+        self.runModule("t.remove", type="stvds", inputs="R", quiet=True)
+
+    @classmethod
+    def tearDownClass(cls):
+        """Remove the temporary region 
+        """
+        cls.runModule("t.remove", flags="rf", inputs="A,B,C,D", type='stvds',  quiet=True)
+        cls.del_temp_region()
+
+    def test_temporal_select(self):
+        """Testing the temporal select operator. """
+        tva = tgis.TemporalVectorAlgebraParser(run = True, debug = True)
+        tva.parse(expression="R = A : A", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="stvds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_number_of_points(), 80) 
+        self.assertEqual(D.metadata.get_number_of_areas(), 0) 
+        self.assertEqual(D.metadata.get_number_of_centroids(), 0) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_select_operators(self):
+        """Testing the temporal select operator. Including temporal relations. """
+        tva = tgis.TemporalVectorAlgebraParser(run = True, debug = True)
+        tva.parse(expression="R = A {:,during} C", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="stvds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_number_of_points(), 40) 
+        self.assertEqual(D.metadata.get_number_of_areas(), 0) 
+        self.assertEqual(D.metadata.get_number_of_centroids(), 0) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_buff_operators_1(self):
+        """Testing the bufferoperator."""
+        tva = tgis.TemporalVectorAlgebraParser(run = True, debug = True)
+        tva.parse(expression="R = buff_p(A,0.5)", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="stvds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_number_of_points(), 0) 
+        self.assertEqual(D.metadata.get_number_of_areas(), 80) 
+        self.assertEqual(D.metadata.get_number_of_centroids(), 80) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_buff_operators_2(self):
+        """Testing the bufferoperator."""
+        tva = tgis.TemporalVectorAlgebraParser(run = True, debug = True)
+        tva.parse(expression="R = buff_a(buff_p(A,1),10)", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="stvds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_number_of_points(), 0) 
+        self.assertEqual(D.metadata.get_number_of_areas(), 20) 
+        self.assertEqual(D.metadata.get_number_of_centroids(), 20) 
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_overlay_operators_1(self):
+        """Testing the spatial overlay operator."""
+        tva = tgis.TemporalVectorAlgebraParser(run = True, debug = True)
+        tva.parse(expression="R = buff_p(A,2) & buff_p(D,2)", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="stvds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_number_of_points(), 0)
+        self.assertEqual(D.metadata.get_number_of_areas(), 6)
+        self.assertEqual(D.metadata.get_number_of_centroids(), 6)
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 3))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+    def test_temporal_overlay_operators_2(self):
+        """Testing the spatial overlay operator."""
+        tva = tgis.TemporalVectorAlgebraParser(run = True, debug = True)
+        tva.parse(expression="R = buff_p(A,1.5) {&,during,r} buff_p(B,1.5)", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="stvds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 4)
+        self.assertEqual(D.metadata.get_number_of_points(), 0)
+        self.assertEqual(D.metadata.get_number_of_areas(), 8)
+        self.assertEqual(D.metadata.get_number_of_centroids(), 8)
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 1))
+        self.assertEqual(end, datetime.datetime(2001, 1, 5))
+        self.assertEqual( D.check_temporal_topology(),  False)
+        self.assertEqual(D.get_granularity(),  u'2 days')
+
+    def test_temporal_overlay_operators_3(self):
+        """Testing the spatial overlay operator."""
+        tva = tgis.TemporalVectorAlgebraParser(run = True, debug = True)
+        tva.parse(expression="R = buff_p(A,2.5) {&,during,l} buff_p(C,2.5)", basename="r", overwrite=True)
+
+        D = tgis.open_old_stds("R", type="stvds")
+        D.select()
+        self.assertEqual(D.metadata.get_number_of_maps(), 2)
+        self.assertEqual(D.metadata.get_number_of_points(), 0)
+        self.assertEqual(D.metadata.get_number_of_areas(), 8)
+        self.assertEqual(D.metadata.get_number_of_centroids(), 8)
+        start, end = D.get_absolute_time()
+        self.assertEqual(start, datetime.datetime(2001, 1, 2))
+        self.assertEqual(end, datetime.datetime(2001, 1, 4))
+        self.assertEqual( D.check_temporal_topology(),  True)
+        self.assertEqual(D.get_granularity(),  u'1 day')
+
+if __name__ == '__main__':
+    gunittest.test()
+
+
+



More information about the grass-commit mailing list