v.in.mapgen.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. #!/usr/bin/env python3
  2. #
  3. ############################################################################
  4. #
  5. # MODULE: v.in.mapgen
  6. #
  7. # AUTHOR(S): Andreas Lange, andreas.lange@rhein-main.de
  8. # Updated for GRASS 6 by Hamish Bowman
  9. # Converted to Python by Glynn Clements
  10. #
  11. # PURPOSE: Import data from Mapgen or Matlab into a GRASS vector map
  12. #
  13. # COPYRIGHT: Original version (c) Andreas Lange
  14. # Updates by Hamish Bowman
  15. # (C) 2008, 2010 the GRASS Development Team
  16. #
  17. # This program is free software under the GNU General Public
  18. # License (>=v2). Read the file COPYING that comes with GRASS
  19. # for details.
  20. #############################################################################
  21. #
  22. # DATA AVAILABILITY: e.g., NOAA's Online Coastline Extractor
  23. # http://www.ngdc.noaa.gov/mgg/shorelines/shorelines.html
  24. #
  25. # %module
  26. # % description: Imports Mapgen or Matlab-ASCII vector maps into GRASS.
  27. # % keyword: vector
  28. # % keyword: import
  29. # %end
  30. # %flag
  31. # % key: f
  32. # % description: Input map is in Matlab format
  33. # %end
  34. # %flag
  35. # % key: z
  36. # % description: Create a 3D vector points map from 3 column Matlab data
  37. # %end
  38. # %option G_OPT_F_INPUT
  39. # % description: Name of input file in Mapgen/Matlab format
  40. # %end
  41. # %option G_OPT_V_OUTPUT
  42. # % description: Name for output vector map (omit for display to stdout)
  43. # % required: no
  44. # %end
  45. import sys
  46. import os
  47. import atexit
  48. import string
  49. import time
  50. import shutil
  51. from grass.script.utils import try_remove
  52. from grass.script import core as grass
  53. from grass.exceptions import CalledModuleError
  54. def cleanup():
  55. try_remove(tmp)
  56. try_remove(tmp + ".dig")
  57. def main():
  58. global tmp
  59. infile = options["input"]
  60. output = options["output"]
  61. matlab = flags["f"]
  62. threeD = flags["z"]
  63. prog = "v.in.mapgen"
  64. if not os.path.isfile(infile):
  65. grass.fatal(_("Input file <%s> not found") % infile)
  66. if output:
  67. name = output
  68. else:
  69. name = ""
  70. if threeD:
  71. matlab = True
  72. if threeD:
  73. do3D = "z"
  74. else:
  75. do3D = ""
  76. tmp = grass.tempfile()
  77. # create ascii vector file
  78. inf = open(infile)
  79. outf = open(tmp, "w")
  80. grass.message(_("Importing data..."))
  81. cat = 1
  82. if matlab:
  83. # HB: OLD v.in.mapgen.sh Matlab import command follows.
  84. # I have no idea what it's all about, so "new" matlab format will be
  85. # a series of x y with "nan nan" breaking lines. (as NOAA provides)
  86. # Old command:
  87. # tac $infile | $AWK 'BEGIN { FS="," ; R=0 }
  88. # $1~/\d*/ { printf("L %d\n", R) }
  89. # $1~/ .*/ { printf(" %lf %lf\n", $2, $1) ; ++R }
  90. # $1~/END/ { }' | tac > "$TMP"
  91. # matlab format.
  92. points = []
  93. for line in inf:
  94. f = line.split()
  95. if f[0].lower() == "nan":
  96. if points != []:
  97. outf.write("L %d 1\n" % len(points))
  98. for point in points:
  99. outf.write(" %.15g %.15g %.15g\n" % tuple(map(float, point)))
  100. outf.write(" 1 %d\n" % cat)
  101. cat += 1
  102. points = []
  103. else:
  104. if len(f) == 2:
  105. f.append("0")
  106. points.append(f)
  107. if points != []:
  108. outf.write("L %d 1\n" % len(points))
  109. for point in points:
  110. try:
  111. outf.write(" %.15g %.15g %.15g\n" % tuple(map(float, point)))
  112. except ValueError:
  113. grass.fatal(
  114. _("An error occurred on line '%s', exiting.") % line.strip()
  115. )
  116. outf.write(" 1 %d\n" % cat)
  117. cat += 1
  118. else:
  119. # mapgen format.
  120. points = []
  121. for line in inf:
  122. if line[0] == "#":
  123. if points != []:
  124. outf.write("L %d 1\n" % len(points))
  125. for point in points:
  126. outf.write(" %.15g %.15g\n" % tuple(map(float, point)))
  127. outf.write(" 1 %d\n" % cat)
  128. cat += 1
  129. points = []
  130. else:
  131. points.append(line.rstrip("\r\n").split("\t"))
  132. if points != []:
  133. outf.write("L %d 1\n" % len(points))
  134. for point in points:
  135. outf.write(" %.15g %.15g\n" % tuple(map(float, point)))
  136. outf.write(" 1 %d\n" % cat)
  137. cat += 1
  138. outf.close()
  139. inf.close()
  140. # create digit header
  141. digfile = tmp + ".dig"
  142. outf = open(digfile, "w")
  143. t = string.Template(
  144. """ORGANIZATION: GRASSroots organization
  145. DIGIT DATE: $date
  146. DIGIT NAME: $user@$host
  147. MAP NAME: $name
  148. MAP DATE: $year
  149. MAP SCALE: 1
  150. OTHER INFO: Imported with $prog
  151. ZONE: 0
  152. MAP THRESH: 0
  153. VERTI:
  154. """
  155. )
  156. date = time.strftime("%m/%d/%y")
  157. year = time.strftime("%Y")
  158. user = os.getenv("USERNAME") or os.getenv("LOGNAME")
  159. host = os.getenv("COMPUTERNAME") or os.uname()[1]
  160. s = t.substitute(prog=prog, name=name, date=date, year=year, user=user, host=host)
  161. outf.write(s)
  162. # process points list to ascii vector file (merge in vertices)
  163. inf = open(tmp)
  164. shutil.copyfileobj(inf, outf)
  165. inf.close()
  166. outf.close()
  167. if not name:
  168. # if no name for vector file given, cat to stdout
  169. inf = open(digfile)
  170. shutil.copyfileobj(inf, sys.stdout)
  171. inf.close()
  172. else:
  173. # import to binary vector file
  174. grass.message(_("Importing with v.in.ascii..."))
  175. try:
  176. grass.run_command(
  177. "v.in.ascii", flags=do3D, input=digfile, output=name, format="standard"
  178. )
  179. except CalledModuleError:
  180. grass.fatal(_('An error occurred on creating "%s", please check') % name)
  181. if __name__ == "__main__":
  182. options, flags = grass.parser()
  183. atexit.register(cleanup)
  184. main()