示例#1
0
 def estimate_fao56_daily(self, day_of_year, temp_c, temp_c_min, temp_c_max,
                          tdew, elevation, latitude, rh, wind_m_s,
                          atmos_pres):
     """ Estimate fao56 from weather """
     sha = pyeto.sunset_hour_angle(pyeto.deg2rad(latitude),
                                   pyeto.sol_dec(day_of_year))
     daylight_hours = pyeto.daylight_hours(sha)
     sunshine_hours = 0.8 * daylight_hours
     ird = pyeto.inv_rel_dist_earth_sun(day_of_year)
     et_rad = pyeto.et_rad(pyeto.deg2rad(latitude),
                           pyeto.sol_dec(day_of_year), sha, ird)
     sol_rad = pyeto.sol_rad_from_sun_hours(daylight_hours, sunshine_hours,
                                            et_rad)
     net_in_sol_rad = pyeto.net_in_sol_rad(sol_rad=sol_rad, albedo=0.23)
     cs_rad = pyeto.cs_rad(elevation, et_rad)
     avp = pyeto.avp_from_tdew(tdew)
     net_out_lw_rad = pyeto.net_out_lw_rad(
         pyeto.convert.celsius2kelvin(temp_c_min),
         pyeto.convert.celsius2kelvin(temp_c_max), sol_rad, cs_rad, avp)
     net_rad = pyeto.net_rad(net_in_sol_rad, net_out_lw_rad)
     eto = pyeto.fao56_penman_monteith(
         net_rad=net_rad,
         t=pyeto.convert.celsius2kelvin(temp_c),
         ws=wind_m_s,
         svp=pyeto.svp_from_t(temp_c),
         avp=avp,
         delta_svp=pyeto.delta_svp(temp_c),
         psy=pyeto.psy_const(atmos_pres))
     return eto
示例#2
0
def calcPET(lat, time, tmin, tmax, tmean):
    '''
    Calculates Potential Evapotranspiration using 
    Hargreaves equation (Hargreaves and Samani, 1985) 
    '''

    latrad = pt.deg2rad(lat)  #Latitude to radians
    dayofyear = pd.Series(time).dt.day.values
    etrad = []
    pet = []

    # Calculate ET radiation
    for x in np.nditer(dayofyear):
        soldec = pt.sol_dec(x)  #Solar declination
        sha = pt.sunset_hour_angle(latrad, soldec)  #Sunset hour aingle
        ird = pt.inv_rel_dist_earth_sun(
            x)  #Inverse relative distance Earth-Sun
        etrad.append(pt.et_rad(latrad, soldec, sha,
                               ird))  #Extraterrestrial radiation

    # Calculate PET using hargreaves
    for x in range(0, len(etrad)):
        pet.append(pt.hargreaves(tmin[x], tmax[x], tmean[x], etrad[x]))

    pet = np.array(pet)
    return (pet)
示例#3
0
        def calculate_extraterrestial_radiation(latitude, day):
            # Calculate solar declination
            solar_declination = pyeto.sol_dec(day)
            # Calculate sunset hour angle
            sunset_hour_angle = pyeto.sunset_hour_angle(latitude, solar_declination)
            # Calculate inverse relative distance earth-sun
            inverse_relative_distance = pyeto.inv_rel_dist_earth_sun(day)
            # Calculate extraterrestial radiation
            extraterrestial_radiation = pyeto.et_rad(latitude, solar_declination,
                sunset_hour_angle, inverse_relative_distance)

            return extraterrestial_radiation
