def _get_rsr(self):
        """Get the relative spectral responses.

        Get the relative spectral responses from file, find the bandname, and
        convert to the requested wave-spave (wavelength or wave number)

        """
        sensor = RelativeSpectralResponse(self.platform_name, self.instrument)

        if self.wavespace == WAVE_NUMBER:
            LOG.debug("Converting to wavenumber...")
            self.rsr, info = convert2wavenumber(sensor.rsr)
        else:
            self.rsr = sensor.rsr
            info = {'unit': sensor.unit, 'si_scale': sensor.si_scale}

        self._wave_unit = info['unit']
        self._wave_si_scale = info['si_scale']

        if isinstance(self.band, str):
            self.bandname = BANDNAMES.get(self.instrument,
                                          BANDNAMES['generic']).get(
                                              self.band, self.band)
        elif isinstance(self.band, Number):
            self.bandwavelength = self.band
            self.bandname = get_bandname_from_wavelength(
                self.instrument, self.band, self.rsr)

        self.wavelength_or_wavenumber = (
            self.rsr[self.bandname][self.detector][self.wavespace] *
            self._wave_si_scale)
        self.response = self.rsr[self.bandname][self.detector]['response']
        # Get the integral of the spectral response curve:
        self.rsr_integral = np.trapz(self.response,
                                     self.wavelength_or_wavenumber)
Example #2
0
    def get_effective_wavelength(self, bandname):
        """Get the effective wavelength with Rayleigh scattering in mind"""
        try:
            rsr = RelativeSpectralResponse(self.platform_name, self.sensor)
        except(IOError, OSError):
            LOG.exception(
                "No spectral responses for this platform and sensor: %s %s", self.platform_name, self.sensor)
            if isinstance(bandname, (float, integer_types)):
                LOG.warning(
                    "Effective wavelength is set to the requested band wavelength = %f", bandname)
                return bandname
            return None

        if isinstance(bandname, str):
            bandname = BANDNAMES.get(self.sensor, BANDNAMES['generic']).get(bandname, bandname)
        elif isinstance(bandname, (float, integer_types)):
            if not(0.4 < bandname < 0.8):
                raise BandFrequencyOutOfRange(
                    'Requested band frequency should be between 0.4 and 0.8 microns!')
            bandname = get_bandname_from_wavelength(self.sensor, bandname, rsr.rsr)

        wvl, resp = rsr.rsr[bandname][
            'det-1']['wavelength'], rsr.rsr[bandname]['det-1']['response']

        cwvl = get_central_wave(wvl, resp, weight=1. / wvl**4)
        LOG.debug("Band name: %s  Effective wavelength: %f", bandname, cwvl)

        return cwvl
    def _get_rsr(self):
        """
        Get the relative spectral responses from file, find the bandname, and
        convert to the requested wave-spave (wavelength or wave number)

        """
        sensor = RelativeSpectralResponse(self.platform_name, self.instrument)

        if self.wavespace == WAVE_NUMBER:
            LOG.debug("Converting to wavenumber...")
            self.rsr, info = convert2wavenumber(sensor.rsr)
        else:
            self.rsr = sensor.rsr
            info = {'unit': sensor.unit, 'si_scale': sensor.si_scale}

        self._wave_unit = info['unit']
        self._wave_si_scale = info['si_scale']

        if isinstance(self.band, str):
            self.bandname = BANDNAMES.get(self.instrument, BANDNAMES['generic']).get(self.band, self.band)
        elif isinstance(self.band, Number):
            self.bandwavelength = self.band
            self.bandname = get_bandname_from_wavelength(self.instrument, self.band, self.rsr)

        self.wavelength_or_wavenumber = (self.rsr[self.bandname][self.detector][self.wavespace] *
                                         self._wave_si_scale)
        self.response = self.rsr[self.bandname][self.detector]['response']
        # Get the integral of the spectral response curve:
        self.rsr_integral = np.trapz(self.response, self.wavelength_or_wavenumber)
