m.proj.py 8.4 KB

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