示例#4
0
def get_evap_i(lat, elev, wind, srad, tmin, tmax, tavg, month):
    if month == 1:
        J = 15
    else:
        J = 15 + (month - 1) * 30

    latitude = pyeto.deg2rad(lat)
    atmosphericVapourPressure = pyeto.avp_from_tmin(tmin)
    saturationVapourPressure = pyeto.svp_from_t(tavg)
    ird = pyeto.inv_rel_dist_earth_sun(J)
    solarDeclination = pyeto.sol_dec(J)
    sha = [pyeto.sunset_hour_angle(l, solarDeclination) for l in latitude]
    extraterrestrialRad = [
        pyeto.et_rad(x, solarDeclination, y, ird)
        for x, y in zip(latitude, sha)
    ]
    clearSkyRad = pyeto.cs_rad(elev, extraterrestrialRad)
    netInSolRadnet = pyeto.net_in_sol_rad(srad * 0.001, albedo=0.23)
    netOutSolRadnet = pyeto.net_out_lw_rad(tmin, tmax, srad * 0.001,
                                           clearSkyRad,
                                           atmosphericVapourPressure)
    netRadiation = pyeto.net_rad(netInSolRadnet, netOutSolRadnet)
    tempKelvin = pyeto.celsius2kelvin(tavg)
    windSpeed2m = pyeto.wind_speed_2m(wind, 10)
    slopeSvp = pyeto.delta_svp(tavg)
    atmPressure = pyeto.atm_pressure(elev)
    psyConstant = pyeto.psy_const(atmPressure)

    return pyeto.fao56_penman_monteith(netRadiation,
                                       tempKelvin,
                                       windSpeed2m,
                                       saturationVapourPressure,
                                       atmosphericVapourPressure,
                                       slopeSvp,
                                       psyConstant,
                                       shf=0.0)
#Completar los valores de ETo
    for j in range(0,len(Tmean["0"])):
            tmin=(Tmin["0"][j])
            tmink=pyeto.celsius2kelvin(tmin)
            tmax=(Tmax["0"][j])
            tmaxk=pyeto.celsius2kelvin(tmax)
            t=(Tmean["0"][j])
            tk=pyeto.celsius2kelvin(t)
            rh_mean=(HR["0"][j])
            ws=(VV["0"][j])
            lat=pyeto.deg2rad(lat)
            day=day+1
            sunshine_hours=(BS["0"][j])
            #Radiacion neta
            sol_dec=pyeto.sol_dec(day)
            sha=pyeto.sunset_hour_angle(lat,sol_dec)
            daylight_hours=pyeto.daylight_hours(sha)
            ird=pyeto.inv_rel_dist_earth_sun(day)
            et_rad=pyeto.et_rad(lat, sol_dec, sha, ird)
            sol_rad=pyeto.sol_rad_from_sun_hours(daylight_hours,sunshine_hours,et_rad)
            ni_sw_rad=pyeto.net_in_sol_rad(sol_rad, albedo=0.23)
            cs_rad=pyeto.cs_rad(altitude, et_rad)
            svp_tmin=pyeto.svp_from_t(tmin)
            svp_tmax=pyeto.svp_from_t(tmax)
            avp=pyeto.avp_from_rhmean(svp_tmin, svp_tmax, rh_mean)
            no_lw_rad=pyeto.net_out_lw_rad(tmink, tmaxk, sol_rad, cs_rad, avp)
            net_rad=pyeto.net_rad(ni_sw_rad, no_lw_rad)
            #Presion de vapor de saturacion
            svp=pyeto.svp_from_t(t)
            #Delta presion de vapor de saturacion
            delta_svp=pyeto.delta_svp(t)
