Read the Terra/Aqua MODIS relative spectral responses. Be aware that
    MODIS has several detectors (more than one) compared to e.g. AVHRR which
    has always only one.
497833
def read_modis_response(filename, scale=1.0):
    
    with open(filename, "r") as fid:
        lines = fid.readlines()

    nodata = -99.0
    # The IR channels seem to be in microns, whereas the short wave channels are
    # in nanometers! For VIS/NIR scale should be 0.001
    detectors = {}
    for line in lines:
        if line.find("#") == 0:
            continue
        dummy, det_num, s_1, s_2 = line.split()
        detector_name = 'det-{0:d}'.format(int(det_num))
        if detector_name not in detectors:
            detectors[detector_name] = {'wavelength': [], 'response': []}

        detectors[detector_name]['wavelength'].append(float(s_1) * scale)
        detectors[detector_name]['response'].append(float(s_2))

    for key in detectors:
        mask = np.array(detectors[key]['response']) == nodata
        detectors[key]['response'] = np.ma.masked_array(
            detectors[key]['response'], mask=mask).compressed()
        detectors[key]['wavelength'] = np.ma.masked_array(
            detectors[key]['wavelength'], mask=mask).compressed()

    return detectors
1235021
def check_read_inputs(self, sampfrom, sampto, channels, physical,
                          smooth_frames, return_res):
        

        # Data Type Check
        if not hasattr(sampfrom, '__index__'):
            raise TypeError('sampfrom must be an integer')
        if not hasattr(sampto, '__index__'):
            raise TypeError('sampto must be an integer')
        if not isinstance(channels, list):
            raise TypeError('channels must be a list of integers')

        # Duration Ranges
        if sampfrom < 0:
            raise ValueError('sampfrom must be a non-negative integer')
        if sampfrom > self.sig_len:
            raise ValueError('sampfrom must be shorter than the signal length')
        if sampto < 0:
            raise ValueError('sampto must be a non-negative integer')
        if sampto > self.sig_len:
            raise ValueError('sampto must be shorter than the signal length')
        if sampto <= sampfrom:
            raise ValueError('sampto must be greater than sampfrom')

        # Channel Ranges
        if len(channels):
            if min(channels) < 0:
                raise ValueError('Input channels must all be non-negative integers')
            if max(channels) > self.n_sig - 1:
                raise ValueError('Input channels must all be lower than the total number of channels')

        if return_res not in [64, 32, 16, 8]:
            raise ValueError("return_res must be one of the following: 64, 32, 16, 8")
        if physical is True and return_res == 8:
            raise ValueError("return_res must be one of the following when physical is True: 64, 32, 16")

        # Cannot expand multiple samples/frame for multi-segment records
        if isinstance(self, MultiRecord):
            if smooth_frames is False:
                raise ValueError('This package version cannot expand all samples when reading multi-segment records. Must enable frame smoothing.')
96564
def _get_coarse_dataset(self, key, info):
        """"""
        angles = self.root.find('.//Tile_Angles')
        if key in ['solar_zenith_angle', 'solar_azimuth_angle']:
            elts = angles.findall(info['xml_tag'] + '/Values_List/VALUES')
            return np.array([[val for val in elt.text.split()] for elt in elts],
                            dtype=np.float)

        elif key in ['satellite_zenith_angle', 'satellite_azimuth_angle']:
            arrays = []
            elts = angles.findall(info['xml_tag'] + '[@bandId="1"]')
            for elt in elts:
                items = elt.findall(info['xml_item'] + '/Values_List/VALUES')
                arrays.append(np.array([[val for val in item.text.split()] for item in items],
                                       dtype=np.float))
            return np.nanmean(np.dstack(arrays), -1)
        else:
            return
516649
def _ircounts2radiance(counts, scale, offset):
        
        rad = (counts - offset) / scale
        return rad.clip(min=0)
347266
def modis2cnes(modis_date):
    

    if not isinstance(modis_date,list) : modis_date=[modis_date]

    if len(modis_date[0]) ==  7 :
        obj=[datetime.datetime.strptime(d,"%Y%j") for d in modis_date] 
    else :
        obj=[datetime.datetime.strptime(d,"%Y%j%H%M") for d in modis_date]
    
#    str,obj=cnes_convert(modis_date)
    dat=[o.strftime("%d/%m/%Y-%H:%M") for o in obj]
    
    return cnes_convert(dat)
465268
def sky2px(wcs,ra,dec,dra,ddec,cell, beam):
    """"""
    dra = beam if dra<beam else dra # assume every source is at least as large as the psf
    ddec = beam if ddec<beam else ddec
    offsetDec = int((ddec/2.)/cell)
    offsetRA = int((dra/2.)/cell)
    if offsetDec%2==1:
        offsetDec += 1
    if offsetRA%2==1:
        offsetRA += 1

    raPix,decPix = map(int, wcs.wcs2pix(ra,dec))
    return np.array([raPix-offsetRA,raPix+offsetRA,decPix-offsetDec,decPix+offsetDec])
