Giter Site home page Giter Site logo

predictiveecology / landr Goto Github PK

View Code? Open in Web Editor NEW
17.0 8.0 7.0 7.43 MB

Landscape Ecosystem Modelling in R

Home Page: https://landr.predictiveecology.org/

License: GNU General Public License v3.0

R 100.00%
spades ecological-modelling r-package landscape-ecosystem-modelling

landr's Introduction

LandR

R build status CRAN_Status_Badge CRAN Downloads Codecov test coverage

Landscape Ecosystem Modelling in R

Utilities for 'LandR' suite of landscape simulation models. These models simulate forest vegetation dynamics based on LANDIS-II, and incorporate fire and insect disturbance, as well as other important ecological processes. Models are implemented as SpaDES modules.

Installation

Current release

R build status Codecov test coverage

Install from CRAN:

#install.packages("LandR") ## not yet on CRAN

Install from GitHub:

#install.packages("devtools")
library("devtools")
install_github("PredictiveEcology/LandR", dependencies = TRUE) 

Development version

R build status Codecov test coverage

Install from GitHub:

#install.packages("devtools")
library("devtools")
install_github("PredictiveEcology/LandR", ref = "development", dependencies = TRUE) 

Getting help

landr's People

Contributors

achubaty avatar ceresbarros avatar eliotmcintire avatar ianmseddy avatar tati-micheletti avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

landr's Issues

functions in inputObjects should produce a single object only

From @achubaty on November 29, 2018 20:21

@ianmseddy @CeresBarros @eliotmcintire

loadkNNSpeciesLayers produces a list that contains 2 input objects: speciesLayers and speciesList.

When providing a custom speciesLayers, the speciesList object wasn't being created and/or was being created from the default by running loadkNNSpeciesLayers and overwriting the custom speciesLayers object.

I am splitting the function in twain and reworking .inputObjects of the 3 modules that use loadkNNSpeciesLayers accordingly.

Please ensure to avoid this in the future.

Copied from original issue: PredictiveEcology/Biomass_borealDataPrep#16

rename `BIOMOD_ModelingOptions` to `bm_ModelingOptions` following recent `biomod2` package update

biomod2 v4.2-5 [2024] renamed BIOMOD_ModelingOptions() to bm_ModelingOptions()

https://github.com/biomodhub/biomod2/releases/tag/v4.2-5

I've made the changes in 9d4aeb9 on the biomod2-updates branch, but since we point to @CeresBarros fork of biomod2 in the package Remotes, we should ensure that forked version has these latest changes -- I believe you had made some tweaks to the package that we likely need to keep using from your fork, unless they have been merged into the upstream version.

avoid partial matching of data.table column names

using $ to extract columns is dangerous due to partial matching. the wrong columns may inadvertently be extracted.

> library(data.table)
> DT <- data.table(col1 = letters, col20 = LETTERS)
> DT$col2 
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
[20] "T" "U" "V" "W" "X" "Y" "Z"

Ensure that columns are extracted using data.table syntax ([["colName"]]):

> DT[["col2"]]
NULL
> DT[["col20"]]
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
[20] "T" "U" "V" "W" "X" "Y" "Z"

failures in dispersal tests

══ Failed tests ════════════════════════════════════════════════════════════════
── Error ('test-wardDispersalFunction.R:397:3'): test Ward 4 immediate neighbours ──
Error in `h(simpleError(msg, call))`: error in evaluating the argument 'x' in selecting a method for function 'raster': insufficient number of elements (should be 4)
Backtrace:1. ├─raster::raster(extent(0, 1250, 0, 1750), res = 250, vals = 0) at test-wardDispersalFunction.R:397:2
 2. ├─quickPlot::extent(0, 1250, 0, 1750)
 3. ├─quickPlot::extent(0, 1250, 0, 1750)
 4. │ └─quickPlot:::.ExtentToList(x)
 5. │   ├─raster::extent(x)
 6. │   └─raster::extent(x)
 7. │     └─base::stop("insufficient number of elements (should be 4)")
 8. └─base::.handleSimpleError(...)
 9.   └─base (local) h(simpleError(msg, call))
