File: space_time_datasets.py

package info (click to toggle)
grass 7.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 135,976 kB
  • ctags: 44,148
  • sloc: ansic: 410,300; python: 166,939; cpp: 34,819; sh: 9,358; makefile: 6,618; xml: 3,551; sql: 769; lex: 519; yacc: 450; asm: 387; perl: 282; sed: 17; objc: 7
file content (1252 lines) | stat: -rw-r--r-- 48,445 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
"""
Map layer and space time dataset classes

(C) 2012-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
"""
import getpass
from .abstract_map_dataset import *
from .abstract_space_time_dataset import *
import grass.script.array as garray

###############################################################################


class RasterDataset(AbstractMapDataset):
    """Raster dataset class

        This class provides functions to select, update, insert or delete raster
        map information and valid time stamps into the SQL temporal database.

        Usage:

        .. code-block:: python

            >>> import grass.script as grass
            >>> init()
            >>> grass.use_temp_region()
            >>> grass.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)
            0
            >>> grass.run_command("r.mapcalc", overwrite=True, quiet=True,
            ... expression="strds_map_test_case = 1")
            0
            >>> grass.run_command("r.timestamp", map="strds_map_test_case",
            ...                   date="15 jan 1999", quiet=True)
            0
            >>> mapset = get_current_mapset()
            >>> name = "strds_map_test_case"
            >>> identifier = "%s@%s" % (name, mapset)
            >>> rmap = RasterDataset(identifier)
            >>> rmap.map_exists()
            True
            >>> rmap.read_timestamp_from_grass()
            True
            >>> rmap.get_temporal_extent_as_tuple()
            (datetime.datetime(1999, 1, 15, 0, 0), None)
            >>> rmap.load()
            True
            >>> rmap.spatial_extent.print_info()
             +-------------------- Spatial extent ----------------------------------------+
             | North:...................... 80.0
             | South:...................... 0.0
             | East:.. .................... 120.0
             | West:....................... 0.0
             | Top:........................ 0.0
             | Bottom:..................... 0.0
            >>> rmap.absolute_time.print_info()
             +-------------------- Absolute time -----------------------------------------+
             | Start time:................. 1999-01-15 00:00:00
             | End time:................... None
            >>> rmap.metadata.print_info()
             +-------------------- Metadata information ----------------------------------+
             | Datatype:................... CELL
             | Number of columns:.......... 8
             | Number of rows:............. 12
             | Number of cells:............ 96
             | North-South resolution:..... 10.0
             | East-west resolution:....... 10.0
             | Minimum value:.............. 1.0
             | Maximum value:.............. 1.0

            >>> grass.run_command("r.timestamp", map="strds_map_test_case",
            ...                   date="2 years", quiet=True)
            0
            >>> rmap.read_timestamp_from_grass()
            True
            >>> rmap.get_temporal_extent_as_tuple()
            (2, None)
            >>> rmap.get_relative_time_unit()
            'years'

            >>> newmap = rmap.get_new_instance("new@PERMANENT")
            >>> isinstance(newmap, RasterDataset)
            True
            >>> newstrds = rmap.get_new_stds_instance("new@PERMANENT")
            >>> isinstance(newstrds, SpaceTimeRasterDataset)
            True
            >>> rmap.get_type()
            'raster'
            >>> rmap.set_absolute_time(start_time=datetime(2001,1,1),
            ...                        end_time=datetime(2012,1,1))
            True
            >>> rmap.get_absolute_time()
            (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2012, 1, 1, 0, 0))
            >>> rmap.get_temporal_extent_as_tuple()
            (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2012, 1, 1, 0, 0))
            >>> rmap.get_name()
            u'strds_map_test_case'
            >>> rmap.get_mapset() == mapset
            True
            >>> rmap.get_temporal_type()
            'absolute'
            >>> rmap.get_spatial_extent_as_tuple()
            (80.0, 0.0, 120.0, 0.0, 0.0, 0.0)
            >>> rmap.is_time_absolute()
            True
            >>> rmap.is_time_relative()
            False

            >>> grass.run_command("g.remove", flags="f", type="raster", name=name, quiet=True)
            0
            >>> grass.del_temp_region()

    """
    def __init__(self, ident):
        AbstractMapDataset.__init__(self)
        self.reset(ident)

    def is_stds(self):
        """Return True if this class is a space time dataset

           :return: True if this class is a space time dataset, False otherwise
        """
        return False

    def get_type(self):
        return 'raster'

    def get_new_instance(self, ident):
        """Return a new instance with the type of this class"""
        return RasterDataset(ident)

    def get_new_stds_instance(self, ident):
        """Return a new space time dataset instance in which maps
        are stored with the type of this class"""
        return SpaceTimeRasterDataset(ident)

    def spatial_overlapping(self, dataset):
        """Return True if the spatial extents 2d overlap"""
        return self.spatial_extent.overlapping_2d(dataset.spatial_extent)

    def spatial_relation(self, dataset):
        """Return the two dimensional spatial relation"""
        return self.spatial_extent.spatial_relation_2d(dataset.spatial_extent)

    def spatial_intersection(self, dataset):
        """Return the two dimensional intersection as spatial_extent
           object or None in case no intersection was found.

           :param dataset: The abstract dataset to intersect with
           :return: The intersection spatial extent or None
        """
        return self.spatial_extent.intersect_2d(dataset.spatial_extent)

    def spatial_union(self, dataset):
        """Return the two dimensional union as spatial_extent
           object or None in case the extents does not overlap or meet.

           :param dataset :The abstract dataset to create a union with
           :return: The union spatial extent or None
        """
        return self.spatial_extent.union_2d(dataset.spatial_extent)

    def spatial_disjoint_union(self, dataset):
        """Return the two dimensional union as spatial_extent object.

           :param dataset: The abstract dataset to create a union with
           :return: The union spatial extent
        """
        return self.spatial_extent.disjoint_union_2d(dataset.spatial_extent)

    def get_np_array(self):
        """Return this raster map as memmap numpy style array to access the raster
           values in numpy style without loading the whole map in the RAM.

           In case this raster map does exists in the grass spatial database,
           the map will be exported using r.out.bin to a temporary location
           and assigned to the memmap object that is returned by this function.

           In case the raster map does not exist, an empty temporary
           binary file will be created and assigned to the memap object.

           You need to call the write function to write the memmap
           array back into grass.
        """

        a = garray.array()

        if self.map_exists():
            a.read(self.get_map_id())

        return a

    def reset(self, ident):
        """Reset the internal structure and set the identifier"""
        self.base = RasterBase(ident=ident)
        self.absolute_time = RasterAbsoluteTime(ident=ident)
        self.relative_time = RasterRelativeTime(ident=ident)
        self.spatial_extent = RasterSpatialExtent(ident=ident)
        self.metadata = RasterMetadata(ident=ident)
        self.stds_register = RasterSTDSRegister(ident=ident)

    def has_grass_timestamp(self):
        """Check if a grass file bsased time stamp exists for this map.

           :return: True if success, False on error
        """
        return self.ciface.has_raster_timestamp(self.get_name(),
                                                self.get_mapset())

    def read_timestamp_from_grass(self):
        """Read the timestamp of this map from the map metadata
           in the grass file system based spatial database and
           set the internal time stamp that should be insert/updated
           in the temporal database.

           :return: True if success, False on error
        """

        if not self.has_grass_timestamp():
            return False

        check, dates = self.ciface.read_raster_timestamp(self.get_name(),
                                                         self.get_mapset(),)

        if check < 1:
            self.msgr.error(_("Unable to read timestamp file "
                              "for raster map <%s>" % (self.get_map_id())))
            return False

        if len(dates) == 2:
            self.set_absolute_time(dates[0], dates[1])
        else:
            self.set_relative_time(dates[0], dates[1], dates[2])

        return True

    def write_timestamp_to_grass(self):
        """Write the timestamp of this map into the map metadata in
           the grass file system based spatial database.

           Internally the libgis API functions are used for writing

           :return: True if success, False on error
        """
        check = self.ciface.write_raster_timestamp(self.get_name(),
                                                   self.get_mapset(),
                                                   self._convert_timestamp())

        if check == -1:
            self.msgr.error(_("Unable to create timestamp file "
                              "for raster map <%s>" % (self.get_map_id())))
            return False

        if check == -2:
            self.msgr.error(_("Invalid datetime in timestamp for raster map "
                              "<%s>" % (self.get_map_id())))
            return False

        if check == -3:
            self.msgr.error(_("Internal error"))
            return False

        return True

    def remove_timestamp_from_grass(self):
        """Remove the timestamp from the grass file system based
           spatial database

           Internally the libgis API functions are used for removal

           :return: True if success, False on error
        """
        check = self.ciface.remove_raster_timestamp(self.get_name(),
                                                    self.get_mapset())

        if check == -1:
            self.msgr.error(_("Unable to remove timestamp for raster map <%s>"
                            % (self.get_name())))
            return False

        return True

    def map_exists(self):
        """Return True in case the map exists in the grass spatial database

           :return: True if map exists, False otherwise
        """
        return self.ciface.raster_map_exists(self.get_name(),
                                             self.get_mapset())

    def load(self):
        """Load all info from an existing raster map into the internal structure

           This method checks first if the map exists, in case it exists
           the metadata of the map is put into this object and True is returned

           :return: True is the map exists and the metadata was filled
                    successfully and getting the data was successful,
                    False otherwise
        """

        if self.map_exists() is not True:
            return False

        # Fill base information
        self.base.set_creator(str(getpass.getuser()))

        kvp = self.ciface.read_raster_info(self.get_name(),
                                           self.get_mapset())

        if kvp:
            # Fill spatial extent
            self.set_spatial_extent_from_values(north=kvp["north"],
                                                south=kvp["south"],
                                                east=kvp["east"],
                                                west=kvp["west"])

            # Fill metadata
            self.metadata.set_nsres(kvp["nsres"])
            self.metadata.set_ewres(kvp["ewres"])
            self.metadata.set_datatype(kvp["datatype"])
            self.metadata.set_min(kvp["min"])
            self.metadata.set_max(kvp["max"])

            rows = int(kvp["rows"])
            cols = int(kvp["cols"])

            ncells = cols * rows

            self.metadata.set_cols(cols)
            self.metadata.set_rows(rows)
            self.metadata.set_number_of_cells(ncells)

            return True

        return False