示例#6
0
def get_data_from_WU():

    ###array to store the reports
    wu_weather_reports = []

    ##  today and last 6 days definition
    day1 = now - datetime.timedelta(days=6)
    day2 = now - datetime.timedelta(days=5)
    day3 = now - datetime.timedelta(days=4)
    day4 = now - datetime.timedelta(days=3)
    day5 = now - datetime.timedelta(days=2)
    day6 = now - datetime.timedelta(days=1)
    day7 = now

    #### convert dates to WU required format
    days = {
        'day1': day1.strftime('%Y%m%d'),
        'day2': day2.strftime('%Y%m%d'),
        'day3': day3.strftime('%Y%m%d'),
        'day4': day4.strftime('%Y%m%d'),
        'day5': day5.strftime('%Y%m%d'),
        'day6': day6.strftime('%Y%m%d'),
        'day7': day7.strftime('%Y%m%d')
    }

    ### make API wather hisotry call for each day
    for day in days:
        url = 'http://api.wunderground.com/api/7c2ab99a0ccee978/history_{0}/q/95316.json'.format(
            days[day])
        headers = {'content-type': 'application/JSON; charset=utf8'}
        response = requests.get(url, headers=headers)

        data = json.loads(response.text)

        #ETo calculation for the day using FAO-56 Penman-Monteith method
        lat = pyeto.deg2rad(37.585652)
        altitude = 38

        julian_day = datetime.datetime.strptime(days.get(day),
                                                '%Y%m%d').timetuple().tm_yday
        sol_dec = pyeto.sol_dec(julian_day)
        sha = pyeto.sunset_hour_angle(lat, sol_dec)
        ird = pyeto.inv_rel_dist_earth_sun(julian_day)

        ### net radiation calculator
        net_rad = pyeto.et_rad(lat, sol_dec, sha, ird)

        temp_c = float(data["history"]["observations"][1]["tempm"])
        temp_k = float(data["history"]["observations"][1]["tempi"])
        humidity = float(data["history"]["observations"][1]["hum"])
        dew_point = float(data["history"]["observations"][1]["dewptm"])
        ws = float(data["history"]["observations"][1]["wspdm"])

        #actual and saturated vapour pressure in kPH
        svp = pyeto.svp_from_t(temp_c)
        avp = pyeto.avp_from_tdew(dew_point)
        delta_svp = pyeto.delta_svp(temp_c)

        atm_pressure = pyeto.atm_pressure(altitude)
        psy = pyeto.psy_const(atm_pressure)

        #### the ETo plugin retun results in mm, it was converted to inched
        ETo_in_mm = pyeto.fao56_penman_monteith(net_rad,
                                                temp_k,
                                                ws,
                                                svp,
                                                avp,
                                                delta_svp,
                                                psy,
                                                shf=0.0)
        ETo = ETo_in_mm * 0.039370

        ## insert eto value to day weather report
        data["history"]["observations"][1].update(
            {"ETo": "{0:.2f}".format(ETo)})

        ###add report to report collector array
        wu_weather_reports.append(data["history"]["observations"][1])

    #return all reports
    return wu_weather_reports
