-
Notifications
You must be signed in to change notification settings - Fork 311
Rothc: Soil file support + read options from settings file #3788
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+610
−72
Merged
Changes from 16 commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
8a0f49b
read soil water options from settings, increment model version
infotroph fd8a5b5
changelog
infotroph 10b724d
formatting
infotroph 9f65c88
read soil water options from settings, soil params from soil_physics …
infotroph 3f9c570
typos + move input params to own map
infotroph 11f64f9
add soil_physics input to rothc demo
infotroph d04530b
move furrr opts
infotroph 35784ef
round soil params, align with headers, fix hulk density typo g_m3->g_cm3
infotroph f76e8f7
typo in soil depth param
infotroph acf88ed
notes for later
infotroph d05b247
move soil file reading to own function
infotroph bd37829
add netcdf2df
infotroph 065643a
use netcdf2df instead of import from data.land
infotroph b12c763
Merge branch 'develop' into rothc-opts
infotroph feca7c0
Merge branch 'develop' into rothc-opts
infotroph 8c1ce9b
Update models/rothc/R/read_soil_physics.R
infotroph d7c1038
error on empty result
infotroph 3f2ea5d
Merge branch 'develop' into rothc-opts
infotroph ee2503c
define %||%
infotroph f0b34e6
Merge branch 'develop' into rothc-opts
infotroph 5b6910b
fix test wording
infotroph 4cf8328
ignore docs folder
infotroph be7026b
Merge branch 'develop' into rothc-opts
infotroph 14b45c2
Merge branch 'develop' into rothc-opts
infotroph 3f12f45
gitignore
infotroph 2b56bf6
Merge branch 'develop' into rothc-opts
infotroph File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| #' Read all variables from a netCDF into a single data frame | ||
| #' | ||
| #' Reads all dimensions and variables from a netCDF and returns them as | ||
| #' a single data frame with one row per cell of the source file's | ||
| #' dimension array. | ||
| #' Units are also read and are attached to the result as attribute "units" | ||
| #' | ||
| #' Written mostly for files where all dimensions are 1d vectors, | ||
| #' e.g. single-site soil or met files. | ||
| #' Many files with more complex dimensions should work | ||
| #' (at least for cases where it's clear how to rectangle them), | ||
| #' but they are not yet well tested. | ||
| #' | ||
| #' @param path path to a netcdf file | ||
| #' | ||
| #' @return data frame with columns for each dim and var of the input file. | ||
| #' Units for all of these are attached as an attribute. | ||
| #' | ||
| #' @author Chris Black | ||
| #' @export | ||
| #' | ||
| netcdf2df <- function(path) { | ||
| nc <- ncdf4::nc_open(path) | ||
| on.exit(ncdf4::nc_close(nc), add = TRUE) | ||
|
|
||
| dim_vals <- nc$dim |> | ||
| sapply(\(x) c(x[["vals"]]), simplify = FALSE) |> | ||
| # Load-bearing assumption: | ||
| # Dimension listed first in nc$dim is fastest-varying (as for expand.grid) | ||
| # TODO verify whether this is reliably true. | ||
| expand.grid() | ||
|
|
||
| var_vals <- nc$var |> | ||
| names() |> | ||
| sapply(\(v) c(ncdf4::ncvar_get(nc, v)), simplify = FALSE) | ||
|
|
||
| if (any(lengths(var_vals) != nrow(dim_vals))) { | ||
| PEcAn.logger::logger.error("Not all variables have same length") | ||
| } | ||
|
|
||
| res <- cbind(dim_vals, as.data.frame(var_vals)) | ||
| attr(res, "units") <- c( | ||
| sapply(nc$dim, `[[`, "units"), | ||
| sapply(nc$var, `[[`, "units") | ||
| ) | ||
|
|
||
| res | ||
| } |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| test_that("one dim", { | ||
| local_edition(3) | ||
|
|
||
| res <- c("a", "b") |> | ||
| example_netcdf(file_path = withr::local_tempfile()) |> | ||
| netcdf2df() | ||
|
|
||
| expect_equal(dim(res), c(365, 3)) | ||
| expect_equal(colnames(res), c("time", "a", "b")) | ||
| expect_equal( | ||
| attr(res, "units"), | ||
| c(time = "days since 2001-01-01", a = "kg", b = "kg") | ||
| ) | ||
| expect_equal(res$time, (0L:364L)) | ||
| }) | ||
|
|
||
|
|
||
|
|
||
| test_that("multiple dims, all but one scalar", { | ||
| local_edition(3) | ||
|
|
||
| # TODO does this work if pkg not installed (eg check time)? | ||
| # I think testthat may shim system.file | ||
| res <- netcdf2df( | ||
| system.file("test-data/CRUNCEP.2000.nc", package = "PEcAn.utils") | ||
| ) | ||
|
|
||
| expect_equal(dim(res), c(366 * 4, 11)) | ||
| expect_equal( | ||
| colnames(res), | ||
| c( | ||
| "latitude", "longitude", "time", | ||
| "air_temperature", "surface_downwelling_longwave_flux_in_air", | ||
| "air_pressure", "surface_downwelling_shortwave_flux_in_air", | ||
| "eastward_wind", "northward_wind", | ||
| "specific_humidity", "precipitation_flux" | ||
| ) | ||
| ) | ||
|
|
||
| # Check units. NB some of these are nonstandard; | ||
| # Key point is they should match what the file reports | ||
| expect_equal( | ||
| attr(res, "units"), | ||
| c( | ||
| latitude = "degree_north", | ||
| longitude = "degree_east", | ||
| time = "days since 2000-01-01T00:00:00Z", | ||
| air_temperature = "Kelvin", | ||
| surface_downwelling_longwave_flux_in_air = "W/m2", | ||
| air_pressure = "Pascal", | ||
| surface_downwelling_shortwave_flux_in_air = "W/m2", | ||
| eastward_wind = "m/s", | ||
| northward_wind = "m/s", | ||
| specific_humidity = "g/g", | ||
| precipitation_flux = "kg/m2/s" | ||
| ) | ||
| ) | ||
| # dims | ||
| expect_equal(res$time, seq(0, 365 + 3 / 4, 1 / 4) + 1 / 8, tolerance = 1e-12) | ||
| expect_equal(unique(res$latitude), 45.25, tolerance = 1e-6) | ||
| expect_equal(unique(res$longitude), -84.75, tolerance = 1e-6) | ||
| expect_equal(mean(res$air_temperature), 278.798636, tolerance = 1e-6) | ||
| }) | ||
|
|
||
| # TODO test with more than one non-degenerate dimension |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| #' Read soil parameters from a PEcAn soil physics file | ||
| #' | ||
| #' Reads values from a netCDF that follows the PEcAn soil standard, | ||
| #' aggregates layers across the depth to be simulated, | ||
| #' and converts to names and units expected by RothC. | ||
| #' | ||
| #' TODO: Currently drops all of any layer that extends below `model_depth`. | ||
| #' It would be better instead to weight all layers by their contribution | ||
| #' to the requested depth. | ||
| #' | ||
| #' @param path filepath to a netcdf, | ||
| #' probably read from `settings$run$inputs$soil_physics$path` | ||
| #' @param model_depth Soil depth to be simulated, in cm | ||
| #' | ||
| #' @return one-row dataframe with columns | ||
| #' `depth_cm`, `clay_pct`, `silt_pct`, | ||
| #' `bulkdens_g_cm3`, `org_C_pct`, `iom_tC_ha` | ||
| #' | ||
| #' @importFrom rlang .data .env | ||
| #' | ||
| read_soil_physics <- function(path, model_depth = 23) { | ||
| soil_vals <- netcdf2df(path) | ||
| soil_units <- as.list(attr(soil_vals, "units")) | ||
|
|
||
| # Input is documented to be in meters, | ||
| # but providing cm instead seems to be a _very_ common error; | ||
| # might as well try to handle it here | ||
| if (tolower(soil_units$depth) %in% c("m", "meters") | ||
| && any(soil_vals$depth >= 10)) { | ||
| PEcAn.logger::logger.warn( | ||
| "Soil depths reported to be in meters, but found values >= 10", | ||
| "in file", path, | ||
| "Assuming the units have been mislabeled and treating all depths as cm." | ||
| ) | ||
| soil_units$depth <- "cm" | ||
| } | ||
|
|
||
| soil_vals |> | ||
| dplyr::mutate( | ||
| depth_cm = .data$depth |> | ||
| PEcAn.utils::ud_convert(soil_units$depth, "cm") | ||
| ) |> | ||
| # TODO 1: Assumes depth is given to bottom of layer -- is that correct? | ||
| # TODO 2: this drops layers that extend past bottom | ||
| # (eg with depth=23 and 0-10/10-30 layering, would use only 0-10) | ||
| # Consider rescaling partial layers | ||
| # (Or throwing an error on mismatch and making everyone generate their soil | ||
| # files with layers that match model depth?) | ||
| dplyr::filter(.data$depth_cm <= model_depth) |> | ||
|
infotroph marked this conversation as resolved.
Outdated
|
||
| dplyr::summarize( | ||
| # TODO consider weighting by layer thickness? | ||
| depth_cm = max(.data$depth_cm), | ||
| clay_pct = .data$fraction_of_clay_in_soil |> | ||
| mean() |> | ||
| PEcAn.utils::ud_convert(soil_units$fraction_of_clay_in_soil, "%"), | ||
| silt_pct = .data$fraction_of_silt_in_soil |> | ||
| mean() |> | ||
| PEcAn.utils::ud_convert(soil_units$fraction_of_silt_in_soil, "%"), | ||
| bulkdens_g_cm3 = .data$soil_bulk_density |> | ||
| mean() |> | ||
| PEcAn.utils::ud_convert(soil_units$soil_bulk_density, "g cm-3"), | ||
| org_C_pct = .data$soil_organic_carbon_stock |> | ||
| sum() |> | ||
| PEcAn.utils::ud_convert( | ||
| soil_units$soil_organic_carbon_stock, | ||
| "g cm-2" | ||
| ) |> | ||
| (\(x) x / (.data$depth_cm * .data$bulkdens_g_cm3))() |> | ||
| PEcAn.utils::ud_convert("1", "%"), | ||
| iom_tC_ha = .data$soil_organic_carbon_stock |> | ||
| sum() |> | ||
| PEcAn.utils::ud_convert( | ||
| soil_units$soil_organic_carbon_stock, | ||
| "t ha-1" | ||
| ) |> | ||
| # Approximation from Falloon et al. 1998, 10.1016/S0038-0717(97)00256-3 | ||
| (\(x) 0.049 * x^1.139)() | ||
| ) | ||
| } | ||
|
|
||
| # an internal wrapper to allow stubbing the function out under test | ||
| # without affecting code outside the package. | ||
| netcdf2df <- PEcAn.utils::netcdf2df | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.