mapcalc.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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) 2008-2011 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 import *
  12. from multiprocessing import Process
  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_space_time_dataset(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_space_time_dataset(input, type, dbif)
  79. input_list.append(copy.copy(sp))
  80. new_sp = check_new_space_time_dataset(output, type, dbif,
  81. core.overwrite())
  82. # Sample all inputs by the first input and create a sample matrix
  83. if spatial:
  84. msgr.message(_("Start spatio-temporal sampling"))
  85. else:
  86. msgr.message(_("Start 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 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(_("Start 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. core.percent(count, num, 1)
  161. # Create the r.mapcalc statement for the current time step
  162. map_name = "%s_%i" % (base, count)
  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 core.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, tz = sample_map_list[i].get_absolute_time()
  195. new_map.set_absolute_time(start, end, tz)
  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. core.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(_("Start map registration in temporal database"))
  226. temporal_type, semantic_type, title, description = first_input.get_initial_values()
  227. new_sp = open_new_space_time_dataset(output, type,
  228. temporal_type, title, description,
  229. semantic_type, dbif,
  230. core.overwrite())
  231. count = 0
  232. # collect empty maps to remove them
  233. empty_maps = []
  234. # Insert maps in the temporal database and in the new space time
  235. # dataset
  236. for new_map in map_list:
  237. count += 1
  238. if count % 10 == 0:
  239. core.percent(count, num, 1)
  240. # Read the map data
  241. new_map.load()
  242. # In case of a null map continue, do not register null maps
  243. if new_map.metadata.get_min() is None and \
  244. new_map.metadata.get_max() is None:
  245. if not register_null:
  246. empty_maps.append(new_map)
  247. continue
  248. # Insert map in temporal database
  249. new_map.insert(dbif)
  250. new_sp.register_map(new_map, dbif)
  251. # Update the spatio-temporal extent and the metadata table entries
  252. new_sp.update_from_registered_maps(dbif)
  253. core.percent(1, 1, 1)
  254. # Remove empty maps
  255. if len(empty_maps) > 0:
  256. names = ""
  257. count = 0
  258. for map in empty_maps:
  259. if count == 0:
  260. names += "%s" % (map.get_name())
  261. else:
  262. names += ",%s" % (map.get_name())
  263. count += 1
  264. if type == "raster":
  265. core.run_command("g.remove", rast=names, quiet=True)
  266. elif type == "raster3d":
  267. core.run_command("g.remove", rast3d=names, quiet=True)
  268. dbif.close()
  269. ###############################################################################
  270. def _run_mapcalc2d(expr):
  271. """Helper function to run r.mapcalc in parallel"""
  272. return core.run_command("r.mapcalc", expression=expr,
  273. overwrite=core.overwrite(), quiet=True)
  274. ###############################################################################
  275. def _run_mapcalc3d(expr):
  276. """Helper function to run r3.mapcalc in parallel"""
  277. return core.run_command("r3.mapcalc", expression=expr,
  278. overwrite=core.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, tz = current.get_absolute_time()
  338. if expr.find("start_year()") >= 0:
  339. if not is_time_absolute:
  340. core.fatal(_("The temporal operators <%s> supports only absolute"\
  341. "time." % ("start_*")))
  342. expr = expr.replace("start_year()", str(start.year))
  343. if expr.find("start_month()") >= 0:
  344. if not is_time_absolute:
  345. core.fatal(_("The temporal operators <%s> supports only absolute"\
  346. "time." % ("start_*")))
  347. expr = expr.replace("start_month()", str(start.month))
  348. if expr.find("start_week()") >= 0:
  349. if not is_time_absolute:
  350. core.fatal(_("The temporal operators <%s> supports only absolute"\
  351. "time." % ("start_*")))
  352. expr = expr.replace("start_week()", str(start.isocalendar()[1]))
  353. if expr.find("start_day()") >= 0:
  354. if not is_time_absolute:
  355. core.fatal(_("The temporal operators <%s> supports only absolute"\
  356. "time." % ("start_*")))
  357. expr = expr.replace("start_day()", str(start.day))
  358. if expr.find("start_hour()") >= 0:
  359. if not is_time_absolute:
  360. core.fatal(_("The temporal operators <%s> supports only absolute"\
  361. "time." % ("start_*")))
  362. expr = expr.replace("start_hour()", str(start.hour))
  363. if expr.find("start_minute()") >= 0:
  364. if not is_time_absolute:
  365. core.fatal(_("The temporal operators <%s> supports only absolute"\
  366. "time." % ("start_*")))
  367. expr = expr.replace("start_minute()", str(start.minute))
  368. if expr.find("start_second()") >= 0:
  369. if not is_time_absolute:
  370. core.fatal(_("The temporal operators <%s> supports only absolute"\
  371. "time." % ("start_*")))
  372. expr = expr.replace("start_second()", str(start.second))
  373. if expr.find("start_dow()") >= 0:
  374. if not is_time_absolute:
  375. core.fatal(_("The temporal operators <%s> supports only absolute"\
  376. "time." % ("start_*")))
  377. expr = expr.replace("start_dow()", str(start.isoweekday()))
  378. if expr.find("start_doy()") >= 0:
  379. if not is_time_absolute:
  380. core.fatal(_("The temporal operators <%s> supports only absolute"\
  381. "time." % ("start_*")))
  382. year = datetime(start.year, 1, 1)
  383. delta = start - year
  384. expr = expr.replace("start_doy()", str(delta.days + 1))
  385. return expr
  386. ###############################################################################
  387. def _parse_end_operators(expr, is_time_absolute, current):
  388. """
  389. Supported operators for absolute time:
  390. - end_doy() - Day of year (doy) from the end time [1 - 366]
  391. - end_dow() - Day of week (dow) from the end time [1 - 7],
  392. the start of the week is monday == 1
  393. - end_year() - The year of the end time [0 - 9999]
  394. - end_month() - The month of the end time [1 - 12]
  395. - end_week() - Week of year of the end time [1 - 54]
  396. - end_day() - Day of month from the end time [1 - 31]
  397. - end_hour() - The hour of the end time [0 - 23]
  398. - end_minute() - The minute of the end time [0 - 59]
  399. - end_second() - The minute of the end time [0 - 59]
  400. In case of time instances the end_* expression will be replaced by
  401. null()
  402. """
  403. start, end, tz = current.get_absolute_time()
  404. if expr.find("end_year()") >= 0:
  405. if not is_time_absolute:
  406. core.fatal(_("The temporal operators <%s> supports only absolute"\
  407. "time." % ("end_*")))
  408. if not end:
  409. expr = expr.replace("end_year()", "null()")
  410. else:
  411. expr = expr.replace("end_year()", str(end.year))
  412. if expr.find("end_month()") >= 0:
  413. if not is_time_absolute:
  414. core.fatal(_("The temporal operators <%s> supports only absolute"\
  415. "time." % ("end_*")))
  416. if not end:
  417. expr = expr.replace("end_month()", "null()")
  418. else:
  419. expr = expr.replace("end_month()", str(end.month))
  420. if expr.find("end_week()") >= 0:
  421. if not is_time_absolute:
  422. core.fatal(_("The temporal operators <%s> supports only absolute"\
  423. "time." % ("end_*")))
  424. if not end:
  425. expr = expr.replace("end_week()", "null()")
  426. else:
  427. expr = expr.replace("end_week()", str(end.isocalendar()[1]))
  428. if expr.find("end_day()") >= 0:
  429. if not is_time_absolute:
  430. core.fatal(_("The temporal operators <%s> supports only absolute"\
  431. "time." % ("end_*")))
  432. if not end:
  433. expr = expr.replace("end_day()", "null()")
  434. else:
  435. expr = expr.replace("end_day()", str(end.day))
  436. if expr.find("end_hour()") >= 0:
  437. if not is_time_absolute:
  438. core.fatal(_("The temporal operators <%s> supports only absolute"\
  439. "time." % ("end_*")))
  440. if not end:
  441. expr = expr.replace("end_hour()", "null()")
  442. else:
  443. expr = expr.replace("end_hour()", str(end.hour))
  444. if expr.find("end_minute()") >= 0:
  445. if not is_time_absolute:
  446. core.fatal(_("The temporal operators <%s> supports only absolute"\
  447. "time." % ("end_*")))
  448. if not end:
  449. expr = expr.replace("end_minute()", "null()")
  450. else:
  451. expr = expr.replace("end_minute()", str(end.minute))
  452. if expr.find("end_second()") >= 0:
  453. if not is_time_absolute:
  454. core.fatal(_("The temporal operators <%s> supports only absolute"\
  455. "time." % ("end_*")))
  456. if not end:
  457. expr = expr.replace("end_second()", "null()")
  458. else:
  459. expr = expr.replace("end_second()", str(end.second))
  460. if expr.find("end_dow()") >= 0:
  461. if not is_time_absolute:
  462. core.fatal(_("The temporal operators <%s> supports only absolute"\
  463. "time." % ("end_*")))
  464. if not end:
  465. expr = expr.replace("end_dow()", "null()")
  466. else:
  467. expr = expr.replace("end_dow()", str(end.isoweekday()))
  468. if expr.find("end_doy()") >= 0:
  469. if not is_time_absolute:
  470. core.fatal(_("The temporal operators <%s> supports only absolute"\
  471. "time." % ("end_*")))
  472. if not end:
  473. expr = expr.replace("end_doy()", "null()")
  474. else:
  475. year = datetime(end.year, 1, 1)
  476. delta = end - year
  477. expr = expr.replace("end_doy()", str(delta.days + 1))
  478. return expr
  479. ###############################################################################
  480. def _parse_td_operator(expr, is_time_absolute, first, current):
  481. """Parse the time delta operator td(). This operator
  482. represents the size of the current sample time interval
  483. in days and fraction of days for absolute time,
  484. and in relative units in case of relative time.
  485. In case of time instances, the td() operator will be of type null().
  486. """
  487. if expr.find("td()") >= 0:
  488. td = "null()"
  489. if is_time_absolute:
  490. start, end, tz = current.get_absolute_time()
  491. if end != None:
  492. td = time_delta_to_relative_time(end - start)
  493. else:
  494. start, end, unit = current.get_relative_time()
  495. if end != None:
  496. td = end - start
  497. expr = expr.replace("td()", str(td))
  498. return expr
  499. ###############################################################################
  500. def _parse_start_time_operator(expr, is_time_absolute, first, current):
  501. """Parse the start_time() operator. This operator represent
  502. the time difference between the start time of the sample space time
  503. raster dataset and the start time of the current sample interval or
  504. instance. The time is measured in days and fraction of days for absolute
  505. time, and in relative units in case of relative time."""
  506. if expr.find("start_time()") >= 0:
  507. if is_time_absolute:
  508. start1, end, tz = first.get_absolute_time()
  509. start, end, tz = current.get_absolute_time()
  510. x = time_delta_to_relative_time(start - start1)
  511. else:
  512. start1, end, unit = first.get_relative_time()
  513. start, end, unit = current.get_relative_time()
  514. x = start - start1
  515. expr = expr.replace("start_time()", str(x))
  516. return expr
  517. ###############################################################################
  518. def _parse_end_time_operator(expr, is_time_absolute, first, current):
  519. """Parse the end_time() operator. This operator represent
  520. the time difference between the start time of the sample space time
  521. raster dataset and the end time of the current sample interval. The time
  522. is measured in days and fraction of days for absolute time,
  523. and in relative units in case of relative time.
  524. The end_time() will be represented by null() in case of a time instance.
  525. """
  526. if expr.find("end_time()") >= 0:
  527. x = "null()"
  528. if is_time_absolute:
  529. start1, end, tz = first.get_absolute_time()
  530. start, end, tz = current.get_absolute_time()
  531. if end:
  532. x = time_delta_to_relative_time(end - start1)
  533. else:
  534. start1, end, unit = first.get_relative_time()
  535. start, end, unit = current.get_relative_time()
  536. if end:
  537. x = end - start1
  538. expr = expr.replace("end_time()", str(x))
  539. return expr