929349
def read(self, vals):
        
        i = 0
        if len(vals[i]) == 0:
            self.year = None
        else:
            self.year = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.month = None
        else:
            self.month = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.day = None
        else:
            self.day = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.hour = None
        else:
            self.hour = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.minute = None
        else:
            self.minute = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.data_source_and_uncertainty_flags = None
        else:
            self.data_source_and_uncertainty_flags = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.dry_bulb_temperature = None
        else:
            self.dry_bulb_temperature = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.dew_point_temperature = None
        else:
            self.dew_point_temperature = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.relative_humidity = None
        else:
            self.relative_humidity = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.atmospheric_station_pressure = None
        else:
            self.atmospheric_station_pressure = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.extraterrestrial_horizontal_radiation = None
        else:
            self.extraterrestrial_horizontal_radiation = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.extraterrestrial_direct_normal_radiation = None
        else:
            self.extraterrestrial_direct_normal_radiation = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.horizontal_infrared_radiation_intensity = None
        else:
            self.horizontal_infrared_radiation_intensity = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.global_horizontal_radiation = None
        else:
            self.global_horizontal_radiation = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.direct_normal_radiation = None
        else:
            self.direct_normal_radiation = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.diffuse_horizontal_radiation = None
        else:
            self.diffuse_horizontal_radiation = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.global_horizontal_illuminance = None
        else:
            self.global_horizontal_illuminance = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.direct_normal_illuminance = None
        else:
            self.direct_normal_illuminance = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.diffuse_horizontal_illuminance = None
        else:
            self.diffuse_horizontal_illuminance = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.zenith_luminance = None
        else:
            self.zenith_luminance = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.wind_direction = None
        else:
            self.wind_direction = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.wind_speed = None
        else:
            self.wind_speed = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.total_sky_cover = None
        else:
            self.total_sky_cover = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.opaque_sky_cover = None
        else:
            self.opaque_sky_cover = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.visibility = None
        else:
            self.visibility = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.ceiling_height = None
        else:
            self.ceiling_height = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.present_weather_observation = None
        else:
            self.present_weather_observation = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.present_weather_codes = None
        else:
            self.present_weather_codes = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.precipitable_water = None
        else:
            self.precipitable_water = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.aerosol_optical_depth = None
        else:
            self.aerosol_optical_depth = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.snow_depth = None
        else:
            self.snow_depth = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.days_since_last_snowfall = None
        else:
            self.days_since_last_snowfall = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.albedo = None
        else:
            self.albedo = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.liquid_precipitation_depth = None
        else:
            self.liquid_precipitation_depth = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.liquid_precipitation_quantity = None
        else:
            self.liquid_precipitation_quantity = vals[i]
        i += 1
67298
def _check(self):
        """"""
        # Run the super method
        super(Photometry, self)._check()

        err_str = None
        has_flux = self._KEYS.FLUX in self
        has_flux_dens = self._KEYS.FLUX_DENSITY in self
        has_u_flux = self._KEYS.U_FLUX in self
        has_u_flux_dens = self._KEYS.U_FLUX_DENSITY in self

        has_freq = self._KEYS.FREQUENCY in self
        has_band = self._KEYS.BAND in self
        has_ener = self._KEYS.ENERGY in self
        has_u_freq = self._KEYS.U_FREQUENCY in self
        has_u_ener = self._KEYS.U_ENERGY in self

        if has_flux or has_flux_dens:
            if not any([has_freq, has_band, has_ener]):
                err_str = ("Has `{}` or `{}`".format(self._KEYS.FLUX,
                                                     self._KEYS.FLUX_DENSITY) +
                           " but None of `{}`, `{}`, `{}`".format(
                               self._KEYS.FREQUENCY, self._KEYS.BAND,
                               self._KEYS.ENERGY))
            elif has_flux and not has_u_flux:
                err_str = "`{}` provided without `{}`.".format(
                    self._KEYS.FLUX, self._KEYS.U_FLUX)
            elif has_flux_dens and not has_u_flux_dens:
                err_str = "`{}` provided without `{}`.".format(
                    self._KEYS.FLUX_DENSITY, self._KEYS.U_FLUX_DENSITY)
            elif has_freq and not has_u_freq:
                err_str = "`{}` provided without `{}`.".format(
                    self._KEYS.FREQUENCY, self._KEYS.U_FREQUENCY)
            elif has_ener and not has_u_ener:
                err_str = "`{}` provided without `{}`.".format(
                    self._KEYS.ENERGY, self._KEYS.U_ENERGY)

        if err_str is not None:
            raise ValueError(err_str)

        return
