Skip to content

Instantly share code, notes, and snippets.

@adamhsparks
Created February 20, 2021 09:29
Show Gist options
  • Save adamhsparks/ecf764f5da0ade8d36ba1fcb75fb0900 to your computer and use it in GitHub Desktop.
Save adamhsparks/ecf764f5da0ade8d36ba1fcb75fb0900 to your computer and use it in GitHub Desktop.
Julia code to calculate leaf wetness using latitude, day of year and relative humidity. Not functional, just a start at translation from R, see leaf_wet.R gist.
function leaf_wet(wth = wth, simple = TRUE)
rh = diurnal_rh(
doy = wth[, DOY],
rh = wth[, RHUM],
tmin = wth[, TMIN],
tmax = wth[, TMAX],
tmp = wth[, TEMP],
lat = wth[, LAT]
)
if simple
lw = length(rh[rh >= 90])
else
w = rh
x = (rh - 80) / 15
w[rh > 95] = 1
cs_1 = rh < 95
w[cs_1] = x[cs_1]
w[rh < 80] = 0
lw = sum(w)
end
return lw
end
function diurnal_rh(rh, tmin, tmax, tmp, doy, lat)
vp = saturated_vapour_pressure(tmp) * rh / 100
hrtemp = diurnal_temp(lat,
doy,
tmin,
tmax)
es = saturated_vapour_pressure(hrtemp)
rh = 100 * vp / es
return rh = findmin(100, findmax(0, rh))
end
# Calculate hourly temperature for a given day
function diurnal_temp(lat, doy, tmin, tmax)
dayl = day_length(lat, doy)
nightl = 24 - dayl
sandhya = 0.5 * dayl
sunris = 12 - sandhya
sunset = 12 + sandhya
x = [[dayl] [nightl] [sunris] [sunset] [tmin] [tmax]]
function hourly_t(x)
hr_temp = zeros(24)
for hr in 1:24
# period a: hours between midnight and sunrise;
if hr < x[3]
tsunst = x[5] + (x[6] - x[5]) * sin(pi * (x[1] / (x[1] + 3)))
hr_temp[hr] = (x[5] - tsunst * exp(-x[2] / 4) + (tsunst - x[5]) *
exp(-(hr + 24 - x[4]) / 4)) / (1 - exp(-x[2] / 4))
elseif hr < x[4]
# period b: hours between time of sunrise and sunset
hr_temp[hr] = x[5] + (x[6] - x[5]) * sin(pi * (hr - x[3]) / (x[1] + 3))
else
# period c: hours between sunset and midnight;
tsunst = x[5] + (x[6] - x[5]) * sin(pi * (x[1] / (x[1] + 3)))
hr_temp[hr] = (x[5] - tsunst * exp(-x[2] / 4) + (tsunst - x[5]) *
exp(-(hr - x[4]) / 4)) / (1 - exp(-x[2] / 4))
end
end
return hr_temp
end
end
# Calculate day length for a given latitude on a given date
function day_length(lat, doy)
if lat > 90 || lat < -90
error("latitude values must fall between -90 and 90 degrees")
end
doy = mod(doy, 366)
# William C. Forsythe and Edward J. Rykiel and Randal S. Stahl and Hsin-i Wu
# and Robert M. Schoolfield. Ecological Modeling, Volume 80 (1995) pp. 87-95,
# "A Model Comparison for Daylength as a Function of Latitude and Day of the
# Year", <DOI: 10.1016/0304-3800(94)00034-F>
P = asin(0.39795 * cos(0.2163108 + 2 * atan(0.9671396 * tan(0.00860 * (doy - 186)))))
a =
(0.014540572569940837 + sin(lat * 0.01745) * sin(P)) /
(cos(lat * 0.01745) * cos(P))
a = min(max(a, -1), 1)
dl = 24 - (24 / pi) * acos(a)
return dl
end
# Calculate saturated vapour pressure, es
function saturated_vapour_pressure(tmp)
0.61094 * exp((17.625 * (tmp)) / ((tmp) + 243.04))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment