mapcalc.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. """!@package grass.temporal
  2. @brief GRASS Python scripting module (temporal GIS functions)
  3. Temporal GIS related functions to be used in Python scripts.
  4. (C) 2008-2011 by the GRASS Development Team
  5. This program is free software under the GNU General Public
  6. License (>=v2). Read the file COPYING that comes with GRASS
  7. for details.
  8. @author Soeren Gebbert
  9. """
  10. from space_time_datasets import *
  11. from open import *
  12. from multiprocessing import Process
  13. ############################################################################
  14. def dataset_mapcalculator(inputs, output, type, expression, base, method,
  15. nprocs=1, register_null=False, spatial=False):
  16. """!Perform map-calculations of maps from different space time
  17. raster/raster3d datasets, using a specific sampling method
  18. to select temporal related maps.
  19. A mapcalc expression must be provided to process the temporal
  20. selected maps. Temporal operators are available in addition to
  21. the r.mapcalc operators:
  22. Supported operators for relative and absolute time are:
  23. - td() - the time delta of the current interval in days
  24. and fractions of days or the unit in case of relative time
  25. - start_time() - The start time of the interval from the begin of
  26. the time series in days and fractions of days or the
  27. unit in case of relative time
  28. - end_time() - The end time of the current interval from the begin of
  29. the time series in days and fractions of days or the
  30. unit in case of relative time
  31. Supported operators for absolute time:
  32. - start_doy() - Day of year (doy) from the start time [1 - 366]
  33. - start_dow() - Day of week (dow) from the start time [1 - 7],
  34. the start of the week is monday == 1
  35. - start_year() - The year of the start time [0 - 9999]
  36. - start_month() - The month of the start time [1 - 12]
  37. - start_week() - Week of year of the start time [1 - 54]
  38. - start_day() - Day of month from the start time [1 - 31]
  39. - start_hour() - The hour of the start time [0 - 23]
  40. - start_minute() - The minute of the start time [0 - 59]
  41. - start_second() - The second of the start time [0 - 59]
  42. - end_doy() - Day of year (doy) from the end time [1 - 366]
  43. - end_dow() - Day of week (dow) from the end time [1 - 7],
  44. the start of the week is monday == 1
  45. - end_year() - The year of the end time [0 - 9999]
  46. - end_month() - The month of the end time [1 - 12]
  47. - end_week() - Week of year of the end time [1 - 54]
  48. - end_day() - Day of month from the end time [1 - 31]
  49. - end_hour() - The hour of the end time [0 - 23]
  50. - end_minute() - The minute of the end time [0 - 59]
  51. - end_second() - The minute of the end time [0 - 59]
  52. @param inputs The names of the input space time raster/raster3d datasets
  53. @param output The name of the extracted new space time raster(3d) dataset
  54. @param type The type of the dataset: "raster" or "raster3d"
  55. @param expression The r(3).mapcalc expression
  56. @param base The base name of the new created maps in case a
  57. mapclac expression is provided
  58. @param method The method to be used for temporal sampling
  59. @param nprocs The number of parallel processes to be used for
  60. mapcalc processing
  61. @param register_null Set this number True to register empty maps
  62. @param spatial Check spatial overlap
  63. """
  64. # We need a database interface for fast computation
  65. dbif = SQLDatabaseInterfaceConnection()
  66. dbif.connect()
  67. mapset = get_current_mapset()
  68. input_name_list = inputs.split(",")
  69. first_input = open_old_space_time_dataset(input_name_list[0], type, dbif)
  70. # All additional inputs in reverse sorted order to avoid
  71. # wrong name substitution
  72. input_name_list = input_name_list[1:]
  73. input_name_list.sort()
  74. input_name_list.reverse()
  75. input_list = []
  76. for input in input_name_list:
  77. sp = open_old_space_time_dataset(input, type, dbif)
  78. input_list.append(copy.copy(sp))
  79. new_sp = check_new_space_time_dataset(output, type, dbif,
  80. core.overwrite())
  81. # Sample all inputs by the first input and create a sample matrix
  82. if spatial:
  83. core.message(_("Start spatio-temporal sampling"))
  84. else:
  85. core.message(_("Start temporal sampling"))
  86. map_matrix = []
  87. id_list = []
  88. sample_map_list = []
  89. # First entry is the first dataset id
  90. id_list.append(first_input.get_name())
  91. if len(input_list) > 0:
  92. has_samples = False
  93. for dataset in input_list:
  94. list = dataset.sample_by_dataset(stds=first_input,
  95. method=method, spatial=spatial,
  96. dbif=dbif)
  97. # In case samples are not found
  98. if not list and len(list) == 0:
  99. dbif.close()
  100. core.message(_("No samples found for map calculation"))
  101. return 0
  102. # The fist entries are the samples
  103. map_name_list = []
  104. if not has_samples:
  105. for entry in list:
  106. granule = entry["granule"]
  107. # Do not consider gaps
  108. if granule.get_id() is None:
  109. continue
  110. sample_map_list.append(granule)
  111. map_name_list.append(granule.get_name())
  112. # Attach the map names
  113. map_matrix.append(copy.copy(map_name_list))
  114. has_samples = True
  115. map_name_list = []
  116. for entry in list:
  117. maplist = entry["samples"]
  118. granule = entry["granule"]
  119. # Do not consider gaps in the sampler
  120. if granule.get_id() is None:
  121. continue
  122. if len(maplist) > 1:
  123. core.warning(_("Found more than a single map in a sample "
  124. "granule. Only the first map is used for "
  125. "computation. Use t.rast.aggregate.ds to "
  126. "create synchronous raster datasets."))
  127. # Store all maps! This includes non existent maps,
  128. # identified by id == None
  129. map_name_list.append(maplist[0].get_name())
  130. # Attach the map names
  131. map_matrix.append(copy.copy(map_name_list))
  132. id_list.append(dataset.get_name())
  133. else:
  134. list = first_input.get_registered_maps_as_objects(dbif=dbif)
  135. if list is None:
  136. dbif.close()
  137. core.message(_("No maps in input dataset"))
  138. return 0
  139. map_name_list = []
  140. for map in list:
  141. map_name_list.append(map.get_name())
  142. sample_map_list.append(map)
  143. # Attach the map names
  144. map_matrix.append(copy.copy(map_name_list))
  145. # Needed for map registration
  146. map_list = []
  147. if len(map_matrix) > 0:
  148. core.message(_("Start mapcalc computation"))
  149. count = 0
  150. # Get the number of samples
  151. num = len(map_matrix[0])
  152. # Parallel processing
  153. proc_list = []
  154. proc_count = 0
  155. # For all samples
  156. for i in range(num):
  157. count += 1
  158. if count % 10 == 0:
  159. core.percent(count, num, 1)
  160. # Create the r.mapcalc statement for the current time step
  161. map_name = "%s_%i" % (base, count)
  162. # Remove spaces and new lines
  163. expr = expression.replace(" ", "")
  164. # Check that all maps are in the sample
  165. valid_maps = True
  166. # Replace all dataset names with their map names of the
  167. # current time step
  168. for j in range(len(map_matrix)):
  169. if map_matrix[j][i] is None:
  170. valid_maps = False
  171. break
  172. # Substitute the dataset name with the map name
  173. expr = expr.replace(id_list[j], map_matrix[j][i])
  174. # Proceed with the next sample
  175. if not valid_maps:
  176. continue
  177. # Create the new map id and check if the map is already
  178. # in the database
  179. map_id = map_name + "@" + mapset
  180. new_map = first_input.get_new_map_instance(map_id)
  181. # Check if new map is in the temporal database
  182. if new_map.is_in_db(dbif):
  183. if core.overwrite():
  184. # Remove the existing temporal database entry
  185. new_map.delete(dbif)
  186. new_map = first_input.get_new_map_instance(map_id)
  187. else:
  188. core.error(_("Map <%s> is already in temporal database, "
  189. "use overwrite flag to overwrite"))
  190. continue
  191. # Set the time stamp
  192. if sample_map_list[i].is_time_absolute():
  193. start, end, tz = sample_map_list[i].get_absolute_time()
  194. new_map.set_absolute_time(start, end, tz)
  195. else:
  196. start, end, unit = sample_map_list[i].get_relative_time()
  197. new_map.set_relative_time(start, end, unit)
  198. # Parse the temporal expressions
  199. expr = _operator_parser(expr, sample_map_list[0],
  200. sample_map_list[i])
  201. # Add the output map name
  202. expr = "%s=%s" % (map_name, expr)
  203. map_list.append(new_map)
  204. #core.verbose(_("Apply mapcalc expression: \"%s\"") % expr)
  205. # Start the parallel r.mapcalc computation
  206. if type == "raster":
  207. proc_list.append(Process(target=_run_mapcalc2d, args=(expr,)))
  208. else:
  209. proc_list.append(Process(target=_run_mapcalc3d, args=(expr,)))
  210. proc_list[proc_count].start()
  211. proc_count += 1
  212. if proc_count == nprocs or proc_count == num or count == num:
  213. proc_count = 0
  214. exitcodes = 0
  215. for proc in proc_list:
  216. proc.join()
  217. exitcodes += proc.exitcode
  218. if exitcodes != 0:
  219. dbif.close()
  220. core.fatal(_("Error while mapcalc computation"))
  221. # Empty process list
  222. proc_list = []
  223. # Register the new maps in the output space time dataset
  224. core.message(_("Start map registration in temporal database"))
  225. temporal_type, semantic_type, title, description = first_input.get_initial_values()
  226. new_sp = open_new_space_time_dataset(output, type,
  227. temporal_type, title, description,
  228. semantic_type, dbif,
  229. core.overwrite())
  230. count = 0
  231. # collect empty maps to remove them
  232. empty_maps = []
  233. # Insert maps in the temporal database and in the new space time
  234. # dataset
  235. for new_map in map_list:
  236. count += 1
  237. if count % 10 == 0:
  238. core.percent(count, num, 1)
  239. # Read the map data
  240. new_map.load()
  241. # In case of a null map continue, do not register null maps
  242. if new_map.metadata.get_min() is None and \
  243. new_map.metadata.get_max() is None:
  244. if not register_null:
  245. empty_maps.append(new_map)
  246. continue
  247. # Insert map in temporal database
  248. new_map.insert(dbif)
  249. new_sp.register_map(new_map, dbif)
  250. # Update the spatio-temporal extent and the metadata table entries
  251. new_sp.update_from_registered_maps(dbif)
  252. core.percent(1, 1, 1)
  253. # Remove empty maps
  254. if len(empty_maps) > 0:
  255. names = ""
  256. count = 0
  257. for map in empty_maps:
  258. if count == 0:
  259. names += "%s" % (map.get_name())
  260. else:
  261. names += ",%s" % (map.get_name())
  262. count += 1
  263. if type == "raster":
  264. core.run_command("g.remove", rast=names, quiet=True)
  265. elif type == "raster3d":
  266. core.run_command("g.remove", rast3d=names, quiet=True)
  267. dbif.close()
  268. ###############################################################################
  269. def _run_mapcalc2d(expr):
  270. """Helper function to run r.mapcalc in parallel"""
  271. return core.run_command("r.mapcalc", expression=expr,
  272. overwrite=core.overwrite(), quiet=True)
  273. ###############################################################################
  274. def _run_mapcalc3d(expr):
  275. """Helper function to run r3.mapcalc in parallel"""
  276. return core.run_command("r3.mapcalc", expression=expr,
  277. overwrite=core.overwrite(), quiet=True)
  278. ###############################################################################
  279. def _operator_parser(expr, first, current):
  280. """This method parses the expression string and substitutes
  281. the temporal operators with numerical values.
  282. Supported operators for relative and absolute time are:
  283. * td() - the time delta of the current interval in days
  284. and fractions of days or the unit in case of relative time
  285. * start_time() - The start time of the interval from the begin of the
  286. time series in days and fractions of days or the unit
  287. in case of relative time
  288. * end_time() - The end time of the current interval from the begin of
  289. the time series in days and fractions of days or the
  290. unit in case of relative time
  291. Supported operators for absolute time:
  292. * start_doy() - Day of year (doy) from the start time [1 - 366]
  293. * start_dow() - Day of week (dow) from the start time [1 - 7],
  294. the start of the week is monday == 1
  295. * start_year() - The year of the start time [0 - 9999]
  296. * start_month() - The month of the start time [1 - 12]
  297. * start_week() - Week of year of the start time [1 - 54]
  298. * start_day() - Day of month from the start time [1 - 31]
  299. * start_hour() - The hour of the start time [0 - 23]
  300. * start_minute() - The minute of the start time [0 - 59]
  301. * start_second() - The second of the start time [0 - 59]
  302. * end_doy() - Day of year (doy) from the end time [1 - 366]
  303. * end_dow() - Day of week (dow) from the end time [1 - 7],
  304. the start of the week is monday == 1
  305. * end_year() - The year of the end time [0 - 9999]
  306. * end_month() - The month of the end time [1 - 12]
  307. * end_week() - Week of year of the end time [1 - 54]
  308. * end_day() - Day of month from the end time [1 - 31]
  309. * end_hour() - The hour of the end time [0 - 23]
  310. * end_minute() - The minute of the end time [0 - 59]
  311. * end_second() - The minute of the end time [0 - 59]
  312. The modified expression is returned.
  313. """
  314. is_time_absolute = first.is_time_absolute()
  315. expr = _parse_td_operator(expr, is_time_absolute, first, current)
  316. expr = _parse_start_time_operator(expr, is_time_absolute, first, current)
  317. expr = _parse_end_time_operator(expr, is_time_absolute, first, current)
  318. expr = _parse_start_operators(expr, is_time_absolute, current)
  319. expr = _parse_end_operators(expr, is_time_absolute, current)
  320. return expr
  321. ###############################################################################
  322. def _parse_start_operators(expr, is_time_absolute, current):
  323. """
  324. Supported operators for absolute time:
  325. * start_doy() - Day of year (doy) from the start time [1 - 366]
  326. * start_dow() - Day of week (dow) from the start time [1 - 7],
  327. the start of the week is monday == 1
  328. * start_year() - The year of the start time [0 - 9999]
  329. * start_month() - The month of the start time [1 - 12]
  330. * start_week() - Week of year of the start time [1 - 54]
  331. * start_day() - Day of month from the start time [1 - 31]
  332. * start_hour() - The hour of the start time [0 - 23]
  333. * start_minute() - The minute of the start time [0 - 59]
  334. * start_second() - The second of the start time [0 - 59]
  335. """
  336. start, end, tz = current.get_absolute_time()
  337. if expr.find("start_year()") >= 0:
  338. if not is_time_absolute:
  339. core.fatal(_("The temporal operators <%s> supports only absolute"\
  340. "time." % ("start_*")))
  341. expr = expr.replace("start_year()", str(start.year))
  342. if expr.find("start_month()") >= 0:
  343. if not is_time_absolute:
  344. core.fatal(_("The temporal operators <%s> supports only absolute"\
  345. "time." % ("start_*")))
  346. expr = expr.replace("start_month()", str(start.month))
  347. if expr.find("start_week()") >= 0:
  348. if not is_time_absolute:
  349. core.fatal(_("The temporal operators <%s> supports only absolute"\
  350. "time." % ("start_*")))
  351. expr = expr.replace("start_week()", str(start.isocalendar()[1]))
  352. if expr.find("start_day()") >= 0:
  353. if not is_time_absolute:
  354. core.fatal(_("The temporal operators <%s> supports only absolute"\
  355. "time." % ("start_*")))
  356. expr = expr.replace("start_day()", str(start.day))
  357. if expr.find("start_hour()") >= 0:
  358. if not is_time_absolute:
  359. core.fatal(_("The temporal operators <%s> supports only absolute"\
  360. "time." % ("start_*")))
  361. expr = expr.replace("start_hour()", str(start.hour))
  362. if expr.find("start_minute()") >= 0:
  363. if not is_time_absolute:
  364. core.fatal(_("The temporal operators <%s> supports only absolute"\
  365. "time." % ("start_*")))
  366. expr = expr.replace("start_minute()", str(start.minute))
  367. if expr.find("start_second()") >= 0:
  368. if not is_time_absolute:
  369. core.fatal(_("The temporal operators <%s> supports only absolute"\
  370. "time." % ("start_*")))
  371. expr = expr.replace("start_second()", str(start.second))
  372. if expr.find("start_dow()") >= 0:
  373. if not is_time_absolute:
  374. core.fatal(_("The temporal operators <%s> supports only absolute"\
  375. "time." % ("start_*")))
  376. expr = expr.replace("start_dow()", str(start.isoweekday()))
  377. if expr.find("start_doy()") >= 0:
  378. if not is_time_absolute:
  379. core.fatal(_("The temporal operators <%s> supports only absolute"\
  380. "time." % ("start_*")))
  381. year = datetime(start.year, 1, 1)
  382. delta = start - year
  383. expr = expr.replace("start_doy()", str(delta.days + 1))
  384. return expr
  385. ###############################################################################
  386. def _parse_end_operators(expr, is_time_absolute, current):
  387. """
  388. Supported operators for absolute time:
  389. - end_doy() - Day of year (doy) from the end time [1 - 366]
  390. - end_dow() - Day of week (dow) from the end time [1 - 7],
  391. the start of the week is monday == 1
  392. - end_year() - The year of the end time [0 - 9999]
  393. - end_month() - The month of the end time [1 - 12]
  394. - end_week() - Week of year of the end time [1 - 54]
  395. - end_day() - Day of month from the end time [1 - 31]
  396. - end_hour() - The hour of the end time [0 - 23]
  397. - end_minute() - The minute of the end time [0 - 59]
  398. - end_second() - The minute of the end time [0 - 59]
  399. In case of time instances the end_* expression will be replaced by
  400. null()
  401. """
  402. start, end, tz = current.get_absolute_time()
  403. if expr.find("end_year()") >= 0:
  404. if not is_time_absolute:
  405. core.fatal(_("The temporal operators <%s> supports only absolute"\
  406. "time." % ("end_*")))
  407. if not end:
  408. expr = expr.replace("end_year()", "null()")
  409. else:
  410. expr = expr.replace("end_year()", str(end.year))
  411. if expr.find("end_month()") >= 0:
  412. if not is_time_absolute:
  413. core.fatal(_("The temporal operators <%s> supports only absolute"\
  414. "time." % ("end_*")))
  415. if not end:
  416. expr = expr.replace("end_month()", "null()")
  417. else:
  418. expr = expr.replace("end_month()", str(end.month))
  419. if expr.find("end_week()") >= 0:
  420. if not is_time_absolute:
  421. core.fatal(_("The temporal operators <%s> supports only absolute"\
  422. "time." % ("end_*")))
  423. if not end:
  424. expr = expr.replace("end_week()", "null()")
  425. else:
  426. expr = expr.replace("end_week()", str(end.isocalendar()[1]))
  427. if expr.find("end_day()") >= 0:
  428. if not is_time_absolute:
  429. core.fatal(_("The temporal operators <%s> supports only absolute"\
  430. "time." % ("end_*")))
  431. if not end:
  432. expr = expr.replace("end_day()", "null()")
  433. else:
  434. expr = expr.replace("end_day()", str(end.day))
  435. if expr.find("end_hour()") >= 0:
  436. if not is_time_absolute:
  437. core.fatal(_("The temporal operators <%s> supports only absolute"\
  438. "time." % ("end_*")))
  439. if not end:
  440. expr = expr.replace("end_hour()", "null()")
  441. else:
  442. expr = expr.replace("end_hour()", str(end.hour))
  443. if expr.find("end_minute()") >= 0:
  444. if not is_time_absolute:
  445. core.fatal(_("The temporal operators <%s> supports only absolute"\
  446. "time." % ("end_*")))
  447. if not end:
  448. expr = expr.replace("end_minute()", "null()")
  449. else:
  450. expr = expr.replace("end_minute()", str(end.minute))
  451. if expr.find("end_second()") >= 0:
  452. if not is_time_absolute:
  453. core.fatal(_("The temporal operators <%s> supports only absolute"\
  454. "time." % ("end_*")))
  455. if not end:
  456. expr = expr.replace("end_second()", "null()")
  457. else:
  458. expr = expr.replace("end_second()", str(end.second))
  459. if expr.find("end_dow()") >= 0:
  460. if not is_time_absolute:
  461. core.fatal(_("The temporal operators <%s> supports only absolute"\
  462. "time." % ("end_*")))
  463. if not end:
  464. expr = expr.replace("end_dow()", "null()")
  465. else:
  466. expr = expr.replace("end_dow()", str(end.isoweekday()))
  467. if expr.find("end_doy()") >= 0:
  468. if not is_time_absolute:
  469. core.fatal(_("The temporal operators <%s> supports only absolute"\
  470. "time." % ("end_*")))
  471. if not end:
  472. expr = expr.replace("end_doy()", "null()")
  473. else:
  474. year = datetime(end.year, 1, 1)
  475. delta = end - year
  476. expr = expr.replace("end_doy()", str(delta.days + 1))
  477. return expr
  478. ###############################################################################
  479. def _parse_td_operator(expr, is_time_absolute, first, current):
  480. """Parse the time delta operator td(). This operator
  481. represents the size of the current sample time interval
  482. in days and fraction of days for absolute time,
  483. and in relative units in case of relative time.
  484. In case of time instances, the td() operator will be of type null().
  485. """
  486. if expr.find("td()") >= 0:
  487. td = "null()"
  488. if is_time_absolute:
  489. start, end, tz = current.get_absolute_time()
  490. if end != None:
  491. td = time_delta_to_relative_time(end - start)
  492. else:
  493. start, end, unit = current.get_relative_time()
  494. if end != None:
  495. td = end - start
  496. expr = expr.replace("td()", str(td))
  497. return expr
  498. ###############################################################################
  499. def _parse_start_time_operator(expr, is_time_absolute, first, current):
  500. """Parse the start_time() operator. This operator represent
  501. the time difference between the start time of the sample space time
  502. raster dataset and the start time of the current sample interval or
  503. instance. The time is measured in days and fraction of days for absolute
  504. time, and in relative units in case of relative time."""
  505. if expr.find("start_time()") >= 0:
  506. if is_time_absolute:
  507. start1, end, tz = first.get_absolute_time()
  508. start, end, tz = current.get_absolute_time()
  509. x = time_delta_to_relative_time(start - start1)
  510. else:
  511. start1, end, unit = first.get_relative_time()
  512. start, end, unit = current.get_relative_time()
  513. x = start - start1
  514. expr = expr.replace("start_time()", str(x))
  515. return expr
  516. ###############################################################################
  517. def _parse_end_time_operator(expr, is_time_absolute, first, current):
  518. """Parse the end_time() operator. This operator represent
  519. the time difference between the start time of the sample space time
  520. raster dataset and the end time of the current sample interval. The time
  521. is measured in days and fraction of days for absolute time,
  522. and in relative units in case of relative time.
  523. The end_time() will be represented by null() in case of a time instance.
  524. """
  525. if expr.find("end_time()") >= 0:
  526. x = "null()"
  527. if is_time_absolute:
  528. start1, end, tz = first.get_absolute_time()
  529. start, end, tz = current.get_absolute_time()
  530. if end:
  531. x = time_delta_to_relative_time(end - start1)
  532. else:
  533. start1, end, unit = first.get_relative_time()
  534. start, end, unit = current.get_relative_time()
  535. if end:
  536. x = end - start1
  537. expr = expr.replace("end_time()", str(x))
  538. return expr