461202
protected static boolean haveSameAspectRatio(RectF r1, RectF r2) {
        // Reduces precision to avoid problems when comparing aspect ratios.
        float srcRectRatio = MathUtils.truncate(MathUtils.getRectRatio(r1), 3);
        float dstRectRatio = MathUtils.truncate(MathUtils.getRectRatio(r2), 3);
        
        // Compares aspect ratios that allows for a tolerance range of [0, 0.01] 
        return (Math.abs(srcRectRatio-dstRectRatio) <= 0.01f);
    }
747442
def ndsi(self):
        
        green, swir1 = self.reflectance(3), self.reflectance(6)
        ndsi = self._divide_zero((green - swir1), (green + swir1), nan)

        return ndsi
242834
def _shift_wavelengths(model1, model2):
    
    if isinstance(model1, _models.RedshiftScaleFactor):
        val = _get_sampleset(model2)
        if val is None:
            w = val
        else:
            w = model1.inverse(val)
    elif isinstance(model1, _models.Scale):
        w = _get_sampleset(model2)
    else:
        w = _get_sampleset(model1)
    return w
610966
def _ir_calibrate(self, data, channel_name, cal_type):
        """"""
        if cal_type == 1:
            # spectral radiances
            return self._srads2bt(data, channel_name)
        elif cal_type == 2:
            # effective radiances
            return self._erads2bt(data, channel_name)
        else:
            raise NotImplementedError('Unknown calibration type')
726008
def convert2hdf5(platform_name):
    """"""

    import h5py

    ahi = AhiRSR(platform_name)
    filename = os.path.join(ahi.output_dir,
                            "rsr_ahi_{platform}.h5".format(platform=platform_name))

    with h5py.File(filename, "w") as h5f:
        h5f.attrs['description'] = 'Relative Spectral Responses for AHI'
        h5f.attrs['platform_name'] = platform_name
        h5f.attrs['sensor'] = 'ahi'
        h5f.attrs['band_names'] = AHI_BAND_NAMES.values()

        for chname in AHI_BAND_NAMES.values():

            grp = h5f.create_group(chname)
            wvl = ahi.rsr[chname][
                'wavelength'][~np.isnan(ahi.rsr[chname]['wavelength'])]
            rsp = ahi.rsr[chname][
                'response'][~np.isnan(ahi.rsr[chname]['wavelength'])]
            grp.attrs['central_wavelength'] = get_central_wave(wvl, rsp)
            arr = ahi.rsr[chname]['wavelength']
            dset = grp.create_dataset('wavelength', arr.shape, dtype='f')
            dset.attrs['unit'] = 'm'
            dset.attrs['scale'] = 1e-06
            dset[...] = arr
            arr = ahi.rsr[chname]['response']
            dset = grp.create_dataset('response', arr.shape, dtype='f')
            dset[...] = arr
216573
def f_aoi(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth):
    
    return pvlib.irradiance.aoi(surface_tilt, surface_azimuth,
                                solar_zenith, solar_azimuth)
42420
def read_inversion_results(self, tomodir):
        
        self._read_inversion_results(tomodir)
        self._read_inv_ctr(tomodir)
        self._read_resm_m(tomodir)
        self._read_eps_ctr(tomodir)
1001309
def _gti_dirint_gte_90(poa_global, aoi, solar_zenith, solar_azimuth,
                       surface_tilt, times, kt_prime,
                       pressure=101325., temp_dew=None, albedo=.25):
    
    kt_prime_gte_90 = _gti_dirint_gte_90_kt_prime(aoi, solar_zenith,
                                                  solar_azimuth, times,
                                                  kt_prime)

    I0 = get_extra_radiation(times, 1370, 'spencer')
    airmass = atmosphere.get_relative_airmass(solar_zenith, model='kasten1966')
    airmass = atmosphere.get_absolute_airmass(airmass, pressure)
    kt = kt_prime_gte_90 * _kt_kt_prime_factor(airmass)
    disc_dni = np.maximum(_disc_kn(kt, airmass)[0] * I0, 0)

    dni_gte_90 = _dirint_from_dni_ktprime(disc_dni, kt_prime, solar_zenith,
                                          False, temp_dew)

    dni_gte_90_proj = dni_gte_90 * tools.cosd(solar_zenith)
    cos_surface_tilt = tools.cosd(surface_tilt)

    # isotropic sky plus ground diffuse
    dhi_gte_90 = (
        (2 * poa_global - dni_gte_90_proj * albedo * (1 - cos_surface_tilt)) /
        (1 + cos_surface_tilt + albedo * (1 - cos_surface_tilt)))

    ghi_gte_90 = dni_gte_90_proj + dhi_gte_90

    return ghi_gte_90, dni_gte_90, dhi_gte_90
