Get the Tb from the radiance using the Planck function

    rad:
        Radiance in SI units
    wavelength:
        Wavelength in SI units (meter)
481573
def radiance2tb(rad, wavelength):
    
    from pyspectral.blackbody import blackbody_rad2temp as rad2temp
    return rad2temp(wavelength, rad)
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
1147865
def Ry(rads: Union[float, sympy.Basic]) -> YPowGate:
    """"""
    pi = sympy.pi if protocols.is_parameterized(rads) else np.pi
    return YPowGate(exponent=rads / pi, global_shift=-0.5)
339990
def tb2radiance(self, tb_, **kwargs):
        
        # L = C1 * νc**3 / (exp (C2 νc / [αTb + β]) − 1)
        #
        # C1 = 2 * h * c**2 and C2 = hc/k
        #
        lut = kwargs.get('lut', None)
        normalized = kwargs.get('normalized', True)

        if lut is not None:
            raise NotImplementedError('Using a tb-radiance LUT is not yet supported')
        if not normalized:
            raise NotImplementedError('Deriving the band integrated radiance is not supported')

        c_1 = 2 * H_PLANCK * C_SPEED ** 2
        c_2 = H_PLANCK * C_SPEED / K_BOLTZMANN

        vc_ = SEVIRI[self.bandname][self.platform_name][0]
        # Multiply by 100 to get SI units!
        vc_ *= 100.0
        alpha = SEVIRI[self.bandname][self.platform_name][1]
        beta = SEVIRI[self.bandname][self.platform_name][2]

        radiance = c_1 * vc_ ** 3 / \
            (np.exp(c_2 * vc_ / (alpha * tb_ + beta)) - 1)

        unit = 'W/m^2 sr^-1 (m^-1)^-1'
        scale = 1.0
        return {'radiance': radiance,
                'unit': unit,
                'scale': scale}
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)
655380
def _load(self):
        """"""
        self.wavelength, self.irradiance = \
            np.genfromtxt(self.filename, unpack=True)
763626
def _counts2radiance(self, counts, coefs, channel):
        """"""
        logger.debug('Converting counts to radiance')

        if self._is_vis(channel):
            # Since the scanline-detector assignment is unknown, use the average
            # coefficients for all scanlines.
            slope = np.array(coefs['slope']).mean()
            offset = np.array(coefs['offset']).mean()
            return self._viscounts2radiance(counts=counts, slope=slope,
                                            offset=offset)

        return self._ircounts2radiance(counts=counts, scale=coefs['scale'],
                                       offset=coefs['offset'])
