Calculate Humidity Index as per Canadian Weather Standards
970167
def cadhumidex(temp, humidity):
    ""
    if temp is None or humidity is None:
        return None
    # Formulas are adapted to not use e^(...) with no appreciable
    # change in accuracy (0.0227%)
    saturation_pressure = (6.112 * (10.0**(7.5 * temp / (237.7 + temp))) *
                           float(humidity) / 100.0)
    return temp + (0.555 * (saturation_pressure - 10.0))
1364843
def get_data(param, data):
    """"""

    try:
        for (_, selected_time_entry) in data:
            loc_data = selected_time_entry['location']
            if param not in loc_data:
                continue
            if param == 'precipitation':
                new_state = loc_data[param]['@value']
            elif param == 'symbol':
                new_state = int(float(loc_data[param]['@number']))
            elif param in ('temperature', 'pressure', 'humidity',
                           'dewpointTemperature'):
                new_state = round(float(loc_data[param]['@value']), 1)
            elif param in ('windSpeed', 'windGust'):
                new_state = round(float(loc_data[param]['@mps']) * 3.6, 1)
            elif param == 'windDirection':
                new_state = round(float(loc_data[param]['@deg']), 1)
            elif param in ('fog', 'cloudiness', 'lowClouds',
                           'mediumClouds', 'highClouds'):
                new_state = round(float(loc_data[param]['@percent']), 1)
            return new_state
    except (ValueError, IndexError, KeyError):
        return None
855504
def dec2hms(dec):
    
    DEGREE = 360.
    HOUR = 24.
    MINUTE = 60.
    SECOND = 3600.
    
    dec = float(dec)
    fhour = dec*(HOUR/DEGREE)
    hour = int(fhour)

    fminute = (fhour - hour)*MINUTE
    minute = int(fminute)
    
    second = (fminute - minute)*MINUTE
    return (hour, minute, second)
812532
def write_epw(self):
        
        epw_prec = self.epw_precision  # precision of epw file input

        for iJ in range(len(self.UCMData)):
            # [iJ+self.simTime.timeInitial-8] = increments along every weather timestep in epw
            # [6 to 21]                       = column data of epw
            self.epwinput[iJ+self.simTime.timeInitial-8][6] = "{0:.{1}f}".format(
                self.UCMData[iJ].canTemp - 273.15, epw_prec)  # dry bulb temperature  [?C]
            # dew point temperature [?C]
            self.epwinput[iJ+self.simTime.timeInitial -
                          8][7] = "{0:.{1}f}".format(self.UCMData[iJ].Tdp, epw_prec)
            # relative humidity     [%]
            self.epwinput[iJ+self.simTime.timeInitial -
                          8][8] = "{0:.{1}f}".format(self.UCMData[iJ].canRHum, epw_prec)
            self.epwinput[iJ+self.simTime.timeInitial-8][21] = "{0:.{1}f}".format(
                self.WeatherData[iJ].wind, epw_prec)        # wind speed [m/s]

        # Writing new EPW file
        epw_new_id = open(self.newPathName, "w")

        for i in range(8):
            new_epw_line = '{}\n'.format(reduce(lambda x, y: x+","+y, self._header[i]))
            epw_new_id.write(new_epw_line)

        for i in range(len(self.epwinput)):
            printme = ""
            for ei in range(34):
                printme += "{}".format(self.epwinput[i][ei]) + ','
            printme = printme + "{}".format(self.epwinput[i][ei])
            new_epw_line = "{0}\n".format(printme)
            epw_new_id.write(new_epw_line)

        epw_new_id.close()

        print("New climate file '{}' is generated at {}.".format(
            self.destinationFileName, self.destinationDir))
512687
def _calc_eddy_time(self):
        
        ens = .5*self.H * self.spec_var(self.wv2*self.ph)
        return 2.*pi*np.sqrt( self.H / ens ) / year
