In [1]:
#PROBLEM: reflectance estimated with demo_refl039 & get_reflectance is a bit different
    #sza (from pytroll) & sunz (from knmi) is quite a bit different

#so far missing: cldmask, cph, qa, structural params...

In [1]:
import datetime
import logging

from mpop.satellites import GeostationaryFactory
from mpop.projector import get_area_def

from pyresample import plot
import numpy as np
from pydecorate import DecoratorAGG
import aggdraw
from trollimage.colormap import rainbow, RainRate
from trollimage.image import Image as trollimage
from PIL import ImageFont, ImageDraw 
from pycoast import ContourWriterAGG
import sys


# to get the local time
import ephem


# to get the solar reflectance of the IR_039 channel
from pyspectral.near_infrared_reflectance import Calculator
from pyspectral.solar import (SolarIrradianceSpectrum, TOTAL_IRRADIANCE_SPECTRUM_2000ASTM)
from pyspectral.rsr_reader import RelativeSpectralResponse
from pyorbital.astronomy import sun_zenith_angle

In [2]:
def solartime(observer, sun=ephem.Sun()):
    sun.compute(observer)
    # sidereal time == ra (right ascension) is the highest point (noon)
    hour_angle = observer.sidereal_time() - sun.ra
    return ephem.hours(hour_angle + ephem.hours('12:00')).norm  # norm for 24h

In [ ]:


In [3]:
# set the date
time_slot=datetime.datetime(2017,6,16,12,0,0,0)
#datetime1=datetime.datetime(2017,6,9,12,0)

In [4]:
# set up to be able to calculate solar time
o = ephem.Observer()
o.date = time_slot # some utc time
o.date


Out[4]:
42901.0

In [ ]:


In [5]:
load_radar=True
load_sat=True
load_knmi = True


# RADAR
prop_str='RATE'




# SATELLITE
#channel_sat=['VIS006','VIS008','IR_016','IR_039','WV_062','WV_073','IR_087','IR_097','IR_108','IR_120','IR_134','HRV']
channel_sat=['VIS006','VIS008','IR_016','IR_039','WV_062','WV_073','IR_087','IR_097','IR_108','IR_120','IR_134']




#KNMI
# ATTENTION: cloud mask channel (cldmask) missing for now because it doesn't have the attribute units 
    #& I do not have the rights to try & add them 
#channel_knmi = ['azidiff','cth','cot','cph','ctt','cwp','dcld','dcot','dcwp','dndv','dreff','qa','reff','satz','sds','sds_cs','sds_diff','sds_diff_cs','sunz']


# here without sunz because it differs (up to 1.18° in time instance I tried) from the pytroll computed one
#channel_knmi = ['azidiff','cth','cot','cph','ctt','cwp','dcld','dcot','dcwp','dndv','dreff','qa','reff','satz','sds','sds_cs','sds_diff','sds_diff_cs']

# test without cldmask, cph & qa because they give the following mistake:
    # TypeError: Fill value 9.96920996839e+36 overflows dtype int16 
channel_knmi = ['azidiff','cth','cldmask','cot','cph','ctt','cwp','dcld','dcot','dcwp','dndv','dreff','qa','reff','satz','sds','sds_cs','sds_diff','sds_diff_cs']
#channel_knmi = ['azidiff','cth','cot','ctt','cwp','dcld','dcot','dcwp','dndv','dreff','reff','satz','sds','sds_cs','sds_diff','sds_diff_cs']

In [6]:
if load_radar:
    global_radar = GeostationaryFactory.create_scene("odyssey", "", "radar", time_slot)
    global_radar.load([prop_str])
    print(global_radar)
    print("=========================")

if load_sat:
    global_sat = GeostationaryFactory.create_scene("meteosat", "09", "seviri", time_slot)
    #global_sat = GeostationaryFactory.create_scene("Meteosat-9", "", "seviri", time_slot)
        # test to be able to apply get_reflectance -> doesn't work -.- need workaround -> only change name
            # right when apply it

    #global_sat.load(['IR_108'], reader_level="seviri-level2") 
    global_sat.load(channel_sat, reader_level="seviri-level2")
    print(global_sat)
    print("=========================")