1160113
def dM(self, t, param, Mt, tips=None, gaps=None):
        """"""
        assert isinstance(t, float) and t > 0, "Invalid t: {0}".format(t)
        assert (param == 't') or (param in self.freeparams), (
                "Invalid param: {0}".format(param))

        if Mt is None:
            Mt = self.M(t, tips=tips, gaps=gaps)

        if (param == 'mu') or (param == 't'):
            if param == 'mu':
                alpha = t
            else:
                alpha = self.mu
            if tips is None:
                dM_param = broadcastMatrixMultiply(self.Prxy, Mt, alpha=alpha)
            else:
                dM_param = broadcastMatrixVectorMultiply(self.Prxy, Mt, alpha=alpha)
                if gaps is not None:
                    dM_param[gaps] = scipy.zeros(N_CODON, dtype='float')
            return dM_param

        paramval = getattr(self, param)
        if isinstance(paramval, float):
            paramisvec = False
        else:
            assert isinstance(paramval, numpy.ndarray) and paramval.ndim == 1
            paramisvec = True
            paramlength = paramval.shape[0]

        if ('expD', t) not in self._cached:
            self._cached[('expD', t)] = scipy.exp(self.D * self.mu * t)
        expD = self._cached[('expD', t)]

        if ('V', t) not in self._cached:
            if 'Dxx_Dyy' not in self._cached:
                Dyy = scipy.tile(self.D, (1, N_CODON)).reshape(
                        self.nsites, N_CODON, N_CODON)
                Dxx = scipy.array([Dyy[r].transpose() for r in
                        range(self.nsites)])
                self._cached['Dxx_Dyy'] = Dxx - Dyy
            Dxx_Dyy = self._cached['Dxx_Dyy']
            if 'Dxx_Dyy_lt_ALMOST_ZERO' not in self._cached:
                self._cached['Dxx_Dyy_lt_ALMOST_ZERO'] = scipy.fabs(
                        Dxx_Dyy) < ALMOST_ZERO
            Dxx_Dyy_lt_ALMOST_ZERO = self._cached['Dxx_Dyy_lt_ALMOST_ZERO']
            with scipy.errstate(divide='raise', under='ignore',
                    over='raise', invalid='ignore'):
                expDyy = scipy.tile(expD,(1, N_CODON)).reshape(
                        self.nsites, N_CODON, N_CODON)
                expDxx = scipy.array([expDyy[r].transpose() for r in
                        range(self.nsites)])
                V = (expDxx - expDyy) / Dxx_Dyy
            with scipy.errstate(under='ignore'): # OK if some values 0
                scipy.copyto(V, self.mu * t * expDxx, where=
                        Dxx_Dyy_lt_ALMOST_ZERO)
            self._cached[('V', t)] = V
        V = self._cached[('V', t)]

        with scipy.errstate(under='ignore'): # don't worry if some values 0
            if tips is None:
                if not paramisvec:
                    dM_param = broadcastMatrixMultiply(self.A,
                            broadcastMatrixMultiply(self.B[param]
                            * V, self.Ainv))
                else:
                    dM_param = scipy.ndarray((paramlength, self.nsites,
                            N_CODON, N_CODON), dtype='float')
                    for j in range(paramlength):
                        dM_param[j] = broadcastMatrixMultiply(self.A,
                                broadcastMatrixMultiply(self.B[param][j]
                                * V, self.Ainv))
            else:
                if not paramisvec:
                    dM_param = broadcastMatrixVectorMultiply(self.A,
                            broadcastGetCols(broadcastMatrixMultiply(
                            self.B[param] * V, self.Ainv), tips))
                else:
                    dM_param = scipy.ndarray((paramlength, self.nsites,
                            N_CODON), dtype='float')
                    for j in range(paramlength):
                        dM_param[j] = broadcastMatrixVectorMultiply(self.A,
                            broadcastGetCols(broadcastMatrixMultiply(
                            self.B[param][j] * V, self.Ainv), tips))
                if gaps is not None:
                    if not paramisvec:
                        dM_param[gaps] = scipy.zeros(N_CODON, dtype='float')
                    else:
                        dM_param[:, gaps] = scipy.zeros(N_CODON, dtype='float')
        return dM_param
361026
def model(self):
        """"""
        if self.z == 0:
            m = self._model
        else:
            # wavelength
            if self._internal_wave_unit.physical_type == 'length':
                rs = self._redshift_model.inverse
            # frequency or wavenumber
            # NOTE: This will never execute as long as internal wavelength
            #       unit remains Angstrom.
            else:  # pragma: no cover
                rs = self._redshift_model

            if self.z_type == 'wavelength_only':
                m = rs | self._model
            else:  # conserve_flux
                m = rs | self._model | self._redshift_flux_model

        return m
45593
def optical_absorption_coeff(self):
        
        if self.dielectric_data["density"]:
            real_avg = [sum(self.dielectric_data["density"][1][i][0:3]) / 3
                        for i in range(len(self.dielectric_data["density"][0]))]
            imag_avg = [sum(self.dielectric_data["density"][2][i][0:3]) / 3
                        for i in range(len(self.dielectric_data["density"][0]))]

            def f(freq, real, imag):
                """
                The optical absorption coefficient calculated in terms of
                equation
                """
                hbar = 6.582119514e-16  # eV/K
                coeff = np.sqrt(
                    np.sqrt(real ** 2 + imag ** 2) - real) * \
                        np.sqrt(2) / hbar * freq
                return coeff

            absorption_coeff = [f(freq, real, imag) for freq, real, imag in
                                zip(self.dielectric_data["density"][0],
                                    real_avg, imag_avg)]
        return absorption_coeff
816741
def get_symbol(units) -> str:
    
    if kind(units) == "energy":
        d = {}
        d["nm"] = r"\lambda"
        d["wn"] = r"\bar\nu"
        d["eV"] = r"\hslash\omega"
        d["Hz"] = r"f"
        d["THz"] = r"f"
        d["GHz"] = r"f"
        return d.get(units, "E")
    elif kind(units) == "delay":
        return r"\tau"
    elif kind(units) == "fluence":
        return r"\mathcal{F}"
    elif kind(units) == "pulse_width":
        return r"\sigma"
    elif kind(units) == "temperature":
        return r"T"
    else:
        return kind(units)
