m.proj.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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-2014 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. #% keyword: miscellaneous
  27. #% keyword: projection
  28. #%end
  29. #%option G_OPT_M_COORDS
  30. #% description: Input coordinates to reproject
  31. #% guisection: Input coordinates
  32. #%end
  33. #%option G_OPT_F_INPUT
  34. #% label: Name of input coordinate file
  35. #% description: '-' for standard input
  36. #% required: no
  37. #% guisection: Input coordinates
  38. #%end
  39. #%option G_OPT_F_OUTPUT
  40. #% description: Name for output coordinate file (omit to send to stdout)
  41. #% required : no
  42. #% guisection: Output
  43. #%end
  44. #%option G_OPT_F_SEP
  45. #% label: Field separator (format: input[,output])
  46. #% required : no
  47. #% guisection: Input coordinates
  48. #%end
  49. #%option
  50. #% key: proj_in
  51. #% type: string
  52. #% description: Input projection parameters (PROJ.4 style)
  53. #% required : no
  54. #% guisection: Projections
  55. #%end
  56. #%option
  57. #% key: proj_out
  58. #% type: string
  59. #% description: Output projection parameters (PROJ.4 style)
  60. #% required : no
  61. #% guisection: Projections
  62. #%end
  63. #%flag
  64. #% key: i
  65. #% description: Use LL WGS84 as input and current location as output projection
  66. #% guisection: Projections
  67. #%end
  68. #%flag
  69. #% key: o
  70. #% description: Use current location as input and LL WGS84 as output projection
  71. #% guisection: Projections
  72. #%end
  73. #%flag
  74. #% key: d
  75. #% description: Output long/lat in decimal degrees, or other projections with many decimal places
  76. #% guisection: Output
  77. #%end
  78. #%flag
  79. #% key: e
  80. #% description: Include input coordinates in output file
  81. #% guisection: Output
  82. #%end
  83. #%flag
  84. #% key: c
  85. #% description: Include column names in output file
  86. #% guisection: Output
  87. #%end
  88. import sys
  89. import os
  90. import threading
  91. from grass.script.utils import separator, parse_key_val
  92. from grass.script import core as grass
  93. class TrThread(threading.Thread):
  94. def __init__(self, ifs, inf, outf):
  95. threading.Thread.__init__(self)
  96. self.ifs = ifs
  97. self.inf = inf
  98. self.outf = outf
  99. def run(self):
  100. while True:
  101. line = self.inf.readline()
  102. if not line:
  103. break
  104. line = line.replace(self.ifs, ' ')
  105. self.outf.write(line)
  106. self.outf.flush()
  107. self.outf.close()
  108. def main():
  109. coords = options['coordinates']
  110. input = options['input']
  111. output = options['output']
  112. fs = options['separator']
  113. proj_in = options['proj_in']
  114. proj_out = options['proj_out']
  115. ll_in = flags['i']
  116. ll_out = flags['o']
  117. decimal = flags['d']
  118. copy_input = flags['e']
  119. include_header = flags['c']
  120. #### check for cs2cs
  121. if not grass.find_program('cs2cs'):
  122. grass.fatal(_("cs2cs program not found, install PROJ.4 first: http://proj.maptools.org"))
  123. #### check for overenthusiasm
  124. if proj_in and ll_in:
  125. grass.fatal(_("Choose only one input parameter method"))
  126. if proj_out and ll_out:
  127. grass.fatal(_("Choose only one output parameter method"))
  128. if ll_in and ll_out:
  129. grass.fatal(_("Choise only one auto-projection parameter method"))
  130. if output and not grass.overwrite() and os.path.exists(output):
  131. grass.fatal(_("Output file already exists"))
  132. if not coords and not input:
  133. grass.fatal(_("One of <coordinates> and <input> must be given"))
  134. if coords and input:
  135. grass.fatal(_("Options <coordinates> and <input> are mutually exclusive"))
  136. #### parse field separator
  137. # FIXME: input_x,y needs to split on multiple whitespace between them
  138. if fs == ',':
  139. ifs = ofs = ','
  140. else:
  141. try:
  142. ifs, ofs = fs.split(',')
  143. except ValueError:
  144. ifs = ofs = fs
  145. ifs = separator(ifs)
  146. ofs = separator(ofs)
  147. #### set up projection params
  148. s = grass.read_command("g.proj", flags='j')
  149. kv = 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 coords:
  179. x, y = coords.split(',')
  180. tmpfile = grass.tempfile()
  181. fd = open(tmpfile, "w")
  182. fd.write("%s%s%s\n" % (x, ifs, y))
  183. fd.close()
  184. inf = file(tmpfile)
  185. else:
  186. if input == '-':
  187. infile = None
  188. inf = sys.stdin
  189. else:
  190. infile = input
  191. if not os.path.exists(infile):
  192. grass.fatal(_("Unable to read input data"))
  193. inf = file(infile)
  194. grass.debug("input file=[%s]" % infile)
  195. #### set up output file
  196. if not output:
  197. outfile = None
  198. outf = sys.stdout
  199. else:
  200. outfile = output
  201. outf = open(outfile, 'w')
  202. grass.debug("output file=[%s]" % outfile)
  203. #### set up output style
  204. if not decimal:
  205. outfmt = ["-w5"]
  206. else:
  207. outfmt = ["-f", "%.8f"]
  208. if not copy_input:
  209. copyinp = []
  210. else:
  211. copyinp = ["-E"]
  212. #### do the conversion
  213. # Convert cs2cs DMS format to GRASS DMS format:
  214. # cs2cs | sed -e 's/d/:/g' -e "s/'/:/g" -e 's/"//g'
  215. cmd = ['cs2cs'] + copyinp + outfmt + in_proj.split() + ['+to'] + out_proj.split()
  216. p = grass.Popen(cmd, stdin = grass.PIPE, stdout = grass.PIPE)
  217. tr = TrThread(ifs, inf, p.stdin)
  218. tr.start()
  219. if not copy_input:
  220. if include_header:
  221. outf.write("x%sy%sz\n" % (ofs, ofs))
  222. for line in p.stdout:
  223. try:
  224. xy, z = line.split(' ', 1)
  225. x, y = xy.split('\t')
  226. except ValueError:
  227. grass.fatal(line)
  228. outf.write('%s%s%s%s%s\n' % \
  229. (x.strip(), ofs, y.strip(), ofs, z.strip()))
  230. else:
  231. if include_header:
  232. outf.write("input_x%sinput_y%sx%sy%sz\n" % (ofs, ofs, ofs, ofs))
  233. for line in p.stdout:
  234. inXYZ, x, rest = line.split('\t')
  235. inX, inY = inXYZ.split(' ')[:2]
  236. y, z = rest.split(' ', 1)
  237. outf.write('%s%s%s%s%s%s%s%s%s\n' % \
  238. (inX.strip(), ofs, inY.strip(), ofs, x.strip(), \
  239. ofs, y.strip(), ofs, z.strip()))
  240. p.wait()
  241. if p.returncode != 0:
  242. grass.warning(_("Projection transform probably failed, please investigate"))
  243. if __name__ == "__main__":
  244. options, flags = grass.parser()
  245. main()