mapcalc.py 27 KB

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