632415
def get_dataset(self, key, info):
        """"""
        if self.mdrs is None:
            self._read_all(self.filename)

        if key.name in ['longitude', 'latitude']:
            lons, lats = self.get_full_lonlats()
            if key.name == 'longitude':
                dataset = create_xarray(lons)
            else:
                dataset = create_xarray(lats)

        elif key.name in ['solar_zenith_angle', 'solar_azimuth_angle',
                          'satellite_zenith_angle', 'satellite_azimuth_angle']:
            sun_azi, sun_zen, sat_azi, sat_zen = self.get_full_angles()
            if key.name == 'solar_zenith_angle':
                dataset = create_xarray(sun_zen)
            elif key.name == 'solar_azimuth_angle':
                dataset = create_xarray(sun_azi)
            if key.name == 'satellite_zenith_angle':
                dataset = create_xarray(sat_zen)
            elif key.name == 'satellite_azimuth_angle':
                dataset = create_xarray(sat_azi)
        else:
            mask = None
            if key.calibration == 'counts':
                raise ValueError('calibration=counts is not supported! ' +
                                 'This reader cannot return counts')
            elif key.calibration not in ['reflectance', 'brightness_temperature', 'radiance']:
                raise ValueError('calibration type ' + str(key.calibration) +
                                 ' is not supported!')

            if key.name in ['3A', '3a'] and self.three_a_mask is None:
                self.three_a_mask = ((self["FRAME_INDICATOR"] & 2 ** 16) != 2 ** 16)

            if key.name in ['3B', '3b'] and self.three_b_mask is None:
                self.three_b_mask = ((self["FRAME_INDICATOR"] & 2 ** 16) != 0)

            if key.name not in ["1", "2", "3a", "3A", "3b", "3B", "4", "5"]:
                LOG.info("Can't load channel in eps_l1b: " + str(key.name))
                return

            if key.name == "1":
                if key.calibration == 'reflectance':
                    array = radiance_to_refl(self["SCENE_RADIANCES"][:, 0, :],
                                             self["CH1_SOLAR_FILTERED_IRRADIANCE"])
                else:
                    array = self["SCENE_RADIANCES"][:, 0, :]

            if key.name == "2":
                if key.calibration == 'reflectance':
                    array = radiance_to_refl(self["SCENE_RADIANCES"][:, 1, :],
                                             self["CH2_SOLAR_FILTERED_IRRADIANCE"])
                else:
                    array = self["SCENE_RADIANCES"][:, 1, :]

            if key.name.lower() == "3a":
                if key.calibration == 'reflectance':
                    array = radiance_to_refl(self["SCENE_RADIANCES"][:, 2, :],
                                             self["CH3A_SOLAR_FILTERED_IRRADIANCE"])
                else:
                    array = self["SCENE_RADIANCES"][:, 2, :]

                mask = np.empty(array.shape, dtype=bool)
                mask[:, :] = self.three_a_mask[:, np.newaxis]

            if key.name.lower() == "3b":
                if key.calibration == 'brightness_temperature':
                    array = radiance_to_bt(self["SCENE_RADIANCES"][:, 2, :],
                                           self["CH3B_CENTRAL_WAVENUMBER"],
                                           self["CH3B_CONSTANT1"],
                                           self["CH3B_CONSTANT2_SLOPE"])
                else:
                    array = self["SCENE_RADIANCES"][:, 2, :]
                mask = np.empty(array.shape, dtype=bool)
                mask[:, :] = self.three_b_mask[:, np.newaxis]

            if key.name == "4":
                if key.calibration == 'brightness_temperature':
                    array = radiance_to_bt(self["SCENE_RADIANCES"][:, 3, :],
                                           self["CH4_CENTRAL_WAVENUMBER"],
                                           self["CH4_CONSTANT1"],
                                           self["CH4_CONSTANT2_SLOPE"])
                else:
                    array = self["SCENE_RADIANCES"][:, 3, :]

            if key.name == "5":
                if key.calibration == 'brightness_temperature':
                    array = radiance_to_bt(self["SCENE_RADIANCES"][:, 4, :],
                                           self["CH5_CENTRAL_WAVENUMBER"],
                                           self["CH5_CONSTANT1"],
                                           self["CH5_CONSTANT2_SLOPE"])
                else:
                    array = self["SCENE_RADIANCES"][:, 4, :]

            dataset = create_xarray(array)
            if mask is not None:
                dataset = dataset.where(~mask)

        dataset.attrs['platform_name'] = self.platform_name
        dataset.attrs['sensor'] = self.sensor_name
        dataset.attrs.update(info)
        dataset.attrs.update(key.to_dict())
        return dataset