Example #4
0
    def get_effective_wavelength(self, bandname):
        """Get the effective wavelength with Rayleigh scattering in mind"""
        try:
            rsr = RelativeSpectralResponse(self.platform_name, self.sensor)
        except(IOError, OSError):
            LOG.exception(
                "No spectral responses for this platform and sensor: %s %s", self.platform_name, self.sensor)
            if isinstance(bandname, (float, integer_types)):
                LOG.warning(
                    "Effective wavelength is set to the requested band wavelength = %f", bandname)
                return bandname

            msg = ("Can't get effective wavelength for band %s on platform %s and sensor %s" %
                   (str(bandname), self.platform_name, self.sensor))
            raise KeyError(msg)

        if isinstance(bandname, str):
            bandname = BANDNAMES.get(self.sensor, BANDNAMES['generic']).get(bandname, bandname)
        elif isinstance(bandname, (float, integer_types)):
            if not(0.4 < bandname < 0.8):
                raise BandFrequencyOutOfRange(
                    'Requested band frequency should be between 0.4 and 0.8 microns!')
            bandname = get_bandname_from_wavelength(self.sensor, bandname, rsr.rsr)

        wvl, resp = rsr.rsr[bandname][
            'det-1']['wavelength'], rsr.rsr[bandname]['det-1']['response']

        cwvl = get_central_wave(wvl, resp, weight=1. / wvl**4)
        LOG.debug("Band name: %s  Effective wavelength: %f", bandname, cwvl)

        return cwvl
    def __init__(self, platform_name, instrument, bandname, method=1,
                 **options):
        """E.g.:
        platform_name = 'Meteosat-9'
        instrument = 'seviri'
        """
        self.platform_name = platform_name
        self.instrument = instrument
        self.rsr = None
        self.bandname = BANDNAMES.get(bandname, bandname)

        if 'detector' in options:
            self.detector = options['detector']
        else:
            self.detector = 'det-1'

        if 'wavespace' in options:
            if options['wavespace'] not in [WAVE_LENGTH, WAVE_NUMBER]:
                raise AttributeError('Wave space not %s or %s!' % (WAVE_LENGTH,
                                                                   WAVE_NUMBER))
            self.wavespace = options['wavespace']
        else:
            self.wavespace = WAVE_LENGTH

        self._wave_unit = ''
        self._wave_si_scale = 1.0

        if 'tb_resolution' in options:
            self.tb_resolution = options['tb_resolution']
        else:
            self.tb_resolution = 0.1
        self.tb_scale = 1. / self.tb_resolution

        if method == 1:
            self.get_rsr()
