mapcalc.py 26 KB

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