示例#7
0
    def etp_Thornthwaite(self, anosCalculoETP, inicioPlantioTuple):
        latitudeRad = deg2rad(self.estacao.latitude)

        temperaturaMensalAcc = np.array([]).reshape(0, 12)
        temperaturaDecendioAcc = np.array([]).reshape(12, 3, 0)
        ETPs = np.zeros([len(anosCalculoETP), 13, 4])
        self.anosCalculo = anosCalculoETP
        # O ETP é calculado anualmente e o resultado final é a média desses cálculos
        # anosCalculoETP grava os anos selecionados pelo usuário para o cálculo do ETP
        if anosCalculoETP:
            for ano in anosCalculoETP:
                #ano = min(anosCalculoETP)
                ### Calcula medias mensais e decendiais de temperatura para um ano ###
                diaAtual = date(ano, 1, 1)

                temperaturaAcum = 0
                temperaturaAcumMes = 0
                diasNoDecendio = 0
                diasNoMes = 0

                temperaturaMensal = []
                temperaturaDecendio = np.zeros((12, 3))

                #final = date(min(anosCalculoETP)+1, inicioPlantioTuple[0], inicioPlantioTuple[1])
                #print(anosCalculoETP)
                while (diaAtual.year == ano):
                    #while (diaAtual.year in anosCalculoETP) and ((diaAtual)!=final):
                    #print(diaAtual)
                    if not np.isnan(
                            self.dadosMeteorologicos['tmed'][diaAtual]):
                        #print(self.dadosMeteorologicos['tmed'][diaAtual])
                        temperaturaAcum += self.dadosMeteorologicos['tmed'][
                            diaAtual]
                        temperaturaAcumMes += self.dadosMeteorologicos['tmed'][
                            diaAtual]
                        diasNoDecendio += 1
                        diasNoMes += 1
                    amanha = diaAtual + timedelta(days=1)
                    #print(temperaturaAcum)
                    if amanha.month != diaAtual.month:
                        #print('trocou mes')
                        #print(amanha.month)
                        if diasNoMes > 0:
                            # Corrigir temperaturas negativas
                            temperaturaMensal.append(temperaturaAcumMes /
                                                     diasNoMes *
                                                     (temperaturaAcumMes >= 0))
                        else:
                            temperaturaMensal.append(25)

                        temperaturaAcumMes = 0
                        diasNoMes = 0

                    if amanha.day == 1 or amanha.day == 11 or amanha.day == 21:
                        decendioAtual = calculosDecendiais.converterToDataDecendio(
                            diaAtual)
                        if diasNoDecendio > 0:
                            temperaturaDecendio[
                                decendioAtual[0] - 1, decendioAtual[1] -
                                1] = (temperaturaAcum /
                                      diasNoDecendio) * (temperaturaAcum >= 0)
                        else:
                            temperaturaDecendio[decendioAtual[0] - 1,
                                                decendioAtual[1] - 1] = 25

                        temperaturaAcum = 0
                        diasNoDecendio = 0
                    #print(diaAtual)
                    diaAtual = amanha

                ###########
                #print('temp Acumulada e temp Mensal')
                #print(temperaturaMensalAcc)
                #print(temperaturaDecendioAcc)

                temperaturaMensalAcc = np.vstack(
                    (temperaturaMensalAcc, temperaturaMensal))
                temperaturaDecendioAcc = np.dstack(
                    (temperaturaDecendioAcc, temperaturaDecendio))
                temperaturaMensalMedia = temperaturaMensal
                temperaturaDecendioMedia = temperaturaDecendio
                #print(temperaturaMensalAcc)
                #print(temperaturaDecendioAcc)
                #print(temperaturaMensalAcc)

                # Calcula o heat index a partir das temperaturas

                I = 0.0
                for Tai in temperaturaMensalMedia:
                    if Tai / 5.0 > 0.0:
                        I += (Tai / 5.0)**1.514

                a = (6.75e-07 * I**3) - (7.71e-05 * I**2) + (1.792e-02 *
                                                             I) + 0.49239

                #print(I)
                #print(a)
                horasDeSolAcum = 0
                diasNoDecendio = 0
                diaAtual = date(ano, 1, 1)
                while (diaAtual.year == ano):
                    # Calcula o valor dos ETPs decendiais
                    #while diaAtual.year == 2000:
                    sd = sol_dec(int(diaAtual.strftime('%j')))
                    sha = sunset_hour_angle(latitudeRad, sd)
                    horasDeSolAcum += daylight_hours(sha)
                    idx = anosCalculoETP.index(ano)
                    diasNoDecendio += 1

                    amanha = diaAtual + timedelta(days=1)

                    if amanha.day == 1 or amanha.day == 11 or amanha.day == 21:
                        horasDeSolMedia = horasDeSolAcum / diasNoDecendio
                        decendioAtual = calculosDecendiais.converterToDataDecendio(
                            diaAtual)
                        #print(idx)
                        #print(decendioAtual)
                        #print(temperaturaDecendioMedia)

                        ETPs[idx][decendioAtual] = 16 * (
                            horasDeSolMedia /
                            12.0) * (diasNoDecendio / 30.0) * (
                                (10.0 *
                                 temperaturaDecendioMedia[decendioAtual[0] - 1,
                                                          decendioAtual[1] - 1]
                                 / I)**a)
                        horasDeSolAcum = 0
                        diasNoDecendio = 0

                    diaAtual = amanha
            self.temperaturaMensalMedia = temperaturaMensalAcc
            return ETPs
