stds_import.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. """
  2. Space time dataset import functions
  3. Usage:
  4. .. code-block:: python
  5. import grass.temporal as tgis
  6. input="/tmp/temp_1950_2012.tar.gz"
  7. output="temp_1950_2012"
  8. directory="/tmp"
  9. title="My new dataset"
  10. descr="May new shiny dataset"
  11. location=None
  12. link=True
  13. exp=True
  14. overr=False
  15. create=False
  16. tgis.import_stds(input, output, directory, title, descr, location,
  17. link, exp, overr, create, "strds")
  18. (C) 2012-2013 by the GRASS Development Team
  19. This program is free software under the GNU General Public
  20. License (>=v2). Read the file COPYING that comes with GRASS
  21. for details.
  22. :authors: Soeren Gebbert
  23. """
  24. import os
  25. import os.path
  26. import tarfile
  27. from space_time_datasets import *
  28. from register import *
  29. import factory
  30. from factory import *
  31. import grass.script as gscript
  32. from grass.exceptions import CalledModuleError
  33. proj_file_name = "proj.txt"
  34. init_file_name = "init.txt"
  35. list_file_name = "list.txt"
  36. # This global variable is for unique vector map export,
  37. # since single vector maps may have several layer
  38. # and therefore several attribute tables
  39. imported_maps = {}
  40. ############################################################################
  41. def _import_raster_maps_from_gdal(maplist, overr, exp, location, link, format_,
  42. set_current_region=False):
  43. impflags = ""
  44. if overr:
  45. impflags += "o"
  46. if exp or location:
  47. impflags += "e"
  48. for row in maplist:
  49. name = row["name"]
  50. if format_ == "GTiff":
  51. filename = row["filename"] + ".tif"
  52. elif format_ == "AAIGrid":
  53. filename = row["filename"] + ".asc"
  54. if not overr:
  55. impflags += "o"
  56. try:
  57. if link:
  58. gscript.run_command("r.external", input=filename,
  59. output=name,
  60. flags=impflags,
  61. overwrite=gscript.overwrite())
  62. else:
  63. gscript.run_command("r.in.gdal", input=filename,
  64. output=name,
  65. flags=impflags,
  66. overwrite=gscript.overwrite())
  67. except CalledModuleError:
  68. gscript.fatal(_("Unable to import/link raster map <%s> from file"
  69. " %s.") % (name, filename))
  70. # Set the color rules if present
  71. filename = row["filename"] + ".color"
  72. if os.path.isfile(filename):
  73. try:
  74. gscript.run_command("r.colors", map=name,
  75. rules=filename,
  76. overwrite=gscript.overwrite())
  77. except CalledModuleError:
  78. gscript.fatal(_("Unable to set the color rules for "
  79. "raster map <%s>.") % name)
  80. # Set the computational region from the last map imported
  81. if set_current_region is True:
  82. gscript.run_command("g.region", raster=name)
  83. ############################################################################
  84. def _import_raster_maps(maplist, set_current_region=False):
  85. # We need to disable the projection check because of its
  86. # simple implementation
  87. impflags = "o"
  88. for row in maplist:
  89. name = row["name"]
  90. filename = row["filename"] + ".pack"
  91. try:
  92. gscript.run_command("r.unpack", input=filename,
  93. output=name, flags=impflags,
  94. overwrite=gscript.overwrite(),
  95. verbose=True)
  96. except CalledModuleError:
  97. gscript.fatal(_("Unable to unpack raster map <%s> from file "
  98. "%s.") % (name, filename))
  99. # Set the computational region from the last map imported
  100. if set_current_region is True:
  101. gscript.run_command("g.region", raster=name)
  102. ############################################################################
  103. def _import_vector_maps_from_gml(maplist, overr, exp, location, link):
  104. impflags = "o"
  105. if exp or location:
  106. impflags += "e"
  107. for row in maplist:
  108. name = row["name"]
  109. filename = row["filename"] + ".xml"
  110. try:
  111. gscript.run_command("v.in.ogr", input=filename,
  112. output=name, flags=impflags,
  113. overwrite=gscript.overwrite())
  114. except CalledModuleError:
  115. gscript.fatal(_("Unable to import vector map <%s> from file "
  116. "%s.") % (name, filename))
  117. ############################################################################
  118. def _import_vector_maps(maplist):
  119. # We need to disable the projection check because of its
  120. # simple implementation
  121. impflags = "o"
  122. for row in maplist:
  123. # Separate the name from the layer
  124. name = row["name"].split(":")[0]
  125. # Import only unique maps
  126. if name in imported_maps:
  127. continue
  128. filename = row["filename"] + ".pack"
  129. try:
  130. gscript.run_command("v.unpack", input=filename,
  131. output=name, flags=impflags,
  132. overwrite=gscript.overwrite(),
  133. verbose=True)
  134. except CalledModuleError:
  135. gscript.fatal(_("Unable to unpack vector map <%s> from file "
  136. "%s.") % (name, filename))
  137. imported_maps[name] = name
  138. ############################################################################
  139. def import_stds(input, output, directory, title=None, descr=None, location=None,
  140. link=False, exp=False, overr=False, create=False,
  141. stds_type="strds", base=None, set_current_region=False):
  142. """Import space time datasets of type raster and vector
  143. :param input: Name of the input archive file
  144. :param output: The name of the output space time dataset
  145. :param directory: The extraction directory
  146. :param title: The title of the new created space time dataset
  147. :param descr: The description of the new created
  148. space time dataset
  149. :param location: The name of the location that should be created,
  150. maps are imported into this location
  151. :param link: Switch to link raster maps instead importing them
  152. :param exp: Extend location extents based on new dataset
  153. :param overr: Override projection (use location's projection)
  154. :param create: Create the location specified by the "location"
  155. parameter and exit.
  156. Do not import the space time datasets.
  157. :param stds_type: The type of the space time dataset that
  158. should be imported
  159. :param base: The base name of the new imported maps, it will be
  160. extended using a numerical index.
  161. """
  162. global raise_on_error
  163. old_state = gscript.raise_on_error
  164. gscript.set_raise_on_error(True)
  165. # Check if input file and extraction directory exits
  166. if not os.path.exists(input):
  167. gscript.fatal(_("Space time raster dataset archive <%s> not found")
  168. % input)
  169. if not create and not os.path.exists(directory):
  170. gscript.fatal(_("Extraction directory <%s> not found") % directory)
  171. tar = tarfile.open(name=input, mode='r')
  172. # Check for important files
  173. members = tar.getnames()
  174. # Make sure that the basenames of the files are used for comparison
  175. member_basenames = [os.path.basename(name) for name in members]
  176. if init_file_name not in member_basenames:
  177. gscript.fatal(_("Unable to find init file <%s>") % init_file_name)
  178. if list_file_name not in member_basenames:
  179. gscript.fatal(_("Unable to find list file <%s>") % list_file_name)
  180. if proj_file_name not in member_basenames:
  181. gscript.fatal(_("Unable to find projection file <%s>") % proj_file_name)
  182. tar.extractall(path=directory)
  183. tar.close()
  184. # We use a new list file name for map registration
  185. new_list_file_name = list_file_name + "_new"
  186. # Save current working directory path
  187. old_cwd = os.getcwd()
  188. # Switch into the data directory
  189. os.chdir(directory)
  190. # Check projection information
  191. if not location:
  192. temp_name = gscript.tempfile()
  193. temp_file = open(temp_name, "w")
  194. proj_name = os.path.abspath(proj_file_name)
  195. # We need to convert projection strings generated
  196. # from other programms than g.proj into
  197. # new line format so that the grass file comparison function
  198. # can be used to compare the projections
  199. proj_name_tmp = temp_name + "_in_projection"
  200. proj_file = open(proj_name, "r")
  201. proj_content = proj_file.read()
  202. proj_content = proj_content.replace(" +", "\n+")
  203. proj_content = proj_content.replace("\t+", "\n+")
  204. proj_file.close()
  205. proj_file = open(proj_name_tmp, "w")
  206. proj_file.write(proj_content)
  207. proj_file.close()
  208. p = gscript.start_command("g.proj", flags="j", stdout=temp_file)
  209. p.communicate()
  210. temp_file.close()
  211. if not gscript.compare_key_value_text_files(temp_name, proj_name_tmp,
  212. sep="="):
  213. if overr:
  214. gscript.warning(_("Projection information does not match. "
  215. "Proceeding..."))
  216. else:
  217. diff = ''.join(gscript.diff_files(temp_name, proj_name))
  218. gscript.warning(_("Difference between PROJ_INFO file of "
  219. "imported map and of current location:"
  220. "\n{diff}").format(diff=diff))
  221. gscript.fatal(_("Projection information does not match. "
  222. "Aborting."))
  223. # Create a new location based on the projection information and switch
  224. # into it
  225. old_env = gscript.gisenv()
  226. if location:
  227. try:
  228. proj4_string = open(proj_file_name, 'r').read()
  229. gscript.create_location(dbase=old_env["GISDBASE"],
  230. location=location,
  231. proj4=proj4_string)
  232. # Just create a new location and return
  233. if create:
  234. os.chdir(old_cwd)
  235. return
  236. except Exception as e:
  237. gscript.fatal(_("Unable to create location %(l)s. Reason: %(e)s")
  238. % {'l': location, 'e': str(e)})
  239. # Switch to the new created location
  240. try:
  241. gscript.run_command("g.mapset", mapset="PERMANENT",
  242. location=location,
  243. dbase=old_env["GISDBASE"])
  244. except CalledModuleError:
  245. gscript.fatal(_("Unable to switch to location %s") % location)
  246. # create default database connection
  247. try:
  248. gscript.run_command("t.connect", flags="d")
  249. except CalledModuleError:
  250. gscript.fatal(_("Unable to create default temporal database "
  251. "in new location %s") % location)
  252. try:
  253. # Make sure the temporal database exists
  254. factory.init()
  255. fs = "|"
  256. maplist = []
  257. mapset = get_current_mapset()
  258. list_file = open(list_file_name, "r")
  259. new_list_file = open(new_list_file_name, "w")
  260. # get number of lines to correctly form the suffix
  261. max_count = -1
  262. for max_count, l in enumerate(list_file):
  263. pass
  264. max_count += 1
  265. list_file.seek(0)
  266. # Read the map list from file
  267. line_count = 0
  268. while True:
  269. line = list_file.readline()
  270. if not line:
  271. break
  272. line_list = line.split(fs)
  273. # The filename is actually the base name of the map
  274. # that must be extended by the file suffix
  275. filename = line_list[0].strip().split(":")[0]
  276. if base:
  277. mapname = "%s_%s" % (base, gscript.get_num_suffix(line_count + 1,
  278. max_count))
  279. mapid = "%s@%s" % (mapname, mapset)
  280. else:
  281. mapname = filename
  282. mapid = mapname + "@" + mapset
  283. row = {}
  284. row["filename"] = filename
  285. row["name"] = mapname
  286. row["id"] = mapid
  287. row["start"] = line_list[1].strip()
  288. row["end"] = line_list[2].strip()
  289. new_list_file.write("%s%s%s%s%s\n" % (mapname, fs, row["start"],
  290. fs, row["end"]))
  291. maplist.append(row)
  292. line_count += 1
  293. list_file.close()
  294. new_list_file.close()
  295. # Read the init file
  296. fs = "="
  297. init = {}
  298. init_file = open(init_file_name, "r")
  299. while True:
  300. line = init_file.readline()
  301. if not line:
  302. break
  303. kv = line.split(fs)
  304. init[kv[0]] = kv[1].strip()
  305. init_file.close()
  306. if "temporal_type" not in init or \
  307. "semantic_type" not in init or \
  308. "number_of_maps" not in init:
  309. gscript.fatal(_("Key words %(t)s, %(s)s or %(n)s not found in init"
  310. " file.") % {'t': "temporal_type",
  311. 's': "semantic_type",
  312. 'n': "number_of_maps"})
  313. if line_count != int(init["number_of_maps"]):
  314. gscript.fatal(_("Number of maps mismatch in init and list file."))
  315. format_ = "GTiff"
  316. type_ = "strds"
  317. if "stds_type" in init:
  318. type_ = init["stds_type"]
  319. if "format" in init:
  320. format_ = init["format"]
  321. if stds_type != type_:
  322. gscript.fatal(_("The archive file is of wrong space time dataset"
  323. " type"))
  324. # Check the existence of the files
  325. if format_ == "GTiff":
  326. for row in maplist:
  327. filename = row["filename"] + ".tif"
  328. if not os.path.exists(filename):
  329. gscript.fatal(_("Unable to find GeoTIFF raster file "
  330. "<%s> in archive.") % filename)
  331. elif format_ == "AAIGrid":
  332. for row in maplist:
  333. filename = row["filename"] + ".asc"
  334. if not os.path.exists(filename):
  335. gscript.fatal(_("Unable to find AAIGrid raster file "
  336. "<%s> in archive.") % filename)
  337. elif format_ == "GML":
  338. for row in maplist:
  339. filename = row["filename"] + ".xml"
  340. if not os.path.exists(filename):
  341. gscript.fatal(_("Unable to find GML vector file "
  342. "<%s> in archive.") % filename)
  343. elif format_ == "pack":
  344. for row in maplist:
  345. if type_ == "stvds":
  346. filename = str(row["filename"].split(":")[0]) + ".pack"
  347. else:
  348. filename = row["filename"] + ".pack"
  349. if not os.path.exists(filename):
  350. gscript.fatal(_("Unable to find GRASS package file "
  351. "<%s> in archive.") % filename)
  352. else:
  353. gscript.fatal(_("Unsupported input format"))
  354. # Check the space time dataset
  355. id = output + "@" + mapset
  356. sp = dataset_factory(type_, id)
  357. if sp.is_in_db() and gscript.overwrite() is False:
  358. gscript.fatal(_("Space time %(t)s dataset <%(sp)s> is already in"
  359. " the database. Use the overwrite flag.") %
  360. {'t': type_, 'sp': sp.get_id()})
  361. # Import the maps
  362. if type_ == "strds":
  363. if format_ == "GTiff" or format_ == "AAIGrid":
  364. _import_raster_maps_from_gdal(maplist, overr, exp, location,
  365. link, format_, set_current_region)
  366. if format_ == "pack":
  367. _import_raster_maps(maplist, set_current_region)
  368. elif type_ == "stvds":
  369. if format_ == "GML":
  370. _import_vector_maps_from_gml(
  371. maplist, overr, exp, location, link)
  372. if format_ == "pack":
  373. _import_vector_maps(maplist)
  374. # Create the space time dataset
  375. if sp.is_in_db() and gscript.overwrite() is True:
  376. gscript.info(_("Overwrite space time %(sp)s dataset "
  377. "<%(id)s> and unregister all maps.") %
  378. {'sp': sp.get_new_map_instance(None).get_type(),
  379. 'id': sp.get_id()})
  380. sp.delete()
  381. sp = sp.get_new_instance(id)
  382. temporal_type = init["temporal_type"]
  383. semantic_type = init["semantic_type"]
  384. relative_time_unit = None
  385. if temporal_type == "relative":
  386. if "relative_time_unit" not in init:
  387. gscript.fatal(_("Key word %s not found in init file.") %
  388. ("relative_time_unit"))
  389. relative_time_unit = init["relative_time_unit"]
  390. sp.set_relative_time_unit(relative_time_unit)
  391. gscript.verbose(_("Create space time %s dataset.") %
  392. sp.get_new_map_instance(None).get_type())
  393. sp.set_initial_values(temporal_type=temporal_type,
  394. semantic_type=semantic_type, title=title,
  395. description=descr)
  396. sp.insert()
  397. # register the maps
  398. fs = "|"
  399. register_maps_in_space_time_dataset(
  400. type=sp.get_new_map_instance(None).get_type(),
  401. name=output, file=new_list_file_name, start="file",
  402. end="file", unit=relative_time_unit, dbif=None, fs=fs,
  403. update_cmd_list=False)
  404. os.chdir(old_cwd)
  405. except:
  406. raise
  407. # Make sure the location is switched back correctly
  408. finally:
  409. if location:
  410. # Switch to the old location
  411. try:
  412. gscript.run_command("g.mapset", mapset=old_env["MAPSET"],
  413. location=old_env["LOCATION_NAME"],
  414. gisdbase=old_env["GISDBASE"])
  415. except CalledModuleError:
  416. grass.warning(_("Switching to original location failed"))
  417. gscript.set_raise_on_error(old_state)