Derive brightness temperatures from radiance using the Planck 
    function. Wavenumber space
172522
def blackbody_wn_rad2temp(wavenumber, radiance):
    """"""

    if np.isscalar(radiance):
        rad = np.array([radiance, ], dtype='float64')
    else:
        rad = np.array(radiance, dtype='float64')
    if np.isscalar(wavenumber):
        wavnum = np.array([wavenumber, ], dtype='float64')
    else:
        wavnum = np.array(wavenumber, dtype='float64')

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

    shape = rad.shape
    resshape = res.shape

    if wavnum.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]))
408756
def Planck_wavenumber(n, T):
    '''
    '''
    # convert to mks units
    n = n*100.
    return c_light * Planck_frequency(n*c_light, T)
1169120
def _calibrate(self, radiance, coefs, channel, calibration):
        """"""
        if self._is_vis(channel):
            if not calibration == 'reflectance':
                raise ValueError('Cannot calibrate VIS channel to '
                                 '{}'.format(calibration))
            return self._calibrate_vis(radiance=radiance, k=coefs['k'])
        else:
            if not calibration == 'brightness_temperature':
                raise ValueError('Cannot calibrate IR channel to '
                                 '{}'.format(calibration))

            # Since the scanline-detector assignment is unknown, use the average
            # coefficients for all scanlines.
            mean_coefs = {'a': np.array(coefs['a']).mean(),
                          'b': np.array(coefs['b']).mean(),
                          'n': np.array(coefs['n']).mean(),
                          'btmin': coefs['btmin'],
                          'btmax': coefs['btmax']}
            return self._calibrate_ir(radiance=radiance, coefs=mean_coefs)
340834
function (data) {
	var tempColorFunction = new L.PiecewiseFunction([new L.HSLHueFunction(new L.Point(100,270), new L.Point(210,270), {outputLuminosity: '25%'}), new L.HSLHueFunction(new L.Point(210,270), new L.Point(320,0), {outputLuminosity: '25%'})]);
	var tempFillColorFunction = new L.PiecewiseFunction([new L.HSLHueFunction(new L.Point(100,270), new L.Point(210,270), {outputLuminosity: '50%'}), new L.HSLHueFunction(new L.Point(210,270), new L.Point(320,0), {outputLuminosity: '50%'})]);
	var radiusFunction = new L.LinearFunction(new L.Point(272,5), new L.Point(320,15));
	var K_TO_C = 273.15;
	var convert = function (value) {
		var celsius = value - K_TO_C;
		var farenheit = (9/5) * celsius + 32;
		
		return {
			c: celsius,
			f: farenheit
		};
	};
	
	var options = {
		recordsField: 'list',
		latitudeField: 'coord.lat',
		longitudeField: 'coord.lon',
		displayOptions: {
			'main.temp': {
				displayName: 'Temperature',
				color: tempColorFunction,
				fillColor: tempFillColorFunction,
				radius: radiusFunction,
				displayText: function (value) {
					var values = convert(value);
					
					return values.f.toFixed(0) + '&deg;F / ' + values.c.toFixed(0) + '&deg;C';
				}
			}
		},
		layerOptions: {
			width: 5,
			weight: 1,
			iconSize: new L.Point(60,40),
			fillOpacity: 0.8,
			opacity: 1.0,
			radius: 6
		},
		tooltipOptions: {
			iconSize: new L.Point(100,55),
			iconAnchor: new L.Point(-5,55)
		},
		onEachRecord: function (layer,record) {
			var html = '<table class="table table-condensed table-striped table-bordered"><thead><tr><th>Name</th><th>Value</th></tr></thead><tbody></tbody></table>';
			var $html = $(html);
			var $tbody = $html.find('tbody');
			
			for (var property in record.main) {
				$tbody.append('<tr><td>' + property + '</td><td>' + record.main[property] + '</td></tr>');
			}
			layer.bindPopup($html.wrap('<div/>').parent().html(),{
				minWidth: 400,
				maxWidth: 400
			});
		}
	};
	
	var weatherLayer = new L.MapMarkerDataLayer(data, options);

	map.addLayer(weatherLayer);
	
	if (!lastWeatherLayer) {		
		var legend = weatherLayer.getLegend({
			numSegments: 20,
			width: 80,
			className: 'well'
		});
		
		$('#legend').append(legend);
	}
	
	lastWeatherLayer = weatherLayer;
	
}
446199
def hourly_horizontal_infrared(self):
        
        sky_cover = self._sky_condition.hourly_sky_cover
        db_temp = self._dry_bulb_condition.hourly_values
        dp_temp = self._humidity_condition.hourly_dew_point_values(
            self._dry_bulb_condition)

        horiz_ir = []
        for i in xrange(len(sky_cover)):
            horiz_ir.append(
                calc_horizontal_infrared(sky_cover[i], db_temp[i], dp_temp[i]))

        return self._get_daily_data_collections(
            energyflux.HorizontalInfraredRadiationIntensity(), 'W/m2', horiz_ir)
