mapcalc.py 26 KB

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