846806
def __parse_fc_data(fc_data):
    """"""
    from buienradar.buienradar import condition_from_code
    fc = []
    for daycnt in range(1, 6):
        daysection = __BRDAYFC % daycnt
        if daysection in fc_data:
            tmpsect = fc_data[daysection]
            fcdatetime = datetime.now(pytz.timezone(__TIMEZONE))
            fcdatetime = fcdatetime.replace(hour=12,
                                            minute=0,
                                            second=0,
                                            microsecond=0)
            # add daycnt days
            fcdatetime = fcdatetime + timedelta(days=daycnt)
            code = tmpsect.get(__BRICOON, []).get(__BRID)
            fcdata = {
                CONDITION: condition_from_code(code),
                TEMPERATURE: __get_float(tmpsect, __BRMAXTEMP),
                MIN_TEMP: __get_float(tmpsect, __BRMINTEMP),
                MAX_TEMP: __get_float(tmpsect, __BRMAXTEMP),
                SUN_CHANCE: __get_int(tmpsect, __BRKANSZON),
                RAIN_CHANCE: __get_int(tmpsect, __BRKANSREGEN),
                RAIN: __get_float(tmpsect, __BRMAXMMREGEN),
                SNOW: __get_float(tmpsect, __BRSNEEUWCMS),
                WINDFORCE: __get_int(tmpsect, __BRWINDKRACHT),
                DATETIME: fcdatetime,
            }
            fcdata[CONDITION][IMAGE] = tmpsect.get(__BRICOON, []).get(__BRTEXT)

            fc.append(fcdata)
    return fc
454117
def _forecast_transform(f_d):
    """"""
    begins = f_d.get('localTimestamp', None)
    issued = f_d.get('issueTimestamp', None)
    solid_stars = f_d.get('solidRating', None)
    faded_stars = f_d.get('fadedRating', None)
    air_pressure = f_d.get('condition_pressure', None)
    unit_pressure = f_d.get('condition_unitPressure', None)
    air_temp = f_d.get('condition_temperature', None)
    unit_temp = f_d.get('condition_unit', None)
    max = f_d.get('swell_maxBreakingHeight', None)
    abs_max = f_d.get('swell_absMaxBreakingHeight', None)
    min = f_d.get('swell_minBreakingHeight', None)
    abs_min = f_d.get('swell_absMinBreakingHeight', None)
    swell_dir = f_d.get('swell_components_combined_compassDirection', None)
    swell_unit = f_d.get('swell_unit', None)
    probability = f_d.get('swell_probability', None)
    period = f_d.get('swell_components_combined_period', None)
    wind_chill = f_d.get('wind_chill', None)
    wind_gusts = f_d.get('wind_gusts', None)
    wind_direction = f_d.get('wind_compassDirection', None)
    wind_degrees = f_d.get('wind_direction', None)
    wind_speed = f_d.get('wind_speed', None)
    wind_unit = f_d.get('wind_unit', None)

    return {
            'air_pressure': "{}{}".format(air_pressure, unit_pressure),
            'air_temp': "{}° {}".format(air_temp, unit_temp),
            'stars': "{} solid, {} faded".format(solid_stars, faded_stars),
            'begins': dt.utcfromtimestamp(begins).strftime("%a %-I %p"),
            'issued': dt.utcfromtimestamp(issued).strftime("%a %-I %p"),
            'max_breaking_height': "{} {}".format(max, swell_unit),
            'min_breaking_height': "{} {}".format(min, swell_unit),
            'probability': "{}%".format(probability),
            'swell_direction': "{}".format(swell_dir),
            'swell_period': "{} seconds".format(period),
            'wind_chill': "{}°".format(wind_chill),
            'wind_direction': "{}° {}".format(wind_degrees, wind_direction),
            'wind_gusts': "{} {}".format(wind_gusts, wind_unit),
            'wind_speed': "{} {}".format(wind_speed, wind_unit),
            }
433834
def region_calcs(self, arr, func):
        """"""
        # Get pressure values for data output on hybrid vertical coordinates.
        bool_pfull = (self.def_vert and self.dtype_in_vert ==
                      internal_names.ETA_STR and self.dtype_out_vert is False)
        if bool_pfull:
            pfull_data = self._get_input_data(_P_VARS[self.dtype_in_vert],
                                              self.start_date,
                                              self.end_date)
            pfull = self._full_to_yearly_ts(
                pfull_data, arr[internal_names.TIME_WEIGHTS_STR]
            ).rename('pressure')
        # Loop over the regions, performing the calculation.
        reg_dat = {}
        for reg in self.region:
            # Just pass along the data if averaged already.
            if 'av' in self.dtype_in_time:
                data_out = reg.ts(arr)
            # Otherwise perform the calculation.
            else:
                method = getattr(reg, func)
                data_out = method(arr)
                if bool_pfull:
                    # Don't apply e.g. standard deviation to coordinates.
                    if func not in ['av', 'ts']:
                        method = reg.ts
                    # Convert Pa to hPa
                    coord = method(pfull) * 1e-2
                    data_out = data_out.assign_coords(
                        **{reg.name + '_pressure': coord}
                    )
            reg_dat.update(**{reg.name: data_out})
        return xr.Dataset(reg_dat)
