mapcalc.py 26 KB

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