Calibrate to radiance.
501359
def convert_to_radiance(self, data):
        """"""

        bnum = self._header["block5"]['band_number'][0]
        # Check calibration mode and select corresponding coefficients
        if self.calib_mode == "UPDATE" and bnum < 7:
            gain = self._header['calibration']["cali_gain_count2rad_conversion"][0]
            offset = self._header['calibration']["cali_offset_count2rad_conversion"][0]
            if gain == 0 and offset == 0:
                logger.info(
                    "No valid updated coefficients, fall back to default values.")
                gain = self._header["block5"]["gain_count2rad_conversion"][0]
                offset = self._header["block5"]["offset_count2rad_conversion"][0]
        else:
            gain = self._header["block5"]["gain_count2rad_conversion"][0]
            offset = self._header["block5"]["offset_count2rad_conversion"][0]

        return (data * gain + offset).clip(0)
111765
def V(self, brightest=False):
        
        mags = self.get_photometry(brightest=brightest, convert=False)
        VT, dVT = mags['VT']
        BT, dBT = mags['BT']
        if (-0.25 < BT - VT < 2.0):
            (a, b, c, d) = (0.00097, 0.1334, 0.05486, 0.01998)
            V = (VT + a - b * (BT - VT) + c * (BT - VT)**2 -
                d * (BT - VT)**3)

            dVdVT = 1 + b - 2*c*(BT-VT) + 3*d*(BT-VT)**2
            dVdBT = -b + 2*c*(BT-VT) - 3*d*(BT-VT)**2
            dV = np.sqrt((dVdVT**2 * dVT**2) + (dVdBT**2*dBT**2))

        else:
            raise ValueError('BT-VT outside of range to convert')

        return V, dV
755847
def reflectance(self, band):
        
        if band == 6:
            raise ValueError('LT5 reflectance must be other than  band 6')

        rad = self.radiance(band)
        esun = self.ex_atm_irrad[band - 1]
        toa_reflect = (pi * rad * self.earth_sun_dist ** 2) / (esun * cos(self.solar_zenith_rad))

        return toa_reflect
913039
def _vis_calibrate(self, data):
        """"""
        solar_irradiance = self['esun']
        esd = self["earth_sun_distance_anomaly_in_AU"].astype(float)

        factor = np.pi * esd * esd / solar_irradiance

        res = data * factor
        res.attrs = data.attrs
        res.attrs['units'] = '1'
        res.attrs['standard_name'] = 'toa_bidirectional_reflectance'
        return res
5254
def calibrate(self, data, calibration):
        """"""
        tic = datetime.now()

        if calibration == 'counts':
            return data
        elif calibration == 'radiance':
            raise NotImplementedError("Can't calibrate to radiance.")
        else:
            cal = self.calibration_table
            res = data.data.map_blocks(self._interp, cal, dtype=cal[:, 0].dtype)
            res = xr.DataArray(res,
                               dims=data.dims, attrs=data.attrs,
                               coords=data.coords)
        res = res.where(data > 0)
        logger.debug("Calibration time " + str(datetime.now() - tic))
        return res
968418
def blackbody_rad2temp(wavelength, radiance):
    

    mask = False
    if np.isscalar(radiance):
        rad = np.array([radiance, ], dtype='float64')
    else:
        rad = np.array(radiance, dtype='float64')
        if np.ma.is_masked(radiance):
            mask = radiance.mask

    rad = np.ma.masked_array(rad, mask=mask)
    rad = np.ma.masked_less_equal(rad, 0)

    if np.isscalar(wavelength):
        wvl = np.array([wavelength, ], dtype='float64')
    else:
        wvl = np.array(wavelength, dtype='float64')

    const1 = H_PLANCK * C_SPEED / K_BOLTZMANN
    const2 = 2 * H_PLANCK * C_SPEED**2
    res = const1 / (wvl * np.log(np.divide(const2, rad * wvl**5) + 1.0))

    shape = rad.shape
    resshape = res.shape

    if wvl.shape[0] == 1:
        if rad.shape[0] == 1:
            return res[0]
        else:
            return res[::].reshape(shape)
    else:
        if rad.shape[0] == 1:
            return res[0, :]
        else:
            if len(shape) == 1:
                return np.reshape(res, (shape[0], resshape[1]))
            else:
                return np.reshape(res, (shape[0], shape[1], resshape[1]))
