mapcalc.py 27 KB

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