if load_knmi:
    global_knmi = GeostationaryFactory.create_scene("cpp", "10", "seviri", time_slot)
    global_knmi.load(channel_knmi)
    print(global_knmi)
    print("=========================")


'RATE: (-inf,-inf,-inf)μm, shape (2200, 1900), resolution 0m'
'RATE-MASK: (-inf,-inf,-inf)μm, shape (2200, 1900), resolution 0m'
=========================
'VIS006: (0.560,0.635,0.710)μm, shape (3712, 3712), resolution 3000.40316582m'
'VIS008: (0.740,0.810,0.880)μm, shape (3712, 3712), resolution 3000.40316582m'
'IR_016: (1.500,1.640,1.780)μm, shape (3712, 3712), resolution 3000.40316582m'
'IR_039: (3.480,3.920,4.360)μm, shape (3712, 3712), resolution 3000.40316582m'
'WV_062: (5.350,6.250,7.150)μm, shape (3712, 3712), resolution 3000.40316582m'
'WV_073: (6.850,7.350,7.850)μm, shape (3712, 3712), resolution 3000.40316582m'
'IR_087: (8.300,8.700,9.100)μm, shape (3712, 3712), resolution 3000.40316582m'
'IR_097: (9.380,9.660,9.940)μm, shape (3712, 3712), resolution 3000.40316582m'
'IR_108: (9.800,10.800,11.800)μm, shape (3712, 3712), resolution 3000.40316582m'
'IR_120: (11.000,12.000,13.000)μm, shape (3712, 3712), resolution 3000.40316582m'
'IR_134: (12.400,13.400,14.400)μm, shape (3712, 3712), resolution 3000.40316582m'
'HRV: (0.500,0.700,0.900)μm, resolution 1000.13434887m, not loaded'
'HRW: (-inf,-inf,-inf)μm, resolution 0m, not loaded'
'HRW: (-inf,-inf,-inf)μm, resolution 0m, not loaded'
=========================
20170616T121500
... search for file:  /data/COALITION2/in/cpp/SEVIR_OPER_R___MSGCPP__L2__20170616T120000_20170616T121500_0001.nc
... read data from /data/COALITION2/in/cpp/SEVIR_OPER_R___MSGCPP__L2__20170616T120000_20170616T121500_0001.nc
... units  degree
*** *** units  degree
... units  None
*** *** units  None
... units  m
*** *** units  m
... units  None
*** *** units  None
... units  W m-2
*** *** units  W m-2
... units  kg m-2
*** *** units  kg m-2
... units  degree
*** *** units  degree
... units  K
*** *** units  K
... units  None
*** *** units  None
... units  m
*** *** units  micro m
... units  m-3
*** *** units  m-3
... units  None
*** *** units  None
*** *** units  None
... units  kg m-2
*** *** units  kg m-2
... units  W m-2
*** *** units  W m-2
... units  m
*** *** units  km
... units  W m-2
*** *** units  W m-2
... units  W m-2
*** *** units  W m-2
... units  m
*** *** units  micro m
'azidiff: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 3000.40316582m'
'cth: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 3000.40316582m'
'cldmask: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 3000.40316582m'
'cot: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 3000.40316582m'
'cph: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 3000.40316582m'
'ctt: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 3000.40316582m'
'cwp: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 3000.40316582m'
'dcld: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 3000.40316582m'
'dcot: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 3000.40316582m'
'dcwp: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 3000.40316582m'
'dndv: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 3000.40316582m'
'dreff: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 3000.40316582m'
'precip: (-inf,-inf,-inf)μm, resolution 3000.40316582m, not loaded'
'precip_ir: (-inf,-inf,-inf)μm, resolution 3000.40316582m, not loaded'
'qa: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 3000.40316582m'
'satz: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 3000.40316582m'
'satz: (-inf,-inf,-inf)μm, resolution 3000.40316582m, not loaded'
'sds: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 3000.40316582m'
'sds_cs: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 3000.40316582m'
'sds_diff: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 3000.40316582m'
'sds_diff_cs: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 3000.40316582m'
'sunz: (-inf,-inf,-inf)μm, resolution 3000.40316582m, not loaded'
'lat: (-inf,-inf,-inf)μm, resolution 3000.40316582m, not loaded'
'lon: (-inf,-inf,-inf)μm, resolution 3000.40316582m, not loaded'
'time_offset: (-inf,-inf,-inf)μm, resolution 3000.40316582m, not loaded'
'MASK: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 0m'
'reff: (-inf,-inf,-inf)μm, shape (3712, 3712), resolution 0m'
=========================