示例#8
0
    def etp_Thornthwaite(self, anosCalculoETP):
        latitudeRad = deg2rad(self.estacao.latitude)

        temperaturaMensalAcc = np.array([]).reshape(0, 12)
        temperaturaDecendioAcc = np.array([]).reshape(12, 3, 0)
        ETPs = {}

        # O ETP é calculado anualmente e o resultado final é a média desses cálculos
        # anosCalculoETP grava os anos selecionados pelo usuário para o cálculo do ETP
        if anosCalculoETP:
            for ano in anosCalculoETP:
                ### Calcula medias mensais e decendiais de temperatura para um ano ###
                diaAtual = date(ano, 1, 1)

                temperaturaAcum = 0
                temperaturaAcumMes = 0
                diasNoDecendio = 0
                diasNoMes = 0

                temperaturaMensal = []
                temperaturaDecendio = np.zeros((12, 3))

                while diaAtual.year == ano:
                    if self.dadosMeteorologicos['tmed'][diaAtual] is not None:
                        temperaturaAcum += self.dadosMeteorologicos['tmed'][
                            diaAtual]
                        temperaturaAcumMes += self.dadosMeteorologicos['tmed'][
                            diaAtual]
                        diasNoDecendio += 1
                        diasNoMes += 1

                    amanha = diaAtual + timedelta(days=1)

                    if amanha.month != diaAtual.month:
                        if diasNoMes > 0:
                            # Corrigir temperaturas negativas
                            temperaturaMensal.append(temperaturaAcumMes /
                                                     diasNoMes *
                                                     (temperaturaAcumMes >= 0))
                        else:
                            temperaturaMensal.append(25)

                        temperaturaAcumMes = 0
                        diasNoMes = 0

                    if amanha.day == 1 or amanha.day == 11 or amanha.day == 21:
                        decendioAtual = calculosDecendiais.converterToDataDecendio(
                            diaAtual)
                        if diasNoDecendio > 0:
                            temperaturaDecendio[
                                decendioAtual[0] - 1, decendioAtual[1] -
                                1] = (temperaturaAcum /
                                      diasNoDecendio) * (temperaturaAcum >= 0)
                        else:
                            temperaturaDecendio[decendioAtual[0] - 1,
                                                decendioAtual[1] - 1] = 25

                        temperaturaAcum = 0
                        diasNoDecendio = 0

                    diaAtual = amanha

                ###########
                temperaturaMensalAcc = np.vstack(
                    (temperaturaMensalAcc, temperaturaMensal))
                temperaturaDecendioAcc = np.dstack(
                    (temperaturaDecendioAcc, temperaturaDecendio))

            temperaturaMensalMedia = np.mean(temperaturaMensalAcc, axis=0)
            temperaturaDecendioMedia = np.mean(temperaturaDecendioAcc, axis=2)

            # Calcula o heat index a partir das temperaturas
            self.temperaturaMensalMedia = temperaturaMensalMedia
            I = 0.0
            for Tai in temperaturaMensalMedia:
                if Tai / 5.0 > 0.0:
                    I += (Tai / 5.0)**1.514

            a = (6.75e-07 * I**3) - (7.71e-05 * I**2) + (1.792e-02 *
                                                         I) + 0.49239

            diaAtual = date(2000, 1, 1)

            horasDeSolAcum = 0
            diasNoDecendio = 0

            # Calcula o valor dos ETPs decendiais
            while diaAtual.year == 2000:
                sd = sol_dec(int(diaAtual.strftime('%j')))
                sha = sunset_hour_angle(latitudeRad, sd)
                horasDeSolAcum += daylight_hours(sha)

                diasNoDecendio += 1

                amanha = diaAtual + timedelta(days=1)

                if amanha.day == 1 or amanha.day == 11 or amanha.day == 21:
                    horasDeSolMedia = horasDeSolAcum / diasNoDecendio

                    decendioAtual = calculosDecendiais.converterToDataDecendio(
                        diaAtual)
                    ETPs[decendioAtual] = 1.6 * (horasDeSolMedia / 12.0) * (
                        diasNoDecendio / 30.0) * (
                            (10.0 *
                             temperaturaDecendioMedia[decendioAtual[0] - 1,
                                                      decendioAtual[1] - 1] /
                             I)**a) * 10.0
                    horasDeSolAcum = 0
                    diasNoDecendio = 0

                diaAtual = amanha

        return ETPs