###############################################################################


class Raster3DDataset(AbstractMapDataset):
    """Raster3d dataset class

        This class provides functions to select, update, insert or delete raster3d
        map information and valid time stamps into the SQL temporal database.

        Usage:

        .. code-block:: python

            >>> import grass.script as grass
            >>> init()
            >>> grass.use_temp_region()
            >>> grass.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, res3=10.0)
            0
            >>> grass.run_command("r3.mapcalc", overwrite=True, quiet=True,
            ...                   expression="str3ds_map_test_case = 1")
            0
            >>> grass.run_command("r3.timestamp", map="str3ds_map_test_case",
            ...                   date="15 jan 1999", quiet=True)
            0
            >>> mapset = get_current_mapset()
            >>> name = "str3ds_map_test_case"
            >>> identifier = "%s@%s" % (name, mapset)
            >>> r3map = Raster3DDataset(identifier)
            >>> r3map.map_exists()
            True
            >>> r3map.read_timestamp_from_grass()
            True
            >>> r3map.get_temporal_extent_as_tuple()
            (datetime.datetime(1999, 1, 15, 0, 0), None)
            >>> r3map.load()
            True
            >>> r3map.spatial_extent.print_info()
             +-------------------- Spatial extent ----------------------------------------+
             | North:...................... 80.0
             | South:...................... 0.0
             | East:.. .................... 120.0
             | West:....................... 0.0
             | Top:........................ 100.0
             | Bottom:..................... 0.0
            >>> r3map.absolute_time.print_info()
             +-------------------- Absolute time -----------------------------------------+
             | Start time:................. 1999-01-15 00:00:00
             | End time:................... None
            >>> r3map.metadata.print_info()
             +-------------------- Metadata information ----------------------------------+
             | Datatype:................... DCELL
             | Number of columns:.......... 8
             | Number of rows:............. 12
             | Number of cells:............ 960
             | North-South resolution:..... 10.0
             | East-west resolution:....... 10.0
             | Minimum value:.............. 1.0
             | Maximum value:.............. 1.0
             | Number of depths:........... 10
             | Top-Bottom resolution:...... 10.0

            >>> grass.run_command("r3.timestamp", map="str3ds_map_test_case",
            ...                   date="2 years", quiet=True)
            0
            >>> r3map.read_timestamp_from_grass()
            True
            >>> r3map.get_temporal_extent_as_tuple()
            (2, None)
            >>> r3map.get_relative_time_unit()
            'years'

            >>> newmap = r3map.get_new_instance("new@PERMANENT")
            >>> isinstance(newmap, Raster3DDataset)
            True
            >>> newstr3ds = r3map.get_new_stds_instance("new@PERMANENT")
            >>> isinstance(newstr3ds, SpaceTimeRaster3DDataset)
            True
            >>> r3map.get_type()
            'raster3d'
            >>> r3map.set_absolute_time(start_time=datetime(2001,1,1),
            ...                        end_time=datetime(2012,1,1))
            True
            >>> r3map.get_absolute_time()
            (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2012, 1, 1, 0, 0))
            >>> r3map.get_temporal_extent_as_tuple()
            (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2012, 1, 1, 0, 0))
            >>> r3map.get_name()
            u'str3ds_map_test_case'
            >>> r3map.get_mapset() == mapset
            True
            >>> r3map.get_temporal_type()
            'absolute'
            >>> r3map.get_spatial_extent_as_tuple()
            (80.0, 0.0, 120.0, 0.0, 100.0, 0.0)
            >>> r3map.is_time_absolute()
            True
            >>> r3map.is_time_relative()
            False
            >>> grass.run_command("g.remove", flags="f", type="raster_3d", name=name, quiet=True)
            0
            >>> grass.del_temp_region()

    """
    def __init__(self, ident):
        AbstractMapDataset.__init__(self)
        self.reset(ident)

    def is_stds(self):
        """Return True if this class is a space time dataset

           :return: True if this class is a space time dataset, False otherwise
        """
        return False

    def get_type(self):
        return "raster3d"

    def get_new_instance(self, ident):
        """Return a new instance with the type of this class"""
        return Raster3DDataset(ident)

    def get_new_stds_instance(self, ident):
        """Return a new space time dataset instance in which maps
        are stored with the type of this class"""
        return SpaceTimeRaster3DDataset(ident)

    def spatial_overlapping(self, dataset):
        """Return True if the spatial extents overlap"""
        if self.get_type() == dataset.get_type() or dataset.get_type() == "str3ds":
            return self.spatial_extent.overlapping(dataset.spatial_extent)
        else:
            return self.spatial_extent.overlapping_2d(dataset.spatial_extent)

    def spatial_relation(self, dataset):
        """Return the two or three dimensional spatial relation"""
        if self.get_type() == dataset.get_type() or dataset.get_type() == "str3ds":
            return self.spatial_extent.spatial_relation(dataset.spatial_extent)
        else:
            return self.spatial_extent.spatial_relation_2d(dataset.spatial_extent)

    def spatial_intersection(self, dataset):
        """Return the three or two dimensional intersection as spatial_extent
           object or None in case no intersection was found.

           :param dataset: The abstract dataset to intersect with
           :return: The intersection spatial extent or None
        """
        if self.get_type() == dataset.get_type() or dataset.get_type() == "str3ds":
            return self.spatial_extent.intersect(dataset.spatial_extent)
        else:
            return self.spatial_extent.intersect_2d(dataset.spatial_extent)

    def spatial_union(self, dataset):
        """Return the three or two dimensional union as spatial_extent
           object or None in case the extents does not overlap or meet.

           :param dataset: The abstract dataset to create a union with
           :return: The union spatial extent or None
        """
        if self.get_type() == dataset.get_type() or dataset.get_type() == "str3ds":
            return self.spatial_extent.union(dataset.spatial_extent)
        else:
            return self.spatial_extent.union_2d(dataset.spatial_extent)

    def spatial_disjoint_union(self, dataset):
        """Return the three or two dimensional union as spatial_extent object.

           :param dataset: The abstract dataset to create a union with
           :return: The union spatial extent
        """
        if self.get_type() == dataset.get_type() or dataset.get_type() == "str3ds":
            return self.spatial_extent.disjoint_union(dataset.spatial_extent)
        else:
            return self.spatial_extent.disjoint_union_2d(dataset.spatial_extent)

    def get_np_array(self):
        """Return this 3D raster map as memmap numpy style array to access the
           3D raster values in numpy style without loading the whole map in
           the RAM.

           In case this 3D raster map does exists in the grass spatial database,
           the map will be exported using r3.out.bin to a temporary location
           and assigned to the memmap object that is returned by this function.

           In case the 3D raster map does not exist, an empty temporary
           binary file will be created and assigned to the memap object.

           You need to call the write function to write the memmap
           array back into grass.
        """

        a = garray.array3d()

        if self.map_exists():
            a.read(self.get_map_id())

        return a

    def reset(self, ident):
        """Reset the internal structure and set the identifier"""
        self.base = Raster3DBase(ident=ident)
        self.absolute_time = Raster3DAbsoluteTime(ident=ident)
        self.relative_time = Raster3DRelativeTime(ident=ident)
        self.spatial_extent = Raster3DSpatialExtent(ident=ident)
        self.metadata = Raster3DMetadata(ident=ident)
        self.stds_register = Raster3DSTDSRegister(ident=ident)

    def has_grass_timestamp(self):
        """Check if a grass file bsased time stamp exists for this map.

           :return: True if success, False on error
        """
        return self.ciface.has_raster3d_timestamp(self.get_name(),
                                                  self.get_mapset())

    def read_timestamp_from_grass(self):
        """Read the timestamp of this map from the map metadata
           in the grass file system based spatial database and
           set the internal time stamp that should be insert/updated
           in the temporal database.

           :return: True if success, False on error
        """

        if not self.has_grass_timestamp():
            return False

        check, dates = self.ciface.read_raster3d_timestamp(self.get_name(),
                                                           self.get_mapset(),)

        if check < 1:
            self.msgr.error(_("Unable to read timestamp file "
                              "for 3D raster map <%s>" % (self.get_map_id())))
            return False

        if len(dates) == 2:
            self.set_absolute_time(dates[0], dates[1])
        else:
            self.set_relative_time(dates[0], dates[1], dates[2])

        return True

    def write_timestamp_to_grass(self):
        """Write the timestamp of this map into the map metadata
        in the grass file system based spatial database.

           Internally the libgis API functions are used for writing

           :return: True if success, False on error
        """
        check = self.ciface.write_raster3d_timestamp(self.get_name(),
                                                     self.get_mapset(),
                                                     self._convert_timestamp())

        if check == -1:
            self.msgr.error(_("Unable to create timestamp file "
                              "for 3D raster map <%s>" % (self.get_map_id())))
            return False

        if check == -2:
            self.msgr.error(_("Invalid datetime in timestamp for 3D raster "
                              "map <%s>" % (self.get_map_id())))
            return False

        if check == -3:
            self.msgr.error(_("Internal error"))
            return False

        return True

    def remove_timestamp_from_grass(self):
        """Remove the timestamp from the grass file system based spatial database

           :return: True if success, False on error
        """
        check = self.ciface.remove_raster3d_timestamp(self.get_name(),
                                                      self.get_mapset())

        if check == -1:
            self.msgr.error(_("Unable to remove timestamp for raster map "
                              "<%s>" % (self.get_name())))
            return False

        return True

    def map_exists(self):
        """Return True in case the map exists in the grass spatial database

           :return: True if map exists, False otherwise
        """
        return self.ciface.raster3d_map_exists(self.get_name(),
                                               self.get_mapset())

    def load(self):
        """Load all info from an existing 3d raster map into the internal structure

           This method checks first if the map exists, in case it exists
           the metadata of the map is put into this object and True is returned

           :return: True is the map exists and the metadata was filled
                    successfully and getting the data was successful,
                    False otherwise
        """

        if self.map_exists() is not True:
            return False

        # Fill base information
        self.base.set_creator(str(getpass.getuser()))

        # Fill spatial extent
        kvp = self.ciface.read_raster3d_info(self.get_name(),
                                             self.get_mapset())

        if kvp:
            self.set_spatial_extent_from_values(north=kvp["north"],
                                                south=kvp["south"],
                                                east=kvp["east"],
                                                west=kvp["west"],
                                                top=kvp["top"],
                                                bottom=kvp["bottom"])

            # Fill metadata
            self.metadata.set_nsres(kvp["nsres"])
            self.metadata.set_ewres(kvp["ewres"])
            self.metadata.set_tbres(kvp["tbres"])
            self.metadata.set_datatype(kvp["datatype"])
            self.metadata.set_min(kvp["min"])
            self.metadata.set_max(kvp["max"])

            rows = int(kvp["rows"])
            cols = int(kvp["cols"])
            depths = int(kvp["depths"])

            ncells = cols * rows * depths

            self.metadata.set_cols(cols)
            self.metadata.set_rows(rows)
            self.metadata.set_depths(depths)
            self.metadata.set_number_of_cells(ncells)

            return True

        return False

