m.proj.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: m.proj
  5. # AUTHOR: M. Hamish Bowman, Dept. Marine Science, Otago Univeristy,
  6. # New Zealand
  7. # Converted to Python by Glynn Clements
  8. # PURPOSE: cs2cs reprojection frontend for a list of coordinates.
  9. # Replacement for m.proj2 from GRASS 5
  10. # COPYRIGHT: (c) 2006-2009 Hamish Bowman, and the GRASS Development Team
  11. # This program is free software under the GNU General Public
  12. # License (>=v2). Read the file COPYING that comes with GRASS
  13. # for details.
  14. #
  15. #############################################################################
  16. # notes:
  17. # - cs2cs expects "x y" data so be sure to send it "lon lat" not "lat lon"
  18. # - if you send cs2cs a third data column, beware it might be treated as "z"
  19. # todo:
  20. # - `cut` away x,y columns into a temp file, feed to cs2cs, then `paste`
  21. # back to input file. see method in v.in.garmin.sh. that way additional
  22. # numeric and string columns would survive the trip, and 3rd column would
  23. # not be modified as z.
  24. #%Module
  25. #% description: Converts coordinates from one projection to another (cs2cs frontend).
  26. #% keywords: miscellaneous
  27. #% keywords: projection
  28. #%End
  29. #%option
  30. #% key: input
  31. #% type: string
  32. #% gisprompt: old_file,file,file
  33. #% description: Input coordinate file ('-' to read from stdin)
  34. #% answer: -
  35. #% key_desc : filename
  36. #% guisection: Files & format
  37. #%end
  38. #%option
  39. #% key: output
  40. #% type: string
  41. #% gisprompt: new_file,file,file
  42. #% description: Output coordinate file (omit to send to stdout)
  43. #% required : no
  44. #% key_desc : filename
  45. #% guisection: Files & format
  46. #%end
  47. #%option
  48. #% key: fs
  49. #% type: string
  50. #% label: Field separator (format: input[,output])
  51. #% description: Valid field separators are also "space", "tab", or "comma"
  52. #% required : no
  53. #% key_desc : string
  54. #% answer : |
  55. #% guisection: Files & format
  56. #%end
  57. #%option
  58. #% key: proj_input
  59. #% type: string
  60. #% description: Input projection parameters (PROJ.4 style)
  61. #% required : no
  62. #% guisection: Projections
  63. #%end
  64. #%option
  65. #% key: proj_output
  66. #% type: string
  67. #% description: Output projection parameters (PROJ.4 style)
  68. #% required : no
  69. #% guisection: Projections
  70. #%end
  71. #%flag
  72. #% key: i
  73. #% description: Use LL WGS84 as input and current location as output projection
  74. #% guisection: Projections
  75. #%end
  76. #%flag
  77. #% key: o
  78. #% description: Use current location as input and LL WGS84 as output projection
  79. #% guisection: Projections
  80. #%end
  81. #%flag
  82. #% key: d
  83. #% description: Output long/lat in decimal degrees, or other projections with many decimal places
  84. #% guisection: Files & format
  85. #%end
  86. #%flag
  87. #% key: e
  88. #% description: Include input coordinates in output file
  89. #% guisection: Files & format
  90. #%end
  91. #%flag
  92. #% key: c
  93. #% description: Include column names in output file
  94. #% guisection: Files & format
  95. #%end
  96. import sys
  97. import os
  98. from grass.script import core as grass
  99. def main():
  100. input = options['input']
  101. output = options['output']
  102. fs = options['fs']
  103. proj_in = options['proj_input']
  104. proj_out = options['proj_output']
  105. ll_in = flags['i']
  106. ll_out = flags['o']
  107. decimal = flags['d']
  108. copy_input = flags['e']
  109. include_header = flags['c']
  110. #### check for cs2cs
  111. if not grass.find_program('cs2cs'):
  112. grass.fatal(_("cs2cs program not found, install PROJ.4 first: http://proj.maptools.org"))
  113. #### check for overenthusiasm
  114. if proj_in and ll_in:
  115. grass.fatal(_("Choose only one input parameter method"))
  116. if proj_out and ll_out:
  117. grass.fatal(_("Choose only one output parameter method"))
  118. if ll_in and ll_out:
  119. grass.fatal(_("Choise only one auto-projection parameter method"))
  120. if output and not grass.overwrite() and os.path.exists(output):
  121. grass.fatal(_("Output file already exists"))
  122. #### parse field separator
  123. # FIXME: input_x,y needs to split on multiple whitespace between them
  124. if fs == ',':
  125. ifs = ofs = ','
  126. else:
  127. try:
  128. ifs, ofs = fs.split(',')
  129. except ValueError:
  130. ifs = ofs = fs
  131. ifs = ifs.lower()
  132. ofs = ofs.lower()
  133. if ifs in ('space', 'tab'):
  134. ifs = ' '
  135. elif ifs == 'comma':
  136. ifs = ','
  137. else:
  138. if len(ifs) > 1:
  139. grass.warning(_("Invalid field separator, using '%s'") % ifs[0])
  140. try:
  141. ifs = ifs[0]
  142. except IndexError:
  143. grass.fatal(_("Invalid field separator '%s'") % ifs)
  144. if ofs.lower() == 'space':
  145. ofs = ' '
  146. elif ofs.lower() == 'tab':
  147. ofs = '\t'
  148. elif ofs.lower() == 'comma':
  149. ofs = ','
  150. else:
  151. if len(ofs) > 1:
  152. grass.warning(_("Invalid field separator, using '%s'") % ofs[0])
  153. try:
  154. ofs = ofs[0]
  155. except IndexError:
  156. grass.fatal(_("Invalid field separator '%s'") % ifs)
  157. #### set up projection params
  158. s = grass.read_command("g.proj", flags='j')
  159. kv = grass.parse_key_val(s)
  160. if "XY location" in kv['+proj'] and (ll_in or ll_out):
  161. grass.fatal(_("Unable to project to or from a XY location"))
  162. in_proj = None
  163. if ll_in:
  164. in_proj = "+proj=longlat +datum=WGS84"
  165. grass.verbose("Assuming LL WGS84 as input, current projection as output ")
  166. if ll_out:
  167. in_proj = grass.read_command('g.proj', flags = 'jf')
  168. if proj_in:
  169. in_proj = proj_in
  170. if not in_proj:
  171. grass.verbose("Assuming current location as input")
  172. in_proj = grass.read_command('g.proj', flags = 'jf')
  173. in_proj = in_proj.strip()
  174. grass.verbose("Input parameters: '%s'" % in_proj)
  175. out_proj = None
  176. if ll_out:
  177. out_proj = "+proj=longlat +datum=WGS84"
  178. grass.verbose("Assuming current projection as input, LL WGS84 as output ")
  179. if ll_in:
  180. out_proj = grass.read_command('g.proj', flags = 'jf')
  181. if proj_out:
  182. out_proj = proj_out
  183. if not out_proj:
  184. grass.fatal(_("Missing output projection parameters "))
  185. out_proj = out_proj.strip()
  186. grass.verbose("Output parameters: '%s'" % out_proj)
  187. #### set up input file
  188. if input == '-':
  189. infile = None
  190. inf = sys.stdin
  191. else:
  192. infile = input
  193. if not os.path.exists(infile):
  194. grass.fatal(_("Unable to read input data"))
  195. inf = file(infile)
  196. grass.debug("input file=[%s]" % infile)
  197. #### set up output file
  198. if not output:
  199. outfile = None
  200. outf = sys.stdout
  201. else:
  202. outfile = output
  203. outf = open(outfile, 'w')
  204. grass.debug("output file=[%s]" % outfile)
  205. #### set up output style
  206. if not decimal:
  207. outfmt = ["-w5"]
  208. else:
  209. outfmt = ["-f", "%.8f"]
  210. if not copy_input:
  211. copyinp = []
  212. else:
  213. copyinp = ["-E"]
  214. #### do the conversion
  215. # Convert cs2cs DMS format to GRASS DMS format:
  216. # cs2cs | sed -e 's/d/:/g' -e "s/'/:/g" -e 's/"//g'
  217. cmd = ['cs2cs'] + copyinp + outfmt + in_proj.split() + ['+to'] + out_proj.split()
  218. p = grass.Popen(cmd, stdin = grass.PIPE, stdout = grass.PIPE)
  219. while True:
  220. line = inf.readline()
  221. if not line:
  222. break
  223. line = line.replace(ifs, ' ')
  224. p.stdin.write(line)
  225. p.stdin.flush()
  226. p.stdin.close()
  227. p.stdin = None
  228. exitcode = p.wait()
  229. if exitcode != 0:
  230. grass.warning(_("Projection transform probably failed, please investigate"))
  231. if not copy_input:
  232. if include_header:
  233. outf.write("x%sy%sz\n" % (ofs, ofs))
  234. for line in p.communicate()[0].splitlines():
  235. x, yz = line.split('\t')
  236. y, z = yz.split(' ')
  237. outf.write('%s%s%s%s%s\n' % \
  238. (x.strip(), ofs, y.strip(), ofs, z.strip()))
  239. else:
  240. if include_header:
  241. outf.write("input_x%sinput_y%sx%sy%sz\n" % (ofs, ofs, ofs, ofs))
  242. for line in p.communicate()[0].splitlines():
  243. inX, therest, z = line.split(' ')
  244. inY, x, y = therest.split('\t')
  245. outf.write('%s%s%s%s%s%s%s%s%s\n' % \
  246. (inX.strip(), ofs, inY.strip(), ofs, x.strip(), \
  247. ofs, y.strip(), ofs, z.strip()))
  248. if __name__ == "__main__":
  249. options, flags = grass.parser()
  250. main()