File: runner.py

package info (click to toggle)
python-mpop 1.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 20,516 kB
  • ctags: 1,877
  • sloc: python: 15,374; xml: 820; makefile: 90; sh: 8
file content (272 lines) | stat: -rw-r--r-- 9,076 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2010, 2011, 2012.

# SMHI,
# Folkborgsvägen 1,
# Norrköping, 
# Sweden

# Author(s):
 
#   Martin Raspaud <martin.raspaud@smhi.se>

# This file is part of mpop.

# mpop is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.

# mpop is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

# You should have received a copy of the GNU General Public License along with
# mpop.  If not, see <http://www.gnu.org/licenses/>.

"""Batch run stuff.
"""
import datetime
import getopt
import logging
import sys

from mpop.channel import NotLoadedError
from mpop.satellites import get_sat_instr_compositer
from mpop.saturn.tasklist import TaskList
from mpop.satellites import GenericFactory


LOG = logging.getLogger("runner")

def usage(scriptname):
    """Print usefull information for running the script.
    """
    print("""
usage: %s [options]

Available options:
    -r
    --rgb
        Output only the pure rgb images from the product list
    -p
    --pge
        Output only the cloudproduct derived images from the product list
    -d <date_str>
    --date <date_str>
        Run on the specified date (eg. 200910081430)
    -a <area_name>
    --area <area_name>
        Run on the specified area (eg. eurol)
    -c <name>
    --composite <name>
        Output the specified composite. Available composites are:
        overview
        natural
        fog
        nightfog
        convection
        airmass
        ir9
        wv_low
        wv_high
        greensnow
        redsnow
        cloudtop
        hr_overview
        PGE02
        PGE02b
        PGE02bj
        PGE02c
        PGE02cj
        PGE02d
        PGE02e
        PGE03
        CtypeHDF
        NordRad
        CtthHDF
    -v
        Be verbose
    --vv
        Be very verbose
    -h
    --help
        Print this message
          """%scriptname)

def parse_options():
    """Parse command line options.
    """

    time_slots = []
    console = logging.StreamHandler()
    console.setFormatter(logging.Formatter("[%(levelname)s: %(asctime)s :"
                                           " %(name)s] %(message)s",
                                           '%Y-%m-%d %H:%M:%S'))
    try:
        opts, args = getopt.getopt(sys.argv[1:],
                                   "hd:va:c:pr",
                                   ["vv", "help", "date=", "pge", "rgb",
                                    "area=", "composite="])
        del args
    except getopt.GetoptError, err:
        print err
        usage(sys.argv[0])
        sys.exit(2)

    mode = set([])
    areas = set([])
    composites = set([])

    for opt, arg in opts:
        if opt == "-v":
            console.setLevel(logging.INFO)
            logging.getLogger('').addHandler(console)
        elif opt == "--vv":
            console.setLevel(logging.DEBUG)
            logging.getLogger('').addHandler(console)
        elif opt in ("-h", "--help"):
            usage(sys.argv[0])
            sys.exit()
        elif opt in ("-d", "--date"):
            time_slots.append(datetime.datetime.strptime(arg, "%Y%m%d%H%M"))
        elif opt in ("-p", "--pge"):
            mode |= set(["pge"])
        elif opt in ("-r", "--rgb"):
            mode |= set(["rgb"])
        elif opt in ("-a", "--area"):
            areas |= set([arg])
        elif opt in ("-c", "--composites"):
            composites |= set([arg])
        else:
            raise ValueError("Option %s not recognized.")

    return time_slots, mode, areas, composites


class SequentialRunner(object):
    """Runs scenes in a sequential order, as opposed to parallelized running.
    """

    def __init__(self, satellite, instrument, tasklist, precompute=False):
        if isinstance(tasklist, str):
            tasklist = TaskList(tasklist)
        self.tasklist = tasklist
        self.data = None
        self.satellite = satellite[0]
        self.number = satellite[1]
        self.variant = satellite[2]
        self.instrument = instrument 

        self.klass = get_sat_instr_compositer((self.satellite,
                                               self.number,
                                               self.variant),
                                              self.instrument)
        self.precompute = precompute
        self.running = True

    def stop(self):
        """Stops the runner.
        """
        self.running = False

    def run_from_cmd(self):
        """Batch run mpop.
        """
        time_slots, mode, areas, composites = parse_options()
                
        tasklist = self.tasklist.shape(self.klass, mode, areas, composites)
        
        for time_slot in time_slots:
            self.data = GenericFactory.create_scene(self.satellite,
                                                    self.number,
                                                    self.instrument,
                                                    time_slot,
                                                    orbit=None,
                                                    variant=self.variant)
            prerequisites = tasklist.get_prerequisites(self.klass)
            self.data.load(prerequisites)
            self.run_from_data(tasklist)
                                

    def run_from_data(self, tasklist=None, radius=None):
        """Run on given data.
        """
        if tasklist is None:
            tasklist = self.tasklist
        for area, productlist in tasklist.items():
            prerequisites = tasklist.get_prerequisites(self.klass, area)
            if not self.running:
                LOG.info("Running interrupted")
                return
            local_data = self.data.project(area, prerequisites, self.precompute,
                                           mode="nearest", radius=radius)
            for product, flist in productlist.items():
                fun = getattr(local_data.image, product)
                flist = flist.put_date(local_data.time_slot)
                metadata = {"area": area}
                LOG.info("Orbit = " + str(local_data.orbit))
                if local_data.orbit is not None:
                    metadata["orbit"] = int(local_data.orbit)
                LOG.info("Instrument Name = " + str(local_data.instrument_name))
                if local_data.instrument_name is not None:
                    metadata["instrument_name"] = str(local_data.instrument_name)

                flist = flist.put_metadata(metadata)
                try:
                    LOG.debug("Doing "+product+".")
                    if not self.running:
                        del local_data
                        LOG.info("Running interrupted")
                        return
                    img = fun()
                    flist.save_object(img)
                    del img
                except (NotLoadedError, KeyError, ValueError), err:
                    LOG.warning("Error in "+product+": "+str(err))
                    LOG.info("Skipping "+product)
            del local_data

    def run_from_local_data(self, tasklist=None, extra_tags=None):
        """Run on given local data (already projected).
        """
        if tasklist is None:
            tasklist = self.tasklist
        metadata = {}
            
        area_name = self.data.area_id or self.data.area_def.area_id
        tasks, dummy = tasklist.split(area_name)
        if area_name not in tasks:
            LOG.debug("Nothing to do for " + area_name)
            return
        for product, flist in tasks[area_name].items():
            try:
                fun = getattr(self.data.image, product)
            except AttributeError:
                LOG.warning("Missing composite function: " + str(product))
                continue
            flist = flist.put_date(self.data.time_slot)

            if self.data.orbit is not None:
                metadata["orbit"] = int(self.data.orbit)
            LOG.info("Instrument Name = " + str(self.data.instrument_name))
            if self.data.instrument_name is not None:
                metadata["instrument_name"] = str(self.data.instrument_name)
            metadata["satellite"] = self.data.fullname
            metadata["area"] = area_name
            flist = flist.put_metadata(metadata)
            try:
                LOG.debug("Doing "+product+".")
                img = fun()
                if extra_tags:
                    img.tags.update(extra_tags)
                flist.save_object(img)
                del img
            except (NotLoadedError, KeyError), err:
                LOG.warning("Error in "+product+": "+str(err))
                LOG.info("Skipping "+product) 
        
if __name__ == "__main__":
    pass