v.in.mapgen.py 5.1 KB

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