Skip to content

Commit

Permalink
honor axis attribute if different from native order -- fixes r-spatia…
Browse files Browse the repository at this point in the history
  • Loading branch information
dblodgett-usgs committed Apr 20, 2024
1 parent f0156c9 commit 5946280
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
2 changes: 1 addition & 1 deletion R/ncdf.R
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,7 @@ read_ncdf = function(.x, ..., var = NULL, ncsub = NULL, curvilinear = character(
dims$id[!dims$id %in% dim_matcher])
dim_matcher <- unique(dim_matcher)
}
dims <- dims[match(dims$id, dim_matcher), ]
dims <- dims[match(dim_matcher, dims$id, nomatch = 0L), ]
}
return(dims)
}
Expand Down
49 changes: 48 additions & 1 deletion tests/testthat/test-ncdf.R
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,54 @@ test_that("units are right with lcc km", {
skip_if_not_installed("ncmeta")
f <- system.file("nc/lcc_km.nc", package = "stars")

nc <- read_ncdf(f)
nc <- expect_warning(read_ncdf(f), "prime meridian")

expect_equal(units(sf::st_crs(nc)$ud_unit)$numerator, "km")
})

test_that("axis attribute order -- see #680", {

# File1 has no "axis" attributes
file1 <- tempfile("tas_example_", fileext = ".nc")
nc <- RNetCDF::create.nc(file1)

id_lat <- RNetCDF::dim.def.nc(nc, "lat", 3)
iv_lat <- RNetCDF::var.def.nc(nc, "lat", "NC_FLOAT", id_lat)
RNetCDF::var.put.nc(nc, "lat", c(40, 45, 50))

id_lon <- RNetCDF::dim.def.nc(nc, "lon", 2)
iv_lon <- RNetCDF::var.def.nc(nc, "lon", "NC_FLOAT", id_lon)
RNetCDF::var.put.nc(nc, "lon", c(-100, -95))

id_bnds <- RNetCDF::dim.def.nc(nc, "bnds", 2)

id_time <- RNetCDF::dim.def.nc(nc, "time", 9)
iv_time <- RNetCDF::var.def.nc(nc, "time", "NC_INT", id_time)
RNetCDF::var.put.nc(nc, "time", 1:9)

iv_tas <- RNetCDF::var.def.nc(nc, "temperature", "NC_FLOAT", c(id_time, id_lon, id_lat))
RNetCDF::var.put.nc(nc, "temperature", tas)

RNetCDF::close.nc(nc)

# File2 has X, Y, T axis attributes
file2 <- tempfile("tas_example_", fileext = ".nc")
file.copy(from = file1, to = file2)
#> [1] TRUE
nc <- RNetCDF::open.nc(file2, write = TRUE)

RNetCDF::att.put.nc(nc, "lon", "axis", "NC_CHAR", "X")
RNetCDF::att.put.nc(nc, "lat", "axis", "NC_CHAR", "Y")
RNetCDF::att.put.nc(nc, "time", "axis", "NC_CHAR", "T")

RNetCDF::close.nc(nc)

s1 <- suppressWarnings(stars::read_ncdf(file1))

expect_equal(names(stars::st_dimensions(s1)), c("time", "lon", "lat"))

s2 <- suppressWarnings(stars::read_ncdf(file2))

expect_equal(names(stars::st_dimensions(s2)), c("lon", "lat", "time"))

})

0 comments on commit 5946280

Please sign in to comment.