236087
function(manufacturerDataString){

  let robject = {};
  let data = manufacturerDataString;
  let dataFormat = data[0] & 0xFF;
  let temperature = (data[1] << 8 | data[2] & 0xFF); 
  if (temperature > 32767) {
    temperature -= 65535;
  }
  temperature /= 200.0;
  let humidity =  ((data[3] & 0xFF) << 8 | data[4] & 0xFF) / 400.0;
  let pressure = ((data[5] & 0xFF) << 8 | data[6] & 0xFF) + 50000;
  let accelerationX = (data[7] << 8 | data[8] & 0xFF) / 1000.0;
  let accelerationY = (data[9] << 8 | data[10] & 0xFF) / 1000.0;
  let accelerationZ = (data[11] << 8 | data[12] & 0xFF) / 1000.0;
  let powerInfo = (data[13] & 0xFF) << 8 | data[14] & 0xFF;
  let batteryVoltage = (powerInfo >>> 5) / 1000.0 + 1.6;
  let txPower = (powerInfo & 0b11111) * 2 - 40;
  let movementCounter = data[15] & 0xFF;
  let measurementSequenceNumber = (data[16] & 0xFF) << 8 | data[17] & 0xFF;
  let mac = toHexString(data.subarray(18));

  robject.destination_endpoint = dataFormat;
  robject.temperature = temperature;
  robject.humidity = humidity;
  robject.pressure = pressure;
  robject.accelerationX = accelerationX;
  robject.accelerationY = accelerationY;
  robject.accelerationZ = accelerationZ;
  robject.batteryVoltage = batteryVoltage;
  robject.txPower = txPower;
  robject.movementCounter = movementCounter;
  robject.measurementSequenceNumber = measurementSequenceNumber;
  robject.mac = mac;

  return robject;
}
879078
def hourly_dew_point_values(self, dry_bulb_condition):
        
        hourly_dew_point = []
        max_dpt = self.dew_point(dry_bulb_condition.dry_bulb_max)
        for db in dry_bulb_condition.hourly_values:
            if db >= max_dpt:
                hourly_dew_point.append(max_dpt)
            else:
                hourly_dew_point.append(db)
        return hourly_dew_point
1048128
def getCoeffs(date):
    
    if date < 1900.0 or date > 2025.0:
        print('This subroutine will not work with a date of ' + str(date))
        print('Date must be in the range 1900.0 <= date <= 2025.0')
        print('On return [], []')
        return [], []
    elif date >= 2015.0:
        if date > 2020.0:
            # not adapt for the model but can calculate
            print('This version of the IGRF is intended for use up to 2020.0.')
            print('values for ' + str(date) + ' will be computed but may be of reduced accuracy')
        t = date - 2015.0
        tc = 1.0
        #     pointer for last coefficient in pen-ultimate set of MF coefficients...
        ll = 3060
        nmx = 13
        nc = nmx * (nmx + 2)
    else:
        t = 0.2 * (date - 1900.0)
        ll = int(t)
        t = t - ll
        #     SH models before 1995.0 are only to degree 10
        if date < 1995.0:
            nmx = 10
            nc = nmx * (nmx + 2)
            ll = nc * ll
        else:
            nmx = 13
            nc = nmx * (nmx + 2)
            ll = round(0.2 * (date - 1995.0))
            #     19 is the number of SH models that extend to degree 10
            ll = 120 * 19 + nc * ll
        tc = 1.0 - t

    g, h = [], []
    temp = ll-1
    for n in range(nmx+1):
        g.append([])
        h.append([])
        if n == 0:
            g[0].append(None)
        for m in range(n+1):
            if m != 0:
                g[n].append(tc*gh[temp] + t*gh[temp+nc])
                h[n].append(tc*gh[temp+1] + t*gh[temp+nc+1])
                temp += 2
                # print(n, m, g[n][m], h[n][m])
            else:
                g[n].append(tc*gh[temp] + t*gh[temp+nc])
                h[n].append(None)
                temp += 1
                # print(n, m, g[n][m], h[n][m])
    return g, h
