diff --git a/.Rbuildignore b/.Rbuildignore index 036cea1..9d31ed2 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -1,6 +1,5 @@ ^.*\.Rproj$ ^\.Rproj\.user$ -^\.travis\.yml$ ^\.github$ ^README\.md$ ^WARP\.md$ @@ -25,3 +24,8 @@ ^_pkgdown\.yml$ ^pkgdown-site$ ^pkgdown$ +^webr$ +^codemeta\.json$ +^CONTRIBUTING\.md$ +^ropensci-readiness\.md$ +^tests/js$ diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml new file mode 100644 index 0000000..6ec1bd4 --- /dev/null +++ b/.github/workflows/R-CMD-check.yaml @@ -0,0 +1,79 @@ +# Runs R CMD check, tests included, on Linux (release, devel, oldrel-1), macOS +# and Windows for every push to the main branch and every pull request. +# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples +# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help +on: + push: + branches: [main, master] + pull_request: + +name: R-CMD-check + +permissions: read-all + +jobs: + R-CMD-check: + runs-on: ${{ matrix.config.os }} + + name: ${{ matrix.config.os }} (${{ matrix.config.r }}) + + strategy: + fail-fast: false + matrix: + config: + - {os: macos-latest, r: 'release'} + - {os: windows-latest, r: 'release'} + - {os: ubuntu-latest, r: 'devel', http-user-agent: 'release'} + - {os: ubuntu-latest, r: 'release'} + - {os: ubuntu-latest, r: 'oldrel-1'} + + env: + GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} + R_KEEP_PKG_SOURCE: yes + # The tests that talk to live services (FishBase, GBIF, Global Names) and + # the ones that build a real vision model are guarded by skip_on_cran(). + # setup-r would set NOT_CRAN=true; keeping it false here makes those tests + # skip, so a slow or changed web service cannot fail the build. The tests + # that need Python (torch, open_clip) also skip because neither + # RETICULATE_PYTHON nor DIMOOSE_CLIP_WEIGHTS is set. Everything else, + # including the parsers and the vision code against a fake model, runs. + NOT_CRAN: false + + steps: + - uses: actions/checkout@v6 + + - uses: r-lib/actions/setup-pandoc@v2 + + - uses: r-lib/actions/setup-r@v2 + with: + r-version: ${{ matrix.config.r }} + http-user-agent: ${{ matrix.config.http-user-agent }} + + - uses: r-lib/actions/setup-r-dependencies@v2 + with: + extra-packages: any::rcmdcheck + needs: check + + # The behaviour tests of the interactive page (tests/js, run from + # tests/testthat/test-wizard-js.R) need node and the jsdom package; they + # skip without them. One job is enough, so only Ubuntu release gets them. + # jsdom is installed outside the checkout so that it cannot end up in + # the package. + - uses: actions/setup-node@v7 + if: matrix.config.os == 'ubuntu-latest' && matrix.config.r == 'release' + with: + node-version: 'lts/*' + + - name: Install jsdom for the wizard tests + if: matrix.config.os == 'ubuntu-latest' && matrix.config.r == 'release' + run: | + mkdir -p "$RUNNER_TEMP/dimoose-jsdom" + cd "$RUNNER_TEMP/dimoose-jsdom" + npm install --no-audit --no-fund jsdom + echo "DIMOOSE_JSDOM=$RUNNER_TEMP/dimoose-jsdom/node_modules" >> "$GITHUB_ENV" + shell: bash + + - uses: r-lib/actions/check-r-package@v2 + with: + upload-snapshots: true + build_args: 'c("--no-manual","--compact-vignettes=gs+qpdf")' diff --git a/.github/workflows/pkgdown.yaml b/.github/workflows/pkgdown.yaml index 6c7c1a9..fc11db7 100644 --- a/.github/workflows/pkgdown.yaml +++ b/.github/workflows/pkgdown.yaml @@ -46,6 +46,12 @@ jobs: file.create("pkgdown-site/.nojekyll") shell: Rscript {0} + # The page for people who do not use R: upload a spreadsheet, get the + # wizard. R runs in the browser (webR); build.R bundles the R code the page + # needs and checks it on the Montana key. Served at .../dimoose/webr/ + - name: Add the spreadsheet-to-wizard page + run: Rscript webr/build.R pkgdown-site/webr + - name: Deploy to GitHub pages if: github.event_name != 'pull_request' uses: JamesIves/github-pages-deploy-action@v4 diff --git a/.github/workflows/test-coverage.yaml b/.github/workflows/test-coverage.yaml new file mode 100644 index 0000000..75a8934 --- /dev/null +++ b/.github/workflows/test-coverage.yaml @@ -0,0 +1,65 @@ +# Measures test coverage with covr and uploads it to Codecov. Uploads from +# pushes need the repository secret CODECOV_TOKEN (from codecov.io); without +# it the upload step fails on pushes and is skipped quietly on pull requests. +# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples +# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help +on: + push: + branches: [main, master] + pull_request: + +name: test-coverage + +permissions: read-all + +jobs: + test-coverage: + runs-on: ubuntu-latest + env: + GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} + # As in R-CMD-check.yaml: skip the tests that need live web services + NOT_CRAN: false + + steps: + - uses: actions/checkout@v6 + + - uses: r-lib/actions/setup-r@v2 + + - uses: r-lib/actions/setup-r-dependencies@v2 + with: + extra-packages: any::covr, any::xml2 + needs: coverage + + - name: Test coverage + run: | + cov <- covr::package_coverage( + quiet = FALSE, + clean = FALSE, + install_path = file.path(normalizePath(Sys.getenv("RUNNER_TEMP"), winslash = "/"), "package") + ) + print(cov) + covr::to_cobertura(cov) + shell: Rscript {0} + + - uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7 + with: + # Fail if error if not on PR, or if on PR and token is given + fail_ci_if_error: ${{ github.event_name != 'pull_request' || secrets.CODECOV_TOKEN }} + files: ./cobertura.xml + plugins: noop + disable_search: true + token: ${{ secrets.CODECOV_TOKEN }} + + - name: Show testthat output + if: always() + run: | + ## -------------------------------------------------------------------- + find '${{ runner.temp }}/package' -name 'testthat.Rout*' -exec cat '{}' \; || true + shell: bash + + - name: Upload test results + if: failure() + uses: actions/upload-artifact@v7 + with: + name: coverage-test-failures + path: ${{ runner.temp }}/package diff --git a/.gitignore b/.gitignore index bff2837..b4694e5 100644 --- a/.gitignore +++ b/.gitignore @@ -42,3 +42,6 @@ WARP.md # pkgdown website (built by .github/workflows/pkgdown.yaml) pkgdown-site/ + +# The browser page built by webr/build.R (published by the pkgdown workflow) +webr/_site/ diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 74ce77d..0000000 --- a/.travis.yml +++ /dev/null @@ -1,24 +0,0 @@ -language: r -cache: packages -r: - - oldrel - - release - - devel - -sudo: false - -warnings_are_errors: true - -r_packages: - - rmarkdown - - covr - -r_check_args: --as-cran - -after_success: - - Rscript -e 'library(covr);codecov()' - -notifications: - email: - on_success: change - on_failure: change diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..fa178a3 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,125 @@ +# Contributing to dimoose + +Thank you for helping. Bug reports, keys that fail to import, ideas and pull +requests are all welcome. + +## Reporting a problem + +Open an issue at . It helps to include: + +- what you ran, as a small example that can be pasted into R. For a key, the + lead table (`key$leads`) or the spreadsheet rows are usually enough; +- what you expected and what happened instead, with the full error message; +- the output of `sessionInfo()`. + +For a FishBase key that imports wrongly, give its key number +(`importFishbase()`). + +Please do not post photos or data you are not allowed to share. + +## Proposing a change + +For anything larger than a small fix, open an issue first so we can agree on +the approach before you spend time on it. + +1. Fork the repository and make a branch from `master`. +2. Install the development dependencies: + + ```r + install.packages(c("remotes", "devtools")) + remotes::install_deps(dependencies = TRUE) + ``` + +3. Make the change, with a test and documentation (see below). +4. Run the checks: + + ```r + devtools::document() # regenerates man/ and NAMESPACE from the roxygen comments + devtools::test() + devtools::check() + ``` + +5. Add a line to the top of `NEWS.md` saying what changed, in words a user + of the package would recognise. +6. Open a pull request. The checks run on Linux, macOS and Windows + (`.github/workflows/R-CMD-check.yaml`). + +## Code style + +- Base R where it is enough; a new dependency needs a good reason. Packages + that only one feature needs go in `Suggests` and are checked for with + `requireNamespace()`, with a message saying what to install. +- Function and argument names are camelCase (`keyFromSpreadsheet()`, + `exportWizard()`), to match the existing interface. +- Call other packages as `pkg::fun()`. +- Error messages say what is wrong and what to do about it, in plain words, + and name the row or lead when there is one + (`"Row 4 has neither `Goes to` nor `Species`"`). Use `stop(..., call. = FALSE)`, + `warning()` and `message()`, not `cat()` or `print()`, outside print methods. +- Comments explain why, not what. + +## Documentation + +Documentation is written as roxygen2 comments with Markdown, above each +function in `R/`. Do not edit `man/` or `NAMESPACE` by hand. Every exported +function needs a description of what it returns (`@return`) and an example +that runs without the network or optional software; wrap the ones that +cannot in `\dontrun{}` or use `@examplesIf`. + +The website () is built from the +repository by `.github/workflows/pkgdown.yaml`; `_pkgdown.yml` lists the +reference sections, so a new exported function has to be added there. + +## Tests + +Tests use testthat (3rd edition) and live in `tests/testthat/`. + +- Tests must pass with no internet connection and without Python. Logic that + handles downloaded data is tested on saved pages or injected data (see + `test-parse-fishbase.R` and `fakeVisionModel()` in `helper-fake-vision.R`). +- A test that really calls a web service starts with `skip_on_cran()` and + `skip_if_unreachable(url)` (`helper-network.R`). These are skipped on GitHub + Actions, which sets `NOT_CRAN=false`; run them yourself before changing + import code: + + ```r + Sys.setenv(NOT_CRAN = "true") + devtools::test(filter = "fishbase|names") + ``` + +- A test that needs an optional package starts with + `skip_if_not_installed()`. +- The tests of the real vision model run only when `DIMOOSE_CLIP_WEIGHTS` + points to a weights file (see `test-vision-python.R`). + +## The page for people who do not use R + +`webr/` holds a static page that runs the spreadsheet-to-wizard path in the +browser with [webR](https://docs.r-wasm.org/webr/latest/). Build and try it with: + +```sh +Rscript webr/build.R # writes webr/_site and checks it on the Montana key +python3 -m http.server --directory webr/_site 8000 +``` + +The page loads only the R files listed in `webr/build.R`. If you change +`keyFromSpreadsheet()`, `exportWizard()` or what they call, run the build +again: it fails if those files have come to need code from another file or +another package. + +## Data and photos + +Third-party data and photos need a licence that allows redistribution, and an +entry in `inst/COPYRIGHTS` (and in `photos.tsv` for the Montana photos) giving +the source, author and licence. + +## Conduct + +Be kind and assume good faith. Harassment and personal attacks are not +accepted in issues, pull requests or any other project space; report problems +to the maintainer (address in `DESCRIPTION`). + +## Licence + +By contributing you agree that your contribution is distributed under the +package's licence (GPL; see `DESCRIPTION`). diff --git a/DESCRIPTION b/DESCRIPTION index 4cea88a..3ec6074 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -2,7 +2,7 @@ Package: dimoose Type: Package Title: Tools to Reshape and Manipulate Dichotomous Keys Used in Taxonomic Identification -Version: 0.2.0 +Version: 0.3.0 Authors@R: person("Jeremy", "Leipzig", , "leipzig@gmail.com", role = c("aut", "cre"), comment = c(ORCID = "0000-0001-7224-9620")) @@ -13,7 +13,7 @@ Description: Transforms between dichotomous identification keys and a and includes PhyloTree Build 17, the human mitochondrial DNA phylogeny (van Oven 2015, ), as distributed by 'Haplogrep' 3. -License: GPL +License: GPL (>= 3) Copyright: See inst/COPYRIGHTS for third-party data and example pages. URL: https://leipzig.github.io/dimoose/, https://github.com/leipzig/dimoose BugReports: https://github.com/leipzig/dimoose/issues @@ -29,6 +29,7 @@ Imports: rpart, rvest (>= 1.0.0), stats, + tools, utils, withr, xml2 @@ -36,14 +37,11 @@ Suggests: ape, phangorn, gbm, - glmertree, igraph, jpeg, jsonlite, knitr, - lme4, magick, - partykit, png, randomForest, reticulate (>= 1.41.0), diff --git a/NAMESPACE b/NAMESPACE index 64c1e6a..a45fd21 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,18 +1,24 @@ # Generated by roxygen2: do not edit by hand +S3method(print,dimooseBenchmark) S3method(print,dimooseVisionModel) -S3method(print,mecit) +S3method(print,tdwgData) +S3method(print,textKeyParse) S3method(summary,dimoose) export(alignmentScores) export(arachnidaKey) +export(benchmarkKey) export(checkNames) export(classify) +export(claudeNamer) export(dimoose) export(discoverSniglets) export(discoverTerms) export(embedImages) export(embedTexts) export(evaluateKey) +export(exportBrowserModel) +export(exportOnnxModel) export(exportWizard) export(featureScores) export(featureTable) @@ -23,34 +29,52 @@ export(imageMeta) export(imageMime) export(imageSet) export(importFishbase) +export(inatPhotos) export(inventNames) export(keyDiagram) export(keyFromAlignment) export(keyFromClusters) export(keyFromLeads) -export(keyFromMecit) +export(keyFromMatrix) export(keyFromRpart) export(keyFromSniglets) export(keyFromSpreadsheet) export(keyFromTerms) +export(keyFromText) +export(keyQuality) +export(keyToSpreadsheet) +export(loadEmbeddings) export(looKey) export(macroHaplogroup) -export(mecit) +export(mergeKeys) export(modelMeta) export(montanaKey) +export(occurrenceWeights) +export(onnxCache) +export(onnxModel) export(parseFishbase) +export(parseTextKey) export(patchExemplars) export(phylotreeKey) +export(pruneKey) export(rawhtml) +export(readDELTA) export(readHaplogrep) +export(readLucid) +export(readLucidKey) +export(readSDD) +export(readSDDKey) +export(readXper) export(recurrentPositions) +export(regionalKey) export(renameSniglets) +export(saveEmbeddings) export(scoreImages) export(sharkKey) -export(simulateExpression) export(snigletNames) export(snigletScores) -export(splitVariables) +export(splitByObservation) +export(suggestSnigletNames) export(suggestSpecies) export(termScores) export(toAuspiceJSON) @@ -58,7 +82,14 @@ export(toIgraph) export(toNewick) export(toTreedata) export(vibrioKey) +export(vibrioMatrix) export(visionModel) export(vocabularyPrompts) +export(writeDELTA) +export(writeLucid) +export(writeLucidKey) +export(writeSDD) +export(writeSDDKey) +export(writeXper) importFrom(R6,R6Class) importFrom(data.tree,Node) diff --git a/NEWS.md b/NEWS.md index 681bb13..f8b689b 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,183 @@ +# dimoose 0.3.0 (development version) + +## Breaking changes + +* `mecit()`, `keyFromMecit()`, `splitVariables()` and `simulateExpression()` + have moved to the companion package + [mecit](https://github.com/leipzig/mecit), with their vignette and + simulation study. `haplotypeMatrix()`, `recurrentPositions()` and + `macroHaplogroup()` stay in dimoose. +* `vibrioKey()` gains `variable = c("both", "missing")` and now defaults to + `"both"`: species with variable or undetermined test results are reached + down both leads (92 couplets instead of 73; 14 species have two or three + results). `vibrioKey(variable = "missing")` returns the previous + rpart-based key unchanged. +* `generateTree()` now defaults to + `rpart.control(minsplit = 2, minbucket = 1, cp = 0)`; rpart's own defaults + made no split on a matrix with one row per taxon. +* `exportWizard(order = )` is deprecated and ignored; `"parsimony"` (never + implemented) now warns instead of stopping. To ask the easiest questions + first, build the key with `keyFromMatrix(characters = )` and give the + characters a `Cost`. +* The licence is now stated as `GPL (>= 3)`; it was the unversioned `GPL`. + +## Reading keys and matrices + +* `keyFromText()` reads keys written as plain text (bracketed or indented + layouts; `1a`/`1b`, primes, dashes, `A.`/`AA.`, back-references such as + `3(1).`; dot leaders, tabs or gaps before the destination; wrapped leads, + page headers) and builds a checked dimoose key. +* `parseTextKey()` returns the lead table and a report of problems, repairs + and notes, each with its line number; `strict = TRUE` stops instead of + repairing OCR noise. +* Both accept `llm`, a user-supplied function for a first pass over messy + scans; its answer is checked against the source and mistakes are reported + by line. dimoose calls no model itself. +* Example text keys are in `inst/extdata/textkeys/`. +* `readSDD()` and `writeSDD()` read and write TDWG SDD 1.1 (Structured + Descriptive Data) as a character matrix: categorical, quantitative and text + characters, variable taxa, not-applicable codings, dependency rules and + ratings. +* `readSDDKey()` and `writeSDDKey()` read and write dichotomous keys stored + in SDD (``), following subkeys; `writeSDD(key = )` + stores a matrix and a key in one file. +* `readDELTA()` and `writeDELTA()` read and write DELTA datasets (specs, + chars and items files), including implicit values, dependent characters, + variant items and comments. +* `readLucid()` and `writeLucid()` exchange matrix keys with Lucid through + the Builder's CSV format and SDD; `readLucid()` also reads the multistate + scores of LIF3 files. +* `readLucidKey()` and `writeLucidKey()` read and write Lucid pathway keys as + Lucid Phoenix XML (.lpxk), CSV, text and SDD. +* `readXper()` and `writeXper()` exchange knowledge bases with Xper2/Xper3 + through their SDD export. +* Small example files for these formats are in `inst/extdata/tdwg/`. Files + written by dimoose have not yet been opened in Lucid, Xper or a DELTA + program. +* `keyToSpreadsheet()` writes a key as the CSV that `keyFromSpreadsheet()` + reads, with embedded photos written out as files, so imported or generated + keys can be edited by hand and read back. +* `keyFromSpreadsheet()` keeps web addresses in the `Photo` column as links, + and a `#` in a cell no longer hides the rest of the row from the + too-many-cells check. + +## Keys from a character matrix + +* `keyFromMatrix()` builds a key from a taxon-by-character matrix. A taxon + that is variable for a character (`"+/-"`) or unknown (`NA`) is keyed out + down both leads of every couplet that uses it, so every state a specimen + can show ends at its taxon. Multi-state characters are keyed out one state + at a time; taxa that cannot be separated share a result. +* `keyFromMatrix()` takes an optional `characters` table: `Cost` makes cheap + characters come first (the split with the most separated pairs of taxa per + unit cost is chosen), and `season` keeps only characters observable in that + season, e.g. `season = "winter"` for a bark and twig key. +* `vibrioMatrix()` returns the `vibrio` dataset as a character matrix for + `keyFromMatrix()`. + +## Pruning, merging and quality + +* `pruneKey()` keeps or drops named taxa, removes dead leads and collapses + couplets that no longer split anything, optionally renumbering in reading + order; the confirming character of a collapsed couplet is kept in a `Note` + column. +* `regionalKey()` prunes a key to the taxa recorded in a place according to + GBIF (GADM region, country, polygon or place name) or iNaturalist, with a + minimum record count and an auditable table of counts in + `attr(x, "records")`. +* `mergeKeys()` grafts one key onto a terminal taxon of another, combining + leads, metadata, images, taxa and features. +* `summary()` on a key now reports how quickly it reaches a result: mean + steps over terminal leads and over taxa, expected steps weighted by how + common each taxon is (`summary(key, weights = )`), the steps the best + possible key to the same taxa would need (`bound`) and an efficiency ratio; + `print()` shows the mean steps. +* `keyQuality()` returns the detail: steps per taxon and per terminal lead, + bound, efficiency, entropy and bits per step, for keys with multi-lead + couplets, taxa keyed out more than once and reticulate keys. +* `occurrenceWeights()` counts GBIF occurrence records per taxon of a key, + optionally within a country or GADM region, for use as weights. + +## The interactive page + +* `exportWizard()`: every couplet has an "I'm not sure" choice (keys `u` or + `?`) that follows all its leads; the page tracks the open branches, counts + and maps the taxa possible in any of them, and lists the candidates if the + reader stays unsure. Back undoes one step, and the address records the open + branches. +* `exportWizard(matrix = , characters = )`: with a character matrix the page + also offers "pick any character you can see", cheapest characters first, + with variable (`"a/b"`) and unknown (`NA`) states handled; + `exportWizard(NULL, matrix = )` makes a multi-access page without a key. +* `exportWizard(offline = TRUE)` writes a web app manifest, a service worker + and icons next to the page, so the key can be installed on a phone and + opened without a connection (needs https or localhost). +* The exported page defines `window.dimoose` (`taxa`, `highlight()`, + `goToTaxon()`, `state()`, `onChange()`) so other scripts, such as + in-browser photo identification, can mark likely taxa on the map and in + candidate lists. +* `exportWizard(photoModel = )`, given a folder written by + `exportBrowserModel()`, adds "Identify from a photo": the image encoder + runs in the reader's browser with onnxruntime-web, the photo never leaves + the device, and the page marks the likely taxa and offers to narrow the key + to them. The model is downloaded only after the reader agrees. +* The wizard's remaining-taxa count is now correct for keys where a couplet + is reached from more than one lead, and is computed without the map. +* A web page turns a key spreadsheet (CSV, with optional photos) into the + interactive wizard without installing R: R runs in the browser through + webR. It is built by `webr/build.R` and published with the website at + . + +## Keys from photos + +* `visionModel(backend = "onnx")` and `onnxModel()` embed images and texts + with ONNX Runtime instead of PyTorch, a much smaller Python install, with + the same embeddings on the example photos. CLIP ViT-B/32 is downloaded + ready-made from the Hugging Face Hub; `precision = "fp16"` or `"int8"` + picks a smaller copy. +* `exportOnnxModel()` converts BioCLIP, BioCLIP 2 and other open_clip models + to ONNX once (image and text encoders, tokenizer, optional int8 and fp16 + copies), for use without PyTorch afterwards. +* `saveEmbeddings()` and `loadEmbeddings()` keep embeddings in a small + safetensors file, so keys can be built and scored from precomputed + embeddings with no Python at all. +* `exportBrowserModel()` writes what a web page needs to identify photos on + the visitor's device: an image encoder, its preprocessing constants, and + text embeddings of a key's species. +* `suggestSnigletNames()` has a vision-language model propose a name and a + one-sentence definition for each sniglet from its example crops, and + returns the names table `renameSniglets()` takes (or writes it as the CSV + it reads), so naming becomes reviewing suggestions. Names are kept short, + distinct and descriptive: class and species names are refused. +* `claudeNamer()` is a ready-made model for `suggestSnigletNames()` that asks + Claude through the Anthropic Messages API (needs an API key; calls are + billed to it). It has been tested against a stand-in for the API only. +* `inatPhotos()` downloads a balanced, reproducible sample of research-grade, + openly licensed iNaturalist photos for a set of species, with a manifest + (observation, photo, licence, attribution, URL) so a benchmark can be cited + and re-run. +* `benchmarkKey()` measures identification on field photos (top-1 and top-k + accuracy, per-species accuracy, confusion table) for species ranked by + name, for a key followed by machine, or for a photo key built from the + training photos; `splitByObservation()` keeps every observation on one side + of the train/test split. +* New `analysis/inat-benchmark/`: a first benchmark on 220 iNaturalist photos + of the eleven Montana broadleaf trees with BioCLIP 2 (script, manifest, + results and limits). +* The Python tests skip instead of failing where PyTorch is not installed. + +## Documentation and infrastructure + +* New vignette, "From a published key to a field key": a text key is read, + checked, cut down to a county, measured and exported for offline use. +* The README no longer lists features the package does not have (YAML, + lexical analysis), and describes the ones added here. +* `citation("dimoose")` now gives how to cite the package, plus PhyloTree + Build 17 and FishBase for users of those data. +* The package is checked on Linux, macOS and Windows with GitHub Actions + (replacing Travis; `.travis.yml` is removed), and test coverage is reported + to Codecov; added `CONTRIBUTING.md` and `codemeta.json`. + # dimoose 0.2.0 * `checkNames()` looks up every scientific name in a key in the GBIF backbone diff --git a/R/benchmark.R b/R/benchmark.R new file mode 100644 index 0000000..fff338f --- /dev/null +++ b/R/benchmark.R @@ -0,0 +1,673 @@ +#' Download a balanced sample of iNaturalist photos +#' +#' Collects field photos to test a key with: for each species, `n` +#' observations from [iNaturalist](https://www.inaturalist.org) with an openly +#' licensed photo, the photo files, and a manifest that says where every photo +#' came from, so that a benchmark can be cited and run again. +#' +#' @section How the sample is drawn: +#' The sample depends only on the arguments, not on the day it is drawn: +#' +#' 1. `idBelow` fixes the snapshot: only observations with a smaller id are +#' considered. When it is `NULL` the newest observation id at the time of +#' the call is used and recorded in the manifest (`id_below`); give that +#' value to draw the same sample again later. +#' 2. For each species a pool of up to `pool` observations is collected from +#' `strata` equal slices of the id range (the newest observations below +#' each cut), so that the pool spans the years rather than being last +#' month's photos. Ids follow upload dates, so each slice is a short +#' stretch of time and the same stretches are used for every species; +#' raise `strata` (one request each) for an evener spread over the +#' seasons. +#' 3. From the pool, sorted by id, `n` observations are drawn with `seed`, +#' taking at most `perObserver` from one observer, so that one person's +#' many photos of the same tree cannot dominate. +#' +#' Observations that were deleted or lost their research grade since are +#' simply no longer returned, so an old sample can shrink; the photo files +#' already in `dir` are kept and not downloaded again. A photo that cannot be +#' downloaded, or that turns out not to be an image, is left out of the +#' manifest with a warning; it is not replaced by another. +#' +#' @section Which taxon a name means: +#' A name is looked up in iNaturalist's taxon search and must match a taxon's +#' name exactly; a looser match (the search also finds "Oenantheae" and +#' "Oenanthe oenanthe" for "Oenanthe") is never used. A name iNaturalist +#' lists as a synonym resolves to the taxon it now belongs to, with a message. +#' The same name can belong to two taxa (the genus *Oenanthe* is a bird and a +#' plant): then the one whose rank fits the name best and that has the most +#' observations is used, with a warning that lists the candidates and their +#' ids. Give the taxon id instead of the name to choose yourself. The +#' manifest records the id that was used. +#' +#' @section API etiquette: +#' Requests are spaced at least `pause` seconds apart (iNaturalist asks for +#' about one request a second) and identify themselves with a generic +#' User-Agent. Only photos whose own licence is in `licenses` are taken; +#' the manifest keeps each photo's licence and attribution, which the CC BY +#' licences require you to show wherever the photos are. +#' +#' @param taxa The species: scientific names, results written +#' `"Common name (Genus species)"`, a [dimoose] key (its results are used), +#' or iNaturalist taxon ids (a numeric vector, named to give the labels). +#' @param n Observations to sample per species. +#' @param place Optional place to restrict the sample to: an iNaturalist +#' place id, or a name to look up (the best match is used and reported). +#' @param qualityGrade iNaturalist quality grade. `"research"` means the +#' community agreed on the species. +#' @param licenses Photo licences to accept. +#' @param dir Folder to put the photos and `manifest.csv` in; one subfolder +#' per species. Keep it outside a package or repository. +#' @param fetch Function `function(url, query)` that performs an API request +#' and returns the parsed JSON as a list. The default calls the iNaturalist +#' API; tests give their own. +#' @param download Function `function(url, destfile)` that saves a photo. +#' @param size Photo size: `"small"` (240 px), `"medium"` (500 px), `"large"` +#' (1024 px) or `"original"`. +#' @param pool,strata Size of the pool the sample is drawn from, and the +#' number of slices of the id range it is collected from. +#' @param idBelow Only observations with an id below this; see above. +#' @param seed Seed for drawing the sample from the pool. +#' @param perObserver Most observations to take from one observer per species. +#' @param photosPerObservation Most photos to take from one observation. +#' @param query Further parameters for the observation search, e.g. +#' `list(month = "6,7,8")` for summer photos only. +#' @param pause Least number of seconds between requests. +#' @return The manifest, a data frame with one row per photo: `taxon` (the +#' label, as given in `taxa`), `scientific_name`, `taxon_id`, +#' `observation_id`, `photo_id`, `license`, `attribution`, `url`, +#' `observation_url`, `observed_on`, `file` (relative to `dir`), +#' `quality_grade`, `place_id`, `id_below` and `retrieved`; plus `path`, the +#' full file name on this computer, which is not written to +#' `manifest.csv`. [benchmarkKey()] takes it as its `photos`. +#' @seealso [benchmarkKey()] +#' @examples +#' \dontrun{ +#' photos <- inatPhotos(montanaKey(), n = 20, dir = file.path(tempdir(), "inat")) +#' table(photos$taxon) +#' } +#' @export +inatPhotos <- function(taxa, n = 20, place = NULL, qualityGrade = "research", licenses = c("cc0", "cc-by", "cc-by-nc"), + dir, fetch = benchInatGet, download = benchDownload, size = "medium", pool = 200, strata = 10, + idBelow = NULL, seed = 1, perObserver = 1, photosPerObservation = 1, query = list(), pause = 1) { + size <- match.arg(size, c("small", "medium", "large", "original")) + if (missing(dir)) stop("Give `dir`, the folder to put the photos in", call. = FALSE) + api <- "https://api.inaturalist.org/v1/" + licenses <- tolower(licenses) + last <- NULL + wait <- function() { # at most one request every `pause` seconds + if (!is.null(last) && pause > 0) { + left <- pause - as.numeric(difftime(Sys.time(), last, units = "secs")) + if (left > 0) Sys.sleep(left) + } + last <<- Sys.time() + } + get <- function(path, q) { + wait() + r <- fetch(paste0(api, path), q[!vapply(q, is.null, logical(1))]) + if (!is.list(r)) stop("iNaturalist returned something that is not JSON for ", path, call. = FALSE) + r + } + + if (inherits(taxa, "dimoose")) taxa <- unique(taxa$leads$Taxon[!is.na(taxa$leads$Taxon) & nzchar(taxa$leads$Taxon)]) + if (is.numeric(taxa)) { + labels <- if (is.null(names(taxa))) as.character(taxa) else names(taxa) + taxonId <- as.numeric(taxa); sci <- rep(NA_character_, length(taxa)) + } else { + labels <- as.character(taxa) + sci <- scientificPart(labels); sci[is.na(sci)] <- labels[is.na(sci)] + taxonId <- rep(NA_real_, length(labels)) + } + if (!length(labels) || anyNA(labels) || any(!nzchar(trimws(labels))) || anyDuplicated(labels)) { + stop("`taxa` must name each species once", call. = FALSE) + } + if (is.numeric(taxa) && (anyNA(taxonId) || any(taxonId <= 0 | taxonId != round(taxonId)))) stop("Taxon ids must be whole numbers", call. = FALSE) + whole <- function(v, least) is.numeric(v) && length(v) == 1 && !is.na(v) && v >= least + if (!whole(n, 1)) stop("`n` must be 1 or more", call. = FALSE) + if (!whole(strata, 1) || !whole(pool, 1)) stop("`pool` and `strata` must be 1 or more", call. = FALSE) + if (!whole(perObserver, 1) || !whole(photosPerObservation, 1)) stop("`perObserver` and `photosPerObservation` must be 1 or more", call. = FALSE) + if (!length(licenses) || anyNA(licenses)) stop("Give at least one licence in `licenses`", call. = FALSE) + + placeId <- NULL + if (!is.null(place)) { + if (is.numeric(place)) placeId <- place else { + found <- get("places/autocomplete", list(q = place, per_page = 10))$results + if (!length(found)) stop("iNaturalist knows no place called ", place, call. = FALSE) + nm <- vapply(found, function(p) c(p$display_name, p$name, "")[1], "") + hit <- match(tolower(place), tolower(c(nm, vapply(found, function(p) c(p$name, "")[1], "")))) + hit <- if (is.na(hit)) 1L else ((hit - 1L) %% length(found)) + 1L + placeId <- found[[hit]]$id + message("Place: ", nm[hit], " (iNaturalist place ", placeId, ")") + } + } + if (is.null(idBelow)) { + newest <- get("observations", list(per_page = 1, order_by = "id", order = "desc"))$results + if (!length(newest)) stop("Could not find the newest iNaturalist observation", call. = FALSE) + idBelow <- newest[[1]]$id + 1 + } + idBelow <- as.numeric(idBelow) + + ext <- function(url) { e <- tolower(sub("^.*\\.([A-Za-z0-9]+)(\\?.*)?$", "\\1", url)); if (e %in% c("jpg", "jpeg", "png", "gif", "webp")) e else "jpg" } + rows <- list() + for (t in seq_along(labels)) { + if (is.na(taxonId[t])) { + found <- get("taxa", list(q = sci[t], is_active = "true", per_page = 30))$results + hit <- benchPickTaxon(sci[t], found) + if (is.null(hit)) { + warning("iNaturalist has no taxon named ", sci[t], "; it is left out", call. = FALSE) + next + } + taxonId[t] <- hit$id + } else if (is.na(sci[t])) { + # a taxon given by its id: ask for its name, so that the folder and the manifest carry it + known <- tryCatch(get(paste0("taxa/", format(taxonId[t], scientific = FALSE)), list())$results, error = function(e) NULL) + if (length(known) && is.character(known[[1]]$name)) sci[t] <- known[[1]]$name + } + # the pool: the newest observations below each of `strata` cuts of the id range + cuts <- unique(ceiling(idBelow * rev(seq_len(strata)) / strata)) + each <- min(200, ceiling(pool / length(cuts))) + obs <- list() + for (cut in cuts) { + got <- get("observations", c(list(taxon_id = taxonId[t], quality_grade = qualityGrade, photos = "true", + photo_license = paste(licenses, collapse = ","), place_id = placeId, + id_below = format(cut, scientific = FALSE), order_by = "id", order = "desc", + per_page = each), query))$results + for (o in got) obs[[as.character(o$id)]] <- o + } + obs <- obs[order(as.numeric(names(obs)))] + usable <- lapply(obs, function(o) { + ok <- Filter(function(p) !is.null(p$license_code) && tolower(p$license_code) %in% licenses && !is.null(p$url), o$photos) + utils::head(ok, photosPerObservation) + }) + obs <- obs[lengths(usable) > 0]; usable <- usable[lengths(usable) > 0] + if (is.na(sci[t]) && length(obs)) sci[t] <- c(obs[[1]]$taxon$name, labels[t])[1] + if (is.na(sci[t])) sci[t] <- labels[t] + # the sample: a seeded shuffle of the pool, taking a few per observer at most + shuffled <- if (length(obs) > 1) withr::with_seed(seed, sample(length(obs))) else seq_along(obs) + who <- vapply(obs, function(o) as.character(c(o$user$id, NA)[1]), "") + pick <- integer() + for (i in shuffled) { + if (length(pick) >= n) break + if (!is.na(who[i]) && sum(who[pick] == who[i], na.rm = TRUE) >= perObserver) next + pick <- c(pick, i) + } + if (length(pick) < n) { + warning("Only ", length(pick), " of ", n, " observations found for ", labels[t], call. = FALSE) + } + folder <- slug(sci[t]) + for (i in sort(pick)) { + o <- obs[[i]] + for (p in usable[[i]]) { + url <- sub("/square\\.", paste0("/", size, "."), p$url) + rows[[length(rows) + 1]] <- data.frame( + taxon = labels[t], scientific_name = sci[t], taxon_id = taxonId[t], observation_id = as.numeric(o$id), + photo_id = as.numeric(p$id), license = tolower(p$license_code), attribution = c(p$attribution, "")[1], url = url, + observation_url = paste0("https://www.inaturalist.org/observations", "/", format(o$id, scientific = FALSE)), + observed_on = c(o$observed_on, NA_character_)[1], + file = file.path(folder, paste0(format(o$id, scientific = FALSE), "_", format(p$id, scientific = FALSE), ".", ext(url))), + stringsAsFactors = FALSE) + } + } + } + if (!length(rows)) stop("No photos found for any of the taxa", call. = FALSE) + manifest <- do.call(rbind, rows) + manifest$quality_grade <- qualityGrade + manifest$place_id <- if (is.null(placeId)) NA_real_ else as.numeric(placeId) + manifest$id_below <- idBelow + manifest$retrieved <- format(Sys.Date()) + + dir.create(dir, recursive = TRUE, showWarnings = FALSE) + keep <- rep(TRUE, nrow(manifest)) + for (r in seq_len(nrow(manifest))) { + dest <- file.path(dir, manifest$file[r]) + # a file from an earlier run is used again, unless it is not an image (a download that was cut short, an error page) + isImage <- function(f) file.exists(f) && file.size(f) > 0 && !is.na(imageMime(f)) + if (isImage(dest)) next + dir.create(dirname(dest), recursive = TRUE, showWarnings = FALSE) + wait() + ok <- tryCatch({ download(manifest$url[r], dest); if (isImage(dest)) TRUE else "what came back is not an image" }, + error = function(e) conditionMessage(e)) + if (!isTRUE(ok)) { + warning("Could not download ", manifest$url[r], if (is.character(ok)) paste0(": ", ok), call. = FALSE) + if (file.exists(dest)) unlink(dest) + keep[r] <- FALSE + } + } + manifest <- manifest[keep, , drop = FALSE] + rownames(manifest) <- NULL + if (!nrow(manifest)) stop("None of the photos could be downloaded", call. = FALSE) + utils::write.csv(manifest, file.path(dir, "manifest.csv"), row.names = FALSE) + manifest$path <- file.path(dir, manifest$file) + manifest +} + +#' Split photos into training and test sets by observation +#' +#' Photos of one observation show the same individual, often seconds apart. +#' Putting one in the training set and another in the test set would make a +#' key look better than it is, so whole observations go to one side. +#' +#' @param observation The observation each photo belongs to. A photo without +#' one (`NA`) counts as an observation of its own. +#' @param label The class of each photo. The split is made within each class, +#' so every class keeps about the same share for testing. +#' @param test Share of each class's observations to test with. +#' @param seed Seed for the draw. +#' @return A character vector, `"train"` or `"test"` for each photo. A class +#' with two or more observations gets at least one on each side; a class +#' with a single observation goes to the training set. An observation with +#' photos in several classes stays whole too: all its photos go to the +#' training set, so nothing in the test set has a sibling in training. +#' @examples +#' obs <- c(1, 1, 2, 3, 4, 5, 5, 6) +#' label <- rep(c("oak", "elm"), each = 4) +#' data.frame(obs, label, split = splitByObservation(obs, label, test = 0.5)) +#' @export +splitByObservation <- function(observation, label, test = 0.3, seed = 1) { + if (length(observation) != length(label)) stop("`observation` and `label` must have one entry per photo", call. = FALSE) + if (!is.numeric(test) || length(test) != 1 || is.na(test) || test < 0 || test > 1) { + stop("`test` must be a share between 0 and 1", call. = FALSE) + } + label <- as.character(label) + if (anyNA(label)) stop("Every photo needs a `label`", call. = FALSE) + observation <- as.character(observation) + lone <- is.na(observation) + observation[lone] <- paste0("\rphoto ", which(lone)) # no observation: the photo is its own + out <- rep("train", length(label)) + if (test == 0 || !length(label)) return(out) + if (test == 1) return(rep("test", length(label))) + # drawn within each class, over its observations + who <- paste(label, observation, sep = "\r") + withr::with_seed(seed, for (l in sort(unique(label))) { + obs <- sort(unique(who[label == l])) + if (length(obs) < 2) next + nTest <- min(length(obs) - 1L, max(1L, as.integer(round(test * length(obs))))) + out[who %in% obs[sample(length(obs), nTest)]] <- "test" + }) + # an observation with photos in two classes may have been drawn to both sides + both <- intersect(observation[out == "train"], observation[out == "test"]) + out[observation %in% both] <- "train" + out +} + +#' Benchmark identification on field photos +#' +#' Measures how often photos are identified correctly, by one of three +#' routes: +#' +#' * `"names"`: the model ranks the key's own species for each photo from +#' their names alone ([suggestSpecies()]); nothing is learned from the +#' photos. With a `lineage` the answers of [identifyPhotos()], which fall +#' back to the genus, family or order when the species is uncertain, are +#' scored too. +#' * `"key"`: a key with machine tests (from [keyFromSniglets()] or +#' [keyFromClusters()]) is followed for each photo ([scoreImages()], +#' [evaluateKey()]). +#' * `"build"`: a photo key is built from the training photos (sniglets +#' found in them, then [keyFromSniglets()]) and followed for the test +#' photos. This is the route to use for "how good a key can be learned +#' from photos like these". +#' +#' Training and test photos are divided by observation with +#' [splitByObservation()], never photo by photo. +#' +#' @param x A [dimoose] key, or (for `route = "build"`) a [visionModel()]. +#' @param photos The photos: the manifest [inatPhotos()] returns, the path of +#' a `manifest.csv` (give `dir` too), or a data frame with `path` and +#' `label` and optionally `id` and `observation`. Labels may be the key's +#' results or just their scientific names. Without an observation column +#' every photo counts as its own observation. +#' @param model A [visionModel()]. +#' @param route `"names"`, `"key"` or `"build"`. By default `"build"` when `x` +#' is a vision model, `"key"` for a key with machine tests and `"names"` +#' for any other key. +#' @param top Report the accuracy within this many guesses (`"names"` only: a +#' key gives one answer). +#' @param test Share of each species' observations to test with. By default +#' 0.3 for `"build"` and all of them for the other routes, which learn +#' nothing from the photos. +#' @param split Instead of `test`: `"train"` or `"test"` for each photo, e.g. +#' from [splitByObservation()], to compare routes on the same test photos. +#' @param seed Seed for the split and for finding sniglets. +#' @param reps Number of splits to run. One split of a small sample says +#' little: six test photos per species move a species' accuracy by 17 +#' points each. With `reps` above 1 the benchmark is repeated with seeds +#' `seed`, `seed + 1`, ..., each with a new split (and, for `"build"`, a new +#' key; the photos are embedded once), and the spread is reported. Needs a +#' `test` share below 1, and no `split`. +#' @param dir The folder the manifest's `file` column is relative to. +#' @param prompt,lineage,confidence As in [identifyPhotos()]. `lineage` is +#' optional and is never looked up here. +#' @param k,tiles,method For `"build"`: number of sniglets +#' ([discoverSniglets()]), tiling ([embedImages()]) and tree method +#' ([keyFromSniglets()]). +#' @param embeddings For `"build"`: the result of [embedImages()] for +#' `photos`, if you have it already (rows in the same order). +#' @return An object of class `dimooseBenchmark`, a list with +#' * `route`, `n` (test photos), `nTrain`, `observations` (test observations); +#' * `accuracy`: share of test photos identified correctly (top-1); +#' * `interval`: its 95% Wilson interval (`lower`, `upper`), which treats the +#' test photos as independent draws: read it as the least uncertainty +#' there is, not all of it; +#' * `topK`: named vector of the accuracy within 1, ..., `top` guesses; +#' * `perSpecies`: for each species its number of test photos, `top1` and +#' (for `"names"`) the accuracy within `top` guesses. Every species of +#' the photos (and of the key) has a row; one without test photos has +#' `n = 0` and `NA` accuracies; +#' * `confusion`: table of actual (rows) against predicted (columns), with +#' the same species in the same order on both sides, so that the row sums +#' are the `n` of `perSpecies` and the diagonal holds the correct answers. +#' Any other answer has a column after them: a leaf that names several +#' species, and `""` when a key gave no answer; +#' * `results`: one row per test photo with `id`, `observation`, `actual`, +#' `predicted`, `rank` (where the true species came in the ranking) and +#' `correct`; +#' * `split`: `"train"` or `"test"` for every photo given; +#' * with `reps` above 1, all of the above describe the first split, and +#' there are also `repeats` (one row per split: `rep`, `seed`, `n`, +#' `nTrain`, `correct`, `accuracy`), `accuracyMean`, `accuracySd` (the +#' standard deviation between splits) and `accuracyRange`, and +#' `perSpecies` gains `top1Mean`, the species' accuracy over all splits' +#' test photos together. The splits share photos, so they are not +#' independent samples: the spread shows how much one split can mislead, +#' it is not a standard error; +#' * `key` (for `"build"`, the key that was built) and `identify` (for +#' `"names"` with a `lineage`: the [identifyPhotos()] answers with +#' `correct`, and the shares that were `confident` and `correct`). +#' @seealso [inatPhotos()], [evaluateKey()], [looKey()] +#' @examples +#' \dontrun{ +#' key <- montanaKey() +#' photos <- inatPhotos(key, n = 20, dir = file.path(tempdir(), "inat")) +#' model <- visionModel(name = "bioclip-2") +#' benchmarkKey(key, photos, model) # species ranked from their names +#' benchmarkKey(model, photos) # a key built from 70% of the observations +#' } +#' @export +benchmarkKey <- function(x, photos, model = NULL, route = NULL, top = 3, test = NULL, split = NULL, seed = 1, dir = NULL, + prompt = "a photo of %s.", lineage = NULL, confidence = 0.8, + k = 40, tiles = 4, method = "rpart", embeddings = NULL, reps = 1) { + if (!is.numeric(reps) || length(reps) != 1 || is.na(reps) || reps < 1 || reps != round(reps)) stop("`reps` must be a whole number, 1 or more", call. = FALSE) + if (reps > 1) { + return(benchRepeat(x, photos, model = model, route = route, top = top, test = test, split = split, seed = seed, dir = dir, + prompt = prompt, lineage = lineage, confidence = confidence, k = k, tiles = tiles, method = method, + embeddings = embeddings, reps = as.integer(reps))) + } + key <- NULL + if (inherits(x, "dimooseVisionModel")) { + model <- x + if (is.null(route)) route <- "build" + } else if (inherits(x, "dimoose")) { + key <- x + if (is.null(route)) route <- if (any(nzchar(normalizeLeads(key$leads)$Feature))) "key" else "names" + } else { + stop("`x` must be a dimoose key or a vision model", call. = FALSE) + } + route <- match.arg(route, c("names", "key", "build")) + if (route != "build" && is.null(key)) stop("The \"", route, "\" route needs a key", call. = FALSE) + if (is.null(model) && !(route == "build" && !is.null(embeddings))) stop("Give `model`, a visionModel()", call. = FALSE) + photos <- benchPhotos(photos, dir) + if (route != "build") photos$label <- benchLabels(photos$label, key, strict = route == "names") + # every species there is to get right: those of the photos, then any others the key ends in + species <- sort(unique(photos$label)) + if (!is.null(key)) { + ends <- unique(key$leads$Taxon[!is.na(key$leads$Taxon) & nzchar(key$leads$Taxon)]) + species <- c(species, sort(setdiff(ends[!grepl(" / ", ends, fixed = TRUE)], species))) + } + if (is.null(split)) { + if (is.null(test)) test <- if (route == "build") 0.3 else 1 + split <- splitByObservation(photos$observation, photos$label, test = test, seed = seed) + } else { + if (length(split) != nrow(photos) || !all(split %in% c("train", "test"))) { + stop("`split` must say \"train\" or \"test\" for each photo", call. = FALSE) + } + both <- intersect(photos$observation[split == "train"], photos$observation[split == "test"]) + if (length(both)) stop("`split` puts photos of one observation on both sides: ", paste(utils::head(both, 5), collapse = ", "), call. = FALSE) + } + isTest <- split == "test" + if (!any(isTest)) stop("There are no test photos", call. = FALSE) + tp <- photos[isTest, , drop = FALSE] + built <- NULL; identify <- NULL + + if (route == "names") { + taxa <- unique(key$leads$Taxon[!is.na(key$leads$Taxon) & nzchar(key$leads$Taxon)]) + top <- max(1L, min(as.integer(top), length(taxa))) + ranked <- suggestSpecies(key, model, tp[, c("id", "path")], top = length(taxa), prompt = prompt) + first <- ranked[ranked$rank == 1, ] + at <- match(paste(tp$id, tp$label, sep = "\r"), paste(ranked$image, ranked$Taxon, sep = "\r")) + res <- data.frame(id = tp$id, observation = tp$observation, actual = tp$label, + predicted = first$Taxon[match(tp$id, first$image)], rank = ranked$rank[at], stringsAsFactors = FALSE) + if (!is.null(lineage)) { + ans <- identifyPhotos(key, model, tp[, c("id", "path")], confidence = confidence, lineage = lineage, prompt = prompt) + ans <- ans[match(tp$id, ans$image), ] + ans$actual <- tp$label + truth <- vapply(seq_len(nrow(ans)), function(i) { + if (ans$rank[i] == "species") return(ans$actual[i]) + as.character(lineage[[ans$rank[i]]][match(ans$actual[i], lineage$Taxon)]) + }, "") + ans$correct <- !is.na(truth) & ifelse(ans$rank == "species", !is.na(ans$Taxon) & ans$Taxon == truth, ans$name == truth) + rownames(ans) <- NULL + identify <- list(results = ans, confident = mean(ans$confident), correct = mean(ans$correct), + correctWhenConfident = if (any(ans$confident)) mean(ans$correct[ans$confident]) else NA_real_, + byRank = table(rank = ans$rank, correct = ans$correct)) + } + } else { + if (route == "build") { + if (!any(!isTest)) stop("There are no training photos to build a key from", call. = FALSE) + emb <- if (is.null(embeddings)) embedImages(model, photos[, c("id", "path")], tiles = tiles) else embeddings + pt <- emb$patches + if (is.null(pt) || dim(pt)[1] != nrow(photos)) stop("`embeddings` must hold the patches of every photo, in order", call. = FALSE) + dimnames(pt)[[1]] <- photos$id + train <- pt[!isTest, , , drop = FALSE] + attr(train, "tiles") <- attr(pt, "tiles"); attr(train, "empty") <- attr(pt, "empty") + filled <- sum(apply(train != 0, c(1, 2), any)) + sn <- discoverSniglets(train, k = max(2L, min(as.integer(k), filled - 1L)), seed = seed) + scores <- snigletScores(pt, sn$centroids) + built <- keyFromSniglets(scores[!isTest, , drop = FALSE], photos[!isTest, c("id", "path", "label")], sn, method = method, + desc = "Key built from the training photos of a benchmark", + meta = if (is.null(model)) NULL else modelMeta(model)) + ev <- evaluateKey(built, scores[isTest, , drop = FALSE], tp$label) + } else { + ev <- evaluateKey(key, scoreImages(key, model, tp[, c("id", "path")]), tp$label) + } + res <- data.frame(id = tp$id, observation = tp$observation, actual = tp$label, predicted = ev$results$predicted, + rank = ifelse(ev$results$correct, 1L, NA_integer_), stringsAsFactors = FALSE) + top <- 1L + } + res$correct <- !is.na(res$predicted) & res$predicted == res$actual + rownames(res) <- NULL + # a species without test photos has no accuracy (NA), rather than 0 or NaN + within <- function(kk, rows = TRUE) if (any(rows)) mean(!is.na(res$rank[rows]) & res$rank[rows] <= kk) else NA_real_ + topK <- stats::setNames(vapply(seq_len(top), within, numeric(1)), paste0("top", seq_len(top))) + per <- data.frame(Taxon = species, n = as.integer(table(factor(res$actual, species))), + top1 = vapply(species, function(s) within(1, res$actual == s), numeric(1)), stringsAsFactors = FALSE) + if (top > 1) per[[paste0("top", top)]] <- vapply(species, function(s) within(top, res$actual == s), numeric(1)) + rownames(per) <- NULL + # the same species, in the same order, down and across; other answers after them + answer <- ifelse(is.na(res$predicted), "", res$predicted) + other <- sort(setdiff(answer, c(species, ""))) + confusion <- table(actual = factor(res$actual, species), + predicted = factor(answer, c(species, other, if ("" %in% answer) ""))) + structure(list(route = route, n = nrow(res), nTrain = sum(!isTest), observations = length(unique(tp$observation)), + accuracy = mean(res$correct), interval = benchWilson(sum(res$correct), nrow(res)), + topK = topK, perSpecies = per, confusion = confusion, + results = res, split = split, key = built, identify = identify, + model = if (is.null(model)) NA_character_ else c(model$spec$arch, NA_character_)[1]), + class = "dimooseBenchmark") +} + +#' @export +print.dimooseBenchmark <- function(x, ...) { + x$perSpecies <- x$perSpecies[!is.na(x$perSpecies$Taxon), , drop = FALSE] + how <- c(names = "species ranked from their names", key = "key followed by machine", + build = "key built from the training photos")[[x$route]] + cat(" ", how, "\n", sep = "") + cat(" ", x$n, " test photos of ", sum(x$perSpecies$n > 0), " species from ", x$observations, " observations", + if (x$nTrain > 0) paste0("; ", x$nTrain, " training photos"), "\n", sep = "") + cat(" ", paste(sprintf("%s %.1f%%", sub("top", "top-", names(x$topK)), 100 * x$topK), collapse = ", "), + if (!is.null(x$interval)) sprintf(" (top-1: %d of %d, 95%% interval %.1f to %.1f%%)", sum(x$results$correct), x$n, + 100 * x$interval[["lower"]], 100 * x$interval[["upper"]]), "\n", sep = "") + if (!is.null(x$repeats)) { + cat(sprintf(" %d splits (seeds %s to %s): top-1 mean %.1f%%, standard deviation %.1f, range %.1f to %.1f%%; the lines here are the first split\n", + nrow(x$repeats), x$repeats$seed[1], x$repeats$seed[nrow(x$repeats)], 100 * x$accuracyMean, 100 * x$accuracySd, + 100 * x$accuracyRange[1], 100 * x$accuracyRange[2])) + } + if (!is.null(x$identify)) { + cat(sprintf(" identifyPhotos: %.1f%% of answers confident; %.1f%% correct at the rank given\n", + 100 * x$identify$confident, 100 * x$identify$correct)) + } + tested <- x$perSpecies[x$perSpecies$n > 0, , drop = FALSE] + worst <- tested[order(tested$top1), ][seq_len(min(3, nrow(tested))), ] + cat(" hardest: ", paste(sprintf("%s (%.0f%% of %d)", worst$Taxon, 100 * worst$top1, worst$n), collapse = "; "), "\n", sep = "") + if (nrow(tested) < nrow(x$perSpecies)) { + cat(" no test photos of: ", paste(x$perSpecies$Taxon[x$perSpecies$n == 0], collapse = "; "), "\n", sep = "") + } + invisible(x) +} + +# ---- internals --------------------------------------------------------------- + +# The taxon a name means, among the results of iNaturalist's taxon search: +# one whose name is exactly the name asked for, or failing that one found +# through exactly that name as a synonym. The search itself matches loosely +# and across kingdoms, so its first result is not to be trusted. Several +# exact matches are homonyms: the rank that fits the name comes first, then +# the most observed, and the choice is reported. +benchPickTaxon <- function(name, found) { + same <- function(a) is.character(a) && length(a) == 1 && identical(tolower(trimws(a)), tolower(trimws(name))) + found <- Filter(function(x) is.list(x) && !is.null(x$id) && !identical(x$is_active, FALSE), found) + hit <- Filter(function(x) same(x$name), found) + synonym <- FALSE + if (!length(hit)) { + hit <- Filter(function(x) same(x$matched_term), found) + synonym <- length(hit) > 0 + } + if (!length(hit)) return(NULL) + words <- length(strsplit(trimws(name), "\\s+")[[1]]) + rank <- vapply(hit, function(x) c(x$rank, "")[1], "") + fits <- if (words == 2) rank == "species" else if (words >= 3) rank %in% c("subspecies", "variety", "form", "hybrid") else rank != "species" + seen <- vapply(hit, function(x) as.numeric(c(x$observations_count, 0)[1]), numeric(1)) + hit <- hit[order(!fits, -seen)] + describe <- function(x) paste0(c(x$rank, "taxon")[1], " ", x$name, if (!is.null(x$iconic_taxon_name)) paste0(" in ", x$iconic_taxon_name), + " (id ", format(x$id, scientific = FALSE), ")") + if (length(hit) > 1) { + warning(name, " is the name of ", length(hit), " iNaturalist taxa: ", paste(vapply(hit, describe, ""), collapse = "; "), + ". The first is used; give the taxon id instead of the name to choose another.", call. = FALSE) + } else if (synonym) { + message(name, " is known to iNaturalist as ", describe(hit[[1]])) + } + hit[[1]] +} + +# The 95% Wilson score interval of `correct` right answers out of `n`. +benchWilson <- function(correct, n, level = 0.95) { + if (!n) return(c(lower = NA_real_, upper = NA_real_)) + z <- stats::qnorm(1 - (1 - level) / 2) + p <- correct / n + mid <- (p + z^2 / (2 * n)) / (1 + z^2 / n) + half <- z * sqrt(p * (1 - p) / n + z^2 / (4 * n^2)) / (1 + z^2 / n) + c(lower = max(0, mid - half), upper = min(1, mid + half)) +} + +# benchmarkKey() over several splits: the first split's result, with the +# accuracy of every split and its spread added. +benchRepeat <- function(x, photos, model, route, test, split, seed, dir, tiles, embeddings, reps, ...) { + if (!is.null(split)) stop("`reps` draws a new split each time, so `split` cannot be given with it", call. = FALSE) + building <- inherits(x, "dimooseVisionModel") || identical(route, "build") + if (is.null(test)) test <- if (building) 0.3 else 1 + if (!is.numeric(test) || length(test) != 1 || is.na(test) || test <= 0 || test >= 1) { + stop("With `reps`, give a `test` share between 0 and 1: when every photo is a test photo each repeat is the same", call. = FALSE) + } + photos <- benchPhotos(photos, dir) + if (building && is.null(embeddings)) { # embed once, not once per split + vision <- if (inherits(x, "dimooseVisionModel")) x else model + if (is.null(vision)) stop("Give `model`, a visionModel()", call. = FALSE) + embeddings <- embedImages(vision, photos[, c("id", "path")], tiles = tiles) + } + seeds <- seed + seq_len(reps) - 1 + runs <- lapply(seeds, function(s) benchmarkKey(x, photos, model = model, route = route, test = test, seed = s, tiles = tiles, + embeddings = embeddings, reps = 1, ...)) + out <- runs[[1]] + acc <- vapply(runs, function(r) r$accuracy, numeric(1)) + out$repeats <- data.frame(rep = seq_len(reps), seed = seeds, n = vapply(runs, function(r) r$n, numeric(1)), + nTrain = vapply(runs, function(r) r$nTrain, numeric(1)), + correct = vapply(runs, function(r) sum(r$results$correct), numeric(1)), accuracy = acc) + out$accuracyMean <- mean(acc); out$accuracySd <- stats::sd(acc); out$accuracyRange <- range(acc) + all <- do.call(rbind, lapply(runs, function(r) r$results[, c("actual", "correct")])) + out$perSpecies$top1Mean <- vapply(out$perSpecies$Taxon, function(sp) if (any(all$actual == sp)) mean(all$correct[all$actual == sp]) else NA_real_, + numeric(1)) + out +} + +# How dimoose introduces itself to iNaturalist: what the client is, and +# nothing about who runs it. +benchUserAgent <- function() httr::user_agent("R httr client sampling photos for an identification benchmark") + +# One GET of the iNaturalist API, parsed. A rate limit (HTTP 429) is waited +# out once. +benchInatGet <- function(url, query) { + for (attempt in 1:2) { + r <- httr::GET(url, query = query, benchUserAgent(), httr::timeout(60)) + if (httr::status_code(r) != 429 || attempt == 2) break + Sys.sleep(60) + } + httr::stop_for_status(r, task = "search iNaturalist") + httr::content(r, as = "parsed", type = "application/json", encoding = "UTF-8") +} + +# Save one photo. +benchDownload <- function(url, destfile) { + r <- httr::GET(url, httr::write_disk(destfile, overwrite = TRUE), benchUserAgent(), httr::timeout(120)) + httr::stop_for_status(r, task = "download a photo") + invisible(destfile) +} + +# Photos in the shape the benchmark works with: id, path, label, observation. +benchPhotos <- function(photos, dir = NULL) { + if (is.character(photos) && length(photos) == 1) { + if (!file.exists(photos)) stop("Manifest not found: ", photos, call. = FALSE) + if (is.null(dir)) dir <- dirname(photos) + photos <- utils::read.csv(photos, stringsAsFactors = FALSE) + } + if (!is.data.frame(photos) || !nrow(photos)) stop("`photos` must be a data frame of photos or a manifest file", call. = FALSE) + # `[[`, not `$`: a manifest has columns such as id_below and observation_url, + # which `$id` and `$observation` would quietly match + label <- if (!is.null(photos[["label"]])) photos[["label"]] else photos[["taxon"]] + if (is.null(label)) stop("`photos` needs a `label` (or `taxon`) column", call. = FALSE) + path <- photos[["path"]] + if (is.null(path)) { + if (is.null(photos[["file"]]) || is.null(dir)) stop("`photos` needs a `path` column, or a `file` column and `dir`", call. = FALSE) + path <- file.path(dir, photos[["file"]]) + } + path <- as.character(path) + id <- if (!is.null(photos[["id"]])) as.character(photos[["id"]]) else sub("\\.[^.]+$", "", basename(path)) + if (anyDuplicated(id)) stop("Photos must have distinct ids (file names): ", paste(utils::head(unique(id[duplicated(id)]), 5), collapse = ", "), call. = FALSE) + observation <- if (!is.null(photos[["observation"]])) photos[["observation"]] else + if (!is.null(photos[["observation_id"]])) photos[["observation_id"]] else id + if (anyNA(label) || anyNA(path)) stop("Every photo needs a label and a path", call. = FALSE) + # a photo without an observation is its own; numbers are written out in full (no 1e+08) + obs <- if (is.numeric(observation)) format(observation, scientific = FALSE, trim = TRUE) else as.character(observation) + lone <- is.na(observation) | !nzchar(trimws(obs)) + obs[lone] <- paste0("photo ", id[lone]) + data.frame(id = id, path = path, label = as.character(label), observation = obs, stringsAsFactors = FALSE) +} + +# The key's result each photo label means: the result itself, or the result +# whose scientific name the label is. Ranking species by name (`strict`) +# needs every label to be one of them; a key that is followed may simply +# lack a species, and then never gets its photos right. +benchLabels <- function(labels, key, strict = TRUE) { + taxa <- unique(key$leads$Taxon[!is.na(key$leads$Taxon) & nzchar(key$leads$Taxon)]) + sci <- scientificPart(taxa); sci[is.na(sci)] <- taxa[is.na(sci)] + sci[grepl(" / ", taxa, fixed = TRUE)] <- NA # a leaf that could not separate several classes is none of them + own <- scientificPart(labels); own[is.na(own)] <- labels[is.na(own)] + at <- match(labels, taxa) + at[is.na(at)] <- match(tolower(own[is.na(at)]), tolower(sci)) + if (anyNA(at)) { + msg <- paste0("Photos are labelled with something the key does not end in: ", + paste(utils::head(unique(labels[is.na(at)]), 5), collapse = ", ")) + if (strict) stop(msg, call. = FALSE) + warning(msg, "; the key cannot get these right", call. = FALSE) + } + ifelse(is.na(at), labels, taxa[at]) +} diff --git a/R/delta.R b/R/delta.R new file mode 100644 index 0000000..e55faf0 --- /dev/null +++ b/R/delta.R @@ -0,0 +1,670 @@ +# DELTA (DEscription Language for TAxonomy): the classic specs / chars / items +# files. Shared helpers (tdwgInput(), tdwgData() ...) are in R/sdd.R. + +# ---- reading ------------------------------------------------------------------- + +tdwgReadText <- function(file) { + if (!file.exists(file)) stop("File ", file, " not found", call. = FALSE) + text <- rawToChar(readBin(file, "raw", file.size(file))) + # DELTA files mostly come from Windows programs + if (!validUTF8(text)) { + # a few bytes mean nothing in Windows-1252; Latin-1 gives every byte a meaning + converted <- iconv(text, "CP1252", "UTF-8") + text <- if (is.na(converted)) iconv(text, "latin1", "UTF-8") else converted + } + Encoding(text) <- "UTF-8" + gsub("\r\n?", "\n", sub("^\ufeff", "", text)) +} + +# Typesetting marks that DELTA programs put in text. They are RTF control +# words, usually closed by an empty pair of braces (\i{}Poa\i0{}), in older +# files also bare (\i0. or \par). Marks that stand for a character become +# that character, breaks become a blank, the others (italics, bold, +# superscript, paragraph settings) are dropped. +tdwgDeltaMarks <- c(endash = "\u2013", emdash = "\u2014", lquote = "\u2018", rquote = "\u2019", + ldblquote = "\u201c", rdblquote = "\u201d", bullet = "\u2022", tab = " ", par = " ", + line = " ", page = " ", sect = " ") + +tdwgDeltaPlain <- function(x) { + if (!any(grepl("\\", x, fixed = TRUE))) return(tdwgSquish(x)) + for (mark in names(tdwgDeltaMarks)) { + x <- gsub(paste0("\\\\", mark, "(\\{\\}|(?![A-Za-z]))"), tdwgDeltaMarks[[mark]], x, perl = TRUE) + } + # the formatting words real files use, so that a mark run into the next + # word (\iPoa) only loses the mark + x <- gsub(paste0("\\\\(nosupersub|super|sub|plain|ulnone|ul|scaps|caps|strike|pard|li|fi|ri|sb|sa|", + "qc|ql|qr|qj|fs|cf|lang|[ibuf](?![a-z]))-?[0-9]*(\\{\\})?"), "", x, perl = TRUE) + x <- gsub("\\\\[A-Za-z]+-?[0-9]*(\\{\\})?", "", x, perl = TRUE) + x <- gsub("{}", "", x, fixed = TRUE) + # \{ and \} are braces meant as such + x <- gsub("\\\\([{}\\\\])", "\\1", x, perl = TRUE) + tdwgSquish(x) +} + +# Split DELTA text into directives: a star at the start of a line or after a +# blank, then a control phrase of up to four upper-case words, then the data. +# Only the first three letters of each word count. +tdwgDeltaKnown <- c("CHARACTER LIST", "ITEM DESCRIPTIONS", "CHARACTER TYPES", "NUMBERS OF STATES", + "NUMBER OF CHARACTERS", "MAXIMUM NUMBER OF STATES", "MAXIMUM NUMBER OF ITEMS", + "IMPLICIT VALUES", "DEPENDENT CHARACTERS", "INAPPLICABLE CHARACTERS", "HEADING", "SHOW") + +tdwgDeltaDirectives <- function(text) { + starts <- gregexpr("(?\002])<[^<>]*>(?![^\\s<>/\001.,;:)])" + store <- character() + repeat { + m <- gregexpr(pattern, text, perl = TRUE) + if (m[[1]][1] == -1) break + found <- regmatches(text, m)[[1]] + regmatches(text, m) <- list(paste0("\001", length(store) + seq_along(found), "\002")) + store <- c(store, found) + } + list(text = text, store = store) +} + +# The same for text in which every bracket counts. Item descriptions run to +# megabytes, so this pairs the brackets in one pass over the bytes ("<" and +# ">" are single bytes in UTF-8) instead of rewriting the text once per level +# of nesting. Each outermost comment becomes one placeholder; the comments +# nested in it stay in its stored text. +tdwgDeltaMaskAll <- function(text) { + bytes <- charToRaw(enc2utf8(text)) + at <- which(bytes == as.raw(0x3c) | bytes == as.raw(0x3e)) + if (!length(at)) return(list(text = text, store = character())) + opens <- bytes[at] == as.raw(0x3c) + from <- to <- integer(length(at)) + n <- 0L + stack <- integer(length(at)) + depth <- 0L + for (k in seq_along(at)) { + if (opens[k]) { + depth <- depth + 1L + stack[depth] <- at[k] + } else if (depth > 0L) { + # a closed pair inside a bracket that never closes is still a comment, + # so every pair is noted and the nested ones are dropped afterwards + n <- n + 1L + from[n] <- stack[depth] + to[n] <- at[k] + depth <- depth - 1L + } + } + if (n == 0L) return(list(text = text, store = character())) + from <- from[seq_len(n)] + to <- to[seq_len(n)] + o <- order(from) + from <- from[o] + to <- to[o] + outer <- to > cummax(c(0L, to[-n])) + from <- from[outer] + to <- to[outer] + piece <- function(a, b) { + out <- if (b < a) "" else rawToChar(bytes[a:b]) + Encoding(out) <- "UTF-8" + out + } + store <- unlist(Map(piece, from, to), use.names = FALSE) + between <- unlist(Map(piece, c(1L, to + 1L), c(from - 1L, length(bytes))), use.names = FALSE) + marks <- c(paste0("\001", seq_along(store), "\002"), "") + list(text = paste0(between, marks, collapse = ""), store = store) +} + +# Put the comments back (`keep`) or drop them +tdwgDeltaUnmask <- function(x, store, keep = FALSE) { + if (!keep) return(gsub("\001[0-9]+\002", "", x)) + repeat { + m <- gregexpr("\001[0-9]+\002", x) + if (all(vapply(m, function(v) v[1] == -1, logical(1)))) break + regmatches(x, m) <- lapply(regmatches(x, m), function(p) store[as.integer(gsub("[\001\002]", "", p))]) + } + x +} + +# The text of the comments in each element of `x`, without their outer +# brackets; several comments are joined with "; ". Comments nested in a +# comment keep their brackets, or are dropped with `nested = FALSE` (they +# are the DELTA way of writing a note that is never to be printed). +tdwgDeltaComment <- function(x, store, nested = TRUE) { + marks <- regmatches(x, gregexpr("\001[0-9]+\002", x)) + vapply(marks, function(found) { + if (!length(found)) return("") + text <- tdwgDeltaUnmask(found, store, keep = TRUE) + text <- substr(text, 2, nchar(text) - 1) + if (!nested) { + repeat { + shorter <- gsub("<[^<>]*>", "", text) + if (identical(shorter, text)) break + text <- shorter + } + } + text <- tdwgSquish(text) + paste(text[nzchar(text)], collapse = "; ") + }, character(1)) +} + +# A name with its comments dropped (or kept); if nothing but a comment is +# there ("#7. /"), the comment is the name +tdwgDeltaName <- function(x, store, comments = FALSE) { + plain <- tdwgDeltaPlain(tdwgDeltaUnmask(x, store, keep = comments)) + empty <- !nzchar(plain) + plain[empty] <- tdwgDeltaPlain(tdwgDeltaComment(x[empty], store, nested = comments)) + plain +} + +# "2-3,OM 4,IN" -> data frame of character number and value +tdwgDeltaPairs <- function(data) { + tokens <- strsplit(trimws(data), "[[:space:]]+")[[1]] + m <- regmatches(tokens, regexec("^([0-9]+)(?:-([0-9]+))?,(.+)$", tokens, perl = TRUE)) + m <- m[lengths(m) > 0] + if (!length(m)) return(data.frame(character = integer(), value = character(), stringsAsFactors = FALSE)) + do.call(rbind, lapply(m, function(p) { + from <- as.integer(p[2]) + to <- if (nzchar(p[3])) as.integer(p[3]) else from + data.frame(character = seq(from, to), value = p[4], stringsAsFactors = FALSE) + })) +} + +tdwgDeltaCharacters <- function(data, comments = FALSE) { + masked <- tdwgDeltaMask(data, strict = TRUE) + blocks <- strsplit(masked$text, "(? 0) substr(block, 1, slash - 1) else block + body <- if (slash > 0) substring(block, slash + 1) else "" + tokens <- strsplit(trimws(body), "[[:space:]]+")[[1]] + tokens <- tokens[nzchar(tokens)] + m <- regmatches(tokens, regexec("^([0-9]+)((?:\001[0-9]+\002)*)(?:,(.*))?$", tokens, perl = TRUE)) + ok <- lengths(m) > 0 + list(name = tdwgDeltaName(name, masked$store, comments), + comment = tdwgDeltaPlain(tdwgDeltaComment(name, masked$store)), + variant = variant, + character = as.integer(vapply(m[ok], `[`, character(1), 2)), + comments = tdwgDeltaPlain(tdwgDeltaComment(vapply(m[ok], `[`, character(1), 3), masked$store)), + values = tdwgDeltaUnmask(vapply(m[ok], `[`, character(1), 4), masked$store), + stray = sum(!ok)) + }) +} + +#' Read and write DELTA datasets +#' +#' DELTA (DEscription Language for TAxonomy, Dallwitz 1980) is the oldest +#' and still widely used text format for descriptive data, and a TDWG +#' standard. A dataset is classically three files: `specs` (how many +#' characters there are and of which type), `chars` (the character list with +#' the states) and `items` (the taxa, each with its attributes). +#' `readDELTA()` reads them into a character matrix (see [readSDD()] for the +#' convention), `writeDELTA()` writes a matrix as the three files. +#' +#' @section What is read: +#' The directives `*CHARACTER LIST`, `*ITEM DESCRIPTIONS`, +#' `*CHARACTER TYPES`, `*NUMBERS OF STATES`, `*NUMBER OF CHARACTERS`, +#' `*IMPLICIT VALUES` and `*DEPENDENT CHARACTERS`, wherever in the given +#' files they are (so a dataset kept in one file, or split differently, reads +#' too); other directives are skipped. Character types are unordered +#' multistate (`UM`, read as `"categorical"`), ordered multistate (`OM`, +#' `"ordered"`), integer (`IN`, `"integer"`), real (`RN`, `"real"`) and text +#' (`TE`, `"text"`). +#' +#' Attributes follow the DELTA standard: `12,1/2` (state 1 or 2) and `12,1&2` +#' (1 and 2) both give `"state 1/state 2"`, so the difference between "or" +#' and "and" is not kept; `13,2-3` is a range, which for +#' an ordered character includes the states in between; `14,U` is unknown +#' (`NA`), `15,-` not applicable (`inapplicable`), `16,V` variable (all +#' states). Numeric values are kept as written, e.g. `"7-8.5"` or +#' `"(1-)2-3(-4)"`, which is the numeric notation of the matrix convention. +#' For a text character the cell is the text of the comment (`7`). Implicit values are filled in. A dependent character that is +#' not coded is "not applicable" when its controlling character only takes +#' the controlling states; the rule itself is kept in the `InapplicableIf` +#' column of `characters`. Variant items (`#+`) take the attributes they +#' leave out from their main item, as the standard says. +#' +#' Comments (text in angle brackets) are dropped from the names of +#' characters, states and taxa unless `comments = TRUE`, and from the +#' attributes of non-text characters; the comment of a taxon name (usually +#' the authority) is kept in `taxa$Comment`. A name that consists of nothing +#' but a comment (`#4. /`) is that comment. Typesetting +#' marks (the RTF control words DELTA programs use, such as `\i{}`, `\b0{}` +#' or `\par{}`) are removed, and those that stand for a character +#' (`\endash{}`, `\ldblquote{}`) become that character. Files that are not +#' valid UTF-8 are read as Windows-1252. The obsolete line sequence numbers +#' are not supported. +#' +#' The reader was checked against the datasets distributed with Open DELTA +#' (among them the "Grass Genera" sample, a flora of 506 taxa and a virus +#' database of 969 taxa) by comparing every coded attribute with a second, +#' independent parse of the files. +#' +#' @param specs Path of the `specs` file, or of a folder holding files +#' named `specs`, `chars` and `items` (any extension, any case). +#' @param chars,items Paths of the `chars` and `items` files. May be left +#' out when `specs` is a folder, or a single file holding everything. +#' @param comments If `TRUE`, keep the comments in the names of characters, +#' states and taxa (`"pronotum "`). +#' @inheritParams readSDD +#' @return `readDELTA()` returns a `tdwgData` list like [readSDD()], with +#' `matrix`, `characters` (`Character`, `Type`, `States`, `Unit`, +#' `InapplicableIf`, `Number`), `taxa` (`Taxon`, `Comment`) and `meta`. +#' `writeDELTA()` returns the paths of the three files, invisibly. +#' @references Dallwitz, M. J. & Paine, T. A. (1992 onwards). Definition of +#' the DELTA format. +#' @seealso [readSDD()], [readLucid()]. +#' @examples +#' dir <- system.file("extdata", "tdwg", "beetles-delta", package = "dimoose") +#' d <- readDELTA(dir) +#' d +#' d$matrix +#' d$characters[, c("Character", "Type", "States", "Unit")] +#' +#' out <- writeDELTA(d, tempfile("delta")) +#' out +#' identical(readDELTA(dirname(out[1]))$matrix, d$matrix) +#' @export +readDELTA <- function(specs, chars = NULL, items = NULL, taxon = "Taxon", sep = "/", inapplicable = NA, + comments = FALSE) { + if (length(specs) == 1 && dir.exists(specs)) { + files <- list.files(specs, full.names = TRUE) + stem <- tolower(sub("\\.[^.]*$", "", basename(files))) + found <- files[match(c("specs", "chars", "items"), stem)] + if (anyNA(found[2:3])) { + stop("Folder ", specs, " needs files named chars and items (and usually specs)", call. = FALSE) + } + files <- found[!is.na(found)] + } else { + files <- c(specs, chars, items) + } + inapplicable <- as.character(inapplicable) + directives <- unlist(lapply(files, function(f) tdwgDeltaDirectives(tdwgReadText(f))), recursive = FALSE) + named <- vapply(directives, function(d) d$name, character(1)) + get <- function(name) { + paste(vapply(directives[named %in% name], function(d) d$data, character(1)), collapse = "\n") + } + if (!"ITEM DESCRIPTIONS" %in% named) { + stop("No *ITEM DESCRIPTIONS directive found: these do not look like DELTA files", call. = FALSE) + } + charList <- tdwgDeltaCharacters(get("CHARACTER LIST"), comments) + itemList <- tdwgDeltaItems(get("ITEM DESCRIPTIONS"), comments) + if (!length(itemList)) stop("The item descriptions hold no items", call. = FALSE) + if (any(vapply(itemList, function(it) it$stray, numeric(1)) > 0)) { + warning(sprintf("%d attribute(s) could not be read and were skipped", + sum(vapply(itemList, function(it) it$stray, numeric(1)))), call. = FALSE) + } + + declared <- suppressWarnings(as.integer(trimws(get("NUMBER OF CHARACTERS")))) + nChar <- max(c(declared, vapply(charList, function(ch) ch$number, integer(1)), + unlist(lapply(itemList, function(it) it$character))), na.rm = TRUE) + number <- seq_len(nChar) + types <- tdwgDeltaPairs(get("CHARACTER TYPES")) + types <- types[types$character <= nChar, ] + code <- rep("UM", nChar) + code[types$character] <- sub("^E", "", toupper(types$value)) + typeNames <- c(UM = "categorical", OM = "ordered", IN = "integer", RN = "real", TE = "text") + if (any(!code %in% names(typeNames))) { + warning("Unknown character type(s) read as unordered multistate: ", + paste(unique(code[!code %in% names(typeNames)]), collapse = ", "), call. = FALSE) + code[!code %in% names(typeNames)] <- "UM" + } + type <- unname(typeNames[code]) + multistate <- code %in% c("UM", "OM") + + # names, states and units: from the character list, or made up without one + name <- paste("Character", number) + unit <- rep("", nChar) + counts <- tdwgDeltaPairs(get("NUMBERS OF STATES")) + counts <- counts[counts$character <= nChar, ] + nStates <- rep(2L, nChar) + nStates[counts$character] <- suppressWarnings(as.integer(counts$value)) + states <- lapply(number, function(j) if (multistate[j]) as.character(seq_len(nStates[j])) else character()) + replaced <- 0 + for (ch in charList) { + j <- ch$number + if (nzchar(ch$name)) name[j] <- ch$name + if (multistate[j]) { + labels <- tdwgCleanStates(ch$states, sep) + if (!is.null(attr(labels, "replaced"))) replaced <- replaced + attr(labels, "replaced") + states[[j]] <- tdwgUnique(as.vector(labels)) + } else { + unit[j] <- ch$unit + } + } + tdwgWarnReplaced(replaced, sep) + name <- tdwgUnique(name) + + # the cells: state positions for multistate characters, text for the others + nItem <- length(itemList) + picked <- matrix(list(integer()), nItem, nChar) + text <- matrix(NA_character_, nItem, nChar) + notApplicable <- coded <- valued <- matrix(FALSE, nItem, nChar) + badStates <- 0 + for (i in seq_len(nItem)) { + it <- itemList[[i]] + for (a in seq_along(it$character)) { + j <- it$character[a] + coded[i, j] <- TRUE + value <- it$values[a] + if (code[j] == "TE") { + if (nzchar(it$comments[a])) text[i, j] <- it$comments[a] + valued[i, j] <- nzchar(it$comments[a]) + next + } + if (is.na(value) || !nzchar(value)) next + valued[i, j] <- TRUE + alternatives <- strsplit(value, "/", fixed = TRUE)[[1]] + if (any(alternatives == "-")) notApplicable[i, j] <- TRUE + alternatives <- alternatives[!alternatives %in% c("-", "U", "")] + if (multistate[j]) { + found <- integer() + for (alt in alternatives) { + if (alt == "V") { + found <- c(found, seq_along(states[[j]])) + next + } + # "&" (and) binds more loosely than "-" (to): 1-2&4 + for (part in strsplit(alt, "&", fixed = TRUE)[[1]]) { + ends <- suppressWarnings(as.integer(strsplit(part, "-", fixed = TRUE)[[1]])) + if (!length(ends)) ends <- NA_integer_ + found <- c(found, if (code[j] == "OM" && length(ends) > 1 && !anyNA(ends)) seq(min(ends), max(ends)) else ends) + } + } + bad <- is.na(found) | found < 1 | found > length(states[[j]]) + badStates <- badStates + sum(bad) + picked[[i, j]] <- sort(unique(found[!bad])) + } else { + alternatives <- alternatives[alternatives != "V"] + if (length(alternatives)) text[i, j] <- paste(gsub("&", sep, alternatives, fixed = TRUE), collapse = sep) + } + } + } + if (badStates > 0) { + warning(sprintf("%d state number(s) in the items are not states of their character and were skipped", + badStates), call. = FALSE) + } + + # variant items take what they leave out from their main item + main <- NA + for (i in seq_len(nItem)) { + if (!itemList[[i]]$variant) { + main <- i + } else if (!is.na(main)) { + copy <- !coded[i, ] + picked[i, copy] <- picked[main, copy] + text[i, copy] <- text[main, copy] + notApplicable[i, copy] <- notApplicable[main, copy] + coded[i, copy] <- coded[main, copy] + valued[i, copy] <- valued[main, copy] + } + } + + # implicit values: "c,s:t" gives s to a character left out and t to one + # written without a value + implicit <- tdwgDeltaPairs(get("IMPLICIT VALUES")) + implicit <- implicit[implicit$character <= nChar, ] + filled <- matrix(FALSE, nItem, nChar) + for (r in seq_len(nrow(implicit))) { + j <- implicit$character[r] + if (!multistate[j]) next + value <- suppressWarnings(as.integer(strsplit(implicit$value[r], ":", fixed = TRUE)[[1]])) + for (i in seq_len(nItem)) { + use <- if (!coded[i, j]) value[1] else if (!valued[i, j] && length(value) > 1) value[2] else NA + if (!is.na(use) && use >= 1 && use <= length(states[[j]])) { + picked[[i, j]] <- use + filled[i, j] <- TRUE + } + } + } + + # dependent characters: "c,s1/s2:d1:d2-d3" + rules <- rep("", nChar) + tokens <- strsplit(trimws(get(c("DEPENDENT CHARACTERS", "INAPPLICABLE CHARACTERS"))), "[[:space:]]+")[[1]] + for (m in regmatches(tokens, regexec("^([0-9]+),([0-9/]+):(.+)$", tokens, perl = TRUE))) { + if (!length(m)) next + controlling <- as.integer(m[2]) + if (controlling > nChar || !multistate[controlling]) next + controllingStates <- as.integer(strsplit(m[3], "/", fixed = TRUE)[[1]]) + controllingStates <- controllingStates[controllingStates >= 1 & controllingStates <= length(states[[controlling]])] + dependents <- unlist(lapply(strsplit(m[4], ":", fixed = TRUE)[[1]], function(d) { + ends <- suppressWarnings(as.integer(strsplit(d, "-", fixed = TRUE)[[1]])) + if (anyNA(ends) || !length(ends)) integer() else seq(ends[1], ends[length(ends)]) + })) + dependents <- dependents[dependents >= 1 & dependents <= nChar] + if (!length(controllingStates) || !length(dependents)) next + rule <- tdwgRuleText(name[controlling], states[[controlling]][controllingStates], sep) + rules[dependents] <- ifelse(nzchar(rules[dependents]), paste(rules[dependents], rule, sep = "; "), rule) + for (i in seq_len(nItem)) { + has <- picked[[i, controlling]] + if (!length(has) || !all(has %in% controllingStates)) next + for (d in dependents) { + if ((length(picked[[i, d]]) || !is.na(text[i, d])) && !filled[i, d]) next + picked[[i, d]] <- integer() + text[i, d] <- NA + notApplicable[i, d] <- TRUE + } + } + } + + cells <- lapply(number, function(j) { + v <- text[, j] + if (multistate[j]) { + v <- vapply(picked[, j], function(p) if (length(p)) paste(states[[j]][p], collapse = sep) else NA_character_, + character(1)) + } + v[is.na(v) & notApplicable[, j]] <- inapplicable + v + }) + itemNames <- vapply(itemList, function(it) it$name, character(1)) + itemNames[!nzchar(itemNames)] <- paste("Item", which(!nzchar(itemNames))) + itemNames <- tdwgUnique(itemNames) + characters <- data.frame( + Character = name, Type = type, + States = vapply(states, function(s) paste(s, collapse = sep), character(1)), + Unit = unit, InapplicableIf = rules, Number = number, stringsAsFactors = FALSE + ) + taxa <- data.frame(Taxon = itemNames, Comment = vapply(itemList, function(it) it$comment, character(1)), + stringsAsFactors = FALSE) + names(taxa)[1] <- taxon + heading <- named %in% c("HEADING", "SHOW") + title <- if (any(heading)) tdwgSquish(sub("^[~:[:space:]]+", "", directives[[which(heading)[1]]]$data)) else NA + # "Grass Genera - specifications.", "Virus specifications. Edited 26th Jan 1996." + title <- sub("[-\u2013:,[:space:]]*\\b(specifications|specs|character list|chars|item descriptions|items)\\b.*$", "", + tdwgDeltaPlain(title), ignore.case = TRUE) + tdwgData(tdwgMatrix(itemNames, cells, name, taxon), characters, taxa, + tdwgMeta(format = "DELTA", title = title)) +} + +# ---- writing ------------------------------------------------------------------- + +# Text as it can stand in a DELTA file. A star after a blank starts a +# directive wherever it is, even inside a comment, so it is put in +# parentheses. In a name (`name = TRUE`) a slash before a blank would end +# the name and a numero after a blank would start the next one: the blank +# after the slash is dropped, a slash at the very end too, and the numero is +# put in parentheses. +tdwgDeltaSafe <- function(x, name = TRUE) { + x <- tdwgSquish(x) + x <- gsub("(^| )\\*", "\\1(*)", x) + if (name) { + x <- gsub("/+$", "", gsub("/ ", "/", x, fixed = TRUE)) + x <- gsub("(^| )#", "\\1(#)", x) + } + trimws(x) +} + +tdwgDeltaWrap <- function(x, indent = 0) { + unlist(lapply(x, function(line) { + if (nchar(line) + indent <= 78) return(paste0(strrep(" ", indent), line)) + strwrap(line, width = 78, indent = indent, exdent = indent) + })) +} + +#' @rdname readDELTA +#' @param x A character matrix (data frame), or the list returned by +#' `readDELTA()`, [readSDD()], [readLucid()] or [readXper()]. +#' @param dir Folder to write the three files into; created if needed. +#' @param characters Optional data frame describing the characters +#' (`Character`, `Type`, `States`, `Unit`, `InapplicableIf`); see +#' [writeSDD()]. +#' @param title Title put in the `*SHOW` line of each file. +#' @param files Names of the three files. +#' @section What is written: +#' `specs` gets the numbers of characters, states and items, the character +#' types, the numbers of states and the dependent characters; `chars` the +#' character list; `items` one item per taxon. Every coded cell is written +#' out (no implicit values are used), `NA` cells are left out, which DELTA +#' reads as unknown, and cells equal to `inapplicable` are written as `-`. +#' The states of a variable taxon are joined with `/` ("or"). A numeric cell +#' that is not a DELTA number or range, and all cells of text characters, +#' are written as comments. Encoding is UTF-8, and lines are wrapped at 78 +#' columns wherever they have a blank to break at. +#' +#' A few things cannot be written as they are, because DELTA would read +#' them as syntax: angle brackets in a name make a comment (which +#' `readDELTA()` drops unless `comments = TRUE`); a star or, in a name, a +#' numero after a blank is put in parentheses (`(*)`, `(#)`); the blank +#' after a slash in a name is dropped. No file written by dimoose has been +#' read into a DELTA program (Confor, Intkey, Open DELTA). +#' @export +writeDELTA <- function(x, dir, characters = NULL, taxon = "Taxon", sep = "/", inapplicable = NULL, + title = NULL, files = c(specs = "specs", chars = "chars", items = "items")) { + input <- tdwgInput(x, characters, taxon, sep, inapplicable) + if (is.null(names(files))) names(files) <- c("specs", "chars", "items")[seq_along(files)] + if (!all(c("specs", "chars", "items") %in% names(files))) { + stop("`files` must name the specs, chars and items files", call. = FALSE) + } + if (is.null(title)) title <- tdwgMetaGet(input$meta, "title") + if (is.null(title)) title <- "Character matrix" + nChar <- length(input$characters) + number <- seq_len(nChar) + code <- unname(c(categorical = "UM", ordered = "OM", integer = "IN", real = "RN", text = "TE")[input$type]) + stateless <- code %in% c("UM", "OM") & lengths(input$states) == 0 + if (any(stateless)) { + warning("Character(s) without any state written as text characters: ", + paste(input$characters[stateless], collapse = ", "), call. = FALSE) + code[stateless] <- "TE" + } + multistate <- code %in% c("UM", "OM") + nStates <- lengths(input$states) + + # dependent characters, grouped by controlling character and states + dependencies <- list() + for (j in number) { + for (rule in tdwgParseRules(input$inapplicableIf[j], input, sep)) { + id <- paste0(rule$character, ",", paste(sort(rule$states), collapse = "/")) + dependencies[[id]] <- c(dependencies[[id]], j) + } + } + dependent <- if (length(dependencies)) { + controlling <- as.integer(sub(",.*$", "", names(dependencies))) + dependencies <- dependencies[order(controlling, names(dependencies))] + paste0(names(dependencies), ":", vapply(dependencies, paste, character(1), collapse = ":")) + } + directive <- function(name, values) { + if (!length(values)) return(NULL) + c("", tdwgDeltaWrap(paste0("*", name, " ", paste(values, collapse = " ")))) + } + show <- function(what) tdwgDeltaWrap(paste0("*SHOW ~ ", tdwgDeltaSafe(title), " - ", what, ".")) + specs <- c(show("specifications"), "", + paste("*NUMBER OF CHARACTERS", nChar), + paste("*MAXIMUM NUMBER OF STATES", max(c(nStates[multistate], 1))), + paste("*MAXIMUM NUMBER OF ITEMS", length(input$taxa)), + directive("CHARACTER TYPES", paste0(number, ",", code)[code != "UM"]), + directive("NUMBERS OF STATES", paste0(number, ",", nStates)[multistate & nStates != 2]), + directive("DEPENDENT CHARACTERS", dependent)) + + chars <- c(show("character list"), "", "*CHARACTER LIST") + for (j in number) { + unit <- if (code[j] %in% c("IN", "RN") && nzchar(input$unit[j])) paste0(" ", tdwgDeltaSafe(input$unit[j]), "/") else "" + chars <- c(chars, tdwgDeltaWrap(paste0("#", j, ". ", tdwgDeltaSafe(input$characters[j]), "/", unit)), + if (multistate[j]) { + tdwgDeltaWrap(paste0(seq_along(input$states[[j]]), ". ", tdwgDeltaSafe(input$states[[j]]), "/"), 7) + }) + } + + # text as a comment: angle brackets in it are kept when they pair up (they + # are then comments within the comment), otherwise written as parentheses + asComment <- function(text) { + text <- tdwgDeltaSafe(text, name = FALSE) + side <- utf8ToInt(gsub("[^<>]", "", text)) == utf8ToInt("<") + depth <- cumsum(ifelse(side, 1, -1)) + if (length(depth) && (any(depth < 0) || depth[length(depth)] != 0)) { + text <- gsub(">", ")", gsub("<", "(", text, fixed = TRUE), fixed = TRUE) + } + paste0("<", text, ">") + } + items <- c(show("items"), "", "*ITEM DESCRIPTIONS") + for (i in seq_along(input$taxa)) { + attributes <- character() + for (j in number) { + cell <- input$cells[[j]][i] + if (input$inapplicable[i, j]) { + attributes <- c(attributes, paste0(j, ",-")) + } else if (is.na(cell)) { + next + } else if (multistate[j]) { + attributes <- c(attributes, paste0(j, ",", paste(sort(unique(tdwgCellStates(cell, input$states[[j]], sep))), collapse = "/"))) + } else if (code[j] == "TE") { + attributes <- c(attributes, paste0(j, asComment(cell))) + } else { + values <- gsub(" ", "", trimws(strsplit(cell, sep, fixed = TRUE)[[1]]), fixed = TRUE) + numeric <- length(values) && !any(vapply(lapply(values, tdwgParseRange), is.null, logical(1))) + attributes <- c(attributes, if (numeric) paste0(j, ",", paste(values, collapse = "/")) else paste0(j, asComment(cell))) + } + } + items <- c(items, "", tdwgDeltaWrap(paste0("# ", tdwgDeltaSafe(input$taxa[i]), "/")), + if (length(attributes)) strwrap(paste(attributes, collapse = " "), width = 78)) + } + + if (!dir.exists(dir)) dir.create(dir, recursive = TRUE) + paths <- file.path(dir, files[c("specs", "chars", "items")]) + names(paths) <- c("specs", "chars", "items") + tdwgWriteLines(specs, paths[["specs"]]) + tdwgWriteLines(chars, paths[["chars"]]) + tdwgWriteLines(items, paths[["items"]]) + invisible(paths) +} diff --git a/R/dimoose-package.R b/R/dimoose-package.R index b77a3b8..099876b 100644 --- a/R/dimoose-package.R +++ b/R/dimoose-package.R @@ -1,8 +1,56 @@ -#' dimoose: manage, manipulate, and mine dichotomous keys +#' dimoose: read, build, check, prune and share dichotomous keys #' -#' Tools to import dichotomous identification keys (currently from FishBase), -#' represent them as tables of couplets and leads, and convert them to other -#' tree representations. +#' A dichotomous key identifies a specimen by a series of choices. dimoose +#' keeps a key as a [dimoose] object, a table of couplets and leads, and +#' provides the tools around it. `key$validate()` checks any key, however it +#' was made. +#' +#' @section Where to start: +#' * **Write a key** in a spreadsheet and read it with [keyFromSpreadsheet()]; +#' [keyToSpreadsheet()] writes any key back out for editing. +#' [montanaKey()], [sharkKey()], [arachnidaKey()], [vibrioKey()] and +#' [phylotreeKey()] are example keys. +#' * **Read a key somebody else wrote**: plain text as printed in a flora +#' ([keyFromText()], [parseTextKey()]), FishBase ([importFishbase()]), or +#' the keys and character matrices of other identification software +#' ([readSDD()], [readSDDKey()], [readDELTA()], [readLucid()], +#' [readLucidKey()], [readXper()], each with a writer). +#' * **Check it**: [checkNames()] looks its names up in GBIF, and `summary()` +#' and [keyQuality()] say how many steps it takes to reach a result, +#' optionally weighted by how common each taxon is ([occurrenceWeights()]). +#' * **Cut it down or join keys up**: [pruneKey()] keeps or drops taxa, +#' [regionalKey()] keeps the taxa recorded in a place, and [mergeKeys()] +#' grafts one key onto a result of another. +#' * **Generate a key from data**: from a character matrix +#' ([keyFromMatrix()], or [generateTree()] with [keyFromRpart()]), from a +#' sequence alignment ([keyFromAlignment()]), or from labelled photos with +#' a vision model ([visionModel()], [embedImages()], [discoverSniglets()], +#' [keyFromSniglets()], [keyFromClusters()]). Such keys can be followed by +#' machine with [classify()] and tested with [evaluateKey()] and +#' [benchmarkKey()]. +#' * **Share it**: [exportWizard()] writes a self-contained web page that +#' works on a phone, [keyDiagram()] draws a box diagram, and [toNewick()], +#' [toIgraph()], [toTreedata()] and [toAuspiceJSON()] hand the key to +#' phylogenetics software. +#' +#' @section Vignettes: +#' * `vignette("montana-hardwoods", package = "dimoose")`: a key written in a +#' spreadsheet, with photos. +#' * `vignette("published-key", package = "dimoose")`: from a printed key to +#' a regional key on a phone. +#' * `vignette("vision-keys", package = "dimoose")`: keys from photos. +#' * `vignette("alignment-keys", package = "dimoose")`: keys from aligned +#' sequences. +#' +#' @section Web services and optional software: +#' Reading, building, checking and exporting keys needs nothing beyond the +#' packages dimoose imports. [checkNames()], [regionalKey()], +#' [occurrenceWeights()], [importFishbase()] and [inatPhotos()] ask public +#' web services (GBIF, iNaturalist, FishBase) and need an internet +#' connection. The vision functions run a model in Python through the +#' reticulate package, which sets Python up on first use; +#' [saveEmbeddings()] and [loadEmbeddings()] let the later steps run without +#' it. #' #' @keywords internal #' @importFrom R6 R6Class diff --git a/R/dimoose.R b/R/dimoose.R index 96e15cb..237b469 100644 --- a/R/dimoose.R +++ b/R/dimoose.R @@ -110,27 +110,40 @@ dimoose <- R6::R6Class("dimoose", print = function(...) { s <- self$summary() cat(" ", if (is.na(s$title)) "(untitled)" else s$title, "\n", sep = "") - cat(sprintf(" %d couplets, %d leads, %d taxa, up to %d steps deep\n", - s$couplets, s$leads, s$taxa, s$depth)) + cat(sprintf(" %d couplets, %d leads, %d taxa, up to %d steps deep%s\n", + s$couplets, s$leads, s$taxa, s$depth, + if (is.na(s$meanTaxonSteps)) "" else sprintf(" (%.1f on average)", s$meanTaxonSteps))) if (s$problems > 0) cat(sprintf(" %d problem(s): see $validate()\n", s$problems)) invisible(self) }, - #' @description Counts describing the key. + #' @description Counts describing the key and how quickly it reaches a + #' result (see [keyQuality()]). + #' @param weights Optional named numeric vector of how common each taxon + #' is, as for [keyQuality()]; by default all taxa count the same. #' @return A one-row data frame: `title`, `couplets`, `leads`, `taxa`, - #' `depth` (longest path in steps) and `problems` (see `validate()`). - summary = function() { + #' `depth` (longest path in steps), `problems` (see `validate()`), + #' `meanLeadSteps` and `meanTaxonSteps` (steps to a result, averaged + #' over terminal leads and over taxa), `expectedSteps` (averaged over + #' taxa by `weights`), `bound` (the expected steps of the best key + #' there could be to these taxa, with couplets no larger than this + #' key's largest) and `efficiency` (`bound / expectedSteps`, 1 for a + #' key that could not be shorter). + summary = function(weights = NULL) { leads <- normalizeLeads(self$leads) check <- checkLeads(leads) - parentLead <- match(leads$Statement, leads$Next) - terminal <- which(leads$Next == "-") - depth <- if (length(terminal)) max(vapply(terminal, function(i) length(pathToLead(leads, i, check$root, parentLead)), 0L)) else 0L + quality <- keyQuality(self, weights) data.frame( title = if (length(private$.desc) == 1) as.character(private$.desc) else NA_character_, couplets = length(check$couplets), leads = nrow(leads), taxa = length(unique(leads$Taxon[leads$Next == "-" & nzchar(leads$Taxon)])), - depth = as.integer(depth), + depth = quality$depth, problems = length(check$problems), + meanLeadSteps = quality$meanLeadSteps, + meanTaxonSteps = quality$meanTaxonSteps, + expectedSteps = quality$expectedSteps, + bound = quality$bound, + efficiency = quality$efficiency, stringsAsFactors = FALSE ) }, @@ -300,5 +313,5 @@ leadsFromPaths <- function(df) { #' @export summary.dimoose <- function(object, ...) { - object$summary() + object$summary(...) } diff --git a/R/export.R b/R/export.R index bd5129e..38ccf6a 100644 --- a/R/export.R +++ b/R/export.R @@ -13,14 +13,139 @@ #' that cannot be reached from the first one are reported as warnings and #' marked in the page. #' -#' @param key A [dimoose] object, e.g. from [importFishbase()]. +#' @section Not sure: +#' Every couplet has an "I'm not sure" button (keys `u` or `?`). It follows +#' all leads of the couplet at once. The page then asks the questions of one +#' branch at a time, lists the branches still open (click one to answer it +#' next), and counts and marks on the map the taxa possible in any of them. +#' Each answer narrows its own branch. If the reader stays unsure to the end, +#' the page lists every result that is left. Back undoes one step at a time. +#' The address of the page records the open branches (`#open=c-3,c-9`), so a +#' reload or a shared link returns to the same place; the trail of choices +#' comes back too when the browser restores the page's history entry. +#' +#' @section Picking characters in any order: +#' With `matrix`, the page gains a second way in: a list of the characters of +#' the matrix, to answer in any order. Picking a state removes the taxa that +#' do not have it. A taxon with several states (`"a/b"`) fits any of them, and +#' a taxon whose state is unknown (`NA`) fits all. The characters that still +#' separate the remaining taxa are listed first: cheapest first when +#' `characters` gives a `Cost`, then those that leave the fewest taxa on +#' average. Taxa of the matrix are matched to the key's taxa by name (ignoring +#' case), so the remaining taxa link to their result sections and show on the +#' map, and the page offers to continue step by step from the couplet they all +#' share. Without JavaScript the matrix is a plain table. The two ways are +#' otherwise independent: answers given step by step do not filter the +#' character list. With `key = NULL` the page is the character list alone. +#' +#' @section Offline use: +#' The page itself needs no connection once it is open, but a browser will not +#' reopen a page it cannot fetch. `offline = TRUE` writes four files next to +#' `file`, named after it: a web app manifest (`.webmanifest`), a +#' service worker (`-sw.js`) and two icons (`-icon-192.png`, +#' `-icon-512.png`; the package logo if the rsvg package is installed, +#' otherwise a simple drawn icon). The worker stores the page, the manifest, +#' the icons and the figures the page loads from other sites, so that the +#' page can be installed on a phone ("Add to Home Screen") and opened without +#' signal. Upload all five files to the same folder. Limits: +#' +#' * Browsers run service workers only on `https://` or `http://localhost`. A +#' page opened from disk (`file://`) works as before but is not installed +#' and stores nothing. +#' * The page must be opened once with a connection before it works without. +#' * Figures on other sites are fetched when the worker installs and again +#' when first shown; any that fail are skipped. A site that does not allow +#' cross-origin requests gives an opaque copy, which browsers count as +#' several megabytes each against the storage they allow, so a key with +#' many such figures may not store them all. Figures embedded in the key +#' (see [imageMeta()]) are part of the page and always available. Full-size +#' figures and taxon pages that open in a new tab are not stored. +#' * The worker only controls the page it was written for (its scope is the +#' page's own address), so several keys can share a folder. Serve the page +#' under its file name; a server that drops the `.html` from addresses puts +#' the page outside the worker's scope. +#' +#' @section Identifying from a photo: +#' `photoModel` adds an "Identify from a photo" button. The reader takes or +#' picks a photo; the page loads the model and +#' [onnxruntime-web](https://onnxruntime.ai/docs/tutorials/web/) (the program +#' that runs it, version 1.31.1, about 15 MB, from the jsDelivr CDN unless +#' `photoRuntime` says otherwise), prepares the picture as the model's +#' `model.json` says, runs the image encoder in the browser and compares the +#' result with the text embeddings of the key's taxa. The photo never leaves +#' the reader's device. The page then marks the likely taxa on the map, lists +#' the five best with their scores, each linked to its result, and offers to +#' narrow the key to them: the leads that reach none of them are greyed and +#' the count of remaining taxa follows, but every lead still works. The key +#' stays the authority; the photo is a hint. +#' +#' `photoModel` is a folder written by [exportBrowserModel()] for the same +#' key, or the web address of one. The model is not put into the page. A +#' folder is copied next to `file` as `_model/` (so `file` is needed); +#' upload it with the page. A web address is used as it is; a model on +#' another site must allow cross-origin requests. What to expect: +#' +#' * Nothing is downloaded until the reader has chosen a photo, been told the +#' size and agreed. An int8 BioCLIP encoder is 90 MB; with the runtime that +#' is about 105 MB on first use. The page shows the progress. +#' * With `offline = TRUE` the service worker keeps the model and the runtime +#' once they have been fetched, so photos can be identified without a +#' connection afterwards. That is the same 105 MB or so of storage on the +#' reader's device, and the first use still needs a connection. +#' * It needs a browser with WebAssembly, and memory: several times the size +#' of the encoder while it loads. If the browser cannot run the model, runs +#' out of memory or cannot fetch it, the page says so and the key works as +#' before. A page opened from disk (`file://`) cannot load the model. +#' * Only the WebAssembly backend is used, on one thread unless the page is +#' served cross-origin isolated. That suits int8 encoders, which WebGPU +#' cannot run. +#' * The scores compare the key's taxa with each other and add up to 100%, +#' so a photo of something that is not in the key still gets a confident +#' best match. If `model.json` has a `min_similarity`, a best match whose +#' cosine similarity is under it is shown as "Not much like any taxon of +#' this key" without a percentage. +#' +#' @section Notes on leads: +#' A `Note` column in the key's leads, as [pruneKey()] writes when it +#' collapses a couplet (the character of the couplet that is no longer asked), +#' is shown under its lead as "Also:" and in the path of each result. A +#' `pruned_note` in the key's meta (the same for a collapsed first couplet) is +#' shown under the title. +#' +#' @section Hook for other scripts: +#' The page defines `window.dimoose` so that another script, for example one +#' that identifies a photo in the browser, can work with the page without +#' knowing how it is built: +#' +#' * `dimoose.taxa`: array of `{ id, name }`, one per result. +#' * `dimoose.highlight(scores, opts)`: `scores` is an object mapping taxon +#' names or ids to numbers, or an array of `{ taxon, score }`; `null` +#' clears. Marks those taxa on the map and in every list of candidates and +#' lists the five best above the key, headed by `opts.label` (default +#' "Suggested"). Scores all within 0 to 1 are shown as percentages. Returns +#' the ids it marked, best first. +#' * `dimoose.goToTaxon(nameOrId)`: shows that result; `false` if unknown. +#' * `dimoose.narrow(namesOrIds)`: narrows the key to these taxa (see +#' 'Identifying from a photo'); `null` undoes it. Returns the ids kept. +#' * `dimoose.state()`: `{ shown, open, remaining, picks, narrowed }`, the +#' section shown, the open branches, the ids of the taxa still possible, the +#' states picked in the character list and the ids the key is narrowed to +#' (or `null`). +#' * `dimoose.photo` (only with `photoModel`): `identify(file)`, a promise of +#' the ranked taxa, and the pure steps `preprocess()` and `score()`. +#' * `dimoose.onChange(fn)`: calls `fn(state)` after every step. +#' +#' @param key A [dimoose] object, e.g. from [importFishbase()]. May be `NULL` +#' if `matrix` is given. #' @param file Path of the HTML file to write. If `NULL`, the HTML is returned #' as a string instead. #' @param displayLinks If `TRUE`, show the couplet numbers each lead leads to #' and comes from, as in a printed key. If `FALSE`, hide them. Leads stay #' clickable either way. -#' @param order Order of couplets. Only `"original"` (the key's own order) is -#' implemented. +#' @param order Deprecated and ignored. Couplets are always exported in the +#' key's own order. `"parsimony"` was never implemented; to ask the +#' questions that are easiest to observe first, build the key with +#' [keyFromMatrix()] and give the characters a `Cost`. #' @param title Page title. Defaults to the key's description. #' @param staticPaths If `TRUE`, write each taxon's path through the key into #' the page, so it shows without JavaScript. If `FALSE`, the page builds @@ -31,60 +156,530 @@ #' tree, marking the current couplet, the path taken so far and the #' branches (and number of taxa) still possible. It sits beside the key on #' wide screens and behind a Map button on phones. +#' @param matrix Optional character matrix: a data frame with one row per +#' taxon, the taxon's name in column `taxon` and one column per character. +#' Cells are states; several states of one taxon are separated by `"/"`; +#' `NA` is unknown or inapplicable. See 'Picking characters in any order'. +#' @param characters Optional data frame describing the characters of +#' `matrix`: column `Character` (a column name of `matrix`) and any of +#' `Cost` (lower is easier to observe), `Season` (when it can be observed) +#' and `Needs` (e.g. `"hand lens"`). +#' @param taxon Name of the column of `matrix` that holds the taxon names. +#' @param offline If `TRUE`, also write a web app manifest, a service worker +#' and icons next to `file`, so that the page can be installed and opened +#' without a connection. Needs `file`. See 'Offline use'. +#' @param photoModel Optional: a folder written by [exportBrowserModel()] for +#' this key, or the web address (`https://...`) of one. Adds "Identify from +#' a photo" to the page. See 'Identifying from a photo'. +#' @param photoRuntime Optional web address of a folder holding the `dist` +#' files of onnxruntime-web (`ort.wasm.min.js`, `ort-wasm-simd-threaded.mjs` +#' and `.wasm`), to serve them yourself instead of loading them from +#' jsDelivr. Relative addresses are relative to the page. #' @return The path to `file`, invisibly, or the HTML as a character string if -#' `file` is `NULL`. +#' `file` is `NULL`. With `offline = TRUE` or a `photoModel` folder the +#' paths of the other files written are in attribute `"files"`. +#' @seealso [keyFromMatrix()] to build a key from a character matrix. #' @examples -#' \dontrun{ -#' sharks <- importFishbase(1, usePhyloService = "none") -#' exportWizard(sharks, "sharks.html") -#' } +#' leads <- data.frame( +#' Statement = c("1", "1", "2", "2"), Choice = c("a", "b", "a", "b"), +#' Character = c("Wings present", "Wings absent", "Two wings", "Four wings"), +#' Next = c("2", "-", "-", "-"), Taxon = c("", "Silverfish", "Fly", "Bee") +#' ) +#' key <- keyFromLeads(leads, "A tiny key") +#' html <- exportWizard(key) +#' substr(html, 1, 15) +#' +#' # With a character matrix the reader can also pick characters in any order +#' insects <- data.frame( +#' Taxon = c("Silverfish", "Fly", "Bee", "Ant"), +#' Wings = c("absent", "present", "present", "present/absent"), +#' Sting = c("absent", "absent", "present", NA) +#' ) +#' characters <- data.frame(Character = c("Wings", "Sting"), Cost = c(1, 3), +#' Needs = c("", "hand lens")) +#' html <- exportWizard(key, matrix = insects, characters = characters) +#' +#' # A matrix alone makes a page with only the character list +#' html <- exportWizard(NULL, matrix = insects, title = "Four insects") +#' +#' # An installable copy that opens without a connection once it is served +#' # over https: the page, a manifest, a service worker and two icons +#' dir <- tempfile("key") +#' dir.create(dir) +#' out <- exportWizard(key, file.path(dir, "insects.html"), offline = TRUE) +#' list.files(dir) +#' unlink(dir, recursive = TRUE) #' @export -exportWizard <- function(key, file = NULL, displayLinks = TRUE, - order = c("original", "parsimony"), title = NULL, - map = TRUE, staticPaths = NULL) { - order <- match.arg(order) +exportWizard <- function(key = NULL, file = NULL, displayLinks = TRUE, + order = "original", title = NULL, + map = TRUE, staticPaths = NULL, + matrix = NULL, characters = NULL, taxon = "Taxon", + offline = FALSE, photoModel = NULL, photoRuntime = NULL) { + order <- match.arg(order, c("original", "parsimony")) if (order == "parsimony") { - stop("order = \"parsimony\" is not implemented yet; use \"original\"", call. = FALSE) + warning("`order` is deprecated and ignored: exportWizard() keeps the key's own order. ", + "To ask the easiest questions first, build the key with ", + "keyFromMatrix(characters = ) and give the characters a Cost.", call. = FALSE) } - if (!inherits(key, "dimoose")) { - stop("`key` must be a dimoose object", call. = FALSE) + if (is.null(key)) { + if (is.null(matrix)) stop("Give a `key`, a `matrix`, or both", call. = FALSE) + leads <- normalizeLeads(data.frame(Statement = character(), stringsAsFactors = FALSE)) + check <- list(root = NA_character_, couplets = character(), missingTarget = logical(), + unreachable = character(), problems = character()) + key <- list(desc = NA, meta = NULL, taxa = NULL, features = NULL) + } else { + if (!inherits(key, "dimoose")) { + stop("`key` must be a dimoose object", call. = FALSE) + } + leads <- normalizeLeads(key$leads) + if (nrow(leads) == 0) { + stop("This key has no leads to export", call. = FALSE) + } + check <- checkLeads(leads) + for (w in check$problems) warning(w, call. = FALSE) } - leads <- normalizeLeads(key$leads) - if (nrow(leads) == 0) { - stop("This key has no leads to export", call. = FALSE) + hasKey <- nrow(leads) > 0 + mx <- if (is.null(matrix)) NULL else wizMatrix(matrix, characters, taxon) + if (is.null(mx) && !is.null(characters)) { + warning("`characters` describes the columns of `matrix` and is ignored without one", call. = FALSE) } - check <- checkLeads(leads) - for (w in check$problems) warning(w, call. = FALSE) if (is.null(title)) { - title <- if (length(key$desc) == 1 && !is.na(key$desc)) key$desc else "Dichotomous key" + title <- if (length(key$desc) == 1 && !is.na(key$desc)) key$desc else if (hasKey) "Dichotomous key" else "Multi-access key" } nodeLabel <- metaValue(key$meta, "node_label") if (is.na(nodeLabel) || !nzchar(nodeLabel)) nodeLabel <- "Couplet" if (is.null(staticPaths)) { staticPaths <- length(unique(leads$Taxon[leads$Next == "-" & nzchar(leads$Taxon)])) <= 1000 } + images <- embeddedImages(key$meta) + + if (isTRUE(offline) && is.null(file)) { + warning("offline = TRUE needs `file`: the manifest, service worker and icons are written next to it. ", + "Returning the page alone.", call. = FALSE) + offline <- FALSE + } + side <- if (isTRUE(offline)) wizOfflineNames(file) else NULL + photo <- if (is.null(photoModel)) NULL else wizPhotoModel(photoModel, file, photoRuntime, leads) + if (is.null(photo) && !is.null(photoRuntime)) { + warning("`photoRuntime` is only used with `photoModel` and is ignored", call. = FALSE) + } + html <- renderWizard(leads, check, nodeLabel = nodeLabel, staticPaths = isTRUE(staticPaths), title = title, citation = metaValue(key$meta, "citation"), taxa = key$taxa, - images = embeddedImages(key$meta), + images = images, displayLinks = displayLinks, map = map, - features = key$features + features = key$features, + matrix = mx, + offline = side, + photo = photo, + note = metaValue(key$meta, "pruned_note") ) if (is.null(file)) { + if (!is.null(photo)) wizPhotoMessage(photo, FALSE) return(html) } - # Write bytes so UTF-8 text survives non-UTF-8 locales + wizWriteText(html, file) + written <- character() + if (!is.null(side)) { + written <- wizWriteOffline(side, html, title, wizExternalImages(leads, images), + keep = if (is.null(photo)) character() else photo$keep, + stamp = if (is.null(photo)) "" else photo$stamp) + } + if (!is.null(photo)) { + written <- c(written, wizCopyPhotoModel(photo)) + wizPhotoMessage(photo, isTRUE(offline)) + } + if (length(written)) attr(file, "files") <- written + invisible(file) +} + +# ---- identify from a photo ------------------------------------------------------- + +# onnxruntime-web, the program that runs the image encoder in the page. The +# version is pinned: the page loads these three files of it. +wizOrt <- list( + version = "1.31.1", + files = c("ort.wasm.min.js", "ort-wasm-simd-threaded.mjs", "ort-wasm-simd-threaded.wasm"), + bytes = 53796 + 24738 + 14848852 +) +wizOrtUrl <- function() sprintf("https://cdn.jsdelivr.net/npm/onnxruntime-web@%s/dist/", wizOrt$version) + +# Checks `photoModel` (a folder written by exportBrowserModel() or the web +# address of one). Returns what the page and the copy need: `url` (the +# address of the folder as the page sees it), `runtime`, `runtimeBytes` +# (known for the pinned runtime only), `from`/`to`/`files` for a folder to +# copy, `bytes` of the model when known, and `keep`, the addresses +# (the model and the runtime) that the service worker should keep once +# fetched, with `stamp`, a fingerprint of the model. NULL (with a warning) when a +# folder is given but there is no `file` to copy it next to. +wizPhotoModel <- function(photoModel, file, runtime = NULL, leads = NULL) { + if (!is.character(photoModel) || length(photoModel) != 1 || is.na(photoModel) || !nzchar(photoModel)) { + stop("`photoModel` must be one folder written by exportBrowserModel(), or the web address of one", call. = FALSE) + } + folderUrl <- function(x) paste0(sub("/+$", "", x), "/") + if (is.null(runtime)) { + runtime <- wizOrtUrl() + runtimeBytes <- wizOrt$bytes + } else { + if (!is.character(runtime) || length(runtime) != 1 || is.na(runtime) || !nzchar(runtime)) { + stop("`photoRuntime` must be the web address of a folder with the files of onnxruntime-web", call. = FALSE) + } + runtime <- folderUrl(runtime) + runtimeBytes <- NA_real_ + } + out <- list(runtime = runtime, runtimeBytes = runtimeBytes, bytes = NA_real_, keep = runtime, stamp = "") + if (grepl("^https?://", photoModel)) { + out$url <- folderUrl(sub("model\\.json$", "", photoModel)) + out$keep <- c(out$keep, out$url) + return(out) + } + dir <- if (!dir.exists(photoModel) && basename(photoModel) == "model.json") dirname(photoModel) else photoModel + manifest <- file.path(dir, "model.json") + if (!dir.exists(dir) || !file.exists(manifest)) { + stop("`photoModel` must be a folder written by exportBrowserModel() (with a model.json), or a web address: ", + photoModel, call. = FALSE) + } + text <- paste(readLines(manifest, warn = FALSE, encoding = "UTF-8"), collapse = "\n") + if (!grepl("dimoose-browser-model", text, fixed = TRUE)) { + stop(manifest, " is not a model written by exportBrowserModel()", call. = FALSE) + } + files <- c("model.json", list.files(dir, pattern = "\\.(bin|onnx)$")) + if (requireNamespace("jsonlite", quietly = TRUE)) { + m <- tryCatch(jsonlite::fromJSON(text, simplifyVector = FALSE), error = function(e) NULL) + if (is.null(m)) stop(manifest, " cannot be read as JSON", call. = FALSE) + named <- c(m$text_embeddings$file, m$image_encoder$file) + missing <- named[!file.exists(file.path(dir, named))] + if (length(missing)) stop("`photoModel` lacks ", paste(missing, collapse = ", "), ", which its model.json names", call. = FALSE) + files <- c("model.json", named) + if (!length(m$image_encoder$file) && !length(m$image_encoder$url)) { + stop(manifest, " names no image encoder (neither a file nor a web address)", call. = FALSE) + } + if (length(m$image_encoder$url)) out$keep <- c(out$keep, m$image_encoder$url) + if (length(m$image_encoder$bytes)) out$bytes <- as.numeric(m$image_encoder$bytes) + if (!is.null(leads)) { + labels <- vapply(m$labels, function(l) as.character(l$taxon), "") + taxa <- unique(leads$Taxon[leads$Next == "-" & nzchar(leads$Taxon)]) + if (length(taxa) && !any(labels %in% taxa)) { + warning("`photoModel` was made for another key: none of its ", length(labels), + " labels is a result of this one, so a photo will highlight nothing. ", + "Make it with exportBrowserModel() from this key.", call. = FALSE) + } else if (length(setdiff(taxa, labels))) { + message(length(setdiff(taxa, labels)), " of ", length(taxa), " results of the key are not in `photoModel` and cannot be suggested from a photo: ", + paste(utils::head(setdiff(taxa, labels), 5), collapse = ", "), if (length(setdiff(taxa, labels)) > 5) ", ..." else "") + } + } + } + if (is.null(file)) { + warning("A `photoModel` folder is copied next to `file`, so it needs `file` (or give a web address). ", + "Returning the page without photo identification.", call. = FALSE) + return(NULL) + } + if (is.na(out$bytes)) out$bytes <- sum(file.size(file.path(dir, files[grepl("\\.onnx$", files)]))) + folder <- paste0(sub("\\.[^.]*$", "", basename(file)), "_model") + out$url <- paste0(utils::URLencode(folder, reserved = TRUE), "/") + out$keep <- c(out$keep, out$url) + # a model made again gets a new store on the reader's device + out$stamp <- wizHash(paste(text, paste(file.size(file.path(dir, files)), collapse = " "))) + out$from <- dir + out$to <- file.path(dirname(file), folder) + out$files <- unique(files) + out +} + +# Copies the model next to the page; files already there with the same size +# and no older than the source are left alone (the encoder is large). +wizCopyPhotoModel <- function(photo) { + if (is.null(photo$from)) return(character()) + dir.create(photo$to, showWarnings = FALSE, recursive = TRUE) + from <- file.path(photo$from, photo$files) + to <- file.path(photo$to, photo$files) + same <- normalizePath(from) == normalizePath(to, mustWork = FALSE) + fresh <- file.exists(to) & file.size(to) == file.size(from) & file.mtime(to) >= file.mtime(from) + todo <- !same & (is.na(fresh) | !fresh) + ok <- file.copy(from[todo], to[todo], overwrite = TRUE, copy.date = TRUE) + if (!all(ok)) stop("Could not copy the model to ", photo$to, call. = FALSE) + to +} + +wizPhotoMessage <- function(photo, offline) { + mb <- function(x) paste(format(round(x / 1e6), big.mark = ","), "MB") + model <- if (is.na(photo$bytes)) "the model" else paste0("the model (", mb(photo$bytes), ")") + runtime <- if (is.na(photo$runtimeBytes)) "onnxruntime-web" else paste0("onnxruntime-web ", wizOrt$version, " (", mb(photo$runtimeBytes), ")") + total <- photo$bytes + photo$runtimeBytes + message( + if (!is.null(photo$to)) paste0("The model was copied to ", photo$to, ": upload that folder with the page. "), + "The first time a reader identifies a photo, the page downloads ", model, " and ", runtime, + if (!is.na(total)) paste0(", ", mb(total), " in all"), ", after asking.", + if (offline) paste0(" With offline = TRUE the service worker then keeps them", + if (!is.na(total)) paste0(" (", mb(total), " of storage on the reader's device)"), + ", so photos can be identified without a connection afterwards.") + ) +} + +# Write bytes so UTF-8 text survives non-UTF-8 locales +wizWriteText <- function(text, file) { con <- file(file, open = "wb") on.exit(close(con)) - writeBin(charToRaw(enc2utf8(html)), con) + writeBin(charToRaw(enc2utf8(text)), con) invisible(file) } +# ---- character matrix -------------------------------------------------------- + +# Checks a character matrix and its optional character table. Returns +# list(taxa, characters, cells, cost, season, needs): `cells` is a character +# matrix (taxa x characters) of trimmed state strings, NA where unknown; +# characters are ordered cheapest first when costs are given. +wizMatrix <- function(matrix, characters = NULL, taxon = "Taxon") { + if (!is.data.frame(matrix)) stop("`matrix` must be a data frame with one row per taxon", call. = FALSE) + if (!is.character(taxon) || length(taxon) != 1 || !taxon %in% names(matrix)) { + stop("`taxon` must name the column of `matrix` that holds the taxon names", call. = FALSE) + } + name <- trimws(as.character(matrix[[taxon]])) + if (length(name) == 0) stop("`matrix` has no rows", call. = FALSE) + if (anyNA(name) || any(!nzchar(name))) stop("`matrix` has rows with no taxon name", call. = FALSE) + if (anyDuplicated(name)) { + stop("`matrix` lists a taxon more than once: ", paste(unique(name[duplicated(name)]), collapse = ", "), + ". Give a variable taxon one row, with its states separated by \"/\".", call. = FALSE) + } + chars <- setdiff(names(matrix), taxon) + if (length(chars) == 0) stop("`matrix` has no character columns", call. = FALSE) + cells <- vapply(chars, function(ch) { + x <- trimws(as.character(matrix[[ch]])) + x[!is.na(x) & !nzchar(gsub("[/[:space:]]", "", x))] <- NA + x + }, character(length(name))) + cells <- base::matrix(cells, nrow = length(name), dimnames = list(name, chars)) + + cost <- rep(NA_real_, length(chars)) + season <- needs <- rep("", length(chars)) + if (!is.null(characters)) { + if (!is.data.frame(characters) || !"Character" %in% names(characters)) { + stop("`characters` must be a data frame with a column `Character`", call. = FALSE) + } + row <- match(chars, trimws(as.character(characters$Character))) + text <- function(col) { + if (is.null(characters[[col]])) return(rep("", length(chars))) + x <- trimws(as.character(characters[[col]])[row]) + x[is.na(x)] <- "" + x + } + if (!is.null(characters$Cost)) cost <- suppressWarnings(as.numeric(characters$Cost))[row] + season <- text("Season") + needs <- text("Needs") + } + o <- order(cost, na.last = TRUE) # stable: matrix order among equal costs + list(taxa = name, characters = chars[o], cells = cells[, o, drop = FALSE], + cost = cost[o], season = season[o], needs = needs[o]) +} + +# The matrix as a section of the page: a plain table, which the page script +# reads and turns into the list of characters to pick from. `ids` gives the +# id of every taxon (the key's result section, or its own). +wizMatrixHtml <- function(mx, ids, linked) { + note <- function(j) { + bits <- c(if (nzchar(mx$needs[j])) paste("needs", mx$needs[j]), if (nzchar(mx$season[j])) mx$season[j]) + if (length(bits)) sprintf("%s", htmlEscape(paste(bits, collapse = " \u00b7 "))) else "" + } + head <- vapply(seq_along(mx$characters), function(j) { + sprintf("%s%s", + htmlEscape(mx$characters[j]), + if (is.na(mx$cost[j])) "" else sprintf(" data-cost=\"%s\"", format(mx$cost[j], scientific = FALSE, trim = TRUE)), + if (nzchar(mx$season[j])) sprintf(" data-season=\"%s\"", htmlEscape(mx$season[j])) else "", + if (nzchar(mx$needs[j])) sprintf(" data-needs=\"%s\"", htmlEscape(mx$needs[j])) else "", + htmlEscape(mx$characters[j]), note(j)) + }, character(1)) + rows <- vapply(seq_along(mx$taxa), function(i) { + x <- mx$cells[i, ] + cells <- ifelse(is.na(x), "?", paste0("", htmlEscape(x), "")) + name <- htmlEscape(mx$taxa[i]) + sprintf("%s%s", ids[i], + if (linked[i]) sprintf("%s", ids[i], name) else name, + paste(cells, collapse = "")) + }, character(1)) + paste0( + "
\n", + "

Pick any character you can see

\n", + "

The table gives the state of each character in each taxon. ", + "States separated by "/" both occur in the taxon; "?" is unknown or does not apply. ", + "Strike out the taxa that do not fit what you see.

\n", + "
\nThe whole table\n
\n", + "\n", paste(head, collapse = ""), "\n", + "\n", paste(rows, collapse = "\n"), "\n\n
Taxon
\n
\n
\n
" + ) +} + +# ---- offline copy -------------------------------------------------------------- + +wizJsonString <- function(x) { + x <- gsub("\\", "\\\\", enc2utf8(x), fixed = TRUE) + x <- gsub("\"", "\\\"", x, fixed = TRUE) + x <- gsub("\n", "\\n", x, fixed = TRUE) + x <- gsub("\r", "\\r", x, fixed = TRUE) + x <- gsub("\t", "\\t", x, fixed = TRUE) + x <- gsub("<", "\\u003c", x, fixed = TRUE) + paste0("\"", x, "\"") +} + +# A short fingerprint of a text, so that a changed page gets a new cache +wizHash <- function(x) { + b <- as.numeric(charToRaw(enc2utf8(x))) + sprintf("%08x%06x", as.integer(sum(b * (seq_along(b) %% 65521 + 1)) %% 2147483629), length(b) %% 16777216) +} + +# Names of the files written next to the page, as paths and as the relative +# addresses the page and the worker use +wizOfflineNames <- function(file) { + page <- basename(file) + base <- sub("\\.[^.]*$", "", page) + names <- c(manifest = paste0(base, ".webmanifest"), sw = paste0(base, "-sw.js"), + icon192 = paste0(base, "-icon-192.png"), icon512 = paste0(base, "-icon-512.png")) + url <- function(x) utils::URLencode(x, reserved = TRUE) + # a page called index.html is usually served as its folder + index <- tolower(page) %in% c("index.html", "index.htm") + list(dir = dirname(file), page = page, base = base, files = names, + url = c(page = url(page), vapply(names, url, "")), + scope = if (index) "./" else paste0("./", url(page))) +} + +wizWriteOffline <- function(side, html, title, external = character(), keep = character(), stamp = "") { + path <- function(x) file.path(side$dir, side$files[[x]]) + icon <- function(size) list(src = side$url[[paste0("icon", size)]], size = size) + manifest <- paste0( + "{\n", + " \"name\": ", wizJsonString(title), ",\n", + " \"short_name\": ", wizJsonString(if (nchar(title) > 12) side$base else title), ",\n", + " \"description\": ", wizJsonString(paste("Identification key:", title)), ",\n", + " \"start_url\": ", wizJsonString(side$scope), ",\n", + " \"scope\": ", wizJsonString(side$scope), ",\n", + " \"display\": \"standalone\",\n", + " \"background_color\": \"#f6f3eb\",\n", + " \"theme_color\": \"#1d6b58\",\n", + " \"icons\": [\n", + paste(vapply(c(192, 512), function(size) { + sprintf(" {\"src\": %s, \"sizes\": \"%dx%d\", \"type\": \"image/png\", \"purpose\": \"any\"}", + wizJsonString(icon(size)$src), size, size) + }, ""), collapse = ",\n"), + "\n ]\n}\n" + ) + wizWriteText(manifest, path("manifest")) + wizIcon(path("icon192"), 192) + wizIcon(path("icon512"), 512) + + sw <- paste(readLines(system.file("wizard", "sw.js", package = "dimoose"), warn = FALSE), collapse = "\n") + prefix <- paste0("dimoose-", gsub("[^A-Za-z0-9_-]", "_", side$base), "-") + array <- function(x) paste(wizJsonString(x), collapse = ", ") + fill <- c( + "\"__CACHE__\"" = wizJsonString(paste0(prefix, wizHash(paste(html, paste(external, collapse = "\n"))))), + "\"__PREFIX__\"" = wizJsonString(prefix), + "\"__KEPT__\"" = wizJsonString(paste0(prefix, "kept-", stamp)), + "\"__PAGE__\"" = wizJsonString(side$url[["page"]]), + "[/*__PRECACHE__*/]" = paste0("[", array(unname(side$url[c("page", "manifest", "icon192", "icon512")])), "]"), + "[/*__EXTERNAL__*/]" = paste0("[", if (length(external)) array(external) else "", "]"), + "[/*__KEEP__*/]" = paste0("[", if (length(keep)) array(unique(keep)) else "", "]") + ) + for (token in names(fill)) sw <- sub(token, fill[[token]], sw, fixed = TRUE) + wizWriteText(paste0(sw, "\n"), path("sw")) + unname(vapply(names(side$files), path, "")) +} + +# Figures the page loads from other sites (those not embedded in the key) +wizExternalImages <- function(leads, images) { + urls <- unique(unlist(lapply(leads$Image, splitUrls))) + if (length(urls) == 0) return(character()) + name <- sub("\\.(gif|jpe?g|png|webp)$", "", basename(urls), ignore.case = TRUE) + urls[grepl("^https?://", urls) & !name %in% names(images)] +} + +# App icon: the package logo when it can be drawn (needs rsvg), otherwise a +# plain drawn one. +wizIcon <- function(file, size) { + logo <- c(system.file("help", "figures", "logo.svg", package = "dimoose"), + system.file("man", "figures", "logo.svg", package = "dimoose")) + logo <- logo[nzchar(logo)] + if (length(logo) > 0 && requireNamespace("rsvg", quietly = TRUE)) { + ok <- tryCatch({ + rsvg::rsvg_png(logo[1], file, width = size, height = size) + file.exists(file) && file.size(file) > 0 + }, error = function(e) FALSE) + if (ok) return(invisible(file)) + } + wizDrawnIcon(file, size) +} + +# A forking branch (one couplet, two leads) in the page's colours, written as +# a PNG with base R only. +wizDrawnIcon <- function(file, size) { + u <- (seq_len(size) - 0.5) / size + x <- base::matrix(u, size, size, byrow = TRUE) + y <- base::matrix(u, size, size) + w <- 0.035 + dot <- function(cx, cy, r = 0.085) (x - cx)^2 + (y - cy)^2 < r^2 + glyph <- (abs(x - 0.5) < w & y > 0.55 & y < 0.76) | + (abs(y - 0.55) < w & x > 0.28 - w & x < 0.72 + w) | + ((abs(x - 0.28) < w | abs(x - 0.72) < w) & y > 0.3 & y < 0.55) | + dot(0.28, 0.27) | dot(0.72, 0.27) | dot(0.5, 0.76) + rgb <- array(rep(c(0x1d, 0x6b, 0x58), each = size * size), c(size, size, 3)) + for (k in 1:3) rgb[, , k][glyph] <- c(0xf6, 0xf3, 0xeb)[k] + wizWritePng(rgb, file) +} + +# Minimal PNG writer: `rgb` is a rows x columns x 3 array of 0..255. +wizWritePng <- function(rgb, file) { + h <- dim(rgb)[1] + w <- dim(rgb)[2] + # each scanline: filter byte 0, then R G B per pixel + lines <- vapply(seq_len(h), function(i) c(0, as.vector(t(rgb[i, , ]))), numeric(1 + 3 * w)) + be32 <- function(n) as.raw(c(n %/% 16777216, (n %/% 65536) %% 256, (n %/% 256) %% 256, n %% 256)) + chunk <- function(type, data) { + body <- c(charToRaw(type), data) + c(be32(length(data)), body, wizCrc32(body)) + } + png <- c( + as.raw(c(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a)), + chunk("IHDR", c(be32(w), be32(h), as.raw(c(8, 2, 0, 0, 0)))), + chunk("IDAT", memCompress(as.raw(as.vector(lines)), "gzip")), + chunk("IEND", raw()) + ) + writeBin(png, file) + invisible(file) +} + +# CRC-32 of a raw vector as 4 bytes, kept in two 16-bit halves because R's +# bitwise functions work on signed 32-bit integers. +wizCrc32 <- function(bytes) { + tab <- vapply(0:255, function(n) { + hi <- 0L + lo <- n + for (k in 1:8) { + odd <- bitwAnd(lo, 1L) == 1L + lo <- bitwOr(bitwShiftR(lo, 1L), bitwShiftL(bitwAnd(hi, 1L), 15L)) + hi <- bitwShiftR(hi, 1L) + if (odd) { + hi <- bitwXor(hi, 0xEDB8L) + lo <- bitwXor(lo, 0x8320L) + } + } + c(hi, lo) + }, integer(2)) + hi <- 0xFFFFL + lo <- 0xFFFFL + for (b in as.integer(bytes)) { + i <- bitwAnd(bitwXor(lo, b), 255L) + 1L + lo <- bitwXor(tab[2, i], bitwOr(bitwShiftR(lo, 8L), bitwShiftL(bitwAnd(hi, 255L), 8L))) + hi <- bitwXor(tab[1, i], bitwShiftR(hi, 8L)) + } + hi <- bitwXor(hi, 0xFFFFL) + lo <- bitwXor(lo, 0xFFFFL) + as.raw(c(hi %/% 256L, hi %% 256L, lo %/% 256L, lo %% 256L)) +} + # ---- key checks -------------------------------------------------------------- normalizeLeads <- function(leads) { @@ -256,17 +851,25 @@ figuresHtml <- function(thumbs, fulls, images, alt) { } renderWizard <- function(leads, check, title, citation, taxa, images, displayLinks, map = TRUE, - nodeLabel = "Couplet", staticPaths = TRUE, features = NULL) { + nodeLabel = "Couplet", staticPaths = TRUE, features = NULL, + matrix = NULL, offline = NULL, photo = NULL, note = NA_character_) { + hasKey <- nrow(leads) > 0 # FALSE for a page made from a character matrix alone + map <- isTRUE(map) && hasKey label <- leadLabels(leads) # Section ids: sanitized names, made unique (e.g. M4'67 and M4"67) - ids <- paste0("c-", gsub("[^A-Za-z0-9_-]", "_", check$couplets)) + ids <- if (hasKey) paste0("c-", gsub("[^A-Za-z0-9_-]", "_", check$couplets)) else character() ids <- ifelse(duplicated(ids) | duplicated(ids, fromLast = TRUE), paste0(ids, "-", seq_along(ids)), ids) names(ids) <- check$couplets coupletId <- function(cp) unname(ids[cp]) terminal <- which(leads$Next == "-" & leads$Taxon != "") taxonNames <- unique(leads$Taxon[terminal]) - taxonId <- stats::setNames(paste0("t-", seq_along(taxonNames)), taxonNames) + taxonId <- stats::setNames(paste0("t-", seq_along(taxonNames))[seq_along(taxonNames)], taxonNames) + + # Notes on leads (pruneKey() writes the character of a collapsed couplet there) + leadNote <- if (is.null(leads$Note)) rep("", nrow(leads)) else trimws(as.character(leads$Note)) + leadNote[is.na(leadNote)] <- "" + noteHtml <- ifelse(nzchar(leadNote), sprintf("Also: %s", htmlEscape(leadNote)), "") # Couplet sections coupletHtml <- vapply(check$couplets, function(cp) { @@ -298,8 +901,8 @@ renderWizard <- function(leads, check, title, citation, taxa, images, displayLin dest <- paste0("→ ", htmlEscape(leads$Next[i])) } inner <- sprintf( - "%s%s%s", - if (nzchar(leads$Choice[i])) htmlEscape(leads$Choice[i]) else "•", htmlEscape(text), dest + "%s%s%s%s", + if (nzchar(leads$Choice[i])) htmlEscape(leads$Choice[i]) else "•", htmlEscape(text), noteHtml[i], dest ) choose <- if (is.na(href)) { sprintf("%s", htmlEscape(label[i]), inner) @@ -326,8 +929,8 @@ renderWizard <- function(leads, check, title, citation, taxa, images, displayLin sprintf("%s %s", htmlEscape(nodeLabel), htmlEscape(cp)) } sprintf( - "
\n

%s%s

\n
    \n%s\n
\n
", - id, id, id, heading, from, paste(leadItems, collapse = "\n") + "
\n

%s%s

\n
    \n%s\n
\n
", + id, id, htmlEscape(paste(nodeLabel, cp)), id, heading, from, paste(leadItems, collapse = "\n") ) }, character(1)) @@ -341,8 +944,8 @@ renderWizard <- function(leads, check, title, citation, taxa, images, displayLin steps <- if (staticPaths) { path <- pathToLead(leads, i, check$root, parentLead) vapply(path, function(p) { - sprintf("
  • %s%s
  • ", - coupletId(leads$Statement[p]), htmlEscape(label[p]), htmlEscape(leads$Character[p])) + sprintf("
  • %s%s%s
  • ", + coupletId(leads$Statement[p]), htmlEscape(label[p]), htmlEscape(leads$Character[p]), noteHtml[p]) }, character(1)) } else { "
  • The path through the key appears here when the page script runs.
  • " @@ -378,8 +981,39 @@ renderWizard <- function(leads, check, title, citation, taxa, images, displayLin "" } citationHtml <- if (!is.na(citation) && nzchar(citation)) sprintf("

    %s

    ", htmlEscape(citation)) else "" + if (length(note) == 1 && !is.na(note) && nzchar(note)) { + citationHtml <- paste0(citationHtml, sprintf("\n

    All taxa of this key: %s

    ", htmlEscape(note))) + } + + mapHtml <- if (map) renderMap(leads, check, coupletId, taxonId, nodeLabel) else "" - mapHtml <- if (isTRUE(map)) renderMap(leads, check, coupletId, taxonId, nodeLabel) else "" + # Character matrix: its taxa are matched to the key's by name, so that they + # share the result sections and the map + matrixHtml <- "" + if (!is.null(matrix)) { + row <- match(matrix$taxa, taxonNames) + loose <- match(tolower(matrix$taxa), tolower(trimws(taxonNames))) + row[is.na(row)] <- loose[is.na(row)] + if (hasKey && anyNA(row)) { + message(sum(is.na(row)), " of ", length(row), " taxa of the matrix are not results of the key and get no link: ", + paste(utils::head(matrix$taxa[is.na(row)], 10), collapse = ", "), if (sum(is.na(row)) > 10) ", ..." else "") + } + matrixIds <- ifelse(is.na(row), paste0("m-", seq_along(row)), unname(taxonId)[row]) + matrixHtml <- paste0(if (hasKey) "

    Characters

    \n" else "", + wizMatrixHtml(matrix, matrixIds, !is.na(row)), "\n") + } + rootId <- if (hasKey) coupletId(check$root) else "matrix" + head <- body <- foot <- "" + if (!is.null(offline)) { + head <- sprintf("\n\n\n", + offline$url[["manifest"]], offline$url[["icon192"]], offline$url[["icon192"]]) + body <- sprintf(" data-sw=\"%s\" data-sw-scope=\"%s\"", offline$url[["sw"]], offline$scope) + foot <- "" + } + if (!is.null(photo)) { + body <- paste0(body, sprintf(" data-photo-model=\"%s\" data-photo-runtime=\"%s\"", htmlEscape(photo$url), htmlEscape(photo$runtime)), + if (!is.na(photo$runtimeBytes)) sprintf(" data-photo-runtime-bytes=\"%.0f\"", photo$runtimeBytes) else "") + } css <- paste(readLines(system.file("wizard", "wizard.css", package = "dimoose"), warn = FALSE), collapse = "\n") js <- paste(readLines(system.file("wizard", "wizard.js", package = "dimoose"), warn = FALSE), collapse = "\n") @@ -392,24 +1026,28 @@ renderWizard <- function(leads, check, title, citation, taxa, images, displayLin "\n", "\n", "\n", - "", htmlEscape(title), "\n\n", imageStyle(images), "\n", - "\n", - "
    \n

    Dichotomous key

    \n

    ", htmlEscape(title), "

    \n", citationHtml, "\n", + "", htmlEscape(title), "\n", head, "\n", imageStyle(images), "\n", + "\n", + "
    \n

    ", if (hasKey) "Dichotomous key" else "Multi-access key", "

    \n

    ", htmlEscape(title), "

    \n", citationHtml, "\n", "\n", + if (hasKey && !is.null(matrix)) "" else "", + if (map) "" else "", + if (hasKey) "" else "", + "\n", "
      \n
      \n", - "
      \n", mapHtml, + "
      \n", mapHtml, "
      \n", warningsHtml, "\n", paste(coupletHtml, collapse = "\n"), "\n", if (length(taxonHtml) > 0) "

      Taxa

      \n" else "", - paste(taxonHtml, collapse = "\n"), "\n", glossaryHtml(features, leads, coupletId, images), "\n
      \n
      \n", - "

      ", length(check$couplets), if (nodeLabel == "Couplet") " couplets, " else " steps, ", - length(taxonNames), if (nodeLabel == "Couplet") " taxa. " else " possible results. ", - "Press a, b (or 1, 2) to choose a lead. ", - "Generated by the dimoose R package.

      \n", + paste(taxonHtml, collapse = "\n"), "\n", matrixHtml, glossaryHtml(features, leads, coupletId, images), "\n\n
      \n", + "

      ", + if (hasKey) paste0(length(check$couplets), if (nodeLabel == "Couplet") " couplets, " else " steps, ", + length(taxonNames), if (nodeLabel == "Couplet") " taxa. " else " possible results. ") + else paste0(length(matrix$characters), " characters, ", length(matrix$taxa), " taxa. "), + if (hasKey) "Press a, b (or 1, 2) to choose a lead, u if you are not sure. " else "", + foot, "Generated by the dimoose R package.

      \n", "\n\n\n" ) } diff --git a/R/generate.R b/R/generate.R index dac0df9..b37f854 100644 --- a/R/generate.R +++ b/R/generate.R @@ -3,6 +3,16 @@ #' Fits a classification tree (or tree ensemble) with the taxon column as the #' response and every other column as a feature. #' +#' The rpart defaults are set for identification data, which usually has one +#' row per taxon: `rpart.control(minsplit = 2, minbucket = 1, cp = 0)`, so the +#' tree keeps splitting until every taxon is separated. (rpart's own defaults, +#' `minsplit = 20, minbucket = 7, cp = 0.01`, make no split at all on such a +#' matrix.) With many specimens per taxon pass your own `control` in `params` +#' to get a smaller tree, or just the settings to change, e.g. +#' `params = list(cp = 0.01)` or `params = list(maxdepth = 3)`. [keyFromRpart()] turns the tree into a key; +#' [keyFromMatrix()] goes from matrix to key in one step and handles taxa that +#' are variable for a character. +#' #' @param data A data frame containing the feature matrix. #' @param target_col Name of the target/response column. #' @param method `"rpart"`, `"randomForest"` (requires the 'randomForest' @@ -11,16 +21,17 @@ #' `"bernoulli"`). #' @param params Optional list of arguments passed to the fitting function, #' overriding the defaults. -#' @return A fitted `rpart`, `randomForest` or `gbm` object. +#' @return A fitted `rpart`, `randomForest` or `gbm` object. For the last two +#' the `call` is the call to `generateTree()`. #' @examples #' features <- data.frame( -#' family = factor(c("A", "B", "C", "A", "B", "C")), -#' fin = factor(c("x", "y", "y", "x", "y", "y")), -#' head = factor(c("p", "p", "q", "p", "p", "q")) -#' ) -#' generateTree(features, "family", -#' params = list(control = rpart::rpart.control(minsplit = 2, minbucket = 1)) +#' family = factor(c("A", "B", "C")), +#' fin = factor(c("x", "y", "y")), +#' head = factor(c("p", "p", "q")) #' ) +#' fit <- generateTree(features, "family") +#' fit +#' keyFromRpart(fit)$leads #' @export generateTree <- function(data, target_col, method = c("rpart", "randomForest", "gbm"), params = list()) { @@ -37,18 +48,34 @@ generateTree <- function(data, target_col, method = c("rpart", "randomForest", " # Backticks keep non-syntactic names such as "Growth at 3% NaCl" intact feature_cols <- setdiff(names(data), target_col) + if (length(feature_cols) == 0) { + stop("data has no feature columns besides target_col", call. = FALSE) + } formula <- stats::reformulate( termlabels = paste0("`", feature_cols, "`"), response = as.name(target_col) ) - switch(method, + if (nrow(data) == 0) stop("data has no rows", call. = FALSE) + if (method == "rpart" && identical(if (is.null(params[["method"]])) "class" else params[["method"]], "class") && + length(unique(stats::na.omit(data[[target_col]]))) < 2) { + stop("target_col must hold at least two different taxa", call. = FALSE) + } + + fit <- switch(method, rpart = { defaults <- list( method = "class", - control = rpart::rpart.control(minsplit = 20, minbucket = 7, cp = 0.01) + control = rpart::rpart.control(minsplit = 2, minbucket = 1, cp = 0) ) - do.call(rpart::rpart, c(list(formula = formula, data = data), utils::modifyList(defaults, params))) + args <- utils::modifyList(defaults, params) + # rpart lets `control` override settings given on their own (cp, + # minsplit, maxdepth ...), and here there is always a `control`, so + # they are put into it + single <- setdiff(intersect(names(args), names(formals(rpart::rpart.control))), "...") + args$control[single] <- args[single] + args[single] <- NULL + do.call(rpart::rpart, c(list(formula = formula, data = data), args)) }, randomForest = { defaults <- list(ntree = 500, mtry = floor(sqrt(length(feature_cols)))) @@ -67,4 +94,10 @@ generateTree <- function(data, target_col, method = c("rpart", "randomForest", " do.call(gbm::gbm, c(list(formula = formula, data = data), utils::modifyList(defaults, params))) } ) + # The fit was made with do.call(), which records the whole data frame (and + # for gbm the fitting function) as its call, and printing a random forest + # or gbm prints that. Record the call to generateTree() instead. An rpart + # fit does not print its call and is returned as rpart made it. + if (method != "rpart") fit$call <- match.call() + fit } diff --git a/R/haplotypes.R b/R/haplotypes.R index 0654641..3e3f2f3 100644 --- a/R/haplotypes.R +++ b/R/haplotypes.R @@ -19,7 +19,7 @@ #' `ancestral` and `derived`. #' @return An integer matrix of 0/1, one row per entry of `haplogroups` (row #' names are the haplogroups) and one column per site. -#' @seealso [recurrentPositions()], [macroHaplogroup()], [simulateExpression()] +#' @seealso [recurrentPositions()], [macroHaplogroup()] #' @examples #' haplotypeMatrix(c("H2a2a1", "U5b", "L0a1b"), sites = c("152", "16311", "16278")) #' @export @@ -131,10 +131,3 @@ macroHaplogroup <- function(haplogroup, level = c("letter", "depth"), depth = 2, }, character(1)) unname(anc[haplogroup]) } - -# Substitution sites on the branches leading into the given haplogroups (the -# markers that define those clades) -cladeMarkerSites <- function(haplogroups, mutations = dimoose::phylotree17_mutations) { - m <- mutations[mutations$haplogroup %in% haplogroups & mutations$type %in% c("transition", "transversion"), ] - unique(mutationSite(m)) -} diff --git a/R/keys.R b/R/keys.R index d871f2f..639af66 100644 --- a/R/keys.R +++ b/R/keys.R @@ -55,22 +55,24 @@ keyFromLeads <- function(leads, desc = NA, meta = NULL, taxa = NULL, features = #' Converts an [rpart::rpart()] classification tree into a dichotomous key: #' every split becomes a couplet with two leads, and every leaf a result. #' Taxa that the tree cannot separate share a leaf and are listed together -#' (`"A / B"`). +#' (`"A / B"`). A taxon rpart could not send down either side of a split, +#' because the split's variable is missing for it, is listed at every result +#' below that split. #' #' @param fit An `rpart` object with `method = "class"`, e.g. from #' [generateTree()]. #' @param desc Title of the key. #' @param meta Key/value metadata data frame. #' @return A [dimoose] object. -#' @seealso [vibrioKey()] +#' @seealso [keyFromMatrix()], which builds a key straight from a character +#' matrix and handles variable taxa; [vibrioKey()] #' @examples #' d <- data.frame( #' taxon = factor(c("A", "B", "C")), #' wings = factor(c("+", "-", "-")), #' spots = factor(c("-", "+", "-")) #' ) -#' fit <- generateTree(d, "taxon", -#' params = list(control = rpart::rpart.control(minsplit = 2, minbucket = 1, cp = 0))) +#' fit <- generateTree(d, "taxon") #' keyFromRpart(fit, "Three taxa")$leads #' @export keyFromRpart <- function(fit, desc = "Key generated from a classification tree", meta = NULL) { @@ -82,8 +84,25 @@ keyFromRpart <- function(fit, desc = "Key generated from a classification tree", leaf <- frame$var == "" if (all(leaf)) stop("The tree has no splits", call. = FALSE) if (is.null(fit$y)) stop("Refit with y = TRUE so leaf members are known", call. = FALSE) - lab <- gsub("=", ": ", labels(fit, minlength = 0L), fixed = TRUE) + # A lead reads "character: state". Only the "=" rpart puts after the + # character's name is replaced, not one in the name or in a state. (Numeric + # splits keep their historical form, "x< 2" and "x>: 2".) + lab <- labels(fit, minlength = 0L) + asked <- as.character(frame$var)[match(node %/% 2L, node)] + byState <- !is.na(asked) & startsWith(lab, paste0(asked, "=")) + lab[byState] <- paste0(asked[byState], ": ", substring(lab[byState], nchar(asked[byState]) + 2L)) + lab[!byState] <- gsub("=", ": ", lab[!byState], fixed = TRUE) members <- split(attr(fit, "ylevels")[fit$y], factor(fit$where, levels = seq_len(nrow(frame)))) + # rpart leaves a row at a split when the split's variable is missing for it + # and no surrogate places it. Such a taxon could be on either side, so it + # is listed at every result below that split. + for (k in which(leaf)) { + up <- node[k] %/% 2L + while (up >= 1L) { + members[[k]] <- c(members[[k]], members[[match(up, node)]]) + up <- up %/% 2L + } + } internal <- node[!leaf] number <- stats::setNames(as.character(seq_along(internal)), internal) @@ -119,18 +138,26 @@ keyFromRpart <- function(fit, desc = "Key generated from a classification tree", #' Johnson (2005), the [arachnida] dataset; 11 couplets, 11 orders #' (Schizomida is reached from two couplets). #' - `vibrioKey()`: a key generated from the [vibrio] consensus matrix of -#' Noguerola & Blanch (2008) with [keyFromRpart()]. Tests scored `+` or -#' `(+)` count as positive and `-` or `(-)` as negative; variable (`v`, -#' `d`) and not determined (`ND`) results are treated as missing, and rpart -#' routes a species past such a test with surrogate splits, so a species -#' that varies for a test appears on only one side of it. Species the tests -#' cannot separate share a result. +#' Noguerola & Blanch (2008) with [keyFromMatrix()] (the matrix itself is +#' [vibrioMatrix()]). Tests scored `+` or `(+)` count as positive and `-` or +#' `(-)` as negative. With `variable = "both"` (the default) a species +#' that is variable for a test (`v`, `d`) is keyed out down both leads of +#' every couplet that uses the test, and so is a species the test was not +#' determined for (`ND`): 92 couplets, 74 species, 14 of them reached at +#' two or three results. With `variable = "missing"` those results are +#' treated as missing and the key is an rpart classification tree +#' ([keyFromRpart()]), which places such a species on one side of the test +#' with surrogate splits: 73 couplets, each species at one result, but a +#' strain showing the species' other result is keyed out wrongly. #' - `montanaKey()`: the native broadleaf trees of Montana, written for #' dimoose (the [montana] dataset); 10 couplets, 11 species, with photos #' from Wikimedia Commons. It is built with [keyFromSpreadsheet()] from #' `inst/extdata/montana/montana-key.csv`, a template for writing your own. #' - [phylotreeKey()]: PhyloTree Build 17. #' +#' @param variable For `vibrioKey()`: `"both"` (default) keys a species +#' that is variable for a test out down both leads; `"missing"` treats +#' variable results as missing. See [keyFromMatrix()]. #' @return A [dimoose] object. #' @references #' Compagno LJV (1998). General remarks. In Carpenter KE, Niem VH (eds.), @@ -150,6 +177,7 @@ keyFromRpart <- function(fit, desc = "Key generated from a classification tree", #' sharks #' summary(arachnidaKey()) #' vibrioKey()$validate() +#' summary(vibrioKey(variable = "missing")) #' \dontrun{ #' exportWizard(sharkKey(), "sharks.html") #' } @@ -186,27 +214,23 @@ arachnidaKey <- function() { #' @rdname exampleKeys #' @export -vibrioKey <- function() { - matrix <- dimoose::vibrio - score <- function(x) { - factor(ifelse(x %in% c("+", "(+)"), "+", ifelse(x %in% c("-", "(-)"), "-", NA)), levels = c("+", "-")) - } - tests <- names(matrix)[-1] - data <- data.frame(species = factor(matrix$species), lapply(matrix[tests], score), check.names = FALSE) - fit <- rpart::rpart( - stats::reformulate(paste0("`", tests, "`"), response = "species"), - data = data, method = "class", y = TRUE, - control = rpart::rpart.control(minsplit = 2, minbucket = 1, cp = 0, xval = 0, maxcompete = 0) - ) - keyFromRpart( - fit, +vibrioKey <- function(variable = c("both", "missing")) { + variable <- match.arg(variable) + keyFromMatrix( + vibrioMatrix(), + variable = variable, desc = "Vibrio species (key generated from the Noguerola & Blanch 2008 matrix)", meta = data.frame( key = "citation", value = paste( "Noguerola I, Blanch AR (2008). Identification of Vibrio spp. with a set of", - "dichotomous keys. J Appl Microbiol 105:175-185. Key generated with rpart;", - "variable and not determined results treated as missing." + "dichotomous keys. J Appl Microbiol 105:175-185.", + if (variable == "both") { + paste("Key generated with dimoose; species with variable or undetermined", + "results follow both leads.") + } else { + "Key generated with rpart; variable and not determined results treated as missing." + } ), stringsAsFactors = FALSE ) @@ -256,7 +280,8 @@ montanaKey <- function() { #' Vibrio consensus identification matrix #' #' Biochemical and growth test results for 74 *Vibrio* taxa from Noguerola & -#' Blanch (2008), one row per taxon. [vibrioKey()] generates a key from it. +#' Blanch (2008), one row per taxon. [vibrioKey()] generates a key from it +#' and [vibrioMatrix()] recodes it for [keyFromMatrix()]. #' #' @format A data frame with 74 rows and 46 columns: `species`, then 45 tests #' coded as in the paper: `+` positive, `-` negative, `(+)` / `(-)` mostly diff --git a/R/lucid.R b/R/lucid.R new file mode 100644 index 0000000..c613e2d --- /dev/null +++ b/R/lucid.R @@ -0,0 +1,612 @@ +# Lucid (lucidcentral.org): matrix keys as Builder CSV, LIF3 and SDD, and +# pathway (dichotomous) keys as Lucid Phoenix XML, CSV, text and SDD. Shared +# helpers (tdwgInput(), tdwgData() ...) are in R/sdd.R. + +# ---- helpers ------------------------------------------------------------------- + +# Which Lucid format a file is in, from its extension and first bytes +tdwgLucidFormat <- function(file) { + if (!file.exists(file)) stop("File ", file, " not found", call. = FALSE) + ext <- tolower(sub("^.*\\.", "", basename(file))) + if (ext %in% c("lif3", "lpxk", "csv", "lif")) return(ext) + if (ext == "txt") return("text") + head <- rawToChar(readBin(file, "raw", min(file.size(file), 4000))) + if (!validUTF8(head)) head <- iconv(head, "latin1", "UTF-8", sub = "") + if (grepl(" Export Key* and *Import Key*, +#' file type CSV). Documented in the Lucid Builder help, which also offers +#' a small example key with its CSV export: the first row holds the +#' entities, every further row one state named `Feature:State` (a +#' colon-separated path through the feature tree), and the cells hold the +#' scores 0 absent, 1 present, 2 rarely present, 3 uncertain, 4 present by +#' misinterpretation, 5 rarely present by misinterpretation, 6 not scoped. +#' A numeric feature is one row named `Feature#` with cells +#' `score type:rare low:low:high:rare high`, or a plain `0` when it is not +#' scored. This is the format `writeLucid()` writes by default, and the +#' documented way to get a matrix **into** Lucid. Use `entities = "rows"` +#' for the Builder's "transposed" variant. +#' - **`"sdd"`**: Lucid exports matrix keys as SDD, the TDWG standard; the +#' file is read with [readSDD()] and written with [writeSDD()]. +#' - **`"lif3"`** (Lucid Interchange Format 3, `.lif3`): an XML file. Lucid +#' publishes no schema or description of it beyond saying that it is XML, +#' so `readLucid()` reads it as far as real exported files show how: +#' features, states and entities (``), the feature and entity trees, +#' and the multistate scores. This was checked against four published keys +#' (Lucid 3 and Lucid 4 exports), one of which was also published as SDD: +#' the two readings agree in all 3454 scores. Those files only use the +#' scores 1 (present) and 3 (uncertain); the scores 2, 4, 5 and 6 are taken +#' to mean what they mean in CSV, as they do in the Builder's own key +#' files, which store scores in the same elements. No real LIF3 file with +#' numeric scores was found: they are read when they are laid out as in the +#' Builder's own key files (`` with `omin`, `nmin`, `nmax`, +#' `omax`), and otherwise left out with a warning. **Units, dependencies, +#' text scores, subsets and media of a LIF3 file are not read** (a warning +#' says so when the file has dependencies or text scores), and dimoose does +#' not write LIF3; export CSV or SDD from the Builder when you need those. +#' - **LIF** (Lucid 2, `.lif`, a sectioned text file) and the Builder's +#' **"XML Dataset"** are not publicly specified; `readLucid()` stops and +#' asks for a CSV or SDD export instead of guessing. +#' +#' @section Scores: +#' By default a taxon gets a state when it is scored present (1), rarely +#' present (2) or uncertain (3) for it; states scored only "by +#' misinterpretation" are left out, because the taxon does not really have +#' them. A feature for which every state of a taxon is uncertain, or nothing +#' is scored, gives `NA`; "not scoped" gives `inapplicable`. `writeLucid()` +#' writes 1 for every state in a cell and 0 otherwise, and 6 for cells equal +#' to `inapplicable`. +#' +#' For numeric features the Lucid help gives the layout of the cell but not +#' the values its score type can take. The one real export at hand uses 1 +#' for a scored range and a plain `0` for a feature that is not scored, and +#' that is all `writeLucid()` writes: `1:rare low:low:high:rare high` for a +#' value or range, `0` for `NA`. A numeric cell equal to `inapplicable` is +#' also written as `0`, with a warning, because no score for "not scoped" is +#' documented for numeric features. On reading, type 1 gives the range, 0 +#' gives `NA`, 6 is taken as "not scoped" by analogy with the multistate +#' scores, and any other type gives `NA` with a warning. +#' +#' Text characters cannot be stored in a Lucid matrix and are left out with a +#' warning. Colons in names are replaced, because Lucid reads them as steps +#' of a path; data that was read from Lucid keeps its paths (the `Path` +#' columns of `characters` and `taxa`). Units of numeric features are not +#' part of the CSV format. No file written by dimoose has been imported +#' into the Lucid Builder. +#' +#' @param file Path of the file to read or write. +#' @param format `"csv"`, `"sdd"` or (reading only) `"lif3"`; by default +#' worked out from the file. +#' @param entities For CSV: whether the entities (taxa) are the `"columns"` +#' (Lucid's default) or the `"rows"` (its "transposed" export). +#' @param scores Which Lucid scores mean that the taxon has the state. +#' @param fullNames If `TRUE`, name characters and taxa by their whole path +#' in Lucid's feature and entity trees (`"Flowers:Petals:Colour"`) rather +#' than by the last step (`"Colour"`). Names that would be ambiguous are +#' always given in full. +#' @inheritParams readSDD +#' @return `readLucid()` returns a `tdwgData` list like [readSDD()]: `matrix`, +#' `characters` (`Character`, `Type`, `States`, `Unit`, `Path`), `taxa` +#' (`Taxon`, `Path`) and `meta`. `writeLucid()` returns `file`, invisibly. +#' @references Lucid Builder help, "CSV (Comma Separated Value) Files" and +#' "Importing and Exporting", . +#' @seealso [readLucidKey()] for Lucid pathway (dichotomous) keys, +#' [readSDD()], [readDELTA()]. +#' @examples +#' f <- system.file("extdata", "tdwg", "bears-lucid.csv", package = "dimoose") +#' d <- readLucid(f) +#' d$matrix +#' d$characters +#' +#' out <- writeLucid(d, tempfile(fileext = ".csv")) +#' readLines(out) +#' identical(readLucid(out)$matrix, d$matrix) +#' @export +readLucid <- function(file, format = NULL, taxon = "Taxon", sep = "/", inapplicable = NA, + entities = c("columns", "rows"), scores = c(1, 2, 3), fullNames = FALSE) { + entities <- match.arg(entities) + if (is.null(format)) format <- tdwgLucidFormat(file) + format <- tolower(format) + inapplicable <- as.character(inapplicable) + if (format == "sdd") { + d <- readSDD(file, taxon = taxon, sep = sep, inapplicable = inapplicable) + d$meta$value[d$meta$key == "format"] <- "Lucid, SDD" + return(d) + } + if (format == "csv") return(tdwgReadLucidCsv(file, taxon, sep, inapplicable, entities, scores, fullNames)) + if (format == "lif3") return(tdwgReadLif3(file, taxon, sep, inapplicable, scores, fullNames)) + if (format == "lpxk") stop("This is a Lucid pathway key; read it with readLucidKey()", call. = FALSE) + if (format == "lif") { + stop("This looks like a LIF file of Lucid 2. That text format is not publicly specified, so dimoose ", + "does not read it: import it into the Lucid Builder and export CSV or SDD", call. = FALSE) + } + stop("Lucid format \"", format, "\" is not supported (the Builder's \"XML Dataset\" is not publicly ", + "specified); export the key as CSV or SDD from the Lucid Builder", call. = FALSE) +} + +tdwgReadLucidCsv <- function(file, taxon, sep, inapplicable, entities, scores, fullNames) { + text <- tdwgReadText(file) + table <- utils::read.csv(text = text, header = FALSE, colClasses = "character", na.strings = character(), + check.names = FALSE, strip.white = TRUE, encoding = "UTF-8") + table <- as.matrix(table) + dimnames(table) <- NULL + if (entities == "rows") table <- t(table) + if (nrow(table) < 2 || ncol(table) < 2) stop("The CSV file holds no scores", call. = FALSE) + table <- table[c(TRUE, nzchar(table[-1, 1])), c(TRUE, nzchar(table[1, -1])), drop = FALSE] + entityPath <- table[1, -1] + rowPath <- table[-1, 1] + cell <- table[-1, -1, drop = FALSE] + + numeric <- endsWith(rowPath, "#") + hasColon <- grepl(":", rowPath, fixed = TRUE) + featurePath <- ifelse(numeric, sub("#$", "", rowPath), ifelse(hasColon, sub(":[^:]*$", "", rowPath), rowPath)) + state <- ifelse(numeric, NA, ifelse(hasColon, trimws(sub("^.*:", "", rowPath)), "present")) + cleaned <- tdwgCleanStates(state[!numeric], sep) + tdwgWarnReplaced(if (is.null(attr(cleaned, "replaced"))) 0 else attr(cleaned, "replaced"), sep) + state[!numeric] <- as.vector(cleaned) + features <- unique(featurePath) + isNumeric <- numeric[match(features, featurePath)] + states <- lapply(features, function(f) state[featurePath == f & !numeric]) + oddTypes <- character() + cells <- lapply(seq_along(features), function(j) { + rows <- which(featurePath == features[j]) + if (isNumeric[j]) { + return(vapply(strsplit(cell[rows[1], ], ":", fixed = TRUE), function(p) { + v <- suppressWarnings(as.numeric(p)) + # a numeric feature that is not scored is a plain 0 + if (!length(v) || is.na(v[1]) || v[1] == 0) return(NA_character_) + if (v[1] == 6) return(inapplicable) + if (v[1] != 1) { + oddTypes <<- c(oddTypes, p[1]) + return(NA_character_) + } + if (length(v) < 5 || anyNA(v[3:4])) return(NA_character_) + tdwgFormatRange(omin = v[2], min = v[3], max = v[4], omax = v[5]) + }, character(1))) + } + score <- suppressWarnings(matrix(as.numeric(cell[rows, , drop = FALSE]), nrow = length(rows))) + score[is.na(score)] <- 0 + tdwgLucidCells(score, states[[j]], scores, sep, inapplicable) + }) + if (length(oddTypes)) { + warning("Numeric score(s) of type ", paste(sort(unique(oddTypes)), collapse = ", "), " read as unknown: the Lucid help ", + "does not say what the score type of a numeric feature can be, and only type 1 is known from a ", + "real export", call. = FALSE) + } + names <- tdwgUnique(tdwgLucidNames(features, fullNames)) + taxa <- tdwgUnique(tdwgLucidNames(entityPath, fullNames)) + characters <- data.frame( + Character = names, Type = ifelse(isNumeric, "real", "categorical"), + States = vapply(states, paste, character(1), collapse = sep), Unit = "", Path = features, + stringsAsFactors = FALSE + ) + taxaInfo <- data.frame(Taxon = taxa, Path = entityPath, stringsAsFactors = FALSE) + names(taxaInfo)[1] <- taxon + tdwgData(tdwgMatrix(taxa, cells, names, taxon), characters, taxaInfo, tdwgMeta(format = "Lucid, CSV")) +} + +# LIF3 as real exported files show it: lists features, states and +# entities; holds the feature tree (states under features) and the +# entity tree; holds, per state, the +# entities scored for it. +tdwgReadLif3 <- function(file, taxon, sep, inapplicable, scores, fullNames) { + doc <- tdwgReadXml(file) + if (xml2::xml_name(xml2::xml_root(doc)) != "lif3_key") stop("This is not a LIF3 file", call. = FALSE) + items <- xml2::xml_find_all(doc, "/lif3_key/items/item") + id <- xml2::xml_attr(items, "item_id") + itemName <- tdwgSquish(xml2::xml_attr(items, "name")) + itemType <- xml2::xml_attr(items, "item_type") + tree <- function(type) { + nodes <- xml2::xml_find_all(doc, sprintf("/lif3_key/trees/tree[@type='%s']/treenode", type)) + data.frame(id = xml2::xml_attr(nodes, "item_id"), parent = xml2::xml_attr(nodes, "parent_id"), + stringsAsFactors = FALSE) + } + path <- function(nodes) { + vapply(nodes$id, function(node) { + steps <- character() + while (!is.na(node) && node %in% nodes$id && length(steps) < 100) { + steps <- c(itemName[match(node, id)], steps) + node <- nodes$parent[match(node, nodes$id)] + } + paste(steps, collapse = ":") + }, character(1)) + } + featureTree <- tree("feature") + entityTree <- tree("entity") + featureTree$type <- itemType[match(featureTree$id, id)] + featureTree$path <- path(featureTree) + entityTree$path <- path(entityTree) + + scoring <- xml2::xml_find_all(doc, "/lif3_key/descriptions/container[@type='normal']/scoring_item") + scored <- lapply(scoring, function(s) { + nodes <- xml2::xml_find_all(s, "./scored_item") + data.frame(state = rep(xml2::xml_attr(s, "item_id"), length(nodes)), entity = xml2::xml_attr(nodes, "item_id"), + value = suppressWarnings(as.numeric(xml2::xml_attr(nodes, "value"))), stringsAsFactors = FALSE) + }) + scored <- if (length(scored)) do.call(rbind, scored) else { + data.frame(state = character(), entity = character(), value = numeric(), stringsAsFactors = FALSE) + } + if (any(!scored$value %in% 0:6)) { + warning("Score(s) other than 0 to 6 in this LIF3 file are not known Lucid scores and are ignored: ", + paste(utils::head(unique(scored$value[!scored$value %in% 0:6]), 5), collapse = ", "), call. = FALSE) + } + # Numeric scores. No real LIF3 file with numeric scores was at hand; Lucid's + # own key files store them as under + # the same scoring_item / scored_item elements, so that layout is read and + # anything else is reported, not guessed at. + numericItems <- xml2::xml_find_all(doc, "/lif3_key/descriptions/container[@type='numeric']/*") + numericData <- xml2::xml_find_all( + doc, "/lif3_key/descriptions/container[@type='numeric']/scoring_item/scored_item/scored_data[@nmin and @nmax]") + measured <- data.frame( + feature = xml2::xml_attr(xml2::xml_parent(xml2::xml_parent(numericData)), "item_id"), + entity = xml2::xml_attr(xml2::xml_parent(numericData), "item_id"), + type = xml2::xml_attr(numericData, "score_type"), stringsAsFactors = FALSE + ) + for (a in c("omin", "nmin", "nmax", "omax")) { + measured[[a]] <- suppressWarnings(as.numeric(xml2::xml_attr(numericData, a))) + } + if (length(numericItems) && !nrow(measured)) { + warning("This LIF3 file has numeric scores in a layout dimoose does not know, so they are not read ", + "(LIF3 is not publicly documented); export CSV or SDD from the Lucid Builder to get them", call. = FALSE) + } + unread <- c(dependencies = "dependency", dependencies = "dependencies", "text scores" = "text") + has <- vapply(unread, function(type) { + length(xml2::xml_find_first(doc, sprintf("/lif3_key/descriptions/container[@type='%s']/*", type))) > 0 + }, logical(1)) + if (any(has)) { + warning("This LIF3 file has ", paste(unique(names(unread)[has]), collapse = " and "), + ", which are not read (LIF3 is not publicly documented); export SDD from the Lucid Builder to get them", + call. = FALSE) + } + + # taxa: the entities at the tips of the entity tree, and any others that are scored + keep <- !entityTree$id %in% entityTree$parent | entityTree$id %in% c(scored$entity, measured$entity) + entity <- entityTree[keep, ] + # characters: features with states under them; a feature with nothing under it is numeric + isState <- featureTree$type == "state" + parentOfState <- unique(featureTree$parent[isState]) + hasChildren <- featureTree$id %in% featureTree$parent + feature <- featureTree[!isState & (featureTree$id %in% parentOfState | !hasChildren), ] + if (!nrow(feature) || !nrow(entity)) stop("The LIF3 file holds no features or no entities", call. = FALSE) + replaced <- 0 + states <- vector("list", nrow(feature)) + cells <- lapply(seq_len(nrow(feature)), function(j) { + stateId <- featureTree$id[isState & featureTree$parent == feature$id[j]] + if (!length(stateId)) { + mine <- measured[measured$feature == feature$id[j] & measured$type %in% "1", ] + at <- match(entity$id, mine$entity) + return(vapply(at, function(k) { + if (is.na(k)) return(NA_character_) + tdwgFormatRange(omin = mine$omin[k], min = mine$nmin[k], max = mine$nmax[k], omax = mine$omax[k]) + }, character(1))) + } + labels <- tdwgCleanStates(itemName[match(stateId, id)], sep) + if (!is.null(attr(labels, "replaced"))) replaced <<- replaced + attr(labels, "replaced") + states[[j]] <<- tdwgUnique(as.vector(labels)) + score <- matrix(0, length(stateId), nrow(entity)) + mine <- scored[scored$state %in% stateId & scored$entity %in% entity$id, ] + score[cbind(match(mine$state, stateId), match(mine$entity, entity$id))] <- mine$value + score[is.na(score)] <- 0 + tdwgLucidCells(score, states[[j]], scores, sep, inapplicable) + }) + tdwgWarnReplaced(replaced, sep) + names <- tdwgUnique(tdwgLucidNames(feature$path, fullNames)) + taxa <- tdwgUnique(tdwgLucidNames(entity$path, fullNames)) + characters <- data.frame( + Character = names, Type = ifelse(lengths(states) > 0, "categorical", "real"), + States = vapply(states, paste, character(1), collapse = sep), Unit = "", Path = feature$path, + stringsAsFactors = FALSE + ) + taxaInfo <- data.frame(Taxon = taxa, Path = entity$path, stringsAsFactors = FALSE) + names(taxaInfo)[1] <- taxon + property <- function(key) { + xml2::xml_attr(xml2::xml_find_first(doc, sprintf("/lif3_key/properties/property[@key='%s']", key)), "value") + } + title <- property("key_title") + if (is.na(title) || !nzchar(title)) title <- gsub("_", " ", property("compile_key_title")) + meta <- tdwgMeta(format = "Lucid, LIF3", title = title, description = property("key_description"), + authors = property("key_authors")) + tdwgData(tdwgMatrix(taxa, cells, names, taxon), characters, taxaInfo, meta) +} + +#' @rdname readLucid +#' @param x A character matrix (data frame), or the list returned by +#' `readLucid()`, [readSDD()], [readDELTA()] or [readXper()]. +#' @param characters Optional data frame describing the characters +#' (`Character`, `Type`, `States`, `Unit`); see [writeSDD()]. +#' @param title Title of the dataset (SDD only). +#' @export +writeLucid <- function(x, file, format = c("csv", "sdd"), characters = NULL, taxon = "Taxon", sep = "/", + inapplicable = NULL, entities = c("columns", "rows"), title = NULL) { + if (identical(tolower(format[1]), "lif3") || identical(tolower(format[1]), "lif")) { + stop("dimoose does not write LIF or LIF3: Lucid publishes no specification of them. ", + "Write \"csv\", which the Lucid Builder imports, or \"sdd\"", call. = FALSE) + } + format <- match.arg(format) + entities <- match.arg(entities) + if (format == "sdd") { + return(writeSDD(x, file, characters = characters, taxon = taxon, title = title, sep = sep, + inapplicable = inapplicable)) + } + input <- tdwgInput(x, characters, taxon, sep, inapplicable) + # the paths through Lucid's feature and entity trees, if the data came from Lucid + path <- function(info, names, key) { + safe <- tdwgLucidSafe(names) + if (!is.data.frame(info) || is.null(info$Path) || is.null(info[[key]])) return(safe) + known <- as.character(info$Path[match(names, info[[key]])]) + ifelse(is.na(known) | !nzchar(known), safe, known) + } + if (is.null(characters) && !is.data.frame(x)) characters <- x$characters + featurePath <- path(characters, input$characters, "Character") + entityPath <- path(input$taxaInfo, input$taxa, taxon) + isText <- input$type == "text" + if (all(isText)) stop("Nothing to write: the matrix has only text characters", call. = FALSE) + if (any(isText)) { + warning("Lucid has no text characters; left out: ", paste(input$characters[isText], collapse = ", "), + call. = FALSE) + } + labels <- character() + rows <- list() + skipped <- unscoped <- character() + for (j in which(!isText)) { + feature <- featurePath[j] + if (input$type[j] %in% c("categorical", "ordered")) { + for (s in seq_along(input$states[[j]])) { + has <- vapply(input$cells[[j]], function(cell) s %in% tdwgCellStates(cell, input$states[[j]], sep), logical(1)) + labels <- c(labels, paste0(feature, ":", tdwgLucidSafe(input$states[[j]][s]))) + rows[[length(rows) + 1]] <- ifelse(input$inapplicable[, j], "6", ifelse(has, "1", "0")) + } + } else { + labels <- c(labels, paste0(feature, "#")) + rows[[length(rows) + 1]] <- vapply(seq_along(input$taxa), function(i) { + cell <- input$cells[[j]][i] + # as the Lucid Builder writes a numeric feature that is not scored + if (input$inapplicable[i, j]) { + unscoped <<- c(unscoped, sprintf("%s, %s", input$taxa[i], input$characters[j])) + return("0") + } + if (is.na(cell)) return("0") + r <- tdwgCellRange(cell, sep) + if (is.null(r)) { + skipped <<- c(skipped, sprintf("%s, %s: \"%s\"", input$taxa[i], input$characters[j], cell)) + return("0") + } + low <- if (is.na(r[["omin"]])) r[["min"]] else r[["omin"]] + high <- if (is.na(r[["omax"]])) r[["max"]] else r[["omax"]] + paste(c("1", vapply(c(low, r[["min"]], r[["max"]], high), tdwgFormatNumber, character(1))), collapse = ":") + }, character(1)) + } + } + if (length(skipped)) { + warning("Not a number or range, so written as not scored: ", paste(utils::head(skipped, 5), collapse = "; "), + if (length(skipped) > 5) sprintf(" and %d more", length(skipped) - 5), call. = FALSE) + } + if (length(unscoped)) { + warning("\"Not applicable\" cannot be written for a numeric feature (Lucid documents no score for it), ", + "so written as not scored: ", paste(utils::head(unscoped, 5), collapse = "; "), + if (length(unscoped) > 5) sprintf(" and %d more", length(unscoped) - 5), call. = FALSE) + } + # quoted as the Lucid Builder writes it: the names are, the first cell and + # the scores are not + quote <- function(x) paste0("\"", gsub("\"", "\"\"", x, fixed = TRUE), "\"") + table <- rbind(c("", quote(entityPath)), cbind(quote(labels), do.call(rbind, rows))) + if (entities == "rows") table <- t(table) + tdwgWriteLines(apply(table, 1, paste, collapse = ","), file) +} + +# ---- pathway keys ------------------------------------------------------------------ + +#' Read and write Lucid pathway (dichotomous) keys +#' +#' The Lucid Builder also makes "pathway" keys: ordinary dichotomous keys of +#' couplets and leads (the successor of the stand-alone Lucid Phoenix). +#' `readLucidKey()` reads one of its exports into a [dimoose] key and +#' `writeLucidKey()` writes a dimoose key in the same forms. All four are +#' described in the Lucid Builder help ("Pathway key exports"): +#' +#' - **`"lpxk"`**, Lucid Phoenix XML: `` with the taxa as +#' `` elements and the couplets as `` elements holding +#' ``s whose `goto` names the next step or the taxon. The step's +#' `text` becomes the couplet's `Question`, an identity's `url` the +#' `TaxonUrl`. Filters (``) and icons are not read or written. +#' - **`"csv"`**: one line per lead, `couplet,"lead text",next couplet or +#' taxon`. +#' - **`"text"`**: the same with blanks instead of commas, as printed in a +#' paper. +#' - **`"sdd"`**: SDD with an identification key; see [readSDDKey()]. +#' +#' In the CSV and text forms the last field is read as a couplet when it +#' matches a couplet number and as a taxon otherwise, so `writeLucidKey()` +#' refuses to write a key in which a taxon is named like a couplet. These +#' two forms hold neither the title of the key nor questions, links or +#' images. The CSV, text and Phoenix XML forms follow the examples printed +#' in the Lucid help; no file exported by the Lucid Builder itself was +#' available to check them against, and no file written by dimoose has been +#' imported into the Builder. +#' +#' @param file Path of the file to read or write. +#' @param format `"lpxk"`, `"csv"`, `"text"` or `"sdd"`; when reading, by +#' default worked out from the file. +#' @param desc Title of the key; by default the title in the file, if any. +#' @param key A [dimoose] key. +#' @return `readLucidKey()` returns a [dimoose] key; `writeLucidKey()` +#' returns `file`, invisibly. +#' @references Lucid Builder help, "Pathway key exports", +#' . +#' @seealso [readLucid()] for Lucid matrix keys, [readSDDKey()], +#' [keyFromSpreadsheet()]. +#' @examples +#' f <- system.file("extdata", "tdwg", "insects.lpxk", package = "dimoose") +#' k <- readLucidKey(f) +#' k +#' k$leads[, c("Statement", "Choice", "Character", "Next", "Taxon")] +#' +#' out <- writeLucidKey(k, tempfile(fileext = ".csv"), format = "csv") +#' readLines(out) +#' @export +readLucidKey <- function(file, format = NULL, desc = NULL) { + if (is.null(format)) format <- tdwgLucidFormat(file) + format <- tolower(format) + if (format == "sdd") return(readSDDKey(file, desc = desc)) + if (format == "lpxk") { + doc <- tdwgReadXml(file) + root <- xml2::xml_root(doc) + if (xml2::xml_name(root) != "PhoenixKey") stop("This is not a Lucid Phoenix XML key", call. = FALSE) + identity <- xml2::xml_find_all(root, "./Identity") + identityId <- xml2::xml_attr(identity, "id") + steps <- xml2::xml_find_all(root, "./Steps/Step") + if (!length(steps)) stop("The key has no steps", call. = FALSE) + stepId <- xml2::xml_attr(steps, "id") + first <- match(xml2::xml_attr(xml2::xml_find_first(root, "./Steps"), "firstStepID"), stepId) + order <- if (is.na(first)) seq_along(steps) else c(first, setdiff(seq_along(steps), first)) + number <- stats::setNames(as.character(seq_along(order)), stepId[order]) + leads <- do.call(rbind, lapply(order, function(s) { + nodes <- xml2::xml_find_all(steps[[s]], "./Lead") + goto <- xml2::xml_attr(nodes, "goto") + goto[is.na(goto)] <- "" + toStep <- goto %in% stepId + who <- match(goto, identityId) + url <- xml2::xml_attr(identity, "url")[who] + question <- xml2::xml_attr(steps[[s]], "text") + data.frame( + Statement = rep(number[[stepId[s]]], length(nodes)), + Choice = if (length(nodes) <= 26) letters[seq_along(nodes)] else as.character(seq_along(nodes)), + Character = tdwgSquish(xml2::xml_text(xml2::xml_find_first(nodes, "./Text"))), + Next = ifelse(toStep, unname(number[goto]), "-"), + Taxon = ifelse(toStep, "", ifelse(is.na(who), goto, tdwgSquish(xml2::xml_attr(identity, "name")[who]))), + Question = rep(if (is.na(question)) "" else tdwgSquish(question), length(nodes)), + TaxonUrl = ifelse(is.na(url), "", url), + stringsAsFactors = FALSE + ) + })) + if (is.null(desc)) desc <- xml2::xml_attr(root, "title") + meta <- tdwgMeta(format = "Lucid Phoenix XML", generator = xml2::xml_attr(root, "CreatedIn")) + } else if (format %in% c("csv", "text")) { + lines <- strsplit(tdwgReadText(file), "\n", fixed = TRUE)[[1]] + lines <- gsub("[\u201c\u201d]", "\"", lines[nzchar(trimws(lines))]) + if (format == "csv") { + table <- utils::read.csv(text = paste(lines, collapse = "\n"), header = FALSE, colClasses = "character", + na.strings = character(), strip.white = TRUE, encoding = "UTF-8") + if (ncol(table) < 3) stop("A Lucid pathway CSV has three columns: couplet, lead, next couplet or taxon", + call. = FALSE) + fields <- data.frame(couplet = table[[1]], lead = table[[2]], goto = table[[3]], stringsAsFactors = FALSE) + } else { + m <- regmatches(lines, regexec("^\\s*(\\S+)\\s+\"(.*)\"\\s*(.*?)\\s*$", lines, perl = TRUE)) + if (any(lengths(m) == 0)) { + stop("Line(s) not of the form 1 \"lead text\" 2 : ", paste(utils::head(which(lengths(m) == 0), 5), collapse = ", "), + call. = FALSE) + } + fields <- data.frame(couplet = vapply(m, `[`, character(1), 2), lead = vapply(m, `[`, character(1), 3), + goto = vapply(m, `[`, character(1), 4), stringsAsFactors = FALSE) + } + fields$couplet <- trimws(fields$couplet) + fields$goto <- trimws(fields$goto) + toCouplet <- fields$goto %in% fields$couplet + choice <- stats::ave(seq_along(fields$couplet), fields$couplet, FUN = seq_along) + leads <- data.frame( + Statement = fields$couplet, Choice = ifelse(choice <= 26, letters[pmin(choice, 26)], as.character(choice)), + Character = tdwgSquish(fields$lead), Next = ifelse(toCouplet, fields$goto, "-"), + Taxon = ifelse(toCouplet, "", fields$goto), stringsAsFactors = FALSE + ) + meta <- tdwgMeta(format = paste("Lucid pathway key,", format)) + } else { + stop("Format \"", format, "\" is not a Lucid pathway key format; use \"lpxk\", \"csv\", \"text\" or \"sdd\"", + call. = FALSE) + } + if (!is.null(leads$Question) && !any(nzchar(leads$Question))) leads$Question <- NULL + if (!is.null(leads$TaxonUrl) && !any(nzchar(leads$TaxonUrl))) leads$TaxonUrl <- NULL + rownames(leads) <- NULL + keyFromLeads(leads, if (is.null(desc) || is.na(desc) || !nzchar(desc)) NA else desc, meta = meta) +} + +#' @rdname readLucidKey +#' @export +writeLucidKey <- function(key, file, format = c("lpxk", "csv", "text", "sdd")) { + format <- match.arg(format) + if (!inherits(key, "dimoose")) stop("`key` must be a dimoose key", call. = FALSE) + if (format == "sdd") return(writeSDDKey(key, file)) + leads <- normalizeLeads(key$leads) + toCouplet <- leads$Next != "-" & leads$Next %in% leads$Statement + if (format %in% c("csv", "text")) { + # the last field of a line is a couplet when it matches a couplet number + clash <- unique(leads$Taxon[!toCouplet & leads$Taxon %in% leads$Statement]) + if (length(clash)) { + stop("Taxon name(s) that are also couplet numbers cannot be told apart in Lucid's ", format, " format: ", + paste(clash, collapse = ", "), "; write \"lpxk\" or \"sdd\" instead", call. = FALSE) + } + quoted <- paste0("\"", gsub("\"", if (format == "csv") "\"\"" else "'", leads$Character, fixed = TRUE), "\"") + goto <- ifelse(toCouplet, leads$Next, leads$Taxon) + if (format == "csv") { + needsQuotes <- grepl("[,\"]", goto) + goto[needsQuotes] <- paste0("\"", gsub("\"", "\"\"", goto[needsQuotes], fixed = TRUE), "\"") + } + return(tdwgWriteLines(paste(leads$Statement, quoted, goto, sep = if (format == "csv") "," else " "), file)) + } + couplets <- unique(leads$Statement) + root <- checkLeads(leads)$root + stepId <- stats::setNames(paste0("s", seq_along(couplets) - 1), couplets) + taxa <- unique(leads$Taxon[!toCouplet & nzchar(leads$Taxon)]) + identityId <- stats::setNames(paste0("i", seq_along(taxa) - 1), taxa) + url <- leads$TaxonUrl[match(taxa, leads$Taxon)] + title <- if (is.null(key$desc) || is.na(key$desc)) "" else as.character(key$desc) + out <- c("", + paste0(""), + paste0(" ")[seq_along(taxa)], + paste0(" ")) + for (couplet in couplets) { + rows <- which(leads$Statement == couplet) + goto <- ifelse(toCouplet[rows], stepId[leads$Next[rows]], + ifelse(nzchar(leads$Taxon[rows]), identityId[leads$Taxon[rows]], "")) + out <- c(out, + paste0(" "), + paste0(" \n ", + tdwgXmlEscape(leads$Character[rows]), "\n "), + " ") + } + tdwgWriteLines(c(out, " ", ""), file) +} diff --git a/R/matrix.R b/R/matrix.R new file mode 100644 index 0000000..b8c11ed --- /dev/null +++ b/R/matrix.R @@ -0,0 +1,681 @@ +#' Build a dimoose key from a character matrix +#' +#' Generates a dichotomous key from a taxon-by-character matrix, the form most +#' identification data is kept in (DELTA, Lucid, SDD, a spreadsheet of test +#' results). Unlike a classification tree, the key is built the way a person +#' writes one: a taxon that is variable for a character is keyed out down both +#' leads of every couplet that uses the character. +#' +#' @section The matrix: +#' A plain data frame (or a character matrix with column names) with one row +#' per taxon: a taxon column and one column per character. Cells are state +#' strings (anything else is converted with `as.character()`). A taxon that +#' is variable (polymorphic) for a character lists its states separated by +#' `/`, e.g. `"+/-"` or `"red/white"`. `NA` or an empty cell means unknown or +#' inapplicable. If a taxon has several rows, they are merged and the taxon +#' takes every state seen in any of them. Characters with fewer than two +#' states among the taxa are dropped. Every column other than `taxon` is taken +#' as a character, so leave out columns of notes. +#' +#' @section Numbers and ranges: +#' A key can only ask about states a specimen either shows or does not, so a +#' measurement is used through the ranges that do not overlap. In a column +#' whose cells are all numbers or ranges, as the readers [readDELTA()], +#' [readSDD()], [readLucid()] and [readXper()] write them (`"3"`, `"4-6"`, +#' `"(1-)2-8(-12)"`, taken from the lowest to the highest number in the +#' cell), ranges that overlap or touch are merged into one state named by its +#' extremes: `"3-5"`, `"5-7"` and `"12-20"` give the two states `"3-7"` and +#' `"12-20"`. A character whose ranges all overlap has one state and is +#' dropped. A message says what was merged or dropped. The cells may end in a +#' unit if it is the same in every cell of the column (`"2-8 mm"`, +#' `"5-12 mm"`). Negative numbers are +#' not understood (a `-` is read as "to"). To key a taxon out on part of an +#' overlapping range, cut the measurement into classes yourself and enter the +#' classes as states (`"3/5"` and `"5/7"` leaflets in the example below). +#' +#' If `characters` has a column `Type`, as the tables of those readers do, +#' characters of type `"text"` are not used, the rule above applies to +#' `"integer"` and `"real"` characters only, and `"categorical"` and +#' `"ordered"` characters are always taken as states. +#' +#' @section How the key is built (`variable = "both"`): +#' Every couplet tests one state of one character against the rest: the first +#' lead reads `"Character: state"`, the second `"Character: other or +#' another"`, naming the other states the taxa still in play may show. A +#' character with three or more states is therefore keyed out over several +#' couplets, and every couplet has exactly two leads. +#' +#' A taxon follows the first lead if it can show the state and the second if +#' it can show any other state not already ruled out, so a variable taxon +#' follows both. So does a taxon whose state is unknown (`NA`), since it +#' cannot be ruled out on either side. The guarantee is: whichever of its +#' states a specimen shows for each character, following the key ends at a +#' result that names its taxon. +#' +#' At each step the couplet is chosen like this. For every state of every +#' character, count the taxa that follow the first lead only (`a`) and the +#' second lead only (`b`). The couplet separates `a * b` pairs of taxa; taxa +#' that follow both leads separate nothing. The split with the largest +#' `a * b / Cost` is taken; ties go to the character that comes first in the +#' matrix, then to the state that appears first in its column. With no +#' `Cost`, every character costs 1. A character with `Cost` 2 is thus chosen +#' over one with `Cost` 1 only if it separates more than twice as many pairs. +#' +#' If no split separates a pair, the taxa that are left overlap: one shows +#' `"+"` and another `"+/-"`, or one has 3 to 5 leaflets and another 5 to 7. +#' A couplet can still rule taxa out on one side (`"-"` can only be the +#' second taxon), so the split with the largest `(a + b) / Cost` is taken, +#' provided some taxon is known to show the state and some taxon is known to +#' show another. When no such split is left either, the remaining taxa share +#' a result, written `"A / B"`: with the states observed they cannot be told +#' apart. +#' +#' A group of taxa that is reached by several routes with the same states +#' still open is keyed out once, and couplets that come out the same lead for +#' lead are merged, so a couplet may be the target of more than one lead, and +#' a variable taxon appears at more than one result. +#' +#' If `characters` has a column `InapplicableIf` (`"Other character=state"` +#' or `"Other character=state/state"`, several rules separated by `;`, as +#' written by [readSDD()] and [readDELTA()]), a character is not asked about +#' while a taxon still in play may show one of those states of the other +#' character: the key asks whether there is an aerial stem before it asks +#' whether the stem is hairy. The rule is dropped where it would leave no +#' couplet at all. +#' +#' @section Size of the key: +#' Because variable and unknown taxa follow both leads, the key grows with +#' the number of such cells. Random two-state matrices of 200 taxa and 60 +#' characters gave 199 couplets with no unknown cells, about 550 with 30% +#' unknown and about 3400 with 50%. A matrix in which most characters are +#' known for only a few taxa can need a number of couplets that doubles with +#' every character; `maxCouplets` stops such a key with an error rather than +#' running out of memory, and a key with more than ten couplets per taxon +#' comes with a warning. Leave out the characters that are unknown for most +#' taxa, or use `variable = "missing"`. +#' +#' @section `variable = "missing"`: +#' Variable cells are treated as unknown and the key is the classification +#' tree fitted by [rpart::rpart()] (through [keyFromRpart()]), with `Cost` +#' passed as rpart's `cost`. Each taxon then appears at one result, but rpart +#' places a taxon it has no state for with surrogate splits, so a specimen +#' showing the taxon's other state is keyed out wrongly. A taxon rpart cannot +#' place at a split at all is listed at every result below that split (a +#' message says how many such taxa there are). The +#' key is smaller; use it when that matters more than the guarantee above. A +#' lead may name several states (`"Colour: red,white"`). `InapplicableIf` is +#' not used. +#' +#' @param matrix A character matrix: a data frame with one row per taxon (see +#' 'The matrix'), e.g. the `matrix` of [readDELTA()] or [readSDD()]. +#' @param taxon Name of the column holding the taxon names. +#' @param characters Optional data frame of character metadata with a column +#' `Character` (matching column names of `matrix`) and any of `Cost` +#' (positive number, lower means easier to observe; missing or blank means +#' 1), `Season` (seasons or conditions in which the character can be +#' observed, separated by `,`, `;` or `/`; blank, `"all"`, `"all year"` or +#' `"always"` means always), `Needs` (free +#' text such as `"hand lens"`, copied to the leads), `Type` (see 'Numbers +#' and ranges') and `InapplicableIf` (see 'How the key is built'). The +#' `characters` table of [readDELTA()], [readSDD()], [readLucid()] or +#' [readXper()] can be passed as it is. Characters not listed cost 1 and +#' can always be observed; rows for characters that are not in `matrix` are +#' ignored (with a warning if no row matches). If a character has several +#' rows the first is used, with a warning. +#' @param season Optional character vector. Only characters whose `Season` is +#' blank or includes one of these (ignoring case) are used, e.g. +#' `season = "winter"` for a bark and twig key. +#' @param variable `"both"` (default) sends a variable taxon down both leads; +#' `"missing"` treats variable cells as unknown and fits a classification +#' tree. +#' @param desc Title of the key. +#' @param meta Key/value metadata data frame. +#' @param maxCouplets For `variable = "both"`: give up with an error once the +#' key has more couplets than this (see 'Size of the key'). +#' @return A [dimoose] object. With `variable = "both"` its leads also carry +#' `Question` (the character's name), `MatrixCharacter` and `MatrixStates` +#' (the character and the `/`-separated states the lead accepts) and, if +#' `characters` has it, `Needs`. +#' @seealso [vibrioKey()], [vibrioMatrix()], [keyFromRpart()], [generateTree()] +#' @examples +#' # Some of Montana's broadleaf trees (see montanaKey() for the key written +#' # by hand). Box elder has 3 to 5 leaflets and green ash 5 to 7, so a leaf +#' # with 5 could be either. +#' trees <- data.frame( +#' Taxon = c("Box elder", "Green ash", "Rocky Mountain maple", "Bur oak", +#' "Quaking aspen", "Paper birch", "Water birch"), +#' `Buds and leaves` = c("opposite", "opposite", "opposite", "alternate", +#' "alternate", "alternate", "alternate"), +#' `Leaf type` = c("compound", "compound", "simple", "simple", "simple", +#' "simple", "simple"), +#' Leaflets = c("3/5", "5/7", NA, NA, NA, NA, NA), +#' `Leaf lobes` = c(NA, NA, "lobed", "lobed", "not lobed", "not lobed", +#' "not lobed"), +#' Bark = c(NA, NA, NA, NA, "smooth and pale", "white and peeling", +#' "gray to brown"), +#' check.names = FALSE +#' ) +#' k <- keyFromMatrix(trees, desc = "Some Montana trees") +#' k$leads[c("Statement", "Choice", "Character", "Next", "Taxon")] +#' +#' # Leaves are easy to see but only there in summer; bud arrangement needs a +#' # closer look but works all year +#' characters <- data.frame( +#' Character = c("Buds and leaves", "Leaf type", "Leaflets", "Leaf lobes", "Bark"), +#' Cost = c(2, 1, 1, 1, 1), +#' Season = c("", "summer", "summer", "summer", ""), +#' Needs = c("a twig in the hand", "", "", "", "") +#' ) +#' keyFromMatrix(trees, characters = characters)$leads$Character +#' +#' # A winter key: what bark and buds cannot separate shares a result +#' winter <- keyFromMatrix(trees, characters = characters, season = "winter") +#' winter$leads[c("Character", "Taxon")] +#' +#' # A matrix read from a DELTA data set, with its character table. Body +#' # length is used because the three ranges do not overlap; the comments are +#' # text and are left out. +#' beetles <- readDELTA(system.file("extdata", "tdwg", "beetles-delta", package = "dimoose")) +#' keyFromMatrix(beetles$matrix, characters = beetles$characters)$leads[c("Character", "Taxon")] +#' @export +keyFromMatrix <- function(matrix, taxon = "Taxon", characters = NULL, season = NULL, + variable = c("both", "missing"), + desc = "Key generated from a character matrix", meta = NULL, + maxCouplets = 10000) { + variable <- match.arg(variable) + if (!is.numeric(maxCouplets) || length(maxCouplets) != 1 || is.na(maxCouplets) || maxCouplets < 1) { + stop("`maxCouplets` must be a positive number", call. = FALSE) + } + if (!is.null(characters) && (!is.data.frame(characters) || !"Character" %in% names(characters))) { + stop("`characters` must be a data frame with a column `Character`", call. = FALSE) + } + m <- genParseMatrix(matrix, taxon) + m <- genTypedStates(m, characters) + info <- genCharacterInfo(m, characters, season) + if (variable == "missing") { + return(genRpartKey(m, info, desc, meta)) + } + keyFromLeads(genPartition(m, info, maxCouplets), desc, meta) +} + +#' The vibrio dataset as a character matrix +#' +#' Recodes the [vibrio] consensus matrix of Noguerola & Blanch (2008) into the +#' character matrix [keyFromMatrix()] takes: `+` and `(+)` (mostly positive) +#' become `"+"`, `-` and `(-)` become `"-"`, the variable results `v` and `d` +#' become `"+/-"`, and `ND` (not determined) and the one blank cell become +#' `NA`. +#' +#' @return A data frame with 74 rows: `Taxon`, then the 45 tests. +#' @seealso [vibrioKey()] +#' @examples +#' m <- vibrioMatrix() +#' m[1:4, 1:4] +#' table(unlist(m[-1]), useNA = "ifany") +#' @export +vibrioMatrix <- function() { + raw <- dimoose::vibrio + score <- function(x) { + ifelse(x %in% c("+", "(+)"), "+", + ifelse(x %in% c("-", "(-)"), "-", + ifelse(x %in% c("v", "d"), "+/-", NA_character_))) + } + data.frame(Taxon = raw$species, lapply(raw[-1], score), check.names = FALSE, stringsAsFactors = FALSE) +} + +# ---- matrix helpers ---------------------------------------------------------- + +# Checks a character matrix and returns list(taxa, characters, states), where +# states[[character]][[i]] holds the states of taxon i (character(0) if +# unknown). Rows of the same taxon are merged. +genParseMatrix <- function(matrix, taxon = "Taxon") { + if (is.matrix(matrix) && !is.null(colnames(matrix))) { + matrix <- as.data.frame(matrix, stringsAsFactors = FALSE, check.names = FALSE) + } + if (!is.data.frame(matrix)) stop("`matrix` must be a data frame", call. = FALSE) + if (anyDuplicated(names(matrix))) { + stop("`matrix` has more than one column named: ", + paste(unique(names(matrix)[duplicated(names(matrix))]), collapse = ", "), call. = FALSE) + } + if (!is.character(taxon) || length(taxon) != 1 || !taxon %in% names(matrix)) { + stop("`taxon` must be the name of a column of `matrix`", call. = FALSE) + } + name <- trimws(as.character(matrix[[taxon]])) + if (anyNA(name) || any(!nzchar(name))) { + stop("`matrix` has rows with no taxon name", call. = FALSE) + } + chars <- setdiff(names(matrix), taxon) + if (length(chars) == 0) stop("`matrix` has no character columns", call. = FALSE) + nested <- chars[!vapply(chars, function(ch) is.atomic(matrix[[ch]]) || is.factor(matrix[[ch]]), logical(1))] + if (length(nested)) { + stop("`matrix` column(s) must hold one value per row: ", paste(nested, collapse = ", "), call. = FALSE) + } + taxa <- unique(name) + row <- match(name, taxa) + states <- lapply(chars, function(ch) { + cells <- strsplit(as.character(matrix[[ch]]), "/", fixed = TRUE) + cells <- lapply(cells, function(s) { + s <- trimws(s) + s[!is.na(s) & nzchar(s)] + }) + unname(lapply(split(cells, factor(row, levels = seq_along(taxa))), function(x) unique(unlist(x)))) + }) + names(states) <- chars + list(taxa = taxa, characters = chars, states = states) +} + +# Which characters to use and what they cost: a data frame with Character, +# Cost and Needs, in matrix order. Applies `season` and drops characters with +# fewer than two states. +genCharacterInfo <- function(m, characters = NULL, season = NULL) { + info <- data.frame(Character = m$characters, Cost = rep(1, length(m$characters)), Season = "", Needs = "", + InapplicableIf = "", stringsAsFactors = FALSE) + if (!is.null(characters)) { + if (!is.data.frame(characters) || !"Character" %in% names(characters)) { + stop("`characters` must be a data frame with a column `Character`", call. = FALSE) + } + listed <- trimws(as.character(characters[["Character"]])) + at <- match(info$Character, listed) + twice <- unique(listed[duplicated(listed) & listed %in% info$Character]) + if (length(twice)) { + warning("`characters` has more than one row for: ", paste(twice, collapse = ", "), + ". The first row of each is used.", call. = FALSE) + } + if (nrow(characters) > 0 && nrow(info) > 0 && all(is.na(at)) && !any(listed %in% m$dropped)) { + warning("No row of `characters` names a column of `matrix`, so it has no effect", call. = FALSE) + } + if ("Cost" %in% names(characters)) { + given <- trimws(as.character(characters[["Cost"]])) + given[!is.na(given) & !nzchar(given)] <- NA + cost <- suppressWarnings(as.numeric(given)) + if (any(!is.na(cost) & (cost <= 0 | !is.finite(cost))) || any(is.na(cost) != is.na(given))) { + stop("`Cost` in `characters` must be positive numbers", call. = FALSE) + } + info$Cost <- ifelse(is.na(cost[at]), 1, cost[at]) + } + for (col in intersect(c("Season", "Needs", "InapplicableIf"), names(characters))) { + x <- trimws(as.character(characters[[col]]))[at] + info[[col]] <- ifelse(is.na(x), "", x) + } + } + if (!is.null(season)) { + if (!is.character(season) || length(season) == 0 || anyNA(season) || any(!nzchar(trimws(season)))) { + stop("`season` must be one or more season names", call. = FALSE) + } + if (is.null(characters) || !"Season" %in% names(characters)) { + warning("`season` is ignored: `characters` has no `Season` column", call. = FALSE) + } else { + wanted <- tolower(trimws(as.character(season))) + always <- c("all", "all year", "all seasons", "always", "any", "year-round", "year round") + observable <- vapply(strsplit(tolower(info$Season), "[,;/]"), function(s) { + s <- trimws(s) + s <- s[nzchar(s)] + length(s) == 0 || any(s %in% c(wanted, always)) + }, logical(1)) + info <- info[observable, , drop = FALSE] + if (nrow(info) == 0) { + stop("No character can be observed in season: ", paste(season, collapse = ", "), call. = FALSE) + } + } + } + informative <- vapply(info$Character, function(ch) length(unique(unlist(m$states[[ch]]))) > 1, logical(1)) + info <- info[informative, , drop = FALSE] + rownames(info) <- NULL + info +} + +# The lead table of the key for `variable = "both"`: recursive partition in +# which a taxon follows every lead it could show. A sub-key is identified by +# the taxa still in play and the character states not yet ruled out on the way +# there; each is keyed out once (`couplets` remembers them) and reused. +genPartition <- function(m, info, maxCouplets = 10000) { + n <- length(m$taxa) + if (n < 2) stop("`matrix` must have at least two taxa", call. = FALSE) + + # One candidate split per character state (a "column"). has[i, j]: taxon i + # is known to show state j; known[i, j]: its state for that character is + # known at all. + colChar <- integer() + colState <- character() + has <- list() + known <- list() + for (k in seq_len(nrow(info))) { + st <- m$states[[info$Character[k]]] + for (s in unique(unlist(st))) { + colChar <- c(colChar, k) + colState <- c(colState, s) + has[[length(has) + 1]] <- vapply(st, function(x) s %in% x, logical(1)) + known[[length(known) + 1]] <- lengths(st) > 0 + } + } + if (length(has) == 0) stop("No character separates the taxa", call. = FALSE) + has <- do.call(cbind, has) + known <- do.call(cbind, known) + cost <- info$Cost[colChar] + # sameChar[j, k]: column j belongs to character k + sameChar <- outer(colChar, seq_len(nrow(info)), "==") * 1 + # blockers[[k]]: the columns (states of another character) that make + # character k inapplicable + blockers <- genBlockers(info, colChar, colState) + dependent <- which(lengths(blockers) > 0) + # A sub-key's name: which taxa and which columns, as hex digits (a plain + # list of numbers is too long a name for an environment with many taxa) + bits <- function(set, size) { + x <- logical(8 * ceiling(size / 8)) + x[set] <- TRUE + paste(as.character(packBits(x)), collapse = "") + } + + couplets <- new.env(parent = emptyenv()) + rows <- list() + + # Leads still to be followed: list(idx, live, slot, side). Kept as a stack + # rather than followed by recursion, which a key hundreds of couplets deep + # would overflow. The first lead of a couplet is followed to its end before + # the second, so couplets are numbered in the order a reader meets them. + todo <- list() + + # Returns list(Next, Taxon) for the lead that arrives at taxa `idx` with the + # states `live` (logical, one per column) not yet ruled out. If that takes + # a new couplet, its two leads are added to `todo`. + visit <- function(idx, live) { + result <- function() list(Next = "-", Taxon = paste(sort(m$taxa[idx]), collapse = " / ")) + if (length(idx) == 1) return(result()) + shows <- has[idx, , drop = FALSE] + shows[, !live] <- FALSE + # how many of its character's remaining states each taxon shows + nStates <- (shows %*% sameChar)[, colChar, drop = FALSE] + only <- shows & nStates == 1 + never <- known[idx, , drop = FALSE] & !has[idx, , drop = FALSE] + a <- colSums(only) + b <- colSums(never) + # A couplet must name a state some taxon shows, leave another state for + # its second lead, and rule out at least one taxon on one side + usable <- live & colSums(shows) > 0 & colSums(nStates - shows) > 0 & (a > 0 | b > 0) + if (!any(usable)) return(result()) + # A character that does not apply to a taxon still in play has to wait, + # unless nothing else is left to ask + blocked <- dependent[vapply(blockers[dependent], function(cols) any(shows[, cols]), logical(1))] + if (length(blocked)) { + waiting <- usable & !(colChar %in% blocked) + if (any(waiting)) usable <- waiting else blocked <- integer() + } + # Only characters with two or more states still shown can be asked about + # from here on, so they are all that tells this sub-key from another + open <- ((colSums(shows) > 0) %*% sameChar)[colChar] > 1 + id <- paste(bits(idx, n), bits(which(live & open), length(live)), paste(blocked, collapse = ",")) + if (!is.null(couplets[[id]])) return(list(Next = couplets[[id]], Taxon = "")) + + score <- ifelse(usable, a * b / cost, -1) + if (max(score) <= 0) score <- ifelse(usable, (a + b) / cost, -1) + j <- which.max(score) + k <- colChar[j] + + slot <- length(rows) + 1L + if (slot > maxCouplets) { + stop("The key has more than ", maxCouplets, " couplets and was given up. A taxon with a variable or ", + "unknown state follows both leads, so a matrix with many such cells needs a very large key. ", + "Leave out characters that are unknown for most taxa, use variable = \"missing\", ", + "or raise `maxCouplets`.", call. = FALSE) + } + number <- as.character(slot) + couplets[[id]] <- number + first <- !never[, j] + second <- !only[, j] + # The second lead takes every other state its taxa may show: all that are + # left if one of them is unknown for the character + others <- live & colChar == k + others[j] <- FALSE + if (all(known[idx[second], j])) others <- others & colSums(shows[second, , drop = FALSE]) > 0 + rows[[slot]] <<- list( + Statement = number, Choice = c("a", "b"), + Character = paste0(info$Character[k], ": ", c(colState[j], paste(colState[others], collapse = " or "))), + Next = c("", ""), Taxon = c("", ""), + Question = info$Character[k], + MatrixCharacter = info$Character[k], + MatrixStates = c(colState[j], paste(colState[others], collapse = "/")), + Needs = info$Needs[k] + ) + liveSecond <- live + liveSecond[j] <- FALSE + todo[[length(todo) + 1]] <<- list(idx = idx[second], live = liveSecond, slot = slot, side = 2L) + todo[[length(todo) + 1]] <<- list(idx = idx[first], live = live & colChar != k, slot = slot, side = 1L) + list(Next = number, Taxon = "") + } + + root <- visit(seq_len(n), rep(TRUE, ncol(has))) + while (length(todo)) { + lead <- todo[[length(todo)]] + todo[[length(todo)]] <- NULL + end <- visit(lead$idx, lead$live) + rows[[lead$slot]]$Next[lead$side] <- end$Next + rows[[lead$slot]]$Taxon[lead$side] <- end$Taxon + } + if (root$Next == "-") stop("No character separates the taxa", call. = FALSE) + leads <- do.call(rbind, lapply(rows, function(r) as.data.frame(r, stringsAsFactors = FALSE))) + if (!any(nzchar(leads$Needs))) leads$Needs <- NULL + rownames(leads) <- NULL + leads <- genMergeCouplets(leads) + size <- length(unique(leads$Statement)) + if (size > 10 * n) { + warning("The key has ", size, " couplets for ", n, " taxa. A taxon with a variable or unknown state ", + "follows both leads, so a matrix with many such cells gives a large key. Leave out characters ", + "that are unknown for most taxa, or use variable = \"missing\".", call. = FALSE) + } + leads +} + +# Sub-keys reached with different states still open can come out the same, +# lead for lead. Keeps the first of each set of identical couplets, points +# the leads of the others at it (which can make further couplets identical, +# hence the loop) and renumbers the couplets in reading order. +genMergeCouplets <- function(leads) { + repeat { + statement <- unique(leads$Statement) + text <- paste(leads$Choice, leads$Character, leads$Next, leads$Taxon, sep = "\r") + signature <- vapply(split(text, factor(leads$Statement, levels = statement)), paste, character(1), collapse = "\n") + kept <- statement[match(signature, signature)] + if (all(kept == statement)) break + leads <- leads[leads$Statement %in% kept, , drop = FALSE] + onward <- leads$Next != "-" + leads$Next[onward] <- kept[match(leads$Next[onward], statement)] + } + if (nrow(leads) == 2 * length(unique(leads$Statement)) && + identical(unique(leads$Statement), as.character(seq_len(nrow(leads) / 2)))) { + return(leads) + } + # reading order: a couplet, then all that its first lead leads to, then its + # second lead + order <- character() + todo <- leads$Statement[1] + while (length(todo)) { + at <- todo[1] + todo <- todo[-1] + if (at %in% order) next + order <- c(order, at) + nexts <- leads$Next[leads$Statement == at] + todo <- c(nexts[nexts != "-"], todo) + } + leads <- leads[order(match(leads$Statement, order)), , drop = FALSE] + leads$Statement <- as.character(match(leads$Statement, order)) + onward <- leads$Next != "-" + leads$Next[onward] <- as.character(match(leads$Next[onward], order)) + rownames(leads) <- NULL + leads +} + +# For each character of `info`, the columns of the partition (states of +# another character) under which it does not apply, from InapplicableIf rules +# written "Other character=state/state; Another=state". Rules that name a +# character or state the key does not use are skipped. +genBlockers <- function(info, colChar, colState) { + lapply(seq_len(nrow(info)), function(k) { + rules <- trimws(strsplit(info$InapplicableIf[k], ";", fixed = TRUE)[[1]]) + cols <- integer() + for (rule in rules[nzchar(rules)]) { + # the controlling character is the longest name the rule starts with + names <- info$Character[startsWith(rule, paste0(info$Character, "="))] + if (length(names) == 0) next + other <- names[which.max(nchar(names))] + states <- trimws(strsplit(substring(rule, nchar(other) + 2), "/", fixed = TRUE)[[1]]) + cols <- c(cols, which(colChar == match(other, info$Character) & colState %in% states)) + } + unique(cols[colChar[cols] != k]) + }) +} + +# Applies the `Type` column of `characters` and turns numeric ranges into +# states. Text characters are left out; in a numeric character (typed +# "integer" or "real", or untyped with nothing but numbers and ranges in its +# cells) ranges that overlap or touch become one state named by its extremes. +# Returns `m` with `states` recoded, text characters removed (their names in +# `dropped`), and says what it did in a message. +genTypedStates <- function(m, characters = NULL) { + type <- rep("", length(m$characters)) + if (!is.null(characters) && "Type" %in% names(characters)) { + type <- tolower(trimws(as.character(characters[["Type"]])))[match(m$characters, trimws(as.character(characters[["Character"]])))] + type[is.na(type)] <- "" + } + numericTypes <- c("integer", "real", "numeric", "quantitative", "in", "rn") + notes <- character() + text <- type %in% c("text", "te") + for (k in which(!text & type %in% c("", numericTypes))) { + ch <- m$characters[k] + states <- unique(unlist(m$states[[ch]])) + if (length(states) == 0) next + range <- genRange(states) + unit <- "" + if (anyNA(range)) { + # "2-8 mm": numbers followed by the same unit in every cell + measured <- genUnit(states) + if (!is.null(measured) && !anyNA(genRange(measured$value))) { + range <- genRange(measured$value) + unit <- paste0(if (grepl("^[[:alpha:]]", measured$unit)) " ", measured$unit) + } + } + if (anyNA(range)) { + if (type[k] != "") { + text[k] <- TRUE + notes <- c(notes, paste0(" ", ch, ": not used, \"", states[is.na(range[, 1])][1], "\" is not a number or a range")) + } + next + } + # sweep through the ranges from the lowest; a range that starts at or + # below the highest value so far belongs to the same state + o <- order(range[, 1], range[, 2]) + group <- integer(length(states)) + group[o] <- cumsum(c(TRUE, range[o, 1][-1] > cummax(range[o, 2])[-length(o)])) + if (!anyDuplicated(group)) next + label <- vapply(split(seq_along(states), group), function(i) { + if (length(i) == 1) return(states[i]) + ends <- format(c(min(range[i, 1]), max(range[i, 2])), trim = TRUE, drop0trailing = TRUE, digits = 15) + paste0(if (ends[1] == ends[2]) ends[1] else paste(ends, collapse = "-"), unit) + }, character(1)) + m$states[[ch]] <- lapply(m$states[[ch]], function(s) unique(unname(label[as.character(group[match(s, states)])]))) + notes <- c(notes, if (length(label) == 1) { + paste0(" ", ch, ": not used, its ranges all overlap (", label, ")") + } else { + paste0(" ", ch, ": overlapping ranges merged, giving the states ", paste(label, collapse = ", ")) + }) + } + if (any(type %in% c("text", "te"))) { + notes <- c(paste0(" not used, text: ", paste(m$characters[type %in% c("text", "te")], collapse = ", ")), notes) + } + if (length(notes)) message("Characters of the matrix:\n", paste(notes, collapse = "\n")) + m$dropped <- m$characters[text] + m$states <- m$states[!text] + m$characters <- m$characters[!text] + if (length(m$characters) == 0) stop("`matrix` has no character a key can use", call. = FALSE) + m +} + +# The lowest and highest number in each string of `x`, written as a number or +# a range ("3", "4-6", "(1-)2-8(-12)", "2.5 - 4"); NA for anything else. +genRange <- function(x) { + ok <- grepl("^[0-9().\u2013\u2212 -]*[0-9][0-9().\u2013\u2212 -]*$", x) + out <- matrix(NA_real_, length(x), 2) + for (i in which(ok)) { + v <- suppressWarnings(as.numeric(regmatches(x[i], gregexpr("[0-9]+\\.?[0-9]*|\\.[0-9]+", x[i]))[[1]])) + if (length(v) && !anyNA(v)) out[i, ] <- range(v) + } + out +} + +# Splits strings such as "2-8 mm" into the number or range and the unit +# after it. NULL unless every string ends in the same unit. +genUnit <- function(x) { + parts <- regmatches(x, regexec("^(.*[0-9)])[[:space:]]*([[:alpha:]%\u00b0\u00b5][^0-9()]*)$", x)) + if (any(lengths(parts) != 3)) return(NULL) + unit <- trimws(vapply(parts, `[`, character(1), 3)) + if (length(unique(unit)) != 1) return(NULL) + list(value = vapply(parts, `[`, character(1), 2), unit = unit[1]) +} + +# The key for `variable = "missing"`: variable cells become NA and rpart fits +# a classification tree. +genRpartKey <- function(m, info, desc, meta) { + if (length(m$taxa) < 2) stop("`matrix` must have at least two taxa", call. = FALSE) + columns <- lapply(info$Character, function(ch) { + st <- m$states[[ch]] + single <- lengths(st) == 1 + x <- rep(NA_character_, length(st)) + x[single] <- unlist(st[single]) + factor(x, levels = unique(unlist(st))) + }) + names(columns) <- info$Character + # With variable cells gone a character may have no two states left + keep <- vapply(columns, function(x) length(unique(x[!is.na(x)])) > 1, logical(1)) + if (!any(keep)) stop("No character separates the taxa", call. = FALSE) + columns <- columns[keep] + info <- info[keep, , drop = FALSE] + if (any(grepl("`", info$Character, fixed = TRUE))) { + stop("variable = \"missing\" cannot use a character with a backtick in its name: ", + paste(info$Character[grepl("`", info$Character, fixed = TRUE)], collapse = ", "), call. = FALSE) + } + # The response gets a name no character has; `~ .` then takes every other + # column whatever its name + response <- make.unique(c(info$Character, "Taxon..response"))[nrow(info) + 1] + data <- data.frame(factor(m$taxa, levels = m$taxa), columns, check.names = FALSE) + names(data)[1] <- response + fit <- rpart::rpart( + stats::as.formula(paste0("`", response, "` ~ .")), + data = data, method = "class", y = TRUE, cost = info$Cost, + control = rpart::rpart.control(minsplit = 2, minbucket = 1, cp = 0, xval = 0, maxcompete = 0) + ) + if (all(fit$frame$var == "")) stop("No character separates the taxa", call. = FALSE) + key <- keyFromRpart(fit, desc, meta) + # rpart leaves out a taxon with no single known state at all. It could be + # anything, so it is listed at every result. + left <- m$taxa[as.integer(fit$na.action)] + stuck <- sum(fit$frame$var[fit$where] != "") + length(left) + if (stuck > 0) { + message("variable = \"missing\": ", stuck, if (stuck == 1) " taxon" else " taxa", " could not be placed at a ", + "couplet whose character is unknown or variable for ", if (stuck == 1) "it" else "them", + " and ", if (stuck == 1) "is" else "are", " listed at every result below it. ", + "variable = \"both\" keys such taxa out.") + } + if (length(left) == 0) return(key) + leads <- key$leads + for (i in which(leads$Next == "-")) { + leads$Taxon[i] <- paste(sort(c(strsplit(leads$Taxon[i], " / ", fixed = TRUE)[[1]], left)), collapse = " / ") + } + keyFromLeads(leads, desc, meta) +} + +# Follows a key made by keyFromMatrix(variable = "both") for a specimen and +# returns the result it ends at. `observed` is a named character vector: the +# state the specimen shows for each character. NA if the key asks for a +# character that is not in `observed` or a state no lead accepts. +genWalk <- function(leads, observed) { + at <- leads$Statement[1] + repeat { + rows <- which(leads$Statement == at) + state <- observed[leads$MatrixCharacter[rows[1]]] + if (is.na(state)) return(NA_character_) + accepts <- vapply(strsplit(leads$MatrixStates[rows], "/", fixed = TRUE), function(s) state %in% s, logical(1)) + if (!any(accepts)) return(NA_character_) + lead <- rows[which(accepts)[1]] + if (leads$Next[lead] == "-") return(leads$Taxon[lead]) + at <- leads$Next[lead] + } +} diff --git a/R/mecit.R b/R/mecit.R deleted file mode 100644 index ceaa678..0000000 --- a/R/mecit.R +++ /dev/null @@ -1,268 +0,0 @@ -#' Mixed-effects conditional inference trees -#' -#' Fits a tree that partitions observations on candidate split variables (for -#' example which mutations each sample carries, from [haplotypeMatrix()]) -#' while a random effect absorbs differences between clusters (for example -#' macrohaplogroups, from [macroHaplogroup()]). Without the random effect, a -#' tree also splits on variables that merely track the clusters, such as -#' clade-defining markers; with it, those differences are removed before the -#' tree looks for splits. -#' -#' `method = "ctree"` (the default) is the RE-EM algorithm of Sela & Simonoff -#' (2012) with conditional inference trees, as proposed by Fu & Simonoff -#' (2015). It alternates between (1) a [partykit::ctree()] on the response -#' minus the current random-effect contribution and (2) a linear mixed model -#' ([lme4::lmer()]) with one fixed effect per terminal node plus the random -#' effects, until the random effects stop changing. `method = "mob"` uses -#' model-based partitioning through [glmertree::lmertree()] (Fokkema et al. -#' 2018). In both, `ranefstart = TRUE` estimates the random effects from an -#' intercept-only mixed model before the first tree, which keeps that tree from -#' splitting on cluster-level variables. -#' -#' With `cluster = NULL` the result is a plain conditional inference tree, the -#' baseline a mixed-effects tree is compared with. -#' -#' @param y Numeric response, one value per observation. -#' @param partition Matrix or data frame of candidate split variables, one row -#' per observation, with column names (which may be non-syntactic, like -#' `"16311"`). -#' @param cluster Cluster of each observation, or `NULL` for no random -#' effect. -#' @param method `"ctree"` or `"mob"`. -#' @param slope Optional names of `partition` columns to give random slopes -#' within clusters, as in `(1 + slope | cluster)`. -#' @param alpha Significance level for splitting (Bonferroni-adjusted over -#' the candidate variables). -#' @param minbucket Smallest allowed terminal node. -#' @param maxdepth Maximum tree depth. -#' @param ranefstart If `TRUE`, start from random effects estimated without a -#' tree. -#' @param abstol,maxit Convergence tolerance and the maximum number of -#' iterations. For `"ctree"` the tolerance is on the largest change in any -#' observation's random-effect contribution; for `"mob"` it is passed to -#' [glmertree::lmertree()], where it applies to the change in log-likelihood. -#' @return An object of class `mecit`: `tree` (a partykit tree), `lmer` (the -#' final mixed model, or `NULL`), `strata` (data frame of `node`, `mean` -#' and `n`; `mean` is the stratum level net of random effects), `node` -#' (terminal node of each observation), `ranef` (random-effect -#' contribution of each observation), `method`, `iterations` and -#' `converged`. -#' @references -#' Sela RJ, Simonoff JS (2012). RE-EM trees: a data mining approach for -#' longitudinal and clustered data. *Machine Learning* 86, 169-207. -#' \doi{10.1007/s10994-011-5258-3} -#' -#' Fu W, Simonoff JS (2015). Unbiased regression trees for longitudinal and -#' clustered data. *Computational Statistics & Data Analysis* 88, 53-74. -#' \doi{10.1016/j.csda.2015.02.004} -#' -#' Fokkema M, Smits N, Zeileis A, Hothorn T, Kelderman H (2018). Detecting -#' treatment-subgroup interactions in clustered data with generalized linear -#' mixed-effects model trees. *Behavior Research Methods* 50, 2016-2034. -#' \doi{10.3758/s13428-017-0971-x} -#' @seealso [splitVariables()], [keyFromMecit()], [simulateExpression()] -#' @examples -#' \dontrun{ -#' sim <- simulateExpression(n = 600, genes = 6) -#' fit <- mecit(sim$expr[, 1], sim$X, sim$samples$macro) -#' fit -#' exportWizard(keyFromMecit(fit), "mecit.html") -#' } -#' @export -mecit <- function(y, partition, cluster = NULL, method = c("ctree", "mob"), slope = NULL, - alpha = 0.05, minbucket = 20L, maxdepth = Inf, ranefstart = TRUE, - abstol = 1e-3, maxit = 50L) { - method <- match.arg(method) - if (!requireNamespace("partykit", quietly = TRUE)) stop("Install the partykit package to fit trees", call. = FALSE) - if (!is.null(cluster) && !requireNamespace("lme4", quietly = TRUE)) { - stop("Install the lme4 package to fit random effects", call. = FALSE) - } - if (is.null(colnames(partition))) stop("`partition` needs column names", call. = FALSE) - X <- as.data.frame(partition, stringsAsFactors = FALSE, optional = TRUE) - if (length(y) != nrow(X)) stop("`y` and `partition` must have the same number of rows", call. = FALSE) - if (!is.null(cluster) && length(cluster) != nrow(X)) { - stop("`cluster` must have one entry per row of `partition`", call. = FALSE) - } - if (anyNA(y) || anyNA(X) || (!is.null(cluster) && anyNA(cluster))) { - stop("`y`, `partition` and `cluster` must not have missing values", call. = FALSE) - } - orig <- colnames(partition) - if (length(slope) && !all(slope %in% orig)) { - stop("`slope` names column(s) not in `partition`: ", paste(setdiff(slope, orig), collapse = ", "), call. = FALSE) - } - # syntactic names that cannot collide with the internal columns - reserved <- c("y_", "ystar_", "cluster_", "node_") - safe <- make.names(c(reserved, orig), unique = TRUE)[-seq_along(reserved)] - names(X) <- safe - d <- data.frame(y_ = as.numeric(y), X, check.names = FALSE) - treeFormula <- stats::reformulate(paste0("`", safe, "`"), response = "ystar_") - control <- partykit::ctree_control(alpha = alpha, minbucket = minbucket, maxdepth = maxdepth) - out <- list(method = if (is.null(cluster)) "ctree (no random effects)" else method, - names = stats::setNames(orig, safe), slope = slope, lmer = NULL, - iterations = 0L, converged = TRUE) - - if (is.null(cluster)) { - d$ystar_ <- d$y_ - tree <- partykit::ctree(treeFormula, data = d, control = control) - re <- rep(0, nrow(d)) - } else { - d$cluster_ <- factor(cluster) - slopeSafe <- paste0("`", safe[match(slope, orig)], "`") - reTerm <- if (length(slope)) sprintf("(1 + %s | cluster_)", paste(slopeSafe, collapse = " + ")) else "(1 | cluster_)" - # Random slopes are deviations around a fixed slope; without the fixed term - # the random slopes would absorb the whole effect before the tree sees it. - slopeFixed <- if (length(slope)) paste0(" + ", paste(slopeSafe, collapse = " + ")) else "" - reContrib <- function(m) stats::predict(m) - stats::predict(m, re.form = NA) - fitLmer <- function(f) suppressMessages(lme4::lmer(stats::as.formula(f), data = d, REML = TRUE, - control = lme4::lmerControl(check.rankX = "silent.drop.cols"))) - - if (method == "mob") { - if (!requireNamespace("glmertree", quietly = TRUE)) stop("Install the glmertree package for method = \"mob\"", call. = FALSE) - if (length(slope)) stop("Random slopes are supported with method = \"ctree\"", call. = FALSE) - f <- stats::as.formula(paste("y_ ~ 1 | cluster_ |", paste0("`", safe, "`", collapse = " + "))) - fit <- suppressMessages(glmertree::lmertree(f, data = d, ranefstart = if (ranefstart) TRUE else NULL, - abstol = abstol, maxit = maxit, alpha = alpha, minsize = minbucket, maxdepth = maxdepth)) - tree <- fit$tree - out$lmer <- fit$lmer - re <- reContrib(fit$lmer) - out$iterations <- as.integer(fit$iterations) - # lmertree stops on convergence, on oscillation, or at maxit; it does - # not record which, so reaching maxit is reported as not converged - out$converged <- fit$iterations < maxit - } else { - re <- if (ranefstart) reContrib(fitLmer(paste0("y_ ~ 1", slopeFixed, " + ", reTerm))) else rep(0, nrow(d)) - out$converged <- FALSE - for (it in seq_len(maxit)) { - d$ystar_ <- d$y_ - re - tree <- partykit::ctree(treeFormula, data = d, control = control) - d$node_ <- factor(stats::predict(tree, newdata = d, type = "node")) - fixed <- if (nlevels(d$node_) > 1) "y_ ~ 0 + node_" else "y_ ~ 1" - m <- fitLmer(paste0(fixed, slopeFixed, " + ", reTerm)) - newRe <- reContrib(m) - delta <- max(abs(newRe - re)) - re <- newRe - out$iterations <- it - if (delta < abstol) { out$converged <- TRUE; break } - } - out$lmer <- m - } - } - node <- as.integer(stats::predict(tree, newdata = d, type = "node")) - level <- d$y_ - re - out$tree <- tree - out$node <- node - out$ranef <- re - out$strata <- data.frame(node = sort(unique(node)), - mean = as.numeric(tapply(level, node, mean)), - n = as.integer(table(node))) - structure(out, class = "mecit") -} - -#' @export -print.mecit <- function(x, ...) { - sv <- splitVariables(x) - cat(" ", x$method, "\n", sep = "") - cat(sprintf(" %d strata; splits on: %s\n", nrow(x$strata), if (length(sv)) paste(sv, collapse = ", ") else "(none)")) - if (!is.null(x$lmer)) { - k <- nlevels(lme4::getME(x$lmer, "flist")[[1]]) - cat(sprintf(" random effects over %d clusters%s; %s after %d iteration(s)\n", k, - if (length(x$slope)) paste0(" (slopes: ", paste(x$slope, collapse = ", "), ")") else "", - if (x$converged) "converged" else "not converged", x$iterations)) - } - invisible(x) -} - -#' Variables a fitted tree splits on -#' -#' @param fit A [mecit()] fit. -#' @return The names (as given in `partition`) of the variables used in any -#' split, in the order they first appear; `character(0)` if the tree has no -#' splits. -#' @export -splitVariables <- function(fit) { - tree <- fit$tree - inner <- setdiff(partykit::nodeids(tree), partykit::nodeids(tree, terminal = TRUE)) - if (length(inner) == 0) return(character(0)) - varids <- unlist(partykit::nodeapply(tree, ids = inner, - FUN = function(n) partykit::varid_split(partykit::split_node(n)))) - safe <- names(tree$data)[varids] - unname(unique(fit$names[safe])) -} - -#' Turn a mixed-effects tree into a key -#' -#' Each split becomes a couplet and each terminal node a result, labelled -#' with its stratum level and size. Splits on 0/1 variables read as -#' "Carries 16311" / "Does not carry 16311". The leads carry machine-readable -#' tests on the split variables, so [classify()] can place new samples given -#' their [haplotypeMatrix()], and [exportWizard()] can draw the tree. -#' Splits on factor columns become text-only couplets ("tissue is liver or -#' lung"), which a person can follow but [classify()] cannot; the function -#' warns when the key has any. -#' -#' @param fit A [mecit()] fit. -#' @param desc Title of the key. -#' @param digits Decimal places for stratum levels. -#' @return A [dimoose] key. -#' @export -keyFromMecit <- function(fit, desc = NULL, digits = 2) { - tree <- fit$tree - if (length(splitVariables(fit)) == 0) stop("This tree has no splits to turn into a key", call. = FALSE) - data <- tree$data - strata <- fit$strata - leafLabel <- function(id) { - s <- strata[strata$node == id, ] - sprintf("Stratum %d: %s (n = %d)", id, formatC(s$mean, format = "f", digits = digits), s$n) - } - rows <- list(); counter <- 0L; used <- character(); factorSplits <- FALSE - walk <- function(nd) { - if (partykit::is.terminal(nd)) return(list(leaf = leafLabel(partykit::id_node(nd)))) - counter <<- counter + 1L - id <- as.character(counter) - sp <- partykit::split_node(nd) - var <- names(data)[partykit::varid_split(sp)] - orig <- fit$names[[var]] - kids <- partykit::kids_node(nd) - x <- data[[var]] - if (is.numeric(x)) { - b <- partykit::breaks_split(sp) - idx <- partykit::index_split(sp) - if (is.null(idx)) idx <- 1:2 - right <- partykit::right_split(sp) - thr <- if (isFALSE(right)) b - 1e-9 else b - binary <- all(x %in% c(0, 1)) - order <- c(idx[2], idx[1]) # high side first - text <- if (binary) c(paste("Carries", orig), paste("Does not carry", orig)) else - c(sprintf("%s > %s", orig, format(b)), sprintf("%s <= %s", orig, format(b))) - feature <- paste0("var:", orig); test <- c(">", "<="); threshold <- thr - used <<- union(used, orig) - } else { - idx <- partykit::index_split(sp) - lev <- levels(x) - # ordered factors split at a break on the level index - if (is.null(idx)) idx <- ifelse(seq_along(lev) <= partykit::breaks_split(sp), 1L, 2L) - order <- 1:2 - factorSplits <<- TRUE - text <- vapply(1:2, function(k) sprintf("%s is %s", orig, paste(lev[!is.na(idx) & idx == k], collapse = " or ")), "") - feature <- ""; test <- ""; threshold <- NA_real_ - } - built <- lapply(kids[order], walk) - rows[[id]] <<- data.frame( - Statement = id, Choice = c("a", "b"), Character = text, - Next = vapply(built, function(k) if (is.null(k$leaf)) k$id else "-", ""), - Taxon = vapply(built, function(k) if (is.null(k$leaf)) "" else k$leaf, ""), - Question = orig, Feature = feature, Test = test, Threshold = threshold, - stringsAsFactors = FALSE) - list(id = id) - } - walk(partykit::node_party(tree)) - if (factorSplits) warning("The tree splits on factor variables; those couplets are text-only and classify() cannot follow them", call. = FALSE) - leads <- do.call(rbind, rows[order(as.integer(names(rows)))]) - rownames(leads) <- NULL - features <- if (length(used)) featureTable(id = paste0("var:", used), kind = "external", label = used) else NULL - if (is.null(desc)) desc <- paste("Mixed-effects tree:", fit$method) - meta <- data.frame(key = c("node_label", "citation"), - value = c("Split", if (fit$method == "mob") "Fokkema et al. (2018), glmertree" else "Fu & Simonoff (2015), RE-EM with conditional inference trees"), - stringsAsFactors = FALSE) - keyFromLeads(leads, desc, meta, features = features) -} diff --git a/R/onnx.R b/R/onnx.R new file mode 100644 index 0000000..984baad --- /dev/null +++ b/R/onnx.R @@ -0,0 +1,985 @@ +# Vision models on ONNX Runtime (no torch), embeddings saved to files, and +# the files a web page needs to identify photos in the browser. + +# ---- where models live ------------------------------------------------------- + +# Ready-made ONNX copies on the Hugging Face Hub of models dimoose names. +# Checked against the torch models on the example photos (cosine 1.0000 for +# the fp32 and fp16 files). There is no official ONNX copy of BioCLIP: convert +# it once with exportOnnxModel(). +onxKnown <- function() { + c("clip-vit-base-patch32" = "Xenova/clip-vit-base-patch32", + "clip-vit-base-patch16" = "Xenova/clip-vit-base-patch16", + "vit-b-32" = "Xenova/clip-vit-base-patch32", + "vit-b-16" = "Xenova/clip-vit-base-patch16", + "mobileclip-s0" = "Xenova/mobileclip_s0", + "bioclip" = "imageomics/bioclip", + "bioclip-2" = "imageomics/bioclip-2") +} + +#' Folder where dimoose keeps downloaded and converted ONNX models +#' +#' Models are large (tens to hundreds of megabytes), so they are kept outside +#' your project, in R's per-user cache folder for dimoose. Set the option +#' `dimoose.onnx.cache` to use another folder. +#' +#' @return A path. The folder is not created until a model is stored in it. +#' @examples +#' onnxCache() +#' @export +onnxCache <- function() { + getOption("dimoose.onnx.cache", file.path(onxUserCache(), "onnx")) +} + +# R's per-user cache folder for dimoose; R before 4.0 has no R_user_dir(). +onxUserCache <- function() { + if (getRversion() >= "4.0.0") return(tools::R_user_dir("dimoose", "cache")) + file.path(path.expand("~"), ".cache", "R", "dimoose") +} + +# Wrapped so that tests can stand in for them. +onxUv <- function() unname(Sys.which("uv")) +onxSize <- function(path) file.size(path) + +# The folder name of a model in the cache: "Xenova/clip-vit-base-patch32" +# becomes "Xenova--clip-vit-base-patch32". +onxSlug <- function(name) { + gsub("[^A-Za-z0-9._-]+", "-", gsub("/", "--", sub("^hf-hub:", "", name), fixed = TRUE)) +} + +onxIsModelDir <- function(dir) { + dir.exists(dir) && (file.exists(file.path(dir, "dimoose_onnx.json")) || file.exists(file.path(dir, "preprocessor_config.json"))) +} + +# What `name` refers to: list(dir=) for a folder on this computer, or +# list(repo=, dir=) for a Hugging Face repository and its folder in the cache. +onxResolve <- function(name, cache = onnxCache()) { + if (!is.character(name) || length(name) != 1 || is.na(name) || !nzchar(name)) { + stop("`name` must be one model name, folder or Hugging Face repository", call. = FALSE) + } + if (startsWith(name, "local-dir:")) { + dir <- sub("^local-dir:", "", name) + if (!dir.exists(dir)) stop("No such folder: ", dir, call. = FALSE) + return(list(dir = dir)) + } + if (dir.exists(name) && !startsWith(name, "hf-hub:")) return(list(dir = name)) + known <- onxKnown() + repo <- if (tolower(name) %in% names(known)) known[[tolower(name)]] else sub("^hf-hub:", "", name) + dir <- file.path(cache, onxSlug(repo)) + if (!grepl("[/:]", name)) { + # a model converted here with exportOnnxModel(name) comes before the + # ready-made copy of the same name + own <- onxExportDir(name, "openai", cache) + if (onxIsModelDir(own)) return(list(dir = own)) + } + # BioCLIP's repositories hold the PyTorch model only: a folder under their + # name was converted here, and none of its files are on the Hub + if (repo %in% c("imageomics/bioclip", "imageomics/bioclip-2") && onxIsModelDir(dir)) return(list(dir = dir)) + if (grepl("^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$", repo)) return(list(repo = repo, dir = dir)) + if (onxIsModelDir(dir)) return(list(dir = dir)) + stop("There is no ONNX copy of the model \"", name, "\" on this computer (looked in ", dir, "). ", + "`name` is a folder with an ONNX model, a Hugging Face repository (\"/\") or one of: ", + paste(names(known), collapse = ", "), ". Convert any other open_clip model once with exportOnnxModel().", call. = FALSE) +} + +# Download `url` to `dest`. TRUE when the file is there afterwards, FALSE when +# the server has no such file; any other failure is an error. +onxDownload <- function(url, dest) { + dir.create(dirname(dest), recursive = TRUE, showWarnings = FALSE) + part <- paste0(dest, ".part") + on.exit(unlink(part), add = TRUE) + todo <- paste0("The model is fetched from huggingface.co the first time it is used: check the internet connection and ", + "try again (files already fetched are kept). On a computer that cannot reach it, copy the model's folder ", + "from one that can (it is in onnxCache() there) and give the folder as `name`.") + r <- tryCatch(httr::GET(url, httr::write_disk(part, overwrite = TRUE), httr::timeout(3600)), + error = function(e) stop("Could not download ", url, ": ", trimws(conditionMessage(e)), "\n", todo, call. = FALSE)) + code <- httr::status_code(r) + if (code %in% c(401, 403, 404)) return(FALSE) + if (code >= 400) stop("Could not download ", url, " (HTTP ", code, ").\n", todo, call. = FALSE) + # a download that stopped early must not be kept as if it were the file + expected <- suppressWarnings(as.numeric(httr::headers(r)[["content-length"]])) + encoded <- !is.null(httr::headers(r)[["content-encoding"]]) + if (length(expected) == 1 && !is.na(expected) && !encoded && !isTRUE(file.size(part) == expected)) { + stop("The download of ", url, " stopped early (", file.size(part), " of ", expected, " bytes).\n", todo, call. = FALSE) + } + file.rename(part, dest) +} + +onxReadJson <- function(file) { + if (!requireNamespace("jsonlite", quietly = TRUE)) stop("Install the jsonlite package", call. = FALSE) + jsonlite::fromJSON(file, simplifyVector = FALSE) +} + +onxHubUrl <- function(repo, file) paste0("https://huggingface.co/", repo, "/resolve/main/", file) + +# File name endings of the three precisions in the transformers.js layout. +onxHubSuffix <- function(precision) c(fp32 = "", fp16 = "_fp16", int8 = "_quantized")[[precision]] + +# Ready-made int8 image encoders that are poor copies of their model, measured +# on dimoose's example photos against the same repository's fp32 file: +# `stop` for ones that are unusable, `warn` for ones that are rough. +onxInt8Note <- function(repo) { + if (is.null(repo)) return(NULL) + switch(repo, + "Xenova/mobileclip_s0" = list(stop = paste0( + "The int8 image encoder of Xenova/mobileclip_s0 does not work: its embeddings have nothing to do with the ", + "model's (cosine 0.09 on average with the fp32 ones). Use precision = \"fp16\" (23 MB) or \"fp32\" (46 MB).")), + "Xenova/clip-vit-base-patch32" = list(warn = paste0( + "The ready-made int8 image encoder of Xenova/clip-vit-base-patch32 is a rough copy of the model: on dimoose's ", + "example photos its embeddings have a cosine of 0.89 on average, and 0.81 at worst, with the full-precision ones ", + "(the int8 copy exportOnnxModel() writes has 0.998). A key built with it must be followed with it. For a close ", + "int8 copy convert the model yourself, once, with exportOnnxModel(\"ViT-B-32\"); or use precision = \"fp16\".")), + NULL) +} + +# Make sure the files of a Hub model that this call needs are in `dir`, +# downloading the missing ones with `fetch(url, dest)`. Returns the paths of +# the model's files inside the repository (image, text). +onxFetchRepo <- function(repo, dir, precision, textPrecision, text = TRUE, fetch = onxDownload, quiet = FALSE) { + get <- function(file, required = TRUE, say = !quiet) { + dest <- file.path(dir, file) + if (file.exists(dest)) return(TRUE) + if (say) message("Downloading ", repo, "/", file, " (once; kept in ", dir, ")") + ok <- isTRUE(fetch(onxHubUrl(repo, file), dest)) + if (!ok && required) { + stop("The Hugging Face repository ", repo, " has no file ", file, call. = FALSE) + } + ok + } + # which layout the repository has: asked quietly, since one of the two files is not there + if (!onxIsModelDir(dir) && !get("dimoose_onnx.json", required = FALSE, say = FALSE) && + !get("preprocessor_config.json", required = FALSE, say = FALSE)) { + stop("The Hugging Face repository ", repo, " holds no ONNX model that dimoose can read (it has neither ", + "dimoose_onnx.json nor preprocessor_config.json), or it cannot be reached. ", + "Convert the model once with exportOnnxModel(\"hf-hub:", repo, "\"); that needs Python with torch, but only once.", + call. = FALSE) + } + if (file.exists(file.path(dir, "dimoose_onnx.json"))) { + cfg <- onxReadJson(file.path(dir, "dimoose_onnx.json")) + pick <- function(which, p) { + f <- cfg[[which]][[p]]$file + if (is.null(f)) stop(repo, " has no ", p, " ", sub("_", " ", which), "; it has: ", paste(names(cfg[[which]]), collapse = ", "), call. = FALSE) + f + } + image <- pick("image_encoder", precision) + get(image) + textFile <- NULL + if (text && length(cfg$text_encoder)) { + textFile <- pick("text_encoder", textPrecision) + get(textFile) + if (!is.null(cfg$tokenizer)) get(cfg$tokenizer) + } + } else { + get("config.json", required = FALSE, say = FALSE) + image <- paste0("onnx/vision_model", onxHubSuffix(precision), ".onnx") + get(image) + textFile <- NULL + if (text) { + textFile <- paste0("onnx/text_model", onxHubSuffix(textPrecision), ".onnx") + get(textFile) + get("tokenizer.json") + } + } + list(image = image, text = textFile) +} + +# ---- the model --------------------------------------------------------------- + +pyOnnx <- local({ + mod <- NULL + function() { + if (!requireNamespace("reticulate", quietly = TRUE)) { + stop("Install the reticulate package to embed images", call. = FALSE) + } + if (is.null(mod)) { + req <- pythonRequirements("onnx") + if (utils::packageVersion("reticulate") >= "1.41.0" && !reticulate::py_available(initialize = FALSE)) { + reticulate::py_require(req) + } + fail <- function(why) { + stop(onxPythonAdvice(why, req, tryCatch(reticulate::py_config()$python, error = function(e) "unknown")), call. = FALSE) + } + loaded <- tryCatch( + reticulate::import_from_path("dimoose_onnx", path = system.file("python", package = "dimoose"), convert = TRUE), + error = function(e) fail(conditionMessage(e))) + # the module imports onnxruntime and tokenizers only when a model is + # opened; ask now, so that a Python without them gets the advice above + lacking <- onxMissingModules(c("onnxruntime", "tokenizers")) + if (length(lacking)) fail(paste0("it has no Python package ", paste(lacking, collapse = " or "))) + mod <<- loaded + } + mod + } +}) + +# What to tell someone whose Python cannot run the ONNX backend. +onxPythonAdvice <- function(why, req, python) { + paste0("Could not load dimoose's ONNX code with the Python at ", python, ":\n", why, + "\nIt needs the Python packages ", paste(req, collapse = ", "), ". Install them there with\n", + " reticulate::py_install(c(", paste0("\"", req, "\"", collapse = ", "), "))\n", + "or let reticulate provide a Python: restart R without RETICULATE_PYTHON set and without the `python` argument.") +} + +# Which of these Python modules the Python in use lacks. Wrapped for tests. +onxMissingModules <- function(modules) { + modules[!vapply(modules, function(m) isTRUE(tryCatch(reticulate::py_module_available(m), error = function(e) FALSE)), logical(1))] +} + +#' Load a vision model that runs on ONNX Runtime, without PyTorch +#' +#' The light way to embed images and texts: the Python side needs only +#' `onnxruntime`, `numpy`, `pillow` and `tokenizers` (about 150 MB installed, +#' against 0.8 GB to several GB for PyTorch, depending on the platform). The +#' result is used exactly like a [visionModel()]: with [embedImages()], +#' [embedTexts()], [scoreImages()], [suggestSpecies()] and the rest. +#' `visionModel(backend = "onnx")` calls this function. +#' +#' @section Where models come from: +#' `name` is one of +#' +#' * a folder on your computer that holds an ONNX model (also written +#' `"local-dir:"`), in either layout described below; +#' * a Hugging Face repository, `"/"` or +#' `"hf-hub:/"`. The files that are needed are +#' downloaded once into [onnxCache()] and reused; nothing is downloaded when +#' they are already there; +#' * `"clip-vit-base-patch32"` (the default; CLIP ViT-B/32, the same weights as +#' `visionModel()`) or `"clip-vit-base-patch16"`: the ready-made exports +#' `Xenova/clip-vit-base-patch32` and `Xenova/clip-vit-base-patch16` on the +#' Hub; +#' * `"mobileclip-s0"`: Apple's MobileCLIP-S0 (`Xenova/mobileclip_s0`), a +#' small model for phones. Its image encoder is 46 MB at `"fp32"` and 23 MB +#' at `"fp16"`. Its `"int8"` file is refused: its embeddings are wrong +#' (measured: cosine 0.09 on average with the `"fp32"` ones); +#' * `"bioclip"`, `"bioclip-2"` or any other model you have converted with +#' [exportOnnxModel()]. There is no official ONNX copy of BioCLIP on the +#' Hub, so it has to be converted once on a computer with PyTorch; the +#' converted folder can then be copied to computers without it. +#' +#' @section Precision and size: +#' Each encoder comes in up to three precisions. Measured on dimoose's 55 +#' example photos against the PyTorch model (CLIP ViT-B/32 image encoder): +#' +#' | `precision` | image encoder | cosine with PyTorch (lowest) | +#' |---|---|---| +#' | `"fp32"` | 352 MB | 1.0000 | +#' | `"fp16"` | 176 MB | 1.0000 | +#' | `"int8"`, converted by [exportOnnxModel()] | 96 MB | 0.998 | +#' | `"int8"`, `Xenova/clip-vit-base-patch32` (`_quantized`) | 89 MB | 0.81 | +#' +#' `"fp16"` halves the download but runs up to three times slower on a CPU +#' than `"fp32"`. BioCLIP converted by [exportOnnxModel()] is 345, 173 and +#' 89 MB, with cosines of 1.0000, 1.0000 and 0.998 (BioCLIP 2, a larger +#' model, is about 1217, 609 and 310 MB); on the Montana example photos all +#' three precisions name the same species. A key must be followed with the +#' model **and precision** it was built with when the precision is `"int8"`: +#' its embeddings differ slightly from the others'. The ready-made `"int8"` +#' file of `Xenova/clip-vit-base-patch32` is a much rougher copy (0.89 on +#' average), so `onnxModel()` warns when it is used; to get the close one, +#' convert the model yourself with `exportOnnxModel("ViT-B-32")`. A model you +#' have converted is used in place of the ready-made copy of the same name. +#' +#' The patch tokens of an `"int8"` encoder (`embedImages(tiles = 0)`) are +#' less faithful than its image embeddings: with BioCLIP the lowest cosine +#' of a token with the `"fp32"` one was 0.86. Use tiles, or a higher +#' precision, to find sniglets with patch tokens. +#' +#' @section Layouts of a model folder: +#' dimoose's own layout, written by [exportOnnxModel()]: `dimoose_onnx.json` +#' (architecture, image size, preprocessing constants, file names), +#' `image_encoder.onnx`, `text_encoder.onnx`, their `_fp16` and `_int8` +#' copies, and `tokenizer.json`. Its image encoder also returns the model's +#' patch tokens, so `embedImages(tiles = 0)` works. +#' +#' The transformers.js layout of ready-made exports on the Hub: `config.json`, +#' `preprocessor_config.json`, `tokenizer.json`, +#' `onnx/vision_model[_fp16|_quantized].onnx` and +#' `onnx/text_model[_fp16|_quantized].onnx`. These give one embedding per +#' image and no patch tokens: tiles (the default of [embedImages()]) work, +#' `tiles = 0` does not. +#' +#' @param name The model: a folder, a Hugging Face repository or a known name +#' (see below). +#' @param precision `"fp32"`, `"fp16"` or `"int8"`: which copy of the image +#' encoder to use. +#' @param textPrecision The same for the text encoder; by default as +#' `precision`. +#' @param text If `FALSE`, the text encoder is not downloaded (about 250 MB +#' less at `"fp32"`). [embedTexts()] then fails; sniglet keys do not need it. +#' @param cache Folder for downloaded models. +#' @param python Optional path to the Python executable to use (passed to +#' [reticulate::use_python()]). +#' @param threads Number of CPU threads for ONNX Runtime; `0` lets it choose. +#' +#' @section When something goes wrong: +#' * *Could not download ...*: the model is fetched from huggingface.co the +#' first time only. Files that arrived are kept, so calling again continues +#' where it stopped. A computer that cannot reach the Hub can be given the +#' model's folder, copied from [onnxCache()] on one that can, as `name`. +#' * *... is not a readable ONNX model*: a model file is damaged, usually a +#' download or copy that stopped early. Delete the file named in the +#' message and load the model again; a file from the Hub is fetched afresh. +#' * *Could not load dimoose's ONNX code*: the Python in use lacks +#' `onnxruntime` or `tokenizers`. The message gives the +#' `reticulate::py_install()` call that installs them. +#' @param fetch For tests: a function `(url, dest)` that downloads a file and +#' returns `TRUE`, or `FALSE` if there is no such file. +#' @return An object of class `dimooseVisionModel`, as [visionModel()] returns, +#' with a `files` entry: the model's folder (`dir`), its image and text +#' encoder files (`image`, `text`) and, for a model from the Hub, its +#' repository (`repo`) and the web address of the image encoder (`imageUrl`). +#' @seealso [exportOnnxModel()] to convert a model, [exportBrowserModel()] to +#' use one in a web page, [saveEmbeddings()] to need no Python at all. +#' @examples +#' \dontrun{ +#' model <- onnxModel() # CLIP ViT-B/32, downloaded once +#' model <- onnxModel(precision = "fp16") # half the download +#' images <- imageSet(system.file("extdata", "pics", package = "dimoose")) +#' emb <- embedImages(model, images) +#' +#' exportOnnxModel("bioclip") # once, needs PyTorch +#' model <- onnxModel("bioclip") # afterwards, without it +#' } +#' @export +onnxModel <- function(name = "clip-vit-base-patch32", precision = c("fp32", "fp16", "int8"), textPrecision = precision, + text = TRUE, cache = onnxCache(), python = NULL, threads = 0, fetch = NULL) { + precision <- match.arg(precision) + textPrecision <- match.arg(textPrecision, c("fp32", "fp16", "int8")) + if (!requireNamespace("reticulate", quietly = TRUE)) { + stop("Install the reticulate package to embed images", call. = FALSE) + } + if (!is.numeric(threads) || length(threads) != 1 || is.na(threads) || threads < 0) { + stop("`threads` must be a number of CPU threads, or 0 to let ONNX Runtime choose", call. = FALSE) + } + where <- onxResolve(name, cache) + files <- list(dir = where$dir, repo = where$repo) + if (precision == "int8") { + note <- onxInt8Note(where$repo) + if (!is.null(note$stop)) stop(note$stop, call. = FALSE) + if (!is.null(note$warn)) warning(note$warn, call. = FALSE) + } + if (!is.null(where$repo)) { + got <- onxFetchRepo(where$repo, where$dir, precision, textPrecision, text = text, + fetch = if (is.null(fetch)) onxDownload else fetch) + files$imageUrl <- onxHubUrl(where$repo, got$image) + } else if (!onxIsModelDir(where$dir)) { + stop(where$dir, " is not an ONNX model folder: it has neither dimoose_onnx.json (written by exportOnnxModel()) ", + "nor preprocessor_config.json (the transformers.js layout)", call. = FALSE) + } + if (!is.null(python)) reticulate::use_python(python, required = TRUE) + mod <- pyOnnx() + py <- mod$load_model(normalizePath(where$dir), precision = precision, text_precision = textPrecision, threads = as.integer(threads)) + spec <- py$spec + if (!is.null(where$repo)) { + spec$repository <- where$repo + # the ready-made exports are the models open_clip calls ViT-B-32 and + # ViT-B-16 (openai): the same name, so that keys built with one backend + # are followed with the other without a warning + same <- c("Xenova/clip-vit-base-patch32" = "ViT-B-32", "Xenova/clip-vit-base-patch16" = "ViT-B-16") + if (where$repo %in% names(same) && !identical(spec$layout, "dimoose")) spec$arch <- same[[where$repo]] + if (identical(spec$arch, basename(where$dir))) spec$arch <- where$repo # a repository that does not name its model + } + files$image <- py$image_file + files$text <- py$text_file + structure(list(py = py, mod = mod, spec = spec, files = files), class = "dimooseVisionModel") +} + +#' Convert an open_clip model to ONNX +#' +#' Runs dimoose's `export_onnx.py` (in the package's `python` folder) to write +#' a model as ONNX image and text encoders that [onnxModel()] runs without +#' PyTorch. The conversion itself needs PyTorch and open_clip, but only once: +#' the folder it writes can be copied to other computers or uploaded to a +#' Hugging Face repository and used from there. +#' +#' Each file is checked against the PyTorch model as it is written; the +#' script prints the files' sizes and how close their embeddings are. +#' +#' @section Files written: +#' * `dimoose_onnx.json`: architecture, image size, patch size, embedding +#' dimensions, preprocessing (`resize`, `interpolation`, `crop`, `rescale`, +#' `mean`, `std`), the file names and sizes of each precision, and the names +#' of the encoders' inputs and outputs. +#' * `image_encoder.onnx`: input `pixel_values` (`n x 3 x S x S`, float32); +#' outputs `image_embeds` (`n x d`, not normalised) and `patch_embeds` +#' (`n x g*g x d`, the projected patch tokens). +#' * `text_encoder.onnx`: input `input_ids` (`n x 77`, int64); output +#' `text_embeds` (`n x d`, not normalised). +#' * `tokenizer.json`: the tokenizer in the Hugging Face `tokenizers` format, +#' which transformers.js also reads. +#' * with `quantize`: `image_encoder_int8.onnx`, `text_encoder_int8.onnx` +#' (weights as 8-bit integers, about a quarter of the size) and +#' `image_encoder_fp16.onnx`, `text_encoder_fp16.onnx` (16-bit floats, half +#' the size, same embeddings). +#' +#' @param name The model, as for [visionModel()]: an open_clip architecture +#' name, `"bioclip"`, `"bioclip-2"`, `"hf-hub:/"` or +#' `"local-dir:"`. Only models with a vision transformer and +#' open_clip's own CLIP tokenizer can be converted. +#' @param pretrained open_clip's tag for the weights of an architecture. +#' @param weights Local checkpoint file instead of a download. +#' @param dir Folder to write to. By default the model's folder in +#' [onnxCache()], where [onnxModel()] and `visionModel(backend = "onnx")` +#' find it by the same `name`. +#' @param quantize Which smaller copies to write as well: `"int8"`, `"fp16"`, +#' both or neither (`character(0)`). +#' @param python The Python to run the script with; it needs the packages in +#' the package's `python/requirements.txt` and +#' `python/requirements-export.txt`. By default, if the `uv` program is +#' installed, `uv` provides a Python with those packages (downloading them +#' the first time); otherwise `python3`. +#' @param run For tests: a function `(command, args)` that runs the script and +#' returns its exit status. +#' @return The folder, invisibly. +#' @examples +#' \dontrun{ +#' exportOnnxModel("bioclip") +#' model <- onnxModel("bioclip", precision = "int8") +#' } +#' @export +exportOnnxModel <- function(name = "bioclip", pretrained = "openai", weights = NULL, dir = NULL, + quantize = c("int8", "fp16"), python = NULL, run = NULL) { + if (length(quantize)) quantize <- match.arg(quantize, c("int8", "fp16"), several.ok = TRUE) + torchNames <- c(bioclip = "hf-hub:imageomics/bioclip", "bioclip-2" = "hf-hub:imageomics/bioclip-2") + model <- if (tolower(name) %in% names(torchNames)) torchNames[[tolower(name)]] else name + if (is.null(dir)) dir <- onxExportDir(name, pretrained) + dir.create(dir, recursive = TRUE, showWarnings = FALSE) + pydir <- system.file("python", package = "dimoose") + args <- c(file.path(pydir, "export_onnx.py"), "--model", model, "--pretrained", pretrained, "--out", normalizePath(dir)) + if (!is.null(weights)) args <- c(args, "--weights", normalizePath(weights)) + if (length(quantize)) args <- c(args, "--quantize", quantize) + command <- python + if (is.null(command)) { + uv <- onxUv() + if (nzchar(uv)) { + command <- uv + args <- c("run", "--no-project", "--with-requirements", file.path(pydir, "requirements.txt"), + "--with-requirements", file.path(pydir, "requirements-export.txt"), "python", args) + } else { + command <- "python3" + } + } + if (is.null(run)) run <- function(command, args) system2(command, shQuote(args)) + status <- run(command, args) + if (!identical(as.integer(status), 0L) || !file.exists(file.path(dir, "dimoose_onnx.json"))) { + stop("The conversion failed (", command, " ", paste(utils::head(args, 3), collapse = " "), " ...). ", + "It needs Python with the packages in ", file.path(pydir, "requirements.txt"), " and ", + file.path(pydir, "requirements-export.txt"), "; give that Python's path in `python`.", call. = FALSE) + } + invisible(dir) +} + +# Where exportOnnxModel() writes a model by default, which is where +# onxResolve() looks for the same name. +onxExportDir <- function(name, pretrained = "openai", cache = onnxCache()) { + # BioCLIP goes by its repository, so that "bioclip" and + # "hf-hub:imageomics/bioclip" are one folder. The models with a ready-made + # copy on the Hub get a folder of their own, apart from that copy's. + known <- onxKnown() + if (grepl("^bioclip", name, ignore.case = TRUE) && tolower(name) %in% names(known)) { + return(file.path(cache, onxSlug(known[[tolower(name)]]))) + } + if (startsWith(name, "hf-hub:")) return(file.path(cache, onxSlug(name))) + if (startsWith(name, "local-dir:")) return(file.path(cache, onxSlug(basename(sub("^local-dir:", "", name))))) + file.path(cache, onxSlug(paste0(name, "-", pretrained))) +} + +# The `name` for onnxModel() that visionModel(name, pretrained, backend = +# "onnx") means. +onxNameFor <- function(name, pretrained = "openai", cache = onnxCache()) { + if (dir.exists(name) || grepl("^(hf-hub|local-dir):", name) || grepl("/", name, fixed = TRUE)) return(name) + # a model you converted yourself comes before the ready-made copy of the + # same name: exportOnnxModel("ViT-B-32") is then what "ViT-B-32" means + dir <- onxExportDir(name, pretrained, cache) + if (onxIsModelDir(dir)) return(dir) + if (tolower(name) %in% names(onxKnown()) && (identical(pretrained, "openai") || grepl("bioclip", name, ignore.case = TRUE))) return(name) + if (!onxIsModelDir(dir)) { + stop("There is no ONNX copy of ", name, " (", pretrained, ") on this computer (looked in ", dir, "). Convert it once with ", + "exportOnnxModel(\"", name, "\", pretrained = \"", pretrained, "\"); that needs Python with torch, but only once.", call. = FALSE) + } + dir +} + +# ---- embeddings in files ----------------------------------------------------- + +# IEEE 754 half precision: numbers to 16-bit patterns (as integers 0..65535) +# and back. Values too large for a half become infinite; NA becomes NaN. +onxToHalf <- function(x) { + x <- as.numeric(x) + bits <- integer(length(x)) + nan <- is.na(x) + sign <- ifelse(!nan & (x < 0 | (x == 0 & 1 / x < 0)), 32768L, 0L) + a <- abs(x) + inf <- !nan & a >= 65520 # rounds up past the largest half + tiny <- !nan & a < 2^-14 # subnormal halves, and zero + norm <- !nan & !inf & !tiny + bits[tiny] <- as.integer(round(a[tiny] * 2^24)) + e <- floor(log2(a[norm])) + m <- round((a[norm] / 2^e - 1) * 1024) + up <- m == 1024 + e[up] <- e[up] + 1; m[up] <- 0 + bits[norm] <- as.integer((e + 15) * 1024 + m) + bits[inf] <- 31744L + bits[nan] <- 32256L + bits + ifelse(nan, 0L, sign) +} + +onxFromHalf <- function(bits) { + sign <- ifelse(bits >= 32768L, -1, 1) + e <- (bits %/% 1024L) %% 32L + m <- bits %% 1024L + out <- ifelse(e == 0L, m * 2^-24, (1 + m / 1024) * 2^(e - 15)) + out[e == 31L] <- ifelse(m[e == 31L] == 0L, Inf, NaN) + sign * out +} + +#' Save embeddings to a file, and read them back +#' +#' Embedding images needs a vision model, and so Python; using embeddings +#' does not. `saveEmbeddings()` writes what [embedImages()] or [embedTexts()] +#' returned to one small file, and `loadEmbeddings()` reads it back as it +#' was, row names and tiling included, on a computer with no Python at all. +#' Everything dimoose does after embedding ([discoverSniglets()], +#' [snigletScores()], [keyFromSniglets()], [keyFromClusters()], +#' [featureScores()], ...) works from the loaded embeddings. +#' +#' @section File format: +#' The file is in the +#' [safetensors](https://huggingface.co/docs/safetensors) format, which +#' Python (`safetensors.numpy.load_file()`), JavaScript and other languages +#' read too: +#' +#' * 8 bytes: the length `N` of the header in bytes, an unsigned 64-bit +#' little-endian integer; +#' * `N` bytes: the header, one JSON object in UTF-8, padded with spaces so +#' that `N` is a multiple of 8. It has one entry per array, in the order +#' the arrays are stored, named `image` and `patches` (for +#' [embedImages()]), `embeddings` (for a single matrix) or by the names of +#' the list given. Each entry has `dtype` (`"F32"` or `"F16"`), `shape` +#' (the dimensions, e.g. `[36, 512]`) and `data_offsets` (`[begin, end]`: +#' the array's first byte and the byte after its last, counted from the end +#' of the header); +#' * the arrays' numbers, one array after another with nothing between them, +#' in row-major (C) order: an `images x d` matrix is stored image by image, +#' an `images x tiles x d` array image by image and tile by tile. +#' +#' Numbers are IEEE 754 floats of 4 bytes (`"F32"`) or 2 bytes (`"F16"`), and +#' always little-endian, whatever the computer that writes or reads the file. +#' +#' The header's `__metadata__` entry is an object of strings: `format` +#' (`"dimoose-embeddings"`), `version` (`"1"`), `single` (`"true"` when `x` +#' was one array and not a list, so that it is read back as one), +#' `rownames.` (a JSON array of the row names: image ids or texts; +#' other dimensions' names are not kept), `tiles.` and +#' `empty.` (the tiling and the rule for empty tiles, see +#' [embedImages()], as numbers separated by commas) and `model` (a JSON +#' object with the model's details, if there is a model). +#' +#' `loadEmbeddings()` also reads safetensors files written by other programs, +#' as long as their arrays are 16-, 32- or 64-bit floats. +#' +#' @section Precision: +#' R keeps numbers as 64-bit floats and the file holds 32-bit ones (about 7 +#' significant digits). Vision models compute in 32 bits, so what +#' [embedImages()] and [embedTexts()] return is saved and read back exactly; +#' other numbers come back rounded to the nearest 32-bit float. With +#' `precision = "float16"` every number is rounded to about 3 significant +#' digits: unit-length embeddings change by at most 0.0005 per coordinate. +#' Numbers too large for the chosen precision become `Inf`, and `NA` is read +#' back as `NaN`. +#' +#' @section Embeddings that come with dimoose: +#' The embeddings of the package's example photos are in its +#' `extdata/embeddings` folder, so the examples can be followed with no +#' Python: `pics-clip-vit-b-32.safetensors` (the 36 fruit photos in +#' `extdata/pics`, whole photos and 4 x 4 tiles), +#' `new-photos-clip-vit-b-32.safetensors` (the 6 photos in +#' `extdata/new-photos`), `texts-clip-vit-b-32.safetensors` (the prompts of +#' the vision vignette) and `montana-bioclip.safetensors` (the tree photos in +#' `extdata/montana` and the names of [montanaKey()]'s species, embedded with +#' BioCLIP). The folder's `README.md` says how each was made. +#' +#' @param x A numeric matrix or array, or a list of them such as +#' [embedImages()] returns (entries that are `NULL` are left out). +#' @param file File to write or read; `.safetensors` is the usual ending. +#' @param precision `"float32"`, or `"float16"` for a file half the size. +#' Embeddings have unit length, so 16-bit floats change cosine +#' similarities only in the fourth decimal place. +#' @param model Optional [visionModel()] the embeddings were made with; its +#' details are stored in the file. Embeddings from `loadEmbeddings()` keep +#' the model they were loaded with when saved again. +#' @return `saveEmbeddings()` returns `file`, invisibly. `loadEmbeddings()` +#' returns what was saved: a matrix or array, or a list of them. If the +#' file records a model, its details are in the result's `model` attribute. +#' @examples +#' # stand-ins for embedImages(model, images): 3 images, 2 tiles each, 4 dimensions +#' emb <- list(image = matrix(rnorm(12), 3, 4, dimnames = list(c("a", "b", "c"), NULL)), +#' patches = array(rnorm(24), c(3, 2, 4), dimnames = list(c("a", "b", "c"), NULL, NULL))) +#' attr(emb$patches, "tiles") <- 1L +#' file <- tempfile(fileext = ".safetensors") +#' saveEmbeddings(emb, file) +#' back <- loadEmbeddings(file) +#' all.equal(back$image, emb$image, tolerance = 1e-6) +#' rownames(back$image) +#' attr(back$patches, "tiles") +#' +#' # the example photos' embeddings, made with CLIP ViT-B/32: a key with no Python +#' pics <- loadEmbeddings(system.file("extdata", "embeddings", "pics-clip-vit-b-32.safetensors", +#' package = "dimoose")) +#' dim(pics$patches) +#' attr(pics, "model")$arch +#' images <- imageSet(system.file("extdata", "pics", package = "dimoose")) +#' sniglets <- discoverSniglets(pics$patches, k = 40) +#' scores <- snigletScores(pics$patches, sniglets$centroids) +#' keyFromSniglets(scores, images, sniglets, method = "rpart") +#' @export +saveEmbeddings <- function(x, file, precision = c("float32", "float16"), model = NULL) { + precision <- match.arg(precision) + if (!requireNamespace("jsonlite", quietly = TRUE)) stop("Install the jsonlite package", call. = FALSE) + if (is.data.frame(x)) x <- as.matrix(x) + single <- !is.list(x) + if (single) x <- list(embeddings = x) + if (!is.null(model) && !inherits(model, "dimooseVisionModel")) { + stop("`model` must be the vision model the embeddings were made with, from visionModel() or onnxModel()", call. = FALSE) + } + # embeddings read by loadEmbeddings() carry their model's details + kept <- if (single) attr(x[[1]], "model") else attr(x, "model") + if (!is.list(kept) || is.null(names(kept))) kept <- NULL + if (!is.character(file) || length(file) != 1 || is.na(file) || !nzchar(file)) stop("`file` must be one file name", call. = FALSE) + if (dir.exists(file)) stop(file, " is a folder; `file` must be the name of a file", call. = FALSE) + if (!dir.exists(dirname(file))) stop("No such folder: ", dirname(file), call. = FALSE) + x <- x[!vapply(x, is.null, logical(1))] + if (!length(x) || is.null(names(x)) || any(!nzchar(names(x))) || anyDuplicated(names(x))) { + stop("`x` must be a numeric array or a list of numeric arrays with distinct names", call. = FALSE) + } + if (any(names(x) == "__metadata__")) stop("An array cannot be called __metadata__", call. = FALSE) + json <- function(v) as.character(jsonlite::toJSON(v, auto_unbox = TRUE, digits = NA, null = "null")) + meta <- list(format = "dimoose-embeddings", version = "1", single = if (single) "true" else "false") + header <- list() + chunks <- list() + offset <- 0 + for (n in names(x)) { + a <- x[[n]] + if (!is.numeric(a)) stop("`", n, "` is not numeric", call. = FALSE) + dims <- if (is.null(dim(a))) length(a) else dim(a) + values <- if (length(dims) > 1) as.vector(aperm(unclass(a))) else as.vector(a) # row-major + raw <- if (precision == "float32") { + writeBin(as.numeric(values), raw(), size = 4, endian = "little") + } else { + bits <- onxToHalf(values) + writeBin(ifelse(bits >= 32768L, bits - 65536L, bits), raw(), size = 2, endian = "little") + } + if (offset + length(raw) > .Machine$integer.max) stop("These embeddings are too large for one file (2 GB)", call. = FALSE) + header[[n]] <- list(dtype = if (precision == "float32") "F32" else "F16", shape = I(as.integer(dims)), + data_offsets = I(as.integer(c(offset, offset + length(raw))))) + offset <- offset + length(raw) + chunks[[n]] <- raw + rn <- if (is.null(dim(a))) names(a) else dimnames(a)[[1]] + if (!is.null(rn)) meta[[paste0("rownames.", n)]] <- as.character(jsonlite::toJSON(as.character(rn))) + if (!is.null(attr(a, "tiles"))) meta[[paste0("tiles.", n)]] <- paste(attr(a, "tiles"), collapse = ",") + if (!is.null(attr(a, "empty"))) meta[[paste0("empty.", n)]] <- paste(attr(a, "empty"), collapse = ",") + } + s <- if (!is.null(model)) model$spec else kept + if (!is.null(s)) { + s <- s[!vapply(s, is.null, logical(1))] + meta$model <- json(lapply(s, function(v) if (length(v) == 1) v else paste(v, collapse = ","))) + } + head <- charToRaw(enc2utf8(json(c(list("__metadata__" = meta), header)))) + head <- c(head, rep(as.raw(0x20), (8 - length(head) %% 8) %% 8)) # pad with spaces to 8 bytes + con <- file(file, "wb") + on.exit(close(con)) + writeBin(c(length(head), 0L), con, size = 4, endian = "little") # 64-bit length, low word first + writeBin(head, con) + for (r in chunks) writeBin(r, con) + invisible(file) +} + +#' @rdname saveEmbeddings +#' @export +loadEmbeddings <- function(file) { + if (!requireNamespace("jsonlite", quietly = TRUE)) stop("Install the jsonlite package", call. = FALSE) + if (!is.character(file) || length(file) != 1 || is.na(file)) stop("`file` must be one file name", call. = FALSE) + if (!file.exists(file)) stop("No such file: ", file, call. = FALSE) + if (dir.exists(file)) stop(file, " is a folder, not a file of embeddings", call. = FALSE) + size <- file.size(file) + con <- file(file, "rb") + on.exit(close(con)) + n <- readBin(con, "integer", 2, size = 4, endian = "little") + if (length(n) < 2 || is.na(n[1]) || n[2] != 0 || n[1] <= 0 || n[1] + 8 > size) { + stop(file, " is not a safetensors file", call. = FALSE) + } + text <- rawToChar(readBin(con, "raw", n[1])) + Encoding(text) <- "UTF-8" + header <- tryCatch(jsonlite::fromJSON(text, simplifyVector = FALSE), + error = function(e) stop(file, " is not a safetensors file: its header is not JSON", call. = FALSE)) + if (!is.list(header) || is.null(names(header)) || any(!nzchar(names(header)))) { + stop(file, " is not a safetensors file: its header is not a JSON object", call. = FALSE) + } + data <- readBin(con, "raw", size - 8 - n[1]) + meta <- header[["__metadata__"]] + header[["__metadata__"]] <- NULL + if (!length(header)) stop(file, " holds no arrays", call. = FALSE) + out <- list() + for (name in names(header)) { + h <- header[[name]] + ok <- is.list(h) && is.character(h$dtype) && length(h$dtype) == 1 && length(h$data_offsets) == 2 && + all(vapply(c(h$shape, h$data_offsets), function(v) is.numeric(v) && length(v) == 1 && !is.na(v) && v >= 0, logical(1))) + if (!ok) stop(file, " is not a safetensors file: `", name, "` lacks a dtype, a shape or its data offsets", call. = FALSE) + dims <- as.integer(unlist(h$shape)) + at <- unlist(h$data_offsets) + count <- prod(dims) + if (at[1] > at[2]) stop(file, " is not a safetensors file: `", name, "` ends before it begins", call. = FALSE) + if (at[2] > length(data)) { + stop(file, " is cut short: `", name, "` should end at byte ", at[2], " of the data, which has ", length(data), call. = FALSE) + } + raw <- data[seq.int(at[1] + 1, length.out = at[2] - at[1])] + values <- switch(h$dtype, + F32 = readBin(raw, "numeric", count, size = 4, endian = "little"), + F64 = readBin(raw, "numeric", count, size = 8, endian = "little"), + F16 = onxFromHalf(readBin(raw, "integer", count, size = 2, signed = FALSE, endian = "little")), + stop("`", name, "` in ", file, " has the type ", h$dtype, ", which loadEmbeddings() does not read", call. = FALSE)) + if (length(values) != count) stop("`", name, "` in ", file, " has ", length(values), " numbers, not the ", count, " its shape says", call. = FALSE) + a <- if (length(dims) > 1) aperm(array(values, rev(dims))) else values + rn <- meta[[paste0("rownames.", name)]] + if (!is.null(rn)) { + rn <- vapply(jsonlite::fromJSON(rn, simplifyVector = FALSE), function(v) if (is.null(v)) NA_character_ else as.character(v), "") + if (length(dims) > 1) dimnames(a) <- c(list(rn), rep(list(NULL), length(dims) - 1)) else names(a) <- rn + } + tiles <- meta[[paste0("tiles.", name)]] + if (!is.null(tiles)) attr(a, "tiles") <- as.integer(strsplit(tiles, ",", fixed = TRUE)[[1]]) + empty <- meta[[paste0("empty.", name)]] + if (!is.null(empty)) attr(a, "empty") <- stats::setNames(as.numeric(strsplit(empty, ",", fixed = TRUE)[[1]]), c("minDetail", "minFill")) + out[[name]] <- a + } + if (identical(meta$single, "true") && length(out) == 1) out <- out[[1]] + if (!is.null(meta$model)) attr(out, "model") <- jsonlite::fromJSON(meta$model, simplifyVector = FALSE) + out +} + +# ---- a model for the browser ------------------------------------------------- + +# How a model prepares images, from its spec: a list for the manifest, or an +# error when the model does not say. +onxPreprocess <- function(spec) { + nums <- function(v) as.numeric(strsplit(as.character(v), ",", fixed = TRUE)[[1]]) + if (is.null(spec$image_mean) || is.null(spec$image_std) || is.null(spec$image_size)) { + stop("This model does not say how images are prepared for it (image size, mean and standard deviation), ", + "so a browser could not prepare photos the same way", call. = FALSE) + } + size <- as.integer(spec$image_size) + list(image_size = size, + resize = if (is.null(spec$image_resize)) "shortest" else spec$image_resize, + resize_to = if (is.null(spec$image_resize_to)) size else as.integer(spec$image_resize_to), + interpolation = if (is.null(spec$image_interpolation)) "bicubic" else spec$image_interpolation, + crop = if (is.null(spec$image_crop)) "center" else spec$image_crop, + rescale = 1 / 255, + mean = nums(spec$image_mean), std = nums(spec$image_std), + layout = "NCHW", channels = "RGB") +} + +#' Write what a web page needs to identify photos with a key's species +#' +#' Photo identification as [suggestSpecies()] and [identifyPhotos()] do it has +#' two halves: the names of the key's results are embedded as texts, and the +#' photo is embedded as an image and compared with them. The text half can be +#' done ahead of time, here; a web page then needs only the image encoder to +#' identify a photo on the visitor's own device, with no server and no +#' upload. This function writes the files such a page loads. +#' +#' @section Files written to `dir`: +#' **`model.json`**, the manifest (UTF-8 JSON): +#' +#' * `format`: `"dimoose-browser-model"`; `version`: `1`. +#' * `key`: `desc` (the key's description) and `taxa` (the number of labels). +#' * `model`: `arch`, `pretrained`, `dim` (embedding dimensions), `library`. +#' * `image_encoder`: `file` (a file name in `dir`, or `null`), `url` (a web +#' address, or `null`; one of the two is set), `bytes`, `precision` +#' (`"int8"`, `"fp16"`, `"fp32"` or `null` if unknown), `input` (the input's +#' name, `"pixel_values"`), `input_type` (`"float32"`), `input_shape` +#' (`[1, 3, S, S]`), `output` (the output to read, `"image_embeds"`), +#' `normalized` (`false`: divide the output by its length). +#' * `preprocess`, how to turn a photo into the input: `resize` +#' (`"shortest"`: scale so the shorter side is `resize_to` pixels, keeping +#' the shape), `interpolation` (`"bicubic"`), `crop` (`"center"`: cut the +#' middle `image_size` x `image_size` square), `rescale` (multiply the 0-255 +#' values by this, 1/255), `mean` and `std` (per channel: subtract, then +#' divide), `layout` (`"NCHW"`), `channels` (`"RGB"`). +#' * `text_embeddings`: `file` (`"text_embeddings.bin"`), `dtype` +#' (`"float32"`), `byte_order` (`"little"`), `shape` (`[labels, dim]`), +#' `order` (`"row-major"`: label by label), `normalized` (`true`), `prompt` +#' (the template). +#' * `labels`: one object per row of the text embeddings, in order: `taxon` +#' (the result as the key's leads write it, which is what to look up in the +#' key), `name` (the name put into the prompt: the scientific name when the +#' result has one) and `prompt` (the text that was embedded). +#' * `logit_scale`: `100`. +#' +#' **`text_embeddings.bin`**: `labels x dim` 32-bit little-endian floats and +#' nothing else, row by row; in JavaScript, +#' `new Float32Array(await (await fetch(url)).arrayBuffer())`. +#' +#' **`image_encoder.onnx`**: the image encoder, unless the manifest gives a +#' `url` instead. +#' +#' @section What the page does: +#' Prepare the photo as `preprocess` says, run the image encoder (for example +#' with onnxruntime-web), divide `image_embeds` by its length to get `v`, and +#' take the dot product of `v` with each row of the text embeddings. The +#' probability of each label is the softmax of `logit_scale` times those dot +#' products, which is what [suggestSpecies()] computes. +#' +#' @section Size: +#' The image encoder is the download that matters. Use an `"int8"` encoder +#' for the web: 96 MB for CLIP ViT-B/32 and 90 MB for BioCLIP as +#' [exportOnnxModel()] writes them, against about 350 MB unquantised, with +#' the same answers on dimoose's example photos (BioCLIP 2, a larger model, +#' is 310 MB even so). Where that is still too much, `"mobileclip-s0"` at +#' `"fp16"` is 23 MB, but it is a general model that does not know species +#' names as BioCLIP does. The text embeddings are tiny +#' (2 KB per label), and are best made with the `"fp32"` text encoder: +#' `onnxModel(name, precision = "int8", textPrecision = "fp32")`. +#' +#' @section Tested with onnxruntime-web: +#' The `"int8"`, `"fp16"` and `"fp32"` encoders that [exportOnnxModel()] +#' writes for CLIP ViT-B/32 and BioCLIP were run in onnxruntime-web 1.31.1 on +#' its WebAssembly backend (under Node.js) from folders this function wrote, +#' with the 14 Montana example photos prepared as `preprocess` says. All +#' three load and run there. Against the same file run in Python the lowest +#' cosine of the embeddings was 0.9996 for `"int8"` and 1.0000 for `"fp16"` +#' and `"fp32"`, and the most likely label was the same for every photo. The +#' `"int8"` files hold 8-bit weights that are turned back into floats when +#' the model loads, so they use no integer arithmetic a runtime might lack. +#' The WebGPU backend was not tested. +#' +#' Ready-made `_quantized` files from the Hub (`encoder = "hub"` with an +#' `"int8"` model) are quantised differently, with integer arithmetic. That +#' of `Xenova/clip-vit-base-patch32` had a lowest cosine of 0.85 with the +#' `"fp32"` embeddings on the same backend and gave another most likely label +#' for 5 of the 14 photos; its `"fp16"` file had 1.0000. Point a page at the +#' `"fp16"` file, or copy in an `"int8"` encoder from [exportOnnxModel()]. +#' +#' How the photo is resized matters more than the encoder's precision. +#' `preprocess$interpolation` names the filter the model was trained with +#' (bicubic, with smoothing when a photo is made smaller, as the Python +#' library Pillow does it). With BioCLIP on the Montana photos, resizing with +#' a bilinear filter instead gave embeddings with a cosine of 0.93 to 0.98 +#' (0.97 on average) with the right ones, and nearest-neighbour 0.84 to 0.95. +#' +#' @param key A key whose results are the labels. +#' @param model The [onnxModel()] (or [visionModel()]) to embed the labels +#' with. It must be the model the image encoder belongs to. +#' @param dir Folder to write to; created if needed. +#' @param encoder The image encoder for the page: `NULL` copies the image +#' encoder of `model` (which must then be an [onnxModel()]); `"hub"` points +#' the page at that file on the Hugging Face Hub instead of copying it (for +#' a model that came from there); a file path copies that file; a web +#' address (`https://...`) is written to the manifest as it is. +#' @param prompt The text each name is put into, with `%s` where the name +#' goes, as in [suggestSpecies()]. +#' @param textEmb Optional text embeddings made earlier, a matrix whose row +#' names are the prompts (from [embedTexts()] or [loadEmbeddings()]); the +#' labels are then not embedded again. +#' @return The path of `model.json`, invisibly. +#' @seealso [onnxModel()], [exportOnnxModel()], [suggestSpecies()]. +#' @examples +#' \dontrun{ +#' model <- onnxModel("bioclip", precision = "int8", textPrecision = "fp32") +#' exportBrowserModel(montanaKey(), model, "site/model") +#' list.files("site/model") # image_encoder.onnx, model.json, text_embeddings.bin +#' } +#' @export +exportBrowserModel <- function(key, model, dir, encoder = NULL, prompt = "a photo of %s.", textEmb = NULL) { + if (!inherits(key, "dimoose")) stop("`key` must be a dimoose object", call. = FALSE) + if (!inherits(model, "dimooseVisionModel")) stop("`model` must be a vision model from onnxModel() or visionModel()", call. = FALSE) + if (!requireNamespace("jsonlite", quietly = TRUE)) stop("Install the jsonlite package", call. = FALSE) + if (!is.character(prompt) || length(prompt) != 1 || is.na(prompt) || !grepl("%s", prompt, fixed = TRUE)) { + stop("`prompt` must contain %s where the species name goes", call. = FALSE) + } + if (!is.character(dir) || length(dir) != 1 || is.na(dir) || !nzchar(dir)) stop("`dir` must be one folder name", call. = FALSE) + if (file.exists(dir) && !dir.exists(dir)) stop(dir, " is a file; `dir` must be a folder", call. = FALSE) + if (!is.null(encoder) && (!is.character(encoder) || length(encoder) != 1 || is.na(encoder) || !nzchar(encoder))) { + stop("`encoder` must be NULL, \"hub\", one file or one web address", call. = FALSE) + } + taxa <- unique(key$leads$Taxon[!is.na(key$leads$Taxon) & nzchar(key$leads$Taxon)]) + if (!length(taxa)) stop("This key names no results", call. = FALSE) + name <- scientificPart(taxa) + name[is.na(name)] <- taxa[is.na(name)] + prompts <- tryCatch(sprintf(prompt, name), error = function(e) { + stop("`prompt` must contain %s once, where the species name goes, and no other % (write %% for a percent sign)", call. = FALSE) + }) + pre <- onxPreprocess(model$spec) + + # the image encoder: a file to copy, or an address to point at + url <- NULL; source <- NULL + if (is.null(encoder)) { + source <- model$files$image + if (is.null(source)) { + stop("`model` is not an ONNX model, so it has no image encoder file for the page; ", + "give one in `encoder` (a file or a web address), or use onnxModel()", call. = FALSE) + } + } else if (identical(encoder, "hub")) { + url <- model$files$imageUrl + if (is.null(url)) stop("`model` did not come from the Hugging Face Hub, so there is no web address for its image encoder", call. = FALSE) + } else if (grepl("^https?://", encoder)) { + url <- encoder + } else { + source <- encoder + } + if (!is.null(source) && (!file.exists(source) || dir.exists(source))) stop("No such image encoder file: ", source, call. = FALSE) + own <- is.null(encoder) || identical(encoder, "hub") + bytes <- if (!is.null(source)) onxSize(source) else if (own && !is.null(model$files$image)) onxSize(model$files$image) else NULL + + if (is.null(textEmb)) { + textEmb <- embedTexts(model, prompts) + } else { + missing <- setdiff(prompts, rownames(textEmb)) + if (length(missing)) stop("`textEmb` lacks rows for ", length(missing), " prompt(s), e.g. ", missing[1], call. = FALSE) + textEmb <- textEmb[prompts, , drop = FALSE] + } + if (ncol(textEmb) != model$spec$dim) { + stop("The text embeddings have ", ncol(textEmb), " dimensions, but the model has ", model$spec$dim, call. = FALSE) + } + textEmb <- textEmb / sqrt(rowSums(textEmb^2)) + bad <- which(!is.finite(rowSums(textEmb))) + if (length(bad)) { + stop("The text embedding of \"", prompts[bad[1]], "\" is all zeros or not a number, so a page could not compare photos with it", + call. = FALSE) + } + + dir.create(dir, recursive = TRUE, showWarnings = FALSE) + if (!dir.exists(dir)) stop("Could not create the folder ", dir, call. = FALSE) + if (!is.null(source)) { + dest <- file.path(dir, "image_encoder.onnx") + if (normalizePath(source) != normalizePath(dest, mustWork = FALSE)) file.copy(source, dest, overwrite = TRUE) + if (bytes > 150e6) { + message("The image encoder is ", round(bytes / 1e6), " MB, a long download for a web page; ", + "an int8 encoder (onnxModel(precision = \"int8\")) is about a quarter of that") + } + } + writeBin(as.numeric(t(textEmb)), file.path(dir, "text_embeddings.bin"), size = 4, endian = "little") + + s <- model$spec + manifest <- list( + format = "dimoose-browser-model", + version = 1L, + key = list(desc = if (is.null(key$desc)) NULL else as.character(key$desc)[1], taxa = length(taxa)), + model = list(arch = s$arch, pretrained = s$pretrained, dim = as.integer(s$dim), library = s$library), + image_encoder = list( + file = if (is.null(source)) NULL else "image_encoder.onnx", + url = url, + bytes = bytes, + precision = if (own) s$precision else NULL, + input = "pixel_values", input_type = "float32", + input_shape = I(c(1L, 3L, pre$image_size, pre$image_size)), + output = "image_embeds", normalized = FALSE), + preprocess = c(pre[c("image_size", "resize", "resize_to", "interpolation", "crop", "rescale")], + list(mean = I(pre$mean), std = I(pre$std), layout = pre$layout, channels = pre$channels)), + text_embeddings = list(file = "text_embeddings.bin", dtype = "float32", byte_order = "little", + shape = I(dim(textEmb)), order = "row-major", normalized = TRUE, prompt = prompt), + labels = lapply(seq_along(taxa), function(i) list(taxon = taxa[i], name = name[i], prompt = prompts[i])), + logit_scale = 100L) + out <- file.path(dir, "model.json") + writeLines(enc2utf8(as.character(jsonlite::toJSON(manifest, auto_unbox = TRUE, pretty = TRUE, null = "null", digits = NA))), + out, useBytes = TRUE) + invisible(out) +} diff --git a/R/prune.R b/R/prune.R new file mode 100644 index 0000000..d194987 --- /dev/null +++ b/R/prune.R @@ -0,0 +1,1240 @@ +#' Prune a key to some of its taxa +#' +#' Keeps only the taxa you name (or removes the ones you name) and tidies up +#' what is left: leads that no longer reach any kept taxon are removed, and a +#' couplet that no longer splits anything is taken out, with the lead that +#' led to it now leading straight to where its one remaining lead went. +#' Collapses are repeated until every couplet again has at least two leads +#' going to different places, so chains of couplets, couplets reached from +#' several leads and the first couplet of the key are all handled. +#' +#' The leads that remain keep their text, their order and (unless +#' `renumber = TRUE`) their couplet names, so every kept taxon is reached by +#' the same leads as before, less the ones that no longer decide anything. +#' Pruning in two steps gives the same key as pruning once to the taxa kept +#' by both. +#' +#' @section Matching taxa: +#' Names are compared without regard to case or extra spaces, and the +#' multiplication sign of a hybrid may be typed as a lower-case `x` +#' (`"Populus x acuminata"`). An entry of `keep` or `drop` matches a taxon of +#' the key when it equals the taxon's whole label +#' (`"Bur oak (Quercus macrocarpa)"`), the scientific name in its +#' parentheses (`"Quercus macrocarpa"`) or the common name before them +#' (`"Bur oak"`); entries may themselves be written with or without a common +#' name. +#' +#' With `ranks = "genus"` (the default) a name also stands for what lies +#' below it, judged by the words the names begin with: +#' * a genus in `keep` or `drop` (`"Populus"`) matches every species of that +#' genus in the key, and a species (`"Populus balsamifera"`) matches its +#' subspecies and varieties (`"Populus balsamifera subsp. trichocarpa"`); +#' * a name matches the same name followed by its author +#' (`"Quercus macrocarpa"` and `"Quercus macrocarpa Michx."`, or +#' `"Carcharodon carcharias (Linnaeus, 1758)"`), whichever of the two has +#' the author; +#' * a species in `keep` (`"Quercus macrocarpa"`) keeps a result of the key +#' that is only its genus (`"Quercus"`), and a subspecies keeps its +#' species. This is not done for `drop`: removing one species does not +#' remove its genus. +#' +#' With `ranks = "exact"` only whole labels, scientific names and common +#' names match. +#' Families and higher ranks cannot be told from a name, so a result such as +#' `"Salicaceae"` is matched only by itself, and a synonym is a different +#' name; [regionalKey()] asks GBIF or iNaturalist instead and so works at any +#' rank and through synonyms. +#' +#' @section Shared results: +#' A result that names several taxa the key cannot tell apart, written +#' `"A / B"` as [keyFromRpart()] and [keyFromMatrix()] write them, is treated +#' as the taxa `A` and `B`: each can be kept or dropped by its own name, and +#' when only `A` is kept the result becomes `"A"`. Naming the whole result +#' (`"A / B"`) keeps or drops all of it. (A label with a common name, such as +#' `"Aspen / Popple (Populus tremuloides)"`, is one taxon.) +#' +#' @section What happens to the removed couplet's character: +#' When a couplet is taken out, the text of its one remaining lead still +#' describes the taxa beyond it, and is useful for confirming an +#' identification. With `note = "column"` (the default) it is added to a +#' `Note` column on the lead that now skips the couplet; with +#' `note = "append"` it is added to that lead's `Character` in square +#' brackets, so it shows wherever the key is displayed; with `note = "none"` +#' it is discarded. Whatever `note` is, the removed lead's pictures (`Image` +#' and `ImageLink`) are added to those of the lead that now skips the +#' couplet. When the first couplet of the key is taken out there is no lead +#' to carry the text: it goes in the key's metadata as `pruned_note` (added +#' to any that is already there), and its pictures are left out. +#' +#' @param key A [dimoose] key. +#' @param keep Taxa to keep; all others are removed. `NULL` keeps all. +#' @param drop Taxa to remove (after `keep` has been applied). +#' @param ranks `"genus"` or `"exact"`; see 'Matching taxa'. +#' @param note `"column"`, `"append"` or `"none"`; see 'What happens to the +#' removed couplet's character'. +#' @param renumber If `TRUE`, number the remaining couplets 1, 2, 3, ... in +#' reading order (each couplet followed by the couplets its leads go to, +#' first lead first). If `FALSE`, couplets keep their names. +#' @return A [dimoose] key with the same columns in its leads as `key` +#' (plus `Note` if a note was written). Embedded images, taxa and features +#' that no remaining lead uses are left out. It is an error if no result is +#' left, or only one (a key needs two results to tell apart). +#' @seealso [regionalKey()] to prune to the taxa recorded in a place, +#' [mergeKeys()] to go the other way. +#' @examples +#' cottonwoods <- pruneKey(montanaKey(), keep = "Populus") +#' cottonwoods +#' cottonwoods$leads[, c("Statement", "Choice", "Next", "Taxon")] +#' +#' # names can be given with or without the common name +#' k <- pruneKey(montanaKey(), drop = c("Acer negundo", "Bur oak (Quercus macrocarpa)"), +#' renumber = TRUE) +#' k$validate() +#' k$leads$Note +#' @export +pruneKey <- function(key, keep = NULL, drop = NULL, ranks = c("genus", "exact"), + note = c("column", "append", "none"), renumber = FALSE) { + if (!inherits(key, "dimoose")) stop("`key` must be a dimoose object", call. = FALSE) + ranks <- match.arg(ranks) + note <- match.arg(note) + for (arg in c("keep", "drop")) { + value <- get(arg) + if (!is.null(value) && !is.character(value) && !is.factor(value)) { + stop("`", arg, "` must be a character vector of taxon names", call. = FALSE) + } + } + leads <- as.data.frame(key$leads, stringsAsFactors = FALSE) + if (!nrow(leads)) stop("This key has no leads", call. = FALSE) + norm <- normalizeLeads(leads) + leads$Statement <- norm$Statement + leads$Next <- norm$Next + leads$Taxon <- norm$Taxon + hadNote <- !is.null(leads$Note) + root <- checkLeads(norm)$root + terminal <- leads$Next == "-" + labels <- unique(leads$Taxon[terminal & nzchar(leads$Taxon)]) + if (!length(labels)) stop("This key names no taxa", call. = FALSE) + + # A shared result "A / B" is the taxa A and B; `wanted` is per taxon. A + # whole result is named only by its whole label: matched by rank, "A" + # would name "A / B" as if that were a subspecies of A. + members <- prnMembers(labels) + taxa <- unique(unlist(members)) + inLabel <- function(hitLabels) taxa %in% unlist(members[hitLabels]) + wanted <- rep(TRUE, length(taxa)) + if (!is.null(keep)) { + byTaxon <- prnMatchTaxa(taxa, keep, ranks, genusOfSpecies = TRUE) + byLabel <- prnMatchTaxa(labels, keep, "exact") + prnWarnUnmatched(byTaxon$used | byLabel$used, "keep") + wanted <- byTaxon$taxa | inLabel(byLabel$taxa) + } + if (!is.null(drop)) { + byTaxon <- prnMatchTaxa(taxa, drop, ranks, genusOfSpecies = FALSE) + byLabel <- prnMatchTaxa(labels, drop, "exact") + prnWarnUnmatched(byTaxon$used | byLabel$used, "drop") + wanted <- wanted & !(byTaxon$taxa | inLabel(byLabel$taxa)) + } + # what each result is called now: the kept taxa of a shared result + newLabel <- vapply(seq_along(labels), function(i) { + ok <- members[[i]] %in% taxa[wanted] + if (all(ok)) labels[i] else paste(members[[i]][ok], collapse = " / ") + }, "") + left <- unique(newLabel[nzchar(newLabel)]) + if (!length(left)) stop("No taxon of the key is left after pruning", call. = FALSE) + if (length(left) == 1) { + stop("Only one ", if (length(prnMembers(left)[[1]]) > 1) "result" else "taxon", " is left after pruning (", left, + "), so there is nothing to key out", call. = FALSE) + } + leads$Taxon[terminal] <- ifelse(nzchar(leads$Taxon[terminal]), newLabel[match(leads$Taxon[terminal], labels)], "") + + # Leads that still reach a kept taxon: the kept terminal leads, then every + # lead into a couplet that has such a lead, until nothing more is added. + alive <- terminal & nzchar(leads$Taxon) + repeat { + more <- !alive & !terminal & leads$Next %in% leads$Statement[alive] + if (!any(more)) break + alive <- alive | more + } + leads <- leads[alive, , drop = FALSE] + leads <- leads[leads$Statement %in% prnReachable(leads, root), , drop = FALSE] + if (!nrow(leads)) stop("No kept taxon can be reached from the first couplet of the key", call. = FALSE) + + collapsed <- prnCollapse(leads, root, note) + leads <- collapsed$leads + root <- collapsed$root + if (!nrow(leads) || length(unique(leads$Statement)) == 0) { + stop("Only one result can still be reached after pruning, so there is nothing to key out", call. = FALSE) + } + # a Note column that says nothing is not added to a key that had none + if (!hadNote && !is.null(leads$Note) && !any(nzchar(leads$Note))) leads$Note <- NULL + if (!is.null(leads$Prev)) leads$Prev <- prnPrev(leads, root) + if (isTRUE(renumber)) leads <- prnRenumber(leads, root) + rownames(leads) <- NULL + + left <- unique(leads$Taxon[leads$Next == "-" & nzchar(leads$Taxon)]) + meta <- prnDropImages(key$meta, key$leads, leads) + if (length(collapsed$rootNotes)) { + before <- metaValue(meta, "pruned_note") + meta <- prnSetMeta(meta, "pruned_note", paste(c(if (!is.na(before) && nzchar(before)) before, collapsed$rootNotes), + collapse = "; ")) + } + keyFromLeads(leads, key$desc, meta, prnSubsetTaxa(key$taxa, left), prnSubsetFeatures(key$features, leads)) +} + +#' A key to the taxa recorded in a place +#' +#' Asks [GBIF](https://www.gbif.org) or [iNaturalist](https://www.inaturalist.org) +#' which of the key's taxa have been recorded in a place and prunes the key +#' to those with [pruneKey()]: the key to the trees of Flathead County from +#' a key to the trees of Montana, in one line. +#' +#' Each result of the key is looked up by the scientific name in its +#' parentheses (`"Bur oak (Quercus macrocarpa)"`), or by the whole result +#' when there is none; the taxa of a shared result (`"A / B"`) are looked up +#' one by one, and the result keeps those that are recorded. The key's names +#' need not be the source's: a synonym is counted under the name the source +#' accepts for it, and the result keeps the key's own label. Results at any +#' rank work: a genus or a family counts the records of all its species. +#' +#' The sources are asked one taxon at a time, so a key of 70 taxa takes about +#' 150 requests of GBIF (about half a minute). If a request fails, it is an +#' error that says which taxon was being asked about, and nothing is pruned. +#' +#' @section GBIF: +#' Each name is matched to the GBIF Backbone (`/v1/species/match`) and its +#' occurrences in the place are counted (`/v1/occurrence/search` with +#' `limit=0`), two requests per taxon. A synonym is counted under its +#' accepted name, and a species that GBIF files under one of its subspecies +#' is counted as the species. A name GBIF has in more than one kingdom is +#' settled by `kingdom`, or, for a genus, by taking the accepted genus. +#' Only records with `occurrenceStatus=PRESENT` are counted. `place` can be +#' * a [GADM](https://gadm.org) id, such as `"USA.27.15_1"` for Flathead +#' County, Montana, or `"USA.27_1"` for Montana (`gadmGid`); +#' * a two-letter country code, such as `"CH"` (`country`); +#' * a polygon in WKT, `"POLYGON((...))"`, with its points anticlockwise +#' (`geometry`); +#' * a named list of GBIF occurrence search parameters, used as they are, +#' such as `list(country = "US", stateProvince = "Montana")`; +#' * the name of a region, looked up in GADM (`/v1/geocode/gadm/search`). +#' Add the regions it lies in after commas to tell places of the same name +#' apart: `"Flathead County, Montana"`, `"Flathead County, MT"`, +#' `"Montana, USA"`. A name that still fits several regions, or none, is +#' an error that lists the regions GADM has with their ids; give the id of +#' the one you mean. The message printed at the end names the region used. +#' +#' @section iNaturalist: +#' The place is found with `/v1/places/autocomplete` (or give its numeric +#' id). Parts after commas pick among places of one name +#' (`"Lake County, MT"`). When several places match, the one of exactly that +#' name is used (if there are several, a country or state before a county +#' or a park, then the largest), and a message names it and lists the others +#' with their ids, so that you can give the id of another. The species +#' observed in the place are listed with `/v1/observations/species_counts`, +#' 500 a page, counting research-grade observations only. A result of the key +#' is counted by name when a listed species has that name; otherwise it is +#' looked up with `/v1/taxa` (which also finds synonyms) and counts every +#' listed species below it, or, for a subspecies or variety, its own +#' observations. Give `kingdom` to list only that group's species, which +#' saves pages. When the list would take more requests than asking about +#' each taxon (a whole country, with no `kingdom`), a message says so and +#' each taxon's observations in the place are counted with two requests +#' instead. Requests made by the default `fetch` are a second apart, as +#' iNaturalist asks. +#' +#' @param key A [dimoose] key. +#' @param place The place; see the section for the source used. +#' @param source `"gbif"` or `"inat"`. +#' @param minRecords Keep a taxon with at least this many records. +#' @param kingdom For GBIF, the kingdom of the key's taxa (`"Plantae"`, +#' `"Animalia"`, ...), which tells apart names used in more than one. For +#' iNaturalist, the name or numeric id of any taxon that contains all the +#' key's taxa (`"Plantae"`, `"Aves"`). +#' @param unknown What to do with results the source does not know by name +#' (such as `"Other"`): `"keep"` them, with a warning, or `"drop"` them. +#' @param filters Named list of further search parameters for the count: +#' for GBIF, occurrence search parameters such as +#' `list(basisOfRecord = "HUMAN_OBSERVATION", year = "2000,2025")`; for +#' iNaturalist, observation search parameters such as +#' `list(quality_grade = "any")`. +#' @param ... Passed to [pruneKey()]: `note` and `renumber`. +#' @param fetch Function that makes a request: called as `fetch(url, query)` +#' with `query` a named list, it returns the parsed JSON as nested lists. +#' Replace it to cache or log requests, or to test without a network. The +#' default asks a busy or unreachable server up to three times. +#' @return A [dimoose] key, pruned. Its attribute `"records"` +#' (`attr(x, "records")`) is a data frame with a row for every taxon of the +#' original key: `Taxon`, `name` (the name looked up), `matched` (the name +#' the source counted it under), `id` (the source's id for that), +#' `records` (`NA` when the source does not know the name) and `kept`. The +#' attribute `"place"` says which place was used. When every taxon is kept +#' the key is returned unpruned. It is an error if the source knows none of +#' the key's taxa by name, or if fewer than two taxa are left. +#' @examples +#' \donttest{ +#' flathead <- regionalKey(montanaKey(), "USA.27.15_1", kingdom = "Plantae") +#' flathead +#' attr(flathead, "records") +#' +#' regionalKey(montanaKey(), "Flathead County", source = "inat", kingdom = "Plantae") +#' } +#' @export +regionalKey <- function(key, place, source = c("gbif", "inat"), minRecords = 1, kingdom = NULL, + unknown = c("keep", "drop"), filters = list(), ..., fetch = prnFetch) { + if (!inherits(key, "dimoose")) stop("`key` must be a dimoose object", call. = FALSE) + source <- match.arg(source) + unknown <- match.arg(unknown) + if (!is.function(fetch)) stop("`fetch` must be a function(url, query)", call. = FALSE) + if (!is.numeric(minRecords) || length(minRecords) != 1 || is.na(minRecords)) { + stop("`minRecords` must be one number", call. = FALSE) + } + if (!is.list(filters)) stop("`filters` must be a named list", call. = FALSE) + if (length(filters) && (is.null(names(filters)) || any(!nzchar(names(filters))))) { + stop("`filters` must be a named list", call. = FALSE) + } + leads <- normalizeLeads(key$leads) + labels <- unique(leads$Taxon[leads$Next == "-" & nzchar(leads$Taxon)]) + if (!length(labels)) stop("This key names no taxa", call. = FALSE) + # the taxa of a shared result "A / B" are looked up one by one + taxa <- unique(unlist(prnMembers(labels))) + name <- prnSciName(taxa) + sourceName <- if (source == "gbif") "GBIF" else "iNaturalist" + + if (source == "gbif") { + where <- prnGbifPlace(place, fetch) + if (length(taxa) > 30) message(sprintf("Asking GBIF about %d taxa, two requests each", length(taxa))) + counts <- prnGbifCounts(name, where$query, kingdom, filters, fetch) + } else { + where <- prnInatPlace(place, fetch) + counts <- prnInatCounts(prnStripAuthor(name), where$query, kingdom, filters, fetch) + } + known <- !is.na(counts$records) + kept <- ifelse(known, counts$records >= minRecords, unknown == "keep") + records <- data.frame(Taxon = taxa, name = name, matched = counts$matched, id = counts$id, + records = counts$records, kept = kept, stringsAsFactors = FALSE) + if (!any(known)) { + stop(sprintf("%s knows none of the key's %d taxa by name (%s%s), so the key cannot be pruned by its records. %s", + sourceName, length(taxa), paste(utils::head(taxa, 5), collapse = ", "), if (length(taxa) > 5) ", ..." else "", + "Results must be scientific names, alone or in parentheses after a common name"), call. = FALSE) + } + if (any(!known)) { + warning(sprintf("%s does not know %d of the key's taxa by name, so they were %s: %s", sourceName, sum(!known), + if (unknown == "keep") "kept" else "dropped", paste(taxa[!known], collapse = ", ")), call. = FALSE) + } + if (!any(kept)) { + stop(sprintf("None of the key's %d taxa has %s record%s in %s according to %s", length(taxa), + format(minRecords), if (minRecords == 1) "" else "s", where$label, sourceName), call. = FALSE) + } + if (sum(kept) == 1) { + stop(sprintf("Only one of the key's taxa is recorded in %s according to %s (%s), so there is nothing to key out", + where$label, sourceName, taxa[kept]), call. = FALSE) + } + out <- if (all(kept)) key$clone() else pruneKey(key, keep = taxa[kept], ranks = "exact", ...) + message(sprintf("Kept %d of %d taxa recorded in %s (%s)", sum(kept), length(taxa), where$label, sourceName)) + attr(out, "records") <- records + attr(out, "place") <- where$label + out +} + +#' Graft one key onto a result of another +#' +#' Joins two keys end to end: the lead of `key` that ended in the taxon `at` +#' now leads to the first couplet of `subkey`. Use it to put a key to the +#' genera of one family under a key to families, or a regional key under a +#' general one. +#' +#' The leads of the two keys are put in one table (a column that only one of +#' them has is left blank for the other), and so are their metadata, embedded +#' images, taxa and features. `key`'s title is kept; `subkey`'s citation is +#' added to `key`'s. If `at` is the result of several leads, they all lead to +#' the subkey. An embedded image or a feature that the two keys both have +#' under one id, with different contents, is kept apart by giving the +#' subkey's a new id (`_2` is added), with a warning for a feature. +#' +#' @param key A [dimoose] key. +#' @param subkey The [dimoose] key to graft onto it. +#' @param at The result of `key` that `subkey` continues from: its whole +#' label, the scientific name in its parentheses or the common name before +#' them (case does not matter). +#' It is an error if no result, or more than one, has that name; a shared +#' result is named in full (`"A / B"`). +#' @param labels How to keep couplet names unique. `"renumber"` numbers the +#' couplets of the merged key 1, 2, 3, ... in reading order, so the +#' subkey's couplets follow the lead they hang from. `"prefix"` keeps +#' `key`'s couplet names and puts `prefix` in front of the subkey's. +#' @param prefix Text put in front of the subkey's couplet names with +#' `labels = "prefix"`; by default the scientific name of `at` and a full +#' stop (`"Salicaceae.1"`). +#' @return A [dimoose] key. +#' @seealso [pruneKey()] +#' @examples +#' families <- keyFromLeads(data.frame( +#' Statement = c("1", "1"), Choice = c("a", "b"), +#' Character = c("Fruit an acorn", "Fruit a capsule releasing cottony seeds"), +#' Next = "-", Taxon = c("Fagaceae", "Salicaceae") +#' ), "Two families of trees") +#' salicaceae <- keyFromLeads(data.frame( +#' Statement = c("1", "1"), Choice = c("a", "b"), +#' Character = c("Buds with one scale", "Buds with several scales"), +#' Next = "-", Taxon = c("Salix", "Populus") +#' ), "Genera of Salicaceae") +#' both <- mergeKeys(families, salicaceae, at = "Salicaceae") +#' both$leads +#' mergeKeys(families, salicaceae, at = "Salicaceae", labels = "prefix")$leads$Statement +#' @export +mergeKeys <- function(key, subkey, at, labels = c("renumber", "prefix"), prefix = NULL) { + if (!inherits(key, "dimoose")) stop("`key` must be a dimoose object", call. = FALSE) + if (!inherits(subkey, "dimoose")) stop("`subkey` must be a dimoose object", call. = FALSE) + if (!is.character(at) || length(at) != 1 || is.na(at) || !nzchar(trimws(at))) { + stop("`at` must be the name of one result of `key`", call. = FALSE) + } + labels <- match.arg(labels) + main <- prnTidyLeads(key$leads) + sub <- prnTidyLeads(subkey$leads) + if (!nrow(sub)) stop("`subkey` has no leads", call. = FALSE) + mainRoot <- checkLeads(normalizeLeads(main))$root + subRoot <- checkLeads(normalizeLeads(sub))$root + + # The result to graft at: the one with that whole label, else the one with + # that scientific name. Several results of one name are not guessed between. + taxa <- unique(main$Taxon[main$Next == "-" & nzchar(main$Taxon)]) + hit <- taxa[prnNorm(taxa) == prnNorm(at)] + if (!length(hit)) hit <- taxa[prnMatchTaxa(taxa, at, "exact")$taxa] + if (!length(hit)) { + shared <- taxa[vapply(prnMembers(taxa), function(m) length(m) > 1 && prnNorm(at) %in% prnNorm(m), logical(1))] + if (length(shared)) { + stop("`at` (", at, ") is one of the taxa of the shared result \"", shared[1], + "\"; give the whole result to graft there", call. = FALSE) + } + stop("`at` (", at, ") is not a result of `key`; its results are: ", paste(taxa, collapse = ", "), call. = FALSE) + } + if (length(hit) > 1) { + stop("`at` (", at, ") is the name of ", length(hit), " results of `key`: ", paste(hit, collapse = "; "), + ". Give the whole label of one of them", call. = FALSE) + } + target <- which(main$Next == "-" & main$Taxon == hit) + + # Make the subkey's couplet names differ from the key's: a prefix, which + # stays (labels = "prefix") or is renumbered away below. + if (is.null(prefix)) { + sci <- scientificPart(hit) + prefix <- paste0(if (is.na(sci)) hit else sci, ".") + } + if (!is.character(prefix) || length(prefix) != 1 || is.na(prefix)) stop("`prefix` must be one string", call. = FALSE) + rename <- function(x) ifelse(x == "-", "-", paste0(prefix, x)) + while (any(rename(unique(sub$Statement)) %in% main$Statement)) prefix <- paste0(prefix, ".") + sub$Statement <- rename(sub$Statement) + sub$Next <- rename(sub$Next) + if (!is.null(sub$Prev)) sub$Prev <- NULL + + main$Next[target] <- rename(subRoot) + main$Taxon[target] <- "" + if (!is.null(main$TaxonUrl)) main$TaxonUrl[target] <- "" + + # Images: the same id with different contents in the two keys would show + # the wrong picture, so the subkey's image gets a new id, in its metadata + # (image_ and image_url_ together) and in its leads. A lead names + # an image by id or by a file or URL whose name without extension is the + # id; either way the name is changed. + mainMeta <- prnMeta(key$meta) + subMeta <- prnMeta(subkey$meta) + isImage <- grepl("^image_", subMeta$key) + imageId <- function(k) sub("^image_(url_)?", "", k) + differs <- isImage & subMeta$key %in% mainMeta$key & + !subMeta$value %in% NA & !(subMeta$value == mainMeta$value[match(subMeta$key, mainMeta$key)]) %in% TRUE + for (id in unique(imageId(subMeta$key[differs]))) { + taken <- function(x) any(paste0(c("image_", "image_url_"), x) %in% c(mainMeta$key, subMeta$key)) + newId <- paste0(id, "_2") + while (taken(newId)) newId <- paste0(newId, "_2") + rows <- isImage & imageId(subMeta$key) == id + subMeta$key[rows] <- paste0(ifelse(grepl("^image_url_", subMeta$key[rows]), "image_url_", "image_"), newId) + if (!is.null(sub$Image)) { + sub$Image <- vapply(as.character(sub$Image), function(x) { + entries <- trimws(splitUrls(x)) + file <- basename(entries) + extension <- regmatches(file, regexpr("\\.(gif|jpe?g|png|webp)$", file, ignore.case = TRUE)) + stem <- sub("\\.(gif|jpe?g|png|webp)$", "", file, ignore.case = TRUE) + same <- stem == id + entries[same] <- paste0(substr(entries[same], 1, nchar(entries[same]) - nchar(file[same])), newId, + substr(file[same], nchar(stem[same]) + 1, nchar(file[same]))) + paste(entries, collapse = ";") + }, character(1), USE.NAMES = FALSE) + } + } + subCitation <- metaValue(subMeta, "citation") + if (!is.na(subCitation) && nzchar(subCitation)) { + mainCitation <- metaValue(mainMeta, "citation") + both <- if (is.na(mainCitation) || !nzchar(mainCitation)) subCitation else { + if (identical(mainCitation, subCitation)) mainCitation else paste0(mainCitation, " ", hit, ": ", subCitation) + } + mainMeta <- prnSetMeta(mainMeta, "citation", both) + } + meta <- rbind(mainMeta, subMeta[!subMeta$key %in% mainMeta$key, , drop = FALSE]) + rownames(meta) <- NULL + + # Features: one id standing for two different features would have the + # subkey's leads tested against the key's feature, so the subkey's is + # renamed, in its table and in its leads. + features <- key$features + subFeatures <- subkey$features + if (is.null(features)) { + features <- subFeatures + } else if (!is.null(subFeatures)) { + if (!is.null(features$id) && !is.null(subFeatures$id)) { + shared <- intersect(names(features), names(subFeatures)) + rowOf <- function(f, id) lapply(f[match(id, f$id), shared, drop = FALSE], function(x) unname(x)) + clash <- Filter(function(id) !identical(rowOf(features, id), rowOf(subFeatures, id)), + intersect(subFeatures$id, features$id)) + for (id in clash) { + newId <- paste0(id, "_2") + while (newId %in% c(features$id, subFeatures$id)) newId <- paste0(newId, "_2") + subFeatures$id[subFeatures$id == id] <- newId + if (!is.null(sub$Feature)) sub$Feature[sub$Feature %in% id] <- newId + } + if (length(clash)) { + warning(sprintf("The two keys define %s differently; the subkey's is renamed %s", + paste(clash, collapse = ", "), paste(paste0(clash, "_2"), collapse = ", ")), call. = FALSE) + } + } + features <- prnBind(features, subFeatures) + if (!is.null(features$id)) features <- features[!duplicated(features$id), , drop = FALSE] + rownames(features) <- NULL + } + + if (!is.null(main$Prev)) main$Prev <- NULL + leads <- prnBind(main, sub) + if (labels == "renumber") leads <- prnRenumber(leads, mainRoot) + if (!is.null(key$leads$Prev)) leads$Prev <- prnPrev(leads, if (labels == "renumber") "1" else mainRoot) + rownames(leads) <- NULL + + left <- unique(leads$Taxon[leads$Next == "-" & nzchar(leads$Taxon)]) + allTaxa <- NULL + if (is.data.frame(key$taxa) && is.data.frame(subkey$taxa) && + "submitted_name" %in% names(key$taxa) && "submitted_name" %in% names(subkey$taxa)) { + allTaxa <- prnBind(key$taxa, subkey$taxa) + allTaxa <- allTaxa[!duplicated(allTaxa$submitted_name) & allTaxa$submitted_name %in% left, , drop = FALSE] + missingTaxa <- setdiff(left, allTaxa$submitted_name) + if (length(missingTaxa)) allTaxa <- NULL else rownames(allTaxa) <- NULL + } + keyFromLeads(leads, key$desc, meta, allTaxa, features) +} + +# ---- pruning internals ------------------------------------------------------- + +# How names are compared: lower case, single spaces, and the hybrid sign +# written one way ("Populus x acuminata", "Populus ×acuminata" and +# "Populus × acuminata" are the same name). +prnNorm <- function(x) { + x <- as.character(x) + x <- gsub("\u00d7", " \u00d7 ", x, fixed = TRUE) + x <- gsub("(^|\\s)x(?=\\s)", "\\1\u00d7", x, perl = TRUE) + tolower(gsub("\\s+", " ", trimws(x))) +} + +# The scientific name of each label: what is in its parentheses +# ("Bur oak (Quercus macrocarpa)"), unless that is the author of a name +# ("Carcharodon carcharias (Linnaeus, 1758)"), else the whole label. +prnSciName <- function(x) { + x <- as.character(x) + s <- scientificPart(x) + author <- !is.na(s) & grepl("^\\S*[.,]( |$)|&|[0-9]{4}| ex ", s) + s[author] <- NA + s[is.na(s)] <- x[is.na(s)] + s +} + +# A name without its author: everything from the first word (after the first) +# that opens a parenthesis or is an abbreviated or dated author ("Michx.", +# "L.", "A.Gray", "Linnaeus,") is left out. +prnStripAuthor <- function(x) { + vapply(strsplit(trimws(as.character(x)), "\\s+"), function(w) { + if (length(w) < 2) return(paste(w, collapse = " ")) + author <- which(grepl("^\\(|^[A-Z][[:alpha:]'.-]*[.,]$|^[A-Z]\\.[A-Z]|^&$", w)) + author <- author[author > 1] + if (length(author)) paste(w[seq_len(author[1] - 1)], collapse = " ") else paste(w, collapse = " ") + }, "") +} + +# The taxa of each result label: "A / B" is A and B. A label that ends in a +# scientific name in parentheses and has no other is one taxon, whatever +# slashes its common name has. +prnMembers <- function(labels) { + lapply(labels, function(x) { + parts <- trimws(strsplit(x, " / ", fixed = TRUE)[[1]]) + parts <- unique(parts[nzchar(parts)]) + if (length(parts) < 2) return(x) + if (!is.na(scientificPart(x)) && !any(grepl("(", parts[-length(parts)], fixed = TRUE))) return(x) + parts + }) +} + +# Every shorter run of whole words each string begins with ("a b c" gives +# "a" and "a b"), as a data frame of the string's index and the run. +prnWordPrefixes <- function(x) { + words <- strsplit(x, " ", fixed = TRUE) + n <- pmax(lengths(words) - 1L, 0L) + data.frame(i = rep(seq_along(x), n), + prefix = as.character(unlist(lapply(words[n > 0], function(w) Reduce(paste, w[-length(w)], accumulate = TRUE)))), + stringsAsFactors = FALSE) +} + +# Which of `taxa` (labels of a key) do the entries of `wanted` name? Returns +# list(taxa = logical per taxon, used = logical per entry of wanted). With +# ranks = "genus" a name also matches the names that begin with it (a genus +# its species, a species its subspecies, a name the same name with its +# author); with genusOfSpecies, an entry also matches the taxon it begins +# with (a species keeps its genus). +prnMatchTaxa <- function(taxa, wanted, ranks = "genus", genusOfSpecies = FALSE) { + wanted <- as.character(wanted) + wanted <- wanted[!is.na(wanted) & nzchar(trimws(wanted))] + bare <- function(x) sub("^\u00d7 ", "", prnNorm(x)) + label <- prnNorm(taxa); sci <- bare(prnSciName(taxa)) + wLabel <- prnNorm(wanted); wSci <- bare(prnSciName(wanted)) + hit <- label %in% c(wLabel, wSci) | sci %in% c(wLabel, wSci) + used <- wLabel %in% c(label, sci) | wSci %in% c(label, sci) + # the common name alone: what a label has before its last parentheses + # (parentheses that hold an author are part of the name) + common <- sub("\\s*\\([^()]*\\)$", "", label) + common[common == label | !nzchar(common) | prnSciName(taxa) == as.character(taxa)] <- NA + hit <- hit | common %in% wLabel + used <- used | wLabel %in% common + if (ranks == "genus" && length(wanted) && length(taxa)) { + # the same name, one of them with its author + sciBare <- bare(prnStripAuthor(prnSciName(taxa))) + wBare <- bare(prnStripAuthor(prnSciName(wanted))) + hit <- hit | sciBare %in% wSci | sci %in% wBare + used <- used | wSci %in% sciBare | wBare %in% sci + # a taxon below an entry: its name begins with the entry's words + below <- prnWordPrefixes(sci) + under <- below$prefix %in% c(wSci, wBare) + hit[below$i[under]] <- TRUE + used <- used | wSci %in% below$prefix | wBare %in% below$prefix + if (genusOfSpecies) { + above <- prnWordPrefixes(wSci) + over <- above$prefix %in% sci + used[above$i[over]] <- TRUE + hit <- hit | sci %in% above$prefix[over] + } + } + list(taxa = hit, used = stats::setNames(used, wanted)) +} + +prnWarnUnmatched <- function(used, arg) { + miss <- names(used)[!used] + if (length(miss)) { + warning(sprintf("%d name%s in `%s` matched no taxon of the key: %s", length(miss), + if (length(miss) == 1) "" else "s", arg, paste(miss, collapse = ", ")), call. = FALSE) + } + invisible(NULL) +} + +# Couplets that can be reached from `root`. +prnReachable <- function(leads, root) { + reachable <- root + frontier <- root + while (length(frontier)) { + nxt <- leads$Next[leads$Statement %in% frontier] + nxt <- setdiff(nxt[nxt != "-"], reachable) + reachable <- c(reachable, nxt) + frontier <- nxt + } + reachable +} + +# The couplets reachable from `root` (an index into `kids`, a list of the +# couplets each couplet's leads go to), each after the couplets below it. +prnPostOrder <- function(kids, root) { + seen <- rep(FALSE, length(kids)) + out <- integer(length(kids)) + done <- 0L + stack <- integer(64) + at <- integer(64) + depth <- 1L + stack[1] <- root + at[1] <- 0L + seen[root] <- TRUE + while (depth > 0L) { + cp <- stack[depth] + at[depth] <- at[depth] + 1L + if (at[depth] > length(kids[[cp]])) { + done <- done + 1L + out[done] <- cp + depth <- depth - 1L + next + } + kid <- kids[[cp]][at[depth]] + if (seen[kid]) next + seen[kid] <- TRUE + depth <- depth + 1L + if (depth > length(stack)) { + stack <- c(stack, integer(length(stack))) + at <- c(at, integer(length(at))) + } + stack[depth] <- kid + at[depth] <- 0L + } + out[seq_len(done)] +} + +# Take out every couplet whose leads all go to the same place (usually a +# couplet left with one lead). Leads into it take over that destination, and +# are handed what is true of everything beyond it: the text and pictures of +# a sole remaining lead, or, of several leads to one place, only the notes +# and pictures they all carry (their own texts differ, and say nothing). +# Couplets are settled from the ends of the key towards its start, so each +# is looked at once, after everything below it. +prnCollapse <- function(leads, root, note) { + n <- nrow(leads) + text <- function(x) { + x <- as.character(x) + x[is.na(x)] <- "" + x + } + # notes are lists of statements, written joined by "; " + items <- function(x) if (nzchar(x)) strsplit(x, "; ", fixed = TRUE)[[1]] else character() + common <- function(x) if (length(x) == 1) x[[1]] else Reduce(intersect, x) + couplets <- unique(leads$Statement) + couplet <- match(leads$Statement, couplets) + rowsOf <- split(seq_len(n), couplet) + nxt <- leads$Next + to <- match(nxt, couplets) # NA for a result + taxon <- leads$Taxon + character <- text(leads$Character) + oldNote <- if (is.null(leads$Note)) rep("", n) else text(leads$Note) + added <- vector("list", n) # statements handed to each lead + url <- if (is.null(leads$TaxonUrl)) NULL else leads$TaxonUrl + image <- if (is.null(leads$Image)) NULL else text(leads$Image) + link <- if (is.null(leads$ImageLink)) NULL else text(leads$ImageLink) + notesOf <- function(i, own) c(if (own) items(character[i]), items(oldNote[i]), added[[i]]) + + kids <- lapply(rowsOf, function(r) unique(to[r][!is.na(to[r])])) + gone <- rep(FALSE, n) + heir <- rep(NA_integer_, length(couplets)) # a lead of each collapsed couplet, for where it goes + handNotes <- vector("list", length(couplets)) # what each collapsed couplet hands on + handImage <- handLink <- vector("list", length(couplets)) + for (cp in prnPostOrder(kids, match(root, couplets))) { + rows <- rowsOf[[cp]] + for (i in rows[!is.na(to[rows])]) { + below <- to[i] + l <- heir[below] + if (is.na(l)) next + if (length(handNotes[[below]])) added[[i]] <- c(added[[i]], handNotes[[below]]) + if (!is.null(image)) image[i] <- paste(unique(c(splitUrls(image[i]), handImage[[below]])), collapse = ";") + if (!is.null(link)) link[i] <- paste(unique(c(splitUrls(link[i]), handLink[[below]])), collapse = ";") + nxt[i] <- nxt[l] + to[i] <- to[l] + taxon[i] <- taxon[l] + if (!is.null(url)) url[i] <- url[l] + } + dest <- ifelse(nxt[rows] == "-", paste0("-\r", taxon[rows]), nxt[rows]) + if (length(unique(dest)) > 1) next + heir[cp] <- rows[1] + sole <- length(rows) == 1 + # (a list element is set with [<- so that an empty value does not remove it) + if (note != "none") handNotes[cp] <- list(common(lapply(rows, notesOf, own = sole))) + if (!is.null(image)) handImage[cp] <- list(common(lapply(image[rows], splitUrls))) + if (!is.null(link)) handLink[cp] <- list(common(lapply(link[rows], splitUrls))) + gone[rows] <- TRUE + } + + rootNotes <- character() + first <- match(root, couplets) + if (!is.na(heir[first])) { + l <- heir[first] + if (nxt[l] == "-") return(list(leads = leads[0, , drop = FALSE], root = NA_character_, rootNotes = rootNotes)) + root <- nxt[l] + if (length(handNotes[[first]])) rootNotes <- paste(handNotes[[first]], collapse = "; ") + } + leads$Next <- nxt + leads$Taxon <- taxon + if (!is.null(url)) leads$TaxonUrl <- url + if (!is.null(image)) leads$Image[!gone] <- image[!gone] + if (!is.null(link)) leads$ImageLink[!gone] <- link[!gone] + more <- lengths(added) > 0 + if (note == "column" && (any(more) || !is.null(leads$Note))) { + oldNote[more] <- vapply(which(more), function(i) paste(notesOf(i, own = FALSE), collapse = "; "), "") + leads$Note <- oldNote + } else if (note == "append" && any(more)) { + leads$Character[more] <- paste0(character[more], " [", vapply(added[more], paste, "", collapse = "; "), "]") + } + list(leads = leads[!gone, , drop = FALSE], root = root, rootNotes = rootNotes) +} + +# The Prev column of FishBase keys: the couplet each couplet is reached from +# (the first, for a couplet reached from several); the root names itself. +prnPrev <- function(leads, root) { + from <- leads$Statement[match(leads$Statement, leads$Next)] + ifelse(is.na(from), leads$Statement, from) +} + +# Number the couplets 1..n in reading order: depth first from the root, +# leads in order, a couplet reached twice numbered where it is first met. +prnRenumber <- function(leads, root) { + couplets <- unique(leads$Statement) + to <- match(leads$Next, couplets) + kids <- lapply(split(to, factor(leads$Statement, levels = couplets)), function(x) unique(x[!is.na(x)])) + numbered <- rep(FALSE, length(couplets)) + order <- integer(length(couplets)) + done <- 0L + stack <- match(root, couplets) + while (length(stack)) { + cp <- stack[1] + stack <- stack[-1] + if (numbered[cp]) next + numbered[cp] <- TRUE + done <- done + 1L + order[done] <- cp + stack <- c(kids[[cp]][!numbered[kids[[cp]]]], stack) + } + order <- c(order[seq_len(done)], which(!numbered)) + number <- character(length(couplets)) + number[order] <- as.character(seq_along(order)) + leads$Next[!is.na(to)] <- number[to[!is.na(to)]] + leads$Statement <- number[match(leads$Statement, couplets)] + if (!is.null(leads$Prev)) leads$Prev <- prnPrev(leads, "1") + leads <- leads[order(as.integer(leads$Statement)), , drop = FALSE] + rownames(leads) <- NULL + leads +} + +# A key's meta as a key/value data frame of strings (empty if it has none). +prnMeta <- function(meta) { + if (!is.data.frame(meta) || !all(c("key", "value") %in% names(meta))) { + return(data.frame(key = character(), value = character(), stringsAsFactors = FALSE)) + } + data.frame(key = as.character(meta$key), value = as.character(meta$value), stringsAsFactors = FALSE) +} + +prnSetMeta <- function(meta, key, value) { + meta <- prnMeta(meta) + if (key %in% meta$key) { + meta$value[meta$key == key] <- value + meta + } else { + rbind(meta, data.frame(key = key, value = value, stringsAsFactors = FALSE)) + } +} + +# Ids of the images a lead table shows (the file name without extension of +# each entry of Image, as exportWizard() reads them). +prnImageIds <- function(leads) { + if (is.null(leads$Image)) return(character()) + x <- as.character(leads$Image) + x <- unlist(strsplit(x[!is.na(x) & nzchar(x)], ";", fixed = TRUE)) + unique(sub("\\.(gif|jpe?g|png|webp)$", "", basename(trimws(x)), ignore.case = TRUE)) +} + +# Drop the image_ and image_url_ rows of meta for images the old leads +# showed and the new ones do not. Images no lead ever showed (such as the +# example crops of features) are left alone. +prnDropImages <- function(meta, oldLeads, newLeads) { + meta <- prnMeta(meta) + gone <- setdiff(prnImageIds(oldLeads), prnImageIds(newLeads)) + if (!length(gone)) return(meta) + out <- meta[!meta$key %in% c(paste0("image_", gone), paste0("image_url_", gone)), , drop = FALSE] + rownames(out) <- NULL + out +} + +prnSubsetTaxa <- function(taxa, left) { + if (!is.data.frame(taxa) || !"submitted_name" %in% names(taxa)) return(NULL) + out <- taxa[taxa$submitted_name %in% left, , drop = FALSE] + if (!all(left %in% out$submitted_name)) return(NULL) + rownames(out) <- NULL + out +} + +prnSubsetFeatures <- function(features, leads) { + if (is.null(features) || is.null(features$id) || is.null(leads$Feature)) return(features) + used <- unique(leads$Feature[!is.na(leads$Feature) & nzchar(leads$Feature)]) + out <- features[features$id %in% used, , drop = FALSE] + rownames(out) <- NULL + out +} + +# Leads with the columns the logic reads cleaned up as normalizeLeads() does, +# and every other column left as it is. +prnTidyLeads <- function(leads) { + leads <- as.data.frame(leads, stringsAsFactors = FALSE) + norm <- normalizeLeads(leads) + for (col in c("Statement", "Next", "Taxon")) leads[[col]] <- norm[[col]] + leads +} + +# rbind for two data frames whose columns differ: a column one lacks is blank +# ("" for text, NA otherwise, NULL in list columns) in its rows. +prnBind <- function(a, b) { + blank <- function(like, n) { + if (is.list(like)) return(vector("list", n)) + if (is.character(like) || is.factor(like)) return(rep("", n)) + rep(like[NA_integer_][1], n) + } + for (col in setdiff(names(b), names(a))) a[[col]] <- blank(b[[col]], nrow(a)) + for (col in setdiff(names(a), names(b))) b[[col]] <- blank(a[[col]], nrow(b)) + for (col in names(a)) { + if (is.factor(a[[col]])) a[[col]] <- as.character(a[[col]]) + if (is.factor(b[[col]])) b[[col]] <- as.character(b[[col]]) + if (is.character(a[[col]]) != is.character(b[[col]]) && !is.list(a[[col]]) && !is.list(b[[col]])) { + a[[col]] <- as.character(a[[col]]) + b[[col]] <- as.character(b[[col]]) + } + } + out <- rbind(a, b[names(a)]) + rownames(out) <- NULL + out +} + +# ---- occurrence lookups ------------------------------------------------------ + +# GET `url` with `query` and return the parsed JSON. iNaturalist asks for +# about a request a second. A server that is busy (HTTP 429), failing (5xx) +# or cannot be reached is asked again, `tries` times in all, after the wait +# it asks for (Retry-After) or 5 and then 10 seconds. `wait` and `get` are +# there to be replaced in tests. +prnFetch <- function(url, query = list(), tries = 3, wait = Sys.sleep, get = httr::GET) { + query <- query[!vapply(query, is.null, logical(1))] + host <- sub("^https?://([^/]+).*$", "\\1", url) + for (try in seq_len(tries)) { + if (grepl("inaturalist.org", url, fixed = TRUE)) wait(1) + r <- tryCatch(get(url, query = query, dimooseUserAgent(), httr::timeout(60)), error = function(e) e) + unreachable <- inherits(r, "error") + if (!unreachable && httr::status_code(r) != 429 && httr::status_code(r) < 500) break + if (try == tries) break + asked <- if (unreachable) NA_real_ else suppressWarnings(as.numeric(c(httr::headers(r)[["retry-after"]], NA)[1])) + wait(if (is.na(asked)) 5 * try else min(max(asked, 1), 60)) + } + if (inherits(r, "error")) stop("Could not reach ", host, ": ", conditionMessage(r), call. = FALSE) + httr::stop_for_status(r, task = paste("ask", host)) + httr::content(r, as = "parsed", type = "application/json", encoding = "UTF-8") +} + +# `fetch`, with an error that says what was being asked when it failed. +prnAsk <- function(fetch, url, query, doing) { + tryCatch(fetch(url, query), error = function(e) { + stop(sprintf("The request failed while %s, so nothing was pruned: %s", doing, conditionMessage(e)), call. = FALSE) + }) +} + +prnGbifApi <- "https://api.gbif.org/v1/" +prnInatApi <- "https://api.inaturalist.org/v1/" + +# Turn `place` into GBIF occurrence search parameters and a name to show. +prnGbifPlace <- function(place, fetch) { + if (is.list(place)) { + if (!length(place) || is.null(names(place)) || any(!nzchar(names(place)))) { + stop("A list given as `place` must be named GBIF occurrence search parameters, ", + "such as list(country = \"US\", stateProvince = \"Montana\")", call. = FALSE) + } + label <- paste(sprintf("%s=%s", names(place), vapply(place, function(x) paste(x, collapse = "|"), "")), collapse = ", ") + return(list(query = place, label = label)) + } + if (!is.character(place) || length(place) != 1 || is.na(place) || !nzchar(trimws(place))) { + stop("`place` must be one string or a named list of GBIF search parameters", call. = FALSE) + } + place <- trimws(place) + if (grepl("^(MULTI)?POLYGON", place, ignore.case = TRUE)) { + return(list(query = list(geometry = place), label = "the polygon given")) + } + if (grepl("^[A-Z]{3}(\\.[0-9]+)*(_[0-9]+)?$", place)) { + return(list(query = list(gadmGid = place), label = paste("GADM region", place))) + } + if (grepl("^[A-Z]{2}$", place)) { + return(list(query = list(country = place), label = paste("country", place))) + } + region <- prnGadmSearch(place, fetch) + above <- vapply(region$higherRegions, function(h) h$name, "") + list(query = list(gadmGid = region$id), + label = sprintf("%s (GADM %s)", paste(c(region$name, rev(above)), collapse = ", "), region$id)) +} + +# Other ways of writing a few countries, by GADM id (GADM itself has only +# the one name, and no two-letter codes). +prnCountryAliases <- list( + USA = c("us", "usa", "u.s.", "u.s.a.", "united states of america"), + GBR = c("uk", "u.k.", "gb", "great britain", "britain"), + CAN = "ca", MEX = "mx", AUS = "au", NZL = "nz", DEU = c("de", "deutschland"), FRA = "fr", CHE = "ch" +) + +# Find one GADM region by name. Parts after commas name regions it lies in, +# by GADM's name or id for them or another name GADM lists ("MT" for +# Montana). A word for the kind of region ("Flathead County") is allowed. +prnGadmSearch <- function(place, fetch) { + parts <- trimws(strsplit(place, ",", fixed = TRUE)[[1]]) + parts <- parts[nzchar(parts)] + if (!length(parts)) stop("`place` names no region", call. = FALSE) + search <- function(q) { + res <- prnAsk(fetch, paste0(prnGbifApi, "geocode/gadm/search"), list(q = q, limit = 100), + paste0("looking up the region \"", q, "\" in GADM"))$results + if (is.null(res)) list() else res + } + called <- function(found, name) { + found[vapply(found, function(r) prnNorm(name) %in% prnNorm(c(r$name, unlist(r$variantName))), logical(1))] + } + describe <- function(r) { + above <- vapply(r$higherRegions, function(h) h$name, "") + sprintf("%s (%s)", paste(c(r$name, rev(above)), collapse = ", "), r$id) + } + listed <- function(found) { + paste0(paste(vapply(found[seq_len(min(10, length(found)))], describe, ""), collapse = "; "), + if (length(found) > 10) "; ..." else "") + } + + found <- search(parts[1]) + exact <- called(found, parts[1]) + kinds <- "county|parish|borough|district|province|state|department|region|municipality|prefecture|canton" + short <- sub(paste0("\\s+(", kinds, ")$"), "", parts[1], ignore.case = TRUE) + if (!length(exact) && short != parts[1]) { + more <- search(short) + exact <- called(more, short) + # "Lake County" is the Lake that is a county, if one is + kind <- tolower(sub("^.*\\s", "", parts[1])) + ofKind <- vapply(exact, function(r) kind %in% tolower(unlist(c(r$type, r$englishType))), logical(1)) + if (any(ofKind)) exact <- exact[ofKind] + if (!length(found)) found <- more + } + if (length(exact)) found <- exact + if (!length(found)) { + stop("GBIF knows no GADM region called \"", parts[1], "\"; give its GADM id (see https://gadm.org) ", + "or a list of GBIF search parameters", call. = FALSE) + } + + # other names of a region that candidates lie in, asked for only when a + # hint matches no candidate by GADM's own name + otherNames <- new.env(parent = emptyenv()) + variants <- function(above) { + if (is.null(otherNames[[above$id]])) { + same <- Filter(function(r) identical(r$id, above$id), search(above$name)) + otherNames[[above$id]] <- c("", if (length(same)) prnNorm(unlist(same[[1]]$variantName))) + } + otherNames[[above$id]] + } + liesIn <- function(r, hint, deep) { + for (above in r$higherRegions) { + if (hint %in% c(prnNorm(above$name), prnNorm(above$id), prnCountryAliases[[above$id]])) return(TRUE) + if (deep && hint %in% variants(above)) return(TRUE) + } + FALSE + } + for (hint in parts[-1]) { + ok <- vapply(found, liesIn, logical(1), hint = prnNorm(hint), deep = FALSE) + if (!any(ok) && length(found) <= 60) ok <- vapply(found, liesIn, logical(1), hint = prnNorm(hint), deep = TRUE) + if (!any(ok)) { + stop("GBIF knows no GADM region \"", parts[1], "\" in \"", hint, "\". It knows: ", listed(found), + ". Name the region it lies in as shown, or give the GADM id in brackets as `place`", call. = FALSE) + } + found <- found[ok] + } + if (length(found) > 1 && !length(exact)) { + stop("GBIF knows no GADM region called \"", parts[1], "\". The nearest names are: ", listed(found), + ". Give the name as shown, or the GADM id in brackets as `place`", call. = FALSE) + } + if (length(found) > 1) { + stop("\"", place, "\" could be any of ", length(found), " GADM regions: ", listed(found), + ". Add the region it lies in after a comma, or give the GADM id in brackets as `place`", call. = FALSE) + } + found[[1]] +} + +# GBIF's match for a name, as list(id, name), or NULL when it has none. The +# id is the accepted name's when the name is a synonym, and the species' when +# a species name is filed under one of its subspecies (records identified to +# the species would not be counted there). A name GBIF has several equal +# matches for, as it has for many genera ("Betula" is a genus of plants and +# an old one of animals), is settled from the alternatives it lists: the +# accepted one of that exact name, and for a single word not a species. +prnGbifUsage <- function(m, name) { + type <- if (is.null(m$matchType)) "NONE" else m$matchType + if (type == "NONE" && length(m$alternatives)) { + alt <- Filter(function(a) !is.null(a$canonicalName) && !is.null(a$usageKey) && + prnNorm(a$canonicalName) == prnNorm(prnStripAuthor(name)), m$alternatives) + narrow <- function(alt, keep) if (any(keep)) alt[keep] else alt + alt <- narrow(alt, vapply(alt, function(a) identical(a$status, "ACCEPTED"), logical(1))) + if (!grepl(" ", trimws(name), fixed = TRUE)) { + alt <- narrow(alt, vapply(alt, function(a) !isTRUE(a$rank %in% c("SPECIES", "SUBSPECIES", "VARIETY", "FORM")), logical(1))) + } + if (length(alt) != 1) return(NULL) + m <- alt[[1]] + type <- "EXACT" + } + # HIGHERRANK: GBIF knows only a taxon above the one asked for + if (type %in% c("NONE", "HIGHERRANK") || is.null(m$usageKey)) return(NULL) + id <- if (is.null(m$acceptedUsageKey)) m$usageKey else m$acceptedUsageKey + shown <- if (is.null(m$canonicalName)) m$scientificName else m$canonicalName + if (identical(m$rank, "SPECIES") && !is.null(m$speciesKey) && !is.null(m$acceptedUsageKey) && m$speciesKey != id) { + id <- m$speciesKey + if (!is.null(m$species)) shown <- m$species + } + list(id = id, name = shown) +} + +# Records of each name in a place, from GBIF: data frame matched, id, records. +prnGbifCounts <- function(name, placeQuery, kingdom, filters, fetch) { + out <- data.frame(matched = rep(NA_character_, length(name)), id = NA_character_, records = NA_real_, + stringsAsFactors = FALSE) + for (i in seq_along(name)) { + doing <- sprintf("asking GBIF about %s (taxon %d of %d)", name[i], i, length(name)) + usage <- prnGbifUsage(prnAsk(fetch, paste0(prnGbifApi, "species/match"), + list(name = name[i], kingdom = kingdom, verbose = "true"), doing), name[i]) + if (is.null(usage)) next + query <- utils::modifyList(c(list(taxonKey = usage$id, occurrenceStatus = "PRESENT"), placeQuery), filters) + query$limit <- 0 + res <- prnAsk(fetch, paste0(prnGbifApi, "occurrence/search"), query, doing) + if (is.null(res$count)) stop("GBIF returned no count for ", name[i], call. = FALSE) + out$matched[i] <- usage$name + out$id[i] <- as.character(usage$id) + out$records[i] <- as.numeric(res$count) + } + out +} + +# Turn `place` into an iNaturalist place_id and a name to show. Parts after +# commas must be among the parts of the place's full name ("Lake County, MT"). +prnInatPlace <- function(place, fetch) { + if (length(place) != 1 || is.na(place) || !(is.numeric(place) || is.character(place)) || + !nzchar(trimws(as.character(place)))) { + stop("`place` must be the name or numeric id of one iNaturalist place", call. = FALSE) + } + if (is.numeric(place)) place <- format(place, scientific = FALSE, trim = TRUE) + place <- trimws(place) + if (grepl("^[0-9]+$", place)) { + return(list(query = list(place_id = place), label = paste("iNaturalist place", place))) + } + search <- function(q) { + prnAsk(fetch, paste0(prnInatApi, "places/autocomplete"), list(q = q, per_page = 20), + paste0("looking up the place \"", q, "\" in iNaturalist"))$results + } + parts <- trimws(strsplit(place, ",", fixed = TRUE)[[1]]) + parts <- parts[nzchar(parts)] + res <- search(place) + wanted <- place + if (!length(res) && length(parts) > 1) { + res <- search(parts[1]) + wanted <- parts[1] + } + if (!length(res)) stop("iNaturalist knows no place called \"", wanted, "\"", call. = FALSE) + full <- vapply(res, function(r) if (is.null(r$display_name)) r$name else r$display_name, "") + short <- vapply(res, function(r) if (is.null(r$name)) "" else r$name, "") + if (wanted != place) { + # the places whose full name has every part given after the commas + usa <- prnCountryAliases$USA + fits <- vapply(full, function(f) { + have <- prnNorm(strsplit(f, ",", fixed = TRUE)[[1]]) + if (any(have %in% usa)) have <- c(have, usa) + all(prnNorm(parts[-1]) %in% have) + }, logical(1)) + if (!any(fits)) { + stop("iNaturalist knows no place \"", parts[1], "\" in \"", paste(parts[-1], collapse = ", "), "\". It knows: ", + paste(sprintf("%s (id %s)", full, vapply(res, function(r) as.character(r$id), "")), collapse = "; "), + ". Give the id of the one you mean as `place`", call. = FALSE) + } + res <- res[fits]; full <- full[fits]; short <- short[fits] + } + # the place of exactly that name, else one whose full name starts with it + # ("Flathead County" for "Flathead County, US, MT"), else the first found + # Of several of one name, a country or state comes before a county, a + # town or a park, and a larger place before a smaller one ("Montana" is + # the state, not the Bulgarian province or a park of that name). + number <- function(field, missing) { + vapply(res, function(r) if (is.numeric(r[[field]]) && length(r[[field]]) == 1) as.numeric(r[[field]]) else missing, 0) + } + rank <- order(number("admin_level", Inf), -number("bbox_area", 0)) + byRank <- function(i) i[order(match(i, rank))] + exact <- byRank(which(prnNorm(full) == prnNorm(wanted) | prnNorm(short) == prnNorm(wanted))) + starts <- byRank(which(startsWith(prnNorm(full), paste0(prnNorm(wanted), ",")))) + pick <- c(exact, starts, 1L)[1] + id <- vapply(res, function(r) as.character(r$id), "") + if (length(res) > 1) { + others <- setdiff(c(exact, starts, seq_along(res)), pick) + shown <- others[seq_len(min(5, length(others)))] + message(sprintf("Using iNaturalist place %s (id %s); %d other place%s matched \"%s\": %s%s. To use another, give its id as `place`", + full[pick], id[pick], length(others), if (length(others) == 1) "" else "s", place, + paste(sprintf("%s (id %s)", full[shown], id[shown]), collapse = "; "), + if (length(others) > length(shown)) "; ..." else "")) + } + list(query = list(place_id = id[pick]), label = sprintf("%s (iNaturalist place %s)", full[pick], id[pick])) +} + +# The iNaturalist taxon a name stands for: its exact name, or a name +# iNaturalist files under another (a synonym). NULL if there is none. +# iNaturalist writes subspecies and varieties without "subsp." or "var.". +prnInatTaxon <- function(name, fetch, within = NULL) { + unranked <- function(x) gsub(" (subsp|ssp|var|subvar|f|forma)\\.? ", " ", x, ignore.case = TRUE) + plain <- function(x) prnNorm(unranked(x)) + res <- prnAsk(fetch, paste0(prnInatApi, "taxa"), + list(q = unranked(trimws(name)), is_active = "true", taxon_id = within, per_page = 30), + paste("asking iNaturalist about", name))$results + if (!length(res)) return(NULL) + nm <- plain(vapply(res, function(r) if (is.null(r$name)) "" else r$name, "")) + term <- plain(vapply(res, function(r) if (is.null(r$matched_term)) "" else r$matched_term, "")) + pick <- c(which(nm == plain(name)), which(term == plain(name))) + if (!length(pick)) NULL else res[[pick[1]]] +} + +# Records of each name in a place, from iNaturalist: data frame matched, id, +# records. One species list for the place, then each name counted in it. The +# list has nothing below species, so a subspecies or variety is counted with +# a request of its own; so is every name not on the first page when the list +# is too long to read through. +prnInatCounts <- function(name, placeQuery, kingdom, filters, fetch) { + within <- NULL + if (!is.null(kingdom)) { + if (is.numeric(kingdom) || grepl("^[0-9]+$", kingdom)) { + within <- format(kingdom, scientific = FALSE, trim = TRUE) + } else { + tx <- prnInatTaxon(kingdom, fetch) + if (is.null(tx)) stop("iNaturalist knows no taxon called \"", kingdom, "\"", call. = FALSE) + within <- as.character(tx$id) + } + } + base <- utils::modifyList(c(placeQuery, list(quality_grade = "research", taxon_id = within)), filters) + species <- list() + page <- 1 + listed <- TRUE + repeat { + res <- prnAsk(fetch, paste0(prnInatApi, "observations/species_counts"), c(base, list(per_page = 500, page = page)), + sprintf("listing the species iNaturalist has for the place (page %d)", page)) + species <- c(species, res$results) + total <- if (is.null(res$total_results)) length(species) else res$total_results + if (!length(res$results) || length(species) >= total) break + # A place with very many species (a country, with no `kingdom` given) + # would take more pages than asking about each taxon takes requests. + if (page == 1 && ceiling((total - length(species)) / length(species)) > 2 * length(name)) { + listed <- FALSE + message(sprintf("iNaturalist has %s species for the place, so each of the key's %d taxa is asked about instead%s", + format(total, big.mark = ","), length(name), + if (is.null(kingdom)) " (give `kingdom` to list fewer)" else "")) + break + } + page <- page + 1 + } + spName <- prnNorm(vapply(species, function(s) if (is.null(s$taxon$name)) "" else s$taxon$name, "")) + spShown <- vapply(species, function(s) if (is.null(s$taxon$name)) "" else s$taxon$name, "") + spId <- vapply(species, function(s) as.character(s$taxon$id), "") + spCount <- vapply(species, function(s) as.numeric(s$count), 0) + spAncestors <- lapply(species, function(s) as.character(unlist(s$taxon$ancestor_ids))) + + out <- data.frame(matched = rep(NA_character_, length(name)), id = NA_character_, records = NA_real_, + stringsAsFactors = FALSE) + for (i in seq_along(name)) { + direct <- which(spName == prnNorm(name[i])) + if (length(direct)) { + out$matched[i] <- spShown[direct[1]] + out$id[i] <- spId[direct[1]] + out$records[i] <- sum(spCount[direct]) + next + } + tx <- prnInatTaxon(name[i], fetch, within) + if (is.null(tx)) next + id <- as.character(tx$id) + out$matched[i] <- tx$name + out$id[i] <- id + if (!listed || (!is.null(tx$rank_level) && tx$rank_level < 10)) { + one <- utils::modifyList(base, list(taxon_id = id, per_page = 0)) + res <- prnAsk(fetch, paste0(prnInatApi, "observations"), one, paste("asking iNaturalist about", name[i])) + out$records[i] <- if (is.null(res$total_results)) NA_real_ else as.numeric(res$total_results) + } else { + below <- spId == id | vapply(spAncestors, function(a) id %in% a, logical(1)) + out$records[i] <- sum(spCount[below]) + } + } + out +} diff --git a/R/quality.R b/R/quality.R new file mode 100644 index 0000000..ea3641e --- /dev/null +++ b/R/quality.R @@ -0,0 +1,472 @@ +#' How quickly a key gets to a result +#' +#' Counts the steps (couplets answered) it takes to reach each result of a +#' key and compares the average with the fewest steps any key could need. +#' +#' A key is a code: each result is spelled by the leads chosen on the way to +#' it. `bound` is the expected number of steps of the best key there could +#' be for the same taxa and the same `weights`, among keys whose couplets +#' have no more leads than the largest couplet of this key (`maxLeads`). It +#' is found by Huffman's construction, which joins the rarest taxa first, so +#' it is a number of steps that a key can really reach: 3 for eight equally +#' common taxa and couplets of two leads, about 3.55 for eleven. No key can +#' do better, however its characters are chosen. `efficiency` is +#' `bound / expectedSteps`: 1 for a key that could not be shorter, and lower +#' the more steps the key takes than it would have to. Real keys rarely +#' reach 1, because the characters that would split the taxa evenly may not +#' exist. +#' +#' When some taxa are met more often than others (`weights`), a good key +#' asks few questions before reaching the common ones, and the bound takes +#' the weights into account in the same way. +#' +#' In a key that has a few large couplets among many small ones (a +#' PhyloTree key has couplets of 2 and of 87 leads), the best key is allowed +#' the largest couplet everywhere, so the bound is far below what the key +#' does and `efficiency` is low. Three more numbers describe such keys +#' without that comparison. `entropy` is the Shannon entropy of the weights +#' in bits (`log2` of the number of taxa when they are equally common): the +#' information a key has to gather. A couplet with `k` leads can give up to +#' `log2(k)` bits, and `bitsPerStep` is the average of that over the steps +#' this key takes (1 for a key of two-lead couplets). `capacityUsed` is +#' `entropy / (bitsPerStep * expectedSteps)`: the share of the information +#' its couplets could give that the key needs. It is 1 when every couplet +#' splits what reaches it evenly, whatever its size, and it is not a +#' comparison with a shorter key. +#' +#' Two cases need a rule: +#' +#' * A taxon that keys out at several terminal leads counts once: its steps +#' are the mean over its leads, as if its specimens were split evenly +#' among them, and its weight is not multiplied by the number of leads. +#' * A couplet reached from several leads (a reticulate key) is counted by +#' its shortest route from the first couplet, so `steps` is the fewest +#' steps in which a result can be reached. `depth` is the longest route. +#' +#' Leads in couplets that cannot be reached from the first couplet, and +#' terminal leads that name no taxon, are left out of the averages. +#' +#' @param key A [dimoose] key. +#' @param weights How common each taxon is: a numeric vector whose names +#' are the key's results as written in its `Taxon` column, such as the +#' output of [occurrenceWeights()]. They need not sum to 1, and names +#' that are not in the key are ignored. Taxa that are missing from it or +#' `NA` count as 0, with a warning. A vector without names is an error, +#' as is a name that is there twice. `NULL` (the default) treats all taxa +#' as equally common. +#' @return A list with +#' * `taxa`: a data frame with one row per taxon: `Taxon`, `leads` (how +#' many terminal leads end in it), `steps` (mean over those leads), +#' `minSteps`, `maxSteps` and `weight` (its share of the weights, summing +#' to 1); +#' * `leads`: a data frame with one row per terminal lead: `Lead` (its +#' label, e.g. `"7b"`), `Statement`, `Choice`, `Taxon` and `steps`; +#' * `meanLeadSteps`: mean steps over terminal leads; +#' * `meanTaxonSteps`: mean steps over taxa; +#' * `expectedSteps`: mean steps over taxa weighted by `weight` (the same +#' as `meanTaxonSteps` without `weights`); +#' * `bound`: the expected steps of the best possible key to these taxa +#' with these weights and couplets of at most `maxLeads` leads; +#' * `efficiency`: `bound / expectedSteps`, above 0 and at most 1 (`NA` +#' for a key to a single taxon, which needs no steps); +#' * `entropy`: the Shannon entropy of `weight`, in bits; +#' * `bitsPerStep`: the most a step of this key can tell, on average +#' (1 when every couplet has two leads); +#' * `capacityUsed`: `entropy / (bitsPerStep * expectedSteps)`, at most 1; +#' * `maxLeads`: the number of leads in the key's largest couplet; +#' * `depth`: the longest route to a result, in steps. +#' @seealso `summary()` on a key, which reports the aggregates; +#' [occurrenceWeights()] for weights from GBIF. +#' @examples +#' q <- keyQuality(arachnidaKey()) +#' q$taxa +#' q$expectedSteps +#' q$bound +#' q$efficiency +#' +#' # spiders and mites are met far more often than the other orders +#' common <- c(Araneae = 50, Acari = 40, Opiliones = 5, Scorpiones = 3) +#' suppressWarnings(keyQuality(arachnidaKey(), common))$expectedSteps +#' @export +keyQuality <- function(key, weights = NULL) { + if (!inherits(key, "dimoose")) stop("`key` must be a dimoose object", call. = FALSE) + leads <- normalizeLeads(key$leads) + check <- checkLeads(leads) + depths <- qualCoupletDepths(leads, check) + label <- leadLabels(leads) + + at <- match(leads$Statement, check$couplets) + terminal <- which(leads$Next == "-" & !is.na(depths$shortest[at])) + leadTable <- data.frame( + Lead = label[terminal], Statement = leads$Statement[terminal], Choice = leads$Choice[terminal], + Taxon = leads$Taxon[terminal], steps = depths$shortest[at[terminal]] + 1, + stringsAsFactors = FALSE + ) + named <- leadTable[nzchar(leadTable$Taxon), , drop = FALSE] + taxon <- unique(named$Taxon) + byTaxon <- split(named$steps, factor(named$Taxon, levels = taxon)) + taxa <- data.frame( + Taxon = taxon, + leads = as.integer(lengths(byTaxon)), + steps = vapply(byTaxon, mean, 0), + minSteps = vapply(byTaxon, min, 0), + maxSteps = vapply(byTaxon, max, 0), + stringsAsFactors = FALSE + ) + taxa$weight <- qualWeights(taxon, weights) + rownames(taxa) <- NULL + + size <- as.numeric(table(factor(leads$Statement, levels = check$couplets))) + reached <- !is.na(depths$shortest) + maxLeads <- if (any(reached)) as.integer(max(size[reached])) else 0L + none <- nrow(taxa) == 0 + expected <- if (none) NA_real_ else sum(taxa$weight * taxa$steps) + p <- taxa$weight[taxa$weight > 0] + entropy <- if (none) NA_real_ else -sum(p * log2(p)) + # The chance of coming through each couplet, with a taxon's weight split + # evenly among its leads; the bits its leads could tell apart are log2(size) + bitsPerStep <- NA_real_ + if (!none) { + share <- taxa$weight[match(named$Taxon, taxon)] / taxa$leads[match(named$Taxon, taxon)] + visit <- qualVisitProbability(match(named$Statement, check$couplets), share, depths) + bitsPerStep <- sum(visit * log2(pmax(size, 1))) / sum(visit) + } + bound <- if (none) NA_real_ else qualOptimalSteps(taxa$weight, maxLeads) + capacity <- if (none || !isTRUE(bitsPerStep > 0)) NA_real_ else min(1, entropy / (bitsPerStep * expected)) + list( + taxa = taxa, + leads = leadTable, + meanLeadSteps = if (nrow(named)) mean(named$steps) else NA_real_, + meanTaxonSteps = if (none) NA_real_ else mean(taxa$steps), + expectedSteps = expected, + bound = bound, + efficiency = if (is.na(bound) || bound <= 0) NA_real_ else min(1, bound / expected), + entropy = entropy, + bitsPerStep = bitsPerStep, + capacityUsed = capacity, + maxLeads = maxLeads, + depth = if (length(terminal)) as.integer(max(depths$longest[at[terminal]]) + 1) else 0L + ) +} + +# The expected steps of the best key to taxa with probabilities `p` whose +# couplets have at most `arity` leads: Huffman's construction, which joins +# the `arity` least likely groups into one couplet until one group is left. +# Each joining adds a step for everything in the new group, so the expected +# steps are the sum of the joined groups' probabilities. Groups of +# probability 0 are added first so that the last couplet made (the first +# one asked) is a full one. +qualOptimalSteps <- function(p, arity) { + n <- length(p) + if (n <= 1) return(0) + arity <- max(2, arity) + if (arity >= n) return(sum(p)) + pad <- (arity - 1 - (n - 1) %% (arity - 1)) %% (arity - 1) + leaf <- c(rep(0, pad), sort(p)) + joins <- (length(leaf) - 1) / (arity - 1) + # `leaf` and the groups made so far (`node`) are both in rising order, so + # the least likely group is always at the front of one of the two + node <- numeric(joins) + i <- 1 + j <- 1 + steps <- 0 + for (made in seq_len(joins)) { + total <- 0 + for (pick in seq_len(arity)) { + if (j >= made || (i <= length(leaf) && leaf[i] <= node[j])) { + total <- total + leaf[i] + i <- i + 1 + } else { + total <- total + node[j] + j <- j + 1 + } + } + node[made] <- total + steps <- steps + total + } + steps +} + +# The probability of coming through each couplet on the way to a result, +# given the probability `share` of ending at a lead of couplet `at`. Each +# couplet passes its probability up to the couplet it is first reached from. +qualVisitProbability <- function(at, share, depths) { + visit <- numeric(length(depths$shortest)) + own <- tapply(share, at, sum) + visit[as.integer(names(own))] <- own + deepest <- suppressWarnings(max(depths$shortest, na.rm = TRUE)) + for (d in rev(seq_len(max(deepest, 0)))) { + here <- which(depths$shortest == d) + up <- tapply(visit[here], depths$parent[here], sum) + visit[as.integer(names(up))] <- visit[as.integer(names(up))] + up + } + visit +} + +# Steps from the root to each couplet (0 for the root, NA when it cannot be +# reached): `shortest` over all routes and `longest` over all routes, and the +# `parent` couplet on a shortest route. A key with a cycle has no longest +# route; `longest` is then the shortest. +qualCoupletDepths <- function(leads, check) { + couplets <- check$couplets + n <- length(couplets) + shortest <- rep(NA_real_, n) + parent <- rep(NA_integer_, n) + if (n == 0) return(list(shortest = shortest, longest = shortest, parent = parent)) + from <- match(leads$Statement, couplets) + to <- match(leads$Next, couplets) + edge <- leads$Next != "-" & !is.na(to) + from <- from[edge] + to <- to[edge] + + root <- match(check$root, couplets) + shortest[root] <- 0 + frontier <- root + while (length(frontier)) { + out <- which(from %in% frontier & is.na(shortest[to])) + nxt <- unique(to[out]) + parent[nxt] <- from[out[match(nxt, to[out])]] + shortest[nxt] <- shortest[frontier[1]] + 1 + frontier <- nxt + } + + # Longest route: push each couplet's depth along its leads until nothing + # changes. In a key without cycles that takes at most one pass per couplet. + longest <- rep(NA_real_, n) + longest[root] <- 0 + settled <- FALSE + for (pass in seq_len(n + 1)) { + reach <- longest[from] + 1 + known <- !is.na(reach) & to != root + if (!any(known)) { + settled <- TRUE + break + } + best <- tapply(reach[known], to[known], max) + target <- as.integer(names(best)) + better <- is.na(longest[target]) | best > longest[target] + if (!any(better)) { + settled <- TRUE + break + } + longest[target[better]] <- best[better] + } + if (!settled) longest <- shortest + list(shortest = shortest, longest = longest, parent = parent) +} + +# Each taxon's share of the weights (summing to 1); equal shares without +# weights. +qualWeights <- function(taxon, weights) { + n <- length(taxon) + if (n == 0) return(numeric()) + if (is.null(weights)) return(rep(1 / n, n)) + if (!is.numeric(weights) || length(dim(weights)) > 1) { + stop("`weights` must be a numeric vector named by the key's taxa", call. = FALSE) + } + if (is.null(names(weights))) { + stop("`weights` must be a numeric vector named by the key's taxa; this one has no names", call. = FALSE) + } + names(weights) <- trimws(names(weights)) + twice <- unique(names(weights)[duplicated(names(weights)) & names(weights) %in% taxon]) + if (length(twice)) { + stop("`weights` has more than one value for ", paste(utils::head(twice, 5), collapse = ", "), + if (length(twice) > 5) ", ...", call. = FALSE) + } + w <- unname(weights[match(taxon, names(weights))]) + absent <- is.na(w) + if (all(absent)) stop("None of the names of `weights` is a taxon of the key", call. = FALSE) + if (any(absent)) { + warning(sprintf("%d of the key's %d taxa have no weight and count as 0: %s", sum(absent), n, + paste(utils::head(taxon[absent], 5), collapse = ", ")), + if (sum(absent) > 5) ", ...", call. = FALSE) + w[absent] <- 0 + } + if (any(w < 0) || any(!is.finite(w))) stop("`weights` must be finite and not negative", call. = FALSE) + if (sum(w) <= 0) stop("`weights` are all 0 for the key's taxa", call. = FALSE) + w / sum(w) +} + +#' How common each taxon of a key is, from GBIF occurrence records +#' +#' Counts the occurrence records [GBIF](https://www.gbif.org) holds for each +#' result of a key, optionally within a country or region. The counts can be +#' given to [keyQuality()] or `summary()` as `weights`, to see how many +#' steps the key takes for the taxa people actually meet. +#' +#' A result written as `"Common name (Genus species)"` is looked up by the +#' name in parentheses; other results by the result itself when it looks +#' like a scientific name, which includes genera and families (`"Salix"`, +#' `"Salix sp."` and `"Salix spp."` all count the genus) and names followed +#' by their author (`"Puma concolor (Linnaeus, 1771)"`). A result that +#' lists several taxa the key does not separate, written `"A / B"` as +#' [keyFromRpart()] and [keyFromMatrix()] write them, gets the sum of their +#' counts. Each name is matched to the GBIF Backbone Taxonomy, and the +#' records of the name GBIF accepts for it are counted, so a synonym gets +#' the count of its accepted name. This makes two requests to GBIF per +#' name, one name at a time; after three failed requests in a row the rest +#' are not tried. +#' +#' A name that GBIF knows in more than one kingdom (`"Morus"` is a mulberry +#' and a gannet) is not counted unless `kingdom` says which is meant. +#' +#' Occurrence counts measure how often a taxon is recorded, which follows +#' how conspicuous and how popular with observers it is as well as how +#' common it is. A taxon with no records gets a weight of 0 and so does not +#' count towards the expected steps at all. +#' +#' @param key A [dimoose] key. +#' @param region Where to count: `NULL` for the whole world, a two-letter +#' ISO country code (`"US"`), or a [GADM](https://gadm.org) id for a +#' country, state or county (`"USA.27_1"` is Montana). Anything else is +#' an error. GBIF answers 0 for a GADM id it does not have, so when no +#' taxon has a record in the region a warning asks to check it. +#' @param source Where the counts come from; only `"gbif"` for now. +#' @param fetch The function that asks GBIF: called as `fetch(url, query)` +#' with a named list of query parameters, it returns the parsed JSON +#' answer as a list. Replace it to use cached answers or to test without +#' a connection. +#' @param kingdom Optional kingdom ("Plantae", "Animalia", ...), which helps +#' GBIF tell apart names that are used in more than one kingdom. +#' @return A numeric vector of record counts named by the key's results (as +#' in its `Taxon` column), `NA` for results that have no scientific name, +#' that GBIF does not know or cannot tell apart, or whose request failed +#' (each with a warning). +#' @seealso [keyQuality()], [checkNames()] +#' @examples +#' # canned answers in place of GBIF, to show the shape of `fetch` +#' counts <- c("Acer negundo" = 61000, "Fraxinus pennsylvanica" = 48000) +#' canned <- function(url, query) { +#' if (grepl("species/match", url)) { +#' list(usageKey = match(query$name, names(counts)), matchType = "EXACT") +#' } else { +#' list(count = unname(counts[query$taxonKey])) +#' } +#' } +#' leads <- data.frame( +#' Statement = "1", Choice = c("a", "b"), Character = c("Leaflets 3.", "Leaflets 5 to 7."), +#' Next = "-", Taxon = c("Box elder (Acer negundo)", "Green ash (Fraxinus pennsylvanica)") +#' ) +#' occurrenceWeights(keyFromLeads(leads), fetch = canned) +#' \donttest{ +#' k <- montanaKey() +#' w <- occurrenceWeights(k, region = "USA.27_1", kingdom = "Plantae") +#' w +#' summary(k, weights = w) +#' } +#' @export +occurrenceWeights <- function(key, region = NULL, source = "gbif", fetch = qualGbifFetch, kingdom = NULL) { + if (!inherits(key, "dimoose")) stop("`key` must be a dimoose object", call. = FALSE) + source <- match.arg(source, "gbif") + if (!is.function(fetch)) stop("`fetch` must be a function of a URL and a list of query parameters", call. = FALSE) + where <- qualRegionQuery(region) + leads <- normalizeLeads(key$leads) + taxa <- unique(leads$Taxon[leads$Next == "-" & nzchar(leads$Taxon)]) + # a result may list several taxa ("A / B"); it gets the sum of their counts + parts <- lapply(strsplit(taxa, " / ", fixed = TRUE), function(x) qualLookupName(trimws(x))) + + # one answer per name: its count, or NA and why + count <- numeric() + why <- character() + failure <- character() + inARow <- 0 + for (name in unique(stats::na.omit(unlist(parts)))) { + if (inARow >= 3) { + count[name] <- NA_real_ + why[name] <- "not tried" + next + } + res <- tryCatch({ + m <- fetch("https://api.gbif.org/v1/species/match", qualDropNull(list(name = name, kingdom = kingdom))) + type <- if (is.null(m$matchType)) "NONE" else m$matchType + taxonKey <- if (!is.null(m$acceptedUsageKey)) m$acceptedUsageKey else m$usageKey + # GBIF calls a genus that also has a species-rank entry of the same + # name a HIGHERRANK match; it is the genus asked for all the same + itself <- !is.null(m$canonicalName) && identical(tolower(m$canonicalName), tolower(name)) + if (type == "NONE" && !is.null(m$note) && grepl("Multiple equal matches", m$note, fixed = TRUE)) { + list(count = NA_real_, why = "ambiguous") + } else if (type == "NONE" || (type == "HIGHERRANK" && !itself) || is.null(taxonKey)) { + list(count = NA_real_, why = "unknown") + } else { + found <- fetch("https://api.gbif.org/v1/occurrence/search", c(list(taxonKey = taxonKey, limit = 0), where)) + if (is.null(found$count)) stop("GBIF's answer for ", name, " has no count") + list(count = as.numeric(found$count), why = "") + } + }, error = function(e) { + failure <<- c(failure, conditionMessage(e)) + list(count = NA_real_, why = "failed") + }) + inARow <- if (res$why == "failed") inARow + 1 else 0 + count[name] <- res$count + why[name] <- res$why + } + counts <- vapply(parts, function(x) if (anyNA(x)) NA_real_ else sum(count[x]), numeric(1)) + names(counts) <- taxa + + some <- function(x) paste0(paste(utils::head(x, 5), collapse = ", "), if (length(x) > 5) ", ..." else "") + noName <- taxa[vapply(parts, anyNA, logical(1))] + if (length(noName)) { + warning(sprintf("%d result%s without a scientific name not counted: %s", length(noName), + if (length(noName) == 1) "" else "s", some(noName)), call. = FALSE) + } + unknown <- names(why)[why == "unknown"] + if (length(unknown)) warning("Not in GBIF, so not counted: ", some(unknown), call. = FALSE) + ambiguous <- names(why)[why == "ambiguous"] + if (length(ambiguous)) { + warning("GBIF knows more than one taxon by this name, so not counted (say which with `kingdom`): ", + some(ambiguous), call. = FALSE) + } + failed <- sum(why %in% c("failed", "not tried")) + if (failed) { + warning(sprintf("Could not get the count of %d name%s from GBIF: %s", failed, if (failed == 1) "" else "s", failure[1]), + if (any(why == "not tried")) "; gave up after 3 failed requests in a row", call. = FALSE) + } + if (length(where) && any(!is.na(counts)) && all(counts[!is.na(counts)] == 0)) { + warning("GBIF has no records of these taxa in ", where[[1]], "; check that it is the region meant", call. = FALSE) + } + counts +} + +# The name to look a result up by, or NA when it has none: the name in +# parentheses of "Common name (Genus species)", otherwise the result itself +# when it looks like a scientific name. Parentheses that hold an author +# ("Puma concolor (Linnaeus, 1771)") are dropped, and "Salix sp." or +# "Salix spp." is the genus. +qualLookupName <- function(taxa) { + genus <- function(x) trimws(sub("\\s+spp?\\.?$", "", x)) + inside <- genus(scientificPart(taxa)) + # an author: the name is what stands before the parentheses + author <- !is.na(inside) & grepl("[0-9]{4}|,|&|\\.$", inside) + inside[author] <- NA_character_ + taxa[author] <- sub("\\s*\\([^()]*\\)$", "", taxa[author]) + name <- ifelse(is.na(inside), genus(taxa), inside) + name[!nzchar(name)] <- NA_character_ + ok <- !is.na(name) + ok[ok] <- isScientificName(name[ok]) + name[!ok] <- NA_character_ + name +} + +# The occurrence search parameter for a region: `country` for a two-letter +# code, `gadmGid` for a GADM id (three letters, then numbered levels). +qualRegionQuery <- function(region) { + if (is.null(region)) return(list()) + if (!is.character(region) || length(region) != 1 || is.na(region) || !nzchar(trimws(region))) { + stop("`region` must be one country code or GADM id", call. = FALSE) + } + region <- toupper(trimws(region)) + if (grepl("^[A-Z]{2}$", region)) return(list(country = region)) + if (!grepl("^[A-Z]{3}(\\.[0-9]+)*(_[0-9]+)?$", region)) { + stop("`region` must be a two-letter country code (\"US\") or a GADM id (\"USA.27_1\"), not ", region, call. = FALSE) + } + list(gadmGid = region) +} + +qualDropNull <- function(x) x[!vapply(x, is.null, logical(1))] + +# Ask the GBIF API (https://techdocs.gbif.org/en/openapi/) and parse its JSON. +qualGbifFetch <- function(url, query) { + r <- httr::GET(url, query = query, dimooseUserAgent(), httr::timeout(30)) + httr::stop_for_status(r, task = "ask GBIF") + httr::content(r, as = "parsed", type = "application/json", encoding = "UTF-8") +} diff --git a/R/sdd.R b/R/sdd.R new file mode 100644 index 0000000..615c134 --- /dev/null +++ b/R/sdd.R @@ -0,0 +1,1050 @@ +# TDWG SDD (Structured Descriptive Data) and the Xper dialect of it, plus the +# helpers shared with R/delta.R and R/lucid.R (all prefixed `tdwg`). + +# ---- shared helpers ------------------------------------------------------------ + +tdwgTypes <- c("categorical", "ordered", "integer", "real", "text") + +# One or more spaces, tabs or line breaks become one space +tdwgSquish <- function(x) trimws(gsub("[[:space:]]+", " ", x)) + +tdwgXmlEscape <- function(x) { + x <- gsub("&", "&", x, fixed = TRUE) + x <- gsub("<", "<", x, fixed = TRUE) + x <- gsub(">", ">", x, fixed = TRUE) + gsub("\"", """, x, fixed = TRUE) +} + +tdwgFormatNumber <- function(x) { + format(x, scientific = FALSE, trim = TRUE, drop0trailing = TRUE, digits = 15) +} + +tdwgNumberPattern <- "-?(?:[0-9]+\\.?[0-9]*|\\.[0-9]+)" + +# Parse one numeric value or range written the DELTA way: "5", "2-8", +# "2-5-8" (the middle value is the mean or median) and, with rare extremes in +# parentheses, "(1-)2-8(-12)". Returns c(omin, min, mid, max, omax) or NULL. +tdwgParseRange <- function(x) { + n <- tdwgNumberPattern + pattern <- sprintf("^(?:\\((%s)-\\))?(%s)(?:-(%s))?(?:-(%s))?(?:\\(-(%s)\\))?$", n, n, n, n, n) + m <- regmatches(x, regexec(pattern, gsub(" ", "", x, fixed = TRUE), perl = TRUE))[[1]] + if (!length(m)) return(NULL) + v <- suppressWarnings(as.numeric(m[-1])) + normal <- v[2:4][!is.na(v[2:4])] + c(omin = v[1], min = normal[1], mid = if (length(normal) == 3) normal[2] else NA_real_, + max = normal[length(normal)], omax = v[5]) +} + +tdwgFormatRange <- function(omin = NA, min = NA, mid = NA, max = NA, omax = NA) { + if (is.na(min)) min <- max + if (is.na(max)) max <- min + if (is.na(min)) { + if (is.na(mid)) return(NA_character_) + min <- max <- mid + mid <- NA + } + f <- tdwgFormatNumber + out <- if (min == max && is.na(mid)) f(min) else paste(c(f(min), if (!is.na(mid)) f(mid), f(max)), collapse = "-") + if (!is.na(omin) && omin != min) out <- paste0("(", f(omin), "-)", out) + if (!is.na(omax) && omax != max) out <- paste0(out, "(-", f(omax), ")") + out +} + +# The smallest range that covers every alternative in a cell ("5/10-15"); +# NULL if any of them is not a number or range. +tdwgCellRange <- function(cell, sep = "/") { + parts <- lapply(trimws(strsplit(cell, sep, fixed = TRUE)[[1]]), tdwgParseRange) + if (!length(parts) || any(vapply(parts, is.null, logical(1)))) return(NULL) + if (length(parts) == 1) return(parts[[1]]) + p <- do.call(rbind, parts) + c(omin = if (all(is.na(p[, "omin"]))) NA_real_ else min(p[, c("omin", "min")], na.rm = TRUE), + min = min(p[, "min"]), mid = NA_real_, max = max(p[, "max"]), + omax = if (all(is.na(p[, "omax"]))) NA_real_ else max(p[, c("omax", "max")], na.rm = TRUE)) +} + +# A state name cannot contain the separator that lists several states in a cell +tdwgCleanStates <- function(states, sep = "/") { + bad <- grepl(sep, states, fixed = TRUE) + if (any(bad)) { + other <- if (sep == "|") "/" else "|" + states[bad] <- gsub(sep, other, states[bad], fixed = TRUE) + attr(states, "replaced") <- sum(bad) + } + states +} + +tdwgWarnReplaced <- function(n, sep) { + if (n > 0) { + warning(sprintf(paste0("%d state name(s) contain \"%s\", which separates the states in a cell; ", + "it was replaced by \"%s\" (use `sep` to pick another separator)"), + n, sep, if (sep == "|") "/" else "|"), call. = FALSE) + } +} + +tdwgUnique <- function(x) { + dup <- duplicated(x) + if (!any(dup)) return(x) + count <- stats::ave(seq_along(x), x, FUN = seq_along) + x[dup] <- paste0(x[dup], " (", count[dup], ")") + if (anyDuplicated(x)) make.unique(x, sep = " ") else x +} + +tdwgMeta <- function(...) { + values <- list(...) + values <- values[!vapply(values, function(v) length(v) == 0 || is.na(v[1]) || !nzchar(v[1]), logical(1))] + data.frame(key = names(values), value = vapply(values, function(v) as.character(v[1]), character(1)), + stringsAsFactors = FALSE, row.names = NULL) +} + +tdwgMetaGet <- function(meta, key) { + if (!is.data.frame(meta) || !all(c("key", "value") %in% names(meta))) return(NULL) + value <- as.character(meta$value[meta$key == key]) + if (length(value) && !is.na(value[1]) && nzchar(value[1])) value[1] else NULL +} + +# What every reader returns +tdwgData <- function(matrix, characters, taxa, meta) { + rownames(matrix) <- rownames(characters) <- rownames(taxa) <- NULL + structure(list(matrix = matrix, characters = characters, taxa = taxa, meta = meta), class = "tdwgData") +} + +# Assemble the matrix data frame from a list of columns (one character vector +# per character) +tdwgMatrix <- function(taxa, cells, names, taxon = "Taxon") { + m <- data.frame(taxa, stringsAsFactors = FALSE) + names(m) <- taxon + for (j in seq_along(names)) m[[names[j]]] <- cells[[j]] + m +} + +#' @export +print.tdwgData <- function(x, ...) { + types <- table(factor(x$characters$Type, levels = tdwgTypes)) + types <- types[types > 0] + title <- tdwgMetaGet(x$meta, "title") + format <- tdwgMetaGet(x$meta, "format") + cat("Character data", if (!is.null(title)) paste0("\"", title, "\""), + if (!is.null(format)) paste0("(", format, ")"), "\n") + cat(sprintf(" %d taxa x %d characters", nrow(x$matrix), nrow(x$characters)), + if (length(types)) paste0("(", paste(types, names(types), collapse = ", "), ")"), "\n") + cat(" $matrix, $characters, $taxa, $meta\n") + invisible(x) +} + +# Turn what a writer is given (a matrix data frame, or the list a reader +# returns) into one tidy description: taxon names, one character vector of +# cells per character, and per character its type, states, unit and so on. +tdwgInput <- function(x, characters = NULL, taxon = "Taxon", sep = "/", inapplicable = NULL) { + taxa <- meta <- NULL + if (is.data.frame(x)) { + m <- x + } else if (is.list(x) && is.data.frame(x$matrix)) { + m <- x$matrix + if (is.null(characters)) characters <- x$characters + taxa <- x$taxa + meta <- x$meta + } else { + stop("`x` must be a character matrix (a data frame) or the list that readSDD(), readDELTA() ", + "or readLucid() return", call. = FALSE) + } + if (!taxon %in% names(m)) stop("The matrix has no taxon column \"", taxon, "\"", call. = FALSE) + m <- as.data.frame(m, stringsAsFactors = FALSE) + if (!nrow(m)) stop("The matrix has no rows", call. = FALSE) + if (anyDuplicated(names(m))) { + stop("Column name(s) used more than once in the matrix: ", + paste(unique(names(m)[duplicated(names(m))]), collapse = ", "), call. = FALSE) + } + taxonNames <- tdwgSquish(as.character(m[[taxon]])) + if (anyNA(taxonNames) || any(!nzchar(taxonNames))) stop("Every row of the matrix needs a taxon name", call. = FALSE) + if (anyDuplicated(taxonNames)) { + stop("Taxon name(s) used for more than one row: ", + paste(unique(taxonNames[duplicated(taxonNames)]), collapse = ", "), call. = FALSE) + } + cols <- setdiff(names(m), taxon) + if (!length(cols)) stop("The matrix has no character columns", call. = FALSE) + + info <- function(column, default) { + if (!is.data.frame(characters) || is.null(characters$Character) || is.null(characters[[column]])) { + return(rep(default, length(cols))) + } + value <- characters[[column]][match(cols, characters$Character)] + if (is.character(default)) { + value <- as.character(value) + value[is.na(value)] <- default + } + value + } + type <- tolower(info("Type", NA_character_)) + delta <- c(um = "categorical", om = "ordered", "in" = "integer", rn = "real", te = "text") + type[type %in% names(delta)] <- delta[type[type %in% names(delta)]] + type[type %in% c("numeric", "quantitative")] <- "real" + unknown <- !is.na(type) & !type %in% tdwgTypes + if (any(unknown)) { + stop("Unknown character type(s): ", paste(unique(type[unknown]), collapse = ", "), + "; use one of ", paste(tdwgTypes, collapse = ", "), call. = FALSE) + } + definedStates <- info("States", "") + cells <- states <- vector("list", length(cols)) + inapp <- matrix(FALSE, nrow(m), length(cols)) + for (j in seq_along(cols)) { + v <- m[[cols[j]]] + if (is.na(type[j])) { + type[j] <- if (!is.numeric(v)) "categorical" else if (all(v == round(v), na.rm = TRUE)) "integer" else "real" + } + if (is.numeric(v)) { + v <- ifelse(is.na(v), NA_character_, vapply(v, tdwgFormatNumber, character(1))) + } else { + v <- trimws(as.character(v)) + v[!is.na(v) & v == ""] <- NA + } + if (!is.null(inapplicable) && !is.na(inapplicable)) { + inapp[, j] <- !is.na(v) & v == inapplicable + v[inapp[, j]] <- NA + } + cells[[j]] <- v + states[[j]] <- character() + if (type[j] %in% c("categorical", "ordered")) { + defined <- trimws(strsplit(definedStates[j], sep, fixed = TRUE)[[1]]) + observed <- trimws(unlist(strsplit(v[!is.na(v)], sep, fixed = TRUE))) + states[[j]] <- unique(c(defined, observed)[nzchar(c(defined, observed))]) + } + } + list(taxa = taxonNames, taxaInfo = taxa, meta = meta, characters = cols, type = type, states = states, + unit = info("Unit", ""), inapplicableIf = info("InapplicableIf", ""), + cost = suppressWarnings(as.numeric(info("Cost", NA_real_))), cells = cells, inapplicable = inapp) +} + +# The states of one cell, as positions in the character's state list +tdwgCellStates <- function(cell, states, sep = "/") { + if (is.na(cell)) return(integer()) + match(trimws(strsplit(cell, sep, fixed = TRUE)[[1]]), states) +} + +# "Wings=absent/reduced; Habitat=marine" -> list(list(character = , states = ), ...) +# Character names may themselves contain "=" or ";", so the text is read by +# looking for the names the data has. Rules that name a character or state +# the data does not have are dropped with a warning. +tdwgParseRules <- function(text, input, sep = "/") { + if (is.na(text) || !nzchar(trimws(text))) return(list()) + heads <- paste0(input$characters, "=") + heads <- heads[order(-nchar(heads))] + startsRule <- function(x) { + hit <- heads[startsWith(x, heads)] + if (length(hit)) hit[1] else NA_character_ + } + rules <- list() + rest <- trimws(text) + while (nzchar(rest)) { + head <- startsRule(rest) + after <- if (is.na(head)) rest else substring(rest, nchar(head) + 1) + # the rule ends where the next one starts: at a "; " followed by a character name + breaks <- gregexpr("; ", after, fixed = TRUE)[[1]] + end <- nchar(after) + 1 + for (at in breaks[breaks > 0]) { + if (!is.na(startsRule(substring(after, at + 2)))) { + end <- at + break + } + } + statesText <- substr(after, 1, end - 1) + rest <- trimws(substring(after, end + 2)) + controlling <- if (is.na(head)) NA else match(substr(head, 1, nchar(head) - 1), input$characters) + stateIndex <- if (is.na(controlling)) NA else { + match(trimws(strsplit(statesText, sep, fixed = TRUE)[[1]]), input$states[[controlling]]) + } + if (is.na(controlling) || anyNA(stateIndex) || !length(stateIndex)) { + warning("Dependency rule \"", if (is.na(head)) "" else head, statesText, + "\" names a character or state that is not in the data; left out", call. = FALSE) + next + } + rules[[length(rules) + 1]] <- list(character = controlling, states = stateIndex) + } + rules +} + +tdwgRuleText <- function(character, states, sep = "/") paste0(character, "=", paste(states, collapse = sep)) + +# ---- SDD: reading ---------------------------------------------------------------- + +tdwgReadXml <- function(file) { + if (!file.exists(file)) stop("File ", file, " not found", call. = FALSE) + doc <- xml2::read_xml(file) + xml2::xml_ns_strip(doc) + doc +} + +tdwgSddDataset <- function(doc, dataset = NULL, want = "CodedDescriptions") { + datasets <- xml2::xml_find_all(doc, "//Dataset") + if (!length(datasets)) stop("This is not an SDD file: it has no element", call. = FALSE) + if (!is.null(dataset)) { + if (!is.numeric(dataset) || dataset < 1 || dataset > length(datasets)) { + stop(sprintf("`dataset` must be a number from 1 to %d", length(datasets)), call. = FALSE) + } + return(datasets[[dataset]]) + } + has <- vapply(datasets, function(d) length(xml2::xml_find_first(d, paste0("./", want))) > 0, logical(1)) + if (!any(has)) return(NULL) + datasets[[which(has)[1]]] +} + +# The first