###############################################################################


class VectorDataset(AbstractMapDataset):
    """Vector dataset class

        This class provides functions to select, update, insert or delete vector
        map information and valid time stamps into the SQL temporal database.

        Usage:

        .. code-block:: python

            >>> import grass.script as grass
            >>> init()
            >>> grass.use_temp_region()
            >>> grass.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)
            0
            >>> grass.run_command("v.random", overwrite=True, output="stvds_map_test_case",
            ... n=100, zmin=0, zmax=100, flags="z", column="elevation", quiet=True)
            0
            >>> grass.run_command("v.timestamp", map="stvds_map_test_case",
            ...                   date="15 jan 1999", quiet=True)
            0
            >>> mapset = get_current_mapset()
            >>> name = "stvds_map_test_case"
            >>> identifier = "%s@%s" % (name, mapset)
            >>> vmap = VectorDataset(identifier)
            >>> vmap.map_exists()
            True
            >>> vmap.read_timestamp_from_grass()
            True
            >>> vmap.get_temporal_extent_as_tuple()
            (datetime.datetime(1999, 1, 15, 0, 0), None)
            >>> vmap.load()
            True
            >>> vmap.absolute_time.print_info()
             +-------------------- Absolute time -----------------------------------------+
             | Start time:................. 1999-01-15 00:00:00
             | End time:................... None
            >>> vmap.metadata.print_info()
             +-------------------- Metadata information ----------------------------------+
             | Is map 3d .................. True
             | Number of points ........... 100
             | Number of lines ............ 0
             | Number of boundaries ....... 0
             | Number of centroids ........ 0
             | Number of faces ............ 0
             | Number of kernels .......... 0
             | Number of primitives ....... 100
             | Number of nodes ............ 0
             | Number of areas ............ 0
             | Number of islands .......... 0
             | Number of holes ............ 0
             | Number of volumes .......... 0

            >>> grass.run_command("v.timestamp", map="stvds_map_test_case",
            ...                   date="2 years", quiet=True)
            0
            >>> vmap.read_timestamp_from_grass()
            True
            >>> vmap.get_temporal_extent_as_tuple()
            (2, None)
            >>> vmap.get_relative_time_unit()
            'years'

            >>> newmap = vmap.get_new_instance("new@PERMANENT")
            >>> isinstance(newmap, VectorDataset)
            True
            >>> newstvds = vmap.get_new_stds_instance("new@PERMANENT")
            >>> isinstance(newstvds, SpaceTimeVectorDataset)
            True
            >>> vmap.get_type()
            'vector'
            >>> vmap.set_absolute_time(start_time=datetime(2001,1,1),
            ...                        end_time=datetime(2012,1,1))
            True
            >>> vmap.get_absolute_time()
            (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2012, 1, 1, 0, 0))
            >>> vmap.get_temporal_extent_as_tuple()
            (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2012, 1, 1, 0, 0))
            >>> vmap.get_name()
            u'stvds_map_test_case'
            >>> vmap.get_mapset() == mapset
            True
            >>> vmap.get_temporal_type()
            'absolute'
            >>> vmap.is_time_absolute()
            True
            >>> vmap.is_time_relative()
            False
            >>> grass.run_command("g.remove", flags="f", type="vector", name=name, quiet=True)
            0
            >>> grass.del_temp_region()

    """
    def __init__(self, ident):
        AbstractMapDataset.__init__(self)
        self.reset(ident)

    def is_stds(self):
        """Return True if this class is a space time dataset

           :return: True if this class is a space time dataset, False otherwise
        """
        return False

    def get_type(self):
        return "vector"

    def get_new_instance(self, ident):
        """Return a new instance with the type of this class"""
        return VectorDataset(ident)

    def get_new_stds_instance(self, ident):
        """Return a new space time dataset instance in which maps
        are stored with the type of this class"""
        return SpaceTimeVectorDataset(ident)

    def get_layer(self):
        """Return the layer"""
        return self.base.get_layer()

    def spatial_overlapping(self, dataset):
        """Return True if the spatial extents 2d overlap"""

        return self.spatial_extent.overlapping_2d(dataset.spatial_extent)

    def spatial_relation(self, dataset):
        """Return the two dimensional spatial relation"""

        return self.spatial_extent.spatial_relation_2d(dataset.spatial_extent)

    def spatial_intersection(self, dataset):
        """Return the two dimensional intersection as spatial_extent
           object or None in case no intersection was found.

           :param dataset: The abstract dataset to intersect with
           :return: The intersection spatial extent or None
        """
        return self.spatial_extent.intersect_2d(dataset.spatial_extent)

    def spatial_union(self, dataset):
        """Return the two dimensional union as spatial_extent
           object or None in case the extents does not overlap or meet.

           :param dataset: The abstract dataset to create a union with
           :return: The union spatial extent or None
        """
        return self.spatial_extent.union_2d(dataset.spatial_extent)

    def spatial_disjoint_union(self, dataset):
        """Return the two dimensional union as spatial_extent object.

           :param dataset: The abstract dataset to create a union with
           :return: The union spatial extent
        """
        return self.spatial_extent.disjoint_union_2d(dataset.spatial_extent)

    def reset(self, ident):
        """Reset the internal structure and set the identifier"""
        self.base = VectorBase(ident=ident)
        self.absolute_time = VectorAbsoluteTime(ident=ident)
        self.relative_time = VectorRelativeTime(ident=ident)
        self.spatial_extent = VectorSpatialExtent(ident=ident)
        self.metadata = VectorMetadata(ident=ident)
        self.stds_register = VectorSTDSRegister(ident=ident)

    def has_grass_timestamp(self):
        """Check if a grass file bsased time stamp exists for this map.
        """
        return self.ciface.has_vector_timestamp(self.get_name(),
                                                self.get_mapset(),
                                                self.get_layer())

    def read_timestamp_from_grass(self):
        """Read the timestamp of this map from the map metadata
           in the grass file system based spatial database and
           set the internal time stamp that should be insert/updated
           in the temporal database.
        """

        if not self.has_grass_timestamp():
            return False

        check, dates = self.ciface.read_vector_timestamp(self.get_name(),
                                                         self.get_mapset(),)

        if check < 1:
            self.msgr.error(_("Unable to read timestamp file "
                              "for vector map <%s>" % (self.get_map_id())))
            return False

        if len(dates) == 2:
            self.set_absolute_time(dates[0], dates[1])
        else:
            self.set_relative_time(dates[0], dates[1], dates[2])

        return True

    def write_timestamp_to_grass(self):
        """Write the timestamp of this map into the map metadata in
           the grass file system based spatial database.

           Internally the libgis API functions are used for writing
        """
        check = self.ciface.write_vector_timestamp(self.get_name(),
                                                   self.get_mapset(),
                                                   self._convert_timestamp(),
                                                   self.get_layer())

        if check == -1:
            self.msgr.error(_("Unable to create timestamp file "
                              "for vector map <%s>" % (self.get_map_id())))
            return False

        if check == -2:
            self.msgr.error(_("Invalid datetime in timestamp for vector "
                              "map <%s>" % (self.get_map_id())))
            return False

        return True

    def remove_timestamp_from_grass(self):
        """Remove the timestamp from the grass file system based spatial
           database

           Internally the libgis API functions are used for removal
        """
        check = self.ciface.remove_vector_timestamp(self.get_name(),
                                                    self.get_mapset())

        if check == -1:
            self.msgr.error(_("Unable to remove timestamp for vector "
                              "map <%s>" % (self.get_name())))
            return False

        return True

    def map_exists(self):
        """Return True in case the map exists in the grass spatial database

           :return: True if map exists, False otherwise
        """
        return self.ciface.vector_map_exists(self.get_name(),
                                             self.get_mapset())

    def load(self):

        """Load all info from an existing vector map into the internal structure

           This method checks first if the map exists, in case it exists
           the metadata of the map is put into this object and True is returned

           :return: True is the map exists and the metadata was filled
                    successfully and getting the data was successful,
                    False otherwise
        """

        if self.map_exists() is not True:
            return False

        # Fill base information
        self.base.set_creator(str(getpass.getuser()))

        # Get the data from an existing vector map

        kvp = self.ciface.read_vector_info(self.get_name(),
                                           self.get_mapset())

        if kvp:
            # Fill spatial extent
            self.set_spatial_extent_from_values(north=kvp["north"],
                                                south=kvp["south"],
                                                east=kvp["east"],
                                                west=kvp["west"],
                                                top=kvp["top"],
                                                bottom=kvp["bottom"])

            # Fill metadata
            self.metadata.set_3d_info(kvp["map3d"])
            self.metadata.set_number_of_points(kvp["points"])
            self.metadata.set_number_of_lines(kvp["lines"])
            self.metadata.set_number_of_boundaries(kvp["boundaries"])
            self.metadata.set_number_of_centroids(kvp["centroids"])
            self.metadata.set_number_of_faces(kvp["faces"])
            self.metadata.set_number_of_kernels(kvp["kernels"])
            self.metadata.set_number_of_primitives(kvp["primitives"])
            self.metadata.set_number_of_nodes(kvp["nodes"])
            self.metadata.set_number_of_areas(kvp["areas"])
            self.metadata.set_number_of_islands(kvp["islands"])
            self.metadata.set_number_of_holes(kvp["holes"])
            self.metadata.set_number_of_volumes(kvp["volumes"])

            return True

        return False

