m.proj.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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 G_OPT_F_INPUT
  30. #% description: Name of input coordinate file ('-' to read from stdin)
  31. #% answer: -
  32. #% guisection: Files & format
  33. #%end
  34. #%option G_OPT_F_OUTPUT
  35. #% description: Name for output coordinate file (omit to send to stdout)
  36. #% required : no
  37. #% guisection: Files & format
  38. #%end
  39. #%option G_OPT_F_SEP
  40. #% label: Field separator (format: input[,output])
  41. #% description: Valid field separators are also "space", "tab", or "comma"
  42. #% required : no
  43. #% guisection: Files & format
  44. #%end
  45. #%option
  46. #% key: proj_input
  47. #% type: string
  48. #% description: Input projection parameters (PROJ.4 style)
  49. #% required : no
  50. #% guisection: Projections
  51. #%end
  52. #%option
  53. #% key: proj_output
  54. #% type: string
  55. #% description: Output projection parameters (PROJ.4 style)
  56. #% required : no
  57. #% guisection: Projections
  58. #%end
  59. #%flag
  60. #% key: i
  61. #% description: Use LL WGS84 as input and current location as output projection
  62. #% guisection: Projections
  63. #%end
  64. #%flag
  65. #% key: o
  66. #% description: Use current location as input and LL WGS84 as output projection
  67. #% guisection: Projections
  68. #%end
  69. #%flag
  70. #% key: d
  71. #% description: Output long/lat in decimal degrees, or other projections with many decimal places
  72. #% guisection: Files & format
  73. #%end
  74. #%flag
  75. #% key: e
  76. #% description: Include input coordinates in output file
  77. #% guisection: Files & format
  78. #%end
  79. #%flag
  80. #% key: c
  81. #% description: Include column names in output file
  82. #% guisection: Files & format
  83. #%end
  84. import sys
  85. import os
  86. from grass.script import core as grass
  87. def main():
  88. input = options['input']
  89. output = options['output']
  90. fs = options['fs']
  91. proj_in = options['proj_input']
  92. proj_out = options['proj_output']
  93. ll_in = flags['i']
  94. ll_out = flags['o']
  95. decimal = flags['d']
  96. copy_input = flags['e']
  97. include_header = flags['c']
  98. #### check for cs2cs
  99. if not grass.find_program('cs2cs'):
  100. grass.fatal(_("cs2cs program not found, install PROJ.4 first: http://proj.maptools.org"))
  101. #### check for overenthusiasm
  102. if proj_in and ll_in:
  103. grass.fatal(_("Choose only one input parameter method"))
  104. if proj_out and ll_out:
  105. grass.fatal(_("Choose only one output parameter method"))
  106. if ll_in and ll_out:
  107. grass.fatal(_("Choise only one auto-projection parameter method"))
  108. if output and not grass.overwrite() and os.path.exists(output):
  109. grass.fatal(_("Output file already exists"))
  110. #### parse field separator
  111. # FIXME: input_x,y needs to split on multiple whitespace between them
  112. if fs == ',':
  113. ifs = ofs = ','
  114. else:
  115. try:
  116. ifs, ofs = fs.split(',')
  117. except ValueError:
  118. ifs = ofs = fs
  119. ifs = ifs.lower()
  120. ofs = ofs.lower()
  121. if ifs in ('space', 'tab'):
  122. ifs = ' '
  123. elif ifs == 'comma':
  124. ifs = ','
  125. else:
  126. if len(ifs) > 1:
  127. grass.warning(_("Invalid field separator, using '%s'") % ifs[0])
  128. try:
  129. ifs = ifs[0]
  130. except IndexError:
  131. grass.fatal(_("Invalid field separator '%s'") % ifs)
  132. if ofs.lower() == 'space':
  133. ofs = ' '
  134. elif ofs.lower() == 'tab':
  135. ofs = '\t'
  136. elif ofs.lower() == 'comma':
  137. ofs = ','
  138. else:
  139. if len(ofs) > 1:
  140. grass.warning(_("Invalid field separator, using '%s'") % ofs[0])
  141. try:
  142. ofs = ofs[0]
  143. except IndexError:
  144. grass.fatal(_("Invalid field separator '%s'") % ifs)
  145. #### set up projection params
  146. s = grass.read_command("g.proj", flags='j')
  147. kv = grass.parse_key_val(s)
  148. if "XY location" in kv['+proj'] and (ll_in or ll_out):
  149. grass.fatal(_("Unable to project to or from a XY location"))
  150. in_proj = None
  151. if ll_in:
  152. in_proj = "+proj=longlat +datum=WGS84"
  153. grass.verbose("Assuming LL WGS84 as input, current projection as output ")
  154. if ll_out:
  155. in_proj = grass.read_command('g.proj', flags = 'jf')
  156. if proj_in:
  157. in_proj = proj_in
  158. if not in_proj:
  159. grass.verbose("Assuming current location as input")
  160. in_proj = grass.read_command('g.proj', flags = 'jf')
  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 = ["-w5"]
  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. if not copy_input:
  217. if include_header:
  218. outf.write("x%sy%sz\n" % (ofs, ofs))
  219. for line in p.communicate()[0].splitlines():
  220. x, yz = line.split('\t')
  221. y, z = yz.split(' ')
  222. outf.write('%s%s%s%s%s\n' % \
  223. (x.strip(), ofs, y.strip(), ofs, z.strip()))
  224. else:
  225. if include_header:
  226. outf.write("input_x%sinput_y%sx%sy%sz\n" % (ofs, ofs, ofs, ofs))
  227. for line in p.communicate()[0].splitlines():
  228. inX, therest, z = line.split(' ')
  229. inY, x, y = therest.split('\t')
  230. outf.write('%s%s%s%s%s%s%s%s%s\n' % \
  231. (inX.strip(), ofs, inY.strip(), ofs, x.strip(), \
  232. ofs, y.strip(), ofs, z.strip()))
  233. if p.returncode != 0:
  234. grass.warning(_("Projection transform probably failed, please investigate"))
  235. if __name__ == "__main__":
  236. options, flags = grass.parser()
  237. main()