46284
def _lmder1_meyer():
    """"""

    y3 = np.asarray([3.478e4, 2.861e4, 2.365e4, 1.963e4, 1.637e4, 1.372e4, 1.154e4,
                     9.744e3, 8.261e3, 7.03e3, 6.005e3, 5.147e3, 4.427e3, 3.82e3,
                     3.307e3, 2.872e3])

    def func(params, vec):
        temp = 5 * (np.arange(16) + 1) + 45 + params[2]
        tmp1 = params[1] / temp
        tmp2 = np.exp(tmp1)
        vec[:] = params[0] * tmp2 - y3

    def jac(params, jac):
        temp = 5 * (np.arange(16) + 1) + 45 + params[2]
        tmp1 = params[1] / temp
        tmp2 = np.exp(tmp1)
        jac[0] = tmp2
        jac[1] = params[0] * tmp2 / temp
        jac[2] = -tmp1 * jac[1]

    guess = np.asfarray([0.02, 4000, 250])

    _lmder1_driver(16, func, jac, guess,
                   0.4115346655430312e+05, 0.9377945146518742e+01,
                   [0.5609636471026614e-02, 0.6181346346286591e+04,
                    0.3452236346241440e+03])
1151525
def calibrate(self, data, calibration, channel):
        """"""
        coefs = CALIB_COEFS[self.platform_name][channel]
        is_vis = self._is_vis(channel)

        # IR files provide radiances, VIS file provides reflectances
        if is_vis and calibration == 'reflectance':
            return data
        elif not is_vis and calibration == 'radiance':
            return data
        elif not is_vis and calibration == 'brightness_temperature':
            return self._calibrate(radiance=data, calibration=calibration,
                                   coefs=coefs, channel=channel)
        else:
            raise ValueError('Unsupported calibration for channel {}: {}'
                             .format(channel, calibration))
1128083
def brightness(im):
    '''
    
    '''
    im_hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
    h, s, v = cv2.split(im_hsv) 
    height, weight = v.shape[:2]
    total_bright = 0
    for i in v:
        total_bright = total_bright+sum(i)
    return float(total_bright)/(height*weight)
1165782
def _planck_deriv(self, lam, Teff):
        

        expterm = np.exp(self.h*self.c/lam/self.k/Teff)
        return 2*self.h*self.c*self.c/self.k/Teff/lam**7 * (expterm-1)**-2 * (self.h*self.c*expterm-5*lam*self.k*Teff*(expterm-1))
404191
def Spectral_to_XYZ(cobj, illuminant_override=None, *args, **kwargs):
    
    # If the user provides an illuminant_override numpy array, use it.
    if illuminant_override:
        reference_illum = illuminant_override
    else:
        # Otherwise, look up the illuminant from known standards based
        # on the value of 'illuminant' pulled from the SpectralColor object.
        try:
            reference_illum = spectral_constants.REF_ILLUM_TABLE[cobj.illuminant]
        except KeyError:
            raise InvalidIlluminantError(cobj.illuminant)

    # Get the spectral distribution of the selected standard observer.
    if cobj.observer == '10':
        std_obs_x = spectral_constants.STDOBSERV_X10
        std_obs_y = spectral_constants.STDOBSERV_Y10
        std_obs_z = spectral_constants.STDOBSERV_Z10
    else:
        # Assume 2 degree, since it is theoretically the only other possibility.
        std_obs_x = spectral_constants.STDOBSERV_X2
        std_obs_y = spectral_constants.STDOBSERV_Y2
        std_obs_z = spectral_constants.STDOBSERV_Z2

    # This is a NumPy array containing the spectral distribution of the color.
    sample = cobj.get_numpy_array()

    # The denominator is constant throughout the entire calculation for X,
    # Y, and Z coordinates. Calculate it once and re-use.
    denom = std_obs_y * reference_illum

    # This is also a common element in the calculation whereby the sample
    # NumPy array is multiplied by the reference illuminant's power distribution
    # (which is also a NumPy array).
    sample_by_ref_illum = sample * reference_illum

    # Calculate the numerator of the equation to find X.
    x_numerator = sample_by_ref_illum * std_obs_x
    y_numerator = sample_by_ref_illum * std_obs_y
    z_numerator = sample_by_ref_illum * std_obs_z

    xyz_x = x_numerator.sum() / denom.sum()
    xyz_y = y_numerator.sum() / denom.sum()
    xyz_z = z_numerator.sum() / denom.sum()

    return XYZColor(
        xyz_x, xyz_y, xyz_z, observer=cobj.observer, illuminant=cobj.illuminant)
269820
def brighten(color, brightness):
    
    h, s, v = rgb_to_hsv(*map(down_scale, color))
    return tuple(map(up_scale, hsv_to_rgb(h, s, v + down_scale(brightness))))