── Error ('test-wardDispersalFunction.R:466:3'): test Ward random collection of neighbours ──
Error in `h(simpleError(msg, call))`: error in evaluating the argument 'x' in selecting a method for function 'raster': insufficient number of elements (should be 4)
Backtrace:1. ├─raster::raster(extent(0, 1250, 0, 1750), res = 250, vals = 0) at test-wardDispersalFunction.R:466:2
 2. ├─quickPlot::extent(0, 1250, 0, 1750)
 3. ├─quickPlot::extent(0, 1250, 0, 1750)
 4. │ └─quickPlot:::.ExtentToList(x)
 5. │   ├─raster::extent(x)
 6. │   └─raster::extent(x)
 7. │     └─base::stop("insufficient number of elements (should be 4)")
 8. └─base::.handleSimpleError(...)
 9.   └─base (local) h(simpleError(msg, call))

[ FAIL 2 | WARN 0 | SKIP 5 | PASS 31 ]

use lintr to cleanup code

this is already being done on travis (see lint bot comments on recent commits), but to run manually:

devtools::install_github("jimhester/lintr")
library(lintr)
lint_package()

table size is not a good predictor of algo performance in `vegTypeMapGenerator`

I noticed that for a table with 1340184 rows, turning assertions off in vegTypeMapGenerator, makes the function use algo == 2 :

Browse[2]>   nrowCohortData
[1] 1340184

Browse[2]>   ## use new vs old algorithm based on size of x. new one (2) is faster in most cases.
Browse[2]>   ## enable assertions to view timings for each algorithm before deciding which to use.
Browse[2]>   algo <- ifelse(nrowCohortData > 3.5e6, 1, 2)
Browse[2]> algo
[1] 2

However, I ran the function a few times with assertions on to compare timings of the two algos and no. 2 (the 'new algo') was at least 5xs slower than no. 1 (the 'old algo'). So table size doesn't seem to be a good predictor...

LandR::vegTypeMapGenerator: new algo 10.1584620475769
LandR::vegTypeMapGenerator: old algo 2.12155604362488

LandR::vegTypeMapGenerator: new algo 5.77787399291992
LandR::vegTypeMapGenerator: old algo 0.236522197723389

This is a minor issue, but I wanted to raise it here because I feel we're not ready to decide on which algorithm to use and if we keep the mechanism of "let the function decide" we'll need a better predictor.

move LandWeb-specific components to LandWebUtils package

I'm starting a list of functions etc. that don't seem to be used by anything other than LandWeb code.
Can these be moved out of the LandR package and into the LandWebUtils package?
I think all of these can be moved without affecting anyone else's projects.

  • polygonClean() only defines a "LandWeb" type, and calls .cleanLandWebStudyArea().
  • prepSpeciesLayers_CASFRI() may be used by others, but it is LandWeb-specific and will be (soon I hope) superceded by a more general version that can handle the latest CASFRI data (v5+)

Error: Error: z error - expecting three columns;

e.g., GHA logs on Windows show failures:

> firePerimeters <- Cache(prepInputsFireYear,
+                         url = paste0("https://cwfis.cfs.nrcan.gc.ca/downloads",
+                         "/nfdb/fire_poly/current_version/NFDB_poly.zip"),
+                         fun = "sf::st_read",
+                         destinationPath = tempDir,
+                         rasterToMatch = ras2match)

<snip>

