Calculate net heat flux, and update element layer temperatures
549749
def SurfFlux(self,forc,parameter,simTime,humRef,tempRef,windRef,boundCond,intFlux):
        

        # Calculated per unit area (m^2)
        dens = forc.pres/(1000*0.287042*tempRef*(1.+1.607858*humRef)) # air density (kgd m-3)
        self.aeroCond = 5.8 + 3.7 * windRef         # Convection coef (ref: uwg, eq. 12))

        if (self.horizontal):     # For roof, mass, road
            # Evaporation (m s-1), Film water & soil latent heat
            if not self.is_near_zero(self.waterStorage) and self.waterStorage > 0.0:
                # N.B In the current uwg code, latent heat from evapotranspiration, stagnant water,
                # or anthropogenic sources is not modelled due to the difficulty of validation, and
                # lack of reliability of precipitation data from EPW files.Therefore this condition
                # is never run because all elements have had their waterStorage hardcoded to 0.
                qtsat = self.qsat([self.layerTemp[0]],[forc.pres],parameter)[0]
                eg = self.aeroCond*parameter.colburn*dens*(qtsat-humRef)/parameter.waterDens/parameter.cp
                self.waterStorage = min(self.waterStorage + simTime.dt*(forc.prec-eg),parameter.wgmax)
                self.waterStorage = max(self.waterStorage,0.) # (m)
            else:
                eg = 0.
            soilLat = eg*parameter.waterDens*parameter.lv

            # Winter, no veg
            if simTime.month < parameter.vegStart and simTime.month > parameter.vegEnd:
                self.solAbs = (1.-self.albedo)*self.solRec # (W m-2)
                vegLat = 0.
                vegSens = 0.
            else:    # Summer, veg
                self.solAbs = ((1.-self.vegCoverage)*(1.-self.albedo)+self.vegCoverage*(1.-parameter.vegAlbedo))*self.solRec
                vegLat = self.vegCoverage*parameter.grassFLat*(1.-parameter.vegAlbedo)*self.solRec
                vegSens = self.vegCoverage*(1.-parameter.grassFLat)*(1.-parameter.vegAlbedo)*self.solRec

            self.lat = soilLat + vegLat
            # Sensible & net heat flux
            self.sens = vegSens + self.aeroCond*(self.layerTemp[0]-tempRef)
            self.flux = -self.sens + self.solAbs + self.infra - self.lat # (W m-2)

        else:               # For vertical surfaces (wall)
            self.solAbs = (1.-self.albedo)*self.solRec
            self.lat = 0.

            # Sensible & net heat flux
            self.sens = self.aeroCond*(self.layerTemp[0]-tempRef)
            self.flux = -self.sens + self.solAbs + self.infra - self.lat # (W m-2)

        self.layerTemp = self.Conduction(simTime.dt, self.flux, boundCond, forc.deepTemp, intFlux)
        self.T_ext = self.layerTemp[0]
        self.T_int = self.layerTemp[-1]
889926
def main():
    
    options = handle_options()

    # read in temperature and resistivity data
    tempdata = readin_temp(options.temp_file)
    magdata = readin_rho(options.filename,
                         options.rhofile,
                         aniso=options.aniso)
    # calculate corrected data
    mag_corr = calc_correction(temp=tempdata,
                               mag=magdata,
                               add=options.add,
                               T_std=options.T_std,
                               m=options.m,)
    # save data
    save_mag_to_file(mag_corr,
                     options.output,
                     options.rhofile)
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;
	
}
1092363
def thermostat(self, temperature):
        
        target = int(temperature * 100)
        data = copy.copy(self._parameters)
        data.update({'value': target})
        response = self._get_data('/client/auth/setPoint', data)
        self._logger.debug('Response received {}'.format(response))
        self._clear_cache()
