library(bomrang)get_historical(stationid ="023000", type ="max")Error infile(con, "r") : cannot open the connection to 'http://www.bom.gov.au/climate/data/lists_by_element/alphaAUS_136.txt'In addition: Warning message:In file(con, "r") : cannot open URL 'http://www.bom.gov.au/climate/data/lists_by_element/alphaAUS_136.txt': HTTP status was '403 Forbidden'
# provide some standard names between DPIRD and SILO for easy merging where# data values are shared# not all columns are renamed, but all are listed for clarity data.table::setnames( response_data,old =c("station_code","station_name","longitude","latitude","elev_m","date","year","month","day","extracted","daily_rain","daily_rain_source","et_morton_actual","et_morton_actual_source","et_morton_potential","et_morton_potential_source","et_morton_wet","et_morton_wet_source","et_short_crop","et_short_crop_source","et_tall_crop","et_tall_crop_source","evap_comb","evap_comb_source","evap_morton_lake","evap_morton_lake_source","evap_pan","evap_pan_source","evap_syn","evap_syn_source","max_temp","max_temp_source","min_temp","min_temp_source","mslp","mslp_source","radiation","radiation_source","rh_tmax","rh_tmax_source","rh_tmin","rh_tmin_source","vp","vp_deficit","vp_deficit_source","vp_source" ),new =c("station_code","station_name","longitude","latitude","elev_m","date","year","month","day","extracted","rainfall","rainfall_source","et_morton_actual","et_morton_actual_source","et_morton_potential","et_morton_potential_source","et_morton_wet","et_morton_wet_source","et_short_crop","et_short_crop_source","et_tall_crop","et_tall_crop_source","evap_comb","evap_comb_source","evap_morton_lake","evap_morton_lake_source","evap_pan","evap_pan_source","evap_syn","evap_syn_source","air_tmax","air_tmax_source","air_tmin","air_tmin_source","mslp","mslp_source","radiation","radiation_source","rh_tmax","rh_tmax_source","rh_tmin","rh_tmin_source","vp","vp_deficit","vp_deficit_source","vp_source" ),skip_absent =TRUE )
DPIRD
# provide some standard names between DPIRD and SILO for easy merging where# data values are shared# not all columns are renamed, but almost all are listed for clarity data.table::setnames( out,old =c("station_code","station_name","year","month","day","date","air_temperature_avg","air_temperature_max","air_temperature_max_time","air_temperature_min","air_temperature_min_time","apparent_air_temperature_avg","apparent_air_temperature_max","apparent_air_temperature_max_time","apparent_air_temperature_min","apparent_air_temperature_min_time","barometric_pressure","battery_min_voltage","battery_min_voltage_date_time","chill_hours","delta_t_avg","delta_t_max","delta_t_max_time","delta_t_min","delta_t_min_time","dew_point_avg","dew_point_max","dew_point_max_time","dew_point_min","dew_point_min_time","erosion_condition_minutes","erosion_condition_start_time","errors","evapotranspiration","evapotranspiration_short_crop","evapotranspiration_tall_crop","frost_condition_minutes","frost_condition_start_time","heat_condition_minutes","heat_condition_start_time","observations_count","observations_percentage","pan_evaporation","pan_evaporation_12am","rainfall","relative_humidity_avg","relative_humidity_max","relative_humidity_max_time","relative_humidity_min","relative_humidity_min_time","richardson_units","soil_temperature","solar_exposure","wet_bulb_avg","wet_bulb_max","wet_bulb_max_time","wet_bulb_min","wet_bulb_min_time","wind_avg_speed","wind_height","wind_max_direction_compass_point","wind_max_direction_degrees","wind_max_speed","wind_max_time" ),new =c("station_code","station_name","year","month","day","date","air_tavg","air_tmax","air_tmax_time","air_tmin","air_tmin_time","apparent_air_tavg","apparent_air_tmax","apparent_air_tmax_time","apparent_air_tmin","apparent_air_tmin_time","barometric_pressure","battery_min_voltage","battery_min_voltage_date_time","chill_hours","delta_tavg","delta_tmax","delta_tmax_time","delta_tmin","delta_tmin_time","dew_point_avg","dew_point_max","dew_point_max_time","dew_point_min","dew_point_min_time","erosion_condition_minutes","erosion_condition_start_time","errors","et","et_short_crop","et_tall_crop","frost_condition_minutes","frost_condition_start_time","heat_condition_minutes","heat_condition_start_time","observations_count","observations_percentage","pan_evaporation","pan_evaporation_12am","rainfall","rh_avg","rh_tmax","rh_tmax_time","rh_tmin","rh_tmin_time","richardson_units","soil_temperature","radiation","wet_bulb_avg","wet_bulb_tmax","wet_bulb_tmax_time","wet_bulb_tmin","wet_bulb_tmin_time","wind_avg_speed","wind_height","wind_max_direction_compass_point","wind_max_direction_degrees","wind_max_speed","wind_max_time" ),skip_absent =TRUE )
Provide Metadata
Include latitude and longitude in data for DPIRD
An excerpt from weatherOz::get_dpird_summaries()lines
.set_dpird_key <-function() {if (interactive()) { utils::browseURL("https://www.agric.wa.gov.au/form/dpird-api-registration") }stop("You need to set your DPIRD API key.\n","After getting your key set it as 'DPIRD_API_KEY' in .Renviron.\n","DPIRD_API_KEY='youractualkeynotthisstring'\n","For that, use `usethis::edit_r_environ()`" )invisible("https://www.agric.wa.gov.au/form/dpird-api-registration") }
Automate API Keys (SILO)
.set_silo_key <-function() {stop("Set your SILO API key (email address) as 'SILO_API_KEY' in .Renviron.\n","SILO_API_KEY='youractualemailnotthisstring'\n","For that, use `usethis::edit_r_environ()`" )invisible(NULL) }
Make Sure It’s the Right Key
SILO (E-mail Address)
.is_valid_email_silo_api_key <-function(.api_key) { pattern <-"\\<[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\>"if (grepl(pattern, as.character(.api_key), ignore.case =TRUE)) {return(invisible(NULL)) } else {stop("For SILO requests you must use your e-mail address as an API key. You have not provided a valid email address.",call. =FALSE) }}
DPIRD (Random String)
.is_valid_dpird_api_key <-function(.api_key) { pattern <-"\\<[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\>"if (grepl(pattern, as.character(.api_key), ignore.case =TRUE)) {stop("For DPIRD requests you must use your DPIRD provided API key. You (may) have provided your e-mail address, which is used for the SILO API instead.",call. =FALSE) } else {return(invisible(NULL)) }}
Use a Standard Example API Key
Check for Example Key Use
.check_not_example_api_key <-function(.api_key) {if (!is.null(.api_key) && .api_key =="your_api_key") {stop("You have copied the example code and not provided a proper API key. An API key may be requested from DPIRD or for SILO you must use your e-mail address as an API key. See the help for the respective functions for more.",call. =FALSE) }return(invisible(NULL))}
# check responses for errors# check to see if request failed or succeeded# - a custom approach this time combining status code,# explanation of the code, and message from the serverif (response$status_code >201) { mssg <- response$parse("UTF-8") x <- response$status_http()stop("HTTP (", x$status_code, ") - ", x$explanation, "\n", mssg,call. =FALSE) } response$raise_for_status()# the API won't return proper responses for malformed requests, so, we check# for the word "Sorry" and parse the response to the user if something slips# through our user checks.if (grepl("Sorry", response$parse("UTF8")) ||grepl("Request Rejected", response$parse("UTF8"))) {stop(call. =FALSE,gettext(response$parse("UTF8")),domain =NA) }
You Don’t Need to Offer Every Option
...#' @param api_group A `string` used to filter the stations to a predefined#' group. These need to be supported on the back end. 'all' returns all#' stations, 'api' returns the default stations in use with the API, 'web'#' returns the list in use by the weather.agric.wa.gov.au and 'rtd' returns#' stations with scientifically complete datasets. Available values: 'api',#' 'all', 'web' and 'rtd'.....build_query <-function(station_code, start_date_time, end_date_time, interval, values,api_group ="all", include_closed, limit, api_key)
If the Data Isn’t Available…
Make it!
#' Get DPIRD Summary Weather Data in the APSIM Format From the Weather 2.0 API#'#' Automates the retrieval and conversion of summary data from the#' \acronym{DPIRD} Weather 2.0 \acronym{API} to an \acronym{APSIM} .met file#' formatted weather data object.#'#' @param station_code A `character` string or `factor` from#' [get_stations_metadata()] of the \acronym{BOM} station code for the station#' of interest.#' @param start_date A `character` string or `Date` object representing the#' beginning of the range to query in the format \dQuote{yyyy-mm-dd}#' (ISO8601). Data returned is inclusive of this date.#' @param end_date A `character` string or `Date` object representing the end of#' the range query in the format \dQuote{yyyy-mm-dd} (ISO8601). Data#' returned is inclusive of this date. Defaults to the current system date.#' @param api_key A `character` string containing your \acronym{API} key from#' \acronym{DPIRD}, <https://www.agric.wa.gov.au/web-apis>, for the#' \acronym{DPIRD} Weather 2.0 \acronym{API}. Defaults to automatically#' detecting your key from your local .Renviron, .Rprofile or similar.#' Alternatively, you may directly provide your key as a string here. If#' nothing is provided, you will be prompted on how to set up your \R session#' so that it is auto-detected.#'#' @section Saving objects:#' To save \dQuote{met} objects the [apsimx::write_apsim_met()] is reexported.#' Note that when saving, comments from SILO will be included, but these will#' not be printed as a part of the resulting `met` object in your \R session.#'#' @examples#' \dontrun{#' # Get an APSIM format object for Binnu#' # Note that you need to supply your own API key#'#' wd <- get_dpird_apsim(#' station_code = "BI",#' start_date = "20220101",#' end_date = "20221231",#' api_key = "your_api_key"#' )#' }#'#'#' @author Adam H. Sparks, \email{adamhsparks@@gmail.com}#'#' @return An \CRANpkg{apsimx} object of class \sQuote{met} with attributes.#'#' @family DPIRD#' @family data fetching#' @family APSIM#' @encoding UTF-8#' @autoglobal#' @exportget_dpird_apsim <-function(station_code, start_date,end_date =Sys.Date(),api_key =get_key(service ="DPIRD")) { apsim <-get_dpird_summaries(station_code = station_code,start_date = start_date,end_date = end_date,interval ="daily",values =c("airTemperatureMax","airTemperatureMin","panEvaporation","rainfall","relativeHumidityAvg","solarExposure","windAvgSpeed" ),api_key = api_key ) site <- apsim$station_name[1] latitude <- apsim$latitude[1] longitude <- apsim$longitude[1] apsim[, day :=NULL] apsim[, day := lubridate::yday(apsim$date)] apsim <- apsim[, c("year","day","radiation","air_tmax","air_tmin","pan_evaporation","rainfall","rh_avg","wind_avg" )] data.table::setnames( apsim,old =c("radiation","air_tmax","air_tmin","pan_evaporation","rainfall","rh_avg","wind_avg" ),new =c("radn", "maxt", "mint", "rain", "evap", "rh", "windspeed") ) apsim <- apsimx::as_apsim_met(filename ="weather.met.met",x = apsim,site = site,latitude = latitude,longitude = longitude,colnames =names(apsim),units =c("()","()","(MJ/m2/day)","(oC)","(oC)","(mm)","(mm)","(%)","(m/s)"),comments =sprintf("!data from DPIRD Weather 2.0 API. retrieved: %s",Sys.time()) )return(apsim)}
Examples
PSHB
Model output of the posibility of Polyphagous Shothole Borer (PSHB) becoming established. The white areas of Australia indicate that the model suggests that this insect cannot become established. Courtesy Prof. Ben Phillips, Curtin University (unpublished).
Sparks, A., G. A. Forbes, R. J. Hijmans, and K. A. Garrett. 2011. “A Metamodeling Framework for Extending the Application Domain of Process-Based Ecological Models.”Ecosphere 2 (8): art90. https://doi.org/10.1890/es11-00128.1.