-
-
Notifications
You must be signed in to change notification settings - Fork 294
/
abstract_space_time_dataset.py
2469 lines (1964 loc) · 99.2 KB
/
abstract_space_time_dataset.py
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
# -*- coding: utf-8 -*-
"""
The abstract_space_time_dataset module provides the AbstractSpaceTimeDataset
class that is the base class for all 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 __future__ import print_function
import sys
import uuid
import os
import copy
from datetime import datetime
import gettext
from abc import ABCMeta, abstractmethod
from .core import init_dbif, get_sql_template_path, get_tgis_metadata, get_current_mapset, \
get_enable_mapset_check
from .abstract_dataset import AbstractDataset, AbstractDatasetComparisonKeyStartTime
from .temporal_granularity import check_granularity_string, compute_absolute_time_granularity,\
compute_relative_time_granularity
from .spatio_temporal_relationships import count_temporal_topology_relationships, \
print_spatio_temporal_topology_relationships, SpatioTemporalTopologyBuilder, \
create_temporal_relation_sql_where_statement
from .datetime_math import increment_datetime_by_string, string_to_datetime
###############################################################################
class AbstractSpaceTimeDataset(AbstractDataset):
"""Abstract space time dataset class
Base class for all space time datasets.
This class represents an abstract space time dataset. Convenient functions
to select, update, insert or delete objects of this type in the SQL
temporal database exists as well as functions to register or unregister
raster maps.
Parts of the temporal logic are implemented in the SQL temporal
database, like the computation of the temporal and spatial extent as
well as the collecting of metadata.
"""
__metaclass__ = ABCMeta
def __init__(self, ident):
AbstractDataset.__init__(self)
self.reset(ident)
self.map_counter = 0
def create_map_register_name(self):
"""Create the name of the map register table of this space time
dataset
A uuid and the map type are used to create the table name
ATTENTION: It must be assured that the base object has selected its
content from the database.
:return: The name of the map register table
"""
uuid_rand = str(uuid.uuid4()).replace("-", "")
table_name = self.get_new_map_instance(None).get_type() + "_map_register_" + uuid_rand
return table_name
@abstractmethod
def get_new_map_instance(self, ident=None):
"""Return a new instance of a map which is associated
with the type of this object
:param ident: The unique identifier of the new object
"""
@abstractmethod
def get_map_register(self):
"""Return the name of the map register table
:return: The map register table name
"""
@abstractmethod
def set_map_register(self, name):
"""Set the name of the map register table
This table stores all map names which are registered
in this space time dataset.
This method only modifies this object and does not commit
the modifications to the temporal database.
:param name: The name of the register table
"""
def print_self(self):
"""Print the content of the internal structure to stdout"""
self.base.print_self()
self.temporal_extent.print_self()
self.spatial_extent.print_self()
self.metadata.print_self()
def print_info(self):
"""Print information about this class in human readable style"""
if self.get_type() == "strds":
# 1 2 3 4 5 6 7
# 0123456789012345678901234567890123456789012345678901234567890123456789012345678
print(" +-------------------- Space Time Raster Dataset -----------------------------+")
if self.get_type() == "str3ds":
# 1 2 3 4 5 6 7
# 0123456789012345678901234567890123456789012345678901234567890123456789012345678
print(" +-------------------- Space Time 3D Raster Dataset --------------------------+")
if self.get_type() == "stvds":
# 1 2 3 4 5 6 7
# 0123456789012345678901234567890123456789012345678901234567890123456789012345678
print(" +-------------------- Space Time Vector Dataset -----------------------------+")
print(" | |")
self.base.print_info()
self.temporal_extent.print_info()
self.spatial_extent.print_info()
self.metadata.print_info()
print(" +----------------------------------------------------------------------------+")
def print_shell_info(self):
"""Print information about this class in shell style"""
self.base.print_shell_info()
self.temporal_extent.print_shell_info()
self.spatial_extent.print_shell_info()
self.metadata.print_shell_info()
def print_history(self):
"""Print history information about this class in human readable
shell style
"""
self.metadata.print_history()
def set_initial_values(self, temporal_type, semantic_type=None,
title=None, description=None):
"""Set the initial values of the space time dataset
In addition the command creation string is generated
an inserted into the metadata object.
This method only modifies this object and does not commit
the modifications to the temporal database.
The insert() function must be called to commit
this content into the temporal database.
:param temporal_type: The temporal type of this space
time dataset (absolute or relative)
:param semantic_type: The semantic type of this dataset
:param title: The title
:param description: The description of this dataset
"""
if temporal_type == "absolute":
self.base.set_ttype("absolute")
elif temporal_type == "relative":
self.base.set_ttype("relative")
else:
self.msgr.fatal(_("Unknown temporal type \"%s\"") % (temporal_type))
self.base.set_semantic_type(semantic_type)
self.metadata.set_title(title)
self.metadata.set_description(description)
self.metadata.set_command(self.create_command_string())
def set_aggregation_type(self, aggregation_type):
"""Set the aggregation type of the space time dataset
:param aggregation_type: The aggregation type of the space time
dataset
"""
self.metadata.set_aggregation_type(aggregation_type)
def update_command_string(self, dbif=None):
"""Append the current command string to any existing command string
in the metadata class and calls metadata update
:param dbif: The database interface to be used
"""
self.metadata.select(dbif=dbif)
command = self.metadata.get_command()
if command is None:
command = ""
command += self.create_command_string()
self.metadata.set_command(command)
self.metadata.update(dbif=dbif)
def create_command_string(self):
"""Create the command string that was used to create this
space time dataset.
The command string should be set with self.metadata.set_command()
:return: The command string
"""
# The grass module
command = "# %s \n"%(str(datetime.today().strftime("%Y-%m-%d %H:%M:%S")))
command += os.path.basename(sys.argv[0])
# We will wrap the command line to fit into 80 character
length = len(command)
for token in sys.argv[1:]:
# We need to remove specific characters
token = token.replace("\'", " ")
token = token.replace("\"", " ")
# Check for sub strings
if token.find("=") > 0:
first = token.split("=")[0]
second = ""
flag = 0
for t in token.split("=")[1:]:
if flag == 0:
second += t
flag = 1
else:
second += "=" + t
token = "%s=\"%s\"" % (first, second)
if length + len(token) >= 76:
command += "\n %s" % (token)
length = len(token) + 4
else:
command += " %s" % (token)
length += len(token) + 1
command += "\n"
return str(command)
def get_semantic_type(self):
"""Return the semantic type of this dataset
:return: The semantic type
"""
return self.base.get_semantic_type()
def get_initial_values(self):
"""Return the initial values: temporal_type,
semantic_type, title, description"""
temporal_type = self.get_temporal_type()
semantic_type = self.base.get_semantic_type()
title = self.metadata.get_title()
description = self.metadata.get_description()
return temporal_type, semantic_type, title, description
def get_granularity(self):
"""Return the granularity of the space time dataset
Granularity can be of absolute time or relative time.
In case of absolute time a string containing an integer
value and the time unit (years, months, days, hours, minuts,
seconds). In case of relative time an integer value is expected.
:return: The granularity
"""
return self.temporal_extent.get_granularity()
def set_granularity(self, granularity):
"""Set the granularity
The granularity is usually computed by the space time dataset at
runtime.
Granularity can be of absolute time or relative time.
In case of absolute time a string containing an integer
value and the time unit (years, months, days, hours, minuts,
seconds). In case of relative time an integer value is expected.
This method only modifies this object and does not commit
the modifications to the temporal database.
:param granularity: The granularity of the dataset
"""
temporal_type = self.get_temporal_type()
check = check_granularity_string(granularity, temporal_type)
if not check:
self.msgr.fatal(_("Wrong granularity: \"%s\"") % str(granularity))
if temporal_type == "absolute":
self.base.set_ttype("absolute")
elif temporal_type == "relative":
self.base.set_ttype("relative")
else:
self.msgr.fatal(_("Unknown temporal type \"%s\"") % (temporal_type))
self.temporal_extent.set_granularity(granularity)
def set_relative_time_unit(self, unit):
"""Set the relative time unit which may be of type:
years, months, days, hours, minutes or seconds
All maps registered in a (relative time)
space time dataset must have the same unit
This method only modifies this object and does not commit
the modifications to the temporal database.
:param unit: The relative time unit
"""
temporal_type = self.get_temporal_type()
if temporal_type == "relative":
if not self.check_relative_time_unit(unit):
self.msgr.fatal(_("Unsupported temporal unit: %s") % (unit))
self.relative_time.set_unit(unit)
def insert(self, dbif=None, execute=True):
"""Insert the space time dataset content into the database from the internal
structure
The map register table will be created, so that maps
can be registered.
: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
"""
dbif, connected = init_dbif(dbif)
# We need to create the register table if it does not exist
stds_register_table = self.get_map_register()
# Create the map register table
sql_path = get_sql_template_path()
statement = ""
# We need to create the map register table
if stds_register_table is None:
# Create table name
stds_register_table = self.create_map_register_name()
# Assure that the table and index do not exist
#dbif.execute_transaction("DROP INDEX IF EXISTS %s; DROP TABLE IF EXISTS %s;"%(stds_register_table + "_index", stds_register_table))
# Read the SQL template
sql = open(os.path.join(sql_path,
"stds_map_register_table_template.sql"),
'r').read()
# Create a raster, raster3d or vector tables
sql = sql.replace("SPACETIME_REGISTER_TABLE", stds_register_table)
statement += sql
if dbif.get_dbmi().__name__ == "sqlite3":
statement += "CREATE INDEX %s_index ON %s (id);" % \
(stds_register_table, stds_register_table)
# Set the map register table name
self.set_map_register(stds_register_table)
self.msgr.debug(1, _("Created register table <%s> for space "
"time %s dataset <%s>") %
(stds_register_table,
self.get_new_map_instance(None).get_type(),
self.get_id()))
statement += AbstractDataset.insert(self, dbif=dbif, execute=False)
if execute:
dbif.execute_transaction(statement)
statement = ""
if connected:
dbif.close()
return statement
def get_map_time(self):
"""Return the type of the map time, interval, point, mixed or invalid
"""
return self.temporal_extent.get_map_time()
def count_temporal_types(self, maps=None, dbif=None):
"""Return the temporal type of the registered maps as dictionary
The map list must be ordered by start time
The temporal type can be:
- point -> only the start time is present
- interval -> start and end time
- invalid -> No valid time point or interval found
:param maps: A sorted (start_time) list of AbstractDataset objects
:param dbif: The database interface to be used
"""
if maps is None:
maps = self.get_registered_maps_as_objects(
where=None, order="start_time", dbif=dbif)
time_invalid = 0
time_point = 0
time_interval = 0
tcount = {}
for i in range(len(maps)):
# Check for point and interval data
if maps[i].is_time_absolute():
start, end = maps[i].get_absolute_time()
if maps[i].is_time_relative():
start, end, unit = maps[i].get_relative_time()
if start is not None and end is not None:
time_interval += 1
elif start is not None and end is None:
time_point += 1
else:
time_invalid += 1
tcount["point"] = time_point
tcount["interval"] = time_interval
tcount["invalid"] = time_invalid
return tcount
def count_gaps(self, maps=None, dbif=None):
"""Count the number of gaps between temporal neighbors
:param maps: A sorted (start_time) list of AbstractDataset objects
:param dbif: The database interface to be used
:return: The numbers of gaps between temporal neighbors
"""
if maps is None:
maps = self.get_registered_maps_as_objects(
where=None, order="start_time", dbif=dbif)
gaps = 0
# Check for gaps
for i in range(len(maps)):
if i < len(maps) - 1:
relation = maps[i + 1].temporal_relation(maps[i])
if relation == "after":
gaps += 1
return gaps
def print_spatio_temporal_relationships(self, maps=None, spatial=None,
dbif=None):
"""Print the spatio-temporal relationships for each map of the space
time dataset or for each map of the optional list of maps
:param maps: a ordered by start_time list of map objects, if None
the registered maps of the space time dataset are used
:param spatial: This indicates if the spatial topology is created as
well: spatial can be None (no spatial topology),
"2D" using west, east, south, north or "3D" using
west, east, south, north, bottom, top
:param dbif: The database interface to be used
"""
if maps is None:
maps = self.get_registered_maps_as_objects(
where=None, order="start_time", dbif=dbif)
print_spatio_temporal_topology_relationships(maps1=maps, maps2=maps,
spatial=spatial,
dbif=dbif)
def count_temporal_relations(self, maps=None, dbif=None):
"""Count the temporal relations between the registered maps.
The map list must be ordered by start time.
Temporal relations are counted by analysing the sparse upper right
side temporal relationships matrix.
:param maps: A sorted (start_time) list of AbstractDataset objects
:param dbif: The database interface to be used
:return: A dictionary with counted temporal relationships
"""
if maps is None:
maps = self.get_registered_maps_as_objects(
where=None, order="start_time", dbif=dbif)
return count_temporal_topology_relationships(maps1=maps, dbif=dbif)
def check_temporal_topology(self, maps=None, dbif=None):
"""Check the temporal topology of all maps of the current space time
dataset or of an optional list of maps
Correct topology means, that time intervals are not overlap or
that intervals does not contain other intervals.
Equal time intervals are not allowed.
The optional map list must be ordered by start time
Allowed and not allowed temporal relationships for correct topology:
- after -> allowed
- precedes -> allowed
- follows -> allowed
- precedes -> allowed
- equal -> not allowed
- during -> not allowed
- contains -> not allowed
- overlaps -> not allowed
- overlapped -> not allowed
- starts -> not allowed
- finishes -> not allowed
- started -> not allowed
- finished -> not allowed
:param maps: An optional list of AbstractDataset objects, in case of
None all maps of the space time dataset are checked
:param dbif: The database interface to be used
:return: True if topology is correct
"""
if maps is None:
maps = self.get_registered_maps_as_objects(
where=None, order="start_time", dbif=dbif)
relations = count_temporal_topology_relationships(maps1=maps,
dbif=dbif)
if relations is None:
return False
map_time = self.get_map_time()
if map_time == "interval" or map_time == "mixed":
if "equal" in relations and relations["equal"] > 0:
return False
if "during" in relations and relations["during"] > 0:
return False
if "contains" in relations and relations["contains"] > 0:
return False
if "overlaps" in relations and relations["overlaps"] > 0:
return False
if "overlapped" in relations and relations["overlapped"] > 0:
return False
if "starts" in relations and relations["starts"] > 0:
return False
if "finishes" in relations and relations["finishes"] > 0:
return False
if "started" in relations and relations["started"] > 0:
return False
if "finished" in relations and relations["finished"] > 0:
return False
elif map_time == "point":
if "equal" in relations and relations["equal"] > 0:
return False
else:
return False
return True
def sample_by_dataset(self, stds, method=None, spatial=False, dbif=None):
"""Sample this space time dataset with the temporal topology
of a second space time dataset
In case spatial is True, the spatial overlap between
temporal related maps is performed. Only
temporal related and spatial overlapping maps are returned.
Return all registered maps as ordered (by start_time) object list.
Each list entry is a list of map
objects which are potentially located in temporal relation to the
actual granule of the second space time dataset.
Each entry in the object list is a dict. The actual sampler
map and its temporal extent (the actual granule) and
the list of samples are stored:
.. code-block:: python
list = self.sample_by_dataset(stds=sampler, method=[
"during","overlap","contains","equal"])
for entry in list:
granule = entry["granule"]
maplist = entry["samples"]
for map in maplist:
map.select()
map.print_info()
A valid temporal topology (no overlapping or inclusion allowed)
is needed to get correct results in case of gaps in the sample
dataset.
Gaps between maps are identified as unregistered maps with id==None.
The objects are initialized with their id's' and the spatio-temporal
extent (temporal type, start time, end time, west, east, south,
north, bottom and top).
In case more map information are needed, use the select()
method for each listed object.
:param stds: The space time dataset to be used for temporal sampling
:param method: This option specifies what sample method should be
used. In case the registered maps are of temporal
point type, only the start time is used for sampling.
In case of mixed of interval data the user can chose
between:
- Example ["start", "during", "equals"]
- start: Select maps of which the start time is
located in the selection granule::
map : s
granule: s-----------------e
map : s--------------------e
granule: s-----------------e
map : s--------e
granule: s-----------------e
- contains: Select maps which are temporal
during the selection granule::
map : s-----------e
granule: s-----------------e
- overlap: Select maps which temporal overlap
the selection granule, this includes overlaps and
overlapped::
map : s-----------e
granule: s-----------------e
map : s-----------e
granule: s----------e
- during: Select maps which temporally contains
the selection granule::
map : s-----------------e
granule: s-----------e
- equals: Select maps which temporally equal
to the selection granule::
map : s-----------e
granule: s-----------e
- follows: Select maps which temporally follow
the selection granule::
map : s-----------e
granule: s-----------e
- precedes: Select maps which temporally precedes
the selection granule::
map : s-----------e
granule: s-----------e
All these methods can be combined. Method must be of
type tuple including the identification strings.
:param spatial: If set True additional the 2d spatial overlapping
is used for selection -> spatio-temporal relation.
The returned map objects will have temporal and
spatial extents
:param dbif: The database interface to be used
:return: A list of lists of map objects or None in case nothing was
found None
"""
if self.get_temporal_type() != stds.get_temporal_type():
self.msgr.error(_("The space time datasets must be of "
"the same temporal type"))
return None
if stds.get_map_time() != "interval":
self.msgr.error(_("The temporal map type of the sample "
"dataset must be interval"))
return None
dbif, connected = init_dbif(dbif)
relations = copy.deepcopy(method)
# Tune the temporal relations
if "start" in relations:
if "overlapped" not in relations:
relations.append("overlapped")
if "starts" not in relations:
relations.append("starts")
if "started" not in relations:
relations.append("started")
if "finishes" not in relations:
relations.append("finishes")
if "contains" not in relations:
relations.append("contains")
if "equals" not in relations:
relations.append("equals")
if "overlap" in relations or "over" in relations:
if "overlapped" not in relations:
relations.append("overlapped")
if "overlaps" not in relations:
relations.append("overlaps")
if "contain" in relations:
if "contains" not in relations:
relations.append("contains")
# Remove start, equal, contain and overlap
relations = [relation.upper().strip() for relation in relations
if relation not in ["start", "overlap", "contain"]]
# print(relations)
tb = SpatioTemporalTopologyBuilder()
if spatial:
spatial = "2D"
else:
spatial = None
mapsA = self.get_registered_maps_as_objects(dbif=dbif)
mapsB = stds.get_registered_maps_as_objects_with_gaps(dbif=dbif)
tb.build(mapsB, mapsA, spatial)
obj_list = []
for map in mapsB:
result = {}
maplist = []
# Get map relations
map_relations = map.get_temporal_relations()
#print(map.get_temporal_extent_as_tuple())
#for key in map_relations.keys():
# if key not in ["NEXT", "PREV"]:
# print(key, map_relations[key][0].get_temporal_extent_as_tuple())
result["granule"] = map
# Append the maps that fulfill the relations
for relation in relations:
if relation in map_relations.keys():
for sample_map in map_relations[relation]:
if sample_map not in maplist:
maplist.append(sample_map)
# Add an empty map if no map was found
if not maplist:
empty_map = self.get_new_map_instance(None)
empty_map.set_spatial_extent(map.get_spatial_extent())
empty_map.set_temporal_extent(map.get_temporal_extent())
maplist.append(empty_map)
result["samples"] = maplist
obj_list.append(result)
if connected:
dbif.close()
return obj_list
def sample_by_dataset_sql(self, stds, method=None, spatial=False,
dbif=None):
"""Sample this space time dataset with the temporal topology
of a second space time dataset using SQL queries.
This function is very slow for huge large space time datasets
but can run several times in the same process without problems.
The sample dataset must have "interval" as temporal map type,
so all sample maps have valid interval time.
In case spatial is True, the spatial overlap between
temporal related maps is performed. Only
temporal related and spatial overlapping maps are returned.
Return all registered maps as ordered (by start_time) object list
with "gap" map objects (id==None). Each list entry is a list of map
objects which are potentially located in temporal relation to the
actual granule of the second space time dataset.
Each entry in the object list is a dict. The actual sampler
map and its temporal extent (the actual granule) and
the list of samples are stored:
.. code-block:: python
list = self.sample_by_dataset(stds=sampler, method=[
"during","overlap","contain","equal"])
for entry in list:
granule = entry["granule"]
maplist = entry["samples"]
for map in maplist:
map.select()
map.print_info()
A valid temporal topology (no overlapping or inclusion allowed)
is needed to get correct results in case of gaps in the sample
dataset.
Gaps between maps are identified as unregistered maps with id==None.
The objects are initialized with their id's' and the spatio-temporal
extent (temporal type, start time, end time, west, east, south,
north, bottom and top).
In case more map information are needed, use the select()
method for each listed object.
:param stds: The space time dataset to be used for temporal sampling
:param method: This option specifies what sample method should be
used. In case the registered maps are of temporal
point type, only the start time is used for sampling.
In case of mixed of interval data the user can chose
between:
- Example ["start", "during", "equals"]
- start: Select maps of which the start time is
located in the selection granule::
map : s
granule: s-----------------e
map : s--------------------e
granule: s-----------------e
map : s--------e
granule: s-----------------e
- contains: Select maps which are temporal
during the selection granule::
map : s-----------e
granule: s-----------------e
- overlap: Select maps which temporal overlap
the selection granule, this includes overlaps and
overlapped::
map : s-----------e
granule: s-----------------e
map : s-----------e
granule: s----------e
- during: Select maps which temporally contains
the selection granule::
map : s-----------------e
granule: s-----------e
- equals: Select maps which temporally equal
to the selection granule::
map : s-----------e
granule: s-----------e
- follows: Select maps which temporally follow
the selection granule::
map : s-----------e
granule: s-----------e
- precedes: Select maps which temporally precedes
the selection granule::
map : s-----------e
granule: s-----------e
All these methods can be combined. Method must be of
type tuple including the identification strings.
:param spatial: If set True additional the 2d spatial overlapping
is used for selection -> spatio-temporal relation.
The returned map objects will have temporal and
spatial extents
:param dbif: The database interface to be used
:return: A list of lists of map objects or None in case nothing was
found None
"""
use_start = False
use_during = False
use_overlap = False
use_contain = False
use_equal = False
use_follows = False
use_precedes = False
# Initialize the methods
if method is not None:
for name in method:
if name == "start":
use_start = True
if name == "during":
use_during = True
if name == "overlap":
use_overlap = True
if name == "contain" or name == "contains":
use_contain = True
if name == "equal" or name == "equals":
use_equal = True
if name == "follows":
use_follows = True
if name == "precedes":
use_precedes = True
else:
use_during = True
use_overlap = True
use_contain = True
use_equal = True
if self.get_temporal_type() != stds.get_temporal_type():
self.msgr.error(_("The space time datasets must be of "
"the same temporal type"))
return None
if stds.get_map_time() != "interval":
self.msgr.error(_("The temporal map type of the sample "
"dataset must be interval"))
return None
# In case points of time are available, disable the interval specific
# methods
if self.get_map_time() == "point":
use_start = True
use_during = False
use_overlap = False
use_contain = False
use_equal = False
use_follows = False
use_precedes = False
dbif, connected = init_dbif(dbif)
obj_list = []
sample_maps = stds.get_registered_maps_as_objects_with_gaps(
where=None, dbif=dbif)
for granule in sample_maps:
# Read the spatial extent
if spatial:
granule.spatial_extent.select(dbif)
start, end = granule.get_temporal_extent_as_tuple()
where = create_temporal_relation_sql_where_statement(
start, end, use_start, use_during, use_overlap,
use_contain, use_equal, use_follows, use_precedes)
maps = self.get_registered_maps_as_objects(
where, "start_time", dbif)
result = {}
result["granule"] = granule
num_samples = 0
maplist = []
if maps is not None:
for map in maps:
# Read the spatial extent
if spatial:
map.spatial_extent.select(dbif)
# Ignore spatial disjoint maps
if not granule.spatial_overlapping(map):
continue
num_samples += 1
maplist.append(copy.copy(map))
# Fill with empty map in case no spatio-temporal relations found
if maps is None or num_samples == 0:
map = self.get_new_map_instance(None)
if self.is_time_absolute():
map.set_absolute_time(start, end)
elif self.is_time_relative():
map.set_relative_time(start, end,
self.get_relative_time_unit())
maplist.append(copy.copy(map))
result["samples"] = maplist