859649
def _update(self):
        

        """

        # Calculate gradient for current iteration.
        self._grad.get_grad(self._x_old)

        # Update z values.
        for i in range(self._prox_list.size):
            z_temp = (2 * self._x_old - self._z[i] - self._gamma *
                      self._grad.grad)
            z_prox = self._prox_list[i].op(z_temp, extra_factor=self._gamma /
                                           self._weights[i])
            self._z[i] += self._lambda_param * (z_prox - self._x_old)

        # Update current reconstruction.
        self._x_new = np.sum([z_i * w_i for z_i, w_i in
                              zip(self._z, self._weights)], axis=0)

        # Update old values for next iteration.
        np.copyto(self._x_old, self._x_new)

        # Update parameter values for next iteration.
        self._update_param()

        # Test cost function for convergence.
        if self._cost_func:
            self.converge = self._cost_func.get_cost(self._x_new)
948744
def _process_flux_param(self, pval, wave):
        """"""
        if isinstance(pval, u.Quantity):
            self._validate_flux_unit(pval.unit)
            outval = units.convert_flux(self._redshift_model(wave), pval,
                                        self._internal_flux_unit).value
        else:  # Assume already in internal unit
            outval = pval
        return outval
627934
def ParallelCalculate(cls,syslst,properties=['energy'],system_changes=all_changes):
        '''
        
        '''
        print('Launching:',end=' ')
        sys.stdout.flush()
        for n,s in enumerate(syslst):
            try :
                s.calc.block=False
                s.calc.calculate(atoms=s,properties=properties,system_changes=system_changes)
            except CalcNotReadyError:
                s.calc.block=True
            print(n+1, end=' ')
            sys.stdout.flush()
        print()
        print('     Done:', end=' ')
        sys.stdout.flush()
        for n,s in enumerate(syslst):
            s.calc.read_results()
            print( n+1, end=' ')
            sys.stdout.flush()
        print()
        return syslst
686460
private function _temperature()
    {
        if (CommonFunctions::executeProgram("snmpwalk", "-Ona -c public -v 1 -t ".PSI_SNMP_TIMEOUT_INT." -r ".PSI_SNMP_RETRY_INT." 127.0.0.1 .1.3.6.1.4.1.24681.1.2.5.0", $buffer, PSI_DEBUG)
           && preg_match('/^[\.\d]+ = STRING:\s\"?(\d+)\sC/', $buffer, $data)) {
            $dev = new SensorDevice();
            $dev->setName("CPU");
            $dev->setValue($data[1]);
            $this->mbinfo->setMbTemp($dev);
        }

        if (CommonFunctions::executeProgram("snmpwalk", "-Ona -c public -v 1 -t ".PSI_SNMP_TIMEOUT_INT." -r ".PSI_SNMP_RETRY_INT." 127.0.0.1 .1.3.6.1.4.1.24681.1.2.6.0", $buffer, PSI_DEBUG)
           && preg_match('/^[\.\d]+ = STRING:\s\"?(\d+)\sC/', $buffer, $data)) {
            $dev = new SensorDevice();
            $dev->setName("System");
            $dev->setValue($data[1]);
            $this->mbinfo->setMbTemp($dev);
        }

        if (CommonFunctions::executeProgram("snmpwalk", "-Ona -c public -v 1 -t ".PSI_SNMP_TIMEOUT_INT." -r ".PSI_SNMP_RETRY_INT." 127.0.0.1 .1.3.6.1.4.1.24681.1.2.11.1.3", $buffer, PSI_DEBUG)) {
            $lines = preg_split('/\r?\n/', $buffer);
            foreach ($lines as $line) if (preg_match('/^[\.\d]+\.(\d+) = STRING:\s\"?(\d+)\sC/', $line, $data)) {
                $dev = new SensorDevice();
                $dev->setName("HDD ".$data[1]);
                $dev->setValue($data[2]);
                $this->mbinfo->setMbTemp($dev);
            }
        }
    }
1100130
def auto(self, minutes, steps=2000):
        

        def run(T, steps):
            """Anneals a system at constant temperature and returns the state,
            energy, rate of acceptance, and rate of improvement."""
            E = self.energy()
            prevState = self.copy_state(self.state)
            prevEnergy = E
            accepts, improves = 0, 0
            for _ in range(steps):
                self.move()
                E = self.energy()
                dE = E - prevEnergy
                if dE > 0.0 and math.exp(-dE / T) < random.random():
                    self.state = self.copy_state(prevState)
                    E = prevEnergy
                else:
                    accepts += 1
                    if dE < 0.0:
                        improves += 1
                    prevState = self.copy_state(self.state)
                    prevEnergy = E
            return E, float(accepts) / steps, float(improves) / steps

        step = 0
        self.start = time.time()

        # Attempting automatic simulated anneal...
        # Find an initial guess for temperature
        T = 0.0
        E = self.energy()
        self.update(step, T, E, None, None)
        while T == 0.0:
            step += 1
            self.move()
            T = abs(self.energy() - E)

        # Search for Tmax - a temperature that gives 98% acceptance
        E, acceptance, improvement = run(T, steps)

        step += steps
        while acceptance > 0.98:
            T = round_figures(T / 1.5, 2)
            E, acceptance, improvement = run(T, steps)
            step += steps
            self.update(step, T, E, acceptance, improvement)
        while acceptance < 0.98:
            T = round_figures(T * 1.5, 2)
            E, acceptance, improvement = run(T, steps)
            step += steps
            self.update(step, T, E, acceptance, improvement)
        Tmax = T

        # Search for Tmin - a temperature that gives 0% improvement
        while improvement > 0.0:
            T = round_figures(T / 1.5, 2)
            E, acceptance, improvement = run(T, steps)
            step += steps
            self.update(step, T, E, acceptance, improvement)
        Tmin = T

        # Calculate anneal duration
        elapsed = time.time() - self.start
        duration = round_figures(int(60.0 * minutes * step / elapsed), 2)

        # Don't perform anneal, just return params
        return {'tmax': Tmax, 'tmin': Tmin, 'steps': duration, 'updates': self.updates}
160273
def set_target_temperature(self, ain, temperature):
        """"""
        param = 16 + ((float(temperature) - 8) * 2)

        if param < min(range(16, 56)):
            param = 253
        elif param > max(range(16, 56)):
            param = 254
        self._aha_request('sethkrtsoll', ain=ain, param=int(param))
34635
private function _temperature()
    {
        foreach ($this->_buf as $sensor) {
            if (((isset($sensor['Sensor Type (Threshold)']) && ($sensor['Sensor Type (Threshold)'] == 'Temperature'))
                ||(isset($sensor['Sensor Type (Analog)']) && ($sensor['Sensor Type (Analog)'] == 'Temperature')))
               && isset($sensor['Unit']) && ($sensor['Unit'] == 'degrees C')
               && isset($sensor['Value'])) {
                $dev = new SensorDevice();
                $dev->setName($sensor['Sensor']);
                $dev->setValue($sensor['Value']);
                if (isset($sensor['Upper Critical']) && (($max = $sensor['Upper Critical']) != "na")) {
                    $dev->setMax($max);
                }
                if (isset($sensor['Status']) && (($status = $sensor['Status']) != "ok")) {
                    $dev->setEvent($status);
                }
                $this->mbinfo->setMbTemp($dev);
            }
        }
    }
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
1330914
def urbflux(UCM, UBL, BEM, forc, parameter, simTime, RSM):
    
    T_can = UCM.canTemp
    Cp = parameter.cp
    UCM.Q_roof = 0.
    sigma = 5.67e-8         # Stephan-Boltzman constant
    UCM.roofTemp = 0.       # Average urban roof temperature
    UCM.wallTemp = 0.       # Average urban wall temperature

    for j in range(len(BEM)):
        # Building energy model
        BEM[j].building.BEMCalc(UCM, BEM[j], forc, parameter, simTime)
        BEM[j].ElecTotal = BEM[j].building.ElecTotal * BEM[j].fl_area # W m-2

        # Update roof infra calc
        e_roof = BEM[j].roof.emissivity
        T_roof = BEM[j].roof.layerTemp[0]
        BEM[j].roof.infra = e_roof * (forc.infra - sigma * T_roof**4.)

        # update wall infra calc (road done later)
        e_wall = BEM[j].wall.emissivity
        T_wall = BEM[j].wall.layerTemp[0]
        # calculates the infrared radiation for wall, taking into account radiation exchange from road
        _infra_road_, BEM[j].wall.infra = infracalcs(UCM, forc, UCM.road.emissivity, e_wall, UCM.roadTemp, T_wall)

        # Update element temperatures
        BEM[j].mass.layerTemp = BEM[j].mass.Conduction(simTime.dt, BEM[j].building.fluxMass,1.,0.,BEM[j].building.fluxMass)
        BEM[j].roof.SurfFlux(forc,parameter,simTime,UCM.canHum,T_can,max(forc.wind,UCM.canWind),1.,BEM[j].building.fluxRoof)
        BEM[j].wall.SurfFlux(forc,parameter,simTime,UCM.canHum,T_can,UCM.canWind,1.,BEM[j].building.fluxWall)

        # Note the average wall & roof temperature
        UCM.wallTemp = UCM.wallTemp + BEM[j].frac*BEM[j].wall.layerTemp[0]
        UCM.roofTemp = UCM.roofTemp + BEM[j].frac*BEM[j].roof.layerTemp[0]

    # Update road infra calc (assume walls have similar emissivity, so use the last one)
    UCM.road.infra, _wall_infra = infracalcs(UCM,forc,UCM.road.emissivity,e_wall,UCM.roadTemp,UCM.wallTemp)
    UCM.road.SurfFlux(forc,parameter,simTime,UCM.canHum,T_can,UCM.canWind,2.,0.)
    UCM.roadTemp = UCM.road.layerTemp[0]

    # Sensible & latent heat flux (total)
    if UCM.latHeat != None:
        UCM.latHeat = UCM.latHeat + UCM.latAnthrop + UCM.treeLatHeat + UCM.road.lat*(1.-UCM.bldDensity)

    # ---------------------------------------------------------------------
    # Advective heat flux to UBL from VDM
    #
    # Note: UWG_Matlab code here is modified to compensate for rounding errors
    # that occur when recursively adding forDens, intAdv1, and intAdv2.
    # This causes issues in the UBL.advHeat calculatiuon when large (1e5)
    # numbers are subtracted to produce small numbers (1e-10) that can
    # differ from equivalent matlab calculations by a factor of 2.
    # Values this small are ~ 0, but for consistency's sake Kahan Summation
    # algorithm is applied to keep margin of difference from UWG_Matlab low.
    # ---------------------------------------------------------------------

    forDens = 0.0
    intAdv1 = 0.0
    intAdv2 = 0.0

    # c1 & c2 stores values truncated by floating point rounding for values < 10^-16
    c1 = 0.0
    c2 = 0.0
    c3 = 0.0

    for iz in range(RSM.nzfor):
        # At c loss of precision at at low order of magnitude, that we need in UBL.advHeat calc
        # Algebraically t is 0, but with floating pt numbers c will accumulate truncated values
        y = RSM.densityProfC[iz]*RSM.dz[iz]/(RSM.z[RSM.nzfor-1] + RSM.dz[RSM.nzfor-1]/2.)
        t = forDens + y
        c1 += (t - forDens) - y
        forDens = t

        y = RSM.windProf[iz]*RSM.tempProf[iz]*RSM.dz[iz]
        t = intAdv1 + y
        c2 += (t - intAdv1) - y
        intAdv1 = t

        y = RSM.windProf[iz]*RSM.dz[iz]
        t = intAdv2 + y
        c3 += (t - intAdv2) - y
        intAdv2 = t

    # Add the truncated values back
    forDens -= c1
    intAdv1 -= c2
    intAdv2 -= c3
    UBL.advHeat = UBL.paralLength*Cp*forDens*(intAdv1-(UBL.ublTemp*intAdv2))/UBL.urbArea

    # ---------------------------------------------------------------------
    # Convective heat flux to UBL from UCM (see Appendix - Bueno (2014))
    # ---------------------------------------------------------------------
    zrUrb = 2*UCM.bldHeight
    zref = RSM.z[RSM.nzref-1]    # Reference height

    # Reference wind speed & canyon air density
    windUrb = forc.wind*log(zref/RSM.z0r)/log(parameter.windHeight/RSM.z0r)*\
        log(zrUrb/UCM.z0u)/log(zref/UCM.z0u)
    dens = forc.pres/(1000*0.287042*T_can*(1.+1.607858*UCM.canHum))

    # Friction velocity
    UCM.ustar = parameter.vk*windUrb/log((zrUrb-UCM.l_disp)/UCM.z0u)

    # Convective scaling velocity
    wstar = (parameter.g*max(UCM.sensHeat,0.0)*zref/dens/Cp/T_can)**(1/3.)
    UCM.ustarMod = max(UCM.ustar,wstar)        # Modified friction velocity
    UCM.uExch = parameter.exCoeff*UCM.ustarMod # Exchange velocity

    # Canyon wind speed, Eq. 27 Chp. 3 Hanna and Britter, 2002
    # assuming CD = 1 and lambda_f = verToHor/4
    UCM.canWind = UCM.ustarMod*(UCM.verToHor/8.)**(-1/2.)

    # Canyon turbulent velocities
    UCM.turbU = 2.4*UCM.ustarMod
    UCM.turbV = 1.9*UCM.ustarMod
    UCM.turbW = 1.3*UCM.ustarMod

    # Urban wind profile
    for iz in range(RSM.nzref):
        UCM.windProf.append(UCM.ustar/parameter.vk*\
            log((RSM.z[iz]+UCM.bldHeight-UCM.l_disp)/UCM.z0u))

    return UCM,UBL,BEM
424924
def interface_temperature(Ts, Tatm, **kwargs):
    ''''''
    #  Actually it's not clear to me how the RRTM code uses these values
    lev = Tatm.domain.axes['lev'].points
    lev_bounds = Tatm.domain.axes['lev'].bounds
    #  Interpolate to layer interfaces
    f = interp1d(lev, Tatm, axis=-1)  # interpolation function
    Tinterp = f(lev_bounds[1:-1])
    #  add TOA value, Assume surface temperature at bottom boundary
    Ttoa = Tatm[...,0]
    Tinterp = np.concatenate((Ttoa[..., np.newaxis], Tinterp, Ts), axis=-1)
    return Tinterp
1302001
def heat_level(self, value):
        """"""
        if value < 0:
            self._heat_level = 0
        elif round(value) > self._num_segments:
            self._heat_level = self._num_segments
        else:
            self._heat_level = int(round(value))
1205032
private function _temperature()
    {
        foreach ($this->_lines as $line) {
            $buffer = preg_split("/\s*\|\s*/", $line);
            if ($buffer[2] == "Temperature" && $buffer[11] != "N/A" && $buffer[4] == "C") {
                $dev = new SensorDevice();
                $dev->setName($buffer[1]);
                $dev->setValue($buffer[3]);
                if ($buffer[9] != "N/A") $dev->setMax($buffer[9]);
                if ($buffer[11] != "'OK'") $dev->setEvent(trim($buffer[11], "'"));
                $this->mbinfo->setMbTemp($dev);
            }
        }
    }
511353
private function _temperature()
    {
        for ($intPosi = 3; $intPosi < 6; $intPosi++) {
            if ($this->_buf_value[$intPosi] == 0) {
                continue;
            }
            preg_match("/([0-9\.])*/", str_replace(",", ".", $this->_buf_value[$intPosi]), $hits);
            $dev = new SensorDevice();
            $dev->setName($this->_buf_label[$intPosi]);
            $dev->setValue($hits[0]);
//            $dev->setMax(70);
            $this->mbinfo->setMbTemp($dev);
        }
    }