In [ ]:


In [7]:
area='EuropeOdyssey95'

reproject=True
if reproject:
  
    print ("start projection")
   # PROJECT data to new area 
    if load_radar:
    
        data_radar = global_radar.project(area, precompute=True)
       #data[prop_str].product_name = global_radar[prop_str].product_name
       #data[prop_str].units = global_radar[prop_str].units
       
        global_radar = data_radar
    if load_sat:
        data_sat = global_sat.project(area, precompute=True)
        global_sat = data_sat

        from pyorbital.astronomy import sun_zenith_angle
        lonlats = global_sat[channel_sat[0]].area.get_lonlats()
        #sza = sun_zenith_angle(datetime1, lonlats[0], lonlats[1])
        sza = sun_zenith_angle(time_slot, lonlats[0], lonlats[1])
        
    
    if load_knmi:
        data_knmi = global_knmi.project(area, precompute=True)
        global_knmi = data_knmi
        print('ok')


start projection
ok

In [ ]:


In [8]:
# correct the VIS channels for the solar zenith angle
cos_sza = np.cos(np.deg2rad(sza))
global_sat['VIS006']=global_sat['VIS006']/cos_sza
global_sat['VIS008']=global_sat['VIS008']/cos_sza
global_sat['IR_016']=global_sat['IR_016']/cos_sza

In [9]:
#carry out a parallax correction for all channels
global_sat = global_sat.parallax_corr(fill='bilinear', estimate_cth='standard', replace=True)


... calculate viewing geometry using  WV_073
... get orbital identification line (norad) for METEOSAT 9
No handlers could be found for logger "pyorbital.tlefile"
*** Simple estimation of Cloud Top Height with IR_108 channel
... automatic choise of temperature profile lon= 10.3038092003  lat= 48.9352808753 , time= 2017-06-16 12:00:00 , doy= 167
    choosing temperature profile for  midlatitude summer
*** estimating CTH using the 10.8 micro meter brightness temperature 
... assume  midlatitude summer  atmosphere for temperature profile
     z0(km)   z1(km)   T0(K)   T1(K)  number of pixels
------------------------------------------------------
      0.0      1.0    294.2    289.7    54354
      1.0      2.0    289.7    285.2    43245
      2.0      3.0    285.2    279.2    54585
      3.0      4.0    279.2    273.2    38694
      4.0      5.0    273.2    267.2    34705
      5.0      6.0    267.2    261.2    27907
      6.0      7.0    261.2    254.7    24292
      7.0      8.0    254.7    248.2    20351
      8.0      9.0    248.2    241.7    15023
      9.0     10.0    241.7    235.3    10984
     10.0     11.0    235.3    228.8     5824
     11.0     12.0    228.8    222.3     3902
     12.0     13.0    222.3    215.8     1379
     13.0     14.0    215.8    215.7       31
     14.0     15.0    215.7    215.7        0
... perform parallax correction for  WV_073
    replace channel  WV_073
... azimuth and elevation angle given
... calculate parallax shift
/opt/users/bel/monti-pytroll/packages/mpop/mpop/channel.py:665: FutureWarning: comparison to `None` will result in an elementwise object comparison in the future.
  if azi==None or ele==None:
... copy data to parallax corrected position
... perform parallax correction for  IR_087
    replace channel  IR_087
... azimuth and elevation angle given
... calculate parallax shift
... copy data to parallax corrected position
... perform parallax correction for  VIS008
    replace channel  VIS008
... azimuth and elevation angle given
... calculate parallax shift
... copy data to parallax corrected position
... perform parallax correction for  IR_016
    replace channel  IR_016
... azimuth and elevation angle given
... calculate parallax shift
... copy data to parallax corrected position
... perform parallax correction for  IR_134
    replace channel  IR_134
