File: eps1a.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 (359 lines) | stat: -rw-r--r-- 11,601 bytes parent folder | download | duplicates (3)
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2010, 2011.

# 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/>.

"""Interface to EPS level 1a format. Uses AAPP and the aapp1b reader.
"""
import glob
import logging
import os.path
import shutil
import subprocess
import tempfile
from ConfigParser import ConfigParser
from mpop.satellites import PolarFactory 
import mpop.satin.aapp1b
import datetime

from mpop import CONFIG_PATH

WORKING_DIR = "/tmp"

SATPOS_DIR = os.path.sep.join(os.environ["AAPP_PREFIX"].split(os.path.sep)[:-1])
SATPOS_DIR = os.path.join(SATPOS_DIR, "data", "satpos")

LOG = logging.getLogger("eps1a loader")

def get_satpos_file(satpos_time, satname):
    """Return the current satpos file
    """
    satpos_file = os.path.join(SATPOS_DIR,
                               "satpos_"+
                               satname+"_"+
                               satpos_time.strftime("%Y%m%d")+".txt")
    if os.path.exists(satpos_file):
	return satpos_file
    elif satpos_time.hour < 2:
        satpos_time -= datetime.timedelta(days=1)
        satpos_file = os.path.join(SATPOS_DIR,
                                   "satpos_"+
                                   satname+"_"+
                                   satpos_time.strftime("%Y%m%d")+".txt")
        return satpos_file
    else:
        raise IOError("Missing satpos file:" + satpos_file)

def load(satscene):
    """Read data from file and load it into *satscene*.
    """
    conf = ConfigParser()
    conf.read(os.path.join(CONFIG_PATH, satscene.fullname + ".cfg"))
    options = {}
    for option, value in conf.items(satscene.instrument_name + "-level1",
                                    raw = True):
        options[option] = value
    CASES[satscene.instrument_name](satscene, options)

def load_avhrr(satscene, options):
    """Read avhrr data from file and load it into *satscene*.
    """

    if "filename" not in options:
        raise IOError("No filename given, cannot load.")
    filename = os.path.join(
        options["dir"],
        (satscene.time_slot.strftime(options["filename"])))

    file_list = glob.glob(satscene.time_slot.strftime(filename))

    if len(file_list) > 1:
        raise IOError("More than one l1a file matching!")
    elif len(file_list) == 0:
        raise IOError("No l1a file matching!: "+
                      satscene.time_slot.strftime(filename))

    
    filename = file_list[0]

    conf = ConfigParser()
    conf.read(os.path.join(CONFIG_PATH, satscene.fullname + ".cfg"))
    new_dir = conf.get(satscene.instrument_name + "-level2", "dir")
    new_name = conf.get(satscene.instrument_name + "-level2", "filename")
    pathname = os.path.join(new_dir, satscene.time_slot.strftime(new_name))

    convert_to_1b(filename, pathname, satscene.time_slot, options["shortname"])
    mpop.satin.aapp1b.load(satscene)
    os.remove(pathname)

def convert_to_1b(in_file, out_file, start_time, shortname):
    """Convert concatenated file to level 1b.
    """
    (handle, tempname) = tempfile.mkstemp(prefix="eps1a_decommuted",
                                          dir=WORKING_DIR)

    os.close(handle)
    del handle
    decommutation(in_file, tempname)
    calibration_navigation(tempname, start_time, shortname)

    LOG.debug("Saving to "+out_file)
    shutil.move(tempname, out_file)