示例#9
0
    def calculate_precipitation(self, d):
        if "rain" in d:
            self.rain_day = float(d["rain"])
        if "snow" in d:
            self.snow_day = float(d["snow"])

    # def calculate_ev_fao56_factor(self, d):
        dt = d['dt']
        factor = 0.0
        if dt > d['sunrise']:
            if dt < d['sunset']:
                factor = min(float(dt - d['sunrise'])/3600.0, 1.0)
            else:
                if dt > d['sunset']:
                    factor = (dt - d['sunrise'])/3600.0
                    if factor < 1.0:
                        factor = 1.0 - factor
            return factor

    #def estimate_fao56_hourly(self, day_of_year, temp_c, tdew, elevation, latitude, rh, wind_m_s, atmos_pres):
        """ Estimate fao56 from weather """
        sha = pyeto.sunset_hour_angle(pyeto.deg2rad(latitude),
                                      pyeto.sol_dec(day_of_year))
        daylight_hours = pyeto.daylight_hours(sha)
        sunshine_hours = 0.8 * daylight_hours
        ird = pyeto.inv_rel_dist_earth_sun(day_of_year)
        et_rad = pyeto.et_rad(pyeto.deg2rad(latitude),
                              pyeto.sol_dec(day_of_year), sha, ird)
        sol_rad = pyeto.sol_rad_from_sun_hours(daylight_hours, sunshine_hours,
                                               et_rad)
        net_in_sol_rad = pyeto.net_in_sol_rad(sol_rad=sol_rad, albedo=0.23)
        cs_rad = pyeto.cs_rad(elevation, et_rad)
        avp = pyeto.avp_from_tdew(tdew)
        #not sure if I trust this net_out_lw_rad calculation here!
        net_out_lw_rad = pyeto.net_out_lw_rad(temp_c-1, temp_c, sol_rad,
                                              cs_rad, avp)
        net_rad = pyeto.net_rad(net_in_sol_rad, net_out_lw_rad)
        eto = pyeto.fao56_penman_monteith(
            net_rad=net_rad,
            t=pyeto.convert.celsius2kelvin(temp_c),
            ws=wind_m_s,
            svp=pyeto.svp_from_t(temp_c),
            avp=avp,
            delta_svp=pyeto.delta_svp(temp_c),
            psy=pyeto.psy_const(atmos_pres))
        return eto

    #def calculate_fao56_hourly(self, d):
        day_of_year = datetime.datetime.now().timetuple().tm_yday
        T_hr = d['temp']
        t_dew = float(d["dew_point"])
        pressure = d['pressure']
        RH_hr = d['humidity']
        u_2 = d['wind_speed']
        #print("CALCULATE_FAO56:")
        #print("T_hr: {}".format(T_hr))
        #print("t_dew: {}".format(t_dew))
        #print("RH_hr: {}".format(RH_hr))
        #print("u_2: {}".format(u_2))
        #print("pressure: {}".format(pressure))
        fao56 = self.estimate_fao56_hourly(day_of_year,
                                    T_hr,
                                    t_dew,
                                    self.elevation,
                                    LAT,
                                    RH_hr,
                                    u_2,
                                    pressure)

        return fao56
coastal = True
altitude = 147
rh_min = 13
rh_max = 88
ws = 1.3

tmean = pyeto.daily_mean_t(tmin, tmax)
atmos_pres = pyeto.atm_pressure(altitude)
psy = pyeto.psy_const(atmos_pres)

# Humidity
svp_tmin = pyeto.svp_from_t(tmin)
svp_tmax = pyeto.svp_from_t(tmax)
delta_svp = pyeto.delta_svp(tmean)
svp = pyeto.mean_svp(tmin, tmax)
avp = pyeto.avp_from_rhmin_rhmax(svp_tmin, svp_tmax, rh_min, rh_max)

# Radiation
sol_dec = pyeto.sol_dec(day_of_year)
sha = pyeto.sunset_hour_angle(latitude, sol_dec)
ird = pyeto.inv_rel_dist_earth_sun(day_of_year)
et_rad = pyeto.et_rad(latitude, sol_dec, sha, ird)
cs_rad = pyeto.cs_rad(altitude, et_rad)
sol_rad = pyeto.sol_rad_from_t(et_rad, cs_rad, tmin, tmax, coastal)
ni_sw_rad = pyeto.net_in_sol_rad(sol_rad)
no_lw_rad = pyeto.net_out_lw_rad(pyeto.celsius2kelvin(tmin), pyeto.celsius2kelvin(tmax), sol_rad, cs_rad, avp)
net_rad = pyeto.net_rad(ni_sw_rad, no_lw_rad)

