File: abstract_dataset.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 (672 lines) | stat: -rw-r--r-- 24,347 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
# -*- coding: utf-8 -*-
"""
The abstract_dataset module provides the AbstractDataset class
that is the base class for all map layer and Space Time Datasets.

(C) 2011-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
"""
from abc import ABCMeta, abstractmethod
from .temporal_extent import *
from .spatial_extent import *
from .metadata import *
from .temporal_topology_dataset_connector import *
from .spatial_topology_dataset_connector import *

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


class AbstractDataset(SpatialTopologyDatasetConnector,
                      TemporalTopologyDatasetConnector):
    """This is the base class for all datasets
       (raster, vector, raster3d, strds, stvds, str3ds)"""

    __metaclass__ = ABCMeta

    def __init__(self):
        SpatialTopologyDatasetConnector.__init__(self)
        TemporalTopologyDatasetConnector.__init__(self)
        self.msgr = get_tgis_message_interface()

    def reset_topology(self):
        """Reset any information about temporal topology"""

        self.reset_spatial_topology()
        self.reset_temporal_topology()

    def get_number_of_relations(self):
        """Return a dictionary in which the keys are the relation names and the
        value are the number of relations.

        The following relations are available:

        Spatial relations:

            - equivalent
            - overlap
            - in
            - contain
            - meet
            - cover
            - covered

        Temporal relations:

            - equal
            - follows
            - precedes
            - overlaps
            - overlapped
            - during (including starts, finishes)
            - contains (including started, finished)
            - starts
            - started
            - finishes
            - finished

        To access topological information the spatial, temporal or booth
        topologies must be build first using the SpatioTemporalTopologyBuilder.

        :return: The dictionary with relations as keys and number as values or
                 None in case the topology  wasn't build
        """
        if self.is_temporal_topology_build() and not self.is_spatial_topology_build():
            return self.get_number_of_temporal_relations()
        elif self.is_spatial_topology_build() and not self.is_temporal_topology_build():
            self.get_number_of_spatial_relations()
        else:
            return self.get_number_of_temporal_relations() + \
                   self.get_number_of_spatial_relations()

        return None

    def set_topology_build_true(self):
        """Use this method when the spatio-temporal topology was build"""
        self.set_spatial_topology_build_true()
        self.set_temporal_topology_build_true()

    def set_topology_build_false(self):
        """Use this method when the spatio-temporal topology was not build"""
        self.set_spatial_topology_build_false()
        self.set_temporal_topology_build_false()

    def is_topology_build(self):
        """Check if the spatial and temporal topology was build

           :return: A dictionary with "spatial" and "temporal" as keys that
                    have boolen values
        """
        d = {}
        d["spatial"] = self.is_spatial_topology_build()
        d["temporal"] = self.is_temporal_topology_build()

        return d

    def print_topology_info(self):
        if self.is_temporal_topology_build():
            self.print_temporal_topology_info()
        if self.is_spatial_topology_build():
            self.print_spatial_topology_info()

    def print_topology_shell_info(self):
        if self.is_temporal_topology_build():
            self.print_temporal_topology_shell_info()
        if self.is_spatial_topology_build():
            self.print_spatial_topology_shell_info()

    @abstractmethod
    def reset(self, ident):
        """Reset the internal structure and set the identifier

            This method creates the dataset specific internal objects
            that store the base information, the spatial and temporal extent
            and the metadata. It must be implemented in the dataset
            specific subclasses. This is the code for the
            vector dataset:

            .. code-block:: python

                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)

           :param ident: The identifier of the dataset that  "name@mapset" or
                         in case of vector maps "name:layer@mapset"
        """

    @abstractmethod
    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
        """

    @abstractmethod
    def get_type(self):
        """Return the type of this class as string

           The type can be "vector", "raster", "raster3d", "stvds", "strds" or "str3ds"

           :return: "vector", "raster", "raster3d", "stvds", "strds" or "str3ds"
        """

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

           :param ident: The identifier of the new dataset instance
           :return: A new instance with the type of this object
        """

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

           :param dataset: The abstract dataset to check spatial overlapping
           :return: True if self and the provided dataset spatial overlap
        """

    @abstractmethod
    def spatial_intersection(self, dataset):
        """Return the spatial 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
        """

    @abstractmethod
    def spatial_union(self, dataset):
        """Return the spatial 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
        """

    @abstractmethod
    def spatial_disjoint_union(self, dataset):
        """Return the spatial union as spatial_extent object.

           :param dataset: The abstract dataset to create a union with
           :return: The union spatial extent
        """

    @abstractmethod
    def spatial_relation(self, dataset):
        """Return the spatial relationship between self and dataset

           :param dataset: The abstract dataset to compute the spatial
                           relation with self
           :return: The spatial relationship as string
        """

    @abstractmethod
    def print_info(self):
        """Print information about this class in human readable style"""

    @abstractmethod
    def print_shell_info(self):
        """Print information about this class in shell style"""

    @abstractmethod
    def print_self(self):
        """Print the content of the internal structure to stdout"""

    def set_id(self, ident):
        """Set the identifier of the dataset"""
        self.base.set_id(ident)
        self.temporal_extent.set_id(ident)
        self.spatial_extent.set_id(ident)
        self.metadata.set_id(ident)
        if self.is_stds() is False:
            self.stds_register.set_id(ident)

    def get_id(self):
        """Return the unique identifier of the dataset
           :return: The id of the dataset "name(:layer)@mapset" as string
        """
        return self.base.get_id()

    def get_name(self):
        """Return the name
           :return: The name of the dataset as string
        """
        return self.base.get_name()

    def get_mapset(self):
        """Return the mapset
           :return: The mapset in which the dataset was created as string
        """
        return self.base.get_mapset()

    def get_temporal_extent_as_tuple(self):
        """Returns a tuple of the valid start and end time

           Start and end time can be either of type datetime or of type
           integer, depending on the temporal type.

           :return: A tuple of (start_time, end_time)
        """
        start = self.temporal_extent.get_start_time()
        end = self.temporal_extent.get_end_time()
        return (start, end)

    def get_absolute_time(self):
        """Returns the start time, the end
           time of the map as tuple

           The start time is of type datetime.

           The end time is of type datetime in case of interval time,
           or None on case of a time instance.

           :return: A tuple of (start_time, end_time)
        """

        start = self.absolute_time.get_start_time()
        end = self.absolute_time.get_end_time()

        return (start, end)

    def get_relative_time(self):
        """Returns the start time, the end
           time and the temporal unit of the dataset as tuple

           The start time is of type integer.

           The end time is of type integer in case of interval time,
           or None on case of a time instance.

           :return: A tuple of (start_time, end_time, unit)
        """

        start = self.relative_time.get_start_time()
        end = self.relative_time.get_end_time()
        unit = self.relative_time.get_unit()

        return (start, end, unit)

    def get_relative_time_unit(self):
        """Returns the relative time unit
           :return: The relative time unit as string, None if not present
        """
        return self.relative_time.get_unit()

    def check_relative_time_unit(self, unit):
        """Check if unit is of type  year(s), month(s), day(s), hour(s),
           minute(s) or second(s)

           :param unit: The unit string
           :return: True if success, False otherwise
        """
        # Check unit
        units = ["year", "years", "month", "months", "day", "days", "hour",
                 "hours", "minute", "minutes", "second", "seconds"]
        if unit not in units:
            return False
        return True

    def get_temporal_type(self):
        """Return the temporal type of this dataset

           The temporal type can be absolute or relative

           :return: The temporal type of the dataset as string
        """
        return self.base.get_ttype()

    def get_spatial_extent_as_tuple(self):
        """Return the spatial extent as tuple

           Top and bottom are set to 0 in case of a two dimensional spatial
           extent.

           :return: A the spatial extent as tuple (north, south, east, west,
                    top, bottom)
        """
        return self.spatial_extent.get_spatial_extent_as_tuple()

    def get_spatial_extent(self):
        """Return the spatial extent
        """
        return self.spatial_extent

    def select(self, dbif=None):
        """Select temporal dataset entry from database and fill
           the internal structure

           The content of every dataset is stored in the temporal database.
           This method must be used to fill this object with the content
           from the temporal database.

           :param dbif: The database interface to be used
        """

        dbif, connected = init_dbif(dbif)

        self.base.select(dbif)
        self.temporal_extent.select(dbif)
        self.spatial_extent.select(dbif)
        self.metadata.select(dbif)
        if self.is_stds() is False:
            self.stds_register.select(dbif)

        if connected:
            dbif.close()

    def is_in_db(self, dbif=None):
        """Check if the dataset is registered in the database

           :param dbif: The database interface to be used
           :return: True if the dataset is registered in the database
        """
        return self.base.is_in_db(dbif)

    @abstractmethod
    def delete(self):
        """Delete dataset from database if it exists"""

    def insert(self, dbif=None, execute=True):
        """Insert dataset into database

           :param dbif: The database interface to be used
           :param execute: If True the SQL statements will be executed.
                           If False the prepared SQL statements are returned
                           and must be executed by the caller.
           :return: The SQL insert statement in case execute=False, or an
                    empty string otherwise
        """

        if get_enable_mapset_check() is True and self.get_mapset() != get_current_mapset():
            self.msgr.fatal(_("Unable to insert dataset <%(ds)s> of type "
                              "%(type)s in the temporal database. The mapset "
                              "of the dataset does not match the current "
                              "mapset") % {"ds": self.get_id(),
                                           "type": self.get_type()})

        dbif, connected = init_dbif(dbif)

        # Build the INSERT SQL statement
        statement = self.base.get_insert_statement_mogrified(dbif)
        statement += self.temporal_extent.get_insert_statement_mogrified(dbif)
        statement += self.spatial_extent.get_insert_statement_mogrified(dbif)
        statement += self.metadata.get_insert_statement_mogrified(dbif)
        if self.is_stds() is False:
            statement += self.stds_register.get_insert_statement_mogrified(dbif)

        if execute:
            dbif.execute_transaction(statement)
            if connected:
                dbif.close()
            return ""

        if connected:
            dbif.close()
        return statement

    def update(self, dbif=None, execute=True, ident=None):
        """Update the dataset entry in the database from the internal structure
           excluding None variables

           :param dbif: The database interface to be used
           :param execute: If True the SQL statements will be executed.
                           If False the prepared SQL statements are returned
                           and must be executed by the caller.
           :param ident: The identifier to be updated, useful for renaming
           :return: The SQL update statement in case execute=False, or an
                    empty string otherwise
        """

        if get_enable_mapset_check() is True and self.get_mapset() != get_current_mapset():
            self.msgr.fatal(_("Unable to update dataset <%(ds)s> of type "
                              "%(type)s in the temporal database. The mapset "
                              "of the dataset does not match the current "
                              "mapset") % {"ds": self.get_id(),
                                           "type": self.get_type()})

        dbif, connected = init_dbif(dbif)

        # Build the UPDATE SQL statement
        statement = self.base.get_update_statement_mogrified(dbif, ident)
        statement += self.temporal_extent.get_update_statement_mogrified(dbif,
                                                                         ident)
        statement += self.spatial_extent.get_update_statement_mogrified(dbif,
                                                                        ident)
        statement += self.metadata.get_update_statement_mogrified(dbif, ident)

        if self.is_stds() is False:
            statement += self.stds_register.get_update_statement_mogrified(dbif, ident)

        if execute:
            dbif.execute_transaction(statement)
            if connected:
                dbif.close()
            return ""

        if connected:
            dbif.close()
        return statement

    def update_all(self, dbif=None, execute=True, ident=None):
        """Update the dataset entry in the database from the internal structure
           and include None variables.

           :param dbif: The database interface to be used
           :param execute: If True the SQL statements will be executed.
                           If False the prepared SQL statements are returned
                           and must be executed by the caller.
           :param ident: The identifier to be updated, useful for renaming
           :return: The SQL update statement in case execute=False, or an
                    empty string otherwise
        """

        if get_enable_mapset_check() is True and self.get_mapset() != get_current_mapset():
            self.msgr.fatal(_("Unable to update dataset <%(ds)s> of type "
                              "%(type)s in the temporal database. The mapset"
                              " of the dataset does not match the current "
                              "mapset") % {"ds": self.get_id(),
                                           "type": self.get_type()})

        dbif, connected = init_dbif(dbif)

        # Build the UPDATE SQL statement
        statement = self.base.get_update_all_statement_mogrified(dbif, ident)
        statement += self.temporal_extent.get_update_all_statement_mogrified(dbif,
                                                                             ident)
        statement += self.spatial_extent.get_update_all_statement_mogrified(dbif,
                                                                            ident)
        statement += self.metadata.get_update_all_statement_mogrified(dbif,
                                                                      ident)

        if self.is_stds() is False:
            statement += self.stds_register.get_update_all_statement_mogrified(dbif, ident)

        if execute:
            dbif.execute_transaction(statement)
            if connected:
                dbif.close()
            return ""

        if connected:
            dbif.close()
        return statement

    def is_time_absolute(self):
        """Return True in case the temporal type is absolute

           :return: True if temporal type is absolute, False otherwise
        """
        if "temporal_type" in self.base.D:
            return self.base.get_ttype() == "absolute"
        else:
            return None

    def is_time_relative(self):
        """Return True in case the temporal type is relative

           :return: True if temporal type is relative, False otherwise
        """
        if "temporal_type" in self.base.D:
            return self.base.get_ttype() == "relative"
        else:
            return None

    def get_temporal_extent(self):
        """Return the temporal extent of the correct internal type
        """
        if self.is_time_absolute():
            return self.absolute_time
        if self.is_time_relative():
            return self.relative_time
        return None

    temporal_extent = property(fget=get_temporal_extent)

    def temporal_relation(self, dataset):
        """Return the temporal relation of self and the provided dataset

           :return: The temporal relation as string
        """
        return self.temporal_extent.temporal_relation(dataset.temporal_extent)

    def temporal_intersection(self, dataset):
        """Intersect self with the provided dataset and
           return a new temporal extent with the new start and end time

           :param dataset: The abstract dataset to temporal intersect with
           :return: The new temporal extent with start and end time,
                    or None in case of no intersection
        """
        return self.temporal_extent.intersect(dataset.temporal_extent)

    def temporal_union(self, dataset):
        """Creates a union with the provided dataset and
           return a new temporal extent with the new start and end time.

           :param dataset: The abstract dataset to create temporal union with
           :return: The new temporal extent with start and end time,
                    or None in case of no intersection
        """
        return self.temporal_extent.union(dataset.temporal_extent)

    def temporal_disjoint_union(self, dataset):
        """Creates a union with the provided dataset and
           return a new temporal extent with the new start and end time.

           :param dataset: The abstract dataset to create temporal union with
           :return: The new temporal extent with start and end time
        """
        return self.temporal_extent.disjoint_union(dataset.temporal_extent)

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


class AbstractDatasetComparisonKeyStartTime(object):
    """This comparison key can be used to sort lists of abstract datasets
       by start time

        Example:

        .. code-block:: python

            # Return all maps in a space time raster dataset as map objects
            map_list = strds.get_registered_maps_as_objects()

            # Sort the maps in the list by start time
            sorted_map_list = sorted(map_list, key=AbstractDatasetComparisonKeyStartTime)
    """
    def __init__(self, obj, *args):
        self.obj = obj

    def __lt__(self, other):
        startA, endA = self.obj.get_temporal_extent_as_tuple()
        startB, endB = other.obj.get_temporal_extent_as_tuple()
        return startA < startB

    def __gt__(self, other):
        startA, endA = self.obj.get_temporal_extent_as_tuple()
        startB, endB = other.obj.get_temporal_extent_as_tuple()
        return startA > startB

    def __eq__(self, other):
        startA, endA = self.obj.get_temporal_extent_as_tuple()
        startB, endB = other.obj.get_temporal_extent_as_tuple()
        return startA == startB

    def __le__(self, other):
        startA, endA = self.obj.get_temporal_extent_as_tuple()
        startB, endB = other.obj.get_temporal_extent_as_tuple()
        return startA <= startB

    def __ge__(self, other):
        startA, endA = self.obj.get_temporal_extent_as_tuple()
        startB, endB = other.obj.get_temporal_extent_as_tuple()
        return startA >= startB

    def __ne__(self, other):
        startA, endA = self.obj.get_temporal_extent_as_tuple()
        startB, endB = other.obj.get_temporal_extent_as_tuple()
        return startA != startB

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


class AbstractDatasetComparisonKeyEndTime(object):
    """This comparison key can be used to sort lists of abstract datasets
       by end time

        Example:

        .. code-block:: python

            # Return all maps in a space time raster dataset as map objects
            map_list = strds.get_registered_maps_as_objects()

            # Sort the maps in the list by end time
            sorted_map_list = sorted(map_list, key=AbstractDatasetComparisonKeyEndTime)
    """
    def __init__(self, obj, *args):
        self.obj = obj

    def __lt__(self, other):
        startA, endA = self.obj.get_temporal_extent_as_tuple()
        startB, endB = other.obj.get_temporal_extent_as_tuple()
        return endA < endB

    def __gt__(self, other):
        startA, endA = self.obj.get_temporal_extent_as_tuple()
        startB, endB = other.obj.get_temporal_extent_as_tuple()
        return endA > endB

    def __eq__(self, other):
        startA, endA = self.obj.get_temporal_extent_as_tuple()
        startB, endB = other.obj.get_temporal_extent_as_tuple()
        return endA == endB

    def __le__(self, other):
        startA, endA = self.obj.get_temporal_extent_as_tuple()
        startB, endB = other.obj.get_temporal_extent_as_tuple()
        return endA <= endB

    def __ge__(self, other):
        startA, endA = self.obj.get_temporal_extent_as_tuple()
        startB, endB = other.obj.get_temporal_extent_as_tuple()
        return endA >= endB

    def __ne__(self, other):
        startA, endA = self.obj.get_temporal_extent_as_tuple()
        startB, endB = other.obj.get_temporal_extent_as_tuple()
        return endA != endB

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

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