mapcalc.py 28 KB

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