tgis_core.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. """!@package grass.script.tgis_core
  2. @brief GRASS Python scripting module (temporal GIS functions)
  3. Temporal GIS core functions to be used in Python sripts.
  4. Usage:
  5. @code
  6. from grass.script import tgis_core as grass
  7. grass.create_temporal_database()
  8. ...
  9. @endcode
  10. (C) 2008-2011 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Soeren Gebbert
  15. """
  16. import os
  17. import sqlite3
  18. import core
  19. import copy
  20. from datetime import datetime, date, time, timedelta
  21. ###############################################################################
  22. def get_grass_location_db_path():
  23. grassenv = core.gisenv()
  24. dbpath = os.path.join(grassenv["GISDBASE"], grassenv["LOCATION_NAME"])
  25. return os.path.join(dbpath, "grass.db")
  26. ###############################################################################
  27. def get_sql_template_path():
  28. base = os.getenv("GISBASE")
  29. base_etc = os.path.join(base, "etc")
  30. return os.path.join(base_etc, "sql")
  31. def test_increment_datetime_by_string():
  32. dt = datetime(2001, 9, 1, 0, 0, 0)
  33. string = "60 seconds, 4 minutes, 12 hours, 10 days, 1 weeks, 5 months, 1 years"
  34. dt1 = datetime(2003,2,18,12,5,0)
  35. dt2 = increment_datetime_by_string(dt, string)
  36. delta = dt1 -dt2
  37. if delta.days != 0 or delta.seconds != 0:
  38. core.fatal("increment computation is wrong")
  39. def increment_datetime_by_string(mydate, increment, mult = 1):
  40. """Return a new datetime object incremented with the provided relative dates specified as string.
  41. Additional a multiplier can be specified to multiply the increment bevor adding to the provided datetime object.
  42. @mydate A datetime object to incremented
  43. @increment A string providing increment information:
  44. The string may include comma separated values of type seconds, minutes, hours, days, weeks, months and years
  45. Example: Increment the datetime 2001-01-01 00:00:00 with "60 seconds, 4 minutes, 12 hours, 10 days, 1 weeks, 5 months, 1 years"
  46. will result in the datetime 2003-02-18 12:05:00
  47. @mult A multiplier, default is 1
  48. """
  49. if increment:
  50. seconds = 0
  51. minutes = 0
  52. hours = 0
  53. days = 0
  54. weeks = 0
  55. months = 0
  56. years = 0
  57. inclist = []
  58. # Split the increment string
  59. incparts = increment.split(",")
  60. for incpart in incparts:
  61. inclist.append(incpart.strip().split(" "))
  62. for inc in inclist:
  63. if inc[1].find("seconds") >= 0:
  64. seconds = mult * int(inc[0])
  65. elif inc[1].find("minutes") >= 0:
  66. minutes = mult * int(inc[0])
  67. elif inc[1].find("hours") >= 0:
  68. hours = mult * int(inc[0])
  69. elif inc[1].find("days") >= 0:
  70. days = mult * int(inc[0])
  71. elif inc[1].find("weeks") >= 0:
  72. weeks = mult * int(inc[0])
  73. elif inc[1].find("months") >= 0:
  74. months = mult * int(inc[0])
  75. elif inc[1].find("years") >= 0:
  76. years = mult * int(inc[0])
  77. else:
  78. core.fatal("Wrong increment format: " + increment)
  79. return increment_datetime(mydate, years, months, weeks, days, hours, minutes, seconds)
  80. return mydate
  81. ###############################################################################
  82. def increment_datetime(mydate, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0):
  83. """Return a new datetime object incremented with the provided relative dates and times"""
  84. tdelta_seconds = timedelta(seconds=seconds)
  85. tdelta_minutes = timedelta(minutes=minutes)
  86. tdelta_hours = timedelta(hours=hours)
  87. tdelta_days = timedelta(days=days)
  88. tdelta_weeks = timedelta(weeks=weeks)
  89. tdelta_months = timedelta(0)
  90. tdelta_years = timedelta(0)
  91. if months > 0:
  92. # Compute the actual number of days in the month to add as timedelta
  93. year = mydate.year
  94. month = mydate.month
  95. all_months = int(months + month)
  96. years_to_add = int(all_months/12)
  97. residual_months = all_months%12
  98. # Make a deep copy of the datetime object
  99. dt1 = copy.copy(mydate)
  100. # Make sure the montha starts with a 1
  101. if residual_months == 0:
  102. residual_months = 1
  103. dt1 = dt1.replace(year = year + years_to_add, month = residual_months)
  104. tdelta_months = dt1 - mydate
  105. if years > 0:
  106. # Make a deep copy of the datetime object
  107. dt1 = copy.copy(mydate)
  108. # Compute the number of days
  109. dt1 = dt1.replace(year=mydate.year + int(years))
  110. tdelta_years = dt1 - mydate
  111. return mydate + tdelta_seconds + tdelta_minutes + tdelta_hours + \
  112. tdelta_days + tdelta_weeks + tdelta_months + tdelta_years
  113. ###############################################################################
  114. def create_temporal_database():
  115. """This function creates the grass location database structure for raster, vector and raster3d maps
  116. as well as for the space-time datasets strds, str3ds and stvds"""
  117. database = get_grass_location_db_path()
  118. # Check if it already exists
  119. if os.path.exists(database):
  120. return False
  121. # Read all SQL scripts and templates
  122. map_tables_template_sql = open(os.path.join(get_sql_template_path(), "map_tables_template.sql"), 'r').read()
  123. raster_metadata_sql = open(os.path.join(get_sql_template_path(), "raster_metadata_table.sql"), 'r').read()
  124. raster3d_metadata_sql = open(os.path.join(get_sql_template_path(), "raster3d_metadata_table.sql"), 'r').read()
  125. vector_metadata_sql = open(os.path.join(get_sql_template_path(), "vector_metadata_table.sql"), 'r').read()
  126. stds_tables_template_sql = open(os.path.join(get_sql_template_path(), "stds_tables_template.sql"), 'r').read()
  127. strds_metadata_sql = open(os.path.join(get_sql_template_path(), "strds_metadata_table.sql"), 'r').read()
  128. str3ds_metadata_sql = open(os.path.join(get_sql_template_path(), "str3ds_metadata_table.sql"), 'r').read()
  129. stvds_metadata_sql = open(os.path.join(get_sql_template_path(), "stvds_metadata_table.sql"), 'r').read()
  130. # Create the raster, raster3d and vector tables
  131. raster_tables_sql = map_tables_template_sql.replace("GRASS_MAP", "raster")
  132. vector_tables_sql = map_tables_template_sql.replace("GRASS_MAP", "vector")
  133. raster3d_tables_sql = map_tables_template_sql.replace("GRASS_MAP", "raster3d")
  134. # Create the space-time raster, raster3d and vector dataset tables
  135. strds_tables_sql = stds_tables_template_sql.replace("STDS", "strds")
  136. stvds_tables_sql = stds_tables_template_sql.replace("STDS", "stvds")
  137. str3ds_tables_sql = stds_tables_template_sql.replace("STDS", "str3ds")
  138. # Check for completion
  139. sqlite3.complete_statement(raster_tables_sql)
  140. sqlite3.complete_statement(vector_tables_sql)
  141. sqlite3.complete_statement(raster3d_tables_sql)
  142. sqlite3.complete_statement(raster_metadata_sql)
  143. sqlite3.complete_statement(vector_metadata_sql)
  144. sqlite3.complete_statement(raster3d_metadata_sql)
  145. sqlite3.complete_statement(strds_tables_sql)
  146. sqlite3.complete_statement(stvds_tables_sql)
  147. sqlite3.complete_statement(str3ds_tables_sql)
  148. sqlite3.complete_statement(strds_metadata_sql)
  149. sqlite3.complete_statement(stvds_metadata_sql)
  150. sqlite3.complete_statement(str3ds_metadata_sql)
  151. # Connect to database
  152. connection = sqlite3.connect(database)
  153. cursor = connection.cursor()
  154. # Execute the SQL statements
  155. # Create the global tables for the native grass datatypes
  156. cursor.executescript(raster_tables_sql)
  157. cursor.executescript(raster_metadata_sql)
  158. cursor.executescript(vector_tables_sql)
  159. cursor.executescript(vector_metadata_sql)
  160. cursor.executescript(raster3d_tables_sql)
  161. cursor.executescript(raster3d_metadata_sql)
  162. # Create the tables for the new space-time datatypes
  163. cursor.executescript(strds_tables_sql)
  164. cursor.executescript(strds_metadata_sql)
  165. cursor.executescript(stvds_tables_sql)
  166. cursor.executescript(stvds_metadata_sql)
  167. cursor.executescript(str3ds_tables_sql)
  168. cursor.executescript(str3ds_metadata_sql)
  169. connection.commit()
  170. cursor.close()