eto = pyeto.fao56_penman_monteith(net_rad, pyeto.celsius2kelvin(tmean), ws, svp, avp, delta_svp, psy)
print eto
def _compute_solar_radiation(date, lat):
    day_of_year = date.timetuple().tm_yday
    sol_dec = pyeto.sol_dec(day_of_year)
    sha = pyeto.sunset_hour_angle(lat, sol_dec)
    ird = pyeto.inv_rel_dist_earth_sun(day_of_year)
    return pyeto.et_rad(lat, sol_dec, sha, ird)
示例#12
0
def get_data_from_WU():

    ###array to store the reports
    wu_weather_reports = []

    ##  today and last 6 days definition
    day1 = now - datetime.timedelta(days=6)
    day2 = now - datetime.timedelta(days=5)
    day3 = now - datetime.timedelta(days=4)
    day4 = now - datetime.timedelta(days=3)
    day5 = now - datetime.timedelta(days=2)
    day6 = now - datetime.timedelta(days=1)
    day7 = now

    #### convert dates to WU required format
    days = {
    'day1': day1.strftime('%Y%m%d'),
    'day2': day2.strftime('%Y%m%d'),
    'day3': day3.strftime('%Y%m%d'),
    'day4': day4.strftime('%Y%m%d'),
    'day5': day5.strftime('%Y%m%d'),
    'day6': day6.strftime('%Y%m%d'),
    'day7': day7.strftime('%Y%m%d')

    }

    ### make API wather hisotry call for each day
    for day in days:
        url = 'http://api.wunderground.com/api/7c2ab99a0ccee978/history_{0}/q/95316.json'.format(days[day])
        headers = {'content-type': 'application/JSON; charset=utf8'} 
        response = requests.get(url, headers=headers)

        data = json.loads(response.text)

        #ETo calculation for the day using FAO-56 Penman-Monteith method
        lat = pyeto.deg2rad(37.585652)
        altitude = 38

        julian_day = datetime.datetime.strptime(days.get(day), '%Y%m%d').timetuple().tm_yday
        sol_dec = pyeto.sol_dec(julian_day)
        sha = pyeto.sunset_hour_angle(lat, sol_dec)
        ird = pyeto.inv_rel_dist_earth_sun(julian_day)

        ### net radiation calculator
        net_rad = pyeto.et_rad(lat, sol_dec, sha, ird) 

        temp_c = float(data["history"]["observations"][1]["tempm"])
        temp_k = float(data["history"]["observations"][1]["tempi"])
        humidity = float(data["history"]["observations"][1]["hum"])
        dew_point = float(data["history"]["observations"][1]["dewptm"])
        ws = float(data["history"]["observations"][1]["wspdm"])

        #actual and saturated vapour pressure in kPH
        svp = pyeto.svp_from_t(temp_c)
        avp = pyeto.avp_from_tdew(dew_point)
        delta_svp = pyeto.delta_svp(temp_c)

        atm_pressure = pyeto.atm_pressure(altitude)
        psy = pyeto.psy_const(atm_pressure)

        #### the ETo plugin retun results in mm, it was converted to inched
        ETo_in_mm = pyeto.fao56_penman_monteith(net_rad, temp_k, ws, svp, avp, delta_svp, psy, shf=0.0)
        ETo = ETo_in_mm * 0.039370

        ## insert eto value to day weather report
        data["history"]["observations"][1].update({"ETo": "{0:.2f}".format(ETo)})

        ###add report to report collector array
        wu_weather_reports.append(data["history"]["observations"][1])

    #return all reports
    return wu_weather_reports
示例#13
0
 def test_sunset_hour_angle(self):
     # Test based on example 8, p.80 of FAO paper
     sha = pyeto.sunset_hour_angle(convert.deg2rad(-20), 0.120)
     self.assertAlmostEqual(sha, 1.527, 3)
示例#14
0
文件: test_fao.py 项目: Macowe/PyETo
 def test_sunset_hour_angle(self):
     # Test based on example 8, p.80 of FAO paper
     sha = pyeto.sunset_hour_angle(convert.deg2rad(-20), 0.120)
     self.assertAlmostEqual(sha, 1.527, 3)