Example #6
0
    def __init__(self, platform_name, instrument, band, method=1,
                 **options):
        """E.g.:
        platform_name = 'Meteosat-9'
        instrument = 'seviri'
        """
        self.platform_name = platform_name
        self.instrument = instrument
        self.rsr = None
        self.bandname = None
        self.bandwavelength = None

        if isinstance(band, str):
            self.bandname = BANDNAMES.get(band, band)
        elif isinstance(band, (int, long, float)):
            self.bandwavelength = band

        if 'detector' in options:
            self.detector = options['detector']
        else:
            self.detector = 'det-1'

        if 'wavespace' in options:
            if options['wavespace'] not in [WAVE_LENGTH, WAVE_NUMBER]:
                raise AttributeError('Wave space not %s or %s!' % (WAVE_LENGTH,
                                                                   WAVE_NUMBER))
            self.wavespace = options['wavespace']
        else:
            self.wavespace = WAVE_LENGTH

        self._wave_unit = ''
        self._wave_si_scale = 1.0

        if 'tb_resolution' in options:
            self.tb_resolution = options['tb_resolution']
        else:
            self.tb_resolution = 0.1
        self.tb_scale = 1. / self.tb_resolution

        if method == 1:
            self.get_rsr()

        if self.bandname is None:
            epsilon = 0.1
            channel_list = [channel for channel in self.rsr if abs(
                self.rsr[channel]['det-1']['central_wavelength'] - self.bandwavelength) < epsilon]
            self.bandname = BANDNAMES.get(channel_list[0], channel_list[0])
    def __init__(self, platform_name, instrument, bandname,
                 solar_flux=None, **kwargs):
        """Init"""
        super(Calculator, self).__init__(platform_name, instrument,
                                         bandname, method=1, **kwargs)

        self.bandname = BANDNAMES.get(bandname, bandname)

        options = {}
        if CONFIG_FILE:
            conf = ConfigParser.ConfigParser()
            try:
                conf.read(CONFIG_FILE)
            except ConfigParser.NoSectionError:
                LOG.warning('Failed reading configuration file: %s',
                            str(CONFIG_FILE))

            for option, value in conf.items(platform_name + '-' + instrument,
                                            raw=True):
                options[option] = value

        if solar_flux is None:
            self._get_solarflux()
        else:
            self.solar_flux = solar_flux
        self._rad37 = None
        self._rad37_t11 = None
        self._solar_radiance = None
        self._rad39_correction = 1.0

        if 'detector' in kwargs:
            self.detector = kwargs['detector']
        else:
            self.detector = 'det-1'

        resp = self.rsr[self.bandname][self.detector]['response']
        wv_ = self.rsr[self.bandname][self.detector][self.wavespace]
        self.rsr_integral = np.trapz(resp, wv_)

        if 'tb2rad_lut_filename' in options:
            self.lutfile = options['tb2rad_lut_filename']
            if not self.lutfile.endswith('.npz'):
                self.lutfile = self.lutfile + '.npz'

            LOG.info("lut filename: " + str(self.lutfile))
            if not os.path.exists(self.lutfile):
                self.make_tb2rad_lut(self.bandname,
                                     self.lutfile)
                self.lut = self.read_tb2rad_lut(self.lutfile)
                LOG.info("LUT file created")
            else:
                self.lut = self.read_tb2rad_lut(self.lutfile)
                LOG.info("File was there and has been read!")
        else:
            LOG.info("No lut filename available in config file. "
                     "No lut will be used")
            self.lutfile = None
            self.lut = None
    def __init__(self, platform_name, band, **kwargs):
        """
        E.g.:
        platform_name = Meteosat-9
        band = 3.75

        """
        super(SeviriRadTbConverter, self).__init__(platform_name, 'seviri',
                                                   band, **kwargs)

        if isinstance(self.band, str):
            self.bandname = BANDNAMES.get(self.instrument, BANDNAMES['generic']).get(self.band, self.band)
        else:
            raise AttributeError('Band name provided as a string is required')
    def __init__(self, platform, satnum, instrument, bandname, method=1,
                 **options):
        """E.g.:
           platform = 'meteosat'
           satnum = '9'
           instrument = 'seviri'
        """
        self.platform = platform
        self.satnumber = satnum
        self.instrument = instrument
        self.rsr = None
        self.bandname = BANDNAMES.get(bandname, bandname)

        if 'detector' in options:
            self.detector = options['detector']
        else:
            self.detector = 'det-1'

        if 'wavespace' in options:
            if options['wavespace'] not in [WAVE_LENGTH, WAVE_NUMBER]:
                raise AttributeError('Wave space not %s or %s!' % (WAVE_LENGTH,
                                                                   WAVE_NUMBER))
            self.wavespace = options['wavespace']
        else:
            self.wavespace = WAVE_LENGTH

        self._wave_unit = ''
        self._wave_si_scale = 1.0

        if 'tb_resolution' in options:
            self.tb_resolution = options['tb_resolution']
        else:
            self.tb_resolution = 0.1
        self.tb_scale = 1. / self.tb_resolution

        if method == 1:
            self.get_rsr()