... azimuth and elevation angle given
... calculate parallax shift
... copy data to parallax corrected position
... perform parallax correction for  IR_097
    replace channel  IR_097
... azimuth and elevation angle given
... calculate parallax shift
... copy data to parallax corrected position
... perform parallax correction for  CTH
    replace channel  CTH
... azimuth and elevation angle given
... calculate parallax shift
... copy data to parallax corrected position
... perform parallax correction for  IR_108
    replace channel  IR_108
... azimuth and elevation angle given
... calculate parallax shift
... copy data to parallax corrected position
... perform parallax correction for  IR_039
    replace channel  IR_039
... azimuth and elevation angle given
... calculate parallax shift
... copy data to parallax corrected position
... perform parallax correction for  VIS006
    replace channel  VIS006
... azimuth and elevation angle given
... calculate parallax shift
... copy data to parallax corrected position
... perform parallax correction for  WV_062
    replace channel  WV_062
... azimuth and elevation angle given
... calculate parallax shift
... copy data to parallax corrected position
... perform parallax correction for  IR_120
    replace channel  IR_120
... azimuth and elevation angle given
... calculate parallax shift
... copy data to parallax corrected position

In [ ]:


In [10]:
# estimate the solar reflectance of the IR_039 chanel (ATTENTION: not trustworthy!)
    # If I use the method from the demo program get slightly different values (& since absolute values so 
    # tiny, this might actually have an impact)
    # what should I do with this channel?!
global_sat['IR_039'].info['satname']='Meteosat-9'
global_sat['IR_039'].info['satnumber']=''

refl039=global_sat['IR_039'].get_reflectance(tb11=global_sat['IR_108'].data,sun_zenith=sza,tb13_4=global_sat['IR_134'].data)

# is this one sunzen corrected yet?!?! if not: can just do after/before parallax corr, right?
    # so far assume it is... considering I need to provide sza as an input argument ^^

In [ ]:


In [ ]:


In [11]:
area_size = global_sat["IR_108"].data.size
write_netCDF=True
if write_netCDF:

    #nc_outfile = '/data/COALITION2/PicturesSatellite/results_BEL/data/logreg/ODYRATE_SEVIRI_' + datetime1.strftime("%Y%m%d_%H%M") + '.nc'
    nc_outfile = '/data/COALITION2/PicturesSatellite/results_BEL/data/logreg/ODYRATE_SEVIRI_' + time_slot.strftime("%Y%m%d_%H%M") + '.nc'

    print("*** write data to: ncdump ", nc_outfile)

    import netCDF4 as nc4
    f = nc4.Dataset(nc_outfile,'w', format='NETCDF4')

    tempgrp = f.createGroup('collocated odyssey rain rate and SEVIRI reflectances and brightness temperatures')

    m = global_radar[prop_str+'-MASK'].data.reshape(area_size)
    y = global_radar[prop_str].data.reshape(area_size)
    y  = y[m==False]
    print("dataset length", len(y))

    #xx = global_sat['IR_108'].data.reshape(area_size)  
    #xx = xx[m==False]

    #import pdb
    #pdb.set_trace()

    lon = lonlats[0].reshape(area_size)
    lat = lonlats[1].reshape(area_size)
    sza = sza.reshape(area_size)
    refl039 = refl039.reshape(area_size)
    lon  = lon[m==False]
    lon_rad = np.deg2rad(lon)
    lat  = lat[m==False]
    sza  = sza[m==False]
    refl039 = refl039[m==False]
    cos_sza =  np.cos(np.deg2rad(sza))
    
    
    
    lstime = np.empty(lon_rad.shape) #local solar time
    for i in range(len(lon_rad)):
        o.lon = lon_rad[i]
        lstime[i]=solartime(o) # =  float number that represents an angle in radians and converts to/from a string     
    
    
    #for i in range(100):
     #   print y.tolist(0)[i], xx[i], lon[i], lat[i], np.cos(np.deg2rad(sza[i]))

    #tempgrp.createDimension('idata', area_size)
    tempgrp.createDimension('ndata', len(y))

    #IR_108 = tempgrp.createVariable('IR_108', 'f4', 'idata')

    varids_sat = range(len(channel_sat))
    for chn,i in zip(channel_sat,range(len(channel_sat))):
        print chn, i
        varids_sat[i] = tempgrp.createVariable(chn, 'f4', 'ndata')
        
    varids_knmi =range(len(channel_knmi))
    for chn,i in zip(channel_knmi,range(len(channel_knmi))):
        print chn, i
        varids_knmi[i] = tempgrp.createVariable(chn, 'f4', 'ndata')        
        
    ODY_RAINRATE = tempgrp.createVariable('ODY_RAINRATE','f4', 'ndata')
    #time = tempgrp.createVariable('Time', 'i4', 'time')

    longitude   = tempgrp.createVariable('Longitude', 'f4', 'ndata')
    latitude    = tempgrp.createVariable('Latitude', 'f4',  'ndata')
    csza        = tempgrp.createVariable('Cosine Solar Zenith Angle','f4', 'ndata')
    lst         = tempgrp.createVariable('Local Solar Time','f4', 'ndata')
    r39         = tempgrp.createVariable('IR_039_refl','f4', 'ndata')
    
    
    ODY_RAINRATE[:] = y.tolist(0)
    longitude[:]    = lon
    latitude[:]     = lat
    csza[:]         = cos_sza
    lst[:]          = lstime
    r39[:]          = refl039

    for chn,i in zip(channel_sat,range(len(channel_sat))):

        x = global_sat[chn].data.reshape(area_size)  
        x = x[m==False]

        print chn, i
        varids_sat[i][:] = x


        
    for chn,i in zip(channel_knmi,range(len(channel_knmi))):

        x = global_knmi[chn].data.reshape(area_size)  
        x = x[m==False]

        print chn, i
        varids_knmi[i][:] = x
        
    #IR_108[:] = x.tolist(0)
    #IR_108[:] = global_sat["IR_108"].data.reshape(area_size) #The "[:]" at the end of the variable instance is necessary

    f.close()