1006800
def get_calibration(self, name, shape, chunks=None):
        """"""
        data_items = self.root.findall(".//calibrationVector")
        data, low_res_coords = self.read_xml_array(data_items, name)
        return self.interpolate_xml_array(data, low_res_coords, shape, chunks=chunks)
935828
def get_reflectance(self, sun_zenith, sat_zenith, azidiff, bandname, redband=None):
        """"""
        # Get wavelength in nm for band:
        if isinstance(bandname, float):
            LOG.warning('A wavelength is provided instead of band name - ' +
                        'disregard the relative spectral responses and assume ' +
                        'it is the effective wavelength: %f (micro meter)', bandname)
            wvl = bandname * 1000.0
        else:
            wvl = self.get_effective_wavelength(bandname)
            wvl = wvl * 1000.0

        rayl, wvl_coord, azid_coord, satz_sec_coord, sunz_sec_coord = self.get_reflectance_lut()

        # force dask arrays
        compute = False
        if HAVE_DASK and not isinstance(sun_zenith, Array):
            compute = True
            sun_zenith = from_array(sun_zenith, chunks=sun_zenith.shape)
            sat_zenith = from_array(sat_zenith, chunks=sat_zenith.shape)
            azidiff = from_array(azidiff, chunks=azidiff.shape)
            if redband is not None:
                redband = from_array(redband, chunks=redband.shape)

        clip_angle = rad2deg(arccos(1. / sunz_sec_coord.max()))
        sun_zenith = clip(sun_zenith, 0, clip_angle)
        sunzsec = 1. / cos(deg2rad(sun_zenith))
        clip_angle = rad2deg(arccos(1. / satz_sec_coord.max()))
        sat_zenith = clip(sat_zenith, 0, clip_angle)
        satzsec = 1. / cos(deg2rad(sat_zenith))
        shape = sun_zenith.shape

        if not(wvl_coord.min() < wvl < wvl_coord.max()):
            LOG.warning(
                "Effective wavelength for band %s outside 400-800 nm range!",
                str(bandname))
            LOG.info(
                "Set the rayleigh/aerosol reflectance contribution to zero!")
            if HAVE_DASK:
                chunks = sun_zenith.chunks if redband is None else redband.chunks
                res = zeros(shape, chunks=chunks)
                return res.compute() if compute else res
            else:
                return zeros(shape)

        idx = np.searchsorted(wvl_coord, wvl)
        wvl1 = wvl_coord[idx - 1]
        wvl2 = wvl_coord[idx]

        fac = (wvl2 - wvl) / (wvl2 - wvl1)
        raylwvl = fac * rayl[idx - 1, :, :, :] + (1 - fac) * rayl[idx, :, :, :]
        tic = time.time()

        smin = [sunz_sec_coord[0], azid_coord[0], satz_sec_coord[0]]
        smax = [sunz_sec_coord[-1], azid_coord[-1], satz_sec_coord[-1]]
        orders = [
            len(sunz_sec_coord), len(azid_coord), len(satz_sec_coord)]
        f_3d_grid = atleast_2d(raylwvl.ravel())

        if HAVE_DASK and isinstance(smin[0], Array):
            # compute all of these at the same time before passing to the interpolator
            # otherwise they are computed separately
            smin, smax, orders, f_3d_grid = da.compute(smin, smax, orders, f_3d_grid)
        minterp = MultilinearInterpolator(smin, smax, orders)
        minterp.set_values(f_3d_grid)

        if HAVE_DASK:
            ipn = map_blocks(self._do_interp, minterp, sunzsec, azidiff,
                             satzsec, dtype=raylwvl.dtype, chunks=azidiff.chunks)
        else:
            ipn = self._do_interp(minterp, sunzsec, azidiff, satzsec)

        LOG.debug("Time - Interpolation: {0:f}".format(time.time() - tic))

        ipn *= 100
        res = ipn
        if redband is not None:
            res = where(redband < 20., res,
                        (1 - (redband - 20) / 80) * res)

        res = clip(res, 0, 100)
        if compute:
            res = res.compute()
        return res
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')
831446
def white_point(illuminant, observer=observers.cie_1931_2()):
    
    values = spectrum_to_xyz100(illuminant, observer)
    # normalize for relative luminance, Y=100
    values /= values[1]
    values *= 100
    return values