###############################################################################


class SpaceTimeRasterDataset(AbstractSpaceTimeDataset):
    """Space time raster dataset class
    """
    def __init__(self, ident):
        AbstractSpaceTimeDataset.__init__(self, ident)

    def is_stds(self):
        """Return True if this class is a space time dataset

           :return: True if this class is a space time dataset, False otherwise
        """
        return True

    def get_type(self):
        return "strds"

    def get_new_instance(self, ident):
        """Return a new instance with the type of this class"""
        return SpaceTimeRasterDataset(ident)

    def get_new_map_instance(self, ident):
        """Return a new instance of a map dataset which is associated "
        "with the type of this class"""
        return RasterDataset(ident)

    def get_map_register(self):
        """Return the name of the map register table"""
        return self.metadata.get_raster_register()

    def set_map_register(self, name):
        """Set the name of the map register table"""
        self.metadata.set_raster_register(name)

    def spatial_overlapping(self, dataset):
        """Return True if the spatial extents 2d overlap"""
        return self.spatial_extent.overlapping_2d(dataset.spatial_extent)

    def spatial_relation(self, dataset):
        """Return the two dimensional spatial relation"""
        return self.spatial_extent.spatial_relation_2d(dataset.spatial_extent)

    def spatial_intersection(self, dataset):
        """Return the two dimensional intersection as spatial_extent
           object or None in case no intersection was found.

           :param dataset: The abstract dataset to intersect with
           :return: The intersection spatial extent or None
        """
        return self.spatial_extent.intersect_2d(dataset.spatial_extent)

    def spatial_union(self, dataset):
        """Return the two dimensional union as spatial_extent
           object or None in case the extents does not overlap or meet.

           :param dataset: The abstract dataset to create a union with
           :return: The union spatial extent or None
        """
        return self.spatial_extent.union_2d(dataset.spatial_extent)

    def spatial_disjoint_union(self, dataset):
        """Return the two dimensional union as spatial_extent object.

           :param dataset: The abstract dataset to create a union with
           :return: The union spatial extent
        """
        return self.spatial_extent.disjoint_union_2d(dataset.spatial_extent)

    def reset(self, ident):

        """Reset the internal structure and set the identifier"""
        self.base = STRDSBase(ident=ident)
        self.base.set_creator(str(getpass.getuser()))
        self.absolute_time = STRDSAbsoluteTime(ident=ident)
        self.relative_time = STRDSRelativeTime(ident=ident)
        self.spatial_extent = STRDSSpatialExtent(ident=ident)
        self.metadata = STRDSMetadata(ident=ident)

