m.proj.py 7.3 KB

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