('*** write data to: ncdump ', '/data/COALITION2/PicturesSatellite/results_BEL/data/logreg/ODYRATE_SEVIRI_20170616_1200.nc')
('dataset length', 294140)
VIS006 0
VIS008 1
IR_016 2
IR_039 3
WV_062 4
WV_073 5
IR_087 6
IR_097 7
IR_108 8
IR_120 9
IR_134 10
azidiff 0
cth 1
cldmask 2
cot 3
cph 4
ctt 5
cwp 6
dcld 7
dcot 8
dcwp 9
dndv 10
dreff 11
qa 12
reff 13
satz 14
sds 15
sds_cs 16
sds_diff 17
sds_diff_cs 18
VIS006 0
VIS008 1
IR_016 2
IR_039 3
WV_062 4
WV_073 5
IR_087 6
IR_097 7
IR_108 8
IR_120 9
IR_134 10
azidiff 0
cth 1
cldmask 2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-176a40d5d469> in <module>()
     94 
     95         print chn, i
---> 96         varids_knmi[i][:] = x
     97 
     98     #IR_108[:] = x.tolist(0)

netCDF4/_netCDF4.pyx in netCDF4._netCDF4.Variable.__setitem__ (netCDF4/_netCDF4.c:43796)()

/opt/users/common/packages/anaconda3/envs/PyTroll_bel/lib/python2.7/site-packages/numpy/ma/core.pyc in filled(self, fill_value)
   3666             fill_value = self.fill_value
   3667         else:
-> 3668             fill_value = _check_fill_value(fill_value, self.dtype)
   3669 
   3670         if self is masked_singleton:

/opt/users/common/packages/anaconda3/envs/PyTroll_bel/lib/python2.7/site-packages/numpy/ma/core.pyc in _check_fill_value(fill_value, ndtype)
    483                 # passed fill_value is not compatible with the ndtype.
    484                 err_msg = "Fill value %s overflows dtype %s"
--> 485                 raise TypeError(err_msg % (fill_value, ndtype))
    486     return np.array(fill_value)
    487 

TypeError: Fill value 9.96920996839e+36 overflows dtype int16

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]: