mapcalc.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  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(semantic_label=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 or len(list) < 1:
  168. dbif.close()
  169. msgr.message(
  170. _("No maps registered in input dataset <{}>").format(
  171. dataset.get_name()
  172. )
  173. )
  174. return 0
  175. map_name_list = []
  176. for map in list:
  177. map_name_list.append(map.get_name())
  178. sample_map_list.append(map)
  179. # Attach the map names
  180. map_matrix.append(copy.copy(map_name_list))
  181. id_list.append(dataset.get_name())
  182. # Needed for map registration
  183. map_list = []
  184. if len(map_matrix) > 0:
  185. msgr.message(_("Starting mapcalc computation..."))
  186. count = 0
  187. # Get the number of samples
  188. num = len(map_matrix[0])
  189. # Parallel processing
  190. proc_list = []
  191. proc_count = 0
  192. # For all samples
  193. for i in range(num):
  194. count += 1
  195. msgr.percent(count, num, 10)
  196. # Create the r.mapcalc statement for the current time step
  197. map_name = "{base}_{suffix}".format(
  198. base=base, suffix=gscript.get_num_suffix(count, num)
  199. )
  200. # Remove spaces and new lines
  201. expr = expression.replace(" ", "")
  202. # Check that all maps are in the sample
  203. valid_maps = True
  204. # Replace all dataset names with their map names of the
  205. # current time step
  206. for j in range(len(map_matrix)):
  207. if map_matrix[j][i] is None:
  208. valid_maps = False
  209. break
  210. # Substitute the dataset name with the map name
  211. expr = expr.replace(id_list[j], map_matrix[j][i])
  212. # Proceed with the next sample
  213. if not valid_maps:
  214. continue
  215. # Create the new map id and check if the map is already
  216. # in the database
  217. map_id = map_name + "@" + mapset
  218. new_map = first_input.get_new_map_instance(map_id)
  219. # Check if new map is in the temporal database
  220. if new_map.is_in_db(dbif):
  221. if gscript.overwrite():
  222. # Remove the existing temporal database entry
  223. new_map.delete(dbif)
  224. new_map = first_input.get_new_map_instance(map_id)
  225. else:
  226. msgr.error(
  227. _(
  228. "Map <%s> is already in temporal database, "
  229. "use overwrite flag to overwrite"
  230. )
  231. )
  232. continue
  233. # Set the time stamp
  234. if sample_map_list[i].is_time_absolute():
  235. start, end = sample_map_list[i].get_absolute_time()
  236. new_map.set_absolute_time(start, end)
  237. else:
  238. start, end, unit = sample_map_list[i].get_relative_time()
  239. new_map.set_relative_time(start, end, unit)
  240. # Parse the temporal expressions
  241. expr = _operator_parser(expr, sample_map_list[0], sample_map_list[i])
  242. # Add the output map name
  243. expr = "%s=%s" % (map_name, expr)
  244. map_list.append(new_map)
  245. msgr.verbose(_('Apply mapcalc expression: "%s"') % expr)
  246. # Start the parallel r.mapcalc computation
  247. if type == "raster":
  248. proc_list.append(Process(target=_run_mapcalc2d, args=(expr,)))
  249. else:
  250. proc_list.append(Process(target=_run_mapcalc3d, args=(expr,)))
  251. proc_list[proc_count].start()
  252. proc_count += 1
  253. if proc_count == nprocs or proc_count == num or count == num:
  254. proc_count = 0
  255. exitcodes = 0
  256. for proc in proc_list:
  257. proc.join()
  258. exitcodes += proc.exitcode
  259. if exitcodes != 0:
  260. dbif.close()
  261. msgr.fatal(_("Error while mapcalc computation"))
  262. # Empty process list
  263. proc_list = []
  264. # Register the new maps in the output space time dataset
  265. msgr.message(_("Starting map registration in temporal database..."))
  266. (
  267. temporal_type,
  268. semantic_type,
  269. title,
  270. description,
  271. ) = first_input.get_initial_values()
  272. new_sp = open_new_stds(
  273. output,
  274. type,
  275. temporal_type,
  276. title,
  277. description,
  278. semantic_type,
  279. dbif,
  280. gscript.overwrite(),
  281. )
  282. count = 0
  283. # collect empty maps to remove them
  284. empty_maps = []
  285. # Insert maps in the temporal database and in the new space time
  286. # dataset
  287. for new_map in map_list:
  288. count += 1
  289. msgr.percent(count, num, 10)
  290. # Read the map data
  291. new_map.load()
  292. # In case of a null map continue, do not register null maps
  293. if (
  294. new_map.metadata.get_min() is None
  295. and new_map.metadata.get_max() is None
  296. ):
  297. if not register_null:
  298. empty_maps.append(new_map)
  299. continue
  300. # Insert map in temporal database
  301. new_map.insert(dbif)
  302. new_sp.register_map(new_map, dbif)
  303. # Update the spatio-temporal extent and the metadata table entries
  304. new_sp.update_from_registered_maps(dbif)
  305. # Remove empty maps
  306. if len(empty_maps) > 0:
  307. n_empty, n_tot = len(empty_maps), len(map_list)
  308. msgr.warning(
  309. _("Removing {}/{} ({}%) maps because empty...").format(
  310. n_empty, n_tot, n_empty * 100.0 / n_tot
  311. )
  312. )
  313. names = ""
  314. count = 0
  315. for map in empty_maps:
  316. if count == 0:
  317. names += "%s" % (map.get_name())
  318. else:
  319. names += ",%s" % (map.get_name())
  320. count += 1
  321. if type == "raster":
  322. gscript.run_command(
  323. "g.remove", flags="f", type="raster", name=names, quiet=True
  324. )
  325. elif type == "raster3d":
  326. gscript.run_command(
  327. "g.remove", flags="f", type="raster_3d", name=names, quiet=True
  328. )
  329. dbif.close()
  330. ###############################################################################
  331. def _run_mapcalc2d(expr):
  332. """Helper function to run r.mapcalc in parallel"""
  333. try:
  334. gscript.run_command(
  335. "r.mapcalc", expression=expr, overwrite=gscript.overwrite(), quiet=True
  336. )
  337. except CalledModuleError:
  338. exit(1)
  339. ###############################################################################
  340. def _run_mapcalc3d(expr):
  341. """Helper function to run r3.mapcalc in parallel"""
  342. try:
  343. gscript.run_command(
  344. "r3.mapcalc", expression=expr, overwrite=gscript.overwrite(), quiet=True
  345. )
  346. except CalledModuleError:
  347. exit(1)
  348. ###############################################################################
  349. def _operator_parser(expr, first, current):
  350. """This method parses the expression string and substitutes
  351. the temporal operators with numerical values.
  352. Supported operators for relative and absolute time are:
  353. - td() - the time delta of the current interval in days
  354. and fractions of days or the unit in case of relative time
  355. - start_time() - The start time of the interval from the begin of the
  356. time series in days and fractions of days or the unit
  357. in case of relative time
  358. - end_time() - The end time of the current interval from the begin of
  359. the time series in days and fractions of days or the
  360. unit in case of relative time
  361. Supported operators for absolute time:
  362. - start_doy() - Day of year (doy) from the start time [1 - 366]
  363. - start_dow() - Day of week (dow) from the start time [1 - 7],
  364. the start of the week is monday == 1
  365. - start_year() - The year of the start time [0 - 9999]
  366. - start_month() - The month of the start time [1 - 12]
  367. - start_week() - Week of year of the start time [1 - 54]
  368. - start_day() - Day of month from the start time [1 - 31]
  369. - start_hour() - The hour of the start time [0 - 23]
  370. - start_minute() - The minute of the start time [0 - 59]
  371. - start_second() - The second of the start time [0 - 59]
  372. - end_doy() - Day of year (doy) from the end time [1 - 366]
  373. - end_dow() - Day of week (dow) from the end time [1 - 7],
  374. the start of the week is monday == 1
  375. - end_year() - The year of the end time [0 - 9999]
  376. - end_month() - The month of the end time [1 - 12]
  377. - end_week() - Week of year of the end time [1 - 54]
  378. - end_day() - Day of month from the end time [1 - 31]
  379. - end_hour() - The hour of the end time [0 - 23]
  380. - end_minute() - The minute of the end time [0 - 59]
  381. - end_second() - The minute of the end time [0 - 59]
  382. The modified expression is returned.
  383. """
  384. is_time_absolute = first.is_time_absolute()
  385. expr = _parse_td_operator(expr, is_time_absolute, first, current)
  386. expr = _parse_start_time_operator(expr, is_time_absolute, first, current)
  387. expr = _parse_end_time_operator(expr, is_time_absolute, first, current)
  388. expr = _parse_start_operators(expr, is_time_absolute, current)
  389. expr = _parse_end_operators(expr, is_time_absolute, current)
  390. return expr
  391. ###############################################################################
  392. def _parse_start_operators(expr, is_time_absolute, current):
  393. """
  394. Supported operators for absolute time:
  395. - start_doy() - Day of year (doy) from the start time [1 - 366]
  396. - start_dow() - Day of week (dow) from the start time [1 - 7],
  397. the start of the week is monday == 1
  398. - start_year() - The year of the start time [0 - 9999]
  399. - start_month() - The month of the start time [1 - 12]
  400. - start_week() - Week of year of the start time [1 - 54]
  401. - start_day() - Day of month from the start time [1 - 31]
  402. - start_hour() - The hour of the start time [0 - 23]
  403. - start_minute() - The minute of the start time [0 - 59]
  404. - start_second() - The second of the start time [0 - 59]
  405. """
  406. start, end = current.get_absolute_time()
  407. msgr = get_tgis_message_interface()
  408. if expr.find("start_year()") >= 0:
  409. if not is_time_absolute:
  410. msgr.fatal(
  411. _(
  412. "The temporal operators <%s> support only absolute "
  413. "time." % ("start_*")
  414. )
  415. )
  416. expr = expr.replace("start_year()", str(start.year))
  417. if expr.find("start_month()") >= 0:
  418. if not is_time_absolute:
  419. msgr.fatal(
  420. _(
  421. "The temporal operators <%s> support only absolute "
  422. "time." % ("start_*")
  423. )
  424. )
  425. expr = expr.replace("start_month()", str(start.month))
  426. if expr.find("start_week()") >= 0:
  427. if not is_time_absolute:
  428. msgr.fatal(
  429. _(
  430. "The temporal operators <%s> support only absolute "
  431. "time." % ("start_*")
  432. )
  433. )
  434. expr = expr.replace("start_week()", str(start.isocalendar()[1]))
  435. if expr.find("start_day()") >= 0:
  436. if not is_time_absolute:
  437. msgr.fatal(
  438. _(
  439. "The temporal operators <%s> support only absolute "
  440. "time." % ("start_*")
  441. )
  442. )
  443. expr = expr.replace("start_day()", str(start.day))
  444. if expr.find("start_hour()") >= 0:
  445. if not is_time_absolute:
  446. msgr.fatal(
  447. _(
  448. "The temporal operators <%s> support only absolute "
  449. "time." % ("start_*")
  450. )
  451. )
  452. expr = expr.replace("start_hour()", str(start.hour))
  453. if expr.find("start_minute()") >= 0:
  454. if not is_time_absolute:
  455. msgr.fatal(
  456. _(
  457. "The temporal operators <%s> support only absolute "
  458. "time." % ("start_*")
  459. )
  460. )
  461. expr = expr.replace("start_minute()", str(start.minute))
  462. if expr.find("start_second()") >= 0:
  463. if not is_time_absolute:
  464. msgr.fatal(
  465. _(
  466. "The temporal operators <%s> support only absolute "
  467. "time." % ("start_*")
  468. )
  469. )
  470. expr = expr.replace("start_second()", str(start.second))
  471. if expr.find("start_dow()") >= 0:
  472. if not is_time_absolute:
  473. msgr.fatal(
  474. _(
  475. "The temporal operators <%s> support only absolute "
  476. "time." % ("start_*")
  477. )
  478. )
  479. expr = expr.replace("start_dow()", str(start.isoweekday()))
  480. if expr.find("start_doy()") >= 0:
  481. if not is_time_absolute:
  482. msgr.fatal(
  483. _(
  484. "The temporal operators <%s> support only absolute "
  485. "time." % ("start_*")
  486. )
  487. )
  488. year = datetime(start.year, 1, 1)
  489. delta = start - year
  490. expr = expr.replace("start_doy()", str(delta.days + 1))
  491. return expr
  492. ###############################################################################
  493. def _parse_end_operators(expr, is_time_absolute, current):
  494. """
  495. Supported operators for absolute time:
  496. - end_doy() - Day of year (doy) from the end time [1 - 366]
  497. - end_dow() - Day of week (dow) from the end time [1 - 7],
  498. the start of the week is monday == 1
  499. - end_year() - The year of the end time [0 - 9999]
  500. - end_month() - The month of the end time [1 - 12]
  501. - end_week() - Week of year of the end time [1 - 54]
  502. - end_day() - Day of month from the end time [1 - 31]
  503. - end_hour() - The hour of the end time [0 - 23]
  504. - end_minute() - The minute of the end time [0 - 59]
  505. - end_second() - The minute of the end time [0 - 59]
  506. In case of time instances the end* expression will be replaced by
  507. null()
  508. """
  509. start, end = current.get_absolute_time()
  510. msgr = get_tgis_message_interface()
  511. if expr.find("end_year()") >= 0:
  512. if not is_time_absolute:
  513. msgr.fatal(
  514. _(
  515. "The temporal operators <%s> support only absolute "
  516. "time." % ("end_*")
  517. )
  518. )
  519. if not end:
  520. expr = expr.replace("end_year()", "null()")
  521. else:
  522. expr = expr.replace("end_year()", str(end.year))
  523. if expr.find("end_month()") >= 0:
  524. if not is_time_absolute:
  525. msgr.fatal(
  526. _(
  527. "The temporal operators <%s> support only absolute "
  528. "time." % ("end_*")
  529. )
  530. )
  531. if not end:
  532. expr = expr.replace("end_month()", "null()")
  533. else:
  534. expr = expr.replace("end_month()", str(end.month))
  535. if expr.find("end_week()") >= 0:
  536. if not is_time_absolute:
  537. msgr.fatal(
  538. _(
  539. "The temporal operators <%s> support only absolute "
  540. "time." % ("end_*")
  541. )
  542. )
  543. if not end:
  544. expr = expr.replace("end_week()", "null()")
  545. else:
  546. expr = expr.replace("end_week()", str(end.isocalendar()[1]))
  547. if expr.find("end_day()") >= 0:
  548. if not is_time_absolute:
  549. msgr.fatal(
  550. _(
  551. "The temporal operators <%s> support only absolute "
  552. "time." % ("end_*")
  553. )
  554. )
  555. if not end:
  556. expr = expr.replace("end_day()", "null()")
  557. else:
  558. expr = expr.replace("end_day()", str(end.day))
  559. if expr.find("end_hour()") >= 0:
  560. if not is_time_absolute:
  561. msgr.fatal(
  562. _(
  563. "The temporal operators <%s> support only absolute "
  564. "time." % ("end_*")
  565. )
  566. )
  567. if not end:
  568. expr = expr.replace("end_hour()", "null()")
  569. else:
  570. expr = expr.replace("end_hour()", str(end.hour))
  571. if expr.find("end_minute()") >= 0:
  572. if not is_time_absolute:
  573. msgr.fatal(
  574. _(
  575. "The temporal operators <%s> support only absolute "
  576. "time." % ("end_*")
  577. )
  578. )
  579. if not end:
  580. expr = expr.replace("end_minute()", "null()")
  581. else:
  582. expr = expr.replace("end_minute()", str(end.minute))
  583. if expr.find("end_second()") >= 0:
  584. if not is_time_absolute:
  585. msgr.fatal(
  586. _(
  587. "The temporal operators <%s> support only absolute "
  588. "time." % ("end_*")
  589. )
  590. )
  591. if not end:
  592. expr = expr.replace("end_second()", "null()")
  593. else:
  594. expr = expr.replace("end_second()", str(end.second))
  595. if expr.find("end_dow()") >= 0:
  596. if not is_time_absolute:
  597. msgr.fatal(
  598. _(
  599. "The temporal operators <%s> support only absolute "
  600. "time." % ("end_*")
  601. )
  602. )
  603. if not end:
  604. expr = expr.replace("end_dow()", "null()")
  605. else:
  606. expr = expr.replace("end_dow()", str(end.isoweekday()))
  607. if expr.find("end_doy()") >= 0:
  608. if not is_time_absolute:
  609. msgr.fatal(
  610. _(
  611. "The temporal operators <%s> support only absolute "
  612. "time." % ("end_*")
  613. )
  614. )
  615. if not end:
  616. expr = expr.replace("end_doy()", "null()")
  617. else:
  618. year = datetime(end.year, 1, 1)
  619. delta = end - year
  620. expr = expr.replace("end_doy()", str(delta.days + 1))
  621. return expr
  622. ###############################################################################
  623. def _parse_td_operator(expr, is_time_absolute, first, current):
  624. """Parse the time delta operator td(). This operator
  625. represents the size of the current sample time interval
  626. in days and fraction of days for absolute time,
  627. and in relative units in case of relative time.
  628. In case of time instances, the td() operator will be of type null().
  629. """
  630. if expr.find("td()") >= 0:
  631. td = "null()"
  632. if is_time_absolute:
  633. start, end = current.get_absolute_time()
  634. if end is not None:
  635. td = time_delta_to_relative_time(end - start)
  636. else:
  637. start, end, unit = current.get_relative_time()
  638. if end is not None:
  639. td = end - start
  640. expr = expr.replace("td()", str(td))
  641. return expr
  642. ###############################################################################
  643. def _parse_start_time_operator(expr, is_time_absolute, first, current):
  644. """Parse the start_time() operator. This operator represent
  645. the time difference between the start time of the sample space time
  646. raster dataset and the start time of the current sample interval or
  647. instance. The time is measured in days and fraction of days for absolute
  648. time, and in relative units in case of relative time."""
  649. if expr.find("start_time()") >= 0:
  650. if is_time_absolute:
  651. start1, end = first.get_absolute_time()
  652. start, end = current.get_absolute_time()
  653. x = time_delta_to_relative_time(start - start1)
  654. else:
  655. start1, end, unit = first.get_relative_time()
  656. start, end, unit = current.get_relative_time()
  657. x = start - start1
  658. expr = expr.replace("start_time()", str(x))
  659. return expr
  660. ###############################################################################
  661. def _parse_end_time_operator(expr, is_time_absolute, first, current):
  662. """Parse the end_time() operator. This operator represent
  663. the time difference between the start time of the sample space time
  664. raster dataset and the end time of the current sample interval. The time
  665. is measured in days and fraction of days for absolute time,
  666. and in relative units in case of relative time.
  667. The end_time() will be represented by null() in case of a time instance.
  668. """
  669. if expr.find("end_time()") >= 0:
  670. x = "null()"
  671. if is_time_absolute:
  672. start1, end = first.get_absolute_time()
  673. start, end = current.get_absolute_time()
  674. if end:
  675. x = time_delta_to_relative_time(end - start1)
  676. else:
  677. start1, end, unit = first.get_relative_time()
  678. start, end, unit = current.get_relative_time()
  679. if end:
  680. x = end - start1
  681. expr = expr.replace("end_time()", str(x))
  682. return expr