~ubuntu-branches/ubuntu/vivid/grass/vivid-proposed

« back to all changes in this revision

Viewing changes to scripts/i.spectral/i.spectral.py

  • Committer: Package Import Robot
  • Author(s): Bas Couwenberg
  • Date: 2015-02-20 23:12:08 UTC
  • mfrom: (8.2.6 experimental)
  • Revision ID: package-import@ubuntu.com-20150220231208-1u6qvqm84v430b10
Tags: 7.0.0-1~exp1
* New upstream release.
* Update python-ctypes-ternary.patch to use if/else instead of and/or.
* Drop check4dev patch, rely on upstream check.
* Add build dependency on libpq-dev to grass-dev for libpq-fe.h.
* Drop patches applied upstream, refresh remaining patches.
* Update symlinks for images switched from jpg to png.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
 
 
3
############################################################################
 
4
#
 
5
# MODULE:       i.spectral
 
6
# AUTHOR(S):    Markus Neteler, 18. August 1998
 
7
#               Converted to Python by Glynn Clements
 
8
# PURPOSE:      Displays spectral response at user specified locations in
 
9
#               group or raster images
 
10
# COPYRIGHT:    (C) 1999-2013 by the GRASS Development Team
 
11
#
 
12
#               This program is free software under the GNU General Public
 
13
#               License (>=v2). Read the file COPYING that comes with GRASS
 
14
#               for details.
 
15
#
 
16
#############################################################################
 
17
#
 
18
#  this script needs gnuplot for pretty rendering
 
19
#  TODO: use PyPlot like the wxGUI Profiling tool
 
20
#
 
21
# written by Markus Neteler 18. August 1998
 
22
#            neteler geog.uni-hannover.de
 
23
 
24
# bugfix: 25. Nov.98/20. Jan. 1999
 
25
# 3 March 2006: Added multiple images and group support by Francesco Pirotti - CIRGEO
 
26
#
 
27
 
 
28
#%Module
 
29
#% description: Displays spectral response at user specified locations in group or images.
 
30
#% keyword: imagery
 
31
#% keyword: querying
 
32
#% keyword: raster
 
33
#% keyword: multispectral
 
34
#%End
 
35
#%option G_OPT_I_GROUP
 
36
#% required : no
 
37
#% guisection: Input
 
38
#%end
 
39
#%option G_OPT_R_INPUTS
 
40
#% key: raster
 
41
#% required : no
 
42
#% guisection: Input
 
43
#%end
 
44
#%option G_OPT_M_COORDS
 
45
#% multiple: yes
 
46
#% required: yes
 
47
#% guisection: Input
 
48
#%end
 
49
#%option G_OPT_F_OUTPUT
 
50
#% key: output
 
51
#% description: Name for output image
 
52
#% guisection: Output
 
53
#% required : no
 
54
#%end
 
55
#%Option
 
56
#% key: format
 
57
#% type: string
 
58
#% description: Graphics format for output file
 
59
#% options: png,eps,svg
 
60
#% answer: png
 
61
#% multiple: no
 
62
#% guisection: Output
 
63
#%End
 
64
#%flag
 
65
#% key: c
 
66
#% description: Show sampling coordinates instead of numbering in the legend
 
67
#%end
 
68
#% flag
 
69
#% key: g
 
70
#% description: Use gnuplot for display
 
71
#%end
 
72
 
 
73
import os
 
74
import atexit
 
75
from grass.script.utils import try_rmdir
 
76
from grass.script import core as grass
 
77
 
 
78
 
 
79
def cleanup():
 
80
    try_rmdir(tmp_dir)
 
81
 
 
82
 
 
83
def draw_gnuplot(what, xlabels, output, img_format, coord_legend):
 
84
    xrange = 0
 
85
 
 
86
    for i, row in enumerate(what):
 
87
        outfile = os.path.join(tmp_dir, 'data_%d' % i)
 
88
        outf = open(outfile, 'w')
 
89
        xrange = max(xrange, len(row) - 2)
 
90
        for j, val in enumerate(row[3:]):
 
91
            outf.write("%d %s\n" % (j + 1, val))
 
92
        outf.close()
 
93
 
 
94
    # build gnuplot script
 
95
    lines = []
 
96
    if output:
 
97
        if img_format == 'png':
 
98
            term_opts = "png truecolor large size 825,550"
 
99
        elif img_format == 'eps':
 
100
            term_opts = "postscript eps color solid size 6,4"
 
101
        elif img_format == 'svg':
 
102
            term_opts = "svg size 825,550 dynamic solid"
 
103
        else:
 
104
            grass.fatal(_("Programmer error (%s)") % img_format)
 
105
 
 
106
        lines += [
 
107
            "set term " + term_opts,
 
108
            "set output '%s'" % output
 
109
        ]
 
110
 
 
111
    lines += [
 
112
        "set xtics (%s)" % xlabels,
 
113
        "set grid",
 
114
        "set title 'Spectral signatures'",
 
115
        "set xrange [0.5 : %d - 0.5]" % xrange,
 
116
        "set noclabel",
 
117
        "set xlabel 'Bands'",
 
118
        "set xtics rotate by -40",
 
119
        "set ylabel 'DN Value'",
 
120
        "set style data lines"
 
121
    ]
 
