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

get_arguments()   B

Complexity

Conditions 1

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
c 0
b 0
f 0
dl 0
loc 39
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, rsr_obj, **kwargs):
37
    """Do the plotting of one band"""
38
    if 'platform_name_in_legend' in kwargs:
39
        platform_name_in_legend = kwargs['platform_name_in_legend']
40
    else:
41
        platform_name_in_legend = False
42
43
    detectors = rsr_obj.rsr[band_name].keys()
44
    # for det in detectors:
45
    det = detectors[0]
46
    resp = rsr_obj.rsr[band_name][det]['response']
47
    wvl = rsr_obj.rsr[band_name][det]['wavelength']
48
49
    resp = np.ma.masked_less_equal(resp, minimum_response)
50
    wvl = np.ma.masked_array(wvl, resp.mask)
51
    resp.compressed()
52
    wvl.compressed()
53
54
    if platform_name_in_legend:
55
        plt_in.plot(wvl, resp, label='{platform} - {band}'.format(
56
            platform=rsr_obj.platform_name, band=band_name))
57
    else:
58
        plt_in.plot(wvl, resp, label='{band}'.format(band=band_name))
59
60
    return plt_in
61
62
63
def get_arguments():
64
    """Get the command line arguments"""
65
    import argparse
66
    parser = argparse.ArgumentParser(
67
        description='Plot spectral responses for a set of satellite imagers')
68
69
    parser.add_argument("--platform_name", '-p', nargs='*',
70
                        help="The Platform name",
71
                        type=str, required=True)
72
    parser.add_argument("--sensor", '-s', nargs='*',
73
                        help="The sensor/instrument name",
74
                        type=str, required=True)
75
    parser.add_argument("-x", "--xlimits", nargs=2,
76
                        help=("x-axis boundaries for plot"),
77
                        default=None, type=float)
78
    parser.add_argument("-t", "--minimum_response",
79
                        help=("Minimum response: Any response lower than " +
80
                              "this will be ignored when plotting"),
81
                        default=0.015, type=float)
82
83
    parser.add_argument("-no_platform_name_in_legend", help=("No platform name in legend"),
84
                        action='store_true')
85
    parser.add_argument("--title", help=("Plot title"),
86
                        default=None, type=str)
87
    parser.add_argument("-o", "--filename", help=("Output plot file name"),
88
                        default=None, type=str)
89
    parser.add_argument(
90
        "-v", '--verbose', help=("Turn logging on"), action='store_true')
91
92
    group = parser.add_mutually_exclusive_group(required=True)
93
    group.add_argument("--bandname", '-b',
94
                       help="The sensor band name", type=str)
95
    group.add_argument("--wavelength", "-w", type=float,
96
                       help='the approximate spectral wavelength in micron')
97
    group.add_argument("--range", "-r", nargs='*',
98
                       help="The wavelength range for the plot",
99
                       default=[None, None], type=float)
100
101
    return parser.parse_args()
102
103
if __name__ == "__main__":
104
    import sys
105
106
    args = get_arguments()
107
108
    LOG = get_logger(__name__)
109
110
    platform_names = args.platform_name
111
    sensors = args.sensor
112
    minimum_response = args.minimum_response
113
    xlimits = args.xlimits
114
    title = args.title
115
    if not title:
116
        title = 'Relative Spectral Responses'
117
    filename = args.filename
118
    no_platform_name_in_legend = args.no_platform_name_in_legend
119
    verbose = args.verbose
120
121
    if verbose:
122
        logging_on()
123
    else:
124
        logging_off()
125
126
    req_wvl = None
127
    band = None
128
    wvlmin, wvlmax = args.range
129
    if args.bandname:
130
        band = args.bandname
131
    elif args.wavelength:
132
        req_wvl = args.wavelength
133
134
    figscale = 1.0
135
    if wvlmin:
136
        figscale = (wvlmax - wvlmin) / 4.
137
    figsize = (figscale * 1. + 10, figscale * 0.5 + 5)
138
139
    plt.figure(figsize=figsize)
140
    something2plot = False
141
    for platform in platform_names:
142
        for sensor in sensors:
143
            try:
144
                rsr = RelativeSpectralResponse(platform, sensor)
145
            except IOError:
146
                # LOG.exception('Failed getting the rsr data for platform %s ' +
147
                #               'and sensor %s', platform, sensor)
148
                rsr = None
149
            else:
150
                break
151
152
        if not rsr:
153
            continue
154
155
        something2plot = True
156
        if req_wvl:
157
            band = get_bandname_from_wavelength(req_wvl, rsr.rsr, 0.5)
158
            if not band:
159
                continue
160
            plt = plot_band(plt, band, rsr,
161
                            platform_name_in_legend=(not no_platform_name_in_legend))
162
        elif band:
163
            plt = plot_band(plt, band, rsr,
164
                            platform_name_in_legend=(not no_platform_name_in_legend))
165
        else:
166
            wvlx = wvlmin
167
            prev_band = None
168
            while wvlx < wvlmax:
169
                band = get_bandname_from_wavelength(wvlx, rsr.rsr, 0.05)
170
                wvlx = wvlx + 0.05
171
                if not band:
172
                    continue
173
                if band != prev_band:
174
                    plt = plot_band(plt, band, rsr,
175
                                    platform_name_in_legend=(not no_platform_name_in_legend))
176
                    prev_band = band
177
178
    if not something2plot:
179
        LOG.error("Nothing to plot!")
180
        sys.exit(0)
181
182
    wmin, wmax = plt.xlim()
183
    delta_x = (wmax - wmin)
184
    wmax = wmax + delta_x / 4.0
185
    if xlimits:
186
        wmin = xlimits[0]
187
        wmax = xlimits[1]
188
189
    plt.xlim((wmin, wmax))
190
191
    plt.title(title)
192
    plt.legend(loc='lower right')
193
    if filename:
194
        plt.savefig(filename)
195
    else:
196
        if req_wvl:
197
            plt.savefig('rsr_band_{:>04d}.png'.format(int(100 * req_wvl)))
198
        elif wvlmin and wvlmax:
199
            plt.savefig('rsr_band_{:>04d}_{:>04d}.png'.format(
200
                int(100 * wvlmin), int(100 * wvlmax)))
201
        else:
202
            plt.savefig('rsr_band_{bandname}.png'.format(bandname=band))
203