Example #10
0
    def __init__(self, platform_name, instrument, band, **kwargs):
        super(Calculator, self).__init__(platform_name, instrument, band,
                                         **kwargs)

        from numbers import Number
        self.bandname = None
        self.bandwavelength = None

        if isinstance(band, str):
            self.bandname = BANDNAMES.get(self.instrument,
                                          BANDNAMES['generic']).get(
                                              band, band)
            self.bandwavelength = self.rsr[
                self.bandname]['det-1']['central_wavelength']
        elif isinstance(band, Number):
            self.bandwavelength = band
            self.bandname = get_bandname_from_wavelength(
                self.instrument, band, self.rsr)

        if self.bandwavelength > 3.95 or self.bandwavelength < 3.5:
            raise NotImplementedError(
                'NIR reflectance is not supported outside ' +
                'the 3.5-3.95 micron interval')

        options = get_config()

        self.solar_flux = kwargs.get('solar_flux', None)
        if self.solar_flux is None:
            self._get_solarflux()

        self._rad3x = None
        self._rad3x_t11 = None
        self._solar_radiance = None
        self._rad3x_correction = 1.0
        self._r3x = None
        self._e3x = None
        self.lutfile = None

        if 'detector' in kwargs:
            self.detector = kwargs['detector']
        else:
            self.detector = 'det-1'

        platform_sensor = platform_name + '-' + instrument
        if platform_sensor in options and 'tb2rad_lut_filename' in options[
                platform_sensor]:
            if isinstance(options[platform_sensor]['tb2rad_lut_filename'],
                          dict):
                for item in options[platform_sensor]['tb2rad_lut_filename']:
                    if item == self.bandname or item == self.bandname.lower():
                        self.lutfile = options[platform_sensor][
                            'tb2rad_lut_filename'][item]
                        break
                if self.lutfile is None:
                    LOG.warning(
                        "Failed determine LUT filename from config: %s",
                        str(options[platform_sensor]['tb2rad_lut_filename']))
            else:
                self.lutfile = options[platform_sensor]['tb2rad_lut_filename']

            if self.lutfile and not self.lutfile.endswith('.npz'):
                self.lutfile = self.lutfile + '.npz'

            if self.lutfile and not os.path.exists(
                    os.path.dirname(self.lutfile)):
                LOG.warning("Directory %s does not exist! Check config file",
                            os.path.dirname(self.lutfile))
                self.lutfile = os.path.join(TMPDIR,
                                            os.path.basename(self.lutfile))

        if self.lutfile is None:
            LOG.info("No lut filename available in config file. "
                     "Will generate filename automatically")
            lutname = 'tb2rad_lut_{0}_{1}_{band}'.format(
                self.platform_name.lower(),
                self.instrument.lower(),
                band=self.bandname.lower())
            self.lutfile = os.path.join(TMPDIR, lutname + '.npz')

        LOG.info("lut filename: " + str(self.lutfile))
        if not os.path.exists(self.lutfile):
            self.make_tb2rad_lut(self.lutfile)
            self.lut = self.read_tb2rad_lut(self.lutfile)
            LOG.info("LUT file created")
        else:
            self.lut = self.read_tb2rad_lut(self.lutfile)
            LOG.info("File was there and has been read!")
Example #11
0
    def __init__(self,
                 platform_name,
                 instrument,
                 band,
                 detector='det-1',
                 wavespace=WAVE_LENGTH,
                 solar_flux=None,
                 sunz_threshold=TERMINATOR_LIMIT,
                 masking_limit=TERMINATOR_LIMIT):
        """Initialize the Class instance."""
        super(Calculator, self).__init__(platform_name,
                                         instrument,
                                         band,
                                         detector=detector,
                                         wavespace=wavespace)

        from numbers import Number
        self.bandname = None
        self.bandwavelength = None

        if isinstance(band, str):
            self.bandname = BANDNAMES.get(self.instrument,
                                          BANDNAMES['generic']).get(
                                              band, band)
            self.bandwavelength = self.rsr[
                self.bandname]['det-1']['central_wavelength']
        elif isinstance(band, Number):
            self.bandwavelength = band
            self.bandname = get_bandname_from_wavelength(
                self.instrument, band, self.rsr)

        if self.bandwavelength > 3.95 or self.bandwavelength < 3.5:
            raise NotImplementedError(
                'NIR reflectance is not supported outside ' +
                'the 3.5-3.95 micron interval')

        options = get_config()

        self.solar_flux = solar_flux
        if self.solar_flux is None:
            self._get_solarflux()

        # The sun-zenith angle limit in degrees defining how far towards the
        # terminator we try derive a
        self.detector = detector
        self.sunz_threshold = sunz_threshold
        self.masking_limit = masking_limit
        self._rad3x = None
        self._rad3x_t11 = None
        self._solar_radiance = None
        self._rad3x_correction = 1.0
        self._r3x = None
        self._e3x = None
        self.lutfile = None

        platform_sensor = platform_name + '-' + instrument
        if platform_sensor in options and 'tb2rad_lut_filename' in options[
                platform_sensor]:
            if isinstance(options[platform_sensor]['tb2rad_lut_filename'],
                          dict):
                for item in options[platform_sensor]['tb2rad_lut_filename']:
                    if item == self.bandname or item == self.bandname.lower():
                        self.lutfile = options[platform_sensor][
                            'tb2rad_lut_filename'][item]
                        break
                if self.lutfile is None:
                    LOG.warning(
                        "Failed determine LUT filename from config: %s",
                        str(options[platform_sensor]['tb2rad_lut_filename']))
            else:
                self.lutfile = options[platform_sensor]['tb2rad_lut_filename']

            if self.lutfile and not self.lutfile.endswith('.npz'):
                self.lutfile = self.lutfile + '.npz'

            if self.lutfile and not os.path.exists(
                    os.path.dirname(self.lutfile)):
                LOG.warning("Directory %s does not exist! Check config file",
                            os.path.dirname(self.lutfile))
                self.lutfile = os.path.join(TB2RAD_DIR,
                                            os.path.basename(self.lutfile))

        if self.lutfile is None:
            LOG.info("No lut filename available in config file. "
                     "Will generate filename automatically")
            lutname = 'tb2rad_lut_{0}_{1}_{band}'.format(
                self.platform_name.lower(),
                self.instrument.lower(),
                band=self.bandname.lower())
            self.lutfile = os.path.join(TB2RAD_DIR, lutname + '.npz')

        LOG.info("lut filename: " + str(self.lutfile))
        if not os.path.exists(self.lutfile):
            self.make_tb2rad_lut(self.lutfile)
            self.lut = self.read_tb2rad_lut(self.lutfile)
            LOG.info("LUT file created")
        else:
            self.lut = self.read_tb2rad_lut(self.lutfile)
            LOG.info("File was there and has been read!")
