v.in.mapgen.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. #!/usr/bin/env python
  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. #% keywords: vector
  28. #% keywords: 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 import core as grass
  52. def cleanup():
  53. grass.try_remove(tmp)
  54. grass.try_remove(tmp + '.dig')
  55. def main():
  56. global tmp
  57. infile = options['input']
  58. output = options['output']
  59. matlab = flags['f']
  60. threeD = flags['z']
  61. prog = 'v.in.mapgen'
  62. opts = ""
  63. if not os.path.isfile(infile):
  64. grass.fatal(_("Input file <%s> not found") % infile)
  65. if output:
  66. name = output
  67. else:
  68. name = ''
  69. if threeD:
  70. matlab = True
  71. if threeD:
  72. do3D = 'z'
  73. else:
  74. do3D = ''
  75. tmp = grass.tempfile()
  76. #### create ascii vector file
  77. inf = file(infile)
  78. outf = file(tmp, 'w')
  79. grass.message(_("Importing data..."))
  80. cat = 1
  81. if matlab:
  82. ## HB: OLD v.in.mapgen.sh Matlab import command follows.
  83. ## I have no idea what it's all about, so "new" matlab format will be
  84. ## a series of x y with "nan nan" breaking lines. (as NOAA provides)
  85. ## Old command:
  86. # tac $infile | $AWK 'BEGIN { FS="," ; R=0 }
  87. # $1~/\d*/ { printf("L %d\n", R) }
  88. # $1~/ .*/ { printf(" %lf %lf\n", $2, $1) ; ++R }
  89. # $1~/END/ { }' | tac > "$TMP"
  90. ## matlab format.
  91. points = []
  92. for line in inf:
  93. f = line.split()
  94. if f[0].lower() == 'nan':
  95. if points != []:
  96. outf.write("L %d 1\n" % len(points))
  97. for point in points:
  98. outf.write(" %.15g %.15g %.15g\n" % tuple(map(float,point)))
  99. outf.write(" 1 %d\n" % cat)
  100. cat += 1
  101. points = []
  102. else:
  103. if len(f) == 2:
  104. f.append('0')
  105. points.append(f)
  106. if points != []:
  107. outf.write("L %d 1\n" % len(points))
  108. for point in points:
  109. try:
  110. outf.write(" %.15g %.15g %.15g\n" % tuple(map(float, point)))
  111. except ValueError:
  112. grass.fatal(_("An error occured on line '%s', exiting.") % line.strip())
  113. outf.write(" 1 %d\n" % cat)
  114. cat += 1
  115. else:
  116. ## mapgen format.
  117. points = []
  118. for line in inf:
  119. if line[0] == '#':
  120. if points != []:
  121. outf.write("L %d 1\n" % len(points))
  122. for point in points:
  123. outf.write(" %.15g %.15g\n" % tuple(map(float,point)))
  124. outf.write(" 1 %d\n" % cat)
  125. cat += 1
  126. points = []
  127. else:
  128. points.append(line.rstrip('\r\n').split('\t'))
  129. if points != []:
  130. outf.write("L %d 1\n" % len(points))
  131. for point in points:
  132. outf.write(" %.15g %.15g\n" % tuple(map(float,point)))
  133. outf.write(" 1 %d\n" % cat)
  134. cat += 1
  135. outf.close()
  136. inf.close()
  137. #### create digit header
  138. digfile = tmp + '.dig'
  139. outf = file(digfile, 'w')
  140. t = string.Template(\
  141. """ORGANIZATION: GRASSroots organization
  142. DIGIT DATE: $date
  143. DIGIT NAME: $user@$host
  144. MAP NAME: $name
  145. MAP DATE: $year
  146. MAP SCALE: 1
  147. OTHER INFO: Imported with $prog
  148. ZONE: 0
  149. MAP THRESH: 0
  150. VERTI:
  151. """)
  152. date = time.strftime("%m/%d/%y")
  153. year = time.strftime("%Y")
  154. user = os.getenv('USERNAME') or os.getenv('LOGNAME')
  155. host = os.getenv('COMPUTERNAME') or os.uname()[1]
  156. s = t.substitute(prog = prog, name = name, date = date, year = year,
  157. user = user, host = host)
  158. outf.write(s)
  159. #### process points list to ascii vector file (merge in vertices)
  160. inf = file(tmp)
  161. shutil.copyfileobj(inf, outf)
  162. inf.close()
  163. outf.close()
  164. if not name:
  165. #### if no name for vector file given, cat to stdout
  166. inf = file(digfile)
  167. shutil.copyfileobj(inf, sys.stdout)
  168. inf.close()
  169. else:
  170. #### import to binary vector file
  171. grass.message(_("Importing with v.in.ascii..."))
  172. if grass.run_command('v.in.ascii', flags = do3D, input = digfile,
  173. output = name, format = 'standard') != 0:
  174. grass.fatal(_('An error occured on creating "%s", please check') % name)
  175. if __name__ == "__main__":
  176. options, flags = grass.parser()
  177. atexit.register(cleanup)
  178. main()