1311391
def dew_point_from_db_hr(db_temp, hr, b_press=101325):
    
    rh = rel_humid_from_db_hr(db_temp, hr, b_press)
    td = dew_point_from_db_rh(db_temp, rh)
    return td
316931
def draw_scatter_plot(world, size, target):
    

    #Find min and max values of humidity and temperature on land so we can
    #normalize temperature and humidity to the chart
    humid = numpy.ma.masked_array(world.layers['humidity'].data, mask=world.layers['ocean'].data)
    temp = numpy.ma.masked_array(world.layers['temperature'].data, mask=world.layers['ocean'].data)
    min_humidity = humid.min()
    max_humidity = humid.max()
    min_temperature = temp.min()
    max_temperature = temp.max()
    temperature_delta = max_temperature - min_temperature
    humidity_delta = max_humidity - min_humidity
    
    #set all pixels white
    for y in range(0, size):
        for x in range(0, size):
            target.set_pixel(x, y, (255, 255, 255, 255))

    #fill in 'bad' boxes with grey
    h_values = ['62', '50', '37', '25', '12']
    t_values = [   0,    1,    2,   3,    5 ]
    for loop in range(0, 5):
        h_min = (size - 1) * ((world.layers['humidity'].quantiles[h_values[loop]] - min_humidity) / humidity_delta)
        if loop != 4:
            h_max = (size - 1) * ((world.layers['humidity'].quantiles[h_values[loop + 1]] - min_humidity) / humidity_delta)
        else:
            h_max = size
        v_max = (size - 1) * ((world.layers['temperature'].thresholds[t_values[loop]][1] - min_temperature) / temperature_delta)
        if h_min < 0:
            h_min = 0
        if h_max > size:
            h_max = size
        if v_max < 0:
            v_max = 0
        if v_max > (size - 1):
            v_max = size - 1
            
        if h_max > 0 and h_min < size and v_max > 0:
            for y in range(int(h_min), int(h_max)):
                for x in range(0, int(v_max)):
                    target.set_pixel(x, (size - 1) - y, (128, 128, 128, 255))
                    
    #draw lines based on thresholds
    for t in range(0, 6):
        v = (size - 1) * ((world.layers['temperature'].thresholds[t][1] - min_temperature) / temperature_delta)
        if 0 < v < size:
            for y in range(0, size):
                target.set_pixel(int(v), (size - 1) - y, (0, 0, 0, 255))
    ranges = ['87', '75', '62', '50', '37', '25', '12']
    for p in ranges:
        h = (size - 1) * ((world.layers['humidity'].quantiles[p] - min_humidity) / humidity_delta)
        if 0 < h < size:
            for x in range(0, size):
                target.set_pixel(x, (size - 1) - int(h), (0, 0, 0, 255))

    #draw gamma curve
    curve_gamma = world.gamma_curve
    curve_bonus = world.curve_offset
    
    for x in range(0, size):
        y = (size - 1) * ((numpy.power((float(x) / (size - 1)), curve_gamma) * (1 - curve_bonus)) + curve_bonus)
        target.set_pixel(x, (size - 1) - int(y), (255, 0, 0, 255))

    #examine all cells in the map and if it is land get the temperature and
    #humidity for the cell.
    for y in range(world.height):
        for x in range(world.width):
            if world.is_land((x, y)):
                t = world.temperature_at((x, y))
                p = world.humidity_at((x, y))

    #get red and blue values depending on temperature and humidity                
                if world.is_temperature_polar((x, y)):
                    r = 0
                elif world.is_temperature_alpine((x, y)):
                    r = 42
                elif world.is_temperature_boreal((x, y)):
                    r = 85
                elif world.is_temperature_cool((x, y)):
                    r = 128
                elif world.is_temperature_warm((x, y)):
                    r = 170
                elif world.is_temperature_subtropical((x, y)):
                    r = 213
                elif world.is_temperature_tropical((x, y)):
                    r = 255
                if world.is_humidity_superarid((x, y)):
                    b = 32
                elif world.is_humidity_perarid((x, y)):
                    b = 64
                elif world.is_humidity_arid((x, y)):
                    b = 96
                elif world.is_humidity_semiarid((x, y)):
                    b = 128
                elif world.is_humidity_subhumid((x, y)):
                    b = 160
                elif world.is_humidity_humid((x, y)):
                    b = 192
                elif world.is_humidity_perhumid((x, y)):
                    b = 224
                elif world.is_humidity_superhumid((x, y)):
                    b = 255

    #calculate x and y position based on normalized temperature and humidity
                nx = (size - 1) * ((t - min_temperature) / temperature_delta)
                ny = (size - 1) * ((p - min_humidity) / humidity_delta)
                    
                target.set_pixel(int(nx), (size - 1) - int(ny), (r, 128, b, 255))