550567
def getLimbdarkeningCoeff(self, wavelength=1.22):  # TODO replace with pylightcurve
        
        # TODO check this returns correct value - im not certain
        # The intervals of values in the tables
        tempind = [ 3500., 3750., 4000., 4250., 4500., 4750., 5000., 5250., 5500., 5750., 6000., 6250.,
                 6500., 6750., 7000., 7250., 7500., 7750., 8000., 8250., 8500., 8750., 9000., 9250.,
                 9500., 9750., 10000., 10250., 10500., 10750., 11000., 11250., 11500., 11750., 12000., 12250.,
                 12500., 12750., 13000., 14000., 15000., 16000., 17000., 19000., 20000., 21000., 22000., 23000.,
                 24000., 25000., 26000., 27000., 28000., 29000., 30000., 31000., 32000., 33000., 34000., 35000.,
                 36000., 37000., 38000., 39000., 40000., 41000., 42000., 43000., 44000., 45000., 46000., 47000.,
                 48000., 49000., 50000.]
        lggind = [0., 0.5, 1., 1.5, 2., 2.5, 3., 3.5, 4., 4.5, 5.]
        mhind = [-5., -4.5, -4., -3.5, -3., -2.5, -2., -1.5, -1., -0.5, -0.3, -0.2, -0.1, 0., 0.1, 0.2, 0.3, 0.5, 1.]

        # Choose the values in the table nearest our parameters
        tempselect = _findNearest(tempind, float(self.T))
        lgselect = _findNearest(lggind, float(self.calcLogg()))
        mhselect = _findNearest(mhind, float(self.Z))

        quadratic_filepath = resource_stream(__name__, 'data/quadratic.dat')
        coeffTable = np.loadtxt(quadratic_filepath)

        foundValues = False
        for i in range(len(coeffTable)):
            if coeffTable[i, 2] == lgselect and coeffTable[i, 3] == tempselect and coeffTable[i, 4] == mhselect:
                if coeffTable[i, 0] == 1:
                    u1array = coeffTable[i, 8:]  # Limb darkening parameter u1 for each wl in waveind
                    u2array = coeffTable[i+1, 8:]
                    foundValues = True
                    break

        if not foundValues:
            raise ValueError('No limb darkening values could be found')  # TODO replace with better exception

        waveind = [0.365, 0.445, 0.551, 0.658, 0.806, 1.22, 1.63, 2.19, 3.45]  # Wavelengths available in table

        # Interpolates the value at wavelength from values in the table (waveind)
        u1AtWavelength = np.interp(wavelength, waveind, u1array, left=0, right=0)
        u2AtWavelength = np.interp(wavelength, waveind, u2array, left=0, right=0)

        return u1AtWavelength, u2AtWavelength
571880
def from_EV(E, V):
        
        a = np.square(E) / V
        b = E / V
        return Gamma(a, b)
875693
def parameters(self):
        

        try:
            return self._parameters

        except AttributeError:
            None

        parameters = []
        parameters.extend(self.grid_points.dtype.names)

        model_configuration = self._configuration.get("model", {})

        # Continuum
        # Note: continuum cannot just be 'True', it should be a dictionary
        n = len(parameters)
        continuum_config = model_configuration.get("continuum", False)
        if continuum_config is not False:
            if not isinstance(continuum_config, dict):
                raise TypeError("incorrect continuum type")
            for name in set(self.channel_names).intersection(continuum_config):
                degree = continuum_config[name]
                if degree is False:
                    continue

                # Note: N_coefficients = degree + 1
                # Example: degree = 3: a^3 + b^2 + c^1 + d 
                parameters.extend(["continuum_{0}_{1}".format(name, n) \
                    for n in range(degree + 1)])

        # Redshift
        parameters.extend(channel_parameters("z", self.channel_names,
            model_configuration.get("redshift", False)))

        # Spectral resolution
        resolution_parameters = channel_parameters(
            "resolution", self.channel_names,
            model_configuration.get("spectral_resolution", False))
        parameters.extend(resolution_parameters)

        # Underestimated variance
        parameters.extend(channel_parameters(
            "ln_f", self.channel_names,
            model_configuration.get("underestimated_variance", False)))

        # Outlier pixels
        if model_configuration.get("outlier_pixels", False):
            parameters.extend(["Po", "Vo"])

        assert len(parameters) == len(set(parameters)), "Duplicate parameters!"

        self._resolution_parameters = resolution_parameters
        self._parameters = tuple(parameters)

        return self._parameters
1239839
def dew_point(temp, hum):
    
    if temp is None or hum is None:
        return None
    a = 17.27
    b = 237.7
    gamma = ((a * temp) / (b + temp)) + math.log(float(hum) / 100.0)
    return (b * gamma) / (a - gamma)
1283720
def Planck_frequency(nu, T):
    '''
    '''
    return 2*hPlanck*nu**3/c_light**2/(exp(hPlanck*nu/kBoltzmann/T)-1)
796188
def brightness(self):
        
        if self.mode == "ww":
            return int(self.raw_state[9])
        else:
            _, _, v = colorsys.rgb_to_hsv(*self.getRgb())
            return v