mapcalc.py 28 KB

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