719186
def _clean_header_df(self, df):
        """"""
        if self.suffix == '-drvd.txt':
            df.units = {'release_time': 'second',
                        'precipitable_water': 'millimeter',
                        'inv_pressure': 'hPa',
                        'inv_height': 'meter',
                        'inv_strength': 'Kelvin',
                        'mixed_layer_pressure': 'hPa',
                        'mixed_layer_height': 'meter',
                        'freezing_point_pressure': 'hPa',
                        'freezing_point_height': 'meter',
                        'lcl_pressure': 'hPa',
                        'lcl_height': 'meter',
                        'lfc_pressure': 'hPa',
                        'lfc_height': 'meter',
                        'lnb_pressure': 'hPa',
                        'lnb_height': 'meter',
                        'lifted_index': 'degC',
                        'showalter_index': 'degC',
                        'k_index': 'degC',
                        'total_totals_index': 'degC',
                        'cape': 'Joule / kilogram',
                        'convective_inhibition': 'Joule / kilogram'}

        else:
            df.units = {'release_time': 'second',
                        'latitude': 'degrees',
                        'longitude': 'degrees'}

        return df
244182
def rho_moist(T,p,q):
    '''
    '''
    e = vapor_pressure_from_specific_humidity(p,q)
    w = mixing_ratio_from_vapor_pressure(p,e)
    Tv = virtual_temperature_from_mixing_ratio(T,w)
    return p*100./ Rd/Tv
820827
def get_weather(self, time, max_hour=6):
        """"""
        if self.data is None:
            return {}

        ordered_entries = []
        for time_entry in self.data['product']['time']:
            valid_from = parse_datetime(time_entry['@from'])
            valid_to = parse_datetime(time_entry['@to'])
            if time > valid_to:
                # Has already passed. Never select this.
                continue

            average_dist = (abs((valid_to - time).total_seconds()) +
                            abs((valid_from - time).total_seconds()))

            if average_dist > max_hour * 3600:
                continue

            ordered_entries.append((average_dist, time_entry))

        if not ordered_entries:
            return {}
        ordered_entries.sort(key=lambda item: item[0])
        res = dict()
        res['datetime'] = time
        res['temperature'] = get_data('temperature', ordered_entries)
        res['condition'] = CONDITIONS.get(get_data('symbol', ordered_entries))
        res['pressure'] = get_data('pressure', ordered_entries)
        res['humidity'] = get_data('humidity', ordered_entries)
        res['wind_speed'] = get_data('windSpeed', ordered_entries)
        res['wind_bearing'] = get_data('windDirection', ordered_entries)
        return res
964360
def get_hum(self, raw = False):
        
        self.bus.write_byte(self.address, self.TRIG_RH_noHOLD); # start humidity measurement
        time.sleep(0.1)

        data = self.bus.read_i2c_block(self.address, 2)

        value = data[0]<<8 | data[1]
        value &= ~0b11    # trow out status bits
        humidity = (-6.0 + 125.0*(value/65536.0))

        if raw:                 # raw sensor output, useful for getting an idea of sensor failure status
            return humidity

        else:

            if humidity > 100.0:        # limit values to relevant physical variable (values out of that limit is sensor error state and are dependent on specific sensor piece)
                return 100.0
            elif humidity < 0.0:
                return 0.0
            else:
                return humidity