###############################################################################


class SpaceTimeRaster3DDataset(AbstractSpaceTimeDataset):
    """Space time raster3d dataset class
    """

    def __init__(self, ident):
        AbstractSpaceTimeDataset.__init__(self, ident)

    def is_stds(self):
        """Return True if this class is a space time dataset

           :return: True if this class is a space time dataset, False otherwise
        """
        return True

    def get_type(self):
        return "str3ds"

    def get_new_instance(self, ident):
        """Return a new instance with the type of this class"""
        return SpaceTimeRaster3DDataset(ident)

    def get_new_map_instance(self, ident):
        """Return a new instance of a map dataset which is associated
        with the type of this class"""
        return Raster3DDataset(ident)

    def get_map_register(self):
        """Return the name of the map register table"""
        return self.metadata.get_raster3d_register()

    def set_map_register(self, name):
        """Set the name of the map register table"""
        self.metadata.set_raster3d_register(name)

    def spatial_overlapping(self, dataset):
        """Return True if the spatial extents overlap"""

        if self.get_type() == dataset.get_type() or dataset.get_type() == "str3ds":
            return self.spatial_extent.overlapping(dataset.spatial_extent)
        else:
            return self.spatial_extent.overlapping_2d(dataset.spatial_extent)

    def spatial_relation(self, dataset):
        """Return the two or three dimensional spatial relation"""

        if self.get_type() == dataset.get_type() or \
           dataset.get_type() == "str3ds":
            return self.spatial_extent.spatial_relation(dataset.spatial_extent)
        else:
            return self.spatial_extent.spatial_relation_2d(dataset.spatial_extent)

    def spatial_intersection(self, dataset):
        """Return the three or two dimensional intersection as spatial_extent
           object or None in case no intersection was found.

           :param dataset: The abstract dataset to intersect with
           :return: The intersection spatial extent or None
        """
        if self.get_type() == dataset.get_type() or dataset.get_type() == "raster3d":
            return self.spatial_extent.intersect(dataset.spatial_extent)
        else:
            return self.spatial_extent.intersect_2d(dataset.spatial_extent)

    def spatial_union(self, dataset):
        """Return the three or two dimensional union as spatial_extent
           object or None in case the extents does not overlap or meet.

           :param dataset: The abstract dataset to create a union with
           :return: The union spatial extent or None
        """
        if self.get_type() == dataset.get_type() or dataset.get_type() == "raster3d":
            return self.spatial_extent.union(dataset.spatial_extent)
        else:
            return self.spatial_extent.union_2d(dataset.spatial_extent)

    def spatial_disjoint_union(self, dataset):
        """Return the three or two dimensional union as spatial_extent object.

           :param dataset: The abstract dataset to create a union with
           :return: The union spatial extent
        """
        if self.get_type() == dataset.get_type() or dataset.get_type() == "raster3d":
            return self.spatial_extent.disjoint_union(dataset.spatial_extent)
        else:
            return self.spatial_extent.disjoint_union_2d(dataset.spatial_extent)

    def reset(self, ident):

        """Reset the internal structure and set the identifier"""
        self.base = STR3DSBase(ident=ident)
        self.base.set_creator(str(getpass.getuser()))
        self.absolute_time = STR3DSAbsoluteTime(ident=ident)
        self.relative_time = STR3DSRelativeTime(ident=ident)
        self.spatial_extent = STR3DSSpatialExtent(ident=ident)
        self.metadata = STR3DSMetadata(ident=ident)