Reading layer `NFDB_poly_20210707' from data source 
  `C:\Users\runneradmin\AppData\Local\Temp\Rtmp6hRlg1\working_dir\RtmpoxCNVb\NFDB_poly_20210707.shp' 
  using driver `ESRI Shapefile'
Error: Error: z error - expecting three columns;

@ianmseddy what was the solution for these erros you had fixed previously elsewhere?

sppHarmonize error when sppColorVect passed with 'Mixed' colour

If sppColorVect is NULL, a default is created that includes the Mixed colour, but otherwise the check code won't allow a Mixed colour.

Error in sppHarmonize(sim$sppEquiv, sim$sppNameVector, P(sim)$sppEquivCol,  : 
  Length of 'sppColorVect' differs from number species in final 'sppEquiv'. Check species provided in 'sppColorVect', 'sppNameVector' and/or 'sppEquiv[[sppEquivCol]]'

current workaround is to not pass sppColorVect to the module

rasterRead() no longer returns a function

rasterRead() used to return the function corresponding to the string set in reproducible.rasterRead.

this was used in e.g., overlayLCCs():

https://github.com/PredictiveEcology/LandR/blob/development/R/overlayLCCs.R#L70-L71

but this now fails because rasterRead() was modified to evaluate the function, and it now accepts and passes ... to the function, returning a SpatRaster or Raster object.

this change broke overlayLCCs() but at this point, reverting the change will likely break something else.

I will use the original version internally within this function, and note that if similar problems arise elsewhere in the package, that we may need the original version restored for general use in the package.

.createCohortData not doing what it says it does?

.createCohortData is supposed to (among other things) message(blue("Set B to 0 where cover > 0 and age = 0, because B is least quality dataset")). However this doesn't seem to be enforced in the code. Both B (biomass) and age are indeed being corrected (to 0) when cover == 0. However, having cover > 0 and age == 0 doesn't seem to be assessed, nor to influence/correct B to 0.

bug in dropTerm

reprex

repos <- c("predictiveecology.r-universe.dev", getOption("repos"))
install.packages(c("LandR"), repos = repos)
library(LandR)

dropTerm("B ~ logAge * speciesCode + cover * speciesCode + (logAge + cover + speciesCode | ecoregionGroup)", c("speciesCode"))
# Error in str2lang(x) : <text>:2:0: unexpected end of input
# 1: . ~ . -
#   ^
dropTerm("B ~ logAge * speciesCode + cover * speciesCode + (logAge + cover + speciesCode | ecoregionGroup)", c("cover"))
# Error in str2lang(x) : <text>:2:0: unexpected end of input
# 1: . ~ . -
#   ^

make a "createRTM" funciton

so that we can stop copy-pasting the steps the RTM across modules.
fucntion needs to get rawBiomassMap if need be

Improve `makePixelTable` documentation

It needs to be clear that rawBiomassMap values are multiplied by 100 in this function (makePixelTable ) to convert biomass units from t/ha (the units in Beaudoin et al. 2014 Knn dataset) to g/m^2

new LandR assertion failing

on l. 467 of prepSpeciesLayers.Rthis:
assertthat::assert_that(identical(raster::maxValue(CCstack), rep(10L, nlayers(CCstack))))
is failing because

raster::maxValue(CCstack)
[1] 10  7 10 10 10

Are the max values supposed to be 10, or anything up to 10? (also is 10, 10% cover?)

assertPostFireDist() undefined

FireDisturbancePM: no visible global function definition forassertPostFireDistUndefined global functions or variables:
     assertPostFireDist

partial argument matching

settig the following options:

options(
    warnPartialMatchArgs = TRUE,
    warnPartialMatchAttr = TRUE,
    warnPartialMatchDollar = TRUE
)

installing LandR shows the following warnings:

Warning in match.call(definition, call, expand.dots, envir) :
  partial argument match of 'cohortData' to 'cohortDataOrig'
Warning in match.call(definition, call, expand.dots, envir) :
  partial argument match of 'pixelGroupMap' to 'pixelGroupMapOrig'

switch from gdalUtils to gdalUtilities

.overlay currently uses gdalUtils::gdalwarp. Can we switch over to gdalUtilities for this, like was done recently in reproducible?

Also, this should be put in Suggests and used conditionally since it's only used for .overlay.

use correct data types when creating/updating species trait tables

Biomass_core asserts that species trait table columns are specific types, yet LandR::getSpeciesTable and LandR::updateSpeciesTable don't check/enforce using the same rules as the assertions in LandR::assertColumns.

In particular, getSpeciesTable simply reads in a csv file using stringsAsFactors = FALSE, with no followup to convert character columns (e.g., postfireregen) to factor.

Cache warnings in prepRawBiomassMap tests

══ Warnings ════════════════════════════════════════════════════════════════════
── Warning ('test-prepRawBiomassMap.R:57:3'): test prepRawBiomassMap ───────────
In do.call(what = prepInputs, args = Args): The Cache file exists, but there is no database entry for it; removing the file and rerunning the call
Backtrace:1. ├─LandR::prepRawBiomassMap(...) at test-prepRawBiomassMap.R:57:2
  2. │ └─reproducible::Cache(do.call, what = prepInputs, args = Args)
  3. │   └─reproducible:::evalTheFun(...)
  4. │     ├─base::withCallingHandlers(...)
  5. │     ├─base (local) out(...)
  6. │     └─reproducible (local) `<fn>`(...)
  7. │       └─reproducible:::process(...)
  8. │         ├─base::withCallingHandlers(...)
  9. │         └─reproducible::Cache(...)
 10. │           └─reproducible:::searchInRepos(...)
 11. │             └─base::warning(...)
 12. ├─base::.signalSimpleWarning(...)
 13. │ └─base::withRestarts(...)
 14. │   └─base (local) withOneRestart(expr, restarts[[1L]])
 15. │     └─base (local) doWithOneRestart(return(expr), restart)
 16. └─reproducible (local) `<fn>`(`<smplWrnn>`)
── Warning ('test-prepRawBiomassMap.R:88:3'): test prepRawBiomassMap ───────────
In do.call(what = prepInputs, args = Args): The Cache file exists, but there is no database entry for it; removing the file and rerunning the call
Backtrace:1. ├─LandR::prepRawBiomassMap(...) at test-prepRawBiomassMap.R:88:2
  2. │ └─reproducible::Cache(do.call, what = prepInputs, args = Args)
  3. │   └─reproducible:::evalTheFun(...)
  4. │     ├─base::withCallingHandlers(...)
  5. │     ├─base (local) out(...)
  6. │     └─reproducible (local) `<fn>`(...)
  7. │       └─reproducible:::process(...)
  8. │         ├─base::withCallingHandlers(...)
  9. │         └─reproducible::Cache(...)
 10. │           └─reproducible:::searchInRepos(...)
 11. │             └─base::warning(...)
 12. ├─base::.signalSimpleWarning(...)
 13. │ └─base::withRestarts(...)
 14. │   └─base (local) withOneRestart(expr, restarts[[1L]])
 15. │     └─base (local) doWithOneRestart(return(expr), restart)
 16. └─reproducible (local) `<fn>`(`<smplWrnn>`)
── Warning ('test-prepRawBiomassMap.R:101:3'): test prepRawBiomassMap ──────────
In do.call(what = prepInputs, args = Args): The Cache file exists, but there is no database entry for it; removing the file and rerunning the call
Backtrace:1. ├─LandR::prepRawBiomassMap(...) at test-prepRawBiomassMap.R:101:2
  2. │ └─reproducible::Cache(do.call, what = prepInputs, args = Args)
  3. │   └─reproducible:::evalTheFun(...)
  4. │     ├─base::withCallingHandlers(...)
  5. │     ├─base (local) out(...)
  6. │     └─reproducible (local) `<fn>`(...)
  7. │       └─reproducible:::process(...)
  8. │         ├─base::withCallingHandlers(...)
  9. │         └─reproducible::Cache(...)
 10. │           └─reproducible:::searchInRepos(...)
 11. │             └─base::warning(...)
 12. ├─base::.signalSimpleWarning(...)
 13. │ └─base::withRestarts(...)
 14. │   └─base (local) withOneRestart(expr, restarts[[1L]])
 15. │     └─base (local) doWithOneRestart(return(expr), restart)
 16. └─reproducible (local) `<fn>`(`<smplWrnn>`)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.