def calibration_navigation(filename, start_time, shortname):
    """Perform calibration on *filename*
    """
    import pysdh2orbnum
    formated_date = start_time.strftime("%d/%m/%y %H:%M:%S.000")
    satpos_file = get_satpos_file(start_time, shortname)
    LOG.debug(formated_date)
    LOG.debug(satpos_file)
    orbit_number = str(pysdh2orbnum.sdh2orbnum(shortname,
                                               formated_date,
                                               satpos_file))
    avhrcl = ("cd /tmp;" +
              "$AAPP_PREFIX/AAPP/bin/avhrcl -c -l -s " +
              shortname + " -d " +
              start_time.strftime("%Y%m%d") + " -h " +
              start_time.strftime("%H%M") + " -n " +
              orbit_number + " " +
              filename)

    LOG.debug("Running " + avhrcl)
    proc = subprocess.Popen(avhrcl, shell=True,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    (out, err) = proc.communicate()
    if out:
        LOG.debug(out)
    if err:
        LOG.error(err)    

    anacl1 = ("cd /tmp;" +
              "$ANA_PATH/bin/ana_lmk_loc -D " + filename)

    LOG.debug("Running " + anacl1)
    proc = subprocess.Popen(anacl1, shell=True,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    (out, err) = proc.communicate()
    if out:
        LOG.debug(out)
    if err:
        LOG.error(err)    
    
    anacl2 = ("cd /tmp;" +
              "$ANA_PATH/bin/ana_estatt -s " + shortname +
              " -d " + start_time.strftime("%Y%m%d") +
              " -h " + start_time.strftime("%H%M") + " -n " +
              orbit_number)

    LOG.debug("Running " + anacl2)
    proc = subprocess.Popen(anacl2, shell=True,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    (out, err) = proc.communicate()
    if out:
        LOG.debug(out)
    if err:
        LOG.error(err)
        
    avhrcl2 = ("cd /tmp;" +
              "$AAPP_PREFIX/AAPP/bin/avhrcl -l -s " +
              shortname + " -d " +
              start_time.strftime("%Y%m%d") + " -h " +
              start_time.strftime("%H%M") + " -n " +
              orbit_number + " " +
              filename)
    LOG.debug("Running " + avhrcl2)
    proc = subprocess.Popen(avhrcl2, shell=True,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    (out, err) = proc.communicate()
    if out:
        LOG.debug(out)
    if err:
        LOG.error(err)


        
def decommutation(filename_from, filename_to):
    """Perform decommutation on *filename_from* and save the result in
    *filename_to*.
    """
    decom = "$AAPP_PREFIX/metop-tools/bin/decom-avhrr-metop"
    flags = "-ignore_degraded_inst_mdr -ignore_degraded_proc_mdr"
    cmd = (decom+" "+
           flags+" "+
           filename_from+" "+
           filename_to)
    LOG.debug("Running " + cmd)
    proc = subprocess.Popen(cmd, shell=True,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    (out, err) = proc.communicate()
    if out:
        LOG.debug(out)
    if err:
        LOG.error(err)
    LOG.debug("Decommutation done")


def get_orbit(time_slot, shortname):
    import pysdh2orbnum
    formated_date = time_slot.strftime("%d/%m/%y %H:%M:%S.000")
    satpos_file = get_satpos_file(time_slot, shortname)
    
    return str(pysdh2orbnum.sdh2orbnum(shortname,
                                       formated_date,
                                       satpos_file))

def concatenate(granules, channels=None):
    """Concatenate eps1a granules.
    """
    if granules[0].file_type.startswith("bzipped"):
        cat_cmd = "bzcat"
    else:
        cat_cmd = "cat"

    new_names = []

    filenames = [os.path.join(granule.directory, granule.file_name)
                 for granule in granules]

    for filename in filenames:
        new_name, ext = os.path.splitext(os.path.basename(filename))
        del ext
        new_name = os.path.join(WORKING_DIR, new_name)
        cmd = (cat_cmd + " " +
               filename + " > " +
               new_name)
        LOG.debug("running " + cmd)
        proc = subprocess.Popen(cmd, shell=True)
        proc.communicate()
        new_names.append(new_name)

    conffile = os.path.join(CONFIG_PATH, granules[0].fullname + ".cfg")
    conf = ConfigParser()
    conf.read(os.path.join(CONFIG_PATH, conffile))
    
    directory = conf.get('avhrr-level1','dir')
    filename = conf.get('avhrr-level1','filename')
    filename = granules[0].time_slot.strftime(filename)
    
    output_name = os.path.join(directory, filename)

    arg_string = " ".join(new_names)

    cmd = "$KAI/kai -i " + arg_string + " -o " + output_name
    proc = subprocess.Popen(cmd, shell=True)
    (out, err) = proc.communicate()
    if out:
        LOG.debug(out)
    if err:
        LOG.error(err)

    #clean up
    for new_name in new_names:
        os.remove(new_name)

    new_dir = conf.get(granules[0].instrument_name + "-level2", "dir")
    new_name = conf.get(granules[0].instrument_name + "-level2", "filename")
    pathname = os.path.join(new_dir, granules[0].time_slot.strftime(new_name))
    shortname = conf.get('avhrr-level1','shortname')
    orbit = get_orbit(granules[0].time_slot, shortname)
    
    convert_to_1b(output_name, pathname, granules[0].time_slot,
                  shortname)
    os.remove(output_name)

    scene = PolarFactory.create_scene(granules[0].satname,
                                      granules[0].number,
                                      granules[0].instrument_name,
                                      granules[0].time_slot,
                                      orbit,
                                      variant=granules[0].variant)
    scene.load(channels)
    os.remove(pathname)
    return scene

def get_lat_lon(satscene, resolution):
    """Read lat and lon.
    """
    del resolution
    
    return LL_CASES[satscene.instrument_name](satscene, None)

def get_lat_lon_avhrr(satscene, options):
    """Read lat and lon.
    """
    del options
    
    return satscene.lat, satscene.lon

def get_lonlat(satscene, row, col):
    """Read lat and lon.
    """

    return LONLAT_CASES[satscene.instrument_name](satscene, row, col)

def get_lonlat_avhrr(satscene, row, col):
    """Read longitude and latitude for a given pixel.
    """
    # Needs the SATID AAPP env variable to be set to find satid.txt...

    import pyaapp
    import math
    t_start = satscene.time_slot
    epoch = datetime.datetime(1950, 1, 1)
    t50_start = (t_start - epoch)
    jday_start = t50_start.seconds / (3600.0 *24) + t50_start.days
    jday_end = jday_start
    if(satscene.satname == "metop"):
        satname = "M02"
    else:
        satname = satscene.satname + satscene.number

    satpos_file = get_satpos_file(satscene.time_slot, satname)

    pyaapp.read_satpos_file(jday_start, jday_end,
                            satscene.satname+" "+str(int(satscene.number)),
                            satpos_file)
    att = pyaapp.prepare_attitude(int(satscene.number), 0, 0, 0)
    lonlat = pyaapp.linepixel2lonlat(int(satscene.number), row, col, att,
                                     jday_start, jday_end)[1:3] 
    return (lonlat[0] * 180.0 / math.pi, lonlat[1] * 180.0 / math.pi)

LONLAT_CASES = {
    "avhrr": get_lonlat_avhrr
    }

LL_CASES = {
    "avhrr": get_lat_lon_avhrr
    }

CASES = {
    "avhrr": load_avhrr
    }