122
 
 
123
    cmd = []
 
124
    for i, row in enumerate(what):
 
125
        if not coord_legend:
 
126
            title = 'Pick ' + str(i + 1)
 
127
        else:
 
128
            title = str(tuple(row[0:2]))
 
129
 
 
130
        x_datafile = os.path.join(tmp_dir, 'data_%d' % i)
 
131
        cmd.append(" '%s' title '%s'" % (x_datafile, title))
 
132
 
 
133
    cmd = ','.join(cmd)
 
134
    cmd = ' '.join(['plot', cmd, "with linespoints pt 779"])
 
135
    lines.append(cmd)
 
136
 
 
137
    plotfile = os.path.join(tmp_dir, 'spectrum.gnuplot')
 
138
    plotf = open(plotfile, 'w')
 
139
    for line in lines:
 
140
        plotf.write(line + '\n')
 
141
    plotf.close()
 
142
 
 
143
    if output:
 
144
        grass.call(['gnuplot', plotfile])
 
145
    else:
 
146
        grass.call(['gnuplot', '-persist', plotfile])
 
147
 
 
148
 
 
149
def draw_linegraph(what):
 
150
    yfiles = []
 
151
 
 
152
    xfile = os.path.join(tmp_dir, 'data_x')
 
153
 
 
154
    xf = open(xfile, 'w')
 
155
    for j, val in enumerate(what[0][3:]):
 
156
        xf.write("%d\n" % (j + 1))
 
157
    xf.close()
 
158
 
 
159
    for i, row in enumerate(what):
 
160
        yfile = os.path.join(tmp_dir, 'data_y_%d' % i)
 
161
        yf = open(yfile, 'w')
 
162
        for j, val in enumerate(row[3:]):
 
163
            yf.write("%s\n" % val)
 
164
        yf.close()
 
165
        yfiles.append(yfile)
 
166
 
 
167
    sienna = '#%02x%02x%02x' % (160,  82, 45)
 
168
    coral = '#%02x%02x%02x' % (255, 127, 80)
 
169
    gp_colors = ['red', 'green', 'blue', 'magenta', 'cyan', sienna, 'orange',
 
170
                 coral]
 
171
 
 
172
    colors = gp_colors
 
173
    while len(what) > len(colors):
 
174
        colors += gp_colors
 
175
    colors = colors[0:len(what)]
 
176
 
 
177
    grass.run_command('d.linegraph', x_file=xfile, y_file=yfiles,
 
178
                      y_color=colors, title='Spectral signatures',
 
179
                      x_title='Bands', y_title='DN Value')
 
180
 
 
181
 
 
182
def main():
 
183
    group = options['group']
 
184
    raster = options['raster']
 
185
    output = options['output']
 
186
    coords = options['coordinates']
 
187
    img_fmt = options['format']
 
188
    coord_legend = flags['c']
 
189
    gnuplot = flags['g']
 
190
    
 
191
    global tmp_dir
 
192
    tmp_dir = grass.tempdir()
 
193
    
 
194
    if not group and not raster:
 
195
        grass.fatal(_("Either group= or raster= is required"))
 
196
 
 
197
    if group and raster:
 
198
        grass.fatal(_("group= and raster= are mutually exclusive"))
 
199
 
 
200
    # check if gnuplot is present
 
201
    if gnuplot and not grass.find_program('gnuplot', '-V'):
 
202
        grass.fatal(_("gnuplot required, please install first"))
 
203
 
 
204
    # get data from group listing and set the x-axis labels
 
205
    if group:
 
206
        # Parse the group list output
 
207
        s = grass.read_command('i.group', flags='g', group=group, quiet=True)
 
208
        rastermaps = s.splitlines()
 
209
    else:
 
210
        # get data from list of files and set the x-axis labels
 
211
        rastermaps = raster.split(',')
 
212
 
 
213
    xlabels = ["'%s' %d" % (n, i + 1) for i, n in enumerate(rastermaps)]
 
214
    xlabels = ','.join(xlabels)
 
215
 
 
216
    # get y-data for gnuplot-data file
 
217
    what = []
 
218
    s = grass.read_command('r.what', map=rastermaps, coordinates=coords,
 
219
                           null='0', quiet=True)
 
220
    if len(s) == 0:
 
221
        grass.fatal(_('No data returned from query'))
 
222
 
 
223
    for l in s.splitlines():
 
224
        f = l.split('|')
 
225
        for i, v in enumerate(f):
 
226
            if v in ['', '*']:
 
227
                f[i] = 0
 
228
            else:
 
229
                f[i] = float(v)
 
230
        what.append(f)
 
231
 
 
232
    # build data files
 
233
    if gnuplot:
 
234
        draw_gnuplot(what, xlabels, output, img_fmt, coord_legend)
 
235
    else:
 
236
        draw_linegraph(what)
 
237
 
 
238
if __name__ == "__main__":
 
239
    options, flags = grass.parser()
 
240
    atexit.register(cleanup)
 
241
    main()