m.proj.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. #% required : yes
  35. #% key_desc : filename
  36. #%end
  37. #%option
  38. #% key: output
  39. #% type: string
  40. #% gisprompt: new_file,file,file
  41. #% description: Output coordinate file (omit to send to stdout)
  42. #% required : no
  43. #% key_desc : filename
  44. #%end
  45. #%option
  46. #% key: fs
  47. #% type: string
  48. #% label: Field separator (format: input[,output])
  49. #% description: Valid field separators are also "space", "tab", or "comma"
  50. #% required : no
  51. #% key_desc : string
  52. #% answer : |
  53. #%end
  54. #%option
  55. #% key: proj_input
  56. #% type: string
  57. #% description: Input projection parameters (PROJ.4 style)
  58. #% required : no
  59. #%end
  60. #%option
  61. #% key: proj_output
  62. #% type: string
  63. #% description: Output projection parameters (PROJ.4 style)
  64. #% required : no
  65. #%end
  66. #%flag
  67. #% key: i
  68. #% description: Use LL WGS84 as input and current location as output projection
  69. #%end
  70. #%flag
  71. #% key: o
  72. #% description: Use current location as input and LL WGS84 as output projection
  73. #%end
  74. #%flag
  75. #% key: d
  76. #% description: Output long/lat in decimal degrees or other projections with many decimal places
  77. #%end
  78. #%flag
  79. #% key: e
  80. #% description: Include input coordinates in output file
  81. #%end
  82. #%flag
  83. #% key: c
  84. #% description: Include column names in output file
  85. #%end
  86. import sys
  87. import os
  88. from grass.script import core as grass
  89. def main():
  90. input = options['input']
  91. output = options['output']
  92. fs = options['fs']
  93. proj_in = options['proj_input']
  94. proj_out = options['proj_output']
  95. ll_in = flags['i']
  96. ll_out = flags['o']
  97. decimal = flags['d']
  98. copy_input = flags['e']
  99. include_header = flags['c']
  100. #### check for cs2cs
  101. if not grass.find_program('cs2cs'):
  102. grass.fatal("cs2cs program not found, install PROJ.4 first: http://proj.maptools.org")
  103. #### check for overenthusiasm
  104. if proj_in and ll_in:
  105. grass.fatal("Choose only one input parameter method")
  106. if proj_out and ll_out:
  107. grass.fatal("Choose only one output parameter method")
  108. if ll_in and ll_out:
  109. grass.fatal("Choise only one auto-projection parameter method")
  110. if output and not grass.overwrite() and os.path.exists(output):
  111. grass.fatal("Output file already exists")
  112. #### parse field separator
  113. # FIXME: input_x,y needs to split on multiple whitespace between them
  114. if fs == ',':
  115. ifs = ofs = ','
  116. else:
  117. try:
  118. ifs, ofs = fs.split(',')
  119. except ValueError:
  120. ifs = ofs = fs
  121. ifs = ifs.lower()
  122. ofs = ofs.lower()
  123. if ifs in ('space', 'tab'):
  124. ifs = ' '
  125. elif ifs == 'comma':
  126. ifs = ','
  127. else:
  128. if len(ifs) > 1:
  129. grass.warning("Invalid field separator, using '%s'" % ifs[0])
  130. try:
  131. ifs = ifs[0]
  132. except IndexError:
  133. grass.fatal("Invalid field separator '%s'" % ifs)
  134. if ofs.lower() == 'space':
  135. ofs = ' '
  136. elif ofs.lower() == 'tab':
  137. ofs = '\t'
  138. elif ofs.lower() == 'comma':
  139. ofs = ','
  140. else:
  141. if len(ofs) > 1:
  142. grass.warning("Invalid field separator, using '%s'" % ofs[0])
  143. try:
  144. ofs = ofs[0]
  145. except IndexError:
  146. grass.fatal("Invalid field separator '%s'" % ifs)
  147. #### set up projection params
  148. s = grass.read_command("g.proj", flags='j')
  149. kv = grass.parse_key_val(s)
  150. if "XY location" in kv['+proj'] and (ll_in or ll_out):
  151. grass.fatal("Unable to project to or from a XY location")
  152. in_proj = None
  153. if ll_in:
  154. in_proj = "+proj=longlat +datum=WGS84"
  155. grass.verbose("Assuming LL WGS84 as input, current projection as output ")
  156. if ll_out:
  157. in_proj = grass.read_command('g.proj', flags = 'jf')
  158. if proj_in:
  159. in_proj = proj_in
  160. if not in_proj:
  161. grass.verbose("Assuming current location as input")
  162. in_proj = grass.read_command('g.proj', flags = 'jf')
  163. in_proj = in_proj.strip()
  164. grass.verbose("Input parameters: '%s'" % in_proj)
  165. out_proj = None
  166. if ll_out:
  167. out_proj = "+proj=longlat +datum=WGS84"
  168. grass.verbose("Assuming current projection as input, LL WGS84 as output ")
  169. if ll_in:
  170. out_proj = grass.read_command('g.proj', flags = 'jf')
  171. if proj_out:
  172. out_proj = proj_out
  173. if not out_proj:
  174. grass.fatal("Missing output projection parameters ")
  175. out_proj = out_proj.strip()
  176. grass.verbose("Output parameters: '%s'" % out_proj)
  177. #### set up input file
  178. if input == '-':
  179. infile = None
  180. inf = sys.stdin
  181. else:
  182. infile = input
  183. if not os.path.exists(infile):
  184. grass.fatal("Unable to read input data")
  185. inf = file(infile)
  186. grass.debug("input file=[%s]" % infile)
  187. #### set up output file
  188. if not output:
  189. outfile = None
  190. outf = sys.stdout
  191. else:
  192. outfile = output
  193. outf = open(outfile, 'w')
  194. grass.debug("output file=[%s]" % outfile)
  195. #### set up output style
  196. if not decimal:
  197. outfmt = []
  198. else:
  199. outfmt = ["-f", "%.8f"]
  200. if not copy_input:
  201. copyinp = []
  202. else:
  203. copyinp = ["-E"]
  204. #### do the conversion
  205. # Convert cs2cs DMS format to GRASS DMS format:
  206. # cs2cs | sed -e 's/d/:/g' -e "s/'/:/g" -e 's/"//g'
  207. cmd = ['cs2cs'] + copyinp + outfmt + in_proj.split() + ['+to'] + out_proj.split()
  208. p = grass.Popen(cmd, stdin = grass.PIPE, stdout = grass.PIPE)
  209. while True:
  210. line = inf.readline()
  211. if not line:
  212. break
  213. line = line.replace(ifs, ' ')
  214. p.stdin.write(line)
  215. p.stdin.flush()
  216. p.stdin.close()
  217. p.stdin = None
  218. exitcode = p.wait()
  219. if exitcode != 0:
  220. grass.warning("Projection transform probably failed, please investigate")
  221. if not copy_input:
  222. if include_header:
  223. outf.write("x%sy%sz\n" % (ofs, ofs))
  224. for line in p.communicate()[0].splitlines():
  225. x, yz = line.split('\t')
  226. y, z = yz.split(' ')
  227. outf.write('%s%s%s%s%s\n' % \
  228. (x.strip(), ofs, y.strip(), ofs, z.strip()))
  229. else:
  230. if include_header:
  231. outf.write("input_x%sinput_y%sx%sy%sz\n" % (ofs, ofs, ofs, ofs))
  232. for line in p.communicate()[0].splitlines():
  233. inX, therest, z = line.split(' ')
  234. inY, x, y = therest.split('\t')
  235. outf.write('%s%s%s%s%s%s%s%s%s\n' % \
  236. (inX.strip(), ofs, inY.strip(), ofs, x.strip(), \
  237. ofs, y.strip(), ofs, z.strip()))
  238. if __name__ == "__main__":
  239. options, flags = grass.parser()
  240. main()