stds_import.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. msgr = get_tgis_message_interface()
  174. msgr.message(_("Checking validity of input file (size: %0.1f MB). Make take a while..."
  175. % (os.path.getsize(input)/(1024*1024.0))))
  176. members = tar.getnames()
  177. # Make sure that the basenames of the files are used for comparison
  178. member_basenames = [os.path.basename(name) for name in members]
  179. if init_file_name not in member_basenames:
  180. gscript.fatal(_("Unable to find init file <%s>") % init_file_name)
  181. if list_file_name not in member_basenames:
  182. gscript.fatal(_("Unable to find list file <%s>") % list_file_name)
  183. if proj_file_name not in member_basenames:
  184. gscript.fatal(_("Unable to find projection file <%s>") % proj_file_name)
  185. msgr.message(_("Extracting data..."))
  186. tar.extractall(path=directory)
  187. tar.close()
  188. # We use a new list file name for map registration
  189. new_list_file_name = list_file_name + "_new"
  190. # Save current working directory path
  191. old_cwd = os.getcwd()
  192. # Switch into the data directory
  193. os.chdir(directory)
  194. # Check projection information
  195. if not location:
  196. temp_name = gscript.tempfile()
  197. temp_file = open(temp_name, "w")
  198. proj_name = os.path.abspath(proj_file_name)
  199. # We need to convert projection strings generated
  200. # from other programms than g.proj into
  201. # new line format so that the grass file comparison function
  202. # can be used to compare the projections
  203. proj_name_tmp = temp_name + "_in_projection"
  204. proj_file = open(proj_name, "r")
  205. proj_content = proj_file.read()
  206. proj_content = proj_content.replace(" +", "\n+")
  207. proj_content = proj_content.replace("\t+", "\n+")
  208. proj_file.close()
  209. proj_file = open(proj_name_tmp, "w")
  210. proj_file.write(proj_content)
  211. proj_file.close()
  212. p = gscript.start_command("g.proj", flags="j", stdout=temp_file)
  213. p.communicate()
  214. temp_file.close()
  215. if not gscript.compare_key_value_text_files(temp_name, proj_name_tmp,
  216. sep="="):
  217. if overr:
  218. gscript.warning(_("Projection information does not match. "
  219. "Proceeding..."))
  220. else:
  221. diff = ''.join(gscript.diff_files(temp_name, proj_name))
  222. gscript.warning(_("Difference between PROJ_INFO file of "
  223. "imported map and of current location:"
  224. "\n{diff}").format(diff=diff))
  225. gscript.fatal(_("Projection information does not match. "
  226. "Aborting."))
  227. # Create a new location based on the projection information and switch
  228. # into it
  229. old_env = gscript.gisenv()
  230. if location:
  231. try:
  232. proj4_string = open(proj_file_name, 'r').read()
  233. gscript.create_location(dbase=old_env["GISDBASE"],
  234. location=location,
  235. proj4=proj4_string)
  236. # Just create a new location and return
  237. if create:
  238. os.chdir(old_cwd)
  239. return
  240. except Exception as e:
  241. gscript.fatal(_("Unable to create location %(l)s. Reason: %(e)s")
  242. % {'l': location, 'e': str(e)})
  243. # Switch to the new created location
  244. try:
  245. gscript.run_command("g.mapset", mapset="PERMANENT",
  246. location=location,
  247. dbase=old_env["GISDBASE"])
  248. except CalledModuleError:
  249. gscript.fatal(_("Unable to switch to location %s") % location)
  250. # create default database connection
  251. try:
  252. gscript.run_command("t.connect", flags="d")
  253. except CalledModuleError:
  254. gscript.fatal(_("Unable to create default temporal database "
  255. "in new location %s") % location)
  256. try:
  257. # Make sure the temporal database exists
  258. factory.init()
  259. fs = "|"
  260. maplist = []
  261. mapset = get_current_mapset()
  262. list_file = open(list_file_name, "r")
  263. new_list_file = open(new_list_file_name, "w")
  264. # get number of lines to correctly form the suffix
  265. max_count = -1
  266. for max_count, l in enumerate(list_file):
  267. pass
  268. max_count += 1
  269. list_file.seek(0)
  270. # Read the map list from file
  271. line_count = 0
  272. while True:
  273. line = list_file.readline()
  274. if not line:
  275. break
  276. line_list = line.split(fs)
  277. # The filename is actually the base name of the map
  278. # that must be extended by the file suffix
  279. filename = line_list[0].strip().split(":")[0]
  280. if base:
  281. mapname = "%s_%s" % (base, gscript.get_num_suffix(line_count + 1,
  282. max_count))
  283. mapid = "%s@%s" % (mapname, mapset)
  284. else:
  285. mapname = filename
  286. mapid = mapname + "@" + mapset
  287. row = {}
  288. row["filename"] = filename
  289. row["name"] = mapname
  290. row["id"] = mapid
  291. row["start"] = line_list[1].strip()
  292. row["end"] = line_list[2].strip()
  293. new_list_file.write("%s%s%s%s%s\n" % (mapname, fs, row["start"],
  294. fs, row["end"]))
  295. maplist.append(row)
  296. line_count += 1
  297. list_file.close()
  298. new_list_file.close()
  299. # Read the init file
  300. fs = "="
  301. init = {}
  302. init_file = open(init_file_name, "r")
  303. while True:
  304. line = init_file.readline()
  305. if not line:
  306. break
  307. kv = line.split(fs)
  308. init[kv[0]] = kv[1].strip()
  309. init_file.close()
  310. if "temporal_type" not in init or \
  311. "semantic_type" not in init or \
  312. "number_of_maps" not in init:
  313. gscript.fatal(_("Key words %(t)s, %(s)s or %(n)s not found in init"
  314. " file.") % {'t': "temporal_type",
  315. 's': "semantic_type",
  316. 'n': "number_of_maps"})
  317. if line_count != int(init["number_of_maps"]):
  318. gscript.fatal(_("Number of maps mismatch in init and list file."))
  319. format_ = "GTiff"
  320. type_ = "strds"
  321. if "stds_type" in init:
  322. type_ = init["stds_type"]
  323. if "format" in init:
  324. format_ = init["format"]
  325. if stds_type != type_:
  326. gscript.fatal(_("The archive file is of wrong space time dataset"
  327. " type"))
  328. # Check the existence of the files
  329. if format_ == "GTiff":
  330. for row in maplist:
  331. filename = row["filename"] + ".tif"
  332. if not os.path.exists(filename):
  333. gscript.fatal(_("Unable to find GeoTIFF raster file "
  334. "<%s> in archive.") % filename)
  335. elif format_ == "AAIGrid":
  336. for row in maplist:
  337. filename = row["filename"] + ".asc"
  338. if not os.path.exists(filename):
  339. gscript.fatal(_("Unable to find AAIGrid raster file "
  340. "<%s> in archive.") % filename)
  341. elif format_ == "GML":
  342. for row in maplist:
  343. filename = row["filename"] + ".xml"
  344. if not os.path.exists(filename):
  345. gscript.fatal(_("Unable to find GML vector file "
  346. "<%s> in archive.") % filename)
  347. elif format_ == "pack":
  348. for row in maplist:
  349. if type_ == "stvds":
  350. filename = str(row["filename"].split(":")[0]) + ".pack"
  351. else:
  352. filename = row["filename"] + ".pack"
  353. if not os.path.exists(filename):
  354. gscript.fatal(_("Unable to find GRASS package file "
  355. "<%s> in archive.") % filename)
  356. else:
  357. gscript.fatal(_("Unsupported input format"))
  358. # Check the space time dataset
  359. id = output + "@" + mapset
  360. sp = dataset_factory(type_, id)
  361. if sp.is_in_db() and gscript.overwrite() is False:
  362. gscript.fatal(_("Space time %(t)s dataset <%(sp)s> is already in"
  363. " the database. Use the overwrite flag.") %
  364. {'t': type_, 'sp': sp.get_id()})
  365. # Import the maps
  366. if type_ == "strds":
  367. if format_ == "GTiff" or format_ == "AAIGrid":
  368. _import_raster_maps_from_gdal(maplist, overr, exp, location,
  369. link, format_, set_current_region)
  370. if format_ == "pack":
  371. _import_raster_maps(maplist, set_current_region)
  372. elif type_ == "stvds":
  373. if format_ == "GML":
  374. _import_vector_maps_from_gml(
  375. maplist, overr, exp, location, link)
  376. if format_ == "pack":
  377. _import_vector_maps(maplist)
  378. # Create the space time dataset
  379. if sp.is_in_db() and gscript.overwrite() is True:
  380. gscript.info(_("Overwrite space time %(sp)s dataset "
  381. "<%(id)s> and unregister all maps.") %
  382. {'sp': sp.get_new_map_instance(None).get_type(),
  383. 'id': sp.get_id()})
  384. sp.delete()
  385. sp = sp.get_new_instance(id)
  386. temporal_type = init["temporal_type"]
  387. semantic_type = init["semantic_type"]
  388. relative_time_unit = None
  389. if temporal_type == "relative":
  390. if "relative_time_unit" not in init:
  391. gscript.fatal(_("Key word %s not found in init file.") %
  392. ("relative_time_unit"))
  393. relative_time_unit = init["relative_time_unit"]
  394. sp.set_relative_time_unit(relative_time_unit)
  395. gscript.verbose(_("Create space time %s dataset.") %
  396. sp.get_new_map_instance(None).get_type())
  397. sp.set_initial_values(temporal_type=temporal_type,
  398. semantic_type=semantic_type, title=title,
  399. description=descr)
  400. sp.insert()
  401. # register the maps
  402. fs = "|"
  403. register_maps_in_space_time_dataset(
  404. type=sp.get_new_map_instance(None).get_type(),
  405. name=output, file=new_list_file_name, start="file",
  406. end="file", unit=relative_time_unit, dbif=None, fs=fs,
  407. update_cmd_list=False)
  408. os.chdir(old_cwd)
  409. except:
  410. raise
  411. # Make sure the location is switched back correctly
  412. finally:
  413. if location:
  414. # Switch to the old location
  415. try:
  416. gscript.run_command("g.mapset", mapset=old_env["MAPSET"],
  417. location=old_env["LOCATION_NAME"],
  418. gisdbase=old_env["GISDBASE"])
  419. except CalledModuleError:
  420. grass.warning(_("Switching to original location failed"))
  421. gscript.set_raise_on_error(old_state)