From dc62d867953ef71587d8660d9fa17c9856a8199a Mon Sep 17 00:00:00 2001 From: HHildenbrandt <38455490+HHildenbrandt@users.noreply.github.com> Date: Tue, 23 Mar 2021 15:45:47 +0100 Subject: [PATCH] v3.2.0 release (#124) * Add zenodo badge [skip ci] * Test cond on constant rate * test constant_rate_shift with cond * Add test sim_time_dependent * Add sim_trait_dependent cond test * Fix sim_constant_rate_shift cond test * Lint * More stringent constant_rate test * Better test title * fix constant_rate_shift test * Typo * More sim_time_dep cond test * More trait_dependent sim cond tests * test conditioning in relaxed rate * Remove duplicated tests * Add 2 type cond warning. Closes #123 * Fix cond relaxed rate gam test * Better warning text. Closes #123 * Lint * Move over tests from DAISIEtesting * No lintrbot * Increase travis wait time * Test warning of cond with 2 types * Split format_CS_sampled_stt and format_CS_trait files * abuse split-rate model with gamma = 0 * abuse time dependent model with gamma = 0 * Remove some input checks * Better tests sim_core_1_4a * test abuse and verbose DAISIE sim time dep * test abuse sim_core_trait_dependent * test no colonization happening returining 0 on stt * trait sims don't take nonoceanic pars * Delete DAISIE_single_branch * Add are_rates test * Better check format tests * Fix typo * Remove lingering nonoceanic pars in traits tests * Better is_simulation_outputs name checking * added higher subdivisions limit to integral_peak * added rel.tol to integral_peak * changed abs.tol to 1e-10 * changed integration to catch errors and return -Inf * changed rho to log gamma distribution and integrand to sum * removed if statement to catch integration errors * removed stop.on.error in integration * manual merge with 'hanno' Signed-off-by: Hanno * builds,install & runs on Linux source package added Signed-off-by: Hanno * Updated version and documentation * useDynLib in DAISIE-package.R, renewed documentation * useDynLib in DAISIE-package.R, renewed documentation * useDynLib in DAISIE-package.R, renewed documentation * No export pipe just import from magrittr * Correct appveyor.yml * logos and AppVeyor status in README * indent * lint * Progress correct brts ONEcolonist #125 * Only remove youngest_col if in vector. Progress #125 * Assert that youngest_col_time must be in btimes_all_clado_desc. Progress #125 * Format * Add comments and asserts. Remove else * Adjust refernce progress #125 * Add /pics to .Rbuildignore * Try adding col times, removing youngest. Progress #125 * Remove appveyor setup * Go GHA * GHA on onecolonist_fix * Switch to else if. Progress #125 * Fix references after testing. Progress #125 * Rename other_clades_same_ancestor to all_colonisations. Lint. Progress #125 * Better CI checks for testing * seq_along() not seq_len(). Progress #125 * Better doc. Progress #125 * Fix reference test CS_full_stt. Progress #125 * other_clades_same_ancestor -> all_colonisations. Progress #125 * other_clades_same_ancestor -> all_colonisations in core_1_4. Consider removing, changed to pass tests. Progress #125 * Better skips * Expand ONEcolonist hedge case coverage. Progress #125 * Comment temp code * Fix reference. Progress #125 * use NULL stt_table for testing. Progress #125 * Remove 1_4 and 1_5 functions and tests * Legacy functions removed from tests. Progress #126 * Remove more legacy code and tests. Progress #126 * V with single string w/ all times. Progress #125 * DAISIE_ONEcolonist returns all_event_times. Closes #125 * Update test-format_CS references. Progress #125 * Add $all_colonisations reference tests. Progress #125 * Add and rearrange ONEcolonist tests. Progress #125 * Remove unnecessary section. Close #125 * Sort all_colonisations from oldest to youngest. #125 * Expand tests and add test for 2 clado 1 nonendemic. #125 * Remove get_brts_mya(). Progress #126 * create_island() is internal. Progress #126 * Don't export DAISIE_make_global(). Progress #126 * Fix ONEcolonist documentation * Minor formatting * Use improved GHA yaml * Remove travis * Faster example in constant_rate * MinAge and better input support in DAISIE_dataprep * Fix table * Format pic * Try travis again * No roxygen doc on .Rproj * Travis in right place * Don't depend on Rcpp, RcppEigen, BH * Delete top level files * Buiild on Windows R4.0.2, Rtools40 Signed-off-by: Hanno * Windows binary package added Signed-off-by: Hanno * Linux: devtools::check pass Signed-off-by: Hanno * Try Rcpp, RcppEigen, BH on imports * Rcpp, RcppEigen, BH on Imports * Don't run on PR. Install doMC on unix * Rcpp, RcppEigen, BH on Depends * still trying * R CMD check passes on Windows (R 3.6.3) R CMD check passes on Linux (R 3.6.3) Signed-off-by: Hanno * Install ggtree * biocViews: to install ggtree instead * No longer use travis * date change * invoke_IW to test * Bug fix dopri5 and documentation * documentation * Solve Error: function 'enterRNGScope' not provided by package 'Rcpp' as outlined on https://github.com/immunogenomics/LISI/blob/master/NAMESPACE * Depend on specific setup-r tag See similar issue https://github.com/rsetienne/DDD/pull/29 * GHA on macOS_fix * Use full SHA * Check if new test breaks covr * Add skip message * Don't define functions in tests * lint 2 integration tests * lint rate-shift and IW vs CS integration tests * Tweak time_dep ML WIP test * 2 type integration test lint * Remove redundant test-integration_tests * Informative comment on parallel test fix * Try loading Rcpp in tests * Avoid coverage check on solver test * Change flag location * Correct nocov flags * Split loglik_IW_solver and add to .covrignore * covr output in GHA output * Fix syntax * Remove Rcpp library call * skip_on_covr() and remove #nocov flags * Just run codecov * Delete wrong argument * Add @xieshu95's ORCID * Add @joshwlambert's ORCID * Add a NEWS.md file to track changes to the package * Add DAISIE_macOS instructions * Update NEWS.md to match v3.2.0 release notes * Add Big Sur note on README.md * Typo * setup-r@v1 again See Neves-P/DAISIErobustness/cb6ae80f545f01e8a2ebe0c134f915d8f804c7b4 * Add LICENSE file * arrows instead of = * Solving numerical problems with logcondprob * Improving numerical accuracy logcond * Modified test to conform to new logcond * cleaning up logcond * Improving logcond * bug fix * Resolving numerical issues near 0 in integration across parameters * passing mean and sd * fixed bug * Correctly format doi * relaxed rate in NEWS.md * Add note on logcondprob fix * Update date * updated relaxed_rate loglik * Use midpoint of function for better approximation * reduce approx threshold to 0.01 for relaxed-rate * Add @rscherrer's ORCID * Touch up references and authors * @HHildenbrandt is an author * changed approx threshold to 1 and change approximation to DAISIE_loglik * added tests for DAISIE_loglik_integrate * tidy DAISIE_loglik_integrate Co-authored-by: Pedro Neves <10762799+Neves-P@users.noreply.github.com> Co-authored-by: Neves-P Co-authored-by: joshwlambert Co-authored-by: rsetienne Co-authored-by: = <=> --- .Rbuildignore | 12 +- .covrignore | 1 + .github/.gitignore | 1 + .github/workflows/R-CMD-check.yaml | 101 +++ .gitignore | 1 - .travis.yml | 51 -- DAISIE.Rproj | 1 + DESCRIPTION | 25 +- LICENSE | 674 ++++++++++++++++++ NAMESPACE | 7 +- NEWS.md | 54 ++ R/DAISIE-package.R | 16 +- R/DAISIE_ONEcolonist.R | 168 +++-- R/DAISIE_check_format.R | 5 +- R/DAISIE_create_island.R | 1 + R/DAISIE_dataprep.R | 122 +++- R/DAISIE_format_CS_sampled_stt.R | 113 --- R/DAISIE_format_CS_trait.R | 114 +++ R/DAISIE_format_IW_v1_5.R | 124 ---- R/DAISIE_get_brts_mya.R | 22 - R/DAISIE_loglik_CS.R | 46 +- R/DAISIE_loglik_IW.R | 137 +++- R/DAISIE_loglik_integrate.R | 253 +++++-- R/DAISIE_make_archipelago.R | 1 - R/DAISIE_plot_input.R | 7 +- R/DAISIE_rates.R | 14 +- R/DAISIE_sim_constant_rate.R | 12 +- R/DAISIE_sim_core_1_4.R | 389 ---------- R/DAISIE_sim_core_1_4a.R | 268 ------- R/DAISIE_sim_core_1_5.R | 265 ------- R/DAISIE_sim_core_trait_dependent.R | 7 - R/DAISIE_sim_relaxed_rate.R | 2 +- R/DAISIE_sim_trait_dependent.R | 6 - R/DAISIE_single_branch.R | 26 - R/RcppExports.R | 11 + R/utils-pipe.R | 11 - README.md | 26 +- appveyor.yml | 45 -- doc/DAISIE_macOS.md | 56 ++ man/DAISIE-package.Rd | 19 +- man/DAISIE_ONEcolonist.Rd | 41 +- man/DAISIE_calc_clade_ana_rate.Rd | 39 - man/DAISIE_calc_clade_clado_rate.Rd | 48 -- man/DAISIE_calc_clade_ext_rate.Rd | 31 - man/DAISIE_calc_clade_imm_rate.Rd | 53 -- man/DAISIE_create_island.Rd | 1 + man/DAISIE_dataprep.Rd | 14 +- man/DAISIE_get_brts_mya.Rd | 28 - man/DAISIE_loglik_IW.Rd | 14 +- man/DAISIE_loglik_integrand.Rd | 8 +- man/DAISIE_plot_input.Rd | 5 +- man/DAISIE_sim.Rd | 4 +- man/DAISIE_sim_core_1_4.Rd | 39 - man/DAISIE_sim_core_1_4a.Rd | 39 - man/DAISIE_sim_core_trait_dependent.Rd | 8 - man/DAISIE_sim_relaxed_rate.Rd | 2 +- man/DAISIE_sim_trait_dependent.Rd | 8 - man/DAISIE_single_branch.Rd | 29 - man/daisie_odeint_iw.Rd | 8 + man/integral_peak.Rd | 13 +- man/pipe.Rd | 12 - man/transform_gamma_pars.Rd | 19 + pics/Codecov.png | Bin 0 -> 1272 bytes pics/TravisCI.png | Bin 0 -> 5416 bytes pics/github_actions_logo.png | Bin 0 -> 3234 bytes src/DAISIE_IW.cpp | 264 +++++++ src/Makevars | 5 - src/R_init_DAISIE.c | 15 +- tests/testthat.R | 5 +- tests/testthat/test-DAISIE_ML1.R | 106 ++- tests/testthat/test-DAISIE_ML2.R | 154 ++-- tests/testthat/test-DAISIE_ML3.R | 85 +++ tests/testthat/test-DAISIE_MW_ML.R | 5 +- tests/testthat/test-DAISIE_ONEcolonist.R | 490 ++++++++++++- tests/testthat/test-DAISIE_format_CS.R | 26 +- .../testthat/test-DAISIE_format_CS_full_stt.R | 71 +- .../test-DAISIE_format_CS_sampled_stt.R | 100 +-- tests/testthat/test-DAISIE_format_CS_trait.R | 99 +++ tests/testthat/test-DAISIE_format_IW.R | 28 - tests/testthat/test-DAISIE_get_brts_mya.R | 9 - tests/testthat/test-DAISIE_loglik_IW_solver.R | 56 ++ tests/testthat/test-DAISIE_loglik_integrate.R | 16 +- tests/testthat/test-DAISIE_sim_MW.R | 337 +++++---- .../testthat/test-DAISIE_sim_constant_rate.R | 127 +++- .../test-DAISIE_sim_constant_rate_shift.R | 74 +- tests/testthat/test-DAISIE_sim_core.R | 135 ---- ...test-DAISIE_sim_core_constant_rate_shift.R | 23 + .../test-DAISIE_sim_core_time_dependent.R | 30 + .../test-DAISIE_sim_core_trait_dependent.R | 55 ++ tests/testthat/test-DAISIE_sim_relaxed_rate.R | 365 ++++++++-- .../testthat/test-DAISIE_sim_time_dependent.R | 329 +++++++++ .../test-DAISIE_sim_trait_dependent.R | 114 ++- tests/testthat/test-are_rates.R | 19 +- tests/testthat/test-get_ana_rate.R | 14 + tests/testthat/test-get_clado_rate.R | 69 ++ tests/testthat/test-get_ext_rate.R | 32 + tests/testthat/test-get_immig_rate.R | 56 ++ tests/testthat/test-integration_DAISIE.R | 134 ++-- tests/testthat/test-is_simulation_outputs.R | 28 + .../testthat/test-time_dep_vs_constant_rate.R | 75 ++ 100 files changed, 4542 insertions(+), 2685 deletions(-) create mode 100644 .covrignore create mode 100644 .github/.gitignore create mode 100644 .github/workflows/R-CMD-check.yaml delete mode 100644 .travis.yml create mode 100644 LICENSE create mode 100644 NEWS.md create mode 100644 R/DAISIE_format_CS_trait.R delete mode 100644 R/DAISIE_format_IW_v1_5.R delete mode 100644 R/DAISIE_get_brts_mya.R delete mode 100644 R/DAISIE_sim_core_1_4.R delete mode 100644 R/DAISIE_sim_core_1_4a.R delete mode 100644 R/DAISIE_sim_core_1_5.R delete mode 100644 R/DAISIE_single_branch.R create mode 100644 R/RcppExports.R delete mode 100644 R/utils-pipe.R delete mode 100644 appveyor.yml create mode 100644 doc/DAISIE_macOS.md delete mode 100644 man/DAISIE_calc_clade_ana_rate.Rd delete mode 100644 man/DAISIE_calc_clade_clado_rate.Rd delete mode 100644 man/DAISIE_calc_clade_ext_rate.Rd delete mode 100644 man/DAISIE_calc_clade_imm_rate.Rd delete mode 100644 man/DAISIE_get_brts_mya.Rd delete mode 100644 man/DAISIE_sim_core_1_4.Rd delete mode 100644 man/DAISIE_sim_core_1_4a.Rd delete mode 100644 man/DAISIE_single_branch.Rd create mode 100644 man/daisie_odeint_iw.Rd delete mode 100644 man/pipe.Rd create mode 100644 man/transform_gamma_pars.Rd create mode 100644 pics/Codecov.png create mode 100644 pics/TravisCI.png create mode 100644 pics/github_actions_logo.png create mode 100644 src/DAISIE_IW.cpp delete mode 100644 src/Makevars create mode 100644 tests/testthat/test-DAISIE_ML3.R create mode 100644 tests/testthat/test-DAISIE_format_CS_trait.R delete mode 100644 tests/testthat/test-DAISIE_get_brts_mya.R create mode 100644 tests/testthat/test-DAISIE_loglik_IW_solver.R create mode 100644 tests/testthat/test-get_ana_rate.R create mode 100644 tests/testthat/test-get_clado_rate.R create mode 100644 tests/testthat/test-get_ext_rate.R create mode 100644 tests/testthat/test-get_immig_rate.R create mode 100644 tests/testthat/test-time_dep_vs_constant_rate.R diff --git a/.Rbuildignore b/.Rbuildignore index e1fd3779..c26245c4 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -1,5 +1,6 @@ +^.*\.git$ +^.*\.github$ ^.*\.Rproj$ -^\.Rproj\.user$ ^\.travis\.yml$ ^README\.md ^appveyor\.yml$ @@ -8,3 +9,12 @@ ^CONTRIBUTING\.md$ ^data-raw$ +^pics$ +^\.github$ + +invoke_IW\.R +test\.R +test\.sh +^\.Rproj\.user$ +^\.covrignore$ +^LICENSE$ diff --git a/.covrignore b/.covrignore new file mode 100644 index 00000000..e15132c2 --- /dev/null +++ b/.covrignore @@ -0,0 +1 @@ +tests/testthat/test-DAISIE_loglik_IW_solver.R diff --git a/.github/.gitignore b/.github/.gitignore new file mode 100644 index 00000000..2d19fc76 --- /dev/null +++ b/.github/.gitignore @@ -0,0 +1 @@ +*.html diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml new file mode 100644 index 00000000..888064ce --- /dev/null +++ b/.github/workflows/R-CMD-check.yaml @@ -0,0 +1,101 @@ +# For help debugging build failures open an issue on the RStudio community with the 'github-actions' tag. +# https://community.rstudio.com/new-topic?category=Package%20development&tags=github-actions +on: + push: + branches: + - main + - master + - develop + - macOS_fix + + # pull_request: + # branches: + # - main + # - master + # - develop + +name: R-CMD-check + +jobs: + R-CMD-check: + runs-on: ${{ matrix.config.os }} + + name: ${{ matrix.config.os }} (${{ matrix.config.r }}) + + strategy: + fail-fast: false + matrix: + config: + - {os: windows-latest, r: 'release'} + - {os: macOS-latest, r: 'release'} + - {os: ubuntu-20.04, r: 'release', rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"} + - {os: ubuntu-20.04, r: 'devel', rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"} + + env: + R_REMOTES_NO_ERRORS_FROM_WARNINGS: true + RSPM: ${{ matrix.config.rspm }} + GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} + + steps: + - uses: actions/checkout@v2 + + - uses: r-lib/actions/setup-r@v1 + with: + r-version: ${{ matrix.config.r }} + + - uses: r-lib/actions/setup-pandoc@v1 + + - name: Query dependencies + run: | + install.packages('remotes') + saveRDS(remotes::dev_package_deps(dependencies = TRUE), ".github/depends.Rds", version = 2) + writeLines(sprintf("R-%i.%i", getRversion()$major, getRversion()$minor), ".github/R-version") + shell: Rscript {0} + + - name: Cache R packages + if: runner.os != 'Windows' + uses: actions/cache@v2 + with: + path: ${{ env.R_LIBS_USER }} + key: ${{ runner.os }}-${{ hashFiles('.github/R-version') }}-1-${{ hashFiles('.github/depends.Rds') }} + restore-keys: ${{ runner.os }}-${{ hashFiles('.github/R-version') }}-1- + + - name: Install system dependencies + if: runner.os == 'Linux' + run: | + while read -r cmd + do + eval sudo $cmd + done < <(Rscript -e 'writeLines(remotes::system_requirements("ubuntu", "20.04"))') + + - name: Install dependencies + run: | + remotes::install_deps(dependencies = TRUE) + remotes::install_cran("rcmdcheck") + if (.Platform$OS.type == "unix") remotes::install_cran("doMC") + shell: Rscript {0} + + - name: Check + env: + _R_CHECK_CRAN_INCOMING_REMOTE_: false + run: rcmdcheck::rcmdcheck(args = c("--no-manual", "--as-cran"), error_on = "warning", check_dir = "check") + shell: Rscript {0} + + - name: Show testthat output + if: always() + run: find check -name 'testthat.Rout*' -exec cat '{}' \; || true + shell: bash + + - name: Install covr and test coverage + if: matrix.config.r == 'devel' + run: | + remotes::install_cran("covr") + covr::codecov() + shell: Rscript {0} + + - name: Upload check results + if: failure() + uses: actions/upload-artifact@main + with: + name: ${{ runner.os }}-r${{ matrix.config.r }}-results + path: check diff --git a/.gitignore b/.gitignore index 062e4602..57d068ce 100644 --- a/.gitignore +++ b/.gitignore @@ -15,5 +15,4 @@ src/*.gcda src/*.gcno **/.DS_Store **/Rplots.pdf -doc Meta diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 866324ac..00000000 --- a/.travis.yml +++ /dev/null @@ -1,51 +0,0 @@ -# R for travis: see documentation at https://docs.travis-ci.com/user/languages/r - -os: linux -language: r -dist: bionic -jobs: - include: - - r: release - os: linux - - r: devel - os: linux -cache: packages - -addons: - apt: - sources: ['ubuntu-toolchain-r-test'] - packages: - - gcc-8 - - g++-8 - - gfortran-8 - -env: - global: - - MAKEFLAGS="-j 2" - - COMPILER=g++-8 - - CC=gcc-8 - - CXX=g++-8 - -r_packages: - - deSolve - - doMC - - knitr - - tidyr - -r_github_packages: - - jimhester/covr - - jimhester/lintr - -before_install: - - sudo apt-get update - - sudo add-apt-repository -y ppa:cran/imagemagick-dev - - sudo apt-get install -y libmagick++-dev - -script: - - travis_wait 30 R CMD build . - - travis_wait 100 R CMD check *tar.gz - -after_success: - - if [ "$TRAVIS_OS_NAME" == "linux" ] && [ "$TRAVIS_R_VERSION_STRING" == "release" ]; then Rscript -e "lintr::lint_package()"; fi - - if [ "$TRAVIS_OS_NAME" == "linux" ] && [ "$TRAVIS_R_VERSION_STRING" == "devel" ]; then travis_wait 40 Rscript -e 'covr::codecov()'; fi - diff --git a/DAISIE.Rproj b/DAISIE.Rproj index f0d61875..e5c3f7cb 100644 --- a/DAISIE.Rproj +++ b/DAISIE.Rproj @@ -18,4 +18,5 @@ StripTrailingWhitespace: Yes BuildType: Package PackageUseDevtools: Yes PackageInstallArgs: --no-multiarch --with-keep.source +PackageCheckArgs: --as-cran PackageRoxygenize: rd,collate,namespace,vignette diff --git a/DESCRIPTION b/DESCRIPTION index a52195a4..4b595213 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,10 +1,11 @@ Package: DAISIE Type: Package Title: Dynamical Assembly of Islands by Speciation, Immigration and Extinction -Version: 3.1.0 -Date: 2020-09-27 +Version: 3.2.0 +Date: 2021-03-11 Depends: R (>= 3.5.0) biocViews: +SystemRequirements: C++14 Imports: deSolve, graphics, @@ -19,7 +20,12 @@ Imports: foreach, doParallel, magrittr, - parallel + parallel, + Rcpp (>= 1.0.5) +LinkingTo: + Rcpp, + RcppEigen, + BH Suggests: covr, testthat (>= 2.1.0), @@ -58,7 +64,8 @@ Authors@R: c( person(given = "Joshua W.", family = "Lambert", role = c("aut"), - email = "j.w.l.lambert@rug.nl"), + email = "j.w.l.lambert@rug.nl", + comment = c(ORCID = "0000-0001-5218-3046")), person(given = "Pedro", family = "Neves", role = c("aut"), @@ -67,12 +74,17 @@ Authors@R: c( person(given = "Shu", family = "Xie", role = c("aut"), - email = "s.xie@rug.nl"), + email = "s.xie@rug.nl", + comment = c(ORCID = "0000-0001-9594-946X")), person(given = "Richèl J.C.", family = "Bilderbeek", email = "richel@richelbilderbeek.nl", role = c("aut"), comment = c(ORCID = "0000-0003-1107-7049")), + person(given = "Hanno", + family = "Hildenbrandt", + email = "h.hildenbrandt@rug.nl", + role = c("aut")), person(given = "Torsten", family = "Hauffe", email = "torsten.hauffe@gmail.com", @@ -91,7 +103,8 @@ Authors@R: c( person(given = "Raphael", family = "Scherrer", email = "r.scherrer@rug.nl", - role = c("ctb"))) + role = c("ctb"), + comment = c(ORCID = "0000-0002-1447-7630"))) License: GPL-3 Description: Simulates and computes the (maximum) likelihood of a dynamical model of island biota assembly through speciation, immigration and diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/NAMESPACE b/NAMESPACE index 426a6888..a84ba72d 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,6 +1,5 @@ # Generated by roxygen2: do not edit by hand -export("%>%") export(DAISIE_ExpEIN) export(DAISIE_IC) export(DAISIE_ML) @@ -13,11 +12,9 @@ export(DAISIE_SR_loglik_CS) export(DAISIE_SR_loglik_all) export(DAISIE_convertprobdist) export(DAISIE_dataprep) -export(DAISIE_get_brts_mya) export(DAISIE_loglik_CS) export(DAISIE_loglik_IW) export(DAISIE_loglik_all) -export(DAISIE_make_global) export(DAISIE_margprobdist) export(DAISIE_numcol) export(DAISIE_plot_age_diversity) @@ -37,8 +34,10 @@ export(create_CS_version) export(create_area_pars) export(create_hyper_pars) export(create_trait_pars) +export(daisie_odeint_iw) +import(Rcpp) importFrom(doParallel,registerDoParallel) importFrom(foreach,"%dopar%") importFrom(foreach,foreach) importFrom(magrittr,"%>%") -useDynLib(DAISIE) +useDynLib(DAISIE, .registration = TRUE) diff --git a/NEWS.md b/NEWS.md new file mode 100644 index 00000000..2865a05f --- /dev/null +++ b/NEWS.md @@ -0,0 +1,54 @@ +# DAISIE 3.2.0 + +**N.B.: MacOS users may experience issues when installing DAISIE, especially when on MacOS Big Sur. If that is you case, please see [here](doc/DAISIE_macOS.md) for detailed installation instructions.** + +## Changes +* `DAISIE_loglikg_IW()` is now more efficient and numerically stable. Numerical integration is now done via C++ with package `odeint`. +* Add relaxed rate capabilities (both inference and simulations). Relaxed rate models allow for parameters to not be static, but to be sampled by specific probability distributions. +* Introduce `MinAge` data status in DAISIE data objects. A status containing `MinAge` sets a lower boundary for colonization in situations when the precise colonization time is unknown. This is interpreted by `DAISIE_dataprep()` so that the information is passed on to the likelihood optimization functions. See the `DAISIE_dataprep()` help page for more details. In the back-end this results in new `stac` values 8 and 9. +* Bug fix of "bug 2" in the bug report manuscript. This bug was present in `DAISIE_ONEcolonist()` when recolonization occurs. It has now been fixed so that the colonization and branching times are stored in the way that we now think is the best for it to be dealt with in the likelihood code. In recolonization cases, `$other_clades_same_ancestor` renamed to `$all_colonisations`. #125 +* Fix bug which occurs rarely, when computing log conditional probabilities. Only applicable to ML code running with `cond`. +* Removed deprecated legacy functions. Removed all functions named `DAISIE_*_VERSION_NUMBER()` and all `DAISIE_calc_*_rate()` funcions and `get_brts_mya()`. #126 +* Made some functions internal, as they should be. `DAISIE_make_global()` and `create_island()` are now internal. #127 +* @HHildenbrandt is now an author. +* Added @xieshu95's and @joshwlambert's ORCIDs. +* Added a `NEWS.md` file to track changes to the package. + +# DAISIE 3.1.0 +[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.4054059.svg)](https://doi.org/10.5281/zenodo.4054059) + +* Expands the possibility of conditioning simulations and MLE of the CS model on the number of colonizing lineages. + +* In simulation and ML functions, the `cond` argument can now be greater than one. A non-zero `cond` signifies that the ML or simulation is conditioned on having at least `cond` colonizations on the island. + +* Implements #121, at sim and ML level. + +* Add BugReports, Website and missing ORCID in DESCRIPTION. + +# DAISIE 3.0.1 +* Correct @joshwlambert's name in `DESCRIPTION`. +* `DAISIE_sim_relaxed_rate()` input is closer to `DAISIE_ML()` input. +* Documentation improvements. +* Tweak Makevars. + +# DAISIE 3.0.0 +* Major revamp to simulation code. Simulations now accessed using `DAISIE_sim_*()` syntax. +* Constant rate, time-dependent, trait-dependent, and (multiple) split-rate available. +* Relaxed-rate inference available in `DAISIE_ML_CS()`. +* Improved vignettes documenting CS and IW cases. +* Full stt can be returned by setting `sample_freq = Inf` in `DAISIE_sim_*()` functions. +* Optional plotting with `DAISIE_plot_input()`. (Requires additional dependencies). +* Back-end architecture improvements. + +# DAISIE 2.0.1 +Minor update to v2.0: when empty islands are simulated the output list contains only one element instead of two (where the second indicated stac = 0, i.e. no surviving colonization). + +# DAISIE 2.0 + +Contains the functions used in: + +* Valente L., Etienne R.S., Garcia-R J.C. (2019) Deep macroevolutionary impact of humans on New Zealand's unique avifauna. Current Biology , 29, 2563-2569.e4. https://doi.org/10.1016/j.cub.2019.06.058 + +* Valente L., Phillimore A.B., Melo M. et al. (2020) A simple dynamic model explains the diversity of island birds worldwide. Nature , 579, 92–96. https://doi.org/10.1038/s41586-020-2022-5 + +* Hauffe T, Delicado D, Etienne R.S. and Valente L. (2020) Lake expansion elevates equilibrium diversity via increasing colonisation. Journal of Biogeography. https://doi.org/10.1111/jbi.13914 diff --git a/R/DAISIE-package.R b/R/DAISIE-package.R index 6166b32e..e3f5e59c 100644 --- a/R/DAISIE-package.R +++ b/R/DAISIE-package.R @@ -5,13 +5,15 @@ #' Cladogenesis and immigration rates can be dependent on diversity. #' @references #' \itemize{ -#' \item Valente, L. M., Etienne, R. S., & Phillimore, A. B. (2014). The effects of island ontogeny on species diversity and phylogeny. Proceedings of the Royal Society of London. Series B, Biological Sciences 281, 20133227. . \cr -#' \item Valente, L., A.B. Phillimore & R.S. Etienne (2015). Equilibrium and non-equilibrium dynamics simultaneously operate in the Galapagos islands. Ecology Letters 18: 844-852, . \cr -#' \item Valente, L., R.S. Etienne & L. Davalos (2017). Recent extinctions disturb path to equilibrium diversity in Caribbean bats. Nature Ecology and Evolution 1: 0026. .\cr -#' \item Valente, L., Illera, J. C., Havenstein, K., Pallien, T., Etienne, R. S., & Tiedemann, R. (2017). Equilibrium Bird Species Diversity in Atlantic Islands. Current Biology 27: 1660-1666. .\cr -#' \item Valente, L., Phillimore, A. B., & Etienne, R. (2018). Using molecular phylogenies in island biogeography: It's about time. Ecography 41: 1684-1686. .\cr -#' \item Valente, L., Etienne, R. S., & Garcia-R, J. C. (2019). Deep macroevolutionary impact of humans on New Zealand's unique avifauna. Current Biology 29: 2563-2569. .\cr -#' \item Valente, L., Phillimore, A. B., Melo, M., Warren, B. H., Clegg, S. M., Havenstein, K., Etienne, R. S. (2020). A simple dynamic model explains the diversity of island birds worldwide. Nature 579: 92-96. .\cr +#' \item Valente, L. M., Etienne, R. S., & Phillimore, A. B. (2014). The effects of island ontogeny on species diversity and phylogeny. Proceedings of the Royal Society of London. Series B, Biological Sciences 281, 20133227. \doi{10.1098/rspb.2013.3227}. \cr +#' \item Valente, L., A.B. Phillimore & R.S. Etienne (2015). Equilibrium and non-equilibrium dynamics simultaneously operate in the Galapagos islands. Ecology Letters 18: 844-852, \doi{10.1111/ele.12461}. \cr +#' \item Valente, L., R.S. Etienne & L. Davalos (2017). Recent extinctions disturb path to equilibrium diversity in Caribbean bats. Nature Ecology and Evolution 1: 0026. \doi{10.1038/s41559-016-0026}.\cr +#' \item Valente, L., Illera, J. C., Havenstein, K., Pallien, T., Etienne, R. S., & Tiedemann, R. (2017). Equilibrium Bird Species Diversity in Atlantic Islands. Current Biology 27: 1660-1666. \doi{10.1016/j.cub.2017.04.053}.\cr +#' \item Valente, L., Phillimore, A. B., & Etienne, R. (2018). Using molecular phylogenies in island biogeography: It's about time. Ecography 41: 1684-1686. \doi{10.1111/ecog.03503}.\cr +#' \item Valente, L., Etienne, R. S., & Garcia-R, J. C. (2019). Deep macroevolutionary impact of humans on New Zealand's unique avifauna. Current Biology 29: 2563-2569. \doi{10.1016/j.cub.2019.06.058}.\cr +#' \item Valente, L., Phillimore, A. B., Melo, M., Warren, B. H., Clegg, S. M., Havenstein, K., Etienne, R. S. (2020). A simple dynamic model explains the diversity of island birds worldwide. Nature 579: 92-96. \doi{10.1038/s41586-020-2022-5}.\cr #' } \cr #' @keywords internal +#' @import Rcpp +#' @useDynLib DAISIE, .registration = TRUE "_PACKAGE" diff --git a/R/DAISIE_ONEcolonist.R b/R/DAISIE_ONEcolonist.R index 1be5c14f..2beb9498 100644 --- a/R/DAISIE_ONEcolonist.R +++ b/R/DAISIE_ONEcolonist.R @@ -1,21 +1,44 @@ -#' Title +#' Convert intermediate output to final simulation output #' #' @inheritParams default_params_doc #' #' @return a list with these elements: #' \itemize{ -#' item{[1]: stt_table, the same stt_table as put in} -#' item{[2]: branching_times, branching times} -#' item{[3]: stac, ?statuses} -#' item{[4]: missing_species, ?the number of missing species} -#' item{[5]: other_clades_same_ancestor, ?no idea} -#' item{[6]: non-endemic species} -#' item{[7]: endemic species} +#' \item{[1]: \code{stt_table}, the same stt_table as put in.} +#' \item{[2]: \code{branching_times}, a sorted numeric vector, as required +#' by the ML estimation functions. The first element always refers to +#' the island age. Subsequent elements refer to colonisation, speciation and +#' recolonisation times. The most recent recolonisation time, if any is +#' always omitted to approximate simulation results to the mathematical +#' formulation of the likelihood functions used for MLE.} +#' \item{[3]: \code{stac}, status of colonist. In this function it can be +#' returned as either 2, 4 or 3. If \code{stac} is 2, then there is only one +#' independent colonisation present on the island and the extant species are +#' endemic. If stac is 4, then only a singleton endemic is present at the +#' present. If stac is 3, then recolonisation occurred, and more than one +#' colonising lineage.} +#' \item{[4]: \code{missing_species}, a numeric value with the number of +#' missing species, that is, species not sampled in the phylogeny but +#' present on the island. As this code only runs for simulation models, +#' here \code{missing_species} is always set to 0.} +#' \item{[5]: +#' \code{all_colonisations}, on recolonising lineages only. It is comprised of +#' \code{$event_times} and \code{$species_type}: +#' \describe{ +#' \item{\code{$event_times}}{ordered numeric vectors containing all +#' events for each extant recolonising lineage. This includes all +#' colonisation and branching times. Each vector pertains to one +#' colonising lineage.} +#' \item{\code{$species_type}}{a string. Can be \code{"A"}, \code{"C"} or +#' \code{"I"} depending on whether the extant clade is of anagenetic, +#' cladogenetic or immigrant origin, respectively.} +#' } #' } +#' } #' @keywords internal DAISIE_ONEcolonist <- function(time, - island_spec, - stt_table) { + island_spec, + stt_table) { ### number of independent colonisations uniquecolonisation <- as.numeric(unique( island_spec[, "Colonisation time (BP)"])) @@ -25,65 +48,120 @@ DAISIE_ONEcolonist <- function(time, if (number_colonisations == 1) { if (island_spec[1, "Species type"] == "I") { descendants <- list(stt_table = stt_table, - branching_times = c(time, as.numeric(island_spec[1, "Colonisation time (BP)"])), - stac = 4, - missing_species = 0) + branching_times = c( + time, + as.numeric(island_spec[1, "Colonisation time (BP)"]) + ), + stac = 4, + missing_species = 0) } if (island_spec[1, "Species type"] == "A") { descendants <- list(stt_table = stt_table, - branching_times = c(time, as.numeric(island_spec[1, "Colonisation time (BP)"])), - stac = 2, - missing_species = 0) + branching_times = c( + time, + as.numeric(island_spec[1, "Colonisation time (BP)"]) + ), + stac = 2, + missing_species = 0) } if (island_spec[1, "Species type"] == "C") { descendants <- list(stt_table = stt_table, - branching_times = c(time, rev(sort(as.numeric(island_spec[, "branching time (BP)"])))), - stac = 2, - missing_species = 0) + branching_times = c( + time, + sort( + as.numeric(island_spec[, "branching time (BP)"]), + decreasing = TRUE + ) + ), + stac = 2, + missing_species = 0) } } - ### if there are two or more independent colonisations, all species are classed as stac=3 and put within same list item: + ### if there are two or more independent colonisations, all species are + ### classed as stac=3 and put within same list item: if (number_colonisations > 1) { descendants <- list(stt_table = stt_table, - branching_times = NA, - stac = 3, - missing_species = 0, - other_clades_same_ancestor = list()) + branching_times = NA, + stac = 3, + missing_species = 0, + all_colonisations = list()) - btimes_all_clado_desc <- rev(sort(as.numeric(island_spec[, "branching time (BP)"]))) + # Get branching and colonisation times + btimes_all_clado_desc <- rev( + sort(as.numeric(island_spec[, "branching time (BP)"])) + ) + col_times <- sort( + unique(as.numeric(island_spec[, "Colonisation time (BP)"])), + decreasing = TRUE + ) - if (length(btimes_all_clado_desc) != 0) { descendants$branching_times= c(time, btimes_all_clado_desc)} - if (length(btimes_all_clado_desc)==0) { descendants$branching_times= c(time, max(as.numeric(island_spec[,"Colonisation time (BP)"])))} + # If there are endemic descendants find youngest col time + if (length(btimes_all_clado_desc) != 0) { + # Ensure all col_times are in b_times at this point. + # Covers cases of one recolonization followed by cladogenesis and + # potential extinction + if (any(!(col_times %in% btimes_all_clado_desc))) { + miss_col_time <- which(!(col_times %in% btimes_all_clado_desc)) + btimes_all_clado_desc <- sort( + c(btimes_all_clado_desc, col_times[miss_col_time]), + decreasing = TRUE + ) + } + youngest_col_time <- min(col_times) + i_youngest_col_btimes <- which(btimes_all_clado_desc == youngest_col_time) + + # Remove youngest col time in branching times + testit::assert(youngest_col_time %in% btimes_all_clado_desc) + btimes_all_clado_desc <- btimes_all_clado_desc[-i_youngest_col_btimes] + + descendants$branching_times <- c(time, btimes_all_clado_desc) + testit::assert(!(youngest_col_time %in% btimes_all_clado_desc)) - ### create table with information on other clades with same ancestor, but this information is not used in DAISIE_ML - oldest <- which(as.numeric(island_spec[,"Colonisation time (BP)"]) == max(as.numeric(island_spec[,"Colonisation time (BP)"]))) + # If no cladogenetic species is present, remove the youngest col time + } else if (length(btimes_all_clado_desc) == 0) { + youngest_col_time <- min(col_times) + i_youngest_col_time <- which(col_times == youngest_col_time) + col_times <- col_times[-i_youngest_col_time] - youngest_table = island_spec[-oldest,] - if (is.character(youngest_table) && !is.matrix(youngest_table)) { ####### TODO: WILL FAIL IN DEVELOP ON rsetienne/DAISIE - youngest_table = t(as.matrix(youngest_table)) + descendants$branching_times <- c(time, col_times) } - uniquecol <- as.numeric(unique(youngest_table[,"Colonisation time (BP)"])) - for (colonisation in 1:length(uniquecol)) { - descendants$other_clades_same_ancestor[[colonisation]] = list(brts_miss = NA,species_type = NA) + # all_colonisations section + uniquecol <- sort(as.numeric( + unique(island_spec[, "Colonisation time (BP)"])), decreasing = TRUE + ) + for (i in seq_along(uniquecol)) { + descendants$all_colonisations[[i]] <- list( + event_times = NA, + species_type = NA + ) - samecolonisation = which(as.numeric(youngest_table[,"Colonisation time (BP)"]) == uniquecol[colonisation]) + samecolonisation <- which(as.numeric( + island_spec[, "Colonisation time (BP)"]) == uniquecol[i] + ) - if (youngest_table[samecolonisation[1],"Species type"] == "I") { - descendants$other_clades_same_ancestor[[colonisation]]$brts_miss = as.numeric(youngest_table[samecolonisation,"Colonisation time (BP)"]) - descendants$other_clades_same_ancestor[[colonisation]]$species_type = "I" + if (island_spec[samecolonisation[1], "Species type"] == "I") { + descendants$all_colonisations[[i]]$event_times <- as.numeric( + c(time,island_spec[samecolonisation, "Colonisation time (BP)"]) + ) + descendants$all_colonisations[[i]]$species_type <- "I" } - if (youngest_table[samecolonisation[1],"Species type"] == "A") { - descendants$other_clades_same_ancestor[[colonisation]]$brts_miss = as.numeric(youngest_table[samecolonisation,"Colonisation time (BP)"]) - descendants$other_clades_same_ancestor[[colonisation]]$species_type = "A" + if (island_spec[samecolonisation[1], "Species type"] == "A") { + descendants$all_colonisations[[i]]$event_times <- as.numeric( + c(time, island_spec[samecolonisation, "Colonisation time (BP)"]) + ) + descendants$all_colonisations[[i]]$species_type <- "A" } - if (youngest_table[samecolonisation[1],"Species type"] == "C") { - descendants$other_clades_same_ancestor[[colonisation]]$brts_miss = rev(sort(as.numeric(youngest_table[samecolonisation,"branching time (BP)"]))) - descendants$other_clades_same_ancestor[[colonisation]]$species_type = "C" + if (island_spec[samecolonisation[1], "Species type"] == "C") { + descendants$all_colonisations[[i]]$event_times <- + sort(c(time, as.numeric( + island_spec[samecolonisation, "branching time (BP)"] + )), decreasing = TRUE) + descendants$all_colonisations[[i]]$species_type <- "C" } } } diff --git a/R/DAISIE_check_format.R b/R/DAISIE_check_format.R index 12918efd..6db15025 100644 --- a/R/DAISIE_check_format.R +++ b/R/DAISIE_check_format.R @@ -144,9 +144,8 @@ is_simulation_outputs <- function(simulation_outputs) { for (n_replicate in seq_along(simulation_outputs)) { if (!"island_age" %in% names(simulation_outputs[[n_replicate]][[1]])) return(FALSE) - if (!(!"not_present" %in% names(simulation_outputs[[n_replicate]][[1]]) || - !"not_present_type1" %in% - names(simulation_outputs[[n_replicate]][[1]]))) { + if (!(names(simulation_outputs[[n_replicate]][[1]])[2] %in% + c("not_present","not_present_type1"))) { return(FALSE) } if (!"stt_all" %in% names(simulation_outputs[[n_replicate]][[1]])) diff --git a/R/DAISIE_create_island.R b/R/DAISIE_create_island.R index 71a67b5a..da278108 100644 --- a/R/DAISIE_create_island.R +++ b/R/DAISIE_create_island.R @@ -5,6 +5,7 @@ #' @return list with the island information, composed stt table, #' branching times of extant species, status of species on #' the island and number of missing species. +#' @keywords internal DAISIE_create_island <- function(stt_table, totaltime, island_spec, diff --git a/R/DAISIE_dataprep.R b/R/DAISIE_dataprep.R index 357ebe15..8c199638 100644 --- a/R/DAISIE_dataprep.R +++ b/R/DAISIE_dataprep.R @@ -24,9 +24,11 @@ #' in the phylogeny ("NA" should be given in the branching times column). It #' could also apply to insular radiations with long stem branches, for which the #' time of the first cladogenetic event is known, but the precise time of colonisation -#' is not. \cr * "Endemic&Non_Endemic": when endemic clade is present and its mainland -#' ancestor has re-colonized \cr \code{$Missing_species} - Number of island -#' species that were not sampled for particular clade (only applicable for +#' is not. \cr * "Endemic_MaxAge_MinAge": same as Endemic_MaxAge but also includes a minimum +#' age for colonisation. \cr * "Non_endemic_MaxAge_MinAge": same as Non_endemic_MaxAge but +#' also includes a minimum age for colonisation.#' \cr * "Endemic&Non_Endemic": when endemic +#' clade is present and its mainland ancestor has re-colonized \cr \code{$Missing_species} +#' - Number of island species that were not sampled for particular clade (only applicable for #' "Endemic" clades). If NA is given in branching times column, this should #' be equal to the number of species in the clade minus 1 \cr \code{$Branching_times} #' - Stem age of the population/species in the case of "Non_endemic", "Non_endemic_MaxAge" @@ -95,7 +97,7 @@ #' #' ### Create Galapagos data object where all taxa have the same macroevolutionary process #' -#' utils::data(Galapagos_datatable) +#' utils::data(Galapagos_datatable, package = "DAISIE") #' DAISIE_dataprep( #' datatable = Galapagos_datatable, #' island_age = 4, @@ -108,7 +110,7 @@ #' # (Darwin's finches). Set fraction of potential colonists of type 2 to be #' # proportional to the number of type2 clades present on the island. #' -#' utils::data(Galapagos_datatable) +#' utils::data(Galapagos_datatable, package = "DAISIE") #' DAISIE_dataprep( #' datatable = Galapagos_datatable, #' island_age = 4, @@ -122,7 +124,7 @@ #' # except for Darwin's finches) and the other applies only to type 2 species #' # (Darwin's finches). Set fraction of potential colonists of type 2 to be 0.163. #' -#' utils::data(Galapagos_datatable) +#' utils::data(Galapagos_datatable, package = "DAISIE") #' DAISIE_dataprep( #' datatable = Galapagos_datatable, #' island_age = 4, @@ -176,7 +178,7 @@ DAISIE_dataprep = function(datatable, colonist_name = as.character(datatable[i, "Clade_name"]), branching_times = NA, stac = NA, - missing_species = datatable[i, "Missing_species"], + missing_species = as.numeric(datatable[i, "Missing_species"]), type1or2 = 1) the_brts <- rev(sort(as.numeric(unlist( strsplit(as.character(datatable[i, "Branching_times"]), split = ","))))) @@ -186,7 +188,10 @@ DAISIE_dataprep = function(datatable, if(datatable[i,"Status"] == "Endemic" | datatable[i,"Status"] == "endemic" ){ levels(datatable$Status) = append(levels(datatable$Status),"Endemic_MaxAge") datatable[i,"Status"] <-"Endemic_MaxAge"} - if(datatable[i,"Status"] == "Non_endemic" | datatable[i,"Status"] == "Non_Endemic"){ + if(datatable[i,"Status"] == "Non_endemic" | datatable[i,"Status"] == "Non_Endemic" + | datatable[i,"Status"] == "NonEndemic" | datatable[i,"Status"] == "Nonendemic" | + datatable[i,"Status"] == "nonendemic" | datatable[i,"Status"] == "non_endemic") + { levels(datatable$Status) = append(levels(datatable$Status),"Non_endemic_MaxAge") datatable[i,"Status"] <-"Non_endemic_MaxAge"} } @@ -202,7 +207,10 @@ DAISIE_dataprep = function(datatable, if(datatable[i,"Status"] == "Endemic" | datatable[i,"Status"] == "endemic" ){ levels(datatable$Status) = append(levels(datatable$Status),"Endemic_MaxAge") datatable[i,"Status"] <-"Endemic_MaxAge"} - if(datatable[i,"Status"] == "Non_endemic" | datatable[i,"Status"] == "Non_Endemic"){ + if(datatable[i,"Status"] == "Non_endemic" | datatable[i,"Status"] == "Non_Endemic" + | datatable[i,"Status"] == "NonEndemic" | datatable[i,"Status"] == "Nonendemic" | + datatable[i,"Status"] == "nonendemic" | datatable[i,"Status"] == "non_endemic" + ) { levels(datatable$Status) = append(levels(datatable$Status),"Non_endemic_MaxAge") datatable[i,"Status"] <-"Non_endemic_MaxAge"} } @@ -215,40 +223,107 @@ DAISIE_dataprep = function(datatable, { the_brts[1] = min(the_brts[1],island_age - epss) datalist[[i + 1]]$branching_times = c(island_age,the_brts) - if(the_brts[2]>=the_brts[1]){stop(paste('Cladogenetic event in ', - as.character(datatable[i,"Clade_name"]),'is older than the island, or of the same age as the island',sep=''))} + if(the_brts[2] >= the_brts[1]){stop(paste('Cladogenetic event or minimum colonisation time in ', + as.character(datatable[i,"Clade_name"]),' is older than the island, or of the same age as the island',sep=''))} } - if(datatable[i,"Status"] == "Non_endemic_MaxAge" | datatable[i,"Status"] == "Non_Endemic_MaxAge" | - datatable[i,"Status"] == "Non_Endemic_Max_Age" | datatable[i,"Status"] == "Non_endemic_maxage" - | datatable[i,"Status"] == "Non_Endemic_Maxage" | datatable[i,"Status"] == "Non_Endemic_maxage" - | datatable[i,"Status"] == "Non_endemic_Maxage") + + if (datatable[i,"Status"] == "Non_endemic_MaxAge" | datatable[i,"Status"] == "Non_Endemic_MaxAge" | + datatable[i,"Status"] == "Non_Endemic_Max_Age" | datatable[i,"Status"] == "Non_endemic_maxage" + | datatable[i,"Status"] == "Non_Endemic_Maxage" | datatable[i,"Status"] == "Non_Endemic_maxage" + | datatable[i,"Status"] == "Non_endemic_Maxage" | datatable[i,"Status"] == "NonEndemic_MaxAge" ) { + + if(length(the_brts)>1){stop(paste('Only one branching time should be provided for ', as.character(datatable[i,"Clade_name"]),' because it is a non-endemic species. If you mean to specifiy a minimum age as well, please use Non_Endemic_MaxAgeMinAge.',sep=''))} + + if(datatable[i, "Missing_species"]>0){stop(paste('Missing species for ', as.character(datatable[i,"Clade_name"]),' should be 0 because it is a non-endemic species.',sep=''))} + datalist[[i + 1]]$stac = 1 + } + if(datatable[i,"Status"] == "Endemic" | datatable[i,"Status"] == "endemic" ) { datalist[[i + 1]]$stac = 2 } - if(datatable[i,"Status"] == "Endemic&Non_endemic" | datatable[i,"Status"] == "Endemic&Non_Endemic") + + if(datatable[i,"Status"] == "Endemic&Non_endemic" | datatable[i,"Status"] == "Endemic&NonEndemic" | + datatable[i,"Status"] == "Endemic&Non_Endemic") { datalist[[i + 1]]$stac = 3 } - if(datatable[i,"Status"] == "Non_endemic" | datatable[i,"Status"] == "Non_Endemic") + + if(datatable[i,"Status"] == "Non_endemic" | datatable[i,"Status"] == "Non_Endemic" + | datatable[i,"Status"] == "NonEndemic" | datatable[i,"Status"] == "Nonendemic" | + datatable[i,"Status"] == "nonendemic" | datatable[i,"Status"] == "non_endemic") { + if(length(the_brts)>1){stop(paste('Only one branching time should be provided for ', as.character(datatable[i,"Clade_name"]),' because it is a non-endemic species. If you mean to specifiy a minimum age as well, please use Non_Endemic_MaxAgeMinAge.',sep=''))} + if(datatable[i, "Missing_species"]>0){stop(paste('Missing species for ', as.character(datatable[i,"Clade_name"]),' should be 0 because it is a non-endemic species.',sep=''))} datalist[[i + 1]]$stac = 4 } - if(datatable[i,"Status"] == "Endemic_MaxAge" | datatable[i,"Status"] == "Endemic_maxage" | datatable[i,"Status"] == "Endemic_Max_Age" - | datatable[i,"Status"] == "Endemic_Maxage") + + if(datatable[i,"Status"] == "Endemic_MaxAge" | datatable[i,"Status"] == "Endemic_maxage" | datatable[i,"Status"] == "Endemic_Max_Age" | + datatable[i,"Status"] == "EndemicMaxAge" | datatable[i,"Status"] == "Endemicmaxage" | datatable[i,"Status"] == "endemicMaxage" | + datatable[i,"Status"] == "Endemic_Maxage" | datatable[i,"Status"] == "EndemicMaxage" | + datatable[i,"Status"] == "endemic_maxage" | datatable[i,"Status"] == "endemicmaxage"| datatable[i,"Status"] == "endemic_Maxage" | + datatable[i,"Status"] == "endemic_MaxAge" | datatable[i,"Status"] == "endemic_maxAge") { if(length(the_brts) == 1){ datalist[[i + 1]]$stac = 5} if(length(the_brts) > 1) { datalist[[i + 1]]$stac = 6} if(max(the_brts)>island_age){ if(length(the_brts) > 1){ - stop(paste('Radiation of ',as.character(datatable[i,"Clade_name"]),' is older than the island',sep=''))} } } + + if(datatable[i,"Status"] == "Non_endemic_MaxAgeMinAge" | + datatable[i,"Status"] == "Non_Endemic_MaxAgeMinAge" | + datatable[i,"Status"] == "Non_endemic_MaxAge_MinAge" | + datatable[i,"Status"] == "Non_Endemic_MaxAge_MinAge" | + datatable[i,"Status"] == "Non_Endemic_Max_AgeMinAge" | + datatable[i,"Status"] == "Non_endemic_maxage_minage" | + datatable[i,"Status"] == "Non_Endemic_MaxageminAge" | + datatable[i,"Status"] == "Non_Endemic_maxage_minage" | + datatable[i,"Status"] == "Non_endemic_MaxageMinage" | + datatable[i,"Status"] == "NonEndemic_MaxageMinAge" | + datatable[i,"Status"] == "Nonendemic_MaxageMinAge" | + datatable[i,"Status"] == "Nonendemic_Maxage_MinAge" | + datatable[i,"Status"] == "Nonendemic_maxage_minage" | + datatable[i,"Status"] == "Nonendemic_Maxage_minage" | + datatable[i,"Status"] == "Nonendemic_Maxage_Minage" | + datatable[i,"Status"] == "NonEndemic_MaxAge_MinAge" | + datatable[i,"Status"] == "NonEndemic_Maxage_MinAge" | + datatable[i,"Status"] == "NonEndemic_Maxage_Minage" | + datatable[i,"Status"] == "NonEndemic_maxage_minage" | + datatable[i,"Status"] == "NonEndemic_Maxage_minage" | + datatable[i,"Status"] == "Non_Endemic_maxAgeMinAge" | + datatable[i,"Status"] == "NonEndemic_MaxAge_Minage" | + datatable[i,"Status"] == "Non_Endemic_MaxAge_Minage" | + datatable[i,"Status"] == "NonEndemic_maxage_MinAge") + { + datalist[[i + 1]]$stac = 8 + } + + if(datatable[i,"Status"] == "Endemic_MaxAgeMinAge" | + datatable[i,"Status"] == "endemic_MaxAgeMinAge" | + datatable[i,"Status"] == "Endemic_MaxAge_MinAge" | + datatable[i,"Status"] == "Endemic_Maxage_Minage" | + datatable[i,"Status"] == "Endemic_Max_Age_Min_Age" | + datatable[i,"Status"] == "endemic_maxage_minage" | + datatable[i,"Status"] == "endemic_Maxage_minage" | + datatable[i,"Status"] == "endemic_Maxage_Minage" | + datatable[i,"Status"] == "Endemic_Maxage_minage" | + datatable[i,"Status"] == "endemic_maxage_Minage" | + datatable[i,"Status"] == "Endemic_MaxageMinage" | + datatable[i,"Status"] == "Endemic_Maxageminage" | + datatable[i,"Status"] == "Endemic_MaxAge_Minage" | + datatable[i,"Status"] == "Endemic_maxageminage" | + datatable[i,"Status"] == "Endemic_maxageMinage") + { + datalist[[i + 1]]$stac = 9 + } + + if(number_clade_types == 2) { if(length(which(list_type2_clades == datatable[i,"Clade_name"])) > 0) @@ -257,5 +332,12 @@ DAISIE_dataprep = function(datatable, } } } + + if (length(which(is.na(unlist(datalist)[which(names(unlist(datalist)) == 'stac')]) == TRUE)) > 0) + { + stop(paste("The status of one or more lineages is incorrectly spelled in + the source table and has not been assigned.")) + } + return(datalist) } diff --git a/R/DAISIE_format_CS_sampled_stt.R b/R/DAISIE_format_CS_sampled_stt.R index f7e7b82d..7c963148 100644 --- a/R/DAISIE_format_CS_sampled_stt.R +++ b/R/DAISIE_format_CS_sampled_stt.R @@ -177,116 +177,3 @@ DAISIE_format_CS_sampled_stt <- function(island_replicates, return(several_islands) } -DAISIE_format_CS_trait <- function(island_replicates, - time, - M, - sample_freq, - verbose = TRUE, - trait_pars = NULL) -{ - totaltime <- time - several_islands <- list() - - for(rep in 1:length(island_replicates)) - { - full_list <- island_replicates[[rep]] - stac_vec <- unlist(full_list)[which(names(unlist(full_list)) == "stac")] - number_not_present <- length(which(stac_vec == 0)) - present <- which(stac_vec!=0) - number_present <- length(present) - type_vec <- unlist(full_list)[which(names(unlist(full_list)) == "type1or2")] - prop_type2_pool <- length(which(type_vec == 2)) / M - - number_type2_cols <- length(which(match(which(stac_vec != 0),which(type_vec == 2)) > 0)) - number_type1_cols <- number_present-number_type2_cols - - island_list <- list() - for(i in 1:(number_present + 1)) - { - island_list[[i]] = list() - } - - ### all species - stt_list = list() - for(i in 1:(M + trait_pars$M2)) - { - stt_list[[i]] = full_list[[i]]$stt_table - } - stt_all = matrix(ncol = 8,nrow = sample_freq + 1) - - colnames(stt_all) = c("Time","nI","nA","nC","nI2","nA2","nC2","present") - stt_all[,"Time"] = rev(seq(from = 0,to = totaltime,length.out = sample_freq + 1)) - - #### - immig_spec <- c() - ana_spec <- c() - immig_spec2 <- c() - ana_spec2 <- c() - for (i in 1:(M + trait_pars$M2)) { - immig_spec[i] <- sum(full_list[[i]]$stt_table[1, 2]) - ana_spec[i] <- sum(full_list[[i]]$stt_table[1, 3]) - immig_spec2[i] <- sum(full_list[[i]]$stt_table[1, 5]) - ana_spec2[i] <- sum(full_list[[i]]$stt_table[1, 6]) - } - immig_spec <- sum(immig_spec) - ana_spec <- sum(ana_spec) - immig_spec2 <- sum(immig_spec2) - ana_spec2 <- sum(ana_spec2) - init_present <- immig_spec + ana_spec + immig_spec2 + ana_spec2 - stt_all[1, 2:8] <- c(immig_spec, ana_spec, 0, immig_spec2, ana_spec2, 0, init_present) - - #### - for(i in 2:nrow(stt_all)) - { - the_age = stt_all[i,"Time"] - store_richness_time_slice = matrix(nrow = M + trait_pars$M2,ncol = 6) - colnames(store_richness_time_slice) = c("I","A","C","I2","A2","C2") - for(x in 1:(M + trait_pars$M2)) - { - # testit::assert(x >= 1) - # testit::assert(x <= length(stt_list)) - # testit::assert("Time" %in% colnames(stt_list[[x]])) - store_richness_time_slice[x,] = stt_list[[x]][max(which(stt_list[[x]][,"Time"] >= the_age)),2:7] - } - count_time_slice = store_richness_time_slice[,1] + - store_richness_time_slice[,2] + - store_richness_time_slice[,3] + - store_richness_time_slice[,4] + - store_richness_time_slice[,5] + - store_richness_time_slice[,6] - present_time_slice = rep(0, M + trait_pars$M2) - present_time_slice[which(count_time_slice>0)] = 1 - store_richness_time_slice = cbind(store_richness_time_slice,present_time_slice) - stt_all[i,c(2:8)] = apply(store_richness_time_slice,2,sum) - } - if(number_type2_cols > 0){ - stop("Two species types and two trait states not considered simutanously.") - } - - island_list[[1]] = list(island_age = totaltime,not_present = number_not_present, stt_all = stt_all) - - - if(number_present > 0) - { - for(i in 1:number_present) - { - island_list[[1 + i]] = full_list[[present[i]]] - island_list[[1 + i]]$stt_table = NULL - } - } - - if(number_present == 0) - { - island_list = list() - island_list[[1]] = list(island_age = totaltime,not_present = M, stt_all = stt_all) - - } - - several_islands[[rep]] = island_list - if (verbose == TRUE) { - print(paste("Island being formatted: ",rep,"/",length(island_replicates),sep = "")) - } - } - - return(several_islands) -} diff --git a/R/DAISIE_format_CS_trait.R b/R/DAISIE_format_CS_trait.R new file mode 100644 index 00000000..2f9a9a55 --- /dev/null +++ b/R/DAISIE_format_CS_trait.R @@ -0,0 +1,114 @@ +DAISIE_format_CS_trait <- function(island_replicates, + time, + M, + sample_freq, + verbose = TRUE, + trait_pars = NULL) +{ + totaltime <- time + several_islands <- list() + + for(rep in 1:length(island_replicates)) + { + full_list <- island_replicates[[rep]] + stac_vec <- unlist(full_list)[which(names(unlist(full_list)) == "stac")] + number_not_present <- length(which(stac_vec == 0)) + present <- which(stac_vec!=0) + number_present <- length(present) + type_vec <- unlist(full_list)[which(names(unlist(full_list)) == "type1or2")] + prop_type2_pool <- length(which(type_vec == 2)) / M + + number_type2_cols <- length(which(match(which(stac_vec != 0),which(type_vec == 2)) > 0)) + number_type1_cols <- number_present-number_type2_cols + + island_list <- list() + for(i in 1:(number_present + 1)) + { + island_list[[i]] = list() + } + + ### all species + stt_list = list() + for(i in 1:(M + trait_pars$M2)) + { + stt_list[[i]] = full_list[[i]]$stt_table + } + stt_all = matrix(ncol = 8,nrow = sample_freq + 1) + + colnames(stt_all) = c("Time","nI","nA","nC","nI2","nA2","nC2","present") + stt_all[,"Time"] = rev(seq(from = 0,to = totaltime,length.out = sample_freq + 1)) + + #### + immig_spec <- c() + ana_spec <- c() + immig_spec2 <- c() + ana_spec2 <- c() + for (i in 1:(M + trait_pars$M2)) { + immig_spec[i] <- sum(full_list[[i]]$stt_table[1, 2]) + ana_spec[i] <- sum(full_list[[i]]$stt_table[1, 3]) + immig_spec2[i] <- sum(full_list[[i]]$stt_table[1, 5]) + ana_spec2[i] <- sum(full_list[[i]]$stt_table[1, 6]) + } + immig_spec <- sum(immig_spec) + ana_spec <- sum(ana_spec) + immig_spec2 <- sum(immig_spec2) + ana_spec2 <- sum(ana_spec2) + init_present <- immig_spec + ana_spec + immig_spec2 + ana_spec2 + stt_all[1, 2:8] <- c(immig_spec, ana_spec, 0, immig_spec2, ana_spec2, 0, init_present) + + #### + for(i in 2:nrow(stt_all)) + { + the_age = stt_all[i,"Time"] + store_richness_time_slice = matrix(nrow = M + trait_pars$M2,ncol = 6) + colnames(store_richness_time_slice) = c("I","A","C","I2","A2","C2") + for(x in 1:(M + trait_pars$M2)) + { + # testit::assert(x >= 1) + # testit::assert(x <= length(stt_list)) + # testit::assert("Time" %in% colnames(stt_list[[x]])) + store_richness_time_slice[x,] = stt_list[[x]][max(which(stt_list[[x]][,"Time"] >= the_age)),2:7] + } + count_time_slice = store_richness_time_slice[,1] + + store_richness_time_slice[,2] + + store_richness_time_slice[,3] + + store_richness_time_slice[,4] + + store_richness_time_slice[,5] + + store_richness_time_slice[,6] + present_time_slice = rep(0, M + trait_pars$M2) + present_time_slice[which(count_time_slice>0)] = 1 + store_richness_time_slice = cbind(store_richness_time_slice,present_time_slice) + stt_all[i,c(2:8)] = apply(store_richness_time_slice,2,sum) + } + + island_list[[1]] = list( + island_age = totaltime, + not_present = number_not_present, + stt_all = stt_all + ) + + + if(number_present > 0) + { + for(i in 1:number_present) + { + island_list[[1 + i]] = full_list[[present[i]]] + island_list[[1 + i]]$stt_table = NULL + } + } + + if(number_present == 0) + { + island_list = list() + island_list[[1]] = list(island_age = totaltime,not_present = M, stt_all = stt_all) + + } + + several_islands[[rep]] = island_list + if (verbose == TRUE) { + print(paste("Island being formatted: ",rep,"/",length(island_replicates),sep = "")) + } + } + + return(several_islands) +} diff --git a/R/DAISIE_format_IW_v1_5.R b/R/DAISIE_format_IW_v1_5.R deleted file mode 100644 index 37e2b551..00000000 --- a/R/DAISIE_format_IW_v1_5.R +++ /dev/null @@ -1,124 +0,0 @@ -DAISIE_format_IW_v1_5 = function(island_replicates,time,M,sample_freq) -{ - several_islands = list() - for(rep in 1:length(island_replicates)) - { - the_island = island_replicates[[rep]] - - stt_all = matrix(ncol = 4,nrow = sample_freq + 1) - colnames(stt_all) = c("Time","nI","nA","nC") - stt_all[,"Time"] = rev(seq(from = 0,to = time,length.out = sample_freq + 1)) - stt_all[1,2:4] = c(0,0,0) - - the_stt = the_island$stt_table - - for(i in 2:nrow(stt_all)) - { - the_age = stt_all[i,"Time"] - stt_all[i,2:4] = the_stt[max(which(the_stt[,"Time"] >= the_age)),2:4] - } - island_list = list() - - if(sum(the_stt[nrow(the_stt),2:4]) == 0) - { - - island_list[[1]] = list(island_age = time,not_present = M, stt_all = stt_all) - - } else - { - island_list[[1]] = list(island_age = time,not_present = M - length(the_island$taxon_list), - stt_all = stt_all) - - for(y in 1:length(the_island$taxon_list)) - { - island_list[[y+1]] = the_island$taxon_list[[y]] - } - } - - island_list = Add_brt_table(island_list) - - several_islands[[rep]] = island_list - - print(paste("Island being formatted: ",rep,"/",length(island_replicates),sep = "")) - - } - return(several_islands) -} - - -Add_brt_table_v1_5 = function(island) { - - island_age <- island[[1]]$island_age - - - if (length(island) == 1) { - brts_table = matrix(ncol = 4, nrow = 1) - brts_table[1, ] = c(island_age, 0, 0, NA) - island[[1]]$brts_table<-brts_table - }else{ - - island_top = island[[1]] - island[[1]] = NULL - - btimes <- list() - for (i in 1:length(island)) - { - btimes[[i]] = island[[i]]$branching_times[-1] - } - - island = island[rev(order(sapply(btimes, "[", 1)))] - - il<-unlist(island) - stac1s<-which(il[which(names(il)=='stac')]=='1') - stac5s<-which(il[which(names(il)=='stac')]=='5') - stac1_5s<-sort(c(stac1s,stac5s)) - - if(length(stac1_5s)!=0) { - - if(length(stac1_5s)==length(island)) - { - brts_table = matrix(ncol = 4, nrow = 1) - brts_table[1, ] = c(island_age, 0, 0, NA) - island_no_stac1or5<-NULL - }else{island_no_stac1or5<-island[-stac1_5s]} - } - - if(length(stac1_5s)==0) {island_no_stac1or5<-island} - - if(length(island_no_stac1or5)!=0){ - btimes = list() - for (i in 1:length(island_no_stac1or5)) { - btimes[[i]] = island_no_stac1or5[[i]]$branching_times[-1] - } - brts = rev(sort(unlist(btimes))) - brts_IWK = matrix(ncol = 4, nrow = length(brts)) - pos1 = 0 - for (i in 1:length(btimes)) { - the_brts = btimes[[i]] - the_stac = island_no_stac1or5[[i]]$stac - pos2 = pos1 + length(the_brts) - brts_IWK[(pos1 + 1):pos2, 1] = the_brts - brts_IWK[(pos1 + 1):pos2, 2] = i - brts_IWK[(pos1 + 1):pos2, 3] = seq(1, length(the_brts)) - brts_IWK[(pos1 + 1):pos2, 4] = (the_stac == 2) + - (the_stac == 3) + (the_stac == 4) * 0 - pos1 = pos2 - } - brts_table = brts_IWK[rev(order(brts_IWK[, 1])), ] - brts_table = rbind(c(island_age, 0, 0, NA), brts_table) - } - - island_top$brts_table = brts_table - - if(length(stac1_5s)!=0){ - for(i in 1:length(stac1_5s)) { - island[[length(island) + 1]] <- island[[stac1_5s[i]]] - island[[stac1_5s[i]]] <- NULL - stac1_5s = stac1_5s - 1 - } - } - island <- append(list(island_top), island)} - - colnames(island[[1]]$brts_table) = c("brt", "clade", "event", "endemic") - return(island) -} diff --git a/R/DAISIE_get_brts_mya.R b/R/DAISIE_get_brts_mya.R deleted file mode 100644 index f1f9c2b0..00000000 --- a/R/DAISIE_get_brts_mya.R +++ /dev/null @@ -1,22 +0,0 @@ -#' Extract the sorted branching times, in million years ago. -#' from a data table -#' -#' @inheritParams default_params_doc -#' -#' @return the sorted branching times, in million years ago -#' @export -#' @examples -#' data(Galapagos_datatable) -#' brts_mya <- DAISIE_get_brts_mya(data_table = Galapagos_datatable) -#' testit::assert(length(brts_mya) > 1) -#' testit::assert(all(brts_mya > 0)) -#' @author Richel J.C. Bilderbeek -DAISIE_get_brts_mya <- function(data_table) { - testit::assert("Branching_times" %in% names(data_table)) - brts_mya <- c() - for (t in data_table$Branching_times) { - brts_mya <- as.numeric(c(brts_mya, - strsplit(as.character(t), split = ",")[[1]])) - } - sort(brts_mya) -} diff --git a/R/DAISIE_loglik_CS.R b/R/DAISIE_loglik_CS.R index 65d7c18d..831a07f4 100644 --- a/R/DAISIE_loglik_CS.R +++ b/R/DAISIE_loglik_CS.R @@ -331,7 +331,7 @@ DAISIE_loglik_CS_M1 <- DAISIE_loglik <- function(pars1, # for stac = 4, brts will contain origin of island, colonization event and 0; # length = 3; no. species should be 1 # for stac = 5, brts will contain origin of island, maximum colonization time - # (usually island age), and 0; length = 2; number of species should be 1 + # (usually island age), and 0; length = 2; number of species should be 1 (+ missing species) # for stac = 6, brts will contain origin of island, maximum colonization time # (usually island age), branching times and 0; # number of species should be no. branching times + 1 @@ -892,7 +892,6 @@ DAISIE_integrate_const <- function(initprobs,tvec,rhs_func,pars,rtol,atol,method return(y) } -#' @useDynLib DAISIE DAISIE_ode_FORTRAN <- function( initprobs, tvec, @@ -915,24 +914,49 @@ DAISIE_ode_FORTRAN <- function( return(probs) } -logcondprob <- function(numcolmin, numimm, logp0) { +logcondprob <- function(numcolmin, numimm, logp0, fac = 2) { + if(numcolmin > sum(numimm)) { + stop('The minimum number of colonizations cannot be smaller than the number of immigrants.') + } + maxi <- min(sum(numimm),fac * numcolmin) logcond <- 0 if(numcolmin >= 1) { - lognotp0 <- log(1 - exp(logp0)) - logpc <- matrix(0,nrow = numcolmin + 1,ncol = length(logp0)) - for(i in 0:numcolmin) { + if(numcolmin == 1 && length(logp0) == 2) { + cat('With two types, conditioning on at least one colonization + implies at least two colonizations. Therefore, the minimum + number of colonizations is changed to 2.\n') + numcolmin <- 2 + } + lognotp0 <- log1p(-exp(logp0)) + logpc <- matrix(0,nrow = maxi + 1,ncol = length(logp0)) + for(i in 0:maxi) { logpc[i + 1,] <- lgamma(numimm + 1) - lgamma(i + 1) - lgamma(numimm - i + 1) + (numimm - i) * logp0 + i * lognotp0 } pc <- exp(logpc) if(length(logp0) == 2) { - pc2 <- DDD::conv(pc[,1],pc[,2])[1:numcolmin] - logcond <- log(1 - sum(pc2) - (numcolmin > 1) * - (pc[1,1] * pc[numcolmin + 1,2] + pc[numcolmin + 1,1] * pc[1,2])) + condprob <- pc[1,1] + pc[1,2] - pc[1,1] * pc[1,2] + #condprob <- sum(pc[1,1] * pc[,2]) + sum(pc[1,2] * pc[,1]) - pc[1,1] * pc[1,2] + if(numcolmin > 2) { + for(i in 2:(numcolmin - 1)) { + condprob <- condprob + sum(pc[2:i,1] * pc[i:2,2]) + } + } + if(condprob >= 1) { + logcond <- log(sum(pc[2:numcolmin,1] * pc[numcolmin:2,2])) + cat('A simple approximation of logcond must be made. Results may be unreliable.\n') + } else { + logcond <- log1p(-condprob) + } } else { - logcond <- log(1 - sum(pc[-(numcolmin + 1)])) + #if(sum(pc[-(numcolmin + 1)]) >= 1) { + if(sum(pc) >= 1) { + logcond <- log(sum(pc[(numcolmin + 1):(maxi + 1)])) + cat('An approximation of logcond must be made. Results may be unreliable.\n') + } else { + logcond <- log1p(-sum(pc[-((numcolmin + 1):(maxi + 1))])) + } } } return(logcond) } - diff --git a/R/DAISIE_loglik_IW.R b/R/DAISIE_loglik_IW.R index ad8b2a8e..4f82ce8c 100644 --- a/R/DAISIE_loglik_IW.R +++ b/R/DAISIE_loglik_IW.R @@ -96,6 +96,79 @@ selectrows <- function(sysdim, order) { return(mat) } + +DAISIE_odeint_iw_pars <- function(pars) +{ + lac = pars[[1]][1] + mu = pars[[1]][2] + Kprime = pars[[1]][3] + gam = pars[[1]][4] + laa = pars[[1]][5] + M = pars[[1]][6] + k = pars[[2]] + ddep = pars[[3]] + lxm1 = pars[[4]]$lxm1 + lxm2 = pars[[4]]$lxm2 + lxe = pars[[4]]$lxe + sysdim = pars[[4]]$sysdim + kmin = pars[[5]]$kmin + kplus = k - kmin + ki = pars[[5]]$ki + nn = pars[[6]]$nn + divdepfac = pars[[6]]$divdepfac + divdepfacmin1 = pars[[6]]$divdepfacmin1 + Mminm = pars[[6]]$Mminm + Mminm[Mminm < 0] = 0 + lminm1minkminplus1 = pars[[6]]$lminm1 - kmin + 1 + lminm1minkminplus1[lminm1minkminplus1 < 0] = 0 + Mminlminm2plus1 = pars[[6]]$Mminlminm2 + 1 + Mminlminm2plus1[Mminlminm2plus1 < 0] = 0 + + nil2lxm1 = 2:(lxm1 + 1) + nil2lxm2 = 2:(lxm2 + 1) + nil2lxe = 3:(lxe + 2) + nilm1 = rep(1,lxm1) + nile = rep(1,lxe) + nilm2 = rep(1,lxm2) + + allc = 1:sysdim + if(sysdim == 1 & lxm1 > 1) + { + dim(Mminm) = c(lxm1,lxm2,lxe) + } else + if(sysdim == 1 & lxm1 == 1) + { + dim(Mminm) = c(lxm2,lxe) + } else + if (sysdim == 1 & lxm1 == 1) { + dim(Mminm) <- c(lxm2, lxe) + } else + if (sysdim > 1 & lxm1 == 1) { + dim(Mminm) <- c(lxm2, lxe, allc) + } + + CP = list( + c1 = (gam * divdepfacmin1 * lminm1minkminplus1), + c2 = (gam * divdepfacmin1 * Mminlminm2plus1), + c3 = (mu * nn[nil2lxm1 + 1, nilm2, nile, allc]), + c4 = (mu * nn[nilm1, nil2lxm2 + 1, nile, allc]), + c5 = (mu * nn[nilm1, nilm2, nil2lxe + 1, allc]), + c6 = (lac * divdepfacmin1 * nn[nil2lxm1 + 1, nilm2, nile, allc]), + c7 = (lac * divdepfacmin1 * nn[nilm1, nil2lxm2 + 1, nile, allc]), + c89 = ((lac * divdepfacmin1 * nn[nilm1, nilm2, nil2lxe - 1, allc]) + (2 * kplus * lac * divdepfacmin1)), + c10 = (laa * nn[nil2lxm1 + 1, nilm2, nile, allc]), + c11 = (laa * nn[nilm1, nil2lxm2 + 1, nile, allc]), + c12 = (-(laa * (nn[nil2lxm1, nil2lxm2, nile, allc] + kmin) + (gam * divdepfac * Mminm) + + ((lac * divdepfac + mu) * (nn[nil2lxm1, nil2lxm2, nil2lxe, allc] + k)))), + c13 = (2 * lac * divdepfacmin1), + ki = ki, + laa = laa, + sysdim = sysdim + ) + return(CP) +} + + DAISIE_loglik_rhs_IW = function(t,x,pars) { lac = pars[[1]][1] @@ -234,8 +307,12 @@ DAISIE_loglik_rhs_IW = function(t,x,pars) #' \code{$missing_species} - #' number of island species that were not sampled for particular clade (only #' applicable for endemic clades) \cr -#' @param methode Method of the ODE-solver. See package deSolve for details. -#' Default is "ode45" +#' @param methode Method of the ODE-solver. Supported odeint solvers (steppers) are: +#' 'odeint::runge_kutta_cash_karp54' +#' 'odeint::runge_kutta_fehlberg78' [default] +#' 'odeint::runge_kutta_dopri5' +#' 'odeint::bulirsch_stoer' +#' without odeint::-prefix, deSolve method is assumed #' @param abstolint Absolute tolerance of the integration #' @param reltolint Relative tolerance of the integration #' @param verbose Logical controling if progress is printed to console. @@ -251,41 +328,37 @@ DAISIE_loglik_IW <- function( pars1, pars2, datalist, - methode = "ode45", - abstolint = 1E-16, - reltolint = 1E-14, + methode = 'odeint::runge_kutta_fehlberg78', + abstolint = 1E-12, + reltolint = 1E-10, verbose = FALSE ) { if(is.na(pars2[4])) { - pars2[4] = 0 + pars2[4] <- 0 } if (is.null(datalist[[1]]$brts_table)) { datalist <- Add_brt_table(datalist) } - brts = c(-abs(datalist[[1]]$brts_table[,1]),0) - clade = datalist[[1]]$brts_table[,2] - event = datalist[[1]]$brts_table[,3] - pars1 = as.numeric(pars1) + brts <- c(-abs(datalist[[1]]$brts_table[,1]),0) + clade <- datalist[[1]]$brts_table[,2] + event <- datalist[[1]]$brts_table[,3] + pars1 <- as.numeric(pars1) if(length(pars1) == 5) { - np = datalist[[1]]$not_present + np <- datalist[[1]]$not_present if(is.null(np)) { - np = datalist[[1]]$not_present_type1 + datalist[[1]]$not_present_type2 + np <- datalist[[1]]$not_present_type1 + datalist[[1]]$not_present_type2 } if(is.null(np)) { cat('Number of species not present is misspecified.\n') - loglik = NA + loglik <- NA return(loglik) } - M = length(datalist) - 1 + np - } else - if(length(pars1) == 6) - { - M = pars1[6] + M <- length(datalist) - 1 + np } else if (length(pars1) == 6) { M <- pars1[6] @@ -295,15 +368,15 @@ DAISIE_loglik_IW <- function( return(loglik) } - ddep = pars2[2] - cond = pars2[3] + ddep <- pars2[2] + cond <- pars2[3] if (cond > 1) { stop('cond > 1 has not been implemented for the island-wide model.') } - lac = pars1[1] - mu = pars1[2] - Kprime = pars1[3] + lac <- pars1[1] + mu <- pars1[2] + Kprime <- pars1[3] if(ddep == 0) { Kprime <- Inf @@ -375,8 +448,13 @@ DAISIE_loglik_IW <- function( } nndd = nndivdep(lxm1,lxm2,lxe,sysdim,Kprime,M,k,l) parslist = list(pars = pars1,k = k,ddep = ddep,dime = dime,kmi = kmi,nndd = nndd) - y = deSolve::ode(y = probs,times = brts[(k + 1):(k + 2)],func = DAISIE_loglik_rhs_IW,parms = parslist,rtol = reltolint,atol = abstolint,method = methode) - probs = y[2,2:(totdim + 1)] + if (startsWith(methode, "odeint::")) { + probs = .Call("daisie_odeint_iw", probs, brts[(k + 1):(k + 2)], DAISIE_odeint_iw_pars(parslist), methode, abstolint, reltolint) + } + else { + y = deSolve::ode(y = probs,times = brts[(k + 1):(k + 2)],func = DAISIE_loglik_rhs_IW,parms = parslist,rtol = reltolint,atol = abstolint,method = methode) + probs = y[2,2:(totdim + 1)] + } cp = checkprobs2(NA, loglik, probs, verbose); loglik = cp[[1]]; probs = cp[[2]] dim(probs) = c(lxm1,lxm2,lxe,sysdim) @@ -443,8 +521,13 @@ DAISIE_loglik_IW <- function( kmi = list(kmin = 0,ki = NULL) nndd = nndivdep(lxm2,lxe,sysdim,Kprime,M,k = 0) parslist = list(pars = pars1,k = k,ddep = ddep,dime = dime,kmi = kmi,nndd = nndd) - y = deSolve::ode(y = probs,times = brts[(k + 1):(k + 2)],func = DAISIE_loglik_rhs_IW,parms = parslist,rtol = reltolint,atol = abstolint,method = methode) - probs = y[2,2:(totdim + 1)] + if (startsWith(methode, "odeint::")) { + probs = .Call("daisie_odeint_iw", probs, brts[(k + 1):(k + 2)], DAISIE_odeint_iw_pars(parslist), methode, abstolint, reltolint) + } + else { + y = deSolve::ode(y = probs,times = brts[(k + 1):(k + 2)],func = DAISIE_loglik_rhs_IW,parms = parslist,rtol = reltolint,atol = abstolint,method = methode) + probs = y[2,2:(totdim + 1)] + } dim(probs) = c(lxm1,lxm2,lxe,sysdim) logcond = log(1 - probs[1,1,1,1]) loglik = loglik - logcond diff --git a/R/DAISIE_loglik_integrate.R b/R/DAISIE_loglik_integrate.R index 023543c8..6e7cedaf 100644 --- a/R/DAISIE_loglik_integrate.R +++ b/R/DAISIE_loglik_integrate.R @@ -1,5 +1,5 @@ -#' Integrates the loglikelihood of a single clade across a parameter weighted by a -#' given distribution +#' Integrates the loglikelihood of a single clade across a parameter weighted +#' by a given distribution #' #' @inheritParams default_params_doc #' @@ -19,20 +19,20 @@ DAISIE_loglik_integrate <- function( verbose) { testit::assert(is.list(CS_version)) - sd <- CS_version$sd + par_sd <- CS_version$sd pick <- which(c("cladogenesis", "extinction", "carrying_capacity", "immigration", "anagenesis") == CS_version$relaxed_par) - mean <- pars1[pick] + par_mean <- pars1[pick] integrated_loglik <- integral_peak( logfun = Vectorize(DAISIE_loglik_integrand, vectorize.args = "DAISIE_par"), - xx = sort(c(seq(-20,20,2), - seq(log(mean) - 1,log(mean) + 1), - log((mean + 10 * sd)/mean))), + xx = sort(c(seq(-20, 20, 2), + seq(log(par_mean) - 1, log(par_mean) + 1), + log((par_mean + 10 * par_sd) / par_mean))), pars1 = pars1, pars2 = pars2, brts = brts, @@ -43,24 +43,11 @@ DAISIE_loglik_integrate <- function( reltolint = reltolint, verbose = verbose, pick = pick, - mean = mean, - sd = sd - ) + par_mean = par_mean, + par_sd = par_sd) return(integrated_loglik) } -#' Gamma distribution density parameterised with mean and standard deviation -#' -#' @inheritParams default_params_doc -#' -#' @return Numeric -#' @keywords internal -rho <- function(DAISIE_par, DAISIE_dist_pars) { - return(stats::dgamma(x = DAISIE_par, - shape = DAISIE_dist_pars[1]^2 / DAISIE_dist_pars[2]^2, - scale = DAISIE_dist_pars[2]^2 / DAISIE_dist_pars[1])) -} - #' Integrand to be integrated to calculate the log likelihood for the relaxed #' rate model. #' @@ -80,10 +67,10 @@ DAISIE_loglik_integrand <- function(DAISIE_par, reltolint, verbose, pick, - mean, - sd) { + par_mean, + par_sd) { pars1[pick] <- DAISIE_par - loglik_DAISIE_par <- exp(DAISIE_loglik( + loglik_DAISIE_par <- DAISIE_loglik( pars1 = pars1, pars2 = pars2, brts = brts, @@ -92,71 +79,189 @@ DAISIE_loglik_integrand <- function(DAISIE_par, methode = methode, abstolint = abstolint, reltolint = reltolint, - verbose = verbose) - ) * + verbose = verbose) + rho( DAISIE_par = DAISIE_par, - DAISIE_dist_pars = c(mean, sd) + DAISIE_dist_pars = list(par_mean = par_mean, + par_sd = par_sd) ) - return(log(loglik_DAISIE_par)) + return(loglik_DAISIE_par) +} + +#' Gamma distribution density parameterised with mean and standard deviation +#' +#' @inheritParams default_params_doc +#' +#' @return Numeric +#' @keywords internal +rho <- function(DAISIE_par, DAISIE_dist_pars) { + + gamma_pars <- transform_gamma_pars( + par_mean = DAISIE_dist_pars$par_mean, + par_sd = DAISIE_dist_pars$par_sd) + + gamma_den <- stats::dgamma( + x = DAISIE_par, + shape = gamma_pars$shape, + scale = gamma_pars$scale, + log = TRUE) + + return(gamma_den) } -#' @title Computes integral of a very peaked function, modified from the SADISA package -#' @description # computes the logarithm of the integral of exp(logfun) from 0 to Inf under the following assumptions: -# . exp(logfun) has a single, sharply peaked maximum -# . exp(logfun) is increasing to the left of the peak and decreasing to the right of the peak -# . exp(logfun) can be zero or positive at zero -# . exp(logfun) tends to zero at infinity +#' @title Computes integral of a very peaked function, modified from the +#' SADISA package +#' @description computes the logarithm of the integral of exp(logfun) from 0 +#' to Inf under the following assumptions: +#' \itemize{ +#' \item{"exp(logfun)"}{has a single, sharply peaked maximum} +#' \item{"exp(logfun)"}{is increasing to the left of the peak and +#' decreasing to the right of the peak} +#' \item{"exp(logfun)"}{can be zero or positive at zero} +#' \item{"exp(logfun)"}{tends to zero at infinity} +#' } #' @param logfun the logarithm of the function to integrate #' @param xx the initial set of points on which to evaluate the function -#' @param xcutoff when the maximum has been found among the xx, this parameter sets the width of the interval to find the maximum in -#' @param ymaxthreshold sets the deviation allowed in finding the maximum among the xx +#' @param xcutoff when the maximum has been found among the xx, this parameter +#' sets the width of the interval to find the maximum in +#' @param ymaxthreshold sets the deviation allowed in finding the maximum +#' among the xx #' @param ... any arguments of the function to optimize #' @return the result of the integration -#' @references Haegeman, B. & R.S. Etienne (2017). A general sampling formula for community structure data. Methods in Ecology & Evolution. In press. +#' @references Haegeman, B. & R.S. Etienne (2017). A general sampling formula +#' for community structure data. Methods in Ecology & Evolution. In press. #' @keywords internal integral_peak <- function(logfun, - xx = seq(-20,20,2), + xx = seq(-20, 20, 2), xcutoff = 2, ymaxthreshold = 1E-12, - ...) { - fun <- function(x) exp(logfun(x, ...)) - #logQ <- log(stats::integrate(f = fun, lower = 0, upper = Inf, rel.tol = 1e-10, abs.tol = 1e-10)$value) + pars1, + pars2, + brts, + stac, + missnumspec, + methode, + abstolint, + reltolint, + verbose, + pick, + par_mean, + par_sd) { + fun <- function(x) { + exp(logfun(x, + pars1, + pars2, + brts, + stac, + missnumspec, + methode, + abstolint, + reltolint, + verbose, + pick, + par_mean, + par_sd)) + } - # 1 determine integrand peak - yy <- xx + logfun(exp(xx), ...) - yy[which(is.na(yy) | is.nan(yy))] <- -Inf - yymax <- max(yy) - if (yymax == -Inf) { - logQ <- -Inf - return(logQ) - } + # determine integrand peak + yy <- xx + logfun(exp(xx), + pars1, + pars2, + brts, + stac, + missnumspec, + methode, + abstolint, + reltolint, + verbose, + pick, + par_mean, + par_sd) + yy[which(is.na(yy) | is.nan(yy))] <- -Inf + yymax <- max(yy) + if (yymax == -Inf) { + logQ <- -Inf + return(logQ) + } - iimax <- which(yy >= (yymax - ymaxthreshold)) - xlft <- xx[iimax[1]] - xcutoff - xrgt <- xx[iimax[length(iimax)]] + xcutoff - optfun <- function(x) x + logfun(exp(x), ...) - optres <- stats::optimize(f = optfun, - interval = c(xlft,xrgt), - maximum = TRUE, - tol = 1e-10) - xmax <- optres$maximum - #ymax <- optres$objective + iimax <- which(yy >= (yymax - ymaxthreshold)) + xlft <- xx[iimax[1]] - xcutoff + xrgt <- xx[iimax[length(iimax)]] + xcutoff + optfun <- function(x) { + x + logfun(exp(x), + pars1, + pars2, + brts, + stac, + missnumspec, + methode, + abstolint, + reltolint, + verbose, + pick, + par_mean, + par_sd) + } + optres <- stats::optimize( + f = optfun, + interval = c(xlft, xrgt), + maximum = TRUE, + tol = 1e-10) + xmax <- optres$maximum - # 2 compute integral - logQ <- log(stats::integrate(f = fun, - lower = 0, - upper = exp(xmax), - abs.tol = 0)$value + - stats::integrate(f = fun, - lower = exp(xmax), - upper = Inf, - abs.tol = 0)$value) - - #intfun <- function(x) exp((x + logfun(exp(x), ...)) - ymax) - #corrfact <- stats::integrate(f = intfun, lower = -Inf, upper = xmax, rel.tol = 1e-10, abs.tol = 1e-10)$value + - # stats::integrate(f = intfun, lower = xmax, upper = Inf, rel.tol = 1e-10, abs.tol = 1e-10)$value - #logQ <- ymax + log(corrfact) + # compute integral + gamma_pars <- transform_gamma_pars( + par_mean = par_mean, + par_sd = par_sd) + if (gamma_pars$shape < 1) { + lower <- min(exp(xmax), 1E-3) + pars1[pick] <- lower / 2 + Q0 <- exp(DAISIE_loglik( + pars1 = pars1, + pars2 = pars2, + brts = brts, + stac = stac, + missnumspec = missnumspec, + methode = methode, + abstolint = abstolint, + reltolint = reltolint, + verbose = verbose)) * + pracma::gammainc(lower/gamma_pars$scale,gamma_pars$shape)["reginc"] + Q0 <- as.numeric(Q0) + } else { + lower <- 0 + Q0 <- 0 + } + Q1 <- stats::integrate(f = fun, + lower = lower, + upper = exp(xmax), + subdivisions = 1000, + rel.tol = 1e-10, + abs.tol = 1e-10) + Q2 <- stats::integrate(f = fun, + lower = exp(xmax), + upper = Inf, + subdivisions = 1000, + rel.tol = 1e-10, + abs.tol = 1e-10) + Q1 <- Q1$value + Q2 <- Q2$value + logQ <- log(Q0 + Q1 + Q2) return(logQ) } + +#' Transforms mean and standard deviation to shape and scale gamma parameters +#' +#' @param par_mean mean of the relaxed parameter +#' @param par_sd standard deviation of the relaxed parameter +#' +#' @keywords internal +#' +#' @return list to shape and scale parameters +transform_gamma_pars <- function(par_mean, par_sd) { + shape <- par_mean^2 / par_sd^2 + scale <- par_sd^2 / par_mean + return(list(shape = shape, + scale = scale)) +} diff --git a/R/DAISIE_make_archipelago.R b/R/DAISIE_make_archipelago.R index 149e4523..87f7efd4 100644 --- a/R/DAISIE_make_archipelago.R +++ b/R/DAISIE_make_archipelago.R @@ -49,7 +49,6 @@ DAISIE_make_archipelago <- function(archipelago, #' @param archipelago_data something #' @keywords internal #' @return something -#' @export DAISIE_make_global <- function(archipelago_list, M, phylo_data, archipelago_data) { global_object <- list() for (i in 1:length(archipelago_list)) { diff --git a/R/DAISIE_plot_input.R b/R/DAISIE_plot_input.R index 77a212f6..d430dc6d 100644 --- a/R/DAISIE_plot_input.R +++ b/R/DAISIE_plot_input.R @@ -26,10 +26,7 @@ #' t1$tip.label <- gsub("t", "t1.", t1$tip.label) #' t2 <- ape::rtree(3) #' t2$tip.label <- gsub("t", "t2.", t2$tip.label) -#' t3 <- DAISIE:::DAISIE_single_branch( -#' "t3.1", -#' edge.length = 4.6 -#' ) # tree with one species +#' t3 <- ape::rtree(2) #' trees <- list(t1, t2, t3) #' names(trees) <- c("A", "B", "C") #' @@ -61,7 +58,7 @@ #' } #' #' @author Raphael Scherrer (github.com/rscherrer) -#' +#' @importFrom magrittr %>% #' @export DAISIE_plot_input <- function( trees, age = NULL, tcols = NULL, metadata = NULL, mapping = NULL, diff --git a/R/DAISIE_rates.R b/R/DAISIE_rates.R index dcbaaf1c..b80dc0b8 100644 --- a/R/DAISIE_rates.R +++ b/R/DAISIE_rates.R @@ -298,17 +298,15 @@ get_ext_rate <- function(mu, island_spec = NULL) { x <- hyper_pars$x - if(is.null(trait_pars)){ + if (is.null(trait_pars)) { ext_rate <- max(0, mu * (A ^ -x) * num_spec, na.rm = TRUE) ext_rate <- min(ext_rate, extcutoff, na.rm = TRUE) # testit::assert(ext_rate >= 0) return(ext_rate) - }else{ ##species have two states + } else { ##species have two states if (is.matrix(island_spec) || is.null(island_spec)) { num_spec_trait1 <- length(which(island_spec[, 8] == "1")) num_spec_trait2 <- length(which(island_spec[, 8] == "2")) - } else if (is.numeric(island_spec)) { - stop("Different trait states cannot be separated,please transform to matrix form.") } ext_rate1 <- mu * num_spec_trait1 ext_rate2 <- trait_pars$ext_rate2 * num_spec_trait2 @@ -470,15 +468,11 @@ get_immig_rate <- function(gam, #' @family rates calculation get_trans_rate <- function(trait_pars, island_spec){ - if(is.null(trait_pars)){ - stop("Transition rate only calculate when exists more than one trait state.") #or trans_rate = NULL - }else{ + # Make function accept island_spec matrix or numeric if (is.matrix(island_spec) || is.null(island_spec)) { num_spec_trait1 <- length(which(island_spec[, 8] == "1")) num_spec_trait2 <- length(which(island_spec[, 8] == "2")) - } else if (is.numeric(island_spec)) { - stop("Different trait states cannot be separated,please transform to matrix form.") } trans_rate1 <- trait_pars$trans_rate * num_spec_trait1 trans_rate2 <- trait_pars$trans_rate2 * num_spec_trait2 @@ -489,7 +483,7 @@ get_trans_rate <- function(trait_pars, trans_list <- list(trans_rate1 = trans_rate1, trans_rate2 = trans_rate2) return(trans_list) - } + } #' Calculates when the next timestep will be. diff --git a/R/DAISIE_sim_constant_rate.R b/R/DAISIE_sim_constant_rate.R index 9aae2622..da0fd364 100644 --- a/R/DAISIE_sim_constant_rate.R +++ b/R/DAISIE_sim_constant_rate.R @@ -24,7 +24,7 @@ #' \itemize{ #' \item{\code{$island_age}: A numeric with the island age.} #' \item{\code{$not_present}: the number of mainland lineages that are not -#' present on the island. It is only present if only 1 typo of species is +#' present on the island. It is only present if only 1 type of species is #' simulated. Becomes \code{$not_present_type1}: the number of mainland #' lineages of type 1 that are not present on the island and #' \code{$not_present_type2}: the number of mainland lineages of type 2 @@ -83,7 +83,7 @@ #' clado_rate <- 0.5 #' ext_rate <- 0.2 #' carr_cap <- Inf -#' immig_rate <- 0.005 +#' immig_rate <- 0.05 #' ana_rate <- 1 #' sim_pars <- c(clado_rate, ext_rate, carr_cap, immig_rate, ana_rate) #' set.seed(1) @@ -253,6 +253,14 @@ DAISIE_sim_constant_rate <- DAISIE_sim <- function( } } } else if (length(pars) == 10) { + if (cond > 0) { + warning( + paste0( + "Conditioning on number of colonisations is not implemented for 2 + type simulations. Returning result with no conditioning instead." + ) + ) + } if (replicates_apply_type2 == TRUE) { island_replicates <- DAISIE_sim_min_type2( time = totaltime, diff --git a/R/DAISIE_sim_core_1_4.R b/R/DAISIE_sim_core_1_4.R deleted file mode 100644 index c8edac98..00000000 --- a/R/DAISIE_sim_core_1_4.R +++ /dev/null @@ -1,389 +0,0 @@ -#' Internal function of the DAISIE simulation -#' Taken from CRAN, commit https://github.com/richelbilderbeek/DAISIE/commit/c700b0fcf9e2c2b5d7248f02af7596fac5a2f573#diff-ddae7ad3ae2def3cb66ecf8a8a45cc41 -#' @param time simulated amount of time -#' @param mainland_n number of mainland species, that -#' is, the number of species that can potentially colonize the island. -#' If \code{\link{DAISIE_sim_constant_rate}()} uses a clade-specific diversity dependence, -#' this value is set to 1. -#' If \code{\link{DAISIE_sim_constant_rate}()} uses an island-specific diversity dependence, -#' this value is set to the number of mainland species. -#' @param pars a numeric vector: -#' \itemize{ -#' \item{[1]: cladogenesis rate} -#' \item{[2]: extinction rate} -#' \item{[3]: carrying capacity} -#' \item{[4]: immigration rate} -#' \item{[5]: anagenesis rate} -#' } -#' @keywords internal -#' @note This function produces an extra element per replicate when the -#' island is empty at time = 0. Functionally this has no effect on the -#' simulations, but care should be taken if using the length of objects to count -#' the number of species present on the island. -DAISIE_sim_core_1_4 = function(time, mainland_n, pars) -{ - lac = pars[1] - mu = pars[2] - K = pars[3] - gam = pars[4] - laa = pars[5] - - if(pars[4]==0) - { - stop('Rate of colonisation is zero. Island cannot be colonised.') - } - - timeval = 0 - - mainland_spec = seq(1,mainland_n,1) - maxspecID = mainland_n - - island_spec = c() - stt_table = matrix(ncol=4) - colnames(stt_table) = c("Time","nI","nA","nC") - stt_table[1,] = c(time,0,0,0) - - while(timeval < time) - { - n_island_species <- length(island_spec[,1]) - n_immigrants <- length(which(island_spec[,4] == "I")) - ext_rate <- DAISIE_calc_clade_ext_rate(ps_ext_rate = mu, n_species = n_island_species) - ana_rate <- DAISIE_calc_clade_ana_rate(ps_ana_rate = laa, n_immigrants = n_immigrants) - clado_rate <- DAISIE_calc_clade_clado_rate(ps_clado_rate = lac, n_species = n_island_species, carr_cap = K) - immig_rate <- DAISIE_calc_clade_imm_rate(ps_imm_rate = gam, n_island_species = n_island_species, n_mainland_species = mainland_n, carr_cap = K) - totalrate <- ext_rate + clado_rate + ana_rate + immig_rate - dt <- stats::rexp(1, totalrate) - timeval <- timeval + dt - possible_event <- sample(1:4,1,replace=FALSE,c(immig_rate,ext_rate,ana_rate,clado_rate)) - ############## - if(timeval <= time) - { - ########################################## - #IMMIGRATION - if(possible_event == 1) - { - colonist = DDD::sample2(mainland_spec,1) - - if(length(island_spec[,1]) != 0){isitthere = which(island_spec[,1] == colonist)} - - if(length(island_spec[,1]) == 0) {isitthere = c()} - - if(length(isitthere) == 0){island_spec = rbind(island_spec,c(colonist,colonist,timeval,"I",NA,NA,NA))} - - if(length(isitthere) != 0){ island_spec[isitthere,] = c(colonist,colonist,timeval,"I",NA,NA,NA)} - } - - ########################################## - #EXTINCTION - if(possible_event == 2) - { - extinct = DDD::sample2(1:length(island_spec[,1]),1) - #this chooses the row of species data to remove - - typeofspecies = island_spec[extinct,4] - - if(typeofspecies == "I") - { - island_spec = island_spec[-extinct,] - } - #remove immigrant - - if(typeofspecies == "A") - { - island_spec = island_spec[-extinct,] - } - #remove anagenetic - - if(typeofspecies == "C") - { - #remove cladogenetic - - #first find species with same ancestor AND arrival time - sisters = intersect(which(island_spec[,2] == island_spec[extinct,2]),which(island_spec[,3] == island_spec[extinct,3])) - survivors = sisters[which(sisters != extinct)] - - if(length(sisters) == 2) - { - #survivors status becomes anagenetic - island_spec[survivors,4] = "A" - island_spec[survivors,c(5,6)] = c(NA,NA) - island_spec[survivors,7] = "Clado_extinct" - island_spec = island_spec[-extinct,] - } - - if(length(sisters) >= 3) - { - numberofsplits = nchar(island_spec[extinct,5]) - - mostrecentspl = substring(island_spec[extinct,5],numberofsplits) - - if(mostrecentspl=="B") - { - sistermostrecentspl = "A" - } - if(mostrecentspl=="A") - { - sistermostrecentspl = "B" - } - - motiftofind = paste(substring(island_spec[extinct,5],1,numberofsplits-1),sistermostrecentspl,sep = "") - - possiblesister = survivors[which(substring(island_spec[survivors,5],1,numberofsplits) == motiftofind)] - - #different rules depending on whether a B or A is removed. B going extinct is simpler because it only - #carries a record of the most recent speciation - if(mostrecentspl == "A") - { - #change the splitting date of the sister species so that it inherits the early splitting that used to belong to A. - tochange = possiblesister[which(island_spec[possiblesister,6] == max(as.numeric(island_spec[possiblesister,6])))] - island_spec[tochange,6] = island_spec[extinct,6] - } - - #remove the offending A/B from these species - island_spec[possiblesister,5] = paste(substring(island_spec[possiblesister,5],1,numberofsplits - 1), - substring(island_spec[possiblesister,5],numberofsplits + 1, - nchar(island_spec[possiblesister,5])),sep = "") - island_spec = island_spec[-extinct,] - } - } - island_spec = rbind(island_spec) - } - - ########################################## - #ANAGENESIS - if(possible_event == 3) - { - immi_specs = which(island_spec[,4] == "I") - - #we only allow immigrants to undergo anagenesis - if(length(immi_specs) == 1) - { - anagenesis = immi_specs - } - if(length(immi_specs) > 1) - { - anagenesis = DDD::sample2(immi_specs,1) - } - - maxspecID = maxspecID + 1 - island_spec[anagenesis,4] = "A" - island_spec[anagenesis,1] = maxspecID - island_spec[anagenesis,7] = "Immig_parent" - } - - ########################################## - #CLADOGENESIS - this splits species into two new species - both of which receive - if(possible_event == 4) - { - tosplit = DDD::sample2(1:length(island_spec[,1]),1) - - #if the species that speciates is cladogenetic - if(island_spec[tosplit,4] == "C") - { - #for daughter A - - island_spec[tosplit,4] = "C" - island_spec[tosplit,1] = maxspecID + 1 - oldstatus = island_spec[tosplit,5] - island_spec[tosplit,5] = paste(oldstatus,"A",sep = "") - #island_spec[tosplit,6] = timeval - island_spec[tosplit,7] = NA - - #for daughter B - island_spec = rbind(island_spec,c(maxspecID + 2,island_spec[tosplit,2],island_spec[tosplit,3], - "C",paste(oldstatus,"B",sep = ""),timeval,NA)) - - maxspecID = maxspecID + 2 - } else { - #if the species that speciates is not cladogenetic - - #for daughter A - - island_spec[tosplit,4] = "C" - island_spec[tosplit,1] = maxspecID + 1 - island_spec[tosplit,5] = "A" - island_spec[tosplit,6] = island_spec[tosplit,3] - island_spec[tosplit,7] = NA - - #for daughter B - island_spec = rbind(island_spec,c(maxspecID + 2,island_spec[tosplit,2],island_spec[tosplit,3],"C","B",timeval,NA)) - - maxspecID = maxspecID + 2 - } - } - } - stt_table = rbind(stt_table,c(time - timeval,length(which(island_spec[,4] == "I")), - length(which(island_spec[,4] == "A")),length(which(island_spec[,4] == "C")))) - } - - stt_table[nrow(stt_table),1] = 0 - ############# - ### if there are no species on the island branching_times = island_age, stac = 0, missing_species = 0 - if(length(island_spec[,1])==0) - { - island = list(stt_table = stt_table, branching_times = time, stac = 0, missing_species = 0) } - else{ - - cnames <- c("Species","Mainland Ancestor","Colonisation time (BP)", - "Species type","branch_code","branching time (BP)","Anagenetic_origin") - colnames(island_spec) <- cnames - - ### set ages as counting backwards from present - island_spec[,"branching time (BP)"] = time - as.numeric(island_spec[,"branching time (BP)"]) - island_spec[,"Colonisation time (BP)"] = time - as.numeric(island_spec[,"Colonisation time (BP)"]) - - if(mainland_n==1) { - island <- DAISIE_ONEcolonist(time,island_spec,stt_table) - } - - if(mainland_n>1) { - - ### number of colonists present - colonists_present = sort(as.numeric(unique(island_spec[,'Mainland Ancestor']))) - number_colonists_present = length(colonists_present) - - island_clades_info<-list() - - for (i in 1:number_colonists_present) { - - subset_island<-island_spec[which(island_spec[,'Mainland Ancestor']==colonists_present[i]),] - - if(!is.matrix(subset_island)) { subset_island<-rbind(subset_island[1:7]) - colnames(subset_island) = cnames} - - island_clades_info[[i]]<-DAISIE_ONEcolonist(time, - island_spec =subset_island, - stt_table = NULL) - island_clades_info[[i]]$stt_table<-NULL - - } - - island = list(stt_table = stt_table, taxon_list = island_clades_info) - - } - } - return(island) -} - -#' Calculate the clade-wide extinction rate -#' @param ps_ext_rate per species extinction rate -#' @param n_species number of species in that clade -#' @return the clade's extinction rate -#' @author Richel J.C. Bilderbeek -#' @examples -#' testit::assert( -#' DAISIE:::DAISIE_calc_clade_ext_rate( -#' ps_ext_rate = 0.2, -#' n_species = 4 -#' ) == 0.8 -#' ) -#' @keywords internal -DAISIE_calc_clade_ext_rate <- function(ps_ext_rate, n_species) { - testit::assert(ps_ext_rate >= 0.0) - testit::assert(n_species >= 0) - ps_ext_rate * n_species -} - -#' Calculate the clade-wide effective anagenesis rate. -#' With 'effective', this means that if an immigrant -#' undergoes anagenesis, it will become a new species. -#' Would such a species undergo anagenesis again, no net new -#' species is created; the species only gets renamed -#' @param ps_ana_rate per species anagensis rate -#' @param n_immigrants number of immigrants in that clade -#' @return the clade's effective anagenesis rate -#' @author Richel J.C. Bilderbeek -#' @examples -#' testit::assert( -#' DAISIE:::DAISIE_calc_clade_ana_rate( -#' ps_ana_rate = 0.3, -#' n_immigrants = 5 -#' ) == 1.5 -#' ) -#' @keywords internal -DAISIE_calc_clade_ana_rate <- function(ps_ana_rate, n_immigrants) { - testit::assert(ps_ana_rate >= 0.0) - testit::assert(n_immigrants >= 0) - ps_ana_rate * n_immigrants -} - -#' Calculate the clade-wide cladogenesis rate. -#' @param ps_clado_rate per species cladogenesis rate -#' @param n_species number of species in that clade -#' @param carr_cap carrying capacity, number of species this clade will -#' grow to -#' @return the clade's cladogenesis rate, which is at least zero. This -#' rate will be zero if there are more species than the carrying capacity -#' allows for -#' @note For clade-specific carrying capacity, -#' each clade is simulated seperately in \code{\link{DAISIE_sim}} -#' @author Richel J.C. Bilderbeek -#' @examples -#' testit::assert( -#' DAISIE:::DAISIE_calc_clade_clado_rate( -#' ps_clado_rate = 0.2, -#' n_species = 5, -#' carr_cap = 10 -#' ) == 0.5 -#' ) -#' testit::assert( -#' DAISIE:::DAISIE_calc_clade_clado_rate( -#' ps_clado_rate = 0.2, -#' n_species = 2, -#' carr_cap = 1 -#' ) == 0.0 -#' ) -#' @keywords internal -DAISIE_calc_clade_clado_rate <- function(ps_clado_rate, n_species, carr_cap) { - testit::assert(ps_clado_rate >= 0.0) - testit::assert(n_species >= 0) - testit::assert(carr_cap >= 0) - return(max( - 0.0, - n_species * ps_clado_rate * (1.0 - (n_species / carr_cap)) - )) -} - -#' Calculate the clade-wide immigration rate. -#' @param ps_imm_rate per species immigration rate -#' @param n_island_species number of species in that clade on the island -#' @param n_mainland_species number of species in that clade on the mainland -#' @param carr_cap carrying capacity, number of species this clade will -#' grow to -#' @return the clade's immigration rate, which is at least zero. This -#' rate will be zero if there are more species than the carrying capacity -#' allows for -#' @author Richel J.C. Bilderbeek -#' @examples -#' testit::assert( -#' DAISIE:::DAISIE_calc_clade_imm_rate( -#' ps_imm_rate = 0.1, -#' n_island_species = 5, -#' n_mainland_species = 2, -#' carr_cap = 10 -#' ) == 0.1 -#' ) -#' testit::assert( -#' DAISIE:::DAISIE_calc_clade_imm_rate( -#' ps_imm_rate = 0.1, -#' n_island_species = 5, -#' n_mainland_species = 2, -#' carr_cap = 1 -#' ) == 0.0 -#' ) -#' @keywords internal -DAISIE_calc_clade_imm_rate <- function( - ps_imm_rate, - n_island_species, - n_mainland_species, - carr_cap -) { - testit::assert(ps_imm_rate >= 0.0) - testit::assert(n_island_species >= 0) - testit::assert(n_mainland_species >= 0) - testit::assert(carr_cap >= 0) - return(max( - 0.0, - n_mainland_species * ps_imm_rate * (1.0 - (n_island_species / carr_cap)) - )) -} diff --git a/R/DAISIE_sim_core_1_4a.R b/R/DAISIE_sim_core_1_4a.R deleted file mode 100644 index b17f2e73..00000000 --- a/R/DAISIE_sim_core_1_4a.R +++ /dev/null @@ -1,268 +0,0 @@ -#' Internal function of the DAISIE simulation -#' Taken from CRAN, commit https://github.com/richelbilderbeek/DAISIE/commit/c700b0fcf9e2c2b5d7248f02af7596fac5a2f573#diff-ddae7ad3ae2def3cb66ecf8a8a45cc41 -#' @param time simulated amount of time -#' @param mainland_n number of mainland species, that -#' is, the number of species that can potentially colonize the island. -#' If \code{\link{DAISIE_sim_constant_rate}()} uses a clade-specific diversity dependence, -#' this value is set to 1. -#' If \code{\link{DAISIE_sim_constant_rate}()} uses an island-specific diversity dependence, -#' this value is set to the number of mainland species. -#' @param pars a numeric vector: -#' \itemize{ -#' \item{[1]: cladogenesis rate} -#' \item{[2]: extinction rate} -#' \item{[3]: carrying capacity} -#' \item{[4]: immigration rate} -#' \item{[5]: anagenesis rate} -#' } -#' @keywords internal -#' @note This function produces an extra element per replicate when the -#' island is empty at time = 0. Functionally this has no effect on the -#' simulations, but care should be taken if using the length of objects to count -#' the number of species present on the island. -DAISIE_sim_core_1_4a <- function(time, mainland_n, pars) -{ - lac = pars[1] - mu = pars[2] - K = pars[3] - gam = pars[4] - laa = pars[5] - - if(pars[4]==0) - { - stop('Rate of colonisation is zero. Island cannot be colonised.') - } - - timeval = 0 - - mainland_spec = seq(1,mainland_n,1) - maxspecID = mainland_n - - island_spec = c() - stt_table = matrix(ncol=4) - colnames(stt_table) = c("Time","nI","nA","nC") - stt_table[1,] = c(time,0,0,0) - - while(timeval < time) - { - n_island_species <- length(island_spec[,1]) - n_immigrants <- length(which(island_spec[,4] == "I")) - ext_rate <- DAISIE_calc_clade_ext_rate(ps_ext_rate = mu, n_species = n_island_species) - ana_rate <- DAISIE_calc_clade_ana_rate(ps_ana_rate = laa, n_immigrants = n_immigrants) - clado_rate <- DAISIE_calc_clade_clado_rate(ps_clado_rate = lac, n_species = n_island_species, carr_cap = K) - immig_rate <- DAISIE_calc_clade_imm_rate(ps_imm_rate = gam, n_island_species = n_island_species, n_mainland_species = mainland_n, carr_cap = K) - totalrate <- ext_rate + clado_rate + ana_rate + immig_rate - dt <- stats::rexp(1, totalrate) - timeval <- timeval + dt - possible_event <- sample(1:4,1,replace=FALSE,c(immig_rate,ext_rate,ana_rate,clado_rate)) - ############## - if(timeval <= time) - { - ########################################## - #IMMIGRATION - if(possible_event == 1) - { - colonist = DDD::sample2(mainland_spec,1) - - if(length(island_spec[,1]) != 0){isitthere = which(island_spec[,1] == colonist)} - - if(length(island_spec[,1]) == 0) {isitthere = c()} - - if(length(isitthere) == 0){island_spec = rbind(island_spec,c(colonist,colonist,timeval,"I",NA,NA,NA))} - - if(length(isitthere) != 0){ island_spec[isitthere,] = c(colonist,colonist,timeval,"I",NA,NA,NA)} - } - - ########################################## - #EXTINCTION - if(possible_event == 2) - { - extinct = DDD::sample2(1:length(island_spec[,1]),1) - #this chooses the row of species data to remove - - typeofspecies = island_spec[extinct,4] - - if(typeofspecies == "I") - { - island_spec = island_spec[-extinct,] - } - #remove immigrant - - if(typeofspecies == "A") - { - island_spec = island_spec[-extinct,] - } - #remove anagenetic - - if(typeofspecies == "C") - { - #remove cladogenetic - - #first find species with same ancestor AND arrival time - sisters = intersect(which(island_spec[,2] == island_spec[extinct,2]),which(island_spec[,3] == island_spec[extinct,3])) - survivors = sisters[which(sisters != extinct)] - - if(length(sisters) == 2) - { - #survivors status becomes anagenetic - island_spec[survivors,4] = "A" - island_spec[survivors,c(5,6)] = c(NA,NA) - island_spec[survivors,7] = "Clado_extinct" - island_spec = island_spec[-extinct,] - } - - if(length(sisters) >= 3) - { - numberofsplits = nchar(island_spec[extinct,5]) - - mostrecentspl = substring(island_spec[extinct,5],numberofsplits) - - if(mostrecentspl=="B") - { - sistermostrecentspl = "A" - } - if(mostrecentspl=="A") - { - sistermostrecentspl = "B" - } - - motiftofind = paste(substring(island_spec[extinct,5],1,numberofsplits-1),sistermostrecentspl,sep = "") - - possiblesister = survivors[which(substring(island_spec[survivors,5],1,numberofsplits) == motiftofind)] - - #different rules depending on whether a B or A is removed. B going extinct is simpler because it only - #carries a record of the most recent speciation - if(mostrecentspl == "A") - { - #change the splitting date of the sister species so that it inherits the early splitting that used to belong to A. - # Bug fix here thanks to Nadiah Kristensen: max -> min - tochange = possiblesister[which(island_spec[possiblesister,6] == min(as.numeric(island_spec[possiblesister,6])))] - island_spec[tochange,6] = island_spec[extinct,6] - } - - #remove the offending A/B from these species - island_spec[possiblesister,5] = paste(substring(island_spec[possiblesister,5],1,numberofsplits - 1), - substring(island_spec[possiblesister,5],numberofsplits + 1, - nchar(island_spec[possiblesister,5])),sep = "") - island_spec = island_spec[-extinct,] - } - } - island_spec = rbind(island_spec) - } - - ########################################## - #ANAGENESIS - if(possible_event == 3) - { - immi_specs = which(island_spec[,4] == "I") - - #we only allow immigrants to undergo anagenesis - if(length(immi_specs) == 1) - { - anagenesis = immi_specs - } - if(length(immi_specs) > 1) - { - anagenesis = DDD::sample2(immi_specs,1) - } - - maxspecID = maxspecID + 1 - island_spec[anagenesis,4] = "A" - island_spec[anagenesis,1] = maxspecID - island_spec[anagenesis,7] = "Immig_parent" - } - - ########################################## - #CLADOGENESIS - this splits species into two new species - both of which receive - if(possible_event == 4) - { - tosplit = DDD::sample2(1:length(island_spec[,1]),1) - - #if the species that speciates is cladogenetic - if(island_spec[tosplit,4] == "C") - { - #for daughter A - - island_spec[tosplit,4] = "C" - island_spec[tosplit,1] = maxspecID + 1 - oldstatus = island_spec[tosplit,5] - island_spec[tosplit,5] = paste(oldstatus,"A",sep = "") - #island_spec[tosplit,6] = timeval - island_spec[tosplit,7] = NA - - #for daughter B - island_spec = rbind(island_spec,c(maxspecID + 2,island_spec[tosplit,2],island_spec[tosplit,3], - "C",paste(oldstatus,"B",sep = ""),timeval,NA)) - - maxspecID = maxspecID + 2 - } else { - #if the species that speciates is not cladogenetic - - #for daughter A - - island_spec[tosplit,4] = "C" - island_spec[tosplit,1] = maxspecID + 1 - island_spec[tosplit,5] = "A" - island_spec[tosplit,6] = island_spec[tosplit,3] - island_spec[tosplit,7] = NA - - #for daughter B - island_spec = rbind(island_spec,c(maxspecID + 2,island_spec[tosplit,2],island_spec[tosplit,3],"C","B",timeval,NA)) - - maxspecID = maxspecID + 2 - } - } - } - stt_table = rbind(stt_table,c(time - timeval,length(which(island_spec[,4] == "I")), - length(which(island_spec[,4] == "A")),length(which(island_spec[,4] == "C")))) - } - - stt_table[nrow(stt_table),1] = 0 - ############# - ### if there are no species on the island branching_times = island_age, stac = 0, missing_species = 0 - if(length(island_spec[,1])==0) - { - island = list(stt_table = stt_table, branching_times = time, stac = 0, missing_species = 0) } - else{ - - cnames <- c("Species","Mainland Ancestor","Colonisation time (BP)", - "Species type","branch_code","branching time (BP)","Anagenetic_origin") - colnames(island_spec) <- cnames - - ### set ages as counting backwards from present - island_spec[,"branching time (BP)"] = time - as.numeric(island_spec[,"branching time (BP)"]) - island_spec[,"Colonisation time (BP)"] = time - as.numeric(island_spec[,"Colonisation time (BP)"]) - - if(mainland_n==1) { - island <- DAISIE_ONEcolonist(time,island_spec,stt_table) - } - - if(mainland_n>1) { - - ### number of colonists present - colonists_present = sort(as.numeric(unique(island_spec[,'Mainland Ancestor']))) - number_colonists_present = length(colonists_present) - - island_clades_info<-list() - - for (i in 1:number_colonists_present) { - - subset_island<-island_spec[which(island_spec[,'Mainland Ancestor']==colonists_present[i]),] - - if(!is.matrix(subset_island)) { subset_island<-rbind(subset_island[1:7]) - colnames(subset_island) = cnames} - - island_clades_info[[i]]<-DAISIE_ONEcolonist(time, - island_spec=subset_island, - stt_table=NULL) - island_clades_info[[i]]$stt_table<-NULL - - } - - island = list(stt_table = stt_table, taxon_list = island_clades_info) - - } - } - return(island) -} - diff --git a/R/DAISIE_sim_core_1_5.R b/R/DAISIE_sim_core_1_5.R deleted file mode 100644 index 2f29775d..00000000 --- a/R/DAISIE_sim_core_1_5.R +++ /dev/null @@ -1,265 +0,0 @@ -# This function produces an extra element per replicate when the -# island is empty at time = 0. Functionally this has no effect on the -# simulations, but care should be taken if using the length of objects to count -# the number of species present on the island. -DAISIE_sim_core_1_5 <- function(time,mainland_n,pars) -{ - totaltime <- time - lac <- pars[1] - mu <- pars[2] - K <- pars[3] - gam <- pars[4] - laa <- pars[5] - - if(pars[4] == 0) - { - stop('Rate of colonisation is zero. Island cannot be colonised.') - } - - timeval <- 0 - - mainland_spec <- seq(1,mainland_n,1) - maxspecID <- mainland_n - - island_spec = c() - stt_table <- matrix(ncol = 4) - colnames(stt_table) <- c("Time","nI","nA","nC") - stt_table[1,] <- c(totaltime,0,0,0) - - while(timeval < totaltime) - { - ext_rate <- mu * length(island_spec[,1]) - ana_rate <- laa * length(which(island_spec[,4] == "I")) - clado_rate <- max(c(length(island_spec[,1]) * (lac * (1 -length(island_spec[,1])/K)),0),na.rm = T) - immig_rate <- max(c(mainland_n * gam * (1 - length(island_spec[,1])/K),0),na.rm = T) - - totalrate <- ext_rate + clado_rate + ana_rate + immig_rate - dt <- stats::rexp(1, totalrate) - - timeval <- timeval + dt - - possible_event <- sample(1:4,1,replace = FALSE,c(immig_rate,ext_rate,ana_rate,clado_rate)) - - ############## - if(timeval <= totaltime) - { - new_state <- DAISIE_sim_update_state_1_5(possible_event,maxspecID,mainland_spec,island_spec,timeval) - island_spec <- new_state$island_spec - maxspecID <- new_state$maxspecID - } - stt_table <- rbind(stt_table, - c(totaltime - timeval, - length(which(island_spec[,4] == "I")), - length(which(island_spec[,4] == "A")), - length(which(island_spec[,4] == "C")) - ) - ) - } - - stt_table[nrow(stt_table),1] <- 0 - - ############# - ### if there are no species on the island branching_times = island_age, stac = 0, missing_species = 0 - if(length(island_spec[,1]) == 0) - { - island <- list(stt_table = stt_table, branching_times = totaltime, stac = 0, missing_species = 0) - } else - { - cnames <- c("Species","Mainland Ancestor","Colonisation time (BP)", - "Species type","branch_code","branching time (BP)","Anagenetic_origin") - colnames(island_spec) <- cnames - - ### set ages as counting backwards from present - island_spec[,"branching time (BP)"] <- totaltime - as.numeric(island_spec[,"branching time (BP)"]) - island_spec[,"Colonisation time (BP)"] <- totaltime - as.numeric(island_spec[,"Colonisation time (BP)"]) - - if(mainland_n == 1) - { - island <- DAISIE_ONEcolonist(totaltime,island_spec,stt_table) - } else if(mainland_n > 1) - { - ### number of colonists present - colonists_present <- sort(as.numeric(unique(island_spec[,'Mainland Ancestor']))) - number_colonists_present <- length(colonists_present) - - island_clades_info <- list() - for(i in 1:number_colonists_present) - { - subset_island <- island_spec[which(island_spec[,'Mainland Ancestor']==colonists_present[i]),] - if(!is.matrix(subset_island)) - { - subset_island <- rbind(subset_island[1:7]) - colnames(subset_island) <- cnames - } - island_clades_info[[i]] <- DAISIE_ONEcolonist(totaltime,island_spec=subset_island,stt_table=NULL) - island_clades_info[[i]]$stt_table <- NULL - } - island <- list(stt_table = stt_table, taxon_list = island_clades_info) - } - } - return(island) -} - -DAISIE_sim_update_state_1_5 <- function(possible_event,maxspecID,mainland_spec,island_spec,timeval) -{ - ########################################## - #IMMIGRATION - if(possible_event == 1) - { - colonist = DDD::sample2(mainland_spec,1) - - if(length(island_spec[,1]) != 0) - { - isitthere = which(island_spec[,1] == colonist) - } else - { - isitthere = c() - } - - if(length(isitthere) == 0) - { - island_spec = rbind(island_spec,c(colonist,colonist,timeval,"I",NA,NA,NA)) - } - - if(length(isitthere) != 0) - { - island_spec[isitthere,] = c(colonist,colonist,timeval,"I",NA,NA,NA) - } - } - - ########################################## - #EXTINCTION - if(possible_event == 2) - { - extinct = DDD::sample2(1:length(island_spec[,1]),1) - #this chooses the row of species data to remove - - typeofspecies = island_spec[extinct,4] - - if(typeofspecies == "I") - { - island_spec = island_spec[-extinct,] - } else - #remove immigrant - - if(typeofspecies == "A") - { - island_spec = island_spec[-extinct,] - } else - #remove anagenetic - - if(typeofspecies == "C") - { - #remove cladogenetic - - #first find species with same ancestor AND arrival time - sisters = intersect(which(island_spec[,2] == island_spec[extinct,2]),which(island_spec[,3] == island_spec[extinct,3])) - survivors = sisters[which(sisters != extinct)] - - if(length(sisters) == 2) - { - #survivors status becomes anagenetic - island_spec[survivors,4] = "A" - island_spec[survivors,c(5,6)] = c(NA,NA) - island_spec[survivors,7] = "Clado_extinct" - island_spec = island_spec[-extinct,] - } else if(length(sisters) >= 3) - { - numberofsplits = nchar(island_spec[extinct,5]) - - mostrecentspl = substring(island_spec[extinct,5],numberofsplits) - - if(mostrecentspl == "B") - { - sistermostrecentspl = "A" - } else if(mostrecentspl == "A") - { - sistermostrecentspl = "B" - } - - motiftofind = paste(substring(island_spec[extinct,5],1,numberofsplits-1),sistermostrecentspl,sep = "") - - possiblesister = survivors[which(substring(island_spec[survivors,5],1,numberofsplits) == motiftofind)] - - #different rules depending on whether a B or A is removed. B going extinct is simpler because it only - #carries a record of the most recent speciation - if(mostrecentspl == "A") - { - #change the splitting date of the sister species so that it inherits the early splitting that used to belong to A. - tochange = possiblesister[which(island_spec[possiblesister,6] == min(as.numeric(island_spec[possiblesister,6])))] - island_spec[tochange,6] = island_spec[extinct,6] - } - - #remove the offending A/B from these species - island_spec[possiblesister,5] = paste(substring(island_spec[possiblesister,5],1,numberofsplits - 1), - substring(island_spec[possiblesister,5],numberofsplits + 1, - nchar(island_spec[possiblesister,5])),sep = "") - island_spec = island_spec[-extinct,] - } - } - island_spec = rbind(island_spec) - } - - ########################################## - #ANAGENESIS - if(possible_event == 3) - { - immi_specs = which(island_spec[,4] == "I") - - #we only allow immigrants to undergo anagenesis - if(length(immi_specs) == 1) - { - anagenesis = immi_specs - } else if(length(immi_specs) > 1) - { - anagenesis = DDD::sample2(immi_specs,1) - } - - maxspecID = maxspecID + 1 - island_spec[anagenesis,4] = "A" - island_spec[anagenesis,1] = maxspecID - island_spec[anagenesis,7] = "Immig_parent" - } - - ########################################## - #CLADOGENESIS - this splits species into two new species - both of which receive - if(possible_event == 4) - { - tosplit = DDD::sample2(1:length(island_spec[,1]),1) - - #if the species that speciates is cladogenetic - if(island_spec[tosplit,4] == "C") - { - #for daughter A - - island_spec[tosplit,4] = "C" - island_spec[tosplit,1] = maxspecID + 1 - oldstatus = island_spec[tosplit,5] - island_spec[tosplit,5] = paste(oldstatus,"A",sep = "") - #island_spec[tosplit,6] = timeval - island_spec[tosplit,7] = NA - - #for daughter B - island_spec = rbind(island_spec,c(maxspecID + 2,island_spec[tosplit,2],island_spec[tosplit,3], - "C",paste(oldstatus,"B",sep = ""),timeval,NA)) - - maxspecID = maxspecID + 2 - } else { - #if the species that speciates is not cladogenetic - - #for daughter A - - island_spec[tosplit,4] = "C" - island_spec[tosplit,1] = maxspecID + 1 - island_spec[tosplit,5] = "A" - island_spec[tosplit,6] = island_spec[tosplit,3] - island_spec[tosplit,7] = NA - - #for daughter B - island_spec = rbind(island_spec,c(maxspecID + 2,island_spec[tosplit,2],island_spec[tosplit,3],"C","B",timeval,NA)) - - maxspecID = maxspecID + 2 - } - } - return(list(island_spec = island_spec,maxspecID = maxspecID)) -} diff --git a/R/DAISIE_sim_core_trait_dependent.R b/R/DAISIE_sim_core_trait_dependent.R index d4f62d29..d0f79282 100644 --- a/R/DAISIE_sim_core_trait_dependent.R +++ b/R/DAISIE_sim_core_trait_dependent.R @@ -6,7 +6,6 @@ DAISIE_sim_core_trait_dependent <- function( time, mainland_n, pars, - nonoceanic_pars = c(0, 0), island_ontogeny = 0, sea_level = 0, hyper_pars, @@ -32,10 +31,6 @@ DAISIE_sim_core_trait_dependent <- function( colonisation is zero. Island cannot be colonised.") } - nonoceanic_sample <- DAISIE_nonoceanic_spec( - prob_samp = nonoceanic_pars[1], - prob_nonend = nonoceanic_pars[2], - mainland_n = mainland_n) #### what is the useage of maxspecID and how to set M1 and M2??#### @@ -52,8 +47,6 @@ DAISIE_sim_core_trait_dependent <- function( island_spec <- c() stt_table <- matrix(ncol = 7) colnames(stt_table) <- c("Time","nI","nA","nC","nI2","nA2","nC2") - init_nonend_spec <- nonoceanic_sample$init_nonend_spec - init_end_spec <- nonoceanic_sample$init_end_spec stt_table[1,] <- c(totaltime,0,0,0,0,0,0) # spec_tables <- list(stt_table = stt_table, # init_nonend_spec = init_nonend_spec, diff --git a/R/DAISIE_sim_relaxed_rate.R b/R/DAISIE_sim_relaxed_rate.R index 74771a0d..990f77c2 100644 --- a/R/DAISIE_sim_relaxed_rate.R +++ b/R/DAISIE_sim_relaxed_rate.R @@ -18,7 +18,7 @@ #' \itemize{ #' \item{\code{$island_age}: A numeric with the island age.} #' \item{\code{$not_present}: the number of mainland lineages that are not -#' present on the island. It is only present if only 1 typo of species is +#' present on the island. It is only present if only 1 type of species is #' simulated. Becomes \code{$not_present_type1}: the number of mainland #' lineages of type 1 that are not present on the island and #' \code{$not_present_type2}: the number of mainland lineages of type 2 diff --git a/R/DAISIE_sim_trait_dependent.R b/R/DAISIE_sim_trait_dependent.R index b229ca78..e86a76c2 100644 --- a/R/DAISIE_sim_trait_dependent.R +++ b/R/DAISIE_sim_trait_dependent.R @@ -64,7 +64,6 @@ DAISIE_sim_trait_dependent <- function( pars, replicates, divdepmodel = "CS", - nonoceanic_pars = c(0, 0), num_guilds = NULL, sample_freq = 25, plot_sims = TRUE, @@ -111,7 +110,6 @@ DAISIE_sim_trait_dependent <- function( time = totaltime, mainland_n = M, pars = pars, - nonoceanic_pars = nonoceanic_pars, island_ontogeny = island_ontogeny, sea_level = sea_level, hyper_pars = hyper_pars, @@ -160,7 +158,6 @@ DAISIE_sim_trait_dependent <- function( time = totaltime, mainland_n = 0, pars = pars, - nonoceanic_pars = nonoceanic_pars, island_ontogeny = island_ontogeny, sea_level = sea_level, hyper_pars = hyper_pars, @@ -184,7 +181,6 @@ DAISIE_sim_trait_dependent <- function( time = totaltime, mainland_n = 1, pars = pars, - nonoceanic_pars = nonoceanic_pars, island_ontogeny = island_ontogeny, sea_level = sea_level, hyper_pars = hyper_pars, @@ -207,7 +203,6 @@ DAISIE_sim_trait_dependent <- function( time = totaltime, mainland_n = 0, pars = pars, - nonoceanic_pars = nonoceanic_pars, island_ontogeny = island_ontogeny, sea_level = sea_level, hyper_pars = hyper_pars, @@ -252,7 +247,6 @@ DAISIE_sim_trait_dependent <- function( time = totaltime, mainland_n = guild_size, pars = pars, - nonoceanic_pars = nonoceanic_pars, island_ontogeny = island_ontogeny, sea_level = sea_level, hyper_pars = hyper_pars, diff --git a/R/DAISIE_single_branch.R b/R/DAISIE_single_branch.R deleted file mode 100644 index 43997bf7..00000000 --- a/R/DAISIE_single_branch.R +++ /dev/null @@ -1,26 +0,0 @@ -#' Single-branch phylogenetic tree -#' -#' @param tip.label Name of the unique tip -#' @param edge.length Length of the unique edge -#' -#' @return A phylogenetic tree in `phylo` format. -#' -#' @examples -#' -#' # A tree with one species with a 15Myr-old stem -#' DAISIE:::DAISIE_single_branch("some species", edge.length = 15) -#' -#' @author Raphael Scherrer (github.com/rscherrer) -#' -#' @keywords internal -# Function to display a single branch -DAISIE_single_branch <- function(tip.label = "t1", edge.length = 1) { - tree <- list( - edge = matrix(c(2, 1), 1, 2), - tip.label = tip.label, - edge.length = edge.length, - Nnode = 1 - ) - class(tree) <- "phylo" - tree -} diff --git a/R/RcppExports.R b/R/RcppExports.R new file mode 100644 index 00000000..b45ddd00 --- /dev/null +++ b/R/RcppExports.R @@ -0,0 +1,11 @@ +# Generated by using Rcpp::compileAttributes() -> do not edit by hand +# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 + +#' @export daisie_odeint_iw +NULL + +#' Driver for the boost::odeint solver +#' +#' @name daisie_odeint_iw +NULL + diff --git a/R/utils-pipe.R b/R/utils-pipe.R deleted file mode 100644 index e79f3d80..00000000 --- a/R/utils-pipe.R +++ /dev/null @@ -1,11 +0,0 @@ -#' Pipe operator -#' -#' See \code{magrittr::\link[magrittr:pipe]{\%>\%}} for details. -#' -#' @name %>% -#' @rdname pipe -#' @keywords internal -#' @export -#' @importFrom magrittr %>% -#' @usage lhs \%>\% rhs -NULL diff --git a/README.md b/README.md index 84c2cea0..ebf07b7d 100644 --- a/README.md +++ b/README.md @@ -3,22 +3,26 @@ [![CRAN_Status_Badge](http://www.r-pkg.org/badges/version/DAISIE)](https://cran.r-project.org/package=DAISIE) [![](http://cranlogs.r-pkg.org/badges/grand-total/DAISIE)]( https://CRAN.R-project.org/package=DAISIE) [![](http://cranlogs.r-pkg.org/badges/DAISIE)](https://CRAN.R-project.org/package=DAISIE) -![GitHub release (latest by date)](https://img.shields.io/github/v/release/rsetienne/DAISIE) +![GitHub R package version](https://img.shields.io/github/r-package/v/rsetienne/DAISIE) +[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.4054058.svg)](https://doi.org/10.5281/zenodo.4054058) -Branch|[Travis](https://travis-ci.org)|[Codecov](https://www.codecov.io) +Branch|![GHA logo](pics/github_actions_logo.png)|[![Codecov logo](pics/Codecov.png)](https://www.codecov.io) ---|---|--- -`master`|[![Build Status](https://travis-ci.org/rsetienne/DAISIE.svg?branch=master)](https://travis-ci.org/rsetienne/DAISIE)|[![codecov.io](https://codecov.io/github/rsetienne/DAISIE/coverage.svg?branch=master)](https://codecov.io/github/rsetienne/DAISIE/branch/master) -`develop`|[![Build Status](https://travis-ci.org/rsetienne/DAISIE.svg?branch=develop)](https://travis-ci.org/rsetienne/DAISIE)|[![codecov.io](https://codecov.io/github/rsetienne/DAISIE/coverage.svg?branch=develop)](https://codecov.io/github/rsetienne/DAISIE/branch/develop) +`master`|[![R build status](https://github.com/rsetienne/DAISIE/workflows/R-CMD-check/badge.svg?branch=master)](https://github.com/rsetienne/DAISIE/actions)|[![codecov.io](https://codecov.io/github/rsetienne/DAISIE/coverage.svg?branch=master)](https://codecov.io/github/rsetienne/DAISIE/branch/master) +`develop`|[![R build status](https://github.com/rsetienne/DAISIE/workflows/R-CMD-check/badge.svg?branch=develop)](https://github.com/rsetienne/DAISIE/actions)|[![codecov.io](https://codecov.io/github/rsetienne/DAISIE/coverage.svg?branch=develop)](https://codecov.io/github/rsetienne/DAISIE/branch/develop) ## Installing DAISIE +**N.B.: MacOS users may experience issues when installing DAISIE, especially when on MacOS Big Sur. If that is you case, please see [here](doc/DAISIE_macOS.md) for detailed installation instructions.** + The DAISIE package has a stable version on [CRAN](https://CRAN.R-project.org/package=DAISIE) and a development version on GitHub. + ### From CRAN From within R, do: -``` +``` r install.packages("DAISIE") ``` @@ -26,7 +30,7 @@ install.packages("DAISIE") Install DAISIE from this GitHub repository by running: -``` +``` r install.packages("remotes") remotes::install_github("rsetienne/DAISIE") ``` @@ -65,13 +69,11 @@ Remotes: ## Contributors -DAISIE was originally developed by Rampal S. Etienne, Luis Valente, Albert B. Phillimore and Bart Haegeman. - -Additional members working on expanding DAISIE at the [TECE lab](https://github.com/tece-lab), University of Groningen are: Joshua Lambert, Pedro Neves, Richèl J. C. Bilderbeek, Sebastian Mader, Shu Xie. +`DAISIE` was originally developed by Rampal S. Etienne, Luis Valente, Albert B. Phillimore and Bart Haegeman. It is continuously maintained by members of the [@tece-lab](https://github.com/tece-lab), at the University of Groningen. ## References -Etienne R. S., Valente, L., Phillimore, A. B., Haegeman, B., Lambert, J. W., Neves, P., Xie, S., & Bilderbeek, R. J. C. (2020). DAISIE: Dynamical Assembly of Islands by Speciation, Immigration and Extinction. R package version 3.0.1. https://cran.r-project.org/package=DAISIE +Etienne R. S., Valente, L., Phillimore, A. B., Haegeman, B., Lambert, J. W., Neves, P., Xie, S., Bilderbeek, R. J. C., & Hildenbrandt, H. (2021). DAISIE: Dynamical Assembly of Islands by Speciation, Immigration and Extinction. R package version 3.2.0. https://cran.r-project.org/package=DAISIE. https://doi.org/10.5281/zenodo.4054058 Valente, L., Etienne, R.S., & Phillimore, A.B. (2014). The effects of island ontogeny on species diversity and phylogeny. Proceedings of the Royal Society B: Biological Sciences, 281(1784), 20133227–20133227. http://doi.org/10.1098/rspb.2013.3227 @@ -83,8 +85,8 @@ Valente, L., Illera, J.C., Havenstein, K., Pallien, T., Etienne, R.S., & Tiedema Valente, L., Phillimore, A.B., & Etienne, R.S. (2018). Using molecular phylogenies in island biogeography: It’s about time. Ecography, 1–3. http://doi.org/10.1111/ecog.03503 -Valente, L., Etienne, R.S., & Garcia-R., J.C. (2019). “Deep Macroevolutionary Impact of Humans on New Zealand’s Unique Avifauna.” Current Biology 29 (15): 2563-2569.e4. https://doi.org/10.1016/j.cub.2019.06.058 +Valente, L., Etienne, R.S., & Garcia-R., J.C. (2019). Deep Macroevolutionary Impact of Humans on New Zealand’s Unique Avifauna. Current Biology 29 (15): 2563-2569.e4. https://doi.org/10.1016/j.cub.2019.06.058 -Valente, L., Phillimore, A.B., Melo, M., Warren, B.H., Clegg, S.M., Havenstein, K., Tiedemann, R., Illera, J.C.,, Thebaud, C., Aschenbach, T. & Etienne, R.S. (2020). “A Simple Dynamic Model Explains the Diversity of Island Birds Worldwide.” Nature 579 (7797): 92–96. https://doi.org/10.1038/s41586-020-2022-5 +Valente, L., Phillimore, A.B., Melo, M., Warren, B.H., Clegg, S.M., Havenstein, K., Tiedemann, R., Illera, J.C., Thebaud, C., Aschenbach, T. & Etienne, R.S. (2020). A Simple Dynamic Model Explains the Diversity of Island Birds Worldwide. Nature 579 (7797): 92–96. https://doi.org/10.1038/s41586-020-2022-5 Hauffe, T., Delicado, D., Etienne, R.S., & Valente, L. (2020). Lake expansion elevates equilibrium diversity via increasing colonization. Journal of Biogeography 47: 1849–1860. https://doi.org/10.1111/jbi.13914 diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index 712608b4..00000000 --- a/appveyor.yml +++ /dev/null @@ -1,45 +0,0 @@ -# DO NOT CHANGE the "init" and "install" sections below - -# Download script file from GitHub -init: - ps: | - $ErrorActionPreference = "Stop" - Invoke-WebRequest http://raw.github.com/krlmlr/r-appveyor/master/scripts/appveyor-tool.ps1 -OutFile "..\appveyor-tool.ps1" - Import-Module '..\appveyor-tool.ps1' - - install: - ps: Bootstrap - - cache: - - C:\RLibrary - - # Adapt as necessary starting from here - - build_script: - - travis-tool.sh install_deps - - test_script: - - travis-tool.sh run_tests - - on_failure: - - 7z a failure.zip *.Rcheck\* - - appveyor PushArtifact failure.zip - - artifacts: - - path: '*.Rcheck\**\*.log' - name: Logs - - - path: '*.Rcheck\**\*.out' - name: Logs - - - path: '*.Rcheck\**\*.fail' - name: Logs - - - path: '*.Rcheck\**\*.Rout' - name: Logs - - - path: '\*_*.tar.gz' - name: Bits - - - path: '\*_*.zip' - name: Bits diff --git a/doc/DAISIE_macOS.md b/doc/DAISIE_macOS.md new file mode 100644 index 00000000..ffe595d3 --- /dev/null +++ b/doc/DAISIE_macOS.md @@ -0,0 +1,56 @@ +# DAISIE on macOS + +This worked on a fresh install of +* Mojave 10.14.4 +* Catalina 10.15.7 +* Big Sur 11.2 + +We install everything via homebrew: + +## Install homebrew +``` +/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" +``` + +## Install gcc and gfortran +``` +brew install gcc +``` + +## Install R +``` +brew install r +``` + +## Add openssl to path +``` +echo 'export PATH="/usr/local/opt/openssl@1.1/bin:$PATH"' >> ~/.profile +source .profile +``` + +## Install libgit2 (devtools needs this) + +``` +brew install libgit2 +``` + +## Check R version + +``` +R --version +R version 4.0.3 (2020-10-10) -- "Bunny-Wunnies Freak Out" +Copyright (C) 2020 The R Foundation for Statistical Computing +Platform: x86_64-apple-darwin18.7.0 (64-bit) +``` + +## Install RStudio +``` +brew install rstudio +``` +Optional: install devtools. + + +## Clean and Rebuild DAISIE.Rproj +``` +DONE (DAISIE) +``` diff --git a/man/DAISIE-package.Rd b/man/DAISIE-package.Rd index 26e31b4a..0cbe9477 100644 --- a/man/DAISIE-package.Rd +++ b/man/DAISIE-package.Rd @@ -14,13 +14,13 @@ Cladogenesis and immigration rates can be dependent on diversity. } \references{ \itemize{ -\item Valente, L. M., Etienne, R. S., & Phillimore, A. B. (2014). The effects of island ontogeny on species diversity and phylogeny. Proceedings of the Royal Society of London. Series B, Biological Sciences 281, 20133227. . \cr -\item Valente, L., A.B. Phillimore & R.S. Etienne (2015). Equilibrium and non-equilibrium dynamics simultaneously operate in the Galapagos islands. Ecology Letters 18: 844-852, . \cr -\item Valente, L., R.S. Etienne & L. Davalos (2017). Recent extinctions disturb path to equilibrium diversity in Caribbean bats. Nature Ecology and Evolution 1: 0026. .\cr -\item Valente, L., Illera, J. C., Havenstein, K., Pallien, T., Etienne, R. S., & Tiedemann, R. (2017). Equilibrium Bird Species Diversity in Atlantic Islands. Current Biology 27: 1660-1666. .\cr -\item Valente, L., Phillimore, A. B., & Etienne, R. (2018). Using molecular phylogenies in island biogeography: It's about time. Ecography 41: 1684-1686. .\cr -\item Valente, L., Etienne, R. S., & Garcia-R, J. C. (2019). Deep macroevolutionary impact of humans on New Zealand's unique avifauna. Current Biology 29: 2563-2569. .\cr -\item Valente, L., Phillimore, A. B., Melo, M., Warren, B. H., Clegg, S. M., Havenstein, K., Etienne, R. S. (2020). A simple dynamic model explains the diversity of island birds worldwide. Nature 579: 92-96. .\cr +\item Valente, L. M., Etienne, R. S., & Phillimore, A. B. (2014). The effects of island ontogeny on species diversity and phylogeny. Proceedings of the Royal Society of London. Series B, Biological Sciences 281, 20133227. \doi{10.1098/rspb.2013.3227}. \cr +\item Valente, L., A.B. Phillimore & R.S. Etienne (2015). Equilibrium and non-equilibrium dynamics simultaneously operate in the Galapagos islands. Ecology Letters 18: 844-852, \doi{10.1111/ele.12461}. \cr +\item Valente, L., R.S. Etienne & L. Davalos (2017). Recent extinctions disturb path to equilibrium diversity in Caribbean bats. Nature Ecology and Evolution 1: 0026. \doi{10.1038/s41559-016-0026}.\cr +\item Valente, L., Illera, J. C., Havenstein, K., Pallien, T., Etienne, R. S., & Tiedemann, R. (2017). Equilibrium Bird Species Diversity in Atlantic Islands. Current Biology 27: 1660-1666. \doi{10.1016/j.cub.2017.04.053}.\cr +\item Valente, L., Phillimore, A. B., & Etienne, R. (2018). Using molecular phylogenies in island biogeography: It's about time. Ecography 41: 1684-1686. \doi{10.1111/ecog.03503}.\cr +\item Valente, L., Etienne, R. S., & Garcia-R, J. C. (2019). Deep macroevolutionary impact of humans on New Zealand's unique avifauna. Current Biology 29: 2563-2569. \doi{10.1016/j.cub.2019.06.058}.\cr +\item Valente, L., Phillimore, A. B., Melo, M., Warren, B. H., Clegg, S. M., Havenstein, K., Etienne, R. S. (2020). A simple dynamic model explains the diversity of island birds worldwide. Nature 579: 92-96. \doi{10.1038/s41586-020-2022-5}.\cr } \cr } \seealso{ @@ -39,10 +39,11 @@ Authors: \item Luis Valente \email{luis.valente@naturalis.nl} (\href{https://orcid.org/0000-0003-4247-8785}{ORCID}) \item Albert B. Phillimore (\href{https://orcid.org/0000-0002-6553-1553}{ORCID}) \item Bart Haegeman (\href{https://orcid.org/0000-0003-2325-4727}{ORCID}) - \item Joshua W. Lambert \email{j.w.l.lambert@rug.nl} + \item Joshua W. Lambert \email{j.w.l.lambert@rug.nl} (\href{https://orcid.org/0000-0001-5218-3046}{ORCID}) \item Pedro Neves \email{p.m.santos.neves@rug.nl} (\href{https://orcid.org/0000-0003-2561-4677}{ORCID}) - \item Shu Xie \email{s.xie@rug.nl} + \item Shu Xie \email{s.xie@rug.nl} (\href{https://orcid.org/0000-0001-9594-946X}{ORCID}) \item Richèl J.C. Bilderbeek \email{richel@richelbilderbeek.nl} (\href{https://orcid.org/0000-0003-1107-7049}{ORCID}) + \item Hanno Hildenbrandt \email{h.hildenbrandt@rug.nl} } Other contributors: diff --git a/man/DAISIE_ONEcolonist.Rd b/man/DAISIE_ONEcolonist.Rd index 4de0db7d..94433bc0 100644 --- a/man/DAISIE_ONEcolonist.Rd +++ b/man/DAISIE_ONEcolonist.Rd @@ -2,7 +2,7 @@ % Please edit documentation in R/DAISIE_ONEcolonist.R \name{DAISIE_ONEcolonist} \alias{DAISIE_ONEcolonist} -\title{Title} +\title{Convert intermediate output to final simulation output} \usage{ DAISIE_ONEcolonist(time, island_spec, stt_table) } @@ -20,16 +20,39 @@ of species.} \value{ a list with these elements: \itemize{ - item{[1]: stt_table, the same stt_table as put in} - item{[2]: branching_times, branching times} - item{[3]: stac, ?statuses} - item{[4]: missing_species, ?the number of missing species} - item{[5]: other_clades_same_ancestor, ?no idea} - item{[6]: non-endemic species} - item{[7]: endemic species} + \item{[1]: \code{stt_table}, the same stt_table as put in.} + \item{[2]: \code{branching_times}, a sorted numeric vector, as required + by the ML estimation functions. The first element always refers to + the island age. Subsequent elements refer to colonisation, speciation and + recolonisation times. The most recent recolonisation time, if any is + always omitted to approximate simulation results to the mathematical + formulation of the likelihood functions used for MLE.} + \item{[3]: \code{stac}, status of colonist. In this function it can be + returned as either 2, 4 or 3. If \code{stac} is 2, then there is only one + independent colonisation present on the island and the extant species are + endemic. If stac is 4, then only a singleton endemic is present at the + present. If stac is 3, then recolonisation occurred, and more than one + colonising lineage.} + \item{[4]: \code{missing_species}, a numeric value with the number of + missing species, that is, species not sampled in the phylogeny but + present on the island. As this code only runs for simulation models, + here \code{missing_species} is always set to 0.} + \item{[5]: + \code{all_colonisations}, on recolonising lineages only. It is comprised of + \code{$event_times} and \code{$species_type}: + \describe{ + \item{\code{$event_times}}{ordered numeric vectors containing all + events for each extant recolonising lineage. This includes all + colonisation and branching times. Each vector pertains to one + colonising lineage.} + \item{\code{$species_type}}{a string. Can be \code{"A"}, \code{"C"} or + \code{"I"} depending on whether the extant clade is of anagenetic, + cladogenetic or immigrant origin, respectively.} + } } } +} \description{ -Title +Convert intermediate output to final simulation output } \keyword{internal} diff --git a/man/DAISIE_calc_clade_ana_rate.Rd b/man/DAISIE_calc_clade_ana_rate.Rd deleted file mode 100644 index 7bd53974..00000000 --- a/man/DAISIE_calc_clade_ana_rate.Rd +++ /dev/null @@ -1,39 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/DAISIE_sim_core_1_4.R -\name{DAISIE_calc_clade_ana_rate} -\alias{DAISIE_calc_clade_ana_rate} -\title{Calculate the clade-wide effective anagenesis rate. -With 'effective', this means that if an immigrant -undergoes anagenesis, it will become a new species. -Would such a species undergo anagenesis again, no net new -species is created; the species only gets renamed} -\usage{ -DAISIE_calc_clade_ana_rate(ps_ana_rate, n_immigrants) -} -\arguments{ -\item{ps_ana_rate}{per species anagensis rate} - -\item{n_immigrants}{number of immigrants in that clade} -} -\value{ -the clade's effective anagenesis rate -} -\description{ -Calculate the clade-wide effective anagenesis rate. -With 'effective', this means that if an immigrant -undergoes anagenesis, it will become a new species. -Would such a species undergo anagenesis again, no net new -species is created; the species only gets renamed -} -\examples{ - testit::assert( - DAISIE:::DAISIE_calc_clade_ana_rate( - ps_ana_rate = 0.3, - n_immigrants = 5 - ) == 1.5 - ) -} -\author{ -Richel J.C. Bilderbeek -} -\keyword{internal} diff --git a/man/DAISIE_calc_clade_clado_rate.Rd b/man/DAISIE_calc_clade_clado_rate.Rd deleted file mode 100644 index b59c1b25..00000000 --- a/man/DAISIE_calc_clade_clado_rate.Rd +++ /dev/null @@ -1,48 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/DAISIE_sim_core_1_4.R -\name{DAISIE_calc_clade_clado_rate} -\alias{DAISIE_calc_clade_clado_rate} -\title{Calculate the clade-wide cladogenesis rate.} -\usage{ -DAISIE_calc_clade_clado_rate(ps_clado_rate, n_species, carr_cap) -} -\arguments{ -\item{ps_clado_rate}{per species cladogenesis rate} - -\item{n_species}{number of species in that clade} - -\item{carr_cap}{carrying capacity, number of species this clade will -grow to} -} -\value{ -the clade's cladogenesis rate, which is at least zero. This - rate will be zero if there are more species than the carrying capacity - allows for -} -\description{ -Calculate the clade-wide cladogenesis rate. -} -\note{ -For clade-specific carrying capacity, - each clade is simulated seperately in \code{\link{DAISIE_sim}} -} -\examples{ - testit::assert( - DAISIE:::DAISIE_calc_clade_clado_rate( - ps_clado_rate = 0.2, - n_species = 5, - carr_cap = 10 - ) == 0.5 - ) - testit::assert( - DAISIE:::DAISIE_calc_clade_clado_rate( - ps_clado_rate = 0.2, - n_species = 2, - carr_cap = 1 - ) == 0.0 - ) -} -\author{ -Richel J.C. Bilderbeek -} -\keyword{internal} diff --git a/man/DAISIE_calc_clade_ext_rate.Rd b/man/DAISIE_calc_clade_ext_rate.Rd deleted file mode 100644 index 49702508..00000000 --- a/man/DAISIE_calc_clade_ext_rate.Rd +++ /dev/null @@ -1,31 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/DAISIE_sim_core_1_4.R -\name{DAISIE_calc_clade_ext_rate} -\alias{DAISIE_calc_clade_ext_rate} -\title{Calculate the clade-wide extinction rate} -\usage{ -DAISIE_calc_clade_ext_rate(ps_ext_rate, n_species) -} -\arguments{ -\item{ps_ext_rate}{per species extinction rate} - -\item{n_species}{number of species in that clade} -} -\value{ -the clade's extinction rate -} -\description{ -Calculate the clade-wide extinction rate -} -\examples{ - testit::assert( - DAISIE:::DAISIE_calc_clade_ext_rate( - ps_ext_rate = 0.2, - n_species = 4 - ) == 0.8 - ) -} -\author{ -Richel J.C. Bilderbeek -} -\keyword{internal} diff --git a/man/DAISIE_calc_clade_imm_rate.Rd b/man/DAISIE_calc_clade_imm_rate.Rd deleted file mode 100644 index a877f7e9..00000000 --- a/man/DAISIE_calc_clade_imm_rate.Rd +++ /dev/null @@ -1,53 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/DAISIE_sim_core_1_4.R -\name{DAISIE_calc_clade_imm_rate} -\alias{DAISIE_calc_clade_imm_rate} -\title{Calculate the clade-wide immigration rate.} -\usage{ -DAISIE_calc_clade_imm_rate( - ps_imm_rate, - n_island_species, - n_mainland_species, - carr_cap -) -} -\arguments{ -\item{ps_imm_rate}{per species immigration rate} - -\item{n_island_species}{number of species in that clade on the island} - -\item{n_mainland_species}{number of species in that clade on the mainland} - -\item{carr_cap}{carrying capacity, number of species this clade will -grow to} -} -\value{ -the clade's immigration rate, which is at least zero. This - rate will be zero if there are more species than the carrying capacity - allows for -} -\description{ -Calculate the clade-wide immigration rate. -} -\examples{ - testit::assert( - DAISIE:::DAISIE_calc_clade_imm_rate( - ps_imm_rate = 0.1, - n_island_species = 5, - n_mainland_species = 2, - carr_cap = 10 - ) == 0.1 - ) - testit::assert( - DAISIE:::DAISIE_calc_clade_imm_rate( - ps_imm_rate = 0.1, - n_island_species = 5, - n_mainland_species = 2, - carr_cap = 1 - ) == 0.0 - ) -} -\author{ -Richel J.C. Bilderbeek -} -\keyword{internal} diff --git a/man/DAISIE_create_island.Rd b/man/DAISIE_create_island.Rd index 629ae1ed..d717259c 100644 --- a/man/DAISIE_create_island.Rd +++ b/man/DAISIE_create_island.Rd @@ -47,3 +47,4 @@ the island and number of missing species. \description{ Converts simulation output into island output } +\keyword{internal} diff --git a/man/DAISIE_dataprep.Rd b/man/DAISIE_dataprep.Rd index b6a6c752..40f72fe0 100644 --- a/man/DAISIE_dataprep.Rd +++ b/man/DAISIE_dataprep.Rd @@ -32,9 +32,11 @@ of anthropogenic causes, and which are not included in the phylogeny ("NA" should be given in the branching times column). It could also apply to insular radiations with long stem branches, for which the time of the first cladogenetic event is known, but the precise time of colonisation -is not. \cr * "Endemic&Non_Endemic": when endemic clade is present and its mainland -ancestor has re-colonized \cr \code{$Missing_species} - Number of island -species that were not sampled for particular clade (only applicable for +is not. \cr * "Endemic_MaxAge_MinAge": same as Endemic_MaxAge but also includes a minimum +age for colonisation. \cr * "Non_endemic_MaxAge_MinAge": same as Non_endemic_MaxAge but +also includes a minimum age for colonisation.#' \cr * "Endemic&Non_Endemic": when endemic +clade is present and its mainland ancestor has re-colonized \cr \code{$Missing_species} +- Number of island species that were not sampled for particular clade (only applicable for "Endemic" clades). If NA is given in branching times column, this should be equal to the number of species in the clade minus 1 \cr \code{$Branching_times} - Stem age of the population/species in the case of "Non_endemic", "Non_endemic_MaxAge" @@ -117,7 +119,7 @@ DAISIE functions. ### Create Galapagos data object where all taxa have the same macroevolutionary process -utils::data(Galapagos_datatable) +utils::data(Galapagos_datatable, package = "DAISIE") DAISIE_dataprep( datatable = Galapagos_datatable, island_age = 4, @@ -130,7 +132,7 @@ DAISIE_dataprep( # (Darwin's finches). Set fraction of potential colonists of type 2 to be # proportional to the number of type2 clades present on the island. -utils::data(Galapagos_datatable) +utils::data(Galapagos_datatable, package = "DAISIE") DAISIE_dataprep( datatable = Galapagos_datatable, island_age = 4, @@ -144,7 +146,7 @@ DAISIE_dataprep( # except for Darwin's finches) and the other applies only to type 2 species # (Darwin's finches). Set fraction of potential colonists of type 2 to be 0.163. -utils::data(Galapagos_datatable) +utils::data(Galapagos_datatable, package = "DAISIE") DAISIE_dataprep( datatable = Galapagos_datatable, island_age = 4, diff --git a/man/DAISIE_get_brts_mya.Rd b/man/DAISIE_get_brts_mya.Rd deleted file mode 100644 index 7e15edbb..00000000 --- a/man/DAISIE_get_brts_mya.Rd +++ /dev/null @@ -1,28 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/DAISIE_get_brts_mya.R -\name{DAISIE_get_brts_mya} -\alias{DAISIE_get_brts_mya} -\title{Extract the sorted branching times, in million years ago. -from a data table} -\usage{ -DAISIE_get_brts_mya(data_table) -} -\arguments{ -\item{data_table}{data table} -} -\value{ -the sorted branching times, in million years ago -} -\description{ -Extract the sorted branching times, in million years ago. -from a data table -} -\examples{ - data(Galapagos_datatable) - brts_mya <- DAISIE_get_brts_mya(data_table = Galapagos_datatable) - testit::assert(length(brts_mya) > 1) - testit::assert(all(brts_mya > 0)) -} -\author{ -Richel J.C. Bilderbeek -} diff --git a/man/DAISIE_loglik_IW.Rd b/man/DAISIE_loglik_IW.Rd index c7fc5bda..bb5a3f5b 100644 --- a/man/DAISIE_loglik_IW.Rd +++ b/man/DAISIE_loglik_IW.Rd @@ -9,9 +9,9 @@ DAISIE_loglik_IW( pars1, pars2, datalist, - methode = "ode45", - abstolint = 1e-16, - reltolint = 1e-14, + methode = "odeint::runge_kutta_fehlberg78", + abstolint = 1e-12, + reltolint = 1e-10, verbose = FALSE ) } @@ -73,8 +73,12 @@ the radiation.\cr number of island species that were not sampled for particular clade (only applicable for endemic clades) \cr} -\item{methode}{Method of the ODE-solver. See package deSolve for details. -Default is "ode45"} +\item{methode}{Method of the ODE-solver. Supported odeint solvers (steppers) are: +'odeint::runge_kutta_cash_karp54' +'odeint::runge_kutta_fehlberg78' [default] +'odeint::runge_kutta_dopri5' +'odeint::bulirsch_stoer' +without odeint::-prefix, deSolve method is assumed} \item{abstolint}{Absolute tolerance of the integration} diff --git a/man/DAISIE_loglik_integrand.Rd b/man/DAISIE_loglik_integrand.Rd index 984f7262..35595c90 100644 --- a/man/DAISIE_loglik_integrand.Rd +++ b/man/DAISIE_loglik_integrand.Rd @@ -17,8 +17,8 @@ DAISIE_loglik_integrand( reltolint, verbose, pick, - mean, - sd + par_mean, + par_sd ) } \arguments{ @@ -61,10 +61,6 @@ means also intermediate progress during loglikelihood computation is shown.} \item{pick}{Numeric determining which parameter is selected for the relaxed-rate model} - -\item{mean}{Numeric mean of the distribution} - -\item{sd}{Numeric standard deviation of the distribution} } \value{ A numeric diff --git a/man/DAISIE_plot_input.Rd b/man/DAISIE_plot_input.Rd index b236e857..ece50d12 100644 --- a/man/DAISIE_plot_input.Rd +++ b/man/DAISIE_plot_input.Rd @@ -51,10 +51,7 @@ Shows the phylogenies of the multiple clades present on the island t1$tip.label <- gsub("t", "t1.", t1$tip.label) t2 <- ape::rtree(3) t2$tip.label <- gsub("t", "t2.", t2$tip.label) - t3 <- DAISIE:::DAISIE_single_branch( - "t3.1", - edge.length = 4.6 - ) # tree with one species + t3 <- ape::rtree(2) trees <- list(t1, t2, t3) names(trees) <- c("A", "B", "C") diff --git a/man/DAISIE_sim.Rd b/man/DAISIE_sim.Rd index 18b02edb..a14e4d60 100644 --- a/man/DAISIE_sim.Rd +++ b/man/DAISIE_sim.Rd @@ -154,7 +154,7 @@ information containing: \itemize{ \item{\code{$island_age}: A numeric with the island age.} \item{\code{$not_present}: the number of mainland lineages that are not - present on the island. It is only present if only 1 typo of species is + present on the island. It is only present if only 1 type of species is simulated. Becomes \code{$not_present_type1}: the number of mainland lineages of type 1 that are not present on the island and \code{$not_present_type2}: the number of mainland lineages of type 2 @@ -217,7 +217,7 @@ includes potential endemic and non-endemic species. clado_rate <- 0.5 ext_rate <- 0.2 carr_cap <- Inf -immig_rate <- 0.005 +immig_rate <- 0.05 ana_rate <- 1 sim_pars <- c(clado_rate, ext_rate, carr_cap, immig_rate, ana_rate) set.seed(1) diff --git a/man/DAISIE_sim_core_1_4.Rd b/man/DAISIE_sim_core_1_4.Rd deleted file mode 100644 index 3b7c635f..00000000 --- a/man/DAISIE_sim_core_1_4.Rd +++ /dev/null @@ -1,39 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/DAISIE_sim_core_1_4.R -\name{DAISIE_sim_core_1_4} -\alias{DAISIE_sim_core_1_4} -\title{Internal function of the DAISIE simulation -Taken from CRAN, commit https://github.com/richelbilderbeek/DAISIE/commit/c700b0fcf9e2c2b5d7248f02af7596fac5a2f573#diff-ddae7ad3ae2def3cb66ecf8a8a45cc41} -\usage{ -DAISIE_sim_core_1_4(time, mainland_n, pars) -} -\arguments{ -\item{time}{simulated amount of time} - -\item{mainland_n}{number of mainland species, that -is, the number of species that can potentially colonize the island. -If \code{\link{DAISIE_sim_constant_rate}()} uses a clade-specific diversity dependence, -this value is set to 1. -If \code{\link{DAISIE_sim_constant_rate}()} uses an island-specific diversity dependence, -this value is set to the number of mainland species.} - -\item{pars}{a numeric vector: -\itemize{ - \item{[1]: cladogenesis rate} - \item{[2]: extinction rate} - \item{[3]: carrying capacity} - \item{[4]: immigration rate} - \item{[5]: anagenesis rate} -}} -} -\description{ -Internal function of the DAISIE simulation -Taken from CRAN, commit https://github.com/richelbilderbeek/DAISIE/commit/c700b0fcf9e2c2b5d7248f02af7596fac5a2f573#diff-ddae7ad3ae2def3cb66ecf8a8a45cc41 -} -\note{ -This function produces an extra element per replicate when the -island is empty at time = 0. Functionally this has no effect on the -simulations, but care should be taken if using the length of objects to count -the number of species present on the island. -} -\keyword{internal} diff --git a/man/DAISIE_sim_core_1_4a.Rd b/man/DAISIE_sim_core_1_4a.Rd deleted file mode 100644 index cf240b5d..00000000 --- a/man/DAISIE_sim_core_1_4a.Rd +++ /dev/null @@ -1,39 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/DAISIE_sim_core_1_4a.R -\name{DAISIE_sim_core_1_4a} -\alias{DAISIE_sim_core_1_4a} -\title{Internal function of the DAISIE simulation -Taken from CRAN, commit https://github.com/richelbilderbeek/DAISIE/commit/c700b0fcf9e2c2b5d7248f02af7596fac5a2f573#diff-ddae7ad3ae2def3cb66ecf8a8a45cc41} -\usage{ -DAISIE_sim_core_1_4a(time, mainland_n, pars) -} -\arguments{ -\item{time}{simulated amount of time} - -\item{mainland_n}{number of mainland species, that -is, the number of species that can potentially colonize the island. -If \code{\link{DAISIE_sim_constant_rate}()} uses a clade-specific diversity dependence, -this value is set to 1. -If \code{\link{DAISIE_sim_constant_rate}()} uses an island-specific diversity dependence, -this value is set to the number of mainland species.} - -\item{pars}{a numeric vector: -\itemize{ - \item{[1]: cladogenesis rate} - \item{[2]: extinction rate} - \item{[3]: carrying capacity} - \item{[4]: immigration rate} - \item{[5]: anagenesis rate} -}} -} -\description{ -Internal function of the DAISIE simulation -Taken from CRAN, commit https://github.com/richelbilderbeek/DAISIE/commit/c700b0fcf9e2c2b5d7248f02af7596fac5a2f573#diff-ddae7ad3ae2def3cb66ecf8a8a45cc41 -} -\note{ -This function produces an extra element per replicate when the -island is empty at time = 0. Functionally this has no effect on the -simulations, but care should be taken if using the length of objects to count -the number of species present on the island. -} -\keyword{internal} diff --git a/man/DAISIE_sim_core_trait_dependent.Rd b/man/DAISIE_sim_core_trait_dependent.Rd index 6e43dd9a..6a3fcdda 100644 --- a/man/DAISIE_sim_core_trait_dependent.Rd +++ b/man/DAISIE_sim_core_trait_dependent.Rd @@ -8,7 +8,6 @@ DAISIE_sim_core_trait_dependent( time, mainland_n, pars, - nonoceanic_pars = c(0, 0), island_ontogeny = 0, sea_level = 0, hyper_pars, @@ -54,13 +53,6 @@ or in the rate shift model. For \code{\link{DAISIE_sim_relaxed_rate}()} relaxed parameter and the parameter chosen by the \code{relaxed_par} argument is the mean of the gamma distribution for the relaxed parameter.} -\item{nonoceanic_pars}{A vector of length two with: -\itemize{ - \item{[1]: the probability of sampling a species from the mainland} - \item{[2]: the probability of the species sampled from the mainland - being nonendemic} -}} - \item{island_ontogeny}{In \code{\link{DAISIE_sim_time_dependent}()}, \code{\link{DAISIE_ML_CS}} and plotting a string describing the type of island ontogeny. Can be \code{"const"}, \code{"beta"} for a beta function diff --git a/man/DAISIE_sim_relaxed_rate.Rd b/man/DAISIE_sim_relaxed_rate.Rd index 5789b453..cb75dba2 100644 --- a/man/DAISIE_sim_relaxed_rate.Rd +++ b/man/DAISIE_sim_relaxed_rate.Rd @@ -122,7 +122,7 @@ information containing: \itemize{ \item{\code{$island_age}: A numeric with the island age.} \item{\code{$not_present}: the number of mainland lineages that are not - present on the island. It is only present if only 1 typo of species is + present on the island. It is only present if only 1 type of species is simulated. Becomes \code{$not_present_type1}: the number of mainland lineages of type 1 that are not present on the island and \code{$not_present_type2}: the number of mainland lineages of type 2 diff --git a/man/DAISIE_sim_trait_dependent.Rd b/man/DAISIE_sim_trait_dependent.Rd index 6bbe0253..fc553bfc 100644 --- a/man/DAISIE_sim_trait_dependent.Rd +++ b/man/DAISIE_sim_trait_dependent.Rd @@ -10,7 +10,6 @@ DAISIE_sim_trait_dependent( pars, replicates, divdepmodel = "CS", - nonoceanic_pars = c(0, 0), num_guilds = NULL, sample_freq = 25, plot_sims = TRUE, @@ -72,13 +71,6 @@ carrying capacity, where diversity-dependence operates within and among clades. Option divdepmodel = 'GW' runs a model with diversity-dependence operates within a guild.} -\item{nonoceanic_pars}{A vector of length two with: -\itemize{ - \item{[1]: the probability of sampling a species from the mainland} - \item{[2]: the probability of the species sampled from the mainland - being nonendemic} -}} - \item{num_guilds}{The number of guilds on the mainland. The number of mainland species is divided by the number of guilds when \code{divdepmodel = "GW"}} diff --git a/man/DAISIE_single_branch.Rd b/man/DAISIE_single_branch.Rd deleted file mode 100644 index 252f842e..00000000 --- a/man/DAISIE_single_branch.Rd +++ /dev/null @@ -1,29 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/DAISIE_single_branch.R -\name{DAISIE_single_branch} -\alias{DAISIE_single_branch} -\title{Single-branch phylogenetic tree} -\usage{ -DAISIE_single_branch(tip.label = "t1", edge.length = 1) -} -\arguments{ -\item{tip.label}{Name of the unique tip} - -\item{edge.length}{Length of the unique edge} -} -\value{ -A phylogenetic tree in `phylo` format. -} -\description{ -Single-branch phylogenetic tree -} -\examples{ - -# A tree with one species with a 15Myr-old stem -DAISIE:::DAISIE_single_branch("some species", edge.length = 15) - -} -\author{ -Raphael Scherrer (github.com/rscherrer) -} -\keyword{internal} diff --git a/man/daisie_odeint_iw.Rd b/man/daisie_odeint_iw.Rd new file mode 100644 index 00000000..8a8af05b --- /dev/null +++ b/man/daisie_odeint_iw.Rd @@ -0,0 +1,8 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/RcppExports.R +\name{daisie_odeint_iw} +\alias{daisie_odeint_iw} +\title{Driver for the boost::odeint solver} +\description{ +Driver for the boost::odeint solver +} diff --git a/man/integral_peak.Rd b/man/integral_peak.Rd index 3bc75d43..cd232721 100644 --- a/man/integral_peak.Rd +++ b/man/integral_peak.Rd @@ -9,7 +9,18 @@ integral_peak( xx = seq(-20, 20, 2), xcutoff = 2, ymaxthreshold = 1e-12, - ... + pars1, + pars2, + brts, + stac, + missnumspec, + methode, + abstolint, + reltolint, + verbose, + pick, + par_mean, + par_sd ) } \arguments{ diff --git a/man/pipe.Rd b/man/pipe.Rd deleted file mode 100644 index 0eec7526..00000000 --- a/man/pipe.Rd +++ /dev/null @@ -1,12 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/utils-pipe.R -\name{\%>\%} -\alias{\%>\%} -\title{Pipe operator} -\usage{ -lhs \%>\% rhs -} -\description{ -See \code{magrittr::\link[magrittr:pipe]{\%>\%}} for details. -} -\keyword{internal} diff --git a/man/transform_gamma_pars.Rd b/man/transform_gamma_pars.Rd new file mode 100644 index 00000000..733d09a5 --- /dev/null +++ b/man/transform_gamma_pars.Rd @@ -0,0 +1,19 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/DAISIE_loglik_integrate.R +\name{transform_gamma_pars} +\alias{transform_gamma_pars} +\title{Transforms mean and standard deviation to shape and scale gamma parameters} +\usage{ +transform_gamma_pars(par_mean, par_sd) +} +\arguments{ +\item{par_mean}{mean of the relaxed parameter} + +\item{par_sd}{standard deviation of the relaxed parameter} +} +\value{ +list to shape and scale parameters +} +\description{ +Transforms mean and standard deviation to shape and scale gamma parameters +} diff --git a/pics/Codecov.png b/pics/Codecov.png new file mode 100644 index 0000000000000000000000000000000000000000..49dbba62d6cccd77b6764bc1712424e5d75776d1 GIT binary patch literal 1272 zcmVqo-O?pC5ib27$h~xRYTQpt4Cw zO%-xa8IqjzpSNo7W%T>Q=qGjHKR+zDv4dx%AulXJs%Ilf2?i__hNiRVi9eye8$@87 z7bz`3ZpnuPvokdqLO-iV*YAK(c!ab9-AZIi9;l+{+R;zOL>|8z$?+OHpC9|#jnE#rp{w|U7f-ZO)+qI(yOAKSx)8jfMx1sfAeY z)IemrxdJY)Jc<&3j@3y^(b7R$f!iT9*^!weaG5(DNlrxjLg;Q^?2!K= z-ToVD+el6ZlodI$aaQuni_P`ODN|4u%!K?bummo2p+}nG=xMNrc)2_&=3SXu0N!*{ ze9p9)cHm+Fax;K(};Yui5~AoW3d^5x}lK*l`GZPXn@Y zk>jo6tXIj&fD2uYqXC#EY<@W!=)+#N7MjjEGt3$T9o<8(?`W}$fvBJ<$%DIQnD^nM zop9`|b6W?{;L_1e7R*Ev6VT3H^qZffduWGp=ge6)$y|LWpgTTCwd>_h#K(C7(9;)O zi8i=1C-S5LR2w0O&vy_Dfr0&N}W-Ykhv~ zhgV~--+{JXGP!+hI`)k^%_!u4#IIIzB1|uW>@l!6#+gh+@f$NcQ78-z{7W i!ADx7;3KV@7W^+ASG0{)UvhQ;0000|6@NmYlanO-*7y=JPKqY|y2?!(*AVSE#^p;-I`~IqKZikzu$%3GOee&J!_N`mD zZl%s&=lthXbu+@@FkC6&34}6qDnv&f?U2%{G^3*l9cB3NxSVAWm+Mj(R{}T)Fc=`K z(eaQ-B(O}GG}e_fK3y>)Q_Yu2c`$X#aQJffX|nFI>LyF&k?$O5&$p<8fq);qejO?< zK_Ifm)$tPn4gyRDIu&EU+&X!J{)tCtYA{F!EAMS6b8q{+s=KkNU4Z(r7J;WYu96!Z zI0!U_3zk`N(GPc49YH zgaA|>SIrFw90ZyY7K`=EhaZ^BeBs%-yh!G&Kphh}?V6M6laE z{AZqAFO;d{*MvqGFbN?i=9#T<{0jkuQ;R^&T4~q$> zT6JU@J||`-ljV(uE(oJPv5*TDhwA%S9V|;0P2#V3a2|m;R5=ym$K@ImVzBucq{MBQ z)8MG-v#m$qtv@X3Q>VVE9j4?ZgFVFPTYkQ^_jBR=Nsy@S!NJsM73W2-(wpQgcvw^yj{nEldhZ0+J?`8sn| zRIcV}9CAmZpNQ3nDWTAyUK|b$9L-_ZRkVB#1Ib5mRb77^rx+*qB1HJxV=cWmzB{Xj z_dnQASqKUcf#BePL)9~wEb#0Lo5>tdM2w~jRtUQ+kys$Xd84?xt`k>MyR=+v3u@KMy3-370`^%>-h8x97e1@?S(25M?s(R~Y~C2P2+yBlzL zUK&@~H4Yq{N8xfgf5;u5Wx4mB$!VB-V9xU1`=7&tS(9M?ougsY=tKwyL$K}3gRt^} zIk5JFuVHiE0}%H4fx%&u#Q51^sQ_*u&u^VP*JEwm9`d|>&rx{(u?4VuKWg{Y#U!9A zk2J%c183p6m$XoG=#ON*_coM;Jzn2bWrAwA)9HRS&Udas;NaW|;uPDnMx^m0O9^zD zar*>#Zq-a+@VLF4MkwUNGY{VecOoEQ3EG{&EYYoeCOY#sE-&pMe&8vYs=yk zO}%A2=kFgps*1jGsOl^rP+b5G$mm6<{UK`7wC*+w&DXDT4%^1$+i1>kUc!0GmZ zTq=aziP>a1mV?Ke$pqlxnidE%X;cff&qP2J@_8f=Vi2s}Tg#VD7R;GB7Jh#J>r;(J z3r-H+aF!?MrYR*j7(s^(9ji|qtI}RCz{yjoB%WB687LA8BgNv#3X|l@!}VZyxDmm% z!Yl874)qOfu;7tD_4~q)w_eb-P$&S2SU_5=;{VwWA`uV9k4?Q0vU|M1p!gC!(&BMB zxPKP`2Ms#rK^a3G1f-neYXmeI6lk#EeM}fc+N=1!$o?sO&_iX+CADZ=thBlX=u|M& zJPy<$qN>wdp{c_NwX0fS!q^`DBqhq>*UvA$sD5UK5~AH)Bob?E>bj^LgV5pdz@BeT z!e6vsfuYL^YuE3EhaS8G5;W3SU5b?xz`)7Bj4>>RpO_#Ztfv0&Sc8kluo%@TM&K!- z$}nhtJ0#$||JQO9B0J!J|NL;D@`&ZZa=y{vu5Zv8`po3oMj{jn1|ru<8YNSsk@pfF zf?)Ax)wRZQm$86TeZHZS)F5^r$7;@dP()+%`~9A;%6qm;w6^KfqaWh1n1nAF>MbXj z47XY+Fc3_ppv7iSpq}gVjFQjO|KE=N?m#HarI<^;0007mr)i8gQtYfa|QxVDFVv6^8IJwbX`N5L?ZE#PA^$) zU*hGf8a<$|2)iWjTDydZD2FmKGK>>Y?0%@~FeHnG9u0>FWqJdbU~`;VBeVRA?wTP= zP^#Fd2~y#^%Dyq{Iy?C4Z6!Liw+`;a5A&kJ?+ z=j7%4E97795t~tw9fjgeS4auPG~d03n(d`@u%S9~Jb>t2Nb#t9Vzg6EMM2e+V)xQ+ zFGS^~{X|e$YEYd#R8~fN_Zm9TFU3nxIsOtr@gO3wqNrz!V}XtWOYxARDy$HmKv@3P zJ6mo+mjai=9(*b_4IGH6ydJdJo4UF+LZQ%+lbg#&p}F4e^)NALuyoj+ybf@ZpM61( z^u)*D)EA%e|jhsKN<-7OVMRK_k7Ah7j5!{u;+ zO%MoXz^^z|qd@0ZuF_W!sHi5x!HkS%(_e5 z#%|?9R0jqCPhr&mb=fZQQslS@xrb_vP+*-Qk+XK#ZH`7;w>Was>2!)3n;Z2$pP%P& zILW~omX@q9oHY$S!tK-0&EvD6UDpNc{9dF8S$#pQaBiF<{>GWr@V6f>-7Wr%M zek3P(bz2*Db&n&^{1EF^4@WBjUsJ9M`~9*gcT-IRK>^KzM1YfyffD5w=(E43KaNC! zjP7Dq)B2#LTw~J^co7U#e;|pqI!>ButJljrZMKln&b@cfPeYbPf|ZLwgXL}QR{yN& zQ#}8Y7hDH}RFkOboHli8gb)}10NY8|Tx#Z`@@vuC^%VmS-iVGt!(@;|g#-bcO?WXmRVd`GQ zjw7)_0I2$k1Bc=@_@CT}I7D6~)HPe}?%XjW0$w!Z)#`+c+!_Xe&DJf6T#LmbJ3b#j zRc{%Qndz@@Xt3NqX@YNFeja3HrWqQVn;?DIF#W#6weFD_DUhg1Ag!8Ez_;j)W*G)t zG?k=s*HV^6N+Za4VQwLnK#K*!Xm?c*bso^d(E*Lab@cI> zs5bjVbOTHXTR*PzvdA%>NyP{-^nb#7{7i#cCKm8oI(5w)HU|zIJ!L{Xr#DVMaP%~+ zTCrFjxkg|RW3EzuxH>#D|4z-`iv7B^FFcZn@7k={`VzymkFA@s8D<(QbbYI{r+6vI-0Vy zQF)-!AzDN-vrLg)dU8`rT^IH9cp2^8xm4=lvc{93_7qpg2yx45>guQdZq);tGn@Cc z=ZqPf@>yxA7lqL_%x!RmdHFX3c3;?~)YP4Kbn1;VHk<83?j;}*i^1GwR@^pmB-z;F zdAIUQKKz$@#`NiM_Iy3#ubX$aZulf1G@C67l}cgeu-Q(vQVvRmG<2@9mG2LP2@INJ zCu&T7pHG>TAh((=)@1l`wo(*CDX(Y<&z91FQ$R!u$CYa9STWmJ2mG%yV0eoCT2 zivbv`57bTrYpld22^`8T#bWhkMw59Rgu~u0lTmQ&Z;VNG!4$ zja>sD z?@Xm;{_1`dj7e+_#fPL(`Iyonyt9nrDaBEWwhjesRE9gBme;{$z2QCO?p9N&1RDjc z>cJ)eaR#{>S)=BE?5t3X8a|ALA|^>&Tbq6EjF}1!huqyK;&QndD9MejE$#a&54Bq? z)&zBe(lkChlfPu{9rEQ1rgP|R{`Se`iob6!bBKj}x7%TEJ>Jm5L?H>&XfP=_T#ipD z6n1ks+>lf%ag|pbNEnwrLX3a|kH1Xr@xg5T-5&`n(N?aSn&}xZxNRI-n$;O{5{}9m z=Tk=!4McfS7GyBixQKdIO6$*FoOO;N5ug_i8aRP-%?ig3EPNQVJ~5>t!{AA=;D$ETF(VP*hlcDbCa{aHuS8DHVC; z>GZ}!Z~SVdz1?8e3{O>qQYO|*B?7)iA?C}ZBKXxCnL-l$l)Yytnpl?!=z6Ia$SjT?c+z$RD{yUQa#^<6!W8Vu5W zqCQwJ<0nv>qH-WZy-$xqN}>SMySPYMf&P@WF^Yp|2N5NKba( zbZ`$NM^RoH*3aLa05i*THXhR^3tQFze zT#i6f0M~#}JivOn#P$mHp&&Yo{XN^mDH+*dqpW^`6Ir*yh{jPD{wgj(5MLbp=UaSC zb|bR0yqe@8i-sk6?sl_zL+S7-ehA*z>1}qOKj!{WHJ=|cxZOC1lzA->ul*{s_Vh5ZPI# z-#XePo0 z7iW;+-pTf{ztDFQacgt!$zZ?bP=r)|B26sj<%ooKF~K0FcnQ8R2rBRl{O}PX?0>(l zjaZVD9GK~6vHPp*3jsJnOp_@LstQXN&fR<*2hFu7gZg15tT<$s9&EIAvzb8#Z;G7_ z!r=MRNAROq)l{tKix25`tdxd=RCmZ?%W z!##wXU_kG8se)mUpytR0OEWtJCkd}}pUJ>Y)Fe26{rFNcYWn^9Pi<|TdMS&+2q<_w zozd-1rR5{a;KHx2$KBJ70vsB6u={vg#p78sg`!{pxgq3=!tEXx2Q}w6dpzX26PrzV z?wFKI{O0k+gj6g5o88sirt2csYPYLuPJf3tC)=nPx#1ZP1_K>z@;j|==^1poj532;bRa{vGi!~g&e!~vBn4jTXf3^z$cK~!i%%~%O^ zROJ=^-ZnE?h>$>lumu%RD9Bb8Q&AA`h@frJ>VY0m5I9N|u~oLvgMb!95o%j1f|e>r zJqjw+)Bp;JfF+QYB_I$I79j!5MwZFU+y37BX5u6>VM42>{mz->z5l)Uzx&_+yZ3(g zNrHfI*d|`zXJK1DaID0Q3Lg;X0=l>KVMI3tQwIuM#{>UEgc)vOQKp68Wor8T0{=@V*N}leXWZ~d!IcT(r_YMi1E7SRwFu1UFii&%>8K|)o zjC+&EB17eegd{9OxEGSQgbnZFI!_yDzZfXjH5kN_r-qt%`CcM-gjX$edLAgMR&aQh ziC*oRkMA;P4-Q1;bR9j8T+~qF)6l=2j^sFjKjx@Neoi2}z;LdIpkU=a^c?Nm^3ORA znh)}}ljJwrWe&tT$mCo~9O&J;7RBj;DB*W9%82zEe!js^yAv|=8`x36yJ0(H z%>nsXsT&ED@&ehTA-o2gBxBQLH?pVcXcH^2qtFfa0vT7lb=+6cGtrAnUKNJXjD~Y@ zY2~V=!{}RmYgZR}-^Sn+KNL#luOA34v_n#i^S|Uujq|@bAaen%GCXt`J)P;gj(gVI zIB?O8T3YPruJk8}(koskr?iX@ETB0ca~UtwRg_mnrahO;<_N6H){*d>hR-N(b0t0S zq=7!2c(DuvhfCv-=r$4KX~wL=+JnpZo4LUef<;v20KHi2!r)g0=484k>?F(|rsLdv z2?IKXiqq$$XABcaOXV}CEHn$GifX?|T&f|#El|FQETH1Td{^elB&;L~P+)Ke16wBp ziSgmp)JES|Y?28owmo8y01LnV!$D@1$AXEq$GA6mi0Pr=!dwf}`qp661QUB^s*M;8 zq>_7d5`8N1~1i{eXd;`5vCF zX;e~Bt@+YIPLT^WhK!E!2FBhD{IoYSAmpGh!x;ici)}35X<*kGjYy<8LaWqE!AU8P zv&XD75#)58F(yW@rK(Elk~0(=&EU+$a$-;l#mQr$38^gb>{cBw?{z~a`|My5mS_%s zOCqsg`=d7cqy*+@#PASu&)fLPYcdA4^C4?y9c{vCVWZ;<63S{NN02=~%D^3|v|LGG z&v`d~yIn$Ig@Rbc#AVVwjT=MWRq^p}AiGr*`A>tPb5lg?aDm^$_AGR2~UKcUxLX26**R8;C7$$A36&|{0(C-a8 zvjco8}*tW3o|(~Ep(vTQckfm zw!eww#00oC8SP_y$S>ELHk?D(5Gpo2q+#z2Kkn~k;s)CG&T%z}Q%#3XjG{`A!7hw{ zTgGh^(41LT-fiN^+X8jKw3%u^jA|n_-b>GW(S?4kJ-Tx*dy>hSeOANjy=350()@l2 zBX6*<^^uU7oTYe|uZb#kscCSk8yhF6IPt8E)9G%^8D_#yJCd0%p<5dnTPAr?MrreM zjf9u(Hoi5Qk#&|D4Vq_CUmb-D+&Gi&a^}dMZaE*EGV|FK2}N^hA@ssh^7ODSbw&rw zEUTu>kaZduu@;z}2D~&jI2Zwog3`vhDvc(!F!y#F z!@Jrf86hW4rQSeNyow_i46NLv z;NT^y;`I2@rwsIH%i``k8_uvW=^cTMhtac(AvHE=l~d5Lcr@ znE1=6lSA**%deoeCZcqQ^n$O=2Mk&jB1eW$&+b!{vj>8E4e zFL5n=drT}HZDaaS4$9~rD86E1{eIv)Rp|OqNofx4Xkg+1 zem-z5s^OMp!n06C`xYdY=CL)6z1XIVVBoKm5%`W_T?~xAkwg$h>COVy=x%2LV|v*5 zcrxG7IM??T*5ZvrF-}%VbQ|cO!tJ1nv!yy^6q-Yl5$_UMb{9=X$5A=X7`{e#BH|UxOgRuYm@=zW~z>tj?Uuz8eUxBD84guY^Oos z?xwOfT-FM#J3s`WIevMIfuX6Kfx^vFs1nO)8*AaBSHlsCohA+EWWRWLEov;&AD}A7*j?bq#{HzSg869kK`(Zk z2s9t#dr?`ZMdn-x1i58d*qEzh?LM32DjZHX6}+7iRk$S+7ph4b2gjPk+>ss>{>E^s zV5KhO!{Z*Ds-OwT1FfhuGcxj3WE94Nx-&Wx*mOJwALcPNgwsDVYRteZPkbYgams~) zO49ap&Vkr81YGb#XNepj|9=XfxKw3}$3L`%ivst(T(2{#8>T3)2?cSr&k{a8&|_wu zGKE4xJoUZ0p3)W<$_=r*&=8MP(5>4Wm?J9ez`aYh>rDq|<8UK6Uc%(Qeuv{L_b|T& zG*v;%*pTPq+%nN1kp5PX4&fvIMiPL8l$I*eQfYUDjf0mtu%j2Nou`D8T5nEnid0Qt zP^!xjKL;+_Y$XPQSqqX&0HOVii_#wX-;{ZJrYy{HxZ{t5j_&V%{;)r0TDZI UK`3?d0000007*qoM6N<$f{I5JdH?_b literal 0 HcmV?d00001 diff --git a/src/DAISIE_IW.cpp b/src/DAISIE_IW.cpp new file mode 100644 index 00000000..3dc666f8 --- /dev/null +++ b/src/DAISIE_IW.cpp @@ -0,0 +1,264 @@ +// [[Rcpp::plugins(cpp14)]] +// [[Rcpp::plugins(openmp)]] +// [[Rcpp::depends(RcppEigen)]] +// [[Rcpp::depends(BH)]] + + +//' @export daisie_odeint_iw + + +#define EIGEN_USE_THREADS +#define STRICT_R_HEADERS +#include +#include +#include +#include +#include +#include +#include +#include + + +using namespace Rcpp; +using namespace Eigen; +using namespace boost::numeric::odeint; + + +namespace { + + using index_v = EIGEN_DEFAULT_DENSE_INDEX_TYPE; + + template + using index_t = DSizes; + + + template + index_t dim_to_index(DoubleVector v) + { + IntegerVector iv = v.attr("dim"); + auto ret = index_t{}; + for (size_t i = 0; i < Rank; ++i) { + ret[i] = iv[i]; + } + return ret; + } + + + template + index_t iofs(index_v i0, index_v i1, index_v i2); + + + template <> + index_t<3> iofs<3>(index_v i0, index_v i1, index_v i2) + { + return index_t<3>{i0, i1, i2}; + } + + + template <> + index_t<4> iofs<4>(index_v i0, index_v i1, index_v i2) + { + return index_t<4>{i0, i1, i2, 0}; + } + + + template + class cpp_daisie_iw + { + static constexpr int rank = Rank; + using index = index_t; + using tensor = Tensor; + using tmap = TensorMap; + using ctensor = const Tensor; + using ctmap = TensorMap; + using matrix = Tensor; + using cmatrix = Tensor; + using cmmap = TensorMap; + + public: + explicit cpp_daisie_iw(List pars); + void rhs(const double* x, double* rdx, ThreadPoolDevice* dev); + + private: + static tmap mapt(List pars, const char* name) + { + DoubleVector v = pars[name]; + auto dim = dim_to_index(v); + return tmap(v.begin(), dim); + } + static ctmap cmapt(List pars, const char* name) + { + DoubleVector v = pars[name]; + auto dim = dim_to_index(v); + return ctmap(v.begin(), dim); + } + + double laa_; + std::array c_; + matrix ki_; + }; + + + template + cpp_daisie_iw::cpp_daisie_iw(List pars) + : laa_(pars["laa"]), + c_{ + cmapt(pars, "c1"), + cmapt(pars, "c2"), + cmapt(pars, "c3"), + cmapt(pars, "c4"), + cmapt(pars, "c5"), + cmapt(pars, "c6"), + cmapt(pars, "c7"), + cmapt(pars, "c89"), + cmapt(pars, "c10"), + cmapt(pars, "c11"), + cmapt(pars, "c12"), + cmapt(pars, "c13") + } + { + if (rank == 4) { + DoubleVector ki = pars["ki"]; + auto dim = dim_to_index<2>(ki); + ki_ = cmmap(ki.begin(), dim); + } + } + + + template <> + void cpp_daisie_iw<3>::rhs(const double* rx, double* rdx, ThreadPoolDevice* dev) + { + const auto dim_c = c_[0].dimensions(); + tmap dx(rdx, dim_c); + std::array, rank> xxpad = { + std::make_pair(1,1), + std::make_pair(1,1), + std::make_pair(2,1) + }; + ctmap x(rx, dim_c); + auto xx = x.pad(xxpad); + auto xce = xx.slice(iofs(1,1,1), dim_c); + auto x12 = xx.slice(iofs(1,1,2), dim_c); + auto ddx = + c_[0] * xx.slice(iofs(0,1,2), dim_c) + + c_[1] * xx.slice(iofs(1,0,2), dim_c) + + c_[2] * xx.slice(iofs(2,1,2), dim_c) + + c_[3] * xx.slice(iofs(1,2,2), dim_c) + + c_[4] * xx.slice(iofs(1,1,3), dim_c) + + c_[5] * xx.slice(iofs(2,1,0), dim_c) + + c_[6] * xx.slice(iofs(1,2,0), dim_c) + + c_[7] * xce + + c_[8] * xx.slice(iofs(2,1,1), dim_c) + + c_[9] * xx.slice(iofs(1,2,1), dim_c) + + c_[10] * x12; + dx.device(*dev) = ddx; + } + + + template <> + void cpp_daisie_iw<4>::rhs(const double* rx, double* rdx, ThreadPoolDevice* dev) + { + const auto dim_c = c_[0].dimensions(); + tmap dx(rdx, dim_c); + std::array, rank> xxpad = { + std::make_pair(1,1), + std::make_pair(1,1), + std::make_pair(2,1), + std::make_pair(0,0) + }; + ctmap x(rx, dim_c); + auto xx = x.pad(xxpad); + auto xce = xx.slice(iofs(1,1,1), dim_c); + auto x12 = xx.slice(iofs(1,1,2), dim_c); + auto ddx = + c_[0] * xx.slice(iofs(0,1,2), dim_c) + + c_[1] * xx.slice(iofs(1,0,2), dim_c) + + c_[2] * xx.slice(iofs(2,1,2), dim_c) + + c_[3] * xx.slice(iofs(1,2,2), dim_c) + + c_[4] * xx.slice(iofs(1,1,3), dim_c) + + c_[5] * xx.slice(iofs(2,1,0), dim_c) + + c_[6] * xx.slice(iofs(1,2,0), dim_c) + + c_[7] * xce + + c_[8] * xx.slice(iofs(2,1,1), dim_c) + + c_[9] * xx.slice(iofs(1,2,1), dim_c) + + c_[10] * x12; + const array, 1> product_dims = { std::make_pair(3, 1) }; + dx.device(*dev) = ddx + (laa_ * x12 + c_[11] * xce).contract(ki_, product_dims); + } + + + struct daisie_iw_wrapper + { + std::unique_ptr pool; + std::unique_ptr dev; + + std::unique_ptr> iw3; + std::unique_ptr> iw4; + + daisie_iw_wrapper(List pars) + { + pool.reset(new ThreadPool(std::thread::hardware_concurrency())); + dev.reset(new ThreadPoolDevice(pool.get(), std::thread::hardware_concurrency())); + + int sysdim = pars["sysdim"]; + if (1 == sysdim) { + iw3 = std::make_unique>(pars); + } + else { + iw4 = std::make_unique>(pars); + } + } + + // odeint interface + void operator()(const std::vector& x, std::vector& dxdt, double) + { + (iw3) ? iw3->rhs(x.data(), dxdt.data(), dev.get()) + : iw4->rhs(x.data(), dxdt.data(), dev.get()); + } + }; + + + template + void integrate(double atol, double rtol, IWrap iw, std::vector& y, double t0, double t1) + { + integrate_adaptive(make_controlled(atol, rtol), iw, y, t0, t1, 0.1 * (t1 - t0)); + } + +} + + +//' Driver for the boost::odeint solver +//' +//' @name daisie_odeint_iw +RcppExport SEXP daisie_odeint_iw(SEXP ry, SEXP rtimes, SEXP rpars, SEXP Stepper, SEXP atolint, SEXP reltolint) { + BEGIN_RCPP + Rcpp::RObject rcpp_result_gen; + Rcpp::RNGScope rcpp_rngScope_gen; + auto y = as>(ry); + auto times = as>(rtimes); + auto pars = as(rpars); + auto stepper = as(Stepper); + auto atol = as(atolint); + auto rtol = as(reltolint); + + daisie_iw_wrapper iw(pars); + if ("odeint::runge_kutta_cash_karp54" == stepper) { + integrate>>(atol, rtol, std::ref(iw), y, times[0], times[1]); + } + else if ("odeint::runge_kutta_fehlberg78" == stepper) { + integrate>>(atol, rtol, std::ref(iw), y, times[0], times[1]); + } + else if ("odeint::runge_kutta_dopri5" == stepper) { + integrate>>(atol, rtol, std::ref(iw), y, times[0], times[1]); + } + else if ("odeint::bulirsch_stoer" == stepper) { + using stepper_t = bulirsch_stoer>; + integrate_adaptive(stepper_t(atol, rtol), std::ref(iw), y, times[0], times[1], 0.1 * (times[1] - times[0])); + } + else { + throw std::runtime_error("daisie_odeint_iw: unknown stepper"); + } + rcpp_result_gen = y; + return rcpp_result_gen; + END_RCPP +} diff --git a/src/Makevars b/src/Makevars deleted file mode 100644 index b7671668..00000000 --- a/src/Makevars +++ /dev/null @@ -1,5 +0,0 @@ -all : clean - -clean : - @rm -rf *.mod *.o - diff --git a/src/R_init_DAISIE.c b/src/R_init_DAISIE.c index 203d7114..e31475a6 100644 --- a/src/R_init_DAISIE.c +++ b/src/R_init_DAISIE.c @@ -17,8 +17,19 @@ static const R_FortranMethodDef FortranEntries[] = { {NULL, NULL, 0} }; + +/* C bindings */ +extern SEXP daisie_odeint_iw(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); + +static const R_CallMethodDef CallEntries[] = { + {"daisie_odeint_iw", (DL_FUNC) &daisie_odeint_iw, 6}, + {NULL, NULL, 0} +}; + + + void R_init_DAISIE(DllInfo *dll) { - R_registerRoutines(dll, NULL, NULL, FortranEntries, NULL); - R_useDynamicSymbols(dll, FALSE); + R_registerRoutines(dll, NULL, CallEntries, FortranEntries, NULL); + R_useDynamicSymbols(dll, TRUE); } diff --git a/tests/testthat.R b/tests/testthat.R index 99d7b72c..a745fa8d 100644 --- a/tests/testthat.R +++ b/tests/testthat.R @@ -1,5 +1,8 @@ +# The setting of R_TESTS exists to work around an R bug. See +# https://github.com/hadley/testthat/issues/144 +# We should remove it when the issue is resolved. Sys.setenv(R_TESTS = "") library(testthat) library(DAISIE) -test_check("DAISIE") \ No newline at end of file +test_check("DAISIE") diff --git a/tests/testthat/test-DAISIE_ML1.R b/tests/testthat/test-DAISIE_ML1.R index 5cbe22d1..eb8c0c11 100644 --- a/tests/testthat/test-DAISIE_ML1.R +++ b/tests/testthat/test-DAISIE_ML1.R @@ -1,68 +1,62 @@ context("DAISIE_ML1") test_that("use", { - if (Sys.getenv("TRAVIS") != "") { + skip_if(Sys.getenv("CI") == "", message = "Run only on CI") - # This is a rough MLE test, built for fast execution. A more thorough test - # can be found in the GitHub repository Neves-P/DAISIEtesting + # This is a rough MLE test, built for fast execution. A more thorough test + # can be found in the GitHub repository Neves-P/DAISIEtesting - utils::data(Galapagos_datalist) - datalist <- Galapagos_datalist - initparsopt <- c(2.5, 2.7, 20, 0.009, 1.01) - ddmodel <- 11 - idparsopt <- 1:5 - parsfix <- NULL - idparsfix <- NULL - tested_MLE <- DAISIE:::DAISIE_ML1( - datalist = datalist, + utils::data(Galapagos_datalist) + datalist <- Galapagos_datalist + initparsopt <- c(2.5, 2.7, 20, 0.009, 1.01) + ddmodel <- 11 + idparsopt <- 1:5 + parsfix <- NULL + idparsfix <- NULL + tested_MLE <- DAISIE:::DAISIE_ML1( + datalist = datalist, + initparsopt = initparsopt, + idparsopt = idparsopt, + parsfix = parsfix, + ddmodel = ddmodel, + idparsfix = idparsfix, + verbose = 0, + tol = c(0.01, 0.1, 0.001), + res = 15, + tolint = c(0.1, 0.01) + ) + expected_MLE <- data.frame( + lambda_c = 4.1558928147225656, + mu = 4.9989880317542603, + K = 514.14066875326353, + gamma = 0.020398370167867434, + lambda_a = 3.7589983231693607, + loglik = -63.993218343764838, + df = 5L, + conv = 0L + ) + expect_equal(tested_MLE, expected_MLE) + +}) + +test_that("abuse", { + skip_if(Sys.getenv("CI") == "", message = "Run only on CI") + utils::data(Galapagos_datalist) + datalist <- Galapagos_datalist + initparsopt <- c(2.5, 2.7, 20, 0.009, 1.01) + ddmodel <- 11 + idparsopt <- 1:5 + parsfix <- NULL + idparsfix <- NULL + expect_error( + DAISIE:::DAISIE_ML1( + datalist = "nonsense", initparsopt = initparsopt, idparsopt = idparsopt, parsfix = parsfix, ddmodel = ddmodel, idparsfix = idparsfix, - verbose = 0, - tol = c(0.01, 0.1, 0.001), - res = 15, - tolint = c(0.1, 0.01) - ) - expected_MLE <- data.frame( - lambda_c = 4.1558928147225656, - mu = 4.9989880317542603, - K = 514.14066875326353, - gamma = 0.020398370167867434, - lambda_a = 3.7589983231693607, - loglik = -63.993218343764838, - df = 5L, - conv = 0L - ) - expect_equal(tested_MLE, expected_MLE) - } else { - skip("Run only on Travis") - } - -}) - -test_that("abuse", { - if (Sys.getenv("TRAVIS") != "") { - utils::data(Galapagos_datalist) - datalist <- Galapagos_datalist - initparsopt <- c(2.5, 2.7, 20, 0.009, 1.01) - ddmodel <- 11 - idparsopt <- 1:5 - parsfix <- NULL - idparsfix <- NULL - expect_error( - DAISIE:::DAISIE_ML1( - datalist = "nonsense", - initparsopt = initparsopt, - idparsopt = idparsopt, - parsfix = parsfix, - ddmodel = ddmodel, - idparsfix = idparsfix, - verbose = 0 - ) + verbose = 0 ) - } else { - skip("Run only on Travis") - } + ) }) diff --git a/tests/testthat/test-DAISIE_ML2.R b/tests/testthat/test-DAISIE_ML2.R index 6113074b..6c7705a0 100644 --- a/tests/testthat/test-DAISIE_ML2.R +++ b/tests/testthat/test-DAISIE_ML2.R @@ -4,89 +4,83 @@ test_that("use", { # This is a rough MLE test, built for fast execution. A more thorough test # can be found in the GitHub repository Neves-P/DAISIEtesting - if (Sys.getenv("TRAVIS") != "") { - utils::data(Macaronesia_datalist, package = "DAISIE") - tested_MLE <- DAISIE:::DAISIE_ML2( - datalist = Macaronesia_datalist, - initparsopt = c( - 1.053151832, - 0.052148979, - 0.512939011, - 0.133766934, - 0.152763179 - ), - idparsmat = rbind( - 1:5, - c(6, 2, 3, 7, 5), - 1:5,1:5 - ), - idparsopt = c(2, 4, 5, 6, 7), - parsfix = c(0, Inf), - idparsfix = c(1, 3), - tol = c(0.01, 0.1, 0.001), - res = 15, - tolint = c(0.1, 0.01) - ) + skip_if(Sys.getenv("CI") == "", message = "Run only on CI") + utils::data(Macaronesia_datalist, package = "DAISIE") + tested_MLE <- DAISIE:::DAISIE_ML2( + datalist = Macaronesia_datalist, + initparsopt = c( + 1.053151832, + 0.052148979, + 0.512939011, + 0.133766934, + 0.152763179 + ), + idparsmat = rbind( + 1:5, + c(6, 2, 3, 7, 5), + 1:5,1:5 + ), + idparsopt = c(2, 4, 5, 6, 7), + parsfix = c(0, Inf), + idparsfix = c(1, 3), + tol = c(0.01, 0.1, 0.001), + res = 15, + tolint = c(0.1, 0.01) + ) - expected_MLE <- data.frame( - lambda_c = c(0.0, - 0.3397037946009278, - 0.0, - 0.0), - mu = c(2.8044328568380257, - 2.8044328568380257, - 2.8044328568380257, - 2.8044328568380257), - K = c(Inf, - Inf, - Inf, - Inf), - gamma = c(0.14401353274629849, - 0.33209131444203649, - 0.14401353274629849, - 0.14401353274629849), - lambda_a = c(1.2641967865150285, - 1.2641967865150285, - 1.2641967865150285 , - 1.2641967865150285), - loglik = c(-413.80819700475951, - -413.80819700475951, - -413.80819700475951, - -413.80819700475951), - df = c(5L, 5L, 5L, 5L), - conv = c(0L, 0L, 0L, 0L) - ) - expect_equal(tested_MLE, expected_MLE) - } else { - testthat::skip("Run only on Travis") - } + expected_MLE <- data.frame( + lambda_c = c(0.0, + 0.3397037946009278, + 0.0, + 0.0), + mu = c(2.8044328568380257, + 2.8044328568380257, + 2.8044328568380257, + 2.8044328568380257), + K = c(Inf, + Inf, + Inf, + Inf), + gamma = c(0.14401353274629849, + 0.33209131444203649, + 0.14401353274629849, + 0.14401353274629849), + lambda_a = c(1.2641967865150285, + 1.2641967865150285, + 1.2641967865150285 , + 1.2641967865150285), + loglik = c(-413.80819700475951, + -413.80819700475951, + -413.80819700475951, + -413.80819700475951), + df = c(5L, 5L, 5L, 5L), + conv = c(0L, 0L, 0L, 0L) + ) + expect_equal(tested_MLE, expected_MLE) }) test_that("abuse", { - if (Sys.getenv("TRAVIS") != "") { - expect_error(tested_MLE <- DAISIE:::DAISIE_ML2( - datalist = "nonsense", - initparsopt = c( - 1.053151832, - 0.052148979, - 0.512939011, - 0.133766934, - 0.152763179 - ), - idparsmat = rbind( - 1:5, - c(6, 2, 3, 7, 5), - 1:5,1:5 - ), - idparsopt = c(2, 4, 5, 6, 7), - parsfix = c(0, Inf), - idparsfix = c(1, 3), - tol = c(0.01, 0.1, 0.001), - res = 15, - tolint = c(0.1, 0.01) - )) - } else { - testthat::skip("Run only on Travis or AppVeyor") - } + skip_if(Sys.getenv("CI") == "", message = "Run only on CI") + expect_error(tested_MLE <- DAISIE:::DAISIE_ML2( + datalist = "nonsense", + initparsopt = c( + 1.053151832, + 0.052148979, + 0.512939011, + 0.133766934, + 0.152763179 + ), + idparsmat = rbind( + 1:5, + c(6, 2, 3, 7, 5), + 1:5,1:5 + ), + idparsopt = c(2, 4, 5, 6, 7), + parsfix = c(0, Inf), + idparsfix = c(1, 3), + tol = c(0.01, 0.1, 0.001), + res = 15, + tolint = c(0.1, 0.01) + )) }) diff --git a/tests/testthat/test-DAISIE_ML3.R b/tests/testthat/test-DAISIE_ML3.R new file mode 100644 index 00000000..9796ec57 --- /dev/null +++ b/tests/testthat/test-DAISIE_ML3.R @@ -0,0 +1,85 @@ +context("DAISIE_ML3") +test_that("use", { + skip_if(Sys.getenv("CI") == "", message = "Run only on CI") + skip("WIP") + # This is a rough MLE test, built for fast execution. A more thorough test + # can be found in the GitHub repository Neves-P/DAISIEtesting + + utils::data(Galapagos_datalist, package = "DAISIE") + pars1 <- c(0.2, 0.1, 17, 0.001, 0.3) + pars1_td <- c( + max_area = 1, + proportional_peak_t = 0.2, + peak_sharpness = 1, + total_island_age = 15, + lac = pars1[1], + mu_min = pars1[2], + mu_max = pars1[2], + K0 = pars1[3], + gam = pars1[4], + laa = pars1[5] + ) + tested_MLE <- DAISIE:::DAISIE_ML3( + datalist = Galapagos_datalist, + initparsopt = pars1_td[5:10], + idparsopt = 5:10, + parsfix = pars1_td[1:4], + idparsfix = 1:4, + island_ontogeny = 1 + ) + idpars <- sort(c(5:10, 1:4)) + expected_MLE <- data.frame( + lambda_c = c(0.0, + 0.133766934, + 0.0, + 0.0), + mu = c(1.0531518319999997, + 1.0531518319999997, + 1.0531518319999997, + 1.0531518319999997), + K = c(Inf, + Inf, + Inf, + Inf), + gamma = c(0.052148978999999998, + 0.152763178999999999, + 0.052148978999999998, + 0.052148978999999998), + lambda_a = c(0.51293901099999994, + 0.51293901099999994, + 0.51293901099999994, + 0.51293901099999994), + loglik = c(-454.93478332906614, + -454.93478332906614, + -454.93478332906614, + -454.93478332906614), + df = c(5L, 5L, 5L, 5L), + conv = c(0L, 0L, 0L, 0L) + ) + expect_equal(tested_MLE, expected_MLE) +}) + +test_that("abuse", { + skip_if(Sys.getenv("CI") == "", message = "Run only on CI") + expect_error(tested_MLE <- DAISIE:::DAISIE_ML2( + datalist = "nonsense", + initparsopt = c( + 1.053151832, + 0.052148979, + 0.512939011, + 0.133766934, + 0.152763179 + ), + idparsmat = rbind( + 1:5, + c(6, 2, 3, 7, 5), + 1:5,1:5 + ), + idparsopt = c(2, 4, 5, 6, 7), + parsfix = c(0, Inf), + idparsfix = c(1, 3), + tol = c(0.01, 0.1, 0.001), + res = 15, + tolint = c(0.1, 0.01) + )) +}) diff --git a/tests/testthat/test-DAISIE_MW_ML.R b/tests/testthat/test-DAISIE_MW_ML.R index 7d98b750..9962bcab 100644 --- a/tests/testthat/test-DAISIE_MW_ML.R +++ b/tests/testthat/test-DAISIE_MW_ML.R @@ -2,7 +2,7 @@ context("DAISIE_MW_ML") test_that("DAISIE_MW_ML produces correct output", { - if (Sys.getenv("TRAVIS") != "") { + skip_if(Sys.getenv("CI") == "", message = "Run only on CI") utils::data(archipelagos41) @@ -54,9 +54,6 @@ test_that("DAISIE_MW_ML produces correct output", { tol = 0.000001 ) - } else { - testthat::skip("Run only on Travis") - } }) test_that("DAISIE_MW_ML produces correct output when in parallel", { diff --git a/tests/testthat/test-DAISIE_ONEcolonist.R b/tests/testthat/test-DAISIE_ONEcolonist.R index 6f5d1a24..969fc862 100644 --- a/tests/testthat/test-DAISIE_ONEcolonist.R +++ b/tests/testthat/test-DAISIE_ONEcolonist.R @@ -70,12 +70,6 @@ test_that("DAISIE_ONEcolonist works on an oceanic DAISIE_sim_core", { expect_equal(result$missing_species, sim$missing_species) }) -#test_that("DAISIE_ONEcolonist works on a nonoceanic DAISIE_sim_core") -#test_that("DAISIE_ONEcolonist works on an oceanic DAISIE_sim_core with -#other_clades_same_ancestor) -#test_that("DAISIE_ONEcolonist works on a nonoceanic DAISIE_sim_core with -#other_clades_same_ancestor) - test_that("DAISIE_ONEcolonist works with >=2 cladogenetic with same ancestor", { set.seed(42) sim_time <- 10 @@ -166,3 +160,487 @@ test_that("DAISIE_ONEcolonist works with >=2 nonendemic with same ancestor", { ) }) +test_that("DAISIE_ONEcolonist stac and brts works for single colonist", { + sim_time <- 10 + + island_spec <- matrix(nrow = 4, ncol = 7, data = "x") + island_spec[, 1] <- c("6", "10", "9", "11") + island_spec[, 2] <- c("1", "1", "1", "1") + island_spec[, 3] <- c("0.755181833128345", + "0.755181833128345", + "0.755181833128345", + "0.755181833128345") + island_spec[, 4] <- c("C", "C", "C", "C") + island_spec[, 5] <- c("AA", "ABA", "B", "ABB") + island_spec[, 6] <- c("0.755181833128345", + "2.66196121187029", + "0.808949241539306", + "9.7444563652974") + island_spec[, 7] <- c(NA, NA, NA, NA) + colnames(island_spec) <- c( + "Species", + "Mainland Ancestor", + "Colonisation time (BP)", + "Species type", + "branch_code", + "branching time (BP)", + "Anagenetic_origin" + ) + stt_table <- NULL + result <- DAISIE:::DAISIE_ONEcolonist( + time = sim_time, + island_spec = island_spec, + stt_table = stt_table + ) + expect_equal( + result$branching_times, + c(sim_time, sort(as.numeric(island_spec[, 6]), decreasing = TRUE)) + ) + # Stac 2 for regular clade on island with no recolonization + expect_equal(result$stac, 2) +}) + +test_that("DAISIE_ONEcolonist stac and brts works for 1 nonendemic colonist", { + # With just 1 nonendemic recolonist, function works + + sim_time <- 2 + + island_spec <- matrix(nrow = 2, ncol = 7, data = "x") + island_spec[, 1] <- c("1", "2") + island_spec[, 2] <- c("1", "1") + island_spec[, 3] <- c("0.7", "0.6") + island_spec[, 4] <- c("A", "I") + island_spec[, 5] <- c(NA, NA) + island_spec[, 6] <- c(NA, NA) + island_spec[, 7] <- c("Immig_parent", NA) + colnames(island_spec) <- c( + "Species", + "Mainland Ancestor", + "Colonisation time (BP)", + "Species type", + "branch_code", + "branching time (BP)", + "Anagenetic_origin" + ) + stt_table <- NULL + result <- DAISIE:::DAISIE_ONEcolonist( + time = sim_time, + island_spec = island_spec, + stt_table = stt_table + ) + expect_equal( + result$branching_times, + c(sim_time, max(as.numeric(island_spec[, 3]))) + ) + + # Stac 3 for recolonisation cases + expect_equal(result$stac, 3) + + expect_equal(result$all_colonisations[[1]]$event_times, c(2, 0.7)) + expect_equal(result$all_colonisations[[1]]$species_type, "A") + + expect_equal(result$all_colonisations[[2]]$event_times, c(2, 0.6)) + expect_equal(result$all_colonisations[[2]]$species_type, "I") + +}) + +test_that("DAISIE_ONEcolonist stac and brts works for 2 endemic colonists, + 1 nonendemic", { + # With > 1 endemic recolonist, function works + + sim_time <- 2 + + island_spec <- matrix(nrow = 3, ncol = 7, data = "x") + island_spec[, 1] <- c("1", "2", "3") + island_spec[, 2] <- c("1", "1", "1") + island_spec[, 3] <- c("0.7", "0.6", "0.5") + island_spec[, 4] <- c("A", "A", "I") + island_spec[, 5] <- c(NA, NA, NA) + island_spec[, 6] <- c(NA, NA, NA) + island_spec[, 7] <- c("Immig_parent", "Immig_parent", NA) + colnames(island_spec) <- c( + "Species", + "Mainland Ancestor", + "Colonisation time (BP)", + "Species type", + "branch_code", + "branching time (BP)", + "Anagenetic_origin" + ) + stt_table <- NULL + result <- DAISIE:::DAISIE_ONEcolonist( + time = sim_time, + island_spec = island_spec, + stt_table = stt_table + ) + # Only include oldest colonisation time time + expect_equal( + result$branching_times, + c(sim_time, as.numeric(island_spec[, 3])[1:2]) + ) + # stac 3 for recolonisation cases + expect_equal(result$stac, 3) + + expect_equal(result$all_colonisations[[1]]$event_times, c(2, 0.7)) + expect_equal(result$all_colonisations[[1]]$species_type, "A") + + expect_equal(result$all_colonisations[[2]]$event_times, c(2, 0.6)) + expect_equal(result$all_colonisations[[2]]$species_type, "A") + + expect_equal(result$all_colonisations[[3]]$event_times, c(2, 0.5)) + expect_equal(result$all_colonisations[[3]]$species_type, "I") +}) + +test_that("DAISIE_ONEcolonist stac and brts works for 3 endemic colonists", { + # With > 1 endemic recolonist, function works + + sim_time <- 2 + + island_spec <- matrix(nrow = 3, ncol = 7, data = "x") + island_spec[, 1] <- c("1", "2", "3") + island_spec[, 2] <- c("1", "1", "1") + island_spec[, 3] <- c("0.7", "0.6", "0.5") + island_spec[, 4] <- c("A", "A", "A") + island_spec[, 5] <- c(NA, NA, NA) + island_spec[, 6] <- c(NA, NA, NA) + island_spec[, 7] <- c("Immig_parent", "Immig_parent", "Immig_parent") + colnames(island_spec) <- c( + "Species", + "Mainland Ancestor", + "Colonisation time (BP)", + "Species type", + "branch_code", + "branching time (BP)", + "Anagenetic_origin" + ) + stt_table <- NULL + result <- DAISIE:::DAISIE_ONEcolonist( + time = sim_time, + island_spec = island_spec, + stt_table = stt_table + ) + # Only include oldest colonisation time time + expect_equal( + result$branching_times, + c(sim_time, as.numeric(island_spec[, 3])[1:2]) + ) + # stac 3 for recolonisation cases + expect_equal(result$stac, 3) + + expect_length(result$all_colonisations, 3) + + expect_equal(result$all_colonisations[[1]]$event_times, c(2, 0.7)) + expect_equal(result$all_colonisations[[1]]$species_type, "A") + + expect_equal(result$all_colonisations[[2]]$event_times, c(2, 0.6)) + expect_equal(result$all_colonisations[[2]]$species_type, "A") + + expect_equal(result$all_colonisations[[3]]$event_times, c(2, 0.5)) + expect_equal(result$all_colonisations[[3]]$species_type, "A") +}) + + +test_that("DAISIE_ONEcolonist stac and brts works for 2 endemic clades", { + # With > 1 endemic clades, function works + + sim_time <- 2 + + + # Species Mainland Ancestor Colonisation time (BP) Species type branch_code branching time (BP) Anagenetic_origin + # [1,] "4" "1" "1.13468671408026" "C" "AA" "1.13468671408026" NA + # [2,] "3" "1" "1.13468671408026" "C" "B" "0.96545899791969" NA + # [3,] "5" "1" "1.13468671408026" "C" "AB" "0.68696590746724" NA + # [4,] "6" "1" "0.67395467208331" "C" "A" "0.67395467208331" NA + # [5,] "7" "1" "0.67395467208331" "C" "B" "0.34198900695798" NA + + + island_spec <- matrix(nrow = 5, ncol = 7, data = "x") + island_spec[, 1] <- c("4", "3", "5", "6", "7") + island_spec[, 2] <- c("1", "1", "1", "1", "1") + island_spec[, 3] <- + c("1.13468671408026", + "1.13468671408026", + "1.13468671408026", + "0.67395467208331", + "0.67395467208331") + island_spec[, 4] <- c("C", "C", "C", "C", "C") + island_spec[, 5] <- c("AA", "B", "AB", "A", "B") + island_spec[, 6] <- + c(1.13468671408026, + 0.96545899791969, + 0.68696590746724, + 0.67395467208331, + 0.34198900695798) + island_spec[, 7] <- c(NA, NA, NA, NA, NA) + colnames(island_spec) <- c( + "Species", + "Mainland Ancestor", + "Colonisation time (BP)", + "Species type", + "branch_code", + "branching time (BP)", + "Anagenetic_origin" + ) + stt_table <- NULL + result <- DAISIE:::DAISIE_ONEcolonist( + time = sim_time, + island_spec = island_spec, + stt_table = stt_table + ) + btimes <- sort(as.numeric(island_spec[, 6]), decreasing = TRUE) + btimes_sans_yng_col <- btimes[-4] + expect_equal( + result$branching_times, + c(sim_time, btimes_sans_yng_col) + ) + + expect_length(result$all_colonisations, 2) + + # stac 3 for recolonisation cases + expect_equal(result$stac, 3) + + # all_colonisations + expect_equal(result$all_colonisations[[1]]$event_times, c( + 2.0, + 1.13468671408026, + 0.96545899791969, + 0.68696590746724 + )) + expect_equal(result$all_colonisations[[1]]$species_type, "C") + + expect_equal(result$all_colonisations[[2]]$event_times, c( + 2.0, + 0.67395467208331, + 0.34198900695798 + )) + expect_equal(result$all_colonisations[[2]]$species_type, "C") +}) + +test_that("DAISIE_ONEcolonist stac and brts works for 2 endemic clades, + 1 nonendemic", { + + # With > 1 endemic clades, function works + + sim_time <- 2 + + + # Species Mainland Ancestor Colonisation time (BP) Species type branch_code branching time (BP) Anagenetic_origin + # [1,] "4" "1" "1.13468671408026" "C" "AA" "1.13468671408026" NA + # [2,] "3" "1" "1.13468671408026" "C" "B" "0.96545899791969" NA + # [3,] "5" "1" "1.13468671408026" "C" "AB" "0.68696590746724" NA + # [4,] "6" "1" "0.67395467208331" "C" "A" "0.67395467208331" NA + # [5,] "7" "1" "0.67395467208331" "C" "B" "0.34198900695798" NA + # [6,] "8" "1" "0.47395467208331" "I" NA NA NA + + + island_spec <- matrix(nrow = 6, ncol = 7, data = "x") + island_spec[, 1] <- c("4", "3", "5", "6", "7", "8") + island_spec[, 2] <- c("1", "1", "1", "1", "1", "1") + island_spec[, 3] <- + c("1.13468671408026", + "1.13468671408026", + "1.13468671408026", + "0.67395467208331", + "0.67395467208331", + "0.47395467208331") + island_spec[, 4] <- c("C", "C", "C", "C", "C", "I") + island_spec[, 5] <- c("AA", "B", "AB", "A", "B", NA) + island_spec[, 6] <- + c(1.13468671408026, + 0.96545899791969, + 0.68696590746724, + 0.67395467208331, + 0.34198900695798, + NA) + island_spec[, 7] <- c(NA, NA, NA, NA, NA, NA) + colnames(island_spec) <- c( + "Species", + "Mainland Ancestor", + "Colonisation time (BP)", + "Species type", + "branch_code", + "branching time (BP)", + "Anagenetic_origin" + ) + stt_table <- NULL + result <- DAISIE:::DAISIE_ONEcolonist( + time = sim_time, + island_spec = island_spec, + stt_table = stt_table + ) + # Here, branching times already exclude youngest colononisation + btimes_sans_yng_col <- sort(as.numeric(island_spec[, 6]), decreasing = TRUE) + expect_equal( + result$branching_times, + c(sim_time, btimes_sans_yng_col) + ) + + expect_length(result$all_colonisations, 3) + + # stac 3 for recolonisation cases + expect_equal(result$stac, 3) + + # all_colonisations + expect_equal(result$all_colonisations[[1]]$event_times, c( + 2.0, + 1.13468671408026, + 0.96545899791969, + 0.68696590746724 + )) + expect_equal(result$all_colonisations[[1]]$species_type, "C") + + expect_equal(result$all_colonisations[[2]]$event_times, c( + 2.0, + 0.67395467208331, + 0.34198900695798 + )) + expect_equal(result$all_colonisations[[2]]$species_type, "C") + + expect_equal(result$all_colonisations[[3]]$event_times, c( + 2.0, + 0.47395467208331 + )) + expect_equal(result$all_colonisations[[3]]$species_type, "I") +}) + +test_that("DAISIE_ONEcolonist stac and brts works for 2 endemic clades, + 1 endemic singleton", { + + # With > 1 endemic clades, function works + + sim_time <- 2 + + + # Species Mainland Ancestor Colonisation time (BP) Species type branch_code branching time (BP) Anagenetic_origin + # [1,] "4" "1" "1.13468671408026" "C" "AA" "1.13468671408026" NA + # [2,] "3" "1" "1.13468671408026" "C" "B" "0.96545899791969" NA + # [3,] "5" "1" "1.13468671408026" "C" "AB" "0.68696590746724" NA + # [4,] "6" "1" "0.7" "A" NA NA "Immig_parent" + # [5,] "7" "1" "0.67395467208331" "C" "A" "0.67395467208331" NA + # [6,] "8" "1" "0.67395467208331" "C" "B" "0.34198900695798" NA + + + island_spec <- matrix(nrow = 6, ncol = 7, data = "x") + island_spec[, 1] <- c("4", "3", "5", "6", "7", "8") + island_spec[, 2] <- c("1", "1", "1", "1", "1", "1") + island_spec[, 3] <- + c("1.13468671408026", + "1.13468671408026", + "1.13468671408026", + "0.7", + "0.67395467208331", + "0.67395467208331") + island_spec[, 4] <- c("C", "C", "C", "A", "C", "C") + island_spec[, 5] <- c("AA", "B", "AB", NA, "B", "C") + island_spec[, 6] <- + c(1.13468671408026, + 0.96545899791969, + 0.68696590746724, + NA, + 0.67395467208331, + 0.34198900695798) + island_spec[, 7] <- c(NA, NA, NA, "Immig_parent", NA, NA) + colnames(island_spec) <- c( + "Species", + "Mainland Ancestor", + "Colonisation time (BP)", + "Species type", + "branch_code", + "branching time (BP)", + "Anagenetic_origin" + ) + stt_table <- NULL + result <- DAISIE:::DAISIE_ONEcolonist( + time = sim_time, + island_spec = island_spec, + stt_table = stt_table + ) + + btimes_sans_yng_col <- c(2.0, 1.1346867, 0.9654590, 0.7, 0.6869659, 0.3419890) + expect_equal( + result$branching_times, + c(btimes_sans_yng_col) + ) + + expect_length(result$all_colonisations, 3) + + # stac 3 for recolonisation cases + expect_equal(result$stac, 3) + + # all_colonisations + expect_equal(result$all_colonisations[[1]]$event_times, c( + 2.0, + 1.13468671408026, + 0.96545899791969, + 0.68696590746724 + )) + expect_equal(result$all_colonisations[[1]]$species_type, "C") + + + expect_equal(result$all_colonisations[[2]]$event_times, c(2.0, 0.7)) + expect_equal(result$all_colonisations[[2]]$species_type, "A") + + expect_equal(result$all_colonisations[[3]]$event_times, c( + 2.0, + 0.67395467208331, + 0.34198900695798 + )) + expect_equal(result$all_colonisations[[3]]$species_type, "C") +}) + + +test_that("DAISIE_ONEcolonist stac and brts works for 1 anagenetic clade from + extinction of cladogenetic and 1 nonendemic recolonist ", { + sim_time <- 10.0 + n_mainland_species <- 1 + clado_rate <- 1.0 + ext_rate <- 0.7 + carr_cap <- 2 + imm_rate <- 1.0 + ana_rate <- 0 + set.seed(3) + area_pars <- DAISIE::create_area_pars( + max_area = 1, + current_area = 1, + proportional_peak_t = 0, + total_island_age = 0, + sea_level_amplitude = 0, + sea_level_frequency = 0, + island_gradient_angle = 0) + hyper_pars <- create_hyper_pars(d = 0, x = 0) + nonoceanic_pars <- c(0, 0) + result <- DAISIE:::DAISIE_sim_core_constant_rate( + time = sim_time, + mainland_n = n_mainland_species, + pars = c(clado_rate, ext_rate, carr_cap, imm_rate, ana_rate), + area_pars = area_pars, + hyper_pars = hyper_pars, + nonoceanic_pars = nonoceanic_pars) + # Species Mainland Ancestor Colonisation time (BP) Species type branch_code branching time (BP) Anagenetic_origin + # island_spec "4" "1" "6.33541590408438" "A" NA NA "Clado_extinct" + # "1" "1" "0.643802977852591" "I" NA NA NA + + expect_equal( + result$branching_times, + c(sim_time, 6.33541590408438) + ) + + expect_length(result$all_colonisations, 2) + + # stac 3 for recolonisation cases + expect_equal(result$stac, 3) + + # all_colonisations + expect_equal(result$all_colonisations[[1]]$event_times, c( + 10.0, + 6.33541590408438 + )) + expect_equal(result$all_colonisations[[1]]$species_type, "A") + + expect_equal(result$all_colonisations[[2]]$event_times, c( + 10.0, + 0.643802977852591) + ) + expect_equal(result$all_colonisations[[2]]$species_type, "I") +}) + diff --git a/tests/testthat/test-DAISIE_format_CS.R b/tests/testthat/test-DAISIE_format_CS.R index ff70e187..e9ba5716 100644 --- a/tests/testthat/test-DAISIE_format_CS.R +++ b/tests/testthat/test-DAISIE_format_CS.R @@ -321,7 +321,7 @@ test_that("use full stt", { expect_equal( formatted_CS_sim[[1]][[2]]$branching_times, - c(5.0000000000000000, 1.3487418169725700, 0.0921013811906803) + c(5.0000000000000000, 2.22760715636035, 1.3487418169725700, 0.0921013811906803) ) expect_equal( @@ -330,23 +330,22 @@ test_that("use full stt", { ) expect_equal( - formatted_CS_sim[[1]][[2]]$other_clades_same_ancestor[[1]]$brts_miss, - c(1.3487418169725700, 0.0921013811906803) + formatted_CS_sim[[1]][[2]]$all_colonisations[[1]]$event_times, + c(5.0, 2.22760716) ) expect_equal( - formatted_CS_sim[[1]][[2]]$other_clades_same_ancestor[[1]]$species_type, - "C" + formatted_CS_sim[[1]][[2]]$all_colonisations[[1]]$species_type, + "A" ) - expect_equal( - formatted_CS_sim[[1]][[2]]$other_clades_same_ancestor[[2]]$brts_miss, - 0.37899779115803 + formatted_CS_sim[[1]][[2]]$all_colonisations[[2]]$event_times, + c(5.0, 1.34874181697257, 0.0921013811906803) ) expect_equal( - formatted_CS_sim[[1]][[2]]$other_clades_same_ancestor[[2]]$species_type, - "I" + formatted_CS_sim[[1]][[2]]$all_colonisations[[2]]$species_type, + "C" ) expect_equal( @@ -436,8 +435,8 @@ test_that("use complete stt with ontogeny", { ) expect_equal( formatted_CS_sim[[1]][[2]]$branching_times, - c(10.00000000000000, 6.27382233420251989, 2.14112644569665012, - 1.41912369348019007, 1.13725415915635009, 0.54321135189076997, + c(10.00000000000000, 6.27382233420251989, 4.99629097366935, + 2.14112644569665012, 1.13725415915635009, 0.54321135189076997, 0.15055819094851100) ) @@ -626,7 +625,7 @@ test_that("full stt with two trait states", { expect_equal( formatted_CS_sim[[1]][[2]]$branching_times, - c(5.00000000, 4.24481817, 0.01277218) + c(5, 4.24481817, 3.61806444, 1.25876988, 0.01277218) ) expect_equal( @@ -639,3 +638,4 @@ test_that("full stt with two trait states", { 0 ) }) + diff --git a/tests/testthat/test-DAISIE_format_CS_full_stt.R b/tests/testthat/test-DAISIE_format_CS_full_stt.R index d543145a..d17c779c 100644 --- a/tests/testthat/test-DAISIE_format_CS_full_stt.R +++ b/tests/testthat/test-DAISIE_format_CS_full_stt.R @@ -295,7 +295,7 @@ test_that("complete stt, 2 type, no geodynamics, oceanic island, one trait state expect_equal( formatted_CS_sim[[1]][[2]]$branching_times, - c(5.00000000000000, 4.24481816687165, 1.44735043895909) + c(5, 4.24481816687165, 4.01220327283541, 1.44735043895909, 1.35145127332475) ) expect_equal( @@ -464,7 +464,7 @@ test_that("complete stt, 1 type, no geodynamics, oceanic island, one trait state ) }) -test_that("complete stt, 1 type, no geodynamics, onoceanic,two trait states +test_that("complete stt, 1 type, no geodynamics, oceanic,two trait states (same arguments as geodynamics, 5 pars)", { pars <- c(0.4, 0.2, 10, 2, 0.5) totaltime <- 1 @@ -472,7 +472,6 @@ test_that("complete stt, 1 type, no geodynamics, onoceanic,two trait states verbose <- FALSE set.seed(1) replicates <- 3 - nonoceanic_pars = c(0, 0) island_ontogeny = 0 sea_level = 0 extcutoff = 1000 @@ -502,7 +501,6 @@ test_that("complete stt, 1 type, no geodynamics, onoceanic,two trait states time = totaltime, mainland_n = 1, pars = pars, - nonoceanic_pars = nonoceanic_pars, island_ontogeny = island_ontogeny, sea_level = sea_level, extcutoff = extcutoff, @@ -531,7 +529,6 @@ test_that("complete stt, 1 type, no geodynamics, onoceanic,two trait states time = totaltime, mainland_n = 0, pars = pars, - nonoceanic_pars = nonoceanic_pars, island_ontogeny = island_ontogeny, sea_level = sea_level, extcutoff = extcutoff, @@ -561,3 +558,67 @@ test_that("complete stt, 1 type, no geodynamics, onoceanic,two trait states ) }) + +test_that("when no colonization happens returns 0", { + pars <- c(0.4, 0.2, 10, 0.000001, 0.5) + totaltime <- 1 + mainland_n <- 1 + area_pars <- DAISIE::create_area_pars( + max_area = 1, + current_area = 1, + proportional_peak_t = 0, + total_island_age = 0, + sea_level_amplitude = 0, + sea_level_frequency = 0, + island_gradient_angle = 0) + hyper_pars <- create_hyper_pars(d = 0, x = 0) + nonoceanic_pars <- c(0, 0) + verbose <- FALSE + set.seed(2) + replicates <- 1 + island_replicates <- list() + island_replicates[[1]] <- list() + full_list <- list() + out <- list() + for (m_spec in 1:mainland_n) { + out <- DAISIE:::DAISIE_sim_core_constant_rate( + time = totaltime, + mainland_n = 1, + pars = pars, + area_pars = area_pars, + hyper_pars = hyper_pars, + nonoceanic_pars = nonoceanic_pars + ) + full_list[[m_spec]] <- out + } + + island_replicates[[1]] <- full_list + + + + expect_silent( + formatted_CS_sim <- DAISIE:::DAISIE_format_CS_full_stt( + island_replicates = island_replicates, + time = totaltime, + M = mainland_n, + verbose = verbose + ) + ) + + expect_equal( + formatted_CS_sim[[1]][[1]]$island_age, + 1 + ) + expect_equal( + formatted_CS_sim[[1]][[1]]$not_present, + 1 + ) + expect_equal( + formatted_CS_sim[[1]][[1]]$stt_all[2, ], + c(Time = 0, nI = 0.0, nA = 0.0, nC = 0.0, present = 0.0) + ) + }) + + + + diff --git a/tests/testthat/test-DAISIE_format_CS_sampled_stt.R b/tests/testthat/test-DAISIE_format_CS_sampled_stt.R index e98df200..da9e96bf 100644 --- a/tests/testthat/test-DAISIE_format_CS_sampled_stt.R +++ b/tests/testthat/test-DAISIE_format_CS_sampled_stt.R @@ -213,7 +213,7 @@ test_that("sampled stt, 2 type, no geodynamics, oceanic island (same arguments "branching_times", "stac", "missing_species", - "other_clades_same_ancestor", + "all_colonisations", "type1or2" ) ) @@ -332,101 +332,3 @@ test_that("sampled stt, 1 type, no geodynamics, oceanic (same arguments as ) }) -test_that("sampled stt, 1 type, no geodynamics, onoceanic,two trait states - (same arguments as geodynamics, 5 pars)", { - pars <- c(0.4, 0.2, 10, 2, 0.5) - totaltime <- 1 - mainland_n <- 2 - verbose <- FALSE - set.seed(1) - replicates <- 3 - nonoceanic_pars = c(0, 0) - island_ontogeny = 0 - sea_level = 0 - extcutoff = 1000 - trait_pars <- create_trait_pars( - trans_rate = 0, - immig_rate2 = 2, - ext_rate2 = 0.2, - ana_rate2 = 0.5, - clado_rate2 = 0.4, - trans_rate2 = 0, - M2 = 2) - island_replicates <- list() - verbose <- FALSE - sample_freq <- 25 - - for (rep in 1:replicates) { - island_replicates[[rep]] <- list() - full_list <- list() - trait_pars_addcol <- create_trait_pars(trans_rate = 0, - immig_rate2 = 0, - ext_rate2 = 0, - ana_rate2 = 0, - clado_rate2 = 0, - trans_rate2 = 0, - M2 = 0) - for (m_spec in 1:mainland_n) { - full_list[[m_spec]] <- DAISIE_sim_core_trait_dependent( - time = totaltime, - mainland_n = 1, - pars = pars, - nonoceanic_pars = nonoceanic_pars, - island_ontogeny = island_ontogeny, - sea_level = sea_level, - extcutoff = extcutoff, - hyper_pars = create_hyper_pars(d = 0, x = 0), - area_pars = DAISIE::create_area_pars( - max_area = 1, - current_area = 1, - proportional_peak_t = 0, - total_island_age = 0, - sea_level_amplitude = 0, - sea_level_frequency = 0, - island_gradient_angle = 0), - trait_pars = trait_pars_addcol - ) - } - for(m_spec in (mainland_n + 1):(mainland_n + trait_pars$M2)) - { - trait_pars_onecolonize <- create_trait_pars(trans_rate = trait_pars$trans_rate, - immig_rate2 = trait_pars$immig_rate2, - ext_rate2 = trait_pars$ext_rate2, - ana_rate2 = trait_pars$ana_rate2, - clado_rate2 = trait_pars$clado_rate2, - trans_rate2 = trait_pars$trans_rate2, - M2 = 1) - full_list[[m_spec]] <- DAISIE_sim_core_trait_dependent( - time = totaltime, - mainland_n = 0, - pars = pars, - nonoceanic_pars = nonoceanic_pars, - island_ontogeny = island_ontogeny, - sea_level = sea_level, - extcutoff = extcutoff, - hyper_pars = create_hyper_pars(d = 0, x = 0), - area_pars = DAISIE::create_area_pars( - max_area = 1, - current_area = 1, - proportional_peak_t = 0, - total_island_age = 0, - sea_level_amplitude = 0, - sea_level_frequency = 0, - island_gradient_angle = 0), - trait_pars = trait_pars_onecolonize - ) - - } - island_replicates[[rep]] <- full_list - } - expect_silent( - formatted_CS_sim <- DAISIE:::DAISIE_format_CS_sampled_stt( - island_replicates = island_replicates, - time = totaltime, - M = mainland_n, - verbose = verbose, - sample_freq = sample_freq, - trait_pars = trait_pars - ) - ) -}) diff --git a/tests/testthat/test-DAISIE_format_CS_trait.R b/tests/testthat/test-DAISIE_format_CS_trait.R new file mode 100644 index 00000000..d06bbc7d --- /dev/null +++ b/tests/testthat/test-DAISIE_format_CS_trait.R @@ -0,0 +1,99 @@ +context("DAISIE_format_CS_trait") + +test_that("sampled stt, 1 type, no geodynamics, oceanic, two trait states + (same arguments as geodynamics, 5 pars)", { + pars <- c(0.4, 0.2, 10, 2, 0.5) + totaltime <- 1 + mainland_n <- 2 + verbose <- FALSE + set.seed(1) + replicates <- 3 + island_ontogeny = 0 + sea_level = 0 + extcutoff = 1000 + trait_pars <- create_trait_pars( + trans_rate = 0, + immig_rate2 = 2, + ext_rate2 = 0.2, + ana_rate2 = 0.5, + clado_rate2 = 0.4, + trans_rate2 = 0, + M2 = 2) + island_replicates <- list() + verbose <- FALSE + sample_freq <- 25 + + for (rep in 1:replicates) { + island_replicates[[rep]] <- list() + full_list <- list() + trait_pars_addcol <- create_trait_pars(trans_rate = 0, + immig_rate2 = 0, + ext_rate2 = 0, + ana_rate2 = 0, + clado_rate2 = 0, + trans_rate2 = 0, + M2 = 0) + for (m_spec in 1:mainland_n) { + full_list[[m_spec]] <- DAISIE_sim_core_trait_dependent( + time = totaltime, + mainland_n = 1, + pars = pars, + island_ontogeny = island_ontogeny, + sea_level = sea_level, + extcutoff = extcutoff, + hyper_pars = create_hyper_pars(d = 0, x = 0), + area_pars = DAISIE::create_area_pars( + max_area = 1, + current_area = 1, + proportional_peak_t = 0, + total_island_age = 0, + sea_level_amplitude = 0, + sea_level_frequency = 0, + island_gradient_angle = 0), + trait_pars = trait_pars_addcol + ) + } + for(m_spec in (mainland_n + 1):(mainland_n + trait_pars$M2)) + { + trait_pars_onecolonize <- create_trait_pars( + trans_rate = trait_pars$trans_rate, + immig_rate2 = trait_pars$immig_rate2, + ext_rate2 = trait_pars$ext_rate2, + ana_rate2 = trait_pars$ana_rate2, + clado_rate2 = trait_pars$clado_rate2, + trans_rate2 = trait_pars$trans_rate2, + M2 = 1 + ) + full_list[[m_spec]] <- DAISIE_sim_core_trait_dependent( + time = totaltime, + mainland_n = 0, + pars = pars, + island_ontogeny = island_ontogeny, + sea_level = sea_level, + extcutoff = extcutoff, + hyper_pars = create_hyper_pars(d = 0, x = 0), + area_pars = DAISIE::create_area_pars( + max_area = 1, + current_area = 1, + proportional_peak_t = 0, + total_island_age = 0, + sea_level_amplitude = 0, + sea_level_frequency = 0, + island_gradient_angle = 0), + trait_pars = trait_pars_onecolonize + ) + + } + island_replicates[[rep]] <- full_list + } + expect_silent( + formatted_CS_sim <- DAISIE:::DAISIE_format_CS_sampled_stt( + island_replicates = island_replicates, + time = totaltime, + M = mainland_n, + verbose = verbose, + sample_freq = sample_freq, + trait_pars = trait_pars + ) + ) + }) diff --git a/tests/testthat/test-DAISIE_format_IW.R b/tests/testthat/test-DAISIE_format_IW.R index df7967eb..73676f3b 100644 --- a/tests/testthat/test-DAISIE_format_IW.R +++ b/tests/testthat/test-DAISIE_format_IW.R @@ -487,38 +487,11 @@ test_that("silent with empty island with correct output", { expect_true(all.equal(formated_IW_sim, expected_IW_format, tolerance = 1e-7)) }) -test_that("new and v1.5 give same results", { - - tol <- 1e-13 - sim_time <- 10 - n_mainland_species <- 300 - clado_rate <- 1.0 - ext_rate <- 0.5 - carr_cap <- 10 - imm_rate <- 1.0 - ana_rate <- 1.0 - pars <- c(clado_rate, ext_rate, carr_cap, imm_rate, ana_rate) - rng_seed <- 42 - set.seed(rng_seed) - ff <- DAISIE_sim(time = sim_time, - M = n_mainland_species, - pars = pars, - replicates = 1, - divdepmodel = 'IW') - ff[[1]][[1]]$brts_table <- 0 - new <- DAISIE:::Add_brt_table(ff[[1]]) - new <- new[[1]]$brts_table[-1,] - old <- DAISIE:::Add_brt_table_v1_5(ff[[1]]) - old <- old[[1]]$brts_table[-1,] - testthat::expect_true(all(abs(new - old) < tol)) -}) - test_that("silent when species with two trait states with correct output", { pars <- c(0.4, 0.2, 10, 0.06, 0.5) time <- 5 mainland_n <- 10 - nonoceanic_pars <- c(0, 0) verbose <- FALSE replicates <- 3 island_ontogeny = 0 @@ -540,7 +513,6 @@ test_that("silent when species with two trait states with time = time, mainland_n = mainland_n, pars = pars, - nonoceanic_pars = nonoceanic_pars, trait_pars = trait_pars, island_ontogeny = island_ontogeny, sea_level = sea_level, diff --git a/tests/testthat/test-DAISIE_get_brts_mya.R b/tests/testthat/test-DAISIE_get_brts_mya.R deleted file mode 100644 index a8ae7227..00000000 --- a/tests/testthat/test-DAISIE_get_brts_mya.R +++ /dev/null @@ -1,9 +0,0 @@ -context("DAISIE_get_brts_mya") - -test_that("use", { - data(Galapagos_datatable) - branching_times_mya <- DAISIE_get_brts_mya(data_table = Galapagos_datatable) - expect_true(class(branching_times_mya) == "numeric") - expect_true(length(branching_times_mya) > 1) - expect_true(all(branching_times_mya > 0)) -}) diff --git a/tests/testthat/test-DAISIE_loglik_IW_solver.R b/tests/testthat/test-DAISIE_loglik_IW_solver.R new file mode 100644 index 00000000..0bc5fe8b --- /dev/null +++ b/tests/testthat/test-DAISIE_loglik_IW_solver.R @@ -0,0 +1,56 @@ +test_that("loglik IW various solver options give similar results", { + # Test is not included in coverage due to issue with running loglik_IW + # code from covr::package_coverage() + testthat::skip_on_covr() + + utils::data(frogs_datalist, package = "DAISIE") + pars1 <- c(0.2, 0.1, 1000.1, 0.001, 0.3) + pars2 <- c(40, 11, 0, 0) + + IW0 <- DAISIE::DAISIE_loglik_IW( + pars1 = pars1, + pars2 = pars2, + datalist = frogs_datalist, + methode = 'odeint::runge_kutta_fehlberg78', + abstolint = 1E-12, + reltolint = 1E-10, + ) + IW1 <- DAISIE::DAISIE_loglik_IW( + pars1 = pars1, + pars2 = pars2, + datalist = frogs_datalist, + methode = 'odeint::runge_kutta_cash_karp54', + abstolint = 1E-12, + reltolint = 1E-10, + ) + IW2 <- DAISIE::DAISIE_loglik_IW( + pars1 = pars1, + pars2 = pars2, + datalist = frogs_datalist, + methode = 'odeint::runge_kutta_dopri5', + abstolint = 1E-12, + reltolint = 1E-10, + ) + IW3 <- DAISIE::DAISIE_loglik_IW( + pars1 = pars1, + pars2 = pars2, + datalist = frogs_datalist, + methode = 'odeint::bulirsch_stoer', + abstolint = 1E-12, + reltolint = 1E-10, + ) + IW4 <- DAISIE::DAISIE_loglik_IW( + pars1 = pars1, + pars2 = pars2, + datalist = frogs_datalist, + methode = 'ode45', + abstolint = 1E-12, + reltolint = 1E-10, + ) + + #print(c(IW0,IW1,IW2,IW3,IW4)) + testthat::expect_equal(IW0,IW1, tolerance = 1E-4) + testthat::expect_equal(IW0,IW2, tolerance = 1E-4) + testthat::expect_equal(IW0,IW3, tolerance = 1E-4) + testthat::expect_equal(IW0,IW4, tolerance = 1E-4) +}) diff --git a/tests/testthat/test-DAISIE_loglik_integrate.R b/tests/testthat/test-DAISIE_loglik_integrate.R index 1b3b6b61..9c9c8320 100644 --- a/tests/testthat/test-DAISIE_loglik_integrate.R +++ b/tests/testthat/test-DAISIE_loglik_integrate.R @@ -73,8 +73,20 @@ test_that("DAISIE_loglik_integrand produces correct output", { reltolint = 1e-10, verbose = FALSE, pick = 1, - mean = 2.550687345, - sd = 1) + par_mean = 2.550687345, + par_sd = 1) expect_equal(output, -2.13638048160996) }) +test_that("rho produces correct output", { + output <- rho(DAISIE_par = 0.5, + DAISIE_dist_pars = list( + par_mean = 1, + par_sd = 1)) + expect_equal(output, -0.5) +}) + +test_that("transform_gamma_pars produces correct output", { + output <- transform_gamma_pars(par_mean = 1, par_sd = 1) + expect_equal(output, list(shape = 1, scale = 1)) +}) diff --git a/tests/testthat/test-DAISIE_sim_MW.R b/tests/testthat/test-DAISIE_sim_MW.R index ace1362d..b85fc0e0 100644 --- a/tests/testthat/test-DAISIE_sim_MW.R +++ b/tests/testthat/test-DAISIE_sim_MW.R @@ -2,184 +2,181 @@ context("DAISIE_sim_MW") test_that("DAISIE_sim_MW works", { - if (Sys.getenv("TRAVIS") != "" && 1 == 0) { - archipelago_data <- NULL - rm(archipelago_data) - utils::data(archipelago_data) - replicates <- 2 - M <- 1000 + skip(message = "Too slow to run") + archipelago_data <- NULL + rm(archipelago_data) + utils::data(archipelago_data) + replicates <- 2 + M <- 1000 - #M1 model - pars <- c(0.025, 0.249, 1.873, 0.145, 1.15098E-13, 8.408, 51.37, 0.254, 0.047, 0.416) - distance_dep <- 'power' - cladogenesis_dep <- 'NULL' - sigmoidal_par <- 'NULL' - M1 <- DAISIE_sim_MW( - archipelago_data = archipelago_data, - M = M, - pars = pars, - replicates = replicates, - distance_dep = distance_dep, - cladogenesis_dep = cladogenesis_dep, - sigmoidal_par = sigmoidal_par, - divdepmodel = 'CS' - ) - testthat::expect(!is.null(M1),'Empty result') + #M1 model + pars <- c(0.025, 0.249, 1.873, 0.145, 1.15098E-13, 8.408, 51.37, 0.254, 0.047, 0.416) + distance_dep <- 'power' + cladogenesis_dep <- 'NULL' + sigmoidal_par <- 'NULL' + M1 <- DAISIE_sim_MW( + archipelago_data = archipelago_data, + M = M, + pars = pars, + replicates = replicates, + distance_dep = distance_dep, + cladogenesis_dep = cladogenesis_dep, + sigmoidal_par = sigmoidal_par, + divdepmodel = 'CS' + ) + testthat::expect(!is.null(M1),'Empty result') - # M14 model - pars <- c(0.025849706, 0.25587591, 2.024864154, 0.143435441, Inf, 0, 66.03008037, 0.285332264, 0.049967897, 0.406500832) - distance_dep <- 'power' - cladogenesis_dep <- 'NULL' - sigmoidal_par <- 'NULL' - M14 <- DAISIE_sim_MW( - archipelago_data = archipelago_data, - M = M, - pars = pars, - replicates = replicates, - distance_dep = distance_dep, - cladogenesis_dep = cladogenesis_dep, - sigmoidal_par = sigmoidal_par, - divdepmodel = 'CS' - ) - testthat::expect(!is.null(M14),'Empty result') + # M14 model + pars <- c(0.025849706, 0.25587591, 2.024864154, 0.143435441, Inf, 0, 66.03008037, 0.285332264, 0.049967897, 0.406500832) + distance_dep <- 'power' + cladogenesis_dep <- 'NULL' + sigmoidal_par <- 'NULL' + M14 <- DAISIE_sim_MW( + archipelago_data = archipelago_data, + M = M, + pars = pars, + replicates = replicates, + distance_dep = distance_dep, + cladogenesis_dep = cladogenesis_dep, + sigmoidal_par = sigmoidal_par, + divdepmodel = 'CS' + ) + testthat::expect(!is.null(M14),'Empty result') - # M15 model - pars <- c(0.008, 0.188, 1.942, 0.150, Inf, 0, 67.65, 0.295, 0.060, 0.380, 0.231) - distance_dep <- 'power' - cladogenesis_dep <- 'additive' - sigmoidal_par <- 'NULL' - M15 <- DAISIE_sim_MW( - archipelago_data = archipelago_data, - M = M, - pars = pars, - replicates = replicates, - distance_dep = distance_dep, - cladogenesis_dep = cladogenesis_dep, - sigmoidal_par = sigmoidal_par, - divdepmodel = 'CS' - ) - testthat::expect(!is.null(M15),'Empty result') + # M15 model + pars <- c(0.008, 0.188, 1.942, 0.150, Inf, 0, 67.65, 0.295, 0.060, 0.380, 0.231) + distance_dep <- 'power' + cladogenesis_dep <- 'additive' + sigmoidal_par <- 'NULL' + M15 <- DAISIE_sim_MW( + archipelago_data = archipelago_data, + M = M, + pars = pars, + replicates = replicates, + distance_dep = distance_dep, + cladogenesis_dep = cladogenesis_dep, + sigmoidal_par = sigmoidal_par, + divdepmodel = 'CS' + ) + testthat::expect(!is.null(M15),'Empty result') - # M16 model - pars <- c( 0.040, 0.00002, 1.943, 0.150, Inf, 0, 67.50, 0.294, 0.059, 0.384, 0.026) - distance_dep <- 'power' - cladogenesis_dep <- 'interactive' - sigmoidal_par <- 'NULL' - M16 <- DAISIE_sim_MW( - archipelago_data = archipelago_data, - M = M, - pars = pars, - replicates = replicates, - distance_dep = distance_dep, - cladogenesis_dep = cladogenesis_dep, - sigmoidal_par = sigmoidal_par, - divdepmodel = 'CS' - ) - testthat::expect(!is.null(M16),'Empty result') + # M16 model + pars <- c( 0.040, 0.00002, 1.943, 0.150, Inf, 0, 67.50, 0.294, 0.059, 0.384, 0.026) + distance_dep <- 'power' + cladogenesis_dep <- 'interactive' + sigmoidal_par <- 'NULL' + M16 <- DAISIE_sim_MW( + archipelago_data = archipelago_data, + M = M, + pars = pars, + replicates = replicates, + distance_dep = distance_dep, + cladogenesis_dep = cladogenesis_dep, + sigmoidal_par = sigmoidal_par, + divdepmodel = 'CS' + ) + testthat::expect(!is.null(M16),'Empty result') - # M19 model - pars <- c(0.040073803, 0, 1.945656546, 0.150429656, Inf, 0, 67.25643672, 0.293635061, - 0.059096872, 0.382688527, 0.026510781) - distance_dep <- 'power' - cladogenesis_dep <- 'interactive' - sigmoidal_par <- 'NULL' - M19 <- DAISIE_sim_MW( - archipelago_data = archipelago_data, - M = M, - pars = pars, - replicates = replicates, - distance_dep = distance_dep, - cladogenesis_dep = cladogenesis_dep, - sigmoidal_par = sigmoidal_par, - divdepmodel = 'CS' - ) - testthat::expect(!is.null(M19),'Empty result') + # M19 model + pars <- c(0.040073803, 0, 1.945656546, 0.150429656, Inf, 0, 67.25643672, 0.293635061, + 0.059096872, 0.382688527, 0.026510781) + distance_dep <- 'power' + cladogenesis_dep <- 'interactive' + sigmoidal_par <- 'NULL' + M19 <- DAISIE_sim_MW( + archipelago_data = archipelago_data, + M = M, + pars = pars, + replicates = replicates, + distance_dep = distance_dep, + cladogenesis_dep = cladogenesis_dep, + sigmoidal_par = sigmoidal_par, + divdepmodel = 'CS' + ) + testthat::expect(!is.null(M19),'Empty result') - # M17 model - pars <- c(0.049, 0.116, 2.006, 0.156, Inf, 0, 67.29, 0.294, 0.057, 0.389, 42764.54) - distance_dep <- 'power' - cladogenesis_dep <- 'interactive1' - sigmoidal_par <- 'NULL' - M17 <- DAISIE_sim_MW( - archipelago_data = archipelago_data, - M = M, - pars = pars, - replicates = replicates, - distance_dep = distance_dep, - cladogenesis_dep = cladogenesis_dep, - sigmoidal_par = sigmoidal_par, - divdepmodel = 'CS' - ) - testthat::expect(!is.null(M17),'Empty result') + # M17 model + pars <- c(0.049, 0.116, 2.006, 0.156, Inf, 0, 67.29, 0.294, 0.057, 0.389, 42764.54) + distance_dep <- 'power' + cladogenesis_dep <- 'interactive1' + sigmoidal_par <- 'NULL' + M17 <- DAISIE_sim_MW( + archipelago_data = archipelago_data, + M = M, + pars = pars, + replicates = replicates, + distance_dep = distance_dep, + cladogenesis_dep = cladogenesis_dep, + sigmoidal_par = sigmoidal_par, + divdepmodel = 'CS' + ) + testthat::expect(!is.null(M17),'Empty result') - # M18 model - pars <- c(0.044, 0.131, 1.964, 0.152, Inf, 0, 63.77, 0.286, 0.056, 0.391, 42566.78) - distance_dep <- 'power' - cladogenesis_dep <- 'interactive2' - sigmoidal_par <- 'NULL' - M18 <- DAISIE_sim_MW( - archipelago_data = archipelago_data, - M = M, - pars = pars, - replicates = replicates, - distance_dep = distance_dep, - cladogenesis_dep = cladogenesis_dep, - sigmoidal_par = sigmoidal_par, - divdepmodel = 'CS' - ) - testthat::expect(!is.null(M18),'Empty result') + # M18 model + pars <- c(0.044, 0.131, 1.964, 0.152, Inf, 0, 63.77, 0.286, 0.056, 0.391, 42566.78) + distance_dep <- 'power' + cladogenesis_dep <- 'interactive2' + sigmoidal_par <- 'NULL' + M18 <- DAISIE_sim_MW( + archipelago_data = archipelago_data, + M = M, + pars = pars, + replicates = replicates, + distance_dep = distance_dep, + cladogenesis_dep = cladogenesis_dep, + sigmoidal_par = sigmoidal_par, + divdepmodel = 'CS' + ) + testthat::expect(!is.null(M18),'Empty result') - # sigmoidal colonisation - pars <- c(0.02, 0.25, 1.86, 0.14, 0.00000000001, 8.74, 108.35, 0.28, 0.05, 0.42, 0.17) - distance_dep <- 'sigmoidal' - sigmoidal_par <- 'colonisation' - cladogenesis_dep <- 'NULL' - M_sigm_col <- DAISIE_sim_MW( - archipelago_data = archipelago_data, - M = M, - pars = pars, - replicates = replicates, - distance_dep = distance_dep, - cladogenesis_dep = cladogenesis_dep, - sigmoidal_par = sigmoidal_par, - divdepmodel = 'CS' - ) - testthat::expect(!is.null(M_sigm_col),'Empty result') + # sigmoidal colonisation + pars <- c(0.02, 0.25, 1.86, 0.14, 0.00000000001, 8.74, 108.35, 0.28, 0.05, 0.42, 0.17) + distance_dep <- 'sigmoidal' + sigmoidal_par <- 'colonisation' + cladogenesis_dep <- 'NULL' + M_sigm_col <- DAISIE_sim_MW( + archipelago_data = archipelago_data, + M = M, + pars = pars, + replicates = replicates, + distance_dep = distance_dep, + cladogenesis_dep = cladogenesis_dep, + sigmoidal_par = sigmoidal_par, + divdepmodel = 'CS' + ) + testthat::expect(!is.null(M_sigm_col),'Empty result') - # sigmoidal anagenesis - pars <- c(0.02, 0.26, 1.85, 0.14, 3.82029371116082E-13, 8.07, 51.51, 0.25, 1.07, 1.70, 293.64) - distance_dep <- 'sigmoidal' - sigmoidal_par <- 'anagenesis' - cladogenesis_dep <- 'NULL' - M_sigm_ana <- DAISIE_sim_MW( - archipelago_data = archipelago_data, - M = M, - pars = pars, - replicates = replicates, - distance_dep = distance_dep, - cladogenesis_dep = cladogenesis_dep, - sigmoidal_par = sigmoidal_par, - divdepmodel = 'CS' - ) - testthat::expect(!is.null(M_sigm_ana),'Empty result') + # sigmoidal anagenesis + pars <- c(0.02, 0.26, 1.85, 0.14, 3.82029371116082E-13, 8.07, 51.51, 0.25, 1.07, 1.70, 293.64) + distance_dep <- 'sigmoidal' + sigmoidal_par <- 'anagenesis' + cladogenesis_dep <- 'NULL' + M_sigm_ana <- DAISIE_sim_MW( + archipelago_data = archipelago_data, + M = M, + pars = pars, + replicates = replicates, + distance_dep = distance_dep, + cladogenesis_dep = cladogenesis_dep, + sigmoidal_par = sigmoidal_par, + divdepmodel = 'CS' + ) + testthat::expect(!is.null(M_sigm_ana),'Empty result') - # sigmoidal cladogenesis - pars <- c(8.68, 0.31, 2.33, 0.17, 0.006, 1.57, 71.48, 0.30, 0.06, 0.37,2.26E+08) - distance_dep <- 'sigmoidal' - sigmoidal_par <- 'cladogenesis' - cladogenesis_dep <- 'NULL' - M_sigm_clado <- DAISIE_sim_MW( - archipelago_data = archipelago_data, - M = M, - pars = pars, - replicates = replicates, - distance_dep = distance_dep, - cladogenesis_dep = cladogenesis_dep, - sigmoidal_par = sigmoidal_par, - divdepmodel = 'CS' - ) - testthat::expect(!is.null(M_sigm_clado),'Empty result') - } else { - testthat::skip('Run only on Travis') - } + # sigmoidal cladogenesis + pars <- c(8.68, 0.31, 2.33, 0.17, 0.006, 1.57, 71.48, 0.30, 0.06, 0.37,2.26E+08) + distance_dep <- 'sigmoidal' + sigmoidal_par <- 'cladogenesis' + cladogenesis_dep <- 'NULL' + M_sigm_clado <- DAISIE_sim_MW( + archipelago_data = archipelago_data, + M = M, + pars = pars, + replicates = replicates, + distance_dep = distance_dep, + cladogenesis_dep = cladogenesis_dep, + sigmoidal_par = sigmoidal_par, + divdepmodel = 'CS' + ) + testthat::expect(!is.null(M_sigm_clado),'Empty result') }) diff --git a/tests/testthat/test-DAISIE_sim_constant_rate.R b/tests/testthat/test-DAISIE_sim_constant_rate.R index 58b72457..7bb8a7b0 100644 --- a/tests/testthat/test-DAISIE_sim_constant_rate.R +++ b/tests/testthat/test-DAISIE_sim_constant_rate.R @@ -20,6 +20,130 @@ test_that("A divdepmodel = 'CS' run should produce no output", { ) }) +test_that("A divdepmodel = 'CS' run with cond works as expected", { + set.seed(Sys.time()) # Always run a different sim + n_mainland_species <- 100 + island_age <- 5 + clado_rate <- 1.0 + ext_rate <- 1.0 + clade_carr_cap <- 10.0 + imm_rate <- 0.01 + ana_rate <- 1.0 + cond <- 5 + expect_silent( + out <- DAISIE_sim_constant_rate( + time = island_age, + M = n_mainland_species, + pars = c(clado_rate, ext_rate, clade_carr_cap, imm_rate, ana_rate), + replicates = 1, + divdepmodel = "CS", + plot_sims = FALSE, + verbose = FALSE, + cond = cond + ) + ) + + expect_true(out[[1]][[1]]$stt_all[nrow(out[[1]][[1]]$stt_all), 5] >= cond) + + +}) + + +test_that("A divdepmodel = 'CS' run with 2 types and cond > 0 throws warning", { + + n_mainland_species <- 100 + island_age <- 0.4 + clado_rate_type_1 <- 1.0 + ext_rate_type_1 <- 1.0 + clade_carr_cap_type_1 <- 10.0 + imm_rate_type_1 <- 0.01 + ana_rate_type_1 <- 1.0 + clado_rate_type_2 <- 1.0 + ext_rate_type_2 <- 1.0 + clade_carr_cap_type_2 <- 10.0 + imm_rate_type_2 <- 0.01 + ana_rate_type_2 <- 1.0 + prop_type2_pool <- 0.1 + replicates_apply_type2 <- TRUE + cond <- 5 + + expect_warning( + sim <- DAISIE_sim_constant_rate( + time = island_age, + M = n_mainland_species, + pars = c(clado_rate_type_1, + ext_rate_type_1, + clade_carr_cap_type_1, + imm_rate_type_1, + ana_rate_type_1, + clado_rate_type_2, + ext_rate_type_2, + clade_carr_cap_type_2, + imm_rate_type_2, + ana_rate_type_2), + replicates = 1, + prop_type2_pool = prop_type2_pool, + replicates_apply_type2 = replicates_apply_type2, + plot_sims = FALSE, + verbose = FALSE, + cond = cond + ), + paste0( + "Conditioning on number of colonisations is not implemented for 2 + type simulations. Returning result with no conditioning instead." + ) + ) +}) + + +test_that("A divdepmodel = 'CS' run with cond 0 and cond works as expected", { + set.seed(1) # Always run the same sim + n_mainland_species <- 100 + island_age <- 5 + clado_rate <- 1.0 + ext_rate <- 1.0 + clade_carr_cap <- 10.0 + imm_rate <- 0.01 + ana_rate <- 1.0 + cond <- 0 + expect_silent( + out_no_cond <- DAISIE_sim_constant_rate( + time = island_age, + M = n_mainland_species, + pars = c(clado_rate, ext_rate, clade_carr_cap, imm_rate, ana_rate), + replicates = 1, + divdepmodel = "CS", + plot_sims = FALSE, + verbose = FALSE, + cond = cond + ) + ) + + expect_true( + out_no_cond[[1]][[1]]$stt_all[nrow(out_no_cond[[1]][[1]]$stt_all), 5] < 5 + ) + + set.seed(1) # Always run the same sim + cond <- 5 + expect_silent( + out_cond <- DAISIE_sim_constant_rate( + time = island_age, + M = n_mainland_species, + pars = c(clado_rate, ext_rate, clade_carr_cap, imm_rate, ana_rate), + replicates = 1, + divdepmodel = "CS", + plot_sims = FALSE, + verbose = FALSE, + cond = cond + ) + ) + expect_true( + out_cond[[1]][[1]]$stt_all[nrow(out_cond[[1]][[1]]$stt_all), 5] >= 5 + ) + + +}) + test_that("A divdepmodel = 'IW' run should produce no output", { n_mainland_species <- 100 island_age <- 0.4 @@ -64,6 +188,7 @@ test_that("A divdepmodel = 'GW' run should produce no output", { ) }) + test_that("A 2 type with replicates_apply_type2 == TRUE divdepmodel = 'CS' run should produce no output", { n_mainland_species <- 100 @@ -557,5 +682,5 @@ test_that("2 type, no geodynamics, nonoceanic should give error", { prop_type2_pool = prop_type2_pool, nonoceanic_pars = nonoceanic_pars, verbose = FALSE) - ) + ) }) diff --git a/tests/testthat/test-DAISIE_sim_constant_rate_shift.R b/tests/testthat/test-DAISIE_sim_constant_rate_shift.R index c52277af..3b93e73b 100644 --- a/tests/testthat/test-DAISIE_sim_constant_rate_shift.R +++ b/tests/testthat/test-DAISIE_sim_constant_rate_shift.R @@ -2,18 +2,82 @@ context("DAISIE_sim_constant_rate_shift") test_that("use CS split-rates model", { expect_silent(DAISIE_sim_constant_rate_shift( - time = 10, - M = 10, - pars = c(1, 1, 1, 0.1, 1, 1, 1, 1, 0.1, 1), + time = 10, + M = 10, + pars = c(1, 1, 1, 0.1, 1, 1, 1, 1, 0.1, 1), + replicates = 1, + divdepmodel = "CS", + shift_times = 5, + plot_sims = FALSE, + verbose = FALSE + ) + ) +}) + +test_that("us CS split-rates with cond", { + set.seed(Sys.time()) # Always run a different sim + time <- 10 + M <- 10 + pars <- c(1, 1, 1, 0.1, 1, 1, 1, 1, 0.1, 1) + replicates <- 1 + divdepmodel <- "CS" + shift_times <- 5 + cond <- 5 + expect_silent( + out <- DAISIE_sim_constant_rate_shift( + time = time, + M = M, + pars = pars, replicates = 1, divdepmodel = "CS", - shift_times = 5, + shift_times = shift_times, plot_sims = FALSE, - verbose = FALSE + verbose = FALSE, + cond = cond ) ) + + expect_true(out[[1]][[1]]$stt_all[nrow(out[[1]][[1]]$stt_all), 5] >= cond) }) +test_that("expected cond or 0 cond CS split-rates model", { + set.seed(1) + cond <- 5 + expect_silent(out_no_cond <- DAISIE_sim_constant_rate_shift( + time = 10, + M = 10, + pars = c(1, 1, 1, 0.1, 1, 1, 1, 1, 0.1, 1), + replicates = 1, + divdepmodel = "CS", + shift_times = 5, + plot_sims = FALSE, + verbose = FALSE + )) + + expect_true( + out_no_cond[[1]][[1]]$stt_all[nrow(out_no_cond[[1]][[1]]$stt_all), 5] < cond + ) + + set.seed(1) + expect_silent(out_cond <- DAISIE_sim_constant_rate_shift( + time = 10, + M = 10, + pars = c(1, 1, 1, 0.1, 1, 1, 1, 1, 0.1, 1), + replicates = 1, + divdepmodel = "CS", + shift_times = 5, + plot_sims = FALSE, + verbose = FALSE, + cond = cond + )) + + expect_true( + out_cond[[1]][[1]]$stt_all[nrow(out_cond[[1]][[1]]$stt_all), 5] >= cond + ) + +}) + + test_that("use IW split-rates model", { expect_silent( DAISIE_sim_constant_rate_shift( diff --git a/tests/testthat/test-DAISIE_sim_core.R b/tests/testthat/test-DAISIE_sim_core.R index e99ed0b6..a9246018 100644 --- a/tests/testthat/test-DAISIE_sim_core.R +++ b/tests/testthat/test-DAISIE_sim_core.R @@ -1,139 +1,4 @@ context("DAISIE_sim_core") - -test_that("new and v1.4a should give same results", { - - tol <- 1e-13 - sim_time <- 10 - n_mainland_species <- 1 - clado_rate <- 1.0 - ext_rate <- 0.5 - carr_cap <- 10 - imm_rate <- 1.0 - ana_rate <- 1.0 - pars <- c(clado_rate, ext_rate, carr_cap, imm_rate, ana_rate) - rng_seed <- 42 - set.seed(rng_seed) - new <- DAISIE:::DAISIE_sim_core_constant_rate( - time = sim_time, - mainland_n = n_mainland_species, - pars = c(clado_rate, ext_rate, carr_cap, imm_rate, ana_rate), - nonoceanic_pars = c(0, 0), - hyper_pars = create_hyper_pars(d = 0, x = 0), - area_pars = create_area_pars( - max_area = 1, - current_area = 1, - proportional_peak_t = 0, - total_island_age = 0, - sea_level_amplitude = 0, - sea_level_frequency = 0, - island_gradient_angle = 0 - ) - ) - set.seed(rng_seed) - old <- DAISIE:::DAISIE_sim_core_1_4a( - time = sim_time, - mainland_n = n_mainland_species, - pars = pars - ) - - testthat::expect_true(all(names(new) == names(old))) - # stt_table has different content - testthat::expect_true(nrow(new$stt_table) == nrow(old$stt_table)) - # different branching times - testthat::expect_equal(length(new$branching_times), length(old$branching_times)) - testthat::expect_true(new$stac == old$stac) - testthat::expect_true(new$missing_species == old$missing_species) - testthat::expect_true(length(new$other_clades_same_ancestor) == length(old$other_clades_same_ancestor)) - testthat::expect_true(new$other_clades_same_ancestor[[1]]$species_type == old$other_clades_same_ancestor[[1]]$species_type) - - testthat::expect_true(all(abs(new$stt_table - old$stt_table) < tol)) - testthat::expect_true(all(abs(new$branching_times - old$branching_times) < tol)) - testthat::expect_true(new$other_clades_same_ancestor[[1]]$brts_miss == old$other_clades_same_ancestor[[1]]$brts_miss) - - # Frog example - rng_seed <- 1234 - set.seed(rng_seed) - time <- 30 - M <- 300 - parsCS <- c(0.437010183, 0.112633464, 36.43883246, 0.00073485, 0) - new <- DAISIE:::DAISIE_sim_core_constant_rate( - time = time, - mainland_n = M, - pars = parsCS, - nonoceanic_pars = c(0, 0), - hyper_pars = create_hyper_pars(d = 0, x = 0), - area_pars = create_area_pars( - max_area = 1, - current_area = 1, - proportional_peak_t = 0, - total_island_age = 0, - sea_level_amplitude = 0, - sea_level_frequency = 0, - island_gradient_angle = 0 - ) - ) - set.seed(rng_seed) - old <- DAISIE:::DAISIE_sim_core_1_4a( - time = time, - mainland_n = M, - pars = parsCS - ) - - testthat::expect_true(all(names(new) == names(old))) - # stt_table has different content - testthat::expect_true(nrow(new$stt_table) == nrow(old$stt_table)) - # different branching times - testthat::expect_equal(length(new$branching_times), length(old$branching_times)) - testthat::expect_true(all(abs(new$stt_table - old$stt_table) < tol)) - - for(i in 1:2){ - testthat::expect_true(new$taxon_list[[i]]$stac == old$taxon_list[[i]]$stac) - testthat::expect_true(new$taxon_list[[i]]$missing_species == old$taxon_list[[i]]$missing_species) - testthat::expect_true(length(new$taxon_list[[i]]$other_clades_same_ancestor) == length(old$taxon_list[[i]]$other_clades_same_ancestor)) - testthat::expect_true(all(abs(new$taxon_list[[i]]$branching_times - old$taxon_list[[i]]$branching_times) < tol)) - } -}) - -test_that("new and v1.5 should give same results", { - - # Frog example - tol <- 1e-14 - rng_seed <- 1234 - set.seed(rng_seed) - time <- 30 - M <- 300 - parsCS <- c(0.437010183, 0.112633464, 36.43883246, 0.00073485, 0) - new <- DAISIE:::DAISIE_sim_core_constant_rate( - time = time, - mainland_n = M, - pars = parsCS, - nonoceanic_pars = c(0, 0), - hyper_pars = create_hyper_pars(d = 0, x = 0), - area_pars = create_area_pars( - max_area = 1, - current_area = 1, - proportional_peak_t = 0, - total_island_age = 0, - sea_level_amplitude = 0, - sea_level_frequency = 0, - island_gradient_angle = 0 - ) - ) - set.seed(rng_seed) - old <- DAISIE:::DAISIE_sim_core_1_5( - time = time, - mainland_n = M, - pars = parsCS - ) - testthat::expect_true(all(names(new) == names(old))) - # stt_table has different content - testthat::expect_true(nrow(new$stt_table) == nrow(old$stt_table)) - # different branching times - testthat::expect_equal(length(new$branching_times), length(old$branching_times)) - testthat::expect_true(all(abs(new$stt_table - old$stt_table) < tol)) - -}) - test_that("Clean run should be silent", { set.seed(42) diff --git a/tests/testthat/test-DAISIE_sim_core_constant_rate_shift.R b/tests/testthat/test-DAISIE_sim_core_constant_rate_shift.R index a2f72153..a8c29d20 100644 --- a/tests/testthat/test-DAISIE_sim_core_constant_rate_shift.R +++ b/tests/testthat/test-DAISIE_sim_core_constant_rate_shift.R @@ -46,3 +46,26 @@ test_that("abuse split-rate model with time smaller than shift_times", { ) }) +test_that("abuse split-rate model with gamma = 0", { + area_pars <- DAISIE::create_area_pars( + max_area = 1, + current_area = 1, + proportional_peak_t = 0, + total_island_age = 0, + sea_level_amplitude = 0, + sea_level_frequency = 0, + island_gradient_angle = 0) + nonoceanic_pars <- c(0, 0) + hyper_pars <- create_hyper_pars(d = 0, x = 0) + expect_error(DAISIE:::DAISIE_sim_core_constant_rate_shift( + time = 1, + mainland_n = 1, + pars = c(1, 1, 1, 0, 1, 1, 1, 1, 1, 1), + shift_times = 5, + area_pars = area_pars), + regexp = + "Island has no species and the rate of + colonisation is zero. Island cannot be colonised." + ) +}) + diff --git a/tests/testthat/test-DAISIE_sim_core_time_dependent.R b/tests/testthat/test-DAISIE_sim_core_time_dependent.R index 57c99b36..3250a3e3 100644 --- a/tests/testthat/test-DAISIE_sim_core_time_dependent.R +++ b/tests/testthat/test-DAISIE_sim_core_time_dependent.R @@ -252,3 +252,33 @@ test_that("(is.null(ext_pars) || is.null(area_pars)) && specify area_pars" ) }) + + +test_that("abuse time dependent model with gamma = 0", { + + expect_error(DAISIE:::DAISIE_sim_core_time_dependent( + time = 1, + mainland_n = 1, + pars = c(1, 1, 1, 0, 1), + area_pars = create_area_pars( + max_area = 5000, + current_area = 2500, + proportional_peak_t = 0.5, + total_island_age = 15, + sea_level_amplitude = 0, + sea_level_frequency = 0, + island_gradient_angle = 0), + nonoceanic_pars = c(0, 0), + peak = 0.5, + Amax = 5000, + Amin = 300, + hyper_pars = create_hyper_pars(d = 0, x = 0), + island_ontogeny = 1 + ), + regexp = + "Island has no species and the rate of + colonisation is zero. Island cannot be colonised." + ) +}) + + diff --git a/tests/testthat/test-DAISIE_sim_core_trait_dependent.R b/tests/testthat/test-DAISIE_sim_core_trait_dependent.R index 65f025ac..37e7bb08 100644 --- a/tests/testthat/test-DAISIE_sim_core_trait_dependent.R +++ b/tests/testthat/test-DAISIE_sim_core_trait_dependent.R @@ -55,3 +55,58 @@ test_that("nonontogeny oceanic trait_dependnet island should run silent CS", { ) ) }) + +test_that("abuse NULL trait pars", { + set.seed(234567890) + expect_error( + DAISIE:::DAISIE_sim_core_trait_dependent( + time = 10, + mainland_n = 100, + hyper_pars = create_hyper_pars(d = 0, x = 0), + area_pars = DAISIE::create_area_pars( + max_area = 1, + current_area = 1, + proportional_peak_t = 0, + total_island_age = 0, + sea_level_amplitude = 0, + sea_level_frequency = 0, + island_gradient_angle = 0), + pars = c(0.0001, 2.2, 0.005, 0.001, 1), + trait_pars = NULL + ), + "A second set of rates should be contain considering two trait states. + If only one state,run DAISIE_sim_constant_rate instead." + ) +}) +test_that("abuse NULL trait pars", { + set.seed(234567890) + expect_error( + DAISIE:::DAISIE_sim_core_trait_dependent( + time = 10, + mainland_n = 100, + hyper_pars = create_hyper_pars(d = 0, x = 0), + area_pars = DAISIE::create_area_pars( + max_area = 1, + current_area = 1, + proportional_peak_t = 0, + total_island_age = 0, + sea_level_amplitude = 0, + sea_level_frequency = 0, + island_gradient_angle = 0), + pars = c(0.0001, 2.2, 0.005, 0, 1), + trait_pars = create_trait_pars( + trans_rate = 0, + immig_rate2 = 0, + ext_rate2 = 0.2, + ana_rate2 = 1, + clado_rate2 = 0.004, + trans_rate2 = 0, + M2 = 200) + ), + "Island has no species and the rate of + colonisation is zero. Island cannot be colonised." + ) +}) + + + diff --git a/tests/testthat/test-DAISIE_sim_relaxed_rate.R b/tests/testthat/test-DAISIE_sim_relaxed_rate.R index 521ab33f..4f1a3333 100644 --- a/tests/testthat/test-DAISIE_sim_relaxed_rate.R +++ b/tests/testthat/test-DAISIE_sim_relaxed_rate.R @@ -1,6 +1,6 @@ context("DAISIE_sim_relaxed_rate") -test_that("A relaxed-cladogenesis should run silent wit correct output", { +test_that("A relaxed-cladogenesis should run silent with correct output", { set.seed(1) replicates <- 1 expect_silent( @@ -31,7 +31,68 @@ test_that("A relaxed-cladogenesis should run silent wit correct output", { expect_equal(sim[[1]][[2]]$missing_species, 0) }) -test_that("A relaxed-extinction should run silent wit correct output", { +test_that("A relaxed-cladogenesis should cond run silent with correct output", { + set.seed(Sys.time()) + replicates <- 1 + pars <- c(5, 1, 10, 0.01, 1, 5) + cond <- 5 + expect_silent( + out <- DAISIE_sim_relaxed_rate( + time = 5, + M = 100, + pars = pars, + replicates = replicates, + relaxed_par = "cladogenesis", + plot_sims = FALSE, + verbose = FALSE, + cond = cond + ) + ) +expect_true(out[[1]][[1]]$stt_all[nrow(out[[1]][[1]]$stt_all), 5] >= cond) +}) + +test_that("A relaxed-cladogenesis should cond run silent with correct output", { + set.seed(1) + replicates <- 1 + pars <- c(5, 1, 10, 0.01, 1, 5) + cond <- 5 + expect_silent( + out_cond <- DAISIE_sim_relaxed_rate( + time = 5, + M = 100, + pars = pars, + replicates = replicates, + relaxed_par = "cladogenesis", + plot_sims = FALSE, + verbose = FALSE, + cond = cond + ) + ) + + expect_true( + out_cond[[1]][[1]]$stt_all[nrow(out_cond[[1]][[1]]$stt_all), 5] >= cond + ) + + set.seed(1) + expect_silent( + out_no_cond <- DAISIE_sim_relaxed_rate( + time = 5, + M = 100, + pars = pars, + replicates = replicates, + relaxed_par = "cladogenesis", + plot_sims = FALSE, + verbose = FALSE, + cond = 0 + ) + ) + expect_true( + out_no_cond[[1]][[1]]$stt_all[nrow(out_no_cond[[1]][[1]]$stt_all), 5] < 5 + ) + +}) + +test_that("A relaxed-extinction should run silent with correct output", { set.seed(1) replicates <- 1 expect_silent( @@ -60,7 +121,69 @@ test_that("A relaxed-extinction should run silent wit correct output", { expect_equal(sim[[1]][[2]]$missing_species, 0) }) -test_that("A relaxed-K should run silent wit correct output", { +test_that("A relaxed-extinction should cond run silent with correct output", { + set.seed(Sys.time()) + replicates <- 1 + pars <- c(1, 0.5, 10, 0.01, 1, 1) + cond <- 5 + expect_silent( + out <- DAISIE_sim_relaxed_rate( + time = 5, + M = 100, + pars = pars, + replicates = replicates, + relaxed_par = "extinction", + plot_sims = FALSE, + verbose = FALSE, + cond = cond + ) + ) + expect_true(out[[1]][[1]]$stt_all[nrow(out[[1]][[1]]$stt_all), 5] >= cond) +}) + +test_that("A relaxed-extinction should cond run silent with correct output", { + set.seed(1) + replicates <- 1 + pars <- c(1, 0.5, 10, 0.01, 1, 1) + cond <- 5 + expect_silent( + out_cond <- DAISIE_sim_relaxed_rate( + time = 5, + M = 100, + pars = pars, + replicates = replicates, + relaxed_par = "extinction", + plot_sims = FALSE, + verbose = FALSE, + cond = cond + ) + ) + + expect_true( + out_cond[[1]][[1]]$stt_all[nrow(out_cond[[1]][[1]]$stt_all), 5] >= cond + ) + + set.seed(1) + expect_silent( + out_no_cond <- DAISIE_sim_relaxed_rate( + time = 5, + M = 100, + pars = pars, + replicates = replicates, + relaxed_par = "extinction", + plot_sims = FALSE, + verbose = FALSE, + cond = 0 + ) + ) + expect_true( + out_no_cond[[1]][[1]]$stt_all[nrow(out_no_cond[[1]][[1]]$stt_all), 5] < 5 + ) + +}) + + +test_that("A relaxed-K should run silent with correct output", { set.seed(1) replicates <- 1 expect_silent( @@ -88,7 +211,68 @@ test_that("A relaxed-K should run silent wit correct output", { expect_equal(sim[[1]][[2]]$missing_species, 0) }) -test_that("A relaxed-immigration should run silent wit correct output", { +test_that("A relaxed-K should cond run silent with correct output", { + set.seed(Sys.time()) + replicates <- 1 + pars <- c(1, 1, 5, 0.01, 1, 5) + cond <- 5 + expect_silent( + out <- DAISIE_sim_relaxed_rate( + time = 5, + M = 100, + pars = pars, + replicates = replicates, + relaxed_par = "carrying_capacity", + plot_sims = FALSE, + verbose = FALSE, + cond = cond + ) + ) + expect_true(out[[1]][[1]]$stt_all[nrow(out[[1]][[1]]$stt_all), 5] >= cond) +}) + +test_that("A relaxed-K should cond run silent with correct output", { + set.seed(1) + replicates <- 1 + pars <- c(1, 1, 5, 0.01, 1, 5) + cond <- 5 + expect_silent( + out_cond <- DAISIE_sim_relaxed_rate( + time = 5, + M = 100, + pars = pars, + replicates = replicates, + relaxed_par = "carrying_capacity", + plot_sims = FALSE, + verbose = FALSE, + cond = cond + ) + ) + + expect_true( + out_cond[[1]][[1]]$stt_all[nrow(out_cond[[1]][[1]]$stt_all), 5] >= cond + ) + + set.seed(1) + expect_silent( + out_no_cond <- DAISIE_sim_relaxed_rate( + time = 5, + M = 100, + pars = pars, + replicates = replicates, + relaxed_par = "carrying_capacity", + plot_sims = FALSE, + verbose = FALSE, + cond = 0 + ) + ) + expect_true( + out_no_cond[[1]][[1]]$stt_all[nrow(out_no_cond[[1]][[1]]$stt_all), 5] < 5 + ) + +}) + +test_that("A relaxed-immigration should run silent with correct output", { set.seed(1) replicates <- 1 expect_silent( @@ -116,7 +300,68 @@ test_that("A relaxed-immigration should run silent wit correct output", { expect_equal(sim[[1]][[2]]$missing_species, 0) }) -test_that("A relaxed-anagenesis should run silent wit correct output", { +test_that("A relaxed-immigration should cond run silent with correct output", { + set.seed(Sys.time()) + replicates <- 1 + pars <- c(1, 1, 10, 1, 1, 5) + cond <- 5 + expect_silent( + out <- DAISIE_sim_relaxed_rate( + time = 5, + M = 100, + pars = pars, + replicates = replicates, + relaxed_par = "immigration", + plot_sims = FALSE, + verbose = FALSE, + cond = cond + ) + ) + expect_true(out[[1]][[1]]$stt_all[nrow(out[[1]][[1]]$stt_all), 5] >= cond) +}) + +test_that("A relaxed-immigration should cond run silent with correct output", { + set.seed(3) + replicates <- 1 + pars <- c(1, 1, 10, 0.01, 1, 0.01) + cond <- 5 + expect_silent( + out_cond <- DAISIE_sim_relaxed_rate( + time = 5, + M = 100, + pars = pars, + replicates = replicates, + relaxed_par = "immigration", + plot_sims = FALSE, + verbose = FALSE, + cond = cond + ) + ) + + expect_true( + out_cond[[1]][[1]]$stt_all[nrow(out_cond[[1]][[1]]$stt_all), 5] >= cond + ) + + set.seed(3) + expect_silent( + out_no_cond <- DAISIE_sim_relaxed_rate( + time = 5, + M = 100, + pars = pars, + replicates = replicates, + relaxed_par = "immigration", + plot_sims = FALSE, + verbose = FALSE, + cond = 0 + ) + ) + expect_true( + out_no_cond[[1]][[1]]$stt_all[nrow(out_no_cond[[1]][[1]]$stt_all), 5] < 5 + ) + +}) + +test_that("A relaxed-anagenesis should run silent with correct output", { set.seed(1) replicates <- 1 expect_silent( @@ -144,6 +389,67 @@ test_that("A relaxed-anagenesis should run silent wit correct output", { expect_equal(sim[[1]][[2]]$missing_species, 0) }) +test_that("A relaxed-anagenesis should cond run silent with correct output", { + set.seed(Sys.time()) + replicates <- 1 + pars <- c(1, 1, 10, 0.01, 5, 5) + cond <- 5 + expect_silent( + out <- DAISIE_sim_relaxed_rate( + time = 5, + M = 100, + pars = pars, + replicates = replicates, + relaxed_par = "anagenesis", + plot_sims = FALSE, + verbose = FALSE, + cond = cond + ) + ) + expect_true(out[[1]][[1]]$stt_all[nrow(out[[1]][[1]]$stt_all), 5] >= cond) +}) + +test_that("A relaxed-anagenesis should cond run silent with correct output", { + set.seed(3) + replicates <- 1 + pars <- c(1, 1, 10, 0.01, 5, 5) + cond <- 5 + expect_silent( + out_cond <- DAISIE_sim_relaxed_rate( + time = 5, + M = 100, + pars = pars, + replicates = replicates, + relaxed_par = "anagenesis", + plot_sims = FALSE, + verbose = FALSE, + cond = cond + ) + ) + + expect_true( + out_cond[[1]][[1]]$stt_all[nrow(out_cond[[1]][[1]]$stt_all), 5] >= cond + ) + + set.seed(1) + expect_silent( + out_no_cond <- DAISIE_sim_relaxed_rate( + time = 5, + M = 100, + pars = pars, + replicates = replicates, + relaxed_par = "anagenesis", + plot_sims = FALSE, + verbose = FALSE, + cond = 0 + ) + ) + expect_true( + out_no_cond[[1]][[1]]$stt_all[nrow(out_no_cond[[1]][[1]]$stt_all), 5] < 5 + ) + +}) + test_that("Output is silent and correct for a nonoceanic simulation", { set.seed(1) replicates <- 1 @@ -167,52 +473,3 @@ test_that("Output is silent and correct for a nonoceanic simulation", { expect_gt(sim[[1]][[1]]$stt_all[1, 3], 0) }) -test_that("Oceanic and non-oceanic should give same results when - initial sampling is zero", { - n_mainland_species <- 1000 - island_age <- 0.4 - clado_rate <- 2.550687345 # cladogenesis rate - ext_rate <- 2.683454548 # extinction rate - clade_carr_cap <- 10.0 # clade-level carrying capacity - imm_rate <- 0.00933207 # immigration rate - ana_rate <- 1.010073119 # anagenesis rate - set.seed(17) - oceanic_sim <- DAISIE_sim_constant_rate( - time = island_age, - M = n_mainland_species, - pars = c(clado_rate, ext_rate, clade_carr_cap, imm_rate, ana_rate), - replicates = 1, - plot_sims = FALSE, - verbose = FALSE - ) - set.seed(17) - nonoceanic_sim <- DAISIE_sim_constant_rate( - time = island_age, - M = n_mainland_species, - pars = c(clado_rate, ext_rate, clade_carr_cap, imm_rate, ana_rate), - replicates = 1, - nonoceanic_pars = c(0.0, 0.9), - plot_sims = FALSE, - verbose = FALSE - ) - expect_true(all(names(oceanic_sim) == names(nonoceanic_sim))) - }) - -test_that("constant rate oceanic CS prints correct output when - verbose == TRUE", { - totaltime <- 1 - mainland_n <- 1 - pars <- c(0.4, 0.2, 10, 2, 0.8) - replicates <- 1 - verbose <- TRUE - set.seed(1) - expect_output( - sim <- DAISIE::DAISIE_sim_constant_rate(time = totaltime, - M = mainland_n, - pars = pars, - replicates = replicates, - plot_sims = FALSE, - verbose = verbose), - regexp = "Island replicate 1" - ) - }) diff --git a/tests/testthat/test-DAISIE_sim_time_dependent.R b/tests/testthat/test-DAISIE_sim_time_dependent.R index fcbf9e1a..3a226953 100644 --- a/tests/testthat/test-DAISIE_sim_time_dependent.R +++ b/tests/testthat/test-DAISIE_sim_time_dependent.R @@ -44,6 +44,139 @@ test_that("A clean CS ontogeny run should produce no output", { ) }) + + +test_that("use CS split-rates with cond", { + set.seed(Sys.time()) # Always run a different sim + n_mainland_species <- 1000 + island_age <- 0.4 + clado_rate <- 0.001 # cladogenesis rate + ext_rate <- 0.5 # extinction rate + clade_carr_cap <- 0.05 # clade-level carrying capacity + imm_rate <- 0.01 # immigration rate + ana_rate <- 0.1 # anagenesis rate + max_area <- 1000 + current_area <- 500 + peak_time <- 0.1 + sharpness <- 1 + total_island_age <- 10 + sea_level_amplitude <- 0 + sea_level_frequency <- 0 + island_gradient_angle <- 0 + island_ontogeny <- "beta" + sea_level <- "const" + extcutoff <- 1000 + hyper_pars <- create_hyper_pars(d = 0.2, x = 0.1) + cond <- 5 + expect_silent( + out <- DAISIE_sim_time_dependent( + time = island_age, + M = n_mainland_species, + pars = c(clado_rate, ext_rate, clade_carr_cap, imm_rate, ana_rate), + replicates = 1, + island_ontogeny = island_ontogeny, + sea_level = sea_level, + area_pars = create_area_pars( + max_area = max_area, + current_area = current_area, + proportional_peak_t = peak_time, + total_island_age = total_island_age, + sea_level_amplitude = sea_level_amplitude, + sea_level_frequency = sea_level_frequency, + island_gradient_angle = island_gradient_angle), + hyper_pars = hyper_pars, + extcutoff = extcutoff, + plot_sims = FALSE, + verbose = FALSE, + cond = cond + ) + ) + + expect_true(out[[1]][[1]]$stt_all[nrow(out[[1]][[1]]$stt_all), 5] >= cond) +}) + + +test_that("CS split-rates with cond to without", { + set.seed(1) # Always run a different sim + n_mainland_species <- 1000 + island_age <- 0.4 + clado_rate <- 0.001 # cladogenesis rate + ext_rate <- 0.5 # extinction rate + clade_carr_cap <- 0.05 # clade-level carrying capacity + imm_rate <- 0.01 # immigration rate + ana_rate <- 0.1 # anagenesis rate + max_area <- 1000 + current_area <- 500 + peak_time <- 0.1 + sharpness <- 1 + total_island_age <- 10 + sea_level_amplitude <- 0 + sea_level_frequency <- 0 + island_gradient_angle <- 0 + island_ontogeny <- "beta" + sea_level <- "const" + extcutoff <- 1000 + hyper_pars <- create_hyper_pars(d = 0.2, x = 0.1) + cond <- 5 + expect_silent( + out_cond <- DAISIE_sim_time_dependent( + time = island_age, + M = n_mainland_species, + pars = c(clado_rate, ext_rate, clade_carr_cap, imm_rate, ana_rate), + replicates = 1, + island_ontogeny = island_ontogeny, + sea_level = sea_level, + area_pars = create_area_pars( + max_area = max_area, + current_area = current_area, + proportional_peak_t = peak_time, + total_island_age = total_island_age, + sea_level_amplitude = sea_level_amplitude, + sea_level_frequency = sea_level_frequency, + island_gradient_angle = island_gradient_angle), + hyper_pars = hyper_pars, + extcutoff = extcutoff, + plot_sims = FALSE, + verbose = FALSE, + cond = cond + ) + ) + expect_true( + out_cond[[1]][[1]]$stt_all[nrow(out_cond[[1]][[1]]$stt_all), 5] >= cond + ) + + set.seed(1) + expect_silent( + out_no_cond <- DAISIE_sim_time_dependent( + time = island_age, + M = n_mainland_species, + pars = c(clado_rate, ext_rate, clade_carr_cap, imm_rate, ana_rate), + replicates = 1, + island_ontogeny = island_ontogeny, + sea_level = sea_level, + area_pars = create_area_pars( + max_area = max_area, + current_area = current_area, + proportional_peak_t = peak_time, + total_island_age = total_island_age, + sea_level_amplitude = sea_level_amplitude, + sea_level_frequency = sea_level_frequency, + island_gradient_angle = island_gradient_angle), + hyper_pars = hyper_pars, + extcutoff = extcutoff, + plot_sims = FALSE, + verbose = FALSE, + cond = 0 + ) + ) + expect_true( + out_no_cond[[1]][[1]]$stt_all[nrow(out_no_cond[[1]][[1]]$stt_all), 5] < cond + ) +}) + + + + test_that("A clean IW ontogeny run should produce no output", { n_mainland_species <- 1000 island_age <- 0.4 @@ -185,3 +318,199 @@ test_that("A clean sea_level run should produce no output", { ) ) }) + + + + + +test_that("A clean CS ontogeny run with verbose should print to console", { + n_mainland_species <- 1000 + island_age <- 0.4 + clado_rate <- 0.0001 # cladogenesis rate + ext_rate <- 0.5 # extinction rate + clade_carr_cap <- 0.05 # clade-level carrying capacity + imm_rate <- 0.001 # immigration rate + ana_rate <- 0.1 # anagenesis rate + max_area <- 1000 + current_area <- 500 + peak_time <- 0.1 + sharpness <- 1 + total_island_age <- 10 + sea_level_amplitude <- 0 + sea_level_frequency <- 0 + island_gradient_angle <- 0 + island_ontogeny <- "beta" + sea_level <- "const" + extcutoff <- 1000 + hyper_pars <- create_hyper_pars(d = 0.2, x = 0.1) + expect_output( + DAISIE_sim_time_dependent( + time = island_age, + M = n_mainland_species, + pars = c(clado_rate, ext_rate, clade_carr_cap, imm_rate, ana_rate), + replicates = 1, + island_ontogeny = island_ontogeny, + sea_level = sea_level, + area_pars = create_area_pars( + max_area = max_area, + current_area = current_area, + proportional_peak_t = peak_time, + total_island_age = total_island_age, + sea_level_amplitude = sea_level_amplitude, + sea_level_frequency = sea_level_frequency, + island_gradient_angle = island_gradient_angle), + hyper_pars = hyper_pars, + extcutoff = extcutoff, + plot_sims = FALSE, + verbose = TRUE + ), + "Island replicate 1" + ) +}) + +test_that("A clean IW ontogeny run should produce no output", { + n_mainland_species <- 1000 + island_age <- 0.4 + clado_rate <- 0.0001 # cladogenesis rate + ext_rate <- 0.5 # extinction rate + clade_carr_cap <- 0.05 # clade-level carrying capacity + imm_rate <- 0.001 # immigration rate + ana_rate <- 0.1 # anagenesis rate + divdepmodel <- "IW" + max_area <- 1000 + current_area <- 500 + peak_time <- 0.1 + total_island_age <- 10 + sea_level_amplitude <- 0 + sea_level_frequency <- 0 + island_gradient_angle <- 0 + island_ontogeny <- "beta" + sea_level <- "const" + extcutoff <- 1000 + hyper_pars <- create_hyper_pars(d = 0.2, x = 0.1) + nonoceanic_pars <- c(0, 0) + expect_output( + DAISIE_sim_time_dependent( + time = island_age, + M = n_mainland_species, + pars = c(clado_rate, ext_rate, clade_carr_cap, imm_rate, ana_rate), + replicates = 1, + divdepmodel = divdepmodel, + island_ontogeny = island_ontogeny, + sea_level = sea_level, + area_pars = create_area_pars( + max_area = max_area, + current_area = current_area, + proportional_peak_t = peak_time, + total_island_age = total_island_age, + sea_level_amplitude = sea_level_amplitude, + sea_level_frequency = sea_level_frequency, + island_gradient_angle = island_gradient_angle), + hyper_pars = hyper_pars, + nonoceanic_pars = nonoceanic_pars, + extcutoff = extcutoff, + plot_sims = FALSE, + verbose = TRUE + ), + "Island replicate 1" + ) +}) + +test_that("A clean GW ontogeny run should produce no output", { + n_mainland_species <- 1000 + island_age <- 0.4 + clado_rate <- 0.0001 # cladogenesis rate + ext_rate <- 0.5 # extinction rate + clade_carr_cap <- 0.05 # clade-level carrying capacity + imm_rate <- 0.001 # immigration rate + ana_rate <- 0.1 # anagenesis rate + divdepmodel <- "GW" + num_guilds <- 10 + max_area <- 1000 + current_area <- 500 + peak_time <- 0.1 + total_island_age <- 10 + sea_level_amplitude <- 0 + sea_level_frequency <- 0 + island_gradient_angle <- 0 + island_ontogeny <- "beta" + sea_level <- "const" + extcutoff <- 1000 + hyper_pars <- create_hyper_pars(d = 0.2, x = 0.1) + nonoceanic_pars <- c(0, 0) + expect_output( + DAISIE_sim_time_dependent( + time = island_age, + M = n_mainland_species, + pars = c(clado_rate, ext_rate, clade_carr_cap, imm_rate, ana_rate), + replicates = 1, + divdepmodel = divdepmodel, + num_guilds = num_guilds, + island_ontogeny = island_ontogeny, + sea_level = sea_level, + area_pars = create_area_pars( + max_area = max_area, + current_area = current_area, + proportional_peak_t = peak_time, + total_island_age = total_island_age, + sea_level_amplitude = sea_level_amplitude, + sea_level_frequency = sea_level_frequency, + island_gradient_angle = island_gradient_angle), + hyper_pars = hyper_pars, + nonoceanic_pars = nonoceanic_pars, + extcutoff = extcutoff, + plot_sims = FALSE, + verbose = TRUE + ), + "Island replicate 1" + ) +}) +test_that("A clean GW ontogeny run should produce no output", { + n_mainland_species <- 1000 + island_age <- 0.4 + clado_rate <- 0.0001 # cladogenesis rate + ext_rate <- 0.5 # extinction rate + clade_carr_cap <- 0.05 # clade-level carrying capacity + imm_rate <- 0.001 # immigration rate + ana_rate <- 0.1 # anagenesis rate + divdepmodel <- "GW" + num_guilds <- "10" + max_area <- 1000 + current_area <- 500 + peak_time <- 0.1 + total_island_age <- 10 + sea_level_amplitude <- 0 + sea_level_frequency <- 0 + island_gradient_angle <- 0 + island_ontogeny <- "beta" + sea_level <- "const" + extcutoff <- 1000 + hyper_pars <- create_hyper_pars(d = 0.2, x = 0.1) + nonoceanic_pars <- c(0, 0) + expect_error( + DAISIE_sim_time_dependent( + time = island_age, + M = n_mainland_species, + pars = c(clado_rate, ext_rate, clade_carr_cap, imm_rate, ana_rate), + replicates = 1, + divdepmodel = divdepmodel, + num_guilds = num_guilds, + island_ontogeny = island_ontogeny, + sea_level = sea_level, + area_pars = create_area_pars( + max_area = max_area, + current_area = current_area, + proportional_peak_t = peak_time, + total_island_age = total_island_age, + sea_level_amplitude = sea_level_amplitude, + sea_level_frequency = sea_level_frequency, + island_gradient_angle = island_gradient_angle), + hyper_pars = hyper_pars, + nonoceanic_pars = nonoceanic_pars, + extcutoff = extcutoff, + plot_sims = FALSE, + verbose = TRUE + ), + "num_guilds must be numeric" + ) +}) diff --git a/tests/testthat/test-DAISIE_sim_trait_dependent.R b/tests/testthat/test-DAISIE_sim_trait_dependent.R index 9d1cb726..0d4aa0ad 100644 --- a/tests/testthat/test-DAISIE_sim_trait_dependent.R +++ b/tests/testthat/test-DAISIE_sim_trait_dependent.R @@ -10,12 +10,12 @@ test_that("A clean CS two trait simulation run should produce no output", { ana_rate <- 0.1 # anagenesis rate trans_rate <- 0.5 # transition rate trait_pars <- create_trait_pars(trans_rate = trans_rate, - immig_rate2 = imm_rate / 2, - ext_rate2 = ext_rate * 2, - ana_rate2 = ana_rate / 2, - clado_rate2 = clado_rate / 2, - trans_rate2 = trans_rate / 2, - M2 = n_mainland_species / 2) + immig_rate2 = imm_rate / 2, + ext_rate2 = ext_rate * 2, + ana_rate2 = ana_rate / 2, + clado_rate2 = clado_rate / 2, + trans_rate2 = trans_rate / 2, + M2 = n_mainland_species / 2) island_ontogeny <- "const" sea_level <- "const" extcutoff <- 1000 @@ -35,6 +35,108 @@ test_that("A clean CS two trait simulation run should produce no output", { ) }) +test_that("A divdepmodel = 'CS' two trait run with cond works as expected", { + set.seed(Sys.time()) # Always run a different sim + n_mainland_species <- 1000 + island_age <- 0.4 + clado_rate <- 0.0001 # cladogenesis rate + ext_rate <- 2.683454548 # extinction rate (not used) + clade_carr_cap <- 0.05 # clade-level carrying capacity + imm_rate <- 0.01 # immigration rate + ana_rate <- 0.1 # anagenesis rate + trans_rate <- 0.5 # transition rate + cond <- 5 + trait_pars <- create_trait_pars(trans_rate = trans_rate, + immig_rate2 = imm_rate / 2, + ext_rate2 = ext_rate * 2, + ana_rate2 = ana_rate / 2, + clado_rate2 = clado_rate / 2, + trans_rate2 = trans_rate / 2, + M2 = n_mainland_species / 2) + island_ontogeny <- "const" + sea_level <- "const" + extcutoff <- 1000 + expect_silent( + out <- DAISIE_sim_trait_dependent( + time = island_age, + M = n_mainland_species, + pars = c(clado_rate, ext_rate, clade_carr_cap, imm_rate, ana_rate), + replicates = 1, + island_ontogeny = island_ontogeny, + sea_level = sea_level, + trait_pars = trait_pars, + extcutoff = extcutoff, + plot_sims = FALSE, + verbose = FALSE, + cond = cond + ) + ) + + expect_true(out[[1]][[1]]$stt_all[nrow(out[[1]][[1]]$stt_all), 8] >= cond) +}) + +test_that("A divdepmodel = 'CS' two trait run cond no cond work as expected", { + set.seed(1) # Always run the same sim + n_mainland_species <- 1000 + island_age <- 0.4 + clado_rate <- 0.0001 # cladogenesis rate + ext_rate <- 2.683454548 # extinction rate (not used) + clade_carr_cap <- 0.05 # clade-level carrying capacity + imm_rate <- 0.01 # immigration rate + ana_rate <- 0.1 # anagenesis rate + trans_rate <- 0.5 # transition rate + cond <- 5 + trait_pars <- create_trait_pars(trans_rate = trans_rate, + immig_rate2 = imm_rate / 2, + ext_rate2 = ext_rate * 2, + ana_rate2 = ana_rate / 2, + clado_rate2 = clado_rate / 2, + trans_rate2 = trans_rate / 2, + M2 = n_mainland_species / 2) + island_ontogeny <- "const" + sea_level <- "const" + extcutoff <- 1000 + expect_silent( + out_cond <- DAISIE_sim_trait_dependent( + time = island_age, + M = n_mainland_species, + pars = c(clado_rate, ext_rate, clade_carr_cap, imm_rate, ana_rate), + replicates = 1, + island_ontogeny = island_ontogeny, + sea_level = sea_level, + trait_pars = trait_pars, + extcutoff = extcutoff, + plot_sims = FALSE, + verbose = FALSE, + cond = cond + ) + ) + + expect_true( + out_cond[[1]][[1]]$stt_all[nrow(out_cond[[1]][[1]]$stt_all), 8] >= cond + ) + + set.seed(1) + expect_silent( + out_no_cond <- DAISIE_sim_trait_dependent( + time = island_age, + M = n_mainland_species, + pars = c(clado_rate, ext_rate, clade_carr_cap, imm_rate, ana_rate), + replicates = 1, + island_ontogeny = island_ontogeny, + sea_level = sea_level, + trait_pars = trait_pars, + extcutoff = extcutoff, + plot_sims = FALSE, + verbose = FALSE, + cond = 0 + ) + ) + + expect_true( + out_no_cond[[1]][[1]]$stt_all[nrow(out_no_cond[[1]][[1]]$stt_all), 8] < 5) +}) + test_that("A clean IW two trait simulation run should produce no output", { n_mainland_species <- 1000 island_age <- 0.4 diff --git a/tests/testthat/test-are_rates.R b/tests/testthat/test-are_rates.R index e11836ac..e04c0273 100644 --- a/tests/testthat/test-are_rates.R +++ b/tests/testthat/test-are_rates.R @@ -444,7 +444,7 @@ test_that("check returns FALSE when wrong", { immig_rate = 0.1, ext_rate = 0.2, ana_rate = 0.5, - clado_rate = -1, + clado_rate = 1, clado_rate = 0.4, immig_rate2 = 0.1, ext_rate2 = 0.2, @@ -455,6 +455,23 @@ test_that("check returns FALSE when wrong", { ) ) ) + expect_false( + are_rates( + list( + immig_rate = 0.1, + ext_rate = 0.2, + ana_rate = 0.5, + clado_rate = -1, + clado_rate = 0.4, + immig_rate2 = 0.1, + ext_rate2 = 0.2, + ana_rate2 = 0.3, + clado_rate2 = 0.4, + trans_rate = 0.5, + trans_rate2 = 1 + ) + ) + ) }) diff --git a/tests/testthat/test-get_ana_rate.R b/tests/testthat/test-get_ana_rate.R new file mode 100644 index 00000000..d37d158b --- /dev/null +++ b/tests/testthat/test-get_ana_rate.R @@ -0,0 +1,14 @@ +context("get_ana_rate") + +test_that("use", { + ps_ana_rate <- 1 + n_immigrants <- 5 + ana_rate <- DAISIE:::get_ana_rate( + laa = ps_ana_rate, + num_immigrants = n_immigrants) + created <- DAISIE:::get_ana_rate( + laa = 1, + num_immigrants = 5) + expected <- ps_ana_rate * n_immigrants + expect_equal(expected, created) +}) diff --git a/tests/testthat/test-get_clado_rate.R b/tests/testthat/test-get_clado_rate.R new file mode 100644 index 00000000..d19cbdd6 --- /dev/null +++ b/tests/testthat/test-get_clado_rate.R @@ -0,0 +1,69 @@ +context("get_clado_rate") + +test_that("use area constant diversity-independent", { + ps_clado_rate <- 0.2 + carr_cap <- Inf + n_species <- 4 + hyper_pars <- DAISIE:::create_hyper_pars(d = 0, x = 0) + area <- 1 + created <- DAISIE:::get_clado_rate( + lac = ps_clado_rate, + hyper_pars = hyper_pars, + num_spec = n_species, + K = carr_cap, + A = area + ) + expected <- ps_clado_rate * n_species * (1 - n_species / carr_cap) + expect_equal(created, expected) +}) + +test_that("use area constant diversity-dependent", { + ps_clado_rate <- 0.2 + carr_cap <- 9 + n_species <- 4 + hyper_pars <- DAISIE:::create_hyper_pars(d = 0, x = 0) + area <- 1 + created <- DAISIE:::get_clado_rate( + lac = ps_clado_rate, + hyper_pars = hyper_pars, + num_spec = n_species, + K = carr_cap, + A = area + ) + expected <- ps_clado_rate * n_species * (1 - n_species / carr_cap) + expect_equal(created, expected) +}) + +test_that("use area variable diversity-independent", { + ps_clado_rate <- 0.2 + carr_cap <- Inf + n_species <- 4 + hyper_pars <- DAISIE:::create_hyper_pars(d = 0.2, x = 0.1) + area <- 10 + created <- DAISIE:::get_clado_rate( + lac = ps_clado_rate, + hyper_pars = hyper_pars, + num_spec = n_species, + K = carr_cap, + A = area + ) + expected <- 1.267914553968891 + expect_equal(created, expected) +}) + +test_that("use area variable diversity-dependent", { + ps_clado_rate <- 0.2 + carr_cap <- 9 + n_species <- 4 + hyper_pars <- DAISIE:::create_hyper_pars(d = 0.2, x = 0.1) + area <- 10 + created <- DAISIE:::get_clado_rate( + lac = ps_clado_rate, + hyper_pars = hyper_pars, + num_spec = n_species, + K = carr_cap, + A = area + ) + expected <- 1.211562796014718 + expect_equal(created, expected) +}) diff --git a/tests/testthat/test-get_ext_rate.R b/tests/testthat/test-get_ext_rate.R new file mode 100644 index 00000000..26ed9d58 --- /dev/null +++ b/tests/testthat/test-get_ext_rate.R @@ -0,0 +1,32 @@ +context("get_ext_rate") + +test_that("use area constant", { + ps_ext_rate <- 2 + n_species <- 4 + hyper_pars = DAISIE:::create_hyper_pars(d = 0, x = 0) + area <- 1 + created <- DAISIE:::get_ext_rate( + mu = ps_ext_rate, + hyper_pars = hyper_pars, + extcutoff = 1000, + num_spec = n_species, + A = area) + expected <- ps_ext_rate * n_species + + expect_equal(created, expected) +}) + +test_that("use area variable", { + ps_ext_rate <- 2 + n_species <- 4 + hyper_pars = DAISIE:::create_hyper_pars(d = 0.2, x = 0.1) + area <- 10 + created <- DAISIE:::get_ext_rate( + mu = ps_ext_rate, + hyper_pars = hyper_pars, + extcutoff = 1000, + num_spec = n_species, + A = area) + expected <- 6.354625877794252 + expect_equal(created, expected) +}) diff --git a/tests/testthat/test-get_immig_rate.R b/tests/testthat/test-get_immig_rate.R new file mode 100644 index 00000000..72e7e620 --- /dev/null +++ b/tests/testthat/test-get_immig_rate.R @@ -0,0 +1,56 @@ +context("get_immig_rate") + +test_that("use area constant diversity-independent", { + carr_cap <- Inf + ps_imm_rate <- 0.1 + n_island_species <- 5 + n_mainland_species <- 1 + hyper_pars <- DAISIE:::create_hyper_pars(0, 0) + area <- 1 + created <- DAISIE:::get_immig_rate( + gam = ps_imm_rate, + A = area, + num_spec = n_island_species, + K = carr_cap, + mainland_n = n_mainland_species) + expected <- ps_imm_rate * n_mainland_species * + (1 - n_island_species / carr_cap) + + expect_equal(expected, created) +}) + +test_that("use area constant diversity-dependent", { + carr_cap <- 10 + ps_imm_rate <- 0.1 + n_island_species <- 5 + n_mainland_species <- 1 + hyper_pars <- DAISIE:::create_hyper_pars(0, 0) + area <- 1 + created <- DAISIE:::get_immig_rate( + gam = ps_imm_rate, + A = area, + num_spec = n_island_species, + K = carr_cap, + mainland_n = n_mainland_species) + expected <- ps_imm_rate * n_mainland_species * + (1 - n_island_species / carr_cap) + + expect_equal(expected, created) +}) + +test_that("use area variable (ontogeny) diversity-dependent", { + carr_cap <- 10 + ps_imm_rate <- 0.1 + n_island_species <- 5 + n_mainland_species <- 1 + hyper_pars <- DAISIE:::create_hyper_pars(0, 0) + area <- 10 + created <- DAISIE:::get_immig_rate( + gam = ps_imm_rate, + A = area, + num_spec = n_island_species, + K = carr_cap, + mainland_n = n_mainland_species) + expected <- 0.095 + expect_equal(expected, created) +}) diff --git a/tests/testthat/test-integration_DAISIE.R b/tests/testthat/test-integration_DAISIE.R index 307bc71b..54140e13 100644 --- a/tests/testthat/test-integration_DAISIE.R +++ b/tests/testthat/test-integration_DAISIE.R @@ -1,11 +1,10 @@ -context("integration test") test_that("loglik Galapagos works", { - Galapagos_datalist = NULL + Galapagos_datalist <- NULL rm(Galapagos_datalist) - Galapagos_datalist_2types = NULL + Galapagos_datalist_2types <- NULL rm(Galapagos_datalist_2types) utils::data(Galapagos_datalist_2types, package = "DAISIE") - pars1 = c( + pars1 <- c( 0.195442017, 0.087959583, Inf, @@ -18,81 +17,80 @@ test_that("loglik Galapagos works", { 0.873605049, 0.163 ) - pars2 = c(100, 11, 0, 0) - loglik = DAISIE::DAISIE_loglik_all(pars1, pars2, Galapagos_datalist_2types) + pars2 <- c(100, 11, 0, 0) + loglik <- DAISIE::DAISIE_loglik_all(pars1, pars2, Galapagos_datalist_2types) testthat::expect_equal(loglik, -61.7094829913735978) }) test_that("loglik macaronesia 2 type works", { - Macaronesia_datalist = NULL + Macaronesia_datalist <- NULL rm(Macaronesia_datalist) utils::data(Macaronesia_datalist, package = "DAISIE") - background = c(0, 1.053151832, Inf, 0.052148979, 0.512939011) - Canaries = c(0.133766934, 1.053151832, Inf, 0.152763179, 0.512939011) - pars1 = rbind(background, Canaries, background, background) - pars2 = c(100, 0, 0, 0) - loglik = 0 - for (i in 1:length(Macaronesia_datalist)) - { - loglik = loglik + DAISIE::DAISIE_loglik_all(pars1[i, ], pars2, Macaronesia_datalist[[i]], methode = "lsodes") + background <- c(0, 1.053151832, Inf, 0.052148979, 0.512939011) + Canaries <- c(0.133766934, 1.053151832, Inf, 0.152763179, 0.512939011) + pars1 <- rbind(background, Canaries, background, background) + pars2 <- c(100, 0, 0, 0) + loglik <- 0 + for (i in seq_along(Macaronesia_datalist)) { + loglik <- loglik + DAISIE::DAISIE_loglik_all(pars1[i, ], + pars2, + Macaronesia_datalist[[i]], + methode = "lsodes") } testthat::expect_equal(loglik, -454.9347833283220552) }) test_that("clade specific rate-shift loglik works", { utils::data(Galapagos_datalist, package = "DAISIE") - pars1 = c(0.2, 0.1, Inf, 0.001, 0.3, 0.2, 0.1, Inf, 0.001, 0.3, 1) - pars2 = c(40, 11, 0, 0) - SR_loglik_CS = DAISIE::DAISIE_SR_loglik_CS( + pars1 <- c(0.2, 0.1, Inf, 0.001, 0.3, 0.2, 0.1, Inf, 0.001, 0.3, 1) + pars2 <- c(40, 11, 0, 0) + SR_loglik_CS <- DAISIE::DAISIE_SR_loglik_CS( pars1 = pars1, pars2 = pars2, datalist = Galapagos_datalist, - methode = 'ode45', - CS_version = 1 - ) - pars1 = c(0.2, 0.1, Inf, 0.001, 0.3) - loglik_CS = DAISIE::DAISIE_loglik_CS( + methode = "ode45", + CS_version = 1) + pars1 <- c(0.2, 0.1, Inf, 0.001, 0.3) + loglik_CS <- DAISIE::DAISIE_loglik_CS( pars1 = pars1, pars2 = pars2, datalist = Galapagos_datalist, - methode = 'ode45', - CS_version = 1 - ) + methode = "ode45", + CS_version = 1) testthat::expect_equal(SR_loglik_CS, loglik_CS) }) test_that("IW and CS loglik is same when K = Inf", { + skip_if(Sys.getenv("CI") == "" || !(Sys.getenv("USERNAME") == "rampa"), + message = "Run only on CI") utils::data(Galapagos_datalist, package = "DAISIE") - pars1 = c(0.2, 0.1, Inf, 0.001, 0.3) - pars2 = c(40, 11, 0, 0) - loglik_IW = DAISIE::DAISIE_loglik_IW( + pars1 <- c(0.2, 0.1, Inf, 0.001, 0.3) + pars2 <- c(40, 11, 0, 0) + loglik_IW <- DAISIE::DAISIE_loglik_IW( pars1 = pars1, pars2 = pars2, datalist = Galapagos_datalist, - methode = 'ode45' - ) - loglik_CS = DAISIE::DAISIE_loglik_CS( + methode = "ode45") + loglik_CS <- DAISIE::DAISIE_loglik_CS( pars1 = pars1, pars2 = pars2, datalist = Galapagos_datalist, - methode = 'ode45', - CS_version = 1 - ) + methode = "ode45", + CS_version = 1) testthat::expect_lt(abs(loglik_IW - loglik_CS), 5E-6) }) -test_that("ontogeny and null-ontogeny loglik is same - when ontogeny is constant", { - skip("time_dep ML does not work") +test_that("ontogeny and null-ontogeny loglik is same when ontogeny is + constant", { + skip("Temporary skip") + pars1 <- c(0.2, 0.1, 17, 0.001, 0.3) + pars2 <- c(40, 11, 0, 0) utils::data(Galapagos_datalist, package = "DAISIE") - pars1 = c(0.2, 0.1, 17, 0.001, 0.3) - pars2 = c(40, 11, 0, 0) - loglik_CS <- DAISIE_loglik_all( + loglik_CS <- DAISIE::DAISIE_loglik_all( pars1 = pars1, pars2 = pars2, datalist = Galapagos_datalist, - methode = 'ode45' - ) + methode = "ode45") pars1_td <- c( max_area = 1, proportional_peak_t = 0.2, @@ -106,8 +104,8 @@ test_that("ontogeny and null-ontogeny loglik is same laa = pars1[5] ) pars1_td <- DAISIE:::order_pars1(pars1_td) - pars2 <- c(pars2, translate_island_ontogeny('const')) - loglik_time <- DAISIE_loglik_all( + pars2 <- c(pars2, DAISIE::translate_island_ontogeny("const")) + loglik_time <- DAISIE::DAISIE_loglik_all( pars1 = pars1_td, pars2 = pars2, datalist = Galapagos_datalist, @@ -117,17 +115,18 @@ test_that("ontogeny and null-ontogeny loglik is same }) testthat::test_that("DAISIE_ML simple case works", { - if (Sys.getenv("TRAVIS") != "" | Sys.getenv("USERNAME") == "rampa") { + skip_if(Sys.getenv("CI") == "" || !(Sys.getenv("USERNAME") == "rampa"), + message = "Run only on CI") expected_mle <- data.frame( - lambda_c = 2.55847849219339, - mu = 2.68768191590176, - K = 6765.0637400135, - gamma = 0.00932987953669849, - lambda_a = 1.00838182578826, - loglik = -76.0001379108545, - df = 5L, - conv = 0L - ) + lambda_c = 2.55847849219339, + mu = 2.68768191590176, + K = 6765.0637400135, + gamma = 0.00932987953669849, + lambda_a = 1.00838182578826, + loglik = -76.0001379108545, + df = 5L, + conv = 0L + ) utils::data(Galapagos_datalist) cat("\n") tested_mle <- DAISIE::DAISIE_ML( @@ -139,9 +138,6 @@ testthat::test_that("DAISIE_ML simple case works", { idparsfix = NULL ) testthat::expect_equal(expected_mle, tested_mle) - } else { - testthat::skip("Run only on Travis") - } }) test_that("The parameter choice for 2type DAISIE_ML works", { @@ -153,11 +149,11 @@ test_that("The parameter choice for 2type DAISIE_ML works", { cat("\n") fit <- DAISIE::DAISIE_ML( datalist = Galapagos_datalist_2types, - initparsopt = c(2.183336,2.517413,0.009909,1.080458,1.316296,0.001416), - idparsopt = c(1,2,4,5,7,11), - parsfix = c(Inf,Inf), - idparsfix = c(3,8), - idparsnoshift = c(6,9,10), + initparsopt = c(2.183336, 2.517413, 0.009909, 1.080458, 1.316296, 0.001416), + idparsopt = c(1, 2, 4, 5, 7, 11), + parsfix = c(Inf, Inf), + idparsfix = c(3, 8), + idparsnoshift = c(6, 9, 10), res = 30, tol = c(1, 1, 1), maxiter = 30 @@ -175,10 +171,10 @@ test_that("conditioning works", { pars1 = pars1_1type_cond0, pars2 = pars2_1type_cond0, datalist = Galapagos_datalist, - methode = 'ode45', + methode = "ode45", CS_version = 1 ) - testthat::expect_equal(loglik_CS_1type_cond0,-96.49629968062564) + testthat::expect_equal(loglik_CS_1type_cond0, -96.49629968062564) ## 2 type utils::data(Galapagos_datalist_2types, package = "DAISIE") @@ -201,7 +197,7 @@ test_that("conditioning works", { pars2_2type_cond0, Galapagos_datalist_2types ) - testthat::expect_equal(loglik_CS_2type_cond0,-61.709482984890265) + testthat::expect_equal(loglik_CS_2type_cond0, -61.709482984890265) # Cond 1 ## 1 type @@ -215,7 +211,7 @@ test_that("conditioning works", { methode = 'ode45', CS_version = 1 ) - testthat::expect_equal(loglik_CS_1type_cond1,-96.463184608046333) + testthat::expect_equal(loglik_CS_1type_cond1, -96.463184608046333) ## 2 type utils::data(Galapagos_datalist_2types, package = "DAISIE") @@ -238,7 +234,7 @@ test_that("conditioning works", { pars2_2type_cond1, Galapagos_datalist_2types ) - testthat::expect_equal(loglik_CS_2type_cond1,-61.709153802942346) + testthat::expect_equal(loglik_CS_2type_cond1,-61.4442595468189054) # Cond 5 ## 1 type @@ -275,5 +271,5 @@ test_that("conditioning works", { pars2_2type_cond5, Galapagos_datalist_2types ) - testthat::expect_equal(loglik_CS_2type_cond5,-61.5667762281177673) + testthat::expect_equal(loglik_CS_2type_cond5, -61.3801835140081025) }) diff --git a/tests/testthat/test-is_simulation_outputs.R b/tests/testthat/test-is_simulation_outputs.R index 5cb6c915..8d0ff62f 100644 --- a/tests/testthat/test-is_simulation_outputs.R +++ b/tests/testthat/test-is_simulation_outputs.R @@ -30,3 +30,31 @@ test_that("use", { ) ) }) + +test_that("abuse is simulation outputs", { + + output <- DAISIE_sim_constant_rate( + time = 0.4, + M = 10, + pars = c(2, 2, Inf, 0.001, 1), + replicates = 2, + plot_sims = FALSE, + verbose = FALSE + ) + names(output[[1]][[1]])[2] <- "nonsense" + expect_false(is_simulation_outputs(output)) +}) + +test_that("abuse is simulation outputs", { + + output <- DAISIE_sim_constant_rate( + time = 0.4, + M = 10, + pars = c(2, 2, Inf, 0.001, 1), + replicates = 2, + plot_sims = FALSE, + verbose = FALSE + ) + names(output[[1]][[1]])[3] <- "nonsense" + expect_false(is_simulation_outputs(output)) +}) diff --git a/tests/testthat/test-time_dep_vs_constant_rate.R b/tests/testthat/test-time_dep_vs_constant_rate.R new file mode 100644 index 00000000..2e3b03fa --- /dev/null +++ b/tests/testthat/test-time_dep_vs_constant_rate.R @@ -0,0 +1,75 @@ +context("DAISIE_sim_time_dependent first line") + +test_that("constant rate output matches time dependent code", { + + # Note: Since both algorithms do not call the RNG an equal number of times, + # the output of Gillespie runs must necessarily be different. To at least + # test some of the output, we verify if the first events match, as the first + # event of each algorithm is sampled from the same number of RNG calls. + + + +# Constant rate code ------------------------------------------------------ + sim_time <- 10 + n_mainland_species <- 1 + clado_rate <- 1.0 + ext_rate <- 0.5 + carr_cap <- 10 + imm_rate <- 1.0 + ana_rate <- 1.0 + pars <- c(clado_rate, ext_rate, carr_cap, imm_rate, ana_rate) + area_pars <- DAISIE::create_area_pars( + max_area = 1, + current_area = 1, + proportional_peak_t = 0, + total_island_age = 10, + sea_level_amplitude = 0, + sea_level_frequency = 0, + island_gradient_angle = 0 + ) + hyper_pars <- DAISIE::create_hyper_pars(d = 0, x = 0) + nonoceanic_pars <- c(0, 0) + rng_seed <- 42 + set.seed(rng_seed) + constant_rate_out <- DAISIE:::DAISIE_sim_constant_rate( + time = sim_time, + M = n_mainland_species, + pars = pars, + replicates = 1, + plot_sims = FALSE, + verbose = FALSE, + sample_freq = Inf + ) + + + # Ontogeny code running constant case ----------------------------------- + # We must use the core function to avoid calling calc_peak with a constant + # area. + hyper_pars <- DAISIE::create_hyper_pars(d = 0, x = 0) + set.seed(rng_seed) + time_dependent_out <- DAISIE:::DAISIE_sim_core_time_dependent( + time = sim_time, + mainland_n = n_mainland_species, + pars = c(clado_rate, ext_rate, carr_cap, imm_rate, ana_rate), + island_ontogeny = "beta", + sea_level = "const", + area_pars = area_pars, + hyper_pars = hyper_pars, + nonoceanic_pars = nonoceanic_pars, + Amax = 1, + Amin = 1, + peak = 1 + ) + + expect_equal( + time_dependent_out[[1]][2, ], + constant_rate_out[[1]][[1]]$stt_all[2, 1:4] + ) + + # Following lines will necessarily be different, see note. + expect_true( + !all(time_dependent_out[[1]][3, ] == + constant_rate_out[[1]][[1]]$stt_all[3, 1:4]) + ) +}) +