###############################################################################


class SpaceTimeVectorDataset(AbstractSpaceTimeDataset):
    """Space time vector dataset class
    """

    def __init__(self, ident):
        AbstractSpaceTimeDataset.__init__(self, ident)

    def is_stds(self):
        """Return True if this class is a space time dataset

           :return: True if this class is a space time dataset, False otherwise
        """
        return True

    def get_type(self):
        return "stvds"

    def get_new_instance(self, ident):
        """Return a new instance with the type of this class"""
        return SpaceTimeVectorDataset(ident)

    def get_new_map_instance(self, ident):
        """Return a new instance of a map dataset which is associated
        with the type of this class"""
        return VectorDataset(ident)

    def get_map_register(self):
        """Return the name of the map register table"""
        return self.metadata.get_vector_register()

    def set_map_register(self, name):
        """Set the name of the map register table"""
        self.metadata.set_vector_register(name)

    def spatial_overlapping(self, dataset):
        """Return True if the spatial extents 2d overlap"""
        return self.spatial_extent.overlapping_2d(dataset.spatial_extent)

    def spatial_relation(self, dataset):
        """Return the two dimensional spatial relation"""
        return self.spatial_extent.spatial_relation_2d(dataset.spatial_extent)

    def spatial_intersection(self, dataset):
        """Return the two dimensional intersection as spatial_extent
           object or None in case no intersection was found.

           :param dataset: The abstract dataset to intersect with
           :return: The intersection spatial extent or None
        """
        return self.spatial_extent.intersect_2d(dataset.spatial_extent)

    def spatial_union(self, dataset):
        """Return the two dimensional union as spatial_extent
           object or None in case the extents does not overlap or meet.

           :param dataset: The abstract dataset to create a union with
           :return: The union spatial extent or None
        """
        return self.spatial_extent.union_2d(dataset.spatial_extent)

    def spatial_disjoint_union(self, dataset):
        """Return the two dimensional union as spatial_extent object.

           :param dataset: The abstract dataset to create a union with
           :return: The union spatial extent
        """
        return self.spatial_extent.disjoint_union_2d(dataset.spatial_extent)

    def reset(self, ident):

        """Reset the internal structure and set the identifier"""
        self.base = STVDSBase(ident=ident)
        self.base.set_creator(str(getpass.getuser()))
        self.absolute_time = STVDSAbsoluteTime(ident=ident)
        self.relative_time = STVDSRelativeTime(ident=ident)
        self.spatial_extent = STVDSSpatialExtent(ident=ident)
        self.metadata = STVDSMetadata(ident=ident)

###############################################################################

if __name__ == "__main__":
    import doctest
    doctest.testmod()