1336876
def offset(self, index=0):
        """"""
        eta = self._geometry[self.camera][index]["ra"]
        xi = self._geometry[self.camera][index]["dec"]
        ra = self.origin.ra - (eta/math.cos(self.dec.radian))*units.degree
        dec = self.origin.dec - xi * units.degree + 45 * units.arcsec
        self._coordinate = SkyCoord(ra, dec)
389087
def _get_reflectance(self, projectables, optional_datasets):
        """"""
        _nir, _tb11 = projectables
        LOG.info('Getting reflective part of %s', _nir.attrs['name'])

        sun_zenith = None
        tb13_4 = None

        for dataset in optional_datasets:
            wavelengths = dataset.attrs.get('wavelength', [100., 0, 0])
            if (dataset.attrs.get('units') == 'K' and
                    wavelengths[0] <= 13.4 <= wavelengths[2]):
                tb13_4 = dataset
            elif ("standard_name" in dataset.attrs and
                  dataset.attrs["standard_name"] == "solar_zenith_angle"):
                sun_zenith = dataset

        # Check if the sun-zenith angle was provided:
        if sun_zenith is None:
            if sun_zenith_angle is None:
                raise ImportError("No module named pyorbital.astronomy")
            lons, lats = _nir.attrs["area"].get_lonlats_dask(CHUNK_SIZE)
            sun_zenith = sun_zenith_angle(_nir.attrs['start_time'], lons, lats)

        return self._refl3x.reflectance_from_tbs(sun_zenith, _nir, _tb11, tb_ir_co2=tb13_4)
993369
private static void adjustCalibrated(FMatrixRMaj rectifyLeft, FMatrixRMaj rectifyRight,
										 FMatrixRMaj rectifyK,
										 RectangleLength2D_F32 bound, float scale) {
		// translation
		float deltaX = -bound.x0*scale;
		float deltaY = -bound.y0*scale;

		// adjustment matrix
		SimpleMatrix A = new SimpleMatrix(3,3,true,new float[]{scale,0,deltaX,0,scale,deltaY,0,0,1});
		SimpleMatrix rL = SimpleMatrix.wrap(rectifyLeft);
		SimpleMatrix rR = SimpleMatrix.wrap(rectifyRight);
		SimpleMatrix K = SimpleMatrix.wrap(rectifyK);

		// remove previous calibration matrix
		SimpleMatrix K_inv = K.invert();
		rL = K_inv.mult(rL);
		rR = K_inv.mult(rR);

		// compute new calibration matrix and apply it
		K = A.mult(K);

		rectifyK.set(K.getFDRM());
		rectifyLeft.set(K.mult(rL).getFDRM());
		rectifyRight.set(K.mult(rR).getFDRM());
	}
551711
def set_calibration(self, attenuations, freqs, frange, calname):
        """"""
        self._stimulus.setCalibration(attenuations, freqs, frange)
854566
def RGB(self, val):
        """"""
        # need to convert to normalized float
        val = np.atleast_1d(val).astype(np.float32) / 255.
        self.rgba = val
1085086
def calibrate_radiance(array, attributes, index):
    """"""
    offset = np.float32(attributes["radiance_offsets"][index])
    scale = np.float32(attributes["radiance_scales"][index])
    array = (array - offset) * scale
    return array
1319423
def _ir_calibrate(self, data):
        """"""
        fk1 = float(self["planck_fk1"])
        fk2 = float(self["planck_fk2"])
        bc1 = float(self["planck_bc1"])
        bc2 = float(self["planck_bc2"])

        res = (fk2 / xu.log(fk1 / data + 1) - bc1) / bc2
        res.attrs = data.attrs
        res.attrs['units'] = 'K'
        res.attrs['standard_name'] = 'toa_brightness_temperature'
        return res