247420
def _convert_flux(wavelengths, fluxes, out_flux_unit, area=None,
                  vegaspec=None):
    """"""
    flux_unit_names = (fluxes.unit.to_string(), out_flux_unit.to_string())

    if PHOTLAM.to_string() not in flux_unit_names:
        raise exceptions.SynphotError(
            'PHOTLAM must be one of the conversion units but get '
            '{0}.'.format(flux_unit_names))

    # VEGAMAG
    if VEGAMAG.to_string() in flux_unit_names:
        from .spectrum import SourceSpectrum

        if not isinstance(vegaspec, SourceSpectrum):
            raise exceptions.SynphotError('Vega spectrum is missing.')

        flux_vega = vegaspec(wavelengths)

        out_flux = fluxes.to(
            out_flux_unit,
            equivalencies=spectral_density_vega(wavelengths, flux_vega))

    # OBMAG or count
    elif (u.count in (fluxes.unit, out_flux_unit) or
          OBMAG.to_string() in flux_unit_names):
        if area is None:
            raise exceptions.SynphotError(
                'Area is compulsory for conversion involving count or OBMAG.')
        elif not isinstance(area, u.Quantity):
            area = area * AREA

        out_flux = fluxes.to(
            out_flux_unit,
            equivalencies=spectral_density_count(wavelengths, area))

    else:
        raise u.UnitsError('{0} and {1} are not convertible'.format(
            fluxes.unit, out_flux_unit))

    return out_flux
88859
def get_b(self):
        

        try:

            return self.b.value

        except AttributeError:

            # Transform from L,B to R.A., Dec

            return self.sky_coord.transform_to('galactic').b.value
36256
def get_spectral_index(src, egy):
    """"""
    delta = 1E-5
    f0 = src.spectrum()(pyLike.dArg(egy * (1 - delta)))
    f1 = src.spectrum()(pyLike.dArg(egy * (1 + delta)))

    if f0 > 0 and f1 > 0:
        gamma = np.log10(f0 / f1) / np.log10((1 - delta) / (1 + delta))
    else:
        gamma = np.nan

    return gamma
667033
def calcTransM(self, gamma=None):
        
        sconf = self.getConfig(type='simu')
        if 'l' in sconf:
            l = float(sconf['l'])
        else:
            l = 0
        self.transM = mathutils.transDrift(l, gamma)
        self.transM_flag = True
        return self.transM
4550
def get_ra(self):
        

        try:

            return self.ra.value

        except AttributeError:

            # Transform from L,B to R.A., Dec

            return self.sky_coord.transform_to('icrs').ra.value
1092879
def wavelengthToRGB(wavelength):
	gamma = 0.80;
	intensityMax = 255;

	

	factor = None
	r = None
	g = None
	b = None

	if((wavelength >= 380) and (wavelength<440)):
		r = -(wavelength - 440) / (440.0 - 380.0)
		g = 0.0
		b = 1.0
	elif((wavelength >= 440) and (wavelength<490)):
		r = 0.0
		g = (wavelength - 440) / (490.0 - 440.0)
		b = 1.0
	elif((wavelength >= 490) and (wavelength<510)):
		r = 0.0
		g = 1.0
		b = -(wavelength - 510) / (510.0 - 490.0)
	elif((wavelength >= 510) and (wavelength<580)):
		r = (wavelength - 510) / (580.0 - 510.0)
		g = 1.0
		b = 0.0
	elif((wavelength >= 580) and (wavelength<645)):
		r = 1.0
		g = -(wavelength - 645) / (645.0 - 580.0)
		b = 0.0
	elif((wavelength >= 645) and (wavelength<781)):
		r = 1.0
		g = 0.0
		b = 0.0
	else:
		r = 0.0
		g = 0.0
		b = 0.0

	# Let the intensity fall off near the vision limits
	if((wavelength >= 380) and (wavelength<420)):
	    factor = 0.3 + 0.7*(wavelength - 380) / (420.0 - 380.0)
	elif((wavelength >= 420) and (wavelength<701)):
	    factor = 1.0
	elif((wavelength >= 701) and (wavelength<781)):
	    factor = 0.3 + 0.7*(780 - wavelength) / (780.0 - 700.0)
	else:
	    factor = 0.0

	# Don't want 0^x = 1 for x != 0

	r = int(round(intensityMax * pow(r * factor, gamma)))
	g = int(round(intensityMax * pow(g * factor, gamma)))
	b = int(round(intensityMax * pow(b * factor, gamma)))

	return (r, g, b)