Example #12
0
    def __init__(self, platform_name, instrument, band,
                 solar_flux=None, **kwargs):
        """Init"""
        super(Calculator, self).__init__(platform_name, instrument,
                                         band, method=1, **kwargs)

        self.bandname = None
        self.bandwavelength = None

        if isinstance(band, str):
            self.bandname = BANDNAMES.get(band, band)
        elif isinstance(band, (int, long, float)):
            self.bandwavelength = band

        if self.bandname is None:
            epsilon = 0.1
            channel_list = [channel for channel in self.rsr if abs(
                self.rsr[channel]['det-1']['central_wavelength'] - self.bandwavelength) < epsilon]
            self.bandname = BANDNAMES.get(channel_list[0], channel_list[0])

        options = {}
        conf = get_config()
        for option, value in conf.items(platform_name + '-' + instrument,
                                        raw=True):
            options[option] = value

        if solar_flux is None:
            self._get_solarflux()
        else:
            self.solar_flux = solar_flux
        self._rad3x = None
        self._rad3x_t11 = None
        self._solar_radiance = None
        self._rad3x_correction = 1.0
        self._r3x = None
        self._e3x = None

        if 'detector' in kwargs:
            self.detector = kwargs['detector']
        else:
            self.detector = 'det-1'

        resp = self.rsr[self.bandname][self.detector]['response']
        wv_ = self.rsr[self.bandname][self.detector][self.wavespace]
        self.rsr_integral = np.trapz(resp, wv_)

        if 'tb2rad_lut_filename' in options:
            self.lutfile = options['tb2rad_lut_filename']
            if not self.lutfile.endswith('.npz'):
                self.lutfile = self.lutfile + '.npz'

            if not os.path.exists(os.path.dirname(self.lutfile)):
                LOG.warning(
                    "Directory %s does not exist! Check config file" % os.path.dirname(self.lutfile))
                self.lutfile = os.path.join(
                    '/tmp', os.path.basename(self.lutfile))

            LOG.info("lut filename: " + str(self.lutfile))
            if not os.path.exists(self.lutfile):
                self.make_tb2rad_lut(self.bandname,
                                     self.lutfile)
                self.lut = self.read_tb2rad_lut(self.lutfile)
                LOG.info("LUT file created")
            else:
                self.lut = self.read_tb2rad_lut(self.lutfile)
                LOG.info("File was there and has been read!")
        else:
            LOG.info("No lut filename available in config file. "
                     "No lut will be used")
            self.lutfile = None
            self.lut = None