Add suntimes and COW_ND.

parent 15ffa998
Pipeline #26355390 passed with stages
in 14 minutes and 56 seconds
Package: claut
Type: Package
Title: Functions from the University of Toronto Climate Lab
Version: 0.1.5
Version: 0.1.6
Date: 2018-04-17
Authors@R: c(person(given = c("Conor", "I."), family = "Anderson",
role = c("aut","cre"), email = "conor.anderson@utoronto.ca"),
......@@ -20,6 +20,7 @@ Imports:
gdata,
iterators,
lpSolve,
lubridate,
parallel,
readr,
reshape2,
......@@ -28,6 +29,9 @@ Imports:
tibble,
utils,
zoo
Suggests:
Rdpack
RdMacros: Rdpack
License: GPL (>= 3)
URL: https://gitlab.com/ConorIA/claut
BugReports: https://gitlab.com/ConorIA/claut/issues
......
# Generated by roxygen2: do not edit by hand
export(COW_ND)
export(deltaDTD)
export(describe_snaps)
export(generate_wkt_csv)
export(missing_data_lab)
export(parse_ASCII_grid)
export(subensemble)
export(suntimes)
export(trimData)
importFrom(doParallel,registerDoParallel)
importFrom(dplyr,"%>%")
importFrom(dplyr,bind_rows)
importFrom(dplyr,filter)
importFrom(dplyr,group_by)
importFrom(dplyr,group_indices)
importFrom(dplyr,left_join)
importFrom(dplyr,mutate)
importFrom(dplyr,rowwise)
importFrom(dplyr,select)
importFrom(dplyr,summarize)
importFrom(dplyr,summarize_all)
importFrom(dplyr,ungroup)
importFrom(foreach,"%do%")
importFrom(foreach,"%dopar%")
importFrom(foreach,foreach)
importFrom(gdata,unmatrix)
importFrom(iterators,icount)
importFrom(lpSolve,lp)
importFrom(lubridate,date)
importFrom(lubridate,force_tz)
importFrom(parallel,detectCores)
importFrom(parallel,makeCluster)
importFrom(parallel,stopCluster)
......
#' Daily extremes using the Night and Day Climatological Observing Window
#'
#' Calculates daily maxima and minima after \insertCite{zaknic-catovic_2018_comparison}{claut}
#'
#' @param lat numeric; the latitude of the observer
#' @param lon numeric; the longitude of the observer
#' @param tz integer; the number of hours shifted from GMT, e.g. for GMT-5, pass \code{-5}
#' @param datetime POSIXct; vector of date times that correspond to the vector \code{var}
#' @param var numeric; a vector of observations for which maxima and minima should be determined
#' @param ... additional parameters to pass to \code{\link{registerDoParallel}}
#'
#' @source \insertRef{zaknic-catovic_2018_comparison}{claut}
#'
#' @return A table of class \code{\link{tbl_df}}.
#'
#' @importFrom dplyr %>% filter mutate rowwise summarize ungroup
#' @importFrom doParallel registerDoParallel
#' @importFrom foreach %dopar%
#' @importFrom lubridate date
#' @importFrom tibble tibble
#'
#' @export
#'
COW_ND <- function(lat, lon, tz, datetime, var, ...) {
date <- date(datetime) %>% unique() %>% sort()
tib <- tibble(Date = date) %>%
rowwise %>%
mutate(period_start = suntimes(lat, lon, tz, Date, "sunrise"),
period_middle = suntimes(lat, lon, tz, Date, "sunset")) %>%
ungroup() %>%
mutate(period_start = period_start + hours(1),
period_end = lead(period_start))
tib2 <- tibble(DateTime = datetime, Var = var)
registerDoParallel(...)
results <- foreach(i = icount(length(date)),
.combine = "rbind",
.packages = "dplyr") %dopar% {
start = tib$period_start[i]
middle = tib$period_middle[i]
end = tib$period_end[i]
max <- tib2 %>% filter(DateTime >= start &
DateTime <= middle) %>%
summarize(Tmax = max(Var)) %>% unlist()
min <- ifelse(is.na(end), NA,
tib2 %>% filter(DateTime >= middle &
DateTime <= end) %>%
summarize(Tmin = min(Var)) %>% unlist())
tibble(
Date = date[i],
Sunrise = start - 3600,
Sunset = end,
Max = max,
Min = min
)
}
results
}
#' Sunrise, solar noon, and sunset times
#'
#' Calculations are based on NOAA's solar calculator, which is, in turn, based on Astronomical Algorithms, by Jean Meeus.
#'
#' @param lat numeric; the latitude of the observer
#' @param lon numeric; the longitude of the observer
#' @param tz integer; the number of hours shifted from GMT, e.g. for GMT-5, pass \code{-5}
#' @param date date; the date to get the sun times for
#' @param out character; one of "sunrise", "solar_noon", or "sunset". Leaving this parameter blank will retrun a list of all three.
#'
#' @source \insertRef{noaa_esrl_solar}{claut}
#'
#' @return POSIXct date time for selected sun time
#'
#' @importFrom lubridate force_tz
#' @export
#'
#' @examples
#' ## Get today's sunrise time for Toronto Pearson Airport
#' suntimes(lat = 43.68, lon = -79.63, tz = -5, date = Sys.Date())
suntimes <- function(lat, lon, tz, date, out = c("sunrise", "solar_noon", "sunset")) {
date <- force_tz(date, "GMT")
deg2rad <- function(deg) {
deg * (pi/180)
}
rad2deg <- function(rad) {
rad * (180/pi)
}
chk2time <- function(chk, tz) {
remainder <- chk * 24
hours <- remainder %/% 1
remainder <- (remainder %% 1) * 60
minutes <- remainder %/% 1
remainder <- (remainder %% 1) * 60
seconds <- remainder %/% 1
as.POSIXct(
paste(date,
paste(sprintf("%02d", c(hours, minutes, seconds)),
collapse = ":")), tz = paste0("Etc/GMT", tz))
}
jdate <- julian(date, -2440588)
jcen <- (jdate - 2451545) / 36525
geom_mean_long_sun <- (280.46646 + jcen * (36000.76983 + jcen * 0.0003032)) %% 360
geom_mean_anom_sun <- 357.52911 + jcen * (35999.05029-0.0001537 * jcen)
eccent_earth_orbit <- 0.016708634 - jcen * (0.000042037 + 0.0000001267 * jcen)
sun_eq_of_crt <- sin(deg2rad(geom_mean_anom_sun)) * (1.914602 - jcen * (0.004817 + 0.000014 * jcen)) + sin(deg2rad(2 * geom_mean_anom_sun)) * (0.019993 - 0.000101 * jcen) + sin(deg2rad(3 * geom_mean_anom_sun)) * 0.000289
sun_true_long <- geom_mean_long_sun + sun_eq_of_crt
sun_app_long <- sun_true_long - 0.00569 - 0.00478*sin(deg2rad(125.04-1934.136 * jcen))
mean_obliq_eliptic <- 23 + (26 + ((21.448 - jcen * (46.815 + jcen * (0.00059 - jcen * 0.001813)))) / 60) / 60
obliq_corr <- mean_obliq_eliptic + 0.00256 * cos(deg2rad(125.04 - 1934.136 * jcen))
var_y <- tan(deg2rad(obliq_corr / 2)) * tan(deg2rad(obliq_corr / 2))
sun_declin <- rad2deg(asin(sin(deg2rad(obliq_corr)) * sin(deg2rad(sun_app_long))))
ha_sunrise <- rad2deg(acos(cos(deg2rad(90.833)) / (cos(deg2rad(lat)) * cos(deg2rad(sun_declin))) - tan(deg2rad(lat)) * tan(deg2rad(sun_declin))))
eq_time_mins <- 4 * rad2deg(var_y * sin(2 * deg2rad(geom_mean_long_sun)) - 2 * eccent_earth_orbit * sin(deg2rad(geom_mean_anom_sun)) + 4 * eccent_earth_orbit * var_y * sin(deg2rad(geom_mean_anom_sun)) * cos(2 * deg2rad(geom_mean_long_sun)) - 0.5 * var_y * var_y * sin(4 * deg2rad(geom_mean_long_sun)) - 1.25 * eccent_earth_orbit * eccent_earth_orbit * sin(2 * deg2rad(geom_mean_anom_sun)))
solar_noon <- (720 - 4 * lon-eq_time_mins + tz * 60)/1440
sunrise <- solar_noon - ha_sunrise * 4 / 1440
sunset <- solar_noon + ha_sunrise * 4 / 1440
if (length(out) == 1 && out %in% c("sunrise", "solar_noon", "sunset")) {
chk2time(get(out), tz)
} else {
list(sunrise = chk2time(sunrise, tz),
solar_noon = chk2time(solar_noon, tz),
sunset = chk2time(sunset, tz))
}
}
---
title: "claut"
output: github_document
bibliography: inst/REFERENCES.bib
---
```{r setup, include=FALSE}
......@@ -20,19 +21,25 @@ This package can be installed via the `install_git()` function in the `devtools`
source("https://gitlab.com/ConorIA/claut/raw/master/install_claut.R")
```
## Functions used in published papers
- [`deltaDTD()`](https://gitlab.com/ConorIA/claut/blob/master/R/deltaDTD.R): Calculate a number of measures of diurnal temperature variability (@anderson_2018_characterization)
## Functions used in papers in review
The following functions were used in studies that are currently under review. If you are a reviewer, this is probably what you are looking for. Note that these functions may undergo some minor optimization or code changes, but the results that they produce will always be the same.
- [`deltaDTD()`](https://gitlab.com/ConorIA/claut/blob/master/R/deltaDTD.R): Calculate a number of measures of diurnal temperature variability.
- [`missing_value_lab()`](https://gitlab.com/ConorIA/claut/blob/master/R/missing_value_lab.R): A function to artificially introduce missing values into monthly climate series, replace those missing values with linear interpolation and cubic splines, and then calculate the error in the calculated mean.
- [`subensembles()`](https://gitlab.com/ConorIA/claut/blob/master/R/missing_value_lab.R): Takes a table of GCM anomalies generated by the [_Conjuntool_](https://gitlab.com/ConorIA/conjuntool) and provides optimal sub-ensembles based on the ability of a sub-ensemble of size $k$ to reproduce an observed baseline.
## Functions implementing other published work
- [`COW_ND()`](https://gitlab.com/ConorIA/claut/blob/master/R/COW_ND.R): Calculates daily maxima and minima after @zaknic-catovic_2018_comparison.
## Misc functions
There are some other helper functions in this package that are here in hopes that they prove useful to someone someday. These are:
- [`describe_snaps()`](https://gitlab.com/ConorIA/claut/blob/master/R/describe_snaps.R): Describes the lengths or other characteristics of run-length-encoded events, such as cold snaps or heatwaves.
- [`suntimes()`](https://gitlab.com/ConorIA/claut/blob/master/R/suntimes.R): Calculates sunrise, solar noon, and sunset times for a given location and date.
- [`trim_data()`](https://gitlab.com/ConorIA/claut/blob/master/R/trimData.R): An easy function to trim a `data.frame` to given start and end years
- functions for working with ASCII gridded data; these were originally written to parse NOAA's [GHCN Merged gridded data set](https://www.ncdc.noaa.gov/temp-and-precip/ghcn-gridded-products/)
- [`parse_ASCII_grid()`](https://gitlab.com/ConorIA/claut/blob/master/R/parse_ASCII_grid.R): Reads an ASCII file of gridded data into a 3D matrix. This is currently quite slow and a little noisy, but it works.
......@@ -46,3 +53,5 @@ For other resources from the climate lab and beyond, please see our [CL@UT Resou
## Contributing to the `claut` package
The members of the Climate Lab are, first and foremost, academics and researchers, not coders. If you would like to contribute code improvements or patches to any of the functions here, please feel free to open a [merge request](https://gitlab.com/ConorIA/claut/merge_requests). Please note that code you contribute will be attributed to you, and will be released under the terms of the [GNU GPLv3](https://gitlab.com/ConorIA/claut/blob/master/LICENSE.md).
#### References
......@@ -23,12 +23,19 @@ without warning.
This package can be installed via the `install_git()` function in the
`devtools` or `remotes` packages, or by running the following
convenience script.
convenience
script.
``` r
source("https://gitlab.com/ConorIA/claut/raw/master/install_claut.R")
```
## Functions used in published papers
- [`deltaDTD()`](https://gitlab.com/ConorIA/claut/blob/master/R/deltaDTD.R):
Calculate a number of measures of diurnal temperature variability
(Anderson, Gough, and Mohsin (2018))
## Functions used in papers in review
The following functions were used in studies that are currently under
......@@ -37,9 +44,6 @@ for. Note that these functions may undergo some minor optimization or
code changes, but the results that they produce will always be the
same.
- [`deltaDTD()`](https://gitlab.com/ConorIA/claut/blob/master/R/deltaDTD.R):
Calculate a number of measures of diurnal temperature
variability.
- [`missing_value_lab()`](https://gitlab.com/ConorIA/claut/blob/master/R/missing_value_lab.R):
A function to artificially introduce missing values into monthly
climate series, replace those missing values with linear
......@@ -50,7 +54,14 @@ code changes, but the results that they produce will always be the
Takes a table of GCM anomalies generated by the
[*Conjuntool*](https://gitlab.com/ConorIA/conjuntool) and provides
optimal sub-ensembles based on the ability of a sub-ensemble of size
\(k\) to reproduce an observed baseline.
\(k\) to reproduce an observed
baseline.
## Functions implementing other published work
- [`COW_ND()`](https://gitlab.com/ConorIA/claut/blob/master/R/COW_ND.R):
Calculates daily maxima and minima after Žaknić-Ćatović and Gough
(2018).
## Misc functions
......@@ -62,6 +73,10 @@ hopes that they prove useful to someone someday. These
Describes the lengths or other characteristics of run-length-encoded
events, such as cold snaps or
heatwaves.
- [`suntimes()`](https://gitlab.com/ConorIA/claut/blob/master/R/suntimes.R):
Calculates sunrise, solar noon, and sunset times for a given
location and
date.
- [`trim_data()`](https://gitlab.com/ConorIA/claut/blob/master/R/trimData.R):
An easy function to trim a `data.frame` to given start and end years
- functions for working with ASCII gridded data; these were originally
......@@ -94,3 +109,28 @@ request](https://gitlab.com/ConorIA/claut/merge_requests). Please note
that code you contribute will be attributed to you, and will be released
under the terms of the [GNU
GPLv3](https://gitlab.com/ConorIA/claut/blob/master/LICENSE.md).
#### References
<div id="refs" class="references">
<div id="ref-anderson_2018_characterization">
Anderson, Conor I., William A. Gough, and Tanzina Mohsin. 2018.
“Characterization of the Urban Heat Island at Toronto: Revisiting the
Choice of Rural Sites Using a Measure of Day-to-Day Variation.” *Urban
Climate* 25 (September):187–95.
<https://doi.org/10.1016/J.UCLIM.2018.07.002>.
</div>
<div id="ref-zaknic-catovic_2018_comparison">
Žaknić-Ćatović, Ana, and William A. Gough. 2018. “A Comparison of
Climatological Observing Windows and Their Impact on Detecting Daily
Temperature Extrema.” *Theoretical and Applied Climatology* 132
(1-2):41–54. <https://doi.org/10.1007/S00704-017-2068-Y>.
</div>
</div>
@article{zaknic-catovic_2018_comparison,
title = {A Comparison of Climatological Observing Windows and Their Impact on Detecting Daily Temperature Extrema},
volume = {132},
issn = {0177-798X, 1434-4483},
doi = {10.1007/S00704-017-2068-Y},
number = {1-2},
journal = {Theoretical and Applied Climatology},
month = apr,
year = {2018},
pages = {41-54},
author = {Žaknić-Ćatović, Ana and Gough, William A.}
}
@misc{noaa_esrl_solar,
title = {{{Solar Calculation Details}}},
url = {https://www.esrl.noaa.gov/gmd/grad/solcalc/calcdetails.html},
author = {{NOAA ESRL Global Monitoring Division, Global Radiation Group}},
month = jul,
year = {2018}
}
@article{anderson_2018_characterization,
title = {Characterization of the Urban Heat Island at {{Toronto}}: {{Revisiting}} the Choice of Rural Sites Using a Measure of Day-to-Day Variation},
volume = {25},
issn = {2212-0955},
doi = {10.1016/J.UCLIM.2018.07.002},
journal = {Urban Climate},
author = {Anderson, Conor I. and Gough, William A. and Mohsin, Tanzina},
month = sep,
year = {2018},
pages = {187-195}
}
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/COW_ND.R
\name{COW_ND}
\alias{COW_ND}
\title{Daily extremes using the Night and Day Climatological Observing Window}
\source{
\insertRef{zaknic-catovic_2018_comparison}{claut}
}
\usage{
COW_ND(lat, lon, tz, datetime, var, ...)
}
\arguments{
\item{lat}{numeric; the latitude of the observer}
\item{lon}{numeric; the longitude of the observer}
\item{tz}{integer; the number of hours shifted from GMT, e.g. for GMT-5, pass \code{-5}}
\item{datetime}{POSIXct; vector of date times that correspond to the vector \code{var}}
\item{var}{numeric; a vector of observations for which maxima and minima should be determined}
\item{...}{additional parameters to pass to \code{\link{registerDoParallel}}}
}
\value{
A table of class \code{\link{tbl_df}}.
}
\description{
Calculates daily maxima and minima after \insertCite{zaknic-catovic_2018_comparison}{claut}
}
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/suntimes.R
\name{suntimes}
\alias{suntimes}
\title{Sunrise, solar noon, and sunset times}
\source{
\insertRef{noaa_esrl_solar}{claut}
}
\usage{
suntimes(lat, lon, tz, date, out = c("sunrise", "solar_noon", "sunset"))
}
\arguments{
\item{lat}{numeric; the latitude of the observer}
\item{lon}{numeric; the longitude of the observer}
\item{tz}{integer; the number of hours shifted from GMT, e.g. for GMT-5, pass \code{-5}}
\item{date}{date; the date to get the sun times for}
\item{out}{character; one of "sunrise", "solar_noon", or "sunset". Leaving this parameter blank will retrun a list of all three.}
}
\value{
POSIXct date time for selected sun time
}
\description{
Calculations are based on NOAA's solar calculator, which is, in turn, based on Astronomical Algorithms, by Jean Meeus.
}
\examples{
## Get today's sunrise time for Toronto Pearson Airport
suntimes(lat = 43.68, lon = -79.63, tz = -5, date = Sys.Date())
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment