Completed
Pull Request — develop (#12)
by Adam
30s
created

get_arguments()   B

Complexity

Conditions 1

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
c 0
b 0
f 0
dl 0
loc 40
rs 8.8571
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
4
# Copyright (c) 2016-2017 Adam.Dybbroe
5
6
# Author(s):
7
8
#   Adam.Dybbroe <[email protected]>
9
10
# This program is free software: you can redistribute it and/or modify
11
# it under the terms of the GNU General Public License as published by
12
# the Free Software Foundation, either version 3 of the License, or
13
# (at your option) any later version.
14
15
# This program is distributed in the hope that it will be useful,
16
# but WITHOUT ANY WARRANTY; without even the implied warranty of
17
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
# GNU General Public License for more details.
19
20
# You should have received a copy of the GNU General Public License
21
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
23
"""A very basic (example) plotting program to display spectral responses for a
24
set of satellite instruments for a give wavelength range
25
26
"""
27
28
import matplotlib.pyplot as plt
29
from pyspectral.rsr_reader import RelativeSpectralResponse
30
from pyspectral.utils import get_bandname_from_wavelength
31
#import logging
32
from pyspectral.utils import logging_on, logging_off, get_logger
33
import numpy as np
34
35
36
def plot_band(plt_in, band_name, spec_response, pltname=None):
37
    """Do the plotting of one band"""
38
39
    detectors = spec_response[band_name].keys()
40
    # for det in detectors:
41
    det = detectors[0]
42
    resp = spec_response[band_name][det]['response']
43
    wvl = spec_response[band_name][det]['wavelength']
44
45
    resp = np.ma.masked_less_equal(resp, minimum_response)
46
    wvl = np.ma.masked_array(wvl, resp.mask)
47
    resp.compressed()
48
    wvl.compressed()
49
50
    # plt.plot(wvl, resp, label='{platform} - {sensor} - {band}'.format(
51
    #    platform=platform, sensor=sensor, band=band))
52
    if pltname:
53
        plt_in.plot(wvl, resp, label='{platform} - {band}'.format(
54
            platform=pltname, band=band_name))
55
    else:
56
        plt_in.plot(wvl, resp, label='{band}'.format(band=band_name))
57
58
    return plt_in
59
60
61
def get_arguments():
62
    """Get the command line arguments"""
63
64
    import argparse
65
    parser = argparse.ArgumentParser(
66
        description='Plot spectral responses for a set of satellite imagers')
67
68
    parser.add_argument("--platform_name", '-p', nargs='*',
69
                        help="The Platform name",
70
                        type=str, required=True)
71
    parser.add_argument("--sensor", '-s', nargs='*',
72
                        help="The sensor/instrument name",
73
                        type=str, required=True)
74
    parser.add_argument("-x", "--xlimits", nargs=2,
75
                        help=("x-axis boundaries for plot"),
76
                        default=None, type=float)
77
    parser.add_argument("-t", "--minimum_response",
78
                        help=("Minimum response: Any response lower than " +
79
                              "this will be ignored when plotting"),
80
                        default=0.015, type=float)
81
82
    parser.add_argument("-no_platform_name_in_legend", help=("No platform name in legend"),
83
                        action='store_true')
84
    parser.add_argument("--title", help=("Plot title"),
85
                        default=None, type=str)
86
    parser.add_argument("-o", "--filename", help=("Output plot file name"),
87
                        default=None, type=str)
88
    parser.add_argument(
89
        "-v", '--verbose', help=("Turn logging on"), action='store_true')
90
91
    group = parser.add_mutually_exclusive_group(required=True)
92
    group.add_argument("--bandname", '-b',
93
                       help="The sensor band name", type=str)
94
    group.add_argument("--wavelength", "-w", type=float,
95
                       help='the approximate spectral wavelength in micron')
96
    group.add_argument("--range", "-r", nargs='*',
97
                       help="The wavelength range for the plot",
98
                       default=[None, None], type=float)
99
100
    return parser.parse_args()
101
102
if __name__ == "__main__":
103
    import sys
104
105
    args = get_arguments()
106
107
    LOG = get_logger(__name__)
108
109
    platform_names = args.platform_name
110
    sensors = args.sensor
111
    minimum_response = args.minimum_response
112
    xlimits = args.xlimits
113
    title = args.title
114
    if not title:
115
        title = 'Relative Spectral Responses'
116
    filename = args.filename
117
    no_platform_name_in_legend = args.no_platform_name_in_legend
118
    verbose = args.verbose
119
120
    if verbose:
121
        logging_on()
122
    else:
123
        logging_off()
124
125
    req_wvl = None
126
    band = None
127
    wvlmin, wvlmax = args.range
128
    if args.bandname:
129
        band = args.bandname
130
    elif args.wavelength:
131
        req_wvl = args.wavelength
132
133
    figscale = 1.0
134
    if wvlmin:
135
        figscale = (wvlmax - wvlmin) / 4.
136
    figsize = (figscale * 1. + 10, figscale * 0.5 + 5)
137
138
    plt.figure(figsize=figsize)
139
    something2plot = False
140
    for platform in platform_names:
141
        for sensor in sensors:
142
            try:
143
                rsr = RelativeSpectralResponse(platform, sensor)
144
            except IOError:
145
                # LOG.exception('Failed getting the rsr data for platform %s ' +
146
                #               'and sensor %s', platform, sensor)
147
                rsr = None
148
            else:
149
                break
150
151
        if not rsr:
152
            continue
153
154
        something2plot = True
155
        if req_wvl:
156
            band = get_bandname_from_wavelength(req_wvl, rsr.rsr, 0.5)
157
            if not band:
158
                continue
159
            if no_platform_name_in_legend:
160
                plt = plot_band(plt, band, rsr.rsr)
161
            else:
162
                plt = plot_band(plt, band, rsr.rsr, platform)
163
        elif band:
164
            if no_platform_name_in_legend:
165
                plt = plot_band(plt, band, rsr.rsr)
166
            else:
167
                plt = plot_band(plt, band, rsr.rsr, platform)
168
        else:
169
            wvlx = wvlmin
170
            prev_band = None
171
            while wvlx < wvlmax:
172
                band = get_bandname_from_wavelength(wvlx, rsr.rsr, 0.05)
173
                wvlx = wvlx + 0.05
174
                if not band:
175
                    continue
176
                if band != prev_band:
177
                    if no_platform_name_in_legend:
178
                        plt = plot_band(plt, band, rsr.rsr)
179
                    else:
180
                        plt = plot_band(plt, band, rsr.rsr, platform)
181
                    prev_band = band
182
183
    if not something2plot:
184
        LOG.error("Nothing to plot!")
185
        sys.exit(0)
186
187
    wmin, wmax = plt.xlim()
188
    delta_x = (wmax - wmin)
189
    wmax = wmax + delta_x / 4.0
190
    if xlimits:
191
        wmin = xlimits[0]
192
        wmax = xlimits[1]
193
194
    plt.xlim((wmin, wmax))
195
196
    plt.title(title)
197
    plt.legend(loc='lower right')
198
    if filename:
199
        plt.savefig(filename)
200
    else:
201
        if req_wvl:
202
            plt.savefig('rsr_band_{:>04d}.png'.format(int(100 * req_wvl)))
203
        elif wvlmin and wvlmax:
204
            plt.savefig('rsr_band_{:>04d}_{:>04d}.png'.format(
205
                int(100 * wvlmin), int(100 * wvlmax)))
206
        else:
207
            plt.savefig('rsr_band_{bandname}.png'.format(bandname=band))
208