[
  {
    "path": ".Rbuildignore",
    "content": "^check\n^examples\n^lib\n^libs\n^library\n^rchk\n^repo\n^revdep\n^scripts\n^tools\n^wiki\n^www\n^yaml\n^Makefile\n^TAGS\n^rules.mk\n^tests/Makefile\n^tests/(.+?)\\.png$\n^tests/(.+?)\\.pdf$\n^tests/(.+?)\\.Rout$\n^inst/doc/Makefile\n^inst/doc/(.+?).md\n^inst/doc/(.+?).Rmd\n^man/roxygen\n^Doxyfile\nLICENSE\\.md$\nREADME\\.(.?)$\nCRAN\\.md$\nTODO\\.md$\nBUILD\\.md$\n^rchk\\.out$\n^\\.gitignore$\n^\\.github\n^\\.travis\\.yml$\n^codecov\\.yml$\n^.*\\.Rproj$\n^\\.Rproj\\.user$\n\\.Rprofile\n\\.Rhistory\n\\.NEWS\n\\.dist\n\\.instdocs\n\\.install\n\\.roxy\n\\.source\n\\.testsource\n\\.includes\n\\.headers\n\\.tests\n^(.+?)\\.pdf\n^(.+?)\\.tar\\.gz\n^(.+?)\\.tgz\n^(.+?)\\.zip\ncovr.html\ncovr.rds\n"
  },
  {
    "path": ".Rprofile",
    "content": "options(\n  help_type=\"html\",\n  repos=c(\n    CRAN=\"https://cloud.r-project.org/\",\n    kingaa=\"https://kingaa.github.io\"\n  ),\n  useFancyQuotes=FALSE,\n  Ncpus=12\n)\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve **pomp**\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**To Reproduce**\n1. **R** code that produces the problem.\n2. Transcript of the R session that gave the errors.\n3. Any graphics that show the problematic results.\n\n**Expected behavior**\nA clear and concise description of what you expected to happen.\n\n**Session information**\nOutput of the command\n```\nsource(\"https://kingaa.github.io/scripts/diagnostics.R\")\n```\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**Is your feature request related to a problem? Please describe.**\nA clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n\n**Describe the solution you'd like**\nA clear and concise description of what you want to happen.\n\n**Describe alternatives you've considered**\nA clear and concise description of any alternative solutions or features you've considered.\n\n**Additional context**\nAdd any other context or screenshots about the feature request here.\n"
  },
  {
    "path": ".github/workflows/binary-build.yml",
    "content": "# Workflow derived from https://github.com/r-lib/actions/tree/master/examples\n# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help\non:\n  push:\n    tags:\n      - '*.*.*.*'\n  workflow_dispatch:\n\nname: binary-build\n\nenv:\n  release_name: ${{ vars.repo_name }}_${{ github.ref_name }}\n\njobs:\n  source_build:          \n    runs-on: ubuntu-latest\n    name: Build source tarball\n    strategy:\n      fail-fast: false\n\n    steps:\n      - uses: actions/checkout@v6\n\n      - uses: r-lib/actions/setup-r@v2\n        with:\n          r-version: latest\n\n      - uses: r-lib/actions/setup-r-dependencies@v2\n        with:\n          extra-packages: |\n            any::pkgbuild\n\n      - name: Build source tarball\n        run: |\n          R CMD build --force --no-manual --resave-data --compact-vignettes=both --md5 .\n          mkdir -p ${{ github.workspace }}/artifacts\n          cp ${{ env.release_name }}.tar.gz ${{ github.workspace }}/artifacts\n\n      - uses: actions/upload-artifact@v7\n        with:\n          name: source_tarball\n          path: ${{ github.workspace }}/artifacts/${{ env.release_name }}.tar.gz\n\n  binary_build:\n    runs-on: ${{ matrix.config.os }}\n\n    name: ${{ matrix.config.os }} (${{ matrix.config.r }})\n\n    strategy:\n      fail-fast: false\n      matrix:\n        config:\n          - {os: macOS-latest,   r: 'release', ext: \"tgz\"}\n          - {os: windows-latest, r: 'release', ext: \"zip\"}\n\n    steps:\n      - uses: actions/checkout@v4\n\n      - uses: r-lib/actions/setup-r@v2\n        with:\n          r-version: ${{ matrix.config.r }}\n\n      - uses: r-lib/actions/setup-r-dependencies@v2\n        with:\n          extra-packages: |\n            any::pkgbuild\n\n      - name: Build binary\n        run: pkgbuild::build(binary=TRUE,manual=TRUE)\n        shell: Rscript {0}\n\n      - name: Copy tarball\n        run: |\n          mkdir -p ${{ github.workspace }}/artifacts\n          cp ../${{ env.release_name }}.${{ matrix.config.ext }} ${{ github.workspace }}/artifacts\n\n      - uses: actions/upload-artifact@v4\n        with:\n          name: ${{ matrix.config.os }}-${{ matrix.config.r }}\n          path: ${{ github.workspace }}/artifacts/${{ env.release_name }}.${{ matrix.config.ext }}\n\n# Workflow derived from https://github.com/marketplace/actions/create-release\n  create_release:\n    needs: [ source_build, binary_build ]\n    runs-on: ubuntu-latest\n    permissions:\n      contents: write\n    steps:\n    - uses: actions/checkout@v4\n    - uses: actions/download-artifact@v4\n      with:\n        path: artifacts\n    - uses: ncipollo/release-action@v1\n      with:\n        draft: true\n        artifacts: \"artifacts/*/*\"\n"
  },
  {
    "path": ".github/workflows/r-cmd-check.yml",
    "content": "# Workflow derived from https://github.com/r-lib/actions/tree/master/examples\n# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help\non:\n  schedule:\n    - cron: '13 11 * * 0'\n  push:\n    branches:\n      - '*'\n    paths:\n      - DESCRIPTION\n      - NAMESPACE\n      - R/**\n      - src/**\n      - tests/**\n      - man/**\n      - data/**\n  pull_request:\n    paths:\n      - DESCRIPTION\n      - NAMESPACE\n      - R/**\n      - src/**\n      - tests/**\n      - man/**\n      - data/**\n  workflow_dispatch:\n\nname: R-CMD-check\n\njobs:\n  R-CMD-check:\n    runs-on: ${{ matrix.config.os }}\n\n    name: ${{ matrix.config.os }} (${{ matrix.config.r }})\n\n    strategy:\n      fail-fast: false\n      matrix:\n        config:\n          - {os: ubuntu-latest,  r: 'devel', http-user-agent: 'release'}\n          - {os: ubuntu-latest,  r: 'release'}\n          - {os: ubuntu-22.04,   r: '4.1.0'}\n          - {os: macOS-latest,   r: 'release'}\n          - {os: windows-latest, r: 'release'}\n\n    env:\n      GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }}\n      R_KEEP_PKG_SOURCE: yes\n\n    steps:\n      - uses: actions/checkout@v6\n\n      - uses: r-lib/actions/setup-r@v2\n        with:\n          r-version: ${{ matrix.config.r }}\n          http-user-agent: ${{ matrix.config.http-user-agent }}\n          use-public-rspm: true\n          extra-repositories: |\n            https://kingaa.github.io/\n\n      - uses: r-lib/actions/setup-r-dependencies@v2\n        with:\n          extra-packages: |\n            any::rcmdcheck\n            any::tidyr\n            any::ggplot2\n            any::dplyr\n            any::knitr\n            any::subplex\n            any::nloptr\n\n      - uses: r-lib/actions/check-r-package@v2\n\n      - uses: actions/upload-artifact@v7\n        with:\n          name: ${{ matrix.config.os }}-${{ matrix.config.r }}-results\n          path: check/${{ vars.repo_name }}.Rcheck/00check.log\n"
  },
  {
    "path": ".github/workflows/test-coverage.yml",
    "content": "# Workflow derived from https://github.com/r-lib/actions/tree/master/examples\n# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help\non:\n  workflow_dispatch:\n  push:\n    branches: [master]\n    paths:\n      - DESCRIPTION\n      - NAMESPACE\n      - R/**\n      - src/**\n      - tests/**\n      - man/**\n      - data/**\n  pull_request:\n    branches: [master]\n    paths:\n      - DESCRIPTION\n      - NAMESPACE\n      - R/**\n      - src/**\n      - tests/**\n      - man/**\n      - data/**\n    \nname: test-coverage\n\njobs:\n  test-coverage:\n    runs-on: ubuntu-latest\n    env:\n      GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }}\n\n    steps:\n      - uses: actions/checkout@v6\n\n      - uses: r-lib/actions/setup-r@v2\n        with:\n          use-public-rspm: true\n\n      - uses: r-lib/actions/setup-r-dependencies@v2\n        with:\n          extra-packages: covr\n\n      - name: Test coverage\n        run: covr::codecov()\n        shell: Rscript {0}\n"
  },
  {
    "path": ".gitignore",
    "content": "\\.NEWS\n\\.dist\n\\.instdocs\n\\.install\n\\.roxy\n\\.source\n\\.testsource\n\\.includes\n\\.headers\n\\.tests\n\\.Rhistory\n\\.Rproj.user\nrchk\\.out\n*.tar.gz\n*.tgz\n*.zip\n*.o\n*.so\n*.gcda\n*.gcno\n*.pdf\n*.sif\ncheck\nlib\nlibrary\nrchk\nwiki\ntmp\ncovr.html\ncovr.rds\n.DS_Store\n"
  },
  {
    "path": "BUILD.md",
    "content": "----------------\n\n# Instructions for building, checking, and installing\n\n## Makefile usage\n\nA `Makefile` is provided.  Most of the rules are defined in the `rules.mk` file.\nThe following key variables are defined in the `Makefile`.\n\n- `REPODIR`: the name of the directory in which a local copy of the Git repo used for publishing source and documentation is located.\n- `INCLUDES`: names of header files that will be copied to `inst/includes`\n- `HEADERS`: names of header files that must be rebuilt whenever source code changes.\n\nThe key targets are:\n\n- `roxy`: runs `devtools::document()` to build the help pages (in `man/`), the package `NAMESPACE`, and the collation order in `DESCRIPTION`.\n- `dist`: builds the package source tarball.\n- `install`: installs the package locally for testing.\n- `tests`: runs `make` in the `tests/` directory, causing tests to be updated as needed.\n- `clean`: cleans the directory of files created during builds and tests.\n- `fresh`: resets the directory for a fresh rebuild.\n\n- `htmlhelp`: builds the package manual in HTML and PDF formats.\n  This command also causes `doxygen` to be run, which produces HTML documentation of the C/C++ source code.\n  These documentation files are installed into the `REPODIR/manuals` directory.\n- `www`: installs the package and runs `make` in the `www` directory.\n  This causes vignettes to be updated, among other things.\n- `NEWS`: builds the plain-text package NEWS file.\n- `instdocs`: runs `make` in the `inst/docs` directory.\n\n- `check`: runs `devtools::check()`.\n- `qcheck`: like `check`, but tests in `tests/` are not run.\n- `qqcheck`: like `qcheck`, but checks for code-documentation mismatch and examples are not run.\n- `xcheck`: runs `devtools::check(cran=TRUE)`, i.e., the additional checks for CRAN suitability are also run.\n- `ycheck`: runs `xcheck` but tests and examples that are ordinarily not run (because expensive) are run.\n- `vcheck`: runs `check` and then tests for memory leaks using `valgrind`.\n  One must examine the output (printed to the console and also stored in a file, the name of which ends in `-Ex.Rout`.\n- `revdeps`: causes checks of reverse-dependent packages to run.\n  The outputs are stored under the `revdep` directory.\n- `rchk`: runs Kalibera's `rchk` utility.\n  This uses `docker` to download and run a Docker container.\n  The stdout for this is stored in `rchk.out`.\n\n- `session`: installs the package locally and then runs an **R** session for interactive testing.\n  This session is controlled by the `RSESSION` environment variable.\n  By default, this runs an `emacs -f R` session.\n- `rsession`: like `session`, but a naked **R** session is started: `RSESSION=R`.\n- `debug`: like `rsession`, but the **R** session is started under a debugger.\n  By default, the `gdb` debugger is used: `RSESSION=R -d gdb`.\n\n- `publish`: causes source and binary tarballs to be installed in the REPODIR respository.\n- `covr`: runs `covr::package_coverage()` to evaluate unit-test coverage.\n  Results are stored in `covr.rds`.\n- `vcovr`: like `covr`, but results are displayed in a browser. \n\n----------------\n\n## Github Actions\n\nSeveral Github Actions are defined in `.github/workflows`:\n\n- `r-cmd-check`: runs checks on various platforms.\n- `test-coverage`: runs `covr::codecov` to upload unit-test coverage information to [codecov.io](https://codecov.io).\n- `binary-build`: causes binary tarballs to be built for OS X and Windows platforms.\n\nThese must be updated manually from time to time as the Actions on which they depend change.\n\n----------------\n"
  },
  {
    "path": "CRAN.md",
    "content": "-------------------------\n\n# Preparing a CRAN submission\n\n## Checks\n\n- check [CRAN test results](https://cran.r-project.org/web/checks/check_results_pomp.html)\n- check [package issues page](https://github.com/kingaa/pomp/issues)\n- examine `R-CMD-CHECK` logs on Github Actions\n- examine tests coverage on [codecov.com](https://codecov.io/gh/kingaa/pomp).\n- copy old CRAN branch to new one and update timestamp:\n\n```\ngit branch v4.6 v4.5\ngit rebase master v4.6\ngit commit --amend --date=now --no-edit\ngit push github v4.6\n```\n\n- rebase: `git rebase master v4.6`\n  - consolidate `NEWS.md`\n  - `make NEWS`\n- verify that `.Rbuildignore` contains\n  - `tests`\n  - `README\\.md$`\n  - `TODO\\.md$`\n  - `CRAN\\.md$`\n  - `^\\.gitignore$`\n  - `^\\.travis\\.yml$`\n  - `^codecov\\.yml$`\n- perform extra checks:\n  - `make xcheck`\n  - `make ycheck`\n  - `make rchk`\n  - `make vcheck` and examine `valgrind` output in `pomp-Ex.Rout` for evidence of memory leaks.\n  - `make revdeps`\n\n## Submitting\n\n- Use the [webform](https://xmpalantir.wu.ac.at/cransubmit/) for submission.\n- **Example submission note text:**  \n  The package has been checked under R-4.1.0, R-release, and R-devel on linux, osx, and windows.\n  I have checked for memory leaks using 'valgrind'.\n  There are two new NOTEs generated, concerning S3 generic/method consistency.\n  These are false positives, since the functions in question `filter.mean` and `filter.traj` are themselves S4 generics.\n  I have checked that the S3 method dispatch system works properly.\n  In any case, these functions have been deprecated as of this version in favor of functions named `filter_mean` and `filter_traj`, so this false positive will go away when these functions are removed in a future release.\n  I have verified that this release does not break the reverse dependencies listed on CRAN, with the exception of **spatPomp**.\n  I am one of the developers of that package and we have prepared a CRAN release of this package that corrects this problem.\n  We will submit this as soon as this version of **pomp** is published to CRAN.\n\n## Announcement\n\n- Prepare an announcement for the blog: `www/_posts/`\n- Update manual pages:\n  - `make publish`\n  - Then push changes to `kingaa.github.io`\n- Make `X.X.0.0` release for Github site.\n\n-------------------------\n"
  },
  {
    "path": "DESCRIPTION",
    "content": "Package: pomp\nType: Package\nTitle: Statistical Inference for Partially Observed Markov Processes\nVersion: 6.4.0.0\nDate: 2025-11-25\nAuthors@R: c(person(given=c(\"Aaron\",\"A.\"),family=\"King\",role=c(\"aut\",\"cre\"),email=\"kingaa@umich.edu\",comment=c(ORCID=\"0000-0001-6159-3207\")),\n\t  person(given=c(\"Edward\",\"L.\"),family=\"Ionides\",role=\"aut\",comment=c(ORCID=\"0000-0002-4190-0174\"))\t,\n\t  person(given=\"Carles\",family=\"Bretó\",role=\"aut\",comment=c(ORCID=\"0000-0003-4695-4902\")),\n\t  person(given=c(\"Stephen\",\"P.\"),family=\"Ellner\",role=\"ctb\",comment=c(ORCID=\"0000-0002-8351-9734\")),\n\t  person(given=c(\"Matthew\",\"J.\"),family=\"Ferrari\",role=\"ctb\",comment=c(ORCID=\"0000-0001-5251-8168\")),\n\t  person(given=\"Sebastian\",family=\"Funk\",role=\"ctb\",comment=c(ORCID=\"0000-0002-2842-3406\")),\n\t  person(given=c(\"Steven\",\"G.\"),family=\"Johnson\",role=\"ctb\"),\n\t  person(given=c(\"Bruce\",\"E.\"),family=\"Kendall\",role=\"ctb\",comment=c(ORCID=\"0000-0003-1782-8106\")),\n\t  person(given=c(\"Michael\"),family=\"Lavine\",role=\"ctb\"),\n\t  person(given=\"Dao\",family=\"Nguyen\",role=\"ctb\",comment=c(ORCID=\"0000-0003-2215-613X\")),\n\t  person(given=c(\"Eamon\",\"B.\"),family=\"O'Dea\",role=\"ctb\",comment=c(ORCID=\"0000-0003-4748-683X\")),\n\t  person(given=c(\"Daniel\",\"C.\"),family=\"Reuman\",role=\"ctb\"),\n\t  person(given=c(\"Helen\"),family=\"Wearing\",role=\"ctb\",comment=c(ORCID=\"0000-0002-9837-9797\")),\n\t  person(given=c(\"Simon\",\"N.\"),family=\"Wood\",role=\"ctb\",comment=c(ORCID=\"0000-0002-2034-7453\"))\n\t  )\nURL: https://kingaa.github.io/pomp/\nDescription: Tools for data analysis with partially observed Markov process (POMP) models (also known as stochastic dynamical systems, hidden Markov models, and nonlinear, non-Gaussian, state-space models).  The package provides facilities for implementing POMP models, simulating them, and fitting them to time series data by a variety of frequentist and Bayesian methods.  It is also a versatile platform for implementation of inference methods for general POMP models.\nDepends: R(>= 4.1.0)\nImports: methods, stats, graphics, digest, mvtnorm, deSolve, coda, data.table\nSuggests: ggplot2, knitr, dplyr, tidyr, subplex, nloptr\nSystemRequirements: For Windows users, Rtools (see https://cran.r-project.org/bin/windows/Rtools/).\nLicense: GPL-3\nLazyData: true\nBugReports: https://github.com/kingaa/pomp/issues/\nEncoding: UTF-8\nRoxygen: list(roclets = c(\"collate\", \"namespace\", \"rd\"))\nRoxygenNote: 7.3.3\nCollate: \n    'package.R'\n    'pstop.R'\n    'undefined.R'\n    'csnippet.R'\n    'pomp_fun.R'\n    'parameter_trans.R'\n    'covariate_table.R'\n    'skeleton_spec.R'\n    'rprocess_spec.R'\n    'safecall.R'\n    'pomp_class.R'\n    'load.R'\n    'workhorses.R'\n    'continue.R'\n    'summary.R'\n    'prior_spec.R'\n    'dmeasure_spec.R'\n    'dprocess_spec.R'\n    'rmeasure_spec.R'\n    'rinit_spec.R'\n    'dinit_spec.R'\n    'templates.R'\n    'builder.R'\n    'pomp.R'\n    'probe.R'\n    'abc.R'\n    'accumulators.R'\n    'melt.R'\n    'kalman.R'\n    'pfilter.R'\n    'wpfilter.R'\n    'proposals.R'\n    'pmcmc.R'\n    'mif2.R'\n    'listie.R'\n    'simulate.R'\n    'spect.R'\n    'plot.R'\n    'bsmc2.R'\n    'as_data_frame.R'\n    'as_pomp.R'\n    'bake.R'\n    'basic_components.R'\n    'basic_probes.R'\n    'betabinom.R'\n    'blowflies.R'\n    'bsflu.R'\n    'bsplines.R'\n    'childhood.R'\n    'coef.R'\n    'conc.R'\n    'concat.R'\n    'cond_logLik.R'\n    'covmat.R'\n    'dacca.R'\n    'design.R'\n    'ebola.R'\n    'eff_sample_size.R'\n    'elementary_algorithms.R'\n    'emeasure_spec.R'\n    'estimation_algorithms.R'\n    'eulermultinom.R'\n    'extract.R'\n    'filter_mean.R'\n    'filter_traj.R'\n    'flow.R'\n    'forecast.R'\n    'gompertz.R'\n    'kf.R'\n    'probe_match.R'\n    'spect_match.R'\n    'nlf.R'\n    'trajectory.R'\n    'traj_match.R'\n    'objfun.R'\n    'loglik.R'\n    'logmeanexp.R'\n    'lookup.R'\n    'mcap.R'\n    'obs.R'\n    'ou2.R'\n    'parmat.R'\n    'parus.R'\n    'pomp_examp.R'\n    'pred_mean.R'\n    'pred_var.R'\n    'show.R'\n    'print.R'\n    'profile_design.R'\n    'resample.R'\n    'ricker.R'\n    'runif_design.R'\n    'rw2.R'\n    'sannbox.R'\n    'saved_states.R'\n    'sir.R'\n    'slice_design.R'\n    'sobol_design.R'\n    'spy.R'\n    'states.R'\n    'time.R'\n    'timezero.R'\n    'traces.R'\n    'transformations.R'\n    'userdata.R'\n    'verhulst.R'\n    'vmeasure_spec.R'\n    'window.R'\n    'wquant.R'\n"
  },
  {
    "path": "Doxyfile",
    "content": "# Doxyfile 1.9.1\n\n# This file describes the settings to be used by the documentation system\n# doxygen (www.doxygen.org) for a project.\n#\n# All text after a double hash (##) is considered a comment and is placed in\n# front of the TAG it is preceding.\n#\n# All text after a single hash (#) is considered a comment and will be ignored.\n# The format is:\n# TAG = value [value, ...]\n# For lists, items can also be appended using:\n# TAG += value [value, ...]\n# Values that contain spaces should be placed between quotes (\\\" \\\").\n\n#---------------------------------------------------------------------------\n# Project related configuration options\n#---------------------------------------------------------------------------\n\n# This tag specifies the encoding used for all characters in the configuration\n# file that follow. The default is UTF-8 which is also the encoding used for all\n# text before the first occurrence of this tag. Doxygen uses libiconv (or the\n# iconv built into libc) for the transcoding. See\n# https://www.gnu.org/software/libiconv/ for the list of possible encodings.\n# The default value is: UTF-8.\n\nDOXYFILE_ENCODING      = UTF-8\n\n# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by\n# double-quotes, unless you are using Doxywizard) that should identify the\n# project for which the documentation is generated. This name is used in the\n# title of most generated pages and in a few other places.\n# The default value is: My Project.\n\nPROJECT_NAME           = pomp\n\n# The PROJECT_NUMBER tag can be used to enter a project or revision number. This\n# could be handy for archiving the generated documentation or if some version\n# control system is used.\n\nPROJECT_NUMBER         =\n\n# Using the PROJECT_BRIEF tag one can provide an optional one line description\n# for a project that appears at the top of each page and should give viewer a\n# quick idea about the purpose of the project. Keep the description short.\n\nPROJECT_BRIEF          = \"Inference for partially observed Markov processes\"\n\n# With the PROJECT_LOGO tag one can specify a logo or an icon that is included\n# in the documentation. The maximum height of the logo should not exceed 55\n# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy\n# the logo to the output directory.\n\nPROJECT_LOGO           =\n\n# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path\n# into which the generated documentation will be written. If a relative path is\n# entered, it will be relative to the location where doxygen was started. If\n# left blank the current directory will be used.\n\nOUTPUT_DIRECTORY       = ../www/manuals/pomp/source\n\n# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub-\n# directories (in 2 levels) under the output directory of each output format and\n# will distribute the generated files over these directories. Enabling this\n# option can be useful when feeding doxygen a huge amount of source files, where\n# putting all generated files in the same directory would otherwise causes\n# performance problems for the file system.\n# The default value is: NO.\n\nCREATE_SUBDIRS         = NO\n\n# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII\n# characters to appear in the names of generated files. If set to NO, non-ASCII\n# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode\n# U+3044.\n# The default value is: NO.\n\nALLOW_UNICODE_NAMES    = NO\n\n# The OUTPUT_LANGUAGE tag is used to specify the language in which all\n# documentation generated by doxygen is written. Doxygen will use this\n# information to generate all constant output in the proper language.\n# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese,\n# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States),\n# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian,\n# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages),\n# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian,\n# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian,\n# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish,\n# Ukrainian and Vietnamese.\n# The default value is: English.\n\nOUTPUT_LANGUAGE        = English\n\n# The OUTPUT_TEXT_DIRECTION tag is used to specify the direction in which all\n# documentation generated by doxygen is written. Doxygen will use this\n# information to generate all generated output in the proper direction.\n# Possible values are: None, LTR, RTL and Context.\n# The default value is: None.\n\nOUTPUT_TEXT_DIRECTION  = None\n\n# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member\n# descriptions after the members that are listed in the file and class\n# documentation (similar to Javadoc). Set to NO to disable this.\n# The default value is: YES.\n\nBRIEF_MEMBER_DESC      = YES\n\n# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief\n# description of a member or function before the detailed description\n#\n# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the\n# brief descriptions will be completely suppressed.\n# The default value is: YES.\n\nREPEAT_BRIEF           = YES\n\n# This tag implements a quasi-intelligent brief description abbreviator that is\n# used to form the text in various listings. Each string in this list, if found\n# as the leading text of the brief description, will be stripped from the text\n# and the result, after processing the whole list, is used as the annotated\n# text. Otherwise, the brief description is used as-is. If left blank, the\n# following values are used ($name is automatically replaced with the name of\n# the entity):The $name class, The $name widget, The $name file, is, provides,\n# specifies, contains, represents, a, an and the.\n\nABBREVIATE_BRIEF       = \"The $name class\" \\\n                         \"The $name widget\" \\\n                         \"The $name file\" \\\n                         is \\\n                         provides \\\n                         specifies \\\n                         contains \\\n                         represents \\\n                         a \\\n                         an \\\n                         the\n\n# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then\n# doxygen will generate a detailed section even if there is only a brief\n# description.\n# The default value is: NO.\n\nALWAYS_DETAILED_SEC    = NO\n\n# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all\n# inherited members of a class in the documentation of that class as if those\n# members were ordinary class members. Constructors, destructors and assignment\n# operators of the base classes will not be shown.\n# The default value is: NO.\n\nINLINE_INHERITED_MEMB  = NO\n\n# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path\n# before files name in the file list and in the header files. If set to NO the\n# shortest path that makes the file name unique will be used\n# The default value is: YES.\n\nFULL_PATH_NAMES        = YES\n\n# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.\n# Stripping is only done if one of the specified strings matches the left-hand\n# part of the path. The tag can be used to show relative paths in the file list.\n# If left blank the directory from which doxygen is run is used as the path to\n# strip.\n#\n# Note that you can specify absolute paths here, but also relative paths, which\n# will be relative from the directory where doxygen is started.\n# This tag requires that the tag FULL_PATH_NAMES is set to YES.\n\nSTRIP_FROM_PATH        =\n\n# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the\n# path mentioned in the documentation of a class, which tells the reader which\n# header file to include in order to use a class. If left blank only the name of\n# the header file containing the class definition is used. Otherwise one should\n# specify the list of include paths that are normally passed to the compiler\n# using the -I flag.\n\nSTRIP_FROM_INC_PATH    =\n\n# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but\n# less readable) file names. This can be useful is your file systems doesn't\n# support long names like on DOS, Mac, or CD-ROM.\n# The default value is: NO.\n\nSHORT_NAMES            = NO\n\n# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the\n# first line (until the first dot) of a Javadoc-style comment as the brief\n# description. If set to NO, the Javadoc-style will behave just like regular Qt-\n# style comments (thus requiring an explicit @brief command for a brief\n# description.)\n# The default value is: NO.\n\nJAVADOC_AUTOBRIEF      = NO\n\n# If the JAVADOC_BANNER tag is set to YES then doxygen will interpret a line\n# such as\n# /***************\n# as being the beginning of a Javadoc-style comment \"banner\". If set to NO, the\n# Javadoc-style will behave just like regular comments and it will not be\n# interpreted by doxygen.\n# The default value is: NO.\n\nJAVADOC_BANNER         = NO\n\n# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first\n# line (until the first dot) of a Qt-style comment as the brief description. If\n# set to NO, the Qt-style will behave just like regular Qt-style comments (thus\n# requiring an explicit \\brief command for a brief description.)\n# The default value is: NO.\n\nQT_AUTOBRIEF           = NO\n\n# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a\n# multi-line C++ special comment block (i.e. a block of //! or /// comments) as\n# a brief description. This used to be the default behavior. The new default is\n# to treat a multi-line C++ comment block as a detailed description. Set this\n# tag to YES if you prefer the old behavior instead.\n#\n# Note that setting this tag to YES also means that rational rose comments are\n# not recognized any more.\n# The default value is: NO.\n\nMULTILINE_CPP_IS_BRIEF = NO\n\n# By default Python docstrings are displayed as preformatted text and doxygen's\n# special commands cannot be used. By setting PYTHON_DOCSTRING to NO the\n# doxygen's special commands can be used and the contents of the docstring\n# documentation blocks is shown as doxygen documentation.\n# The default value is: YES.\n\nPYTHON_DOCSTRING       = YES\n\n# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the\n# documentation from any documented member that it re-implements.\n# The default value is: YES.\n\nINHERIT_DOCS           = YES\n\n# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new\n# page for each member. If set to NO, the documentation of a member will be part\n# of the file/class/namespace that contains it.\n# The default value is: NO.\n\nSEPARATE_MEMBER_PAGES  = NO\n\n# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen\n# uses this value to replace tabs by spaces in code fragments.\n# Minimum value: 1, maximum value: 16, default value: 4.\n\nTAB_SIZE               = 4\n\n# This tag can be used to specify a number of aliases that act as commands in\n# the documentation. An alias has the form:\n# name=value\n# For example adding\n# \"sideeffect=@par Side Effects:\\n\"\n# will allow you to put the command \\sideeffect (or @sideeffect) in the\n# documentation, which will result in a user-defined paragraph with heading\n# \"Side Effects:\". You can put \\n's in the value part of an alias to insert\n# newlines (in the resulting output). You can put ^^ in the value part of an\n# alias to insert a newline as if a physical newline was in the original file.\n# When you need a literal { or } or , in the value part of an alias you have to\n# escape them by means of a backslash (\\), this can lead to conflicts with the\n# commands \\{ and \\} for these it is advised to use the version @{ and @} or use\n# a double escape (\\\\{ and \\\\})\n\nALIASES                =\n\n# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources\n# only. Doxygen will then generate output that is more tailored for C. For\n# instance, some of the names that are used will be different. The list of all\n# members will be omitted, etc.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_FOR_C  = YES\n\n# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or\n# Python sources only. Doxygen will then generate output that is more tailored\n# for that language. For instance, namespaces will be presented as packages,\n# qualified scopes will look different, etc.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_JAVA   = NO\n\n# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran\n# sources. Doxygen will then generate output that is tailored for Fortran.\n# The default value is: NO.\n\nOPTIMIZE_FOR_FORTRAN   = NO\n\n# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL\n# sources. Doxygen will then generate output that is tailored for VHDL.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_VHDL   = NO\n\n# Set the OPTIMIZE_OUTPUT_SLICE tag to YES if your project consists of Slice\n# sources only. Doxygen will then generate output that is more tailored for that\n# language. For instance, namespaces will be presented as modules, types will be\n# separated into more groups, etc.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_SLICE  = NO\n\n# Doxygen selects the parser to use depending on the extension of the files it\n# parses. With this tag you can assign which parser to use for a given\n# extension. Doxygen has a built-in mapping, but you can override or extend it\n# using this tag. The format is ext=language, where ext is a file extension, and\n# language is one of the parsers supported by doxygen: IDL, Java, JavaScript,\n# Csharp (C#), C, C++, D, PHP, md (Markdown), Objective-C, Python, Slice, VHDL,\n# Fortran (fixed format Fortran: FortranFixed, free formatted Fortran:\n# FortranFree, unknown formatted Fortran: Fortran. In the later case the parser\n# tries to guess whether the code is fixed or free formatted code, this is the\n# default for Fortran type files). For instance to make doxygen treat .inc files\n# as Fortran files (default is PHP), and .f files as C (default is Fortran),\n# use: inc=Fortran f=C.\n#\n# Note: For files without extension you can use no_extension as a placeholder.\n#\n# Note that for custom extensions you also need to set FILE_PATTERNS otherwise\n# the files are not read by doxygen. When specifying no_extension you should add\n# * to the FILE_PATTERNS.\n#\n# Note see also the list of default file extension mappings.\n\nEXTENSION_MAPPING      =\n\n# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments\n# according to the Markdown format, which allows for more readable\n# documentation. See https://daringfireball.net/projects/markdown/ for details.\n# The output of markdown processing is further processed by doxygen, so you can\n# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in\n# case of backward compatibilities issues.\n# The default value is: YES.\n\nMARKDOWN_SUPPORT       = YES\n\n# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up\n# to that level are automatically included in the table of contents, even if\n# they do not have an id attribute.\n# Note: This feature currently applies only to Markdown headings.\n# Minimum value: 0, maximum value: 99, default value: 5.\n# This tag requires that the tag MARKDOWN_SUPPORT is set to YES.\n\nTOC_INCLUDE_HEADINGS   = 5\n\n# When enabled doxygen tries to link words that correspond to documented\n# classes, or namespaces to their corresponding documentation. Such a link can\n# be prevented in individual cases by putting a % sign in front of the word or\n# globally by setting AUTOLINK_SUPPORT to NO.\n# The default value is: YES.\n\nAUTOLINK_SUPPORT       = YES\n\n# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want\n# to include (a tag file for) the STL sources as input, then you should set this\n# tag to YES in order to let doxygen match functions declarations and\n# definitions whose arguments contain STL classes (e.g. func(std::string);\n# versus func(std::string) {}). This also make the inheritance and collaboration\n# diagrams that involve STL classes more complete and accurate.\n# The default value is: NO.\n\nBUILTIN_STL_SUPPORT    = NO\n\n# If you use Microsoft's C++/CLI language, you should set this option to YES to\n# enable parsing support.\n# The default value is: NO.\n\nCPP_CLI_SUPPORT        = NO\n\n# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:\n# https://www.riverbankcomputing.com/software/sip/intro) sources only. Doxygen\n# will parse them like normal C++ but will assume all classes use public instead\n# of private inheritance when no explicit protection keyword is present.\n# The default value is: NO.\n\nSIP_SUPPORT            = NO\n\n# For Microsoft's IDL there are propget and propput attributes to indicate\n# getter and setter methods for a property. Setting this option to YES will make\n# doxygen to replace the get and set methods by a property in the documentation.\n# This will only work if the methods are indeed getting or setting a simple\n# type. If this is not the case, or you want to show the methods anyway, you\n# should set this option to NO.\n# The default value is: YES.\n\nIDL_PROPERTY_SUPPORT   = YES\n\n# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC\n# tag is set to YES then doxygen will reuse the documentation of the first\n# member in the group (if any) for the other members of the group. By default\n# all members of a group must be documented explicitly.\n# The default value is: NO.\n\nDISTRIBUTE_GROUP_DOC   = NO\n\n# If one adds a struct or class to a group and this option is enabled, then also\n# any nested class or struct is added to the same group. By default this option\n# is disabled and one has to add nested compounds explicitly via \\ingroup.\n# The default value is: NO.\n\nGROUP_NESTED_COMPOUNDS = NO\n\n# Set the SUBGROUPING tag to YES to allow class member groups of the same type\n# (for instance a group of public functions) to be put as a subgroup of that\n# type (e.g. under the Public Functions section). Set it to NO to prevent\n# subgrouping. Alternatively, this can be done per class using the\n# \\nosubgrouping command.\n# The default value is: YES.\n\nSUBGROUPING            = YES\n\n# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions\n# are shown inside the group in which they are included (e.g. using \\ingroup)\n# instead of on a separate page (for HTML and Man pages) or section (for LaTeX\n# and RTF).\n#\n# Note that this feature does not work in combination with\n# SEPARATE_MEMBER_PAGES.\n# The default value is: NO.\n\nINLINE_GROUPED_CLASSES = NO\n\n# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions\n# with only public data fields or simple typedef fields will be shown inline in\n# the documentation of the scope in which they are defined (i.e. file,\n# namespace, or group documentation), provided this scope is documented. If set\n# to NO, structs, classes, and unions are shown on a separate page (for HTML and\n# Man pages) or section (for LaTeX and RTF).\n# The default value is: NO.\n\nINLINE_SIMPLE_STRUCTS  = NO\n\n# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or\n# enum is documented as struct, union, or enum with the name of the typedef. So\n# typedef struct TypeS {} TypeT, will appear in the documentation as a struct\n# with name TypeT. When disabled the typedef will appear as a member of a file,\n# namespace, or class. And the struct will be named TypeS. This can typically be\n# useful for C code in case the coding convention dictates that all compound\n# types are typedef'ed and only the typedef is referenced, never the tag name.\n# The default value is: NO.\n\nTYPEDEF_HIDES_STRUCT   = NO\n\n# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This\n# cache is used to resolve symbols given their name and scope. Since this can be\n# an expensive process and often the same symbol appears multiple times in the\n# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small\n# doxygen will become slower. If the cache is too large, memory is wasted. The\n# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range\n# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536\n# symbols. At the end of a run doxygen will report the cache usage and suggest\n# the optimal cache size from a speed point of view.\n# Minimum value: 0, maximum value: 9, default value: 0.\n\nLOOKUP_CACHE_SIZE      = 0\n\n# The NUM_PROC_THREADS specifies the number threads doxygen is allowed to use\n# during processing. When set to 0 doxygen will based this on the number of\n# cores available in the system. You can set it explicitly to a value larger\n# than 0 to get more control over the balance between CPU load and processing\n# speed. At this moment only the input processing can be done using multiple\n# threads. Since this is still an experimental feature the default is set to 1,\n# which efficively disables parallel processing. Please report any issues you\n# encounter. Generating dot graphs in parallel is controlled by the\n# DOT_NUM_THREADS setting.\n# Minimum value: 0, maximum value: 32, default value: 1.\n\nNUM_PROC_THREADS       = 1\n\n#---------------------------------------------------------------------------\n# Build related configuration options\n#---------------------------------------------------------------------------\n\n# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in\n# documentation are documented, even if no documentation was available. Private\n# class members and static file members will be hidden unless the\n# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.\n# Note: This will also disable the warnings about undocumented members that are\n# normally produced when WARNINGS is set to YES.\n# The default value is: NO.\n\nEXTRACT_ALL            = YES\n\n# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will\n# be included in the documentation.\n# The default value is: NO.\n\nEXTRACT_PRIVATE        = YES\n\n# If the EXTRACT_PRIV_VIRTUAL tag is set to YES, documented private virtual\n# methods of a class will be included in the documentation.\n# The default value is: NO.\n\nEXTRACT_PRIV_VIRTUAL   = NO\n\n# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal\n# scope will be included in the documentation.\n# The default value is: NO.\n\nEXTRACT_PACKAGE        = NO\n\n# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be\n# included in the documentation.\n# The default value is: NO.\n\nEXTRACT_STATIC         = YES\n\n# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined\n# locally in source files will be included in the documentation. If set to NO,\n# only classes defined in header files are included. Does not have any effect\n# for Java sources.\n# The default value is: YES.\n\nEXTRACT_LOCAL_CLASSES  = YES\n\n# This flag is only useful for Objective-C code. If set to YES, local methods,\n# which are defined in the implementation section but not in the interface are\n# included in the documentation. If set to NO, only methods in the interface are\n# included.\n# The default value is: NO.\n\nEXTRACT_LOCAL_METHODS  = NO\n\n# If this flag is set to YES, the members of anonymous namespaces will be\n# extracted and appear in the documentation as a namespace called\n# 'anonymous_namespace{file}', where file will be replaced with the base name of\n# the file that contains the anonymous namespace. By default anonymous namespace\n# are hidden.\n# The default value is: NO.\n\nEXTRACT_ANON_NSPACES   = NO\n\n# If this flag is set to YES, the name of an unnamed parameter in a declaration\n# will be determined by the corresponding definition. By default unnamed\n# parameters remain unnamed in the output.\n# The default value is: YES.\n\nRESOLVE_UNNAMED_PARAMS = YES\n\n# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all\n# undocumented members inside documented classes or files. If set to NO these\n# members will be included in the various overviews, but no documentation\n# section is generated. This option has no effect if EXTRACT_ALL is enabled.\n# The default value is: NO.\n\nHIDE_UNDOC_MEMBERS     = NO\n\n# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all\n# undocumented classes that are normally visible in the class hierarchy. If set\n# to NO, these classes will be included in the various overviews. This option\n# has no effect if EXTRACT_ALL is enabled.\n# The default value is: NO.\n\nHIDE_UNDOC_CLASSES     = NO\n\n# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend\n# declarations. If set to NO, these declarations will be included in the\n# documentation.\n# The default value is: NO.\n\nHIDE_FRIEND_COMPOUNDS  = NO\n\n# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any\n# documentation blocks found inside the body of a function. If set to NO, these\n# blocks will be appended to the function's detailed documentation block.\n# The default value is: NO.\n\nHIDE_IN_BODY_DOCS      = NO\n\n# The INTERNAL_DOCS tag determines if documentation that is typed after a\n# \\internal command is included. If the tag is set to NO then the documentation\n# will be excluded. Set it to YES to include the internal documentation.\n# The default value is: NO.\n\nINTERNAL_DOCS          = NO\n\n# With the correct setting of option CASE_SENSE_NAMES doxygen will better be\n# able to match the capabilities of the underlying filesystem. In case the\n# filesystem is case sensitive (i.e. it supports files in the same directory\n# whose names only differ in casing), the option must be set to YES to properly\n# deal with such files in case they appear in the input. For filesystems that\n# are not case sensitive the option should be be set to NO to properly deal with\n# output files written for symbols that only differ in casing, such as for two\n# classes, one named CLASS and the other named Class, and to also support\n# references to files without having to specify the exact matching casing. On\n# Windows (including Cygwin) and MacOS, users should typically set this option\n# to NO, whereas on Linux or other Unix flavors it should typically be set to\n# YES.\n# The default value is: system dependent.\n\nCASE_SENSE_NAMES       = NO\n\n# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with\n# their full class and namespace scopes in the documentation. If set to YES, the\n# scope will be hidden.\n# The default value is: NO.\n\nHIDE_SCOPE_NAMES       = NO\n\n# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will\n# append additional text to a page's title, such as Class Reference. If set to\n# YES the compound reference will be hidden.\n# The default value is: NO.\n\nHIDE_COMPOUND_REFERENCE= NO\n\n# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of\n# the files that are included by a file in the documentation of that file.\n# The default value is: YES.\n\nSHOW_INCLUDE_FILES     = YES\n\n# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each\n# grouped member an include statement to the documentation, telling the reader\n# which file to include in order to use the member.\n# The default value is: NO.\n\nSHOW_GROUPED_MEMB_INC  = NO\n\n# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include\n# files with double quotes in the documentation rather than with sharp brackets.\n# The default value is: NO.\n\nFORCE_LOCAL_INCLUDES   = NO\n\n# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the\n# documentation for inline members.\n# The default value is: YES.\n\nINLINE_INFO            = YES\n\n# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the\n# (detailed) documentation of file and class members alphabetically by member\n# name. If set to NO, the members will appear in declaration order.\n# The default value is: YES.\n\nSORT_MEMBER_DOCS       = YES\n\n# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief\n# descriptions of file, namespace and class members alphabetically by member\n# name. If set to NO, the members will appear in declaration order. Note that\n# this will also influence the order of the classes in the class list.\n# The default value is: NO.\n\nSORT_BRIEF_DOCS        = NO\n\n# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the\n# (brief and detailed) documentation of class members so that constructors and\n# destructors are listed first. If set to NO the constructors will appear in the\n# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.\n# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief\n# member documentation.\n# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting\n# detailed member documentation.\n# The default value is: NO.\n\nSORT_MEMBERS_CTORS_1ST = NO\n\n# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy\n# of group names into alphabetical order. If set to NO the group names will\n# appear in their defined order.\n# The default value is: NO.\n\nSORT_GROUP_NAMES       = NO\n\n# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by\n# fully-qualified names, including namespaces. If set to NO, the class list will\n# be sorted only by class name, not including the namespace part.\n# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.\n# Note: This option applies only to the class list, not to the alphabetical\n# list.\n# The default value is: NO.\n\nSORT_BY_SCOPE_NAME     = NO\n\n# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper\n# type resolution of all parameters of a function it will reject a match between\n# the prototype and the implementation of a member function even if there is\n# only one candidate or it is obvious which candidate to choose by doing a\n# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still\n# accept a match between prototype and implementation in such cases.\n# The default value is: NO.\n\nSTRICT_PROTO_MATCHING  = NO\n\n# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo\n# list. This list is created by putting \\todo commands in the documentation.\n# The default value is: YES.\n\nGENERATE_TODOLIST      = YES\n\n# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test\n# list. This list is created by putting \\test commands in the documentation.\n# The default value is: YES.\n\nGENERATE_TESTLIST      = YES\n\n# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug\n# list. This list is created by putting \\bug commands in the documentation.\n# The default value is: YES.\n\nGENERATE_BUGLIST       = YES\n\n# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO)\n# the deprecated list. This list is created by putting \\deprecated commands in\n# the documentation.\n# The default value is: YES.\n\nGENERATE_DEPRECATEDLIST= YES\n\n# The ENABLED_SECTIONS tag can be used to enable conditional documentation\n# sections, marked by \\if <section_label> ... \\endif and \\cond <section_label>\n# ... \\endcond blocks.\n\nENABLED_SECTIONS       =\n\n# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the\n# initial value of a variable or macro / define can have for it to appear in the\n# documentation. If the initializer consists of more lines than specified here\n# it will be hidden. Use a value of 0 to hide initializers completely. The\n# appearance of the value of individual variables and macros / defines can be\n# controlled using \\showinitializer or \\hideinitializer command in the\n# documentation regardless of this setting.\n# Minimum value: 0, maximum value: 10000, default value: 30.\n\nMAX_INITIALIZER_LINES  = 30\n\n# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at\n# the bottom of the documentation of classes and structs. If set to YES, the\n# list will mention the files that were used to generate the documentation.\n# The default value is: YES.\n\nSHOW_USED_FILES        = YES\n\n# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This\n# will remove the Files entry from the Quick Index and from the Folder Tree View\n# (if specified).\n# The default value is: YES.\n\nSHOW_FILES             = YES\n\n# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces\n# page. This will remove the Namespaces entry from the Quick Index and from the\n# Folder Tree View (if specified).\n# The default value is: YES.\n\nSHOW_NAMESPACES        = YES\n\n# The FILE_VERSION_FILTER tag can be used to specify a program or script that\n# doxygen should invoke to get the current version for each file (typically from\n# the version control system). Doxygen will invoke the program by executing (via\n# popen()) the command command input-file, where command is the value of the\n# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided\n# by doxygen. Whatever the program writes to standard output is used as the file\n# version. For an example see the documentation.\n\nFILE_VERSION_FILTER    =\n\n# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed\n# by doxygen. The layout file controls the global structure of the generated\n# output files in an output format independent way. To create the layout file\n# that represents doxygen's defaults, run doxygen with the -l option. You can\n# optionally specify a file name after the option, if omitted DoxygenLayout.xml\n# will be used as the name of the layout file.\n#\n# Note that if you run doxygen from a directory containing a file called\n# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE\n# tag is left empty.\n\nLAYOUT_FILE            =\n\n# The CITE_BIB_FILES tag can be used to specify one or more bib files containing\n# the reference definitions. This must be a list of .bib files. The .bib\n# extension is automatically appended if omitted. This requires the bibtex tool\n# to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info.\n# For LaTeX the style of the bibliography can be controlled using\n# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the\n# search path. See also \\cite for info how to create references.\n\nCITE_BIB_FILES         =\n\n#---------------------------------------------------------------------------\n# Configuration options related to warning and progress messages\n#---------------------------------------------------------------------------\n\n# The QUIET tag can be used to turn on/off the messages that are generated to\n# standard output by doxygen. If QUIET is set to YES this implies that the\n# messages are off.\n# The default value is: NO.\n\nQUIET                  = NO\n\n# The WARNINGS tag can be used to turn on/off the warning messages that are\n# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES\n# this implies that the warnings are on.\n#\n# Tip: Turn warnings on while writing the documentation.\n# The default value is: YES.\n\nWARNINGS               = YES\n\n# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate\n# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag\n# will automatically be disabled.\n# The default value is: YES.\n\nWARN_IF_UNDOCUMENTED   = YES\n\n# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for\n# potential errors in the documentation, such as not documenting some parameters\n# in a documented function, or documenting parameters that don't exist or using\n# markup commands wrongly.\n# The default value is: YES.\n\nWARN_IF_DOC_ERROR      = YES\n\n# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that\n# are documented, but have no documentation for their parameters or return\n# value. If set to NO, doxygen will only warn about wrong or incomplete\n# parameter documentation, but not about the absence of documentation. If\n# EXTRACT_ALL is set to YES then this flag will automatically be disabled.\n# The default value is: NO.\n\nWARN_NO_PARAMDOC       = NO\n\n# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when\n# a warning is encountered. If the WARN_AS_ERROR tag is set to FAIL_ON_WARNINGS\n# then doxygen will continue running as if WARN_AS_ERROR tag is set to NO, but\n# at the end of the doxygen process doxygen will return with a non-zero status.\n# Possible values are: NO, YES and FAIL_ON_WARNINGS.\n# The default value is: NO.\n\nWARN_AS_ERROR          = NO\n\n# The WARN_FORMAT tag determines the format of the warning messages that doxygen\n# can produce. The string should contain the $file, $line, and $text tags, which\n# will be replaced by the file and line number from which the warning originated\n# and the warning text. Optionally the format may contain $version, which will\n# be replaced by the version of the file (if it could be obtained via\n# FILE_VERSION_FILTER)\n# The default value is: $file:$line: $text.\n\nWARN_FORMAT            = \"$file:$line: $text\"\n\n# The WARN_LOGFILE tag can be used to specify a file to which warning and error\n# messages should be written. If left blank the output is written to standard\n# error (stderr).\n\nWARN_LOGFILE           =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the input files\n#---------------------------------------------------------------------------\n\n# The INPUT tag is used to specify the files and/or directories that contain\n# documented source files. You may enter file names like myfile.cpp or\n# directories like /usr/src/myproject. Separate the files or directories with\n# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING\n# Note: If this tag is empty the current directory is searched.\n\nINPUT                  = ./src\n\n# This tag can be used to specify the character encoding of the source files\n# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses\n# libiconv (or the iconv built into libc) for the transcoding. See the libiconv\n# documentation (see:\n# https://www.gnu.org/software/libiconv/) for the list of possible encodings.\n# The default value is: UTF-8.\n\nINPUT_ENCODING         = UTF-8\n\n# If the value of the INPUT tag contains directories, you can use the\n# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and\n# *.h) to filter out the source-files in the directories.\n#\n# Note that for custom extensions or not directly supported extensions you also\n# need to set EXTENSION_MAPPING for the extension otherwise the files are not\n# read by doxygen.\n#\n# Note the list of default checked file patterns might differ from the list of\n# default file extension mappings.\n#\n# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp,\n# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h,\n# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc,\n# *.m, *.markdown, *.md, *.mm, *.dox (to be provided as doxygen C comment),\n# *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, *.f18, *.f, *.for, *.vhd, *.vhdl,\n# *.ucf, *.qsf and *.ice.\n\nFILE_PATTERNS          = *.c \\\n                         *.cc \\\n                         *.cxx \\\n                         *.cpp \\\n                         *.c++ \\\n                         *.java \\\n                         *.ii \\\n                         *.ixx \\\n                         *.ipp \\\n                         *.i++ \\\n                         *.inl \\\n                         *.idl \\\n                         *.ddl \\\n                         *.odl \\\n                         *.h \\\n                         *.hh \\\n                         *.hxx \\\n                         *.hpp \\\n                         *.h++ \\\n                         *.cs \\\n                         *.d \\\n                         *.php \\\n                         *.php4 \\\n                         *.php5 \\\n                         *.phtml \\\n                         *.inc \\\n                         *.m \\\n                         *.markdown \\\n                         *.md \\\n                         *.mm \\\n                         *.dox \\\n                         *.doc \\\n                         *.txt \\\n                         *.py \\\n                         *.pyw \\\n                         *.f90 \\\n                         *.f95 \\\n                         *.f03 \\\n                         *.f08 \\\n                         *.f \\\n                         *.for \\\n                         *.tcl \\\n                         *.vhd \\\n                         *.vhdl \\\n                         *.ucf \\\n                         *.qsf \\\n                         *.ice\n\n# The RECURSIVE tag can be used to specify whether or not subdirectories should\n# be searched for input files as well.\n# The default value is: NO.\n\nRECURSIVE              = NO\n\n# The EXCLUDE tag can be used to specify files and/or directories that should be\n# excluded from the INPUT source files. This way you can easily exclude a\n# subdirectory from a directory tree whose root is specified with the INPUT tag.\n#\n# Note that relative paths are relative to the directory from which doxygen is\n# run.\n\nEXCLUDE                =\n\n# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or\n# directories that are symbolic links (a Unix file system feature) are excluded\n# from the input.\n# The default value is: NO.\n\nEXCLUDE_SYMLINKS       = NO\n\n# If the value of the INPUT tag contains directories, you can use the\n# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude\n# certain files from those directories.\n#\n# Note that the wildcards are matched against the file with absolute path, so to\n# exclude all test directories for example use the pattern */test/*\n\nEXCLUDE_PATTERNS       =\n\n# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names\n# (namespaces, classes, functions, etc.) that should be excluded from the\n# output. The symbol name can be a fully qualified name, a word, or if the\n# wildcard * is used, a substring. Examples: ANamespace, AClass,\n# AClass::ANamespace, ANamespace::*Test\n#\n# Note that the wildcards are matched against the file with absolute path, so to\n# exclude all test directories use the pattern */test/*\n\nEXCLUDE_SYMBOLS        =\n\n# The EXAMPLE_PATH tag can be used to specify one or more files or directories\n# that contain example code fragments that are included (see the \\include\n# command).\n\nEXAMPLE_PATH           =\n\n# If the value of the EXAMPLE_PATH tag contains directories, you can use the\n# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and\n# *.h) to filter out the source-files in the directories. If left blank all\n# files are included.\n\nEXAMPLE_PATTERNS       = *\n\n# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be\n# searched for input files to be used with the \\include or \\dontinclude commands\n# irrespective of the value of the RECURSIVE tag.\n# The default value is: NO.\n\nEXAMPLE_RECURSIVE      = NO\n\n# The IMAGE_PATH tag can be used to specify one or more files or directories\n# that contain images that are to be included in the documentation (see the\n# \\image command).\n\nIMAGE_PATH             =\n\n# The INPUT_FILTER tag can be used to specify a program that doxygen should\n# invoke to filter for each input file. Doxygen will invoke the filter program\n# by executing (via popen()) the command:\n#\n# <filter> <input-file>\n#\n# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the\n# name of an input file. Doxygen will then use the output that the filter\n# program writes to standard output. If FILTER_PATTERNS is specified, this tag\n# will be ignored.\n#\n# Note that the filter must not add or remove lines; it is applied before the\n# code is scanned, but not when the output code is generated. If lines are added\n# or removed, the anchors will not be placed correctly.\n#\n# Note that for custom extensions or not directly supported extensions you also\n# need to set EXTENSION_MAPPING for the extension otherwise the files are not\n# properly processed by doxygen.\n\nINPUT_FILTER           =\n\n# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern\n# basis. Doxygen will compare the file name with each pattern and apply the\n# filter if there is a match. The filters are a list of the form: pattern=filter\n# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how\n# filters are used. If the FILTER_PATTERNS tag is empty or if none of the\n# patterns match the file name, INPUT_FILTER is applied.\n#\n# Note that for custom extensions or not directly supported extensions you also\n# need to set EXTENSION_MAPPING for the extension otherwise the files are not\n# properly processed by doxygen.\n\nFILTER_PATTERNS        =\n\n# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using\n# INPUT_FILTER) will also be used to filter the input files that are used for\n# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).\n# The default value is: NO.\n\nFILTER_SOURCE_FILES    = NO\n\n# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file\n# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and\n# it is also possible to disable source filtering for a specific pattern using\n# *.ext= (so without naming a filter).\n# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.\n\nFILTER_SOURCE_PATTERNS =\n\n# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that\n# is part of the input, its contents will be placed on the main page\n# (index.html). This can be useful if you have a project on for instance GitHub\n# and want to reuse the introduction page also for the doxygen output.\n\nUSE_MDFILE_AS_MAINPAGE =\n\n#---------------------------------------------------------------------------\n# Configuration options related to source browsing\n#---------------------------------------------------------------------------\n\n# If the SOURCE_BROWSER tag is set to YES then a list of source files will be\n# generated. Documented entities will be cross-referenced with these sources.\n#\n# Note: To get rid of all source code in the generated output, make sure that\n# also VERBATIM_HEADERS is set to NO.\n# The default value is: NO.\n\nSOURCE_BROWSER         = YES\n\n# Setting the INLINE_SOURCES tag to YES will include the body of functions,\n# classes and enums directly into the documentation.\n# The default value is: NO.\n\nINLINE_SOURCES         = YES\n\n# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any\n# special comment blocks from generated source code fragments. Normal C, C++ and\n# Fortran comments will always remain visible.\n# The default value is: YES.\n\nSTRIP_CODE_COMMENTS    = YES\n\n# If the REFERENCED_BY_RELATION tag is set to YES then for each documented\n# entity all documented functions referencing it will be listed.\n# The default value is: NO.\n\nREFERENCED_BY_RELATION = NO\n\n# If the REFERENCES_RELATION tag is set to YES then for each documented function\n# all documented entities called/used by that function will be listed.\n# The default value is: NO.\n\nREFERENCES_RELATION    = NO\n\n# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set\n# to YES then the hyperlinks from functions in REFERENCES_RELATION and\n# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will\n# link to the documentation.\n# The default value is: YES.\n\nREFERENCES_LINK_SOURCE = YES\n\n# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the\n# source code will show a tooltip with additional information such as prototype,\n# brief description and links to the definition and documentation. Since this\n# will make the HTML file larger and loading of large files a bit slower, you\n# can opt to disable this feature.\n# The default value is: YES.\n# This tag requires that the tag SOURCE_BROWSER is set to YES.\n\nSOURCE_TOOLTIPS        = YES\n\n# If the USE_HTAGS tag is set to YES then the references to source code will\n# point to the HTML generated by the htags(1) tool instead of doxygen built-in\n# source browser. The htags tool is part of GNU's global source tagging system\n# (see https://www.gnu.org/software/global/global.html). You will need version\n# 4.8.6 or higher.\n#\n# To use it do the following:\n# - Install the latest version of global\n# - Enable SOURCE_BROWSER and USE_HTAGS in the configuration file\n# - Make sure the INPUT points to the root of the source tree\n# - Run doxygen as normal\n#\n# Doxygen will invoke htags (and that will in turn invoke gtags), so these\n# tools must be available from the command line (i.e. in the search path).\n#\n# The result: instead of the source browser generated by doxygen, the links to\n# source code will now point to the output of htags.\n# The default value is: NO.\n# This tag requires that the tag SOURCE_BROWSER is set to YES.\n\nUSE_HTAGS              = NO\n\n# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a\n# verbatim copy of the header file for each class for which an include is\n# specified. Set to NO to disable this.\n# See also: Section \\class.\n# The default value is: YES.\n\nVERBATIM_HEADERS       = YES\n\n# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the\n# clang parser (see:\n# http://clang.llvm.org/) for more accurate parsing at the cost of reduced\n# performance. This can be particularly helpful with template rich C++ code for\n# which doxygen's built-in parser lacks the necessary type information.\n# Note: The availability of this option depends on whether or not doxygen was\n# generated with the -Duse_libclang=ON option for CMake.\n# The default value is: NO.\n\nCLANG_ASSISTED_PARSING = NO\n\n# If clang assisted parsing is enabled and the CLANG_ADD_INC_PATHS tag is set to\n# YES then doxygen will add the directory of each input to the include path.\n# The default value is: YES.\n\nCLANG_ADD_INC_PATHS    = YES\n\n# If clang assisted parsing is enabled you can provide the compiler with command\n# line options that you would normally use when invoking the compiler. Note that\n# the include paths will already be set by doxygen for the files and directories\n# specified with INPUT and INCLUDE_PATH.\n# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.\n\nCLANG_OPTIONS          =\n\n# If clang assisted parsing is enabled you can provide the clang parser with the\n# path to the directory containing a file called compile_commands.json. This\n# file is the compilation database (see:\n# http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html) containing the\n# options used when the source files were built. This is equivalent to\n# specifying the -p option to a clang tool, such as clang-check. These options\n# will then be passed to the parser. Any options specified with CLANG_OPTIONS\n# will be added as well.\n# Note: The availability of this option depends on whether or not doxygen was\n# generated with the -Duse_libclang=ON option for CMake.\n\nCLANG_DATABASE_PATH    =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the alphabetical class index\n#---------------------------------------------------------------------------\n\n# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all\n# compounds will be generated. Enable this if the project contains a lot of\n# classes, structs, unions or interfaces.\n# The default value is: YES.\n\nALPHABETICAL_INDEX     = YES\n\n# In case all classes in a project start with a common prefix, all classes will\n# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag\n# can be used to specify a prefix (or a list of prefixes) that should be ignored\n# while generating the index headers.\n# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.\n\nIGNORE_PREFIX          =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the HTML output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output\n# The default value is: YES.\n\nGENERATE_HTML          = YES\n\n# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: html.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_OUTPUT            = html\n\n# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each\n# generated HTML page (for example: .htm, .php, .asp).\n# The default value is: .html.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_FILE_EXTENSION    = .html\n\n# The HTML_HEADER tag can be used to specify a user-defined HTML header file for\n# each generated HTML page. If the tag is left blank doxygen will generate a\n# standard header.\n#\n# To get valid HTML the header file that includes any scripts and style sheets\n# that doxygen needs, which is dependent on the configuration options used (e.g.\n# the setting GENERATE_TREEVIEW). It is highly recommended to start with a\n# default header using\n# doxygen -w html new_header.html new_footer.html new_stylesheet.css\n# YourConfigFile\n# and then modify the file new_header.html. See also section \"Doxygen usage\"\n# for information on how to generate the default header that doxygen normally\n# uses.\n# Note: The header is subject to change so you typically have to regenerate the\n# default header when upgrading to a newer version of doxygen. For a description\n# of the possible markers and block names see the documentation.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_HEADER            =\n\n# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each\n# generated HTML page. If the tag is left blank doxygen will generate a standard\n# footer. See HTML_HEADER for more information on how to generate a default\n# footer and what special commands can be used inside the footer. See also\n# section \"Doxygen usage\" for information on how to generate the default footer\n# that doxygen normally uses.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_FOOTER            =\n\n# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style\n# sheet that is used by each HTML page. It can be used to fine-tune the look of\n# the HTML output. If left blank doxygen will generate a default style sheet.\n# See also section \"Doxygen usage\" for information on how to generate the style\n# sheet that doxygen normally uses.\n# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as\n# it is more robust and this tag (HTML_STYLESHEET) will in the future become\n# obsolete.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_STYLESHEET        =\n\n# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined\n# cascading style sheets that are included after the standard style sheets\n# created by doxygen. Using this option one can overrule certain style aspects.\n# This is preferred over using HTML_STYLESHEET since it does not replace the\n# standard style sheet and is therefore more robust against future updates.\n# Doxygen will copy the style sheet files to the output directory.\n# Note: The order of the extra style sheet files is of importance (e.g. the last\n# style sheet in the list overrules the setting of the previous ones in the\n# list). For an example see the documentation.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_EXTRA_STYLESHEET  =\n\n# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or\n# other source files which should be copied to the HTML output directory. Note\n# that these files will be copied to the base HTML output directory. Use the\n# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these\n# files. In the HTML_STYLESHEET file, use the file name only. Also note that the\n# files will be copied as-is; there are no commands or markers available.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_EXTRA_FILES       =\n\n# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen\n# will adjust the colors in the style sheet and background images according to\n# this color. Hue is specified as an angle on a colorwheel, see\n# https://en.wikipedia.org/wiki/Hue for more information. For instance the value\n# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300\n# purple, and 360 is red again.\n# Minimum value: 0, maximum value: 359, default value: 220.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COLORSTYLE_HUE    = 222\n\n# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors\n# in the HTML output. For a value of 0 the output will use grayscales only. A\n# value of 255 will produce the most vivid colors.\n# Minimum value: 0, maximum value: 255, default value: 100.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COLORSTYLE_SAT    = 182\n\n# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the\n# luminance component of the colors in the HTML output. Values below 100\n# gradually make the output lighter, whereas values above 100 make the output\n# darker. The value divided by 100 is the actual gamma applied, so 80 represents\n# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not\n# change the gamma.\n# Minimum value: 40, maximum value: 240, default value: 80.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COLORSTYLE_GAMMA  = 183\n\n# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML\n# page will contain the date and time when the page was generated. Setting this\n# to YES can help to show when doxygen was last run and thus if the\n# documentation is up to date.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_TIMESTAMP         = NO\n\n# If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML\n# documentation will contain a main index with vertical navigation menus that\n# are dynamically created via JavaScript. If disabled, the navigation index will\n# consists of multiple levels of tabs that are statically embedded in every HTML\n# page. Disable this option to support browsers that do not have JavaScript,\n# like the Qt help browser.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_DYNAMIC_MENUS     = YES\n\n# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML\n# documentation will contain sections that can be hidden and shown after the\n# page has loaded.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_DYNAMIC_SECTIONS  = NO\n\n# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries\n# shown in the various tree structured indices initially; the user can expand\n# and collapse entries dynamically later on. Doxygen will expand the tree to\n# such a level that at most the specified number of entries are visible (unless\n# a fully collapsed tree already exceeds this amount). So setting the number of\n# entries 1 will produce a full collapsed tree by default. 0 is a special value\n# representing an infinite number of entries and will result in a full expanded\n# tree by default.\n# Minimum value: 0, maximum value: 9999, default value: 100.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_INDEX_NUM_ENTRIES = 100\n\n# If the GENERATE_DOCSET tag is set to YES, additional index files will be\n# generated that can be used as input for Apple's Xcode 3 integrated development\n# environment (see:\n# https://developer.apple.com/xcode/), introduced with OSX 10.5 (Leopard). To\n# create a documentation set, doxygen will generate a Makefile in the HTML\n# output directory. Running make will produce the docset in that directory and\n# running make install will install the docset in\n# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at\n# startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy\n# genXcode/_index.html for more information.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_DOCSET        = NO\n\n# This tag determines the name of the docset feed. A documentation feed provides\n# an umbrella under which multiple documentation sets from a single provider\n# (such as a company or product suite) can be grouped.\n# The default value is: Doxygen generated docs.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_FEEDNAME        = \"Doxygen generated docs\"\n\n# This tag specifies a string that should uniquely identify the documentation\n# set bundle. This should be a reverse domain-name style string, e.g.\n# com.mycompany.MyDocSet. Doxygen will append .docset to the name.\n# The default value is: org.doxygen.Project.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_BUNDLE_ID       = org.doxygen.Project\n\n# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify\n# the documentation publisher. This should be a reverse domain-name style\n# string, e.g. com.mycompany.MyDocSet.documentation.\n# The default value is: org.doxygen.Publisher.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_PUBLISHER_ID    = org.doxygen.Publisher\n\n# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.\n# The default value is: Publisher.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_PUBLISHER_NAME  = Publisher\n\n# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three\n# additional HTML index files: index.hhp, index.hhc, and index.hhk. The\n# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop\n# (see:\n# https://www.microsoft.com/en-us/download/details.aspx?id=21138) on Windows.\n#\n# The HTML Help Workshop contains a compiler that can convert all HTML output\n# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML\n# files are now used as the Windows 98 help format, and will replace the old\n# Windows help format (.hlp) on all Windows platforms in the future. Compressed\n# HTML files also contain an index, a table of contents, and you can search for\n# words in the documentation. The HTML workshop also contains a viewer for\n# compressed HTML files.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_HTMLHELP      = NO\n\n# The CHM_FILE tag can be used to specify the file name of the resulting .chm\n# file. You can add a path in front of the file if the result should not be\n# written to the html output directory.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nCHM_FILE               =\n\n# The HHC_LOCATION tag can be used to specify the location (absolute path\n# including file name) of the HTML help compiler (hhc.exe). If non-empty,\n# doxygen will try to run the HTML help compiler on the generated index.hhp.\n# The file has to be specified with full path.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nHHC_LOCATION           =\n\n# The GENERATE_CHI flag controls if a separate .chi index file is generated\n# (YES) or that it should be included in the main .chm file (NO).\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nGENERATE_CHI           = NO\n\n# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc)\n# and project file content.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nCHM_INDEX_ENCODING     =\n\n# The BINARY_TOC flag controls whether a binary table of contents is generated\n# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it\n# enables the Previous and Next buttons.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nBINARY_TOC             = NO\n\n# The TOC_EXPAND flag can be set to YES to add extra items for group members to\n# the table of contents of the HTML help documentation and to the tree view.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nTOC_EXPAND             = NO\n\n# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and\n# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that\n# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help\n# (.qch) of the generated HTML documentation.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_QHP           = NO\n\n# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify\n# the file name of the resulting .qch file. The path specified is relative to\n# the HTML output folder.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQCH_FILE               =\n\n# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help\n# Project output. For more information please see Qt Help Project / Namespace\n# (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace).\n# The default value is: org.doxygen.Project.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_NAMESPACE          = org.doxygen.Project\n\n# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt\n# Help Project output. For more information please see Qt Help Project / Virtual\n# Folders (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual-folders).\n# The default value is: doc.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_VIRTUAL_FOLDER     = doc\n\n# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom\n# filter to add. For more information please see Qt Help Project / Custom\n# Filters (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_CUST_FILTER_NAME   =\n\n# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the\n# custom filter to add. For more information please see Qt Help Project / Custom\n# Filters (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_CUST_FILTER_ATTRS  =\n\n# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this\n# project's filter section matches. Qt Help Project / Filter Attributes (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes).\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_SECT_FILTER_ATTRS  =\n\n# The QHG_LOCATION tag can be used to specify the location (absolute path\n# including file name) of Qt's qhelpgenerator. If non-empty doxygen will try to\n# run qhelpgenerator on the generated .qhp file.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHG_LOCATION           =\n\n# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be\n# generated, together with the HTML files, they form an Eclipse help plugin. To\n# install this plugin and make it available under the help contents menu in\n# Eclipse, the contents of the directory containing the HTML and XML files needs\n# to be copied into the plugins directory of eclipse. The name of the directory\n# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.\n# After copying Eclipse needs to be restarted before the help appears.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_ECLIPSEHELP   = NO\n\n# A unique identifier for the Eclipse help plugin. When installing the plugin\n# the directory name containing the HTML and XML files should also have this\n# name. Each documentation set should have its own identifier.\n# The default value is: org.doxygen.Project.\n# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.\n\nECLIPSE_DOC_ID         = org.doxygen.Project\n\n# If you want full control over the layout of the generated HTML pages it might\n# be necessary to disable the index and replace it with your own. The\n# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top\n# of each HTML page. A value of NO enables the index and the value YES disables\n# it. Since the tabs in the index contain the same information as the navigation\n# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nDISABLE_INDEX          = NO\n\n# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index\n# structure should be generated to display hierarchical information. If the tag\n# value is set to YES, a side panel will be generated containing a tree-like\n# index structure (just like the one that is generated for HTML Help). For this\n# to work a browser that supports JavaScript, DHTML, CSS and frames is required\n# (i.e. any modern browser). Windows users are probably better off using the\n# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can\n# further fine-tune the look of the index. As an example, the default style\n# sheet generated by doxygen has an example that shows how to put an image at\n# the root of the tree instead of the PROJECT_NAME. Since the tree basically has\n# the same information as the tab index, you could consider setting\n# DISABLE_INDEX to YES when enabling this option.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_TREEVIEW      = YES\n\n# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that\n# doxygen will group on one line in the generated HTML documentation.\n#\n# Note that a value of 0 will completely suppress the enum values from appearing\n# in the overview section.\n# Minimum value: 0, maximum value: 20, default value: 4.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nENUM_VALUES_PER_LINE   = 4\n\n# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used\n# to set the initial width (in pixels) of the frame in which the tree is shown.\n# Minimum value: 0, maximum value: 1500, default value: 250.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nTREEVIEW_WIDTH         = 250\n\n# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to\n# external symbols imported via tag files in a separate window.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nEXT_LINKS_IN_WINDOW    = NO\n\n# If the HTML_FORMULA_FORMAT option is set to svg, doxygen will use the pdf2svg\n# tool (see https://github.com/dawbarton/pdf2svg) or inkscape (see\n# https://inkscape.org) to generate formulas as SVG images instead of PNGs for\n# the HTML output. These images will generally look nicer at scaled resolutions.\n# Possible values are: png (the default) and svg (looks nicer but requires the\n# pdf2svg or inkscape tool).\n# The default value is: png.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_FORMULA_FORMAT    = png\n\n# Use this tag to change the font size of LaTeX formulas included as images in\n# the HTML documentation. When you change the font size after a successful\n# doxygen run you need to manually remove any form_*.png images from the HTML\n# output directory to force them to be regenerated.\n# Minimum value: 8, maximum value: 50, default value: 10.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nFORMULA_FONTSIZE       = 10\n\n# Use the FORMULA_TRANSPARENT tag to determine whether or not the images\n# generated for formulas are transparent PNGs. Transparent PNGs are not\n# supported properly for IE 6.0, but are supported on all modern browsers.\n#\n# Note that when changing this option you need to delete any form_*.png files in\n# the HTML output directory before the changes have effect.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nFORMULA_TRANSPARENT    = YES\n\n# The FORMULA_MACROFILE can contain LaTeX \\newcommand and \\renewcommand commands\n# to create new LaTeX commands to be used in formulas as building blocks. See\n# the section \"Including formulas\" for details.\n\nFORMULA_MACROFILE      =\n\n# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see\n# https://www.mathjax.org) which uses client side JavaScript for the rendering\n# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX\n# installed or if you want to formulas look prettier in the HTML output. When\n# enabled you may also need to install MathJax separately and configure the path\n# to it using the MATHJAX_RELPATH option.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nUSE_MATHJAX            = NO\n\n# When MathJax is enabled you can set the default output format to be used for\n# the MathJax output. See the MathJax site (see:\n# http://docs.mathjax.org/en/v2.7-latest/output.html) for more details.\n# Possible values are: HTML-CSS (which is slower, but has the best\n# compatibility), NativeMML (i.e. MathML) and SVG.\n# The default value is: HTML-CSS.\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_FORMAT         = HTML-CSS\n\n# When MathJax is enabled you need to specify the location relative to the HTML\n# output directory using the MATHJAX_RELPATH option. The destination directory\n# should contain the MathJax.js script. For instance, if the mathjax directory\n# is located at the same level as the HTML output directory, then\n# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax\n# Content Delivery Network so you can quickly see the result without installing\n# MathJax. However, it is strongly recommended to install a local copy of\n# MathJax from https://www.mathjax.org before deployment.\n# The default value is: https://cdn.jsdelivr.net/npm/mathjax@2.\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_RELPATH        = https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/\n\n# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax\n# extension names that should be enabled during MathJax rendering. For example\n# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_EXTENSIONS     =\n\n# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces\n# of code that will be used on startup of the MathJax code. See the MathJax site\n# (see:\n# http://docs.mathjax.org/en/v2.7-latest/output.html) for more details. For an\n# example see the documentation.\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_CODEFILE       =\n\n# When the SEARCHENGINE tag is enabled doxygen will generate a search box for\n# the HTML output. The underlying search engine uses javascript and DHTML and\n# should work on any modern browser. Note that when using HTML help\n# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)\n# there is already a search function so this one should typically be disabled.\n# For large projects the javascript based search engine can be slow, then\n# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to\n# search using the keyboard; to jump to the search box use <access key> + S\n# (what the <access key> is depends on the OS and browser, but it is typically\n# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down\n# key> to jump into the search results window, the results can be navigated\n# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel\n# the search. The filter options can be selected when the cursor is inside the\n# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>\n# to select a filter and <Enter> or <escape> to activate or cancel the filter\n# option.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nSEARCHENGINE           = YES\n\n# When the SERVER_BASED_SEARCH tag is enabled the search engine will be\n# implemented using a web server instead of a web client using JavaScript. There\n# are two flavors of web server based searching depending on the EXTERNAL_SEARCH\n# setting. When disabled, doxygen will generate a PHP script for searching and\n# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing\n# and searching needs to be provided by external tools. See the section\n# \"External Indexing and Searching\" for details.\n# The default value is: NO.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nSERVER_BASED_SEARCH    = NO\n\n# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP\n# script for searching. Instead the search results are written to an XML file\n# which needs to be processed by an external indexer. Doxygen will invoke an\n# external search engine pointed to by the SEARCHENGINE_URL option to obtain the\n# search results.\n#\n# Doxygen ships with an example indexer (doxyindexer) and search engine\n# (doxysearch.cgi) which are based on the open source search engine library\n# Xapian (see:\n# https://xapian.org/).\n#\n# See the section \"External Indexing and Searching\" for details.\n# The default value is: NO.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nEXTERNAL_SEARCH        = NO\n\n# The SEARCHENGINE_URL should point to a search engine hosted by a web server\n# which will return the search results when EXTERNAL_SEARCH is enabled.\n#\n# Doxygen ships with an example indexer (doxyindexer) and search engine\n# (doxysearch.cgi) which are based on the open source search engine library\n# Xapian (see:\n# https://xapian.org/). See the section \"External Indexing and Searching\" for\n# details.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nSEARCHENGINE_URL       =\n\n# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed\n# search data is written to a file for indexing by an external tool. With the\n# SEARCHDATA_FILE tag the name of this file can be specified.\n# The default file is: searchdata.xml.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nSEARCHDATA_FILE        = searchdata.xml\n\n# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the\n# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is\n# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple\n# projects and redirect the results back to the right project.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nEXTERNAL_SEARCH_ID     =\n\n# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen\n# projects other than the one defined by this configuration file, but that are\n# all added to the same external search index. Each project needs to have a\n# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of\n# to a relative location where the documentation can be found. The format is:\n# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nEXTRA_SEARCH_MAPPINGS  =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the LaTeX output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output.\n# The default value is: YES.\n\nGENERATE_LATEX         = NO\n\n# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: latex.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_OUTPUT           = latex\n\n# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be\n# invoked.\n#\n# Note that when not enabling USE_PDFLATEX the default is latex when enabling\n# USE_PDFLATEX the default is pdflatex and when in the later case latex is\n# chosen this is overwritten by pdflatex. For specific output languages the\n# default can have been set differently, this depends on the implementation of\n# the output language.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_CMD_NAME         =\n\n# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate\n# index for LaTeX.\n# Note: This tag is used in the Makefile / make.bat.\n# See also: LATEX_MAKEINDEX_CMD for the part in the generated output file\n# (.tex).\n# The default file is: makeindex.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nMAKEINDEX_CMD_NAME     = makeindex\n\n# The LATEX_MAKEINDEX_CMD tag can be used to specify the command name to\n# generate index for LaTeX. In case there is no backslash (\\) as first character\n# it will be automatically added in the LaTeX code.\n# Note: This tag is used in the generated output file (.tex).\n# See also: MAKEINDEX_CMD_NAME for the part in the Makefile / make.bat.\n# The default value is: makeindex.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_MAKEINDEX_CMD    = makeindex\n\n# If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX\n# documents. This may be useful for small projects and may help to save some\n# trees in general.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nCOMPACT_LATEX          = NO\n\n# The PAPER_TYPE tag can be used to set the paper type that is used by the\n# printer.\n# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x\n# 14 inches) and executive (7.25 x 10.5 inches).\n# The default value is: a4.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nPAPER_TYPE             = a4\n\n# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names\n# that should be included in the LaTeX output. The package can be specified just\n# by its name or with the correct syntax as to be used with the LaTeX\n# \\usepackage command. To get the times font for instance you can specify :\n# EXTRA_PACKAGES=times or EXTRA_PACKAGES={times}\n# To use the option intlimits with the amsmath package you can specify:\n# EXTRA_PACKAGES=[intlimits]{amsmath}\n# If left blank no extra packages will be included.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nEXTRA_PACKAGES         =\n\n# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the\n# generated LaTeX document. The header should contain everything until the first\n# chapter. If it is left blank doxygen will generate a standard header. See\n# section \"Doxygen usage\" for information on how to let doxygen write the\n# default header to a separate file.\n#\n# Note: Only use a user-defined header if you know what you are doing! The\n# following commands have a special meaning inside the header: $title,\n# $datetime, $date, $doxygenversion, $projectname, $projectnumber,\n# $projectbrief, $projectlogo. Doxygen will replace $title with the empty\n# string, for the replacement values of the other commands the user is referred\n# to HTML_HEADER.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_HEADER           =\n\n# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the\n# generated LaTeX document. The footer should contain everything after the last\n# chapter. If it is left blank doxygen will generate a standard footer. See\n# LATEX_HEADER for more information on how to generate a default footer and what\n# special commands can be used inside the footer.\n#\n# Note: Only use a user-defined footer if you know what you are doing!\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_FOOTER           =\n\n# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined\n# LaTeX style sheets that are included after the standard style sheets created\n# by doxygen. Using this option one can overrule certain style aspects. Doxygen\n# will copy the style sheet files to the output directory.\n# Note: The order of the extra style sheet files is of importance (e.g. the last\n# style sheet in the list overrules the setting of the previous ones in the\n# list).\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_EXTRA_STYLESHEET =\n\n# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or\n# other source files which should be copied to the LATEX_OUTPUT output\n# directory. Note that the files will be copied as-is; there are no commands or\n# markers available.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_EXTRA_FILES      =\n\n# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is\n# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will\n# contain links (just like the HTML output) instead of page references. This\n# makes the output suitable for online browsing using a PDF viewer.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nPDF_HYPERLINKS         = YES\n\n# If the USE_PDFLATEX tag is set to YES, doxygen will use the engine as\n# specified with LATEX_CMD_NAME to generate the PDF file directly from the LaTeX\n# files. Set this option to YES, to get a higher quality PDF documentation.\n#\n# See also section LATEX_CMD_NAME for selecting the engine.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nUSE_PDFLATEX           = YES\n\n# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode\n# command to the generated LaTeX files. This will instruct LaTeX to keep running\n# if errors occur, instead of asking the user for help. This option is also used\n# when generating formulas in HTML.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_BATCHMODE        = NO\n\n# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the\n# index chapters (such as File Index, Compound Index, etc.) in the output.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_HIDE_INDICES     = NO\n\n# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source\n# code with syntax highlighting in the LaTeX output.\n#\n# Note that which sources are shown also depends on other settings such as\n# SOURCE_BROWSER.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_SOURCE_CODE      = NO\n\n# The LATEX_BIB_STYLE tag can be used to specify the style to use for the\n# bibliography, e.g. plainnat, or ieeetr. See\n# https://en.wikipedia.org/wiki/BibTeX and \\cite for more info.\n# The default value is: plain.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_BIB_STYLE        = plain\n\n# If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated\n# page will contain the date and time when the page was generated. Setting this\n# to NO can help when comparing the output of multiple runs.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_TIMESTAMP        = NO\n\n# The LATEX_EMOJI_DIRECTORY tag is used to specify the (relative or absolute)\n# path from which the emoji images will be read. If a relative path is entered,\n# it will be relative to the LATEX_OUTPUT directory. If left blank the\n# LATEX_OUTPUT directory will be used.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_EMOJI_DIRECTORY  =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the RTF output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The\n# RTF output is optimized for Word 97 and may not look too pretty with other RTF\n# readers/editors.\n# The default value is: NO.\n\nGENERATE_RTF           = NO\n\n# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: rtf.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_OUTPUT             = rtf\n\n# If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF\n# documents. This may be useful for small projects and may help to save some\n# trees in general.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nCOMPACT_RTF            = NO\n\n# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will\n# contain hyperlink fields. The RTF file will contain links (just like the HTML\n# output) instead of page references. This makes the output suitable for online\n# browsing using Word or some other Word compatible readers that support those\n# fields.\n#\n# Note: WordPad (write) and others do not support links.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_HYPERLINKS         = NO\n\n# Load stylesheet definitions from file. Syntax is similar to doxygen's\n# configuration file, i.e. a series of assignments. You only have to provide\n# replacements, missing definitions are set to their default value.\n#\n# See also section \"Doxygen usage\" for information on how to generate the\n# default style sheet that doxygen normally uses.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_STYLESHEET_FILE    =\n\n# Set optional variables used in the generation of an RTF document. Syntax is\n# similar to doxygen's configuration file. A template extensions file can be\n# generated using doxygen -e rtf extensionFile.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_EXTENSIONS_FILE    =\n\n# If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code\n# with syntax highlighting in the RTF output.\n#\n# Note that which sources are shown also depends on other settings such as\n# SOURCE_BROWSER.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_SOURCE_CODE        = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the man page output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for\n# classes and files.\n# The default value is: NO.\n\nGENERATE_MAN           = NO\n\n# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it. A directory man3 will be created inside the directory specified by\n# MAN_OUTPUT.\n# The default directory is: man.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_OUTPUT             = man\n\n# The MAN_EXTENSION tag determines the extension that is added to the generated\n# man pages. In case the manual section does not start with a number, the number\n# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is\n# optional.\n# The default value is: .3.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_EXTENSION          = .3\n\n# The MAN_SUBDIR tag determines the name of the directory created within\n# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by\n# MAN_EXTENSION with the initial . removed.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_SUBDIR             =\n\n# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it\n# will generate one additional man file for each entity documented in the real\n# man page(s). These additional files only source the real man page, but without\n# them the man command would be unable to find the correct page.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_LINKS              = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the XML output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that\n# captures the structure of the code including all documentation.\n# The default value is: NO.\n\nGENERATE_XML           = NO\n\n# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: xml.\n# This tag requires that the tag GENERATE_XML is set to YES.\n\nXML_OUTPUT             = xml\n\n# If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program\n# listings (including syntax highlighting and cross-referencing information) to\n# the XML output. Note that enabling this will significantly increase the size\n# of the XML output.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_XML is set to YES.\n\nXML_PROGRAMLISTING     = YES\n\n# If the XML_NS_MEMB_FILE_SCOPE tag is set to YES, doxygen will include\n# namespace members in file scope as well, matching the HTML output.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_XML is set to YES.\n\nXML_NS_MEMB_FILE_SCOPE = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the DOCBOOK output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files\n# that can be used to generate PDF.\n# The default value is: NO.\n\nGENERATE_DOCBOOK       = NO\n\n# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.\n# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in\n# front of it.\n# The default directory is: docbook.\n# This tag requires that the tag GENERATE_DOCBOOK is set to YES.\n\nDOCBOOK_OUTPUT         = docbook\n\n# If the DOCBOOK_PROGRAMLISTING tag is set to YES, doxygen will include the\n# program listings (including syntax highlighting and cross-referencing\n# information) to the DOCBOOK output. Note that enabling this will significantly\n# increase the size of the DOCBOOK output.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_DOCBOOK is set to YES.\n\nDOCBOOK_PROGRAMLISTING = NO\n\n#---------------------------------------------------------------------------\n# Configuration options for the AutoGen Definitions output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an\n# AutoGen Definitions (see http://autogen.sourceforge.net/) file that captures\n# the structure of the code including all documentation. Note that this feature\n# is still experimental and incomplete at the moment.\n# The default value is: NO.\n\nGENERATE_AUTOGEN_DEF   = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the Perl module output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module\n# file that captures the structure of the code including all documentation.\n#\n# Note that this feature is still experimental and incomplete at the moment.\n# The default value is: NO.\n\nGENERATE_PERLMOD       = NO\n\n# If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary\n# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI\n# output from the Perl module output.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_PERLMOD is set to YES.\n\nPERLMOD_LATEX          = NO\n\n# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely\n# formatted so it can be parsed by a human reader. This is useful if you want to\n# understand what is going on. On the other hand, if this tag is set to NO, the\n# size of the Perl module output will be much smaller and Perl will parse it\n# just the same.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_PERLMOD is set to YES.\n\nPERLMOD_PRETTY         = YES\n\n# The names of the make variables in the generated doxyrules.make file are\n# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful\n# so different doxyrules.make files included by the same Makefile don't\n# overwrite each other's variables.\n# This tag requires that the tag GENERATE_PERLMOD is set to YES.\n\nPERLMOD_MAKEVAR_PREFIX =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the preprocessor\n#---------------------------------------------------------------------------\n\n# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all\n# C-preprocessor directives found in the sources and include files.\n# The default value is: YES.\n\nENABLE_PREPROCESSING   = YES\n\n# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names\n# in the source code. If set to NO, only conditional compilation will be\n# performed. Macro expansion can be done in a controlled way by setting\n# EXPAND_ONLY_PREDEF to YES.\n# The default value is: NO.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nMACRO_EXPANSION        = NO\n\n# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then\n# the macro expansion is limited to the macros specified with the PREDEFINED and\n# EXPAND_AS_DEFINED tags.\n# The default value is: NO.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nEXPAND_ONLY_PREDEF     = NO\n\n# If the SEARCH_INCLUDES tag is set to YES, the include files in the\n# INCLUDE_PATH will be searched if a #include is found.\n# The default value is: YES.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nSEARCH_INCLUDES        = YES\n\n# The INCLUDE_PATH tag can be used to specify one or more directories that\n# contain include files that are not input files but should be processed by the\n# preprocessor.\n# This tag requires that the tag SEARCH_INCLUDES is set to YES.\n\nINCLUDE_PATH           =\n\n# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard\n# patterns (like *.h and *.hpp) to filter out the header-files in the\n# directories. If left blank, the patterns specified with FILE_PATTERNS will be\n# used.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nINCLUDE_FILE_PATTERNS  =\n\n# The PREDEFINED tag can be used to specify one or more macro names that are\n# defined before the preprocessor is started (similar to the -D option of e.g.\n# gcc). The argument of the tag is a list of macros of the form: name or\n# name=definition (no spaces). If the definition and the \"=\" are omitted, \"=1\"\n# is assumed. To prevent a macro definition from being undefined via #undef or\n# recursively expanded use the := operator instead of the = operator.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nPREDEFINED             =\n\n# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this\n# tag can be used to specify a list of macro names that should be expanded. The\n# macro definition that is found in the sources will be used. Use the PREDEFINED\n# tag if you want to use a different macro definition that overrules the\n# definition found in the source code.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nEXPAND_AS_DEFINED      =\n\n# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will\n# remove all references to function-like macros that are alone on a line, have\n# an all uppercase name, and do not end with a semicolon. Such function macros\n# are typically used for boiler-plate code, and will confuse the parser if not\n# removed.\n# The default value is: YES.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nSKIP_FUNCTION_MACROS   = YES\n\n#---------------------------------------------------------------------------\n# Configuration options related to external references\n#---------------------------------------------------------------------------\n\n# The TAGFILES tag can be used to specify one or more tag files. For each tag\n# file the location of the external documentation should be added. The format of\n# a tag file without this location is as follows:\n# TAGFILES = file1 file2 ...\n# Adding location for the tag files is done as follows:\n# TAGFILES = file1=loc1 \"file2 = loc2\" ...\n# where loc1 and loc2 can be relative or absolute paths or URLs. See the\n# section \"Linking to external documentation\" for more information about the use\n# of tag files.\n# Note: Each tag file must have a unique name (where the name does NOT include\n# the path). If a tag file is not located in the directory in which doxygen is\n# run, you must also specify the path to the tagfile here.\n\nTAGFILES               =\n\n# When a file name is specified after GENERATE_TAGFILE, doxygen will create a\n# tag file that is based on the input files it reads. See section \"Linking to\n# external documentation\" for more information about the usage of tag files.\n\nGENERATE_TAGFILE       =\n\n# If the ALLEXTERNALS tag is set to YES, all external class will be listed in\n# the class index. If set to NO, only the inherited external classes will be\n# listed.\n# The default value is: NO.\n\nALLEXTERNALS           = NO\n\n# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed\n# in the modules index. If set to NO, only the current project's groups will be\n# listed.\n# The default value is: YES.\n\nEXTERNAL_GROUPS        = YES\n\n# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in\n# the related pages index. If set to NO, only the current project's pages will\n# be listed.\n# The default value is: YES.\n\nEXTERNAL_PAGES         = YES\n\n#---------------------------------------------------------------------------\n# Configuration options related to the dot tool\n#---------------------------------------------------------------------------\n\n# If the CLASS_DIAGRAMS tag is set to YES, doxygen will generate a class diagram\n# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to\n# NO turns the diagrams off. Note that this option also works with HAVE_DOT\n# disabled, but it is recommended to install and use dot, since it yields more\n# powerful graphs.\n# The default value is: YES.\n\nCLASS_DIAGRAMS         = YES\n\n# You can include diagrams made with dia in doxygen documentation. Doxygen will\n# then run dia to produce the diagram and insert it in the documentation. The\n# DIA_PATH tag allows you to specify the directory where the dia binary resides.\n# If left empty dia is assumed to be found in the default search path.\n\nDIA_PATH               =\n\n# If set to YES the inheritance and collaboration graphs will hide inheritance\n# and usage relations if the target is undocumented or is not a class.\n# The default value is: YES.\n\nHIDE_UNDOC_RELATIONS   = YES\n\n# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is\n# available from the path. This tool is part of Graphviz (see:\n# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent\n# Bell Labs. The other options in this section have no effect if this option is\n# set to NO\n# The default value is: YES.\n\nHAVE_DOT               = YES\n\n# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed\n# to run in parallel. When set to 0 doxygen will base this on the number of\n# processors available in the system. You can set it explicitly to a value\n# larger than 0 to get control over the balance between CPU load and processing\n# speed.\n# Minimum value: 0, maximum value: 32, default value: 0.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_NUM_THREADS        = 0\n\n# When you want a differently looking font in the dot files that doxygen\n# generates you can specify the font name using DOT_FONTNAME. You need to make\n# sure dot is able to find the font, which can be done by putting it in a\n# standard location or by setting the DOTFONTPATH environment variable or by\n# setting DOT_FONTPATH to the directory containing the font.\n# The default value is: Helvetica.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_FONTNAME           = Helvetica\n\n# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of\n# dot graphs.\n# Minimum value: 4, maximum value: 24, default value: 10.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_FONTSIZE           = 10\n\n# By default doxygen will tell dot to use the default font as specified with\n# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set\n# the path where dot can find it using this tag.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_FONTPATH           =\n\n# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for\n# each documented class showing the direct and indirect inheritance relations.\n# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCLASS_GRAPH            = YES\n\n# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a\n# graph for each documented class showing the direct and indirect implementation\n# dependencies (inheritance, containment, and class references variables) of the\n# class with other documented classes.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCOLLABORATION_GRAPH    = YES\n\n# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for\n# groups, showing the direct groups dependencies.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nGROUP_GRAPHS           = YES\n\n# If the UML_LOOK tag is set to YES, doxygen will generate inheritance and\n# collaboration diagrams in a style similar to the OMG's Unified Modeling\n# Language.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nUML_LOOK               = NO\n\n# If the UML_LOOK tag is enabled, the fields and methods are shown inside the\n# class node. If there are many fields or methods and many nodes the graph may\n# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the\n# number of items for each type to make the size more manageable. Set this to 0\n# for no limit. Note that the threshold may be exceeded by 50% before the limit\n# is enforced. So when you set the threshold to 10, up to 15 fields may appear,\n# but if the number exceeds 15, the total amount of fields shown is limited to\n# 10.\n# Minimum value: 0, maximum value: 100, default value: 10.\n# This tag requires that the tag UML_LOOK is set to YES.\n\nUML_LIMIT_NUM_FIELDS   = 10\n\n# If the DOT_UML_DETAILS tag is set to NO, doxygen will show attributes and\n# methods without types and arguments in the UML graphs. If the DOT_UML_DETAILS\n# tag is set to YES, doxygen will add type and arguments for attributes and\n# methods in the UML graphs. If the DOT_UML_DETAILS tag is set to NONE, doxygen\n# will not generate fields with class member information in the UML graphs. The\n# class diagrams will look similar to the default class diagrams but using UML\n# notation for the relationships.\n# Possible values are: NO, YES and NONE.\n# The default value is: NO.\n# This tag requires that the tag UML_LOOK is set to YES.\n\nDOT_UML_DETAILS        = NO\n\n# The DOT_WRAP_THRESHOLD tag can be used to set the maximum number of characters\n# to display on a single line. If the actual line length exceeds this threshold\n# significantly it will wrapped across multiple lines. Some heuristics are apply\n# to avoid ugly line breaks.\n# Minimum value: 0, maximum value: 1000, default value: 17.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_WRAP_THRESHOLD     = 17\n\n# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and\n# collaboration graphs will show the relations between templates and their\n# instances.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nTEMPLATE_RELATIONS     = NO\n\n# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to\n# YES then doxygen will generate a graph for each documented file showing the\n# direct and indirect include dependencies of the file with other documented\n# files.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nINCLUDE_GRAPH          = YES\n\n# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are\n# set to YES then doxygen will generate a graph for each documented file showing\n# the direct and indirect include dependencies of the file with other documented\n# files.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nINCLUDED_BY_GRAPH      = YES\n\n# If the CALL_GRAPH tag is set to YES then doxygen will generate a call\n# dependency graph for every global function or class method.\n#\n# Note that enabling this option will significantly increase the time of a run.\n# So in most cases it will be better to enable call graphs for selected\n# functions only using the \\callgraph command. Disabling a call graph can be\n# accomplished by means of the command \\hidecallgraph.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCALL_GRAPH             = YES\n\n# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller\n# dependency graph for every global function or class method.\n#\n# Note that enabling this option will significantly increase the time of a run.\n# So in most cases it will be better to enable caller graphs for selected\n# functions only using the \\callergraph command. Disabling a caller graph can be\n# accomplished by means of the command \\hidecallergraph.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCALLER_GRAPH           = YES\n\n# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical\n# hierarchy of all classes instead of a textual one.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nGRAPHICAL_HIERARCHY    = YES\n\n# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the\n# dependencies a directory has on other directories in a graphical way. The\n# dependency relations are determined by the #include relations between the\n# files in the directories.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDIRECTORY_GRAPH        = YES\n\n# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images\n# generated by dot. For an explanation of the image formats see the section\n# output formats in the documentation of the dot tool (Graphviz (see:\n# http://www.graphviz.org/)).\n# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order\n# to make the SVG files visible in IE 9+ (other browsers do not have this\n# requirement).\n# Possible values are: png, png:cairo, png:cairo:cairo, png:cairo:gd, png:gd,\n# png:gd:gd, jpg, jpg:cairo, jpg:cairo:gd, jpg:gd, jpg:gd:gd, gif, gif:cairo,\n# gif:cairo:gd, gif:gd, gif:gd:gd, svg, png:gd, png:gd:gd, png:cairo,\n# png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and\n# png:gdiplus:gdiplus.\n# The default value is: png.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_IMAGE_FORMAT       = png\n\n# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to\n# enable generation of interactive SVG images that allow zooming and panning.\n#\n# Note that this requires a modern browser other than Internet Explorer. Tested\n# and working are Firefox, Chrome, Safari, and Opera.\n# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make\n# the SVG files visible. Older versions of IE do not have SVG support.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nINTERACTIVE_SVG        = NO\n\n# The DOT_PATH tag can be used to specify the path where the dot tool can be\n# found. If left blank, it is assumed the dot tool can be found in the path.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_PATH               =\n\n# The DOTFILE_DIRS tag can be used to specify one or more directories that\n# contain dot files that are included in the documentation (see the \\dotfile\n# command).\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOTFILE_DIRS           =\n\n# The MSCFILE_DIRS tag can be used to specify one or more directories that\n# contain msc files that are included in the documentation (see the \\mscfile\n# command).\n\nMSCFILE_DIRS           =\n\n# The DIAFILE_DIRS tag can be used to specify one or more directories that\n# contain dia files that are included in the documentation (see the \\diafile\n# command).\n\nDIAFILE_DIRS           =\n\n# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the\n# path where java can find the plantuml.jar file. If left blank, it is assumed\n# PlantUML is not used or called during a preprocessing step. Doxygen will\n# generate a warning when it encounters a \\startuml command in this case and\n# will not generate output for the diagram.\n\nPLANTUML_JAR_PATH      =\n\n# When using plantuml, the PLANTUML_CFG_FILE tag can be used to specify a\n# configuration file for plantuml.\n\nPLANTUML_CFG_FILE      =\n\n# When using plantuml, the specified paths are searched for files specified by\n# the !include statement in a plantuml block.\n\nPLANTUML_INCLUDE_PATH  =\n\n# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes\n# that will be shown in the graph. If the number of nodes in a graph becomes\n# larger than this value, doxygen will truncate the graph, which is visualized\n# by representing a node as a red box. Note that doxygen if the number of direct\n# children of the root node in a graph is already larger than\n# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that\n# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.\n# Minimum value: 0, maximum value: 10000, default value: 50.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_GRAPH_MAX_NODES    = 50\n\n# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs\n# generated by dot. A depth value of 3 means that only nodes reachable from the\n# root by following a path via at most 3 edges will be shown. Nodes that lay\n# further from the root node will be omitted. Note that setting this option to 1\n# or 2 may greatly reduce the computation time needed for large code bases. Also\n# note that the size of a graph can be further restricted by\n# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.\n# Minimum value: 0, maximum value: 1000, default value: 0.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nMAX_DOT_GRAPH_DEPTH    = 0\n\n# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent\n# background. This is disabled by default, because dot on Windows does not seem\n# to support this out of the box.\n#\n# Warning: Depending on the platform used, enabling this option may lead to\n# badly anti-aliased labels on the edges of a graph (i.e. they become hard to\n# read).\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_TRANSPARENT        = NO\n\n# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output\n# files in one run (i.e. multiple -o and -T options on the command line). This\n# makes dot run faster, but since only newer versions of dot (>1.8.10) support\n# this, this feature is disabled by default.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_MULTI_TARGETS      = NO\n\n# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page\n# explaining the meaning of the various boxes and arrows in the dot generated\n# graphs.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nGENERATE_LEGEND        = YES\n\n# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate\n# files that are used to generate the various graphs.\n#\n# Note: This setting is not only used for dot files but also for msc and\n# plantuml temporary files.\n# The default value is: YES.\n\nDOT_CLEANUP            = YES\n"
  },
  {
    "path": "LICENSE.md",
    "content": "### GNU GENERAL PUBLIC LICENSE\n\nVersion 3, 29 June 2007\n\nCopyright (C) 2007 Free Software Foundation, Inc.\n<http://fsf.org/>\n\nEveryone is permitted to copy and distribute verbatim copies of this\nlicense document, but changing it is not allowed.\n\n### Preamble\n\nThe GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\nThe licenses for most software and other practical works are designed\nto take away your freedom to share and change the works. By contrast,\nthe GNU General Public License is intended to guarantee your freedom\nto share and change all versions of a program--to make sure it remains\nfree software for all its users. We, the Free Software Foundation, use\nthe GNU General Public License for most of our software; it applies\nalso to any other work released this way by its authors. You can apply\nit to your programs, too.\n\nWhen we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\nTo protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights. Therefore, you\nhave certain responsibilities if you distribute copies of the\nsoftware, or if you modify it: responsibilities to respect the freedom\nof others.\n\nFor example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received. You must make sure that they, too, receive\nor can get the source code. And you must show them these terms so they\nknow their rights.\n\nDevelopers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\nFor the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software. For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\nSome devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the\nmanufacturer can do so. This is fundamentally incompatible with the\naim of protecting users' freedom to change the software. The\nsystematic pattern of such abuse occurs in the area of products for\nindividuals to use, which is precisely where it is most unacceptable.\nTherefore, we have designed this version of the GPL to prohibit the\npractice for those products. If such problems arise substantially in\nother domains, we stand ready to extend this provision to those\ndomains in future versions of the GPL, as needed to protect the\nfreedom of users.\n\nFinally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish\nto avoid the special danger that patents applied to a free program\ncould make it effectively proprietary. To prevent this, the GPL\nassures that patents cannot be used to render the program non-free.\n\nThe precise terms and conditions for copying, distribution and\nmodification follow.\n\n### TERMS AND CONDITIONS\n\n#### 0. Definitions.\n\n\"This License\" refers to version 3 of the GNU General Public License.\n\n\"Copyright\" also means copyright-like laws that apply to other kinds\nof works, such as semiconductor masks.\n\n\"The Program\" refers to any copyrightable work licensed under this\nLicense. Each licensee is addressed as \"you\". \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\nTo \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of\nan exact copy. The resulting work is called a \"modified version\" of\nthe earlier work or a work \"based on\" the earlier work.\n\nA \"covered work\" means either the unmodified Program or a work based\non the Program.\n\nTo \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy. Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\nTo \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies. Mere interaction with a user\nthrough a computer network, with no transfer of a copy, is not\nconveying.\n\nAn interactive user interface displays \"Appropriate Legal Notices\" to\nthe extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License. If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n#### 1. Source Code.\n\nThe \"source code\" for a work means the preferred form of the work for\nmaking modifications to it. \"Object code\" means any non-source form of\na work.\n\nA \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\nThe \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form. A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\nThe \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities. However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work. For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\nThe Corresponding Source need not include anything that users can\nregenerate automatically from other parts of the Corresponding Source.\n\nThe Corresponding Source for a work in source code form is that same\nwork.\n\n#### 2. Basic Permissions.\n\nAll rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met. This License explicitly affirms your unlimited\npermission to run the unmodified Program. The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work. This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\nYou may make, run and propagate covered works that you do not convey,\nwithout conditions so long as your license otherwise remains in force.\nYou may convey covered works to others for the sole purpose of having\nthem make modifications exclusively for you, or provide you with\nfacilities for running those works, provided that you comply with the\nterms of this License in conveying all material for which you do not\ncontrol copyright. Those thus making or running the covered works for\nyou must do so exclusively on your behalf, under your direction and\ncontrol, on terms that prohibit them from making any copies of your\ncopyrighted material outside their relationship with you.\n\nConveying under any other circumstances is permitted solely under the\nconditions stated below. Sublicensing is not allowed; section 10 makes\nit unnecessary.\n\n#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\nNo covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\nWhen you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such\ncircumvention is effected by exercising rights under this License with\nrespect to the covered work, and you disclaim any intention to limit\noperation or modification of the work as a means of enforcing, against\nthe work's users, your or third parties' legal rights to forbid\ncircumvention of technological measures.\n\n#### 4. Conveying Verbatim Copies.\n\nYou may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\nYou may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n#### 5. Conveying Modified Source Versions.\n\nYou may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these\nconditions:\n\n-   a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n-   b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under\n    section 7. This requirement modifies the requirement in section 4\n    to \"keep intact all notices\".\n-   c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy. This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged. This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n-   d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\nA compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit. Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n#### 6. Conveying Non-Source Forms.\n\nYou may convey a covered work in object code form under the terms of\nsections 4 and 5, provided that you also convey the machine-readable\nCorresponding Source under the terms of this License, in one of these\nways:\n\n-   a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n-   b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the Corresponding\n    Source from a network server at no charge.\n-   c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source. This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n-   d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge. You need not require recipients to copy the\n    Corresponding Source along with the object code. If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source. Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n-   e) Convey the object code using peer-to-peer transmission,\n    provided you inform other peers where the object code and\n    Corresponding Source of the work are being offered to the general\n    public at no charge under subsection 6d.\n\nA separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\nA \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal,\nfamily, or household purposes, or (2) anything designed or sold for\nincorporation into a dwelling. In determining whether a product is a\nconsumer product, doubtful cases shall be resolved in favor of\ncoverage. For a particular product received by a particular user,\n\"normally used\" refers to a typical or common use of that class of\nproduct, regardless of the status of the particular user or of the way\nin which the particular user actually uses, or expects or is expected\nto use, the product. A product is a consumer product regardless of\nwhether the product has substantial commercial, industrial or\nnon-consumer uses, unless such uses represent the only significant\nmode of use of the product.\n\n\"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to\ninstall and execute modified versions of a covered work in that User\nProduct from a modified version of its Corresponding Source. The\ninformation must suffice to ensure that the continued functioning of\nthe modified object code is in no case prevented or interfered with\nsolely because modification has been made.\n\nIf you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information. But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\nThe requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or\nupdates for a work that has been modified or installed by the\nrecipient, or for the User Product in which it has been modified or\ninstalled. Access to a network may be denied when the modification\nitself materially and adversely affects the operation of the network\nor violates the rules and protocols for communication across the\nnetwork.\n\nCorresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n#### 7. Additional Terms.\n\n\"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law. If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\nWhen you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit. (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.) You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\nNotwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders\nof that material) supplement the terms of this License with terms:\n\n-   a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n-   b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n-   c) Prohibiting misrepresentation of the origin of that material,\n    or requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n-   d) Limiting the use for publicity purposes of names of licensors\n    or authors of the material; or\n-   e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n-   f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions\n    of it) with contractual assumptions of liability to the recipient,\n    for any liability that these contractual assumptions directly\n    impose on those licensors and authors.\n\nAll other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10. If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term. If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\nIf you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\nAdditional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions; the\nabove requirements apply either way.\n\n#### 8. Termination.\n\nYou may not propagate or modify a covered work except as expressly\nprovided under this License. Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\nHowever, if you cease all violation of this License, then your license\nfrom a particular copyright holder is reinstated (a) provisionally,\nunless and until the copyright holder explicitly and finally\nterminates your license, and (b) permanently, if the copyright holder\nfails to notify you of the violation by some reasonable means prior to\n60 days after the cessation.\n\nMoreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\nTermination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License. If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n#### 9. Acceptance Not Required for Having Copies.\n\nYou are not required to accept this License in order to receive or run\na copy of the Program. Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance. However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work. These actions infringe copyright if you do\nnot accept this License. Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n#### 10. Automatic Licensing of Downstream Recipients.\n\nEach time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License. You are not responsible\nfor enforcing compliance by third parties with this License.\n\nAn \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations. If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\nYou may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License. For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n#### 11. Patents.\n\nA \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based. The\nwork thus licensed is called the contributor's \"contributor version\".\n\nA contributor's \"essential patent claims\" are all patent claims owned\nor controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version. For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\nEach contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\nIn the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement). To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\nIf you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients. \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\nIf, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\nA patent license is \"discriminatory\" if it does not include within the\nscope of its coverage, prohibits the exercise of, or is conditioned on\nthe non-exercise of one or more of the rights that are specifically\ngranted under this License. You may not convey a covered work if you\nare a party to an arrangement with a third party that is in the\nbusiness of distributing software, under which you make payment to the\nthird party based on the extent of your activity of conveying the\nwork, and under which the third party grants, to any of the parties\nwho would receive the covered work from you, a discriminatory patent\nlicense (a) in connection with copies of the covered work conveyed by\nyou (or copies made from those copies), or (b) primarily for and in\nconnection with specific products or compilations that contain the\ncovered work, unless you entered into that arrangement, or that patent\nlicense was granted, prior to 28 March 2007.\n\nNothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n#### 12. No Surrender of Others' Freedom.\n\nIf conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License. If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under\nthis License and any other pertinent obligations, then as a\nconsequence you may not convey it at all. For example, if you agree to\nterms that obligate you to collect a royalty for further conveying\nfrom those to whom you convey the Program, the only way you could\nsatisfy both those terms and this License would be to refrain entirely\nfrom conveying the Program.\n\n#### 13. Use with the GNU Affero General Public License.\n\nNotwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work. The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n#### 14. Revised Versions of this License.\n\nThe Free Software Foundation may publish revised and/or new versions\nof the GNU General Public License from time to time. Such new versions\nwill be similar in spirit to the present version, but may differ in\ndetail to address new problems or concerns.\n\nEach version is given a distinguishing version number. If the Program\nspecifies that a certain numbered version of the GNU General Public\nLicense \"or any later version\" applies to it, you have the option of\nfollowing the terms and conditions either of that numbered version or\nof any later version published by the Free Software Foundation. If the\nProgram does not specify a version number of the GNU General Public\nLicense, you may choose any version ever published by the Free\nSoftware Foundation.\n\nIf the Program specifies that a proxy can decide which future versions\nof the GNU General Public License can be used, that proxy's public\nstatement of acceptance of a version permanently authorizes you to\nchoose that version for the Program.\n\nLater license versions may give you additional or different\npermissions. However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n#### 15. Disclaimer of Warranty.\n\nTHERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT\nWARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND\nPERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE\nDEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR\nCORRECTION.\n\n#### 16. Limitation of Liability.\n\nIN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR\nCONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES\nARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT\nNOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR\nLOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM\nTO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER\nPARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n\n#### 17. Interpretation of Sections 15 and 16.\n\nIf the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\nEND OF TERMS AND CONDITIONS\n\n### How to Apply These Terms to Your New Programs\n\nIf you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these\nterms.\n\nTo do so, attach the following notices to the program. It is safest to\nattach them to the start of each source file to most effectively state\nthe exclusion of warranty; and each file should have at least the\n\"copyright\" line and a pointer to where the full notice is found.\n\n        <one line to give the program's name and a brief idea of what it does.>\n        Copyright (C) <year>  <name of author>\n\n        This program is free software: you can redistribute it and/or modify\n        it under the terms of the GNU General Public License as published by\n        the Free Software Foundation, either version 3 of the License, or\n        (at your option) any later version.\n\n        This program is distributed in the hope that it will be useful,\n        but WITHOUT ANY WARRANTY; without even the implied warranty of\n        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n        GNU General Public License for more details.\n\n        You should have received a copy of the GNU General Public License\n        along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper\nmail.\n\nIf the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n        <program>  Copyright (C) <year>  <name of author>\n        This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n        This is free software, and you are welcome to redistribute it\n        under certain conditions; type `show c' for details.\n\nThe hypothetical commands \\`show w' and \\`show c' should show the\nappropriate parts of the General Public License. Of course, your\nprogram's commands might be different; for a GUI interface, you would\nuse an \"about box\".\n\nYou should also get your employer (if you work as a programmer) or\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary. For more information on this, and how to apply and follow\nthe GNU GPL, see <http://www.gnu.org/licenses/>.\n\nThe GNU General Public License does not permit incorporating your\nprogram into proprietary programs. If your program is a subroutine\nlibrary, you may consider it more useful to permit linking proprietary\napplications with the library. If this is what you want to do, use the\nGNU Lesser General Public License instead of this License. But first,\nplease read <http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "Makefile",
    "content": "REPODIR = repo\nINCLUDES = inst/include/pomp.h inst/include/pomp_defines.h\nHEADERS = src/decls.h\nSESSION_PKGS = datasets,utils,grDevices,graphics,stats,methods,tidyverse,pomp\n\ninclude rules.mk\n\nsrc/decls.h: $(CSOURCE)\n\tfile=`mktemp tmpXXXXXXX.h` && \\\n\tcproto -f2 -I $(R_HOME)/include -e $(CSOURCE) > $$file && \\\n\tmv $$file $@\n"
  },
  {
    "path": "NAMESPACE",
    "content": "# Generated by roxygen2: do not edit by hand\n\nS3method(as.character,Csnippet)\nS3method(as.data.frame,abcList)\nS3method(as.data.frame,bsmcd_pomp)\nS3method(as.data.frame,kalmand_pomp)\nS3method(as.data.frame,mif2List)\nS3method(as.data.frame,pfilterList)\nS3method(as.data.frame,pfilterd_pomp)\nS3method(as.data.frame,pmcmcList)\nS3method(as.data.frame,pomp)\nS3method(as.data.frame,pompList)\nS3method(as.data.frame,probed_pomp)\nS3method(as.data.frame,wpfilterd_pomp)\nS3method(c,Pomp)\nexport(Csnippet)\nexport(append_data)\nexport(as_pomp)\nexport(bake)\nexport(blowflies1)\nexport(blowflies2)\nexport(bspline_basis)\nexport(concat)\nexport(continue)\nexport(dacca)\nexport(dbetabinom)\nexport(deulermultinom)\nexport(discrete_time)\nexport(ebolaModel)\nexport(eeulermultinom)\nexport(euler)\nexport(expit)\nexport(freeze)\nexport(gillespie)\nexport(gillespie_hl)\nexport(gompertz)\nexport(hitch)\nexport(inv_log_barycentric)\nexport(kalmanFilter)\nexport(logLik)\nexport(log_barycentric)\nexport(logit)\nexport(logmeanexp)\nexport(lookup)\nexport(map)\nexport(mcap)\nexport(mvn_diag_rw)\nexport(mvn_rw)\nexport(mvn_rw_adaptive)\nexport(onestep)\nexport(ou2)\nexport(parameter_trans)\nexport(periodic_bspline_basis)\nexport(pomp)\nexport(probe_acf)\nexport(probe_ccf)\nexport(probe_marginal)\nexport(probe_mean)\nexport(probe_median)\nexport(probe_nlar)\nexport(probe_period)\nexport(probe_quantile)\nexport(probe_sd)\nexport(probe_var)\nexport(profile_design)\nexport(rbetabinom)\nexport(repair_lookup_table)\nexport(reulermultinom)\nexport(rgammawn)\nexport(ricker)\nexport(runif_design)\nexport(rw2)\nexport(rw_sd)\nexport(sannbox)\nexport(sir)\nexport(sir2)\nexport(slice_design)\nexport(sobol_design)\nexport(stew)\nexport(systematic_resample)\nexport(vectorfield)\nexport(verhulst)\nexport(wquant)\nexportClasses(pomp)\nexportMethods(\"[\")\nexportMethods(\"coef<-\")\nexportMethods(\"solibs<-\")\nexportMethods(\"time<-\")\nexportMethods(\"timezero<-\")\nexportMethods(abc)\nexportMethods(bsmc2)\nexportMethods(coef)\nexportMethods(cond_logLik)\nexportMethods(continue)\nexportMethods(covariate_table)\nexportMethods(covmat)\nexportMethods(dinit)\nexportMethods(dmeasure)\nexportMethods(dprior)\nexportMethods(dprocess)\nexportMethods(eakf)\nexportMethods(eff_sample_size)\nexportMethods(emeasure)\nexportMethods(enkf)\nexportMethods(filter_mean)\nexportMethods(filter_traj)\nexportMethods(flow)\nexportMethods(forecast)\nexportMethods(logLik)\nexportMethods(melt)\nexportMethods(mif2)\nexportMethods(nlf_objfun)\nexportMethods(obs)\nexportMethods(parameter_trans)\nexportMethods(parmat)\nexportMethods(partrans)\nexportMethods(pfilter)\nexportMethods(plot)\nexportMethods(pmcmc)\nexportMethods(pompLoad)\nexportMethods(pompUnload)\nexportMethods(pred_mean)\nexportMethods(pred_var)\nexportMethods(print)\nexportMethods(probe)\nexportMethods(probe_objfun)\nexportMethods(rinit)\nexportMethods(rmeasure)\nexportMethods(rprior)\nexportMethods(rprocess)\nexportMethods(saved_states)\nexportMethods(show)\nexportMethods(simulate)\nexportMethods(skeleton)\nexportMethods(spect)\nexportMethods(spect_objfun)\nexportMethods(spy)\nexportMethods(states)\nexportMethods(summary)\nexportMethods(time)\nexportMethods(timezero)\nexportMethods(traces)\nexportMethods(traj_objfun)\nexportMethods(trajectory)\nexportMethods(vmeasure)\nexportMethods(window)\nexportMethods(wpfilter)\nimport(methods)\nimportFrom(coda,mcmc)\nimportFrom(coda,mcmc.list)\nimportFrom(data.table,fread)\nimportFrom(data.table,fwrite)\nimportFrom(data.table,rbindlist)\nimportFrom(deSolve,diagnostics)\nimportFrom(deSolve,ode)\nimportFrom(digest,digest)\nimportFrom(grDevices,dev.interactive)\nimportFrom(grDevices,rgb)\nimportFrom(graphics,abline)\nimportFrom(graphics,axis)\nimportFrom(graphics,box)\nimportFrom(graphics,hist)\nimportFrom(graphics,legend)\nimportFrom(graphics,lines)\nimportFrom(graphics,matplot)\nimportFrom(graphics,mtext)\nimportFrom(graphics,pairs)\nimportFrom(graphics,par)\nimportFrom(graphics,plot.default)\nimportFrom(graphics,points)\nimportFrom(graphics,polygon)\nimportFrom(graphics,rect)\nimportFrom(graphics,text)\nimportFrom(graphics,title)\nimportFrom(mvtnorm,dmvnorm)\nimportFrom(mvtnorm,rmvnorm)\nimportFrom(stats,.lm.fit)\nimportFrom(stats,approx)\nimportFrom(stats,coef)\nimportFrom(stats,cor)\nimportFrom(stats,cov)\nimportFrom(stats,density)\nimportFrom(stats,dnorm)\nimportFrom(stats,kernel)\nimportFrom(stats,lm)\nimportFrom(stats,loess)\nimportFrom(stats,logLik)\nimportFrom(stats,median)\nimportFrom(stats,optim)\nimportFrom(stats,pbeta)\nimportFrom(stats,predict)\nimportFrom(stats,qchisq)\nimportFrom(stats,quantile)\nimportFrom(stats,rnorm)\nimportFrom(stats,runif)\nimportFrom(stats,sd)\nimportFrom(stats,setNames)\nimportFrom(stats,simulate)\nimportFrom(stats,smooth.spline)\nimportFrom(stats,spec.pgram)\nimportFrom(stats,time)\nimportFrom(stats,var)\nimportFrom(stats,vcov)\nimportFrom(stats,window)\nimportFrom(utils,read.csv2)\nuseDynLib(pomp, .registration = TRUE, .fixes=\"P_\")\n"
  },
  {
    "path": "R/abc.R",
    "content": "##' Approximate Bayesian computation\n##'\n##' The approximate Bayesian computation (ABC) algorithm for estimating the parameters of a partially-observed Markov process.\n##'\n##' @name abc\n##' @rdname abc\n##' @aliases abc,missing-method abc,ANY-method\n##' @docType methods\n##' @include pomp_class.R probe.R continue.R workhorses.R\n##' @importFrom stats runif\n##' @author Edward L. Ionides, Aaron A. King\n##' @family summary statistic-based methods\n##' @family estimation methods\n##' @family MCMC methods\n##' @family Bayesian methods\n##' @concept approximate Bayesian computation\n##' @inheritParams probe\n##' @inheritParams pmcmc\n##' @inheritParams pomp\n##' @param Nabc the number of ABC iterations to perform.\n##' @param scale named numeric vector of scales.\n##' @param epsilon ABC tolerance.\n##'\n##' @inheritSection pomp Note for Windows users\n##'\n##' @section Running ABC:\n##'\n##' \\code{abc} returns an object of class \\sQuote{abcd_pomp}.\n##' One or more \\sQuote{abcd_pomp} objects can be joined to form an \\sQuote{abcList} object.\n##'\n##' @section Re-running ABC iterations:\n##'\n##' To re-run a sequence of ABC iterations, one can use the \\code{abc} method on a \\sQuote{abcd_pomp} object.\n##' By default, the same parameters used for the original ABC run are re-used (except for \\code{verbose}, the default of which is shown above).\n##' If one does specify additional arguments, these will override the defaults.\n##'\n##' @section Continuing ABC iterations:\n##'\n##' One can continue a series of ABC iterations from where one left off using the \\code{continue} method.\n##' A call to \\code{abc} to perform \\code{Nabc=m} iterations followed by a call to \\code{continue} to perform \\code{Nabc=n} iterations will produce precisely the same effect as a single call to \\code{abc} to perform \\code{Nabc=m+n} iterations.\n##' By default, all the algorithmic parameters are the same as used in the original call to \\code{abc}.\n##' Additional arguments will override the defaults.\n##'\n##' @section Methods:\n##' The following can be applied to the output of an \\code{abc} operation:\n##' \\describe{\n##' \\item{\\code{abc}}{repeats the calculation, beginning with the last state}\n##' \\item{\\code{\\link{continue}}}{continues the \\code{abc} calculation}\n##' \\item{\\code{plot}}{produces a series of diagnostic plots}\n##' \\item{\\code{\\link{traces}}}{produces an \\code{\\link[coda]{mcmc}} object, to which the various \\pkg{coda} convergence diagnostics can be applied}\n##' }\n##'\n##' @references\n##'\n##' \\Marin2012\n##'\n##' \\Toni2010\n##'\n##' \\Toni2009\n##'\nNULL\n\nsetClass(\n  \"abcd_pomp\",\n  contains=\"pomp\",\n  slots=c(\n    pars = \"character\",\n    Nabc = \"integer\",\n    accepts = \"integer\",\n    probes=\"list\",\n    scale = \"numeric\",\n    epsilon = \"numeric\",\n    proposal = \"function\",\n    traces = \"matrix\"\n  ),\n  prototype=prototype(\n    pars = character(0),\n    Nabc = 0L,\n    accepts = 0L,\n    probes = list(),\n    scale = numeric(0),\n    epsilon = 1.0,\n    proposal = function (...) pStop(who=\"abc\",\"proposal not specified.\"),\n    traces=array(dim=c(0,0))\n  )\n)\n\nsetGeneric(\n  \"abc\",\n  function (data, ...)\n    standardGeneric(\"abc\")\n)\n\nsetMethod(\n  \"abc\",\n  signature=signature(data=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"abc\",\"data\")\n  }\n)\n\nsetMethod(\n  \"abc\",\n  signature=signature(data=\"ANY\"),\n  definition=function (data, ...) {\n    undef_method(\"abc\",data)\n  }\n)\n\n##' @rdname abc\n##' @export\nsetMethod(\n  \"abc\",\n  signature=signature(data=\"data.frame\"),\n  definition=function (\n    data,\n    ...,\n    Nabc = 1, proposal, scale, epsilon,\n    probes,\n    params, rinit, rprocess, rmeasure, dprior,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      abc_internal(\n        data,\n        ...,\n        Nabc=Nabc,\n        proposal=proposal,\n        scale=scale,\n        epsilon=epsilon,\n        probes=probes,\n        params=params,\n        rinit=rinit,\n        rprocess=rprocess,\n        rmeasure=rmeasure,\n        dprior=dprior,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"abc\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname abc\n##' @export\nsetMethod(\n  \"abc\",\n  signature=signature(data=\"pomp\"),\n  definition=function (\n    data,\n    ...,\n    Nabc = 1, proposal, scale, epsilon,\n    probes,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      abc_internal(\n        data,\n        ...,\n        Nabc=Nabc,\n        proposal=proposal,\n        scale=scale,\n        epsilon=epsilon,\n        probes=probes,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"abc\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname abc\n##' @export\nsetMethod(\n  \"abc\",\n  signature=signature(data=\"probed_pomp\"),\n  definition=function (\n    data,\n    ...,\n    probes,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    if (missing(probes)) probes <- data@probes\n\n    abc(\n      as(data,\"pomp\"),\n      ...,\n      probes=probes,\n      verbose=verbose\n    )\n\n  }\n)\n\n##' @rdname abc\n##' @export\nsetMethod(\n  \"abc\",\n  signature=signature(data=\"abcd_pomp\"),\n  definition=function (\n    data,\n    ...,\n    Nabc, proposal, scale, epsilon,\n    probes,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    if (missing(Nabc)) Nabc <- data@Nabc\n    if (missing(proposal)) proposal <- data@proposal\n    if (missing(scale)) scale <- data@scale\n    if (missing(epsilon)) epsilon <- data@epsilon\n    if (missing(probes)) probes <- data@probes\n\n    abc(\n      as(data,\"pomp\"),\n      ...,\n      Nabc=Nabc,\n      proposal=proposal,\n      scale=scale,\n      epsilon=epsilon,\n      probes=probes,\n      verbose=verbose\n    )\n\n  }\n)\n\n##' @rdname continue\n##' @param Nabc positive integer; number of additional ABC iterations to perform\n##' @export\nsetMethod(\n  \"continue\",\n  signature=signature(object=\"abcd_pomp\"),\n  definition=function (\n    object,\n    ...,\n    Nabc = 1\n  ) {\n\n    ndone <- object@Nabc\n    accepts <- object@accepts\n\n    obj <- abc(object,...,Nabc=Nabc,.ndone=ndone,.accepts=accepts)\n\n    obj@traces <- rbind(\n      object@traces[,colnames(obj@traces)],\n      obj@traces[-1,]\n    )\n    names(dimnames(obj@traces)) <- c(\"iteration\",\"name\")\n    obj@Nabc <- as.integer(ndone+Nabc)\n    obj@accepts <- as.integer(accepts+obj@accepts)\n\n    obj\n  }\n)\n\nabc_internal <- function (\n  object,\n  ...,\n  Nabc, proposal, scale, epsilon, probes,\n  verbose,\n  .ndone = 0L, .accepts = 0L, .gnsi = TRUE\n) {\n\n  verbose <- as.logical(verbose)\n\n  object <- pomp(object,...,verbose=verbose)\n\n  if (undefined(object@rprocess) || undefined(object@rmeasure))\n    pStop_(paste(sQuote(c(\"rprocess\",\"rmeasure\")),collapse=\", \"),\" are needed basic components.\")\n\n  if (missing(proposal)) proposal <- NULL\n  if (missing(probes)) probes <- NULL\n  if (missing(scale)) scale <- NULL\n  if (missing(epsilon)) epsilon <- NULL\n\n  gnsi <- as.logical(.gnsi)\n  scale <- as.numeric(scale)\n  epsilon <- as.numeric(epsilon)\n  epssq <- epsilon*epsilon\n  .ndone <- as.integer(.ndone)\n  .accepts <- as.integer(.accepts)\n\n  params <- coef(object)\n\n  Nabc <- as.integer(Nabc)\n  if (!is.finite(Nabc) || Nabc < 0)\n    pStop_(sQuote(\"Nabc\"),\" must be a positive integer.\")\n\n  param.names <- names(params)\n  if (is.null(param.names) || !is.numeric(params))\n    pStop_(sQuote(\"params\"),\" must be a named numeric vector.\")\n\n  if (is.null(proposal))\n    pStop_(sQuote(\"proposal\"),\" must be specified.\")\n  if (!is.function(proposal))\n    pStop_(sQuote(\"proposal\"),\" must be a function.\")\n\n  if (is.null(probes))\n    pStop_(sQuote(\"probes\"),\" must be specified.\")\n  if (!is.list(probes)) probes <- list(probes)\n  if (!all(vapply(probes,is.function,logical(1L))))\n    pStop_(sQuote(\"probes\"),\" must be a function or a list of functions.\")\n  if (!all(vapply(probes,\\(f)length(formals(f))==1L,logical(1L))))\n    pStop_(\"each probe must be a function of a single argument.\")\n\n  if (length(scale)==0)\n    pStop_(sQuote(\"scale\"),\" must be specified.\")\n\n  if (length(epsilon)==0)\n    pStop_(\"abc match criterion, \",sQuote(\"epsilon\"),\", must be specified.\")\n\n  pompLoad(object,verbose=verbose)\n  on.exit(pompUnload(object,verbose=verbose))\n\n  ## test proposal distribution\n  theta <- tryCatch(\n    proposal(params,.n=0),\n    error = function (e)\n      pStop_(\"in proposal function: \",conditionMessage(e))\n  )\n  if (is.null(names(theta)) || !is.numeric(theta) || any(!nzchar(names(theta))))\n    pStop_(sQuote(\"proposal\"),\" must return a named numeric vector.\")\n\n  theta <- params\n  log.prior <-dprior(object,params=theta,log=TRUE,.gnsi=gnsi)\n\n  if (!is.finite(log.prior))\n    pStop_(\"non-finite log prior at starting parameters.\")\n\n  ## we suppose that theta is a \"match\",\n  ## which does the right thing for continue() and\n  ## should have negligible effect unless doing many short calls to continue()\n\n  traces <- matrix(\n    data=NA,\n    nrow=Nabc+1,\n    ncol=length(theta),\n    dimnames=list(\n      iteration=seq(from=0,to=Nabc,by=1),\n      name=names(theta)\n    )\n  )\n\n  ## apply probes to data\n  datval <- tryCatch(\n    .Call(P_apply_probe_data,object,probes),\n    error = function (e) {\n      pStop_(\"applying probes to data: \",conditionMessage(e))\n    }\n  )\n\n  if (length(scale) != 1 && length(scale) != length(datval))\n    pStop_(sQuote(\"scale\"),\" must have either length 1 or length equal to the\",\n      \" number of probes (here, \",length(datval),\").\")\n\n  traces[1,names(theta)] <- theta\n\n  for (n in seq_len(Nabc)) { # main loop\n\n    theta.prop <- tryCatch(\n      proposal(theta,.n=n+.ndone,.accepts=.accepts,verbose=verbose),\n      error = function (e)\n        pStop_(\"in proposal function: \",conditionMessage(e))\n    )\n    log.prior.prop <- dprior(object,params=theta.prop,log=TRUE,\n      .gnsi=gnsi)\n\n    if (is.finite(log.prior.prop) && runif(1) < exp(log.prior.prop-log.prior)) {\n\n      ## compute the probes for the proposed new parameter values\n\n      simval <- tryCatch(\n        .Call(P_apply_probe_sim,object=object,nsim=1L,params=theta.prop,\n          probes=probes,datval=datval,gnsi=gnsi),\n        error = function (e)\n          pStop_(\"applying probes to simulations: \",conditionMessage(e))\n      )\n\n      ## ABC update rule\n      distance <- sum(((datval-simval)/scale)^2)\n      if( (is.finite(distance)) && (distance<epssq) ){\n        theta <- theta.prop\n        log.prior <- log.prior.prop\n        .accepts <- .accepts+1L\n      }\n\n    }\n\n    ## store a record of this iteration\n    traces[n+1,names(theta)] <- theta\n    if (verbose && (n%%5==0))\n      cat(\"ABC iteration\",n+.ndone,\"of\",Nabc+.ndone,\n        \"completed\\nacceptance ratio:\",\n        round(.accepts/(n+.ndone),3),\"\\n\")\n\n    gnsi <- FALSE\n\n  }\n\n  pars <- apply(traces,2L,\\(x)diff(range(x))>0)\n  pars <- names(pars[pars])\n\n  new(\n    \"abcd_pomp\",\n    object,\n    params=theta,\n    pars=pars,\n    Nabc=Nabc,\n    accepts=.accepts,\n    probes=probes,\n    scale=scale,\n    epsilon=epsilon,\n    proposal=proposal,\n    traces=traces\n  )\n\n}\n"
  },
  {
    "path": "R/accumulators.R",
    "content": "##' accumulator variables\n##'\n##' Latent state variables that accumulate quantities through time.\n##'\n##' @name accumvars\n##' @rdname accumvars\n##' @family implementation information\n##' @seealso \\code{\\link{sir}}\n##' @details\n##' In formulating models, one sometimes wishes to define a state variable that will accumulate some quantity over the interval between successive observations.\n##' \\pkg{pomp} provides a facility to make such features more convenient.\n##' Specifically, if \\eqn{a} is a state-variable named in the \\code{pomp}'s \\code{accumvars} argument, then for each interval \\eqn{(t_k,t_{k+1})}{(t[k],t[k+1])}, \\eqn{k=0,1,2,\\dots}, \\eqn{a} will be set to zero at prior to any \\code{\\link{rprocess}} computation over that interval.\n##' Deterministic trajectory computation is handled slightly differently:\n##' see \\code{\\link{flow}}.\n##' For examples, see \\code{\\link{sir}} and the tutorials on the \\href{https://kingaa.github.io/pomp/}{package website}.\n##' @example examples/accumulators.R\n##'\nNULL\n"
  },
  {
    "path": "R/as_data_frame.R",
    "content": "##' Coerce to data frame\n##'\n##' All \\pkg{pomp} model objects can be recast as data frames.\n##' The contents of the resulting data frame depend on the nature of the object.\n##'\n##' @name as.data.frame\n##' @docType methods\n##' @keywords internal\n##' @rdname as_data_frame\n##' @include pomp_class.R pfilter.R bsmc2.R mif2.R pmcmc.R abc.R wpfilter.R\n##' @include probe.R kalman.R melt.R\n##'\nNULL\n\nsetAs(\n  from=\"pomp\",\n  to=\"data.frame\",\n  def = function (from) {\n    x <- as.data.frame(cbind(from@times,t(from@data)))\n    names(x) <- c(from@timename,rownames(from@data))\n    if (length(from@states) > 0) {\n      nm <- c(names(x),rownames(from@states))\n      x <- cbind(x,t(from@states))\n      names(x) <- nm\n    }\n    cnames <- get_covariate_names(from@covar)\n    if (length(cnames) > 0) {\n      nm <- c(names(x),cnames) # see issue #56\n      y <- .Call(P_lookup_in_table,from@covar,from@times)\n      x <- cbind(x,t(y))\n      names(x) <- nm\n    }\n    x\n  }\n)\n\n##' @rdname as_data_frame\n##' @inheritParams base::as.data.frame\n##' @details\n##' When \\code{object} is a simple \\sQuote{pomp} object,\n##' \\code{as(object,\"data.frame\")} or \\code{as.data.frame(object)} results in a\n##' data frame with the times, observables, states (if known), and\n##' interpolated covariates (if any).\n##' @export\nas.data.frame.pomp <- function (x, ...) as(x,\"data.frame\")\n\nsetAs(\n  from=\"pfilterd_pomp\",\n  to=\"data.frame\",\n  def = function (from) {\n    pm <- pred_mean(from)\n    pv <- pred_var(from)\n    fm <- filter_mean(from)\n    out <- cbind(\n      as(as(from,\"pomp\"),\"data.frame\"),\n      ess=eff_sample_size(from),\n      cond.logLik=cond_logLik(from)\n    )\n    if (length(pm)>0) {\n      pm <- as.data.frame(t(pm))\n      names(pm) <- paste0(\"pred.mean.\",names(pm))\n      out <- cbind(out,pm)\n    }\n    if (length(pv)>0) {\n      pv <- as.data.frame(t(pv))\n      names(pv) <- paste0(\"pred.var.\",names(pv))\n      out <- cbind(out,pv)\n    }\n    if (length(fm)>0) {\n      fm <- as.data.frame(t(fm))\n      names(fm) <- paste0(\"filter.mean.\",names(fm))\n      out <- cbind(out,fm)\n    }\n    out\n  }\n)\n\n##' @rdname as_data_frame\n##' @details When \\code{object} is a \\sQuote{pfilterd_pomp} object,\n##' coercion to a data frame results in a data frame with the same content as for a simple \\sQuote{pomp},\n##' but with conditional log likelihood and effective sample size estimates included, as well as filtering means, prediction means, and prediction variances, if these have been computed.\n##' @export\nas.data.frame.pfilterd_pomp <- function (x, ...) as(x,\"data.frame\")\n\nsetAs(\n  from=\"probed_pomp\",\n  to=\"data.frame\",\n  def = function (from) {\n    x <- as.data.frame(rbind(from@datvals,from@simvals))\n    row.names(x) <- seq.int(from=0,to=nrow(x)-1)\n    x$.id <- factor(c(\"data\",rep(\"sim\",nrow(x)-1)))\n    x\n  }\n)\n\n##' @rdname as_data_frame\n##' @details When \\code{object} is a \\sQuote{probed_pomp} object,\n##' coercion to a data frame results in a data frame with the values of the probes computed on the data and on simulations.\n##' @export\nas.data.frame.probed_pomp <- function (x, ...)\n  as(x,\"data.frame\")\n\nsetAs(\n  from=\"kalmand_pomp\",\n  to=\"data.frame\",\n  def = function (from) {\n    pm <- pred_mean(from)\n    fm <- filter_mean(from)\n    fc <- forecast(from)\n    out <- cbind(\n      as(as(from,\"pomp\"),\"data.frame\"),\n      cond.logLik=cond_logLik(from)\n    )\n    if (length(pm)>0) {\n      pm <- as.data.frame(t(pm))\n      names(pm) <- paste0(\"pred.mean.\",names(pm))\n      out <- cbind(out,pm)\n    }\n    if (length(fm)>0) {\n      fm <- as.data.frame(t(fm))\n      names(fm) <- paste0(\"filter.mean.\",names(fm))\n      out <- cbind(out,fm)\n    }\n    if (length(fc)>0) {\n      fc <- as.data.frame(t(fc))\n      names(fc) <- paste0(\"forecast.\",names(fc))\n      out <- cbind(out,fc)\n    }\n    out\n  }\n)\n\n##' @rdname as_data_frame\n##' @details When \\code{object} is a \\sQuote{kalmand_pomp} object,\n##' coercion to a data frame results in a data frame with prediction means, filter means and forecasts, in addition to the data.\n##' @export\nas.data.frame.kalmand_pomp <- function (x, ...) {\n  as(x,\"data.frame\")\n}\n\nsetAs(\n  from=\"bsmcd_pomp\",\n  to=\"data.frame\",\n  def = function (from) {\n    prior <- as.data.frame(t(from@prior))\n    post <- as.data.frame(t(from@post))\n    prior$.id <- \"prior\"\n    post$.id <- \"posterior\"\n    rbind(prior,post)\n  }\n)\n\n##' @rdname as_data_frame\n##' @details When \\code{object} is a \\sQuote{bsmcd_pomp} object,\n##' coercion to a data frame results in a data frame with samples from the prior and posterior distribution.\n##' The \\code{.id} variable distinguishes them.\n##' @export\nas.data.frame.bsmcd_pomp <- function (x, ...) {\n  as(x,\"data.frame\")\n}\n\nsetAs(\n  from=\"listie\",\n  to=\"data.frame\",\n  def = function (from) {\n    rbind_fill(\n      lapply(from,as,\"data.frame\"),\n      .id=\".L1\"\n    )\n  }\n)\n\n##' @rdname as_data_frame\n##' @export\nas.data.frame.pompList <- function (x, ...) {\n  as(x,\"data.frame\")\n}\n\n##' @rdname as_data_frame\n##' @export\nas.data.frame.pfilterList <- function (x, ...) {\n  as(x,\"data.frame\")\n}\n\n##' @rdname as_data_frame\n##' @export\nas.data.frame.abcList <- function (x, ...) {\n  as(x,\"data.frame\")\n}\n\n##' @rdname as_data_frame\n##' @export\nas.data.frame.mif2List <- function (x, ...) {\n  as(x,\"data.frame\")\n}\n\n##' @rdname as_data_frame\n##' @export\nas.data.frame.pmcmcList <- function (x, ...) {\n  as(x,\"data.frame\")\n}\n\nsetAs(\n  from=\"wpfilterd_pomp\",\n  to=\"data.frame\",\n  def = function (from) {\n    cbind(\n      as(as(from,\"pomp\"),\"data.frame\"),\n      eff.sample.size=eff_sample_size(from),\n      cond.logLik=cond_logLik(from)\n    )\n  }\n)\n\n##' @rdname as_data_frame\n##' @details When \\code{object} is a \\sQuote{wpfilterd_pomp} object,\n##' coercion to a data frame results in a data frame with the same content as for a simple \\sQuote{pomp},\n##' but with conditional log likelihood and effective sample size estimates included.\n##' @export\nas.data.frame.wpfilterd_pomp <- function (x, ...) as(x,\"data.frame\")\n"
  },
  {
    "path": "R/as_pomp.R",
    "content": "##' as.pomp\n##'\n##' Coerce to a \\sQuote{pomp} object\n##'\n##' @name as_pomp\n##' @docType methods\n##' @keywords internal\n##' @rdname as_pomp\n##' @include pomp_class.R\n##'\n##' @param object the object to be coerced\n##' @param \\dots additional arguments\n##'\n##' @export\nas_pomp <- function (object, ...) {\n  as(object,\"pomp\")\n}\n"
  },
  {
    "path": "R/bake.R",
    "content": "##' Tools for reproducible computations\n##'\n##' Archiving of computations and control of the random-number generator.\n##'\n##' @name reproducibility_tools\n##' @rdname bake\n##' @include package.R\n##' @concept reproducibility\n##' @author Aaron A. King\n##' @details\n##' On cooking shows, recipes requiring lengthy baking or stewing are prepared beforehand.\n##' The \\code{bake} and \\code{stew} functions perform analogously:\n##' an computation is performed and archived in a named file.\n##' If the function is called again and the file is present, the computation is not executed.\n##' Instead, the results are loaded from the archive.\n##' Moreover, via their optional \\code{seed} argument, \\code{bake} and \\code{stew} can control the pseudorandom-number generator (RNG) for greater reproducibility.\n##' After the computation is finished, these functions restore the pre-existing RNG state to avoid side effects.\n##'\n##' The \\code{freeze} function doesn't save results, but does set the RNG state to the specified value and restore it after the computation is complete.\n##'\n##' Both \\code{bake} and \\code{stew} first test to see whether \\code{file} exists.\n##' If it does, \\code{bake} reads it using \\code{\\link{readRDS}} and returns the resulting object.\n##' By contrast, \\code{stew} loads the file using \\code{\\link{load}} and copies the objects it contains into the user's workspace (or the environment of the call to \\code{stew}).\n##'\n##' If \\code{file} does not exist, then both \\code{bake} and \\code{stew} evaluate the expression \\code{expr};\n##' they differ in the results that they save.\n##' \\code{bake} saves the value of the evaluated expression to \\code{file} as a single object.\n##' The name of that object is not saved.\n##' By contrast, \\code{stew} creates a local environment within which \\code{expr} is evaluated; all objects in that environment are saved (by name) in \\code{file}.\n##' \\code{bake} and \\code{stew} also store information about the code executed, the dependencies, and the state of the random-number generator (if the latter is controlled) in the archive file.\n##' Re-computation is triggered if any of these things change.\n##' @section Avoid using \\sQuote{pomp} objects as dependencies:\n##' Note that when a \\sQuote{pomp} object is built with one or more \\link[=Csnippet]{C snippets}, the resulting code is \\dQuote{salted} with a random element to prevent collisions in parallel computations.\n##' As a result, two such \\sQuote{pomp} objects will never match perfectly, even if the codes and data used to construct them are identical.\n##' Therefore, avoid using \\sQuote{pomp} objects as dependencies in \\code{bake} and \\code{stew}.\n##' @param file Name of the archive file in which the result will be stored or retrieved, as appropriate.\n##' For \\code{bake}, this will contain a single object and hence be an RDS file (extension \\sQuote{rds});\n##' for \\code{stew}, this will contain one or more named objects and hence be an RDA file (extension \\sQuote{rda});\n##' for \\code{append_data}, this will be a CSV file.\n##' @param dir Directory holding archive files;\n##' by default, this is the current working directory.\n##' This can also be set using the global option \\code{pomp_archive_dir}.\n##' If it does not exist, this directory will be created (with a message).\n##' @param expr Expression to be evaluated.\n##' @param seed,kind,normal.kind optional.\n##' To set the state and of the RNG.\n##' The default, \\code{seed = NULL}, will not change the RNG state.\n##' \\code{seed} should be a single integer.\n##' See \\code{\\link{set.seed}} for more information.\n##' @param dependson arbitrary \\R object (optional).\n##' Variables on which the computation in \\code{expr} depends.\n##' A hash of these objects will be archived in \\code{file}, along with the results of evaluation \\code{expr}.\n##' When \\code{bake} or \\code{stew} are called and \\code{file} exists, the hash of these objects will be compared against the archived hash;\n##' recomputation is forced when these do not match.\n##' The dependencies should be specified as unquoted symbols:\n##' use a list if there are multiple dependencies.\n##' See the note below about avoiding using \\sQuote{pomp} objects as dependencies.\n##' @param timing logical.\n##' If \\code{TRUE}, the time required for the computation is returned.\n##' This is returned as the \\dQuote{system.time} attribute of the returned object.\n##' @param info logical.\n##' If \\code{TRUE}, the \\dQuote{ingredients} of the calculation are returned as a list.\n##' In the case of \\code{bake}, this list is the \\dQuote{ingredients} attribute of the returned object.\n##' In the case of \\code{stew}, this list is a hidden object named \\dQuote{.ingredients}, located in the environment within which \\code{stew} was called.\n##' @inheritParams base::eval\n##' @section Compatibility with older versions:\n##' With \\pkg{pomp} version 3.4.4.2, the behavior of \\code{bake} and \\code{stew} changed.\n##' In particular, older versions did no dependency checking, and did not check to see whether \\code{expr} had changed.\n##' Accordingly, the archive files written by older versions have a format that is not compatible with the newer ones.\n##' When an archive file in the old format is encountered, it will be updated to the new format, with a warning message.\n##' \\strong{Note that this will overwrite existing archive files!}\n##' However, there will be no loss of information.\n##' @return \\code{bake} returns the value of the evaluated expression \\code{expr}.\n##' Other objects created in the evaluation of \\code{expr} are discarded along with the temporary, local environment created for the evaluation.\n##'\n##' The latter behavior differs from that of \\code{stew}, which returns the names of the objects created during the evaluation of \\code{expr}.\n##' After \\code{stew} completes, these objects are copied into the environment in which \\code{stew} was called.\n##'\n##' \\code{freeze} returns the value of evaluated expression \\code{expr}.\n##' However, \\code{freeze} evaluates \\code{expr} within the parent environment, so other objects created in the evaluation of \\code{expr} will therefore exist after \\code{freeze} completes.\n##'\n##' \\code{bake} and \\code{stew} store information about the code executed, the dependencies, and the state of the random-number generator in the archive file.\n##' In the case of \\code{bake}, this is recorded in the \\dQuote{ingredients} attribute (\\code{attr(.,\"ingredients\")});\n##' in the \\code{stew} case, this is recorded in an object, \\dQuote{.ingredients}, in the archive.\n##' This information is returned only if \\code{info=TRUE}.\n##'\n##' The time required for execution is also recorded.\n##' \\code{bake} stores this in the \\dQuote{system.time} attribute of the archived \\R object;\n##' \\code{stew} does so in a hidden variable named \\code{.system.time}.\n##' The timing is obtained using \\code{\\link{system.time}}.\n##'\n##' @example examples/bake.R\n##'\nNULL\n\n##' @importFrom digest digest\ncode_digest <- function (expr) {\n  digest(deparse(expr,\n    control=c(\"keepInteger\",\"quoteExpressions\",\"showAttributes\",\n      \"keepNA\",\"niceNames\",\"delayPromises\",\"hexNumeric\")))\n}\n\nprocess_dependencies <- function (dependson, envir, ep)\n{\n  tryCatch(\n    digest(eval(dependson,envir=envir)),\n    error = function (e) {\n      pStop(who=ep,\"cannot compute hash of dependencies: \",\n        conditionMessage(e))\n    }\n  )\n}\n\nreload_check <- function (ingredients, code, deps,\n  seed, kind, normal.kind, file, ep)\n{\n  if (is.null(ingredients)) {\n    pStop(who=ep,sQuote(basename(file)),\" lacks ingredients.\")\n  }\n  identical(code,ingredients$code) &&\n    identical(deps,ingredients$dependencies) &&\n    identical(seed,ingredients$seed) &&\n    identical(kind,ingredients$kind) &&\n    identical(normal.kind,ingredients$normal.kind)\n}\n\nupdate_bake_archive <- function (val, code, deps, file) {\n  if (is.null(attr(val,\"ingredients\")) &&\n        !is.null(attr(val,\"system.time\"))\n  ) {\n    pMess(who=\"bake\",\"archive in old format detected. Updating....\")\n    attr(val,\"ingredients\") <- list(\n      code=code,\n      dependencies=deps,\n      seed=attr(val,\"seed\"),\n      kind=attr(val,\"kind\"),\n      normal.kind=attr(val,\"normal.kind\")\n    )\n    attr(val,\"seed\") <- NULL\n    attr(val,\"kind\") <- NULL\n    attr(val,\"normal.kind\") <- NULL\n    saveRDS(val,file=file)\n  }\n  val\n}\n\ncreate_path <- function (dir, file, mode = \"0755\") {\n  path <- file.path(as.character(dir[[1L]]),as.character(file[1L]))\n  dir <- dirname(path)\n  if (!dir.exists(dir)) {\n    pMess_(\"creating archive directory \",sQuote(dir),\".\")\n    dir.create(dir,recursive=TRUE,mode=mode)\n  }\n  path\n}\n\n##' @rdname bake\n##' @export\nbake <- function (\n  file, expr,\n  seed = NULL, kind = NULL, normal.kind = NULL,\n  dependson = NULL, info = FALSE, timing = TRUE,\n  dir = getOption(\"pomp_archive_dir\",getwd())\n) {\n  expr <- substitute(expr)\n  code <- code_digest(expr)\n  deps <- process_dependencies(\n    dependson=substitute(dependson),\n    envir=parent.frame(),\n    ep=\"bake\"\n  )\n  info <- as.logical(info)\n  timing <- as.logical(timing)\n  file <- create_path(dir,file)\n  reload <- file.exists(file)\n  if (reload) {\n    val <- readRDS(file)\n    val <- update_bake_archive(val,code=code,deps=deps,file=file)\n    reload <- reload_check(\n      ingredients=attr(val,\"ingredients\"),\n      code=code,deps=deps,\n      seed=seed,kind=kind,normal.kind=normal.kind,\n      file=file,\n      ep=\"bake\"\n    )\n    if (!reload) {\n      pMess(who=\"bake\",\"recomputing archive \",basename(file),\".\")\n    }\n  }\n  if (!reload) {\n    tmg <- system.time(\n      val <- freeze(\n        expr,\n        seed=seed,\n        kind=kind,\n        normal.kind=normal.kind,\n        envir=parent.frame(1L),\n        enclos=parent.frame(2L)\n      )\n    )\n    if (is.null(val)) {\n      pWarn(\"expression evaluates to NULL,\",\n        \" an empty list will be returned.\")\n      val <- list()\n    }\n    attr(val,\"ingredients\") <- list(\n      code=code,\n      dependencies=deps,\n      seed=seed,\n      kind=kind,\n      normal.kind=normal.kind\n    )\n    attr(val,\"system.time\") <- tmg\n    saveRDS(val,file=file)\n  }\n  if (!info) {\n    attr(val,\"ingredients\") <- NULL\n  }\n  if (!timing) {\n    attr(val,\"system.time\") <- NULL\n  }\n  val\n}\n\nupdate_stew_archive <- function (\n  e, code, deps,\n  seed, kind, normal.kind,\n  file\n) {\n  if (is.null(e$.ingredients)) {\n    pMess(who=\"stew\",\"archive in old format detected. Updating....\")\n    e$.ingredients <- list(\n      code=code,\n      dependencies=deps,\n      seed=seed,\n      kind=kind,\n      normal.kind=normal.kind\n    )\n    e$.system.time <- NULL\n    save(list=objects(envir=e,all.names=TRUE),file=file,envir=e)\n  }\n  e\n}\n\n##' @rdname bake\n##' @export\nstew <- function (\n  file, expr,\n  seed = NULL, kind = NULL, normal.kind = NULL,\n  dependson = NULL, info = FALSE, timing = TRUE,\n  dir = getOption(\"pomp_archive_dir\",getwd())\n) {\n  expr <- substitute(expr)\n  code <- code_digest(expr)\n  pf <- parent.frame()\n  deps <- process_dependencies(\n    dependson=substitute(dependson),\n    envir=pf,\n    ep=\"stew\"\n  )\n  info <- as.logical(info)\n  timing <- as.logical(timing)\n  file <- create_path(dir,file)\n  reload <- file.exists(file)\n  e <- new.env(parent=pf)\n  if (reload) {\n    objlist <- load(file,envir=e)\n    e <- update_stew_archive(e,code=code,deps=deps,\n      seed=seed,kind=kind,normal.kind=normal.kind,file=file)\n    reload <- reload_check(\n      ingredients=e$.ingredients,\n      code=code,deps=deps,\n      seed=seed,kind=kind,normal.kind=normal.kind,\n      file=file,\n      ep=\"stew\"\n    )\n    if (!reload) {\n      pMess(who=\"stew\",\"recomputing archive \",basename(file),\".\")\n    }\n  }\n  if (!reload) {\n    e <- new.env()\n    tmg <- system.time(\n      freeze(\n        expr,\n        envir=e,\n        enclos=pf,\n        seed=seed,\n        kind=kind,\n        normal.kind=normal.kind\n      )\n    )\n    e$.ingredients <- list(\n      code=code,\n      dependencies=deps,\n      seed=seed,\n      kind=kind,\n      normal.kind=normal.kind\n    )\n    e$.system.time <- tmg\n    save(list=objects(envir=e,all.names=TRUE),file=file,envir=e)\n  }\n  objlist <- objects(envir=e,all.names=FALSE)\n  for (obj in objlist) {\n    assign(obj,get(obj,envir=e),envir=pf)\n  }\n  if (info) {\n    assign(\".ingredients\",e$.ingredients,envir=pf)\n  }\n  if (timing) {\n    assign(\".system.time\",e$.system.time,envir=pf)\n  }\n  invisible(objlist)\n}\n\n##' @rdname bake\n##' @export\nfreeze <- function (expr,\n  seed = NULL, kind = NULL, normal.kind = NULL,\n  envir = parent.frame(),\n  enclos =  if(is.list(envir) || is.pairlist(envir))\n              parent.frame() else baseenv()\n) {\n  seed <- as.integer(seed)\n  rng.control <- (length(seed) > 0)\n  if (rng.control) {\n    if (!exists(\".Random.seed\",envir=.GlobalEnv)) set.seed(NULL)\n    save.seed <- get(\".Random.seed\",envir=.GlobalEnv)\n    set.seed(seed,kind=kind,normal.kind=normal.kind)\n  }\n  val <- eval(expr,envir=envir,enclos=enclos)\n  if (rng.control) {\n    assign(\".Random.seed\",save.seed,envir=.GlobalEnv)\n  }\n  val\n}\n\n##' @rdname bake\n##' @param data data frame\n##' @param overwrite logical; if \\code{TRUE}, \\code{data} are written to \\code{file}, replacing any existing contents.\n##' If \\code{FALSE}, the \\code{data} is appended to the existing contents of \\code{file}.\n##' @return\n##' \\code{append_data} returns a data frame containing the new contents of \\code{file}, invisibly.\n##' @importFrom data.table fread fwrite rbindlist\n##' @export\nappend_data <- function (\n  data,\n  file,\n  overwrite = FALSE,\n  dir = getOption(\"pomp_archive_dir\",getwd())\n) {\n  tryCatch({\n    file <- create_path(dir,file)\n    append <- file.exists(file) && !as.logical(overwrite)\n    if (append) {\n      data <- rbindlist(\n        list(\n          fread(file=file),\n          data\n        ),\n        fill=TRUE,\n        use.names=TRUE\n      )\n    }\n    fwrite(data,file=file)\n    invisible(fread(file=file))\n  },\n  error=function (e) {\n    pStop(who=\"append_data\",conditionMessage(e))\n  })\n}\n"
  },
  {
    "path": "R/basic_components.R",
    "content": "##' Basic POMP model components.\n##'\n##' Mathematically, the parts of a \\acronym{POMP} model include the latent-state process transition distribution, the measurement-process distribution, the initial-state distribution, and possibly a prior parameter distribution.\n##' Algorithmically, each of these corresponds to at least two distinct operations.\n##' In particular, for each of the above parts, one sometimes needs to make a random draw from the distribution and sometimes to evaluate the density function.\n##' Accordingly, for each such component, there are two basic model components, one prefixed by a \\sQuote{r}, the other by a \\sQuote{d}, following the usual \\R convention.\n##'\n##' In addition to the parts listed above, \\pkg{pomp} includes two additional basic model components: the deterministic skeleton, and parameter transformations that can be used to map the parameter space onto a Euclidean space for estimation purposes.\n##' There are also basic model components for computing the mean and variance of the measurement process conditional on the latent-state process.\n##'\n##' There are thus altogether twelve \\bold{basic model components}:\n##' \\enumerate{\n##' \\item \\link[=rprocess_spec]{rprocess}, which samples from the latent-state transition distribution,\n##' \\item \\link[=dprocess_spec]{dprocess}, which evaluates the latent-state transition density,\n##' \\item \\link[=rmeasure_spec]{rmeasure}, which samples from the measurement distribution,\n##' \\item \\link[=emeasure_spec]{emeasure}, which computes the conditional expectation of the measurements, given the latent states,\n##' \\item \\link[=vmeasure_spec]{vmeasure}, which computes the conditional covariance matrix of the measurements, given the latent states,\n##' \\item \\link[=dmeasure_spec]{dmeasure}, which evaluates the measurement density,\n##' \\item \\link[=prior_spec]{rprior}, which samples from the prior distribution,\n##' \\item \\link[=prior_spec]{dprior}, which evaluates the prior density,\n##' \\item \\link[=rinit_spec]{rinit}, which samples from the initial-state distribution,\n##' \\item \\link[=dinit_spec]{dinit}, which evaluates the initial-state density,\n##' \\item \\link[=skeleton_spec]{skeleton}, which evaluates the deterministic skeleton,\n##' \\item \\link[=parameter_trans]{partrans}, which evaluates the forward or inverse parameter transformations.\n##' }\n##'\n##' Each of these can be set or modified in the \\code{pomp} \\link[=pomp]{constructor function} or in any of the \\pkg{pomp} \\link[=elementary_algorithms]{elementary algorithms} or \\link[=estimation_algorithms]{estimation algorithms} using an argument that matches the basic model component.\n##' A basic model component can be unset by passing \\code{NULL} in the same way.\n##'\n##' Help pages detailing each basic model component are provided.\n##'\n##' @name basic_components\n##' @rdname basic_components\n##' @concept basic model components\n##' @family implementation information\n##' @seealso \\link[=workhorses]{workhorse functions},\n##' \\link[=elementary_algorithms]{elementary algorithms},\n##' \\link[=estimation_algorithms]{estimation algorithms}.\n##'\nNULL\n"
  },
  {
    "path": "R/basic_probes.R",
    "content": "##' Useful probes for partially-observed Markov processes\n##'\n##' Several simple and configurable probes are provided with in the package.\n##' These can be used directly and as templates for custom probes.\n##'\n##' @name basic_probes\n##' @rdname basic_probes\n##' @family summary statistic-based methods\n##' @concept diagnostics\n##' @importFrom stats median spec.pgram kernel quantile sd var\n##' @param var,vars character; the name(s) of the observed variable(s).\n##' @param trim the fraction of observations to be trimmed (see \\code{\\link{mean}}).\n##' @param transform transformation to be applied to the data before the probe is computed.\n##' @param na.rm if \\code{TRUE}, remove all NA observations prior to computing the probe.\n##' @param kernel.width width of modified Daniell smoothing kernel to be used\n##' in power-spectrum computation: see \\code{\\link[stats]{kernel}}.\n##' @param lags In \\code{probe_ccf}, a vector of lags between time series.\n##' Positive lags correspond to \\code{x} advanced relative to \\code{y};\n##' negative lags, to the reverse.\n##'\n##' In \\code{probe_nlar}, a vector of lags present in the nonlinear\n##' autoregressive model that will be fit to the actual and simulated data.\n##' See Details, below, for a precise description.\n##' @param powers the powers of each term (corresponding to \\code{lags}) in the\n##' the nonlinear autoregressive model that will be fit to the actual and\n##' simulated data.  See Details, below, for a precise description.\n##' @param type Compute autocorrelation or autocovariance?\n##' @param ... additional arguments passed to the underlying algorithms.\n##' @return\n##' A call to any one of these functions returns a probe function,\n##' suitable for use in \\code{\\link{probe}} or \\code{\\link{probe_objfun}}.  That\n##' is, the function returned by each of these takes a data array (such as\n##' comes from a call to \\code{\\link{obs}}) as input and returns a single\n##' numerical value.\n##' @author Daniel C. Reuman, Aaron A. King\n##' @references\n##'\n##' \\Kendall1999\n##'\n##' \\Wood2010\n##'\nNULL\n\n##' @rdname basic_probes\n##' @export\nprobe_mean <- function (var, trim = 0, transform = identity, na.rm = TRUE) {\n  if (length(var)>1)\n    pStop_(sQuote(\"probe_mean\"),\" is a univariate probe.\")\n  transform <- match.fun(transform)\n  \\(y) mean(x=transform(y[var,]),trim=trim,na.rm=na.rm)\n}\n\n##' @rdname basic_probes\n##' @export\nprobe_median <- function (var, na.rm = TRUE) {\n  if (length(var)>1) pStop_(sQuote(\"probe_median\"),\" is a univariate probe.\")\n  \\(y) median(x=as.numeric(y[var,]),na.rm=na.rm)\n}\n\n##' @rdname basic_probes\n##' @export\nprobe_var <- function (var, transform = identity, na.rm = TRUE) {\n  if (length(var)>1) pStop_(sQuote(\"probe_var\"),\" is a univariate probe.\")\n  transform <- match.fun(transform)\n  \\(y) var(x=transform(y[var,]),na.rm=na.rm)\n}\n\n##' @rdname basic_probes\n##' @export\nprobe_sd <- function (var, transform = identity, na.rm = TRUE) {\n  if (length(var)>1) pStop_(sQuote(\"probe_sd\"),\" is a univariate probe.\")\n  transform <- match.fun(transform)\n  \\(y) sd(x=transform(y[var,]),na.rm=na.rm)\n}\n\n##' @rdname basic_probes\n##' @export\nprobe_period <- function (var, kernel.width, transform = identity) {\n  if (length(var)>1) pStop_(sQuote(\"probe_period\"),\" is a univariate probe.\")\n  transform <- match.fun(transform)\n  function (y) {\n    zz <- spec.pgram(\n      x=transform(y[var,]),\n      kernel=kernel(\"modified.daniell\",m=kernel.width,r=NA),\n      taper=0,\n      fast=FALSE,\n      pad=0,\n      detrend=FALSE,\n      plot=FALSE\n    )\n    1/zz$freq[which.max(zz$spec)]\n  }\n}\n\n##' @rdname basic_probes\n##' @param probs the quantile or quantiles to compute: see \\code{\\link{quantile}}.\n##' @export\nprobe_quantile <- function (var, probs, ...) {\n  if (length(var)>1) pStop_(sQuote(\"probe_quantile\"),\" is a univariate probe.\")\n  function (y) quantile(y[var,],probs=probs, ...)\n}\n\n##' @rdname basic_probes\n##' @export\nprobe_acf <- function (var, lags, type = c(\"covariance\", \"correlation\"),\n  transform = identity) {\n  type <- match.arg(type)\n  corr <- type==\"correlation\"\n  transform <- match.fun(transform)\n  if (corr && any(lags<=0)) pStop(\"lags must be positive integers.\")\n  lags <- as.integer(lags)\n  function (y)\n    tryCatch(\n      .Call(P_probe_acf,x=transform(y[var,,drop=FALSE]),lags=lags,corr=corr),\n      error = function (e) pStop(who=\"probe_acf\",conditionMessage(e))\n    )\n}\n\n##' @rdname basic_probes\n##' @export\nprobe_ccf <- function (vars, lags, type = c(\"covariance\", \"correlation\"),\n  transform = identity) {\n  type <- match.arg(type)\n  corr <- type==\"correlation\"\n  transform <- match.fun(transform)\n  if (length(vars)!=2)\n    pStop(sQuote(\"vars\"),\" must name two variables.\")\n  lags <- as.integer(lags)\n  function (y)\n    tryCatch(\n      .Call(P_probe_ccf,x=transform(y[vars[1L],,drop=TRUE]),y=transform(y[vars[2L],,drop=TRUE]),lags=lags,corr=corr),\n      error = function (e) pStop(who=\"probe_ccf\",conditionMessage(e))\n    )\n}\n\n##' @rdname basic_probes\n##' @param ref empirical reference distribution.  Simulated data will be\n##' regressed against the values of \\code{ref}, sorted and, optionally,\n##' differenced.  The resulting regression coefficients capture information\n##' about the shape of the marginal distribution.  A good choice for \\code{ref}\n##' is the data itself.\n##' @param order order of polynomial regression.\n##' @param diff order of differencing to perform.\n##' @export\nprobe_marginal <- function (var, ref, order = 3, diff = 1,\n  transform = identity) {\n  if (length(var)>1) pStop_(sQuote(\"probe_marginal\"),\" is a univariate probe.\")\n  transform <- match.fun(transform)\n  setup <- .Call(P_probe_marginal_setup,transform(ref),order,diff)\n  function (y)\n    tryCatch(\n      .Call(P_probe_marginal_solve,x=transform(y[var,,drop=TRUE]),setup=setup,diff=diff),\n      error = function (e) pStop(who=\"probe_marginal\",conditionMessage(e))\n    )\n}\n\n##' @rdname basic_probes\n##' @export\nprobe_nlar <- function (var, lags, powers, transform = identity) {\n  ep <- \"probe_nlar\"\n  if (length(var)>1) pStop_(sQuote(ep),\" is a univariate probe.\")\n  transform <- match.fun(transform)\n  if (missing(lags) || missing(powers))\n    pStop(who=ep,sQuote(\"lags\"),\" and \",sQuote(\"powers\"),\" are required arguments.\")\n  lags <- as.integer(lags)\n  powers <- as.integer(powers)\n  if (any(lags<1)||any(powers<1))\n    pStop(who=ep,sQuote(\"lags\"),\" and \",sQuote(\"powers\"),\" must be positive integers.\")\n  if (length(lags)<length(powers)) {\n    if (length(lags)>1)\n      pStop(who=ep,sQuote(\"lags\"),\" must match \",sQuote(\"powers\"),\" in length, or have length 1.\")\n    lags <- rep(lags,length(powers))\n  } else if (length(lags)>length(powers)) {\n    if (length(powers)>1)\n      pStop(who=ep,sQuote(\"powers\"),\" must match \",sQuote(\"lags\"),\" in length, or have length 1.\")\n    powers <- rep(powers,length(lags))\n  }\n  lags <- as.integer(lags)\n  powers <- as.integer(powers)\n  function (y)\n    tryCatch(\n      .Call(P_probe_nlar,x=transform(y[var,,drop=TRUE]),lags=lags,powers=powers),\n      error = function (e) pStop(who=ep,conditionMessage(e))\n    )\n}\n"
  },
  {
    "path": "R/betabinom.R",
    "content": "##' Beta-binomial distribution\n##'\n##' Density and random generation for the Beta-binomial distribution with parameters \\code{size}, \\code{mu}, and \\code{theta}.\n##'\n##' A variable \\eqn{X} is Beta-binomially distributed if\n##' \\eqn{X\\sim{\\mathrm{Binomial}(n,P)}}{X~{Binomial(n,P)}} where \\eqn{P\\sim{\\mathrm{Beta}(\\mu,\\theta)}}{P~Beta(mu,theta)}.\n##' Using the standard \\eqn{(a,b)} parameterization, \\eqn{a=\\mu\\,\\theta}{a=mu*theta} and \\eqn{b=(1-\\mu)\\,\\theta}{b=(1-mu)*theta}.\n##'\n##' @name betabinomial\n##' @rdname betabinom\n##' @family implementation information\n##' @concept probability distributions\n##' @inheritSection eulermultinom C API\n##' @inheritParams eulermultinom\n##' @param size \\code{size} parameter of the binomial distribution\n##' @param prob mean of the Beta distribution\n##' @param theta Beta distribution dispersion parameter\n##' @param x vector of non-negative integer quantiles\n##' @return\n##' \\item{rbetabinom}{\n##'    Returns a vector of length \\code{n} containing random variates drawn from the Beta-binomial distribution.\n##' }\n##' \\item{dbetabinom}{\n##'    Returns a vector (of length equal to the number of columns of \\code{x}) containing the probabilities of observing each column of \\code{x} given the specified parameters (\\code{size}, \\code{prob}, \\code{theta}).\n##' }\nNULL\n\n##' @rdname betabinom\n##' @export\nrbetabinom <- function (n = 1, size, prob, theta) {\n  tryCatch(\n    .Call(P_R_BetaBinom,n,size,prob,theta),\n    error = function (e) pStop(who=\"rbetabinom\",conditionMessage(e))\n  )\n}\n\n##' @rdname betabinom\n##' @export\ndbetabinom <- function (x, size, prob, theta, log = FALSE) {\n  tryCatch(\n    .Call(P_D_BetaBinom,x,size,prob,theta,log),\n    error = function (e) pStop(who=\"dbetabinom\",conditionMessage(e))\n  )\n}\n"
  },
  {
    "path": "R/blowflies.R",
    "content": "##' Nicholson's blowflies.\n##'\n##' \\code{blowflies} is a data frame containing the data from several of Nicholson's classic experiments with the Australian sheep blowfly, \\emph{Lucilia cuprina}.\n##'\n##' \\code{blowflies1()} and \\code{blowflies2()} construct \\sQuote{pomp} objects encoding stochastic delay-difference equation models.\n##' The data for these come from \"population I\", a control culture.\n##' The experiment is described on pp. 163--4 of Nicholson (1957).\n##' Unlimited quantities of larval food were provided;\n##' the adult food supply (ground liver) was constant at 0.4g per day.\n##' The data were taken from the table provided by Brillinger et al. (1980).\n##'\n##' The models are discrete delay equations:\n##' \\deqn{R(t+1) \\sim \\mathrm{Poisson}(P N(t-\\tau) \\exp{(-N(t-\\tau)/N_{0})} e(t+1) {\\Delta}t)}{R[t+1] ~ Poisson(P N[t-tau] exp(-N[t-tau]/N0) e[t+1] dt)}\n##' \\deqn{S(t+1) \\sim \\mathrm{Binomial}(N(t),\\exp{(-\\delta \\epsilon(t+1) {\\Delta}t)})}{S[t+1] ~ binomial(N[t],exp(-delta eps[t+1] dt))}\n##' \\deqn{N(t) = R(t)+S(t)}{N[t]=R[t]+S[t]}\n##' where \\eqn{e(t)}{e[t]} and \\eqn{\\epsilon(t)}{eps[t]} are Gamma-distributed i.i.d. random variables\n##' with mean 1 and variances \\eqn{{\\sigma_P^2}/{{\\Delta}t}}{sigma.P^2/dt}, \\eqn{{\\sigma_d^2}/{{\\Delta}t}}{sigma.d^2/dt}, respectively.\n##' \\code{blowflies1} has a timestep (\\eqn{{\\Delta}t}{dt}) of 1 day; \\code{blowflies2} has a timestep of 2 days.\n##' The process model in \\code{blowflies1} thus corresponds exactly to that studied by Wood (2010).\n##' The measurement model in both cases is taken to be\n##' \\deqn{y(t) \\sim  \\mathrm{NegBin}(N(t),1/\\sigma_y^2)}{y[t] ~ negbin(N[t],1/sigma.y^2),}\n##' i.e., the observations are assumed to be negative-binomially distributed with\n##' mean \\eqn{N(t)}{N[t]} and variance \\eqn{N(t)+(\\sigma_y N(t))^2}{N[t]+(sigma.y N[t])^2}.\n##'\n##' Default parameter values are the MLEs as estimated by Ionides (2011).\n##'\n##' @name blowflies\n##' @docType data\n##' @family pomp examples\n##' @family pomp datasets\n##' @include pomp.R\n##' @importFrom utils read.csv2\n##' @importFrom stats approx\n##'\n##' @return\n##' \\code{blowflies1} and \\code{blowflies2} return \\sQuote{pomp} objects containing the actual data and two variants of the model.\n##'\n##' @references\n##'\n##' \\Nicholson1957\n##'\n##' \\Xia2011\n##'\n##' \\Ionides2011\n##'\n##' \\Wood2010\n##'\n##' \\Gurney1980a\n##'\n##' \\Brillinger1980\n##'\n##' @keywords models\n##' @examples\n##'\n##' plot(blowflies1())\n##' plot(blowflies2())\n##'\nNULL\n\n## blowfly model, with general dt\n## here, set up for dt=1 and dt=2\n## dt is hard-coded, and initial values are customized for each dt\n\n## following Xia and Tong, the delay is treated as fixed at 14 days\n## Xia and Tong claim to be using tau=8 bidays, but on inspection\n## their Euler method is really tau=7 bidays\n\n##' @rdname blowflies\n##' @name blowflies1\n##'\n##' @param P reproduction parameter\n##' @param delta death rate\n##' @param N0 population scale factor\n##' @param sigma.P intensity of \\eqn{e} noise\n##' @param sigma.d intensity of \\eqn{eps} noise\n##' @param sigma.y measurement error s.d.\n##'\n##' @export\nblowflies1 <- function (\n  P = 3.2838, delta = 0.16073, N0 = 679.94,\n  sigma.P = 1.3512, sigma.d = 0.74677, sigma.y = 0.026649\n)\n{\n\n  dat <- read.csv2(text=blowfly_dat)\n\n  pomp(\n    data=dat[dat$day>14,],\n    times=\"day\",t0=14,\n    params=c(P=P,delta=delta,N0=N0,\n      sigma.P=sigma.P,sigma.d=sigma.d,sigma.y=sigma.y),\n    cfile=\"blowfly1_source\",\n    compile=FALSE,\n    rprocess=discrete_time(\n      step.fun=Csnippet(\"\n        double *N = &N1;\n        int tau = 14, k;\n        e = rgammawn(sigma_P,dt)/dt;\n        eps = rgammawn(sigma_d,dt)/dt;\n        R = rpois(P*N[tau]*exp(-N[tau]/N0)*dt*e);\n        S = rbinom(N[0],exp(-delta*dt*eps));\n        for (k = tau; k > 0; k--) N[k] = N[k-1];\n        N[0] = R+S;\"\n      ),\n      delta.t=1\n    ),\n    dmeasure=Csnippet(\"\n      double size = 1.0/sigma_y/sigma_y;\n      lik = dnbinom_mu(y,size,N1,give_log);\"\n    ),\n    rmeasure=Csnippet(\"\n      double size = 1.0/sigma_y/sigma_y;\n      y = rnbinom_mu(size,N1);\"\n    ),\n    partrans=parameter_trans(\n      log=c(\"P\",\"delta\",\"N0\",\"sigma.P\",\"sigma.d\",\"sigma.y\")\n    ),\n    paramnames=c(\"P\",\"N0\",\"delta\",\"sigma.P\",\"sigma.d\",\"sigma.y\"),\n    statenames=c(\"N1\",\"R\",\"S\",\"e\",\"eps\"),\n    userdata=list(\n      y.init=with( ## initial data\n        dat,\n        approx(x=day,y=y,xout=seq(from=0,to=14,by=1),rule=2)$y\n      )\n    ),\n    ## y.init=c(948, 948, 942, 930, 911, 885, 858, 833.7, 801, 748.3, 676, 589.8, 504, 434.9, 397),\n    rinit=function (params, t0, y.init, ...) {\n      ntau <- length(y.init)\n      n <- y.init[ntau:1]\n      names(n) <- paste(\"N\",seq_len(ntau),sep=\"\")\n      c(n,R=0,S=0,e=0,eps=0)\n    }\n  )\n\n}\n\n##' @rdname blowflies\n##' @name blowflies2\n##' @export\nblowflies2 <- function (\n  P = 2.7319, delta = 0.17377, N0 = 800.31,\n  sigma.P = 1.442, sigma.d = 0.76033, sigma.y = 0.010846)\n{\n\n  dat <- read.csv2(text=blowfly_dat)\n\n  pomp(\n    data=dat[dat$day>14,],\n    times=\"day\",t0=14,\n    params=c(P=P,delta=delta,N0=N0,\n      sigma.P=sigma.P,sigma.d=sigma.d,sigma.y=sigma.y),\n    cfile=\"blowfly2_source\",\n    compile=FALSE,\n    rprocess=discrete_time(\n      step.fun=Csnippet(\"\n        double *N = &N1;\n        int tau = 7, k;\n        e = rgammawn(sigma_P,dt)/dt;\n        eps = rgammawn(sigma_d,dt)/dt;\n        R = rpois(P*N[tau]*exp(-N[tau]/N0)*dt*e);\n        S = rbinom(N[0],exp(-delta*dt*eps));\n        for (k = tau; k > 0; k--) N[k] = N[k-1];\n        N[0] = R+S;\"\n      ),\n      delta.t=2\n    ),\n    dmeasure=Csnippet(\"\n      double size = 1.0/sigma_y/sigma_y;\n      lik = dnbinom_mu(y,size,N1,give_log);\"\n    ),\n    rmeasure=Csnippet(\"\n      double size = 1.0/sigma_y/sigma_y;\n      y = rnbinom_mu(size,N1);\"\n    ),\n    partrans=parameter_trans(\n      log=c(\"P\",\"delta\",\"N0\",\"sigma.P\",\"sigma.d\",\"sigma.y\")\n    ),\n    userdata=list(\n      y.init=with( ## initial data\n        dat,\n        approx(x=day,y=y,xout=seq(from=0,to=14,by=2),rule=2)$y\n      )\n      ## y.init=c(948, 942, 911, 858, 801, 676, 504, 397),\n    ),\n    paramnames=c(\"P\",\"N0\",\"delta\",\"sigma.P\",\"sigma.d\",\"sigma.y\"),\n    statenames=c(\"N1\",\"R\",\"S\",\"e\",\"eps\"),\n    rinit=function (params, t0, y.init, ...) {\n      ntau <- length(y.init)\n      n <- y.init[ntau:1]\n      names(n) <- paste(\"N\",seq_len(ntau),sep=\"\")\n      c(n,R=0,S=0,e=0,eps=0)\n    }\n  )\n\n}\n\nblowfly_dat <- \"\nday;y\n0;948\n2;942\n4;911\n6;858\n8;801\n10;676\n12;504\n14;397\n16;248\n18;146\n20;1801\n22;6235\n24;5974\n26;8921\n28;6610\n30;5973\n32;5673\n34;3875\n36;2361\n38;1352\n40;1226\n42;912\n44;521\n46;363\n48;229\n50;142\n52;82\n54;542\n56;939\n58;2431\n60;3687\n62;4543\n64;4535\n66;5441\n68;4412\n70;3022\n72;2656\n74;1967\n76;1295\n78;915\n80;551\n82;313\n84;167\n86;95\n88;93\n90;60\n92;68\n94;5259\n96;6673\n98;5441\n100;3987\n102;2952\n104;3648\n106;4222\n108;3889\n110;2295\n112;1509\n114;928\n116;739\n118;566\n120;383\n122;274\n124;192\n126;226\n128;519\n130;1224\n132;2236\n134;3818\n136;6208\n138;5996\n140;5789\n142;6652\n144;7939\n146;4868\n148;3952\n150;2712\n152;1734\n154;1224\n156;703\n158;508\n160;366\n162;279\n164;243\n166;343\n168;761\n170;1025\n172;1221\n174;1600\n176;2267\n178;3290\n180;3471\n182;3637\n184;3703\n186;4876\n188;5364\n190;4890\n192;3029\n194;1950\n196;1225\n198;1076\n200;905\n202;772\n204;628\n206;473\n208;539\n210;825\n212;1702\n214;2868\n216;4473\n218;5221\n220;6592\n222;6400\n224;4752\n226;3521\n228;2719\n230;1931\n232;1500\n234;1082\n236;849\n238;774\n240;864\n242;1308\n244;1624\n246;2224\n248;2423\n250;2959\n252;3547\n254;7237\n256;5218\n258;5311\n260;4273\n262;3270\n264;2281\n266;1549\n268;1091\n270;796\n272;610\n274;445\n276;894\n278;1454\n280;2262\n282;2363\n284;3847\n286;3876\n288;3935\n290;3479\n292;3415\n294;3861\n296;3571\n298;3113\n300;2319\n302;1630\n304;1297\n306;861\n308;761\n310;659\n312;701\n314;762\n316;1188\n318;1778\n320;2428\n322;3806\n324;4519\n326;5646\n328;4851\n330;5374\n332;4713\n334;7367\n336;7236\n338;5245\n340;3636\n342;2417\n344;1258\n346;766\n348;479\n350;402\n352;248\n354;254\n356;604\n358;1346\n360;2342\n362;3328\n364;3599\n366;4081\n368;7643\n370;7919\n372;6098\n374;6896\n376;5634\n378;5134\n380;4188\n382;3469\n384;2442\n386;1931\n388;1790\n390;1722\n392;1488\n394;1416\n396;1369\n398;1666\n\"\n"
  },
  {
    "path": "R/bsflu.R",
    "content": "##' Influenza outbreak in a boarding school\n##'\n##' An outbreak of influenza in an all-boys boarding school.\n##'\n##' Data are recorded from a 1978 flu outbreak in a closed population.\n##' The variable \\sQuote{B} refers to boys confined to bed on the corresponding day and \\sQuote{C} to boys in convalescence,\n##' i.e., not yet allowed back to class.\n##' In total, 763 boys were at risk of infection and, over the course of the outbreak, 512 boys spent between 3 and 7 days away from class (either in bed or convalescent).\n##' The index case was a boy who arrived at school from holiday six days before the next case.\n##' @name bsflu\n##' @rdname bsflu\n##' @family pomp datasets\n##' @seealso \\link[=compartmental_models]{compartmental models}\n##' @references\n##'\n##' \\Anonymous1978\n##'\n##' @example examples/bsflu.R\n##'\nNULL\n"
  },
  {
    "path": "R/bsmc2.R",
    "content": "##' The Liu and West Bayesian particle filter\n##'\n##' Modified version of the Liu & West (2001) algorithm.\n##'\n##' \\code{bsmc2} uses a version of the original algorithm (Liu & West 2001), but discards the auxiliary particle filter.\n##' The modification appears to give superior performance for the same amount of effort.\n##'\n##' Samples from the prior distribution are drawn using the \\code{rprior} component.\n##' This is allowed to depend on elements of \\code{params}, i.e., some of the elements of \\code{params} can be treated as \\dQuote{hyperparameters}.\n##' \\code{Np} draws are made from the prior distribution.\n##'\n##' @name bsmc2\n##' @docType methods\n##' @rdname bsmc2\n##' @aliases bsmc2,missing-method bsmc2,ANY-method\n##' @include pomp_class.R workhorses.R pomp.R plot.R\n##' @family Bayesian methods\n##' @family full-information methods\n##' @family particle filter methods\n##' @family estimation methods\n##' @importFrom mvtnorm rmvnorm\n##' @importFrom stats median cov\n##' @inheritParams pfilter\n##' @inheritParams pomp\n##' @param smooth Kernel density smoothing parameter.\n##' The compensating shrinkage factor will be \\code{sqrt(1-smooth^2)}.\n##' Thus, \\code{smooth=0} means that no noise will be added to parameters.\n##' The general recommendation is that the value of \\code{smooth} should be chosen close to 0 (e.g., \\code{shrink} ~ 0.1).\n##' @return\n##' An object of class \\sQuote{bsmcd_pomp}.\n##' The following methods are avaiable:\n##' \\describe{\n##' \\item{\\code{\\link[=plot,bsmcd_pomp-method]{plot}}}{produces diagnostic plots}\n##' \\item{\\code{\\link{as.data.frame}}}{puts the prior and posterior samples into a data frame}\n##' }\n##' @inheritSection pomp Note for Windows users\n##' @author Michael Lavine, Matthew Ferrari, Aaron A. King, Edward L. Ionides\n##' @references\n##'\n##' \\Liu2001b\nNULL\n\n## In annotation, L&W AGM == Liu & West \"A General Algorithm\"\n##\n## params = the initial particles for the parameter values;\n##          these should be drawn from the prior distribution for the parameters\n## est = names of parameters to estimate; other parameters are not updated.\n## smooth = parameter 'h' from AGM\n\nsetClass(\n  \"bsmcd_pomp\",\n  contains=\"pomp\",\n  slots=c(\n    post=\"array\",\n    prior=\"array\",\n    est=\"character\",\n    eff.sample.size=\"numeric\",\n    smooth=\"numeric\",\n    cond.log.evidence=\"numeric\",\n    log.evidence=\"numeric\"\n  )\n)\n\nsetGeneric(\n  \"bsmc2\",\n  function (data, ...)\n    standardGeneric(\"bsmc2\")\n)\n\nsetMethod(\n  \"bsmc2\",\n  signature=signature(data=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"bsmc2\",\"data\")\n  }\n)\n\nsetMethod(\n  \"bsmc2\",\n  signature=signature(data=\"ANY\"),\n  definition=function (data, ...) {\n    undef_method(\"bsmc2\",data)\n  }\n)\n\n##' @rdname bsmc2\n##' @export\nsetMethod(\n  \"bsmc2\",\n  signature=signature(data=\"data.frame\"),\n  definition = function (\n    data,\n    ...,\n    Np, smooth = 0.1,\n    params, rprior, rinit, rprocess, dmeasure, partrans,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      bsmc2_internal(\n        data,\n        ...,\n        Np=Np,\n        smooth=smooth,\n        params=params,\n        rprior=rprior,\n        rinit=rinit,\n        rprocess=rprocess,\n        dmeasure=dmeasure,\n        partrans=partrans,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"bsmc2\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname bsmc2\n##' @export\nsetMethod(\n  \"bsmc2\",\n  signature=signature(data=\"pomp\"),\n  definition = function (\n    data,\n    ...,\n    Np, smooth = 0.1,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      bsmc2_internal(\n        data,\n        ...,\n        Np=Np,\n        smooth=smooth,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"bsmc2\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname plot\n##' @param thin integer; when the number of samples is very large, it can be helpful to plot a random subsample:\n##' \\code{thin} specifies the size of this subsample.\n##' @export\nsetMethod(\n  \"plot\",\n  signature=signature(x=\"bsmcd_pomp\"),\n  definition=function (x, pars, thin, ...) {\n    if (missing(pars)) pars <- x@est\n    pars <- as.character(pars)\n    if (length(pars)<1) pStop(who=\"plot\",\"no parameters to plot.\")\n    if (missing(thin)) thin <- Inf\n    bsmc_plot(\n      prior=partrans(x,x@prior,dir=\"fromEst\"),\n      post=partrans(x,x@post,dir=\"fromEst\"),\n      pars=pars,\n      thin=thin,\n      ...\n    )\n  }\n)\n\nbsmc2_internal <- function (\n  object,\n  ...,\n  Np, smooth,\n  verbose, .gnsi = TRUE\n) {\n\n  verbose <- as.logical(verbose)\n\n  object <- pomp(object,...,verbose=verbose)\n\n  if (undefined(object@rprior) || undefined(object@rprocess) || undefined(object@dmeasure))\n    pStop_(paste(sQuote(c(\"rprior\",\"rprocess\",\"dmeasure\")),collapse=\", \"),\" are needed basic components.\")\n\n  gnsi <- as.logical(.gnsi)\n\n  ntimes <- length(time(object))\n\n  Np <- np_check(Np,ntimes+1)\n\n  params <- parmat(coef(object),Np[1L])\n\n  if (!is.numeric(smooth) || length(smooth) != 1 || (!is.finite(smooth)) ||\n        (smooth>1) || (smooth<=0))\n    pStop_(sQuote(\"smooth\"),\" must be a scalar in (0,1]\")\n  smooth <- as.numeric(smooth)\n\n  hsq <- smooth^2             #  see Liu & West eq(10.3.12)\n  shrink <- sqrt(1-hsq)       #  'a' parameter of Liu & West\n\n  pompLoad(object,verbose=verbose)\n  on.exit(pompUnload(object,verbose=verbose))\n\n  params <- rprior(object,params=params,.gnsi=gnsi)\n\n  paramnames <- rownames(params)\n  prior <- params\n\n  times <- time(object,t0=TRUE)\n  x <- rinit(object,params=params,.gnsi=gnsi)\n\n  params <- partrans(object,params,dir=\"toEst\",.gnsi=gnsi)\n\n  estind <- which(apply(params,1L,\\(x)diff(range(x))>0))\n  est <- paramnames[estind]\n  nest <- length(est)\n  if (nest < 1) pStop_(\"no parameters to estimate\")\n\n  evidence <- as.numeric(rep(NA,ntimes))\n  eff.sample.size <- as.numeric(rep(NA,ntimes))\n\n  for (nt in seq_len(ntimes)) {\n\n    ## calculate particle means ; as per L&W AGM (1)\n    params.mean <- apply(params,1L,mean)\n    ## calculate particle covariances : as per L&W AGM (1)\n    params.var  <- cov(t(params[estind,,drop=FALSE]))\n\n    if (verbose) {\n      cat(\"at step \",nt,\" (time = \",times[nt+1],\")\\n\",sep=\"\")\n      print(\n        rbind(\n          prior.mean=params.mean[estind],\n          prior.sd=sqrt(diag(params.var))\n        )\n      )\n    }\n\n    m <- shrink*params[estind,]+(1-shrink)*params.mean[estind]\n\n    ## sample new parameter vector as per L&W AGM (3) and Liu & West eq(3.2)\n    pert <- tryCatch(\n      rmvnorm(n=Np[nt],mean=rep(0,nest),sigma=hsq*params.var,method=\"svd\"),\n      error = function (e)\n        pStop(who=\"rmvnorm\",conditionMessage(e))\n    )\n\n    if (!all(is.finite(pert))) pStop_(\"extreme particle depletion\") #nocov\n\n    params[estind,] <- m+t(pert)\n\n    tparams <- partrans(object,params,dir=\"fromEst\",.gnsi=gnsi)\n\n    xpred <- rprocess(object,x0=x,t0=times[nt],times=times[nt+1],\n      params=tparams,.gnsi=gnsi)\n\n    ## evaluate log likelihood of observation given xpred\n    weights <- dmeasure(object,y=object@data[,nt,drop=FALSE],x=xpred,\n      times=times[nt+1],params=tparams,log=TRUE,.gnsi=gnsi)\n    gnsi <- FALSE  ## all native symbols have been looked up\n\n    ## the following is triggered by the first illegal weight value\n    xx <- vapply(\n      as.numeric(weights),\n      function (x) is.finite(x)||isTRUE(x==-Inf),\n      logical(1L)\n    )\n    if (!all(xx)) {\n      xx <- which(!xx)[1L]\n      illegal_dmeasure_error(\n        time=times[nt+1],\n        loglik=weights[xx],\n        datvals=object@data[,nt],\n        states=xpred[,xx,1L],\n        params=tparams[,xx]\n      )\n    }\n\n    x[,] <- xpred\n\n    dim(weights) <- NULL\n    evidence[nt] <- lmw <- logmeanexp(weights)\n    weights <- exp(weights-lmw)\n    weights <- weights/sum(weights)\n    ## compute effective sample-size\n    eff.sample.size[nt] <- 1/crossprod(weights)\n\n    if (verbose)\n      cat(\"effective sample size =\",round(eff.sample.size[nt],1),\"\\n\")\n\n    ## Matrix with samples (columns) from filtering distribution theta.t | Y.t\n    smp <- systematic_resample(weights,Np[nt+1])\n    x <- x[,smp,drop=FALSE]\n    params <- params[,smp,drop=FALSE]\n\n  }\n\n  ## replace parameters with point estimate (posterior median)\n  coef(object,transform=TRUE) <- apply(params,1L,median)\n\n  new(\n    \"bsmcd_pomp\",\n    object,\n    post=partrans(object,params,dir=\"fromEst\",.gnsi=gnsi),\n    prior=prior,\n    est=as.character(est),\n    eff.sample.size=eff.sample.size,\n    smooth=smooth,\n    cond.log.evidence=evidence,\n    log.evidence=sum(evidence)\n  )\n\n}\n\nbsmc_plot <- function (prior, post, pars, thin, ...) {\n  p1 <- sample.int(n=ncol(prior),size=min(thin,ncol(prior)))\n  p2 <- sample.int(n=ncol(post),size=min(thin,ncol(post)))\n  if (!all(pars %in% rownames(prior))) {\n    missing <- which(!(pars%in%rownames(prior)))\n    pStop(who=\"plot\",\"unrecognized parameters: \",paste(sQuote(pars[missing]),collapse=\",\"))\n  }\n  prior <- t(prior[pars,,drop=FALSE])\n  post <- t(post[pars,,drop=FALSE])\n  all <- rbind(prior,post)\n\n  scplot <- function (x, y, ...) { ## prior, posterior pairwise scatterplot\n    op <- par(new=TRUE)\n    on.exit(par(op))\n    i <- which(x[1L]==all[1L,])\n    j <- which(y[1L]==all[1L,])\n    points(prior[p1,i],prior[p1,j],pch=20,col=rgb(0.85,0.85,0.85,0.1),\n      xlim=range(all[,i]),ylim=range(all[,j]))\n    points(post[p2,i],post[p2,j],pch=20,col=rgb(0,0,1,0.01))\n  }\n\n  dplot <- function (x, ...) { ## marginal posterior histogram\n    i <- which(x[1L]==all[1L,])\n    d1 <- density(prior[,i])\n    d2 <- density(post[,i])\n    usr <- par(\"usr\")\n    op <- par(usr=c(usr[c(1L,2L)],0,1.5*max(d1$y,d2$y)))\n    on.exit(par(op))\n    polygon(d1,col=rgb(0.85,0.85,0.85,0.5))\n    polygon(d2,col=rgb(0,0,1,0.5))\n  }\n\n  if (length(pars) > 1) {\n    pairs(all,labels=pars,panel=scplot,diag.panel=dplot)\n  }  else {\n    d1 <- density(prior[,1])\n    d2 <- density(post[,1])\n    usr <- par(\"usr\")\n    op <- par(usr=c(usr[c(1L,2L)],0,1.5*max(d1$y,d2$y)))\n    on.exit(par(op))\n    plot(range(all[,1]),range(c(0,d1$y,d2$y)),type='n',\n      xlab=pars,ylab=\"density\")\n    polygon(d1,col=rgb(0.85,0.85,0.85,0.5))\n    polygon(d2,col=rgb(0,0,1,0.5))\n  }\n}\n"
  },
  {
    "path": "R/bsplines.R",
    "content": "##' B-spline bases\n##'\n##' These functions generate B-spline basis functions.\n##' \\code{bspline_basis} gives a basis of spline functions.\n##' \\code{periodic_bspline_basis} gives a\n##' basis of periodic spline functions.\n##'\n##' @name bsplines\n##' @rdname bsplines\n##' @concept splines\n##' @family interpolation\n##'\n##' @param x Vector at which the spline functions are to be evaluated.\n##' @param rg numeric of length 2; range of the B-spline basis.\n##' To be properly specified, we must have \\code{rg[1] < rg[2]}.\n##' @param nbasis The number of basis functions to return.\n##' @param degree Degree of requested B-splines.\n##' @param period The period of the requested periodic B-splines.\n##' @param deriv The order of the derivative required.\n##' @param names optional; the names to be given to the basis functions.  These\n##' will be the column-names of the matrix returned.  If the names are\n##' specified as a format string (e.g., \"basis\\%d\"), \\code{\\link{sprintf}} will\n##' be used to generate the names from the column number.  If a single\n##' non-format string is specified, the names will be generated by\n##' \\code{\\link{paste}}-ing \\code{name} to the column number.  One can also\n##' specify each column name explicitly by giving a length-\\code{nbasis} string\n##' vector.  By default, no column-names are given.\n##'\n##' @return\n##' \\item{bspline_basis}{ Returns a matrix with \\code{length(x)} rows\n##' and \\code{nbasis} columns.  Each column contains the values one of the\n##' spline basis functions.}\n##' \\item{periodic_bspline_basis}{ Returns a matrix with \\code{length(x)} rows\n##' and \\code{nbasis} columns.  The basis functions returned are periodic with\n##' period \\code{period}.}\n##' If \\code{deriv>0}, the derivative of that order of each of the corresponding spline basis functions are returned.\n##'\n##' @section C API:\n##' Access to the underlying C routines is available: see\n##' \\href{https://kingaa.github.io/pomp/C_API.html}{the \\pkg{pomp} C API document}.\n##' for definition and documentation of the C API.\n##'\n##' @author Aaron A. King\n##'\n##' @keywords smooth\n##' @examples\n##'\n##' x <- seq(0,2,by=0.01)\n##' y <- bspline_basis(x,degree=3,nbasis=9,names=\"basis\")\n##' matplot(x,y,type='l',ylim=c(0,1.1))\n##' lines(x,apply(y,1,sum),lwd=2)\n##'\n##' x <- seq(-1,2,by=0.01)\n##' y <- periodic_bspline_basis(x,nbasis=5,names=\"spline%d\")\n##' matplot(x,y,type='l')\n##'\nNULL\n\n##' @rdname bsplines\n##' @export\nbspline_basis <- function (x, nbasis, degree = 3, deriv = 0, names = NULL, rg = range(x)) {\n  rg <- as.numeric(rg)\n  y <- tryCatch(\n    .Call(P_bspline_basis,rg,x,nbasis,degree,deriv),\n    error = function (e) {\n      pStop(who=\"bspline_basis\",conditionMessage(e))\n    }\n  )\n  if (deriv > degree)\n    pWarn(\"returning 0 since \",sQuote(\"deriv\"),\" > \",sQuote(\"degree\"))\n  if (!is.null(names)) {\n    if (length(names)==1) {\n      if (!grepl(\"%\",names)) {\n        names <- paste0(names,\".%d\")\n      }\n      colnames(y) <- sprintf(names,seq_len(nbasis))\n    } else if (length(names)==nbasis) {\n      colnames(y) <- names\n    } else {\n      pStop(sQuote(\"names\"),\" must be of length 1 or \",nbasis)\n    }\n  }\n  y\n}\n\n##' @rdname bsplines\n##' @export\nperiodic_bspline_basis <- function (x, nbasis, degree = 3, period = 1,\n  deriv = 0, names = NULL) {\n  y <- tryCatch(\n    .Call(P_periodic_bspline_basis,x,nbasis,degree,period,deriv),\n    error = function (e) {\n      pStop(who=\"periodic_bspline_basis\",conditionMessage(e))\n    }\n  )\n  if (deriv > degree)\n    pWarn(\"returning 0 since \",sQuote(\"deriv\"),\" > \",sQuote(\"degree\"))\n  if (!is.null(names)) {\n    if (length(names)==1) {\n      if (!grepl(\"%\",names)) {\n        names <- paste0(names,\".%d\")\n      }\n      colnames(y) <- sprintf(names,seq_len(nbasis))\n    } else if (length(names)==nbasis) {\n      colnames(y) <- names\n    } else {\n      pStop(sQuote(\"names\"),\" must be of length 1 or \",nbasis)\n    }\n  }\n  y\n}\n"
  },
  {
    "path": "R/builder.R",
    "content": "##' Hitching C snippets and R functions to pomp_fun objects\n##'\n##' The algorithms in \\pkg{pomp} are formulated using \\R functions that access the \\link[=basic_components]{basic model components}\n##' (\\code{rprocess}, \\code{dprocess}, \\code{rmeasure}, \\code{dmeasure}, etc.).\n##' For short, we refer to these elementary functions as \\dQuote{\\link{workhorses}}.\n##' In implementing a model, the user specifies basic model components\n##' using functions, procedures in dynamically-linked libraries, or C snippets.\n##' Each component is then packaged into a \\sQuote{pomp_fun} objects, which gives a uniform interface.\n##' The construction of \\sQuote{pomp_fun} objects is handled by the \\code{hitch} function,\n##' which conceptually \\dQuote{hitches} the workhorses to the user-defined procedures.\n##' @name hitch\n##' @docType methods\n##' @include pomp_class.R csnippet.R safecall.R templates.R pomp_fun.R\n##' @importFrom digest digest\n##' @importFrom stats runif\n##' @param \\dots named arguments representing the user procedures to be hitched.\n##' These can be functions, character strings naming routines in external, dynamically-linked libraries, C snippets, or \\code{NULL}.\n##' The first three are converted by \\code{hitch} to \\sQuote{pomp_fun} objects which perform the indicated computations.\n##' \\code{NULL} arguments are translated to default \\sQuote{pomp_fun} objects.\n##' If any of these procedures are already \\sQuote{pomp_fun} objects, they are returned unchanged.\n##' @param templates named list of templates.\n##' Each workhorse must have a corresponding template.\n##' See \\code{pomp:::workhorse_templates} for a list.\n##' @param obsnames,statenames,paramnames,covarnames character vectors\n##' specifying the names of observable variables, latent state variables, parameters, and covariates, respectively.\n##' These are only needed if one or more of the horses are furnished as C snippets.\n##' @param PACKAGE optional character;\n##' the name (without extension) of the external, dynamically loaded library in which any native routines are to be found.\n##' This is only useful if one or more of the model components has been specified using a precompiled dynamically loaded library;\n##' it is not used for any component specified using C snippets.\n##' \\code{PACKAGE} can name at most one library.\n##' @param globals optional character or C snippet;\n##' arbitrary C code that will be hard-coded into the shared-object library created when C snippets are provided.\n##' If no C snippets are used, \\code{globals} has no effect.\n##' @param on_load optional character or C snippet:\n##' arbitrary C code that will be executed when the C snippet file is loaded.\n##' If no C snippets are used, \\code{on_load} has no effect.\n##' @param cdir optional character variable.\n##' \\code{cdir} specifies the name of the directory within which C snippet code will be compiled.\n##' By default, this is in a temporary directory specific to the \\R session.\n##' One can also set this directory using the \\code{pomp_cdir} global option.\n##' @param cfile optional character variable.\n##' \\code{cfile} gives the name of the file (in directory \\code{cdir}) into which C snippet codes will be written.\n##' By default, a random filename is used.\n##' If the chosen filename would result in over-writing an existing file, an error is generated.\n##' @param shlib.args optional character variables.\n##' Command-line arguments to the \\code{R CMD SHLIB} call that compiles the C snippets.\n##' One can, for example, specify libraries against which the C snippets are to be linked.\n##' In doing so, take care to make sure the appropriate header files are available to the C snippets, e.g., using the \\code{globals} argument.\n##' See \\code{\\link{Csnippet}} for more information.\n##' @param compile logical;\n##' if \\code{FALSE}, compilation of the C snippets will be postponed until they are needed.\n##' @param verbose logical.\n##' Setting \\code{verbose=TRUE} will cause additional information to be displayed.\n##' @return\n##' \\code{hitch} returns a named list of length two.  The element named\n##' \\dQuote{funs} is itself a named list of \\sQuote{pomp_fun} objects, each of\n##' which corresponds to one of the horses passed in.  The element named\n##' \\dQuote{lib} contains information on the shared-object library created\n##' using the C snippets (if any were passed to \\code{hitch}).  If no C\n##' snippets were passed to \\code{hitch}, \\code{lib} is \\code{NULL}.\n##' Otherwise, it is a length-3 named list with the following elements:\n##' \\describe{\n##' \\item{name}{The name of the library created.}\n##' \\item{dir}{ The\n##' directory in which the library was created.  If this is \\code{NULL}, the\n##' library was created in the session's temporary directory.  }\n##' \\item{src}{ A\n##' character string with the full contents of the C snippet file.  } }\n##' @author Aaron A. King\n##' @seealso \\code{\\link{pomp}}, \\code{\\link{spy}}\n##' @concept extending the pomp package\n##' @concept low-level interface\n##'\nNULL\n\n## 'hitch' takes (as '...') the workhorse specifications (as R functions or\n## C snippets, processes these, and hitches them to 'pomp_fun' objects\n## suitable for use in the appropriate slots in 'pomp' objects.\n\n##' @rdname hitch\n##' @export\nhitch <- function (..., templates,\n  obsnames, statenames, paramnames, covarnames,\n  PACKAGE, globals, cfile, cdir = getOption(\"pomp_cdir\", NULL),\n  on_load, shlib.args, compile = TRUE,\n  verbose = getOption(\"verbose\", FALSE)) {\n\n  if (missing(templates))\n    pStop(sQuote(\"templates\"),\" must be supplied.\")\n\n  if (missing(cfile)) cfile <- NULL\n  if (missing(cdir)) cdir <- NULL\n  if (missing(PACKAGE)) PACKAGE <- NULL\n  if (missing(globals)) globals <- NULL\n  if (missing(on_load)) on_load <- NULL\n  if (missing(shlib.args)) shlib.args <- NULL\n  PACKAGE <- as.character(PACKAGE)\n  compile <- as.logical(compile)\n\n  ## defaults for names of states, parameters, observations, and covariates\n  if (missing(statenames)) statenames <- NULL\n  if (missing(paramnames)) paramnames <- NULL\n  if (missing(obsnames)) obsnames <- NULL\n  if (missing(covarnames)) covarnames <- NULL\n\n  statenames <- as.character(statenames)\n  paramnames <- as.character(paramnames)\n  obsnames <- as.character(obsnames)\n  covarnames <- as.character(covarnames)\n\n  if (anyDuplicated(c(statenames,paramnames,obsnames,covarnames))) {\n    pStop(\"the variable names in \",sQuote(\"statenames\"),\", \",\n      sQuote(\"paramnames\"),\", \",sQuote(\"covarnames\"),\n      \", and \",sQuote(\"obsnames\"),\" must be unique and disjoint.\")\n  }\n\n  horses <- list(...)\n  snippets <- horses[vapply(horses,is,logical(1),\"Csnippet\")]\n  snippets <- lapply(snippets,slot,\"text\")\n\n  if (length(snippets) > 0) {\n    lib <- tryCatch(\n      do.call(\n        Cbuilder,\n        c(\n          list(\n            templates=templates,\n            dir=cdir,\n            name=cfile,\n            obsnames=obsnames,\n            statenames=statenames,\n            paramnames=paramnames,\n            covarnames=covarnames,\n            globals=globals,\n            on_load=on_load,\n            shlib.args=shlib.args,\n            compile=compile,\n            verbose=verbose\n          ),\n          snippets\n        )\n      ),\n      error = function (e)\n        pStop_(\"error in building shared-object library from C snippets: \",conditionMessage(e)) #nocov\n    )\n    libname <- lib$name\n  } else {\n    libname <- \"\"\n    lib <- NULL\n  }\n\n  funs <- vector(mode=\"list\",length=length(horses))\n  names(funs) <- names(horses)\n\n  for (s in names(funs)) {\n    funs[[s]] <- pomp_fun(\n      f=horses[[s]],\n      slotname=templates[[s]]$slotname,\n      PACKAGE=PACKAGE,\n      proto=templates[[s]]$proto,\n      Cname=templates[[s]]$Cname,\n      libname=libname,\n      statenames=statenames,\n      paramnames=paramnames,\n      obsnames=obsnames,\n      covarnames=covarnames\n    )\n  }\n\n  list(funs=funs,lib=lib)\n}\n\nCbuilder <- function (..., templates, name = NULL, dir = NULL,\n  statenames, paramnames, covarnames, obsnames,\n  globals, on_load, shlib.args = NULL, compile,\n  verbose = getOption(\"verbose\",FALSE))\n{\n\n  name <- cleanForC(name)\n  statenames <- cleanForC(statenames)\n  paramnames <- cleanForC(paramnames)\n  covarnames <- cleanForC(covarnames)\n  obsnames <- cleanForC(obsnames)\n\n  globals <- as(globals,\"character\")\n  on_load <- as(on_load,\"character\")\n\n  snippets <- list(...)\n\n  ## 'registry' holds a list of functions to register\n  registry <- c(\"__pomp_load_stack_incr\",\"__pomp_load_stack_decr\")\n  ## which utilities are needed?\n  utils <- which(\n    vapply(\n      seq_along(pomp_templates$utilities),\n      \\(x) any(\n             grepl(\n               pomp_templates$utilities[[x]]$trigger,\n               c(snippets,on_load),\n               perl=TRUE\n             )\n           ),\n      logical(1L)\n    )\n  )\n\n  ## rely on \"-I\" flags under *nix\n  if (.Platform$OS.type==\"unix\") {\n    pompheader <- \"pomp.h\"\n  } else {\n    pompheader <- system.file(\"include/pomp.h\",package=\"pomp\") #nocov\n  }\n\n  ## some information to help make file (and filename) unique\n  timestamp <- format(Sys.time(),\"%Y-%m-%d %H:%M:%OS3 %z\")\n  salt <- paste(format(as.hexmode(ceiling(runif(n=4L,max=2^24))),\n    upper.case=TRUE),collapse=\"\")\n\n  ## string 'csrc' will hold the full C source code\n  csrc <- \"\"\n  out <- textConnection(object=\"csrc\",open=\"w\",local=TRUE)\n\n  cat(file=out,render(pomp_templates$file$header,\n    pompheader=pompheader,timestamp=timestamp,salt=salt),\"\\n\")\n\n  cat(file=out,globals,\"\\n\\n\")\n\n  for (u in utils)\n    cat(file=out,pomp_templates$utilities[[u]]$header)\n\n  ## now we write the snippets, using the templates provided\n  for (snip in names(snippets)) {\n    ## we add each 'Cname' to the 'registry'\n    registry <- c(registry,templates[[snip]]$Cname)\n    ## define variables\n    cat(file=out,render(\"\\n\\n/* C snippet: '{%snip%}' */\\n\",snip=snip))\n    for (k in seq_along(templates[[snip]]$vars)) {\n      vtpl <- templates[[snip]]$vars[[k]]\n      nm <- eval(vtpl$names)\n      for (v in seq_along(nm)) {\n        cat(\n          file=out,\n          render(\n            pomp_templates$define,\n            variable=nm[v],\n            cref=render(vtpl$cref,v=v-1)\n          ))\n      }\n    }\n    ## render the C snippet in context\n    cat(file=out,\"\\n\",render(templates[[snip]]$header),\n      snippets[[snip]],templates[[snip]]$footer,\"\\n\")\n    ## undefine variables\n    for (k in seq_along(templates[[snip]]$vars)) {\n      vtpl <- templates[[snip]]$vars[[k]]\n      nm <- eval(vtpl$names)\n      for (v in nm) {\n        cat(file=out,render(pomp_templates$undefine,variable=v))\n      }\n    }\n  }\n\n  ## load/unload stack handling codes\n  cat(file=out,pomp_templates$stackhandling,\"\\n\")\n\n  ## registration\n  cat(file=out,\"\\n\",render(pomp_templates$registration$header))\n  for (v in utils)\n    cat(file=out,pomp_templates$utilities[[v]]$reg)\n  for (v in registry)\n    cat(file=out,render(pomp_templates$registration$main,fun=v))\n  cat(file=out,\"\\n\",on_load,\"\\n\") # code to be executed at library load\n  cat(file=out,pomp_templates$registration$footer,\"\\n\")\n\n  close(out)\n\n  csrc <- paste(csrc,collapse=\"\\n\")\n\n  if (length(name)==0)\n    name <- paste0(\"pomp_\",digest(csrc,serialize=FALSE))\n\n  csrc <- render(csrc,name=name)\n\n  tryCatch(\n    pompCompile(\n      fname=name,\n      direc=srcDir(dir,verbose=verbose),\n      src=csrc,\n      shlib.args=shlib.args,\n      compile=compile,\n      verbose=verbose\n    ),\n    error = function (e)\n      pStop(who=\"Cbuilder\",\"compilation error: \",conditionMessage(e)) #nocov\n  )\n\n  invisible(list(name=name,dir=dir,src=csrc))\n}\n\npompCompile <- function (fname, direc, src, shlib.args = NULL,\n  compile = TRUE, verbose) {\n\n  stem <- file.path(direc,fname)\n  if (.Platform$OS.type==\"windows\")\n    stem <- gsub(\"\\\\\",\"/\",stem,fixed=TRUE) #nocov\n\n  modelfile <- paste0(stem,\".c\")\n\n  tryCatch(\n    cat(src,file=modelfile),\n    error = function (e) {\n      pStop_(\"cannot write file \",sQuote(modelfile))   #nocov\n    }\n  )\n\n  if (verbose) cat(\"model codes written to\",sQuote(modelfile),\"\\n\")\n\n  cflags <- Sys.getenv(\"PKG_CPPFLAGS\")\n  cflags <- paste0(\"PKG_CPPFLAGS=\\\"\",\n    if (nchar(cflags)>0) paste0(cflags,\" \") else \"\",\n    \"-I\",shQuote(system.file(\"include\",package=\"pomp\")),\n    \" -I\",shQuote(getwd()),\"\\\"\")\n\n  shlib.args <- as.character(shlib.args)\n\n  solib <- paste0(stem,.Platform$dynlib.ext)\n\n  if (compile) {\n\n    if (verbose) cat(\"compiling\",sQuote(solib),\"\\n\")\n\n    tryCatch(\n    {\n      rv <- system2(\n        command=R.home(\"bin/R\"),\n        args=c(\"CMD\",\"SHLIB\",\"-c\",\"-o\",solib,modelfile,shlib.args),\n        env=cflags,\n        wait=TRUE,\n        stdout=TRUE,\n        stderr=TRUE\n      )\n    },\n    error = function (e) pStop_(\"error compiling C snippets: \",conditionMessage(e)) #nocov\n    )\n\n    stat <- as.integer(attr(rv,\"status\"))\n\n    if (length(stat) > 0 && stat != 0L) {\n      pStop_(\"cannot compile shared-object library \",sQuote(solib),          #nocov\n        \": status = \",stat,\"\\ncompiler messages:\\n\",paste(rv,collapse=\"\\n\")) #nocov\n    } else if (verbose) {\n      cat(\"compiler messages:\",rv,sep=\"\\n\")\n    }\n\n  }\n\n  invisible(solib)\n}\n\nsrcDir <- function (dir, verbose) {\n  if (is.null(dir)) {\n    dir <- file.path(tempdir(),Sys.getpid())\n  }\n  if (!dir.exists(dir)) {\n    if (verbose) cat(\"creating C snippet directory \",sQuote(dir),\"\\n\") #nocov\n    tryCatch(\n    {\n      dir.create(dir,recursive=TRUE,showWarnings=FALSE,mode=\"0700\")\n      stopifnot(dir.exists(dir))\n    },\n    error = function (e) pStop_(\"cannot create cache directory \",sQuote(dir))   #nocov\n    )\n  }\n  dir\n}\n\ncleanForC <- function (text) {\n  text <- as.character(text)\n  text <- gsub(\"\\\\.\",\"_\",text)\n  text <- gsub(\"-\",\"_\",text)\n  text\n}\n\nrender <- function (template, ...) {\n  vars <- list(...)\n  if (length(vars)==0) return(template)\n  n <- vapply(vars,length,integer(1L))\n  if (!all((n==max(n))|(n==1)))\n    pStop(\"incommensurate lengths of replacements.\") #nocov\n  short <- which(n==1)\n  n <- max(n)\n  for (i in short) vars[[i]] <- rep(vars[[i]],n)\n\n  retval <- vector(mode=\"list\",length=n)\n  for (i in seq_len(n)) {\n    tpl <- template\n    for (v in names(vars)) {\n      src <- sprintf(\"\\\\{%%%s%%\\\\}\",v)\n      tgt <- vars[[v]][i]\n      tpl <- gsub(src,tgt,tpl)\n    }\n    retval[[i]] <- tpl\n  }\n  do.call(paste0,retval)\n}\n"
  },
  {
    "path": "R/childhood.R",
    "content": "##' Historical childhood disease incidence data\n##'\n##' @description\n##' \\code{LondonYorke} is a data frame containing the monthly number of reported cases of chickenpox, measles, and mumps from two American cities (Baltimore and New York) in the mid-20th century (1928--1972).\n##'\n##' \\code{ewmeas} and \\code{ewcitmeas} are data frames containing weekly reported cases of measles in England and Wales.\n##' \\code{ewmeas} records the total measles reports for the whole country, 1948--1966.\n##' One questionable data point has been replaced with an NA.\n##' \\code{ewcitmeas} records the incidence in seven English cities 1948--1987.\n##' These data were kindly provided by Ben Bolker, who writes:\n##' \\dQuote{Most of these data have been manually entered from published records by various people, and are prone to errors at several levels.\n##' All data are provided as is; use at your own risk.}\n##'\n##' @name childhood_disease_data\n##' @rdname childhood\n##' @aliases LondonYorke ewmeas ewcitmeas\n##' @docType data\n##' @seealso \\link[=compartmental_models]{compartmental models}, \\code{\\link{bsflu}}\n##' @references\n##'\n##' \\London1973\n##'\n##' @family pomp datasets\n##' @family pomp examples\n##'\n##' @examples\n##'\n##' plot(cases~time,data=LondonYorke,subset=disease==\"measles\",type='n',main=\"measles\",bty='l')\n##' lines(cases~time,data=LondonYorke,subset=disease==\"measles\"&town==\"Baltimore\",col=\"red\")\n##' lines(cases~time,data=LondonYorke,subset=disease==\"measles\"&town==\"New York\",col=\"blue\")\n##' legend(\"topright\",legend=c(\"Baltimore\",\"New York\"),lty=1,col=c(\"red\",\"blue\"),bty='n')\n##'\n##' plot(\n##'      cases~time,\n##'      data=LondonYorke,\n##'      subset=disease==\"chickenpox\"&town==\"New York\",\n##'      type='l',col=\"blue\",main=\"chickenpox, New York\",\n##'      bty='l'\n##'     )\n##'\n##' plot(\n##'      cases~time,\n##'      data=LondonYorke,\n##'      subset=disease==\"mumps\"&town==\"New York\",\n##'      type='l',col=\"blue\",main=\"mumps, New York\",\n##'      bty='l'\n##'     )\n##'\n##' plot(reports~time,data=ewmeas,type='l')\n##'\n##' plot(reports~date,data=ewcitmeas,subset=city==\"Liverpool\",type='l')\n##'\nNULL\n"
  },
  {
    "path": "R/coef.R",
    "content": "##' Extract, set, or alter coefficients\n##'\n##' Extract, set, or modify the estimated parameters from a fitted model.\n##'\n##' @name coef\n##' @rdname coef\n##' @aliases coef<- coef<-,missing-method\n##' @docType methods\n##' @include pomp_class.R listie.R\n##' @family extraction methods\nNULL\n\n##' @importFrom stats coef\nsetGeneric(\"coef\")\n\nsetGeneric(\n  \"coef<-\",\n  function (object, ..., value)\n    standardGeneric(\"coef<-\")\n)\n\nsetMethod(\n  \"coef<-\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"coef<-\",\"object\") #nocov\n  }\n)\n\n##' @rdname coef\n##' @export\nsetMethod(\n  \"coef\",\n  signature=signature(object=\"listie\"),\n  definition=function(object, ...) {\n    x <- do.call(cbind,lapply(object,coef,...))\n    names(dimnames(x)) <- c(\"name\",\".id\")\n    x\n  }\n)\n\n##' @rdname coef\n##' @param object an object of class \\sQuote{pomp}, or of a class extending \\sQuote{pomp}\n##' @param pars optional character; names of parameters to be retrieved or set.\n##' @param transform logical; perform parameter transformation?\n##' @param \\dots ignored or passed to the more primitive function\n##'\n##' @details\n##' \\code{coef} allows one to extract the parameters from a fitted model.\n##'\n##' \\code{coef(object,transform=TRUE)} returns the parameters transformed onto\n##' the estimation scale.\n##' @export\nsetMethod(\n  \"coef\",\n  signature=signature(object=\"pomp\"),\n  definition=function (object, pars, transform = FALSE, ...) {\n    if (length(object@params)>0) {\n      if (transform)\n        params <- partrans(object,params=object@params,...,dir=\"toEst\")\n      else\n        params <- object@params\n      if (missing(pars))\n        pars <- names(params)\n      else {\n        excl <- setdiff(pars,names(params))\n        nexcl <- length(excl)\n        if (nexcl > 0) {\n          pStop(who=\"coef\",\"name\",ngettext(nexcl,\" \",\"s \"),\n            paste(sQuote(excl),collapse=\",\"),\n            \" correspond\",ngettext(nexcl,\"s\",\"\"),\n            \" to no parameter\",ngettext(nexcl,\".\",\"s.\"))\n        }\n      }\n      params[pars]\n    } else {\n      numeric(0)\n    }\n  }\n)\n\n##' @rdname coef\n##' @param value numeric vector or list; values to be assigned.\n##' If \\code{value = NULL}, the parameters are unset.\n##' @details\n##' \\code{coef(object) <- value} sets or alters the coefficients of a\n##' \\sQuote{pomp} object.\n##'\n##' \\code{coef(object,transform=TRUE) <- value} assumes that \\code{value} is on\n##' the estimation scale, and applies the \\dQuote{from estimation scale}\n##' parameter transformation from \\code{object} before altering the\n##' coefficients.\n##' @export\nsetMethod(\n  \"coef<-\",\n  signature=signature(object=\"pomp\"),\n  definition=function (object, pars, transform = FALSE, ..., value) {\n    if (is.null(value)) value <- numeric(0)\n    if (is.list(value)) value <- unlist(value)\n    if (missing(pars)) {          ## replace the whole params slot with 'value'\n      if (length(value)>0) {\n        if (transform)\n          value <- partrans(object,params=value,...,dir=\"fromEst\")\n        pars <- names(value)\n        if (is.null(pars)) {\n          pStop(who=\"coef<-\",sQuote(\"value\"),\" must be a named vector.\")\n        }\n      }\n      object@params <- value\n    } else { ## replace or append only the parameters named in 'pars'\n      if (!is.null(names(value))) ## we ignore the names of 'value'\n        pWarn(who=-2L,\"names of \",sQuote(\"value\"),\" are being discarded.\")\n      if (length(object@params)==0) { ## no pre-existing 'params' slot\n        val <- numeric(length(pars))\n        names(val) <- pars\n        val[] <- value\n        if (transform) val <- partrans(object,params=val,...,dir=\"fromEst\")\n        object@params <- val\n      } else { ## pre-existing params slot\n        params <- coef(object,transform=transform)\n        val <- numeric(length(pars))\n        names(val) <- pars\n        val[] <- value\n        excl <- !(pars%in%names(params)) ## new parameter names\n        if (any(excl)) { ## append parameters\n          nexcl <- sum(excl)\n          pWarn(who=-2L,ngettext(nexcl,\"name\",\"names\"),\" \",\n            paste(sQuote(pars[excl]),collapse=\",\"),\n            \" refer\",ngettext(nexcl,\"s\",\"\"),\" to no existing parameter\",\n            ngettext(nexcl,\"\",\"s\"),\"; \",\n            ngettext(nexcl,\"it is\",\"they are\"),\" being concatenated.\")\n          params <- c(params,val[excl])\n        }\n        params[pars] <- val\n        if (transform) params <- partrans(object,params=params,...,dir=\"fromEst\")\n        object@params <- params\n      }\n    }\n    storage.mode(object@params) <- \"double\"\n    object\n  }\n)\n"
  },
  {
    "path": "R/conc.R",
    "content": "##' Concatenate\n##'\n##' @description Internal methods to concatenate objects into useful listie.\n##' @details Not exported.\n##' @name conc\n##' @rdname conc\n##' @include listie.R\n##' @importFrom stats setNames\n##' @keywords internal\n##'\nNULL\n\nsetGeneric(\n  \"conc\",\n  function (...)\n    standardGeneric(\"conc\")\n)\n\nsetMethod(\n  \"conc\",\n  signature=signature(...=\"ANY\"),\n  definition=function (...) {\n    if (...length()==0L) {\n      cls <- \"missing\"\n    } else {\n      cls <- unique(vapply(list(...),class,character(1L)))\n    }\n    pStop_(\n      sQuote(\"c\"),\n      \" is not defined for objects of \",\n      ngettext(length(cls),\"class \",\"classes \"),\n      paste(sQuote(cls),collapse=\", \"),\".\"\n    )\n  }\n)\n\nflatten_list <- function (...) {\n  unlist(\n    lapply(\n      list(...),\n      \\(z) {\n        if (is(z,\"list\")) {\n          setNames(as(z,\"list\"),names(z))\n        } else {\n          z\n        }\n      }\n    )\n  )\n}\n\n##' @rdname conc\nsetMethod(\n  \"conc\",\n  signature=signature(...=\"Pomp\"),\n  definition=function (...) {\n    y <- flatten_list(...)\n    setNames(\n      new(\n        \"pompList\",\n        lapply(y,as,\"pomp\")\n      ),\n      names(y)\n    )\n  }\n)\n\n##' @rdname conc\nsetMethod(\n  \"conc\",\n  signature=signature(...=\"Pfilter\"),\n  definition=function (...) {\n    y <- flatten_list(...)\n    setNames(\n      new(\n        \"pfilterList\",\n        lapply(y,as,\"pfilterd_pomp\")\n      ),\n      names(y)\n    )\n  }\n)\n\n##' @rdname conc\nsetMethod(\n  \"conc\",\n  signature=signature(...=\"Abc\"),\n  definition=function (...) {\n    y <- flatten_list(...)\n    setNames(\n      new(\n        \"abcList\",\n        lapply(y,as,\"abcd_pomp\")\n      ),\n      names(y)\n    )\n  }\n)\n\n##' @rdname conc\nsetMethod(\n  \"conc\",\n  signature=signature(...=\"Mif2\"),\n  definition=function (...) {\n    y <- flatten_list(...)\n    setNames(\n      new(\n        \"mif2List\",\n        lapply(y,as,\"mif2d_pomp\")\n      ),\n      names(y)\n    )\n  }\n)\n\n##' @rdname conc\nsetMethod(\n  \"conc\",\n  signature=signature(...=\"Pmcmc\"),\n  definition=function (...) {\n    y <- flatten_list(...)\n    setNames(\n      new(\n        \"pmcmcList\",\n        lapply(y,as,\"pmcmcd_pomp\")\n      ),\n      names(y)\n    )\n  }\n)\n"
  },
  {
    "path": "R/concat.R",
    "content": "##' Concatenate\n##'\n##' Concatenate two or more \\sQuote{pomp} objects into a list-like \\sQuote{listie}.\n##'\n##' @name concat\n##' @rdname concat\n##' @aliases c\n##' @include listie.R conc.R\n##' @param ... elements to be recursively combined into a \\sQuote{listie}\n##' @details\n##' \\code{concat} applied to one or more \\sQuote{pomp} objects or lists of \\sQuote{pomp} objects converts the list into a \\sQuote{listie}.\n##' In particular, \\code{concat(A,B,C)} is equivalent to \\code{do.call(c,unlist(list(A,B,C)))}.\n##'\n##' @example examples/concat.R\n##'\nNULL\n\n##' @rdname concat\n##' @export\nc.Pomp <- function (...) conc(...)\n\n##' @rdname concat\n##' @export\nconcat <- function (...) {\n  do.call(conc,unlist(list(...)))\n}\n"
  },
  {
    "path": "R/cond_logLik.R",
    "content": "##' Conditional log likelihood\n##'\n##' The estimated conditional log likelihood from a fitted model.\n##'\n##' The conditional likelihood is defined to be the value of the density\n##' of \\deqn{Y(t_k) | Y(t_1),\\dots,Y(t_{k-1})}{Yk | Y1,\\dots,Y(k-1)} evaluated at \\eqn{Y(t_k) = y^*_k}{Yk = yk*}.\n##' Here, \\eqn{Y(t_k)}{Yk} is the observable process, and \\eqn{y^*_k}{yk*} the data, at time \\eqn{t_k}.\n##'\n##' Thus the conditional log likelihood at time \\eqn{t_k} is\n##' \\deqn{\\ell_k(\\theta) = \\log f[Y(t_k)=y^*_k \\vert Y(t_1)=y^*_1, \\dots, Y(t_{k-1})=y^*_{k-1}],}{ell_k(theta)=log f[Yk = yk* | Y1=y1*, \\dots, Y(k-1)=y(k-1)*],}\n##' where \\eqn{f} is the probability density above.\n##'\n##' @name cond_logLik\n##' @docType methods\n##' @rdname cond_logLik\n##' @include pomp_class.R kalman.R pfilter.R wpfilter.R melt.R\n##' @aliases cond_logLik,missing-method cond_logLik,ANY-method\n##' @family particle filter methods\n##' @family extraction methods\n##' @inheritParams filter_mean\n##' @return\n##' The numerical value of the conditional log likelihood.\n##' Note that some methods compute not the log likelihood itself but instead a related quantity.\n##' To keep the code simple, the \\code{cond_logLik} function is nevertheless used to extract this quantity.\nNULL\n\nsetGeneric(\n  \"cond_logLik\",\n  function (object, ...)\n    standardGeneric(\"cond_logLik\")\n)\n\nsetMethod(\n  \"cond_logLik\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"cond_logLik\",\"object\")\n  }\n)\n\nsetMethod(\n  \"cond_logLik\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"cond_logLik\",object)\n  }\n)\n\n##' @rdname cond_logLik\n##' @export\nsetMethod(\n  \"cond_logLik\",\n  signature=signature(object=\"kalmand_pomp\"),\n  definition=function (object, ...,\n    format = c(\"numeric\", \"data.frame\")) {\n    format <- match.arg(format)\n    if (format == \"numeric\") {\n      object@cond.logLik\n    } else {\n      data.frame(\n        time=time(object),\n        cond.logLik=object@cond.logLik\n      )\n    }\n  }\n)\n\n##' @rdname cond_logLik\n##' @export\nsetMethod(\n  \"cond_logLik\",\n  signature=signature(object=\"pfilterd_pomp\"),\n  definition=function (object, ...,\n    format = c(\"numeric\", \"data.frame\")) {\n    format <- match.arg(format)\n    if (format == \"numeric\") {\n      object@cond.logLik\n    } else {\n      data.frame(\n        time=time(object),\n        cond.logLik=object@cond.logLik\n      )\n    }\n  }\n)\n\n##' @rdname cond_logLik\n##' @export\nsetMethod(\n  \"cond_logLik\",\n  signature=signature(object=\"wpfilterd_pomp\"),\n  definition=function (object, ...,\n    format = c(\"numeric\", \"data.frame\")) {\n    format <- match.arg(format)\n    if (format == \"numeric\") {\n      object@cond.logLik\n    } else {\n      data.frame(\n        time=time(object),\n        cond.logLik=object@cond.logLik\n      )\n    }\n  }\n)\n\n##' @rdname cond_logLik\n##' @return\n##' When \\code{object} is of class \\sQuote{bsmcd_pomp}\n##' (i.e., the result of a \\code{bsmc2} computation),\n##' \\code{cond_logLik} returns the conditional log \\dQuote{evidence}\n##' (see \\code{\\link{bsmc2}}).\n##' @export\nsetMethod(\n  \"cond_logLik\",\n  signature=signature(object=\"bsmcd_pomp\"),\n  definition=function (object, ...,\n    format = c(\"numeric\", \"data.frame\")) {\n    format <- match.arg(format)\n    if (format == \"numeric\") {\n      object@cond.log.evidence\n    } else {\n      data.frame(\n        time=time(object),\n        cond_log.evidence=object@cond.log.evidence\n      )\n    }\n  }\n)\n\n##' @rdname cond_logLik\n##' @export\nsetMethod(\n  \"cond_logLik\",\n  signature=signature(object=\"pfilterList\"),\n  definition=function (object, ...,\n    format = c(\"numeric\", \"data.frame\")) {\n    format <- match.arg(format)\n    x <- lapply(object,cond_logLik,format=format)\n    if (format == \"data.frame\") {\n      x <- rbind_fill(x,.id=\".id\")\n    }\n    x\n  }\n)\n"
  },
  {
    "path": "R/continue.R",
    "content": "##' Continue an iterative calculation\n##'\n##' Continue an iterative computation where it left off.\n##'\n##' @name continue\n##' @aliases continue,missing-method continue,ANY-method\n##' @rdname continue\n##' @seealso \\code{\\link{mif2}} \\code{\\link{pmcmc}} \\code{\\link{abc}}\n##'\n##' @param object the result of an iterative \\pkg{pomp} computation\n##' @param \\dots additional arguments will be passed to the underlying method.\n##' This allows one to modify parameters used in the original computations.\nNULL\n\n##' @export\nsetGeneric(\n  \"continue\",\n  function (object, ...)\n    standardGeneric(\"continue\")\n)\n\nsetMethod(\n  \"continue\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"continue\",\"object\")\n  }\n)\n\nsetMethod(\n  \"continue\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"continue\",object)\n  }\n)\n"
  },
  {
    "path": "R/covariate_table.R",
    "content": "##' Covariates\n##'\n##' Incorporating time-varying covariates using lookup tables.\n##'\n##' If the \\sQuote{pomp} object contains covariates (specified via the \\code{covar} argument), then interpolated values of the covariates will be available to each of the model components whenever it is called.\n##' In particular, variables with names as they appear in the \\code{covar} covariate table will be available to any C snippet.\n##' When a basic component is defined using an \\R function, that function will be called with an extra argument, \\code{covars}, which will be a named numeric vector containing the interpolated values from the covariate table.\n##'\n##' An exception to this rule is the prior (\\code{rprior} and \\code{dprior}):\n##' covariate-dependent priors are not allowed.\n##' Nor are parameter transformations permitted to depend upon covariates.\n##'\n##' @name covariates\n##' @rdname covariate_table\n##' @aliases covariate_table covariate_table,missing-method covariate_table,ANY-method\n##' @include pomp_class.R pstop.R\n##' @concept covariates\n##' @family implementation information\n##' @family interpolation\n##' @param times the times corresponding to the covariates.\n##' This may be given as a vector of (non-decreasing, finite) numerical values.\n##' Alternatively, one can specify by name which of the given variables is the time variable.\n##' @param order the order of interpolation to be used.\n##' Options are \\dQuote{linear} (the default) and \\dQuote{constant}.\n##' Setting \\code{order=\"linear\"} treats the covariates as piecewise linear functions of time;\n##' \\code{order=\"constant\"} treats them as right-continuous piecewise constant functions.\n##' @param \\dots numeric vectors or data frames containing time-varying covariates.\n##' It must be possible to bind these into a data frame.\n##'\n##' @return\n##' \\code{covariate_table} returns a lookup table suitable for inclusion of covariates in a \\sQuote{pomp} object.\n##' Specifically, this is an object of class \\sQuote{covartable}.\n##' @section Extrapolation:\n##' If \\code{t} is outside the range of the lookup table, the values will be extrapolated, and a warning will be issued.\n##' The type of extrapolation performed will be constant or linear according to the \\code{order} flag used when creating the table.\nNULL\n\nsetClass(\n  \"covartable\",\n  slots=c(\n    times=\"numeric\",\n    table=\"matrix\",\n    order=\"integer\"\n  ),\n  prototype=prototype(\n    times=numeric(0),\n    table=array(data=numeric(0),dim=c(0,0)),\n    order=1L\n  )\n)\n\nsetGeneric(\n  \"covariate_table\",\n  function (..., times)\n    standardGeneric(\"covariate_table\")\n)\n\nsetMethod(\n  \"covariate_table\",\n  signature=signature(times=\"missing\"),\n  definition=function (...) {\n    if (nargs() > 0) reqd_arg(\"covariate_table\",\"times\")\n    new(\"covartable\")\n  }\n)\n\nsetMethod(\n  \"covariate_table\",\n  signature=signature(times=\"ANY\"),\n  definition=function (..., times) {\n    undef_method(\"covariate_table\",times)\n  }\n)\n\n##' @rdname covariate_table\n##' @export\nsetMethod(\n  \"covariate_table\",\n  signature=signature(times=\"numeric\"),\n  definition=function (..., order = c(\"linear\", \"constant\"), times) {\n    order <- match.arg(order)\n    env <- parent.frame(2)\n    tryCatch(\n      covariate_table_internal(...,times=times,order=order,env=env),\n      error = function (e) pStop(who=\"covariate_table\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname covariate_table\n##' @export\nsetMethod(\n  \"covariate_table\",\n  signature=signature(times=\"character\"),\n  definition=function (..., order = c(\"linear\", \"constant\"), times) {\n    order <- match.arg(order)\n    env <- parent.frame(2)\n    tryCatch(\n      covariate_table_internal(...,.timevar=times,order=order,env=env),\n      error = function (e) pStop(who=\"covariate_table\",conditionMessage(e))\n    )\n\n  }\n)\n\ncovariate_table_internal <- function (..., times = NULL, .timevar = NULL,\n  order, env) {\n\n  d <- as.list(substitute(list(...)))[-1]\n  if (length(d)==0) pStop_(\"no covariates specified.\")\n  nm <- names(d)\n  if (is.null(nm)) nm <- character(length(d))\n  noname <- !nzchar(nm)\n  nm[noname] <- paste0(\".cov.int.\",seq_len(sum(noname)))\n  names(d) <- nm\n\n  e <- new.env(parent=env)\n\n  e$times <- as.numeric(times)\n\n  for (i in names(d)) e[[i]] <- eval(d[[i]],envir=e)\n\n  remove(list=c(\"times\"),pos=e)\n\n  e <- as.list(e,all.names=TRUE)\n  names(e) <- sub(\".cov.int.*\",\"\",names(e))\n\n  df <- tryCatch(\n    data.frame(e,check.names=FALSE),\n    error = function (e) pStop_(\"binding columns: \",conditionMessage(e))\n  )\n\n  if (anyDuplicated(names(df))) pStop_(\"names of covariates must be unique.\")\n\n  if (!is.null(times) && (length(times) != nrow(df)))\n    pStop_(sQuote(\"times\"),\" must agree in length with the covariates.\")\n\n  if (!is.null(.timevar)) {\n\n    tpos <- match(.timevar,names(df),nomatch=0L)\n    if (tpos == 0L)\n      pStop_(sQuote(\"times\"),\" does not identify a unique time variable.\")\n    times <- df[[tpos]]\n    df <- df[-tpos]\n\n  }\n\n  if (length(df) == 0) pStop_(\"no covariates specified.\")\n\n  if (any(!is.finite(times)) || !all(diff(times)>=0))\n    pStop_(sQuote(\"times\"),\n      \" must be a non-decreasing numeric sequence (without missing values).\")\n\n  names(df) <- cleanForC(names(df))\n\n  new(\"covartable\",times=as.double(times),\n    table=do.call(rbind,lapply(df,as.double)),\n    order=switch(order,linear=1L,constant=0L))\n\n}\n\nget_covariate_names <- function (object) {\n  rownames(object@table)\n}\n\ncovar_time_warning <- function (object, times, t0, wp) {\n  if ((length(object@times)>0) &&\n        ((min(object@times)>t0) || (max(object@times)<max(times))))\n    pWarn(who=wp,\"the supplied covariate times do not embrace the \",\n      \"data times: covariates may be extrapolated.\")\n}\n\nsetMethod(\n  \"undefined\",\n  signature=signature(object=\"covartable\"),\n  definition=function (object) {\n    nrow(object@table) == 0L\n  }\n)\n"
  },
  {
    "path": "R/covmat.R",
    "content": "##' Estimate a covariance matrix from algorithm traces\n##'\n##' A helper function to extract a covariance matrix.\n##'\n##' @name covmat\n##' @aliases covmat,missing-method covmat,ANY-method\n##' @include pmcmc.R abc.R probe.R\n##' @rdname covmat\n##' @family extraction methods\n##'\n##' @seealso \\link[=proposals]{MCMC proposals}.\nNULL\n\nsetGeneric(\n  \"covmat\",\n  function (object, ...)\n    standardGeneric(\"covmat\")\n)\n\n##' @rdname covmat\n##' @param object an object extending \\sQuote{pomp}\n##' @param start the first iteration number to be used in estimating the covariance matrix.\n##' Setting \\code{thin > 1} allows for a burn-in period.\n##' @param thin factor by which the chains are to be thinned\n##' @param expand the expansion factor\n##' @param \\dots ignored\n##' @return\n##' When \\code{object} is the result of a \\code{pmcmc} or \\code{abc} computation,\n##' \\code{covmat(object)} gives the covariance matrix of the chains.\n##' This can be useful, for example, in tuning the proposal distribution.\n##' @export\nsetMethod(\n  \"covmat\",\n  signature=signature(object=\"pmcmcd_pomp\"),\n  definition=function (object, start = 1, thin = 1,\n    expand = 2.38, ...) {\n    covmat_internal(traces=as.matrix(traces(object,object@pars)),\n      start=start,thin=thin,expand=expand)\n  })\n\n##' @rdname covmat\n##' @export\nsetMethod(\n  \"covmat\",\n  signature=signature(object=\"pmcmcList\"),\n  definition=function (object, start = 1, thin = 1,\n    expand = 2.38, ...) {\n    pars <- unique(c(sapply(object,slot,\"pars\")))\n    covmat_internal(traces=as.array(traces(object,pars)),\n      start=start,thin=thin,expand=expand)\n  })\n\n##' @rdname covmat\n##' @export\nsetMethod(\n  \"covmat\",\n  signature=signature(object=\"abcd_pomp\"),\n  definition=function (object, start = 1, thin = 1,\n    expand = 2.38, ...) {\n    covmat_internal(traces=as.matrix(traces(object,object@pars)),\n      start=start,thin=thin,expand=expand)\n  })\n\n##' @rdname covmat\n##' @export\nsetMethod(\n  \"covmat\",\n  signature=signature(object=\"abcList\"),\n  definition=function (object, start = 1, thin = 1,\n    expand = 2.38, ...) {\n    pars <- unique(c(sapply(object,slot,\"pars\")))\n    covmat_internal(traces=as.array(traces(object,pars)),\n      start=start,thin=thin,expand=expand)\n  })\n\n##' @rdname covmat\n##' @importFrom stats var\n##' @return\n##' When \\code{object} is a \\sQuote{probed_pomp} object (i.e., the result\n##' of a \\code{probe} computation), \\code{covmat(object)} returns the\n##' covariance matrix of the probes, as applied to simulated data.\n##' @export\nsetMethod(\n  \"covmat\",\n  signature=signature(object=\"probed_pomp\"),\n  definition=function (object, ...) {\n    n <- nrow(object@simvals)\n    crossprod(object@simvals)/(n-1)\n  })\n\ncovmat_internal <- function (traces, start, thin, expand = 2.38, ...) {\n  dd <- dim(traces)\n  nms <- colnames(traces)\n  keep <- seq.int(from=as.integer(start),to=dd[1],by=as.integer(thin))\n  if (length(keep) < 100)\n    pWarn(who=\"covmat\",\"only \",length(keep),\n      ngettext(length(keep),\" point is\",\" points are\"),\n      \" being used to estimate covariance matrix.\")\n  if (length(dd)==2L) {\n    traces <- traces[keep,,drop=FALSE]\n  } else if (length(dd)==3L) {\n    traces <- aperm(traces[keep,,,drop=FALSE],c(1L,3L,2L))\n    dd <- dim(traces)\n    dim(traces) <- c(dd[1L]*dd[2L],dd[3L])\n  }\n  v <- var(traces)\n  keep <- which(diag(v)>0)\n  v <- expand^2*v[keep,keep]/length(keep)\n  dimnames(v) <- list(nms[keep],nms[keep])\n  v\n}\n"
  },
  {
    "path": "R/csnippet.R",
    "content": "##' C snippets\n##'\n##' Accelerating computations through inline snippets of C code\n##'\n##' \\pkg{pomp} provides a facility whereby users can define their model's components using inline C code.\n##' C snippets are written to a C file, by default located in the \\R session's temporary directory, which is then compiled (via \\code{\\link[=SHLIB]{R CMD SHLIB}}) into a dynamically loadable shared object file.\n##' This is then loaded as needed.\n##'\n##' @name Csnippet\n##' @rdname csnippet\n##' @include package.R\n##' @family implementation information\n##' @seealso spy\n##'\n##' @section Note to Windows and Mac users:\n##'\n##' By default, your \\R installation may not support \\code{\\link[=SHLIB]{R CMD SHLIB}}.\n##' The \\href{https://kingaa.github.io/pomp/install.html}{package website contains installation instructions} that explain how to enable this powerful feature of \\R.\n##'\n##' @inheritSection pomp Note for Windows users\n##'\n##' @section General rules for writing C snippets:\n##'\n##' In writing a C snippet one must bear in mind both the \\emph{goal} of the snippet, i.e., what computation it is intended to perform, and the \\emph{context} in which it will be executed.\n##' These are explained here in the form of general rules.\n##' Additional specific rules apply according to the function of the particular C snippet.\n##' Illustrative examples are given in the tutorials on the \\href{https://kingaa.github.io/pomp/}{package website}.\n##' \\enumerate{\n##' \\item C snippets must be valid C.\n##' They will embedded verbatim in a template file which will then be compiled by a call to \\code{\\link[=SHLIB]{R CMD SHLIB}}.\n##' If the resulting file does not compile, an error message will be generated.\n##' Compiler messages will be displayed, but no attempt will be made by \\pkg{pomp} to interpret them.\n##' Typically, compilation errors are due to either invalid C syntax or undeclared variables.\n##' \\item State variables, parameters, observables, and covariates must be left undeclared within the snippet.\n##' State variables and parameters are declared via the \\code{statenames} or \\code{paramnames} arguments to \\code{pomp}, respectively.\n##' Compiler errors that complain about undeclared state variables or parameters are usually due to failure to declare these in \\code{statenames} or \\code{paramnames}, as appropriate.\n##' \\item A C snippet can declare local variables.\n##' Be careful not to use names that match those of state variables, observables, or parameters.\n##' One must never declare state variables, observables, covariates, or parameters within a C snippet.\n##' \\item Names of observables must match the names given given in the data.\n##' They must be referred to in measurement model C snippets (\\code{rmeasure} and \\code{dmeasure}) by those names.\n##' \\item If the \\sQuote{pomp} object contains a table of covariates (see above), then the variables in the covariate table will be available, by their names, in the context within which the C snippet is executed.\n##' \\item Because the dot \\sQuote{.} has syntactic meaning in C, \\R variables with names containing dots (\\sQuote{.}) are replaced in the C codes by variable names in which all dots have been replaced by underscores (\\sQuote{_}).\n##' \\item The headers \\file{R.h} and \\file{Rmath.h}, provided with \\R, will be included in the generated C file, making all of the \\href{https://CRAN.R-project.org/doc/manuals/r-release/R-exts.html#The-R-API}{\\R C API} available for use in the C snippet.\n##' This makes a great many useful functions available, including all of \\R's \\href{https://CRAN.R-project.org/doc/manuals/r-release/R-exts.html#Distribution-functions}{statistical distribution functions}.\n##' \\item The header \\href{https://github.com/kingaa/pomp/blob/master/inst/include/pomp.h}{\\file{pomp.h}}, provided with \\pkg{pomp}, will also be included, making all of the \\href{https://kingaa.github.io/pomp/C_API.html}{\\pkg{pomp} C API} available for use in every C snippet.\n##' \\item Snippets of C code passed to the \\code{globals} argument of \\code{pomp} will be included at the head of the generated C file.\n##' This can be used to declare global variables, define useful functions, and include arbitrary header files.\n##' }\n##'\n##' @section Linking to precompiled libraries:\n##' It is straightforward to link C snippets with precompiled C libraries.\n##' To do so, one must make sure the library's header files are included;\n##' the \\code{globals} argument can be used for this purpose.\n##' The \\code{shlib.args} argument can then be used to specify additional arguments to be passed to \\code{\\link[=SHLIB]{R CMD SHLIB}}.\n##' \\href{https://kingaa.github.io/pomp/FAQ.html#linking-C-libraries}{FAQ 3.7} gives an example.\n##'\n##' @section C snippets are salted:\n##' To prevent collisions in parallel computations, a \\sQuote{pomp} object built using C snippets is \\dQuote{salted} with the current time and a random number.\n##' A result is that two \\sQuote{pomp} objects, built on identical codes and data, will \\strong{not} be identical as \\R objects, though they will be functionally identical in every respect.\n##'\nNULL\n\nsetClass(\n  \"Csnippet\",\n  slots=c(\n    text=\"character\"\n  ),\n  prototype=prototype(\n    text=character(0)\n  )\n)\n\n##' @name Csnippet\n##' @rdname csnippet\n##' @param text character; text written in the C language\n##' @export\nCsnippet <- function (text) {\n  new(\"Csnippet\",text=as.character(text))\n}\n\nsetAs(\n  from=\"Csnippet\",\n  to=\"character\",\n  def = function (from) {\n    from@text\n  }\n)\n\n##' @export\nas.character.Csnippet <- function(x, ...) as(x,\"character\")\n"
  },
  {
    "path": "R/dacca.R",
    "content": "##' Model of cholera transmission for historic Bengal.\n##'\n##' \\code{dacca} constructs a \\sQuote{pomp} object containing census and cholera\n##' mortality data from the Dacca district of the former British province of\n##' Bengal over the years 1891 to 1940 together with a stochastic differential\n##' equation transmission model.\n##' The model is that of King et al. (2008).\n##' The parameters are the MLE for the SIRS model with seasonal reservoir.\n##'\n##' Data are provided courtesy of Dr. Menno J. Bouma, London School of Tropical\n##' Medicine and Hygiene.\n##'\n##' @return\n##' \\code{dacca} returns a \\sQuote{pomp} object containing the model, data, and MLE\n##' parameters, as estimated by King et al. (2008).\n##'\n##' @name dacca\n##' @docType data\n##' @family pomp examples\n##' @family pomp datasets\n##' @include pomp.R\n##' @importFrom stats smooth.spline predict\n##'\n##' @references\n##'\n##' \\King2008\n##'\n##' @keywords models\n##' @example examples/dacca.R\n##'\nNULL\n\n## pomp object encoding the \"SIRS model with seasonal reservoir\" of\n##   King, A. A., Ionides, E. L., Pascual, M., & Bouma, M. J.\n##   Inapparent infections and cholera dynamics.\n##   Nature 454:877-880 (2008)\n## Data are cholera deaths and decadal census figures from the Dacca district of Bengal province, 1891-1941.\n\n##' @rdname dacca\n##'\n##' @param gamma recovery rate\n##' @param eps rate of waning of immunity for severe infections\n##' @param rho rate of waning of immunity for inapparent infections\n##' @param delta baseline mortality rate\n##' @param deltaI cholera mortality rate\n##' @param clin fraction of infections that lead to severe infection\n##' @param alpha transmission function exponent\n##' @param beta_trend slope of secular trend in transmission\n##' @param logbeta seasonal transmission rates\n##' @param sd_beta environmental noise intensity\n##' @param tau measurement error s.d.\n##' @param logomega seasonal environmental reservoir parameters\n##' @param S_0 initial susceptible fraction\n##' @param I_0 initial fraction of population infected\n##' @param Y_0 initial fraction of the population in the Y class\n##' @param R1_0,R2_0,R3_0 initial fractions in the respective R classes\n##'\n##' @export\ndacca <- function (\n  gamma = 20.8, eps = 19.1, rho = 0,\n  delta = 0.02, deltaI = 0.06, clin = 1, alpha = 1,\n  beta_trend = -0.00498,\n  logbeta = c(0.747, 6.38, -3.44, 4.23, 3.33, 4.55),\n  logomega = log(c(0.184, 0.0786, 0.0584, 0.00917, 0.000208, 0.0124)),\n  sd_beta = 3.13, tau = 0.23,\n  S_0 = 0.621, I_0 = 0.378, Y_0 = 0,\n  R1_0 = 0.000843, R2_0 = 0.000972, R3_0 = 1.16e-07\n)\n{\n  nrstage <- 3L\n  nbasis <- length(logbeta)\n  if (length(logomega) != nbasis)\n    pStop(sQuote(\"logbeta\"),\" and \",sQuote(\"logomega\"),\" should be of equal length.\")\n\n  mle <- c(\n    gamma=gamma,eps=eps,rho=rho,\n    delta=delta, deltaI=deltaI, clin=clin, alpha=alpha,\n    beta_trend=beta_trend,\n    logbeta=unname(logbeta),\n    logomega=unname(logomega),\n    sd_beta=sd_beta, tau=tau,\n    S_0=S_0, I_0=I_0, Y_0=Y_0, R1_0=R1_0, R2_0=R2_0, R3_0=R3_0\n  )\n\n  census <- data.frame(\n    year = c(1891L, 1901L, 1911L, 1921L, 1931L, 1941L),\n    census = c(2420656L, 2649522L, 2960402L, 3125967L, 3432577L, 4222142L)\n  )\n\n  cholera <- data.frame(\n    time=seq(from=1891+1/12,to=1941,by=1/12),\n    cholera.deaths = c(\n      2641L, 939L, 905L, 1219L, 368L, 78L, 29L, 12L, 30L, 44L, 270L, 1149L,\n      633L, 501L, 855L, 1271L, 666L, 101L, 62L, 23L, 20L, 28L, 461L,\n      892L, 751L, 170L, 253L, 906L, 700L, 98L, 57L, 72L, 471L, 4217L,\n      5168L, 4747L, 2380L, 852L, 1166L, 2122L, 576L, 60L, 53L, 62L,\n      241L, 403L, 551L, 739L, 862L, 348L, 490L, 5596L, 1180L, 142L,\n      41L, 28L, 39L, 748L, 3934L, 3562L, 587L, 311L, 1639L, 1903L,\n      601L, 110L, 32L, 19L, 82L, 420L, 1014L, 1073L, 416L, 168L, 909L,\n      1355L, 447L, 59L, 13L, 21L, 43L, 109L, 338L, 470L, 489L, 394L,\n      483L, 842L, 356L, 29L, 17L, 16L, 57L, 110L, 488L, 1727L, 1253L,\n      359L, 245L, 549L, 215L, 9L, 7L, 31L, 236L, 279L, 819L, 1728L,\n      1942L, 1251L, 3521L, 3412L, 290L, 46L, 35L, 14L, 79L, 852L, 2951L,\n      2656L, 607L, 172L, 325L, 2191L, 584L, 58L, 38L, 8L, 22L, 50L,\n      380L, 2059L, 938L, 389L, 767L, 1882L, 286L, 94L, 61L, 10L, 106L,\n      281L, 357L, 1388L, 810L, 306L, 381L, 1308L, 702L, 87L, 9L, 14L,\n      36L, 46L, 553L, 1302L, 618L, 147L, 414L, 768L, 373L, 39L, 10L,\n      36L, 151L, 1130L, 3437L, 4041L, 1415L, 207L, 92L, 128L, 147L,\n      32L, 7L, 59L, 426L, 2644L, 2891L, 4249L, 2291L, 797L, 680L, 1036L,\n      404L, 41L, 19L, 12L, 10L, 121L, 931L, 2158L, 1886L, 803L, 397L,\n      613L, 132L, 48L, 17L, 22L, 26L, 34L, 344L, 657L, 117L, 75L, 443L,\n      972L, 646L, 107L, 18L, 6L, 9L, 5L, 12L, 142L, 133L, 189L, 1715L,\n      3115L, 1412L, 182L, 50L, 37L, 77L, 475L, 1730L, 1489L, 620L,\n      190L, 571L, 1558L, 440L, 27L, 7L, 14L, 93L, 1462L, 2467L, 1703L,\n      1262L, 458L, 453L, 717L, 232L, 26L, 16L, 18L, 9L, 78L, 353L,\n      897L, 777L, 404L, 799L, 2067L, 613L, 98L, 19L, 26L, 47L, 171L,\n      767L, 1896L, 887L, 325L, 816L, 1653L, 355L, 85L, 54L, 88L, 609L,\n      882L, 1363L, 2178L, 580L, 396L, 1493L, 2154L, 683L, 78L, 19L,\n      10L, 27L, 88L, 1178L, 1862L, 611L, 478L, 2697L, 3395L, 520L,\n      67L, 41L, 36L, 209L, 559L, 971L, 2144L, 1099L, 494L, 586L, 508L,\n      269L, 27L, 19L, 21L, 12L, 22L, 333L, 676L, 487L, 262L, 535L,\n      979L, 170L, 25L, 9L, 19L, 13L, 45L, 229L, 673L, 432L, 107L, 373L,\n      1126L, 339L, 19L, 11L, 3L, 15L, 101L, 539L, 709L, 200L, 208L,\n      926L, 1783L, 831L, 103L, 37L, 17L, 33L, 179L, 426L, 795L, 481L,\n      491L, 773L, 936L, 325L, 101L, 22L, 25L, 24L, 88L, 633L, 513L,\n      298L, 93L, 687L, 1750L, 356L, 33L, 2L, 18L, 70L, 648L, 2471L,\n      1270L, 616L, 193L, 706L, 1372L, 668L, 107L, 58L, 21L, 23L, 93L,\n      318L, 867L, 332L, 118L, 437L, 2233L, 491L, 27L, 7L, 21L, 96L,\n      360L, 783L, 1492L, 550L, 176L, 633L, 922L, 267L, 91L, 42L, 4L,\n      10L, 7L, 43L, 377L, 563L, 284L, 298L, 625L, 131L, 35L, 12L, 8L,\n      9L, 83L, 502L, 551L, 256L, 198L, 664L, 1701L, 425L, 76L, 17L,\n      9L, 16L, 5L, 141L, 806L, 1603L, 587L, 530L, 771L, 511L, 97L,\n      35L, 39L, 156L, 1097L, 1233L, 1418L, 1125L, 420L, 1592L, 4169L,\n      1535L, 371L, 139L, 55L, 85L, 538L, 1676L, 1435L, 804L, 370L,\n      477L, 394L, 306L, 132L, 84L, 87L, 53L, 391L, 1541L, 1859L, 894L,\n      326L, 853L, 1891L, 1009L, 131L, 77L, 63L, 66L, 33L, 178L, 1003L,\n      1051L, 488L, 911L, 1806L, 837L, 280L, 132L, 76L, 381L, 1328L,\n      2639L, 2164L, 1082L, 326L, 254L, 258L, 119L, 106L, 93L, 29L,\n      17L, 17L, 17L, 46L, 79L, 135L, 1290L, 2240L, 561L, 116L, 24L,\n      15L, 33L, 18L, 16L, 38L, 26L, 45L, 151L, 168L, 57L, 32L, 29L,\n      27L, 20L, 106L, 1522L, 2013L, 434L, 205L, 528L, 634L, 195L, 45L,\n      33L, 19L, 20L, 46L, 107L, 725L, 572L, 183L, 2199L, 4018L, 428L,\n      67L, 31L, 8L, 44L, 484L, 1324L, 2054L, 467L, 216L, 673L, 887L,\n      353L, 73L, 46L, 15L, 20L, 27L, 25L, 38L, 158L, 312L, 1226L, 1021L,\n      222L, 90L, 31L, 93L, 368L, 657L, 2208L, 2178L, 702L, 157L, 317L,\n      146L, 63L, 27L, 22L, 23L, 28L, 225L, 483L, 319L, 120L, 59L, 274L,\n      282L, 155L, 31L, 16L, 15L, 12L, 14L, 14L, 42L\n    )\n  )\n\n  rinit <- Csnippet(\"\n    int k;\n    double sum = S_0+I_0+Y_0;\n    double *R = &R1;\n    const double *R0 = &R1_0;\n    for (k = 0; k < nrstage; k++) sum += R0[k];\n    S = nearbyint(pop*S_0/sum);\n    I = nearbyint(pop*I_0/sum);\n    Y = nearbyint(pop*Y_0/sum);\n    for (k = 0; k < nrstage; k++) R[k] = nearbyint(pop*R0[k]/sum);\n    W = 0;\n    deaths = 0;\n    count = 0;\n  \")\n\n  norm_rmeas <- Csnippet(\"\n    double v, tol = 1.0e-18;\n    v = deaths*tau;\n    if ((count > 0) || (!(R_FINITE(v)))) {\n    cholera_deaths = R_NaReal;\n    } else {\n    cholera_deaths = rnorm(deaths,v+tol);\n    }\n  \")\n\n  norm_dmeas <- Csnippet(\"\n    double v, tol = 1.0e-18;\n    v = deaths*tau;\n    if ((count>0.0) || (!(R_FINITE(v)))) {\n    lik = tol;\n    } else {\n    lik = dnorm(cholera_deaths,deaths,v+tol,0)+tol;\n    }\n    if (give_log) lik = log(lik);\n  \")\n\n  ## two-path SIRS cholera model using SDEs\n  ## exponent (alpha) on I/n\n  ## only \"severe\" infections are infectious\n  ## truncation is not used\n  ## instead, particles with negative states are killed\n\n  cholmodel_one <- Csnippet(\"\n    double births;\n    double infections;\n    double sdeaths;\n    double ideaths;\n    double ydeaths;\n    double rdeaths[nrstage];\n    double disease;\n    double wanings;\n    double passages[nrstage+1];\n    double effI;\n    double neps;\n    double beta;\n    double omega;\n    double dw;\n    double *pt;\n    int j;\n\n    if (count != 0.0) return;\n\n    neps = eps*nrstage;\n\n    beta = exp(dot_product(nbasis,&seas_1,&logbeta1)+beta_trend*trend);\n    omega = exp(dot_product(nbasis,&seas_1,&logomega1));\n\n    dw = rnorm(0,sqrt(dt));     // white noise\n\n    effI = pow(I/pop,alpha);\n    births = dpopdt + delta*pop;        // births\n\n    passages[0] = gamma*I;      // recovery\n    ideaths = delta*I;          // natural i deaths\n    disease = deltaI*I;         // disease death\n    ydeaths = delta*Y;          // natural rs deaths\n    wanings = rho*Y;            // loss of immunity\n\n    for (pt = &R1, j = 0; j < nrstage; j++, pt++) {\n    rdeaths[j] = *pt*delta;     // natural R deaths\n    passages[j+1] = *pt*neps;   // passage to the next immunity class\n    }\n\n    infections = (omega+(beta+sd_beta*dw/dt)*effI)*S; // infection\n    sdeaths = delta*S;          // natural S deaths\n\n    S += (births - infections - sdeaths + passages[nrstage] + wanings)*dt;\n    I += (clin*infections - disease - ideaths - passages[0])*dt;\n    Y += ((1-clin)*infections - ydeaths - wanings)*dt;\n    for (pt = &R1, j = 0; j < nrstage; j++, pt++)\n    *pt += (passages[j] - passages[j+1] - rdeaths[j])*dt;\n    deaths += disease*dt;               // cumulative deaths due to disease\n    W += dw;\n\n    // check for violations of positivity constraints\n    // nonzero 'count' variable signals violation\n    if (S < 0.0) {\n    S = 0.0; I = 0.0; Y = 0.0;\n    count += 1;\n    }\n    if (I < 0.0) {\n    I = 0.0; S = 0.0;\n    count += 1e3;\n    }\n    if (Y < 0.0) {\n    Y = 0.0; S = 0.0;\n    count += 1e6;\n    }\n    if (deaths < 0.0) {\n    deaths = 0.0;\n    count += 1e9;\n    }\n    for (pt = &R1, j = 0; j < nrstage-1; j++, pt++) {\n    if (*pt < 0.0) {\n    *pt = 0.0; *(pt+1) = 0.0;\n    count += 1e12;\n    }\n    }\n    if (*pt < 0.0) {\n    *pt = 0.0; S = 0.0;\n    count += 1e12;\n    }\n    \"\n  )\n\n  t0 <- with(cholera,2*time[1]-time[2])\n\n  pomp(\n    data=cholera,\n    times='time',\n    t0=t0,\n    params=mle,\n    cfile=\"dacca_source\",\n    globals = sprintf(\"int nrstage = %d, nbasis = %d;\",nrstage,nbasis),\n    rprocess = euler(\n      step.fun = cholmodel_one,\n      delta.t=1/240\n    ),\n    dmeasure = norm_dmeas,\n    rmeasure=norm_rmeas,\n    partrans=parameter_trans(\n      log=c(\"tau\",\"gamma\",\"eps\",\"delta\",\"deltaI\",\"sd_beta\",\"alpha\",\"rho\"),\n      logit=\"clin\",\n      barycentric=c(\"S_0\",\"I_0\",\"Y_0\",sprintf(\"R%01d_0\",1:nrstage))\n    ),\n    rinit=rinit,\n    covar=covariate_table(\n      t=seq(from=t0,to=max(cholera$time)+2/12,by=0.01),\n      seas=periodic_bspline_basis(t-1/12,nbasis=nbasis,degree=3,period=1),\n      pop=predict(smooth.spline(x=census$year,y=census$census),x=t)$y,\n      dpopdt=predict(smooth.spline(x=census$year,y=census$census),x=t,deriv=1)$y,\n      trend=t-mean(t),\n      times=\"t\"\n    ),\n    accumvars = c(\"deaths\",\"count\"),\n    statenames = c(\"S\",\"I\",\"Y\",sprintf(\"R%d\",seq_len(nrstage)),\"deaths\",\"W\",\"count\"),\n    paramnames = c(\"tau\",\"gamma\",\"eps\",\"delta\",\"deltaI\",\n      \"logomega1\",\"sd_beta\",\"beta_trend\",\"logbeta1\",\n      \"alpha\",\"rho\",\"clin\",\"S_0\",\"I_0\",\"Y_0\",\"R1_0\")\n  )\n}\n"
  },
  {
    "path": "R/design.R",
    "content": "##' Design matrices for pomp calculations\n##'\n##' These functions are useful for generating designs for the exploration of parameter space.\n##'\n##' @name design\n##' @rdname design\n##' @concept search design\n##'\n##' @author Aaron A. King\n##'\n##' @param ...\n##' In \\code{profile_design}, additional arguments specify the parameters over which to profile and the values of these parameters.\n##' In \\code{slice_design}, additional numeric vector arguments specify the locations of points along the slices.\n##'\n##' @example examples/design.R\n##'\nNULL\n"
  },
  {
    "path": "R/dinit_spec.R",
    "content": "##' dinit specification\n##'\n##' Specification of the initial-state distribution density evaluator, dinit.\n##'\n##' @name dinit_spec\n##' @rdname dinit_spec\n##' @family implementation information\n##' @seealso \\code{\\link{dinit}}\n##' @details\n##' To fully specify the unobserved Markov state process, one must give its distribution at the zero-time (\\code{t0}).\n##' One specifies how to evaluate the log probability density function for this distribution using the \\code{dinit} argument.\n##' As usual, this can be provided either as a C snippet or as an \\R function.\n##' In the former case, bear in mind that:\n##' \\enumerate{\n##'   \\item The goal of a this snippet is computation of a log likelihood, to be put into a variable named \\code{loglik}.\n##'   \\item In addition to the state variables, parameters, and covariates (if any), the variable \\code{t}, containing the zero-time, will be defined in the context in which the snippet is executed.\n##' }\n##' \\link[=Csnippet]{General rules for writing C snippets can be found here}.\n##'\n##' If an \\R function is to be used, pass\n##' \\preformatted{\n##'    dinit = f\n##' }\n##' to \\code{pomp}, where \\code{f} is a function with arguments that can include the time \\code{t}, any or all of the model state variables, parameters, and covariates.\n##' As usual, \\code{f} may take additional arguments, provided these are passed along with it in the call to \\code{pomp}.\n##' \\code{f} must return a single numeric value, the log likelihood.\n##'\n##' @inheritSection pomp Note for Windows users\n##'\nNULL\n"
  },
  {
    "path": "R/dmeasure_spec.R",
    "content": "##' dmeasure specification\n##'\n##' Specification of the measurement model density function, dmeasure.\n##'\n##' @name dmeasure_spec\n##' @rdname dmeasure_spec\n##' @family implementation information\n##' @seealso \\code{\\link{dmeasure}}\n##' @details\n##' The measurement model is the link between the data and the unobserved state process.\n##' It can be specified either by using one or both of the \\code{rmeasure} and \\code{dmeasure} arguments.\n##'\n##' Suppose you have a procedure to compute the probability density of an observation given the value of the latent state variables.\n##' Then you can furnish \\preformatted{\n##'    dmeasure = f}\n##' to \\pkg{pomp} algorithms,\n##' where \\code{f} is a C snippet or \\R function that implements your procedure.\n##'\n##' Using a C snippet is much preferred, due to its much greater computational efficiency.\n##' See \\code{\\link{Csnippet}} for general rules on writing C snippets.\n##' The goal of a \\dfn{dmeasure} C snippet is to fill the variable \\code{lik} with the either the probability density or the log probability density, depending on the value of the variable \\code{give_log}.\n##'\n##' In writing a \\code{dmeasure} C snippet, observe that:\n##'   \\enumerate{\n##'     \\item In addition to the states, parameters, covariates (if any), and observables, the variable \\code{t}, containing the time of the observation will be defined in the context in which the snippet is executed.\n##'     \\item Moreover, the Boolean variable \\code{give_log} will be defined.\n##'     \\item The goal of a dmeasure C snippet is to set the value of the predefined \\code{lik} variable to the likelihood of the data given the state, if \\code{give_log == 0}.\n##'     If \\code{give_log == 1}, \\code{lik} should be set to the log likelihood.\n##'   }\n##'\n##' If \\code{dmeasure} is to be provided instead as an \\R function, this is accomplished by supplying \\preformatted{\n##'   dmeasure = f}\n##' to \\code{pomp}, where \\code{f} is a function.\n##' The arguments of \\code{f} should be chosen from among the observables, state variables, parameters, covariates, and time.\n##' It must also have the arguments \\code{\\dots}, and \\code{log}.\n##' It can take additional arguments via the \\link[=userdata]{userdata facility}.\n##' \\code{f} must return a single numeric value, the probability density (or log probability density if \\code{log = TRUE}) of \\code{y} given \\code{x} at time \\code{t}.\n##'\n##' @example examples/dmeasure_spec.R\n##'\n##' @section Important note:\n##' \\strong{It is a common error to fail to account for both \\code{log = TRUE} and \\code{log = FALSE} when writing the \\code{dmeasure} C snippet or function.}\n##'\n##' @section Default behavior:\n##' If \\code{dmeasure} is left unspecified, calls to \\code{\\link{dmeasure}} will return missing values (\\code{NA}).\n##'\n##' @inheritSection pomp Note for Windows users\n##'\nNULL\n"
  },
  {
    "path": "R/dprocess_spec.R",
    "content": "##' dprocess specification\n##'\n##' Specification of the latent state process density function, dprocess.\n##'\n##' @name dprocess_spec\n##' @rdname dprocess_spec\n##' @family implementation information\n##' @seealso \\code{\\link{dprocess}}\n##'\n##' @details\n##' Suppose you have a procedure that allows you to compute the probability density\n##' of an arbitrary transition from state \\eqn{x_1}{x1} at time \\eqn{t_1}{t1}\n##' to state \\eqn{x_2}{x2} at time \\eqn{t_2>t_1}{t2}\n##' under the assumption that the state remains unchanged\n##' between \\eqn{t_1}{t1} and \\eqn{t_2}{t2}.\n##' Then you can furnish\n##' \\preformatted{\n##'     dprocess = f\n##' }\n##' to \\code{pomp}, where \\code{f} is a C snippet or \\R function that implements your procedure.\n##' Specifically, \\code{f} should compute the \\emph{log} probability density.\n##'\n##' Using a C snippet is much preferred, due to its much greater computational efficiency.\n##' See \\code{\\link{Csnippet}} for general rules on writing C snippets.\n##' The goal of a \\dfn{dprocess} C snippet is to fill the predefined variable \\code{loglik} with the log probability density.\n##' In the context of such a C snippet, the parameters, and covariates will be defined, as will the times \\code{t_1} and \\code{t_2}.\n##' The state variables at time \\code{t_1} will have their usual name (see \\code{statenames}) with a \\dQuote{\\code{_1}} appended.\n##' Likewise, the state variables at time \\code{t_2} will have a \\dQuote{\\code{_2}} appended.\n##'\n##' If \\code{f} is given as an \\R function, it should take as arguments any or all of the state variables, parameter, covariates, and time.\n##' The state-variable and time arguments will have suffices \\dQuote{\\code{_1}} and \\dQuote{\\code{_2}} appended.\n##' Thus for example, if \\code{var} is a state variable, when \\code{f} is called, \\code{var_1} will value of state variable \\code{var} at time \\code{t_1}, \\code{var_2} will have the value of \\code{var} at time \\code{t_2}.\n##' \\code{f} should return the \\emph{log} likelihood of a transition from \\code{x1} at time \\code{t1} to \\code{x2} at time \\code{t2},\n##' assuming that no intervening transitions have occurred.\n##'\n##'   To see examples, consult the demos and the tutorials on the \\href{https://kingaa.github.io/pomp/}{package website}.\n##'\n##' @section \\strong{Note}:\n##' It is not typically necessary (or even feasible) to define \\code{dprocess}.\n##' In fact, no current \\pkg{pomp} inference algorithm makes use of \\code{dprocess}.\n##' This functionality is provided only to support future algorithm development.\n##'\n##' @section Default behavior:\n##' By default, \\code{dprocess} returns missing values (\\code{NA}).\n##'\n##' @inheritSection pomp Note for Windows users\n##'\nNULL\n"
  },
  {
    "path": "R/ebola.R",
    "content": "##' Ebola outbreak, West Africa, 2014-2016\n##'\n##' Data and models for the 2014--2016 outbreak of Ebola virus disease in West Africa.\n##'\n##' The data include monthly case counts and death reports derived from WHO situation reports, as reported by the U.S. CDC.\n##' The models are described in King et al. (2015).\n##'\n##' The data-cleaning script is included in the R source code file \\file{ebola.R}.\n##'\n##' @rdname ebola\n##' @name ebola\n##' @aliases ebolaWA2014\n##' @docType data\n##' @include pomp.R\n##' @family pomp datasets\n##' @family pomp examples\n##'\n##' @references\n##'\n##' \\King2015\n##'\n##' \\WHO2014\n##'\n##' \\He2010\n##'\n##' @example examples/ebola.R\n##'\nNULL\n\n##' @rdname ebola\n##' @param country ISO symbol for the country (GIN=Guinea, LBR=Liberia, SLE=Sierra Leone).\n##' @param data if NULL, the situation report data (WHO Ebola Response Team 2014) for the appropriate country or region will be used.\n##' Providing a dataset here will override this behavior.\n##' @param nstageE integer; number of incubation stages.\n##' @param incubation_period,infectious_period mean duration (in days) of the incubation and infectious periods.\n##' @param R0 basic reproduction ratio\n##' @param cfr case fatality rate\n##' @param rho case reporting efficiency\n##' @param k dispersion parameter (negative binomial \\code{size} parameter)\n##' @param index_case number of cases on day 0 (2014-04-01)\n##' @param timestep duration (in days) of Euler timestep for the simulations.\n##'\n##' @section Model structure:\n##' The default incubation period is supposed to be Gamma distributed with shape parameter \\code{nstageE} and mean 11.4 days and the case-fatality ratio (`cfr`) is taken to be 0.7 (cf. WHO Ebola Response Team 2014).\n##' The discrete-time formula is used to calculate the corresponding \\code{alpha} (cf. He et al. 2010).\n##'\n##' The observation model is a hierarchical model for cases and deaths:\n##'   \\deqn{p(R_t, D_t| C_t) = p(R_t | C_t) p(D_t | C_t, R_t).}\n##' Here, \\eqn{p(R_t | C_t)} is negative binomial with mean \\eqn{\\rho C_t} and dispersion parameter \\eqn{1/k};\n##' \\eqn{p(D_t | C_t, R_t)} is binomial with size \\eqn{R_t} and probability equal to the case fatality rate \\code{cfr}.\n##' @export\nebolaModel <- function (\n  country=c(\"GIN\", \"LBR\", \"SLE\"),\n  data = NULL,\n  timestep = 1/8, nstageE = 3L,\n  R0 = 1.4, rho = 0.2, cfr = 0.7, k = 0, index_case = 10,\n  incubation_period = 11.4, infectious_period = 7\n) {\n\n  ## Population sizes in Guinea, Liberia, and Sierra Leone (census 2014)\n  populations <- c(GIN=10628972,LBR=4092310,SLE=6190280)\n\n  pomp::ebolaWA2014 -> dat\n  dat$date <- as.Date(as.character(dat$date))\n  dat$country <- as.character(dat$country)\n  dat$day <- julian(dat$date,origin=as.Date(\"2014-04-01\"))\n\n  ctry <- match.arg(country)\n  pop <- unname(populations[ctry])\n  nstageE <- as.integer(nstageE)\n  dt <- as.numeric(timestep)\n\n  globs <- paste0(\"static int nstageE = \",nstageE,\";\");\n\n  theta <- c(\n    N=pop,R0=1.4,\n    rho=rho,cfr=cfr,k=k,\n    alpha=-1/(nstageE*dt)*log(1-nstageE*dt/incubation_period),\n    gamma=-log(1-dt/infectious_period)/dt,\n    S_0=1-index_case/pop,\n    E_0=index_case/pop/2-5e-9,\n    I_0=index_case/pop/2-5e-9,\n    R_0=1e-8\n  )\n\n  if (is.null(data)) {\n    dat <- subset(dat,country==ctry,select=c(\"day\",\"cases\",\"deaths\"))\n  } else {\n    dat <- data\n  }\n\n  dObs <- Csnippet(\"\n    double f, g;\n    if (k > 0.0) {\n      f = dnbinom_mu(nearbyint(cases),1.0/k,rho*N_EI,give_log);\n      g = dnbinom_mu(nearbyint(deaths),1.0/k,rho*cfr*N_IR,give_log);\n    } else {\n      f = dpois(nearbyint(cases),rho*N_EI,give_log);\n      g = dpois(nearbyint(deaths),rho*cfr*N_IR,give_log);\n    }\n    lik = (give_log) ? f+g : f*g;\n    \"\n  )\n\n  rObs <- Csnippet(\"\n    if (k > 0) {\n      cases = rnbinom_mu(1.0/k,rho*N_EI);\n      deaths = rnbinom_mu(1.0/k,rho*cfr*N_IR);\n    } else {\n      cases = rpois(rho*N_EI);\n      deaths = rpois(rho*cfr*N_IR);\n    }\n    \"\n  )\n\n  rInit <- Csnippet(\"\n    double m = N/(S_0+E_0+I_0+R_0);\n    double *E = &E1;\n    int j;\n    S = nearbyint(m*S_0);\n    for (j = 0; j < nstageE; j++) E[j] = nearbyint(m*E_0/nstageE);\n    I = nearbyint(m*I_0);\n    R = nearbyint(m*R_0);\n    N_EI = 0;\n    N_IR = 0;\n    \"\n  )\n\n  rSim <- Csnippet(\"\n    double lambda, beta;\n    double *E = &E1;\n    beta = R0 * gamma; // Transmission rate\n    lambda = beta * I / N; // Force of infection\n    int i;\n\n    // Transitions\n    // From class S\n    double transS = rbinom(S, 1.0 - exp(- lambda * dt)); // No of infections\n    // From class E\n    double transE[nstageE]; // No of transitions between classes E\n    for(i = 0; i < nstageE; i++){\n      transE[i] = rbinom(E[i], 1.0 - exp(- nstageE * alpha * dt));\n    }\n    // From class I\n    double transI = rbinom(I, 1.0 - exp(- gamma * dt)); // No of transitions I->R\n\n    // Balance the equations\n    S -= transS;\n    E[0] += transS - transE[0];\n    for(i=1; i < nstageE; i++) {\n      E[i] += transE[i-1] - transE[i];\n    }\n    I += transE[nstageE - 1] - transI;\n    R += transI;\n    N_EI += transE[nstageE - 1]; // No of transitions from E to I\n    N_IR += transI; // No of transitions from I to R\n    \"\n  )\n\n  skel <- Csnippet(\"\n    double lambda, beta;\n    const double *E = &E1;\n    double *DE = &DE1;\n    beta = R0 * gamma; // Transmission rate\n    lambda = beta * I / N; // Force of infection\n    int i;\n\n    // Balance the equations\n    DS = - lambda * S;\n    DE[0] = lambda * S - nstageE * alpha * E[0];\n    for (i=1; i < nstageE; i++)\n      DE[i] = nstageE * alpha * (E[i-1]-E[i]);\n    DI = nstageE * alpha * E[nstageE-1] - gamma * I;\n    DR = gamma * I;\n    DN_EI = nstageE * alpha * E[nstageE-1];\n    DN_IR = gamma * I;\n    \"\n  )\n\n  pomp(\n    data=dat,\n    times=\"day\",\n    t0=0,\n    params=theta,\n    globals=globs,\n    rinit=rInit,\n    rprocess=discrete_time(rSim,delta.t=timestep),\n    dmeasure=dObs,\n    rmeasure=rObs,\n    skeleton=vectorfield(skel),\n    partrans=parameter_trans(\n      log=c(\"N\",\"R0\",\"alpha\",\"gamma\",\"k\"),\n      logit=c(\"rho\",\"cfr\"),\n      barycentric=c(\"S_0\",\"E_0\",\"I_0\",\"R_0\")\n    ),\n    statenames=c(\"S\",sprintf(\"E%d\",1:nstageE),\"I\",\"R\",\"N_EI\",\"N_IR\"),\n    paramnames=c(\"N\",\"R0\",\"alpha\",\"gamma\",\"rho\",\"k\",\"cfr\",\n      \"S_0\",\"E_0\",\"I_0\",\"R_0\"),\n    accumvars=c(\"N_EI\",\"N_IR\")\n  )\n\n}\n\n## This codes below processes case count and death data from the 2014-2016 Ebola\n## outbreak in West Africa, as provided by the WHO via US CDC.\n## In particular, the following are purportedly the\n## \"Number of Cases and Deaths in Guinea, Liberia, and Sierra Leone\n## during the 2014-2016 West Africa Ebola Outbreak.\"\n## These data were accessed from\n## https://www.cdc.gov/vhf/ebola/history/2014-2016-outbreak/case-counts.html\n## on 2019-03-09 and are included below.\n##\n## Variables are:\n## - WHO report date\n## - Total Cases, Guinea\n## - Total Deaths, Guinea\n## - Total Cases, Liberia\n## - Total Deaths, Liberia\n## - Total Cases, Sierra Leone\n## - Total Deaths, Sierra Leone\n## - Total Cases\n## - Total Deaths\n##\n## In this script, these data are processed to produce monthly incidence\n## and deaths for each of the three countries.\n##\n\n## BEGIN DATA-CLEANING CODE\n## \"date,cases_GIN,deaths_GIN,cases_LBR,deaths_LBR,cases_SLE,deaths_SLE,cases_total,deaths_total\n## 4/13/2016,3814,2544,10678,4810,14124,3956,28616,11310\n## 3/30/2016,3811,2543,10675,4809,14124,3956,28610,11308\n## 3/23/2016,3809,2540,10675,4809,14124,3956,28608,11305\n## 3/3/2016,3804,2536,10675,4809,14124,3956,28603,11301\n## 2/17/2016,3804,2536,10675,4809,14124,3956,28603,11301\n## 2/10/2016,3804,2536,10675,4809,14124,3956,28603,11301\n## 2/3/2016,3804,2536,10675,4809,14124,3956,28603,11301\n## 1/27/2016,3804,2536,10675,4809,14124,3956,28603,11301\n## 1/20/2016,3804,2536,10675,4809,14123,3956,28602,11301\n## 1/13/2016,3804,2536,10675,4809,14122,3955,28601,11300\n## 1/6/2016,3804,2536,10675,4809,14122,3955,28601,11300\n## 12/30/2015,3804,2536,10675,4809,14122,3955,28601,11300\n## 12/29/2015,3804,2536,10675,4809,14122,3955,28601,11300\n## 12/28/2015,3804,2536,10675,4809,14122,3955,28601,11300\n## 12/25/2015,3805,2536,10675,4809,14122,3955,28602,11300\n## 12/24/2015,3804,2536,10675,4809,14122,3955,28601,11300\n## 12/23/2015,3804,2536,10675,4809,14122,3955,28601,11300\n## 12/22/2015,3804,2536,10675,4809,14122,3955,28601,11300\n## 12/21/2015,3804,2536,10675,4809,14122,3955,28601,11300\n## 12/18/2015,3804,2536,10675,4809,14122,3955,28601,11300\n## 12/17/2015,3805,2536,10675,4809,14122,3955,28602,11300\n## 12/16/2015,3807,2536,10675,4809,14122,3955,28604,11300\n## 12/15/2015,3807,2536,10675,4809,14122,3955,28604,11300\n## 12/14/2015,3806,2536,10675,4809,14122,3955,28603,11300\n## 12/11/2015,3804,2536,10675,4809,14122,3955,28601,11300\n## 12/10/2015,3804,2536,10675,4809,14122,3955,28601,11300\n## 12/9/2015,3804,2536,10675,4809,14122,3955,28601,11300\n## 12/8/2015,3804,2536,10675,4809,14122,3955,28601,11300\n## 12/7/2015,3804,2536,10675,4809,14122,3955,28601,11300\n## 12/4/2015,3805,2536,10675,4809,14122,3955,28602,11300\n## 12/3/2015,3805,2536,10675,4809,14122,3955,28602,11300\n## 12/2/2015,3804,2536,10675,4809,14122,3955,28601,11300\n## 12/1/2015,3804,2536,10675,4808,14122,3955,28601,11299\n## 11/30/2015,3804,2536,10675,4808,14122,3955,28601,11299\n## 11/27/2015,3804,2536,10675,4808,14122,3955,28601,11299\n## 11/26/2015,3804,2536,10675,4808,14122,3955,28601,11299\n## 11/25/2015,3804,2536,10675,4808,14122,3955,28601,11299\n## 11/24/2015,3804,2536,10672,4808,14122,3955,28598,11299\n## 11/23/2015,3804,2536,10672,4808,14122,3955,28598,11299\n## 11/20/2015,3804,2536,10672,4808,14122,3955,28598,11299\n## 11/19/2015,3806,2536,10672,4808,14122,3955,28600,11299\n## 11/18/2015,3804,2536,10672,4808,14122,3955,28598,11299\n## 11/17/2015,3404,2536,10672,4808,14122,3955,28598,11299\n## 11/16/2015,3805,2536,10672,4808,14122,3955,28599,11299\n## 11/12/2015,3805,2536,10672,4808,14122,3955,28599,11299\n## 11/10/2015,3805,2536,10672,4808,14122,3955,28599,11299\n## 11/9/2015,3806,2536,10672,4808,14122,3955,28600,11299\n## 11/6/2015,3805,2536,10672,4808,14109,3955,28586,11299\n## 11/5/2015,3805,2536,10672,4808,14104,3955,28581,11299\n## 11/3/2015,3810,2536,10672,4808,14089,3955,28571,11299\n## 11/2/2015,3808,2536,10672,4808,14078,3955,28558,11299\n## 10/30/2015,3808,2536,10672,4808,14067,3955,28547,11299\n## 10/29/2015,3808,2536,10672,4808,14066,3955,28546,11299\n## 10/27/2015,3806,2535,10672,4808,14061,3955,28539,11298\n## 10/26/2015,3804,2535,10672,4808,14052,3955,28528,11298\n## 10/23/2015,3801,2535,10672,4808,14038,3955,28511,11298\n## 10/22/2015,3801,2535,10672,4808,14031,3955,28504,11298\n## 10/20/2015,3803,2535,10672,4808,14001,3955,28476,11298\n## 10/19/2015,3806,2535,10672,4808,13999,3955,28513,11298\n## 10/16/2015,3804,2535,10672,4808,13992,3955,28468,11298\n## 10/15/2015,3802,2534,10672,4808,13992,3955,28466,11297\n## 10/13/2015,3800,2534,10672,4808,13982,3955,28454,11297\n## 10/12/2015,3798,2534,10672,4808,13978,3955,28448,11297\n## 10/9/2015,3800,2534,10672,4808,13957,3955,28429,11297\n## 10/8/2015,3799,2534,10672,4808,13956,3955,28427,11297\n## 10/7/2015,3804,2534,10672,4808,13945,3955,28421,11297\n## 10/5/2015,3804,2534,10672,4808,13941,3955,28417,11297\n## 10/2/2015,3809,2533,10672,4808,13931,3955,28412,11296\n## 10/1/2015,3808,2533,10672,4808,13928,3955,28408,11296\n## 9/29/2015,3805,2533,10672,4808,13911,3955,28388,11296\n## 9/28/2015,3805,2533,10672,4808,13894,3955,28371,11296\n## 9/24/2015,3801,2533,10672,4808,13846,3955,28319,11296\n## 9/22/2015,3800,2532,10672,4808,13823,3955,28295,11295\n## 9/21/2015,3797,2532,10672,4808,13811,3955,28280,11295\n## 9/18/2015,3794,2531,10672,4808,13785,3955,28251,11294\n## 9/17/2015,3794,2530,10672,4808,13573,3955,28245,11293\n## 9/15/2015,3792,2530,10672,4808,13756,3953,28220,11291\n## 9/14/2015,3793,2530,10672,4808,13747,3953,28212,11291\n## 9/11/2015,3791,2530,10672,4808,13701,3953,28164,11291\n## 9/10/2015,3791,2530,10672,4808,13697,3953,28160,11291\n## 9/8/2015,3792,2530,10672,4808,13683,3953,28147,11291\n## 9/4/2015,3792,2529,10672,4808,13639,3953,28103,11290\n## 9/3/2015,3792,2529,10672,4808,13638,3953,28102,11290\n## 9/1/2015,3792,2529,10672,4808,13609,3953,28073,11290\n## 8/31/2015,3790,2528,10672,4808,13603,3953,28065,11289\n## 8/28/2015,3797,2528,10672,4808,13586,3952,28055,11288\n## 8/27/2015,3797,2528,10672,4808,13582,3952,28051,11288\n## 8/25/2015,3792,2527,10672,4808,13541,3952,28005,11287\n## 8/24/2015,3790,2527,10672,4808,13538,3952,28000,11287\n## 8/21/2015,3795,2526,10672,4808,13533,3952,28000,11286\n## 8/20/2015,3792,2526,10672,4808,13518,3952,27982,11286\n## 8/18/2015,3786,2524,10672,4808,13494,3952,27952,11284\n## 8/17/2015,3790,2524,10672,4808,13489,3952,27951,11284\n## 8/14/2015,3791,2524,10672,4808,13485,3952,27948,11284\n## 8/13/2015,3792,2524,10672,4808,13484,3951,27948,11283\n## 8/11/2015,3787,2524,10672,4808,13470,3951,27929,11283\n## 8/10/2015,3791,2524,10672,4808,13465,3951,27928,11283\n## 8/7/2015,3795,2524,10672,4808,13428,3951,27895,11283\n## 8/6/2015,3792,2524,10672,4808,13426,3951,27890,11283\n## 8/5/2015,3784,2522,10672,4808,13406,3951,27862,11281\n## 8/4/2015,3784,2522,10672,4808,13406,3951,27862,11281\n## 8/3/2015,3786,2522,10672,4808,13402,3951,27860,11281\n## 7/31/2015,3781,2521,10672,4808,13387,3951,27840,11280\n## 7/30/2015,3785,2521,10672,4808,13379,3951,27836,11280\n## 7/29/2015,3786,2520,10672,4808,13290,3951,27748,11279\n## 7/28/2015,3786,2520,10673,4808,13291,3951,27750,11279\n## 7/27/2015,3792,2519,10673,4808,13284,3951,27749,11278\n## 7/24/2015,3787,2517,10673,4808,13264,3949,27724,11274\n## 7/23/2015,3788,2516,10673,4808,13262,3949,27723,11273\n## 7/22/2015,3783,2512,10672,4808,13250,3949,27705,11269\n## 7/21/2015,3783,2512,10673,4808,13250,3949,27706,11269\n## 7/20/2015,3784,2511,10673,4808,13241,3949,27698,11268\n## 7/17/2015,3770,2509,10673,4808,13209,3947,27652,11264\n## 7/16/2015,3762,2506,10672,4808,13209,3947,27643,11261\n## 7/15/2015,3760,2506,10673,4808,13209,3947,27642,11261\n## 7/14/2015,3760,2506,10673,4808,13209,3947,27642,11261\n## 7/13/2015,3754,2506,10672,4807,13201,3946,27627,11259\n## 7/10/2015,3751,2505,10672,4807,13177,3941,27600,11253\n## 7/9/2015,3744,2505,10672,4807,13169,3941,27585,11253\n## 7/8/2015,3748,2499,10670,4807,13155,3940,27573,11246\n## 7/5/2015,3748,2499,10670,4807,13155,3940,27573,11246\n## 7/4/2015,3744,2492,10670,4807,13150,3940,27564,11245\n## 7/3/2015,3750,2492,10706,4811,13135,3935,27591,11238\n## 6/30/2015,3745,2490,10666,4806,13129,3933,27540,11229\n## 6/30/2015,3729,2482,10666,4806,13119,3932,27514,11220\n## 6/29/2015,3724,2482,10666,4806,13115,3932,27505,11220\n## 6/24/2015,3720,2480,10666,4806,13093,3931,24479,11217\n## 6/23/2015,3718,2480,10666,4806,13083,3931,27467,11217\n## 6/21/2015,3718,2473,10666,4806,13059,3928,27443,11207\n## 6/17/2015,3674,2446,10666,4806,13012,3926,27352,11178\n## 6/16/2015,3675,2445,10666,4806,12990,3922,27331,11173\n## 6/14/2015,3678,2444,10666,4806,12965,3919,27309,11169\n## 6/13/2015,3677,2443,10666,4806,12962,3919,27305,11168\n## 6/10/2015,3677,2440,10666,4806,12932,3917,27275,11163\n## 6/9/2015,3674,2440,10666,4806,12911,3917,27251,11163\n## 6/7/2015,3670,2437,10666,4806,12901,3915,27237,11158\n## 6/6/2015,3669,2435,10666,4806,12884,3913,27219,11154\n## 6/5/2015,3664,2431,10666,4806,12859,3912,27189,11149\n## 6/4/2015,3657,2431,10666,4806,12850,3912,27173,11149\n## 5/31/2015,3652,2429,10666,4806,12827,3912,27145,11147\n## 5/30/2015,3653,2428,10666,4806,12816,3911,27135,11145\n## 5/27/2015,3644,2425,10666,4806,12745,3911,27055,11142\n## 5/26/2015,3639,2423,10666,4806,12735,3911,27040,11140\n## 5/24/2015,3641,2420,10666,4806,12706,3908,27013,11134\n## 5/20/2015,3647,2412,10666,4806,12666,3907,26979,11125\n## 5/19/2015,3649,2409,10666,4806,12656,3907,26971,11122\n## 5/16/2015,3626,2405,10666,4806,12593,3906,26885,11117\n## 5/13/2015,3619,2401,10604,4769,12540,3904,26763,11074\n## 5/12/2015,3615,2399,10604,4769,12536,3904,26755,11072\n## 5/10/2015,3597,2392,10604,4769,12523,3904,26724,11065\n## 5/9/2015,3599,2391,10604,4769,12519,3904,26722,11064\n## 5/6/2015,3592,2387,10564,4716,12492,3904,26648,11007\n## 5/5/2015,3592,2387,10564,4716,12470,3904,26626,11007\n## 5/3/2015,3589,2386,10564,4716,12440,3903,26593,11005\n## 5/3/2015,3589,2386,10507,4691,12440,3903,26536,10980\n## 5/2/2015,3591,2385,10322,4608,12426,3902,26339,10895\n## 4/29/2015,3578,2383,10322,4608,12398,3901,26298,10892\n## 4/28/2015,3581,2381,10322,4608,12387,3901,26290,10890\n## 4/26/2015,3584,2377,10322,4608,12371,3899,26277,10884\n## 4/24/2015,3585,2374,10212,4573,12362,3895,26159,10842\n## 4/22/2015,3576,2365,10212,4573,12313,3886,26101,10824\n## 4/21/2015,3568,2362,10212,4573,12294,3885,26074,10820\n## 4/19/2015,3565,2358,10212,4573,12267,3877,26044,10808\n## 4/19/2015,3565,2358,10042,4486,12256,3877,25872,10721\n## 4/18/2015,3565,2357,10042,4486,12256,3872,25863,10715\n## 4/17/2015,3569,2351,10042,4486,12244,3865,25855,10702\n## 4/16/2015,3566,2348,10042,4486,12223,3865,25831,10699\n## 4/15/2015,3548,2346,10042,4486,12201,3857,25791,10689\n## 4/14/2015,3548,2346,9862,4408,12201,3857,25611,10611\n## 4/13/2015,3541,2342,9862,4408,12188,3854,25591,10604\n## 4/10/2015,3524,2337,9862,4408,12170,3842,25556,10587\n## 4/9/2015,3515,2335,9862,4408,12155,3841,25532,10584\n## 4/8/2015,3515,2333,9862,4408,12138,3831,25515,10572\n## 4/7/2015,3515,2333,9862,4408,12139,3832,25516,10573\n## 4/2/2015,3494,2320,9712,4332,12022,3810,25228,10462\n## 4/1/2015,3492,2314,9712,4332,11974,3799,25178,10445\n## 3/31/2015,3492,2314,9712,4332,11974,3799,25178,10445\n## 3/30/2015,3485,2305,9602,4301,11943,3792,25030,10398\n## 3/27/2015,3466,2276,9602,4301,11889,3773,24957,10350\n## 3/26/2015,3459,2273,9602,4301,11866,3764,24927,10338\n## 3/25/2015,3429,2263,9602,4301,11841,3747,24872,10311\n## 3/18/2015,3389,2224,9526,4264,11751,3691,24666,10179\n## 3/11/2015,3285,2170,9343,4162,11619,3629,24247,9961\n## 3/4/2015,3219,2129,9249,4117,11466,3546,23934,9792\n## 2/25/2015,3155,2091,9238,4037,11301,3461,23694,9589\n## 2/18/2015,3108,2057,9007,3900,11103,3408,23218,9365\n## 2/11/2015,3044,1995,8881,3826,10934,3341,22859,9162\n## 2/4/2015,2975,1944,8745,3746,10740,3276,22460,8966\n## 1/28/2015,2917,1910,8622,3686,10518,3199,22057,8795\n## 1/21/2015,2871,1876,8478,3605,10340,3145,21689,8626\n## 1/14/2015,2806,1814,8331,3538,10124,3062,21261,8414\n## 1/7/2015,2775,1781,8157,3496,9780,2943,20712,8220\n## 12/31/2014,2707,1708,8018,3423,9446,2758,20171,7889\n## 12/24/2014,2597,1607,7862,3384,9004,2582,19463,7573\n## 12/17/2014,2416,1525,7797,3290,8356,2085,18569,6900\n## 12/10/2014,2292,1428,7719,3177,7897,1768,17908,6373\n## 12/3/2014,2164,1327,7635,3145,7312,1583,17111,6055\n## 11/28/2014,2155,1312,7635,3145,7109,1530,16899,5987\n## 11/26/2014,2134,1260,7168,3016,6599,1398,15901,5674\n## 11/21/2014,2047,1214,7082,2963,6190,1267,15319,5444\n## 11/19/2014,1971,1192,7069,2964,6073,1250,15113,5406\n## 11/14/2014,1919,1166,6878,2812,5586,1187,14383,5165\n## 11/12/2014,1878,1142,6822,2836,5368,1169,14068,5147\n## 11/7/2014,1760,1054,6619,2766,4862,1130,13241,4950\n## 11/5/2014,1731,1041,6525,2697,4759,1070,13015,4808\n## 10/31/2014,1667,1018,6535,2413,5338,1510,13540,4941\n## 10/29/2014,1906,997,6535,2413,5235,1500,13676,4910\n## 10/25/2014,1553,926,4665,2705,3896,1281,10114,4912\n## 10/22/2014,1540,904,4665,2705,3706,1359,9911,4968\n## 10/17/2014,1519,862,4262,2484,3410,1200,9191,4546\n## 10/15/2014,1472,843,4249,2458,3252,1183,8973,4484\n## 10/10/2014,1350,778,4076,2316,2950,930,8376,4024\n## 10/8/2014,1298,768,3924,2210,2789,879,8011,3857\n## 10/3/2014,1199,739,3834,2069,2437,623,7470,3431\n## 10/1/2014,1157,710,3696,1998,2304,622,7157,3330\n## 9/26/2014,1074,648,3458,1830,2021,605,6553,3083\n## 9/24/2014,1022,635,3280,1677,1940,597,6242,2909\n## 9/22/2014,1008,632,3022,1578,1813,593,5843,2803\n## 9/18/2014,942,601,2710,1459,1673,562,5325,2622\n## 9/16/2014,936,595,2407,1296,1620,562,4963,2453\n## 9/12/2014,861,557,2081,1137,1424,524,4366,2218\n## 9/8/2014,862,555,2046,1224,1361,509,4269,2288\n## 9/6/2014,812,517,1871,1089,1261,491,3944,2097\n## 8/28/2014,648,430,1378,694,1026,422,3052,1546\n## 8/22/2014,607,406,1082,624,910,392,2599,1422\n## 8/21/2014,579,396,972,576,907,374,2458,1346\n## 8/19/2014,543,394,834,466,848,365,2225,1225\n## 8/15/2014,519,380,786,348,810,348,2115,1076\n## 8/13/2014,510,377,670,355,783,334,1963,1066\n## 8/12/2014,506,373,599,323,730,315,1835,1011\n## 8/8/2014,495,367,554,294,717,298,1766,959\n## 8/4/2014,485,358,486,255,646,273,1617,886\n## 8/3/2014,472,346,391,227,574,252,1437,825\n## 7/31/2014,460,339,329,156,533,233,1322,728\n## 7/28/2014,427,319,249,129,525,224,1201,672\n## 7/24/2014,415,314,224,127,454,219,1093,660\n## 7/21/2014,410,310,196,116,442,206,1048,632\n## 7/16/2014,406,304,172,105,386,192,964,601\n## 7/14/2014,409,309,142,88,337,142,888,539\n## 7/8/2014,408,307,131,84,305,127,844,518\n## 7/7/2014,412,305,115,75,252,101,779,481\n## 7/2/2014,413,303,107,65,239,99,759,467\n## 6/24/2014,390,270,51,34,158,34,599,338\n## 6/18/2014,398,264,33,24,97,49,528,337\n## 6/11/2014,376,241,15,10,117,19,508,270\n## 6/10/2014,372,236,15,10,89,7,476,253\n## 6/5/2014,344,215,13,9,81,7,438,231\n## 6/2/2014,291,193,13,9,50,6,354,208\n## 5/28/2014,281,186,12,9,16,5,309,200\n## 5/27/2014,258,174,12,9,1,4,271,187\n## 5/23/2014,258,174,12,9,0,0,270,183\n## 5/14/2014,233,157,12,11,0,0,245,168\n## 5/5/2014,231,155,13,11,0,0,244,166\n## 4/30/2014,221,146,13,11,0,0,234,157\n## 4/23/2014,208,136,34,11,0,0,242,147\n## 4/21/2014,203,129,27,13,0,0,230,142\n## 4/17/2014,197,122,27,13,0,0,224,135\n## 4/10/2014,157,101,22,14,0,0,179,115\n## 4/7/2014,151,95,18,7,0,0,169,102\n## 4/2/2014,127,83,8,5,0,0,135,88\n## 4/1/2014,122,80,8,2,0,0,130,82\n## 3/31/2014,112,70,8,6,0,0,120,76\n## 3/27/2014,103,66,8,6,6,5,117,77\n## 3/26/2014,86,60,0,0,0,0,86,60\n## 3/25/2014,86,59,0,0,0,0,86,59\n## \" -> dat_text\n\n## library(tidyverse)\n## library(lubridate)\n\n## read_csv(dat_text,comment=\"#\") |>\n##   mutate(date=as.Date(date,format=\"%m/%d/%Y\")) |>\n##   gather(variable,value,-date) |>\n##   separate(variable,into=c(\"vbl\",\"country\")) |>\n##   filter(country != \"total\") |>\n##   group_by(vbl,country) |>\n##   arrange(date) |>\n##   mutate(value=value-lag(value)) |>\n##   filter(!is.na(value)) |>\n##   ungroup() |>\n##   group_by(date,country,vbl) |>\n##   summarize(value=sum(value)) |>\n##   ungroup() |>\n##   mutate(date=ceiling_date(date,\"month\")-ddays(1)) |>\n##   group_by(date,vbl,country) |>\n##   summarize(value=sum(value)) |>\n##   group_by(date,country) |>\n##   spread(vbl,value) |>\n##   ungroup() |>\n##   filter(date>\"2014-04-01\") |>\n##   mutate(\n##     cases=pmax(cases,0),\n##     deaths=pmax(deaths,0)\n##   ) |>\n##   as.data.frame() -> ebolaWA2014\n\n## save(ebolaWA2014,file=\"ebolaWA2014.rda\",compress=\"xz\")\n## END DATA-CLEANING CODE\n"
  },
  {
    "path": "R/eff_sample_size.R",
    "content": "##' Effective sample size\n##'\n##' Estimate the effective sample size of a Monte Carlo computation.\n##'\n##' Effective sample size is computed as\n##' \\deqn{\\left(\\sum_i\\!w_{it}^2\\right)^{-1},}{1/(sum(w_it^2)),}\n##' where \\eqn{w_{it}}{w_it} is the normalized weight of particle \\eqn{i} at time \\eqn{t}.\n##'\n##' @name eff_sample_size\n##' @rdname eff_sample_size\n##' @include pfilter.R wpfilter.R bsmc2.R\n##' @aliases eff_sample_size,missing-method eff_sample_size,ANY-method\n##' @family particle filter methods\n##' @family extraction methods\n##' @inheritParams filter_mean\n##'\nNULL\n\nsetGeneric(\n  \"eff_sample_size\",\n  function (object, ...)\n    standardGeneric(\"eff_sample_size\")\n)\n\nsetMethod(\n  \"eff_sample_size\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"eff_sample_size\",\"object\")\n  }\n)\n\nsetMethod(\n  \"eff_sample_size\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"eff_sample_size\",object)\n  }\n)\n\n##' @rdname eff_sample_size\n##' @export\nsetMethod(\n  \"eff_sample_size\",\n  signature=signature(object=\"bsmcd_pomp\"),\n  definition=function (object, ...,\n    format = c(\"numeric\", \"data.frame\")) {\n    format <- match.arg(format)\n    if (format == \"numeric\") {\n      object@eff.sample.size\n    } else {\n      data.frame(\n        time=time(object),\n        eff.sample.size=object@eff.sample.size\n      )\n    }\n  }\n)\n\n##' @rdname eff_sample_size\n##' @export\nsetMethod(\n  \"eff_sample_size\",\n  signature=signature(object=\"pfilterd_pomp\"),\n  definition=function (object, ...,\n    format = c(\"numeric\", \"data.frame\")) {\n    format <- match.arg(format)\n    if (format == \"numeric\") {\n      object@eff.sample.size\n    } else {\n      data.frame(\n        time=time(object),\n        eff.sample.size=object@eff.sample.size\n      )\n    }\n  }\n)\n\n##' @rdname eff_sample_size\n##' @export\nsetMethod(\n  \"eff_sample_size\",\n  signature=signature(object=\"wpfilterd_pomp\"),\n  definition=function (object, ...,\n    format = c(\"numeric\", \"data.frame\")) {\n    format <- match.arg(format)\n    if (format == \"numeric\") {\n      object@eff.sample.size\n    } else {\n      data.frame(\n        time=time(object),\n        eff.sample.size=object@eff.sample.size\n      )\n    }\n  }\n)\n\n##' @rdname eff_sample_size\n##' @export\nsetMethod(\n  \"eff_sample_size\",\n  signature=signature(object=\"pfilterList\"),\n  definition=function (object, ...,\n    format = c(\"numeric\", \"data.frame\")) {\n    format <- match.arg(format)\n    x <- lapply(object,eff_sample_size,format=format)\n    if (format == \"data.frame\") {\n      x <- rbind_fill(x,.id=\".id\")\n    }\n    x\n  }\n)\n"
  },
  {
    "path": "R/elementary_algorithms.R",
    "content": "##' Elementary computations on POMP models.\n##'\n##' In \\pkg{pomp}, elementary algorithms perform POMP model operations.\n##' These operations do not themselves estimate parameters, though they may be instrumental in inference methods.\n##'\n##' There are six elementary algorithms in \\pkg{pomp}:\n##' \\itemize{\n##' \\item \\code{\\link{simulate}} which simulates from the joint distribution of latent and observed variables,\n##' \\item \\code{\\link{pfilter}}, which performs a simple particle filter operation,\n##' \\item \\code{\\link{wpfilter}}, which performs a weighted particle filter operation,\n##' \\item \\code{\\link{probe}}, which computes a suite of user-specified summary statistics on actual and simulated data,\n##' \\item \\code{\\link{spect}}, which performs a power-spectral density function computation on actual and simulated data,\n##' \\item \\code{\\link{trajectory}}, which iterates or integrates the deterministic skeleton according to whether the latter is a (discrete-time) map or a (continuous-time) vectorfield.\n##' }\n##'\n##' Help pages detailing each elementary algorithm component are provided.\n##' @name elementary_algorithms\n##' @rdname elementary_algorithms\n##' @family elementary algorithms\n##' @seealso \\link[=basic_components]{basic model components},\n##' \\link[=workhorses]{workhorse functions},\n##' \\link[=estimation_algorithms]{estimation algorithms}.\n##'\nNULL\n"
  },
  {
    "path": "R/emeasure_spec.R",
    "content": "##' emeasure specification\n##'\n##' Specification of the measurement-model conditional expectation, emeasure.\n##'\n##' @name emeasure_spec\n##' @rdname emeasure_spec\n##' @family implementation information\n##' @seealso \\code{\\link{emeasure}}\n##'\n##' @details\n##' The measurement model is the link between the data and the unobserved state process.\n##' Some algorithms require the conditional expectation of the measurement model, given the latent state and parameters.\n##' This is supplied using the \\code{emeasure} argument.\n##'\n##' Suppose you have a procedure to compute this conditional expectation, given the value of the latent state variables.\n##' Then you can furnish \\preformatted{\n##'   emeasure = f}\n##' to \\pkg{pomp} algorithms,\n##' where \\code{f} is a C snippet or \\R function that implements your procedure.\n##'\n##' Using a C snippet is much preferred, due to its much greater computational efficiency.\n##' See \\code{\\link{Csnippet}} for general rules on writing C snippets.\n##'\n##' In writing an \\code{emeasure} C snippet, bear in mind that:\n##'   \\enumerate{\n##'     \\item The goal of such a snippet is to fill variables named \\code{E_y} with the conditional expectations of observables \\code{y}.\n##'     Accordingly, there should be one assignment of \\code{E_y} for each observable \\code{y}.\n##'     \\item In addition to the states, parameters, and covariates (if any), the variable \\code{t}, containing the time of the observation, will be defined in the context in which the snippet is executed.\n##'   }\n##'\n##' The demos and the tutorials on the \\href{https://kingaa.github.io/pomp/}{package website} give examples.\n##'\n##' It is also possible, though less efficient, to specify \\code{emeasure} using an \\R function.\n##' In this case, specify the measurement model expectation by furnishing \\preformatted{\n##'   emeasure = f}\n##' to \\code{pomp}, where \\code{f} is an \\R function.\n##' The arguments of \\code{f} should be chosen from among the state variables, parameters, covariates, and time.\n##' It must also have the argument \\code{...}.\n##' \\code{f} must return a named numeric vector of length equal to the number of observable variables.\n##' The names should match those of the observable variables.\n##'\n##' @section Default behavior:\n##' The default \\code{emeasure} is undefined.\n##' It will yield missing values (\\code{NA}).\n##'\n##' @inheritSection pomp Note for Windows users\n##'\nNULL\n"
  },
  {
    "path": "R/estimation_algorithms.R",
    "content": "##' Parameter estimation algorithms for POMP models.\n##'\n##' \\pkg{pomp} currently implements the following algorithms for estimating model parameters:\n##' \\itemize{\n##' \\item \\link[=mif2]{iterated filtering (IF2)}\n##' \\item \\link[=pmcmc]{particle Markov chain Monte Carlo (PMCMC)}\n##' \\item \\link[=abc]{approximate Bayesian computation (ABC)}\n##' \\item \\link[=probe_match]{probe-matching via synthetic likelihood}\n##' \\item \\link[=nlf]{nonlinear forecasting}\n##' \\item \\link[=spect_match]{power-spectrum matching}\n##' \\item \\link[=bsmc2]{Liu-West Bayesian sequential Monte Carlo}\n##' \\item \\link[=kalman]{Ensemble and ensemble-adjusted Kalman filters}\n##' }\n##'\n##' Help pages detailing each estimation algorithm are provided.\n##'\n##' @name estimation_algorithms\n##' @rdname estimation_algorithms\n##' @family estimation methods\n##' @seealso \\link[=basic_components]{basic model components},\n##' \\link[=workhorses]{workhorse functions},\n##' \\link[=elementary_algorithms]{elementary algorithms}.\n##'\nNULL\n"
  },
  {
    "path": "R/eulermultinom.R",
    "content": "##' Eulermultinomial and Gamma-whitenoise distributions\n##'\n##' \\pkg{pomp} provides a number of probability distributions that have proved useful in modeling partially observed Markov processes.\n##' These include the Euler-multinomial family of distributions and\n##' the the Gamma white-noise processes.\n##'\n##' If \\eqn{N} individuals face constant hazards of death in \\eqn{K} ways\n##' at rates \\eqn{r_1, r_2, \\dots, r_K}{r1,r2,\\dots,rK},\n##' then in an interval of duration \\eqn{\\Delta{t}}{dt},\n##' the number of individuals remaining alive and dying in each way is multinomially distributed:\n##' \\deqn{(\\Delta{n_0}, \\Delta{n_1}, \\dots, \\Delta{n_K}) \\sim \\mathrm{Multinomial}(N;p_0,p_1,\\dots,p_K),}{(dn0, dn1, \\dots, dnK) ~ multinomial(N; p0, p1, \\dots, pK),}\n##' where \\eqn{\\Delta{n_0}=N-\\sum_{k=1}^K \\Delta{n_k}}{dn0 = N - sum(dnk,k=1:K)} is the number of individuals remaining alive and\n##' \\eqn{\\Delta{n_k}}{dnk} is the number of individuals dying in way \\eqn{k} over the interval.\n##' Here, the probability of remaining alive is \\deqn{p_0=\\exp(-\\sum_k r_k \\Delta{t})}{p0 = exp(-sum(rk, k=1:K)*dt)}\n##' and the probability of dying in way \\eqn{k} is \\deqn{p_k=\\frac{r_k}{\\sum_j r_j} (1-p_0).}{pk = (1-p0)*rk/sum(rj, j=1:K).}\n##' In this case, we say that \\deqn{(\\Delta{n_1},\\dots,\\Delta{n_K})\\sim\\mathrm{Eulermultinom}(N,r,\\Delta t),}{(dn1,\\dots,dnK) ~ eulermultinom(N,r,dt),} where \\eqn{r=(r_1,\\dots,r_K)}{r=(r1,\\dots,rK)}.\n##' Draw \\eqn{m} random samples from this distribution by doing \\preformatted{\n##'     dn <- reulermultinom(n=m,size=N,rate=r,dt=dt),\n##' } where \\code{r} is the vector of rates.\n##' Evaluate the probability that \\eqn{x=(x_1,\\dots,x_K)}{x=(x1,\\dots,xK)} are the numbers of individuals who have died in each of the \\eqn{K} ways over the interval \\eqn{\\Delta t=}{dt=}\\code{dt},\n##' by doing \\preformatted{\n##'     deulermultinom(x=x,size=N,rate=r,dt=dt).\n##' }\n##'\n##' Bretó & Ionides (2011) discuss how an infinitesimally overdispersed death process can be constructed by compounding a multinomial process with a Gamma white noise process.\n##' The Euler approximation of the resulting process can be obtained as follows.\n##' Let the increments of the equidispersed process be given by\n##' \\preformatted{\n##'     reulermultinom(size=N,rate=r,dt=dt).\n##' }\n##' In this expression, replace the rate \\eqn{r} with \\eqn{r\\,{\\Delta{W}}/{\\Delta t}}{r*dW/dt},\n##' where \\eqn{\\Delta{W} \\sim \\mathrm{Gamma}(\\Delta{t}/\\sigma^2,\\sigma^2)}{dW ~ Gamma(dt/sigma^2,sigma^2)}\n##' is the increment of an integrated Gamma white noise process with intensity \\eqn{\\sigma}{sigma}.\n##' That is, \\eqn{\\Delta{W}}{dW} has mean \\eqn{\\Delta{t}}{dt} and variance \\eqn{\\sigma^2 \\Delta{t}}{sigma^2*dt}.\n##' The resulting process is overdispersed and converges (as \\eqn{\\Delta{t}}{dt} goes to zero) to a well-defined process.\n##' The following lines of code accomplish this:\n##' \\preformatted{\n##'     dW <- rgammawn(sigma=sigma,dt=dt)\n##' } \\preformatted{\n##'     dn <- reulermultinom(size=N,rate=r,dt=dW)\n##' } or\n##' \\preformatted{\n##'     dn <- reulermultinom(size=N,rate=r*dW/dt,dt=dt).\n##' }\n##' He et al. (2010) use such overdispersed death processes in modeling measles and the \\href{https://kingaa.github.io/sbied/measles/}{\"Simulation-based Inference\" course} discusses the value of allowing for overdispersion more generally.\n##'\n##' For all of the functions described here, access to the underlying C routines is available:\n##' see below.\n##' @name eulermultinom\n##' @rdname eulermultinom\n##' @family implementation information\n##' @concept probability distributions\n##' @param n integer; number of random variates to generate.\n##' @param size scalar integer; number of individuals at risk.\n##' @param rate numeric vector of hazard rates.\n##' @param sigma numeric scalar; intensity of the Gamma white noise process.\n##' @param dt numeric scalar; duration of Euler step.\n##' @param x matrix or vector containing number of individuals that have\n##' succumbed to each death process.\n##' @param log logical; if TRUE, return logarithm(s) of probabilities.\n##' @section C API:\n##' An interface for C codes using these functions is provided by the package.\n##' Visit the package homepage to view the \\href{https://kingaa.github.io/pomp/C_API.html}{\\pkg{pomp} C API document}.\n##' @author Aaron A. King\n##' @references\n##' \\Breto2011\n##' \\He2010\n##' @keywords distribution\n##' @example examples/eulermultinom.R\nNULL\n\n##' @rdname eulermultinom\n##' @return\n##' \\code{reulermultinom} returns a \\code{length(rate)} by \\code{n} matrix.\n##' Each column is a different random draw.\n##' Each row contains the numbers of individuals that have succumbed to the corresponding process.\n##' @export\nreulermultinom <- function (n = 1, size, rate, dt) {\n  tryCatch(\n    .Call(P_R_Euler_Multinom,n,size,rate,dt),\n    error = function (e) pStop(who=\"reulermultinom\",conditionMessage(e))\n  )\n}\n\n##' @rdname eulermultinom\n##' @return\n##' \\code{deulermultinom} returns a vector (of length equal to the number of columns of \\code{x}).\n##' This contains the probabilities of observing each column of \\code{x} given the specified parameters (\\code{size}, \\code{rate}, \\code{dt}).\n##' @export\ndeulermultinom <- function (x, size, rate, dt, log = FALSE) {\n  tryCatch(\n    .Call(P_D_Euler_Multinom,as.matrix(x),size,rate,dt,log),\n    error = function (e) pStop(who=\"deulermultinom\",conditionMessage(e))\n  )\n}\n\n##' @rdname eulermultinom\n##' @return\n##' \\code{eeulermultinom} returns a \\code{length(rate)}-vector\n##' containing the expected number of individuals to have succumbed to the corresponding process.\n##' With the notation above, if\n##' \\preformatted{\n##'     dn <- eeulermultinom(size=N,rate=r,dt=dt),\n##' }\n##' then the \\eqn{k}-th element of the vector \\code{dn} will be \\eqn{p_k N}{pk N}.\n##' @export\neeulermultinom <- function (size, rate, dt) {\n  tryCatch(\n    .Call(P_E_Euler_Multinom,size,rate,dt),\n    error = function (e) pStop(who=\"eeulermultinom\",conditionMessage(e))\n  )\n}\n\n##' @rdname eulermultinom\n##' @return\n##' \\code{rgammawn} returns a vector of length \\code{n} containing random increments of the integrated Gamma white noise process with intensity \\code{sigma}.\n##' @export\nrgammawn <- function (n = 1, sigma, dt) {\n  tryCatch(\n    .Call(P_R_GammaWN,n,sigma,dt),\n    error = function (e) pStop(who=\"rgammwn\",conditionMessage(e))\n  )\n}\n"
  },
  {
    "path": "R/extract.R",
    "content": "##' @include listie.R\n##' @keywords internal\n##' @rdname listie\n##' @name [-listie\n##' @aliases [,listie-method\nNULL\n\n##' @rdname listie\n##' @importFrom stats setNames\n##' @export\nsetMethod(\n  \"[\",\n  signature=signature(x=\"listie\"),\n  definition=function(x, i, ...) {\n    y <- as(x,\"list\")\n    names(y) <- names(x)\n    cl <- class(x)\n    y <- unlist(y[i])\n    if (is.null(y)) {\n      list(NULL)\n    } else {\n      setNames(new(cl,y),names(y))\n    }\n  }\n)\n"
  },
  {
    "path": "R/filter_mean.R",
    "content": "##' Filtering mean\n##'\n##' The mean of the filtering distribution\n##'\n##' The filtering distribution is that of\n##' \\deqn{X(t_k) \\vert Y(t_1)=y^*_1,\\dots,Y(t_k)=y^*_k,}{Xk | Y1=y1*,\\dots,Yk=yk*,}\n##' where \\eqn{X(t_k)}{Xk}, \\eqn{Y(t_k)}{Yk} are the latent state and observable processes, respectively, and \\eqn{y^*_t}{yt*} is the data, at time \\eqn{t_k}{tk}.\n##'\n##' The filtering mean is therefore the expectation of this distribution\n##' \\deqn{E[X(t_k) \\vert Y(t_1)=y^*_1,\\dots,Y(t_k)=y^*_k].}{E[Xk | Y1=y1*,\\dots,Yk=yk*].}\n##'\n##' @name filter_mean\n##' @docType methods\n##' @aliases filter_mean,ANY-method filter_mean,missing-method\n##' @include pfilter.R kalman.R melt.R\n##' @rdname filter_mean\n##' @family particle filter methods\n##' @family extraction methods\n##'\n##' @param object result of a filtering computation\n##' @param vars optional character; names of variables\n##' @param format format of the returned object\n##' @param ... ignored\n##'\nNULL\n\nsetGeneric(\n  \"filter_mean\",\n  function (object, ...)\n    standardGeneric(\"filter_mean\")\n)\n\nsetMethod(\n  \"filter_mean\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"filter_mean\",\"object\")\n  }\n)\n\nsetMethod(\n  \"filter_mean\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"filter_mean\",object)\n  }\n)\n\n##' @rdname filter_mean\n##' @export\nsetMethod(\n  \"filter_mean\",\n  signature=signature(object=\"kalmand_pomp\"),\n  definition=function (object, vars, ...,\n    format = c(\"array\", \"data.frame\")) {\n    if (missing(vars)) {\n      x <- object@filter.mean\n    } else {\n      x <- object@filter.mean[vars,,drop=FALSE]\n    }\n    format <- match.arg(format)\n    if (format == \"data.frame\") {\n      x <- melt(object@filter.mean[vars,,drop=FALSE])\n      x$time <- time(object)[as.integer(x$time)]\n    }\n    x\n  }\n)\n\n##' @rdname filter_mean\n##' @export\nsetMethod(\n  \"filter_mean\",\n  signature=signature(object=\"pfilterd_pomp\"),\n  definition=function (object, vars, ...,\n    format = c(\"array\", \"data.frame\")) {\n    if (missing(vars)) {\n      x <- object@filter.mean\n    } else {\n      x <- object@filter.mean[vars,,drop=FALSE]\n    }\n    format <- match.arg(format)\n    if (format == \"data.frame\") {\n      x <- melt(object@filter.mean[vars,,drop=FALSE])\n      x$time <- time(object)[as.integer(x$time)]\n    }\n    x\n  }\n)\n"
  },
  {
    "path": "R/filter_traj.R",
    "content": "##' Filtering trajectories\n##'\n##' Drawing from the smoothing distribution\n##'\n##' The smoothing distribution is the distribution of\n##' \\deqn{X(t_k) | Y(t_1)=y^*_1, \\dots, Y(t_n)=y^*_n,}{Xk | Y1=y1*, \\dots, Yn=yn*,}\n##' where \\eqn{X(t_k)}{Xk} is the latent state process and \\eqn{Y(t_k)}{Yk} is the observable process at time \\eqn{t_k}{tk}, and \\eqn{n} is the number of observations.\n##'\n##' To draw samples from this distribution, one can run a number of independent particle filter (\\code{\\link{pfilter}}) operations, sampling the full trajectory of \\emph{one} randomly-drawn particle from each one.\n##' One should view these as \\emph{weighted} samples from the smoothing distribution, where the weights are the \\emph{likelihoods} returned by each of the \\code{\\link{pfilter}} computations.\n##'\n##' One accomplishes this by setting \\code{filter.traj = TRUE} in each \\code{\\link{pfilter}} computation and extracting the trajectory using the \\code{filter_traj} command.\n##'\n##' In particle MCMC (\\code{\\link{pmcmc}}), the tracking of an individual trajectory is performed automatically.\n##'\n##' @name filter_traj\n##' @aliases filter_traj,ANY-method filter_traj,missing-method\n##' @include pfilter.R pmcmc.R melt.R\n##' @rdname filter_traj\n##' @family particle filter methods\n##' @family extraction methods\n##' @inheritParams filter_mean\nNULL\n\nsetGeneric(\n  \"filter_traj\",\n  function (object,...) standardGeneric(\"filter_traj\")\n)\n\nsetMethod(\n  \"filter_traj\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"filter_traj\",\"object\")\n  }\n)\n\nsetMethod(\n  \"filter_traj\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"filter_traj\",object)\n  }\n)\n\n##' @rdname filter_traj\n##' @export\nsetMethod(\n  \"filter_traj\",\n  signature=signature(object=\"pfilterd_pomp\"),\n  definition=function (object, vars, ...,\n    format = c(\"array\", \"data.frame\")) {\n    if (missing(vars)) {\n      x <- object@filter.traj\n    } else {\n      x <- object@filter.traj[vars,,,drop=FALSE]\n    }\n    format <- match.arg(format)\n    if (format == \"data.frame\") {\n      x <- melt(x)\n      x$time <- time(object,t0=TRUE)[as.integer(x$time)]\n    }\n    x\n  }\n)\n\n##' @rdname filter_traj\n##' @export\nsetMethod(\n  \"filter_traj\",\n  signature=signature(object=\"listie\"),\n  definition=function (object, vars, ...,\n    format = c(\"array\", \"data.frame\")) {\n    format <- match.arg(format)\n    fts <- lapply(object,filter_traj,vars=vars,format=\"array\",...)\n    d <- vapply(fts,dim,integer(3L))\n    if (!all(apply(d,1L,\\(x)x==x[1L])))\n      pStop(who=\"filter_traj\",\"incommensurate dimensions.\")\n    d <- d[,1L]\n    nm <- dimnames(fts[[1L]])\n    x <- do.call(c,fts)\n    dim(x) <- c(d,length(fts))\n    dimnames(x) <- c(nm,list(chain=names(fts)))\n    if (format == \"array\") {\n      x\n    } else {\n      melt(x)\n    }\n  }\n)\n\n##' @rdname filter_traj\n##' @export\nsetMethod(\n  \"filter_traj\",\n  signature=signature(object=\"pmcmcd_pomp\"),\n  definition=function (object, vars, ...) {\n    filter_traj(as(object,\"pfilterd_pomp\"),vars,...)\n  }\n)\n"
  },
  {
    "path": "R/flow.R",
    "content": "##' flow workhorse\n##'\n##' Compute the flow generated by a deterministic vectorfield or map.\n##'\n##' In the case of a discrete-time system (map), \\code{flow} iterates the map to yield trajectories of the system.\n##' In the case of a continuous-time system (vectorfield), \\code{flow} uses the numerical solvers in \\pkg{\\link[deSolve]{deSolve}} to integrate the vectorfield starting from given initial conditions.\n##'\n##' @name flow\n##' @rdname flow\n##' @include pomp_class.R skeleton_spec.R workhorses.R\n##' @aliases flow,missing-method flow,ANY-method\n##' @family pomp workhorses\n##' @family deterministic methods\n##' @concept extending the pomp package\n##' @concept low-level interface\n##' @importFrom deSolve ode diagnostics\n##' @importFrom stats setNames\n##' @inheritParams dmeasure\n##' @inheritParams pomp\n##' @param x0 an array with dimensions \\code{nvar} x \\code{nrep} giving the initial conditions of the trajectories to be computed.\n##' @param t0 the time at which the initial conditions are assumed to hold.\n##' By default, this is the zero-time (see \\code{\\link{timezero}}).\n##' @param times a numeric vector (length \\code{ntimes}) containing times at which the itineraries are desired.\n##' These must be in non-decreasing order with \\code{times[1]>t0}.\n##' By default, this is the full set of observation times (see \\code{\\link{time}}).\n##' @param ... Additional arguments are passed to the ODE integrator (if the skeleton is a vectorfield) and are ignored if it is a map.\n##' See \\code{\\link[deSolve]{ode}} for a description of the additional arguments accepted by the ODE integrator.\n##' By default, this is the parameter vector stored in \\code{object} (see \\code{\\link[pomp]{coef}}).\n##' @return\n##' \\code{flow} returns an array of dimensions \\code{nvar} x \\code{nrep} x \\code{ntimes}.\n##' If \\code{x} is the returned matrix, \\code{x[i,j,k]} is the i-th component of the state vector at time \\code{times[k]} given parameters \\code{params[,j]}.\n##' @section Accumulator variables:\n##' When there are accumulator variables (as determined by the \\code{\\link{accumvars}} argument), their handling in the continuous-time (vectorfield) case differs from that in the discrete-time (map) case.\n##' In the latter, accumulator variables are set to zero at the beginning of each interval \\eqn{(t_k,t_{k+1})}{(t[k],t[k+1])}, \\eqn{k=0,1,2,\\dots} over which flow computation is required.\n##' In the former, the flow computation proceeds over the entire set of intervals required, and accumulator variables are then differenced.\n##' That is, the value \\eqn{a_k}{a[k]} of accumulator variable \\eqn{a} at times \\eqn{t_k}{t[k]}, \\eqn{k=1,2,\\dots} will be \\eqn{A_k-A_{k-1}}{A[k]-A[k-1]}, where \\eqn{A_k}{A[k]} is the solution of the corresponding differential equation at \\eqn{t_k}{t[k]}.\nNULL\n\nsetGeneric(\n  \"flow\",\n  function (object, ...)\n    standardGeneric(\"flow\")\n)\n\nsetMethod(\n  \"flow\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"flow\",\"object\")\n  }\n)\n\nsetMethod(\n  \"flow\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"flow\",object)\n  }\n)\n\n##' @rdname flow\n##' @export\nsetMethod(\n  \"flow\",\n  signature=signature(object=\"pomp\"),\n  definition=function (\n    object,\n    ...,\n    x0,\n    t0 = timezero(object),\n    times = time(object),\n    params = coef(object),\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      flow_internal(object=object,x0=x0,t0=t0,times=times,params=params,\n        ...,verbose=verbose),\n      error = function (e) pStop(who=\"flow\",conditionMessage(e))\n    )\n\n  }\n)\n\nflow_internal <- function (\n  object,\n  ...,\n  x0, t0, times, params,\n  .gnsi = TRUE,\n  verbose\n) {\n\n  verbose <- as.logical(verbose)\n\n  t0 <- as.numeric(t0)\n  times <- as.numeric(times)\n\n  if (length(times)==0)\n    pStop_(sQuote(\"times\"),\" is empty, there is no work to do.\")\n\n  if (any(diff(times)<0))\n    pStop_(sQuote(\"times\"),\" must be a non-decreasing numeric sequence.\")\n\n  if (times[1]<t0)\n    pStop_(sQuote(\"times[1]\"),\" must be no later than \",sQuote(\"t0\"),\".\")\n\n  params <- as.matrix(params)\n  nrep <- ncol(params)\n  storage.mode(params) <- \"double\"\n\n  x0 <- as.matrix(x0)\n  nvar <- nrow(x0)\n  storage.mode(x0) <- \"double\"\n\n  statenames <- rownames(x0)\n  repnames <- colnames(x0)\n  dim(x0) <- c(nvar,nrep,1)\n  dimnames(x0) <- list(statenames,repnames,NULL)\n\n  ntimes <- length(times)\n\n  type <- object@skeleton@type          # map or vectorfield?\n\n  pompLoad(object)\n  on.exit(pompUnload(object))\n\n  if (type == skeletontype$map) {                  ## MAP\n\n    x <- .Call(P_iterate_map,object,times,t0,x0,params,.gnsi)\n    .gnsi <- FALSE\n\n  } else if (type == skeletontype$vectorfield) {   ## VECTORFIELD\n\n    znames <- object@accumvars\n    if (length(znames)>0) {\n      if (!all(znames %in% statenames)) {\n        mz <- znames[which(!(znames %in% statenames))[1L]]\n        pStop_(\"accumulator variable \",sQuote(mz),\" not found among the state variables.\")\n      }\n      x0[znames,,] <- 0\n    }\n\n    .Call(P_pomp_desolve_setup,object,x0,params,.gnsi)\n    .gnsi <- FALSE\n\n    X <- tryCatch(\n      ode(\n        y=x0,\n        times=c(t0,times),\n        func=\"pomp_vf_eval\",\n        dllname=\"pomp\",\n        initfunc=NULL,\n        parms=NULL,\n        ...\n      ),\n      error = function (e) {\n        pStop_(\"error in ODE integrator: \",conditionMessage(e))\n      }\n    )\n\n    .Call(P_pomp_desolve_takedown)\n\n    if (attr(X,\"istate\")[1L] != 2)\n      pWarn(who=\"flow\",\n        \"abnormal exit from ODE integrator, istate = \",attr(X,'istate')[1L])\n\n    if (verbose) diagnostics(X)\n\n    x <- array(data=t(X[-1L,-1L]),dim=c(nvar,nrep,ntimes),\n      dimnames=list(statenames,repnames,NULL))\n\n    for (z in znames)\n      for (r in seq_len(ncol(x)))\n        x[z,r,-1] <- diff(x[z,r,])\n\n  } else {                  ## DEFAULT SKELETON\n\n    x <- array(data=NA_real_,dim=c(nrow(x0),ncol(x0),length(times)),\n      dimnames=list(rownames(x0),colnames(x0),NULL))\n\n  }\n\n  dimnames(x) <- setNames(dimnames(x),c(\"name\",\".id\",object@timename))\n\n  x\n}\n"
  },
  {
    "path": "R/forecast.R",
    "content": "##' Forecast mean\n##'\n##' Mean of the one-step-ahead forecasting distribution.\n##'\n##' @name forecast\n##' @rdname forecast\n##' @aliases forecast,missing-method forecast,ANY-method\n##' @family extraction methods\n##' @include pfilter.R kalman.R melt.R\n##' @inheritParams filter_mean\n##'\n\nsetGeneric(\n  \"forecast\",\n  function (object, ...)\n    standardGeneric(\"forecast\")\n)\n\nsetMethod(\n  \"forecast\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"forecast\",\"object\")\n  }\n)\n\nsetMethod(\n  \"forecast\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"forecast\",object)\n  }\n)\n\n##' @rdname forecast\n##' @export\nsetMethod(\n  \"forecast\",\n  signature=signature(object=\"kalmand_pomp\"),\n  definition=function (object, vars, ...,\n    format = c(\"array\", \"data.frame\")) {\n    if (missing(vars)) {\n      x <- object@forecast\n    } else {\n      x <- object@forecast[vars,,drop=FALSE]\n    }\n    format <- match.arg(format)\n    if (format == \"data.frame\") {\n      x <- melt(object@forecast[vars,,drop=FALSE])\n      x$time <- time(object)[as.integer(x$time)]\n    }\n    x\n  }\n)\n\n##' @rdname forecast\n##' @export\nsetMethod(\n  \"forecast\",\n  signature=signature(object=\"pfilterd_pomp\"),\n  definition=function (object, vars, ...,\n    format = c(\"array\", \"data.frame\")) {\n    if (undefined(object@emeasure))\n      pStop(who=\"forecast\",paste(sQuote(c(\"emeasure\")),collapse=\", \"),\n        \" is a needed basic component.\")\n    x <- pred_mean(object)\n    if (length(x)==0)\n      pStop(who=\"forecast\",\"no prediction mean. \",\n        \"Rerun \",sQuote(\"pfilter\"),\" with \",\n        sQuote(\"pred.mean=TRUE\"),\".\")\n    y <- emeasure(\n      object,\n      x=x,\n      times=time(object),\n      params=coef(object)\n    )\n    if (!missing(vars))\n      y <- y[vars,,,drop=FALSE]\n    dn <- dim(y)[c(1L,3L)]\n    dnm <- dimnames(y)[c(1L,3L)]\n    dim(y) <- dn\n    dimnames(y) <- dnm\n    format <- match.arg(format)\n    if (format==\"data.frame\") {\n      y <- melt(y)\n      y$time <- time(object)[as.integer(y$time)]\n    }\n    y\n  }\n)\n"
  },
  {
    "path": "R/gompertz.R",
    "content": "##' Gompertz model with log-normal observations.\n##'\n##' \\code{gompertz()} constructs a \\sQuote{pomp} object encoding a stochastic Gompertz population model with log-normal measurement error.\n##'\n##' The state process is\n##' \\deqn{X_{t+1} = K^{1-S} X_{t}^S \\epsilon_{t},}{X[t+1]=K^(1-S) X[t]^S eps[t],} where \\eqn{S=e^{-r}}{S=e^{-r}}\n##' and the \\eqn{\\epsilon_t}{eps[t]} are i.i.d. lognormal random deviates with\n##' variance \\eqn{\\sigma^2}{sigma^2}.\n##' The observed variables \\eqn{Y_t} are distributed as\n##' \\deqn{Y_t\\sim\\mathrm{Lognormal}(\\log{X_t},\\tau).}{Y[t]~Lognormal(log(X[t]),tau).}\n##' Parameters include the per-capita growth rate \\eqn{r}, the carrying\n##' capacity \\eqn{K}, the process noise s.d. \\eqn{\\sigma}{sigma}, the\n##' measurement error s.d. \\eqn{\\tau}{tau}, and the initial condition\n##' \\eqn{X_0}{X[0]}.  The \\sQuote{pomp} object includes parameter\n##' transformations that log-transform the parameters for estimation purposes.\n##'\n##' @name gompertz\n##' @docType data\n##' @keywords models\n##' @include simulate.R\n##' @family pomp examples\n##'\n##' @return\n##' A \\sQuote{pomp} object with simulated data.\n##'\n##' @examples\n##'\n##' plot(gompertz())\n##' plot(gompertz(K=2,r=0.01))\n##'\nNULL\n\n##' @rdname gompertz\n##'\n##' @param r growth rate\n##' @param K carrying capacity\n##' @param sigma process noise intensity\n##' @param tau measurement error s.d.\n##' @param X_0 value of the latent state variable \\code{X} at the zero time\n##' @param t0 zero time\n##' @param times observation times\n##' @param seed seed of the random number generator\n##'\n##' @export\ngompertz <- function (K = 1, r = 0.1, sigma = 0.1, tau = 0.1, X_0 = 1,\n  times = 1:100, t0 = 0, seed = 299438676L)\n{\n\n  simulate(\n    times=times, t0=t0,\n    params=c(K=K,r=r,sigma=sigma,tau=tau,X_0=X_0),\n    partrans=parameter_trans(\n      toEst=\"_gompertz_to_trans\",\n      fromEst=\"_gompertz_from_trans\"\n    ),\n    rprocess=discrete_time(\"_gompertz_step\",delta.t=1),\n    emeasure=\"_gompertz_normal_emeasure\",\n    vmeasure=\"_gompertz_normal_vmeasure\",\n    rmeasure=\"_gompertz_normal_rmeasure\",\n    dmeasure=\"_gompertz_normal_dmeasure\",\n    skeleton=map(\"_gompertz_skeleton\",delta.t=1),\n    PACKAGE=\"pomp\",\n    paramnames=c(\"r\",\"K\",\"sigma\",\"tau\",\"X_0\"),\n    obsnames=c(\"Y\"),\n    statenames=c(\"X\"),\n    seed=seed\n  )\n\n}\n"
  },
  {
    "path": "R/kalman.R",
    "content": "##' Ensemble Kalman filters\n##'\n##' The ensemble Kalman filter and ensemble adjustment Kalman filter.\n##'\n##' @name kalman\n##' @rdname kalman\n##' @include pomp_class.R pomp.R workhorses.R\n##' @importFrom stats dnorm rnorm\n##' @aliases enkf,ANY-method enkf,missing-method\n##' eakf,ANY-method eakf,missing-method\n##' @author Aaron A. King\n##' @concept Kalman filter\n##' @seealso \\code{\\link{kalmanFilter}}\n##' @family particle filter methods\n##' @family elementary algorithms\n##' @inheritSection pomp Note for Windows users\n##' @inheritParams pfilter\n##' @inheritParams pomp\n##' @param Np integer; the number of particles to use, i.e., the size of the ensemble.\n##' @return\n##' An object of class \\sQuote{kalmand_pomp}.\n##' @references\n##'\n##' \\Evensen1994\n##'\n##' \\Anderson2001\n##'\n##' \\Evensen2009\nNULL\n\nsetClass(\n  \"kalmand_pomp\",\n  contains=\"pomp\",\n  slots=c(\n    Np=\"integer\",\n    pred.mean=\"array\",\n    filter.mean=\"array\",\n    forecast=\"array\",\n    cond.logLik=\"numeric\",\n    loglik=\"numeric\"\n  ),\n  prototype=prototype(\n    Np=0L,\n    R=array(data=numeric(0L),dim=c(0L,0L)),\n    pred.mean=array(data=numeric(0L),dim=c(0L,0L)),\n    filter.mean=array(data=numeric(0L),dim=c(0L,0L)),\n    forecast=array(data=numeric(0L),dim=c(0L,0L)),\n    cond.logLik=numeric(0L),\n    loglik=as.double(NA)\n  )\n)\n\nsetClass(\n  \"eakfd_pomp\",\n  contains=\"kalmand_pomp\",\n  slots=c(\n    Cmatrix=\"array\"\n  ),\n  prototype=prototype(\n    Cmatrix=array(data=numeric(0L),dim=c(0L,0L))\n  )\n)\n\nsetGeneric(\n  \"enkf\",\n  function (data, ...)\n    standardGeneric(\"enkf\")\n)\n\nsetMethod(\n  \"enkf\",\n  signature=signature(data=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"enkf\",\"data\")\n  }\n)\n\nsetMethod(\n  \"enkf\",\n  signature=signature(data=\"ANY\"),\n  definition=function (data, ...) {\n    undef_method(\"enkf\",data)\n  }\n)\n\n##' @rdname kalman\n##' @aliases enkf\n##' @export\nsetMethod(\n  \"enkf\",\n  signature=signature(data=\"data.frame\"),\n  function (\n    data,\n    ...,\n    Np,\n    params, rinit, rprocess, emeasure, vmeasure,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      enkf_internal(\n        data,\n        ...,\n        Np=Np,\n        params=params,\n        rinit=rinit,\n        rprocess=rprocess,\n        emeasure=emeasure,\n        vmeasure=vmeasure,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"enkf\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname kalman\n##' @export\nsetMethod(\n  \"enkf\",\n  signature=signature(data=\"pomp\"),\n  function (\n    data,\n    ...,\n    Np,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      enkf_internal(\n        data,\n        ...,\n        Np=Np,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"enkf\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname kalman\n##' @export\nsetMethod(\n  \"enkf\",\n  signature=signature(data=\"kalmand_pomp\"),\n  function (\n    data,\n    ...,\n    Np,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n    if (missing(Np)) Np <- data@Np\n    tryCatch(\n      enkf_internal(\n        as(data,\"pomp\"),\n        ...,\n        Np=Np,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"enkf\",conditionMessage(e))\n    )\n\n  }\n)\n\n## ENSEMBLE KALMAN FILTER (ENKF)\n\n## Ensemble: $X_t\\in \\mathbb{R}^{m\\times q}$\n## Prediction mean: $M_t=\\langle X \\rangle$\n## Prediction variance: $V_t=\\langle\\langle X \\rangle\\rangle$\n## Forecast: $Y_t=emeasure(X_t)$\n## Forecast mean: $N_t=\\langle Y \\rangle$.\n## Forecast variance: $S_t=\\langle\\langle Y \\rangle\\rangle$\n## State/forecast covariance: $W_t=\\langle\\langle X,Y\\rangle\\rangle$\n## Kalman gain: $K_t = W_t\\,S_t^{-1}$\n## New observation: $y_t\\in \\mathbb{R}^{n\\times 1}$\n## Updated ensemble: $X^u_{t}=X_t + K_t\\,(O_t - Y_t)$\n## Filter mean: $m_t=\\langle X^u_t \\rangle = \\frac{1}{q} \\sum\\limits_{i=1}^q x^{u_i}_t$\n\nenkf_internal <- function (\n  object,\n  ...,\n  Np,\n  verbose\n) {\n\n  verbose <- as.logical(verbose)\n\n  object <- pomp(object,...,verbose=verbose)\n\n  if (undefined(object@rprocess))\n    pStop_(paste(sQuote(c(\"rprocess\")),collapse=\", \"),\" is a needed basic component.\")\n\n  if (undefined(object@emeasure))\n    pStop_(paste(sQuote(c(\"emeasure\")),collapse=\", \"),\" is a needed basic component.\")\n\n  if (undefined(object@vmeasure))\n    pStop_(paste(sQuote(c(\"vmeasure\")),collapse=\", \"),\" is a needed basic component.\")\n\n  Np <- as.integer(Np)\n  if (length(Np)>1 || !is.finite(Np) || isTRUE(Np<=0))\n    pStop_(sQuote(\"Np\"),\" should be a single positive integer.\")\n\n  params <- coef(object)\n\n  t <- time(object)\n  tt <- time(object,t0=TRUE)\n  ntimes <- length(t)\n\n  y <- obs(object)\n  nobs <- nrow(y)\n\n  pompLoad(object,verbose=verbose)\n  on.exit(pompUnload(object,verbose=verbose))\n\n  X <- rinit(object,params=params,nsim=Np)\n  nvar <- nrow(X)\n\n  filterMeans <- array(dim=c(nvar,ntimes),dimnames=list(name=rownames(X),time=t))\n  predMeans <- array(dim=c(nvar,ntimes),dimnames=list(name=rownames(X),time=t))\n  forecast <- array(dim=c(nobs,ntimes),dimnames=dimnames(y))\n  condlogLik <- numeric(ntimes)\n\n  first <- TRUE\n\n  for (k in seq_len(ntimes)) {\n    ## advance ensemble according to state process\n    X <- rprocess(object,x0=X,t0=tt[k],times=tt[k+1],params=params,.gnsi=first)\n    rn <- rownames(X)\n\n    predMeans[,k] <- pm <- rowMeans(X) # prediction mean\n    Y <- emeasure(object,x=X,times=tt[k+1],params=params,.gnsi=first)\n    ym <- rowMeans(Y)                  # forecast mean\n    if (first && nrow(Y) != nobs)\n      pStop_(\"number of observables returned by \",sQuote(\"emeasure\"),\n        \" does not match data.\")\n\n    if (first && (nrow(Y)!=nrow(y) || !all(rownames(Y)==rownames(y)))) {\n      y <- y[rownames(Y),]\n      rownames(forecast) <- rownames(Y)\n    }\n\n    R <- vmeasure(object,x=pm,params=params,times=tt[k+1],.gnsi=first)\n    if (first && (nrow(R)!=nrow(y) || !all(rownames(R)==rownames(y)))) {\n      pStop_(\"rownames of matrix returned by \",sQuote(\"vmeasure\"),\n        \" do not match those returned by \",sQuote(\"emeasure\"),\".\")\n    }\n\n    first <- FALSE\n\n    dn <- dim(R)[c(1L,2L)]\n    dim(R) <- dn\n\n    sqrtR <- tryCatch(\n      t(chol(R)), ## t(sqrtR)%*%sqrtR == R\n      error = function (e) {\n        pStop_(\"degenerate \",sQuote(\"vmeasure\"),\": \",conditionMessage(e))\n      }\n    )\n\n    X <- X-pm\n    Y <- Y-ym\n\n    dim(X) <- dim(X)[-3L]\n    rownames(X) <- rn\n    dim(Y) <- dim(Y)[-3L]\n\n    fv <- tcrossprod(Y)/(Np-1L)+R        # forecast variance\n    vyx <- tcrossprod(Y,X)/(Np-1L) # forecast/state covariance\n\n    svdS <- svd(fv,nv=0)            # singular value decomposition\n    Kt <- svdS$u%*%(crossprod(svdS$u,vyx)/svdS$d) # transpose of Kalman gain\n    Ek <- sqrtR%*%matrix(rnorm(n=nobs*Np),nobs,Np) # artificial noise\n    resid <- y[,k]-ym\n\n    X <- X+pm+crossprod(Kt,resid+Ek-Y)\n\n    condlogLik[k] <- sum(dnorm(x=crossprod(svdS$u,resid),mean=0,sd=sqrt(svdS$d),log=TRUE))\n    filterMeans[,k] <- rowMeans(X)  # filter mean\n    forecast[,k] <- ym\n  }\n\n  new(\n    \"kalmand_pomp\",\n    object,\n    Np=Np,\n    filter.mean=filterMeans,\n    pred.mean=predMeans,\n    forecast=forecast,\n    cond.logLik=condlogLik,\n    loglik=sum(condlogLik)\n  )\n\n}\n\nsetGeneric(\n  \"eakf\",\n  function (data, ...)\n    standardGeneric(\"eakf\")\n)\n\nsetMethod(\n  \"eakf\",\n  signature=signature(data=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"eakf\",\"data\")\n  }\n)\n\nsetMethod(\n  \"eakf\",\n  signature=signature(data=\"ANY\"),\n  definition=function (data, ...) {\n    undef_method(\"eakf\",data)\n  }\n)\n\n##' @rdname kalman\n##' @aliases eakf\n##' @export\nsetMethod(\n  \"eakf\",\n  signature=signature(data=\"data.frame\"),\n  function (\n    data,\n    ...,\n    Np,\n    params, rinit, rprocess, emeasure, vmeasure,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      eakf_internal(\n        data,\n        ...,\n        Np=Np,\n        params=params,\n        rinit=rinit,\n        rprocess=rprocess,\n        emeasure=emeasure,\n        vmeasure=vmeasure,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"eakf\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname kalman\n##' @export\nsetMethod(\n  \"eakf\",\n  signature=signature(data=\"pomp\"),\n  function (\n    data,\n    ...,\n    Np,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      eakf_internal(\n        data,\n        ...,\n        Np=Np,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"eakf\",conditionMessage(e))\n    )\n\n  }\n)\n\n## ENSEMBLE ADJUSTMENT KALMAN FILTER (EAKF)\n\n## Ensemble: $X_t\\in \\mathbb{R}^{m\\times q}$\n## Prediction mean: $M_t=\\langle X \\rangle$ (ensemble average).\n## Prediction variance: $V_t=\\langle\\langle X \\rangle\\rangle$ (ensemble variance).\n## SVD of prediction variance: $V = Q_{V}\\,D_{V}\\,Q_{V}^T$\n## Another SVD: $U=D_V^{1/2}\\,Q_V^T\\,C^T\\,R^{-1}\\,C\\,Q_V\\,D_V^{1/2}=Q_U\\,D_U\\,Q_U^T$\n## Adjustment: $B=Q_V\\,D_V^{1/2}\\,Q_U\\,(I+D_U)^{-1/2}\\,D_V^{-1/2}\\,Q_V^T$\n## Kalman gain: $K=B\\,V\\,B^T\\,C^T\\,R^{-1}$\n## Filter mean: $m_t=M_t+K_t\\,(y_t-C\\,M_t)$\n## Updated ensemble: $x_{t}=B\\,(X_t-M_t\\,\\mathbb{1})+m_t\\,\\mathbb{1}$\n\neakf_internal <- function (\n  object,\n  ...,\n  Np,\n  verbose\n) {\n\n  verbose <- as.logical(verbose)\n\n  object <- pomp(object,...,verbose=verbose)\n\n  if (undefined(object@rprocess))\n    pStop_(paste(sQuote(c(\"rprocess\")),collapse=\", \"),\" is a needed basic component.\")\n\n  if (undefined(object@emeasure))\n    pStop_(paste(sQuote(c(\"emeasure\")),collapse=\", \"),\" is a needed basic component.\")\n\n  if (undefined(object@vmeasure))\n    pStop_(paste(sQuote(c(\"vmeasure\")),collapse=\", \"),\" is a needed basic component.\")\n\n  Np <- as.integer(Np)\n  if (length(Np)>1 || !is.finite(Np) || isTRUE(Np<=0))\n    pStop_(sQuote(\"Np\"),\" should be a single positive integer.\")\n\n  params <- coef(object)\n\n  t <- time(object)\n  tt <- time(object,t0=TRUE)\n  ntimes <- length(t)\n\n  y <- obs(object)\n  nobs <- nrow(y)\n\n  pompLoad(object,verbose=verbose)\n  on.exit(pompUnload(object,verbose=verbose))\n\n  X <- rinit(object,params=params,nsim=Np)\n  nvar <- nrow(X)\n\n  filterMeans <- array(dim=c(nvar,ntimes),\n    dimnames=list(name=rownames(X),time=t))\n  predMeans <- array(dim=c(nvar,ntimes),\n    dimnames=list(name=rownames(X),time=t))\n  forecast <- array(dim=c(nobs,ntimes),dimnames=dimnames(y))\n  condlogLik <- numeric(ntimes)\n\n  first <- TRUE\n\n  for (k in seq_len(ntimes)) {\n\n    ## advance ensemble according to state process\n    X <- rprocess(object,x0=X,t0=tt[k],times=tt[k+1],params=params,.gnsi=first)\n    Y <- emeasure(object,x=X,times=tt[k+1],params=params,.gnsi=first)\n    if (first && nrow(Y) != nobs)\n      pStop_(\"number of observables returned by \",sQuote(\"emeasure\"),\n        \" does not match data.\")\n    if (first && (nrow(Y)!=nrow(y) || !all(rownames(Y)==rownames(y)))) {\n      y <- y[rownames(Y),]\n      rownames(forecast) <- rownames(Y)\n    }\n    dn <- dim(Y)[c(1L,2L)]\n    dim(Y) <- dn\n\n    dn <- dim(X)[c(1L,2L)]\n    nx <- rownames(X)\n    dim(X) <- dn\n    rownames(X) <- nx\n\n    predMeans[,k] <- pm <- rowMeans(X) # prediction mean\n    X <- X-pm\n\n    pv <- tcrossprod(X)/(Np-1L) # prediction variance\n    svdV <- svd(pv,nv=0)        # SVD 1: pv = U%*%D%*%t(U)\n\n    Ct <- solve(pv,tcrossprod(X,Y))/(Np-1L) # t(C)\n\n    forecast[,k] <- emeasure(object,x=pm,times=tt[k+1],params=params,.gnsi=FALSE) # forecast (observables)\n    resid <- y[,k]-forecast[,k] # forecast error\n\n    R <- vmeasure(object,x=pm,params=params,times=tt[k+1],.gnsi=first)\n    if (first && (nrow(R)!=nrow(y) || !all(rownames(R)==rownames(y)))) {\n      pStop_(\"rownames of matrix returned by \",sQuote(\"vmeasure\"),\n        \" do not match those returned by \",sQuote(\"emeasure\"),\".\")\n    }\n    dn <- dim(R)[c(1L,2L)]\n    dim(R) <- dn\n    first <- FALSE\n\n    Ri <- tryCatch(\n      solve(R),\n      error = function (e) {\n        pStop_(\"degenerate \",sQuote(\"vmeasure\"),\": \",conditionMessage(e))\n      }\n    )\n\n    ww <- crossprod(svdV$u,Ct)\n    w <- crossprod(ww,svdV$d*ww)+R # forecast variance\n    svdW <- svd(w,nv=0) # SVD 2:  needed for log likelihood\n\n    condlogLik[k] <- sum(dnorm(x=crossprod(svdW$u,resid),mean=0,\n      sd=sqrt(svdW$d),log=TRUE))\n\n    u <- sqrt(svdV$d)*ww\n    u <- tcrossprod(u%*%Ri,u)\n    svdU <- svd(u,nv=0) # SVD 3\n\n    ## adjustment\n    b <- svdV$u%*%(sqrt(svdV$d)*svdU$u)%*%\n      (1/sqrt(1+svdU$d)/sqrt(svdV$d)*t(svdV$u))\n\n    K <- tcrossprod(b%*%pv,b)%*%Ct%*%Ri # Kalman gain\n\n    filterMeans[,k] <- fm <- pm+K%*%resid # filter mean\n\n    X[,] <- b%*%X+fm[,]\n  }\n\n  new(\n    \"kalmand_pomp\",\n    object,\n    Np=Np,\n    filter.mean=filterMeans,\n    pred.mean=predMeans,\n    forecast=forecast,\n    cond.logLik=condlogLik,\n    loglik=sum(condlogLik)\n  )\n}\n"
  },
  {
    "path": "R/kf.R",
    "content": "##' Kalman filter\n##'\n##' The basic Kalman filter for multivariate, linear, Gaussian processes.\n##'\n##' If the latent state is \\eqn{X}, the observed variable is \\eqn{Y},\n##' \\eqn{X_t \\in R^m}, \\eqn{Y_t \\in R^n}, and\n##' \\deqn{X_t \\sim \\mathrm{MVN}(A X_{t-1}, Q)}{X_t ~ MVN(A X_{t-1}, Q)}\n##' \\deqn{Y_t \\sim \\mathrm{MVN}(C X_t, R)}{Y_t ~ MVN(C X_t, R)}\n##' where \\eqn{\\mathrm{MVN}(M,V)} denotes the multivariate normal distribution with mean \\eqn{M} and variance \\eqn{V}.\n##' Then the Kalman filter computes the exact likelihood of \\eqn{Y}\n##' given \\eqn{A}, \\eqn{C}, \\eqn{Q}, and \\eqn{R}.\n##'\n##' @rdname kf\n##' @concept Kalman filter\n##' @seealso \\code{\\link{enkf}}, \\code{\\link{eakf}}\n##'\n##' @param object a pomp object containing data;\n##' @param X0 length-m vector containing initial state.\n##' This is assumed known without uncertainty.\n##' @param A \\eqn{m\\times m}{m x m} latent state-process transition matrix.\n##' \\eqn{E[X_{t+1} | X_t] = A.X_t}.\n##' @param Q \\eqn{m\\times m}{m x m} latent state-process covariance matrix.\n##' \\eqn{Var[X_{t+1} | X_t] = Q}\n##' @param C \\eqn{n\\times m}{n x m} link matrix.\n##' \\eqn{E[Y_t | X_t] = C.X_t}.\n##' @param R \\eqn{n\\times n}{n x n} observation process covariance matrix.\n##' \\eqn{Var[Y_t | X_t] = R}\n##' @param tol numeric;\n##' the tolerance to be used in computing matrix pseudoinverses via singular-value decomposition.\n##' Singular values smaller than \\code{tol} are set to zero.\n##'\n##' @example examples/kf.R\n##'\n##' @return\n##' A named list containing the following elements:\n##' \\describe{\n##'   \\item{object}{the \\sQuote{pomp} object}\n##'   \\item{A, Q, C, R}{as in the call}\n##'   \\item{filter.mean}{\\eqn{E[X_t|y^*_1,\\dots,y^*_t]}}\n##'   \\item{pred.mean}{\\eqn{E[X_t|y^*_1,\\dots,y^*_{t-1}]}}\n##'   \\item{forecast}{\\eqn{E[Y_t|y^*_1,\\dots,y^*_{t-1}]}}\n##'   \\item{cond.logLik}{\\eqn{f(y^*_t|y^*_1,\\dots,y^*_{t-1})}}\n##'   \\item{logLik}{\\eqn{f(y^*_1,\\dots,y^*_T)}}\n##' }\n##\n## X(t) ~ MultivariateNormal(A X(t-1), Q)\n## Y(t) ~ MultivariateNormal(C X(t), R)\n##\n## FM,FV = filter mean, variance\n## PM,PV = prediction mean, variance\n## YM,YV = forecast mean, variance\n## r = residual\n## K = Kalman gain\n##\n## PM(t) = A FM(t-1)\n## PV(t) = A FV(t-1) A^T + Q\n## YM(t) = C PM(t)\n## r(t) = y*(t) - YM(t)\n## YV(t) = C PV(t) C^T + R\n## FV(t)^(-1) = PV(t)^(-1) + C^T R^(-1) C\n## FV(t) = (I - K C) PV\n## K(t) = FV(t) C^T R^(-1)\n##      = PV C^T YV^(-1)\n## FM(t) = PM(t) + K(t) r(t)\n##\n##' @export\nkalmanFilter <- function (\n  object,\n  X0 = rinit(object),\n  A, Q, C, R, tol = 1e-6\n) {\n\n  t <- time(object,t0=FALSE)\n  y <- obs(object)\n  N <- length(t)     # number of observations\n  nvar <- length(X0) # number of state variables\n  nobs <- nrow(y)    # number of observables\n\n  filterMeans <- array(\n    dim=c(nvar,N),\n    dimnames=list(name=names(X0),time=NULL)\n  )\n  predMeans <- array(\n    dim=c(nvar,N),\n    dimnames=list(name=names(X0),time=NULL)\n  )\n  forecast <- array(\n    dim=c(nobs,N),\n    dimnames=dimnames(y)\n  )\n  condlogLik <- numeric(N)\n\n  fm <- X0\n  fv <- matrix(0,nvar,nvar)\n\n  for (k in seq_along(t)) {\n\n    predMeans[,k] <- pm <- A%*%fm # prediction mean\n    pv <- A%*%tcrossprod(fv,A)+Q  # prediction variance\n\n    forecast[,k] <- ym <- C%*%pm # forecast mean\n    resid <- y[,k]-ym            # forecast error\n    yv <- tcrossprod(C%*%pv,C)+R # forecast variance\n\n    ## SVD to invert yv\n    s <- svd_pseudoinv(yv,tol=tol)\n\n    condlogLik[k] <- sum(\n      dnorm(x=s$vt%*%resid,mean=0,sd=sqrt(s$d),log=TRUE)\n    )\n\n    K <- pv%*%crossprod(C,s$inv)          # Kalman gain\n    filterMeans[,k] <- fm <- pm+K%*%resid # filter mean\n    fv <- pv - K%*%C%*%pv                 # filter variance\n  }\n\n  list(\n    object=object,\n    A=A,\n    Q=Q,\n    C=C,\n    R=R,\n    filter.mean=filterMeans,\n    pred.mean=predMeans,\n    forecast=forecast,\n    cond.logLik=condlogLik,\n    logLik=sum(condlogLik)\n  )\n\n}\n\nsvd_pseudoinv <- function (A, tol) {\n  s <- La.svd(A,nu=0,nv=0)\n  n <- sum(s$d > tol*max(s$d))\n  s <- La.svd(A,nu=0,nv=n)\n  s$d <- s$d[seq_len(n)]\n  s$inv <- crossprod(s$vt,s$vt/s$d)\n  s\n}\n"
  },
  {
    "path": "R/listie.R",
    "content": "##' listie\n##'\n##' List-like objects.\n##'\n##' @name listie\n##' @rdname listie\n##' @keywords internal\n##' @include pomp_class.R\n##' @include abc.R pmcmc.R mif2.R pfilter.R\nNULL\n\nsetClass(\n  \"pompList\",\n  contains=\"list\",\n  validity=function (object) {\n    if (length(object) > 0L) {\n      if (!all(vapply(object,is,logical(1L),\"pomp\"))) {\n        retval <- paste0(\n          \"error in \",sQuote(\"c\"),\n          \": dissimilar objects cannot be combined\"\n        )\n        return(retval)\n      }\n    }\n    TRUE\n  }\n)\n\nsetClass(\n  \"abcList\",\n  contains=\"pompList\",\n  validity=function (object) {\n    if (length(object) > 0L) {\n      if (!all(vapply(object,is,logical(1L),\"abcd_pomp\"))) {\n        retval <- paste0(\n          \"error in \",sQuote(\"c\"),\n          \": dissimilar objects cannot be combined\"\n        )\n        return(retval)\n      }\n      d <- sapply(object,\\(x)dim(x@traces))\n      if (!all(apply(d,1L,diff)==0L)) {\n        retval <- paste0(\n          \"error in \",sQuote(\"c\"),\n          \": to be combined, \",sQuote(\"abcd_pomp\"),\n          \" objects must have chains of equal length\"\n        )\n        return(retval)\n      }\n    }\n    TRUE\n  }\n)\n\nsetClass(\n  \"pfilterList\",\n  contains=\"pompList\",\n  validity=function (object) {\n    if (length(object) > 0L) {\n      pftypes <- vapply(object,is,logical(1L),\"pfilterd_pomp\")\n      wftypes <- vapply(object,is,logical(1L),\"wpfilterd_pomp\")\n      if (!all(pftypes | wftypes)) {\n        retval <- paste0(\n          \"error in \",sQuote(\"c\"),\n          \": dissimilar objects cannot be combined\"\n        )\n        return(retval)\n      }\n    }\n    TRUE\n  }\n)\n\nsetClass(\n  \"mif2List\",\n  contains=\"pfilterList\",\n  validity=function (object) {\n    if (length(object) > 0L) {\n      if (!all(vapply(object,is,logical(1L),\"mif2d_pomp\"))) {\n        retval <- paste0(\n          \"error in \",sQuote(\"c\"),\n          \": dissimilar objects cannot be combined\"\n        )\n        return(retval)\n      }\n      d <- sapply(object,\\(x)dim(x@traces))\n      if (!all(apply(d,1L,diff)==0L)) {\n        retval <- paste0(\n          \"error in \",sQuote(\"c\"),\n          \": to be combined, \",sQuote(\"mif2d_pomp\"),\n          \" objects must have chains of equal length\"\n        )\n        return(retval)\n      }\n    }\n    TRUE\n  }\n)\n\nsetClass(\n  \"pmcmcList\",\n  contains=\"pfilterList\",\n  validity=function (object) {\n    if (length(object) > 0L) {\n      if (!all(vapply(object,is,logical(1L),\"pmcmcd_pomp\"))) {\n        retval <- paste0(\n          \"error in \",sQuote(\"c\"),\n          \": dissimilar objects cannot be combined\"\n        )\n        return(retval)\n      }\n      d <- sapply(object,\\(x)dim(x@traces))\n      if (!all(apply(d,1L,diff)==0L)) {\n        retval <- paste0(\n          \"error in \",sQuote(\"c\"),\n          \": to be combined, \",sQuote(\"pmcmcd_pomp\"),\n          \" objects must have chains of equal length\"\n        )\n        return(retval)\n      }\n    }\n    TRUE\n  }\n)\n\nsetClassUnion(\"Pomp\",c(\"pomp\",\"pompList\"))\n\nsetClassUnion(\"Pfilter\",\n  c(\"pfilterd_pomp\",\"wpfilterd_pomp\",\"pfilterList\")\n)\n\nsetClassUnion(\"Abc\",c(\"abcd_pomp\",\"abcList\"))\n\nsetClassUnion(\"Mif2\",c(\"mif2d_pomp\",\"mif2List\"))\n\nsetClassUnion(\"Pmcmc\",c(\"pmcmcd_pomp\",\"pmcmcList\"))\n\nsetClassUnion(\"listie\",\n  members=c(\"pompList\",\"abcList\",\"mif2List\",\"pmcmcList\",\"pfilterList\"))\n"
  },
  {
    "path": "R/load.R",
    "content": "##' Loading and unloading shared-object libraries\n##'\n##' \\code{pompLoad} and \\code{pompUnload} cause compiled codes associated with \\code{object} to be dynamically linked or unlinked, respectively.\n##' \\code{solibs<-} is a helper function for developers of packages that extend \\pkg{pomp}.\n##'\n##' When C snippets are used in the construction of a \\sQuote{pomp} object, the resulting shared-object library is dynamically loaded (linked) before each use, and unloaded afterward.\n##'\n##' @name load\n##' @docType methods\n##' @rdname load\n##' @aliases pompLoad pompUnload solibs<-\n##' @include pomp_class.R\n##' @keywords internal\nNULL\n\nsetGeneric(\n  \"pompLoad\",\n  function (object, ...)\n    standardGeneric(\"pompLoad\")\n)\n\nsetGeneric(\n  \"pompUnload\",\n  function (object, ...)\n    standardGeneric(\"pompUnload\")\n)\n\nsetGeneric(\n  \"solibs<-\",\n  function (object, ..., value)\n    standardGeneric(\"solibs<-\")\n)\n\n##' @rdname load\n##' @param object an object of class \\sQuote{pomp}, or extending this class.\n##' @export\nsetMethod(\n  \"pompLoad\",\n  signature=signature(object=\"pomp\"),\n  definition = function (object, ...) {\n    pompLoad_internal(object,...)\n  })\n\n##' @rdname load\n##' @export\nsetMethod(\n  \"pompUnload\",\n  signature=signature(object=\"pomp\"),\n  definition = function (object, ...) {\n    pompUnload_internal(object,...)\n  })\n\n##' @rdname load\n##' @details\n##' \\code{solibs<-} prepends the \\sQuote{lib} generated by \\code{\\link{hitch}}\n##'  to the \\sQuote{solibs} slot of a \\sQuote{pomp} object.\n##' @export\nsetMethod(\n  \"solibs<-\",\n  signature=signature(object=\"pomp\"),\n  definition=function (object, ..., value) {\n    if (!is.null(value)) {\n      object@solibs <- c(list(value),object@solibs)\n    }\n    object\n  }\n)\n\npompLoad_internal <- function (object, ...,\n  verbose = getOption(\"verbose\", FALSE)) {\n  .Call(P_set_userdata,object@userdata)\n  for (lib in object@solibs) {\n    if (!is.loaded(\"__pomp_load_stack_incr\",PACKAGE=lib$name)) {\n      dir <- srcDir(lib$dir,verbose=verbose)\n      solib <- file.path(dir,paste0(lib$name,.Platform$dynlib.ext))\n      if (file.exists(solib)) {\n        dyn.load(solib)\n      } else {\n        pompCompile(fname=lib$name,direc=dir,src=lib$src,verbose=verbose)\n        dyn.load(solib)\n      }\n      if (verbose) cat(\"loading\",sQuote(solib),\"\\n\")\n    }\n    .Call(P_load_stack_incr,lib$name)\n  }\n  invisible(NULL)\n}\n\npompUnload_internal <- function (object, ...,\n  verbose = getOption(\"verbose\", FALSE)) {\n  for (lib in object@solibs) {\n    if (is.loaded(\"__pomp_load_stack_decr\",PACKAGE=lib$name)) {\n      st <- .Call(P_load_stack_decr,lib$name)\n      if (st==0) {\n        dir <- srcDir(lib$dir,verbose=verbose)\n        solib <- file.path(dir,paste0(lib$name,.Platform$dynlib.ext))\n        dyn.unload(solib)\n        if (verbose) cat(\"unloading\",sQuote(solib),\"\\n\")\n      }\n    }\n  }\n  invisible(NULL)\n}\n"
  },
  {
    "path": "R/loglik.R",
    "content": "##' Log likelihood\n##'\n##' Extract the estimated log likelihood (or related quantity) from a fitted model.\n##'\n##' @name logLik\n##' @rdname loglik\n##' @aliases logLik,ANY-method logLik,missing-method\n##' @include pfilter.R wpfilter.R mif2.R pmcmc.R probe.R kalman.R nlf.R listie.R\n##' @include objfun.R spect_match.R nlf.R\n##' @family extraction methods\n##'\n##' @param object fitted model object\n##' @param \\dots ignored\n##'\n##' @return numerical value of the log likelihood.\n##' Note that some methods compute not the log likelihood itself but instead a related quantity.\n##' To keep the code simple, the \\code{logLik} function is nevertheless used to extract this quantity.\n##'\nNULL\n\n##' @rdname loglik\n##' @importFrom stats logLik\n##' @export\nsetGeneric(\"logLik\")\n\nsetMethod(\n  \"logLik\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"logLik\",\"object\")\n  }\n)\n\nsetMethod(\n  \"logLik\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    NA_real_\n  }\n)\n\n##' @rdname loglik\n##' @export\nsetMethod(\n  \"logLik\",\n  signature=signature(object=\"listie\"),\n  definition=function(object,...) {\n    do.call(c,lapply(object,logLik,...))\n  }\n)\n\n##' @rdname loglik\n##' @return\n##' When \\code{object} is of \\sQuote{pfilterd_pomp} class (i.e., the result of a \\code{wpfilter} computation), \\code{logLik} retrieves the estimated log likelihood.\n##' @export\nsetMethod(\n  \"logLik\",\n  signature=signature(object=\"pfilterd_pomp\"),\n  definition=function(object)object@loglik\n)\n\n##' @rdname loglik\n##' @return\n##' When \\code{object} is of \\sQuote{wpfilterd_pomp} class (i.e., the result of a \\code{wpfilter} computation), \\code{logLik} retrieves the estimated log likelihood.\n##' @export\nsetMethod(\n  \"logLik\",\n  signature=signature(object=\"wpfilterd_pomp\"),\n  definition=function(object)object@loglik\n)\n\n##' @rdname loglik\n##' @return\n##' When \\code{object} is of \\sQuote{probed_pomp} class (i.e., the result of a \\code{\\link{probe}} computation), \\code{logLik} retrieves the \\dQuote{synthetic likelihood}.\n##' @export\nsetMethod(\n  \"logLik\",\n  signature=signature(object=\"probed_pomp\"),\n  definition=function(object)object@synth.loglik\n)\n\n##' @rdname loglik\n##' @return\n##' When \\code{object} is of \\sQuote{kalmand_pomp} class (i.e., the result of an \\code{\\link{eakf}} or \\code{\\link{enkf}} computation), \\code{logLik} retrieves the estimated log likelihood.\n##' @export\nsetMethod(\n  \"logLik\",\n  signature=signature(object=\"kalmand_pomp\"),\n  definition=function(object)object@loglik\n)\n\n##' @rdname loglik\n##' @return\n##' When \\code{object} is of \\sQuote{pmcmcd_pomp} class (i.e., the result of a \\code{\\link{pmcmc}} computation), \\code{logLik} retrieves the estimated log likelihood as of the last particle filter operation.\n##' @export\nsetMethod(\n  \"logLik\",\n  signature=signature(object=\"pmcmcd_pomp\"),\n  definition=function (object)\n    object@loglik\n)\n\n##' @rdname loglik\n##' @return\n##' When \\code{object} is of \\sQuote{bsmcd_pomp} class (i.e., the result of a \\code{\\link{bsmc2}} computation), \\code{logLik} retrieves the \\dQuote{log evidence}.\n##' @export\nsetMethod(\n  \"logLik\",\n  signature=signature(object=\"bsmcd_pomp\"),\n  definition=function(object)object@log.evidence\n)\n\n##' @rdname loglik\n##' @export\nsetMethod(\n  \"logLik\",\n  signature=signature(object=\"objfun\"),\n  definition=function (object) {\n    object@env$loglik\n  }\n)\n\n##' @rdname loglik\n##' @return\n##' When \\code{object} is of \\sQuote{spect_match_objfun} class (i.e., an objective function constructed by \\code{\\link{spect_objfun}}), \\code{logLik} retrieves minus the spectrum mismatch.\n##' @export\nsetMethod(\n  \"logLik\",\n  signature=signature(object=\"spect_match_objfun\"),\n  definition=function (object) {\n    -object@env$discrep\n  }\n)\n\n##' @rdname loglik\n##' @return\n##' When \\code{object} is an NLF objective function, i.e., the result of a call to \\code{\\link{nlf_objfun}},\n##' \\code{logLik} retrieves the \\dQuote{quasi log likelihood}.\n##' @export\nsetMethod(\n  \"logLik\",\n  signature=signature(object=\"nlf_objfun\"),\n  definition = function(object, ...) {\n    object@env$logql\n  }\n)\n"
  },
  {
    "path": "R/logmeanexp.R",
    "content": "##' The log-mean-exp trick\n##'\n##' \\code{logmeanexp} computes\n##' \\deqn{\\log\\frac{1}{n}\\sum_{i=1}^n\\!e^{x_i},}{log(mean(exp(x))),}\n##' avoiding over- and under-flow in doing so.\n##' It can optionally return an estimate of the standard error in this quantity.\n##'\n##' When \\code{se = TRUE}, \\code{logmeanexp} uses a jackknife estimate of the variance in \\eqn{log(x)}.\n##'\n##' When \\code{ess = TRUE}, \\code{logmeanexp} returns an estimate of the effective sample size.\n##'\n##' @importFrom stats sd\n##' @param x numeric\n##' @param se logical; give approximate standard error?\n##' @param ess logical; give effective sample size?\n##' @return\n##' \\code{log(mean(exp(x)))} computed so as to avoid over- or underflow.\n##' If \\code{se = TRUE}, the approximate standard error is returned as well.\n##' If \\code{ess = TRUE}, the effective sample size is returned also.\n##' @author Aaron A. King\n##' @example examples/logmeanexp.R\n##' @export\nlogmeanexp <- function (x, se = FALSE, ess = FALSE) {\n  se <- isTRUE(se)\n  ess <- isTRUE(ess)\n  x <- as.numeric(x)\n  est <- .Call(P_logmeanexp,x,-1L)\n  if (se || ess) {\n    if (se) {\n      n <- length(x)\n      jk <- vapply(\n        seq_len(n),\n        \\(k) .Call(P_logmeanexp,x,k),\n        double(1L)\n      )\n      xse <- (n-1)*sd(jk)/sqrt(n)\n    }\n    if (ess) {\n      w <- exp(x-max(x))\n      xss <- sum(w)^2/sum(w^2)\n      if (se) {\n        c(est=est,se=xse,ess=xss)\n      } else {\n        c(est=est,ess=xss)\n      }\n    } else {\n      c(est=est,se=xse)\n    }\n  } else {\n    est\n  }\n}\n"
  },
  {
    "path": "R/lookup.R",
    "content": "##' Lookup table\n##'\n##' Interpolate values from a lookup table\n##'\n##' @rdname lookup\n##' @name lookup\n##' @family interpolation\n##' @include covariate_table.R\n##' @param table a \\sQuote{covartable} object created by a call to \\code{\\link{covariate_table}}\n##' @param t numeric vector; times at which interpolated values of the covariates in \\code{table} are required.\n##' @return\n##' A numeric vector or matrix of the interpolated values.\n##' @inheritSection covariates Extrapolation\n##' @export\nlookup <- function (table, t) {\n  d <- .Call(P_lookup_in_table,table,t)\n  data.frame(t=t,t(d))\n}\n\n##' @rdname covariate_table\n##' @return\n##' \\code{repair_lookup_table} returns a lookup table with entries at the provided values of \\code{t}.\n##' @param table a \\sQuote{covartable} object created by a call to \\code{\\link{covariate_table}}\n##' @param t numeric vector;\n##' times at which interpolated values of the covariates in \\code{table} are required.\n##' @details\n##' \\code{repair_lookup_table} applies \\code{\\link{lookup}} at the provided values of \\code{t} and returns the resulting lookup table.\n##' If \\code{order} is unsupplied, the interpolation-order from \\code{table} is preserved.\n##' \\strong{\\code{repair_lookup_table} should be considered experimental: its interface may change without notice}.\n##' @export\nrepair_lookup_table <- function (table, t, order) {\n  if (missing(order))\n    order <- if (table@order==0L) \"constant\" else \"linear\"\n  covariate_table(\n    lookup(table,t=t),\n    order=order,\n    times=\"t\"\n  )\n}\n"
  },
  {
    "path": "R/mcap.R",
    "content": "##' Monte Carlo adjusted profile\n##'\n##' Given a collection of points maximizing the likelihood over a range\n##' of fixed values of a focal parameter, this function constructs\n##' a profile likelihood confidence interval accommodating both\n##' Monte Carlo error in the profile and statistical uncertainty present\n##' in the likelihood function.\n##'\n##' @param logLik numeric; a vector of profile log likelihood evaluations.\n##' @param parameter numeric; the corresponding values of the focal parameter.\n##' @param level numeric; the confidence level required.\n##' @param span numeric; the \\code{\\link[stats]{loess}} smoothing parameter.\n##' @param Ngrid integer; the number of points to evaluate the smoothed profile.\n##'\n##' @references\n##'\n##' \\Ionides2017\n##'\n##' @return\n##' \\code{mcap} returns a list including the \\code{\\link[stats]{loess}}-smoothed\n##' profile, a quadratic approximation, and the constructed confidence interval.\n##'\n##' @author Edward L. Ionides\n##' @concept profile likelihood\n##' @importFrom stats loess predict lm vcov qchisq\n##' @include package.R design.R\n##'\n##' @rdname mcap\n##' @export\nmcap <- function (\n  logLik, parameter,\n  level = 0.95,\n  span = 0.75, Ngrid = 1000\n)\n{\n  smooth_fit <- loess(logLik ~ parameter,span=span)\n  parameter_grid <- seq(min(parameter),max(parameter),length.out=Ngrid)\n  smoothed_logLik <- predict(smooth_fit,newdata=parameter_grid)\n  smooth_arg_max <- parameter_grid[which.max(smoothed_logLik)]\n  dist <- abs(parameter-smooth_arg_max)\n  included <- dist < sort(dist)[trunc(span*length(dist))]\n  maxdist <- max(dist[included])\n  weights <- numeric(length(parameter))\n  weights[included] <- (1-(dist[included]/maxdist)^3)^3\n  quadratic_fit <- lm(\n    logLik ~ a + b,\n    weights=weights,\n    data = data.frame(logLik=logLik,b=parameter,a=-parameter^2)\n  )\n  b <- unname(coef(quadratic_fit)[\"b\"] )\n  a <- unname(coef(quadratic_fit)[\"a\"] )\n  m <- vcov(quadratic_fit)\n  var_b <- m[\"b\",\"b\"]\n  var_a <- m[\"a\",\"a\"]\n  cov_ab <- m[\"a\",\"b\"]\n  se_mc_squared <- (1/(4*a*a))*(var_b-(2*b/a)*cov_ab+(b*b/a/a)*var_a)\n  se_stat_squared <- 1/2/a\n  se_total_squared <- se_mc_squared + se_stat_squared\n  delta <- qchisq(level,df=1) * (a*se_mc_squared+0.5)\n  logLik_diff <- max(smoothed_logLik)-smoothed_logLik\n  ci <- range(parameter_grid[logLik_diff < delta])\n  list(\n    logLik=logLik,\n    parameter=parameter,\n    level=level,\n    span=span,\n    quadratic_fit=quadratic_fit,\n    quadratic_max=b/(2*a),\n    smooth_fit=smooth_fit,\n    fit=data.frame(\n      parameter=parameter_grid,\n      smoothed=smoothed_logLik,\n      quadratic=predict(\n        quadratic_fit,\n        newdata=list(\n          b=parameter_grid,\n          a=-parameter_grid^2\n        )\n      )\n    ),\n    mle=smooth_arg_max,\n    ci=ci,\n    delta=delta,\n    se_stat=sqrt(se_stat_squared),\n    se_mc=sqrt(se_mc_squared),\n    se=sqrt(se_total_squared)\n  )\n}\n"
  },
  {
    "path": "R/melt.R",
    "content": "##' Melt\n##'\n##' Convert arrays, lists, and other objects to data frames.\n##'\n##' \\code{melt} converts its first argument to a data frame.\n##' It is a simplified version of the \\code{melt} command provided by the no-longer maintained \\pkg{reshape2} package.\n##'\n##' @name melt\n##' @rdname melt\n##' @aliases melt,ANY-method melt,missing-method\n##' @param data object to convert\n##' @param level integer; level of recursion\n##' @param ... ignored\n##'\nNULL\n\n##' @importFrom data.table rbindlist\nrbind_fill <- function (x, .id = \".id\") {\n  as.data.frame(\n    rbindlist(x,use.names=TRUE,fill=TRUE,idcol=.id)\n  )\n}\n\nsetGeneric(\n  \"melt\",\n  function (data, ...)\n    standardGeneric(\"melt\")\n)\n\nsetMethod(\n  \"melt\",\n  signature=signature(data=\"missing\"),\n  definition=function (data, ...) {\n    reqd_arg(\"melt\",\"data\")\n  }\n)\n\n##' @rdname melt\n##' @importFrom stats setNames\n##' @export\nsetMethod(\n  \"melt\",\n  signature=signature(data=\"ANY\"),\n  definition=function (data, ...) {\n    if (is.null(names(data))) {\n      data.frame(\n        name=seq_along(data),\n        value=data,\n        row.names=NULL,\n        check.names=FALSE,\n        fix.empty.names=FALSE\n      )\n    } else {\n      data.frame(\n        name=names(data),\n        value=data,\n        row.names=NULL,\n        check.names=FALSE,\n        fix.empty.names=FALSE\n      )\n    }\n  }\n)\n\n##' @rdname melt\n##' @details An array can be melted into a data frame.\n##' In this case, the data frame will have one row per entry in the array.\n##' @export\nsetMethod(\n  \"melt\",\n  signature=signature(data=\"array\"),\n  definition=function (data, ...) {\n    dn <- dimnames(data)\n    if (is.null(dn)) dn <- vector(mode=\"list\",length=length(dim(data)))\n    nullnames <- which(unlist(lapply(dn,is.null)))\n    dn[nullnames] <- lapply(nullnames,\\(i)seq_len(dim(data)[i]))\n    labels <- expand.grid(dn,KEEP.OUT.ATTRS=FALSE,stringsAsFactors=FALSE)\n    dim(data) <- NULL\n    cbind(labels,value=data)\n  }\n)\n\n##' @rdname melt\n##' @details A list can be melted into a data frame.\n##' This operation is recursive.\n##' A variable will be appended to distinguish the separate list entries.\n##' @export\nsetMethod(\n  \"melt\",\n  signature=signature(data=\"list\"),\n  definition=function (data, ..., level = 1) {\n    if (length(unique(lapply(data,mode))) > 1L)\n      pStop(who=\"melt\",\"refusing to melt data of incompatible types.\")\n    rbind_fill(\n      lapply(data,melt,level=level+1,...),\n      .id=paste0(\".L\",level)\n    )\n  }\n)\n"
  },
  {
    "path": "R/mif2.R",
    "content": "##' Iterated filtering: maximum likelihood by iterated, perturbed Bayes maps\n##'\n##' An iterated filtering algorithm for estimating the parameters of a partially-observed Markov process.\n##' Running \\code{mif2} causes the algorithm to perform a specified number of particle-filter iterations.\n##' At each iteration, the particle filter is performed on a perturbed version of the model, in which the parameters to be estimated are subjected to random perturbations at each observation.\n##' This extra variability effectively smooths the likelihood surface and combats particle depletion by introducing diversity into particle population.\n##' As the iterations progress, the magnitude of the perturbations is diminished according to a user-specified cooling schedule.\n##' The algorithm is presented and justified in Ionides et al. (2015).\n##' @name mif2\n##' @rdname mif2\n##' @include pfilter.R workhorses.R pomp_class.R safecall.R continue.R\n##' @aliases mif2,missing-method mif2,ANY-method\n##' @author Aaron A. King, Edward L. Ionides, Dao Nguyen\n##' @family full-information methods\n##' @family particle filter methods\n##' @family estimation methods\n##' @family methods based on maximization\n##' @inheritParams pfilter\n##' @inheritParams pomp\n##' @param Nmif The number of filtering iterations to perform.\n##' @param rw.sd specification of the magnitude of the random-walk perturbations that will be applied to some or all model parameters.\n##' Parameters that are to be estimated should have positive perturbations specified here.\n##' The specification is given using the \\code{\\link{rw_sd}} function, which creates a list of unevaluated expressions.\n##' The latter are evaluated in a context where vector of observation times is visible (as \\sQuote{\\code{time}}).\n##' The expression \\code{ivp(s)} can be used in this context as shorthand for \\preformatted{ifelse(time==time[1],s,0).}\n##' Likewise, \\code{ivp(s,lag)} is equivalent to \\preformatted{ifelse(time==time[lag],s,0).}\n##' See below for some examples.\n##'\n##' The perturbations that are applied are normally distributed with the specified s.d.\n##' If parameter transformations have been supplied, then the perturbations are applied on the transformed (estimation) scale.\n##' @param cooling.type,cooling.fraction.50 specifications for the cooling schedule,\n##' i.e., the manner and rate with which the intensity of the parameter perturbations is reduced with successive filtering iterations.\n##' \\code{cooling.type} specifies the nature of the cooling schedule.\n##' See below (under \\dQuote{Specifying the perturbations}) for more detail.\n##'\n##' @return\n##' Upon successful completion, \\code{mif2} returns an object of class\n##' \\sQuote{mif2d_pomp}.\n##'\n##' @section Number of particles:\n##' If \\code{Np} is anything other than a constant, the user must take care that the number of particles requested at the end of the time series matches that requested at the beginning.\n##' In particular, if \\code{T=length(time(object))}, then one should have \\code{Np[1]==Np[T+1]} when \\code{Np} is furnished as an integer vector and \\code{Np(0)==Np(T)} when \\code{Np} is furnished as a function.\n##'\n##' @section Methods:\n##' The following methods are available for such an object:\n##' \\describe{\n##' \\item{\\code{\\link{continue}}}{ picks up where \\code{mif2} leaves off and performs more filtering iterations. }\n##' \\item{\\code{\\link{logLik}}}{ returns the so-called \\dfn{mif log likelihood} which is the log likelihood of the perturbed model, not of the focal model itself.\n##' To obtain the latter, it is advisable to run several \\code{\\link{pfilter}} operations on the result of a \\code{mif2} computatation.}\n##' \\item{\\code{\\link{coef}}}{ extracts the point estimate }\n##' \\item{\\code{\\link{eff_sample_size}}}{ extracts the effective sample size of the final filtering iteration}\n##' }\n##' Various other methods can be applied, including all the methods applicable to a \\code{\\link[=pfilter]{pfilterd_pomp}} object and all other \\pkg{pomp} estimation algorithms and diagnostic methods.\n##'\n##' @section Specifying the perturbations:\n##' The \\code{rw_sd} function simply returns a list containing its arguments as unevaluated expressions.\n##' These are then evaluated in a context in which the vector of observation times is defined (as \\sQuote{\\code{time}}).\n##' This allows for easy specification of the structure of the perturbations that are to be applied.\n##' For example,\n##' \\preformatted{\n##'     rw_sd(\n##'       a=0.05,\n##'       b=ifelse(time==time[1], 0.2, 0),\n##'       c=ivp(0.2),\n##'       d=ifelse(time==time[13], 0.2, 0),\n##'       e=ivp(0.2, lag=13),\n##'       f=ifelse(time<23, 0.02, 0),\n##'       g=ifelse(time>=23 & time<50, 0.02, 0),\n##'       h=ivp(0.1,lags=3:8)\n##'     )\n##' }\n##' results in random perturbations of parameter \\code{a} with s.d. 0.05 at every time step, while parameters \\code{b} and \\code{c} both get perturbations of s.d. 0.2 only before the first observation (i.e., at the zero-time).\n##' Parameters \\code{d} and \\code{e}, by contrast, get perturbations of s.d. 0.2 only before the thirteenth observation.\n##' Parameter \\code{f} gets a random perturbation of size 0.02 before every observation falling before \\eqn{t=23},\n##' while \\code{g} gets perturbed before all observations that fall in the interval \\eqn{23\\le{t}<{50}}{23<=t<50}.\n##' Finally, the magnitude of the perturbation of parameter \\code{h} is applied before the third through eighth observations.\n##'\n##' On the \\eqn{m}-th IF2 iteration, prior to time-point \\eqn{n}, the \\eqn{d}-th parameter is given a random increment normally distributed with mean \\eqn{0} and standard deviation \\eqn{c_{m,n} \\sigma_{d,n}}{c[m,n] sigma[d,n]}, where \\eqn{c} is the cooling schedule and \\eqn{\\sigma}{sigma} is specified using \\code{rw_sd}, as described above.\n##' Let \\eqn{N} be the length of the time series and \\eqn{\\alpha=}{alpha=}\\code{cooling.fraction.50}.\n##' Then, when \\code{cooling.type=\"geometric\"}, we have \\deqn{c_{m,n}=\\alpha^{\\frac{n-1+(m-1)N}{50N}}.}{c[m,n]=alpha^((n-1+(m-1)N)/(50N)).}\n##' When \\code{cooling.type=\"hyperbolic\"}, we have \\deqn{c_{m,n}=\\frac{s+1}{s+n+(m-1)N},}{c[m,n]=(s+1)/(s+n+(m-1)N),} where \\eqn{s} satisfies \\deqn{\\frac{s+1}{s+50N}=\\alpha.}{(s+1)/(s+50N)=alpha.}\n##' Thus, in either case, the perturbations at the end of 50 IF2 iterations are a fraction \\eqn{\\alpha}{alpha} smaller than they are at first.\n##'\n##' @section Re-running IF2 iterations:\n##' To re-run a sequence of IF2 iterations, one can use the \\code{mif2} method on a \\sQuote{mif2d_pomp} object.\n##' By default, the same parameters used for the original IF2 run are re-used (except for \\code{verbose}, the default of which is shown above).\n##' If one does specify additional arguments, these will override the defaults.\n##'\n##' @inheritSection pomp Note for Windows users\n##'\n##' @references\n##'\n##' \\Ionides2015\n##'\nNULL\n\nsetClass(\n  'mif2d_pomp',\n  contains='pfilterd_pomp',\n  slots=c(\n    Nmif = 'integer',\n    rw.sd = 'matrix',\n    cooling.type = 'character',\n    cooling.fraction.50 = 'numeric',\n    traces = 'matrix'\n  )\n)\n\nsetGeneric(\n  \"mif2\",\n  function (data, ...)\n    standardGeneric(\"mif2\")\n)\n\nsetMethod(\n  \"mif2\",\n  signature=signature(data=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"mif2\",\"data\")\n  }\n)\n\nsetMethod(\n  \"mif2\",\n  signature=signature(data=\"ANY\"),\n  definition=function (data, ...) {\n    undef_method(\"mif2\",data)\n  }\n)\n\n##' @rdname mif2\n##' @export\nsetMethod(\n  \"mif2\",\n  signature=signature(data=\"data.frame\"),\n  definition = function (\n    data,\n    ...,\n    Nmif = 1,\n    rw.sd,\n    cooling.type = c(\"geometric\", \"hyperbolic\"), cooling.fraction.50,\n    Np,\n    params, rinit, rprocess, dmeasure, partrans,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      mif2_internal(\n        data,\n        ...,\n        Nmif=Nmif,\n        rw.sd=rw.sd,\n        cooling.type=match.arg(cooling.type),\n        cooling.fraction.50=cooling.fraction.50,\n        Np=Np,\n        params=params,\n        rinit=rinit,\n        rprocess=rprocess,\n        dmeasure=dmeasure,\n        partrans=partrans,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"mif2\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname mif2\n##' @export\nsetMethod(\n  \"mif2\",\n  signature=signature(data=\"pomp\"),\n  definition = function (\n    data,\n    ...,\n    Nmif = 1,\n    rw.sd,\n    cooling.type = c(\"geometric\", \"hyperbolic\"),\n    cooling.fraction.50,\n    Np,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      mif2_internal(\n        data,\n        ...,\n        Nmif=Nmif,\n        rw.sd=rw.sd,\n        cooling.type=match.arg(cooling.type),\n        cooling.fraction.50=cooling.fraction.50,\n        Np=Np,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"mif2\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname mif2\n##' @export\nsetMethod(\n  \"mif2\",\n  signature=signature(data=\"pfilterd_pomp\"),\n  definition = function (\n    data,\n    ...,\n    Nmif = 1, Np,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    if (missing(Np)) Np <- data@Np\n\n    mif2(\n      as(data,\"pomp\"),\n      ...,\n      Nmif=Nmif,\n      Np=Np,\n      verbose=verbose\n    )\n  }\n)\n\n##' @rdname mif2\n##' @export\nsetMethod(\n  \"mif2\",\n  signature=signature(data=\"mif2d_pomp\"),\n  definition = function (\n    data,\n    ...,\n    Nmif,\n    rw.sd,\n    cooling.type,\n    cooling.fraction.50,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    if (missing(Nmif)) Nmif <- data@Nmif\n    if (missing(rw.sd)) rw.sd <- data@rw.sd\n    if (missing(cooling.type)) cooling.type <- data@cooling.type\n    if (missing(cooling.fraction.50)) cooling.fraction.50 <- data@cooling.fraction.50\n\n    mif2(\n      as(data,\"pfilterd_pomp\"),\n      ...,\n      Nmif=Nmif,\n      rw.sd=rw.sd,\n      cooling.type=cooling.type,\n      cooling.fraction.50=cooling.fraction.50,\n      verbose=verbose\n    )\n\n  }\n)\n\n##' @rdname continue\n##' @param Nmif positive integer; number of additional filtering iterations to perform\n##' @export\nsetMethod(\n  \"continue\",\n  signature=signature(object=\"mif2d_pomp\"),\n  definition = function (\n    object,\n    ...,\n    Nmif = 1\n  ) {\n\n    ndone <- object@Nmif\n\n    obj <- mif2(\n      object,\n      ...,\n      Nmif=Nmif,\n      .ndone=ndone,\n      .paramMatrix=object@paramMatrix\n    )\n\n    object@traces[ndone+1,\"loglik\"] <- obj@traces[1L,\"loglik\"]\n    obj@traces <- rbind(\n      object@traces,\n      obj@traces[-1L,colnames(object@traces)]\n    )\n    names(dimnames(obj@traces)) <- c(\"iteration\",\"name\")\n    obj@Nmif <- as.integer(ndone+Nmif)\n\n    obj\n  }\n)\n\nmif2_internal <- function (\n  object,\n  ...,\n  Nmif, rw.sd,\n  cooling.type,\n  cooling.fraction.50,\n  Np,\n  verbose,\n  .ndone = 0L,\n  .indices = integer(0),\n  .paramMatrix = NULL,\n  .gnsi = TRUE\n) {\n\n  verbose <- as.logical(verbose)\n\n  object <- pomp(object,...,verbose=verbose)\n\n  if (undefined(object@rprocess) || undefined(object@dmeasure))\n    pStop_(paste(sQuote(c(\"rprocess\",\"dmeasure\")),collapse=\", \"),\" are needed basic components.\")\n\n  gnsi <- as.logical(.gnsi)\n\n  if (length(Nmif) != 1 || !is.numeric(Nmif) || !is.finite(Nmif) || Nmif < 1)\n    pStop_(sQuote(\"Nmif\"),\" must be a positive integer.\")\n  Nmif <- as.integer(Nmif)\n\n  if (is.null(.paramMatrix)) {\n    start <- coef(object)\n  } else {  ## if '.paramMatrix' is supplied, 'start' is ignored\n    start <- apply(.paramMatrix,1L,mean)\n  }\n\n  ntimes <- length(time(object))\n\n  Np <- np_check(Np,ntimes)\n  if (Np[1L] != Np[ntimes+1L])\n    pStop_(\"Np[1] must equal Np[\",ntimes+1L,\"].\")\n\n  if (missing(rw.sd))\n    pStop_(sQuote(\"rw.sd\"),\" must be specified!\")\n  rw.sd <- perturbn_kernel_sd(rw.sd,time=time(object),paramnames=names(start))\n\n  if (missing(cooling.fraction.50))\n    pStop_(sQuote(\"cooling.fraction.50\"),\" is a required argument.\")\n  if (length(cooling.fraction.50) != 1 || !is.numeric(cooling.fraction.50) ||\n        !is.finite(cooling.fraction.50) || cooling.fraction.50 <= 0 ||\n          cooling.fraction.50 > 1)\n    pStop_(sQuote(\"cooling.fraction.50\"),\" must be in (0,1].\")\n  cooling.fraction.50 <- as.numeric(cooling.fraction.50)\n\n  cooling.fn <- mif2_cooling(\n    type=cooling.type,\n    fraction=cooling.fraction.50,\n    ntimes=length(time(object))\n  )\n\n  if (is.null(.paramMatrix)) {\n    paramMatrix <- array(data=start,dim=c(length(start),Np[1L]),\n      dimnames=list(name=names(start),rep=NULL))\n  } else {\n    paramMatrix <- .paramMatrix\n  }\n\n  traces <- array(\n    data=NA_real_,\n    dim=c(Nmif+1,length(start)+1),\n    dimnames=list(\n      iteration=NULL,\n      name=c(\"loglik\",names(start))\n    )\n  )\n  traces[1L,] <- c(NA,start)\n\n  pompLoad(object,verbose=verbose)\n  on.exit(pompUnload(object,verbose=verbose))\n\n  paramMatrix <- partrans(object,paramMatrix,dir=\"toEst\",.gnsi=gnsi)\n\n  ## iterate the filtering\n  for (n in seq_len(Nmif)) {\n\n    pfp <- mif2_pfilter(\n      object=object,\n      params=paramMatrix,\n      Np=Np,\n      mifiter=.ndone+n,\n      cooling.fn=cooling.fn,\n      rw.sd=rw.sd,\n      verbose=verbose,\n      .indices=.indices,\n      .gnsi=gnsi\n    )\n\n    gnsi <- FALSE\n\n    paramMatrix <- pfp@paramMatrix\n    traces[n+1,-1L] <- coef(pfp)\n    traces[n,1L] <- pfp@loglik\n    .indices <- pfp@indices\n\n    if (verbose) cat(\"mif2 iteration\",n,\"of\",Nmif,\"completed\\n\")\n\n  }\n\n  pfp@paramMatrix <- partrans(object,paramMatrix,dir=\"fromEst\",.gnsi=gnsi)\n\n  new(\n    \"mif2d_pomp\",\n    pfp,\n    Nmif=Nmif,\n    rw.sd=rw.sd,\n    cooling.type=cooling.type,\n    cooling.fraction.50=cooling.fraction.50,\n    traces=traces\n  )\n\n}\n\nmif2_cooling <- function (type, fraction, ntimes) {\n  switch(\n    type,\n    geometric={\n      factor <- fraction^(1/50)\n      function (nt, m) {\n        alpha <- factor^(nt/ntimes+m-1)\n        list(alpha=alpha,gamma=alpha^2)\n      }\n    },\n    hyperbolic={\n      if (fraction < 1) {\n        scal <- (50*ntimes*fraction-1)/(1-fraction)\n        function (nt, m) {\n          alpha <- (1+scal)/(scal+nt+ntimes*(m-1))\n          list(alpha=alpha,gamma=alpha^2)\n        }\n      } else {\n        function (nt, m) {\n          list(alpha=1,gamma=1)\n        }\n      }\n    }\n  )\n}\n\nmif2_pfilter <- function (\n  object,\n  params, Np, mifiter, rw.sd, cooling.fn,\n  verbose,\n  .indices = integer(0),\n  .gnsi = TRUE\n) {\n\n  gnsi <- as.logical(.gnsi)\n  verbose <- as.logical(verbose)\n  mifiter <- as.integer(mifiter)\n  Np <- as.integer(Np)\n\n  do_ta <- length(.indices)>0L\n  if (do_ta && length(.indices)!=Np[1L])\n    pStop_(sQuote(\".indices\"),\" has improper length.\")\n\n  times <- time(object,t0=TRUE)\n  ntimes <- length(times)-1\n\n  loglik <- rep(NA,ntimes)\n  eff.sample.size <- numeric(ntimes)\n\n  for (nt in seq_len(ntimes)) {\n\n    ## perturb parameters\n    pmag <- cooling.fn(nt,mifiter)$alpha*rw.sd[,nt]\n    params <- .Call(P_randwalk_perturbation,params,pmag)\n\n    tparams <- partrans(object,params,dir=\"fromEst\",.gnsi=gnsi)\n\n    ## get initial states\n    if (nt == 1L) {\n      x <- rinit(object,params=tparams)\n    }\n\n    ## advance the state variables according to the process model\n    X <- rprocess(\n      object,\n      x0=x,\n      t0=times[nt],\n      times=times[nt+1],\n      params=tparams,\n      .gnsi=gnsi\n    )\n\n    ## determine the weights\n    weights <-dmeasure(\n      object,\n      y=object@data[,nt,drop=FALSE],\n      x=X,\n      times=times[nt+1],\n      params=tparams,\n      log=TRUE,\n      .gnsi=gnsi\n    )\n    gnsi <- FALSE\n\n    ## compute effective sample size, log-likelihood\n    ## also do resampling if filtering has not failed\n    xx <- .Call(P_pfilter_computations,x=X,params=params,Np=Np[nt+1],\n      predmean=FALSE,predvar=FALSE,filtmean=FALSE,trackancestry=do_ta,\n      doparRS=TRUE,weights=weights,wave=(nt==ntimes))\n\n    ## the following is triggered by the first illegal weight value\n    if (is.integer(xx)) {\n      illegal_dmeasure_error(\n        time=times[nt+1],\n        loglik=weights[xx],\n        datvals=object@data[,nt],\n        states=X[,xx,1L],\n        params=tparams[,xx]\n      )\n    }\n\n    if (nt == ntimes) coef(object,transform=TRUE) <- xx$wmean\n    loglik[nt] <- xx$loglik\n    eff.sample.size[nt] <- xx$ess\n    if (do_ta) .indices <- .indices[xx$ancestry]\n\n    x <- xx$states\n    params <- xx$params\n\n    if (verbose && (nt%%5==0))\n      cat(\"mif2 pfilter timestep\",nt,\"of\",ntimes,\"finished.\\n\")\n\n  }\n\n  new(\n    \"pfilterd_pomp\",\n    as(object,\"pomp\"),\n    paramMatrix=params,\n    eff.sample.size=eff.sample.size,\n    cond.logLik=loglik,\n    indices=.indices,\n    Np=Np,\n    loglik=sum(loglik)\n  )\n}\n\nperturbn_kernel_sd <- function (rw.sd, time, paramnames) {\n\n  if (is.matrix(rw.sd)) return(rw.sd)\n  if (is(rw.sd,\"safecall\")) {\n    enclos <- rw.sd@envir\n    rw.sd <- as.list(rw.sd@call)[-1L]\n  } else {\n    pStop_(sQuote(\"rw.sd\"),\" should be specified using the \",sQuote(\"rw_sd\"),\n      \" function. See \",sQuote(\"?mif2\"),\".\")\n  }\n  if (is.null(names(rw.sd)) | any(names(rw.sd)==\"\"))\n    pStop(who=\"rw.sd\",\"parameters must be referenced by name.\")\n  if (!all(names(rw.sd) %in% paramnames)) {\n    unrec <- names(rw.sd)[!names(rw.sd) %in% paramnames]\n    pStop_(\"the following parameter(s), \",\n      \"given random walks in \",sQuote(\"rw.sd\"),\", are not present in \",\n      sQuote(\"params\"),\": \",paste(lapply(unrec,sQuote),collapse=\",\"),\".\")\n  }\n  ivp <- function (sd, lag = 1L) {\n    sd*(seq_along(time) %in% lag)\n  }\n  sds <- lapply(rw.sd,eval,envir=list(time=time,ivp=ivp),enclos=enclos)\n  for (n in names(sds)) {\n    len <- length(sds[[n]])\n    if (len==1) {\n      sds[[n]] <- rep(sds[[n]],length(time))\n    } else if (len!=length(time)) {\n      pStop_(sQuote(\"rw.sd\"),\" spec for parameter \",sQuote(n),\n        \" does not evaluate to a vector of the correct length (\",\n        sQuote(\"length(time(object))\"),\"=\",length(time),\").\")\n    }\n  }\n  do.call(rbind,sds)\n}\n\n##' rw_sd\n##'\n##' Specifying random-walk intensities.\n##'\n##' See \\code{\\link{mif2}} for details.\n##'\n##' @name rw_sd\n##' @rdname rw_sd\n##' @param \\dots Specification of the random-walk intensities (as standard deviations).\n##' @seealso \\code{\\link{mif2}}\n##'\n##' @export\nrw_sd <- safecall\n"
  },
  {
    "path": "R/nlf.R",
    "content": "##' Nonlinear forecasting\n##'\n##' Parameter estimation by maximum simulated quasi-likelihood.\n##'\n##' Nonlinear forecasting (NLF) is an \\sQuote{indirect inference} method.\n##' The NLF approximation to the log likelihood of the data series is computed by simulating data from a model, fitting a nonlinear autoregressive model to the simulated time series, and quantifying the ability of the resulting fitted model to predict the data time series.\n##' The nonlinear autoregressive model is implemented as a generalized additive model (GAM), conditional on lagged values, for each observation variable.\n##' The errors are assumed multivariate normal.\n##'\n##' The NLF objective function constructed by \\code{nlf_objfun} simulates long time series (\\code{nasymp} is the number of observations in the simulated times series), perhaps after allowing for a transient period (\\code{ntransient} steps).\n##' It then fits the GAM for the chosen lags to the simulated time series.\n##' Finally, it computes the quasi-likelihood of the data under the fitted GAM.\n##'\n##' NLF assumes that the observation frequency (equivalently the time between successive observations) is uniform.\n##'\n##' @name nlf\n##' @rdname nlf\n##' @include pomp.R simulate.R probe_match.R\n##' @importFrom stats .lm.fit optim setNames dnorm .lm.fit sd cov\n##' @importFrom mvtnorm dmvnorm\n##' @aliases nlf_objfun nlf_objfun,missing-method nlf_objfun,ANY-method\n##' @author Stephen P. Ellner, Bruce E. Kendall, Aaron A. King\n##' @concept nonlinear forecasting\n##' @family estimation methods\n##' @family summary statistic-based methods\n##' @family methods based on maximization\n##' @seealso \\code{\\link[stats]{optim}} \\code{\\link[subplex]{subplex}} \\code{\\link[nloptr]{nloptr}}\n##' @return\n##' \\code{nlf_objfun} constructs a stateful objective function for NLF estimation.\n##' Specfically, \\code{nlf_objfun} returns an object of class \\sQuote{nlf_objfun}, which is a function suitable for use in an \\code{\\link[stats]{optim}}-like optimizer.\n##' In particular, this function takes a single numeric-vector argument that is assumed to contain the parameters named in \\code{est}, in that order.\n##' When called, it will return the negative log quasilikelihood.\n##' It is a stateful function:\n##' Each time it is called, it will remember the values of the parameters and its estimate of the log quasilikelihood.\n##' @references\n##'\n##' \\Ellner1998\n##'\n##' \\Kendall1999\n##'\n##' \\Kendall2005\n##'\n##' @section Periodically-forced systems (seasonality):\n##' Unlike other \\pkg{pomp} estimation methods, NLF cannot accommodate general time-dependence in the model via explicit time-dependence or dependence on time-varying covariates.\n##' However, NLF can accommodate periodic forcing.\n##' It does this by including forcing phase as a predictor in the nonlinear autoregressive model.\n##' To accomplish this, one sets \\code{period} to the period of the forcing (a positive numerical value).\n##' In this case, if \\code{tensor = FALSE}, the effect is to add a periodic intercept in the autoregressive model.\n##' If \\code{tensor = TRUE}, by contrast, the fitted model includes time-periodic coefficients,\n##' constructed using tensor products of basis functions of observables with\n##' basis functions of time.\n##' @inheritSection pomp Note for Windows users\n##' @inheritSection objfun Important Note\n##' @inheritSection objfun Warning! Objective functions based on C snippets\n##' @param lags A vector specifying the lags to use when constructing the nonlinear autoregressive prediction model.\n##' The first lag is the prediction interval.\n##' @param nrbf integer scalar;\n##' the number of radial basis functions to be used at each lag.\n##' @param ti,tf required numeric values.\n##' NLF works by generating simulating long time series from the model.\n##' The simulated time series will be from \\code{ti} to \\code{tf}, with the same sampling frequency as the data.\n##' \\code{ti} should be chosen large enough so that transient dynamics have died away.\n##' \\code{tf} should be chosen large enough so that sufficiently many data points are available to estimate the nonlinear forecasting model well.\n##' An error will be generated unless the data-to-parameter ratio exceeds 10 and\n##' a warning will be given if the ratio is smaller than 30.\n##' @param period numeric; \\code{period=NA} means the model is nonseasonal.\n##' \\code{period > 0} is the period of seasonal forcing.\n##' \\code{period <= 0} is equivalent to \\code{period = NA}.\n##' @param tensor logical;\n##' if FALSE, the fitted model is a generalized additive model with time mod period as one of the predictors,\n##' i.e., a gam with time-varying intercept.\n##' If TRUE, the fitted model is a gam with lagged state variables as predictors and time-periodic coefficients, constructed using tensor products of basis functions of state variables with basis\n##' functions of time.\n##' @param transform.data optional function.\n##' If specified, forecasting is performed using data and model simulations transformed by this function.\n##' By default, \\code{transform.data} is the identity function,\n##' i.e., no transformation is performed.\n##' The main purpose of \\code{transform.data} is to achieve approximately multivariate normal forecasting errors.\n##' If the data are univariate, \\code{transform.data} should take a scalar and return a scalar.\n##' If the data are multivariate, \\code{transform.data} should assume a vector input and return a vector of the same length.\n##' @inheritParams probe_match\n##' @inheritParams pomp\n##'\n##' @example examples/nlf.R\n##'\nNULL\n\n## nonlinear forecasting\n## v. 0.1, 3 Dec. 2007\n## by Bruce Kendall & Steve Ellner\n##\n## v. 0.2, 30 May 2008, by Steve Ellner\n## Adds automatic Wald asymptotic standard errors and the\n## capability for moving-blocks bootstrap standard errors.\n## Quadratic regression near optimum used to select increments\n## for finite-difference approximations to gradient and Hessian\n##\n## v 1.0, 19 June 2008 by Steve Ellner and Aaron King\n## adds capacity to fit models with periodically time-varying parameters\n## of known period and improves the compatibility with the standard for pomp objects\n##\n## v 2.0, 3 September 2018, by Aaron King\n## - removes bootstrapping and standard errors\n## - incorporates the new stateful-function approach of pomp version 2\n\nsetClass(\n  \"nlf_objfun\",\n  contains=\"function\",\n  slots=c(\n    env=\"environment\",\n    ti=\"numeric\",\n    tf=\"numeric\",\n    est=\"character\"\n  )\n)\n\nsetGeneric(\n  \"nlf_objfun\",\n  function (data, ...)\n    standardGeneric(\"nlf_objfun\")\n)\n\nsetMethod(\n  \"nlf_objfun\",\n  signature=signature(data=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"nlf_objfun\",\"data\")\n  }\n)\n\nsetMethod(\n  \"nlf_objfun\",\n  signature=signature(data=\"ANY\"),\n  definition=function (data, ...) {\n    undef_method(\"nlf_objfun\",data)\n  }\n)\n\n##' @rdname nlf\n##' @export\nsetMethod(\n  \"nlf_objfun\",\n  signature=signature(data=\"data.frame\"),\n  definition=function (\n    data,\n    ...,\n    est = character(0),\n    lags, nrbf = 4, ti, tf,\n    seed = NULL,\n    transform.data = identity,\n    period = NA,\n    tensor = TRUE,\n    fail.value = NA_real_,\n    params, rinit, rprocess, rmeasure,\n    verbose = getOption(\"verbose\")\n  ) {\n\n    tryCatch(\n      nlfof_internal(\n        object=data,\n        ...,\n        est=est,\n        lags=lags,\n        nrbf=nrbf,\n        ti=ti,\n        tf=tf,\n        seed=seed,\n        period=period,\n        tensor=tensor,\n        transform.data=transform.data,\n        fail.value=fail.value,\n        params=params,\n        rinit=rinit,\n        rprocess=rprocess,\n        rmeasure=rmeasure,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"nlf_objfun\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname nlf\n##' @export\nsetMethod(\n  \"nlf_objfun\",\n  signature=signature(data=\"pomp\"),\n  definition=function (\n    data,\n    ...,\n    est = character(0),\n    lags, nrbf = 4, ti, tf,\n    seed = NULL,\n    transform.data = identity,\n    period = NA,\n    tensor = TRUE,\n    fail.value = NA,\n    verbose = getOption(\"verbose\")\n  ) {\n\n    tryCatch(\n      nlfof_internal(\n        object=data,\n        ...,\n        est=est,\n        lags=lags,\n        nrbf=nrbf,\n        ti=ti,\n        tf=tf,\n        seed=seed,\n        period=period,\n        tensor=tensor,\n        transform.data=transform.data,\n        fail.value=fail.value,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"nlf_objfun\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname nlf\n##' @export\nsetMethod(\n  \"nlf_objfun\",\n  signature=signature(data=\"nlf_objfun\"),\n  definition=function (\n    data,\n    ...,\n    est,\n    lags, nrbf, ti, tf,\n    seed = NULL,\n    period, tensor,\n    transform.data,\n    fail.value,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    if (missing(est)) est <- data@est\n    if (missing(lags)) lags <- data@env$lags\n    if (missing(nrbf)) nrbf <- data@env$nrbf\n    if (missing(ti)) ti <- data@ti\n    if (missing(tf)) tf <- data@tf\n    if (missing(period)) period <- data@env$period\n    if (missing(tensor)) tensor <- data@env$tensor\n    if (missing(transform.data)) transform.data <- data@env$transform.data\n    if (missing(fail.value)) fail.value <- data@env$fail.value\n\n    nlf_objfun(\n      data@env$object,\n      est=est,\n      lags=lags,\n      nrbf=nrbf,\n      ti=ti,\n      tf=tf,\n      seed=seed,\n      period=period,\n      tensor=tensor,\n      transform.data=transform.data,\n      fail.value=fail.value,\n      ...,\n      verbose=verbose\n    )\n\n  }\n)\n\nnlfof_internal <- function (\n  object,\n  ...,\n  est, lags, nrbf, ti, tf, seed, period, tensor,\n  transform.data, fail.value,\n  verbose\n)\n{\n\n  verbose <- as.logical(verbose)\n\n  object <- pomp(object, ..., verbose=verbose)\n\n  if (!undefined(object@covar))\n    pStop_(\"NLF is incompatible with time-varying covariates.\")\n\n  est <- as.character(est)\n  est <- est[nzchar(est)]\n\n  if (!is.numeric(lags) || !all(is.finite(lags)) || any(lags < 1))\n    pStop_(sQuote(\"lags\"),\" must be positive integers.\")\n  lags <- as.integer(lags)\n\n  if (!is.numeric(nrbf) || length(nrbf) != 1 || !is.finite(nrbf) || nrbf < 4)\n    pStop_(sQuote(\"nrbf\"),\" must be at least 4.\")\n  nrbf <- as.integer(nrbf)\n\n  if (!(is.logical(period) || is.numeric(period)) ||\n        length(period) != 1 || is.infinite(period))\n    pStop_(sQuote(\"period\"),\" must be single finite number or NA.\")\n  period <- as.numeric(period)\n  if (!is.na(period) && period <= 0) period <- NA_real_\n\n  tensor <- as.logical(tensor)\n\n  ## check that times are equally spaced\n  dt.tol <- 1e-3\n  dts <- diff(time(object,t0=FALSE))\n  dt <- mean(dts)\n  if (diff(range(dts)) > dt.tol*dt)\n    pStop_(\"NLF requires uniform sampling frequency.\")\n\n  t0 <- timezero(object)\n\n  if (!is.numeric(ti) || length(ti) != 1 || !is.finite(ti) || ti < t0)\n    pStop_(sQuote(\"ti\"),\" must be a single numeric value larger than \",sQuote(\"t0\"),\".\")\n\n  if (!is.numeric(tf) || length(tf) != 1 || !is.finite(tf) || tf <= ti)\n    pStop_(sQuote(\"tf\"),\" must be a single numeric value larger than \",sQuote(\"ti\"),\".\")\n\n  times <- seq(from=ti,to=tf,by=dt)\n\n  dof <- length(lags)*nrbf\n  if (isTRUE(period > 0)) {\n    if (tensor) {\n      dof <- dof*nrbf\n    } else {\n      dof <- dof+nrbf\n    }\n  }\n\n  if (length(times) < 10*dof)\n    pStop_(\"insufficiently long simulated time series: increase \",sQuote(\"tf\"),\n      \" to at least \",ti+10*dof*dt,\".\")\n  if (length(times) < 30*dof)\n    pWarn(who=\"nlf_objfun\",\"insufficiently long simulated time series: \",\n      \"consider increasing \",sQuote(\"tf\"),\" to \",ti+30*dof*dt,\" or larger.\")\n\n  transform.data <- match.fun(transform.data)\n\n  if (!(is.logical(fail.value) || is.numeric(fail.value)) || length(fail.value) != 1)\n    pStop_(sQuote(\"fail.value\"),\" should be a single (large) number or \",sQuote(\"NA\"),\".\")\n  fail.value <- as.numeric(fail.value)\n  if (isTRUE(fail.value < 1000))\n    pWarn(who=\"nlf_objfun\",\n      sQuote(\"fail.value\"),\" should be a large number or \",sQuote(\"NA\"),\".\")\n\n  pompLoad(object,verbose=verbose)\n\n  params <- coef(object,transform=TRUE)\n\n  idx <- match(est,names(params))\n  if (any(is.na(idx))) {\n    missing <- est[is.na(idx)]\n    pStop_(\"parameter\",ngettext(length(missing),\"\",\"s\"),\" \",\n      paste(sQuote(missing),collapse=\",\"),\" not found in \",sQuote(\"params\"),\".\")\n  }\n\n  logql <- nlf_lql(object,times=times,lags=lags,nrbf=nrbf,fail.value=fail.value,\n    period=period,tensor=tensor,seed=seed,transform.data=transform.data,\n    verbose=verbose)\n\n  .gnsi <- TRUE\n\n  ofun <- function (par = numeric(0)) {\n    params[idx] <- par\n    coef(object,transform=TRUE) <<- params\n    logql <<- nlf_lql(object,times=times,lags=lags,nrbf=nrbf,fail.value=fail.value,\n      period=period,tensor=tensor,seed=seed,transform.data=transform.data,\n      .gnsi=.gnsi,verbose=verbose)\n    .gnsi <<- FALSE\n    if (is.finite(logql) || is.na(fail.value)) -logql else fail.value #nocov\n  }\n\n  environment(ofun) <- list2env(\n    list(object=object,times=times,lags=lags,nrbf=nrbf,fail.value=fail.value,\n      period=period,tensor=tensor,seed=seed,transform.data=transform.data,\n      params=params,idx=idx,logql=logql,.gnsi=.gnsi,verbose=verbose),\n    parent=parent.frame(2)\n  )\n\n  new(\"nlf_objfun\",ofun,env=environment(ofun),ti=ti,tf=tf,est=est)\n\n}\n\n## Evaluates the NLF objective function given a POMP object.\n##\n## Computes the vector of log quasi-likelihood values at the observations\n## Note that the log QL itself is returned, not the negative log QL,\n## so a large NEGATIVE value is used to flag bad parameters\n\nnlf_lql <- function (object, times, lags, nrbf, period, tensor,\n  seed, transform.data, fail.value, .gnsi = TRUE, verbose)\n{\n\n  y <- simulate(object,times=times,seed=seed,format=\"arrays\",.gnsi=.gnsi,verbose=verbose)$obs\n\n  ## Test whether the model time series is valid\n  if (!all(is.finite(y))) return(-fail.value)\n\n  dat.mat <- obs(object)\n  mod.mat <- array(dim=dim(y)[c(1L,3L)],dimnames=list(rownames(dat.mat),NULL))\n  tryCatch(\n  {\n    dat.mat[,] <- apply(dat.mat,2L,transform.data)\n    mod.mat[,] <- apply(y[,1L,,drop=FALSE],c(2L,3L),transform.data)\n  },\n  error = function (e) pStop(who=\"transform.data\",conditionMessage(e))\n  )\n\n  tryCatch(\n    nlf_internal(\n      dat.mat=dat.mat,\n      dat.times=time(object),\n      mod.mat=mod.mat,\n      mod.times=times,\n      lags=lags,\n      nrbf=nrbf,\n      period=period,\n      tensor=tensor,\n      fail.value=fail.value,\n      verbose=verbose\n    ),\n    error = function (e) pStop(who=\"nlf_lql\",conditionMessage(e))\n  )\n\n}\n\n## CENTRAL NLF FUNCTION\n##\n## Version 1.0, 4 December 2007, S.P. Ellner and Bruce E. Kendall\n## Version 1.1, 19 June 2008, S.P. Ellner and A.A. King.\n## Version 1.2, 3 September 2018, A.A. King\n\n## Peculiarity of the code: No basis functions involving cross terms of observables.\n\n#####################################################################################\n## ARGUMENTS:\n## dat.mat = matrix of data time series, nobs x ntimes.data\n## mod.mat = matrix of model time series, nobs x ntimes.sim\n## lags = vector of lag times for forecasting y(t) = f(y(t-lag1),y(t-lag2),....)+error\n## nrbf = number of radial basis functions\n## period: period=NA means the model is nonseasonal. period=integer>0 is the period of\n##         seasonal forcing in 'real time' (the units of mod.times).\n## tensor: logical. if FALSE, the fitted model is a gam with time(mod period) as\n##         one of the predictors, i.e. a gam with time-varying intercept.\n##         if TRUE, the fitted model is a gam with lagged state variables as\n##         predictors and time-periodic coefficients, constructed using tensor\n##         products of basis functions of state variables with basis functions of time.\n##\n##       NOTE: periodic models are constructed so that the time variable on the\n##       right hand side corresponds to the observation time of the predictee,\n##       not of the predictors\n##\n## VALUE: the NLF approximation to the log likelihood of the data series\n##        under the forecasting model based on mod.mat. The approximation used\n##        here is a generalized additive model for each observation variable, conditional\n##        on lagged values of all observation variables, with multivariate normal errors.\n##        The return from this function is the vector of log quasi-likelihood values at\n##        the data points; this must be summed to get the log quasiliklihood function.\n##\n## IMPORTANT NOTE TO FUTURE PROGRAMMERS: It may appear at first glance that basis\n## functions for the data series, and other things related to the data series, could be\n## constructed once and for all rather than rebuilt on each call to this function.\n## THIS IS NOT TRUE. The basis functions are constructed anew on each call using\n## information from the model-simulated time series, and this feature is important\n## for reliable NLF parameter estimation because it rules out spurious good fits\n## that really are due to extrapolation far from the model-simulated time series.\n#######################################################################################\n\nnlf_internal <- function (dat.mat, dat.times, mod.mat, mod.times,\n  lags, nrbf, period, tensor, fail.value, verbose) {\n\n  seas <- !is.na(period)\n  nvar <- nrow(dat.mat)\n\n  knots <- apply(mod.mat,1L,rbf_knots,n=nrbf)\n\n  dat.lags <- make_lags_nlf(x=dat.mat,times=dat.times,lags=lags)\n  sim.lags <- make_lags_nlf(x=mod.mat,times=mod.times,lags=lags)\n\n  dat.pred <- array(dim=c(dim(dat.lags$x),nrbf))\n  sim.pred <- array(dim=c(dim(sim.lags$x),nrbf))\n\n  for (i in seq_len(nvar)) {\n    dat.pred[,i,,] <- rbf_basis(dat.lags$x[,i,],knots=knots[,i])\n    sim.pred[,i,,] <- rbf_basis(sim.lags$x[,i,],knots=knots[,i])\n  }\n\n  dd <- dim(dat.pred)\n  dim(dat.pred) <- c(dd[1],prod(dd[-1]))\n  dd <- dim(sim.pred)\n  dim(sim.pred) <- c(dd[1],prod(dd[-1]))\n\n  dat.resp <- dat.lags$y\n  sim.resp <- sim.lags$y\n\n  if (seas) {\n\n    knots <- seq(from=-0.1,to=1.1*period,length.out=nrbf)\n    dat.seas <- rbf_basis(as.matrix(dat.lags$t %% period),knots=knots)\n    sim.seas <- rbf_basis(as.matrix(sim.lags$t %% period),knots=knots)\n    dd <- dim(dat.seas)\n    dim(dat.seas) <- c(dd[1],prod(dd[-1]))\n    dd <- dim(sim.seas)\n    dim(sim.seas) <- c(dd[1],prod(dd[-1]))\n\n    if (tensor) {\n\n      ## make gam coefficients time-dependent\n      dat.pred <- make_tensorbasis(dat.pred,dat.seas)\n      sim.pred <- make_tensorbasis(sim.pred,sim.seas)\n\n    } else {\n\n      ## add time-varying intercept\n      dat.pred <- cbind(dat.pred,dat.seas)\n      sim.pred <- cbind(sim.pred,sim.seas)\n\n\n    }\n  }\n\n  model.lm <- .lm.fit(sim.pred,sim.resp)\n\n  prediction.err <- dat.resp - dat.pred %*% model.lm$coefficients\n\n  LQL <- dmvnorm(prediction.err,sigma=cov(model.lm$residuals),log=TRUE)\n  ## NOTE: This could be improved using GLS.\n\n  LQL <- sum(LQL)\n\n  if (verbose) cat(sprintf(\"logql = %g\\n\",LQL))\n\n  if (is.finite(LQL)) LQL else -fail.value\n\n}\n\n## Create design array and response matrix out of lagged variables.\n## Data series are in the rows of 'x'.\nmake_lags_nlf <- function (x, times, lags) {\n\n  nvar <- nrow(x)\n  m <- length(lags)     ## number of lag variables per observable\n  maxlag <- max(lags)\n  n <- ncol(x)-maxlag   ## length of lagged time series\n  start <- maxlag+1     ## first predicted observation\n\n  X <- array(dim=c(n,nvar,m))\n  for (k in seq_len(length(lags)))\n    X[,,k] <- t(x[,seq.int(from=start-lags[k],by=1,length.out=n)])\n\n  y <- t(x[,seq.int(from=start,by=1,length.out=n),drop=FALSE])\n  t <- times[seq.int(from=start,by=1,length.out=n)]\n\n  list(x=X,y=y,t=t)\n\n}\n\nrbf_knots <- function (X, n, margin = 0.1) {\n  r <- range(X)\n  seq(\n    from=(1+margin)*r[1]-margin*r[2],\n    to=(1+margin)*r[2]-margin*r[1],\n    length.out=n\n  )\n}\n\nrbf_basis <- function (X, knots) {\n  X1 <- array(dim=c(dim(X),length(knots)))\n  X1[] <- as.numeric(X)-rep(knots,each=length(X))\n  s <- diff(range(knots))/length(knots)\n  fac <- -1/2/s/s\n  exp(fac*X1*X1)\n}\n\n## GAUSS trimr function:\n## trims n1 rows from the start,\n## n2 rows from the end of a matrix or vector\n## trimr <- function (a, n1, n2) {\n##   a[seq.int(from=n1+1,to=NROW(a)-n2,by=1)]\n## }\n\n## Newey.West <- function (x, y, maxlag) {\n##   w <- 1-seq_len(maxlag)/(maxlag+1)\n##   out <- mean(x*y,na.rm=TRUE)\n##   for (i in seq_len(maxlag)) {\n##     out <- out+\n##       w[i]*mean(trimr(x,i,0)*trimr(y,0,i),na.rm=TRUE)+\n##       w[i]*mean(trimr(y,i,0)*trimr(x,0,i),na.rm=TRUE)\n##   }\n##   out\n## }\n\nmake_tensorbasis <- function(A,B) {\n  if (nrow(A) != nrow(B))\n    pStop(who=\"make_tensorbasis\",\"incompatible matrices.\") #nocov\n  nA <- ncol(A)\n  nB <- ncol(B)\n  Tmat <- matrix(0,nrow(A),nA*nB)\n  for (j in seq_len(nB)) {\n    Tmat[,seq.int(from=(j-1)*nA+1,to=j*nA,by=1)] <- A*B[,j]\n  }\n  Tmat\n}\n"
  },
  {
    "path": "R/objfun.R",
    "content": "##' Objective functions\n##'\n##' Methods common to \\pkg{pomp} stateful objective functions\n##'\n##' @name objfun\n##' @rdname objfun\n##' @keywords internal\n##' @include traj_match.R spect_match.R probe_match.R nlf.R\n##' @include loglik.R summary.R coef.R as_data_frame.R as_pomp.R\n##'\n##' @section Important Note:\n##' Since \\pkg{pomp} cannot guarantee that the \\emph{final} call an optimizer makes to the function is a call \\emph{at} the optimum, it cannot guarantee that the parameters stored in the function are the optimal ones.\n##' Therefore, it is a good idea to evaluate the function on the parameters returned by the optimization routine, which will ensure that these parameters are stored.\n##' @section Warning! Objective functions based on C snippets:\n##' If you use C snippets (see \\code{\\link{Csnippet}}), a dynamically loadable library will be built.\n##' As a rule, \\pkg{pomp} functions load this library as needed and unload it when it is no longer needed.\n##' The stateful objective functions are an exception to this rule.\n##' For efficiency, calls to the objective function do not execute \\code{\\link{pompLoad}} or \\code{\\link{pompUnload}}:\n##' rather, it is assumed that \\code{\\link{pompLoad}} has been called before any call to the objective function.\n##' When a stateful objective function using one or more C snippets is created, \\code{\\link{pompLoad}} is called internally to build and load the library:\n##' therefore, within a single \\R session, if one creates a stateful objective function, one can freely call that objective function and (more to the point) pass it to an optimizer that calls it freely, without needing to call \\code{\\link{pompLoad}}.\n##' On the other hand, if one retrieves a stored objective function from a file, or passes one to another \\R session, one must call \\code{\\link{pompLoad}} before using it.\n##' \\strong{Failure to do this will typically result in a segmentation fault (i.e., it will crash the \\R session).}\n##'\nNULL\n\nsetClassUnion(\n  \"objfun\",\n  members=c(\n    \"traj_match_objfun\",\n    \"spect_match_objfun\",\n    \"probe_match_objfun\",\n    \"nlf_objfun\"\n  )\n)\n\n##' @rdname coef\n##' @export\nsetMethod(\n  \"coef\",\n  signature=signature(object=\"objfun\"),\n  definition=function (object, ...) {\n    coef(object@env$object,...)\n  }\n)\n\n##' @rdname coef\n##' @export\nsetMethod(\n  \"coef<-\",\n  signature=signature(object=\"objfun\"),\n  definition=function (object, pars, transform = FALSE, ..., value) {\n    coef(object@env$object,pars=pars,transform=transform,...) <- value\n    object@env$params <- coef(object@env$object,transform=TRUE)\n    object\n  }\n)\n\n##' @rdname summary\n##' @export\nsetMethod(\n  \"summary\",\n  signature=signature(object=\"objfun\"),\n  definition=function (object, ...) {\n    summary(object@env$object)\n  }\n)\n\nsetIs(\n  class1=\"objfun\",\n  class2=\"pomp\",\n  coerce = function (from) {\n    as(from@env$object,\"pomp\")\n  },\n  replace= function (from, to, value) {\n    pStop(who=-4L,\"cannot replace the pomp object in a stateful objective function.\")\n  }\n)\n\nsetAs(\n  from=\"objfun\",\n  to=\"data.frame\",\n  def = function (from) {\n    as(as(from@env$object,\"pomp\"),\"data.frame\")\n  }\n)\n\n##' @rdname partrans\n##' @export\nsetMethod(\n  \"partrans\",\n  signature=signature(object=\"objfun\"),\n  definition=function (object, ...) {\n    partrans(as(object,\"pomp\"),...)\n  }\n)\n\n##' @rdname simulate\n##' @export\nsetMethod(\n  \"simulate\",\n  signature=signature(object=\"objfun\"),\n  definition=function (object, seed = NULL,...) {\n    simulate(as(object,\"pomp\"),seed=seed,...)\n  }\n)\n\n##' @rdname probe\n##' @export\nsetMethod(\n  \"probe\",\n  signature=signature(data=\"objfun\"),\n  definition=function (data, ..., seed = NULL) {\n    probe(as(data,\"pomp\"),seed=seed,...)\n  }\n)\n\n##' @rdname pfilter\n##' @export\nsetMethod(\n  \"pfilter\",\n  signature=signature(data=\"objfun\"),\n  definition=function (data, ...) {\n    pfilter(as(data,\"pomp\"),...)\n  }\n)\n\n##' @rdname spect\n##' @export\nsetMethod(\n  \"spect\",\n  signature=signature(data=\"objfun\"),\n  definition=function (data, ..., seed = NULL) {\n    spect(as(data,\"pomp\"),seed=seed,...)\n  }\n)\n\n##' @rdname load\n##' @export\nsetMethod(\n  \"pompLoad\",\n  signature=signature(object=\"objfun\"),\n  definition = function (object, ...) {\n    object@env$.gnsi <- TRUE\n    pompLoad_internal(object@env$object,...)\n  }\n)\n\n##' @rdname load\n##' @export\nsetMethod(\n  \"pompUnload\",\n  signature=signature(object=\"objfun\"),\n  definition = function (object, ...) {\n    object@env$.gnsi <- TRUE\n    pompUnload_internal(object@env$object,...)\n  }\n)\n"
  },
  {
    "path": "R/obs.R",
    "content": "##' obs\n##'\n##' Extract the data array from a \\sQuote{pomp} object.\n##'\n##' @name obs\n##' @aliases obs,ANY-method obs,missing-method\n##' @docType methods\n##' @rdname obs\n##' @include pomp_class.R melt.R\n##' @importFrom stats setNames\n##' @family extraction methods\n##'\nNULL\n\nsetGeneric(\n  \"obs\",\n  function (object, ...)\n    standardGeneric(\"obs\")\n)\n\nsetMethod(\n  \"obs\",\n  signature=signature(object=\"missing\"),\n  definition=function (object, ...) {\n    reqd_arg(\"obs\",\"object\")\n  }\n)\n\nsetMethod(\n  \"obs\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"obs\",\"object\")\n  }\n)\n\n##' @rdname obs\n##' @param object an object of class \\sQuote{pomp}, or of a class extending \\sQuote{pomp}\n##' @param vars names of variables to retrieve\n##' @param format format of the returned object\n##' @param \\dots ignored\n##' @export\nsetMethod(\n  \"obs\",\n  signature=signature(object=\"pomp\"),\n  definition=function (object, vars, ...,\n    format = c(\"array\", \"data.frame\")) {\n    if (missing(vars)) {\n      y <- object@data\n      names(dimnames(y)) <- c(\"name\",object@timename)\n    } else {\n      varnames <- rownames(object@data)\n      if (!all(vars%in%varnames))\n        pStop(who=\"obs\",\"some elements of \",\n          sQuote(\"vars\"),\" correspond to no observed variable.\")\n      y <- object@data[vars,,drop=FALSE]\n      dimnames(y) <- setNames(list(vars,NULL),c(\"name\",object@timename))\n    }\n    format <- match.arg(format)\n    if (format == \"data.frame\") {\n      y <- data.frame(time=time(object),t(y))\n      names(y)[1L] <- object@timename\n    }\n    y\n  }\n)\n\n##' @rdname obs\n##' @export\nsetMethod(\n  \"obs\",\n  signature=signature(object=\"listie\"),\n  definition=function (object, vars, ...,\n    format = c(\"array\", \"data.frame\")) {\n    format <- match.arg(format)\n    y <- lapply(object,obs,vars=vars,format=format,...)\n    if (format == \"data.frame\") {\n      rbind_fill(y,.id=\".id\")\n    } else {\n      y\n    }\n  }\n)\n"
  },
  {
    "path": "R/ou2.R",
    "content": "##' Two-dimensional discrete-time Ornstein-Uhlenbeck process\n##'\n##' \\code{ou2()} constructs a \\sQuote{pomp} object encoding a bivariate discrete-time Ornstein-Uhlenbeck process with noisy observations.\n##'\n##' If the state process is \\eqn{X(t) = (X_{1}(t),X_{2}(t))}, then\n##' \\deqn{X(t+1) = \\alpha X(t) + \\sigma \\epsilon(t),}\n##' where \\eqn{\\alpha} and \\eqn{\\sigma} are 2x2 matrices,\n##' \\eqn{\\sigma} is lower-triangular, and\n##' \\eqn{\\epsilon(t)} is standard bivariate normal.\n##' The observation process is \\eqn{Y(t) = (Y_1(t),Y_2(t))}, where\n##' \\eqn{Y_i(t) \\sim \\mathrm{normal}(X_i(t),\\tau)}.\n##'\n##' @name ou2\n##' @rdname ou2\n##' @include simulate.R\n##' @docType data\n##' @keywords models\n##' @family pomp examples\n##' @return A \\sQuote{pomp} object with simulated data.\n##' @example examples/ou2.R\n##'\nNULL\n\n##' @rdname ou2\n##' @param alpha_1,alpha_2,alpha_3,alpha_4 entries of the \\eqn{\\alpha} matrix, in column-major order.\n##' That is, \\code{alpha_2} is in the lower-left position.\n##' @param sigma_1,sigma_2,sigma_3 entries of the lower-triangular \\eqn{\\sigma} matrix.\n##' \\code{sigma_2} is the entry in the lower-left position.\n##' @param tau measurement error s.d.\n##' @param x1_0,x2_0 latent variable values at time \\code{t0}\n##' @param t0 the zero time\n##' @param times vector of observation times\n##' @param seed seed of the random number generator\n##'\n##' @export\nou2 <- function (\n  alpha_1 = 0.8, alpha_2 = -0.5, alpha_3 = 0.3, alpha_4 = 0.9,\n  sigma_1 = 3, sigma_2 = -0.5, sigma_3 = 2,\n  tau = 1,\n  x1_0 = -3, x2_0 = 4,\n  times = 1:100, t0 = 0,\n  seed = 787832394L\n)\n{\n  simulate(\n    times=times,\n    t0=t0,\n    seed=seed,\n    rprocess=discrete_time(\"_ou2_step\"),\n    dprocess=\"_ou2_pdf\",\n    emeasure = \"_ou2_emeasure\",\n    vmeasure = \"_ou2_vmeasure\",\n    dmeasure = \"_ou2_dmeasure\",\n    rmeasure = \"_ou2_rmeasure\",\n    skeleton = map(\"_ou2_skel\",delta.t=1),\n    PACKAGE=\"pomp\",\n    paramnames = c(\n      \"alpha_1\",\"alpha_2\",\"alpha_3\",\"alpha_4\",\n      \"sigma_1\",\"sigma_2\",\"sigma_3\",\n      \"tau\"\n    ),\n    statenames = c(\"x1\",\"x2\"),\n    obsnames = c(\"y1\",\"y2\"),\n    params=c(\n      alpha_1=alpha_1, alpha_2=alpha_2, alpha_3=alpha_3, alpha_4=alpha_4,\n      sigma_1=sigma_1, sigma_2=sigma_2, sigma_3=sigma_3,\n      tau=tau,\n      x1_0=x1_0, x2_0=x2_0\n    )\n  )\n}\n"
  },
  {
    "path": "R/package.R",
    "content": "##' Inference for partially observed Markov processes\n##'\n##' The \\pkg{pomp} package provides facilities for inference on time series\n##' data using partially-observed Markov process (\\acronym{POMP}) models.\n##' These models are also known as state-space models, hidden Markov models, or\n##' nonlinear stochastic dynamical systems.  One can use \\pkg{pomp} to fit\n##' nonlinear, non-Gaussian dynamic models to time-series data.  The package is\n##' both a set of tools for data analysis and a platform upon which statistical\n##' inference methods for \\acronym{POMP} models can be implemented.\n##'\n##' @name pomp-package\n##' @aliases pomp,package pomp-package\n##' @author Aaron A. King\n##' @family implementation information\n##' @family pomp workhorses\n##' @family estimation methods\n##' @family elementary algorithms\n##' @keywords ts models multivariate\n##'\n##' @section Data analysis using \\pkg{pomp}:\n##' \\pkg{pomp} provides algorithms for:\n##' \\enumerate{\n##' \\item Simulation of stochastic dynamical systems;\n##' see \\code{\\link{simulate}}.\n##' \\item Particle filtering (AKA sequential Monte Carlo or sequential importance sampling);\n##' see \\code{\\link{pfilter}} and \\code{\\link{wpfilter}}.\n##' \\item The iterated filtering methods of Ionides et al. (2006, 2011, 2015);\n##' see \\code{\\link{mif2}}.\n##' \\item The nonlinear forecasting algorithm of Kendall et al. (2005);\n##' see \\link{nlf}.\n##' \\item The particle MCMC approach of Andrieu et al. (2010);\n##' see \\code{\\link{pmcmc}}.\n##' \\item The probe-matching method of Kendall et al. (1999, 2005);\n##' see \\link{probe_match}.\n##' \\item Synthetic likelihood a la Wood (2010);\n##' see \\code{\\link{probe}}.\n##' \\item A spectral probe-matching method (Reuman et al. 2006, 2008);\n##' see \\link{spect_match}.\n##' \\item Approximate Bayesian computation (Toni et al. 2009);\n##' see \\code{\\link{abc}}.\n##' \\item The approximate Bayesian sequential Monte Carlo scheme of Liu & West (2001);\n##' see \\code{\\link{bsmc2}}.\n##' \\item Ensemble and ensemble adjusted Kalman filters;\n##' see \\link{kalman}.\n##' \\item Simple trajectory matching;\n##' see \\link{traj_match}.\n##' }\n##' The package also provides various tools for plotting and extracting information on models and data.\n##'\n##' @section Structure of the package:\n##'\n##' \\pkg{pomp} algorithms are arranged into several levels.\n##' At the top level, \\link[=estimation_algorithms]{estimation algorithms} estimate model parameters and return information needed for other aspects of inference.\n##' \\link[=elementary_algorithms]{Elementary algorithms} perform common operations on \\acronym{POMP} models, including simulation, filtering, and application of diagnostic probes;\n##' these functions may be useful in inference, but they do not themselves perform estimation.\n##' At the lowest level, \\link[=workhorses]{workhorse functions} provide the interface to \\link[=basic_components]{basic POMP model components}.\n##' Beyond these, \\pkg{pomp} provides a variety of auxiliary functions for manipulating and extracting information from \\sQuote{pomp} objects, producing diagnostic plots, \\link[=bake]{facilitating reproducible computations}, and so on.\n##'\n##' @section Implementing a model:\n##'\n##' The basic structure at the heart of the package is the \\sQuote{pomp object}.\n##' This is a container holding a time series of data (possibly multivariate) and a model.\n##' The model is specified by specifying some or all of its \\link[=basic_components]{basic model components}.\n##' One does this using the \\link[=basic_components]{basic component arguments} to the \\code{\\link{pomp}} constructor.\n##' One can also add, modify, or delete basic model components \\dQuote{on the fly} in any \\pkg{pomp} function that accepts them.\n##'\n##' @section Documentation and examples:\n##'\n##' The package contains a number of examples.\n##' Some of these are included in the help pages.\n##' In addition, \\link[=pomp_examples]{several pre-built POMP models} are included with the package.\n##' Tutorials and other documentation, including a \\href{https://kingaa.github.io/pomp/FAQ.html}{package FAQ}, are available from the \\href{https://kingaa.github.io/pomp/}{package website}.\n##'\n##' @section Useful links:\n##' \\itemize{\n##'  \\item{\\pkg{pomp} homepage: \\url{https://kingaa.github.io/pomp/}}\n##'  \\item{Report bugs to: \\url{https://github.com/kingaa/pomp/issues}}\n##'  \\item{Frequently asked questions: \\url{https://kingaa.github.io/pomp/FAQ.html}}\n##'  \\item{User guides and tutorials: \\url{https://kingaa.github.io/pomp/docs.html}}\n##'  \\item{\\pkg{pomp} news: \\url{https://kingaa.github.io/pomp/blog.html}}\n##' }\n##'\n##' @section Citing \\pkg{pomp}:\n##' Execute \\code{citation(\"pomp\")} to view the correct citation for publications.\n##'\n##' @references\n##'\n##' \\King2016\n##'\n##' See \\href{https://kingaa.github.io/pomp/biblio.html}{the package website for more references}, including many publications that use \\pkg{pomp}.\n##'\n##' @useDynLib pomp, .registration = TRUE, .fixes=\"P_\"\n##' @import methods\n\"_PACKAGE\"\n\n## .onAttach <- function (...) {\n##   .banner()\n## }\n\n## .banner <- function (...) {\n##   msg <- r\"{\n## Welcome to pomp!\n## }\"\n##  packageStartupMessage(\"\\n\",paste(strwrap(msg),collapse=\"\\n\"),\"\\n\")\n## }\n"
  },
  {
    "path": "R/parameter_trans.R",
    "content": "##' parameter transformations\n##'\n##' Equipping models with parameter transformations to facilitate searches in constrained parameter spaces.\n##'\n##' @name parameter_trans\n##' @rdname parameter_trans\n##' @docType methods\n##' @include pomp_fun.R csnippet.R pstop.R undefined.R\n##' @aliases parameter_trans,missing,missing-method\n##' parameter_trans,ANY,ANY-method parameter_trans,ANY,missing-method\n##' parameter_trans,NULL,NULL-method parameter_trans,missing,ANY-method\n##' @family implementation information\n##' @seealso \\code{\\link{partrans}}\n##' @param toEst,fromEst procedures that perform transformation of model parameters to and from the estimation scale, respectively.\n##' These can be furnished using C snippets, \\R functions, or via procedures in an external, dynamically loaded library.\n##' @param log names of parameters to be log transformed.\n##' @param logit names of parameters to be logit transformed.\n##' @param barycentric names of parameters to be collectively transformed according to the log barycentric transformation.\n##' \\strong{Important note:} variables to be log-barycentrically transformed \\emph{must be adjacent} in the parameter vector.\n##' @param \\dots ignored.\n##' @inheritSection pomp Note for Windows users\n##' @details\n##' When parameter transformations are desired, they can be integrated into the \\sQuote{pomp} object via the \\code{partrans} arguments using the \\code{parameter_trans} function.\n##' As with the other \\link[=basic_components]{basic model components}, these should ordinarily be specified using C snippets.\n##' When doing so, note that:\n##' \\enumerate{\n##'   \\item The parameter transformation mapping a parameter vector from the scale used by the model codes to another scale, and the inverse transformation, are specified via a call to \\preformatted{parameter_trans(toEst,fromEst)}.\n##'   \\item The goal of these snippets is the transformation of the parameters from the natural scale to the estimation scale, and vice-versa.\n##'   If \\code{p} is the name of a variable on the natural scale, its value on the estimation scale is \\code{T_p}.\n##'   Thus the \\code{toEst} snippet computes \\code{T_p} given \\code{p} whilst the \\code{fromEst} snippet computes \\code{p} given \\code{T_p}.\n##'   \\item Time-, state-, and covariate-dependent transformations are not allowed.\n##'   Therefore, neither the time, nor any state variables, nor any of the covariates will be available in the context within which a parameter transformation snippet is executed.\n##' }\n##'\n##' These transformations can also be specified using \\R functions with arguments chosen from among the parameters.\n##' Such an \\R function must also have the argument \\sQuote{\\code{...}}.\n##' In this case, \\code{toEst} should transform parameters from the scale that the basic components use internally to the scale used in estimation.\n##' \\code{fromEst} should be the inverse of \\code{toEst}.\n##'\n##' Note that it is the user's responsibility to make sure that the transformations are mutually inverse.\n##' If \\code{obj} is the constructed \\sQuote{pomp} object, and \\code{coef(obj)} is non-empty, a simple check of this property is \\preformatted{\n##'   x <- coef(obj, transform = TRUE)\n##'   obj1 <- obj\n##'   coef(obj1, transform = TRUE) <- x\n##'   identical(coef(obj), coef(obj1))\n##'   identical(coef(obj1, transform=TRUE), x)}\n##'\n##' One can use the \\code{log} and \\code{logit} arguments of \\code{parameter_trans} to name variables that should be log-transformed or logit-transformed, respectively.\n##' The \\code{barycentric} argument can name sets of parameters that should be log-barycentric transformed.\n##'\n##' Note that using the \\code{log}, \\code{logit}, or \\code{barycentric} arguments causes C snippets to be generated.\n##' Therefore, you must make sure that variables named in any of these arguments are also mentioned in \\code{paramnames} at the same time.\n##'\n##' The logit transform is defined by\n##' \\deqn{\\mathrm{logit}(\\theta)=\\log\\frac{\\theta}{1-\\theta}.}{logit(theta) = log(theta/(1-theta)).}\n##'\n##' The log barycentric transformation of variables \\eqn{\\theta_1,\\dots,\\theta_n}{theta1,\\dots,thetan} is given by\n##' \\deqn{\\mathrm{logbarycentric}(\\theta_1,\\dots,\\theta_n)=\\left(\\log\\frac{\\theta_1}{\\sum_i \\theta_i},\\dots,\\log\\frac{\\theta_n}{\\sum_i \\theta_i}\\right).}{logbarycentric(theta1,\\dots,thetan)=(log(theta1/sum(theta)),\\dots,log(thetan/sum(theta))).}\n##\nNULL\n\nsetClass(\n  \"partransPlugin\",\n  slots=c(\n    has=\"logical\",\n    to=\"ANY\",\n    from=\"ANY\"\n  ),\n  prototype=prototype(\n    has=FALSE,\n    to=NULL,\n    from=NULL\n  )\n)\n\nsetMethod(\n  \"undefined\",\n  signature=signature(object=\"partransPlugin\"),\n  definition=function (object, ...) {\n    undefined(object@to) || undefined(object@from)\n  }\n)\n\n##' @rdname parameter_trans\n##' @export\nsetGeneric(\n  \"parameter_trans\",\n  function (toEst, fromEst, ...)\n    standardGeneric(\"parameter_trans\")\n)\n\n##' @rdname parameter_trans\n##' @export\nsetMethod(\n  \"parameter_trans\",\n  signature=signature(toEst=\"NULL\",fromEst=\"NULL\"),\n  definition=function(toEst, fromEst, ...) {\n    new(\"partransPlugin\",has=FALSE)\n  }\n)\n\n##' @rdname parameter_trans\n##' @export\nsetMethod(\n  \"parameter_trans\",\n  signature=signature(toEst=\"pomp_fun\",fromEst=\"pomp_fun\"),\n  definition=function(toEst, fromEst, ...) {\n    if (undefined(toEst) || undefined(fromEst))\n      new(\"partransPlugin\",has=FALSE)\n    else\n      new(\"partransPlugin\",has=TRUE,to=toEst,from=fromEst)\n  }\n)\n\n##' @rdname parameter_trans\n##' @export\nsetMethod(\n  \"parameter_trans\",\n  signature=signature(toEst=\"Csnippet\",fromEst=\"Csnippet\"),\n  definition=function(toEst, fromEst, ..., log, logit, barycentric) {\n    if (missing(log) && missing(logit) && missing(barycentric))\n      new(\"partransPlugin\",has=TRUE,to=toEst,from=fromEst)\n    else\n      parameter_trans_internal(toEst=as(toEst,\"character\"),\n        fromEst=as(fromEst,\"character\"),log=log,logit=logit,\n        barycentric=barycentric)\n  }\n)\n\nsetMethod(\n  \"parameter_trans\",\n  signature=signature(toEst=\"missing\",fromEst=\"missing\"),\n  definition=function(..., log, logit, barycentric) {\n    if (missing(log) && missing(logit) && missing(barycentric))\n      new(\"partransPlugin\",has=FALSE)\n    else\n      parameter_trans_internal(toEst=NULL,fromEst=NULL,\n        log=log,logit=logit,barycentric=barycentric)\n  }\n)\n\n##' @rdname parameter_trans\n##' @export\nsetMethod(\n  \"parameter_trans\",\n  signature=signature(toEst=\"character\",fromEst=\"character\"),\n  definition=function(toEst, fromEst, ...) {\n    new(\"partransPlugin\",has=TRUE,to=toEst,from=fromEst)\n  }\n)\n\n##' @rdname parameter_trans\n##' @export\nsetMethod(\n  \"parameter_trans\",\n  signature=signature(toEst=\"function\",fromEst=\"function\"),\n  definition=function(toEst, fromEst, ...) {\n    new(\"partransPlugin\",has=TRUE,to=toEst,from=fromEst)\n  }\n)\n\nsetMethod(\n  \"parameter_trans\",\n  signature=signature(toEst=\"ANY\",fromEst=\"missing\"),\n  definition=function(toEst, fromEst, ...) {\n    pStop(who=\"parameter_trans\",\"if one of \",sQuote(\"toEst\"),\", \",\n      sQuote(\"fromEst\"),\" is supplied, then so must the other be.\")\n  }\n)\n\nsetMethod(\n  \"parameter_trans\",\n  signature=signature(toEst=\"missing\",fromEst=\"ANY\"),\n  definition=function(toEst, fromEst, ...) {\n    pStop(who=\"parameter_trans\",\"if one of \",sQuote(\"toEst\"),\", \",\n      sQuote(\"fromEst\"),\" is supplied, then so must the other be.\")\n  }\n)\n\nsetMethod(\n  \"parameter_trans\",\n  signature=signature(toEst=\"ANY\",fromEst=\"ANY\"),\n  definition=function(toEst, fromEst, ...) {\n    pStop_(sQuote(\"parameter_trans\"),\" not defined for arguments of class \",\n      sQuote(class(toEst)),\", \",sQuote(class(fromEst)),\".\")\n  }\n)\n\nparameter_trans_internal <- function (toEst = NULL, fromEst = NULL,\n  ..., log, logit, barycentric) {\n\n  if (missing(log)) log <- NULL\n  if (missing(logit)) logit <- NULL\n  if (missing(barycentric)) barycentric <- list()\n\n  toEst <- as.character(toEst)\n  fromEst <- as.character(fromEst)\n\n  log <- cleanForC(as.character(log))\n  logit <- cleanForC(as.character(logit))\n  if (is.character(barycentric)) barycentric <- list(barycentric)\n  barycentric <- lapply(lapply(barycentric,as.character),cleanForC)\n\n  out1 <- textConnection(object=\"fromEst\",open=\"a\",local=TRUE)\n  out2 <- textConnection(object=\"toEst\",open=\"a\",local=TRUE)\n\n  if (length(log) > 0) {\n    tpl1 <- r\"{\n  {%v%} = exp(T_{%v%});}\"\n    tpl2 <- r\"{\n  T_{%v%} = log({%v%});}\"\n    for (v in log) {\n      cat(file=out1,render(tpl1,v=v))\n      cat(file=out2,render(tpl2,v=v))\n    }\n  }\n\n  if (length(logit) > 0) {\n    tpl1 <- r\"{\n  {%v%} = expit(T_{%v%});}\"\n    tpl2 <- r\"{\n  T_{%v%} = logit({%v%});}\"\n    for (v in logit) {\n      cat(file=out1,render(tpl1,v=v))\n      cat(file=out2,render(tpl2,v=v))\n    }\n  }\n\n  if (length(barycentric) > 0) {\n    tpl1 <- r\"{\n  from_log_barycentric(&{%v%},&T_{%v%},{%n%});}\"\n    tpl2 <- r\"{\n  to_log_barycentric(&T_{%v%},&{%v%},{%n%});}\"\n    for (b in barycentric) {\n      cat(file=out1,render(tpl1,v=b[1],n=length(b)))\n      cat(file=out2,render(tpl2,v=b[1],n=length(b)))\n    }\n  }\n\n  close(out1)\n  close(out2)\n  fromEst <- paste(fromEst,collapse=\"\\n\")\n  toEst <- paste(toEst,collapse=\"\\n\")\n\n  new(\"partransPlugin\",has=TRUE,to=Csnippet(toEst),from=Csnippet(fromEst))\n}\n\nhas_partrans <- function (object) {\n  object@partrans@has\n}\n"
  },
  {
    "path": "R/parmat.R",
    "content": "##' Create a matrix of parameters\n##'\n##' \\code{parmat} is a utility that makes a vector of parameters suitable for\n##' use in \\pkg{pomp} functions.\n##' @aliases parmat parmat,missing-method parmat,ANY-method\n##' @author Aaron A. King\n##'\nsetGeneric(\n  \"parmat\",\n  function (params, ...)\n    standardGeneric(\"parmat\")\n)\n\nsetMethod(\n  \"parmat\",\n  signature=signature(params=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"parmat\",\"params\")\n  }\n)\n\nsetMethod(\n  \"parmat\",\n  signature=signature(params=\"ANY\"),\n  definition=function (params, ...) {\n    undef_method(\"parmat\",params)\n  }\n)\n\n##' @param params named numeric vector or matrix of parameters.\n##' @param nrep number of replicates (columns) desired.\n##' @param names optional character; column names.\n##' @param ... additional arguments, currently ignored.\n##' @return \\code{parmat} returns a matrix consisting of \\code{nrep} copies of\n##' \\code{params}.\n##' @example examples/ricker-bifdiag.R\n##'\n##' @rdname parmat\n##' @export\nsetMethod(\n  \"parmat\",\n  signature=signature(params=\"numeric\"),\n  definition=function (params, nrep = 1, ..., names = NULL) {\n    matrix(data=params,nrow=length(params),ncol=nrep,\n      dimnames=list(name=names(params),.id=names))\n  }\n)\n\n##' @rdname parmat\n##' @export\nsetMethod(\n  \"parmat\",\n  signature=signature(params=\"array\"),\n  definition=function (params, nrep = 1, ..., names = NULL) {\n    d <- dim(params)\n    tryCatch(\n      if (length(d) == 1L) {\n        matrix(\n          data=as.numeric(params),\n          nrow=length(params),\n          ncol=nrep,\n          dimnames=list(\n            name=names(params),\n            .id=names\n          )\n        )\n      } else if (length(d) == 2L) {\n        matrix(\n          data=as.numeric(params),\n          nrow=nrow(params),\n          ncol=ncol(params)*nrep,\n          dimnames=list(\n            name=rownames(params),\n            .id=names\n          )\n        )\n      } else {\n        matrix(\n          data=as.numeric(params),\n          nrow=nrow(params),\n          ncol=prod(d[-1L])*nrep,\n          dimnames=list(\n            name=rownames(params),\n            .id=names\n          )\n        )\n      },\n      error = function (e) pStop(who=\"parmat\",conditionMessage(e)),\n      warning = function (e) pStop(who=\"parmat\",conditionMessage(e))\n    )\n  }\n)\n\n##' @rdname parmat\n##' @export\nsetMethod(\n  \"parmat\",\n  signature=signature(params=\"data.frame\"),\n  definition=function (params, nrep = 1, ...) {\n    d <- dim(params)\n    rn <- rownames(params)\n    nrep <- as.integer(nrep)\n    if (nrep > 1)\n      rn <- as.character(outer(rn,seq_len(nrep),paste,sep=\"_\"))\n    rv <- array(\n      data=NA_real_,\n      dim=c(d[2L],nrep*d[1L]),\n      dimnames=list(name=names(params),.id=rn)\n    )\n    tryCatch(\n      for (n in names(params)) {\n        if (!is.numeric(params[[n]]))\n          pStop_(sQuote(\"params\"),\" must contain numeric variables only.\")\n        rv[n,] <- rep(as.double(params[[n]]),times=nrep)\n      },\n      error = function (e) pStop(who=\"parmat\",conditionMessage(e)),\n      warning = function (e) pStop(who=\"parmat\",conditionMessage(e))\n    )\n    rv\n  }\n)\n"
  },
  {
    "path": "R/parus.R",
    "content": "##' Parus major population dynamics\n##'\n##' Size of a population of great tits (\\emph{Parus major}) from Wytham Wood, near Oxford.\n##'\n##' Provenance: Global Population Dynamics Database dataset #10163.\n##' (NERC Centre for Population Biology, Imperial College (2010)\n##' The Global Population Dynamics Database Version 2.\n##' \\url{https://www.imperial.ac.uk/cpb/gpdd2/}).\n##' Original source: McCleer and Perrins (1991).\n##'\n##' @name parus\n##' @rdname parus\n##' @docType data\n##' @family pomp datasets\n##'\n##' @example examples/parus.R\n##'\n##' @references\n##'\n##' \\McCleery1991\n##'\nNULL\n"
  },
  {
    "path": "R/pfilter.R",
    "content": "##' Particle filter\n##'\n##' A plain vanilla sequential Monte Carlo (particle filter) algorithm.\n##' Resampling is performed at each observation.\n##'\n##' @name pfilter\n##' @rdname pfilter\n##' @aliases pfilter,ANY-method pfilter,missing-method\n##' @author Aaron A. King\n##' @family elementary algorithms\n##' @family particle filter methods\n##' @family full-information methods\n##' @include pomp_class.R pomp.R rprocess_spec.R dmeasure_spec.R\n##' @importFrom stats setNames\n##' @inheritSection pomp Note for Windows users\n##' @inheritParams pomp\n##' @param Np the number of particles to use.\n##' This may be specified as a single positive integer, in which case the same number of particles will be used at each timestep.\n##' Alternatively, if one wishes the number of particles to vary across timesteps, one may specify \\code{Np} either as a vector of positive integers of length \\preformatted{length(time(object,t0=TRUE))} or as a function taking a positive integer argument.\n##' In the latter case, \\code{Np(k)} must be a single positive integer, representing the number of particles to be used at the \\code{k}-th timestep:\n##' \\code{Np(0)} is the number of particles to use going from \\code{timezero(object)} to \\code{time(object)[1]},\n##' \\code{Np(1)}, from \\code{timezero(object)} to \\code{time(object)[1]},\n##' and so on,\n##' while when \\code{T=length(time(object))}, \\code{Np(T)} is the number of particles to sample at the end of the time-series.\n##' @param pred.mean logical; if \\code{TRUE}, the prediction means are calculated for the state variables and parameters.\n##' @param pred.var logical; if \\code{TRUE}, the prediction variances are calculated for the state variables and parameters.\n##' @param filter.mean logical; if \\code{TRUE}, the filtering means are calculated for the state variables and parameters.\n##' @param filter.traj logical; if \\code{TRUE}, a filtered trajectory is returned for the state variables and parameters.\n##' See \\code{\\link{filter_traj}} for more information.\n##' @param save.states character;\n##' If \\code{save.states=\"no\"} (the default), information on the latent states is not saved.\n##' If \\code{save.states=\"filter\"}, the state-vector for each filtered particle \\eqn{X_{n,j}^F} at each time \\eqn{n} is saved.\n##' If \\code{save.states=\"prediction\"}, the state-vector for each prediction particle \\eqn{X_{n,j}^P} at each time \\eqn{n} is saved, along with the corresponding weight \\eqn{w_{n,j} = f_{Y_n|X_n}(y^*|X_{n, j}^P;\\theta)}.\n##' The options \"unweighted\", \"weighted\", TRUE, and FALSE are deprecated and will issue a warning if used, mapping to the new values for backward compatibility.\n##' The options \"unweighted\" and TRUE are synonymous with \"filter\";\n##' the option \"weighted\" is synonymous with \"prediction\";\n##' the option FALSE is synonymous with \"no\".\n##' To retrieve the saved states, apply \\code{\\link{saved_states}} to the result of the \\code{pfilter} computation.\n##' @param ... additional arguments are passed to \\code{\\link{pomp}}.\n##' This allows one to set, unset, or modify \\link[=basic_components]{basic model components} within a call to this function.\n##' @return\n##' An object of class \\sQuote{pfilterd_pomp}, which extends class \\sQuote{pomp}.\n##' Information can be extracted from this object using the methods documented below.\n##' @section Methods:\n##' \\describe{\n##' \\item{\\code{\\link{logLik}}}{ the estimated log likelihood  }\n##' \\item{\\code{\\link{cond_logLik}}}{ the estimated conditional log likelihood }\n##' \\item{\\code{\\link{eff_sample_size}}}{\n##' the (time-dependent) estimated effective sample size }\n##' \\item{\\code{\\link{pred_mean}}, \\code{\\link{pred_var}}}{ the mean and variance of the approximate prediction distribution }\n##' \\item{\\code{\\link{filter_mean}}}{ the mean of the filtering distribution }\n##' \\item{\\code{\\link{filter_traj}}}{\n##'   retrieve one particle trajectory.\n##'   Useful for building up the smoothing distribution.\n##' }\n##' \\item{\\code{\\link{saved_states}}}{retrieve saved states}\n##' \\item{\\code{\\link{as.data.frame}}}{coerce to a data frame}\n##' \\item{\\code{\\link{plot}}}{diagnostic plots}\n##' }\n##' @references\n##'\n##' \\Arulampalam2002\n##'\n##' \\Bhadra2016\n##' @example examples/pfilter.R\nNULL\n\nsetClass(\n  \"pfilterd_pomp\",\n  contains=\"pomp\",\n  slots=c(\n    pred.mean=\"array\",\n    pred.var=\"array\",\n    filter.mean=\"array\",\n    filter.traj=\"array\",\n    paramMatrix=\"array\",\n    indices=\"vector\",\n    eff.sample.size=\"numeric\",\n    cond.logLik=\"numeric\",\n    saved.states=\"list\",\n    Np=\"integer\",\n    loglik=\"numeric\"\n  ),\n  prototype=prototype(\n    pred.mean=array(data=numeric(0),dim=c(0,0)),\n    pred.var=array(data=numeric(0),dim=c(0,0)),\n    filter.mean=array(data=numeric(0),dim=c(0,0)),\n    filter.traj=array(data=numeric(0),dim=c(0,0,0)),\n    paramMatrix=array(data=numeric(0),dim=c(0,0)),\n    indices=integer(0),\n    eff.sample.size=numeric(0),\n    cond.logLik=numeric(0),\n    saved.states=list(),\n    Np=as.integer(NA),\n    loglik=as.double(NA)\n  )\n)\n\nsetGeneric(\n  \"pfilter\",\n  function (data, ...)\n    standardGeneric(\"pfilter\")\n)\n\nsetMethod(\n  \"pfilter\",\n  signature=signature(data=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"pfilter\",\"data\")\n  }\n)\n\nsetMethod(\n  \"pfilter\",\n  signature=signature(data=\"ANY\"),\n  definition=function (data, ...) {\n    undef_method(\"pfilter\",data)\n  }\n)\n\n##' @rdname pfilter\n##' @export\nsetMethod(\n  \"pfilter\",\n  signature=signature(data=\"data.frame\"),\n  definition=function (\n    data,\n    ...,\n    Np,\n    params, rinit, rprocess, dmeasure,\n    pred.mean = FALSE,\n    pred.var = FALSE,\n    filter.mean = FALSE,\n    filter.traj = FALSE,\n    save.states = c(\"no\", \"filter\", \"prediction\",\n      \"weighted\", \"unweighted\", \"FALSE\", \"TRUE\"),\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      pfilter_internal(\n        data,\n        Np=Np,\n        pred.mean=pred.mean,\n        pred.var=pred.var,\n        filter.mean=filter.mean,\n        filter.traj=filter.traj,\n        save.states=save.states,\n        rinit=rinit,\n        rprocess=rprocess,\n        dmeasure=dmeasure,\n        params=params,\n        ...,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"pfilter\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname pfilter\n##' @export\nsetMethod(\n  \"pfilter\",\n  signature=signature(data=\"pomp\"),\n  definition=function (\n    data,\n    ...,\n    Np,\n    pred.mean = FALSE,\n    pred.var = FALSE,\n    filter.mean = FALSE,\n    filter.traj = FALSE,\n    save.states = c(\"no\", \"filter\", \"prediction\",\n      \"weighted\", \"unweighted\", \"FALSE\", \"TRUE\"),\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      pfilter_internal(\n        data,\n        Np=Np,\n        pred.mean=pred.mean,\n        pred.var=pred.var,\n        filter.mean=filter.mean,\n        filter.traj=filter.traj,\n        save.states=save.states,\n        ...,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"pfilter\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname pfilter\n##' @export\nsetMethod(\n  \"pfilter\",\n  signature=signature(data=\"pfilterd_pomp\"),\n  function (\n    data,\n    ...,\n    Np,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    if (missing(Np)) Np <- data@Np\n\n    pfilter(as(data,\"pomp\"),Np=Np,...,verbose=verbose)\n\n  }\n)\n\npfilter_internal <- function (\n  object, ..., Np,\n  pred.mean = FALSE, pred.var = FALSE, filter.mean = FALSE,\n  filter.traj = FALSE, cooling, cooling.m,\n  save.states = c(\"no\", \"filter\", \"prediction\",\n    \"weighted\", \"unweighted\", \"FALSE\", \"TRUE\"),\n  .gnsi = TRUE, verbose = FALSE\n) {\n\n  verbose <- as.logical(verbose)\n\n  object <- pomp(object,...,verbose=verbose)\n\n  if (undefined(object@rprocess) || undefined(object@dmeasure))\n    pStop_(paste(sQuote(c(\"rprocess\",\"dmeasure\")),collapse=\", \"),\" are needed basic components.\")\n\n  gnsi <- as.logical(.gnsi)\n  pred.mean <- as.logical(pred.mean)\n  pred.var <- as.logical(pred.var)\n  filter.mean <- as.logical(filter.mean)\n  filter.traj <- as.logical(filter.traj)\n\n  save.states <- as.character(save.states)\n  save.states <- match.arg(save.states)\n\n  ## Check if input is deprecated argument, and return warning.\n  state_arg_map <- c(\n    `FALSE`=\"no\",`TRUE`=\"filter\",\n    weighted=\"prediction\",unweighted=\"filter\"\n  )\n  if (save.states %in% names(state_arg_map)) {\n    pWarn_(\"The \", sQuote(\"save.states\"), \" option \",\n      sQuote(save.states),\" is deprecated and will be removed in a future version.\\nUse \", sQuote(state_arg_map[save.states]), \" instead.\")\n    save.states <- state_arg_map[save.states]\n  }\n\n  params <- coef(object)\n  times <- time(object,t0=TRUE)\n  ntimes <- length(times)-1\n\n  Np <- np_check(Np,ntimes)\n\n  pompLoad(object,verbose=verbose)\n  on.exit(pompUnload(object,verbose=verbose))\n\n  init.x <- rinit(object,params=params,nsim=Np[1L],.gnsi=gnsi)\n  statenames <- rownames(init.x)\n  nvars <- nrow(init.x)\n  x <- init.x\n\n  ## set up storage for saving samples from filtering distributions\n  stsav <- save.states %in% c(\"filter\")\n  wtsav <- save.states == \"prediction\"\n  if (stsav || wtsav || filter.traj) {\n    xparticles <- vector(mode=\"list\",length=ntimes)\n    if (wtsav) xweights <- xparticles\n  }\n  if (filter.traj) {\n    pedigree <- vector(mode=\"list\",length=ntimes+1)\n  }\n\n  loglik <- rep(NA,ntimes)\n  eff.sample.size <- numeric(ntimes)\n\n  ## set up storage for prediction means, variances, etc.\n  if (pred.mean) {\n    pred.m <- array(data=numeric(1),dim=c(nvars,ntimes),\n      dimnames=list(name=statenames,time=NULL))\n  } else {\n    pred.m <- array(data=numeric(0),dim=c(0,0))\n  }\n\n  if (pred.var) {\n    pred.v <- array(data=numeric(1),dim=c(nvars,ntimes),\n      dimnames=list(name=statenames,time=NULL))\n  } else {\n    pred.v <- array(data=numeric(0),dim=c(0,0))\n  }\n\n  if (filter.mean) {\n    filt.m <- array(data=numeric(1),dim=c(nvars,ntimes),\n      dimnames=list(name=statenames,time=NULL))\n  } else {\n    filt.m <- array(data=numeric(0),dim=c(0,0))\n  }\n\n  if (filter.traj) {\n    filt.t <- array(data=numeric(1),dim=c(nvars,1,ntimes+1),\n      dimnames=list(name=statenames,rep=1,time=NULL))\n  } else {\n    filt.t <- array(data=numeric(0),dim=c(0,0,0))\n  }\n\n  for (nt in seq_len(ntimes)) { ## main loop\n\n    ## advance the state variables according to the process model\n    X <- rprocess(object,x0=x,t0=times[nt],times=times[nt+1],params=params,.gnsi=gnsi)\n\n    if (pred.var) { ## check for nonfinite state variables and parameters\n      problem.indices <- unique(which(!is.finite(X),arr.ind=TRUE)[,1L])\n      nprob <- length(problem.indices)\n      if (nprob > 0)\n        pStop_(\"non-finite state variable\",ngettext(nprob,\"\",\"s\"),\": \",\n          paste(rownames(X)[problem.indices],collapse=', '))\n    }\n\n    ## determine the weights\n    weights <- dmeasure(object,y=object@data[,nt,drop=FALSE],x=X,\n      times=times[nt+1],params=params,log=TRUE,.gnsi=gnsi)\n    gnsi <- FALSE\n\n    ## store unweighted particles and their weights\n    if (wtsav) {\n      xparticles[[nt]] <- array(X,dim=dim(X)[c(1L,2L)],\n        dimnames=list(name=statenames,.id=NULL))\n      xweights[[nt]] <- array(weights,dim=length(weights),\n        dimnames=list(.id=NULL))\n    }\n\n    ## compute prediction mean, prediction variance, filtering mean,\n    ## effective sample size, log-likelihood.\n    ## also do resampling.\n    xx <- .Call(P_pfilter_computations,x=X,params=params,Np=Np[nt+1],\n      predmean=pred.mean,predvar=pred.var,filtmean=filter.mean,\n      trackancestry=filter.traj,doparRS=FALSE,weights=weights,\n      wave=FALSE)\n\n    ## the following is triggered by the first illegal weight value\n    if (is.integer(xx)) {\n      illegal_dmeasure_error(\n        time=times[nt+1],\n        loglik=weights[xx],\n        datvals=object@data[,nt],\n        states=X[,xx,1L],\n        params=params\n      )\n    }\n\n    loglik[nt] <- xx$loglik\n    eff.sample.size[nt] <- xx$ess\n\n    x <- xx$states\n    params <- xx$params[,1L]\n\n    if (pred.mean) pred.m[,nt] <- xx$pm\n    if (pred.var) pred.v[,nt] <- xx$pv\n    if (filter.mean) filt.m[,nt] <- xx$fm\n    if (filter.traj) pedigree[[nt]] <- xx$ancestry\n\n    if (stsav || filter.traj) {\n      xparticles[[nt]] <- x\n      dimnames(xparticles[[nt]]) <- list(name=statenames,.id=NULL)\n    }\n\n    if (verbose && (nt%%5 == 0))\n      cat(\"pfilter timestep\",nt,\"of\",ntimes,\"finished\\n\")\n\n  } ## end of main loop\n\n  if (filter.traj) { ## select a single trajectory\n    b <- sample.int(n=length(weights),size=1L,replace=TRUE)\n    filt.t[,1L,ntimes+1] <- xparticles[[ntimes]][,b]\n    for (nt in seq.int(from=ntimes-1,to=1L,by=-1L)) {\n      b <- pedigree[[nt+1]][b]\n      filt.t[,1L,nt+1] <- xparticles[[nt]][,b]\n    }\n    if (times[2L] > times[1L]) {\n      b <- pedigree[[1L]][b]\n      filt.t[,1L,1L] <- init.x[,b]\n    } else {\n      filt.t <- filt.t[,,-1L,drop=FALSE]\n    }\n  }\n\n  if (stsav) {\n    stsav <- xparticles\n  } else if (wtsav) {\n    stsav <- list(states=xparticles,weights=xweights)\n  } else {\n    stsav <- list()\n  }\n\n  new(\n    \"pfilterd_pomp\",\n    object,\n    pred.mean=pred.m,\n    pred.var=pred.v,\n    filter.mean=filt.m,\n    filter.traj=filt.t,\n    paramMatrix=array(data=numeric(0),dim=c(0,0)),\n    eff.sample.size=eff.sample.size,\n    cond.logLik=loglik,\n    saved.states=stsav,\n    Np=as.integer(Np),\n    loglik=sum(loglik)\n  )\n}\n\nillegal_dmeasure_error <- function (time, loglik, datvals, states, params) {\n  showvals <- c(time=time,loglik=loglik,datvals,states,params)\n  m1 <- formatC(names(showvals),preserve.width=\"common\")\n  m2 <- formatC(showvals,digits=6,width=12,format=\"g\",preserve.width=\"common\")\n  pStop_(\n    sQuote(\"dmeasure\"),\" with log=TRUE returns illegal value.\\n\",\n    \"Log likelihood, data, states, and parameters are:\\n\",\n    paste0(m1,\": \",m2,collapse=\"\\n\")\n  )\n}\n\nnp_check <- function (Np, ntimes) {\n  if (missing(Np) || is.null(Np)) {\n    pStop_(sQuote(\"Np\"),\" must be specified.\")\n  } else if (is.function(Np)) {\n    Np <- tryCatch(\n      vapply(seq.int(from=0,to=ntimes,by=1),Np,numeric(1)),\n      error = function (e) {\n        pStop_(\"if \",sQuote(\"Np\"),\" is a function, it must return \",\n          \"a single positive integer.\")\n      }\n    )\n  } else if (!is.numeric(Np)) {\n    pStop_(sQuote(\"Np\"),\" must be a number, a vector of numbers, or a function.\")\n  }\n\n  if (length(Np) == 1)\n    Np <- rep(Np,times=ntimes+1)\n  else if (length(Np) != (ntimes+1))\n    pStop_(sQuote(\"Np\"),\" must have length 1 or length \",ntimes+1,\".\")\n\n  if (!all(is.finite(Np)) || any(Np <= 0))\n    pStop_(\"number of particles, \",sQuote(\"Np\"),\", must be a positive integer.\")\n\n  as.integer(Np)\n}\n"
  },
  {
    "path": "R/plot.R",
    "content": "##' pomp plotting facilities\n##'\n##' Diagnostic plots.\n##'\n##' @name plot\n##' @rdname plot\n##' @include pomp_class.R\n##' @include abc.R mif2.R pmcmc.R pfilter.R spect.R probe.R wpfilter.R\n##' @include listie.R\n##' @aliases plot,missing-method\n##' @importFrom graphics par abline pairs matplot box axis mtext points polygon lines plot.default legend hist rect text title\n##' @importFrom grDevices rgb dev.interactive\n##' @importFrom stats quantile cor density\n##'\nNULL\n\nsetGeneric(\"plot\")\n\nsetClassUnion(\n  \"pomp_plottable\",\n  c(\n    \"pomp\",\"pfilterd_pomp\",\"wpfilterd_pomp\",\n    \"pompList\",\"pfilterList\"\n  )\n)\n\n##' @rdname plot\n##' @aliases plot,pomp-method\n##' @param x the object to plot\n##' @param variables optional character; names of variables to be displayed\n##' @param panel function of the form \\code{panel(x, col, bg, pch, type, ...)} which gives the action to be carried out in each panel of the display.\n##' @param nc the number of columns to use.\n##' Defaults to 1 for up to 4 series, otherwise to 2.\n##' @param yax.flip logical;\n##' if TRUE, the y-axis (ticks and numbering) should flip from side 2 (left) to 4 (right) from series to series.\n##' @param mar,oma the \\code{\\link{par}} \\code{mar} and \\code{oma} settings.\n##' Modify with care!\n##' @param axes logical; indicates if x- and y- axes should be drawn\n##' @param \\dots ignored or passed to low-level plotting functions\n##' @export\nsetMethod(\n  \"plot\",\n  signature=signature(x=\"pomp_plottable\"),\n  definition=function (x, variables,\n    panel = lines, nc = NULL, yax.flip = FALSE,\n    mar = c(0, 5.1, 0, if (yax.flip) 5.1 else 2.1),\n    oma = c(6, 0, 5, 0), axes = TRUE, ...) {\n\n    plotpomp_internal(x=x,variables=variables,\n      panel=panel,nc=nc,yax.flip=yax.flip,\n      mar=mar,oma=oma,axes=axes,...)\n\n  }\n)\n\n##' @rdname plot\n##' @param pars names of parameters.\n##' @export\nsetMethod(\n  \"plot\",\n  signature=signature(x=\"Pmcmc\"),\n  definition=function (x, ..., pars) {\n    plot(traces(x,pars),...)\n  }\n)\n\n##' @rdname plot\n##' @param scatter logical; if \\code{FALSE}, traces of the parameters named in \\code{pars} will be plotted against ABC iteration number.\n##' If \\code{TRUE}, the traces will be displayed or as a scatterplot.\n##' @export\nsetMethod(\n  \"plot\",\n  signature=signature(x=\"Abc\"),\n  definition=function (x, ..., pars, scatter = FALSE) {\n    abc_diagnostics(x,pars=pars,scatter=scatter,...)\n  }\n)\n\n##' @rdname plot\n##' @param transform logical; should the parameter be transformed onto the estimation scale?\n##' @export\nsetMethod(\n  \"plot\",\n  signature=signature(x=\"Mif2\"),\n  definition=function (x, ..., pars, transform = FALSE) {\n    mif2_diagnostics(x,pars,transform=as.logical(transform))\n  }\n)\n\n##' @rdname plot\n##' @param y ignored\n##' @export\nsetMethod(\n  \"plot\",\n  signature=signature(x=\"probed_pomp\"),\n  definition=function (x, ...) {\n    probeplot_internal(x,...)\n  }\n)\n\n##' @rdname plot\n##' @param max.plots.per.page positive integer; maximum number of plots on a page\n##' @param plot.data logical; should the data spectrum be included?\n##' @param quantiles numeric; quantiles to display\n##' @param quantile.styles list; plot styles to use for quantiles\n##' @param data.styles list; plot styles to use for data\n##' @export\nsetMethod(\n  \"plot\",\n  signature=signature(x=\"spectd_pomp\"),\n  definition=function (x, ..., max.plots.per.page = 4, plot.data = TRUE,\n    quantiles = c(.025, .25, .5, .75, .975),\n    quantile.styles = list(lwd=1, lty=1, col=\"gray70\"),\n    data.styles = list(lwd=2, lty=2, col=\"black\")) {\n\n    tryCatch(\n      plot_spect_internal(x,max.plots.per.page=max.plots.per.page,\n        plot.data=plot.data,quantiles=quantiles,quantile.styles=quantile.styles,\n        data.styles=data.styles),\n      error = function (e) pStop(who=\"plot\",conditionMessage(e))\n    )\n\n  }\n)\n\nplotpomp_internal <- function (x, variables,\n  panel = lines, nc = NULL, yax.flip = FALSE,\n  mar = c(0, 5.1, 0, if (yax.flip) 5.1 else 2.1),\n  oma = c(6, 0, 5, 0), axes = TRUE, ...) {\n\n  if (!is.list(x)) x <- list(x)\n  xx <- lapply(x,as,\"data.frame\")\n  vars <- unique(c(lapply(xx,names),recursive=TRUE))\n  tname <- x[[1]]@timename\n  tpos <- match(tname,vars)\n  if (missing(variables)) {\n    vars <- vars[-tpos]\n    covnames <- unique(\n      c(\n        lapply(x,\\(p)get_covariate_names(p@covar)),\n        recursive=TRUE\n      )\n    )\n    vars <- setdiff(vars,covnames)\n    ylabels <- NULL\n  } else {\n    vars <- variables\n    ylabels <- names(variables)\n  }\n  time <- xx[[1]][[tname]]\n  X <- vector(mode=\"list\",length=length(vars))\n  names(X) <- vars\n  for (v in vars) {\n    X[[v]] <- as.matrix(sapply(xx,\"[\",,v))\n  }\n\n  plotpomp <- function (x, time,\n    xy.labels, xy.lines, panel = lines, nc,\n    type = \"l\", xlim = NULL, ylim = NULL, xlab = \"time\",\n    ylab, log = \"\", col = NULL, bg = NA,\n    pch = par(\"pch\"),\n    cex = par(\"cex\"), lty = par(\"lty\"), lwd = par(\"lwd\"),\n    axes = TRUE, frame.plot = axes, ann = par(\"ann\"),\n    main = NULL,\n    ...) {\n    panel <- match.fun(panel)\n    addmain <- function (main,\n      cex.main = par(\"cex.main\"),\n      font.main = par(\"font.main\"),\n      col.main = par(\"col.main\"),\n      ...) {\n      mtext(main,side=3,line=3,cex=cex.main,font=font.main,col=col.main,...)\n    }\n    nser <- length(x)\n    nm <- ylab\n    if (is.null(nm)) nm <- names(x)\n    if (is.null(nc)) nc <- if(nser>4){2}else{1}\n    nr <- ceiling(nser/nc)\n    oldpar <- par(mar=mar,oma=oma,mfcol=c(nr,nc))\n    on.exit(par(oldpar))\n    for (i in seq_len(nser)) {\n      plot.default(\n        x=range(time),y=range(x[[i]],na.rm=TRUE),\n        axes=FALSE,xlab=\"\",ylab=\"\",log=log,\n        col=col,bg=bg,pch=pch,ann=ann,type=\"n\",...\n      )\n      if (is.null(col)) {\n        ncolor <- NCOL(x[[i]])\n        col <- seq_len(ncolor)\n      } else {\n        ncolor <- length(col)\n      }\n      for (j in seq_len(NCOL(x[[i]]))) {\n        panel(\n          x=time,y=x[[i]][,j],\n          col=col[(j-1L)%%ncolor+1L],\n          bg=bg,pch=pch,type=type,...\n        )\n      }\n      if (frame.plot) box(...)\n      y.side <- if(i%%2||!yax.flip){2}else{4}\n      do.xax <- (i%%nr==0)||(i==nser)\n      if (axes) {\n        axis(y.side, xpd = NA)\n        if (do.xax)\n          axis(1, xpd = NA)\n      }\n      if (ann) {\n        mtext(nm[i], y.side, line = 3, ...)\n        if (do.xax)\n          mtext(xlab, side = 1, line = 3, ...)\n      }\n    }\n    if (ann && !is.null(main)) {\n      par(mfcol=c(1L,1L))\n      addmain(main,...)\n    }\n    invisible(NULL)\n  }\n  n.page <- ceiling(length(vars)/10L)\n  plots.per.page <- ceiling(length(vars)/n.page)\n  if (n.page > 1L) {\n    op <- par(ask=dev.interactive(orNone=TRUE))\n    on.exit(par(op))\n  }\n  v1 <- 1L\n  v2 <- min(v1+plots.per.page-1L,length(vars))\n  for (page in seq_len(n.page)) {\n    vv <- vars[seq.int(from=v1,to=v2)]\n    plotpomp(\n      x=X[vv],\n      time=time,\n      xlab=tname,\n      ylab=ylabels,\n      xy.labels=FALSE,\n      panel=panel,\n      nc=nc,\n      axes=axes,\n      ...\n    )\n    v1 <- v2+1L\n    v2 <- min(v1+plots.per.page-1L,length(vars))\n  }\n  invisible(NULL)\n}\n\nabc_diagnostics <- function (z, pars, scatter = FALSE, ...) {\n  if (!is.list(z)) z <- list(z)\n  if (missing(pars)) {\n    pars <- unique(do.call(c,lapply(z,slot,\"pars\")))\n    if (length(pars)<1)\n      pars <- unique(do.call(c,lapply(z,\\(x)names(x@params))))\n  }\n  if (scatter) {\n    x <- lapply(z,\\(x)as.matrix(traces(x,pars)))\n    x <- lapply(seq_along(x),\\(n)cbind(x[[n]],.num=n))\n    x <- do.call(rbind,x)\n    if (ncol(x)<3) {\n      pStop(who=\"plot\",\"can't make a scatterplot with only one variable.\")\n    } else {\n      pairs(x[,pars],col=x[,\".num\"],...)\n    }\n  } else {\n    mar.multi <- c(0,5.1,0,2.1)\n    oma.multi <- c(6,0,5,0)\n    xx <- z[[1]]\n    estnames <- pars\n    ## plot abc convergence diagnostics\n    other.diagnostics <- c()\n    plotnames <- c(other.diagnostics,estnames)\n    nplots <- length(plotnames)\n    n.per.page <- min(nplots,10)\n    nc <- if (n.per.page<=4) 1 else 2\n    nr <- ceiling(n.per.page/nc)\n    oldpar <- par(mar=mar.multi,oma=oma.multi,mfcol=c(nr,nc))\n    on.exit(par(oldpar))\n    low <- 1\n    hi <- 0\n    iteration <- seq(0,xx@Nabc)\n    while (hi<nplots) {\n      hi <- min(low+n.per.page-1,nplots)\n      for (i in seq(from=low,to=hi,by=1)) {\n        n <- i-low+1\n        dat <- sapply(z,traces,pars=plotnames[i])\n        matplot(y=dat,x=iteration,axes = FALSE,xlab = \"\",ylab = \"\",type = \"l\")\n        box()\n        y.side <- 2\n        axis(y.side,xpd=NA)\n        mtext(plotnames[i],y.side,line=3)\n        do.xax <- (n%%nr==0||n==n.per.page)\n        if (do.xax) axis(1,xpd=NA)\n        if (do.xax) mtext(\"ABC iteration\",side=1,line=3)\n      }\n      low <- hi+1\n      mtext(\"ABC convergence diagnostics\",3,line=2,outer=TRUE)\n    }\n  }\n  invisible(NULL)\n}\n\nmif2_diagnostics <- function (z, pars, transform) {\n  if (!is.list(z)) z <- list(z)\n  ## assumes that z is a list of mif2d_pomps with identical structure\n  mar.multi <- c(0,5.1,0,2.1)\n  oma.multi <- c(6,0,5,0)\n  xx <- z[[1]]\n  estnames <- names(coef(xx,pars=pars,transform=transform))\n\n  ## plot ESS and cond.logLik\n  nplots <- 2\n  n.per.page <- 2\n  nc <- 1\n  nr <- 2\n  oldpar <- par(mar=mar.multi,oma=oma.multi,mfcol=c(2,1),\n    ask=dev.interactive(orNone=TRUE))\n  on.exit(par(oldpar))\n\n  time <- time(xx)\n  dat <- sapply(z,eff_sample_size)\n  matplot(y=dat,x=time,axes=FALSE,xlab=\"\",log=\"y\",\n    ylab=\"eff.sample.size\",type=\"l\")\n  box()\n  axis(2, xpd = NA)\n  mtext(\"Filter diagnostics (last iteration)\",side=3,line=2,outer=TRUE)\n\n  dat <- sapply(z,cond_logLik)\n  matplot(y=dat,x=time,axes=FALSE,xlab=\"\",log='',\n    ylab=\"cond.logLik\",type=\"l\")\n  box()\n  axis(2, xpd = NA)\n\n  axis(1,xpd=NA)\n  mtext(\"time\",side=1,line=3)\n\n  ## plot mif convergence diagnostics\n  other.diagnostics <- c(\"loglik\")\n  plotnames <- c(other.diagnostics,estnames)\n  nplots <- length(plotnames)\n  n.per.page <- min(nplots,10)\n  nc <- if (n.per.page<=4) 1 else 2\n  nr <- ceiling(n.per.page/nc)\n  par(mar=mar.multi,oma=oma.multi,mfcol=c(nr,nc))\n  ## on.exit(par(oldpar))\n  low <- 1\n  hi <- 0\n  iteration <- seq(0,xx@Nmif)\n  while (hi<nplots) {\n    hi <- min(low+n.per.page-1,nplots)\n    for (i in seq(from=low,to=hi,by=1)) {\n      n <- i-low+1\n      matplot(\n        y=sapply(\n          z,\n          \\(po, label) {\n            traces(\n              po,label,\n              transform=(transform && label %in% estnames)\n            )\n          },\n          label=plotnames[i]\n        ),\n        x=iteration,\n        axes = FALSE,\n        xlab = \"\",\n        ylab = \"\",\n        type = \"l\"\n      )\n      box()\n      y.side <- 2\n      axis(y.side,xpd=NA)\n      mtext(plotnames[i],y.side,line=3)\n      do.xax <- (n%%nr==0||n==n.per.page)\n      if (do.xax) axis(1,xpd=NA)\n      if (do.xax) mtext(\"MIF iteration\",side=1,line=3)\n    }\n    low <- hi+1\n    mtext(\"MIF2 convergence diagnostics\",3,line=2,outer=TRUE)\n  }\n  invisible(NULL)\n}\n\nprobeplot_internal <- function (x, ...) {\n  ##function for plotting diagonal panels\n  diag.panel.hist <- function (x, ...) {\n    ##plot a histogram for the simulations\n    usr <- par(\"usr\")\n    on.exit(par(usr=usr))\n    par(usr=c(usr[c(1L,2L)],0,1.5))\n    h <- hist(x[-1L],plot=FALSE)\n    breaks <- h$breaks\n    nB <- length(breaks)\n    y <- h$counts\n    y <- y/max(y)\n    rect(breaks[-nB],0,breaks[-1L],y,...)\n    ##plot the data point\n    lines(c(x[1L],x[1L]),c(0,max(h$counts)),col=\"red\")\n  }\n\n  ##function for plotting above-diagonal panels\n  above.diag.panel <- function (x, y, ...) {\n    ##plot the simulations\n    points(x[-1L],y[-1L],...)\n    ##plot the data\n    mMx <- c(min(x),max(x))\n    mMy <- c(min(y),max(y))\n    lines(c(x[1L],x[1L]),mMy,col=\"red\")\n    lines(mMx,c(y[1L],y[1L]),col=\"red\")\n  }\n\n  ##function for plotting below-diagonal panels\n  below.diag.panel <- function (x, y, ...) {\n    mMx <- c(min(x),max(x))\n    mMy <- c(min(y),max(y))\n    x <- x[-1L]\n    y <- y[-1L]\n    correls <- round(cor(x,y),3)\n    text(mean(mMx),mean(mMy),correls,cex=1)\n  }\n\n  ##prepare the arguments for these functions\n  nprobes <- length(x@datvals)\n  nsim <- nrow(x@simvals)\n  datsimvals <- array(dim=c(nsim+1,nprobes))\n  datsimvals[1L,] <- x@datvals\n  datsimvals[-1L,] <- x@simvals\n\n  labels <- paste(\"probe\",seq_len(nprobes))\n  if (!is.null(names(x@datvals)))\n    labels <- ifelse(names(x@datvals)==\"\",labels,names(x@datvals))\n  lab.plus <- paste(labels,paste0(\"p=\",round(x@pvals,3)),sep=\"\\n\")\n  ##now make the plot\n\n  if (nprobes>1) {\n    pairs(\n      datsimvals,\n      diag.panel=diag.panel.hist,\n      lower.panel=below.diag.panel,\n      upper.panel=above.diag.panel,\n      labels=lab.plus,\n      cex.labels=if (nprobes>5) 5/nprobes else 1\n    )\n  } else {\n    plot(datsimvals,datsimvals,type=\"n\",xlab=\"\",ylab=\"\",yaxt=\"n\",main=lab.plus)\n    diag.panel.hist(datsimvals)\n  }\n}\n\nplot_spect_internal <- function (x, max.plots.per.page, plot.data,\n  quantiles, quantile.styles, data.styles) {\n\n  spomp <- x\n  nquants <- length(quantiles)\n\n  if (!is.list(quantile.styles))\n    pStop_(sQuote(\"quantile.styles\"),\" must be a list.\")\n\n  for (i in c(\"lwd\", \"lty\", \"col\")) {\n    if (is.null(quantile.styles[[i]]))\n      quantile.styles[[i]] <- rep(1,nquants)\n    if (length(quantile.styles[[i]])==1)\n      quantile.styles[[i]] <- rep(quantile.styles[[i]],nquants)\n    if (length(quantile.styles[[i]])<nquants) {\n      pWarn(who=\"plot\",sQuote(\"quantile.styles\"),\n        \" contains an element with more than 1 entry but \",\n        \"fewer entries than quantiles.\")\n      quantile.styles[[i]]<-rep(quantile.styles[[i]],nquants)\n    }\n  }\n\n  if (plot.data) {\n    nreps <- ncol(spomp@datspec)\n\n    if (!is.list(data.styles))\n      pStop_(sQuote(\"data.styles\"),\" must be a list\")\n\n    for (i in c(\"lwd\", \"lty\", \"col\")) {\n      if(is.null(data.styles[[i]]))\n        data.styles[[i]] <- rep(2,nreps)\n      if(length(data.styles[[i]])==1)\n        data.styles[[i]] <- rep(data.styles[[i]],nreps)\n      if(length(data.styles[[i]]) < nreps) {\n        pWarn(who=\"plot\",sQuote(\"data.styles\"),\n          \" contains an element with more than 1 entry but \",\n          \"fewer entries than observed variables.\")\n        data.styles[[i]] <- rep(data.styles[[i]],nreps)\n      }\n    }\n  }\n\n  dimsim <- dim(spomp@simspec)\n  nfreq <- dimsim[2]\n  nobs <- dimsim[3]\n  oldpar <- par(\n    mfrow=c(min(nobs,max.plots.per.page),1),\n    mar=c(3,3,1,0.5),\n    mgp=c(2,1,0),\n    bty=\"l\",\n    ask=if (nobs>max.plots.per.page) TRUE else par(\"ask\")\n  )\n  on.exit(par(oldpar))\n  ylabs <- dimnames(spomp@simspec)[[3]]\n  for (i in seq_len(nobs)) {\n    spectraquants <- array(dim=c(nfreq,length(quantiles)))\n    for (j in seq_len(nfreq))\n      spectraquants[j,] <- quantile(\n        spomp@simspec[,j,i],\n        probs=quantiles\n      )\n    if (plot.data) {\n      ylimits <- c(\n        min(spectraquants,spomp@datspec[,i]),\n        max(spectraquants,spomp@datspec[,i])\n      )\n    } else {\n      ylimits <- c(\n        min(spectraquants),\n        max(spectraquants)\n      )\n    }\n    plot(\n      NULL,\n      xlim=range(spomp@freq),ylim=ylimits,\n      xlab=if (i==nobs) \"frequency\" else \"\",\n      ylab=expression(paste(log[10],\"power\"))\n    )\n    title(\n      main=paste0(ylabs[i],\", p = \",round(spomp@pvals[i],4)),\n      line=0\n    )\n    for (j in seq_along(quantiles)) {\n      lines(\n        x=spomp@freq,\n        y=spectraquants[,j],\n        lwd=quantile.styles$lwd[j],\n        lty=quantile.styles$lty[j],\n        col=quantile.styles$col[j]\n      )\n    }\n    if(plot.data) {\n      lines(\n        x=spomp@freq,\n        y=spomp@datspec[,i],\n        lty=data.styles$lty[i],\n        lwd=data.styles$lwd[i],\n        col=data.styles$col[i]\n      )\n    }\n  }\n}\n"
  },
  {
    "path": "R/pmcmc.R",
    "content": "##' The particle Markov chain Metropolis-Hastings algorithm\n##'\n##' The Particle MCMC algorithm for estimating the parameters of a\n##' partially-observed Markov process.  Running \\code{pmcmc} causes a particle\n##' random-walk Metropolis-Hastings Markov chain algorithm to run for the\n##' specified number of proposals.\n##'\n##' @name pmcmc\n##' @rdname pmcmc\n##' @include pfilter.R proposals.R load.R continue.R\n##' @aliases pmcmc,ANY-method pmcmc,missing-method\n##' @author Edward L. Ionides, Aaron A. King, Sebastian Funk\n##' @family estimation methods\n##' @family particle filter methods\n##' @family full-information methods\n##' @family MCMC methods\n##' @family Bayesian methods\n##'\n##' @importFrom stats runif\n##' @inheritParams pfilter\n##' @inheritParams pomp\n##' @param Nmcmc The number of PMCMC iterations to perform.\n##' @param proposal optional function that draws from the proposal\n##' distribution.  Currently, the proposal distribution must be symmetric for\n##' proper inference: it is the user's responsibility to ensure that it is.\n##' Several functions that construct appropriate proposal function are\n##' provided: see \\link[=proposals]{MCMC proposals} for more information.\n##'\n##' @section Methods:\n##' The following can be applied to the output of a \\code{pmcmc} operation:\n##' \\describe{\n##' \\item{\\code{pmcmc}}{repeats the calculation, beginning with the last state}\n##' \\item{\\code{\\link{continue}}}{continues the \\code{pmcmc} calculation}\n##' \\item{\\code{plot}}{produces a series of diagnostic plots}\n##' \\item{\\code{\\link{filter_traj}}}{extracts a random sample from the smoothing distribution}\n##' \\item{\\code{\\link{traces}}}{produces an \\code{\\link[coda]{mcmc}} object, to which the various \\pkg{coda} convergence diagnostics can be applied}\n##' }\n##'\n##' @return An object of class \\sQuote{pmcmcd_pomp}.\n##'\n##' @inheritSection pomp Note for Windows users\n##'\n##' @section Re-running PMCMC Iterations:\n##' To re-run a sequence of PMCMC\n##' iterations, one can use the \\code{pmcmc} method on a \\sQuote{pmcmc} object.\n##' By default, the same parameters used for the original PMCMC run are re-used\n##' (except for \\code{verbose}, the default of which is shown above).  If one\n##' does specify additional arguments, these will override the defaults.\n##'\n##' @references\n##'\n##' \\Andrieu2010\n##'\nNULL\n\nsetClass(\n  \"pmcmcd_pomp\",\n  contains=\"pfilterd_pomp\",\n  slots=c(\n    pars = \"character\",\n    Nmcmc = \"integer\",\n    accepts = \"integer\",\n    proposal = \"function\",\n    traces = \"array\",\n    log.prior = \"numeric\"\n  ),\n  prototype=prototype(\n    pars = character(0),\n    Nmcmc = 0L,\n    accepts = 0L,\n    proposal = function (...)\n      pStop(who=\"pmcmc\",\"proposal not specified.\"),\n    traces=array(dim=c(0,0)),\n    log.prior=numeric(0)\n  )\n)\n\nsetGeneric(\n  \"pmcmc\",\n  function (data, ...)\n    standardGeneric(\"pmcmc\")\n)\n\nsetMethod(\n  \"pmcmc\",\n  signature=signature(data=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"pmcmc\",\"data\")\n  }\n)\n\nsetMethod(\n  \"pmcmc\",\n  signature=signature(data=\"ANY\"),\n  definition=function (data, ...) {\n    undef_method(\"pmcmc\",data)\n  }\n)\n\n##' @rdname pmcmc\n##' @export\nsetMethod(\n  \"pmcmc\",\n  signature=signature(data=\"data.frame\"),\n  function (\n    data,\n    ...,\n    Nmcmc = 1,\n    proposal,\n    Np,\n    params, rinit, rprocess, dmeasure, dprior,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      pmcmc_internal(\n        data,\n        ...,\n        Nmcmc=Nmcmc,\n        proposal=proposal,\n        Np=Np,\n        params=params,\n        rinit=rinit,\n        rprocess=rprocess,\n        dmeasure=dmeasure,\n        dprior=dprior,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"pmcmc\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname pmcmc\n##' @export\nsetMethod(\n  \"pmcmc\",\n  signature=signature(data=\"pomp\"),\n  function (\n    data,\n    ...,\n    Nmcmc = 1,\n    proposal,\n    Np,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      pmcmc_internal(\n        data,\n        ...,\n        Nmcmc=Nmcmc,\n        proposal=proposal,\n        Np=Np,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"pmcmc\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname pmcmc\n##' @export\nsetMethod(\n  \"pmcmc\",\n  signature=signature(data=\"pfilterd_pomp\"),\n  function (\n    data,\n    ...,\n    Nmcmc = 1,\n    proposal,\n    Np,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    if (missing(Np)) Np <- data@Np\n\n    pmcmc(\n      as(data,\"pomp\"),\n      ...,\n      Nmcmc=Nmcmc,\n      proposal=proposal,\n      Np=Np,\n      verbose=verbose\n    )\n\n  }\n)\n\n##' @rdname pmcmc\n##' @export\nsetMethod(\n  \"pmcmc\",\n  signature=signature(data=\"pmcmcd_pomp\"),\n  function (\n    data,\n    ...,\n    Nmcmc,\n    proposal,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    if (missing(Nmcmc)) Nmcmc <- data@Nmcmc\n    if (missing(proposal)) proposal <- data@proposal\n\n    pmcmc(\n      as(data,\"pfilterd_pomp\"),\n      ...,\n      Nmcmc=Nmcmc,\n      proposal=proposal,\n      verbose=verbose\n    )\n\n  }\n)\n\n##' @rdname continue\n##' @param Nmcmc positive integer; number of additional PMCMC iterations to perform\n##' @export\nsetMethod(\n  \"continue\",\n  signature=signature(object=\"pmcmcd_pomp\"),\n  function (\n    object,\n    ...,\n    Nmcmc = 1\n  ) {\n\n    ndone <- object@Nmcmc\n    accepts <- object@accepts\n\n    obj <- pmcmc(\n      object,\n      ...,\n      Nmcmc=Nmcmc,\n      .ndone=ndone,\n      .accepts=accepts,\n      .prev.pfp=as(object,\"pfilterd_pomp\"),\n      .prev.log.prior=object@log.prior\n    )\n\n    obj@traces <- rbind(\n      object@traces[,colnames(obj@traces)],\n      obj@traces[-1,]\n    )\n    names(dimnames(obj@traces)) <- c(\"iteration\",\"name\")\n    ft <- array(\n      dim=replace(dim(obj@filter.traj),2L,ndone+Nmcmc),\n      dimnames=list(\n        name=rownames(obj@filter.traj),\n        rep=NULL,\n        time=NULL\n      )\n    )\n    ft[,seq_len(ndone),] <- object@filter.traj\n    ft[,ndone+seq_len(Nmcmc),] <- obj@filter.traj\n    obj@filter.traj <- ft\n    obj@Nmcmc <- as.integer(ndone+Nmcmc)\n    obj@accepts <- as.integer(accepts+obj@accepts)\n\n    obj\n  }\n)\n\npmcmc_internal <- function (\n  object,\n  ...,\n  Nmcmc, proposal, Np,\n  verbose,\n  .ndone = 0L,\n  .accepts = 0L,\n  .prev.pfp = NULL,\n  .prev.log.prior = NULL,\n  .gnsi = TRUE\n) {\n\n  verbose <- as.logical(verbose)\n\n  object <- pomp(object,...,verbose=verbose)\n\n  gnsi <- as.logical(.gnsi)\n  .ndone <- as.integer(.ndone)\n  .accepts <- as.integer(.accepts)\n\n  if (missing(proposal) || is.null(proposal))\n    pStop_(sQuote(\"proposal\"),\" must be specified\")\n  proposal <- tryCatch(\n    match.fun(proposal),\n    error = function (e) {\n      pStop_(sQuote(\"proposal\"),\" must be a function: \",conditionMessage(e))\n    }\n  )\n\n  pompLoad(object,verbose=verbose)\n  on.exit(pompUnload(object,verbose=verbose))\n\n  start <- coef(object)\n\n  ## test proposal distribution\n  theta <- tryCatch(\n    proposal(start,.n=0L),\n    error = function (e) {\n      pStop_(\"error in proposal function: \",conditionMessage(e))\n    }\n  )\n  if (is.null(names(theta)) || !is.numeric(theta) || any(names(theta)==\"\"))\n    pStop_(sQuote(\"proposal\"),\" must return a named numeric vector.\")\n\n  theta <- start\n\n  Nmcmc <- as.integer(Nmcmc)\n  if (length(Nmcmc)!=1L || !is.finite(Nmcmc) || Nmcmc < 0L)\n    pStop_(sQuote(\"Nmcmc\"),\" must be a positive integer\")\n\n  if (verbose)\n    cat(\"performing\",Nmcmc,\"PMCMC iteration(s) using\",Np[1L],\"particles\\n\")\n\n  traces <- array(\n    data=NA_real_,\n    dim=c(Nmcmc+1L,length(theta)+2L),\n    dimnames=list(\n      iteration=NULL,\n      name=c(\"loglik\",\"log.prior\",names(theta))\n    )\n  )\n\n  if (.ndone==0L) { ## compute prior and likelihood on initial parameter vector\n\n    log.prior <- dprior(object,params=theta,log=TRUE,.gnsi=gnsi)\n\n    if (!is.finite(log.prior))\n      pStop_(\"non-finite log prior at starting parameters.\")\n\n    pfp <- pfilter(\n      object,\n      params=theta,\n      Np=Np,\n      filter.traj=TRUE,\n      .gnsi=gnsi,\n      verbose=verbose\n    )\n\n    if (!is.finite(pfp@loglik))\n      pStop_(\"non-finite log likelihood at starting parameters.\")\n\n  } else { ## has been computed previously\n\n    pfp <- .prev.pfp\n    log.prior <- .prev.log.prior\n    pfp@filter.traj <- pfp@filter.traj[,.ndone,,drop=FALSE]\n\n  }\n\n  traces[1L,names(theta)] <- theta\n  traces[1L,c(1L,2L)] <- c(pfp@loglik,log.prior)\n\n  filt.t <- array(\n    data=NA_real_,\n    dim=replace(dim(pfp@filter.traj),2L,Nmcmc),\n    dimnames=list(\n      name=rownames(pfp@filter.traj),\n      rep=NULL,\n      time=NULL\n    )\n  )\n\n  for (n in seq_len(Nmcmc)) { # main loop\n\n    theta.prop <- tryCatch(\n      proposal(theta,.n=n+.ndone,.accepts=.accepts,verbose=verbose),\n      error = function (e) {\n        pStop_(\"error in proposal function: \",conditionMessage(e))\n      }\n    )\n\n    ## compute log prior\n    log.prior.prop <- dprior(object,params=theta.prop,log=TRUE,.gnsi=gnsi)\n\n    if (is.finite(log.prior.prop)) {\n\n      ## run the particle filter on the proposed new parameter values\n      pfp.prop <- pfilter(\n        pfp,\n        params=theta.prop,\n        Np=Np,\n        filter.traj=TRUE,\n        verbose=verbose,\n        .gnsi=gnsi\n      )\n\n      ## PMCMC update rule (OK because proposal is symmetric)\n      alpha <- exp(pfp.prop@loglik+log.prior.prop-pfp@loglik-log.prior)\n\n      if (!is.finite(alpha))\n        pWarn_(\"non-finite log likelihood or log prior encountered.\") #nocov\n\n      if (is.finite(alpha) && runif(1) < alpha) {\n        pfp <- pfp.prop\n        theta <- theta.prop\n        log.prior <- log.prior.prop\n        .accepts <- .accepts+1L\n      }\n    }\n\n    ## add filtered trajectory to the store\n    filt.t[,n,] <- pfp@filter.traj[,1L,]\n\n    ## store a record of this iteration\n    traces[n+1,names(theta)] <- theta\n    traces[n+1,c(1L,2L)] <- c(pfp@loglik,log.prior)\n\n    if (verbose) cat(\"PMCMC iteration\",n+.ndone,\"of\",Nmcmc+.ndone,\n      \"completed\\nacceptance ratio:\",\n      round(.accepts/(n+.ndone),3),\"\\n\")\n\n    gnsi <- FALSE\n\n  }\n\n  pars <- apply(traces,2L,\\(x)diff(range(x))>0)\n  pars <- setdiff(names(pars[pars]),c(\"loglik\",\"log.prior\"))\n\n  new(\n    \"pmcmcd_pomp\",\n    pfp,\n    params=theta,\n    pars=pars,\n    Nmcmc=Nmcmc,\n    accepts=.accepts,\n    proposal=proposal,\n    traces=traces,\n    log.prior=log.prior,\n    filter.traj=filt.t\n  )\n\n}\n"
  },
  {
    "path": "R/pomp.R",
    "content": "##' Constructor of the basic pomp object\n##'\n##' This function constructs a \\sQuote{pomp} object, encoding a partially-observed Markov process (\\acronym{POMP}) model together with a uni- or multi-variate time series.\n##' As such, it is central to all the package's functionality.\n##' One implements the \\acronym{POMP} model by specifying some or all of its \\emph{basic components}.\n##' These comprise:\n##' \\describe{\n##' \\item{rinit}{which samples from the distribution of the state process at the zero-time;}\n##' \\item{dinit}{which evaluates the density of the state process at the zero-time;}\n##' \\item{rprocess}{the simulator of the unobserved Markov state process;}\n##' \\item{dprocess}{the evaluator of the probability density function for transitions of the unobserved Markov state process;}\n##' \\item{rmeasure}{the simulator of the observed process, conditional on the unobserved state;}\n##' \\item{dmeasure}{the evaluator of the measurement model probability density function;}\n##' \\item{emeasure}{the expectation of the measurements, conditional on the latent state;}\n##' \\item{vmeasure}{the covariance matrix of the measurements, conditional on the latent state;}\n##' \\item{rprior}{which samples from a prior probability distribution on the parameters;}\n##' \\item{dprior}{which evaluates the prior probability density function;}\n##' \\item{skeleton}{which computes the deterministic skeleton of the unobserved state process;}\n##' \\item{partrans}{which performs parameter transformations.}\n##' }\n##' The basic structure and its rationale are described in the \\emph{Journal of Statistical Software} paper, an updated version of which is to be found on the \\href{https://kingaa.github.io/pomp/}{package website}.\n##'\n##' Each basic component is supplied via an argument of the same name.\n##' These can be given in the call to \\code{pomp}, or to many of the package's other functions.\n##' In any case, the effect is the same: to add, remove, or modify the basic component.\n##'\n##' Each basic component can be furnished using C snippets, \\R functions, or pre-compiled native routine available in user-provided dynamically loaded libraries.\n##' @name pomp_constructor\n##' @aliases pomp\n##' @rdname pomp\n##' @family implementation information\n##' @include pomp_class.R pomp_fun.R csnippet.R safecall.R builder.R\n##' @include dinit_spec.R rinit_spec.R rprocess_spec.R rmeasure_spec.R\n##' @include dprocess_spec.R dmeasure_spec.R prior_spec.R\n##' @include skeleton_spec.R parameter_trans.R covariate_table.R\n##' @importFrom stats setNames\n##' @inheritParams hitch\n##' @param data either a data frame holding the time series data,\n##' or an object of class \\sQuote{pomp},\n##' i.e., the output of another \\pkg{pomp} calculation.\n##' Internally, \\code{data} will be coerced to an array with storage-mode \\code{double}.\n##' @param times the sequence of observation times.\n##' \\code{times} must indicate the column of observation times by name or index.\n##' The time vector must be numeric and non-decreasing.\n##' @param t0 The zero-time, i.e., the time of the initial state.\n##' This must be no later than the time of the first observation, i.e., \\code{t0 <= times[1]}.\n##' @param rinit simulator of the initial-state distribution.\n##' This can be furnished either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\n##' Setting \\code{rinit=NULL} sets the initial-state simulator to its default.\n##' For more information, see \\link[=rinit_spec]{rinit specification}.\n##' @param dinit evaluator of the initial-state density.\n##' This can be furnished either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\n##' Setting \\code{dinit=NULL} removes this basic component.\n##' For more information, see \\link[=dinit_spec]{dinit specification}.\n##' @param rprocess simulator of the latent state process, specified using one of the \\link[=rprocess_spec]{rprocess plugins}.\n##' Setting \\code{rprocess=NULL} removes the latent-state simulator.\n##' For more information, see \\link[=rprocess_spec]{rprocess specification for the documentation on these plugins}.\n##' @param dprocess evaluator of the probability density of transitions of the unobserved state process.\n##' Setting \\code{dprocess=NULL} removes the latent-state density evaluator.\n##' For more information, see \\link[=dprocess_spec]{dprocess specification}.\n##' @param rmeasure simulator of the measurement model, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\n##' Setting \\code{rmeasure=NULL} removes the measurement model simulator.\n##' For more information, see \\link[=rmeasure_spec]{rmeasure specification}.\n##' @param dmeasure evaluator of the measurement model density, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\n##' Setting \\code{dmeasure=NULL} removes the measurement density evaluator.\n##' For more information, see \\link[=dmeasure_spec]{dmeasure specification}.\n##' @param emeasure the expectation of the measured variables, conditional on the latent state.\n##' This can be specified as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\n##' Setting \\code{emeasure=NULL} removes the emeasure component.\n##' For more information, see \\link[=emeasure_spec]{emeasure specification}.\n##' @param vmeasure the covariance of the measured variables, conditional on the latent state.\n##' This can be specified as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\n##' Setting \\code{vmeasure=NULL} removes the vmeasure component.\n##' For more information, see \\link[=vmeasure_spec]{vmeasure specification}.\n##' @param skeleton optional; the deterministic skeleton of the unobserved state process.\n##' Depending on whether the model operates in continuous or discrete time, this is either a vectorfield or a map.\n##' Accordingly, this is supplied using either the \\code{\\link[=skeleton_spec]{vectorfield}} or \\code{\\link[=skeleton_spec]{map}} fnctions.\n##' For more information, see \\link[=skeleton_spec]{skeleton specification}.\n##' Setting \\code{skeleton=NULL} removes the deterministic skeleton.\n##' @param rprior optional; prior distribution sampler, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\n##' For more information, see \\link[=prior_spec]{prior specification}.\n##' Setting \\code{rprior=NULL} removes the prior distribution sampler.\n##' @param dprior optional; prior distribution density evaluator, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\n##' For more information, see \\link[=prior_spec]{prior specification}.\n##' Setting \\code{dprior=NULL} resets the prior distribution to its default, which is a flat improper prior.\n##' @param partrans optional parameter transformations, constructed using \\code{\\link{parameter_trans}}.\n##'\n##' Many algorithms for parameter estimation search an unconstrained space of parameters.\n##' When working with such an algorithm and a model for which the parameters are constrained, it can be useful to transform parameters.\n##' One should supply the \\code{partrans} argument via a call to \\code{\\link{parameter_trans}}.\n##' For more information, see \\link[=parameter_trans]{parameter_trans}.\n##' Setting \\code{partrans=NULL} removes the parameter transformations, i.e., sets them to the identity transformation.\n##' @param covar optional covariate table, constructed using \\code{\\link{covariate_table}}.\n##'\n##' If a covariate table is supplied, then the value of each of the covariates is interpolated as needed.\n##' The resulting interpolated values are made available to the appropriate basic components.\n##' See the documentation for \\code{\\link{covariate_table}} for details.\n##' @param params optional; named numeric vector of parameters.\n##' This will be coerced internally to storage mode \\code{double}.\n##' @param obsnames optional character vector;\n##' names of the observables.\n##' It is not usually necessary to specify \\code{obsnames} since, by default,\n##' these are read from the names of the data variables.\n##' @param statenames optional character vector;\n##' names of the latent state variables.\n##' It is typically only necessary to supply \\code{statenames} when C snippets are in use.\n##' See also \\code{nstatevars}.\n##' @param nstatevars optional integer scalar;\n##' If C snippets or native routines are used, one can specify the number of state variables with this argument.\n##' By default, \\code{nstatevars = length(statenames)}.\n##' @param paramnames optional character vector;\n##' names of model parameters.\n##' It is typically only necessary to supply \\code{paramnames} when C snippets are in use.\n##' @param covarnames optional character vector;\n##' names of the covariates.\n##' It is not usually necessary to specify \\code{covarnames} since, by default,\n##' these are read from the names of the covariates.\n##' @param accumvars optional character vector;\n##' contains the names of accumulator variables.\n##' See \\link{accumvars} for a definition and discussion of accumulator variables.\n##' @param userdata optional list; the elements of this list will be available to basic model components.\n##' This allows the user to pass information to the basic components outside of the usual routes of covariates (\\code{covar}) and model parameters (\\code{params}).\n##' See \\link[=userdata]{userdata} for information on how to use this facility.\n##' @param ... additional arguments will generate an error.\n##' @param verbose logical; if \\code{TRUE}, diagnostic messages will be printed to the console.\n##' @return\n##' The \\code{pomp} constructor function returns an object, call it \\code{P}, of class \\sQuote{pomp}.\n##' \\code{P} contains, in addition to the data, any elements of the model that have been specified as arguments to the \\code{pomp} constructor function.\n##' One can add or modify elements of \\code{P} by means of further calls to \\code{pomp}, using \\code{P} as the first argument in such calls.\n##' One can pass \\code{P} to most of the \\pkg{pomp} package methods via their \\code{data} argument.\n##' @section Note:\n##'\n##' It is not typically necessary (or indeed feasible) to define all of the basic components for any given purpose.\n##' However, each \\pkg{pomp} algorithm makes use of only a subset of these components.\n##' When an algorithm requires a basic component that has not been furnished, an error is generated to let you know that you must provide the needed component to use the algorithm.\n##' @section Note for Windows users:\n##'\n##' Some Windows users report problems when using C snippets in parallel computations.\n##' These appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\n##' To circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n##' @author Aaron A. King\n##' @references\n##'\n##' \\King2016\n##'\nNULL\n\n##' @rdname pomp\n##' @export\npomp <- function (\n  data,\n  ...,\n  times, t0,\n  rinit, dinit,\n  rprocess, dprocess,\n  rmeasure, dmeasure, emeasure, vmeasure,\n  skeleton,\n  rprior, dprior,\n  partrans,\n  covar, params, accumvars,\n  obsnames, statenames, paramnames, covarnames,\n  nstatevars, PACKAGE, globals, on_load,\n  userdata,\n  cdir = getOption(\"pomp_cdir\", NULL), cfile,\n  shlib.args, compile = TRUE,\n  verbose = getOption(\"verbose\", FALSE)\n) {\n\n  if (missing(data))\n    reqd_arg(\"pomp\",\"data\")\n\n  if (!inherits(data,what=c(\"data.frame\",\"pomp\",\"NULL\")))\n    pStop(who=\"pomp\",sQuote(\"data\"),\" must be a data frame or an object of \",\n      \"class \",sQuote(\"pomp\"),\".\")\n\n  ## return as quickly as possible if no work is to be done\n  if (\n    is(data,\"pomp\") && missing(times) && missing(t0) &&\n      missing(rinit) && missing(dinit) &&\n      missing(rprocess) && missing(dprocess) &&\n      missing(rmeasure) && missing(dmeasure) && missing(emeasure) &&\n      missing(vmeasure) && missing(skeleton) &&\n      missing(rprior) && missing(dprior) && missing(partrans) &&\n      missing(covar) && missing(params) && missing(accumvars) &&\n      missing(nstatevars) &&\n      missing(userdata) && ...length() == 0\n  )\n    return(as(data,\"pomp\"))\n\n  extra_args <- list(...)\n  if (length(extra_args)>0L) {\n    nm <- names(extra_args)\n    if (length(nm)==0 || any(nchar(nm)==0))\n      pStop_(\"Unnamed arguments are not permitted.\")\n    else\n      pStop_(\"The \",\n        ngettext(length(extra_args),\"argument \",\"arguments \"),\n        paste(sQuote(nm),collapse=\",\"),\n        ngettext(length(extra_args),\" is\",\" are\"),\n        \" not recognized.\\nUse the \",sQuote(\"userdata\"),\n        \" argument to supply extra objects to basic model components.\\n\",\n        \"See \",sQuote(\"?userdata\"),\".\"\n      )\n  }\n\n  if (missing(times)) times <- NULL\n\n  tryCatch(\n    construct_pomp(\n      data=data,times=times,t0=t0,\n      rinit=rinit,dinit=dinit,\n      rprocess=rprocess,dprocess=dprocess,\n      rmeasure=rmeasure,dmeasure=dmeasure,\n      emeasure=emeasure,vmeasure=vmeasure,\n      skeleton=skeleton,rprior=rprior,dprior=dprior,partrans=partrans,\n      params=params,covar=covar,accumvars=accumvars,\n      obsnames=obsnames,statenames=statenames,paramnames=paramnames,\n      covarnames=covarnames,nstatevars=nstatevars,PACKAGE=PACKAGE,\n      globals=globals,on_load=on_load,userdata=userdata,\n      cdir=cdir,cfile=cfile,shlib.args=shlib.args,\n      compile=compile,verbose=verbose\n    ),\n    error = function (e) pStop_(conditionMessage(e))\n  )\n}\n\nsetGeneric(\n  \"construct_pomp\",\n  function (data, times, ...)\n    standardGeneric(\"construct_pomp\")\n)\n\nsetMethod(\n  \"construct_pomp\",\n  signature=signature(data=\"ANY\", times=\"ANY\"),\n  definition = function (data, times, t0, ...) {\n    pStop_(sQuote(\"times\"),\" should either be a numeric vector of observation\",\n      \" times or a single name identifying the column of data that represents\",\n      \" the observation times.\")\n  }\n)\n\nsetMethod(\n  \"construct_pomp\",\n  signature=signature(data=\"data.frame\", times=\"character\"),\n  definition = function (data, times, t0, ...) {\n\n    if (anyDuplicated(names(data)))\n      pStop_(\"names of data variables must be unique.\")\n\n    if (missing(t0)) reqd_arg(NULL,\"t0\")\n\n    tpos <- match(times,names(data),nomatch=0L)\n\n    if (length(times) != 1 || tpos == 0L)\n      pStop_(sQuote(\"times\"),\" does not identify a single column of \",\n        sQuote(\"data\"),\" by name.\")\n\n    timename <- times\n\n    times <- data[[tpos]]\n    data <- do.call(rbind,lapply(data[-tpos],as.double))\n\n    construct_pomp(data=data,times=times,t0=t0,...,timename=timename)\n\n  }\n)\n\nsetMethod(\n  \"construct_pomp\",\n  signature=signature(data=\"data.frame\", times=\"numeric\"),\n  definition = function (data, times, t0, ...) {\n\n    if (anyDuplicated(names(data)))\n      pStop_(\"names of data variables must be unique.\")\n\n    if (missing(t0)) reqd_arg(NULL,\"t0\")\n\n    if (length(times) != nrow(data))\n      pStop_(\"the length of \",sQuote(\"times\"),\n        \" does not match that of the data.\")\n\n    timename <- \"time\"\n    data <- do.call(rbind,lapply(data,as.double))\n\n    construct_pomp(data=data,times=times,t0=t0,...,timename=timename)\n\n  }\n)\n\nsetMethod(\n  \"construct_pomp\",\n  signature=signature(data=\"NULL\", times=\"numeric\"),\n  definition = function (data, times, t0, ...) {\n\n    if (missing(t0)) reqd_arg(NULL,\"t0\")\n\n    construct_pomp(data=array(dim=c(0,length(times))),times=times,t0=t0,...)\n\n  }\n)\n\nsetMethod(\n  \"construct_pomp\",\n  signature=signature(data=\"array\", times=\"numeric\"),\n  definition = function (\n    data, times,\n    ...,\n    userdata,\n    rinit, dinit, rprocess, dprocess,\n    rmeasure, dmeasure, emeasure, vmeasure,\n    skeleton, rprior, dprior,\n    partrans, params, covar\n  ) {\n\n    if (missing(rinit)) rinit <- NULL\n    if (missing(dinit)) dinit <- NULL\n\n    if (missing(rprocess) || is.null(rprocess)) {\n      rprocess <- rproc_plugin()\n    }\n\n    if (missing(dprocess)) dprocess <- NULL\n    if (missing(rmeasure)) rmeasure <- NULL\n    if (missing(dmeasure)) dmeasure <- NULL\n    if (missing(emeasure)) emeasure <- NULL\n    if (missing(vmeasure)) vmeasure <- NULL\n\n    if (missing(skeleton) || is.null(skeleton)) {\n      skeleton <- skel_plugin()\n    }\n\n    if (missing(rprior)) rprior <- NULL\n    if (missing(dprior)) dprior <- NULL\n\n    if (missing(partrans) || is.null(partrans)) {\n      partrans <- parameter_trans()\n    }\n\n    if (missing(params)) params <- numeric(0)\n    if (is.list(params)) params <- unlist(params)\n\n    if (missing(covar)) covar <- covariate_table()\n    if (missing(userdata)) userdata <- list()\n\n    pomp_internal(\n      data=data,\n      ...,\n      times=times,\n      rinit=rinit,\n      dinit=dinit,\n      rprocess=rprocess,\n      dprocess=dprocess,\n      rmeasure=rmeasure,\n      dmeasure=dmeasure,\n      emeasure=emeasure,\n      vmeasure=vmeasure,\n      skeleton=skeleton,\n      dprior=dprior,\n      rprior=rprior,\n      partrans=partrans,\n      params=params,\n      covar=covar,\n      userdata=userdata\n    )\n\n  }\n)\n\nsetMethod(\n  \"construct_pomp\",\n  signature=signature(data=\"pomp\", times=\"numeric\"),\n  definition = function (data, times, ...) {\n    time(data) <- times\n    construct_pomp(data,times=NULL,...)\n  }\n)\n\nsetMethod(\n  \"construct_pomp\",\n  signature=signature(data=\"pomp\", times=\"NULL\"),\n  definition = function (\n    data, times, t0,\n    ...,\n    timename,\n    userdata,\n    rinit, dinit, rprocess, dprocess,\n    rmeasure, dmeasure, emeasure, vmeasure,\n    skeleton, rprior, dprior, partrans, params, covar,\n    accumvars, nstatevars, cfile\n  ) {\n\n    times <- data@times\n    if (missing(t0)) t0 <- data@t0\n    if (missing(timename)) timename <- data@timename\n\n    if (missing(rinit)) rinit <- data@rinit\n    if (missing(dinit)) dinit <- data@dinit\n\n    if (missing(rprocess)) rprocess <- data@rprocess\n    else if (is.null(rprocess)) rprocess <- rproc_plugin()\n\n    if (missing(dprocess)) dprocess <- data@dprocess\n    if (missing(rmeasure)) rmeasure <- data@rmeasure\n    if (missing(dmeasure)) dmeasure <- data@dmeasure\n    if (missing(emeasure)) emeasure <- data@emeasure\n    if (missing(vmeasure)) vmeasure <- data@vmeasure\n\n    if (missing(skeleton)) skeleton <- data@skeleton\n    else if (is.null(skeleton)) skeleton <- skel_plugin()\n\n    if (missing(rprior)) rprior <- data@rprior\n    if (missing(dprior)) dprior <- data@dprior\n\n    if (missing(partrans)) partrans <- data@partrans\n    else if (is.null(partrans)) partrans <- parameter_trans()\n\n    if (missing(params)) params <- data@params\n    if (missing(covar)) covar <- data@covar\n    if (missing(accumvars)) accumvars <- data@accumvars\n\n    if (missing(nstatevars)) nstatevars <- data@nstatevars\n    else nstatevars <- max(nstatevars[1L],data@nstatevars,na.rm=TRUE)\n\n    if (missing(userdata)) userdata <- list()\n\n    if (missing(cfile)) cfile <- NULL\n    if (!is.null(cfile)) {\n      cfile <- as.character(cfile)\n      fnames <- unlist(lapply(data@solibs,getElement,\"name\"))\n      if (any(cfile==fnames)) {\n        pStop_(\"C file name \",dQuote(cfile),\" cannot be re-used.\")\n      }\n    }\n\n    pomp_internal(\n      data=data@data,\n      ...,\n      times=times,\n      t0=t0,\n      timename=timename,\n      rinit=rinit,\n      dinit=dinit,\n      rprocess=rprocess,\n      dprocess=dprocess,\n      rmeasure=rmeasure,\n      dmeasure=dmeasure,\n      emeasure=emeasure,\n      vmeasure=vmeasure,\n      skeleton=skeleton,\n      rprior=rprior,\n      dprior=dprior,\n      partrans=partrans,\n      covar=covar,\n      accumvars=accumvars,\n      nstatevars=nstatevars,\n      userdata=userdata,\n      params=params,\n      .solibs=data@solibs,\n      .userdata=data@userdata,\n      cfile=cfile\n    )\n\n  }\n)\n\npomp_internal <- function (\n  data,\n  times, t0, timename,\n  rinit, dinit, rprocess, dprocess,\n  rmeasure, dmeasure, emeasure, vmeasure,\n  skeleton, rprior, dprior,\n  partrans, params, covar, accumvars, obsnames, statenames,\n  paramnames, covarnames, nstatevars,\n  PACKAGE, globals, on_load, cdir, cfile, shlib.args,\n  compile,\n  userdata = list(), .userdata = list(),\n  .solibs = list(),\n  verbose = getOption(\"verbose\", FALSE)\n) {\n\n  ## check times\n  if (missing(times) || !is.numeric(times) || !all(is.finite(times)) ||\n        (length(times)>1 && !all(diff(times)>=0)))\n    pStop_(sQuote(\"times\"),\" must be a non-decreasing sequence of numbers.\")\n  storage.mode(times) <- \"double\"\n\n  ## check t0\n  if (missing(t0) || !is.numeric(t0) || !is.finite(t0) ||\n        length(t0) > 1 ||  t0 > times[1])\n    pStop_(sQuote(\"t0\"),\" must be a single number not greater than \",\n      sQuote(\"times[1]\"),\".\")\n  storage.mode(t0) <- \"double\"\n\n  if (missing(timename) || is.null(timename))\n    timename <- \"time\"\n  else\n    timename <- as.character(timename)\n\n  .userdata[names(userdata)] <- userdata\n\n  if (!is(rprocess,\"rprocPlugin\")) {\n    pStop_(sQuote(\"rprocess\"),\n      \" must be specified using one of the plugins:\\n\",\n      sQuote(\"onestep\"),\", \",sQuote(\"discrete_time\"),\n      \", \",sQuote(\"euler\"),\", \",sQuote(\"gillespie\"),\n      \", or \",sQuote(\"gillespie_hl\"),\".\")\n  }\n\n  if (!is(skeleton,\"skelPlugin\")) {\n    pStop_(sQuote(\"skeleton\"),\" must be specified using either \",\n      sQuote(\"map\"),\" or \",sQuote(\"vectorfield\"),\".\")\n  }\n\n  if (!is(partrans,\"partransPlugin\")) {\n    pStop_(sQuote(\"partrans\"),\" must be specified using \",\n      sQuote(\"parameter_trans\"),\".\")\n  }\n\n  if (missing(statenames)) statenames <- NULL\n  if (missing(paramnames)) paramnames <- NULL\n  if (missing(obsnames)) obsnames <- NULL\n  if (missing(covarnames)) covarnames <- NULL\n\n  if (missing(nstatevars)) nstatevars <- 0L\n  nstatevars <- as.integer(nstatevars[1L])\n  nstatevars <- max(nstatevars,length(statenames),na.rm=TRUE)\n\n  if (missing(accumvars)) accumvars <- NULL\n  accumvars <- unique(as.character(accumvars))\n\n  ## store the data as double-precision matrix\n  storage.mode(data) <- \"double\"\n  if (is.null(obsnames)) obsnames <- row.names(data)\n\n  ## check the parameters and force them to be double-precision\n  params <- tryCatch(\n    setNames(as.double(params),names(params)),\n    warning = function (e) pWarn_(conditionMessage(e)),\n    error = function (e) pStop_(conditionMessage(e))\n  )\n  if (length(params) > 0) {\n    if (is.null(names(params)) || !is.numeric(params) ||\n          !all(nzchar(names(params))))\n      pStop_(sQuote(\"params\"),\" must be a named numeric vector.\")\n  }\n\n  if (is(rinit,\"Csnippet\") && is.null(statenames)) {\n    pStop_(\"when \",sQuote(\"rinit\"),\" is provided as a C snippet, \",\n      \"you must also provide \",sQuote(\"statenames\"),\".\")\n  }\n\n  if (is(rmeasure,\"Csnippet\") && is.null(obsnames)) {\n    pStop_(\"when \",sQuote(\"rmeasure\"),\" is provided as a C snippet, \",\n      \"you must also provide \",sQuote(\"obsnames\"),\".\")\n  }\n\n  if (is(emeasure,\"Csnippet\") && is.null(obsnames)) {\n    pStop_(\"when \",sQuote(\"emeasure\"),\" is provided as a C snippet, \",\n      \"you must also provide \",sQuote(\"obsnames\"),\".\")\n  }\n\n  if (is(vmeasure,\"Csnippet\") && is.null(obsnames)) {\n    pStop_(\"when \",sQuote(\"vmeasure\"),\" is provided as a C snippet, \",\n      \"you must also provide \",sQuote(\"obsnames\"),\".\")\n  }\n\n  ## check and arrange covariates\n  if (is.null(covar)) {\n    covar <- covariate_table()\n  } else if (!is(covar,\"covartable\")) {\n    pStop_(\"bad option for \",sQuote(\"covar\"),\".\")\n  }\n\n  if (is.null(covarnames)) covarnames <- get_covariate_names(covar)\n\n  hitches <- hitch(\n    rinit=rinit,\n    dinit=dinit,\n    step.fn=rprocess@step.fn,\n    rate.fn=rprocess@rate.fn,\n    dprocess=dprocess,\n    rmeasure=rmeasure,\n    dmeasure=dmeasure,\n    emeasure=emeasure,\n    vmeasure=vmeasure,\n    rprior=rprior,\n    dprior=dprior,\n    toEst=partrans@to,\n    fromEst=partrans@from,\n    skeleton=skeleton@skel.fn,\n    templates=workhorse_templates,\n    obsnames=obsnames,\n    statenames=statenames,\n    paramnames=paramnames,\n    covarnames=covarnames,\n    PACKAGE=PACKAGE,\n    globals=globals,\n    on_load=on_load,\n    cfile=cfile,\n    cdir=cdir,\n    shlib.args=shlib.args,\n    compile=compile,\n    verbose=verbose\n  )\n\n  ## check to see if covariate times embrace the data times\n  covar_time_warning(covar,times,t0,\"pomp\")\n\n  new(\n    \"pomp\",\n    data=data,\n    times=times,\n    t0=t0,\n    timename=timename,\n    rinit=hitches$funs$rinit,\n    dinit=hitches$funs$dinit,\n    rprocess=rproc_plugin(\n      rprocess,\n      step.fn=hitches$funs$step.fn,\n      rate.fn=hitches$funs$rate.fn\n    ),\n    dprocess=hitches$funs$dprocess,\n    dmeasure=hitches$funs$dmeasure,\n    rmeasure=hitches$funs$rmeasure,\n    emeasure=hitches$funs$emeasure,\n    vmeasure=hitches$funs$vmeasure,\n    skeleton=skel_plugin(\n      skeleton,\n      skel.fn=hitches$funs$skeleton\n    ),\n    dprior=hitches$funs$dprior,\n    rprior=hitches$funs$rprior,\n    partrans=parameter_trans(\n      toEst=hitches$funs$toEst,\n      fromEst=hitches$funs$fromEst\n    ),\n    params=params,\n    covar=covar,\n    accumvars=accumvars,\n    nstatevars=nstatevars,\n    solibs=if (is.null(hitches$lib)) {\n             .solibs\n           } else {\n             c(list(hitches$lib),.solibs)\n           },\n    userdata=.userdata\n  )\n}\n"
  },
  {
    "path": "R/pomp_class.R",
    "content": "##' The basic pomp class\n##'\n##' The basic class implementing a \\acronym{POMP} model with data\n##'\n##' @rdname pomp_class\n##' @include pomp_fun.R\n##' @include csnippet.R safecall.R\n##' @include rprocess_spec.R skeleton_spec.R\n##' @include covariate_table.R parameter_trans.R\n##' @keywords internal\n##' @seealso \\link{pomp_constructor}\n\n##' @export\nsetClass(\n  \"pomp\",\n  slots=c(\n    data = \"array\",\n    times = \"numeric\",\n    t0 = \"numeric\",\n    timename = \"character\",\n    rinit = \"pomp_fun\",\n    dinit = \"pomp_fun\",\n    rprocess = \"rprocPlugin\",\n    dprocess = \"pomp_fun\",\n    rmeasure = \"pomp_fun\",\n    dmeasure = \"pomp_fun\",\n    emeasure = \"pomp_fun\",\n    vmeasure = \"pomp_fun\",\n    rprior = \"pomp_fun\",\n    dprior = \"pomp_fun\",\n    skeleton = \"skelPlugin\",\n    partrans = \"partransPlugin\",\n    params = \"numeric\",\n    states = \"array\",\n    covar = \"covartable\",\n    accumvars = \"character\",\n    nstatevars = \"integer\",\n    solibs = \"list\",\n    userdata = \"list\"\n  ),\n  prototype=prototype(\n    data=array(data=numeric(),dim=c(0,0)),\n    times=numeric(),\n    t0=numeric(),\n    timename=\"time\",\n    rinit=pomp_fun(slotname=\"rinit\"),\n    dinit=pomp_fun(slotname=\"dinit\"),\n    rprocess=rproc_plugin(),\n    dprocess=pomp_fun(slotname=\"dprocess\"),\n    rmeasure=pomp_fun(slotname=\"rmeasure\"),\n    dmeasure=pomp_fun(slotname=\"dmeasure\"),\n    emeasure=pomp_fun(slotname=\"emeasure\"),\n    vmeasure=pomp_fun(slotname=\"vmeasure\"),\n    rprior=pomp_fun(slotname=\"rprior\"),\n    dprior=pomp_fun(slotname=\"dprior\"),\n    skeleton=skel_plugin(),\n    partrans=parameter_trans(),\n    params=numeric(),\n    states=array(data=numeric(),dim=c(0,0)),\n    covar=covariate_table(),\n    nstatevars=0L,\n    accumvars=character(),\n    solibs=list(),\n    userdata=list()\n  ),\n  validity=function (object) {\n    retval <- character(0)\n    if (length(object@times)<1)\n      retval <- append(retval,paste(sQuote(\"times\"),\"is a required argument.\"))\n    if (!is.numeric(object@params) || (length(object@params)>0 && is.null(names(object@params))))\n      retval <- append(retval,paste(sQuote(\"params\"),\"must be a named numeric vector.\"))\n    if (ncol(object@data)!=length(object@times))\n      retval <- append(retval,paste(\"the length of\",sQuote(\"times\"),\"should match the number of observations.\"))\n    if (length(object@t0)<1)\n      retval <- append(retval,paste(sQuote(\"t0\"),\"is a required argument.\"))\n    if (!is.numeric(object@t0) || !is.finite(object@t0) || length(object@t0)>1)\n      retval <- append(retval,paste(sQuote(\"t0\"),\"must be a single number.\"))\n    if (object@t0 > object@times[1])\n      retval <- append(retval,paste(\"the zero-time\",sQuote(\"t0\"),\n        \"must occur no later than the first observation.\"))\n    if (is.na(object@nstatevars) || object@nstatevars < 0L)\n      retval <- append(retval,paste(\"the number of state variables,\",\n        sQuote(\"nstatevars\"),\"must be non-negative.\"))\n    if (length(retval)==0) TRUE else retval\n  }\n)\n"
  },
  {
    "path": "R/pomp_examp.R",
    "content": "##' pre-built pomp examples\n##'\n##' Examples of pomp objects containing models and data.\n##'\n##' @name pomp_examples\n##' @rdname pomp_examp\n##' @docType data\n##' @keywords models\n##' @family pomp examples\n##' @details\n##' \\pkg{pomp} includes a number of pre-built examples of pomp objects and data that can be analyzed using \\pkg{pomp} methods.\n##' These include:\n##' \\describe{\n##' \\item{\\code{\\link{blowflies}}}{Data from Nicholson's experiments with sheep blowfly populations}\n##' \\item{\\code{\\link{blowflies1}()}}{A pomp object with some of the blowfly data together with a discrete delay equation model.}\n##' \\item{\\code{\\link{blowflies2}()}}{A variant of \\code{blowflies1}.}\n##' \\item{\\code{\\link{bsflu}}}{Data from an outbreak of influenza in a boarding school.}\n##' \\item{\\code{\\link{dacca}()}}{Fifty years of census and cholera mortality data, together with a stochastic differential equation transmission model (King et al. 2008).}\n##' \\item{\\code{\\link{ebolaModel}()}}{Data from the 2014 West Africa outbreak of Ebola virus disease, together with simple transmission models (King et al. 2015).}\n##' \\item{\\code{\\link{gompertz}()}}{The Gompertz population dynamics model, with simulated data.}\n##' \\item{\\code{\\link{LondonYorke}}}{Data on incidence of several childhood diseases (London and Yorke 1973)}\n##' \\item{\\code{\\link{ewmeas}}}{Measles incidence data from England and Wales}\n##' \\item{\\code{\\link{ewcitmeas}}}{Measles incidence data from 7 English cities}\n##' \\item{\\code{\\link{ou2}()}}{A 2-D Ornstein-Uhlenbeck process with simulated data}\n##' \\item{\\code{\\link{parus}}}{Population censuses of a \\emph{Parus major} population in Wytham Wood, England.}\n##' \\item{\\code{\\link{ricker}}}{The Ricker population dynamics model, with simulated data}\n##' \\item{\\code{\\link{rw2}}}{A 2-D Brownian motion model, with simulated data.}\n##' \\item{\\code{\\link{sir}()}}{A simple continuous-time Markov chain SIR model, coded using Euler-multinomial steps, with simulated data.}\n##' \\item{\\code{\\link{sir2}()}}{A simple continuous-time Markov chain SIR model, coded using Gillespie's algorithm, with simulated data.}\n##' \\item{\\code{\\link{verhulst}()}}{The Verhulst-Pearl (logistic) model, a continuous-time model of population dynamics, with simulated data}\n##' }\n##'\n##' See also the tutorials on the \\href{https://kingaa.github.io/pomp/}{package website} for more examples.\n##'\n##' @references\n##'\n##' \\Anonymous1978\n##'\n##' \\King2008\n##'\n##' \\King2015\n##'\n##' \\London1973\n##'\n##' \\Nicholson1957\n##'\nNULL\n"
  },
  {
    "path": "R/pomp_fun.R",
    "content": "##' The \"pomp_fun\" class\n##'\n##' Definition and methods of the \\sQuote{pomp_fun} class.\n##'\n##' The \\sQuote{pomp_fun} class implements a common interface for user-defined procedures that can be defined in terms of R code or by compiled native routines.\n##'\n##' @name pomp_fun\n##' @rdname pomp_fun\n##' @include package.R csnippet.R pstop.R undefined.R\n##' @docType methods\n##' @keywords internal\n##' @concept extending the pomp package\n##' @concept low-level interface\n##'\n##' @param f A function or the name of a native routine.\n##' @param PACKAGE optional; the name of the dynamically-loadable library in\n##' which the native function \\code{f} can be found.\n##' @param proto optional string; a prototype against which \\code{f} will be\n##' checked.\n##' @author Aaron A. King\n##' @seealso \\code{\\link{pomp}}\nNULL\n\n## also defined in 'pomp_defines.h'\npompfunmode <- list(undef=0L,Rfun=1L,native=2L,regNative=3L)\n\nsetClass(\n  \"pomp_fun\",\n  slots=c(\n    R.fun = \"function\",\n    native.fun = \"character\",\n    PACKAGE = \"character\",\n    mode = \"integer\",\n    address = \"externalptr\",\n    statenames = \"character\",\n    paramnames = \"character\",\n    obsnames = \"character\",\n    covarnames = \"character\",\n    stateindex = \"integer\",\n    paramindex = \"integer\",\n    obsindex = \"integer\",\n    covarindex = \"integer\",\n    purpose = \"character\"\n  ),\n  prototype=prototype(\n    R.fun=function (...) {\n      pStop(who=\"pomp_fun\",\"unreachable error: please report this bug!\")\n    },\n    native.fun=character(0),\n    PACKAGE=character(0),\n    mode=pompfunmode$undef,\n    statenames = character(0),\n    paramnames = character(0),\n    obsnames = character(0),\n    covarnames = character(0),\n    stateindex = integer(0),\n    paramindex = integer(0),\n    obsindex = integer(0),\n    covarindex = integer(0),\n    purpose = \"a needed function\"\n  )\n)\n\nsetGeneric(\n  \"pomp_fun\",\n  function (f, ...)\n    standardGeneric(\"pomp_fun\")\n)\n\n##' @rdname pomp_fun\nsetMethod(\n  \"pomp_fun\",\n  signature=signature(f=\"missing\"),\n  definition=function (slotname = NULL,\n    obsnames = character(0), statenames = character(0),\n    paramnames = character(0), covarnames = character(0), ...) {\n    new(\"pomp_fun\",\n      obsnames=obsnames,\n      statenames=statenames,\n      paramnames=paramnames,\n      covarnames=covarnames,\n      purpose=as.character(slotname))\n  }\n)\n\nsetMethod(\n  \"pomp_fun\",\n  signature=signature(f=\"NULL\"),\n  definition=function (f, slotname = NULL,\n    obsnames = character(0), statenames = character(0),\n    paramnames = character(0), covarnames = character(0), ...) {\n    new(\"pomp_fun\",\n      obsnames=obsnames,\n      statenames=statenames,\n      paramnames=paramnames,\n      covarnames=covarnames,\n      purpose=as.character(slotname))\n  }\n)\n\nsetMethod(\n  \"pomp_fun\",\n  signature=signature(f=\"ANY\"),\n  definition=function (f, slotname = NULL, ...) {\n    pStop_(\"bad option for \",sQuote(slotname),\" argument.\")\n  }\n)\n\n##' @rdname pomp_fun\nsetMethod(\n  \"pomp_fun\",\n  signature=signature(f=\"function\"),\n  definition=function (f, proto = NULL, slotname = NULL, ...) {\n    if (!is.null(proto)) {\n      prototype <- as.character(proto)\n      fname <- prototype[1]\n      args <- prototype[-1]\n      if (is.function(f)&&(!all(args%in%names(formals(f)))))\n        pStop(who=slotname,\n          sQuote(fname),\" must be a function of the form \",\n          sQuote(deparse(proto)))\n    }\n    new(\"pomp_fun\",R.fun=f,mode=pompfunmode$Rfun,purpose=as.character(slotname))\n  }\n)\n\n##' @rdname pomp_fun\nsetMethod(\n  \"pomp_fun\",\n  signature=signature(f=\"character\"),\n  definition=function (f, PACKAGE = NULL,\n    obsnames = character(0), statenames = character(0),\n    paramnames = character(0), covarnames = character(0),\n    slotname = NULL, ...) {\n    new(\n      \"pomp_fun\",\n      native.fun=f,\n      PACKAGE=as.character(PACKAGE),\n      mode=pompfunmode$native,\n      obsnames=obsnames,\n      statenames=statenames,\n      paramnames=paramnames,\n      covarnames=covarnames,\n      purpose=as.character(slotname)\n    )\n  }\n)\n\n##' @rdname pomp_fun\nsetMethod(\n  \"pomp_fun\",\n  signature=signature(f=\"Csnippet\"),\n  definition=function (f, slotname = NULL, libname = NULL,\n    obsnames = character(0), statenames = character(0),\n    paramnames = character(0), covarnames = character(0),\n    Cname, ...) {\n    slotname <- as.character(slotname)\n    libname <- as.character(libname)\n    new(\n      \"pomp_fun\",\n      native.fun=render(Cname,name=libname),\n      PACKAGE=libname,\n      mode=pompfunmode$regNative,\n      obsnames=obsnames,\n      statenames=statenames,\n      paramnames=paramnames,\n      covarnames=covarnames,\n      purpose=slotname\n    )\n  }\n)\n\n##' @rdname pomp_fun\nsetMethod(\n  \"pomp_fun\",\n  signature=signature(f=\"pomp_fun\"),\n  definition=function (f, ...) f\n)\n\n##' @rdname undefined\nsetMethod(\n  \"undefined\",\n  signature=signature(object=\"pomp_fun\"),\n  definition=function (object, ...) {\n    object@mode == pompfunmode$undef\n  }\n)\n"
  },
  {
    "path": "R/pred_mean.R",
    "content": "##' Prediction mean\n##'\n##' The mean of the prediction distribution\n##'\n##' The prediction distribution is that of\n##' \\deqn{X(t_k) \\vert Y(t_1)=y^*_1,\\dots,Y(t_{k-1})=y^*_{k-1},}{Xk | Y1=y1*,\\dots,Y(k-1)=y(k-1)*,}\n##' where \\eqn{X(t_k)}{Xk}, \\eqn{Y(t_k)}{Yk} are the latent state and observable processes, respectively, and \\eqn{y^*_k}{yk*} is the data, at time \\eqn{t_k}{tk}.\n##'\n##' The prediction mean is therefore the expectation of this distribution\n##' \\deqn{E[X(t_k) \\vert Y(t_1)=y^*_1,\\dots,Y(t_{k-1})=y^*_{k-1}].}{E[Xk | Y1=y1*,\\dots,Y(k-1)=y(k-1)*].}\n##'\n##' @name pred_mean\n##' @aliases pred_mean,ANY-method pred_mean,missing-method\n##' @include pfilter.R kalman.R melt.R\n##' @rdname pred_mean\n##' @family particle filter methods\n##' @family extraction methods\n##' @inheritParams filter_mean\n##'\nNULL\n\nsetGeneric(\n  \"pred_mean\",\n  function (object, ...)\n    standardGeneric(\"pred_mean\")\n)\n\nsetMethod(\n  \"pred_mean\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"pred_mean\",\"object\")\n  }\n)\n\nsetMethod(\n  \"pred_mean\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"pred_mean\",object)\n  }\n)\n\n##' @rdname pred_mean\n##' @export\nsetMethod(\n  \"pred_mean\",\n  signature=signature(object=\"kalmand_pomp\"),\n  definition=function (object, vars, ...,\n    format = c(\"array\", \"data.frame\")) {\n    if (missing(vars)) {\n      x <- object@pred.mean\n    } else {\n      x <- object@pred.mean[vars,,drop=FALSE]\n    }\n    format <- match.arg(format)\n    if (format == \"data.frame\") {\n      x <- melt(object@pred.mean[vars,,drop=FALSE])\n      x$time <- time(object)[as.integer(x$time)]\n    }\n    x\n  }\n)\n\n##' @rdname pred_mean\n##' @export\nsetMethod(\n  \"pred_mean\",\n  signature=signature(object=\"pfilterd_pomp\"),\n  definition=function (object, vars, ...,\n    format = c(\"array\", \"data.frame\")) {\n    if (missing(vars)) {\n      x <- object@pred.mean\n    } else {\n      x <- object@pred.mean[vars,,drop=FALSE]\n    }\n    format <- match.arg(format)\n    if (format == \"data.frame\") {\n      x <- melt(object@pred.mean[vars,,drop=FALSE])\n      x$time <- time(object)[as.integer(x$time)]\n    }\n    x\n  }\n)\n"
  },
  {
    "path": "R/pred_var.R",
    "content": "##' Prediction variance\n##'\n##' The variance of the prediction distribution\n##'\n##' The prediction distribution is that of\n##' \\deqn{X(t_k) \\vert Y(t_1)=y^*_1,\\dots,Y(t_{k-1})=y^*_{k-1},}{Xk | Y1=y1*,\\dots,Y(k-1)=y(k-1)*,}\n##' where \\eqn{X(t_k)}{Xk}, \\eqn{Y(t_k)}{Yk} are the latent state and observable processes, respectively, and \\eqn{y^*_k}{yk*} is the data, at time \\eqn{t_k}{tk}.\n##'\n##' The prediction variance is therefore the variance of this distribution\n##' \\deqn{\\mathrm{Var}[X(t_k) \\vert Y(t_1)=y^*_1,\\dots,Y(t_{k-1})=y^*_{k-1}].}{Var[Xk | Y1=y1*,\\dots,Y(k-1)=y(k-1)*].}\n##'\n##' @name pred_var\n##' @aliases pred_var,ANY-method pred_var,missing-method\n##' @include pfilter.R kalman.R melt.R\n##' @rdname pred_var\n##' @family particle filter methods\n##' @family extraction methods\n##' @inheritParams filter_mean\n##'\nNULL\n\nsetGeneric(\n  \"pred_var\",\n  function (object, ...)\n    standardGeneric(\"pred_var\")\n)\n\nsetMethod(\n  \"pred_var\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"pred_var\",\"object\")\n  }\n)\n\nsetMethod(\n  \"pred_var\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"pred_var\",object)\n  }\n)\n\n##' @rdname pred_var\n##' @export\nsetMethod(\n  \"pred_var\",\n  signature=signature(object=\"pfilterd_pomp\"),\n  definition=function (object, vars, ...,\n    format = c(\"array\", \"data.frame\")) {\n    if (missing(vars)) {\n      x <- object@pred.var\n    } else {\n      x <- object@pred.var[vars,,drop=FALSE]\n    }\n    format <- match.arg(format)\n    if (format == \"data.frame\") {\n      x <- melt(object@pred.var[vars,,drop=FALSE])\n      x$time <- time(object)[as.integer(x$time)]\n    }\n    x\n  }\n)\n"
  },
  {
    "path": "R/print.R",
    "content": "##' Print methods\n##'\n##' These methods print their argument and return it *invisibly*.\n##'\n##' @name print\n##' @rdname print\n##' @keywords internal\n##' @param x object to print\n##' @param ... ignored\n##' @include show.R\nNULL\n\nsetGeneric(\"print\")\n\n##' @rdname print\n##' @export\nsetMethod(\n  \"print\",\n  signature=signature(x=\"unshowable\"),\n  definition=function (x, ...) {\n    show(x)\n    invisible(x)\n  }\n)\n\n##' @rdname print\n##' @export\nsetMethod(\n  \"print\",\n  signature=signature(x=\"listie\"),\n  definition=function (x, ...) {\n    show(x)\n    invisible(x)\n  }\n)\n\n##' @rdname print\n##' @export\nsetMethod(\n  \"print\",\n  \"pomp_fun\",\n  function (x, ...) {\n    show(x)\n    invisible(x)\n  }\n)\n"
  },
  {
    "path": "R/prior_spec.R",
    "content": "##' prior specification\n##'\n##' Specification of prior distributions via the rprior and dprior components.\n##'\n##' @name prior_spec\n##' @aliases priors\n##' @rdname prior_spec\n##' @family implementation information\n##' @family Bayesian methods\n##' @seealso \\code{\\link{dprior}} \\code{\\link{rprior}}\n##' @inheritSection pomp Note for Windows users\n##' @details\n##' A prior distribution on parameters is specified by means of the \\code{rprior} and/or \\code{dprior} arguments to \\code{pomp}.\n##' As with the other \\link[=basic_components]{basic model components}, it is preferable to specify these using C snippets.\n##' In writing a C snippet for the prior sampler (\\code{rprior}), keep in mind that:\n##' \\enumerate{\n##'   \\item Within the context in which the snippet will be evaluated, only the parameters will be defined.\n##'   \\item The goal of such a snippet is the replacement of parameters with values drawn from the prior distribution.\n##'   \\item Hyperparameters can be included in the ordinary parameter list.\n##'   Obviously, hyperparameters should not be replaced with random draws.\n##' }\n##' In writing a C snippet for the prior density function (\\code{dprior}), observe that:\n##' \\enumerate{\n##'   \\item Within the context in which the snippet will be evaluated, only the parameters and \\code{give_log} will be defined.\n##'   \\item The goal of such a snippet is computation of the prior probability density, or the log of same, at a given point in parameter space.\n##'   This scalar value should be returned in the variable \\code{lik}.\n##'   When \\code{give_log == 1}, \\code{lik} should contain the log of the prior probability density.\n##'   \\item Hyperparameters can be included in the ordinary parameter list.\n##' }\n##' \\link[=Csnippet]{General rules for writing C snippets can be found here}.\n##'\n##' Alternatively, one can furnish \\R functions for one or both of these arguments.\n##' In this case, \\code{rprior} must be a function that makes a draw from\n##' the prior distribution of the parameters and returns a named vector\n##' containing all the parameters.\n##' The only required argument of this function is \\code{...}.\n##'\n##' Similarly, the \\code{dprior} function must evaluate the prior probability\n##' density (or log density if \\code{log == TRUE}) and return that single\n##' scalar value.\n##' The only required arguments of this function are \\code{...} and \\code{log}.\n##' @section Default behavior:\n##' By default, the prior is assumed flat and improper.\n##' In particular, \\code{dprior} returns \\code{1} (\\code{0} if \\code{log = TRUE}) for every parameter set.\n##' Since it is impossible to simulate from a flat improper prior, \\code{rprocess} returns missing values (\\code{NA}s).\n##'\n##' @example examples/prior_spec.R\n##'\nNULL\n"
  },
  {
    "path": "R/probe.R",
    "content": "##' Probes (AKA summary statistics)\n##'\n##' Probe a partially-observed Markov process by computing summary statistics\n##' and the synthetic likelihood.\n##'\n##' \\code{probe} applies one or more \\dQuote{probes} to time series data and\n##' model simulations and compares the results.  It can be used to diagnose\n##' goodness of fit and/or as the basis for \\dQuote{probe-matching}, a\n##' generalized method-of-moments approach to parameter estimation.\n##'\n##' A call to \\code{probe} results in the evaluation of the probe(s) in\n##' \\code{probes} on the data.  Additionally, \\code{nsim} simulated data sets\n##' are generated (via a call to \\code{\\link{simulate}}) and\n##' the probe(s) are applied to each of these.  The results of the probe\n##' computations on real and simulated data are stored in an object of class\n##' \\sQuote{probed_pomp}.\n##'\n##' @docType methods\n##' @name probe\n##' @rdname probe\n##' @aliases probe,missing-method probe,ANY-method\n##' @author Daniel C. Reuman, Aaron A. King\n##' @concept synthetic likelihood\n##' @family elementary algorithms\n##' @family summary statistic-based methods\n##' @inheritSection pomp Note for Windows users\n##' @include pomp_class.R pomp_fun.R pomp.R\n##' @importFrom stats quantile\n##' @param probes a single probe or a list of one or more probes.\n##' A probe is simply a scalar- or vector-valued function of one argument that can be applied to the data array of a \\sQuote{pomp}.\n##' A vector-valued probe must always return a vector of the same size.\n##' A number of useful probes are provided with the package:\n##' see \\link[=basic_probes]{basic probes}.\n##' @param nsim the number of model simulations to be computed.\n##' @inheritParams pfilter\n##' @inheritParams simulate\n##' @inheritParams pomp\n##' @return\n##' \\code{probe} returns an object of class \\sQuote{probed_pomp}, which contains the data and the model, together with the results of the \\code{probe} calculation.\n##' @section Methods:\n##' The following methods are available.\n##' \\describe{\n##' \\item{\\code{plot}}{ displays diagnostic plots.  }\n##' \\item{\\code{summary}}{ displays summary information.\n##' The summary includes quantiles (fractions of simulations with probe values less than those realized on the data) and the corresponding two-sided p-values.\n##' In addition, the \\dQuote{synthetic likelihood} (Wood 2010) is computed,\n##' under the assumption that the probe values are multivariate-normally distributed.  }\n##' \\item{\\code{logLik}}{ returns the synthetic likelihood for the probes.\n##' NB: in general, this is not the same as the likelihood.  }\n##' \\item{\\code{as.data.frame}}{\n##'  coerces a \\sQuote{probed_pomp} to a \\sQuote{data.frame}.\n##'  The latter contains the realized values of the probes on the data and on the simulations.\n##' The variable \\code{.id} indicates whether the probes are from the data or simulations.  }\n##' }\n##'\n##' @references\n##'\n##' \\Kendall1999\n##'\n##' \\Wood2010\n##'\nNULL\n\nsetClass(\n  \"probed_pomp\",\n  contains=\"pomp\",\n  slots=c(\n    probes=\"list\",\n    nsim=\"integer\",\n    datvals=\"numeric\",\n    simvals=\"array\",\n    quantiles=\"numeric\",\n    pvals=\"numeric\",\n    synth.loglik=\"numeric\",\n    seed=\"integer\"\n  )\n)\n\nsetGeneric(\n  \"probe\",\n  function (data, ...)\n    standardGeneric(\"probe\")\n)\n\nsetMethod(\n  \"probe\",\n  signature=signature(data=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"probe\",\"data\")\n  }\n)\n\nsetMethod(\n  \"probe\",\n  signature=signature(data=\"ANY\"),\n  definition=function (data, ...) {\n    undef_method(\"probe\",data)\n  }\n)\n\n##' @rdname probe\n##' @export\nsetMethod(\n  \"probe\",\n  signature=signature(data=\"data.frame\"),\n  definition=function (\n    data,\n    ...,\n    probes, nsim, seed = NULL,\n    params, rinit, rprocess, rmeasure,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      probe_internal(data,probes=probes,nsim=nsim,seed=seed,\n        rinit=rinit,rprocess=rprocess,rmeasure=rmeasure,params=params,\n        ...,verbose=verbose),\n      error = function (e) pStop(who=\"probe\",conditionMessage(e))\n    )\n\n\n  }\n)\n\n##' @rdname probe\n##' @export\nsetMethod(\n  \"probe\",\n  signature=signature(data=\"pomp\"),\n  definition=function (\n    data,\n    ...,\n    probes,\n    nsim, seed = NULL,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      probe_internal(data,...,probes=probes,nsim=nsim,seed=seed,verbose=verbose),\n      error = function (e) pStop(who=\"probe\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname probe\n##' @export\nsetMethod(\n  \"probe\",\n  signature=signature(data=\"probed_pomp\"),\n  definition=function (\n    data,\n    ...,\n    probes,\n    nsim,\n    seed = NULL,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    if (missing(probes)) probes <- data@probes\n    if (missing(nsim)) nsim <- data@nsim\n\n    probe(as(data,\"pomp\"),probes=probes,nsim=nsim,seed=seed,\n      ...,verbose=verbose)\n\n  }\n)\n\nprobe_internal <- function (\n  object,\n  ...,\n  probes, nsim, seed,\n  .gnsi = TRUE, verbose\n) {\n\n  verbose <- as.logical(verbose)\n\n  object <- pomp(object,...,verbose=verbose)\n\n  if (undefined(object@rprocess) || undefined(object@rmeasure))\n    pStop_(paste(sQuote(c(\"rprocess\",\"rmeasure\")),collapse=\", \"),\" are needed basic components.\")\n\n  if (missing(probes)) probes <- NULL\n  if (missing(nsim)) nsim <- NULL\n\n  if (is.null(probes)) pStop_(sQuote(\"probes\"),\" must be furnished.\")\n  if (!is.list(probes)) probes <- list(probes)\n  if (!all(vapply(probes,is.function,logical(1L))))\n    pStop_(sQuote(\"probes\"),\" must be a function or a list of functions.\")\n  if (!all(vapply(probes,\\(f)length(formals(f))==1L,logical(1L))))\n    pStop_(\"each probe must be a function of a single argument.\")\n\n  nsim <- as.integer(nsim)\n  if (length(nsim) < 1) pStop_(sQuote(\"nsim\"),\" must be specified.\")\n  if (length(nsim) > 1 || !is.finite(nsim) || nsim <= 0)\n    pStop_(\"number of simulations, \",sQuote(\"nsim\"),\", must be a single positive integer.\")\n\n  seed <- as.integer(seed)\n  gnsi <- as.logical(.gnsi)\n\n  params <- coef(object)\n\n  pompLoad(object,verbose=verbose)\n  on.exit(pompUnload(object,verbose=verbose))\n\n  ## apply probes to data\n  datval <- tryCatch(\n    .Call(P_apply_probe_data,object,probes),\n    error = function (e)\n      pStop_(\"applying probes to actual data: \",conditionMessage(e))\n  )\n\n  nprobes <- length(datval)\n\n  if (nprobes >= nsim)\n    pStop_(sQuote(\"nsim\"),\" (=\",nsim,\"), should be (much) larger than the \", \"number of probes (=\",nprobes,\").\")\n\n  ## apply probes to model simulations\n  simval <- tryCatch(\n    freeze(\n      .Call(P_apply_probe_sim,object=object,nsim=nsim,params=params,probes=probes,\n        datval=datval,gnsi=gnsi),\n      seed=seed\n    ),\n    error = function (e)\n      pStop_(\"applying probes to simulated data: \",conditionMessage(e))\n  )\n\n  pvals <- numeric(nprobes)\n  names(pvals) <- names(datval)\n  quants <- numeric(nprobes)\n  names(quants) <- names(datval)\n\n  for (k in seq_len(nprobes)) {\n    r <- min(sum(simval[,k]>datval[k]),sum(simval[,k]<datval[k]))\n    tails <- (r+1)/(nsim+1)\n    pvals[k] <- min(2*tails,1)\n    quants[k] <- sum(simval[,k]<datval[k])/nsim\n  }\n\n  ll <- tryCatch(\n    .Call(P_synth_loglik,simval,datval),\n    error = function (e)\n      pStop_(\"in synthetic likelihood computation: \",conditionMessage(e))\n  )\n\n  names(dimnames(simval)) <- c(\".id\",\"probe\")\n\n  new(\n    \"probed_pomp\",\n    object,\n    probes=probes,\n    nsim=nsim,\n    datvals=datval,\n    simvals=simval,\n    quantiles=quants,\n    pvals=pvals,\n    synth.loglik=ll,\n    seed=seed\n  )\n}\n\n##' @rdname summary\n##' @include summary.R\n##' @export\nsetMethod(\n  \"summary\",\n  signature=signature(object=\"probed_pomp\"),\n  definition=function (object, ...) {\n    list(\n      coef=coef(object),\n      nsim=nrow(object@simvals),\n      quantiles=object@quantiles,\n      pvals=object@pvals,\n      synth.loglik=object@synth.loglik\n    )\n  }\n)\n"
  },
  {
    "path": "R/probe_match.R",
    "content": "##' Probe matching\n##'\n##' Estimation of parameters by maximum synthetic likelihood\n##'\n##' In probe-matching, one attempts to minimize the discrepancy between simulated and actual data, as measured by a set of summary statistics called \\emph{probes}.\n##' In \\pkg{pomp}, this discrepancy is measured using the \\dQuote{synthetic likelihood} as defined by Wood (2010).\n##'\n##' @docType methods\n##' @name probe_match\n##' @rdname probe_match\n##' @aliases probe_objfun probe_objfun,missing-method probe_objfun,ANY-method\n##' @include probe.R plot.R\n##' @author Aaron A. King\n##' @concept probe matching\n##' @concept synthetic likelihood\n##' @family summary statistic-based methods\n##' @family estimation methods\n##' @family methods based on maximization\n##' @references\n##'\n##' \\Kendall1999\n##'\n##' \\Wood2010\n##'\n##' @seealso \\code{\\link[stats]{optim}} \\code{\\link[subplex]{subplex}} \\code{\\link[nloptr]{nloptr}}\n##' @param est character vector; the names of parameters to be estimated.\n##' @param fail.value optional numeric scalar;\n##' if non-\\code{NA}, this value is substituted for non-finite values of the objective function.\n##' It should be a large number (i.e., bigger than any legitimate values the objective function is likely to take).\n##' @param seed  integer.\n##' When fitting, it is often best to fix the seed of the random-number generator (RNG).\n##' This is accomplished by setting \\code{seed} to an integer.\n##' By default, \\code{seed = NULL}, which does not alter the RNG state.\n##' @inheritParams probe\n##' @inheritParams pomp\n##' @return\n##' \\code{probe_objfun} constructs a stateful objective function for probe matching.\n##' Specifically, \\code{probe_objfun} returns an object of class \\sQuote{probe_match_objfun}, which is a function suitable for use in an \\code{\\link[stats]{optim}}-like optimizer.\n##' In particular, this function takes a single numeric-vector argument that is assumed to contain the parameters named in \\code{est}, in that order.\n##' When called, it will return the negative synthetic log likelihood for the probes specified.\n##' It is a stateful function:\n##' Each time it is called, it will remember the values of the parameters and its estimate of the synthetic likelihood.\n##' @inheritSection pomp Note for Windows users\n##' @inheritSection objfun Important Note\n##' @inheritSection objfun Warning! Objective functions based on C snippets\n##' @example examples/probe_match.R\n##'\nNULL\n\nsetClass(\n  \"probe_match_objfun\",\n  contains=\"function\",\n  slots=c(\n    env=\"environment\",\n    est=\"character\"\n  )\n)\n\nsetGeneric(\n  \"probe_objfun\",\n  function (data, ...)\n    standardGeneric(\"probe_objfun\")\n)\n\nsetMethod(\n  \"probe_objfun\",\n  signature=signature(data=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"probe_objfun\",\"data\")\n  }\n)\n\nsetMethod(\n  \"probe_objfun\",\n  signature=signature(data=\"ANY\"),\n  definition=function (data, ...) {\n    undef_method(\"probe_objfun\",data)\n  }\n)\n\n##' @rdname probe_match\n##' @export\nsetMethod(\n  \"probe_objfun\",\n  signature=signature(data=\"data.frame\"),\n  definition=function (\n    data,\n    ...,\n    est = character(0), fail.value = NA,\n    probes, nsim, seed = NULL,\n    params, rinit, rprocess, rmeasure, partrans,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      pmof_internal(\n        data,\n        ...,\n        est=est,\n        fail.value=fail.value,\n        probes=probes,\n        nsim=nsim,\n        seed=seed,\n        params=params,\n        rinit=rinit,\n        rprocess=rprocess,\n        rmeasure=rmeasure,\n        partrans=partrans,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"probe_objfun\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname probe_match\n##' @export\nsetMethod(\n  \"probe_objfun\",\n  signature=signature(data=\"pomp\"),\n  definition=function (\n    data,\n    ...,\n    est = character(0),\n    fail.value = NA,\n    probes, nsim, seed = NULL,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      pmof_internal(\n        data,\n        ...,\n        est=est,\n        fail.value=fail.value,\n        probes=probes,\n        nsim=nsim,\n        seed=seed,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"probe_objfun\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname probe_match\n##' @export\nsetMethod(\n  \"probe_objfun\",\n  signature=signature(data=\"probed_pomp\"),\n  definition=function (\n    data,\n    ...,\n    est = character(0),\n    fail.value = NA,\n    probes, nsim, seed = NULL,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    if (missing(probes)) probes <- data@probes\n    if (missing(nsim)) nsim <- data@nsim\n\n    probe_objfun(\n      as(data,\"pomp\"),\n      ...,\n      est=est,\n      fail.value=fail.value,\n      probes=probes,\n      nsim=nsim,\n      seed=seed,\n      verbose=verbose\n    )\n\n  }\n)\n\n##' @rdname probe_match\n##' @export\nsetMethod(\n  \"probe_objfun\",\n  signature=signature(data=\"probe_match_objfun\"),\n  definition=function (\n    data,\n    ...,\n    est, fail.value, seed = NULL,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    if (missing(est)) est <- data@est\n    if (missing(fail.value)) fail.value <- data@env$fail.value\n\n    probe_objfun(\n      data@env$object,\n      ...,\n      est=est,\n      fail.value=fail.value,\n      seed=seed,\n      verbose=verbose\n    )\n\n  }\n)\n\npmof_internal <- function (\n  object,\n  ...,\n  est, fail.value = NA,\n  probes, nsim, seed = NULL,\n  verbose\n) {\n\n  verbose <- as.logical(verbose)\n\n  object <- probe(object,probes=probes,nsim=nsim,seed=seed,...,verbose=verbose)\n\n  fail.value <- as.numeric(fail.value)\n  loglik <- logLik(object)\n  .gnsi <- TRUE\n\n  est <- as.character(est)\n  est <- est[nzchar(est)]\n\n  params <- coef(object,transform=TRUE)\n\n  idx <- match(est,names(params))\n  if (any(is.na(idx))) {\n    missing <- est[is.na(idx)]\n    pStop_(\"parameter\",ngettext(length(missing),\"\",\"s\"),\" \",\n      paste(sQuote(missing),collapse=\",\"),\" not found in \",sQuote(\"params\"),\".\")\n  }\n\n  pompLoad(object,verbose=verbose)\n\n  ofun <- function (par = numeric(0)) {\n    params[idx] <- par\n    coef(object,transform=TRUE,.gnsi=.gnsi) <<- params\n    loglik <<- probe.eval(object,.gnsi=.gnsi)\n    .gnsi <<- FALSE\n    if (is.finite(loglik) || is.na(fail.value)) -loglik else fail.value\n  }\n\n  environment(ofun) <- list2env(\n    list(object=object,fail.value=fail.value,.gnsi=.gnsi,\n      params=params,idx=idx,loglik=loglik,seed=seed),\n    parent=parent.frame(2)\n  )\n\n  new(\"probe_match_objfun\",ofun,env=environment(ofun),est=est)\n\n}\n\nprobe.eval <- function (object, .gnsi = TRUE) {\n\n  ## apply probes to model simulations\n  simvals <- tryCatch(\n    freeze(\n      .Call(P_apply_probe_sim,object=object,nsim=object@nsim,params=object@params,\n        probes=object@probes,datval=object@datvals,.gnsi=.gnsi),\n      seed=object@seed\n    ),\n    error = function (e) pStop_(\"applying probes to simulated data: \",conditionMessage(e))\n  )\n\n  tryCatch(\n    .Call(P_synth_loglik,simvals,object@datvals),\n    error = function (e) pStop_(\"in synthetic likelihood computation: \",conditionMessage(e))\n  )\n\n}\n\n##' @rdname probe\n##' @details\n##' When \\code{probe} operates on a probe-matching objective function (a \\sQuote{probe_match_objfun} object), by default, the\n##' random-number generator seed is fixed at the value given when the objective function was constructed.\n##' Specifying \\code{NULL} or an integer for \\code{seed} overrides this behavior.\n##' @export\nsetMethod(\n  \"probe\",\n  signature=signature(data=\"probe_match_objfun\"),\n  definition=function (\n    data,\n    ...,\n    seed,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    if (missing(seed)) seed <- data@env$seed\n\n    probe(\n      data@env$object,\n      ...,\n      seed=seed,\n      verbose=verbose\n    )\n\n  }\n)\n\nsetAs(\n  from=\"probe_match_objfun\",\n  to=\"probed_pomp\",\n  def = function (from) {\n    from@env$object\n  }\n)\n\n##' @rdname plot\n##' @export\nsetMethod(\n  \"plot\",\n  signature=signature(x=\"probe_match_objfun\"),\n  definition=function (x, ...) {\n    plot(as(x,\"probed_pomp\"),...)\n  }\n)\n"
  },
  {
    "path": "R/profile_design.R",
    "content": "##' @description\n##' \\code{profile_design} generates a data-frame where each row can be used as the starting point for a profile likelihood calculation.\n##' @concept profile likelihood\n##'\n##' @rdname design\n##' @return\n##' \\code{profile_design} returns a data frame with \\code{nprof} points per profile point.\n##' @param nprof The number of points per profile point.\n##' @param type the type of design to use.\n##' \\code{type=\"runif\"} uses \\code{\\link{runif_design}}.\n##' \\code{type=\"sobol\"} uses \\code{\\link{sobol_design}};\n##' @param stringsAsFactors should character vectors be converted to factors?\n##'\n##' @export\nprofile_design <- function (...,\n  lower, upper, nprof,\n  type = c(\"runif\",\"sobol\"),\n  stringsAsFactors = getOption(\"stringsAsFactors\",FALSE)\n) {\n  type <- match.arg(type)\n  prof <- list(...)\n  pvars <- names(prof)\n  if (any(pvars==\"\"))\n    pStop(\"you cannot profile over an unnamed variable!\")\n  ovars <- names(lower)\n  if (!all(sort(ovars)==sort(names(upper))))\n    pStop(\"names of \",sQuote(\"lower\"),\" and \",sQuote(\"upper\"),\" must match!\")\n  x <- expand.grid(...,stringsAsFactors=stringsAsFactors)\n  n <- nrow(x)\n  z <- vector(mode='list',length=n)\n  y <- switch(type,\n    runif=runif_design(lower=lower,upper=upper,nseq=n*nprof),\n    sobol_design(lower=lower,upper=upper,nseq=n*nprof)\n  )\n  y <- split(y,rep(seq_len(n),each=nprof))\n  for (i in seq_len(n)) {\n    z[[i]] <- data.frame(\n      x[i,,drop=FALSE], y[[i]],\n      check.rows=FALSE,\n      check.names=FALSE,\n      row.names=seq_len(nprof)\n    )\n  }\n  do.call(rbind,z)\n}\n"
  },
  {
    "path": "R/proposals.R",
    "content": "##' MCMC proposal distributions\n##'\n##' Functions to construct proposal distributions for use with MCMC methods.\n##'\n##'\n##' @name proposals\n##' @rdname proposals\n##' @importFrom stats rnorm\n##' @family MCMC methods\n##'\n##' @param rw.var square numeric matrix with row- and column-names.  Specifies\n##' the variance-covariance matrix for a multivariate normal random-walk\n##' proposal distribution.\n##' @param rw.sd named numeric vector; random-walk SDs for a multivariate\n##' normal random-walk proposal with diagonal variance-covariance matrix.\n##' @param scale.start,scale.cooling,shape.start,target,max.scaling parameters\n##' to control the proposal adaptation algorithm.  Beginning with MCMC\n##' iteration \\code{scale.start}, the scale of the proposal covariance matrix\n##' will be adjusted in an effort to match the \\code{target} acceptance ratio.\n##' This initial scale adjustment is \\dQuote{cooled}, i.e., the adjustment\n##' diminishes as the chain moves along.  The parameter \\code{scale.cooling}\n##' specifies the cooling schedule: at n iterations after \\code{scale.start},\n##' the current scaling factor is multiplied with \\code{scale.cooling^n}.  The\n##' maximum scaling factor allowed at any one iteration is \\code{max.scaling}.\n##' After \\code{shape.start} accepted proposals have accumulated, a scaled\n##' empirical covariance matrix will be used for the proposals, following\n##' Roberts and Rosenthal (2009).\n##'\n##' @return Each of these calls constructs a function suitable for use as the\n##' \\code{proposal} argument of \\code{pmcmc} or \\code{abc}.  Given a parameter\n##' vector, each such function returns a single draw from the corresponding\n##' proposal distribution.\n##'\n##' @author Aaron A. King, Sebastian Funk\n##'\n##' @references\n##'\n##' \\Roberts2009\n##'\nNULL\n\n##' @rdname proposals\n##' @export\nmvn_diag_rw <- function (rw.sd) {\n  if (missing(rw.sd) || !is.numeric(rw.sd)) {\n    pStop(sQuote(\"rw.sd\"),\" must be a named numeric vector.\")\n  }\n  rw.sd <- rw.sd[rw.sd>0]\n  parnm <- names(rw.sd)\n  n <- length(rw.sd)\n  if (is.null(parnm))\n    pStop(sQuote(\"rw.sd\"),\" must have names.\")\n  function (theta, ...) {\n    theta[parnm] <- rnorm(n=n,mean=theta[parnm],sd=rw.sd)\n    theta\n  }\n}\n\n##' @rdname proposals\n##' @export\nmvn_rw <- function (rw.var) {\n  rw.var <- as.matrix(rw.var)\n  parnm <- colnames(rw.var)\n  if (is.null(parnm))\n    pStop(sQuote(\"rw.var\"),\" must have row- and column-names.\")\n  if (nrow(rw.var)!=ncol(rw.var))\n    pStop(sQuote(\"rw.var\"),\" must be a square matrix.\")\n  ch <- chol(rw.var,pivot=TRUE)\n  if (attr(ch,\"rank\") < ncol(ch))\n    pWarn(\"rank-deficient covariance matrix\")\n  oo <- order(attr(ch,\"pivot\"))\n  n <- Q <- NULL                 # to evade R CMD check false positive\n  e <- new.env()\n  e$Q <- ch[,oo]\n  e$n <- ncol(rw.var)\n  e$parnm <- parnm\n  f <- function (theta, ...) {\n    theta[parnm] <- theta[parnm]+rnorm(n=n,mean=0,sd=1)%*%Q\n    theta\n  }\n  environment(f) <- e\n  f\n}\n\n##' @rdname proposals\n##' @export\n## a stateful function implementing an adaptive proposal\nmvn_rw_adaptive <- function (rw.sd, rw.var, scale.start = NA,\n  scale.cooling = 0.999, shape.start = NA, target = 0.234, max.scaling = 50) {\n\n  if (!xor(missing(rw.sd),missing(rw.var))) {\n    pStop(\"exactly one of \",sQuote(\"rw.sd\"),\" and \",sQuote(\"rw.var\"),\n      \" must be supplied.\")\n  }\n  if (!missing(rw.var)) { ## variance supplied\n    rw.var <- as.matrix(rw.var)\n    parnm <- colnames(rw.var)\n    if (is.null(parnm))\n      pStop(sQuote(\"rw.var\"),\" must have row- and column-names.\")\n    if (nrow(rw.var)!=ncol(rw.var))\n      pStop(sQuote(\"rw.var\"),\" must be a square matrix.\")\n    if (any(parnm!=rownames(rw.var)))\n      pStop(\"row- and column-names of \",sQuote(\"rw.var\"),\" must agree.\")\n  } else if (!missing(rw.sd)) { ## sd supplied (diagonal)\n    if (!is.numeric(rw.sd) || is.null(names(rw.sd))) {\n      pStop(sQuote(\"rw.sd\"),\" must be a named numeric vector.\")\n    }\n    rw.sd <- rw.sd[rw.sd>0]\n    parnm <- names(rw.sd)\n    rw.var <- diag(rw.sd^2,nrow=length(rw.sd),ncol=length(rw.sd))\n    dimnames(rw.var) <- list(parnm,parnm)\n  }\n\n  scale.start <- as.integer(scale.start)\n  scale.cooling <- as.numeric(scale.cooling)\n  shape.start <- as.integer(shape.start)\n  target <- as.numeric(target) ## target acceptance ratio\n  if (!isTRUE(scale.start > 0))\n    pStop(sQuote(\"scale.start\"),\" must be a positive integer.\")\n  if (!isTRUE((scale.cooling > 0) && (scale.cooling <= 1)))\n    pStop(sQuote(\"scale.cooling\"),\" must be in (0,1].\")\n  if (!isTRUE(shape.start > 0))\n    pStop(sQuote(\"shape.start\"),\" must be a positive integer.\")\n  if (!isTRUE(target > 0 && target < 1)) {\n    pStop(sQuote(\"target\"),\" must be a number in (0,1).\")\n  }\n\n  ## variables that will follow 'f'\n  scaling <- 1\n  theta.mean <- NULL\n  covmat.emp <- array(data=0,dim=dim(rw.var),dimnames=dimnames(rw.var))\n\n  function (theta, .n, .accepts, verbose, ...) {\n    if (.n == 0) return(theta) ## handle initial test run by pmcmc\n    if (is.null(theta.mean)) theta.mean <<- theta[parnm]\n    if (!is.na(scale.start) && .n >= scale.start &&\n          (is.na(shape.start) || .accepts < shape.start)) {\n      ## adapt size of covmat until we get enough accepted jumps\n      scaling <<- min(scaling*exp(scale.cooling^(.n-scale.start)*\n                                    (.accepts/.n-target)),\n        max.scaling)\n      covmat <- scaling^2*rw.var\n    } else if (!is.na(shape.start) && .accepts >= shape.start) {\n      scaling <<- 2.38^2/length(parnm)\n      covmat <- scaling*covmat.emp\n    } else {\n      covmat <- rw.var\n    }\n    if (verbose) {\n      cat(\"proposal covariance matrix:\\n\")\n      print(covmat)\n    }\n    if (!is.na(shape.start)) {\n      theta.mean <<- ((.n-1)*theta.mean+theta[parnm])/.n\n      covmat.emp <<- ((.n-1)*covmat.emp+tcrossprod(theta[parnm]-theta.mean))/.n\n    }\n    ch <- chol(covmat,pivot=TRUE)\n    if (attr(ch,\"rank\")<length(parnm))\n      pWarn(who=\"mvn_rw_adaptive\",\"degenerate proposal.\")\n    oo <- order(attr(ch,\"pivot\"))\n    Q <- ch[,oo]\n    theta[parnm] <- theta[parnm]+rnorm(n=length(parnm),mean=0,sd=1)%*%Q\n    theta\n  }\n}\n"
  },
  {
    "path": "R/pstop.R",
    "content": "##' pStop, pWarn, pMess\n##'\n##' Custom error, warning, and message functions.\n##' @name pStop\n##' @rdname pStop\n##' @keywords internal\n##' @include package.R\n##' @param who integer or character.\n##' If \\code{who} is an integer, it is passed to \\code{\\link{sys.call}} to retrieve the name of the calling function.\n##' One can also pass the name of the calling function in \\code{who}.\n##' In either case, the name of the calling function is included in the message.\n##' @param \\dots message\nNULL\n\n##' @rdname pStop\npStop <- function (..., who = -1L) {\n  if (is.integer(who)) {\n    who <- sys.call(who)[[1]]\n  }\n  who <- as.character(who)\n  if (length(who) > 0L)\n    stop(\"in \",sQuote(who[1L]),\": \",...,call.=FALSE)\n  else\n    stop(...,call.=FALSE)\n}\n\n##' @rdname pStop\npStop_ <- function (...) {\n  pStop(...,who=NULL)\n}\n\n##' @rdname pStop\npWarn <- function (..., who = -1L) {\n  if (is.integer(who)) {\n    who <- sys.call(who)[[1]]\n  }\n  who <- as.character(who)\n  if (length(who) > 0L)\n    warning(\"in \",sQuote(who[1L]),\": \",...,call.=FALSE)\n  else\n    warning(...,call.=FALSE)\n}\n\n##' @rdname pStop\npWarn_ <- function (...) {\n  pWarn(...,who=NULL)\n}\n\n##' @rdname pStop\npMess <- function (..., who = -1L) {\n  if (is.integer(who)) {\n    who <- sys.call(who)[[1]] #nocov\n  }\n  who <- as.character(who)\n  if (length(who) > 0L)\n    message(\"NOTE: in \",sQuote(who[1L]),\": \",...)\n  else\n    message(\"NOTE: \",...)\n}\n\n##' @rdname pStop\npMess_ <- function (...) {\n  pMess(...,who=NULL)\n}\n\nundef_method <- function (method, object) {\n  o <- deparse(substitute(object))\n  pStop_(sQuote(method),\" is undefined for \",sQuote(o),\" of class \",\n    sQuote(class(object)),\".\")\n}\n\nreqd_arg <- function (method, object) {\n  if (is.null(method) || length(method)==0)\n    pStop_(sQuote(object),\" is a required argument.\")\n  else\n    pStop(who=method,sQuote(object),\" is a required argument.\")\n}\n\ninvalid_names <- function (names) {\n  is.null(names) || !all(nzchar(names)) || any(is.na(names)) || anyDuplicated(names)\n}\n"
  },
  {
    "path": "R/resample.R",
    "content": "##' Resample\n##'\n##' Systematic resampling.\n##'\n##' @return\n##' A vector of integers containing the indices of the resample.\n##'\n##' @rdname resample\n##' @name resample\n##' @keywords internal\n##' @concept sampling\n##'\n##' @param weights numeric; vector of weights.\n##' @param Np integer scalar; number of samples to draw.\n##'\nNULL\n\n##' @export\n##' @name systematic_resample\n##' @rdname resample\n##'\nsystematic_resample <- function (weights, Np = length(weights))\n  .Call(P_systematic_resampling,weights,Np)\n"
  },
  {
    "path": "R/ricker.R",
    "content": "##' Ricker model with Poisson observations.\n##'\n##' \\code{ricker} is a \\sQuote{pomp} object encoding a stochastic Ricker model\n##' with Poisson measurement error.\n##'\n##' The state process is \\eqn{N_{t+1} = r N_{t} \\exp(-c N_{t}+e_{t})}{N[t+1] =\n##' r N[t] exp(-c N[t]+e[t])}, where the \\eqn{e_t}{e[t]} are i.i.d. normal\n##' random deviates with zero mean and variance \\eqn{\\sigma^2}{sigma^2}.  The\n##' observed variables \\eqn{y_t}{y[t]} are distributed as\n##' \\eqn{\\mathrm{Poisson}(\\phi N_t)}{Poisson(phi N[t])}.\n##'\n##' @return\n##' A \\sQuote{pomp} object containing the Ricker model and simulated data.\n##'\n##' @name ricker\n##' @docType data\n##' @keywords models\n##' @family pomp examples\n##' @include pomp.R\n##' @importFrom utils read.csv2\n##'\n##' @param r  intrinsic growth rate\n##' @param c  density dependence parameter\n##' @param sigma environmental process noise s.d.\n##' @param phi sampling rate\n##' @param N_0 initial condition\n##'\n##' @example examples/ricker.R\n##' @example examples/ricker-bifdiag.R\n##'\nNULL\n\n##' @rdname ricker\n##' @export\nricker <- function (r = exp(3.8), sigma = 0.3, phi = 10, c = 1,\n  N_0 = 7)\n{\n\n  dat <- '\n\"time\";\"y\"\n0;68\n1;2\n2;87\n3;0\n4;12\n5;174\n6;0\n7;0\n8;1\n9;57\n10;11\n11;178\n12;0\n13;1\n14;0\n15;34\n16;72\n17;3\n18;101\n19;0\n20;8\n21;156\n22;0\n23;0\n24;3\n25;93\n26;0\n27;17\n28;121\n29;0\n30;0\n31;19\n32;107\n33;0\n34;4\n35;127\n36;0\n37;1\n38;47\n39;8\n40;117\n41;0\n42;3\n43;82\n44;2\n45;39\n46;70\n47;11\n48;275\n49;0\n50;0\n'\n\n  pomp(\n    data=read.csv2(text=dat),\n    times=\"time\", t0=0,\n    params=c(r=r,sigma=sigma,phi=phi,c=c,N_0=N_0,e_0=0),\n    cfile=\"ricker_source\",\n    rprocess=discrete_time(\n      step.fun=Csnippet(r\"{\n        e = (sigma > 0.0) ? rnorm(0,sigma) : 0.0;\n        N = exp(log(r)+log(N)-c*N+e);}\"),\n      delta.t=1\n    ),\n    emeasure=Csnippet(\"E_y = phi*N;\"),\n    vmeasure=Csnippet(\"V_y_y = phi*N;\"),\n    rmeasure=Csnippet(\"y = rpois(phi*N);\"),\n    dmeasure=Csnippet(\"lik = dpois(y,phi*N,give_log);\"),\n    skeleton=map(\n      Csnippet(r\"{\n        DN = exp(log(r)+log(N)-c*N);\n        De = 0.0;}\"),\n      delta.t=1),\n    partrans=parameter_trans(log=c(\"r\",\"sigma\",\"phi\",\"c\",\"N_0\")),\n    rinit=Csnippet(\"N = N_0; e = 0;\"),\n    dinit=Csnippet(\"loglik = (N == N_0) ? 0 : R_NegInf;\"),\n    paramnames=c(\"r\",\"sigma\",\"phi\",\"c\",\"N_0\"),\n    statenames=c(\"N\",\"e\")\n  )\n\n}\n"
  },
  {
    "path": "R/rinit_spec.R",
    "content": "##' rinit specification\n##'\n##' Specification of the initial-state distribution simulator, rinit.\n##'\n##' @name rinit_spec\n##' @rdname rinit_spec\n##' @family implementation information\n##' @seealso \\code{\\link{rinit}}\n##' @details\n##' To fully specify the unobserved Markov state process, one must give its distribution at the zero-time (\\code{t0}).\n##' One does this by furnishing a value for the \\code{rinit} argument.\n##' As usual, this can be provided either as a C snippet or as an \\R function.\n##' In the former case, bear in mind that:\n##' \\enumerate{\n##'   \\item The goal of a this snippet is the construction of a state vector, i.e., the setting of the dynamical states at time \\eqn{t_0}{t0}.\n##'   \\item In addition to the parameters and covariates (if any), the variable \\code{t}, containing the zero-time, will be defined in the context in which the snippet is executed.\n##'   \\item \\strong{NB:} The \\code{statenames} argument plays a particularly important role when the rinit is specified using a C snippet.\n##'    In particular, every state variable must be named in \\code{statenames}.\n##'    \\strong{Failure to follow this rule will result in undefined behavior.}\n##'  }\n##' \\link[=Csnippet]{General rules for writing C snippets can be found here}.\n##'\n##' If an \\R function is to be used, pass\n##' \\preformatted{\n##'    rinit = f\n##' }\n##' to \\code{pomp}, where \\code{f} is a function with arguments that can include the initial time \\code{t0}, any of the model parameters, and any covariates.\n##' As usual, \\code{f} may take additional arguments, provided these are passed along with it in the call to \\code{pomp}.\n##' \\code{f} must return a named numeric vector of initial states.\n##' It is of course important that the names of the states match the expectations of the other basic components.\n##'\n##' Note that the state-process \\code{rinit} can be either deterministic (as in the default) or stochastic.\n##' In the latter case, it samples from the distribution of the state process at the zero-time, \\code{t0}.\n##'\n##' @section Default behavior:\n##' By default, \\code{pomp} assumes that the initial distribution is concentrated on a single point.\n##' In particular, any parameters in \\code{params}, the names of which end in \\dQuote{\\code{_0}} or \\dQuote{\\code{.0}}, are assumed to be initial values of states.\n##' When the state process is initialized, these are simply copied over as initial conditions.\n##' The names of the resulting state variables are obtained by dropping the suffix.\n##'\n##' @inheritSection pomp Note for Windows users\n##'\n##' @example examples/rinit_spec.R\n##'\nNULL\n"
  },
  {
    "path": "R/rmeasure_spec.R",
    "content": "##' rmeasure specification\n##'\n##' Specification of the measurement-model simulator, rmeasure.\n##'\n##' @name rmeasure_spec\n##' @rdname rmeasure_spec\n##' @family implementation information\n##' @seealso \\code{\\link{rmeasure}}\n##'\n##' @details\n##' The measurement model is the link between the data and the unobserved state process.\n##' It can be specified either by using one or both of the \\code{rmeasure} and \\code{dmeasure} arguments.\n##'\n##' Suppose you have a procedure to simulate observations given the value of the latent state variables.\n##' Then you can furnish \\preformatted{\n##'   rmeasure = f}\n##' to \\pkg{pomp} algorithms,\n##' where \\code{f} is a C snippet or \\R function that implements your procedure.\n##'\n##' Using a C snippet is much preferred, due to its much greater computational efficiency.\n##' See \\code{\\link{Csnippet}} for general rules on writing C snippets.\n##'\n##' In writing an \\code{rmeasure} C snippet, bear in mind that:\n##'   \\enumerate{\n##'     \\item The goal of such a snippet is to fill the observables with random values drawn from the measurement model distribution.\n##'     Accordingly, each observable should be assigned a new value.\n##'     \\item In addition to the states, parameters, and covariates (if any), the variable \\code{t}, containing the time of the observation, will be defined in the context in which the snippet is executed.\n##'   }\n##'\n##' The demos and the tutorials on the \\href{https://kingaa.github.io/pomp/}{package website} give examples.\n##'\n##' It is also possible, though far less efficient, to specify \\code{rmeasure} using an \\R function.\n##' In this case, specify the measurement model simulator by furnishing \\preformatted{\n##'   rmeasure = f}\n##' to \\code{pomp}, where \\code{f} is an \\R function.\n##' The arguments of \\code{f} should be chosen from among the state variables, parameters, covariates, and time.\n##' It must also have the argument \\code{...}.\n##' \\code{f} must return a named numeric vector of length equal to the number of observable variables.\n##'\n##' @section Default behavior:\n##' The default \\code{rmeasure} is undefined.\n##' It will yield missing values (\\code{NA}).\n##'\n##' @inheritSection pomp Note for Windows users\n##'\n##' @example examples/rmeasure_spec.R\n##'\nNULL\n"
  },
  {
    "path": "R/rprocess_spec.R",
    "content": "##' rprocess specification\n##'\n##' Specification of the latent state process simulator, rprocess.\n##'\n##' @name rprocess_spec\n##' @rdname rprocess_spec\n##' @docType methods\n##' @include pomp_fun.R csnippet.R\n##' @family implementation information\n##' @seealso \\code{\\link{rprocess}}\n##'\n##' @section Discrete-time processes:\n##' If the state process evolves in discrete time, specify \\code{rprocess} using the \\code{discrete_time} plug-in.\n##' Specifically, provide\n##' \\preformatted{\n##'     rprocess = discrete_time(step.fun = f, delta.t),\n##' }\n##' where \\code{f} is a C snippet or \\R function that simulates one step of the state process.\n##' The former is the preferred option, due to its much greater computational efficiency.\n##' The goal of such a C snippet is to replace the state variables with their new random values at the end of the time interval.\n##' Accordingly, each state variable should be over-written with its new value.\n###' In addition to the states, parameters, covariates (if any), and observables, the variables \\code{t} and \\code{dt}, containing respectively the time at the beginning of the step and the step's duration, will be defined in the context in which the C snippet is executed.\n##' See \\code{\\link{Csnippet}} for general rules on writing C snippets.\n##' Examples are to be found in the tutorials on the \\href{https://kingaa.github.io/pomp/}{package website}.\n##'\n##' If \\code{f} is given as an \\R function, its arguments should come from the state variables, parameters, covariates, and time.\n##' It may also take the argument \\sQuote{\\code{delta.t}};\n##' when called, the latter will be the timestep.\n##' It must also have the argument \\sQuote{\\code{...}}.\n##' It should return a named vector of length equal to the number of state variables, representing a draw from the distribution of the state process at time \\code{t+delta.t} conditional on its value at time \\code{t}.\n##'\n##' @section Continuous-time processes:\n##' If the state process evolves in continuous time, but you can use an Euler approximation, implement \\code{rprocess} using the \\code{euler} plug-in.\n##' Specify\n##' \\preformatted{\n##'     rprocess = euler(step.fun = f, delta.t)\n##' }\n##' in this case.\n##' As before, \\code{f} can be provided either as a C snippet or as an \\R function, the former resulting in much quicker computations.\n##' The form of \\code{f} will be the same as above (in the discrete-time case).\n##'\n##' If you have a procedure that allows you, given the value of the state process at any time,\n##' to simulate it at an arbitrary time in the future, use the \\code{onestep} plug-in.\n##' To do so, specify\n##' \\preformatted{\n##'     rprocess = onestep(step.fun = f).\n##' }\n##' Again, \\code{f} can be provided either as a C snippet or as an \\R function, the former resulting in much quicker computations.\n##' The form of \\code{f} should be as above (in the discrete-time or Euler cases).\n##' @section Size of time step:\n##' The simulator plug-ins \\code{discrete_time}, \\code{euler}, and \\code{onestep} all work by taking discrete time steps.\n##' They differ as to how this is done.\n##' Specifically,\n##' \\enumerate{\n##' \\item \\code{onestep} takes a single step to go from any given time \\code{t1} to any later time \\code{t2} (\\code{t1 <= t2}).\n##' Thus, this plug-in is designed for use in situations where a closed-form solution to the process exists.\n##' \\item To go from \\code{t1} to \\code{t2}, \\code{euler} takes \\code{n} steps of equal size, where\n##' \\preformatted{\n##'     n = ceiling((t2-t1)/delta.t).\n##' }\n##' \\item \\code{discrete_time} assumes that the process evolves in discrete time, where the interval between successive times is \\code{delta.t}.\n##' Thus, to go from \\code{t1} to \\code{t2}, \\code{discrete_time} takes \\code{n} steps of size exactly \\code{delta.t}, where\n##' \\preformatted{\n##'     n = floor((t2-t1)/delta.t).\n##' }\n##' }\n##'\n##' @section Exact (event-driven) simulations:\n##' If you desire exact simulation of certain continuous-time Markov chains, an implementation of Gillespie's algorithm (Gillespie 1977) is available,\n##' via the \\code{gillespie} and \\code{gillespie_hl} plug-ins.\n##' The former allows for the rate function to be provided as an \\R function or a single C snippet,\n##' while the latter provides a means of specifying the elementary events via a list of C snippets.\n##'\n##' A high-level interface to the simulator is provided by \\code{gillespie_hl}.\n##' To use it, supply\n##' \\preformatted{\n##'     rprocess = gillespie_hl(..., .pre = \"\", .post = \"\", hmax = Inf)\n##' }\n##' to \\code{pomp}.\n##' Each argument in \\code{...} corresponds to a single elementary event and should be a list containing two elements.\n##' The first should be a string or C snippet;\n##' the second should be a named integer vector.\n##' The variable \\code{rate} will exist in the context of the C snippet, as will the parameter, state variables, covariates, and the time \\code{t}.\n##' The C snippet should assign to the variable \\code{rate} the corresponding elementary event rate.\n##'\n##' The named integer vector specifies the changes to the state variables corresponding to the elementary event.\n##' There should be named value for each of the state variables returned by \\code{rinit}.\n##' The arguments \\code{.pre} and \\code{.post} can be used to provide C code that will run respectively before and after the elementary-event snippets.\n##' These hooks can be useful for avoiding duplication of code that performs calculations needed to obtain several of the different event rates.\n##'\n##' Here's how a simple birth-death model might be specified:\n##' \\preformatted{\n##'     gillespie_hl(\n##'         birth=list(\"rate = b*N;\",c(N=1)),\n##'         death=list(\"rate = m*N;\",c(N=-1))\n##'     )\n##' }\n##' In the above, the state variable \\code{N} represents the population size and parameters \\code{b}, \\code{m} are the birth and death rates, respectively.\n##'\n##' To use the lower-level \\code{gillespie} interface, furnish\n##' \\preformatted{\n##'     rprocess = gillespie(rate.fun = f, v, hmax = Inf)\n##' }\n##' to \\code{pomp}, where \\code{f} gives the rates of the elementary events.\n##' Here, \\code{f} may be furnished as an \\R function or as a C snippet.\n##' If \\code{f} is an \\R function, its arguments should come from the state variables, parameters, covariates, and time.\n##' It must also have the arguments \\sQuote{\\code{j}} and \\sQuote{\\code{...}}.\n##' When \\code{f} is called,\n##' the integer \\code{j} will indicate the elementary event (corresponding to the column the matrix \\code{v}, see below).\n##' \\code{f} should return a single numerical value, representing the rate of that elementary event at that point in state space and time.\n##' If \\code{f} is supplied as a C snippet, the parameters, latent state variables, covariates, and time will be visible in the context wherein the snippet is executed, as will the integer \\sQuote{\\code{j}}.\n##' The purpose of the C snippet is to fill the double-precision variable \\sQuote{\\code{rate}} with the corresponding event rate.\n##'\n##' Here, the stoichiometric matrix \\code{v} specifies the continuous-time Markov process in terms of its elementary events.\n##' It should have dimensions \\code{nvar} x \\code{nevent}, where \\code{nvar} is the number of state variables and \\code{nevent} is the number of elementary events.\n##' \\code{v} describes the changes that occur in each elementary event:\n##' it will usually comprise the values 1, -1, and 0 according to whether a state variable is incremented, decremented, or unchanged in an elementary event.\n##' The rows of \\code{v} should have names corresponding to the state variables.\n##' If any of the row names of \\code{v} cannot be found among the state variables or if any row names of \\code{v} are duplicated, an error will occur.\n##'\n##' This lower-level interface may be preferable if it is easier to write code that calculates the correct rate based on \\code{j} rather than to write a snippet for each possible value of \\code{j}.\n##' For example, if the number of possible values of \\code{j} is large and the rates vary according to a few simple rules, the lower-level interface may provide the easier way of specifying the model.\n##'\n##' When the process is non-autonomous (i.e., the event rates depend explicitly on time), it can be useful to set \\code{hmax} to the maximum step that will be taken.\n##' By default, the elementary event rates will be recomputed at least once per observation interval.\n##'\n##' @section Default behavior:\n##' The default \\code{rprocess} is undefined.\n##' It will yield missing values (\\code{NA}) for all state variables.\n##'\n##' @param step.fun a C snippet, an R function, or\n##' the name of a native routine in a shared-object library.\n##' This gives a procedure by which one simulates a single step of the latent state process.\n##' @param delta.t positive numerical value; for \\code{euler} and \\code{discrete_time}, the size of the step to take\n##' @param rate.fun a C snippet, an R function, or\n##' the name of a native routine in a shared-object library.\n##' This gives a procedure by which one computes the event-rate of the elementary events in the continuous-time latent Markov chain.\n##' @param v integer matrix; giving the stoichiometry of the continuous-time latent Markov process.\n##' It should have dimensions \\code{nvar} x \\code{nevent}, where \\code{nvar} is the number of state variables and \\code{nevent} is the number of elementary events.\n##' \\code{v} describes the changes that occur in each elementary event:\n##' it will usually comprise the values 1, -1, and 0 according to whether a state variable is incremented, decremented, or unchanged in an elementary event.\n##' The rows of \\code{v} may be unnamed or named.\n##' If the rows are unnamed, they are assumed to be in the same order as the vector of state variables returned by \\code{rinit}.\n##' If the rows are named,\n##' the names of the state variables returned by \\code{rinit} will be matched\n##' to the rows of \\code{v} to ensure a correct mapping.\n##' If any of the row names of \\code{v} cannot be found among the state variables or if any row names of \\code{v} are duplicated, an error will occur.\n##' @param .pre,.post C snippets (see Details)\n##' @param \\dots individual C snippets corresponding to elementary events\n##' @param hmax maximum time step allowed (see below)\n##'\n##' @inheritSection pomp Note for Windows users\n##'\nNULL\n\n## also defined in 'pomp_internal.h'\nrprocmode <- list(default=0L,onestep=1L,discrete=2L,euler=3L,gillespie=4L)\n\nsetClass(\n  \"rprocPlugin\",\n  slots=c(\n    csnippet='logical',\n    slotname='character',\n    type='integer',\n    step.fn=\"ANY\",\n    rate.fn=\"ANY\"\n  ),\n  prototype=prototype(\n    csnippet=FALSE,\n    slotname=character(0),\n    type=rprocmode$default,\n    step.fn=NULL,\n    rate.fn=NULL\n  )\n)\n\n##' @rdname undefined\nsetMethod(\n  \"undefined\",\n  signature=signature(object=\"rprocPlugin\"),\n  definition=function (object, ...) {\n    undefined(object@step.fn) && undefined(object@rate.fn)\n  }\n)\n\nsetClass(\n  \"onestepRprocPlugin\",\n  contains=\"rprocPlugin\",\n  prototype=prototype(\n    type=rprocmode$onestep\n  )\n)\n\nsetClass(\n  \"discreteRprocPlugin\",\n  contains=\"rprocPlugin\",\n  slots=c(\n    delta.t=\"numeric\"\n  ),\n  prototype=prototype(\n    type=rprocmode$discrete,\n    delta.t=1.0\n  )\n)\n\nsetClass(\n  \"eulerRprocPlugin\",\n  contains=\"rprocPlugin\",\n  slots=c(\n    delta.t=\"numeric\"\n  ),\n  prototype=prototype(\n    type=rprocmode$euler,\n    delta.t=NA_real_\n  )\n)\n\nsetClass(\n  \"gillespieRprocPlugin\",\n  contains=\"rprocPlugin\",\n  slots=c(\n    hmax=\"numeric\",\n    v=\"matrix\"\n  ),\n  prototype=prototype(\n    type=rprocmode$gillespie\n  )\n)\n\nrproc_plugin <- function (object, step.fn, rate.fn) {\n  if (missing(object)) {\n    new(\"rprocPlugin\")\n  } else {\n    if (!missing(step.fn)) object@step.fn <- step.fn\n    if (!missing(rate.fn)) object@rate.fn <- rate.fn\n    object\n  }\n}\n\n##' @name onestep\n##' @rdname rprocess_spec\n##' @export\nonestep <- function (step.fun) {\n  new(\"onestepRprocPlugin\",\n    step.fn=step.fun,\n    slotname=\"step.fun\",\n    csnippet=is(step.fun,\"Csnippet\")\n  )\n}\n\n##' @rdname rprocess_spec\n##' @name discrete_time\n##' @export\ndiscrete_time <- function (step.fun, delta.t = 1) {\n  new(\"discreteRprocPlugin\",\n    step.fn=step.fun,\n    delta.t=delta.t,\n    slotname=\"step.fun\",\n    csnippet=is(step.fun,\"Csnippet\")\n  )\n}\n\n##' @rdname rprocess_spec\n##' @name euler\n##' @export\neuler <- function (step.fun, delta.t) {\n  new(\"eulerRprocPlugin\",\n    step.fn=step.fun,\n    delta.t=delta.t,\n    slotname=\"step.fun\",\n    csnippet=is(step.fun,\"Csnippet\")\n  )\n}\n\n##' @rdname rprocess_spec\n##' @name gillespie\n##' @export\ngillespie <- function (rate.fun, v, hmax = Inf) {\n  if (!is.matrix(v)) pStop(sQuote(\"v\"),\" must be a matrix.\")\n  if (anyDuplicated(rownames(v)))\n    pStop(\"duplicates in row names of \",sQuote(\"v\"),\".\")\n  if (!is.null(colnames(v)) && anyDuplicated(colnames(v)))\n    pStop(\"duplicates in column names of \",sQuote(\"v\"),\".\")\n\n  new(\"gillespieRprocPlugin\",\n    rate.fn=rate.fun,\n    v=v,\n    hmax=hmax,\n    slotname=\"rate.fun\",\n    csnippet=is(rate.fun,\"Csnippet\")\n  )\n}\n\n##' @rdname rprocess_spec\n##' @name gillespie_hl\n##' @export\ngillespie_hl <- function (..., .pre = \"\", .post = \"\", hmax = Inf) {\n\n  args <- list(...)\n\n  if (!all(vapply(args,inherits,what=\"list\",logical(1L))) ||\n        !all(vapply(args,length,integer(1L)) == 2L))\n    pStop(\"each event should be specified using a length-2 list.\")\n\n  codeChunks <- lapply(args,\"[[\",1)\n  stoich <- lapply(args,\"[[\",2)\n\n  checkCode <- function (x) {\n    inh <- inherits(x,what=c(\"Csnippet\", \"character\"))\n    if (!any(inh) || length(x) != 1)\n      pStop(who=\"gillespie_hl\",\"for each event, the first list-element should be a C snippet or string.\")\n    as(x,\"character\")\n  }\n\n  codeChunks <- lapply(codeChunks,checkCode)\n\n  if (!inherits(.pre,what=c(\"character\",\"Csnippet\")) ||\n        !inherits(.post,what=c(\"character\",\"Csnippet\")))\n    pStop(sQuote(\".pre\"),\" and \",sQuote(\".post\"),\" must be C snippets or strings.\")\n\n  .pre <- paste(as(.pre,\"character\"),collapse=\"\\n\")\n  .post <- paste(as(.post,\"character\"),collapse=\"\\n\")\n\n  if (!all(vapply(stoich,is.numeric,logical(1L))) ||\n        any(vapply(stoich,\\(x)invalid_names(names(x)),logical(1L))))\n    pStop(\"for each event, the second list-element should be \",\n      \"a named numeric vector (without duplicate names).\")\n\n  ## Create C snippet of switch statement\n  header <- paste0(.pre, \"\\nswitch (j) {\")\n  body <- paste0(\n    sprintf(\"case %d:\\n{\\n%s\\n}\\nbreak;\\n\",seq_along(codeChunks),codeChunks),\n    collapse=\"\\n\"\n  )\n  footer <- paste0(\"default:\\nerror(\\\"unrecognized event %d\\\",j);\\nbreak;\\n}\\n\",.post)\n  rate.fn <- Csnippet(paste(header, body, footer, sep=\"\\n\"))\n\n  ## now put together the stoichiometry matrix\n  if (anyDuplicated(names(stoich)))\n    pStop(\"duplicated elementary event names.\")\n  vars <- unique(do.call(c,lapply(stoich,names)))\n  v <- array(data=0,dim=c(length(vars),length(stoich)),\n    dimnames=list(name=vars,event=names(stoich)))\n  for (s in seq_along(stoich))\n    v[names(stoich[[s]]),s] <- stoich[[s]]\n\n  new(\"gillespieRprocPlugin\",\n    rate.fn=rate.fn,\n    v=v,\n    hmax=hmax,\n    slotname=\"rate.fun\",\n    csnippet=TRUE\n  )\n}\n"
  },
  {
    "path": "R/runif_design.R",
    "content": "##' @description\n##' \\code{runif_design} generates a design based on random samples from a multivariate uniform distribution.\n##' @rdname design\n##' @return\n##' \\code{runif_design} returns a data frame with \\code{nseq} rows and one column for each variable named in \\code{lower} and \\code{upper}.\n##'\n##' @export\nrunif_design <- function (lower = numeric(0), upper = numeric(0), nseq) {\n  if (length(lower)!=length(upper))\n    pStop(sQuote(\"lower\"),\" and \",sQuote(\"upper\"),\" must have same length.\")\n  lnames <- names(lower)\n  if (is.null(lnames))\n    pStop(sQuote(\"lower\"),\" and \",sQuote(\"upper\"),\" must be named vectors.\")\n  if (!all(sort(lnames)==sort(names(upper))))\n    pStop(\"names of \",sQuote(\"lower\"),\" and \",sQuote(\"upper\"),\" must match.\")\n  upper <- upper[lnames]\n  if (!all(upper>=lower))\n    pStop(\"upper values should be at least as large as lower ones.\")\n  nseq <- as.integer(nseq)\n  if (nseq < 0)\n    pStop(sQuote(\"nseq\"),\"< 0.\")\n  y <- matrix(\n    data=runif(n=nseq*length(lower),min=lower,max=upper),\n    nrow=nseq,ncol=length(lower),\n    byrow=TRUE\n  )\n  colnames(y) <- lnames\n  as.data.frame(y)\n}\n"
  },
  {
    "path": "R/rw2.R",
    "content": "##' Two-dimensional random-walk process\n##'\n##' \\code{rw2} constructs a \\sQuote{pomp} object encoding a 2-D Gaussian random walk.\n##'\n##' The random-walk process is fully but noisily observed.\n##'\n##' @name rw2\n##' @docType data\n##' @keywords models\n##' @family pomp examples\n##'\n##' @return\n##' A \\sQuote{pomp} object containing simulated data.\n##'\n##' @example examples/rw2.R\n##'\nNULL\n\n##' @rdname rw2\n##'\n##' @param x1_0,x2_0 initial conditions (i.e., latent state variable values at the zero time \\code{t0})\n##' @param s1,s2 random walk intensities\n##' @param tau observation error s.d.\n##' @param t0 zero time\n##' @param times observation times\n##' @param seed seed of the random number generator\n##'\n##' @export\nrw2 <- function (\n  x1_0 = 0, x2_0 = 0,\n  s1 = 1, s2 = 3,\n  tau = 1,\n  times = 1:100,\n  t0 = 0,\n  seed=1376784970L\n) {\n  simulate(\n    times=times,\n    t0=t0,\n    params=c(x1_0=x1_0,x2_0=x2_0,s1=s1,s2=s2,tau=tau),\n    cfile=\"rw2_source\",\n    rprocess = onestep(\n      Csnippet(\"\n        x1 = rnorm(x1,s1*sqrt(dt));\n        x2 = rnorm(x2,s2*sqrt(dt));\"\n      )\n    ),\n    dprocess = Csnippet(\"\n        double sdt = sqrt(t_2 - t_1);\n        loglik = dnorm(x1_2,x1_1,s1*sdt,1)+\n        dnorm(x2_2,x2_1,s2*sdt,1);\"\n    ),\n    emeasure=Csnippet(\"\n        E_y1 = x1;\n        E_y2 = x2;\"\n    ),\n    vmeasure=Csnippet(\"\n        V_y1_y1 = V_y2_y2 = tau*tau;\n        V_y1_y2 = V_y2_y1 = 0;\"\n    ),\n    rmeasure=Csnippet(\"\n        y1 = rnorm(x1,tau);\n        y2 = rnorm(x2,tau);\"\n    ),\n    dmeasure=Csnippet(\"\n        lik = dnorm(y1,x1,tau,1)+dnorm(y2,x2,tau,1);\n        lik = (give_log) ? lik : exp(lik);\"\n    ),\n    statenames=c(\"x1\",\"x2\"),\n    obsnames=c(\"y1\",\"y2\"),\n    paramnames=c(\"s1\",\"s2\",\"tau\"),\n    seed=seed\n  )\n}\n"
  },
  {
    "path": "R/safecall.R",
    "content": "## a class to hold unevaluated function calls\n\nsetClass(\n  \"safecall\",\n  slots=c(\n    call=\"call\",\n    envir=\"environment\"\n  ),\n  prototype=prototype(\n    call=NULL,\n    envir=NULL\n  )\n)\n\nsafecall <- function (...) {\n  new(\"safecall\",call=match.call(),envir=parent.frame())\n}\n"
  },
  {
    "path": "R/sannbox.R",
    "content": "##' Simulated annealing with box constraints.\n##'\n##' A straightforward implementation of simulated annealing with box constraints.\n##'\n##' @name sannbox\n##' @rdname sannbox\n##' @importFrom stats rnorm\n##'\n##' @details\n##' The \\code{control} argument is a list that can supply any of the following components:\n##' \\describe{\n##' \\item{trace}{ Non-negative integer.\n##' If positive, tracing information on the progress of the optimization is\n##' produced.  Higher values may produce more tracing information.  }\n##' \\item{fnscale}{ An overall scaling to be applied to the value of\n##' \\code{fn} during optimization.  If negative, turns the problem into a\n##' maximization problem.  Optimization is performed on \\code{fn(par)/fnscale}.}\n##' \\item{parscale}{ A vector of scaling values for the parameters.\n##' Optimization is performed on \\code{par/parscale} and these should be\n##' comparable in the sense that a unit change in any element produces about a\n##' unit change in the scaled value.  }\n##' \\item{maxit}{ The total number of function evaluations: there is no\n##' other stopping criterion.  Defaults to \\code{10000}.  }\n##' \\item{temp}{ starting temperature for the cooling\n##' schedule.  Defaults to \\code{1}.  }\n##' \\item{tmax}{ number of function evaluations at each temperature.\n##' Defaults to \\code{10}.  }\n##' \\item{candidate.dist}{ function to randomly select a new candidate\n##' parameter vector.  This should be a function with three arguments, the\n##' first being the current parameter vector, the second the temperature, and\n##' the third the parameter scaling.  By default, \\code{candidate.dist} is\n##' \\preformatted{function(par,temp,scale)\n##'                 rnorm(n=length(par),mean=par,sd=scale*temp).} }\n##' \\item{sched}{ cooling schedule.  A function of a three arguments giving the\n##' temperature as a function of iteration number and the control parameters\n##' \\code{temp} and \\code{tmax}.\n##' By default, \\code{sched} is\n##' \\preformatted{function(k,temp,tmax) temp/log(((k-1)\\%/\\%tmax)*tmax+exp(1)).}\n##' Alternatively, one can supply a numeric vector of temperatures.\n##' This must be of length at least \\code{maxit}. }\n##' \\item{lower,upper}{ optional\n##' numeric vectors.  These describe the lower and upper box constraints,\n##' respectively.  Each can be specified either as a single scalar (common to\n##' all parameters) or as a vector of the same length as \\code{par}.  By\n##' default, \\code{lower=-Inf} and \\code{upper=Inf}, i.e., there are no\n##' constraints.} }\n##'\n##' @param par Initial values for the parameters to be optimized over.\n##' @param fn A function to be minimized, with first argument the vector of\n##' parameters over which minimization is to take place.  It should return a\n##' scalar result.\n##' @param control A named list of control parameters.  See \\sQuote{Details}.\n##' @param \\dots ignored.\n##' @return \\code{sannbox} returns a list with components:\n##' \\describe{\n##' \\item{counts}{\n##' two-element integer vector.\n##' The first number gives the number of calls made to \\code{fn}.\n##' The second number is provided for compatibility with \\code{\\link[stats]{optim}} and will always be NA.\n##' }\n##' \\item{convergence}{\n##' provided for compatibility with \\code{\\link[stats]{optim}};\n##' will always be 0.\n##' }\n##' \\item{final.params}{last tried value of \\code{par}.}\n##' \\item{final.value}{value of \\code{fn} corresponding to\n##' \\code{final.params}.}\n##' \\item{par}{best tried value of \\code{par}.}\n##' \\item{value}{value of \\code{fn} corresponding to \\code{par}.} }\n##'\n##' @author Daniel Reuman, Aaron A. King\n##'\n##' @seealso \\link[=traj_match]{trajectory matching}, \\link[=probe_match]{probe matching}, \\link[=spect_match]{spectrum matching}, \\link[=nlf]{nonlinear forecasting}.\n##'\n##' @keywords optimize\nNULL\n\n######################\n## Simulated annealing minimizer with box constraints\n##\n## By default, the annealing schedule is\n## temp / log(((k-1) %/% tmax)*tmax + exp(1)), where\n## the parameters of this schedule can be changed via\n## the 'control' argument, and k ranges from 0 to 'maxit'\n##\n## modified from code originally written by\n## Daniel Reuman, Imperial College London\n\n##' @rdname sannbox\n##' @export\nsannbox <- function (par, fn, control = list(), ...) {\n\n  big <- 1e35  ## a very large number\n\n  npar <- length(par)\n  neval <- 0\n\n  control.default <- list(\n    maxit=10000,\n    temp=1,\n    tmax=10,\n    sched=NULL,\n    candidate.dist=NULL,\n    fnscale=1,\n    parscale=1,\n    lower=-Inf,\n    upper=Inf,\n    trace=0\n  )\n  control.default[names(control)] <- control\n  control <- control.default\n  if (is.null(control$lower)) control$lower <- -Inf\n  if (is.null(control$upper)) control$upper <- Inf\n\n  if (is.null(control$sched))           # default cooling schedule\n    control$sched <- function (k, temp, tmax) temp/log(((k-1)%/%tmax)*tmax+exp(1))\n\n  if (is.function(control$sched))\n    temps <- vapply(\n      seq_len(control$maxit),\n      FUN=control$sched,\n      FUN.VALUE=numeric(1),\n      temp=control$temp,\n      tmax=control$tmax\n    )\n  else if (is.numeric(control$sched)) {\n    temps <- control$sched\n    if (length(temps)<control$maxit)\n      pStop(\"insufficiently many temperatures supplied in \",sQuote(\"control$sched\"))\n  }\n\n  if (is.null(control$candidate.dist))\n    candidate.dist <- function (par, temp, scale)\n      rnorm(n=npar,mean=par,sd=scale*temp)\n  else if (is.function(control$candidate.dist)) {\n    candidate.dist <- control$candidate.dist\n    if (!all(c(\"par\",\"temp\",\"scale\") %in% names(formals(candidate.dist))))\n      pStop(sQuote(\"candidate.dist\"),\" must be a function of the form \",\n        sQuote(\"candidate.dist(par, temp, scale, ...)\"),\".\")\n  } else\n    pStop(sQuote(\"control$candidate.dist\"),\" must be a function.\")\n\n  if (length(control$lower)<npar)\n    control$lower <- rep(control$lower,npar)\n  if (length(control$upper)<npar)\n    control$upper <- rep(control$upper,npar)\n\n  ## initialization for the algorithm\n  thetabest <- thetacurrent <- par\n  ycurrent <- fn(thetacurrent,...)/control$fnscale\n  if (!is.finite(ycurrent)) ycurrent <- big\n  ybest <- ycurrent\n  neval <- 1\n\n  if (control$trace>0)\n    cat(\"initial evaluation: \",ycurrent,\"\\n\")\n  if (control$trace>2)\n    cat(\"initial parameters: \",thetacurrent,\"\\n\")\n\n  ## main loop\n  for (k in seq_len(control$maxit)) {\n    ## get a candidate thetacand\n    thetacand <- candidate.dist(thetacurrent,temps[k],control$parscale)\n    ## enforce box constraints\n    thetacand <- ifelse(\n      thetacand<control$lower,\n      control$lower,\n      thetacand\n    )\n    thetacand <- ifelse(\n      thetacand>control$upper,\n      control$upper,\n      thetacand\n    )\n    ycand <- fn(thetacand,...)/control$fnscale\n    if (!is.finite(ycand)) ycand <- big\n    neval <- neval+1\n\n    ## see if you have a new best.params\n    if (ycand<ybest) {\n      ybest <- ycand\n      thetabest <- thetacand\n    }\n\n    accept <- runif(1)<exp((ycurrent-ycand)/temps[k])\n    if (accept) { # simulated annealing step\n      thetacurrent <- thetacand\n      ycurrent <- ycand\n    }\n\n    if (control$trace>1)\n      cat(\"iter \",k,\" val=\",ycurrent,\", accept=\",accept,\"\\n\")\n    if (control$trace>3)\n      cat(\"proposed params: \",thetacand,\"\\n\")\n    if (control$trace>2)\n      cat(\"current params: \",thetacurrent,\"\\n\")\n\n  }\n\n  if (control$trace>0)\n    cat(\"best val=\",ybest,\"\\n\")\n\n  names(thetacurrent) <- names(thetabest) <- names(par)\n\n  list(\n    counts=c(neval,NA),\n    convergence=0,\n    final.params=thetacurrent,\n    final.value=ycurrent,\n    par=thetabest,\n    value=ybest\n  )\n}\n"
  },
  {
    "path": "R/saved_states.R",
    "content": "##' Saved states\n##'\n##' Retrieve latent state trajectories from a particle filter calculation.\n##'\n##' When one calls \\code{\\link{pfilter}} with \\code{save.states=\"filter\"} or \\code{save.states=\"prediction\"}, the latent state vector associated with each particle is saved.\n##' This can be extracted by calling \\code{saved_states} on the \\sQuote{pfilterd.pomp} object.\n##' If the filtered particles are saved, these particles are \\emph{unweighted}, saved \\emph{after} resampling using their normalized weights.\n##' If the argument  \\code{save.states=\"prediction\"} was used, the particles correspond to simulations from \\code{rprocess}, and their corresponding unnormalized weights are included in the output.\n##'\n##' @name saved_states\n##' @aliases saved_states,ANY-method saved_states,missing-method\n##' @include pfilter.R pmcmc.R melt.R\n##' @rdname saved_states\n##' @family particle filter methods\n##' @family extraction methods\n##' @inheritParams filter_mean\n##' @param format character;\n##' format of the returned object (see below).\n##'\n##' @return According to the \\code{format} argument, the saved states are returned either as a list or a data frame.\n##'\n##' If \\code{format=\"data.frame\"}, then the returned data frame holds the state variables and (optionally) the unnormalized log weight of each particle at each observation time.\n##' The \\code{.id} variable distinguishes particles.\n##'\n##' If \\code{format=\"list\"} and \\code{\\link{pfilter}} was called with \\code{save.states=\"unweighted\"} or \\code{save.states=\"TRUE\"}, the returned list contains one element per observation time.\n##' Each element consists of a matrix, with one row for each state variable and one column for each particle.\n##' If \\code{\\link{pfilter}} was called with \\code{save.states=\"weighted\"}, the list itself contains two lists:\n##' the first holds the particles as above, the second holds the corresponding unnormalized log weights.\n##' In particular, it has one element per observation time; each element is the vector of per-particle log weights.\n##'\nNULL\n\nsetGeneric(\n  \"saved_states\",\n  function (object,...) standardGeneric(\"saved_states\")\n)\n\nsetMethod(\n  \"saved_states\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"saved_states\",\"object\")\n  }\n)\n\nsetMethod(\n  \"saved_states\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"saved_states\",object)\n  }\n)\n\n##' @rdname saved_states\n##' @export\nsetMethod(\n  \"saved_states\",\n  signature=signature(object=\"pfilterd_pomp\"),\n  definition=function (object, ...,\n    format = c(\"list\",\"data.frame\")) {\n    format <- match.arg(format)\n    if (format==\"list\") {\n      object@saved.states\n    } else if (\"weights\" %in% names(object@saved.states)) {\n      s <- melt(object@saved.states$states)\n      w <- melt(object@saved.states$weights)\n      s[[object@timename]] <- time(object)[as.integer(s$.L1)]\n      w[[object@timename]] <- time(object)[as.integer(w$.L1)]\n      w$name <- \".log.weight\"\n      x <- rbind(\n        s[,c(object@timename,\".id\",\"name\",\"value\")],\n        w[,c(object@timename,\".id\",\"name\",\"value\")]\n      )\n      x <- x[order(x[[object@timename]],x$.id),]\n      row.names(x) <- NULL\n      x\n    } else {\n      s <- melt(object@saved.states)\n      s[[object@timename]] <- time(object)[as.integer(s$.L1)]\n      s <- s[,c(object@timename,\".id\",\"name\",\"value\")]\n      row.names(s) <- NULL\n      s\n    }\n  }\n)\n\n##' @rdname saved_states\n##' @export\nsetMethod(\n  \"saved_states\",\n  signature=signature(object=\"pfilterList\"),\n  definition=function (object, ...,\n    format = c(\"list\",\"data.frame\")) {\n    format <- match.arg(format)\n    x <- lapply(object,saved_states,...,format=format)\n    if (format == \"data.frame\") {\n      x <- rbind_fill(x,.id=\".L1\")\n    }\n    x\n  }\n)\n"
  },
  {
    "path": "R/show.R",
    "content": "##' Show methods\n##'\n##' Display the object, according to its class.\n##'\n##' @name show\n##' @rdname show\n##' @docType methods\n##' @keywords internal\n##' @include pomp_class.R abc.R bsmc2.R kalman.R mif2.R nlf.R pfilter.R\n##' @include pmcmc.R probe.R spect.R\n##' @include probe_match.R traj_match.R spect_match.R\nNULL\n\nsetClassUnion(\"unshowable\",members=c(\"pomp\",\"abcd_pomp\",\"bsmcd_pomp\",\n  \"kalmand_pomp\",\"mif2d_pomp\",\"pfilterd_pomp\",\"pmcmcd_pomp\",\n  \"probed_pomp\",\"spectd_pomp\",\"probe_match_objfun\",\"spect_match_objfun\",\n  \"nlf_objfun\",\"traj_match_objfun\"))\n\n##' @rdname show\n##' @export\nsetMethod(\n  \"show\",\n  signature=signature(object=\"unshowable\"),\n  definition=function (object) {\n    cat(\"<object of class \",sQuote(as.character(class(object))),\">\\n\",sep=\"\")\n    invisible(NULL)\n  }\n)\n\n##' @rdname show\n##' @include listie.R\n##' @export\nsetMethod(\n  \"show\",\n  signature=signature(object=\"listie\"),\n  definition=function (object) {\n    y <- as(object,\"list\")\n    names(y) <- names(object)\n    show(y)\n  }\n)\n\n##' @rdname show\n##' @include rprocess_spec.R\n##' @export\nsetMethod(\n  \"show\",\n  signature=signature(object=\"rprocPlugin\"),\n  definition=function (object) {\n    cat(\"<undefined>\\n\")\n  }\n)\n\n##' @rdname show\n##' @include rprocess_spec.R\n##' @export\nsetMethod(\n  \"show\",\n  signature=signature(object=\"onestepRprocPlugin\"),\n  definition=function (object) {\n    cat(\"one-step process-model simulator\\n\")\n    cat(\"  - step.fun: \")\n    show(object@step.fn)\n  }\n)\n\n##' @rdname show\n##' @include rprocess_spec.R\n##' @export\nsetMethod(\n  \"show\",\n  signature=signature(object=\"discreteRprocPlugin\"),\n  definition=function (object) {\n    cat(\"discrete-time process-model simulator\\n\")\n    cat(\"  - timestep =\",object@delta.t,\"\\n\")\n    cat(\"  - step.fun: \")\n    show(object@step.fn)\n  }\n)\n\n##' @rdname show\n##' @include rprocess_spec.R\n##' @export\nsetMethod(\n  \"show\",\n  signature=signature(object=\"eulerRprocPlugin\"),\n  definition=function (object) {\n    cat(\"Euler-method process-model simulator\\n\")\n    cat(\"  - timestep =\",object@delta.t,\"\\n\")\n    cat(\"  - step.fun: \")\n    show(object@step.fn)\n  }\n)\n\n##' @rdname show\n##' @include rprocess_spec.R\n##' @export\nsetMethod(\n  \"show\",\n  signature=signature(object=\"gillespieRprocPlugin\"),\n  definition=function (object) {\n    cat(\"Gillespie-method process-model simulator\\n\")\n    cat(\"  - stoichiometry matrix:\\n\")\n    print(object@v)\n    cat(\"  - rate.fun: \")\n    show(object@rate.fn)\n  }\n)\n\n##' @rdname show\n##' @include pomp_fun.R\n##' @export\nsetMethod(\n  \"show\",\n  signature=signature(\"pomp_fun\"),\n  definition=function (object) {\n\n    mode <- object@mode\n\n    if (mode==pompfunmode$Rfun) { # R function\n\n      cat(\"R function\\n  - definition: \")\n      f <- object@R.fun\n      environment(f) <- globalenv()\n      print(f)\n\n    } else if (mode==pompfunmode$native) { # user supplied native code\n\n      cat(\"native function\\n  - name: \",sQuote(object@native.fun),\"\\n\",sep=\"\")\n      if (length(object@PACKAGE)>0)\n        cat(\"  - dynamically loaded from: \",sQuote(object@PACKAGE),sep=\"\")\n\n    } else if (mode==pompfunmode$regNative) { # built from C snippets\n\n      cat(\"native function\\n  - name: \",sQuote(object@native.fun),\"\\n\",sep=\"\")\n      if (length(object@PACKAGE)>0)\n        cat(\"  - defined by a C snippet in library \",sQuote(object@PACKAGE),sep=\"\")\n\n    } else {\n\n      cat(\"<default>\")\n\n    }\n    cat(\"\\n\")\n  }\n)\n\n##' @rdname show\n##' @include parameter_trans.R\n##' @export\nsetMethod(\n  \"show\",\n  signature=signature(object=\"partransPlugin\"),\n  definition=function (object) {\n    if (object@has) {\n      cat(\"  - to estimation scale: \")\n      show(object@to)\n      cat(\"  - from estimation scale: \")\n      show(object@from)\n    } else {\n      cat(\"  - to estimation scale: <identity>\\n\")\n      cat(\"  - from estimation scale: <identity>\\n\")\n    }\n  }\n)\n\n##' @rdname show\n##' @include covariate_table.R\n##' @export\nsetMethod(\n  \"show\",\n  signature=signature(object=\"covartable\"),\n  definition=function (object) {\n    if (length(object@times)>0) {\n      cat(\"\\n  -\",ncol(object@table),\"records of\",\n        nrow(object@table),\"covariates,\",\n        \"recorded from t =\",min(object@times),\n        \"to\",max(object@times),\"\\n\")\n      cat(\"  - summary of covariates:\\n\")\n      print(summary(as.data.frame(t(object@table))))\n    } else {\n      cat(\"<none>\\n\")\n    }\n  }\n)\n\n##' @rdname show\n##' @include skeleton_spec.R\n##' @export\nsetMethod(\n  \"show\",\n  signature=signature(object=\"skelPlugin\"),\n  definition=function (object) {\n    cat(\"<default>\\n\\n\")\n  }\n)\n\n##' @rdname show\n##' @include skeleton_spec.R\n##' @export\nsetMethod(\n  \"show\",\n  signature=signature(object=\"vectorfieldPlugin\"),\n  definition=function (object) {\n    cat(\"vectorfield:\\n  - \")\n    show(object@skel.fn)\n  }\n)\n\n##' @rdname show\n##' @include skeleton_spec.R\n##' @export\nsetMethod(\n  \"show\",\n  signature=signature(object=\"mapPlugin\"),\n  definition=function (object) {\n    cat(\"map:\\n\")\n    cat(\"  - timestep =\",object@delta.t,\"\\n\")\n    cat(\"  - \")\n    show(object@skel.fn)\n  }\n)\n"
  },
  {
    "path": "R/simulate.R",
    "content": "##' Simulations of a partially-observed Markov process\n##'\n##' \\code{simulate} generates simulations of the state and measurement\n##' processes.\n##'\n##' @name simulate\n##' @docType methods\n##' @rdname simulate\n##' @include workhorses.R pomp_class.R pomp.R\n##' @author Aaron A. King\n##' @family elementary algorithms\n##' @inheritSection pomp Note for Windows users\n##' @inheritParams pomp\n##' @param object optional;\n##' if present, it should be a data frame or a \\sQuote{pomp} object.\n##' @param params a named numeric vector or a matrix with rownames\n##' containing the parameters at which the simulations are to be performed.\n##' @param nsim The number of simulations to perform.\n##' Note that the number of replicates will be \\code{nsim} times \\code{ncol(params)}.\n##' @param seed optional integer;\n##' if set, the pseudorandom number generator (RNG) will be initialized with \\code{seed}.\n##' The RNG will be restored to its original state afterward.\n##' @param format the format in which to return the results.\n##'\n##' \\code{format = \"pomps\"} causes the results to be returned as a single \\dQuote{pomp} object, if \\code{params} is a vector, or a list of \\dQuote{pomp} objects, if \\code{params} is a matrix with more than one column.\n##' Each of these will be identical to \\code{object} except in that the latent states and observations will have been replaced by their simulated values.\n##'\n##' \\code{format = \"arrays\"} causes the results to be returned as a list of two arrays.\n##' The \\dQuote{states} element will contain the simulated state trajectories in a rank-3 array with dimensions\n##' \\code{nvar} x \\code{(ncol(params)*nsim)} x \\code{ntimes}.\n##' Here, \\code{nvar} is the number of state variables and \\code{ntimes} the length of the argument \\code{times}.\n##' The \\dQuote{obs} element will contain the simulated data, returned as a rank-3 array with dimensions\n##' \\code{nobs} x \\code{(ncol(params)*nsim)} x \\code{ntimes}.\n##' Here, \\code{nobs} is the number of observables.\n##'\n##' \\code{format = \"data.frame\"} causes the results to be returned as a single data frame containing\n##' the time, states, and observations.\n##' An ordered factor variable, \\sQuote{.id}, distinguishes one simulation from another.\n##'\n##' @param include.data if \\code{TRUE}, the original data and covariates (if any) are included (with \\code{.id = \"data\"}).\n##' This option is ignored unless \\code{format = \"data.frame\"}.\n##' @param ... additional arguments are passed to \\code{\\link{pomp}}.\n##'\n##' @return\n##' A single \\dQuote{pomp} object,\n##' a \\dQuote{pompList} object,\n##' a named list of two arrays,\n##' or a data frame, according to the \\code{format} option.\n##'\n##' If \\code{params} is a matrix, each column is treated as a distinct parameter set.\n##' In this case, if \\code{nsim=1},\n##' then \\code{simulate} will return one simulation for each parameter set.\n##' If \\code{nsim>1},\n##' then \\code{simulate} will yield \\code{nsim} simulations for each parameter set.\n##' These will be ordered such that\n##' the first \\code{ncol(params)} simulations represent one simulation\n##' from each of the distinct parameter sets,\n##' the second \\code{ncol(params)} simulations represent a second simulation from each,\n##' and so on.\n##'\n##' Adding column names to \\code{params} can be helpful.\n##'\nNULL\n\n##' @importFrom stats simulate\nsetGeneric(\"simulate\")\n\n##' @rdname simulate\n##' @export\nsetMethod(\n  \"simulate\",\n  signature=signature(object=\"missing\"),\n  definition=function (\n    object,\n    nsim = 1,\n    seed = NULL,\n    ...,\n    times, t0,\n    params, rinit, rprocess, rmeasure,\n    format = c(\"pomps\", \"arrays\", \"data.frame\"),\n    include.data = FALSE,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      simulate_internal(\n        object=NULL,\n        ...,\n        nsim=nsim,\n        seed=seed,\n        times=times,\n        t0=t0,\n        params=params,\n        rinit=rinit,\n        rprocess=rprocess,\n        rmeasure=rmeasure,\n        format=match.arg(format),\n        include.data=include.data,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"simulate\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname simulate\n##' @export\nsetMethod(\n  \"simulate\",\n  signature=signature(object=\"data.frame\"),\n  definition=function (\n    object,\n    nsim = 1,\n    seed = NULL,\n    ...,\n    times, t0,\n    params, rinit, rprocess, rmeasure,\n    format = c(\"pomps\", \"arrays\", \"data.frame\"),\n    include.data = FALSE,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      simulate_internal(\n        object,\n        ...,\n        nsim=nsim,\n        seed=seed,\n        times=times,\n        t0=t0,\n        params=params,\n        rinit=rinit,\n        rprocess=rprocess,\n        rmeasure=rmeasure,\n        format=match.arg(format),\n        include.data=include.data,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"simulate\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname simulate\n##' @export\nsetMethod(\n  \"simulate\",\n  signature=signature(object=\"pomp\"),\n  definition=function (\n    object,\n    nsim = 1,\n    seed = NULL,\n    ...,\n    format = c(\"pomps\", \"arrays\", \"data.frame\"),\n    include.data = FALSE,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      simulate_internal(\n        object,\n        ...,\n        nsim=nsim,\n        seed=seed,\n        format=match.arg(format),\n        include.data=include.data,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"simulate\",conditionMessage(e))\n    )\n\n  }\n)\n\nsimulate_internal <- function (\n  object,\n  ...,\n  nsim = 1L,\n  seed = NULL,\n  params,\n  format,\n  include.data = FALSE,\n  .gnsi = TRUE,\n  verbose\n) {\n\n  object <- pomp(object,...,verbose=verbose)\n\n  if (undefined(object@rprocess)) pStop_(sQuote(\"rprocess\"),\" is undefined.\")\n\n  include.data <- as.logical(include.data)\n\n  if (length(nsim)!=1 || !is.numeric(nsim) || !is.finite(nsim) || nsim < 1)\n    pStop_(sQuote(\"nsim\"),\" must be a positive integer.\")\n  nsim <- as.integer(nsim)\n\n  if (missing(params)) params <- coef(object)\n  if (is.list(params)) params <- unlist(params)\n  if (is.null(params)) params <- numeric(0)\n  if (!is.numeric(params))\n    pStop_(sQuote(\"params\"),\" must be named and numeric.\")\n  params <- as.matrix(params)\n  storage.mode(params) <- \"double\"\n\n  if (ncol(params) == 1L) coef(object) <- params[,1L]\n\n  pompLoad(object,verbose=verbose)\n  on.exit(pompUnload(object,verbose=verbose))\n\n  return.type <- switch(format,arrays=0L,data.frame=0L,pomps=1L)\n\n  sims <- freeze(\n    .Call(P_do_simulate,object,params,nsim,return.type,.gnsi),\n    seed=seed\n  )\n\n  if (format == \"data.frame\") {\n\n    nsims <- ncol(sims$states)\n    ntimes <- length(time(object))\n    simnames <- colnames(sims$states)\n    if (is.null(simnames)) simnames <- seq_len(nsims)\n\n    dm <- dim(sims$states)\n    nm <- rownames(sims$states)\n    dim(sims$states) <- c(dm[1L],prod(dm[-1L]))\n    rownames(sims$states) <- nm\n\n    dm <- dim(sims$obs)\n    nm <- rownames(sims$obs)\n    dim(sims$obs) <- c(dm[1L],prod(dm[-1L]))\n    rownames(sims$obs) <- nm\n\n    sims <- cbind(\n      time=rep(time(object),each=length(simnames)),\n      as.data.frame(t(sims$states)),\n      as.data.frame(t(sims$obs)),\n      .id=rep(simnames,times=ntimes)\n    )\n\n    names(sims)[[1]] <- object@timename\n\n    if (include.data) {\n      dat <- as.data.frame(object)\n      dat$.id <- \"data\"\n      allnm <- union(names(dat),names(sims))\n      for (n in setdiff(allnm,names(dat))) dat[[n]] <- NA\n      for (n in setdiff(allnm,names(sims))) sims[[n]] <- rep(dat[[n]],each=nsim)\n      sims <- rbind(dat,sims)\n      sims$.id <- ordered(sims$.id,levels=c(\"data\",simnames))\n    } else {\n      sims$.id <- ordered(sims$.id,levels=simnames)\n    }\n    othernm <- setdiff(names(sims),c(object@timename,\".id\"))\n    sims <- sims[,c(object@timename,\".id\",othernm)]\n\n  } else if (format == \"pomps\") {\n\n    if (length(sims) == 1) sims <- sims[[1]]\n    else sims <- do.call(concat,sims)\n\n  }\n\n  sims\n\n}\n"
  },
  {
    "path": "R/sir.R",
    "content": "##' Compartmental epidemiological models\n##'\n##' Simple SIR-type models implemented in various ways.\n##'\n##' \\code{sir()} producees a \\sQuote{pomp} object encoding a simple seasonal SIR model with simulated data.\n##' Simulation is performed using an Euler multinomial approximation.\n##'\n##' \\code{sir2()} has the same model implemented using Gillespie's algorithm.\n##'\n##' In both cases the measurement model is negative binomial:\n##' \\code{reports} is distributed as a negative binomial random variable with mean equal to \\code{rho*cases} and size equal to \\code{1/k}.\n##'\n##' This and similar examples are discussed and constructed in tutorials\n##' available on the \\href{https://kingaa.github.io/pomp/}{package website}.\n##'\n##' @name compartmental_models\n##' @aliases SIR_models\n##' @rdname sir\n##' @aliases sir sir2\n##' @docType data\n##' @keywords models\n##' @family pomp examples\n##' @return\n##' These functions return \\sQuote{pomp} objects containing simulated data.\n##'\n##' @example examples/sir.R\n##'\nNULL\n\n##' @rdname sir\n##' @param gamma recovery rate\n##' @param mu death rate (assumed equal to the birth rate)\n##' @param iota infection import rate\n##' @param rho reporting efficiency\n##' @param k reporting overdispersion parameter (reciprocal of the negative-binomial \\emph{size} parameter)\n##' @param pop overall host population size\n##' @param S_0,I_0,R_0 the fractions of the host population that are susceptible, infectious, and recovered, respectively, at time zero.\n##' @param beta1,beta2,beta3 seasonal contact rates\n##' @param beta_sd environmental noise intensity\n##' @param t0 zero time\n##' @param times observation times\n##' @param seed seed of the random number generator\n##' @param delta.t Euler step size\n##' @export\nsir <- function (\n  gamma = 26, mu = 0.02, iota = 0.01,\n  beta1 = 400, beta2 = 480, beta3 = 320,\n  beta_sd = 1e-3, rho = 0.6, k = 0.1,\n  pop = 2.1e6,\n  S_0 = 26/400, I_0 = 0.001, R_0 = 1-S_0-I_0,\n  t0 = 0,\n  times = seq(from = t0 + 1/52, to = t0 + 4, by = 1/52),\n  seed=329343545, delta.t = 1/52/20\n) {\n\n  tt0 <- t0\n  tt <- times\n\n  simulate(\n    times=tt,t0=tt0,\n    seed=seed,\n    params=c(\n      gamma=gamma,mu=mu,iota=iota,\n      beta1=beta1,beta2=beta2,beta3=beta3,\n      beta_sd=beta_sd,rho=rho,k=k,\n      pop=pop,\n      S_0=S_0,I_0=I_0,R_0=R_0\n    ),\n    covar=covariate_table(\n      t=seq(from=tt0,to=max(tt)+0.2,by=0.01),\n      seas=periodic_bspline_basis(\n        x=t,\n        period=1,\n        nbasis=3,\n        degree=3\n      ),\n      times=\"t\"\n    ),\n    cfile=\"sir_source\",\n    globals=Csnippet(\"\n      static int nbasis = 3;\"\n    ),\n    rinit=Csnippet(\"\n      double m = pop/(S_0+I_0+R_0);\n      S = nearbyint(m*S_0);\n      I = nearbyint(m*I_0);\n      R = nearbyint(m*R_0);\n      cases = 0;\n      W = 0;\"\n    ),\n    rprocess=euler(\n      step.fun=Csnippet(\"\n        int nrate = 6;\n        double rate[nrate];               // transition rates\n        double trans[nrate];            // transition numbers\n        double beta;\n        double dW;\n\n        beta = dot_product(nbasis,&beta1,&seas_1);\n\n        // gamma noise, mean=dt, variance=(beta_sd^2 dt)\n        dW = rgammawn(beta_sd,dt);\n\n        // compute the transition rates\n        rate[0] = mu*pop;               // birth into susceptible class\n        rate[1] = (iota+beta*I*dW/dt)/pop; // force of infection\n        rate[2] = mu;                   // death from susceptible class\n        rate[3] = gamma;        // recovery\n        rate[4] = mu;                   // death from infectious class\n        rate[5] = mu;           // death from recovered class\n\n        // compute the transition numbers\n        trans[0] = rpois(rate[0]*dt);   // births are Poisson\n        reulermultinom(2,S,&rate[1],dt,&trans[1]);\n        reulermultinom(2,I,&rate[3],dt,&trans[3]);\n        reulermultinom(1,R,&rate[5],dt,&trans[5]);\n\n        // balance the equations\n        S += trans[0]-trans[1]-trans[2];\n        I += trans[1]-trans[3]-trans[4];\n        R += trans[3]-trans[5];\n        cases += trans[3];              // cases are cumulative recoveries\n        if (beta_sd > 0.0)  W += (dW-dt)/beta_sd;\"\n      ),\n      delta.t=delta.t\n    ),\n    skeleton=vectorfield(Csnippet(\"\n      int nrate = 6;\n      double rate[nrate];                 // transition rates\n      double term[nrate];               // terms in the equations\n      double beta;\n      double dW;\n\n      beta = dot_product(nbasis,&beta1,&seas_1);\n\n      // compute the transition rates\n      rate[0] = mu*pop;         // birth into susceptible class\n      rate[1] = (iota+beta*I)/pop; // force of infection\n      rate[2] = mu;                     // death from susceptible class\n      rate[3] = gamma;  // recovery\n      rate[4] = mu;                     // death from infectious class\n      rate[5] = mu;             // death from recovered class\n\n      // compute the several terms\n      term[0] = rate[0];\n      term[1] = rate[1]*S;\n      term[2] = rate[2]*S;\n      term[3] = rate[3]*I;\n      term[4] = rate[4]*I;\n      term[5] = rate[5]*R;\n\n      // balance the equations\n      DS = term[0]-term[1]-term[2];\n      DI = term[1]-term[3]-term[4];\n      DR = term[3]-term[5];\n      Dcases = term[3];         // accumulate the new I->R transitions\n      DW = 0;                   // no noise, so no noise accumulation\"\n    )\n    ),\n    emeasure=Csnippet(\"\n      E_reports = cases*rho;\"\n    ),\n    vmeasure=Csnippet(\"\n      double mean = cases*rho;\n      V_reports_reports = mean*(1+k*mean);\"\n    ),\n    rmeasure=Csnippet(\"\n      reports = rnbinom_mu(1.0/k,cases*rho);\"\n    ),\n    dmeasure=Csnippet(\"\n      lik = dnbinom_mu(nearbyint(reports),1.0/k,cases*rho,give_log);\"\n    ),\n    partrans=parameter_trans(\n      fromEst=Csnippet(\"\n        int j;\n        const double *TBETA = &T_beta1;\n        double *BETA = &beta1;\n        for (j = 0; j < nbasis; j++) BETA[j] = exp(TBETA[j]);\"\n      ),\n      toEst=Csnippet(\"\n        int j;\n        const double *BETA = &beta1;\n        double *TBETA = &T_beta1;\n        for (j = 0; j < nbasis; j++) TBETA[j] = log(BETA[j]);\"\n      ),\n      log=c(\"gamma\",\"mu\",\"iota\",\"beta_sd\",\"k\"),\n      logit=\"rho\",\n      barycentric=c(\"S_0\",\"I_0\",\"R_0\")\n    ),\n    statenames=c(\"S\",\"I\",\"R\",\"cases\",\"W\"),\n    obsnames=\"reports\",\n    paramnames=c(\n      \"gamma\",\"mu\",\"iota\",\n      \"beta1\",\"beta_sd\",\"pop\",\"rho\",\"k\",\n      \"S_0\",\"I_0\",\"R_0\"\n    ),\n    accumvars=c(\"cases\")\n  )\n}\n\n##' @name sir2\n##' @rdname sir\n##' @export\nsir2 <- function (\n  gamma = 24, mu = 1/70, iota = 0.1,\n  beta1 = 330, beta2 = 410, beta3 = 490,\n  rho = 0.1, k = 0.1, pop = 1e6,\n  S_0 = 0.05, I_0 = 0.0001, R_0 = 1 - S_0 - I_0,\n  t0 = 0,\n  times = seq(from = t0 + 1/12, to = t0 + 10, by=1/12),\n  seed=1772464524\n) {\n\n  tt0 <- t0\n  tt <- times\n\n  simulate(\n    times=tt,t0=tt0,\n    seed=seed,\n    params=c(\n      gamma=gamma,mu=mu,iota=iota,rho=rho,k=k,\n      beta1=beta1,beta2=beta2,beta3=beta3,\n      S_0=S_0,I_0=I_0,R_0=R_0,\n      pop=pop\n    ),\n    cfile=\"sir2_source\",\n    covar=covariate_table(\n      t=seq(tt0,max(tt)+0.2,by=0.01),\n      seas=periodic_bspline_basis(\n        x=t,\n        period=1,\n        nbasis=3,\n        degree=3\n      ),\n      times=\"t\"\n    ),\n    globals=Csnippet(\"static int nbasis = 3;\"),\n    rprocess=gillespie_hl(\n      .pre=\"double beta;\",\n      birth=list(\n        \"rate = mu*pop;\",\n        c(S=1,I=0,R=0,N=1,cases=0)),\n      susc.death=list(\n        \"rate = mu*S;\",\n        c(S=-1,I=0,R=0,N=-1,cases=0)),\n      infection=list(\"\n      beta = dot_product(nbasis,&beta1,&seas_1);\n      rate = (beta*I+iota)*S/pop;\",\n      c(S=-1,I=1,N=0,R=0,cases=0)),\n      inf.death=list(\n        \"rate = mu*I;\",\n        c(S=0,I=-1,R=0,N=-1,cases=0)),\n      recovery=list(\n        \"rate = gamma*I;\",\n        c(S=0,I=-1,R=1,N=0,cases=1)),\n      recov.death=list(\n        \"rate = mu*R;\",\n        c(S=0,I=0,R=-1,N=-1,cases=0)),\n      hmax=0.05),\n    skeleton=vectorfield(\n      Csnippet(\"\n        int nrate = 6;\n        double rate[nrate];\n        double term[nrate];\n        double beta;\n\n        beta = dot_product(nbasis,&beta1,&seas_1);\n\n        rate[0] = mu*pop;\n        rate[1] = (iota+beta*I)/pop;\n        rate[2] = mu;\n        rate[3] = gamma;\n        rate[4] = mu;\n        rate[5] = mu;\n\n        term[0] = rate[0];\n        term[1] = rate[1]*S;\n        term[2] = rate[2]*S;\n        term[3] = rate[3]*I;\n        term[4] = rate[4]*I;\n        term[5] = rate[5]*R;\n\n        DS = term[0]-term[1]-term[2];\n        DI = term[1]-term[3]-term[4];\n        DR = term[3]-term[5];\n        DN = term[0]-term[2]-term[4]-term[5];\n        Dcases = term[3];\"\n      )\n    ),\n    emeasure=Csnippet(\"\n      E_reports = cases*rho;\"\n    ),\n    vmeasure=Csnippet(\"\n      double mean = cases*rho;\n      V_reports_reports = mean*(1+k*mean);\"\n    ),\n    rmeasure=Csnippet(\"\n      reports = rnbinom_mu(1.0/k,cases*rho);\"\n    ),\n    dmeasure=Csnippet(\"\n      lik = dnbinom_mu(nearbyint(reports),1.0/k,cases*rho,give_log);\"\n    ),\n    statenames=c(\"S\",\"I\",\"R\",\"N\",\"cases\"),\n    obsnames=\"reports\",\n    paramnames=c(\n      \"gamma\",\"mu\",\"iota\",\"pop\",\"rho\",\"k\",\n      \"beta1\",\"beta2\",\"beta3\",\n      \"S_0\",\"I_0\",\"R_0\"\n    ),\n    accumvars=c(\"cases\"),\n    partrans=parameter_trans(\n      log=c(\"gamma\",\"mu\",\"iota\",\"k\",sprintf(\"beta%d\",1:3)),\n      logit=\"rho\",\n      barycentric=c(\"S_0\",\"I_0\",\"R_0\")\n    ),\n    rinit=Csnippet(\"\n      double m;\n      m = pop/(S_0+I_0+R_0);\n      S = nearbyint(m*S_0);\n      I = nearbyint(m*I_0);\n      N = nearbyint(pop);\n      R = nearbyint(m*R_0);\n      cases = 0;\"\n    )\n  )\n\n}\n"
  },
  {
    "path": "R/skeleton_spec.R",
    "content": "##' skeleton specification\n##'\n##' Specification of the deterministic skeleton.\n##'\n##' @name skeleton_spec\n##' @rdname skeleton_spec\n##' @docType methods\n##' @include pomp_fun.R csnippet.R\n##' @family implementation information\n##' @family deterministic methods\n##' @seealso \\code{\\link{skeleton}}\n##'\n##' @inheritSection pomp Note for Windows users\n##'\n##' @details\n##' The skeleton is a dynamical system that expresses the central tendency of the unobserved Markov state process.\n##' As such, it is not uniquely defined, but can be both interesting in itself and useful in practice.\n##' In \\pkg{pomp}, the skeleton is used by \\code{\\link{trajectory}} and \\code{\\link{traj_objfun}}.\n##'\n##' If the state process is a discrete-time stochastic process, then the skeleton is a discrete-time map.\n##' To specify it, provide \\preformatted{\n##'   skeleton = map(f, delta.t)}\n##' to \\code{pomp}, where \\code{f} implements the map and \\code{delta.t} is the size of the timestep covered at one map iteration.\n##'\n##' If the state process is a continuous-time stochastic process, then the skeleton is a vectorfield (i.e., a system of ordinary differential equations).\n##' To specify it, supply \\preformatted{\n##'   skeleton = vectorfield(f)}\n##' to \\code{pomp}, where \\code{f} implements the vectorfield, i.e., the right-hand-size of the differential equations.\n##'\n##' In either case, \\code{f} can be furnished either as a C snippet (the preferred choice), or an \\R function.\n##' \\link[=Csnippet]{General rules for writing C snippets can be found here}.\n##' In writing a \\code{skeleton} C snippet, be aware that:\n##' \\enumerate{\n##'   \\item For each state variable, there is a corresponding component of the deterministic skeleton.\n##'   The goal of such a snippet is to compute all the components.\n##'   \\item When the skeleton is a map, the component corresponding to state variable \\code{x} is named \\code{Dx} and is the new value of \\code{x} after one iteration of the map.\n##'   \\item When the skeleton is a vectorfield, the component corresponding to state variable \\code{x} is named \\code{Dx} and is the value of \\eqn{dx/dt}.\n##'   \\item As with the other C snippets, all states, parameters and covariates, as well as the current time, \\code{t}, will be defined in the context within which the snippet is executed.\n##'   \\item \\bold{NB:} When the skeleton is a map, the duration of the timestep will \\bold{not} be defined in the context within which the snippet is executed.\n##'   When the skeleton is a vectorfield, of course, no timestep is defined.\n##'   In this regard, C snippets for the skeleton and rprocess components differ.\n##' }\n##' The tutorials on the \\href{https://kingaa.github.io/pomp/}{package website} give some examples.\n##'\n##' If \\code{f} is an \\R function, its arguments should be taken from among the state variables, parameters, covariates, and time.\n##' It must also take the argument \\sQuote{\\code{...}}.\n##' As with the other basic components, \\code{f} may take additional arguments, provided these are passed along with it in the call to \\code{pomp}.\n##' The function \\code{f} must return a numeric vector of the same length as the number of state variables, which contains the value of the map or vectorfield at the required point and time.\n##'\n##' @section Masking of \\code{map}:\n##' Other packages (most notably the \\pkg{tidyverse} package \\pkg{purrr}) have functions named \\sQuote{map}.\n##' Beware that, if you load one of these packages after you load \\pkg{pomp}, the \\pkg{pomp} function \\code{map} described here will be masked.\n##' You can always access the \\pkg{pomp} function by calling \\code{pomp::map}.\n##'\n##' @section Default behavior:\n##' The default \\code{skeleton} is undefined.\n##' It will yield missing values (\\code{NA}) for all state variables.\n##'\n##' @example examples/skeleton_spec.R\n##'\nNULL\n\nskeletontype <- list(undef=0L,vectorfield=1L,map=2L)\n\nsetClass(\n  \"skelPlugin\",\n  slots=c(\n    csnippet='logical',\n    type='integer',\n    skel.fn=\"ANY\"\n  ),\n  prototype=prototype(\n    csnippet=FALSE,\n    type=skeletontype$undef,\n    skel.fn=NULL\n  )\n)\n\n##' @rdname undefined\nsetMethod(\n  \"undefined\",\n  signature=signature(object=\"skelPlugin\"),\n  definition=function (object, ...) {\n    object@type==skeletontype$undef || undefined(object@skel.fn)\n  }\n)\n\nsetClass(\n  \"vectorfieldPlugin\",\n  contains=\"skelPlugin\",\n  prototype=prototype(\n    type=skeletontype$vectorfield\n  )\n)\n\nsetClass(\n  \"mapPlugin\",\n  contains=\"skelPlugin\",\n  slots=c(\n    delta.t=\"numeric\"\n  ),\n  prototype=prototype(\n    type=skeletontype$map,\n    delta.t=1.0\n  )\n)\n\nskel_plugin <- function (object, skel.fn) {\n  if (missing(object)) {\n    new(\"skelPlugin\")\n  } else {\n    if (!missing(skel.fn)) object@skel.fn <- skel.fn\n    object\n  }\n}\n\n##' @rdname skeleton_spec\n##' @param f procedure for evaluating the deterministic skeleton\n##' This can be a C snippet, an \\R function, or the name of a native routine in a dynamically linked library.\n##' @export\nvectorfield <- function (f) {\n  new(\"vectorfieldPlugin\",skel.fn=f)\n}\n\n##' @rdname skeleton_spec\n##' @param delta.t positive numerical value; the size of the discrete time step corresponding to an application of the map\n##' @export\nmap <- function (f, delta.t = 1) {\n  if (!isTRUE(length(delta.t)==1 && is.finite(delta.t) && delta.t > 0))\n    pStop(sQuote(\"delta.t\"),\" must be a positive number.\")\n  new(\"mapPlugin\",skel.fn=f,delta.t=delta.t)\n}\n"
  },
  {
    "path": "R/slice_design.R",
    "content": "##' @description\n##' \\code{slice_design} generates points along slices through a specified point.\n##' @rdname design\n##' @return\n##' \\code{slice_design} returns a data frame with one row per point.\n##' The \\sQuote{slice} variable indicates which slice the point belongs to.\n##' @param center \\code{center} is a named numeric vector specifying the point\n##' through which the slice(s) is (are) to be taken.\n##'\n##' @export\nslice_design <- function (center, ...) {\n  slices <- list(...)\n  if ((!is.numeric(center))||is.null(names(center)))\n    pStop(sQuote(\"center\"),\" must be a named numeric vector\")\n  slnm <- names(slices)\n  if (any(slnm==\"\"))\n    pStop(\"cannot slice along an unnamed parameter.\")\n  if (!all(slnm%in%names(center))) {\n    problems <- slnm[!(slnm%in%names(center))]\n    pStop(\n      ngettext(length(problems),\"variable \",\"variables \"),\n      paste(lapply(problems,sQuote),collapse=\",\"),\n      ngettext(length(problems),\" does \",\" do \"),\n      \"not appear in \",sQuote(\"center\")\n    )\n  }\n  nslice <- length(slices)\n  nvars <- length(center)\n\n  y <- vector(mode=\"list\",length=nslice)\n  for (k in seq_len(nslice)) {\n    y[[k]] <- as.data.frame(\n      matrix(\n        data=center,\n        nrow=length(slices[[k]]),\n        ncol=nvars,\n        byrow=TRUE,\n        dimnames=list(names(slices[[k]]),names(center))\n      )\n    )\n    y[[k]][[slnm[k]]] <- as.numeric(slices[[k]])\n    y[[k]]$slice <- slnm[k]\n  }\n  y <- do.call(rbind,y)\n  y$slice <- as.factor(y$slice)\n  y\n}\n"
  },
  {
    "path": "R/sobol_design.R",
    "content": "##' @description\n##' \\code{sobol_design} generates a Latin hypercube design based on the Sobol' low-discrepancy sequence.\n##' @rdname design\n##'\n##' @details\n##' The Sobol' sequence generation is performed using codes from the \\pkg{NLopt} library by S. Johnson.\n##' @return\n##' \\code{sobol_design} returns a data frame with \\code{nseq} rows and one column for each variable named in \\code{lower} and \\code{upper}.\n##' @param lower,upper named numeric vectors giving the lower and upper bounds\n##' of the ranges, respectively.\n##' @param nseq Total number of points requested.\n##' @references\n##' \\Kucherenko2005\n##'\n##' \\NLopt\n##'\n##' \\Bratley1988\n##'\n##' \\Joe2003\n##'\n##' @export\nsobol_design <- function (lower = numeric(0), upper = numeric(0), nseq) {\n  if (length(lower)!=length(upper))\n    pStop(sQuote(\"lower\"),\" and \",sQuote(\"upper\"),\" must have same length.\")\n  lnames <- names(lower)\n  if (is.null(lnames))\n    pStop(sQuote(\"lower\"),\" and \",sQuote(\"upper\"),\" must be named vectors.\")\n  if (!all(sort(lnames)==sort(names(upper))))\n    pStop(\"names of \",sQuote(\"lower\"),\" and \",sQuote(\"upper\"),\" must match.\")\n  upper <- upper[lnames]\n  ranges <- lapply(seq_along(lnames),\\(k)c(lower[k],upper[k]))\n  names(ranges) <- lnames\n  tryCatch(\n    sobol(ranges,n=as.integer(nseq)),\n    error = function (e) pStop(who=\"sobol_design\",conditionMessage(e))\n  )\n}\n\nsobol <- function (vars, n) {\n  d <- length(vars)\n  if (!is.finite(n) || (n > 1073741824L))\n    pStop_(\"too many points requested.\")\n  x <- .Call(P_sobol_sequence,as.integer(d),as.integer(n))\n  y <- vapply(\n    seq_len(d),\n    function (k) {\n      vars[[k]][1L]+(vars[[k]][2L]-vars[[k]][1L])*x[k,]\n    },\n    numeric(n)\n  )\n  colnames(y) <- names(vars)\n  as.data.frame(y)\n}\n"
  },
  {
    "path": "R/spect.R",
    "content": "##' Power spectrum\n##'\n##' Power spectrum computation and spectrum-matching for partially-observed\n##' Markov processes.\n##'\n##' \\code{spect} estimates the power spectrum of time series data and model\n##' simulations and compares the results.  It can be used to diagnose goodness\n##' of fit and/or as the basis for frequency-domain parameter estimation\n##' (\\code{spect.match}).\n##'\n##' A call to \\code{spect} results in the estimation of the power spectrum for\n##' the (transformed, detrended) data and \\code{nsim} model simulations.  The\n##' results of these computations are stored in an object of class\n##' \\sQuote{spectd_pomp}.\n##'\n##' @name spect\n##' @docType methods\n##' @rdname spect\n##' @aliases spect,missing-method spect,ANY-method\n##' @family summary statistic-based methods\n##' @family elementary algorithms\n##'\n##' @inheritSection pomp Note for Windows users\n##'\n##' @include simulate.R pomp.R\n##' @importFrom stats spec.pgram kernel .lm.fit\n##'\n##' @param vars optional; names of observed variables for which the power spectrum will be computed.\n##' By default, the spectrum will be computed for all observables.\n##' @param kernel.width width parameter for the smoothing kernel used for\n##' calculating the estimate of the spectrum.\n##' @param nsim number of model simulations to be computed.\n##' @param seed optional; if non-\\code{NULL}, the random number generator will\n##' be initialized with this seed for simulations.\n##' See \\code{\\link{simulate}}.\n##' @param transform.data function; this transformation will be applied to the\n##' observables prior to estimation of the spectrum, and prior to any\n##' detrending.\n##' @param detrend de-trending operation to perform.  Options include no\n##' detrending, and subtraction of constant, linear, and quadratic trends from\n##' the data.  Detrending is applied to each data series and to each model\n##' simulation independently.\n##' @inheritParams probe\n##' @inheritParams pomp\n##'\n##' @return\n##' An object of class \\sQuote{spectd_pomp}, which contains the model, the data, and the results of the \\code{spect} computation.\n##' The following methods are available:\n##' \\describe{\n##' \\item{plot}{produces some diagnostic plots}\n##' \\item{summary}{displays a summary}\n##' \\item{logLik}{gives a measure of the agreement of the power spectra}\n##' }\n##'\n##' @author Daniel C. Reuman, Cai GoGwilt, Aaron A. King\n##'\n##' @references\n##'\n##' \\Reuman2006\n##'\n##' \\Reuman2008\n##'\nNULL\n\nsetClass(\n  \"spectd_pomp\",\n  contains=\"pomp\",\n  slots=c(\n    nsim=\"integer\",\n    seed=\"integer\",\n    kernel.width=\"numeric\",\n    transform.data=\"function\",\n    vars=\"character\",\n    freq=\"numeric\",\n    datspec=\"array\",\n    simspec=\"array\",\n    pvals=\"numeric\",\n    detrend=\"character\"\n  )\n)\n\nsetGeneric(\n  \"spect\",\n  function (data, ...)\n    standardGeneric(\"spect\")\n)\n\nsetMethod(\n  \"spect\",\n  signature=signature(data=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"spect\",\"data\")\n  }\n)\n\nsetMethod(\n  \"spect\",\n  signature=signature(data=\"ANY\"),\n  definition=function (data, ...) {\n    undef_method(\"spect\",data)\n  }\n)\n\n##' @rdname spect\n##' @export\nsetMethod(\n  \"spect\",\n  signature(data=\"data.frame\"),\n  function (\n    data,\n    ...,\n    vars, kernel.width, nsim, seed = NULL,\n    transform.data = identity,\n    detrend = c(\"none\",\"mean\",\"linear\",\"quadratic\"),\n    params, rinit, rprocess, rmeasure,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      spect_internal(\n        data,\n        ...,\n        vars=vars,\n        kernel.width=kernel.width,\n        nsim=nsim,\n        seed=seed,\n        transform.data=match.fun(transform.data),\n        detrend=match.arg(detrend),\n        params=params,\n        rinit=rinit,\n        rprocess=rprocess,\n        rmeasure=rmeasure,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"spect\",conditionMessage(e))\n    )\n\n  }\n)\n##' @rdname spect\n##' @export\nsetMethod(\n  \"spect\",\n  signature(data=\"pomp\"),\n  function (\n    data,\n    ...,\n    vars, kernel.width, nsim, seed = NULL,\n    transform.data = identity,\n    detrend = c(\"none\",\"mean\",\"linear\",\"quadratic\"),\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      spect_internal(\n        data,\n        ...,\n        vars=vars,\n        kernel.width=kernel.width,\n        nsim=nsim,\n        seed=seed,\n        transform.data=match.fun(transform.data),\n        detrend=match.arg(detrend),\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"spect\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname spect\n##' @export\nsetMethod(\n  \"spect\",\n  signature=signature(data=\"spectd_pomp\"),\n  definition=function (\n    data,\n    ...,\n    vars, kernel.width, nsim, seed = NULL,\n    transform.data,\n    detrend,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    if (missing(vars)) vars <- colnames(data@datspec)\n    if (missing(kernel.width)) kernel.width <- data@kernel.width\n    if (missing(nsim)) nsim <- data@nsim\n    if (missing(transform.data)) transform.data <- data@transform.data\n    if (missing(detrend)) detrend <- data@detrend\n\n    spect(\n      as(data,\"pomp\"),\n      ...,\n      vars=vars,\n      kernel.width=kernel.width,\n      nsim=nsim,\n      seed=seed,\n      transform.data=transform.data,\n      detrend=detrend,\n      verbose=verbose\n    )\n\n  }\n)\n\nspect_internal <- function (\n  object,\n  ...,\n  vars, kernel.width, nsim, seed = NULL,\n  transform.data, detrend,\n  .gnsi = TRUE, verbose\n) {\n\n  verbose <- as.logical(verbose)\n\n  object <- pomp(object,...,verbose=verbose)\n\n  if (undefined(object@rprocess) || undefined(object@rmeasure))\n    pStop_(paste(sQuote(c(\"rprocess\",\"rmeasure\")),collapse=\", \"),\" are needed basic components.\")\n\n  if (missing(vars)) vars <- rownames(object@data)\n\n  if (missing(kernel.width) || length(kernel.width) > 1 ||\n        !is.numeric(kernel.width) ||\n        !is.finite(kernel.width) || kernel.width < 0)\n    pStop_(sQuote(\"kernel.width\"),\" must be a positive integer.\")\n\n  if (missing(nsim) || length(nsim) > 1 || !is.numeric(nsim)||\n        !is.finite(nsim) || (nsim<1))\n    pStop_(sQuote(\"nsim\"),\" must be a positive integer.\")\n\n  nsim <- as.integer(nsim)\n  seed <- as.integer(seed)\n\n  ker <- reuman_kernel(kernel.width)\n\n  params <- coef(object)\n\n  pompLoad(object)\n  on.exit(pompUnload(object))\n\n  ds <- compute_spect_data(\n    object,\n    vars=vars,\n    transform.data=transform.data,\n    detrend=detrend,\n    ker=ker\n  )\n  freq <- ds$freq\n  datspec <- ds$spec\n\n  simspec <- compute_spect_sim(\n    object,\n    params=params,\n    vars=vars,\n    nsim=nsim,\n    seed=seed,\n    transform.data=transform.data,\n    detrend=detrend,\n    ker=ker,\n    .gnsi=.gnsi\n  )\n  .gnsi <- FALSE\n\n  pvals <- numeric(length(vars)+1)\n  names(pvals) <- c(vars,\"all\")\n  mean.simspec <- colMeans(simspec) # mean spectrum of simulations\n  totdatdist <- 0\n  totsimdist <- 0\n  for (j in seq_along(vars)) {\n    ## L-2 distance between data and mean simulated spectrum\n    datdist <- sum((datspec[,j]-mean.simspec[,j])^2)\n    ## L-2 distance betw. each sim. and mean simulated spectrum\n    simdist <- vapply(\n      seq_len(nsim),\n      \\(k)sum((simspec[k,,j]-mean.simspec[,j])^2),\n      numeric(1L)\n    )\n    pvals[j] <- (nsim+1-sum(simdist<datdist))/(nsim+1)\n    totdatdist <- totdatdist+datdist\n    totsimdist <- totsimdist+simdist\n  }\n  pvals[length(vars)+1] <- (nsim+1-sum(totsimdist<totdatdist))/(nsim+1)\n\n  coef(object) <- params\n\n  new(\n    \"spectd_pomp\",\n    object,\n    nsim=nsim,\n    seed=seed,\n    kernel.width=kernel.width,\n    transform.data=transform.data,\n    vars=vars,\n    detrend=detrend,\n    freq=freq,\n    datspec=datspec,\n    simspec=simspec,\n    pvals=pvals\n  )\n}\n\ncompute_spect_data <- function (object, vars, transform.data, detrend, ker) {\n\n  dat <- obs(object,vars)\n  if (any(!is.finite(dat)))\n    pStop_(\"missing or infinite values in the data.\")\n\n  dt <- diff(time(object,t0=FALSE))\n  base.freq <- 1/mean(dt)\n  dt.tol <- 0.025\n  if (max(dt)-min(dt)>dt.tol*mean(dt))\n    pStop_(sQuote(\"spect\"),\" assumes evenly spaced times.\")\n\n  for (j in seq_along(vars)) {\n    sp <- spec.pgram(\n      pomp_detrend(transform.data(dat[j,]),type=detrend),spans=ker,taper=0,\n      pad=0,fast=FALSE,detrend=FALSE,plot=FALSE\n    )\n    if (j==1) {\n      freq <- base.freq*sp$freq\n      datspec <- array(\n        dim=c(length(freq),nrow(dat)),\n        dimnames=list(NULL,vars)\n      )\n    }\n    datspec[,j] <- log10(sp$spec)\n  }\n  list(freq=freq,spec=datspec)\n}\n\ncompute_spect_sim <- function (object, params, vars, nsim, seed,\n  transform.data, detrend, ker, .gnsi = TRUE) {\n\n  sims <- tryCatch(\n  {\n    s <- freeze(\n      .Call(P_do_simulate,object,params,nsim,0L,gnsi=.gnsi),\n      seed=seed\n    )\n    s$obs[vars,,,drop=FALSE]\n  },\n  error = function (e) pStop_(\"in simulation: \",\n    conditionMessage(e))\n  )\n\n  if (any(!is.finite(sims)))\n    pStop_(\"missing or infinite values in simulated data.\")\n\n  nobs <- length(vars)\n  for (j in seq_len(nobs)) {\n    for (k in seq_len(nsim)) {\n      sp <- tryCatch(\n        spec.pgram(pomp_detrend(transform.data(sims[j,k,]),type=detrend),\n          spans=ker,taper=0,pad=0,fast=FALSE,detrend=FALSE,plot=FALSE),\n        error = function (e) pStop(who=\"spec.pgram\",conditionMessage(e))\n      )\n      if ((j==1)&&(k==1)) {\n        simspec <- array(\n          dim=c(nsim,length(sp$freq),nobs),\n          dimnames=list(NULL,NULL,vars)\n        )\n      }\n      simspec[k,,j] <- log10(sp$spec)\n    }\n  }\n  simspec\n}\n\n## detrends in one of several ways, according to type.\n## tseries is a numeric vector,\npomp_detrend <- function (tseries, type) {\n  switch(\n    type,\n    mean=tseries-mean(tseries),\n    linear={\n      m <- cbind(1,seq_along(tseries))\n      .lm.fit(m,tseries)$residuals\n    },\n    quadratic={\n      x <- seq_along(tseries)\n      m <- cbind(1,x,x*x)\n      .lm.fit(m,tseries)$residuals\n    },\n    tseries\n  )\n}\n\n## The default smoothing kernel for the R spec.pgram function is weird.\n## This function creates a better one.\nreuman_kernel <- function (kernel.width) {\n  ker <- kernel(\"modified.daniell\",m=kernel.width,r=NA)\n  x <- seq.int(from=0,to=kernel.width,by=1)/kernel.width\n  ker[[1L]] <- (15/(16*2*pi))*((x-1)^2)*((x+1)^2)\n  ker[[1L]] <- ker[[1L]]/(2*sum(ker[[1L]][-1])+ker[[1L]][1L])\n  attr(ker,\"name\") <- NULL\n  ker\n}\n\n##' @rdname summary\n##' @export\nsetMethod(\n  \"summary\",\n  signature=signature(object=\"spectd_pomp\"),\n  definition=function (object, ...) {\n    list(\n      coef=coef(object),\n      nsim=nrow(object@simspec),\n      pvals=object@pvals\n    )\n  }\n)\n"
  },
  {
    "path": "R/spect_match.R",
    "content": "##' Spectrum matching\n##'\n##' Estimation of parameters by matching power spectra\n##'\n##' In spectrum matching, one attempts to minimize the discrepancy between a \\acronym{POMP} model's predictions and data, as measured in the frequency domain by the power spectrum.\n##'\n##' \\code{spect_objfun} constructs an objective function that measures the discrepancy.\n##' It can be passed to any one of a variety of numerical optimization routines, which will adjust model parameters to minimize the discrepancies between the power spectrum of model simulations and that of the data.\n##'\n##' @docType methods\n##' @name spect_match\n##' @rdname spect_match\n##' @aliases spect_objfun spect_objfun,missing-method spect_objfun,ANY-method\n##' @concept power-spectrum matching\n##' @family estimation methods\n##' @family summary statistic-based methods\n##' @family methods based on maximization\n##' @include spect.R probe_match.R loglik.R plot.R\n##' @param weights optional numeric or function.\n##' The mismatch between model and data is measured by a weighted average of mismatch at each frequency.\n##' By default, all frequencies are weighted equally.\n##' \\code{weights} can be specified either as a vector (which must have length equal to the number of frequencies) or as a function of frequency.\n##' If the latter, \\code{weights(freq)} must return a nonnegative weight for each frequency.\n##' @inheritParams probe_match\n##' @inheritParams spect\n##' @inheritParams pomp\n##' @return\n##' \\code{spect_objfun} constructs a stateful objective function for spectrum matching.\n##' Specifically, \\code{spect_objfun} returns an object of class \\sQuote{spect_match_objfun}, which is a function suitable for use in an \\code{\\link[stats]{optim}}-like optimizer.\n##' This function takes a single numeric-vector argument that is assumed to contain the parameters named in \\code{est}, in that order.\n##' When called, it will return the (optionally weighted) \\eqn{L^2}{L2} distance between the data spectrum and simulated spectra.\n##' It is a stateful function:\n##' Each time it is called, it will remember the values of the parameters and the discrepancy measure.\n##' @references\n##'\n##' \\Reuman2006\n##'\n##' \\Reuman2008\n##' @inheritSection pomp Note for Windows users\n##' @inheritSection objfun Important Note\n##' @inheritSection objfun Warning! Objective functions based on C snippets\n##' @seealso \\code{\\link{spect}} \\code{\\link[stats]{optim}}\n##' \\code{\\link[subplex]{subplex}} \\code{\\link[nloptr]{nloptr}}\n##'\n##' @example examples/spect_match.R\n##'\nNULL\n\nsetClass(\n  \"spect_match_objfun\",\n  contains=\"function\",\n  slots=c(\n    env=\"environment\",\n    est=\"character\"\n  )\n)\n\nsetGeneric(\n  \"spect_objfun\",\n  function (data, ...)\n    standardGeneric(\"spect_objfun\")\n)\n\nsetMethod(\n  \"spect_objfun\",\n  signature=signature(data=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"spect_objfun\",\"data\")\n  }\n)\n\nsetMethod(\n  \"spect_objfun\",\n  signature=signature(data=\"ANY\"),\n  definition=function (data, ...) {\n    undef_method(\"spect_objfun\",data)\n  }\n)\n\n##' @rdname spect_match\n##' @export\nsetMethod(\n  \"spect_objfun\",\n  signature=signature(data=\"data.frame\"),\n  definition=function(\n    data,\n    ...,\n    est = character(0),\n    weights = 1, fail.value = NA,\n    vars, kernel.width, nsim, seed = NULL,\n    transform.data = identity,\n    detrend = c(\"none\",\"mean\",\"linear\",\"quadratic\"),\n    params, rinit, rprocess, rmeasure, partrans,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      smof_internal(\n        data,\n        ...,\n        est=est,\n        weights=weights,\n        fail.value=fail.value,\n        vars=vars,\n        kernel.width=kernel.width,\n        nsim=nsim,\n        seed=seed,\n        transform.data=transform.data,\n        detrend=detrend,\n        params=params,\n        rinit=rinit,\n        rprocess=rprocess,\n        rmeasure=rmeasure,\n        partrans=partrans,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"spect_objfun\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname spect_match\n##' @export\nsetMethod(\n  \"spect_objfun\",\n  signature=signature(data=\"pomp\"),\n  definition=function(\n    data,\n    ...,\n    est = character(0),\n    weights = 1, fail.value = NA,\n    vars, kernel.width, nsim, seed = NULL,\n    transform.data = identity,\n    detrend = c(\"none\",\"mean\",\"linear\",\"quadratic\"),\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      smof_internal(\n        data,\n        ...,\n        est=est,\n        weights=weights,\n        fail.value=fail.value,\n        vars=vars,\n        kernel.width=kernel.width,\n        nsim=nsim,\n        seed=seed,\n        transform.data=transform.data,\n        detrend=detrend,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"spect_objfun\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname spect_match\n##' @export\nsetMethod(\n  \"spect_objfun\",\n  signature=signature(data=\"spectd_pomp\"),\n  definition=function(\n    data,\n    ...,\n    est = character(0),\n    weights = 1, fail.value = NA,\n    vars, kernel.width, nsim, seed = NULL,\n    transform.data = identity,\n    detrend,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    if (missing(vars)) vars <- data@vars\n    if (missing(kernel.width)) kernel.width <- data@kernel.width\n    if (missing(nsim)) nsim <- data@nsim\n    if (missing(transform.data)) transform.data <- data@transform.data\n    if (missing(detrend)) detrend <- data@detrend\n\n    spect_objfun(\n      as(data,\"pomp\"),\n      ...,\n      est=est,\n      weights=weights,\n      fail.value=fail.value,\n      vars=vars,\n      kernel.width=kernel.width,\n      nsim=nsim,\n      seed=seed,\n      transform.data=transform.data,\n      detrend=detrend,\n      verbose=verbose\n    )\n\n  }\n)\n\n##' @rdname spect_match\n##' @export\nsetMethod(\n  \"spect_objfun\",\n  signature=signature(data=\"spect_match_objfun\"),\n  definition=function(\n    data,\n    ...,\n    est, weights, fail.value,\n    seed = NULL,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    if (missing(est)) est <- data@est\n    if (missing(weights)) weights <-data@env$weights\n    if (missing(fail.value)) fail.value <- data@env$fail.value\n\n    spect_objfun(\n      data@env$object,\n      ...,\n      est=est,\n      weights=weights,\n      fail.value=fail.value,\n      seed=seed,\n      verbose=verbose\n    )\n\n  }\n)\n\nsmof_internal <- function (\n  object,\n  ...,\n  est, weights, fail.value,\n  vars, kernel.width, nsim, seed,\n  transform.data, detrend,\n  verbose\n) {\n\n  verbose <- as.logical(verbose)\n\n  object <- spect(object,vars=vars,kernel.width=kernel.width,\n    nsim=nsim,seed=seed, transform.data=transform.data,detrend=detrend,\n    ...,verbose=verbose)\n\n  fail.value <- as.numeric(fail.value)\n\n  if (is.numeric(weights)) {\n    if (length(weights)==1) {\n      weights <- rep(weights,length(object@freq))\n    } else if ((length(weights) != length(object@freq)))\n      pStop_(\"if \",sQuote(\"weights\"),\n        \" is provided as a vector, it must have length \",\n        length(object@freq))\n  } else if (is.function(weights)) {\n    weights <- tryCatch(\n      vapply(object@freq,weights,numeric(1)),\n      error = function (e)\n        pStop_(sQuote(\"weights\"),\" function: \",conditionMessage(e))\n    )\n  } else {\n    pStop_(sQuote(\"weights\"),\n      \" must be specified as a vector or as a function\")\n  }\n\n  if (any(!is.finite(weights) | weights<0))\n    pStop_(sQuote(\"weights\"),\" should be nonnegative and finite\")\n  weights <- weights/mean(weights)\n\n  params <- coef(object,transform=TRUE)\n\n  est <- as.character(est)\n  est <- est[nzchar(est)]\n\n  idx <- match(est,names(params))\n  if (any(is.na(idx))) {\n    missing <- est[is.na(idx)]\n    pStop_(ngettext(length(missing),\"parameter\",\"parameters\"),\" \",\n      paste(sQuote(missing),collapse=\",\"),\n      \" not found in \",sQuote(\"params\"))\n  }\n\n  pompLoad(object)\n\n  ker <- reuman_kernel(kernel.width)\n  discrep <- spect_discrep(object,ker=ker,weights=weights)\n  .gnsi <- TRUE\n\n  ofun <- function (par = numeric(0)) {\n    params[idx] <- par\n    coef(object,transform=TRUE,.gnsi=.gnsi) <<- params\n    object@simspec <- compute_spect_sim(\n      object,\n      vars=object@vars,\n      params=object@params,\n      nsim=object@nsim,\n      seed=object@seed,\n      transform.data=object@transform.data,\n      detrend=object@detrend,\n      ker=ker,\n      .gnsi=.gnsi\n    )\n    discrep <<- spect_discrep(object,ker=ker,weights=weights)\n    .gnsi <<- FALSE\n    if (is.finite(discrep) || is.na(fail.value)) discrep else fail.value #nocov\n  }\n\n  environment(ofun) <- list2env(\n    list(object=object,fail.value=fail.value,\n      params=params,idx=idx,discrep=discrep,seed=seed,ker=ker,\n      .gnsi=.gnsi,weights=weights),\n    parent=parent.frame(2)\n  )\n\n  new(\"spect_match_objfun\",ofun,env=environment(ofun),est=est)\n\n}\n\n## compute a measure of the discrepancies between simulations and data\nspect_discrep <- function (object, ker, weights) {\n  discrep <- array(dim=c(length(object@freq),length(object@vars)))\n  sim.means <- colMeans(object@simspec)\n  for (j in seq_along(object@freq)) {\n    for (k in seq_along(object@vars)) {\n      discrep[j,k] <- ((object@datspec[j,k]-sim.means[j,k])^2)/\n        mean((object@simspec[,j,k]-sim.means[j,k])^2)\n    }\n    discrep[j,] <- weights[j]*discrep[j,]\n  }\n  sum(discrep)\n}\n\n##' @rdname spect\n##' @details\n##' When \\code{spect} operates on a spectrum-matching objective function (a \\sQuote{spect_match_objfun} object), by default, the\n##' random-number generator seed is fixed at the value given when the objective function was constructed.\n##' Specifying \\code{NULL} or an integer for \\code{seed} overrides this behavior.\n##' @export\nsetMethod(\n  \"spect\",\n  signature=signature(data=\"spect_match_objfun\"),\n  definition=function (\n    data,\n    ...,\n    seed,\n    verbose=getOption(\"verbose\", FALSE)\n  ) {\n\n    if (missing(seed)) seed <- data@env$seed\n\n    spect(\n      data@env$object,\n      ...,\n      seed=seed,\n      verbose=verbose\n    )\n\n  }\n)\n\nsetAs(\n  from=\"spect_match_objfun\",\n  to=\"spectd_pomp\",\n  def = function (from) {\n    from@env$object\n  }\n)\n\n##' @rdname plot\n##' @export\nsetMethod(\n  \"plot\",\n  signature=signature(x=\"spect_match_objfun\"),\n  definition=function (x, ...) {\n    plot(as(x,\"spectd_pomp\"),...)\n  }\n)\n"
  },
  {
    "path": "R/spy.R",
    "content": "##' Spy\n##'\n##' Peek into the inside of one of \\pkg{pomp}'s objects.\n##'\n##' @name spy\n##' @rdname spy\n##' @include pomp_class.R\n##' @aliases spy,missing-method spy,ANY-method\n##' @param object the object whose structure we wish to examine\n##' @seealso Csnippet\n##' @example examples/spy.R\n##' @family extraction methods\n##'\nNULL\n\nsetGeneric(\n  \"spy\",\n  function (object, ...)\n    standardGeneric(\"spy\")\n)\n\nsetMethod(\n  \"spy\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"spy\",\"object\")\n  }\n)\n\nsetMethod(\n  \"spy\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"spy\",object)\n  }\n)\n\n##' @rdname spy\n##' @export\nsetMethod(\n  \"spy\",\n  signature=signature(object=\"pomp\"),\n  definition=function (object) {\n\n    nm <- deparse(substitute(object,env=parent.frame()))\n    f <- tempfile()\n    con <- file(description=f,open=\"w+\")\n    sink(file=con)\n    on.exit(if (sink.number()) sink())\n\n    cat(\"==================\\npomp object \",sQuote(nm),\":\\n\\n\",sep=\"\")\n\n    if (nrow(object@data) > 0L) {\n      cat(\"- data:\\n\")\n      cat(\"  -\",length(object@times),\"records of\",\n        nrow(object@data),\n        ngettext(nrow(object@data),\"observable,\",\"observables,\"),\n        \"recorded from t =\",\n        min(object@times),\"to\",max(object@times),\"\\n\")\n      cat(\"  - summary of data:\\n\")\n      print(summary(as.data.frame(t(obs(object)))))\n    } else {\n      cat(\"- data: <none>\\n\")\n    }\n\n    cat(\"- zero time, t0 = \",object@t0,\"\\n\",sep=\"\")\n\n    cat(\"- covariates: \")\n    show(object@covar)\n\n    cat(\"- initial state simulator, rinit: \")\n    show(object@rinit)\n\n    cat(\"- initial state density, dinit: \")\n    show(object@dinit)\n\n    cat(\"- process-model simulator, rprocess: \")\n    show(object@rprocess)\n\n    cat(\"- process model density, dprocess: \")\n    show(object@dprocess)\n\n    cat(\"- measurement model simulator, rmeasure: \")\n    show(object@rmeasure)\n\n    cat(\"- measurement model density, dmeasure: \")\n    show(object@dmeasure)\n\n    cat(\"- measurement model expectation, emeasure: \")\n    show(object@emeasure)\n\n    cat(\"- measurement model covariance, vmeasure: \")\n    show(object@vmeasure)\n\n    cat(\"- prior simulator, rprior: \")\n    show(object@rprior)\n\n    cat(\"- prior density, dprior: \")\n    show(object@dprior)\n\n    cat(\"- deterministic skeleton: \")\n    show(object@skeleton)\n\n    if (object@partrans@has) {\n      cat(\"- parameter transformations:\\n\")\n      show(object@partrans)\n    }\n\n    if (length(coef(object))>0) {\n      cat(\"- parameter vector:\\n\")\n      print(coef(object))\n    } else {\n      cat (\"- parameter vector unspecified\\n\");\n    }\n\n    if (length(object@userdata)>0) {\n      unames <- names(object@userdata)\n      utypes <- vapply(object@userdata,typeof,character(1))\n      cat(\n        \"- extra user-defined variables:\",\n        sprintf(\"  - %s (type %s)\",sQuote(unames),sQuote(utypes)),\n        sep=\"\\n\"\n      )\n    }\n\n    cat(\"\\n\")\n\n    ## now display C snippets\n    if (length(object@solibs) > 0) {\n      for (i in seq_along(object@solibs)) {\n        cat(\"- C snippet file \",i,\":\\n\\n\")\n        cat(object@solibs[[i]]$src)\n      }\n    }\n\n    sink()\n    close(con)\n    file.show(f,delete.file=TRUE)\n    invisible(NULL)\n  }\n)\n"
  },
  {
    "path": "R/states.R",
    "content": "##' Latent states\n##'\n##' Extract the latent states from a \\sQuote{pomp} object.\n##'\n##' @name states\n##' @aliases states,ANY-method states,missing-method\n##' @rdname states\n##' @docType methods\n##' @include pomp_class.R melt.R\n##' @importFrom stats setNames\n##' @family extraction methods\n##'\nNULL\n\nsetGeneric(\n  \"states\",\n  function (object, ...)\n    standardGeneric(\"states\")\n)\n\nsetMethod(\n  \"states\",\n  signature=signature(object=\"missing\"),\n  definition=function (object, ...) {\n    reqd_arg(\"states\",\"object\")\n  }\n)\n\nsetMethod(\n  \"states\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"states\",\"object\")\n  }\n)\n\n##' @rdname states\n##' @inheritParams obs\n##' @export\nsetMethod(\n  \"states\",\n  signature=signature(object=\"pomp\"),\n  definition=function (object, vars, ...,\n    format = c(\"array\", \"data.frame\")) {\n    if (length(object@states)==0) {\n      x <- array(NA_real_,dim=c(0,length(object@times)),\n        dimnames=setNames(list(NULL,NULL),c(\"name\",object@timename)))\n    } else if (missing(vars)) {\n      x <- object@states\n      names(dimnames(x)) <- c(\"name\",object@timename)\n    } else {\n      varnames <- rownames(object@states)\n      if (!all(vars%in%varnames))\n        pStop(who=\"states\",\"some elements of \",\n          sQuote(\"vars\"),\" correspond to no state variable\")\n      x <- object@states[vars,,drop=FALSE]\n      dimnames(x) <- setNames(list(vars,NULL),c(\"name\",object@timename))\n    }\n    format <- match.arg(format)\n    if (format == \"data.frame\") {\n      x <- data.frame(time=time(object),t(x))\n      names(x)[1L] <- object@timename\n    }\n    x\n  }\n)\n\n##' @rdname states\n##' @inheritParams obs\n##' @export\nsetMethod(\n  \"states\",\n  signature=signature(object=\"listie\"),\n  definition=function (object, vars, ...,\n    format = c(\"array\", \"data.frame\")) {\n    format <- match.arg(format)\n    x <- lapply(object,states,vars=vars,format=format,...)\n    if (format == \"data.frame\") {\n      rbind_fill(x,.id=\".id\")\n    } else {\n      x\n    }\n  }\n)\n"
  },
  {
    "path": "R/summary.R",
    "content": "##' Summary methods\n##'\n##' Display a summary of a fitted model object.\n##'\n##' @name summary\n##' @rdname summary\n##' @param object a fitted model object\n##' @param \\dots ignored or passed to the more primitive function\n##' @family extraction methods\nNULL\n\nsetGeneric(\"summary\")\n"
  },
  {
    "path": "R/templates.R",
    "content": "## default templates for pomp's own C snippets.\n## This is used in 'pomp.R' and 'builder.R'.\n\n## BASIC TEMPLATES\n\npomp_templates <- list(\n  define=r\"{\n#define {%variable%} ({%cref%})}\",\n  undefine=r\"{\n#undef {%variable%}}\",\n  file=list(\n    header=r\"{\n/* pomp C snippet file: {%name%} */\n/* Time: {%timestamp%} */\n/* Salt: {%salt%} */\n\n#include <{%pompheader%}>\n#include <R_ext/Rdynload.h>}\"\n  ),\n  utilities=list(\n    bspline_basis=list(\n      trigger=r\"{(?<!periodic_)bspline_basis_eval}\",\n      header=r\"{\nstatic bspline_basis_eval_deriv_t *__pomp_bspline_basis_eval_deriv;\n#define bspline_basis_eval(X,K,P,N,Y)  (__pomp_bspline_basis_eval_deriv((X),(K),(P),(N),0,(Y)))\n#define bspline_basis_eval_deriv(X,K,P,N,D,Y)  (__pomp_bspline_basis_eval_deriv((X),(K),(P),(N),(D),(Y)))}\",\n      reg=r\"{\n  __pomp_bspline_basis_eval_deriv = (bspline_basis_eval_deriv_t *) R_GetCCallable(\"pomp\",\"bspline_basis_eval_deriv\");}\"\n    ),\n    periodic_bspline_basis=list(\n      trigger=\"periodic_bspline_basis_eval\",\n      header=r\"{\nstatic periodic_bspline_basis_eval_deriv_t *__pomp_periodic_bspline_basis_eval_deriv;\n#define periodic_bspline_basis_eval(X,T,P,N,Y)  (__pomp_periodic_bspline_basis_eval_deriv((X),(T),(P),(N),0,(Y)))\n#define periodic_bspline_basis_eval_deriv(X,T,P,N,D,Y)  (__pomp_periodic_bspline_basis_eval_deriv((X),(T),(P),(N),(D),(Y)))}\",\n      reg=r\"{\n  __pomp_periodic_bspline_basis_eval_deriv = (periodic_bspline_basis_eval_deriv_t *) R_GetCCallable(\"pomp\",\"periodic_bspline_basis_eval_deriv\");}\"\n    ),\n    get_userdata_int=list(\n      trigger=\"get_userdata_int\",\n      header=r\"{\nstatic get_userdata_int_t *__pomp_get_userdata_int;\n#define get_userdata_int(X)  (__pomp_get_userdata_int(X))}\",\n      reg=r\"{\n  __pomp_get_userdata_int = (get_userdata_int_t *) R_GetCCallable(\"pomp\",\"get_userdata_int\");}\"\n    ),\n    get_userdata_double=list(\n      trigger=\"get_userdata_double\",\n      header=r\"{\nstatic get_userdata_double_t *__pomp_get_userdata_double;\n#define get_userdata_double(X)  (__pomp_get_userdata_double(X))}\",\n      reg=r\"{\n  __pomp_get_userdata_double = (get_userdata_double_t *) R_GetCCallable(\"pomp\",\"get_userdata_double\");}\"\n    ),\n    get_userdata=list(\n      trigger=r\"{get_userdata(?!_)}\",\n      header=r\"{\nstatic get_userdata_t *__pomp_get_userdata;\n#define get_userdata(X)  (__pomp_get_userdata(X))}\",\n      reg=r\"{\n  __pomp_get_userdata = (get_userdata_t *) R_GetCCallable(\"pomp\",\"get_userdata\");}\"\n    )\n  ),\n  stackhandling=r\"{\nstatic int __pomp_load_stack = 0;\nvoid __pomp_load_stack_incr (void) {++__pomp_load_stack;}\nvoid __pomp_load_stack_decr (int *val) {*val = --__pomp_load_stack;}}\",\n  registration=list(\n    header=r\"{\nvoid R_init_{%name%} (DllInfo *info) {}\",\n    main=r\"(\n  R_RegisterCCallable(\"{%name%}\", \"{%fun%}\", (DL_FUNC) {%fun%});)\",\n    footer=\"\\n}\\n\"\n  )\n)\n\n## WORKHORSE-SPECIFIC TEMPLATES\n\nworkhorse_templates <- list(\n  rinit=list(\n    slotname=\"rinit\",\n    Cname=\"__pomp_rinit\",\n    proto=quote(rinit(...)),\n    header=r\"{\nvoid __pomp_rinit (double *__x, const double *__p, double t,\n   const int *__stateindex, const int *__parindex, const int *__covindex,\n   const double *__covars) {}\",\n    footer=\"\\n}\\n\",\n    vars=list(\n      params=list(\n        names=quote(paramnames),\n        cref=r\"{__p[__parindex[{%v%}]]}\"\n      ),\n      covars=list(\n        names=quote(covarnames),\n        cref=r\"{__covars[__covindex[{%v%}]]}\"\n      ),\n      states=list(\n        names=quote(statenames),\n        cref=r\"{__x[__stateindex[{%v%}]]}\"\n      )\n    )\n  ),\n  dinit=list(\n    slotname=\"dinit\",\n    Cname=\"__pomp_dinit\",\n    proto=quote(dinit(...)),\n    header=r\"{\nvoid __pomp_dinit (double *__loglik, const double *__x, const double *__p,\n  double t, const int *__stateindex, const int *__parindex, const int *__covindex,\n  const double *__covars) {}\",\n    footer=\"\\n}\\n\",\n    vars=list(\n      params=list(\n        names=quote(paramnames),\n        cref=r\"{__p[__parindex[{%v%}]]}\"\n      ),\n      covars=list(\n        names=quote(covarnames),\n        cref=r\"{__covars[__covindex[{%v%}]]}\"\n      ),\n      states=list(\n        names=quote(statenames),\n        cref=r\"{__x[__stateindex[{%v%}]]}\"\n      ),\n      loglik=list(\n        names=r\"{loglik}\",\n        cref=r\"{__loglik[0]}\"\n      )\n    )\n  ),\n  rmeasure=list(\n    slotname=\"rmeasure\",\n    Cname=\"__pomp_rmeasure\",\n    proto=quote(rmeasure(...)),\n    header=r\"{\nvoid __pomp_rmeasure (double *__y, const double *__x, const double *__p,\n  const int *__obsindex, const int *__stateindex, const int *__parindex,\n  const int *__covindex, const double *__covars, double t) {}\",\n    footer=\"\\n}\\n\",\n    vars=list(\n      params=list(\n        names=quote(paramnames),\n        cref=r\"{__p[__parindex[{%v%}]]}\"\n      ),\n      covars=list(\n        names=quote(covarnames),\n        cref=r\"{__covars[__covindex[{%v%}]]}\"\n      ),\n      states=list(\n        names=quote(statenames),\n        cref=r\"{__x[__stateindex[{%v%}]]}\"\n      ),\n      obs=list(\n        names=quote(obsnames),\n        cref=r\"{__y[__obsindex[{%v%}]]}\"\n      )\n    )\n  ),\n  emeasure=list(\n    slotname=\"emeasure\",\n    Cname=\"__pomp_emeasure\",\n    proto=quote(emeasure(...)),\n    header=r\"{\nvoid __pomp_emeasure (double *__f, const double *__x, const double *__p,\n  const int *__obsindex, const int *__stateindex, const int *__parindex,\n  const int *__covindex, const double *__covars, double t) {}\",\n    footer=\"\\n}\\n\",\n    vars=list(\n      params=list(\n        names=quote(paramnames),\n        cref=r\"{__p[__parindex[{%v%}]]}\"\n      ),\n      covars=list(\n        names=quote(covarnames),\n        cref=r\"{__covars[__covindex[{%v%}]]}\"\n      ),\n      states=list(\n        names=quote(statenames),\n        cref=r\"{__x[__stateindex[{%v%}]]}\"\n      ),\n      expectations=list(\n        names=quote(paste0(\"E_\",obsnames)),\n        cref=r\"{__f[__obsindex[{%v%}]]}\"\n      )\n    )\n  ),\n  vmeasure=list(\n    slotname=\"vmeasure\",\n    Cname=\"__pomp_vmeasure\",\n    proto=quote(vmeasure(...)),\n    header=r\"{\nvoid __pomp_vmeasure (double *__f, const double *__x, const double *__p,\n  const int *__vmatindex, const int *__stateindex, const int *__parindex,\n  const int *__covindex, const double *__covars, int nobs, double t) {}\",\n    footer=\"\\n}\\n\",\n    vars=list(\n      params=list(\n        names=quote(paramnames),\n        cref=r\"{__p[__parindex[{%v%}]]}\"\n      ),\n      covars=list(\n        names=quote(covarnames),\n        cref=r\"{__covars[__covindex[{%v%}]]}\"\n      ),\n      states=list(\n        names=quote(statenames),\n        cref=r\"{__x[__stateindex[{%v%}]]}\"\n      ),\n      variance_matrix=list(\n        names=quote(paste0(\"V_\",outer(obsnames,obsnames,paste,sep=\"_\"))),\n        cref=r\"{__f[__vmatindex[{%v%}]]}\"\n      )\n    )\n  ),\n  dmeasure=list(\n    slotname=\"dmeasure\",\n    Cname= \"__pomp_dmeasure\",\n    proto=quote(dmeasure(log,...)),\n    header=r\"{\nvoid __pomp_dmeasure (double *__lik, const double *__y, const double *__x,\n  const double *__p, int give_log, const int *__obsindex,\n  const int *__stateindex, const int *__parindex, const int *__covindex,\n  const double *__covars, double t) {}\",\n    footer=\"\\n}\\n\",\n    vars=list(\n      params=list(\n        names=quote(paramnames),\n        cref=r\"{__p[__parindex[{%v%}]]}\"\n      ),\n      covars=list(\n        names=quote(covarnames),\n        cref=r\"{__covars[__covindex[{%v%}]]}\"\n      ),\n      states=list(\n        names=quote(statenames),\n        cref=r\"{__x[__stateindex[{%v%}]]}\"\n      ),\n      obs=list(\n        names=quote(obsnames),\n        cref=r\"{__y[__obsindex[{%v%}]]}\"\n      ),\n      lik=list(\n        names=\"lik\",\n        cref=r\"{__lik[0]}\"\n      )\n    )\n  ),\n  step.fn=list(\n    slotname=\"step.fun\",\n    Cname=\"__pomp_stepfn\",\n    proto=quote(step.fun(...)),\n    header=r\"{\nvoid __pomp_stepfn (double *__x, const double *__p, const int *__stateindex,\n  const int *__parindex, const int *__covindex, const double *__covars,\n  double t, double dt) {}\",\n    footer=\"\\n}\\n\",\n    vars=list(\n      params=list(\n        names=quote(paramnames),\n        cref=r\"{__p[__parindex[{%v%}]]}\"\n      ),\n      covars=list(\n        names=quote(covarnames),\n        cref=r\"{__covars[__covindex[{%v%}]]}\"\n      ),\n      states=list(\n        names=quote(statenames),\n        cref=r\"{__x[__stateindex[{%v%}]]}\"\n      )\n    )\n  ),\n  rate.fn=list(\n    slotname=\"rate.fun\",\n    Cname=\"__pomp_ratefn\",\n    proto=quote(rate.fun(j,...)),\n    header=r\"{\ndouble __pomp_ratefn (int j, double t, double *__x, const double *__p,\n  const int *__stateindex, const int *__parindex, const int *__covindex,\n  const double *__covars) {\n  double rate = 0.0;}\",\n    footer=r\"{\n  return rate;\n}}\",\n    vars=list(\n      params=list(\n        names=quote(paramnames),\n        cref=r\"{__p[__parindex[{%v%}]]}\"\n      ),\n      covars=list(\n        names=quote(covarnames),\n        cref=r\"{__covars[__covindex[{%v%}]]}\"\n      ),\n      states=list(\n        names=quote(statenames),\n        cref=r\"{__x[__stateindex[{%v%}]]}\"\n      )\n    )\n  ),\n  dprocess=list(\n    slotname=\"dprocess\",\n    Cname=\"__pomp_dproc\",\n    proto=quote(dprocess(...)),\n    header=r\"{\nvoid __pomp_dproc (double *__loglik, const double *__x1, const double *__x2,\n  double t_1, double t_2, const double *__p, const int *__stateindex,\n  const int *__parindex, const int *__covindex, const double *__covars) {}\",\n    footer=\"\\n}\\n\",\n    vars=list(\n      params=list(\n        names=quote(paramnames),\n        cref=r\"{__p[__parindex[{%v%}]]}\"\n      ),\n      covars=list(\n        names=quote(covarnames),\n        cref=r\"{__covars[__covindex[{%v%}]]}\"\n      ),\n      before=list(\n        names=quote(paste0(statenames,\"_1\")),\n        cref=r\"{__x1[__stateindex[{%v%}]]}\"\n      ),\n      after=list(\n        names=quote(paste0(statenames,\"_2\")),\n        cref=r\"{__x2[__stateindex[{%v%}]]}\"\n      ),\n      loglik=list(\n        names=\"loglik\",\n        cref=r\"{__loglik[0]}\"\n      )\n    )\n  ),\n  skeleton=list(\n    slotname=\"skeleton\",\n    Cname=\"__pomp_skelfn\",\n    proto=quote(skeleton(...)),\n    header=r\"{\nvoid __pomp_skelfn (double *__f, const double *__x, const double *__p,\n  const int *__stateindex, const int *__parindex, const int *__covindex,\n  const double *__covars, double t) {}\",\n    footer=\"\\n}\\n\",\n    vars=list(\n      params=list(\n        names=quote(paramnames),\n        cref=r\"{__p[__parindex[{%v%}]]}\"\n      ),\n      covars=list(\n        names=quote(covarnames),\n        cref=r\"{__covars[__covindex[{%v%}]]}\"\n      ),\n      states=list(\n        names=quote(statenames),\n        cref=r\"{__x[__stateindex[{%v%}]]}\"\n      ),\n      derivs=list(\n        names=quote(paste0(\"D\",statenames)),\n        cref=r\"{__f[__stateindex[{%v%}]]}\"\n      )\n    )\n  ),\n  fromEst=list(\n    slotname=\"fromEst\",\n    Cname=\"__pomp_from_trans\",\n    proto=quote(from.trans(...)),\n    header=r\"{\nvoid __pomp_from_trans (double *__p, const double *__pt, const int *__parindex) {}\",\n    footer=\"\\n}\\n\",\n    vars=list(\n      covars=list(\n        names=quote(covarnames),\n        cref=r\"{__covars[__covindex[{%v%}]]}\"\n      ),\n      params=list(\n        names=quote(paramnames),\n        cref=r\"{__p[__parindex[{%v%}]]}\"\n      ),\n      transforms=list(\n        names=quote(paste0(\"T_\",paramnames)),\n        cref=r\"{__pt[__parindex[{%v%}]]}\"\n      )\n    )\n  ),\n  toEst=list(\n    slotname=\"toEst\",\n    Cname=\"__pomp_to_trans\",\n    proto=quote(to.trans(...)),\n    header=r\"{\nvoid __pomp_to_trans (double *__pt, const double *__p, const int *__parindex) {}\",\n    footer=\"\\n}\\n\",\n    vars=list(\n      covars=list(\n        names=quote(covarnames),\n        cref=r\"{__covars[__covindex[{%v%}]]}\"\n      ),\n      params=list(\n        names=quote(paramnames),\n        cref=r\"{__p[__parindex[{%v%}]]}\"\n      ),\n      transforms=list(\n        names=quote(paste0(\"T_\",paramnames)),\n        cref=r\"{__pt[__parindex[{%v%}]]}\"\n      )\n    )\n  ),\n  rprior=list(\n    slotname=\"rprior\",\n    Cname=\"__pomp_rprior\",\n    proto=quote(rprior(...)),\n    header=r\"{\nvoid __pomp_rprior (double *__p, const int *__parindex) {}\",\n    footer=\"\\n}\\n\",\n    vars=list(\n      params=list(\n        names=quote(paramnames),\n        cref=r\"{__p[__parindex[{%v%}]]}\"\n      )\n    )\n  ),\n  dprior=list(\n    slotname=\"dprior\",\n    Cname=\"__pomp_dprior\",\n    proto=quote(dprior(log,...)),\n    header=r\"{\nvoid __pomp_dprior (double *__lik, const double *__p, int give_log,\n  const int *__parindex) {}\",\n    footer=\"\\n}\\n\",\n    vars=list(\n      params=list(\n        names=quote(paramnames),\n        cref=r\"{__p[__parindex[{%v%}]]}\"\n      ),\n      lik=list(\n        names=\"lik\",\n        cref=r\"{__lik[0]}\"\n      )\n    )\n  )\n)\n"
  },
  {
    "path": "R/time.R",
    "content": "##' Methods to extract and manipulate the obseration times\n##'\n##' Get and set the vector of observation times.\n##'\n##' @name time\n##' @rdname time\n##' @aliases time<- time,missing-method\n##' @family extraction methods\n##'\nNULL\n\n##' @importFrom stats time\nsetGeneric(\"time\")\n\nsetGeneric(\n  \"time<-\",\n  function (object, ..., value)\n    standardGeneric(\"time<-\")\n)\n\n##' @rdname time\n##' @param x  a \\sQuote{pomp} object\n##' @param t0 logical; should the zero time be included?\n##' @param ... ignored or passed to the more primitive function\n##' @details\n##' \\code{time(object)} returns the vector of observation times.\n##' \\code{time(object,t0=TRUE)} returns the vector of observation\n##' times with the zero-time \\code{t0} prepended.\n##' @export\nsetMethod(\n  \"time\",\n  signature=signature(x=\"pomp\"),\n  definition=function (x, t0 = FALSE, ...) {\n    if (t0) c(x@t0,x@times) else x@times\n  }\n)\n\n##' @rdname time\n##' @param object  a \\sQuote{pomp} object\n##' @param value numeric vector; the new vector of times\n##' @details\n##' \\code{time(object) <- value} replaces the observation times slot (\\code{times}) of \\code{object} with \\code{value}.\n##' \\code{time(object,t0=TRUE) <- value} has the same effect, but the first element in \\code{value} is taken to be the initial time.\n##' The second and subsequent elements of \\code{value} are taken to be the observation times.\n##' Those data and states (if they exist) corresponding to the new times are retained.\n##' @export\nsetMethod(\n  \"time<-\",\n  signature=signature(object=\"pomp\"),\n  definition=function (object, t0 = FALSE, ..., value) {\n    tryCatch(\n      time_repl_internal(object,t0=t0,...,value=value),\n      error = function (e) pStop(who=\"time<-\",conditionMessage(e))\n    )\n  }\n)\n\ntime_repl_internal <- function (object, t0 = FALSE, ..., value) {\n  value <- tryCatch(\n    as.double(value),\n    warning = function (e) NULL,\n    error = function (e) pStop_(conditionMessage(e))\n  )\n  if (length(value)<1L || !all(is.finite(value)))\n    pStop_(\" times must be numeric and finite.\")\n  tt <- object@times\n  dd <- object@data\n  ss <- object@states\n  if (t0) {\n    object@t0 <- value[1]\n    object@times <- value[-1]\n  } else {\n    object@times <- value\n  }\n  if (!all(diff(object@times)>=0))\n    pStop_(\"times must be a non-decreasing numeric sequence.\")\n  if (object@t0>object@times[1L])\n    pStop_(\"the zero-time \",sQuote(\"t0\"),\n      \" must occur no later than the first observation.\")\n  object@data <- array(\n    data=NA,\n    dim=c(nrow(dd),length(object@times)),\n    dimnames=list(rownames(dd),NULL)\n  )\n  idx2 <- match(object@times,tt,nomatch=0)\n  idx1 <- idx2 > 0\n  object@data[,idx1] <- dd[,idx2]\n  if (length(ss)>0) {\n    object@states <- array(\n      data=NA,\n      dim=c(nrow(ss),length(object@times)),\n      dimnames=list(rownames(ss),NULL)\n    )\n    object@states[,idx1] <- ss[,idx2]\n  }\n  object\n}\n\n##' @rdname time\n##' @export\nsetMethod(\n  \"time\",\n  signature=signature(x=\"listie\"),\n  definition=function (x, t0 = FALSE, ...) {\n    lapply(x,time,t0=t0,...)\n  }\n)\n"
  },
  {
    "path": "R/timezero.R",
    "content": "##' The zero time\n##'\n##' Get and set the zero-time.\n##'\n##' @name timezero\n##' @rdname timezero\n##' @docType methods\n##' @aliases timezero<- timezero,missing-method timezero,ANY-method\n##' timezero<-,missing-method timezero<-,ANY-method\n##' @family extraction methods\n##' @return\n##' the value of the zero time\n##'\nNULL\n\nsetGeneric(\n  \"timezero\",\n  function (object, ...)\n    standardGeneric(\"timezero\")\n)\n\nsetGeneric(\n  \"timezero<-\",\n  function (object, ..., value)\n    standardGeneric(\"timezero<-\")\n)\n\n##' @rdname timezero\n##' @param object an object of class \\sQuote{pomp}, or of a class that extends \\sQuote{pomp}\n##' @param \\dots ignored or passed to the more primitive function\n##' @export\nsetMethod(\n  \"timezero\",\n  signature=signature(object=\"pomp\"),\n  definition = function (object, ...) object@t0\n)\n\n##' @rdname timezero\n##' @param value numeric; the new zero-time value\n##' @export\nsetMethod(\n  \"timezero<-\",\n  signature=signature(object=\"pomp\"),\n  definition=function(object,...,value) {\n    ep <- \"timezero<-\"\n    if (!(is.numeric(value) && length(value) == 1L && is.finite(value)))\n      pStop(who=ep,\"the zero-time \",sQuote(\"t0\"),\" must be a single finite number.\")\n    if (value > object@times[1L])\n      pStop(who=ep,\"the zero-time \",sQuote(\"t0\"),\n        \" must occur no later than the first observation.\")\n    storage.mode(value) <- \"double\"\n    object@t0 <- value\n    object\n  }\n)\n"
  },
  {
    "path": "R/traces.R",
    "content": "##' Traces\n##'\n##' Retrieve the history of an iterative calculation.\n##'\n##' @name traces\n##' @rdname traces\n##' @aliases traces traces,missing-method traces,ANY-method\n##' @family extraction methods\n##' @include pmcmc.R mif2.R abc.R\nNULL\n\nsetGeneric(\n  \"traces\",\n  function (object, ...)\n    standardGeneric(\"traces\")\n)\n\nsetMethod(\n  \"traces\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"traces\",\"object\")\n  }\n)\n\nsetMethod(\n  \"traces\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"traces\",object)\n  }\n)\n\n##' @rdname traces\n##' @importFrom coda mcmc mcmc.list\n##' @param object an object of class extending \\sQuote{pomp}, the result of the application of a parameter estimation algorithm\n##' @param pars names of parameters\n##' @param transform logical; should the traces be transformed back onto the natural scale?\n##' @param \\dots ignored or passed to the more primitive function\n##'\n##' @return\n##' When \\code{object} is the result of a \\code{\\link{mif2}} calculation,\n##' \\code{traces(object, pars)} returns the traces of the parameters named in \\code{pars}.\n##' By default, the traces of all parameters are returned.\n##' If \\code{transform=TRUE}, the parameters are transformed from the natural scale to the estimation scale.\n##'\n##' @export\nsetMethod(\n  \"traces\",\n  signature=signature(object=\"mif2d_pomp\"),\n  definition=function (object, pars, transform = FALSE, ...) {\n    traces_internal(object=object,pars=pars,transform=transform,...)\n  }\n)\n\n##' @rdname traces\n##' @export\nsetMethod(\n  \"traces\",\n  signature=signature(object=\"mif2List\"),\n  definition=function (object, pars, ...) {\n    lapply(object,traces,pars,...)\n  }\n)\n\n##' @rdname traces\n##' @return\n##' When \\code{object} is a \\sQuote{abcd_pomp}, \\code{traces(object)}\n##' extracts the traces as a \\code{coda::mcmc}.\n##' @export\nsetMethod(\n  \"traces\",\n  signature=signature(object=\"abcd_pomp\"),\n  definition=function (object, pars, ...) {\n    tr <- traces_internal(object,pars=pars)\n    coda::mcmc(tr)\n  }\n)\n\n##' @rdname traces\n##' @return\n##' When \\code{object} is a \\sQuote{abcList}, \\code{traces(object)}\n##' extracts the traces as a \\code{coda::mcmc.list}.\n##' @export\nsetMethod(\n  \"traces\",\n  signature=signature(object=\"abcList\"),\n  definition=function (object, pars, ...) {\n    coda::mcmc.list(lapply(object,traces,pars=pars))\n  }\n)\n\n##' @rdname traces\n##' @return\n##' When \\code{object} is a \\sQuote{pmcmcd_pomp}, \\code{traces(object)}\n##' extracts the traces as a \\code{coda::mcmc}.\n##' @details\n##' Note that \\code{\\link{pmcmc}} does not currently support parameter transformations.\n##' @export\nsetMethod(\n  \"traces\",\n  signature=signature(object=\"pmcmcd_pomp\"),\n  function (object, pars, ...) {\n    tr <- traces_internal(object,pars=pars)\n    coda::mcmc(tr)\n  }\n)\n\n##' @rdname traces\n##' @return\n##' When \\code{object} is a \\sQuote{pmcmcList}, \\code{traces(object)}\n##' extracts the traces as a \\code{coda::mcmc.list}.\n##' @export\nsetMethod(\n  \"traces\",\n  signature=signature(object=\"pmcmcList\"),\n  definition=function (object, pars, ...) {\n    coda::mcmc.list(lapply(object,traces,pars=pars))\n  }\n)\n\ntraces_internal <- function (object, pars, transform = FALSE, ...) {\n  transform <- as.logical(transform)\n  if (transform) {\n    retval <- cbind(\n      object@traces[,1L],\n      t(\n        partrans(\n          object,\n          params=t(object@traces)[-1L,,drop=FALSE],\n          dir=\"toEst\"\n        )\n      )\n    )\n    names(dimnames(retval)) <- names(dimnames(object@traces))\n  } else {\n    retval <- object@traces\n  }\n  if (missing(pars)) {\n    retval\n  } else {\n    pars <- as.character(pars)\n    bad.pars <- setdiff(pars,colnames(retval))\n    if (length(bad.pars)>0)\n      pStop(who=\"traces\",\n        ngettext(length(bad.pars),\"parameter \",\"parameters \"),\n        paste(sQuote(bad.pars),collapse=\",\"),\" not found.\")\n\n    retval[,pars,drop=FALSE]\n\n  }\n}\n"
  },
  {
    "path": "R/traj_match.R",
    "content": "##' Trajectory matching\n##'\n##' Estimation of parameters for deterministic \\acronym{POMP} models via trajectory matching.\n##'\n##' In trajectory matching, one attempts to minimize the discrepancy between a \\acronym{POMP} model's predictions and data under the assumption that the latent state process is deterministic and all discrepancies between model and data are due to measurement error.\n##' The measurement model likelihood (\\code{dmeasure}), or rather its negative, is the natural measure of the discrepancy.\n##'\n##' Trajectory matching is a generalization of the traditional nonlinear least squares approach.\n##' In particular, if, on some scale, measurement errors are normal with constant variance, then trajectory matching is equivalent to least squares on that particular scale.\n##'\n##' \\code{traj_objfun} constructs an objective function that evaluates the likelihood function.\n##' It can be passed to any one of a variety of numerical optimization routines, which will adjust model parameters to minimize the discrepancies between the power spectrum of model simulations and that of the data.\n##'\n##' @name traj_match\n##' @rdname traj_match\n##' @docType methods\n##' @include trajectory.R pomp_class.R workhorses.R\n##' @aliases traj_objfun traj_objfun,missing-method traj_objfun,ANY-method\n##' @concept trajectory matching\n##' @family deterministic methods\n##' @family methods based on maximization\n##' @inheritParams probe_match\n##' @inheritParams trajectory\n##' @inheritParams pomp\n##' @param \\dots additional arguments will modify the model structure\n##' @return\n##' \\code{traj_objfun} constructs a stateful objective function for spectrum matching.\n##' Specifically, \\code{traj_objfun} returns an object of class \\sQuote{traj_match_objfun}, which is a function suitable for use in an \\code{\\link[stats]{optim}}-like optimizer.\n##' In particular, this function takes a single numeric-vector argument that is assumed to contain the parameters named in \\code{est}, in that order.\n##' When called, it will return the negative log likelihood.\n##' It is a stateful function:\n##' Each time it is called, it will remember the values of the parameters and its estimate of the log likelihood.\n##' @inheritSection pomp Note for Windows users\n##' @inheritSection objfun Important Note\n##' @inheritSection objfun Warning! Objective functions based on C snippets\n##' @seealso \\code{\\link[stats]{optim}}, \\code{\\link[subplex]{subplex}}, \\code{\\link[nloptr]{nloptr}}\n##'\n##' @example examples/traj_match.R\n##'\nNULL\n\nsetClass(\n  \"traj_match_objfun\",\n  contains=\"function\",\n  slots=c(\n    env=\"environment\",\n    est=\"character\"\n  )\n)\n\nsetGeneric(\n  \"traj_objfun\",\n  function (data, ...)\n    standardGeneric(\"traj_objfun\")\n)\n\nsetMethod(\n  \"traj_objfun\",\n  signature=signature(data=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"traj_objfun\",\"data\")\n  }\n)\n\nsetMethod(\n  \"traj_objfun\",\n  signature=signature(data=\"ANY\"),\n  definition=function (data, ...) {\n    undef_method(\"traj_objfun\",data)\n  }\n)\n\n##' @rdname traj_match\n##' @export\nsetMethod(\n  \"traj_objfun\",\n  signature=signature(data=\"data.frame\"),\n  definition=function(\n    data,\n    ...,\n    est = character(0),\n    fail.value = NA,\n    ode_control = list(),\n    params, rinit, skeleton, dmeasure, partrans,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      tmof_internal(\n        data,\n        ...,\n        est=est,\n        fail.value=fail.value,\n        ode_control=ode_control,\n        params=params,\n        rinit=rinit,\n        skeleton=skeleton,\n        dmeasure=dmeasure,\n        partrans=partrans,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"traj_objfun\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname traj_match\n##' @export\nsetMethod(\n  \"traj_objfun\",\n  signature=signature(data=\"pomp\"),\n  definition=function (\n    data,\n    ...,\n    est = character(0),\n    fail.value = NA,\n    ode_control = list(),\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      tmof_internal(\n        data,\n        ...,\n        est=est,\n        fail.value=fail.value,\n        ode_control=ode_control,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"traj_objfun\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname traj_match\n##' @export\nsetMethod(\n  \"traj_objfun\",\n  signature=signature(data=\"traj_match_objfun\"),\n  definition=function (\n    data,\n    ...,\n    est,\n    fail.value,\n    ode_control,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    if (missing(est)) est <- data@est\n    if (missing(fail.value)) fail.value <- data@env$fail.value\n    if (missing(ode_control)) ode_control <- data@env$ode_control\n\n    traj_objfun(\n      data@env$object,\n      ...,\n      est=est,\n      fail.value=fail.value,\n      ode_control=ode_control,\n      verbose=verbose\n    )\n\n  }\n)\n\ntmof_internal <- function (\n  object,\n  ...,\n  est,\n  fail.value,\n  ode_control,\n  verbose\n) {\n\n  verbose <- as.logical(verbose)\n  object <- pomp(object,...,verbose=verbose)\n\n  if (undefined(object@skeleton) || undefined(object@dmeasure))\n    pStop_(paste(sQuote(c(\"skeleton\",\"dmeasure\")),collapse=\", \"),\n      \" are needed basic components.\")\n\n  fail.value <- as.numeric(fail.value)\n  .gnsi <- TRUE\n\n  est <- as.character(est)\n  est <- est[nzchar(est)]\n\n  params <- coef(object,transform=TRUE)\n\n  idx <- match(est,names(params))\n  if (any(is.na(idx))) {\n    missing <- est[is.na(idx)]\n    pStop_(\"parameter\",ngettext(length(missing),\"\",\"s\"),\" \",\n      paste(sQuote(missing),collapse=\",\"),\" not found in \",sQuote(\"params\"))\n  }\n\n  pompLoad(object,verbose=verbose)\n\n  loglik <- traj_match_logLik(object,ode_control=ode_control)\n\n  ofun <- function (par = numeric(0)) {\n    params[idx] <- par\n    coef(object,transform=TRUE,.gnsi=.gnsi) <<- params\n    loglik <<- traj_match_logLik(object,ode_control=ode_control,.gnsi=.gnsi)\n    .gnsi <<- FALSE\n    if (is.finite(loglik) || is.na(fail.value)) -loglik else fail.value\n  }\n\n  environment(ofun) <- list2env(\n    list(object=object,fail.value=fail.value,params=params,\n      idx=idx,loglik=loglik,ode_control=ode_control,.gnsi=.gnsi),\n    parent=parent.frame(2)\n  )\n\n  new(\"traj_match_objfun\",ofun,env=environment(ofun),est=est)\n\n}\n\ntraj_match_logLik <- function (object, ode_control, .gnsi = TRUE) {\n  object@states <- do.call(\n    flow,\n    c(list(object,x0=rinit(object),.gnsi=.gnsi),ode_control)\n  )\n  sum(\n    dmeasure(\n      object,\n      y=object@data,\n      x=object@states,\n      times=object@times,\n      params=object@params,\n      log=TRUE,\n      .gnsi=.gnsi\n    )\n  )\n}\n\n##' @rdname trajectory\n##' @export\nsetMethod(\n  \"trajectory\",\n  signature=signature(object=\"traj_match_objfun\"),\n  definition=function (\n    object,\n    ...,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    trajectory(\n      object@env$object,\n      ...,\n      verbose=verbose\n    )\n\n  }\n)\n"
  },
  {
    "path": "R/trajectory.R",
    "content": "##' Trajectory of a deterministic model\n##'\n##' Compute trajectories of the deterministic skeleton of a Markov process.\n##'\n##' In the case of a discrete-time system, the deterministic skeleton is a map and a trajectory is obtained by iterating the map.\n##' In the case of a continuous-time system, the deterministic skeleton is a vector-field;\n##' \\code{trajectory} uses the numerical solvers in \\pkg{\\link[deSolve]{deSolve}} to integrate the vectorfield.\n##'\n##' @name trajectory\n##' @rdname trajectory\n##' @include workhorses.R pomp_class.R flow.R\n##' @aliases trajectory,missing-method trajectory,ANY-method\n##' @family elementary algorithms\n##' @family deterministic methods\n##' @importFrom deSolve ode diagnostics\n##' @importFrom stats setNames\n##' @inheritParams simulate\n##' @inheritParams pomp\n##' @param object optional;\n##' if present, it should be a data frame or a \\sQuote{pomp} object.\n##' @param ode_control optional list;\n##' the elements of this list will be passed to \\code{\\link[deSolve]{ode}} if the skeleton is a vectorfield, and ignored if it is a map.\n##' @param format the format in which to return the results.\n##'\n##' \\code{format = \"pomps\"} causes the trajectories to be returned as a single \\sQuote{pomp} object (if a single parameter vector has been furnished to \\code{trajectory}) or as a \\sQuote{pompList} object (if a matrix of parameters have been furnished).\n##' In each of these, the \\code{states} slot will have been replaced by the computed trajectory.\n##' Use \\code{\\link{states}} to view these.\n##'\n##' \\code{format = \"array\"} causes the trajectories to be returned\n##' in a rank-3 array with dimensions\n##' \\code{nvar} x \\code{ncol(params)} x \\code{ntimes}.\n##' Here, \\code{nvar} is the number of state variables and \\code{ntimes} the length of the argument \\code{times}.\n##' Thus if \\code{x} is the returned array, \\code{x[i,j,k]} is the i-th component of the state vector at time \\code{times[k]} given parameters \\code{params[,j]}.\n##'\n##' \\code{format = \"data.frame\"} causes the results to be returned as a single data frame containing the time and states.\n##' An ordered factor variable, \\sQuote{.id}, distinguishes the trajectories from one another.\n##'\n##' @return\n##' The \\code{format} option controls the nature of the return value of \\code{trajectory}.\n##' See above for details.\n##' @example examples/trajectory.R\n##' @example examples/ricker-bifdiag.R\nNULL\n\nsetGeneric(\n  \"trajectory\",\n  function (object, ...)\n    standardGeneric(\"trajectory\")\n)\n\nsetMethod(\n  \"trajectory\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"trajectory\",\"object\")\n  }\n)\n\nsetMethod(\n  \"trajectory\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"trajectory\",object)\n  }\n)\n\n##' @rdname trajectory\n##' @export\nsetMethod(\n  \"trajectory\",\n  signature=signature(object=\"missing\"),\n  definition=function (\n    ...,\n    t0, times, params,\n    skeleton, rinit,\n    ode_control = list(),\n    format = c(\"pomps\", \"array\", \"data.frame\"),\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      trajectory_internal(\n        object=NULL,\n        ...,\n        t0=t0,\n        times=times,\n        params=params,\n        skeleton=skeleton,\n        rinit=rinit,\n        ode_control=ode_control,\n        format=format,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"trajectory\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname trajectory\n##' @export\nsetMethod(\n  \"trajectory\",\n  signature=signature(object=\"data.frame\"),\n  definition=function (\n    object,\n    ...,\n    t0, times, params,\n    skeleton, rinit,\n    ode_control = list(),\n    format = c(\"pomps\", \"array\", \"data.frame\"),\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      trajectory_internal(\n        object=object,\n        ...,\n        t0=t0,\n        times=times,\n        params=params,\n        skeleton=skeleton,\n        rinit=rinit,\n        ode_control=ode_control,\n        format=format,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"trajectory\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname trajectory\n##' @export\nsetMethod(\n  \"trajectory\",\n  signature=signature(object=\"pomp\"),\n  definition=function (\n    object,\n    ...,\n    params,\n    skeleton, rinit,\n    ode_control = list(),\n    format = c(\"pomps\", \"array\", \"data.frame\"),\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      trajectory_internal(\n        object=object,\n        ...,\n        params=params,\n        skeleton=skeleton,\n        rinit=rinit,\n        ode_control=ode_control,\n        format=format,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"trajectory\",conditionMessage(e))\n    )\n\n  }\n)\n\ntrajectory_internal <- function (\n  object,\n  ...,\n  params,\n  format = c(\"pomps\", \"array\", \"data.frame\"),\n  ode_control = list(),\n  .gnsi = TRUE,\n  verbose\n) {\n\n  format <- match.arg(format)\n  verbose <- as.logical(verbose)\n\n  object <- pomp(object,...,verbose=verbose)\n\n  if (missing(params)) params <- coef(object)\n  if (is.list(params)) params <- unlist(params)\n  if (is.null(params)) params <- numeric(0)\n  if (!is.numeric(params))\n    pStop_(sQuote(\"params\"),\" must be named and numeric.\")\n  params <- as.matrix(params)\n  storage.mode(params) <- \"double\"\n\n  if (ncol(params) == 1) object@params <- params[,1L]\n\n  pompLoad(object)\n  on.exit(pompUnload(object))\n\n  x0 <- rinit(object,params=params,.gnsi=.gnsi)\n\n  x <- do.call(\n    flow,\n    c(\n      list(object,x0=x0,params=params),\n      ode_control,\n      list(.gnsi=.gnsi,verbose=verbose)\n    )\n  )\n\n  repnames <- colnames(x)\n\n  if (format == \"data.frame\") {\n    x <- lapply(\n      seq_len(ncol(x)),\n      function (k) {\n        nm <- rownames(x)\n        y <- x[,k,,drop=FALSE]\n        dim(y) <- dim(y)[c(1L,3L)]\n        y <- as.data.frame(t(y))\n        names(y) <- nm\n        y[[object@timename]] <- object@times\n        y$.id <- as.integer(k)\n        y\n      }\n    )\n    x <- do.call(rbind,x)\n    x$.id <- ordered(x$.id)\n    if (!is.null(repnames)) {\n      levels(x$.id) <- repnames\n    }\n\n  } else if (format == \"pomps\") {\n    rv <- rep(list(object),ncol(x))\n    dy <- dim(x)[c(1L,3L)]\n    ny <- dimnames(x)[c(1L,3L)]\n    for (k in seq_len(ncol(x))) {\n      y <- x[,k,,drop=FALSE]\n      dim(y) <- dy\n      dimnames(y) <- ny\n      rv[[k]]@states <- y\n      rv[[k]]@params <- params[,k]\n    }\n    if (length(rv)>1) {\n      names(rv) <- colnames(x)\n      x <- do.call(c,rv)\n    } else {\n      x <- rv[[1]]\n    }\n  }\n\n  x\n}\n"
  },
  {
    "path": "R/transformations.R",
    "content": "##' Transformations\n##'\n##' Some useful parameter transformations.\n##'\n##' Parameter transformations can be used in many cases to recast constrained optimization problems as unconstrained problems.\n##' Although there are no limits to the transformations one can implement using the \\code{\\link{parameter_trans}} facilty, \\pkg{pomp} provides a few ready-built functions to implement some very commonly useful ones.\n##'\n##' @name transformations\n##' @rdname transformations\n##' @family implementation information\n##' @concept parameter transformations\n##'\nNULL\n\n##' @export\n##' @rdname transformations\n##'\n##' @param p numeric; a quantity in [0,1].\n##'\n##' @details\n##' The logit transformation takes a probability \\eqn{p} to its log odds, \\eqn{\\log\\frac{p}{1-p}}{log(p/(1-p))}.\n##' It maps the unit interval \\eqn{[0,1]} into the extended real line \\eqn{[-\\infty,\\infty]}.\n##'\nlogit <- function (p) {\n  .Call(P_LogitTransform,p)\n}\n\n##' @export\n##' @rdname transformations\n##'\n##' @param x numeric; the log odds ratio.\n##'\n##' @details The inverse of the logit transformation is the expit transformation.\n##'\nexpit <- function (x) {\n  .Call(P_ExpitTransform,x)\n}\n\n##' @export\n##' @rdname transformations\n##'\n##' @param X numeric; a vector containing the quantities to be transformed according to the log-barycentric transformation.\n##'\n##' @details\n##' The log-barycentric transformation takes a vector \\eqn{X\\in{R^{n}_+}}{X in the non-negative cone of R^n}, to a vector \\eqn{Y\\in{R^n}}{Y in R^n}, where \\deqn{Y_i = \\log\\frac{X_i}{\\sum_j X_j}.}{Yi = log(Xi/sum(X)).}\n##' The transformation is not one-to-one.\n##' However, for each \\eqn{c>0}, it maps the simplex \\eqn{\\{X\\in{R^n_+}:\\sum_i X_i = c\\}}{sum(X)=c} bijectively onto \\eqn{n}-dimensional Euclidean space \\eqn{R^n}.\n##'\nlog_barycentric <- function (X) {\n  .Call(P_LogBarycentricTransform,X)\n}\n\n##' @export\n##' @rdname transformations\n##'\n##' @param Y numeric; a vector containing the log fractions.\n##'\n##' @details\n##' The inverse of the log-barycentric transformation is implemented as \\code{inv_log_barycentric}.\n##' Note that it is not a true inverse, in the sense that it takes \\eqn{R^n} to the \\emph{unit} simplex, \\eqn{\\{X\\in{R^n_+}:\\sum_i X_i = 1\\}}{sum(X)=1}.\n##' Thus, \\preformatted{\n##'     log_barycentric(inv_log_barycentric(Y)) == Y,\n##' } but \\preformatted{\n##'     inv_log_barycentric(log_barycentric(X)) == X\n##' } only if \\code{sum(X) == 1}.\n##'\ninv_log_barycentric <- function (Y) {\n  .Call(P_InverseLogBarycentricTransform,Y)\n}\n"
  },
  {
    "path": "R/undefined.R",
    "content": "##' Undefined\n##'\n##' Check for undefined methods.\n##'\n##' @name undefined\n##' @rdname undefined\n##' @return\n##' Returns \\code{TRUE} if the \\pkg{pomp} workhorse method is undefined,\n##' \\code{FALSE} if it is defined,\n##' and \\code{NA} if the question is inapplicable.\n##' @include pstop.R\n##' @keywords internal\n##' @param object  object to test.\n##' @param ... currently ignored.\n##'\nNULL\n\nsetGeneric(\n  \"undefined\",\n  function (object, ...)\n    standardGeneric(\"undefined\")\n)\n\nsetMethod(\n  \"undefined\",\n  signature=signature(object=\"NULL\"),\n  definition=function (object, ...) TRUE\n)\n\nsetMethod(\n  \"undefined\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) NA\n)\n\nsetMethod(\n  \"undefined\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) NA\n)\n"
  },
  {
    "path": "R/userdata.R",
    "content": "##' Facilities for making additional information available to basic model components\n##'\n##' When \\acronym{POMP} basic components need information they can't get from parameters or covariates.\n##'\n##' It can happen that one desires to pass information to one of the \\acronym{POMP} model \\dfn{basic components} (see \\link[=basic_components]{here for a definition of this term}) outside of the standard routes (i.e., via model parameters or covariates).\n##' \\pkg{pomp} provides facilities for this purpose.\n##' We refer to the objects one wishes to pass in this way as \\dfn{user data}.\n##'\n##' The following will apply to every \\link[=basic_components]{basic model component}.\n##' For the sake of definiteness, however, we'll use the \\code{rmeasure} component as an example.\n##' To be even more specific, the measurement model we wish to implement is\n##' \\preformatted{\n##'       y1 ~ Poisson(x1+theta),  y2 ~ Poisson(x2+theta),}\n##' where \\code{theta} is a parameter.\n##' Although it would be very easy (and indeed far preferable) to include \\code{theta} among the ordinary parameters (by including it in \\code{params}), we will assume here that we have some reason for not wanting to do so.\n##'\n##' Now, we have the choice of providing \\code{rmeasure} in one of three ways:\n##' \\enumerate{\n##'   \\item as an \\R function,\n##'   \\item as a C snippet, or\n##'   \\item as a procedure in an external, dynamically loaded library.\n##' }\n##' We'll deal with these three cases in turn.\n##'\n##' @section When the basic component is specified as an \\R function:\n##' We can implement a simulator for the aforementioned measurement model so: \\preformatted{\n##'    f <- function (t, x, params, theta, ...) {\n##'       y <- rpois(n=2,x[c(\"x1\",\"x2\")]+theta)\n##'       setNames(y,c(\"y1\",\"y2\"))\n##'    }}\n##' So far, so good, but how do we get \\code{theta} to this function?\n##' We simply provide an additional argument to whichever \\pkg{pomp} algorithm we are employing (e.g., \\code{\\link{simulate}}, \\code{\\link{pfilter}}, \\code{\\link{mif2}}, \\code{\\link{abc}}, etc.).\n##' For example:\n##' \\preformatted{\n##'     simulate(..., rmeasure = f, userdata = list(theta = 42), ...)\n##' }\n##' where the \\code{\\dots} represent other arguments.\n##'\n##' @section When the basic component is specified via a C snippet:\n##' A C snippet implementation of the aforementioned measurement model is:\n##' \\preformatted{\n##'     f <- Csnippet(r\"{\n##'      double theta = *get_userdata_double(\"theta\");\n##'      y1 = rpois(x1+theta); y2 = rpois(x2+theta);\n##'     }\")}\n##' Here, the call to \\code{get_userdata_double} retrieves a \\emph{pointer} to the stored value of \\code{theta}.\n##' Note that, by using \\R string literals (\\code{r\"{}\"}) we avoid the need to escape the quotes in the C snippet text.\n##'\n##' It is possible to store and retrieve integer objects also, using \\code{get_userdata_int}.\n##'\n##' One must take care that one stores the user data with the appropriate storage type.\n##' For example, it is wise to wrap floating point scalars and vectors with \\code{as.double} and integers with \\code{as.integer}.\n##' In the present example, our call to simulate might look like\n##' \\preformatted{\n##'     simulate(..., rmeasure = f, userdata = list(theta = as.double(42)), ...)\n##' }\n##'\n##' Since the two functions \\code{get_userdata_double} and \\code{get_userdata_int} return pointers, it is trivial to pass vectors of double-precision and integers.\n##'\n##' A simpler and more elegant approach is afforded by the \\code{globals} argument (see below).\n##'\n##' @section When the basic component is specified via an external library:\n##'\n##' The rules are essentially the same as for C snippets.\n##' \\code{typedef} declarations for the \\code{get_userdata_double} and \\code{get_userdata_int} are given in the \\file{pomp.h} header file and these two routines are registered so that they can be retrieved via a call to \\code{R_GetCCallable}.\n##' See the \\href{https://cran.r-project.org/doc/manuals/R-exts.html}{Writing \\R extensions manual} for more information.\n##'\n##' @section Setting \\code{globals}:\n##'\n##' The use of the userdata facilities incurs a run-time cost.\n##' It is often more efficient, when using C snippets, to put the needed objects directly into the C snippet library.\n##' The \\code{globals} argument does this.\n##' See the example below.\n##'\n##' @example examples/userdata.R\n##'\n##' @name userdata\n##' @rdname userdata\n##' @include pomp.R pomp_class.R\n##' @family implementation information\n##'\nNULL\n"
  },
  {
    "path": "R/verhulst.R",
    "content": "##' Verhulst-Pearl model\n##'\n##' The Verhulst-Pearl (logistic) model of population growth.\n##'\n##' A stochastic version of the Verhulst-Pearl logistic model.\n##' This evolves in continuous time, according to the stochastic differential equation\n##' \\deqn{dn_t = r\\,n_t\\,\\left(1-\\frac{n_t}{K}\\right)\\,dt+\\sigma\\,n_t\\,dW_t.}{dn[t] = r n[t] (1-n[t]/K) dt + sigma n[t] dW[t].}\n##'\n##' Numerically, we simulate the stochastic dynamics using an Euler approximation.\n##'\n##' The measurements are assumed to be log-normally distributed:\n##' \\deqn{N_t \\sim \\mathrm{Lognormal}\\left(\\log{n_t},\\tau\\right).}{N[t] ~ Lognormal(log(n[t]),tau).}\n##'\n##' @name verhulst\n##' @rdname verhulst\n##' @docType data\n##' @family pomp examples\n##' @param r intrinsic growth rate\n##' @param K carrying capacity\n##' @param sigma environmental process noise s.d.\n##' @param tau measurement error s.d.\n##' @param n_0 initial condition\n##' @param dt Euler timestep\n##' @param seed seed of the random number generator\n##' @return\n##' A \\sQuote{pomp} object containing the model and simulated data.\n##' The following basic components are included in the \\sQuote{pomp} object:\n##' \\sQuote{rinit}, \\sQuote{rprocess}, \\sQuote{rmeasure}, \\sQuote{dmeasure}, and \\sQuote{skeleton}.\n##'\n##' @example examples/verhulst.R\n##'\nNULL\n\n##' @rdname verhulst\n##' @export\nverhulst <- function (\n  n_0 = 10000, K = 10000, r = 0.9,\n  sigma = 0.4, tau = 0.1, dt = 0.01,\n  seed=73658676L\n) {\n  simulate(\n    times=seq(0.1,by=0.1,length=1000),\n    t0=0,\n    params=c(n_0=n_0,K=K,r=r,sigma=sigma,tau=tau),\n    rprocess=euler(\n      step.fun=Csnippet(\"\n        n = rnorm(n+r*n*(1-n/K)*dt,sigma*n*sqrt(dt));\n      \"\n      ),\n      delta.t=dt\n    ),\n    emeasure=Csnippet(\"E_N = n*exp(tau*tau/2);\"),\n    vmeasure=Csnippet(\"\n      double et = exp(tau*tau);\n      V_N_N = n*n*et*(et-1);\"),\n    rmeasure=Csnippet(\"N = rlnorm(log(n),tau);\"),\n    dmeasure=Csnippet(\"lik = dlnorm(N,log(n),tau,give_log);\"),\n    skeleton=vectorfield(Csnippet(\"Dn = r*n*(1-n/K);\")),\n    rinit=Csnippet(\"n = n_0;\"),\n    paramnames=c(\"r\",\"K\",\"tau\",\"sigma\",\"n_0\"),\n    statenames=c(\"n\"),\n    obsnames=\"N\",\n    seed=seed\n  )\n}\n"
  },
  {
    "path": "R/vmeasure_spec.R",
    "content": "##' vmeasure specification\n##'\n##' Specification of the measurement-model covariance  matrix, vmeasure.\n##'\n##' @name vmeasure_spec\n##' @rdname vmeasure_spec\n##' @family implementation information\n##' @seealso \\code{\\link{vmeasure}}\n##'\n##' @details\n##' The measurement model is the link between the data and the unobserved state process.\n##' Some algorithms require the conditional covariance of the measurement model, given the latent state and parameters.\n##' This is supplied using the \\code{vmeasure} argument.\n##'\n##' Suppose you have a procedure to compute this conditional covariance matrix, given the value of the latent state variables.\n##' Then you can furnish \\preformatted{\n##'   vmeasure = f}\n##' to \\pkg{pomp} algorithms,\n##' where \\code{f} is a C snippet or \\R function that implements your procedure.\n##'\n##' Using a C snippet is much preferred, due to its much greater computational efficiency.\n##' See \\code{\\link{Csnippet}} for general rules on writing C snippets.\n##'\n##' In writing a \\code{vmeasure} C snippet, bear in mind that:\n##'   \\enumerate{\n##'     \\item The goal of such a snippet is to fill variables named \\code{V_y_z} with the conditional covariances of observables \\code{y}, \\code{z}.\n##'     Accordingly, there should be one assignment of \\code{V_y_z} and one assignment of \\code{V_z_y} for each pair of observables \\code{y} and \\code{z}.\n##'     \\item In addition to the states, parameters, and covariates (if any), the variable \\code{t}, containing the time of the observation, will be defined in the context in which the snippet is executed.\n##'   }\n##'\n##' The demos and the tutorials on the \\href{https://kingaa.github.io/pomp/}{package website} give examples.\n##'\n##' It is also possible, though less efficient, to specify \\code{vmeasure} using an \\R function.\n##' In this case, specify it by furnishing \\preformatted{\n##'   vmeasure = f}\n##' to \\code{pomp}, where \\code{f} is an \\R function.\n##' The arguments of \\code{f} should be chosen from among the state variables, parameters, covariates, and time.\n##' It must also have the argument \\code{...}.\n##' \\code{f} must return a square matrix of dimension equal to the number of observable variables.\n##' The row- and column-names of this matrix should match the names of the observable variables.\n##' The matrix should of course be symmetric.\n##'\n##' @section Default behavior:\n##' The default \\code{vmeasure} is undefined.\n##' It will yield missing values (\\code{NA}).\n##'\n##' @inheritSection pomp Note for Windows users\n##'\nNULL\n"
  },
  {
    "path": "R/window.R",
    "content": "##' Window\n##'\n##' Restrict to a portion of a time series.\n##'\n##' @name window\n##' @docType methods\n##' @rdname window\n##' @include pomp_class.R\nNULL\n\n##' @importFrom stats window\nsetGeneric(\"window\")\n\n##' @rdname window\n##' @param x a \\sQuote{pomp} object or object of class extending \\sQuote{pomp}\n##' @param start,end the left and right ends of the window, in units of time\n##' @param \\dots ignored\n##' @export\nsetMethod(\n  \"window\",\n  signature=signature(x=\"pomp\"),\n  definition=function (x, start, end, ...) {\n    tm <- time(x,t0=FALSE)\n    if (missing(start)) start <- tm[1L]\n    if (missing(end)) end <- tm[length(tm)]\n    if (!(is.numeric(start) && is.finite(start) && length(start)==1 &&\n            is.numeric(end) && is.finite(end) && length(end)==1))\n      pStop(who=\"window\",sQuote(\"start\"),\" and \",sQuote(\"end\"),\n        \" must be finite times.\")\n    if (!isTRUE(start <= end))\n      pStop(who=\"window\",sQuote(\"start\"),\n        \" must not be later than \",sQuote(\"end\"),\".\")\n    tm <- tm[(tm>=start)&(tm<=end)]\n    time(x,t0=FALSE) <- tm\n    x\n  }\n)\n"
  },
  {
    "path": "R/workhorses.R",
    "content": "##' Workhorse functions for the \\pkg{pomp} algorithms.\n##'\n##' These functions mediate the interface between the user's model and the package algorithms.\n##' They are low-level functions that do the work needed by the package's inference methods.\n##'\n##' They include \\describe{\n##' \\item{\\code{\\link{rinit}}}{which samples from the initial-state distribution,}\n##' \\item{\\code{\\link{dinit}}}{which evaluates the initial-state density,}\n##' \\item{\\code{\\link{dmeasure}}}{which evaluates the measurement model density,}\n##' \\item{\\code{\\link{rmeasure}}}{which samples from the measurement model distribution,}\n##' \\item{\\code{\\link{emeasure}}}{which computes the expectation of the observed variables conditional on the latent state,}\n##' \\item{\\code{\\link{vmeasure}}}{which computes the covariance matrix of the observed variables conditional on the latent state,}\n##' \\item{\\code{\\link{dprocess}}}{which evaluates the process model density,}\n##' \\item{\\code{\\link{rprocess}}}{which samples from the process model distribution,}\n##' \\item{\\code{\\link{dprior}}}{which evaluates the prior probability density,}\n##' \\item{\\code{\\link{rprior}}}{which samples from the prior distribution,}\n##' \\item{\\code{\\link{skeleton}}}{which evaluates the model's deterministic skeleton,}\n##' \\item{\\code{\\link{flow}}}{which iterates or integrates the deterministic skeleton to yield trajectories,}\n##' \\item{\\code{\\link{partrans}}}{which performs parameter transformations associated with the model.}\n##' }\n##'\n##' @name workhorses\n##' @include pomp_class.R pomp_fun.R load.R pstop.R\n##' @docType methods\n##' @family pomp workhorses\n##' @concept extending the pomp package\n##' @concept low-level interface\n##' @seealso \\link[=basic_components]{basic model components},\n##' \\link[=elementary_algorithms]{elementary algorithms},\n##' \\link[=estimation_algorithms]{estimation algorithms}\n##' @author Aaron A. King\n##' @concept extending the pomp package\n##' @concept low-level interface\nNULL\n\n##' dmeasure workhorse\n##'\n##' \\code{dmeasure} evaluates the probability density of observations given states.\n##' @name dmeasure\n##' @docType methods\n##' @aliases dmeasure,ANY-method dmeasure,missing-method\n##' @family pomp workhorses\n##' @concept extending the pomp package\n##' @concept low-level interface\n##' @seealso Specification of the measurement density evaluator: \\link{dmeasure_spec}\n##' @param object an object of class \\sQuote{pomp}, or of a class that extends \\sQuote{pomp}.\n##' This will typically be the output of \\code{pomp}, \\code{simulate}, or one of the \\pkg{pomp} inference algorithms.\n##' @param x an array containing states of the unobserved process.\n##' The dimensions of \\code{x} are \\code{nvars} x \\code{nrep} x \\code{ntimes},\n##' where \\code{nvars} is the number of state variables,\n##' \\code{nrep} is the number of replicates,\n##' and \\code{ntimes} is the length of \\code{times}.\n##' One can also pass \\code{x} as a named numeric vector, which is equivalent to the \\code{nrep=1}, \\code{ntimes=1} case.\n##' @param y a matrix containing observations.\n##' The dimensions of \\code{y} are \\code{nobs} x \\code{ntimes}, where \\code{nobs} is the number of observables\n##' and \\code{ntimes} is the length of \\code{times}.\n##' @param times a numeric vector (length \\code{ntimes}) containing times.\n##' These must be in non-decreasing order.\n##' @param params a \\code{npar} x \\code{nrep} matrix of parameters.\n##' Each column is treated as an independent parameter set, in correspondence with the corresponding column of \\code{x}.\n##' @param log if TRUE, log probabilities are returned.\n##' @param ... additional arguments are ignored.\n##' @return\n##' \\code{dmeasure} returns a matrix of dimensions \\code{nreps} x \\code{ntimes}.\n##' If \\code{d} is the returned matrix, \\code{d[j,k]} is the likelihood (or log likelihood if \\code{log = TRUE}) of the observation \\code{y[,k]} at time \\code{times[k]} given the state \\code{x[,j,k]}.\n##'\nNULL\n\nsetGeneric(\n  \"dmeasure\",\n  function (object, ...)\n    standardGeneric(\"dmeasure\")\n)\n\nsetMethod(\n  \"dmeasure\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"dmeasure\",\"object\")\n  }\n)\n\nsetMethod(\n  \"dmeasure\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"dmeasure\",object)\n  }\n)\n\n##' @export\n##' @rdname dmeasure\nsetMethod(\n  \"dmeasure\",\n  signature=signature(object=\"pomp\"),\n  definition=function (\n    object,\n    ...,\n    y = obs(object),\n    x = states(object),\n    times = time(object),\n    params = coef(object),\n    log = FALSE\n  ) {\n    tryCatch(\n      dmeasure_internal(object=object,y=y,x=x,times=times,\n        params=params,log=log,...),\n      error = function (e) pStop(who=\"dmeasure\",conditionMessage(e))\n    )\n  }\n)\n\ndmeasure_internal <- function (\n  object,\n  y, x, times, params,\n  log = FALSE,\n  .gnsi = TRUE\n) {\n  storage.mode(y) <- \"double\"\n  storage.mode(x) <- \"double\"\n  storage.mode(params) <- \"double\"\n  pompLoad(object)\n  on.exit(pompUnload(object))\n  .Call(P_do_dmeasure,object,y,x,times,params,log,.gnsi)\n}\n\n##' dprior workhorse\n##'\n##' Evaluates the prior probability density.\n##'\n##' @name dprior\n##' @docType methods\n##' @aliases dprior,ANY-method dprior,missing-method\n##' @family pomp workhorses\n##' @family Bayesian methods\n##' @concept extending the pomp package\n##' @concept low-level interface\n##' @seealso Specification of the prior density evaluator: \\link{prior_spec}\n##' @inheritParams dmeasure\n##' @return\n##' The required density (or log density), as a numeric vector.\n##'\nNULL\n\nsetGeneric(\n  \"dprior\",\n  function (object, ...)\n    standardGeneric(\"dprior\")\n)\n\nsetMethod(\n  \"dprior\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"dprior\",\"object\")\n  }\n)\n\nsetMethod(\n  \"dprior\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"dprior\",object)\n  }\n)\n\n##' @export\n##' @rdname dprior\nsetMethod(\n  \"dprior\",\n  signature=signature(object=\"pomp\"),\n  definition=function (\n    object,\n    ...,\n    params = coef(object),\n    log = FALSE\n  ) {\n    tryCatch(\n      dprior_internal(object=object,params=params,log=log,...),\n      error = function (e) pStop(who=\"dprior\",conditionMessage(e))\n    )\n  }\n)\n\ndprior_internal <- function (\n  object,\n  params,\n  log = FALSE,\n  .gnsi = TRUE\n) {\n  storage.mode(params) <- \"double\"\n  pompLoad(object)\n  on.exit(pompUnload(object))\n  .Call(P_do_dprior,object,params,log,.gnsi)\n}\n\n##' dprocess workhorse\n##'\n##' Evaluates the probability density of a sequence of consecutive state transitions.\n##'\n##' @name dprocess\n##' @docType methods\n##' @aliases dprocess,ANY-method dprocess,missing-method\n##' @family pomp workhorses\n##' @concept extending the pomp package\n##' @concept low-level interface\n##' @seealso Specification of the process-model density evaluator: \\link{dprocess_spec}\n##' @inheritParams dmeasure\n##' @return\n##' \\code{dprocess} returns a matrix of dimensions \\code{nrep} x \\code{ntimes-1}.\n##' If \\code{d} is the returned matrix, \\code{d[j,k]} is the likelihood (or the log likelihood if \\code{log=TRUE}) of the transition from state \\code{x[,j,k-1]} at time \\code{times[k-1]} to state \\code{x[,j,k]} at time \\code{times[k]}.\n##'\nNULL\n\nsetGeneric(\n  \"dprocess\",\n  function (object, ...)\n    standardGeneric(\"dprocess\")\n)\n\nsetMethod(\n  \"dprocess\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"dprocess\",\"object\")\n  }\n)\n\nsetMethod(\n  \"dprocess\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"dprocess\",object)\n  }\n)\n\n##' @export\n##' @rdname dprocess\nsetMethod(\n  \"dprocess\",\n  signature=signature(object=\"pomp\"),\n  definition = function (\n    object,\n    ...,\n    x = states(object),\n    times = time(object),\n    params = coef(object),\n    log = FALSE\n  ) {\n    tryCatch(\n      dprocess_internal(object=object,x=x,times=times,params=params,log=log,...),\n      error = function (e) pStop(who=\"dprocess\",conditionMessage(e))\n    )\n  }\n)\n\ndprocess_internal <- function (\n  object,\n  x, times, params,\n  log = FALSE,\n  .gnsi = TRUE\n) {\n  storage.mode(x) <- \"double\"\n  storage.mode(params) <- \"double\"\n  pompLoad(object)\n  on.exit(pompUnload(object))\n  .Call(P_do_dprocess,object,x,times,params,log,.gnsi)\n}\n\n##' partrans workhorse\n##'\n##' Performs parameter transformations.\n##'\n##' @name partrans\n##' @docType methods\n##' @aliases partrans,ANY-method partrans,missing-method\n##' @family pomp workhorses\n##' @concept extending the pomp package\n##' @concept low-level interface\n##' @seealso Specification of parameter transformations: \\code{\\link{parameter_trans}}\n##' @inheritParams dmeasure\n##' @param dir the direction of the transformation to perform.\n##' @return\n##' If \\code{dir=fromEst}, the parameters in \\code{params} are assumed to be on the estimation scale and are transformed onto the natural scale.\n##' If \\code{dir=toEst}, they are transformed onto the estimation scale.\n##' In both cases, the parameters are returned as a named numeric vector or an array with rownames, as appropriate.\n##'\nNULL\n\nsetGeneric(\n  \"partrans\",\n  function (object, ...)\n    standardGeneric(\"partrans\")\n)\n\nsetMethod(\n  \"partrans\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"partrans\",\"object\")\n  }\n)\n\nsetMethod(\n  \"partrans\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"partrans\",object)\n  }\n)\n\n##' @export\n##' @rdname partrans\nsetMethod(\n  \"partrans\",\n  signature=signature(object=\"pomp\"),\n  definition=function (\n    object,\n    params,\n    ...,\n    dir = c(\"fromEst\", \"toEst\")\n  ) {\n    dir <- match.arg(dir)\n    tryCatch(\n      partrans_internal(object=object,params=params,dir=dir,...),\n      error = function (e) pStop(who=\"partrans\",conditionMessage(e))\n    )\n  }\n)\n\npartrans_internal <- function (\n  object,\n  params,\n  dir = c(\"fromEst\", \"toEst\"),\n  .gnsi = TRUE\n) {\n  if (object@partrans@has) {\n    dir <- switch(dir,fromEst=-1L,toEst=1L)\n    pompLoad(object)\n    on.exit(pompUnload(object))\n    params <- .Call(P_do_partrans,object,params,dir,.gnsi)\n  }\n  params\n}\n\n##' rinit workhorse\n##'\n##' Samples from the initial-state distribution.\n##'\n##' @name rinit\n##' @docType methods\n##' @aliases rinit,ANY-method rinit,missing-method\n##' @family pomp workhorses\n##' @concept extending the pomp package\n##' @concept low-level interface\n##' @seealso_spec of the initial-state distribution: \\link{rinit_spec}\n##' @inheritParams dmeasure\n##' @param t0 the initial time, i.e., the time corresponding to the initial-state distribution.\n##' @param nsim optional integer; the number of initial states to simulate per column of \\code{params}.\n##' @return\n##' \\code{rinit} returns an \\code{nvar} x \\code{nsim*ncol(params)} matrix of state-process initial conditions when given an \\code{npar} x \\code{nsim} matrix of parameters, \\code{params}, and an initial time \\code{t0}.\n##' By default, \\code{t0} is the initial time defined when the \\sQuote{pomp} object ws constructed.\n##'\nNULL\n\nsetGeneric(\n  \"rinit\",\n  function (object, ...)\n    standardGeneric(\"rinit\")\n)\n\nsetMethod(\n  \"rinit\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"rinit\",\"object\")\n  }\n)\n\nsetMethod(\n  \"rinit\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"rinit\",object)\n  }\n)\n\n##' @export\n##' @rdname rinit\nsetMethod(\n  \"rinit\",\n  signature=signature(\"pomp\"),\n  definition=function (\n    object,\n    ...,\n    params = coef(object),\n    t0 = timezero(object),\n    nsim = 1\n  ) {\n    tryCatch(\n      rinit_internal(object=object,params=params,t0=t0,nsim=nsim,...),\n      error = function (e) pStop(who=\"rinit\",conditionMessage(e))\n    )\n  }\n)\n\nrinit_internal <- function (\n  object,\n  params, t0,\n  nsim = 1,\n  .gnsi = TRUE\n) {\n  storage.mode(params) <- \"double\"\n  pompLoad(object)\n  on.exit(pompUnload(object))\n  .Call(P_do_rinit,object,params,t0,nsim,.gnsi)\n}\n\n##' dinit workhorse\n##'\n##' Evaluates the initial-state density.\n##'\n##' @name dinit\n##' @docType methods\n##' @aliases dinit,ANY-method dinit,missing-method\n##' @family pomp workhorses\n##' @concept extending the pomp package\n##' @concept low-level interface\n##' @seealso Specification of the initial-state distribution: \\link{dinit_spec}\n##' @inheritParams dmeasure\n##' @param t0 the initial time, i.e., the time corresponding to the initial-state distribution.\n##' @return\n##' \\code{dinit} returns a 1-D numerical array containing the likelihoods (or log likelihoods if \\code{log=TRUE}).\n##' By default, \\code{t0} is the initial time defined when the \\sQuote{pomp} object ws constructed.\n##'\nNULL\n\nsetGeneric(\n  \"dinit\",\n  function (object, ...)\n    standardGeneric(\"dinit\")\n)\n\nsetMethod(\n  \"dinit\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"dinit\",\"object\")\n  }\n)\n\nsetMethod(\n  \"dinit\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"dinit\",object)\n  }\n)\n\n##' @export\n##' @rdname dinit\nsetMethod(\n  \"dinit\",\n  signature=signature(\"pomp\"),\n  definition=function (\n    object,\n    ...,\n    params = coef(object),\n    t0 = timezero(object),\n    x,\n    log = FALSE\n  ) {\n    tryCatch(\n      dinit_internal(object=object,x=x,params=params,t0=t0,log=log,...),\n      error = function (e) pStop(who=\"dinit\",conditionMessage(e))\n    )\n  }\n)\n\ndinit_internal <- function (\n  object,\n  x, params, t0,\n  log,\n  .gnsi = TRUE\n) {\n  storage.mode(x) <- \"double\"\n  storage.mode(params) <- \"double\"\n  pompLoad(object)\n  on.exit(pompUnload(object))\n  .Call(P_do_dinit,object,t0,x,params,log,.gnsi)\n}\n\n##' rmeasure workhorse\n##'\n##' Sample from the measurement model distribution, given values of the latent states and the parameters.\n##'\n##' @name rmeasure\n##' @docType methods\n##' @aliases rmeasure,ANY-method rmeasure,missing-method\n##' @family pomp workhorses\n##' @concept extending the pomp package\n##' @concept low-level interface\n##' @seealso Specification of the measurement-model simulator: \\link{rmeasure_spec}\n##' @inheritParams dmeasure\n##' @return\n##' \\code{rmeasure} returns a rank-3 array of dimensions\n##' \\code{nobs} x \\code{nrep} x \\code{ntimes},\n##' where \\code{nobs} is the number of observed variables.\n##'\nNULL\n\nsetGeneric(\n  \"rmeasure\",\n  function (object, ...)\n    standardGeneric(\"rmeasure\")\n)\n\nsetMethod(\n  \"rmeasure\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"rmeasure\",\"object\")\n  }\n)\n\nsetMethod(\n  \"rmeasure\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"rmeasure\",object)\n  }\n)\n\n##' @export\n##' @rdname rmeasure\nsetMethod(\n  \"rmeasure\",\n  signature=signature(object=\"pomp\"),\n  definition=function (\n    object,\n    ...,\n    x = states(object),\n    times = time(object),\n    params = coef(object)\n  ) {\n    tryCatch(\n      rmeasure_internal(object=object,x=x,times=times,params=params,...),\n      error = function (e) pStop(who=\"rmeasure\",conditionMessage(e))\n    )\n  }\n)\n\nrmeasure_internal <- function (\n  object,\n  x, times, params,\n  .gnsi = TRUE\n) {\n  storage.mode(x) <- \"double\"\n  storage.mode(params) <- \"double\"\n  pompLoad(object)\n  on.exit(pompUnload(object))\n  .Call(P_do_rmeasure,object,x,times,params,.gnsi)\n}\n\n##' emeasure workhorse\n##'\n##' Return the expected value of the observed variables, given values of the latent states and the parameters.\n##'\n##' @name emeasure\n##' @docType methods\n##' @aliases emeasure,ANY-method emeasure,missing-method\n##' @family pomp workhorses\n##' @seealso Specification of the measurement-model expectation: \\link{emeasure_spec}\n##' @inheritParams dmeasure\n##' @return\n##' \\code{emeasure} returns a rank-3 array of dimensions\n##' \\code{nobs} x \\code{nrep} x \\code{ntimes},\n##' where \\code{nobs} is the number of observed variables.\n##'\nNULL\n\nsetGeneric(\n  \"emeasure\",\n  function (object, ...)\n    standardGeneric(\"emeasure\")\n)\n\nsetMethod(\n  \"emeasure\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"emeasure\",\"object\")\n  }\n)\n\nsetMethod(\n  \"emeasure\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"emeasure\",object)\n  }\n)\n\n##' @export\n##' @rdname emeasure\nsetMethod(\n  \"emeasure\",\n  signature=signature(object=\"pomp\"),\n  definition=function (\n    object,\n    ...,\n    x = states(object),\n    times = time(object),\n    params = coef(object)\n  ) {\n    tryCatch(\n      emeasure_internal(object=object,x=x,times=times,params=params,...),\n      error = function (e) pStop(who=\"emeasure\",conditionMessage(e))\n    )\n  }\n)\n\nemeasure_internal <- function (\n  object,\n  x, times, params,\n  .gnsi = TRUE\n) {\n  storage.mode(x) <- \"double\"\n  storage.mode(params) <- \"double\"\n  pompLoad(object)\n  on.exit(pompUnload(object))\n  .Call(P_do_emeasure,object,x,times,params,.gnsi)\n}\n\n##' vmeasure workhorse\n##'\n##' Return the covariance matrix of the observed variables, given values of the latent states and the parameters.\n##'\n##' @name vmeasure\n##' @docType methods\n##' @aliases vmeasure,ANY-method vmeasure,missing-method\n##' @family pomp workhorses\n##' @seealso Specification of the measurement-model covariance matrix: \\link{vmeasure_spec}\n##' @inheritParams dmeasure\n##' @return\n##' \\code{vmeasure} returns a rank-4 array of dimensions\n##' \\code{nobs} x \\code{nobs} x \\code{nrep} x \\code{ntimes},\n##' where \\code{nobs} is the number of observed variables.\n##' If \\code{v} is the returned array, \\code{v[,,j,k]} contains the\n##' covariance matrix at time \\code{times[k]} given the state \\code{x[,j,k]}.\n##'\nNULL\n\nsetGeneric(\n  \"vmeasure\",\n  function (object, ...)\n    standardGeneric(\"vmeasure\")\n)\n\nsetMethod(\n  \"vmeasure\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"vmeasure\",\"object\")\n  }\n)\n\nsetMethod(\n  \"vmeasure\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"vmeasure\",object)\n  }\n)\n\n##' @export\n##' @rdname vmeasure\nsetMethod(\n  \"vmeasure\",\n  signature=signature(object=\"pomp\"),\n  definition=function (\n    object,\n    ...,\n    x = states(object),\n    times = time(object),\n    params = coef(object)\n  ) {\n    tryCatch(\n      vmeasure_internal(object=object,x=x,times=times,params=params,...),\n      error = function (e) pStop(who=\"vmeasure\",conditionMessage(e))\n    )\n  }\n)\n\nvmeasure_internal <- function (\n  object,\n  x, times, params,\n  .gnsi = TRUE\n) {\n  storage.mode(x) <- \"double\"\n  storage.mode(params) <- \"double\"\n  pompLoad(object)\n  on.exit(pompUnload(object))\n  .Call(P_do_vmeasure,object,x,times,params,.gnsi)\n}\n\n##' rprior workhorse\n##'\n##' Sample from the prior probability distribution.\n##'\n##' @name rprior\n##' @docType methods\n##' @aliases rprior,ANY-method rprior,missing-method\n##' @family pomp workhorses\n##' @family Bayesian methods\n##' @concept extending the pomp package\n##' @concept low-level interface\n##' @seealso Specification of the prior distribution simulator: \\link{prior_spec}\n##' @inheritParams dmeasure\n##' @return\n##' A numeric matrix containing the required samples.\n##'\nNULL\n\nsetGeneric(\n  \"rprior\",\n  function (object, ...)\n    standardGeneric(\"rprior\")\n)\n\nsetMethod(\n  \"rprior\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"rprior\",\"object\")\n  }\n)\n\nsetMethod(\n  \"rprior\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"rprior\",object)\n  }\n)\n\n##' @export\n##' @rdname rprior\nsetMethod(\n  \"rprior\",\n  signature=signature(object=\"pomp\"),\n  definition=function (\n    object,\n    ...,\n    params = coef(object)\n  )\n    tryCatch(\n      rprior_internal(object=object,params=params,...),\n      error = function (e) pStop(who=\"rprior\",conditionMessage(e))\n    )\n)\n\nrprior_internal <- function (\n  object,\n  params,\n  .gnsi = TRUE\n) {\n  storage.mode(params) <- \"double\"\n  pompLoad(object)\n  on.exit(pompUnload(object))\n  .Call(P_do_rprior,object,params,.gnsi)\n}\n\n##' rprocess workhorse\n##'\n##' \\code{rprocess} simulates the process-model portion of partially-observed Markov process.\n##'\n##' When \\code{rprocess} is called, \\code{t0} is taken to be the initial time (i.e., that corresponding to \\code{x0}).\n##' The values in \\code{times} are the times at which the state of the simulated processes are required.\n##'\n##' @name rprocess\n##' @docType methods\n##' @aliases rprocess,ANY-method rprocess,missing-method\n##' @family pomp workhorses\n##' @concept extending the pomp package\n##' @concept low-level interface\n##' @seealso Specification of the process-model simulator: \\link{rprocess_spec}\n##' @inheritParams dmeasure\n##' @param x0 an \\code{nvar} x \\code{nrep} matrix containing the starting state of the system.\n##' Columns of \\code{x0} correspond to states;\n##' rows to components of the state vector.\n##' One independent simulation will be performed for each column.\n##' Note that in this case, \\code{params} must also have \\code{nrep} columns.\n##' @param t0 the initial time, i.e., the time corresponding to the state in \\code{x0}.\n##' @param params a \\code{npar} x \\code{nrep} matrix of parameters.\n##' Each column is treated as an independent parameter set, in correspondence with the corresponding column of \\code{x0}.\n##' @return\n##' \\code{rprocess} returns a rank-3 array with rownames.\n##' Suppose \\code{x} is the array returned.\n##' Then \\preformatted{dim(x)=c(nvars,nrep,ntimes),}\n##' where \\code{nvars} is the number of state variables (=\\code{nrow(x0)}),\n##' \\code{nrep} is the number of independent realizations simulated (=\\code{ncol(x0)}), and\n##' \\code{ntimes} is the length of the vector \\code{times}.\n##' \\code{x[,j,k]} is the value of the state process in the \\code{j}-th realization at time \\code{times[k]}.\n##' The rownames of \\code{x} will correspond to those of \\code{x0}.\n##'\nNULL\n\nsetGeneric(\n  \"rprocess\",\n  function (object, ...)\n    standardGeneric(\"rprocess\")\n)\n\nsetMethod(\n  \"rprocess\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"rprocess\",\"object\")\n  }\n)\n\nsetMethod(\n  \"rprocess\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"rprocess\",object)\n  }\n)\n\n##' @export\n##' @rdname rprocess\nsetMethod(\n  \"rprocess\",\n  signature=signature(object=\"pomp\"),\n  definition=function (\n    object,\n    ...,\n    x0 = rinit(object),\n    t0 = timezero(object),\n    times = time(object),\n    params = coef(object)\n  ) {\n    tryCatch(\n      rprocess_internal(object=object,x0=x0,t0=t0,times=times,params=params,...),\n      error = function (e) pStop(who=\"rprocess\",conditionMessage(e))\n    )\n  }\n)\n\nrprocess_internal <- function (\n  object,\n  x0, t0, times, params,\n  .gnsi = TRUE\n) {\n  storage.mode(x0) <- \"double\"\n  storage.mode(params) <- \"double\"\n  pompLoad(object)\n  on.exit(pompUnload(object))\n  .Call(P_do_rprocess,object,x0,t0,times,params,.gnsi)\n}\n\n##' skeleton workhorse\n##'\n##' Evaluates the deterministic skeleton at a point or points in state space, given parameters.\n##' In the case of a discrete-time system, the skeleton is a map.\n##' In the case of a continuous-time system, the skeleton is a vectorfield.\n##' NB: \\code{skeleton} just evaluates the deterministic skeleton;\n##' it does not iterate or integrate (see \\code{\\link{flow}} and \\code{\\link{trajectory}} for this).\n##'\n##' @name skeleton\n##' @docType methods\n##' @aliases skeleton,ANY-method skeleton,missing-method\n##' @family pomp workhorses\n##' @family deterministic methods\n##' @concept extending the pomp package\n##' @concept low-level interface\n##' @seealso Specification of the deterministic skeleton: \\link{skeleton_spec}\n##' @inheritParams dmeasure\n##' @return\n##' \\code{skeleton} returns an array of dimensions \\code{nvar} x \\code{nrep} x \\code{ntimes}.\n##' If \\code{f} is the returned matrix, \\code{f[i,j,k]} is the i-th component of the deterministic skeleton at time \\code{times[k]} given the state \\code{x[,j,k]} and parameters \\code{params[,j]}.\n##'\nNULL\n\nsetGeneric(\n  \"skeleton\",\n  function (object, ...)\n    standardGeneric(\"skeleton\")\n)\n\nsetMethod(\n  \"skeleton\",\n  signature=signature(object=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"skeleton\",\"object\")\n  }\n)\n\nsetMethod(\n  \"skeleton\",\n  signature=signature(object=\"ANY\"),\n  definition=function (object, ...) {\n    undef_method(\"skeleton\",object)\n  }\n)\n\n##' @export\n##' @rdname skeleton\nsetMethod(\n  \"skeleton\",\n  signature=signature(\"pomp\"),\n  definition=function (\n    object,\n    ...,\n    x = states(object),\n    times = time(object),\n    params = coef(object)\n  )\n    tryCatch(\n      skeleton_internal(object=object,x=x,times=times,params=params,...),\n      error = function (e) pStop(who=\"skeleton\",conditionMessage(e))\n    )\n)\n\nskeleton_internal <- function (\n  object,\n  x, times, params,\n  .gnsi = TRUE\n) {\n  storage.mode(x) <- \"double\"\n  storage.mode(params) <- \"double\"\n  pompLoad(object)\n  on.exit(pompUnload(object))\n  .Call(P_do_skeleton,object,x,times,params,.gnsi)\n}\n"
  },
  {
    "path": "R/wpfilter.R",
    "content": "##' Weighted particle filter\n##'\n##' A sequential importance sampling (particle filter) algorithm.\n##' Unlike in \\code{pfilter}, resampling is performed only when triggered by\n##' deficiency in the effective sample size.\n##'\n##' \\bold{This function is experimental and should be considered in alpha stage.\n##' Both interface and underlying algorithms may change without warning at any time.\n##' Please explore the function and give feedback via the \\pkg{pomp} Issues page.}\n##'\n##' @name wpfilter\n##' @rdname wpfilter\n##' @aliases wpfilter,ANY-method wpfilter,missing-method\n##' @author Aaron A. King\n##' @family elementary algorithms\n##' @family particle filter methods\n##' @family full-information methods\n##' @inheritSection pomp Note for Windows users\n##' @include pomp_class.R pomp.R rprocess_spec.R dmeasure_spec.R pfilter.R\n##' @importFrom stats setNames\n##' @inheritParams pfilter\n##' @param trigger numeric; if the effective sample size becomes smaller than \\code{trigger * Np}, resampling is triggered.\n##' @param target numeric; target power.\n##'\n##' @return\n##' An object of class \\sQuote{wpfilterd_pomp}, which extends class \\sQuote{pomp}.\n##' Information can be extracted from this object using the methods documented below.\n##'\n##' @section Methods:\n##' \\describe{\n##' \\item{\\code{\\link{logLik}}}{ the estimated log likelihood}\n##' \\item{\\code{\\link{cond_logLik}}}{ the estimated conditional log likelihood}\n##' \\item{\\code{\\link{eff_sample_size}}}{the (time-dependent) estimated effective sample size}\n##' \\item{\\code{\\link{as.data.frame}}}{ coerce to a data frame}\n##' \\item{\\code{\\link{plot}}}{diagnostic plots}\n##' }\n##'\n##' @references\n##'\n##' \\Arulampalam2002\n##'\nNULL\n\nsetClass(\n  \"wpfilterd_pomp\",\n  contains=\"pfilterd_pomp\",\n  slots=c(\n    trigger=\"numeric\",\n    target=\"numeric\"\n  ),\n  prototype=prototype(\n    trigger=0.0,\n    target=0.5\n  )\n)\n\nsetGeneric(\n  \"wpfilter\",\n  function (data, ...)\n    standardGeneric(\"wpfilter\")\n)\n\nsetMethod(\n  \"wpfilter\",\n  signature=signature(data=\"missing\"),\n  definition=function (...) {\n    reqd_arg(\"wpfilter\",\"data\")\n  }\n)\n\nsetMethod(\n  \"wpfilter\",\n  signature=signature(data=\"ANY\"),\n  definition=function (data, ...) {\n    undef_method(\"wpfilter\",data)\n  }\n)\n\n##' @rdname wpfilter\n##' @export\nsetMethod(\n  \"wpfilter\",\n  signature=signature(data=\"data.frame\"),\n  definition=function (\n    data,\n    ...,\n    Np,\n    params, rinit, rprocess, dmeasure,\n    trigger = 1, target = 0.5,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      wpfilter_internal(\n        data,\n        ...,\n        Np=Np,\n        rinit=rinit,\n        rprocess=rprocess,\n        dmeasure=dmeasure,\n        params=params,\n        trigger=trigger,\n        target=target,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"wpfilter\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname wpfilter\n##' @export\nsetMethod(\n  \"wpfilter\",\n  signature=signature(data=\"pomp\"),\n  definition=function (\n    data,\n    ...,\n    Np,\n    trigger = 1, target = 0.5,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    tryCatch(\n      wpfilter_internal(\n        data,\n        ...,\n        Np=Np,\n        trigger=trigger,\n        target=target,\n        verbose=verbose\n      ),\n      error = function (e) pStop(who=\"wpfilter\",conditionMessage(e))\n    )\n\n  }\n)\n\n##' @rdname wpfilter\n##' @export\nsetMethod(\n  \"wpfilter\",\n  signature=signature(data=\"wpfilterd_pomp\"),\n  function (\n    data,\n    ...,\n    Np, trigger, target,\n    verbose = getOption(\"verbose\", FALSE)\n  ) {\n\n    if (missing(Np)) Np <- data@Np\n    if (missing(trigger)) trigger <- data@trigger\n    if (missing(target)) target <- data@target\n\n    wpfilter(\n      as(data,\"pomp\"),\n      ...,\n      Np=Np,\n      trigger=trigger,\n      target=target,\n      verbose=verbose\n    )\n\n  }\n)\n\nwpfilter_internal <- function (\n  object,\n  ...,\n  Np, trigger, target,\n  .gnsi = TRUE, verbose = FALSE\n) {\n\n  verbose <- as.logical(verbose)\n\n  object <- pomp(object,...,verbose=verbose)\n\n  if (undefined(object@rprocess) || undefined(object@dmeasure))\n    pStop_(paste(sQuote(c(\"rprocess\",\"dmeasure\")),collapse=\", \"),\" are needed basic components.\")\n\n  gnsi <- as.logical(.gnsi)\n\n  params <- coef(object)\n  times <- time(object,t0=TRUE)\n  ntimes <- length(times)-1\n\n  Np <- np_check(Np,ntimes)\n\n  pompLoad(object,verbose=verbose)\n  on.exit(pompUnload(object,verbose=verbose))\n\n  trigger <- as.numeric(trigger)\n  if (length(trigger)!=1L || !is.finite(trigger) || trigger < 0)\n    pStop_(sQuote(\"trigger\"),\" should be a non-negative scalar.\")\n  target <- as.numeric(target)\n  if (length(target)!=1L || !is.finite(trigger) || target < 0 || target > 1)\n    pStop_(sQuote(\"target\"),\" should be a scalar in [0,1].\")\n\n  x <- rinit(object,params=params,nsim=Np[1L],.gnsi=gnsi)\n\n  loglik <- rep(NA,ntimes)\n  eff.sample.size <- numeric(ntimes)\n  W <- numeric(Np[1L])\n\n  for (nt in seq_len(ntimes)) { ## main loop\n\n    ## advance the state variables according to the process model\n    X <- rprocess(object,x0=x,t0=times[nt],times=times[nt+1],params=params,.gnsi=gnsi)\n\n    ## density of Y_t | X_t\n    w <- dmeasure(object,y=object@data[,nt,drop=FALSE],x=X,\n      times=times[nt+1],params=params,log=TRUE,.gnsi=gnsi)\n    gnsi <- FALSE\n\n    ## compute effective sample size, log-likelihood.\n    xx <- .Call(P_wpfilter_comps,X,params,W,w,trigger,target,Np[nt+1])\n\n    ## the following is triggered by the first illegal weight value\n    if (is.integer(xx)) {\n      illegal_dmeasure_error(\n        time=times[nt+1],\n        loglik=w[xx],\n        datvals=object@data[,nt],\n        states=X[,xx,1L],\n        params=params\n      )\n    }\n\n    x <- xx$states\n    params <- xx$params[,1L]\n    W <- xx$weights\n    loglik[nt] <- xx$loglik\n    eff.sample.size[nt] <- xx$ess\n\n  } ## end of main loop\n\n  new(\n    \"wpfilterd_pomp\",\n    object,\n    trigger=trigger,\n    target=target,\n    eff.sample.size=eff.sample.size,\n    cond.logLik=loglik,\n    Np=as.integer(Np),\n    loglik=sum(loglik)\n  )\n}\n"
  },
  {
    "path": "R/wquant.R",
    "content": "##' Weighted quantile function\n##'\n##' Estimate weighted quantiles.\n##'\n##' \\code{wquant} estimates quantiles of weighted data using the estimator of Harrell & Davis (1982), with improvements recommended by Andrey Akinshin (2023).\n##'\n##' @param x numeric; a vector of data.\n##' @param weights numeric; vector of weights.\n##' @param probs numeric; desired quantiles.\n##'\n##' @return\n##' \\code{wquant} returns a vector containing the estimated quantiles.\n##' If \\code{probs} has names, these are inherited.\n##'\n##' @author Aaron A. King\n##' @include package.R\n##' @examples\n##' x <- c(1,1,1,2,2,3,3,3,3,4,5,5,6,6,6)\n##' quantile(x)\n##' wquant(x)\n##' wquant(c(1,2,3,4,5,6),weights=c(3,2,4,1,2,3))\n##' wquant(c(1,2,3,4,5),c(1,0,0,1,1))\n##' @references\n##' \\Harrell1982\n##'\n##' \\Akinshin2023\n##'\n## The discussion in Andrey Akinshin's blog post\n## https://aakinshin.net/posts/weighted-quantiles/\n## was instrumental in developing these codes.\n##'\n##' @rdname wquant\n##' @importFrom stats pbeta\n##' @export\nwquant <- function (\n  x, weights = rep(1, length(x)),\n  probs = c(`0%`=0, `25%`=0.25, `50%`=0.5, `75%`=0.75, `100%`=1)\n) {\n  x <- as.numeric(x)\n  weights <- as.numeric(weights)\n  if (length(weights) != length(x))\n    pStop(sQuote(\"x\"),\" and \",sQuote(\"weights\"),\" must be of equal length.\")\n  if (any(is.na(x)) || any(!is.finite(weights)))\n    pStop(\"NA and non-finite values are disallowed.\")\n  if (any(weights < 0))\n    pStop(\"weights must be non-negative.\")\n  if (!is.numeric(probs) || any(is.na(probs)) ||\n        isTRUE(any(probs < 0 | probs > 1))) {\n    pStop(sQuote(\"probs\"),\" must be a numeric vector with values in [0,1].\")\n  }\n  ## order the data and the weights\n  idx <- order(x)\n  x <- x[idx]\n  weights <- weights[idx]\n  ## accumulate and normalize the weights\n  w <- cumsum(c(0,weights))\n  w <- w/w[length(w)]\n  q <- probs       # inherits the names of `probs`\n  ess <- sum(weights)^2/sum(weights^2) # Kish effective sample size\n  a <- probs*(ess+1) # a,b are shape parameters for Beta distribution\n  b <- (1-probs)*(ess+1)\n  for (j in seq_along(probs)) {\n    W <- pbeta(q=w,shape1=a[j],shape2=b[j])\n    W[w==0] <- 0\n    W[w==1] <- 1\n    q[j] <- sum(diff(W)*x)\n  }\n  q\n}\n"
  },
  {
    "path": "README.md",
    "content": "# **pomp**\n\n## an *R* package for statistical inference on partially observed Markov processes\n\n[![Project Status: Active – The project has reached a stable, usable state and is being actively developed.](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active)\n[![Development Release](https://img.shields.io/github/release/kingaa/pomp.svg)](https://github.com/kingaa/pomp/releases/latest)\n[![CRAN Status](https://www.r-pkg.org/badges/version/pomp?color=blue)](https://cran.r-project.org/package=pomp)\n[![Last CRAN release date](https://www.r-pkg.org/badges/last-release/pomp?color=blue)](https://cran.r-project.org/package=pomp)\n[![R-CMD-check](https://github.com/kingaa/pomp/actions/workflows/r-cmd-check.yml/badge.svg)](https://github.com/kingaa/pomp/actions/workflows/r-cmd-check.yml)\n[![binary-build](https://github.com/kingaa/pomp/actions/workflows/binary-build.yml/badge.svg)](https://github.com/kingaa/pomp/actions/workflows/binary-build.yml)\n[![test-coverage](https://github.com/kingaa/pomp/actions/workflows/test-coverage.yml/badge.svg)](https://github.com/kingaa/pomp/actions/workflows/test-coverage.yml)\n[![codecov](https://codecov.io/gh/kingaa/pomp/branch/master/graph/badge.svg)](https://app.codecov.io/gh/kingaa/pomp)\n![CRAN mirror monthly downloads](https://cranlogs.r-pkg.org/badges/last-month/pomp?color=yellow)\n![CRAN mirror total downloads](https://cranlogs.r-pkg.org/badges/grand-total/pomp?color=yellow)\n[![Dependencies](https://tinyverse.netlify.app/badge/pomp)](https://tinyverse.netlify.app/)\n[![manual](https://img.shields.io/badge/manual-HTML-brown)](https://kingaa.github.io/pomp/manual/)\n[![pdf-manual](https://img.shields.io/badge/manual-PDF-brown)](https://kingaa.github.io/pomp/manual/pdf/)\n[![doxygen](https://img.shields.io/badge/doxygen-HTML-brown)](https://kingaa.github.io/manuals/pomp/source/html/index.html)\n[![DOI](https://zenodo.org/badge/38616252.svg)](https://doi.org/10.5281/zenodo.15364461)\n\n\nFor installation instructions and user guides, see [the package website](https://kingaa.github.io/pomp/).\n\nRelated packages:\n\n- [**PartiallyObservedMarkovProcesses.jl**](https://github.com/kingaa/PartiallyObservedMarkovProcesses.jl):\n  Experimental port of **pomp** to Julia\n- [**phylopomp**](https://github.com/kingaa/phylopomp/):\n  **pomp** for phylodynamics\n- [**panelPomp**](https://github.com/panelPomp-org/panelPomp/):\n  **pomp** for panel data\n- [**spatPomp**](https://github.com/spatPomp-org/spatPomp/):\n  Spatiotemporal dynamics\n- [**circumstance**](https://github.com/kingaa/circumstance/):\n  Experimental parallelization tools\n- [**subplex**](https://github.com/kingaa/subplex/): \n  The *subplex* optimization algorithm\n"
  },
  {
    "path": "TODO.md",
    "content": "-------------\n\n# pomp to-do list\n\n## For pomp:\n\n- References using new bibtex support for Rd files.\n[R-exts.html#Bibliographic-citations-and-references]\n\n- Rosenzweig-MacArthur example\n- Make certain error checks in inline codes depend on NDEBUG flag?\n- replace `melt` with `data.table::melt`?\n- YAML interface\n- \"Getting Started\" vignette:\n  - ~~finish discussion of smoothing and hindcasting~~\n  - include discussion of forecasting\n- ARMA benchmarking (a la **spatPomp**)?\n- make `mcap` into a generic, provide a method for data frames and a plotting method\n\n- overriding C snippets should overwrite/delete old C snippets, keep one C snippet file\n- `options(pomp_cdir)` should take effect *at run time* and not at initial compile time as currently\n- `pomp_fun` should be able to take symbols\n\n- in `pfilter`, perhaps filter trajectory (one sample from the smoothing distribution) should go into `states` slot (??)\n\n- rewrite to use `rmultinom`, which is now part of the **R** API (?)\n\n- more demanding tests of `enkf` and `eakf`\n- iterated EnKF\n- better scheme for indicating derivatives and maps in C snippets\n\n- support for asymmetric MCMC proposals\n- `spy` methods for derived objects\n- for log-barycentric transformations, check that parameters are contiguous\n- manual pages on the organization of the package\n    - diagnostic tools\n    - auxiliary functions\n    - plotting methods\n    - parallelization tools\n    - extending the package\n- make R-level functions for various distributions and transformations\n\t- BetaBinom\n\t- BetaNegBinom\n- remove need to specify paramnames when log,logit,barycentric partrans is given? HOW?\n\n- demonstration of Fisher information via `pfilter` on slice designs?\n- new `userdata` function to get void *?\n\n- easier interface for lists of probes in `probe`\n- documentation on `mifList`, `pmcmcList`, etc.?\n- methods to change data (`obs<-`)?\n\t- perhaps recognized data variables, states, covariates in calls to `pomp` are replaced?\n- MCMC proposals as pomp slots?\n- probes as pomp slots?\n- what does a generic `pomp_fun` interface look like?\n\n- should parameter transformations allow renaming of variables?\n\t- would require attention to `rw_sd`, e.g.\n\n- streamline the R snippets so that ... is unnecessary?\n\t- probably not worth the trouble, since C snippets are so much faster\n- add `include` argument to `pomp`?\n- graceful stopping for optimizers (at least for `nloptr`)\n- trap errors for LAPACK\n\n- one-point SCQL function for possible use in fitting initial conditions\n- partial rejection control for `pfilter`?\n- adaptive particle numbers in pfilter (?)\n\n- plugin for adaptive tau leaping algorithm.\n- plugin for compartmental models\n\n## Documentation\n\n- FAQ needs update with new issues from @MarieAugerMethe:\n\t- prediction vs smoothing \n- documentation for existing issues with \"todo\" label\n\n## Helper packages\n\n- parallel mif-farm and multi-start optimization helpers\n- number of processors stored in `bake`, `stew`, `freeze` outputs\n- parallel likelihood profiling tool (with MCAP)\n\n## Examples\n\n- SDE examples\n- LPA beetle examples\n- budmoth examples\n- variants on SIR: SEIR, SIRS, ...\n- more toy models\n- more/better examples\n\t- need examples of objective function methods\n\t- `pmcmc` examples\n\n-------------\n"
  },
  {
    "path": "codecov.yml",
    "content": "coverage:\n  precision: 2\n  round: nearest\n  range: \"90...100\"\ncomment:\n  layout: \"header, diff, changes, sunburst, uncovered\"\n  branches: null\n  behavior: default\ncodecov: \n token: cbbc302d-fff3-4530-8474-0f3f48db6776\n"
  },
  {
    "path": "data/blowflies.csv",
    "content": "day;count;set\n40;3721;1\n41;3373;1\n42;2880;1\n43;1805;1\n44;1195;1\n45;557;1\n46;267;1\n47;239;1\n48;182;1\n49;270;1\n50;300;1\n51;330;1\n52;360;1\n53;390;1\n54;420;1\n55;362;1\n56;363;1\n57;423;1\n58;423;1\n59;483;1\n60;425;1\n61;397;1\n62;573;1\n63;864;1\n64;1533;1\n65;2377;1\n66;3366;1\n67;4472;1\n68;5403;1\n69;7613;1\n70;7498;1\n71;7440;1\n72;7529;1\n73;7820;1\n74;7996;1\n75;8316;1\n76;5061;1\n77;5150;1\n78;5296;1\n79;4337;1\n80;3728;1\n81;3060;1\n82;2654;1\n83;2074;1\n84;1697;1\n85;1290;1\n86;971;1\n87;769;1\n88;683;1\n89;655;1\n90;626;1\n91;511;1\n92;425;1\n93;426;1\n94;310;1\n95;253;1\n96;196;1\n97;168;1\n98;197;1\n99;286;1\n100;781;1\n101;927;1\n102;1073;1\n103;1249;1\n104;1366;1\n105;1570;1\n106;1949;1\n107;2473;1\n108;3578;1\n110;4800;1\n111;5440;1\n112;4715;1\n113;4192;1\n114;3844;1\n115;3177;1\n116;3439;1\n117;3731;1\n118;4168;1\n119;3617;1\n120;3123;1\n121;2223;1\n122;1759;1\n123;800;1\n124;656;1\n125;483;1\n126;367;1\n127;223;1\n128;224;1\n129;138;1\n130;51;1\n131;0;1\n132;82;1\n133;170;1\n134;287;1\n135;172;1\n136;80;1\n137;115;1\n138;0;1\n139;379;1\n140;961;1\n141;2095;1\n142;2678;1\n143;3231;1\n144;3116;1\n145;2914;1\n146;2740;1\n147;2944;1\n148;3526;1\n149;4225;1\n150;5127;1\n151;6116;1\n152;7222;1\n153;6554;1\n154;5944;1\n155;4405;1\n156;3010;1\n157;2255;1\n158;1413;1\n159;862;1\n160;601;1\n161;544;1\n162;516;1\n163;488;1\n164;488;1\n165;489;1\n166;490;1\n167;462;1\n168;463;1\n169;464;1\n170;464;1\n171;465;1\n172;496;1\n173;584;1\n174;701;1\n175;818;1\n176;1400;1\n177;1953;1\n178;2710;1\n179;3234;1\n180;3729;1\n181;3875;1\n182;4022;1\n183;3761;1\n184;3559;1\n185;3996;1\n186;4462;1\n187;4928;1\n188;5248;1\n189;5889;1\n190;6616;1\n191;7548;1\n192;9642;1\n193;8596;1\n194;4585;1\n195;2812;1\n196;1883;1\n197;1477;1\n198;984;1\n199;607;1\n200;404;1\n201;434;1\n202;377;1\n203;349;1\n204;321;1\n205;292;1\n206;235;1\n207;207;1\n208;121;1\n209;92;1\n210;122;1\n211;152;1\n212;328;1\n213;648;1\n214;1347;1\n215;1784;1\n216;2337;1\n217;2803;1\n218;3269;1\n219;3735;1\n220;4376;1\n221;4260;1\n222;4174;1\n223;4116;1\n224;4321;1\n225;4496;1\n226;4701;1\n227;4411;1\n228;4034;1\n229;3657;1\n230;3890;1\n231;4269;1\n232;4939;1\n233;5754;1\n234;4940;1\n235;4040;1\n236;3227;1\n237;2356;1\n238;1427;1\n239;1108;1\n240;905;1\n241;1052;1\n242;1110;1\n243;1169;1\n244;1257;1\n245;1258;1\n246;1230;1\n247;1173;1\n248;1203;1\n249;1116;1\n250;1059;1\n251;1002;1\n252;1090;1\n253;1237;1\n254;1615;1\n255;2168;1\n256;2721;1\n257;3420;1\n258;4381;1\n259;5254;1\n260;6185;1\n261;7697;1\n262;7465;1\n263;6478;1\n264;6188;1\n265;5898;1\n266;5522;1\n267;5057;1\n268;4331;1\n269;4042;1\n270;3839;1\n271;3607;1\n272;3289;1\n273;2446;1\n274;1749;1\n275;1023;1\n276;646;1\n277;444;1\n278;242;1\n279;214;1\n280;69;1\n281;70;1\n282;100;1\n283;101;1\n284;130;1\n285;248;1\n286;336;1\n287;482;1\n288;629;1\n289;862;1\n290;1066;1\n291;1329;1\n292;1765;1\n293;2202;1\n294;2406;1\n295;4733;1\n296;4851;1\n297;4502;1\n298;4213;1\n299;3982;1\n300;3895;1\n301;3663;1\n302;4013;1\n303;4508;1\n304;5352;1\n305;6079;1\n306;6546;1\n307;5588;1\n308;4774;1\n309;3932;1\n310;3119;1\n311;2073;1\n312;1638;1\n313;1348;1\n314;797;1\n315;536;1\n240;439;2\n242;244;2\n244;146;2\n246;78;2\n248;39;2\n250;10;2\n252;19;2\n254;156;2\n256;1550;2\n258;2262;2\n260;2301;2\n262;2067;2\n264;1521;2\n266;1024;2\n268;1326;2\n270;1238;2\n272;1033;2\n274;809;2\n276;556;2\n278;322;2\n280;136;2\n282;49;2\n284;29;2\n286;10;2\n288;19;2\n290;19;2\n292;1521;2\n294;2662;2\n296;2798;2\n298;2506;2\n300;1774;2\n302;1248;2\n304;809;2\n306;829;2\n308;526;2\n310;331;2\n312;214;2\n314;97;2\n316;39;2\n318;49;2\n320;585;2\n322;1521;2\n324;3013;2\n326;3519;2\n328;3149;2\n330;2554;2\n332;1979;2\n334;2525;2\n336;2174;2\n338;1638;2\n340;1121;2\n342;643;2\n344;370;2\n346;234;2\n348;117;2\n350;49;2\n352;19;2\n354;19;2\n356;58;2\n358;575;2\n360;1716;2\n362;1950;2\n364;1813;2\n366;1482;2\n368;975;2\n370;595;2\n372;487;2\n374;536;2\n376;419;2\n378;312;2\n380;234;2\n382;107;2\n384;49;2\n386;1316;2\n388;1930;2\n390;1813;2\n392;1813;2\n394;2398;2\n396;3256;2\n398;3334;2\n400;2964;2\n402;1872;2\n404;1131;2\n406;731;2\n408;458;2\n410;253;2\n412;107;2\n414;49;2\n416;10;2\n418;29;2\n420;273;2\n422;1199;2\n424;1716;2\n426;1716;2\n428;1521;2\n430;1199;2\n432;731;2\n434;419;2\n436;819;2\n438;643;2\n440;526;2\n442;234;2\n444;97;2\n446;721;2\n448;1024;2\n450;936;2\n452;829;2\n454;916;2\n456;1833;2\n458;2662;2\n460;2623;2\n240;33;3\n242;16;3\n244;6;3\n246;22;3\n248;378;3\n250;860;3\n252;1084;3\n254;1249;3\n256;1172;3\n258;909;3\n260;718;3\n262;543;3\n264;367;3\n266;269;3\n268;258;3\n270;181;3\n272;110;3\n274;61;3\n276;17;3\n278;1;3\n280;6;3\n282;297;3\n284;565;3\n286;505;3\n288;549;3\n290;691;3\n292;822;3\n294;899;3\n296;1195;3\n298;1047;3\n300;845;3\n302;631;3\n304;423;3\n306;221;3\n308;117;3\n310;46;3\n312;18;3\n314;13;3\n316;18;3\n318;111;3\n320;511;3\n322;719;3\n324;785;3\n326;708;3\n328;610;3\n330;511;3\n332;610;3\n334;709;3\n336;599;3\n338;495;3\n340;369;3\n342;232;3\n344;145;3\n346;68;3\n348;36;3\n350;8;3\n352;3;3\n354;3;3\n356;145;3\n358;726;3\n360;1328;3\n362;1503;3\n364;1459;3\n366;1251;3\n368;1016;3\n370;748;3\n372;638;3\n374;491;3\n376;332;3\n378;190;3\n380;69;3\n382;25;3\n384;9;3\n386;4;3\n388;37;3\n390;80;3\n392;425;3\n394;847;3\n396;1082;3\n398;1050;3\n400;803;3\n402;749;3\n404;935;3\n406;891;3\n408;716;3\n410;514;3\n412;344;3\n414;229;3\n416;141;3\n418;87;3\n420;65;3\n422;21;3\n424;26;3\n426;142;3\n428;727;3\n430;919;3\n432;979;3\n434;925;3\n436;782;3\n438;536;3\n440;350;3\n442;213;3\n444;115;3\n446;65;3\n448;22;3\n450;11;3\n452;0;3\n454;5;3\n456;334;3\n458;498;3\n460;761;3\n0;948;4\n2;942;4\n4;911;4\n6;858;4\n8;801;4\n10;676;4\n12;504;4\n14;397;4\n16;248;4\n18;146;4\n20;1801;4\n22;6235;4\n24;5974;4\n26;8921;4\n28;6610;4\n30;5973;4\n32;5673;4\n34;3875;4\n36;2361;4\n38;1352;4\n40;1226;4\n42;912;4\n44;521;4\n46;363;4\n48;229;4\n50;142;4\n52;82;4\n54;542;4\n56;939;4\n58;2431;4\n60;3687;4\n62;4543;4\n64;4535;4\n66;5441;4\n68;4412;4\n70;3022;4\n72;2656;4\n74;1967;4\n76;1295;4\n78;915;4\n80;551;4\n82;313;4\n84;167;4\n86;95;4\n88;93;4\n90;60;4\n92;68;4\n94;5259;4\n96;6673;4\n98;5441;4\n100;3987;4\n102;2952;4\n104;3648;4\n106;4222;4\n108;3889;4\n110;2295;4\n112;1509;4\n114;928;4\n116;739;4\n118;566;4\n120;383;4\n122;274;4\n124;192;4\n126;226;4\n128;519;4\n130;1224;4\n132;2236;4\n134;3818;4\n136;6208;4\n138;5996;4\n140;5789;4\n142;6652;4\n144;7939;4\n146;4868;4\n148;3952;4\n150;2712;4\n152;1734;4\n154;1224;4\n156;703;4\n158;508;4\n160;366;4\n162;279;4\n164;243;4\n166;343;4\n168;761;4\n170;1025;4\n172;1221;4\n174;1600;4\n176;2267;4\n178;3290;4\n180;3471;4\n182;3637;4\n184;3703;4\n186;4876;4\n188;5364;4\n190;4890;4\n192;3029;4\n194;1950;4\n196;1225;4\n198;1076;4\n200;905;4\n202;772;4\n204;628;4\n206;473;4\n208;539;4\n210;825;4\n212;1702;4\n214;2868;4\n216;4473;4\n218;5221;4\n220;6592;4\n222;6400;4\n224;4752;4\n226;3521;4\n228;2719;4\n230;1931;4\n232;1500;4\n234;1082;4\n236;849;4\n238;774;4\n240;864;4\n242;1308;4\n244;1624;4\n246;2224;4\n248;2423;4\n250;2959;4\n252;3547;4\n254;7237;4\n256;5218;4\n258;5311;4\n260;4273;4\n262;3270;4\n264;2281;4\n266;1549;4\n268;1091;4\n270;796;4\n272;610;4\n274;445;4\n276;894;4\n278;1454;4\n280;2262;4\n282;2363;4\n284;3847;4\n286;3876;4\n288;3935;4\n290;3479;4\n292;3415;4\n294;3861;4\n296;3571;4\n298;3113;4\n300;2319;4\n302;1630;4\n304;1297;4\n306;861;4\n308;761;4\n310;659;4\n312;701;4\n314;762;4\n316;1188;4\n318;1778;4\n320;2428;4\n322;3806;4\n324;4519;4\n326;5646;4\n328;4851;4\n330;5374;4\n332;4713;4\n334;7367;4\n336;7236;4\n338;5245;4\n340;3636;4\n342;2417;4\n344;1258;4\n346;766;4\n348;479;4\n350;402;4\n352;248;4\n354;254;4\n356;604;4\n358;1346;4\n360;2342;4\n362;3328;4\n364;3599;4\n366;4081;4\n368;7643;4\n370;7919;4\n372;6098;4\n374;6896;4\n376;5634;4\n378;5134;4\n380;4188;4\n382;3469;4\n384;2442;4\n386;1931;4\n388;1790;4\n390;1722;4\n392;1488;4\n394;1416;4\n396;1369;4\n398;1666;4\n400;2627;4\n402;2840;4\n404;4044;4\n406;4929;4\n408;5111;4\n410;3152;4\n412;4462;4\n414;4082;4\n416;3026;4\n418;1589;4\n420;2075;4\n422;1829;4\n424;1388;4\n426;1149;4\n428;968;4\n430;1170;4\n432;1465;4\n434;1676;4\n436;3075;4\n438;3815;4\n440;4639;4\n442;4424;4\n444;2784;4\n446;5860;4\n448;5781;4\n450;4897;4\n452;3920;4\n454;3835;4\n456;3618;4\n458;3050;4\n460;3772;4\n462;3517;4\n464;3350;4\n466;3018;4\n468;2625;4\n470;2412;4\n472;2221;4\n474;2619;4\n476;3203;4\n478;2706;4\n480;2717;4\n482;2175;4\n484;1628;4\n486;2388;4\n488;3677;4\n490;3156;4\n492;4272;4\n494;3771;4\n496;4955;4\n498;5584;4\n500;3891;4\n502;3501;4\n504;4436;4\n506;4369;4\n508;3394;4\n510;3869;4\n512;2922;4\n514;1843;4\n516;2837;4\n518;4690;4\n520;5119;4\n522;5839;4\n524;5389;4\n526;4993;4\n528;4446;4\n530;4851;4\n532;4243;4\n534;4620;4\n536;4849;4\n538;3664;4\n540;3016;4\n542;2881;4\n544;3821;4\n546;4300;4\n548;4168;4\n550;5446;4\n552;5917;4\n554;8579;4\n556;7533;4\n558;6884;4\n560;4127;4\n562;5546;4\n564;6313;4\n566;6650;4\n568;6304;4\n570;4842;4\n572;4352;4\n574;3215;4\n576;2652;4\n578;2330;4\n580;3123;4\n582;3955;4\n584;4494;4\n586;4780;4\n588;5753;4\n590;5555;4\n592;5712;4\n594;4786;4\n596;4066;4\n598;2891;4\n600;3270;4\n602;4404;4\n604;4398;4\n606;4112;4\n608;4401;4\n610;5779;4\n612;6597;4\n614;8091;4\n616;11282;4\n618;12446;4\n620;13712;4\n622;11017;4\n624;14683;4\n626;7258;4\n628;6195;4\n630;5962;4\n632;4213;4\n634;2775;4\n636;1781;4\n638;936;4\n640;898;4\n642;1160;4\n644;3158;4\n646;3386;4\n648;4547;4\n650;4823;4\n652;4970;4\n654;4940;4\n656;5793;4\n658;7836;4\n660;4457;4\n662;6901;4\n664;8191;4\n666;6766;4\n668;5165;4\n670;2919;4\n672;3415;4\n674;3431;4\n676;3162;4\n678;2525;4\n680;2290;4\n682;1955;4\n684;1936;4\n686;2384;4\n688;4666;4\n690;7219;4\n692;8306;4\n694;8027;4\n696;7010;4\n698;8149;4\n700;8949;4\n702;6105;4\n704;5324;4\n706;5766;4\n708;6214;4\n710;7007;4\n712;8154;4\n714;9049;4\n716;6883;4\n718;8103;4\n720;6803;4\n"
  },
  {
    "path": "data/parus.csv",
    "content": "## Parus major (Great Tit) census (all individuals)\n## Wytham Wood, Oxfordshire\n## Global Population Dynamics Database dataset #10163.\n## (NERC Centre for Population Biology, Imperial College (2010) \n## The Global Population Dynamics Database Version 2. \n## http://www.sw.ic.ac.uk/cpb/cpb/gpdd.html).\n##\n## Original source: \n## McCleery, R. & Perrins, C. (1991)\n## Effects of predation on the numbers of Great Tits, Parus major.\n## In: Bird Population Studies, \n## edited by Perrins, C.M., Lebreton, J.-D. & Hirons, G.J.M. \n## Oxford. Univ. Press. pp. 129--147.\n##\nyear;pop\n1960;148\n1961;258\n1962;185\n1963;170\n1964;267\n1965;239\n1966;196\n1967;132\n1968;167\n1969;186\n1970;128\n1971;227\n1972;174\n1973;177\n1974;137\n1975;172\n1976;119\n1977;226\n1978;166\n1979;161\n1980;199\n1981;306\n1982;206\n1983;350\n1984;214\n1985;175\n1986;211\n"
  },
  {
    "path": "examples/accumulators.R",
    "content": "\\donttest{\n  ## A simple SIR model.\n\n  ewmeas |>\n    subset(time < 1952) |>\n    pomp(\n      times=\"time\",t0=1948,\n      rprocess=euler(\n        Csnippet(\"\n        int nrate = 6;\n        double rate[nrate];     // transition rates\n        double trans[nrate];    // transition numbers\n        double dW;\n\n        // gamma noise, mean=dt, variance=(sigma^2 dt)\n        dW = rgammawn(sigma,dt);\n\n        // compute the transition rates\n        rate[0] = mu*pop;       // birth into susceptible class\n        rate[1] = (iota+Beta*I*dW/dt)/pop; // force of infection\n        rate[2] = mu;           // death from susceptible class\n        rate[3] = gamma;        // recovery\n        rate[4] = mu;           // death from infectious class\n        rate[5] = mu;           // death from recovered class\n\n        // compute the transition numbers\n        trans[0] = rpois(rate[0]*dt);   // births are Poisson\n        reulermultinom(2,S,&rate[1],dt,&trans[1]);\n        reulermultinom(2,I,&rate[3],dt,&trans[3]);\n        reulermultinom(1,R,&rate[5],dt,&trans[5]);\n\n        // balance the equations\n        S += trans[0]-trans[1]-trans[2];\n        I += trans[1]-trans[3]-trans[4];\n        R += trans[3]-trans[5];\n      \"),\n      delta.t=1/52/20\n      ),\n      rinit=Csnippet(\"\n        double m = pop/(S_0+I_0+R_0);\n        S = nearbyint(m*S_0);\n        I = nearbyint(m*I_0);\n        R = nearbyint(m*R_0);\n    \"),\n    paramnames=c(\"mu\",\"pop\",\"iota\",\"gamma\",\"Beta\",\"sigma\",\n      \"S_0\",\"I_0\",\"R_0\"),\n    statenames=c(\"S\",\"I\",\"R\"),\n    params=c(mu=1/50,iota=10,pop=50e6,gamma=26,Beta=400,sigma=0.1,\n      S_0=0.07,I_0=0.001,R_0=0.93)\n    ) -> ew1\n\n  ew1 |>\n    simulate() |>\n    plot(variables=c(\"S\",\"I\",\"R\"))\n\n  ## A simple SIR model that tracks cumulative incidence.\n\n  ew1 |>\n    pomp(\n      rprocess=euler(\n        Csnippet(\"\n        int nrate = 6;\n        double rate[nrate];     // transition rates\n        double trans[nrate];    // transition numbers\n        double dW;\n\n        // gamma noise, mean=dt, variance=(sigma^2 dt)\n        dW = rgammawn(sigma,dt);\n\n        // compute the transition rates\n        rate[0] = mu*pop;       // birth into susceptible class\n        rate[1] = (iota+Beta*I*dW/dt)/pop; // force of infection\n        rate[2] = mu;           // death from susceptible class\n        rate[3] = gamma;        // recovery\n        rate[4] = mu;           // death from infectious class\n        rate[5] = mu;           // death from recovered class\n\n        // compute the transition numbers\n        trans[0] = rpois(rate[0]*dt);   // births are Poisson\n        reulermultinom(2,S,&rate[1],dt,&trans[1]);\n        reulermultinom(2,I,&rate[3],dt,&trans[3]);\n        reulermultinom(1,R,&rate[5],dt,&trans[5]);\n\n        // balance the equations\n        S += trans[0]-trans[1]-trans[2];\n        I += trans[1]-trans[3]-trans[4];\n        R += trans[3]-trans[5];\n        H += trans[3];          // cumulative incidence\n      \"),\n      delta.t=1/52/20\n      ),\n      rmeasure=Csnippet(\"\n        double mean = H*rho;\n        double size = 1/tau;\n        reports = rnbinom_mu(size,mean);\n    \"),\n    rinit=Csnippet(\"\n        double m = pop/(S_0+I_0+R_0);\n        S = nearbyint(m*S_0);\n        I = nearbyint(m*I_0);\n        R = nearbyint(m*R_0);\n        H = 0;\n    \"),\n    paramnames=c(\"mu\",\"pop\",\"iota\",\"gamma\",\"Beta\",\"sigma\",\"tau\",\"rho\",\n      \"S_0\",\"I_0\",\"R_0\"),\n    statenames=c(\"S\",\"I\",\"R\",\"H\"),\n    params=c(mu=1/50,iota=10,pop=50e6,gamma=26,\n      Beta=400,sigma=0.1,tau=0.001,rho=0.6,\n      S_0=0.07,I_0=0.001,R_0=0.93)\n    ) -> ew2\n\n  ew2 |>\n    simulate() |>\n    plot()\n\n  ## A simple SIR model that tracks weekly incidence.\n\n  ew2 |>\n    pomp(accumvars=\"H\") -> ew3\n\n  ew3 |>\n    simulate() |>\n    plot()\n\n}\n"
  },
  {
    "path": "examples/bake.R",
    "content": "\\dontrun{\n  bake(file=\"example1.rds\",{\n    x <- runif(1000)\n    mean(x)\n  })\n\n  bake(file=\"example1.rds\",{\n    x <- runif(1000)\n    mean(x)\n  })\n\n  bake(file=\"example1.rds\",{\n    a <- 3\n    x <- runif(1000)\n    mean(x)\n  })\n\n  a <- 5\n  b <- 2\n\n  stew(file=\"example2.rda\",\n    dependson=list(a,b),{\n      x <- runif(10)\n      y <- rnorm(n=10,mean=a*x+b,sd=2)\n    })\n\n  plot(x,y)\n\n  set.seed(11)\n  runif(2)\n  freeze(runif(3),seed=5886730)\n  runif(2)\n  freeze(runif(3),seed=5886730)\n  runif(2)\n\n  set.seed(11)\n  runif(2)\n  runif(2)\n  runif(2)\n\n}\n"
  },
  {
    "path": "examples/bsflu.R",
    "content": "if (require(tidyr) && require(ggplot2)) {\n\n  bsflu |>\n    gather(variable,value,-date,-day) |>\n    ggplot(aes(x=date,y=value,color=variable))+\n    geom_line()+\n    labs(y=\"number of boys\",title=\"boarding school flu outbreak\")+\n    theme_bw()\n\n}\n"
  },
  {
    "path": "examples/concat.R",
    "content": "gompertz(sigma=2,tau=1) -> g\nNp <- c(low=100,med=1000,high=10000)\nlapply(\n  Np,\n  \\(np) pfilter(g,Np=np)\n) |>\n  concat() -> pfs\n\npfs\ncoef(pfs)\nlogLik(pfs)\neff_sample_size(pfs)\ncond_logLik(pfs)\n\npfs |> plot()\n"
  },
  {
    "path": "examples/dacca.R",
    "content": "\\donttest{ # takes too long for R CMD check\n  po <- dacca()\n  plot(po)\n  ## MLE:\n  coef(po)\n  plot(simulate(po))\n}\n"
  },
  {
    "path": "examples/design.R",
    "content": "## Sobol' low-discrepancy design\nplot(sobol_design(lower=c(a=0,b=100),upper=c(b=200,a=1),nseq=100))\n\n## Uniform random design\nplot(runif_design(lower=c(a=0,b=100),upper=c(b=200,a=1),100))\n\n## A one-parameter profile design:\nx <- profile_design(p=1:10,lower=c(a=0,b=0),upper=c(a=1,b=5),nprof=20)\ndim(x)\nplot(x)\n\n## A two-parameter profile design:\nx <- profile_design(p=1:10,q=3:5,lower=c(a=0,b=0),upper=c(b=5,a=1),nprof=200)\ndim(x)\nplot(x)\n\n## A two-parameter profile design with random points:\nx <- profile_design(p=1:10,q=3:5,lower=c(a=0,b=0),upper=c(b=5,a=1),nprof=200,type=\"runif\")\ndim(x)\nplot(x)\n\n## A single 11-point slice through the point c(A=3,B=8,C=0) along the B direction.\nx <- slice_design(center=c(A=3,B=8,C=0),B=seq(0,10,by=1))\ndim(x)\nplot(x)\n\n## Two slices through the same point along the A and C directions.\nx <- slice_design(c(A=3,B=8,C=0),A=seq(0,5,by=1),C=seq(0,5,length=11))\ndim(x)\nplot(x)\n\n"
  },
  {
    "path": "examples/dmeasure_spec.R",
    "content": "\\donttest{\n  ## We start with the pre-built Ricker example:\n  ricker() -> po\n\n  ## To change the measurement model density, dmeasure,\n  ## we use the 'dmeasure' argument in any 'pomp'\n  ## elementary or estimation function.\n  ## Here, we pass the dmeasure specification to 'pfilter'\n  ## as an R function.\n\n  po |>\n    pfilter(\n      dmeasure=function (y, N, phi, ..., log) {\n        dpois(y,lambda=phi*N,log=log)\n      },\n      Np=100\n    ) -> pf\n\n  ## We can also pass it as a C snippet:\n\n  po |>\n    pfilter(\n      dmeasure=Csnippet(\"lik = dpois(y,phi*N,give_log);\"),\n      paramnames=\"phi\",\n      statenames=\"N\",\n      Np=100\n    ) -> pf\n\n}\n"
  },
  {
    "path": "examples/ebola.R",
    "content": "\\donttest{ # takes too long for R CMD check\n  if (require(ggplot2) && require(tidyr)) {\n    \n    ebolaWA2014 |>\n      pivot_longer(c(cases,deaths)) |>\n      ggplot(aes(x=date,y=value,group=name,color=name))+\n      geom_line()+\n      facet_grid(country~.,scales=\"free_y\")+\n      theme_bw()+\n      theme(axis.text=element_text(angle=-90))\n    \n  }\n  \n  plot(ebolaModel(country=\"SLE\"))\n  plot(ebolaModel(country=\"GIN\"))\n  plot(ebolaModel(country=\"LBR\"))\n}\n"
  },
  {
    "path": "examples/eulermultinom.R",
    "content": "## Simulate 5 realizations of Euler-multinomial random variable:\n\ndn <- reulermultinom(5,size=100,rate=c(a=1,b=2,c=3),dt=0.1)\ndn\n\n## Compute the probability mass function at each of the 5 realizations:\n\ndeulermultinom(x=dn,size=100,rate=c(1,2,3),dt=0.1)\n\n## Compute the expectation of an Euler-multinomial:\n\neeulermultinom(size=100,rate=c(a=1,b=2,c=3),dt=0.1)\n\n## An Euler-multinomial with overdispersed transitions:\n\ndt <- 0.1\ndW <- rgammawn(sigma=0.1,dt=dt)\nreulermultinom(5,size=100,rate=c(a=1,b=2,c=3),dt=dW)\n"
  },
  {
    "path": "examples/kf.R",
    "content": "if (require(dplyr)) {\n\n  gompertz() -> po\n\n  po |>\n    as.data.frame() |>\n    mutate(\n      logY=log(Y)\n    ) |>\n    select(time,logY) |>\n    pomp(times=\"time\",t0=0) |>\n    kalmanFilter(\n      X0=c(logX=0),\n      A=matrix(exp(-0.1),1,1),\n      Q=matrix(0.01,1,1),\n      C=matrix(1,1,1),\n      R=matrix(0.01,1,1)\n    ) -> kf\n\n  po |>\n    pfilter(Np=1000) -> pf\n\n  kf$logLik\n  logLik(pf) + sum(log(obs(pf)))\n\n}\n"
  },
  {
    "path": "examples/logmeanexp.R",
    "content": "\\donttest{ # takes too long for R CMD check\n  ## an estimate of the log likelihood:\n  ricker() |>\n    pfilter(Np=1000) |>\n    logLik() |>\n    replicate(n=5) -> ll\n  logmeanexp(ll)\n  ## with standard error:\n  logmeanexp(ll,se=TRUE)\n  ## with effective sample size\n  logmeanexp(ll,ess=TRUE)\n}\n"
  },
  {
    "path": "examples/nlf.R",
    "content": "\\donttest{\n\n  if (require(subplex)) {\n\n    ricker() |>\n      nlf_objfun(est=c(\"r\",\"sigma\",\"N_0\"),lags=c(4,6),\n        partrans=parameter_trans(log=c(\"r\",\"sigma\",\"N_0\")),\n        paramnames=c(\"r\",\"sigma\",\"N_0\"),\n        ti=100,tf=2000,seed=426094906L) -> m1\n\n    subplex(par=log(c(20,0.5,5)),fn=m1,control=list(reltol=1e-4)) -> out\n\n    m1(out$par)\n    coef(m1)\n    plot(simulate(m1))\n\n  }\n}\n"
  },
  {
    "path": "examples/ou2.R",
    "content": "po <- ou2()\nplot(po)\ncoef(po)\nx <- simulate(po)\nplot(x)\npf <- pfilter(po,Np=1000)\nlogLik(pf)\n"
  },
  {
    "path": "examples/parus.R",
    "content": "\\donttest{ # takes too long for R CMD check\n  parus |>\n    pfilter(Np=1000,times=\"year\",t0=1960,\n      params=c(K=190,r=2.7,sigma=0.2,theta=0.05,N.0=148),\n      rprocess=discrete_time(\n        function (r, K, sigma, N, ...) {\n          e <- rnorm(n=1,mean=0,sd=sigma)\n          c(N = exp(log(N)+r*(1-N/K)+e))\n        },\n        delta.t=1\n      ),\n      rmeasure=function (N, theta, ...) {\n        c(pop=rnbinom(n=1,size=1/theta,mu=N+1e-10))\n      },\n      dmeasure=function (pop, N, theta, ..., log) {\n        dnbinom(x=pop,mu=N+1e-10,size=1/theta,log=log)\n      },\n      partrans=parameter_trans(log=c(\"sigma\",\"theta\",\"N_0\",\"r\",\"K\")),\n      paramnames=c(\"sigma\",\"theta\",\"N_0\",\"r\",\"K\")\n    ) -> pf\n\n  pf |> logLik()\n\n  pf |> simulate() |> plot()\n}\n"
  },
  {
    "path": "examples/pfilter.R",
    "content": "pf <- pfilter(gompertz(),Np=1000)\t## use 1000 particles\n\nplot(pf)\nlogLik(pf)\ncond_logLik(pf)\t\t\t## conditional log-likelihoods\neff_sample_size(pf)             ## effective sample size\nlogLik(pfilter(pf))      \t## run it again with 1000 particles\n\n## run it again with 2000 particles\npf <- pfilter(pf,Np=2000,filter.mean=TRUE,filter.traj=TRUE,save.states=\"filter\")\nfm <- filter_mean(pf) ## extract the filtering means\nft <- filter_traj(pf) ## one draw from the smoothing distribution\nss <- saved_states(pf,format=\"d\") ## the latent-state portion of each particle\n\nas(pf,\"data.frame\") |> head()\n"
  },
  {
    "path": "examples/pmcmc.R",
    "content": "\\donttest{\nsir(\n  times=seq(from=0,to=1,by=1/26),\n  t0=-1/26\n) |>\n  pmcmc(\n    Np = 1000,\n    Nmcmc = 50,\n    dprior = function (beta1, beta2, beta3, ..., log = FALSE) {\n      lp <- sum(dnorm(c(beta1,beta2,beta3),mean=400,sd=100,log=TRUE))\n      if (log) lp else exp(lp)\n    },\n    proposal = mvn_diag_rw(c(beta1=1,beta2=1,beta3=1))\n  ) -> sirpm\n\nsirpm |>\n  traces(c(\"beta1\",\"beta2\",\"beta3\")) |>\n  plot()\n}\n"
  },
  {
    "path": "examples/prior_spec.R",
    "content": "\\donttest{ # takes too long for R CMD check\n  ## Starting with an existing pomp object:\n  verhulst() |> window(end=30) -> po\n  \n  ## We add or change prior distributions using the two\n  ## arguments 'rprior' and 'dprior'. Here, we introduce\n  ## a Gamma prior on the 'r' parameter.\n  ## We construct 'rprior' and 'dprior' using R functions.\n\n  po |>\n    bsmc2(\n      rprior=function (n_0, K0, K1, sigma, tau, r0, r1, ...) {\n        c(\n          n_0 = n_0,\n          K = rgamma(n=1,shape=K0,scale=K1),\n          r = rgamma(n=1,shape=r0,scale=r1),\n          sigma = sigma,\n          tau = tau\n        )\n      },\n      dprior=function(K, K0, K1, r, r0, r1, ..., log) {\n        p <- dgamma(x=c(K,r),shape=c(K0,r0),scale=c(K1,r1),log=log)\n        if (log) sum(p) else prod(p)\n      },\n      params=c(n_0=10000,K=10000,K0=10,K1=1000,\n        r=0.9,r0=0.9,r1=1,sigma=0.5,tau=0.3),\n      Np=1000\n    ) -> B\n\n  ## We can also pass them as C snippets:\n\n  po |>\n    bsmc2(\n      rprior=Csnippet(\"\n         K = rgamma(K0,K1);\n         r = rgamma(r0,r1);\"\n      ),\n      dprior=Csnippet(\"\n         double lik1 = dgamma(K,K0,K1,give_log);\n         double lik2 = dgamma(r,r0,r1,give_log);\n         lik = (give_log) ? lik1+lik2 : lik1*lik2;\"\n      ),\n      paramnames=c(\"K\",\"K0\",\"K1\",\"r\",\"r0\",\"r1\"),\n      params=c(n_0=10000,K=10000,K0=10,K1=1000,\n        r=0.9,r0=0.9,r1=1,sigma=0.5,tau=0.3),\n      Np=10000\n    ) -> B\n\n  ## The prior is plotted in grey; the posterior, in blue.\n  plot(B)\n\n  B |>\n    pmcmc(Nmcmc=100,Np=1000,proposal=mvn_diag_rw(c(r=0.01,K=10))) -> Bb\n\n  plot(Bb,pars=c(\"loglik\",\"log.prior\",\"r\",\"K\"))\n\n}\n"
  },
  {
    "path": "examples/probe_match.R",
    "content": "\\donttest{\n  gompertz() -> po\n  \n  ## A list of probes:\n  plist <- list(\n    mean=probe_mean(\"Y\",trim=0.1,transform=sqrt),\n    sd=probe_sd(\"Y\",transform=sqrt),\n    probe_marginal(\"Y\",ref=obs(po)),\n    probe_acf(\"Y\",lags=c(1,3,5),type=\"correlation\",transform=sqrt),\n    probe_quantile(\"Y\",prob=c(0.25,0.75),na.rm=TRUE)\n  )\n\n  ## Construct the probe-matching objective function.\n  ## Here, we just want to estimate 'K'.\n  po |>\n    probe_objfun(probes=plist,nsim=100,seed=5069977,\n      est=\"K\") -> f\n\n  ## Any numerical optimizer can be used to minimize 'f'.\n  if (require(subplex)) {\n\n    subplex(fn=f,par=0.4,control=list(reltol=1e-5)) -> out\n\n  } else {\n\n    optim(fn=f,par=0.4,control=list(reltol=1e-5)) -> out\n\n  }\n\n  ## Call the objective one last time on the optimal parameters:\n  f(out$par)\n  coef(f)\n\n  ## There are 'plot' and 'summary' methods:\n  f |> as(\"probed_pomp\") |> plot()\n  f |> summary()\n\n  ## One can convert an objective function to a data frame:\n  f |> as(\"data.frame\") |> head()\n  f |> as(\"probed_pomp\") |> as(\"data.frame\") |> head()\n\n  f |> probe() |> plot()\n\n  ## One can modify the objective function with another call\n  ## to 'probe_objfun':\n\n  f |> probe_objfun(est=c(\"r\",\"K\")) -> f1\n  optim(fn=f1,par=c(0.3,0.3),control=list(reltol=1e-5)) -> out\n  f1(out$par)\n  coef(f1)\n}\n"
  },
  {
    "path": "examples/ricker-bifdiag.R",
    "content": "\\donttest{ # takes too long for R CMD check\n  ## generate a bifurcation diagram for the Ricker map\n  p <- parmat(coef(ricker()),nrep=500)\n  p[\"r\",] <- exp(seq(from=1.5,to=4,length=500))\n  trajectory(\n    ricker(),\n    times=seq(from=1000,to=2000,by=1),\n    params=p,\n    format=\"array\"\n  ) -> x\n  matplot(p[\"r\",],x[\"N\",,],pch='.',col='black',\n    xlab=expression(log(r)),ylab=\"N\",log='x')\n}\n"
  },
  {
    "path": "examples/ricker.R",
    "content": "po <- ricker()\nplot(po)\ncoef(po)\nsimulate(po) |> plot()\n"
  },
  {
    "path": "examples/rinit_spec.R",
    "content": "\\donttest{\n  ## Starting with an existing pomp object\n\n  verhulst() -> po\n  \n  ## we add or change the initial-state simulator,\n  ## rinit, using the 'rinit' argument in any 'pomp'\n  ## elementary or estimation function (or in the\n  ## 'pomp' constructor itself).\n  ## Here, we pass the rinit specification to 'simulate'\n  ## as an R function.\n\n  po |>\n    simulate(\n      rinit=function (n_0, ...) {\n        c(n=rpois(n=1,lambda=n_0))\n      }\n    ) -> sim\n\n  ## We can also pass it as a C snippet:\n\n  po |>\n    simulate(\n      rinit=Csnippet(\"n = rpois(n_0);\"),\n      paramnames=\"n_0\",\n      statenames=\"n\"\n    ) -> sim\n\n}\n"
  },
  {
    "path": "examples/rmeasure_spec.R",
    "content": "\\donttest{\n  ## We start with the pre-built Ricker example:\n  \n  ricker() -> po\n\n  ## To change the measurement model simulator, rmeasure,\n  ## we use the 'rmeasure' argument in any 'pomp'\n  ## elementary or estimation function.\n  ## Here, we pass the rmeasure specification to 'simulate'\n  ## as an R function.\n\n  po |>\n    simulate(\n      rmeasure=function (N, phi, ...) {\n        c(y=rpois(n=1,lambda=phi*N))\n      }\n    ) -> sim\n\n  ## We can also pass it as a C snippet:\n\n  po |>\n    simulate(\n      rmeasure=Csnippet(\"y = rpois(phi*N);\"),\n      paramnames=\"phi\",\n      statenames=\"N\"\n    ) -> sim\n\n}\n"
  },
  {
    "path": "examples/rw2.R",
    "content": "\\donttest{\n\n  if (require(ggplot2)) {\n\n    rw2() |> plot()\n\n    rw2(s1=1,s2=1,tau=0.1) |>\n      simulate(nsim=10,format=\"d\") |>\n      ggplot(aes(x=y1,y=y2,group=.id,color=.id))+\n      geom_path()+\n      guides(color=\"none\")+\n      theme_bw()\n\n  }\n}\n"
  },
  {
    "path": "examples/sir.R",
    "content": "\\donttest{\n  po <- sir()\n  plot(po)\n  coef(po)\n  \n  po <- sir2()\n  plot(po)\n  plot(simulate(window(po,end=3)))\n  coef(po)\n  \n  po |> as.data.frame() |> head()\n}\n"
  },
  {
    "path": "examples/skeleton_spec.R",
    "content": "\\donttest{\n  ## Starting with an existing pomp object,\n  ## e.g., the continuous-time Verhulst-Pearl model,\n\n  verhulst() -> po\n  \n  ## we add or change the deterministic skeleton\n  ## using the 'skeleton' argument in any 'pomp'\n  ## elementary or estimation function\n  ## (or in the 'pomp' constructor itself).\n  ## Here, we pass the skeleton specification\n  ## to 'trajectory' as an R function.\n  ## Since this is a continuous-time POMP, the\n  ## skeleton is a vectorfield.\n\n  po |>\n    trajectory(\n      skeleton=vectorfield(\n        function(r, K, n, ...) {\n          c(n=r*n*(1-n/K))\n        }\n      ),\n      format=\"data.frame\"\n    ) -> traj\n\n  ## We can also pass it as a C snippet:\n\n  po |>\n    traj_objfun(\n      skeleton=vectorfield(Csnippet(\"Dn=r*n*(1-n/K);\")),\n      paramnames=c(\"r\",\"K\"),\n      statenames=\"n\"\n    ) -> ofun\n\n  ofun()\n\n  ## For a discrete-time POMP, the deterministic skeleton\n  ## is a map.  For example,\n\n  gompertz() -> po\n\n  po |>\n    traj_objfun(\n      skeleton=map(\n        Csnippet(\"\n          double dt = 1.0;\n          double s = exp(-r*dt);\n          DX = pow(K,(1-s))*pow(X,s);\"\n        ), delta.t=1\n      ),\n      paramnames=c(\"r\",\"K\"),\n      statenames=c(\"X\")\n    ) -> ofun\n\n  ofun()\n\n}\n"
  },
  {
    "path": "examples/spect_match.R",
    "content": "\\donttest{\n\n  ricker() |>\n    spect_objfun(\n      est=c(\"r\",\"sigma\",\"N_0\"),\n      partrans=parameter_trans(log=c(\"r\",\"sigma\",\"N_0\")),\n      paramnames=c(\"r\",\"sigma\",\"N_0\"),\n      kernel.width=3,\n      nsim=100,\n      seed=5069977\n    ) -> f\n\n  f(log(c(20,0.3,10)))\n  f |> spect() |> plot()\n\n  if (require(subplex)) {\n    subplex(fn=f,par=log(c(20,0.3,10)),control=list(reltol=1e-5)) -> out\n  } else {\n    optim(fn=f,par=log(c(20,0.3,10)),control=list(reltol=1e-5)) -> out\n  }\n  f(out$par)\n\n  f |> summary()\n\n  f |> spect() |> plot()\n\n}\n"
  },
  {
    "path": "examples/spy.R",
    "content": "\\donttest{\n\n  ricker() |> spy()\n\n  sir() |> spy()\n\n  sir2() |> spy()\n\n}\n"
  },
  {
    "path": "examples/traj_match.R",
    "content": "\\donttest{\n\n  ricker() |>\n    traj_objfun(\n      est=c(\"r\",\"sigma\",\"N_0\"),\n      partrans=parameter_trans(log=c(\"r\",\"sigma\",\"N_0\")),\n      paramnames=c(\"r\",\"sigma\",\"N_0\")\n      ) -> f\n\n  f(log(c(20,0.3,10)))\n\n  if (require(subplex)) {\n    subplex(fn=f,par=log(c(20,0.3,10)),control=list(reltol=1e-5)) -> out\n  } else {\n    optim(fn=f,par=log(c(20,0.3,10)),control=list(reltol=1e-5)) -> out\n  }\n\n  f(out$par)\n\n  if (require(ggplot2)) {\n\n    f |>\n      trajectory(format=\"data.frame\") |>\n      ggplot(aes(x=time,y=N))+geom_line()+theme_bw()\n\n  }\n\n}\n"
  },
  {
    "path": "examples/trajectory.R",
    "content": "\\donttest{\n  ## The basic components needed to compute trajectories\n  ## of a deterministic dynamical system are\n  ## rinit and skeleton.\n\n  ## The following specifies these for a simple continuous-time\n  ## model: dx/dt = r (1+e cos(t)) x\n\n  trajectory(\n    t0 = 0, times = seq(1,30,by=0.1),\n    rinit = function (x0, ...) {\n      c(x = x0)\n    },\n    skeleton = vectorfield(\n      function (r, e, t, x, ...) {\n        c(x=r*(1+e*cos(t))*x)\n      }\n    ),\n    params = c(r=1,e=3,x0=1)\n  ) -> po\n\n  plot(po,log='y')\n\n  ## In the case of a discrete-time skeleton,\n  ## we use the 'map' function.  For example,\n  ## the following computes a trajectory from\n  ## the dynamical system with skeleton\n  ## x -> x exp(r sin(omega t)).\n\n  trajectory(\n    t0 = 0, times=seq(1,100),\n    rinit = function (x0, ...) {\n      c(x = x0)\n    },\n    skeleton = map(\n      function (r, t, x, omega, ...) {\n        c(x=x*exp(r*sin(omega*t)))\n      },\n      delta.t=1\n    ),\n    params = c(r=1,x0=1,omega=4)\n  ) -> po\n\n  plot(po)\n\n}\n"
  },
  {
    "path": "examples/userdata.R",
    "content": "\\donttest{\n  ## The familiar Ricker example.\n  ## Suppose that for some reason we wish to pass 'phi'\n  ## via the userdata facility instead of as a parameter.\n\n  ## C snippet approach:\n\n  simulate(times=1:100,t0=0,\n    userdata=list(phi=as.double(100)),\n    params=c(r=3.8,sigma=0.3,N.0=7),\n    rprocess=discrete_time(\n      step.fun=Csnippet(r\"{\n      double e = (sigma > 0.0) ? rnorm(0,sigma) : 0.0;\n      N = r*N*exp(-N+e);}\"\n      ),\n      delta.t=1\n    ),\n    rmeasure=Csnippet(r\"{\n       double phi = *get_userdata_double(\"phi\");\n       y = rpois(phi*N);}\"\n    ),\n    paramnames=c(\"r\",\"sigma\"),\n    statenames=\"N\",\n    obsnames=\"y\"\n  ) -> rick1\n\n  ## The same problem solved using 'globals':\n  simulate(times=1:100,t0=0,\n    globals=Csnippet(\"static double phi = 100;\"),\n    params=c(r=3.8,sigma=0.3,N.0=7),\n    rprocess=discrete_time(\n      step.fun=Csnippet(r\"{\n      double e = (sigma > 0.0) ? rnorm(0,sigma) : 0.0;\n      N = r*N*exp(-N+e);}\"\n      ),\n      delta.t=1\n    ),\n    rmeasure=Csnippet(\"\n       y = rpois(phi*N);\"\n    ),\n    paramnames=c(\"r\",\"sigma\"),\n    statenames=\"N\",\n    obsnames=\"y\"\n  ) -> rick2\n\n  ## Finally, the R function approach:\n\n  simulate(times=1:100,t0=0,\n    userdata=list(phi=100),\n    params=c(r=3.8,sigma=0.3,N_0=7),\n    rprocess=discrete_time(\n      step.fun=function (r, N, sigma, ...) {\n        e <- rnorm(n=1,mean=0,sd=sigma)\n        c(N=r*N*exp(-N+e))\n      },\n      delta.t=1\n    ),\n    rmeasure=function (phi, N, ...) {\n      c(y=rpois(n=1,lambda=phi*N))\n    }\n  ) -> rick3\n\n}\n"
  },
  {
    "path": "examples/verhulst.R",
    "content": "\\donttest{ # takes too long for R CMD check\n  verhulst() -> po\n  plot(po)\n  plot(simulate(po))\n  pfilter(po,Np=1000) -> pf\n  logLik(pf)\n  spy(po)\n}\n"
  },
  {
    "path": "inst/CITATION",
    "content": "year <- sub(\"-.*\", \"\", meta$Date)\nnote1 <- sprintf(\"{R}~package, version~%s\", meta$Version)\nnote2 <- sprintf(\"(R package, version %s)\", meta$Version)\n\nc(\n  bibentry(\n    header=paste(\"To cite the\",sQuote(\"pomp\"),\"package in publications, use:\"),\n    bibtype = \"Article\",\n    title = \"Statistical Inference for Partially Observed {Markov} Processes via the {R} Package {pomp}\",\n    author=c(\n      as.person(\"Aaron A. King\"),\n      as.person(\"Dao Nguyen\"),\n      as.person(\"Edward L. Ionides\")\n    ),\n    journal=\"Journal of Statistical Software\",\n    year=\"2016\",\n    volume=\"69\",\n    number=\"12\",\n    pages=\"1--43\",\n    doi=\"10.18637/jss.v069.i12\",\n    textVersion=paste(\n      \"A. A. King, D. Nguyen, E. L. Ionides (2016).\",\n      \"Statistical Inference for Partially Observed Markov Processes via the R Package pomp.\",\n      \"Journal of Statistical Software 69(12): 1–43.\",\n      \"DOI:10.18637/jss.v069.i12.\"\n    )\n  ),\n  bibentry(\n    header=\"Additionally, consider citing the package itself:\",\n    bibtype=\"Manual\",\n    title=\"{pomp}: {Statistical} Inference for Partially Observed {Markov} Processes\",\n    doi=\"10.5281/zenodo.15364462\",\n    author=c(\n      as.person(\"Aaron A. King\"),\n      as.person(\"Edward L. Ionides\"),\n      as.person(\"Carles Martinez Bret\\\\'o\"),\n      as.person(\"Stephen P. Ellner\"), \n      as.person(\"Matthew J. Ferrari\"),\n      as.person(\"Sebastian Funk\"),\n      as.person(\"Steven G. Johnson\"),\n      as.person(\"Bruce E. Kendall\"),\n      as.person(\"Michael Lavine\"),\n      as.person(\"Dao Nguyen\"),\n      as.person(\"Eamon B. O'Dea\"),\n      as.person(\"Daniel C. Reuman\"),\n      as.person(\"Helen Wearing\"),\n      as.person(\"Simon N. Wood\")\n    ),     \n    year=year,\n    note=note1,\n    url=meta$URL,\n    textVersion=paste0(\n      \"A. A. King, E. L. Ionides, C. M. Breto, S. P. Ellner, M. J. Ferrari, S. Funk, S. G. Johnson, B. E. Kendall, M. Lavine, D. Nguyen, E. B. O'Dea, D. C. Reuman, H. Wearing, and S. N. Wood\",\" (\",year,\"). \",\n      \"pomp: Statistical Inference for Partially Observed Markov Processes. \",\n      note2,\". \",meta$URL,\". DOI: 10.5281/zenodo.15364462\"\n    )      \n  )\n)\n"
  },
  {
    "path": "inst/GPL",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "inst/NEWS",
    "content": "_\bN_\be_\bw_\bs _\bf_\bo_\br _\bp_\ba_\bc_\bk_\ba_\bg_\be '_\bp_\bo_\bm_\bp'\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b6._\b3._\b1:\n\n        • ‘coef’ can now extract parameters by name from a ‘listie’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b6._\b2._\b1:\n\n        • The built-in examples that use simulated data add a ‘seed’\n          argument to allow changing the simulated data.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b6._\b1._\b1:\n\n        • The basic Kalman filter (‘kalmanFilter’) has been refactored,\n          with a roughly 3-fold speed up.\n\n        • Some internal changes have been made in anticipation of\n          changes to the C API for R.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b6._\b0._\b5:\n\n        • It is now possible to specify more than one lag in the ‘ivp’\n          function, which is evaluated only when the ‘mif2’\n          perturbations are specified.  See ‘?mif2’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b6._\b0._\b4:\n\n        • The new function ‘append_data’ appends a data frame to an\n          existing CSV file (creating the file if it does not exist).\n          This facilitates keeping a database of parameter-space\n          explorations.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b6._\b0._\b3:\n\n        • The new function ‘eeulermultinom’ gives the expectation of an\n          Euler-multinomial random variable.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b6._\b0._\b2:\n\n        • The ‘save.states’ option to ‘pfilter’ has changed.  See\n          ‘?pfilter’ and ‘?saved_states’ for details.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b6._\b0._\b1:\n\n        • In calls to ‘pomp’ elementary and inference algorithms, it is\n          now necessary to pass all arguments by name.  This has always\n          been good practice, but from this release, calls that rely on\n          the position of arguments will typically generate errors.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b6._\b0._\b0:\n\n        • From version 5.8.4, the manner in which extra model elements\n          (‘userdata’) are supplied has changed.  As of that version,\n          use of the old method generated a warning.  As of this\n          version, an error will be generated.  To supply additional\n          elements (i.e., beyond parameters, latent-state variables,\n          observations, and covariates) to the basic model components,\n          provide them as a list via the ‘userdata’ argument.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b1_\b1._\b1:\n\n        • A new addition to the C API allows one to easily compute the\n          expectation of the Euler-multinomial.  The function is\n          ‘eeulermultinom’.\n\n        • The help-page discussion of accumulator variables has been\n          expanded and clarified.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b1_\b0._\b1:\n\n        • An improper typecast in the C snippet system, which was\n          resolvable by many compilers but threw an error under recent\n          versions of ‘clang’ on MacOS, has been repaired.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b9._\b1:\n\n        • The rprocess plugin ‘onestep’ now always takes exactly one\n          step to get from one observation time to the next, even when\n          the interval between them is zero.  That is, if ‘P’ is a\n          ‘pomp’ object with an rprocess built using\n          ‘rprocess=onestep(f)’, ‘t0=timezero(P)’, and ‘t=time(P)’,\n          then ‘f’ will be called exactly once for the interval\n          (‘t0’,‘t[1]’) and once for each of the intervals\n          (‘t[i-1]’,‘t[i]’), ‘i=2,...,length(t)’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b8._\b4:\n\n        • To add additional elements for use by the basic model\n          components (i.e., “userdata”), the ‘userdata’ argument should\n          now be used.  The old behavior will still work, but will\n          generate a warning.  In a future release, this will become an\n          error.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b8._\b3:\n\n        • Internally, ‘pomp’ codes no longer include ‘Rinternal.h’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b8._\b2:\n\n        • A bug in covariate-table extrapolation for the case\n          ‘order=\"constant\"’ has been fixed.\n\n        • A new experimental function ‘repair_lookup_table’ is provided\n          to help eliminate unnecessary warnings about extrapolation.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b8._\b1:\n\n        • Functions with names that include dots (‘.’), which have been\n          defunct since version 4.7, have been expunged.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b7._\b1:\n\n        • The ‘err()’ and ‘warn()’ C-level macros have been redefined\n          to forestall problems that would arise when these macros are\n          included in C++ code under forthcoming versions of R.\n\n        • More changes in C codes to forestall issues detected by\n          ‘rchk’.\n\n        • Minor corrections to documentation.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b6._\b1:\n\n        • Minor corrections to documentation.\n\n        • Changes in some C codes to avoid issues detected by ‘rchk’.\n\n        • Fixed bug in ‘wquant’ introduced by changes in ‘pbeta’ with R\n          version 4.3.3.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b5._\b2:\n\n        • Minor corrections to documentation.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b5._\b1:\n\n        • C-level functions ‘set_pomp_userdata’ and\n          ‘unset_pomp_userdata’ are no longer exported.\n\n        • ‘bspline_eval’ is no longer exported.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b4._\b4:\n\n        • C-level functions ‘set_pomp_userdata’ and\n          ‘unset_pomp_userdata’ have been temporarily restored.  The\n          latter generates a warning.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b4._\b3:\n\n        • There is now access to ordinary B-spline basis functions (and\n          their derivatives) at the C snippet level.  It will still\n          almost always be preferable to construct a spline basis once\n          and pass it to ‘pomp’ functions as part of a\n          ‘covariate_table’, but this functionality may occasionally be\n          useful.\n\n        • ‘bspline_eval’ is now deprecated as part of the ‘pomp’ C API.\n\n        • The formatting of some printed messages has been modified to\n          forestall warnings in the latest R-devel.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b4._\b2:\n\n        • Stateful objective functions (class ‘objfun’) now behave as\n          if they are ‘pomp’ objects.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b4._\b1:\n\n        • C-level functions ‘set_pomp_userdata’ and\n          ‘unset_pomp_userdata’ are no longer exported.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b3._\b1:\n\n        • ‘stew’ now returns timing information by default.\n\n        • The spurious warnings associated with NULL ‘userdata’ have\n          been eliminated.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b2._\b5:\n\n        • The new option ‘on_load’ allows one to specify a C snippet\n          that will be executed at the time the C snippet library is\n          loaded.\n\n        • Internally, the ‘userdata’ are made available via calls to\n          ‘pompLoad’ rather than within each call to a ‘pomp’\n          workhorse.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b2._\b4:\n\n        • The data frames returned by ‘cond_logLik’ and\n          ‘eff_sample_size’ when ‘format=\"data.frame\"’ have been\n          improved.  In particular, they contain (as variable ‘time’)\n          the times (rather than the index of the time vector as\n          before).\n\n        • Changes to the report generated by ‘spy’.\n\n        • Some documentation improvements.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b2._\b3:\n\n        • The manual pages have been reorganized, with improved\n          cross-linking.\n\n        • A bug in ‘filter_traj’ etc. arising when not all state\n          variables have names was fixed.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b2._\b2:\n\n        • This version adds the new basic component ‘dinit’ for\n          evaluating the probability density function of the\n          initial-state distribution.  There is a corresponding\n          workhorse function, ‘dinit()’.\n\n        • The constructor ‘pomp’ now takes the optional argument\n          ‘nstatevars’, which can be used to increase the dimension of\n          the latent state-vectors created by ‘rinit’.  By default,\n          ‘nstatevars = length(statenames)’, and ‘nstatevars’ can only\n          be used to _increase_, not to decrease, the dimension of the\n          latent state process.  Moreover, ‘nstatevars’ has no effect\n          if the ‘rinit’ basic component is furnished as an R function.\n\n        • Name checking on internally-created vectors and arrays is\n          less strict than previously.  In particular, it is possible\n          to have variables without names (i.e., ‘\"\"’).\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b2._\b1:\n\n        • ‘reulermultinom’ now returns ‘NA’ rather than ‘NaN’, in\n          keeping with the behavior of ‘rbinom’.  Thanks to John Drake\n          for calling attention to this issue.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b1._\b1:\n\n        • A bug in ‘stew’ resulting in namespace conflicts has been\n          repaired.\n\n        • We no longer import directly from ‘tidyverse’ functions.\n          This reduces the list of packages upon which ‘pomp’ depends\n          from 20 to 5.  This does introduce a dependency on the\n          ‘data.table’ package.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b0._\b1:\n\n        • When the archive directory does not exist, ‘bake’ and ‘stew’\n          now create it.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b5._\b0._\b0:\n\n        • We no longer import from ‘plyr’.\n\n        • The ‘dimnames’ attributes of various arrays that appear in\n          ‘pomp’, including arrays of observables, state variables,\n          parameters, covariates, and so on, have been made uniform.\n          In particular, when a dimension of an array corresponds to\n          variables with different names, this dimension is itself\n          named “name”.  Previously, its name was sometimes “variable”\n          and sometimes “parameter”.  This change is meant to\n          streamline interaction with the ‘tidyverse’.\n\n        • Some minor bugfixes.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b7._\b0:\n\n        • Functions with names.that.contain.dots that have been\n          deprecated since version 4.5.1 are now defunct.  Attempts to\n          use such functions will generate an error with a message\n          indicating the replacement function.\n\n        • ‘plot’ now removes ‘NA’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b6._\b4:\n\n        • Better handling of ‘listie’s (lists of ‘pomp’ objects).\n\n        • New ‘concat’ function to turn lists of ‘pomp’ objects into\n          ‘listies’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b6._\b3:\n\n        • Bug fix in ‘filter_traj’ applied to ‘pfilterList’ and\n          ‘pmcmcList’ objects.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b6._\b2:\n\n        • The ‘states’ and ‘obs’ methods take a new optional argument,\n          ‘format’.  Setting ‘format=\"data.frame\"’ causes the method to\n          return the states or data in a convenient data-frame format.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b6._\b1:\n\n        • When ‘melt’ is applied to a list, the identifier variable is\n          now “‘.Lx’”, where ‘x’ denotes the level.  This applies when\n          ‘as.data.frame’ is used to coerce a list of ‘pomp’ objects,\n          and when ‘saved_states’ is used to extract the particles from\n          a list of ‘pfilterd_pomp’ objects.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b5._\b3:\n\n        • ‘logmeanexp’ can now compute the effective sample size, which\n          can be useful in determining the reliability of its estimate.\n          To do so, set ‘ess=TRUE’ in a call to ‘logmeanexp’.\n\n        • ‘logmeanexp’ now returns a fully-named vector when either\n          ‘se=TRUE’ or ‘ess=TRUE’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b5._\b2:\n\n        • A new ‘format’ argument has been added to the extractor\n          functions ‘cond_logLik’, ‘eff_sample_size’, ‘filter_mean’,\n          ‘filter_traj’, ‘forecast’, ‘pred_mean’, ‘pred_var’, and\n          ‘saved_states’.  This allows the user to extract the relevant\n          elements in data-frame format if desired.\n\n        • ‘pomp’ no longer depends on the superseded package\n          ‘reshape2’.  The ‘melt’ function for converting arrays and\n          nested lists into data frames is accordingly no longer\n          re-exported from ‘reshape2’.  It has been replaced by a\n          stricter version of ‘melt’.\n\n        • The ‘magrittr’ pipe ‘%>%’ is no longer re-exported by ‘pomp’:\n          use the native R pipe ‘|>’ instead.\n\n        • The package now requires R version 4.1 at least.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b5._\b1:\n\n        • All ‘pomp’ functions with names.that.contain.dots have been\n          deprecated in favor of functions in ‘snake_case’.  This is to\n          avoid anticipated problems with CRAN checks, which (falsely)\n          assume that certain functions with dotted.names are S3\n          methods.  From this point, no exported ‘pomp’ function has\n          such a name.\n\n        • The ‘dimnames’ attributes for some of the arrays computed in\n          ‘pfilter’ and ‘pmcmc’ computations have changed.  In\n          particular, whereas in previous versions, the ‘time’\n          dimension was given names that were character strings\n          composed of decimal representations of the time (difficult to\n          work with and prone to roundoff error), the ‘time’ dimension\n          now is not given names.\n\n        • A bug that resulted in ‘gompertz’ giving different\n          simulations on Windows machines has been fixed.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b4._\b3:\n\n        • A bug in trajectory computation for maps (discrete-time\n          dynamical systems) has been fixed.  Thanks to Felicia\n          Magpantay for noticing it and tracking it down.\n\n        • Minor documentation improvements.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b4._\b2:\n\n        • The weighted quantile function ‘wquant’ now uses the\n          Harrell-Davis estimator instead of the type-7 estimator used\n          previously.  This eliminates bugs associated with non-integer\n          weights.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b4._\b1:\n\n        • It is now possible to retrieve the weighted particles\n          computed in the course of a ‘pfilter’ computation.  To\n          accomplish this, set ‘save.states=\"weighted\"’ in the call to\n          ‘pfilter’ and retrieve the particles and their weights using\n          ‘saved.states’.  Previously, one could obtain only the\n          unweighted particles.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b4._\b0:\n\n        • Some documentation improvements.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b3._\b4:\n\n        • The new function ‘wquant’ computes weighted quantiles.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b3._\b3:\n\n        • The precise order in which the ‘pmcmc’ function computes\n          prior and likelihood of furnished and proposed parameters has\n          changed slightly.  This prevents proposals that are\n          incompatible with the prior from being passed to ‘pfilter’\n          and forestalls an associated class of errors.  A consequence\n          of this change, ‘pmcmc’ computations using the new version\n          will differ very slightly from previous computations, even\n          with the RNG seed fixed at its previous values.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b3._\b2:\n\n        • There is now a C interface to the ‘bspline_eval’ function.\n          See the ‘pomp’ C API documentation for details.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b3._\b1:\n\n        • The ‘bspline.basis’ function now takes the optional argument\n          ‘rg’ which allows one to specify the range over which the\n          basis will be constructed.  By default, this is ‘range(x)’,\n          which agrees with the behavior in earlier versions.\n\n        • Documentation improvements.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b2._\b2:\n\n        • The archiving functions ‘bake’ and ‘stew’ now use a slightly\n          less exacting comparison of the expression, ‘expr’, they are\n          furnished.  *NB:* Running ‘bake’ or ‘stew’ with archives\n          created by earlier versions may result in recomputation.\n\n        • The ‘time’ method has been extended to ‘pompList’ and related\n          objects.\n\n        • All workhorse functions except ‘partrans’ have new default\n          arguments.\n\n        • Some documentation improvements.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b2._\b1:\n\n        • The archiving functions ‘bake’ and ‘stew’ now take the\n          argument ‘dir’, which is the directory holding the archive\n          files.  By default, this is the current working directory or\n          the value of the global option ‘pomp.archive.dir’.\n\n        • A new global option, ‘pomp_archive_dir’, can be used to\n          specify the locations of archive files used by ‘bake’ and\n          ‘stew’.\n\n        • Documentation repair of issue flagged by Kurt Hornik (9 June\n          2022).\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b2._\b0:\n\n        • Minor changes, invisible to the user.\n\n        • Minor changes to the C codes to keep up with R-devel.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b1._\b0:\n\n        • Minor changes to the C codes to keep up with R-devel.\n\n        • Minor changes in the implementation of ‘bake’ and ‘stew’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b0._\b1_\b1:\n\n        • Change in the names of the variables returned by\n          ‘as.data.frame’ applied to a ‘pfilterd.pomp’ object.\n\n        • Fixed bug found by Jesse Wheeler and Ed Ionides, to do with\n          `simulate()` with `include.data=TRUE`.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b0._\b1_\b0:\n\n        • It is now possible to plot lists of ‘pomp’ and ‘pomp’-derived\n          objects using a single call to ‘plot’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b0._\b9:\n\n        • The ‘rbetabinom’ and ‘dbetabinom’ functions, long present as\n          part of the C API, are now available as R functions.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b0._\b8:\n\n        • The SIR examples ‘sir()’ and ‘sir2()’ now use a negative\n          binomial measurement model.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b0._\b7:\n\n        • ‘parmat’ can now take a data frame of parameters and convert\n          it into a matrix suitable for furnishing to the ‘params’\n          argument of any ‘pomp’ function.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b0._\b6:\n\n        • It is now possible to change the parameters in an ‘objfun’\n          (objective function) object using ‘coef(object)<-value’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b0._\b5:\n\n        • ‘parmat’ now takes an optional argument, ‘names’, which\n          allows the user to name the parameter sets.\n\n        • Independent realizations of the stochastic processes modeled\n          in ‘pomp’ are now distinguished by different values of ‘.id’.\n          This behavior is now uniform throughout.\n\n        • ‘bake’ and ‘stew’ now send messages instead of warnings when\n          they recompute an archive due to a change in code or\n          dependencies.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b0._\b4:\n\n        • The ensemble adjusted Kalman filter (‘eakf’) has been\n          refactored.  It now makes use of the ‘emeasure’ and\n          ‘vmeasure’ basic components to compute an approximation of\n          the linear relationship between the latent state and the\n          observed variables.\n\n        • The ‘forecast’ method now works for ‘pfiterd_pomp’ objects\n          (i.e., results of ‘pfilter’, ‘pmcmc’, or ‘mif2’\n          computations).\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b0._\b3:\n\n        • Two new basic model components have been introduced.  These\n          are:\n\n          emeasure, which computes the expectation of the observable\n              variables conditional on the latent state;\n\n          vmeasure, which computes the covariance matrix of the\n              observables given the latent state.\n\n          These are used by the newly refactored ensemble Kalman\n          filter, ‘enkf’.\n\n        • The basic (linear, Gaussian) Kalman filter is now available\n          as ‘kalmanFilter’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b0._\b2:\n\n        • Computation of Monte Carlo-adjusted profile likelihood is now\n          facilitated by the new ‘mcap’ function.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b0._\b1:\n\n        • The default return-value format for ‘trajectory’ now matches\n          that of ‘simulate’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b4._\b0._\b0:\n\n     Version 4 contains a few changes that are not backward compatible.\n     These are all to do with the elementary function ‘trajectory’,\n     which computes trajectories of the deterministic dynamical\n     skeleton.  See below for details.\n\n        • The behavior of ‘trajectory’ now fully conforms to the\n          behavior of other ‘pomp’ elementary functions.  In\n          particular, one can now add, remove, or modify basic model\n          components in a call to ‘trajectory’ just as one can with\n          ‘simulate’, ‘pfilter’, ‘probe’, etc.  Before version 4,\n          additional arguments to ‘trajectory’ (i.e., those passed via\n          ‘...’) were passed on to the ODE integrator in the case of\n          continuous-time deterministic skeletons (i.e., vectorfields)\n          and ignored in the case of discrete-time skeletons (i.e.,\n          maps).  As of version 4, in order to adjust ODE integrator\n          settings it is necessary to use the ‘ode_control’ argument of\n          ‘trajectory’.  This behavior matches that of ‘traj_objfun’.\n\n        • It is now possible to create a ‘pomp’ object from scratch\n          using ‘trajectory’, together with a specification of the\n          rinit and skeleton components.  Prior to version 4, in order\n          to do so, it was necessary to first create a dummy data set,\n          then call ‘pomp’, and then pass the resulting ‘pomp’ object\n          to ‘trajectory’.  This can now be achieved in one call.\n\n        • The user now has the option, in a call to ‘trajectory’, to\n          have the results returned as one or ‘pomp’ objects.  In this\n          regard, its behavior matches that of ‘simulate’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b3._\b5._\b6:\n\n        • The ‘states’ and ‘obs’ methods now work for lists of ‘pomp’\n          objects (‘listies’).\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b3._\b5._\b5:\n\n        • The workhorse function ‘flow’ now has default arguments.\n\n        • The stateful objective function created by ‘traj_objfun’ has\n          been refactored so that it is independent of ‘trajectory’.\n          This change is invisible to the user, but lays the groundwork\n          for future changes in ‘trajectory’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b3._\b5._\b4:\n\n        • Stateful objective functions created by ‘traj_objfun’,\n          ‘nlf_objfun’, ‘probe_objfun’, and ‘spect_objfun’ now have\n          default arguments.  In particular, the default is argument is\n          a zero-length numeric vector.  Calling such a function with\n          no arguments is valid if and only if the objective function\n          was created with no variables to estimate (empty ‘est’).\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b3._\b5._\b3:\n\n        • Fixed bug in ‘rprior’ arising with integer-valued return\n          vectors.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b3._\b5._\b2:\n\n        • Major improvements to the package manual, including richer\n          cross-linking and better organization.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b3._\b5._\b1:\n\n        • When ‘simulate’ is called with ‘format=\"data.frame\"’ and\n          ‘include.data=TRUE’, the interpolated covariates are now\n          included in the data frame that is returned.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b3._\b4._\b6:\n\n        • ‘bake’ takes a new option, ‘timing’, that controls whether\n          information on the timing is returned or merely stored.  By\n          default, this is set to ‘TRUE’, though this default behavior\n          may change in future.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b3._\b4._\b5:\n\n        • When they encounter an archive produced by an older version,\n          ‘bake’ and ‘stew’ now update the archive in the new format.\n          Recomputation should never be triggered in this case: If\n          recomputation is desired, delete the archive file.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b3._\b4._\b4:\n\n        • ‘bake’ and ‘stew’ now archive a digest of the code in ‘expr’\n          and on subsequent calls check to see if the archived version\n          matches the current version.  Thus, changes to the code\n          automatically trigger recomputation.\n\n        • ‘bake’ and ‘stew’ take the new argument ‘dependson’.  Using\n          this argument, the user can specify objects upon which the\n          computation depends.  These should be passed as unquoted\n          variables; if there are multiple dependencies, they can be\n          passed using ‘c’ or ‘list’.  Digests of these objects will be\n          archived and checked against current values on subsequent\n          calls.  Thus, changing any dependency will automatically\n          trigger recomputation.\n\n        • ‘bake’ now archives the information pertinent to the ‘bake’\n          call; this information is no longer returned along with the\n          result of the computation (unless ‘info=TRUE’).  Similarly,\n          ‘stew’ stores a list, “.ingredients”, in the file it creates.\n          In the ‘stew’ case, unlike all the other objects that are\n          created by ‘expr’, this list is _not_ by default loaded into\n          the calling environment (e.g., the user's workspace).  It\n          will be loaded if the ‘info’ flag is set to ‘TRUE’.\n\n        • ‘freeze’ no longer stores the details of the RNG seed and\n          kind as an attribute of the returned object.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b3._\b4._\b2:\n\n        • Fix bug in ‘bsmc2’ arising when some particles have zero\n          likelihood.  This is Issue #152.  Thanks to Hola-Kwame\n          Adrakey for reporting it.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b3._\b4._\b1:\n\n        • It is now possible to call ‘partrans’ directly on an\n          objective function, such as those created by ‘traj_objfun’,\n          ‘nlf_objfun’, ‘probe_objfun’, or ‘spect_objfun’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b3._\b3._\b1:\n\n        • The package manual and help pages has been streamlined.\n\n        • The ‘mif2’ diagnostic plots have been made more flexible.\n\n        • Some deprecated functions have been removed.  These include\n          ‘cond.loglik’, ‘sliceDesign’, ‘runifDesign’, ‘sobolDesign’,\n          and ‘profileDesign’, which have been replaced by\n          ‘code.logLik’, ‘slice_design’, ‘runif_design’,\n          ‘sobol_design’, and ‘profile_design’, respectively.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b3._\b3._\b0:\n\n        • A bug in ‘rgammawn’ has been fixed.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b3._\b2._\b0:\n\n        • The ‘pomp’ C API has been expanded a bit, to facilitate other\n          packages' linking to the ‘pomp’ library.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b3._\b1._\b1:\n\n        • The help pages have been improved, with an description of the\n          overall package structure and pages on basic model\n          components, elementary algorithms, and estimation algorithms.\n\n        • A note to Windows users on avoiding certain C snippet\n          compilation errors has been added to the help pages.\n\n        • The behavior of ‘profile_design’ has changed.  Previously,\n          the same random (or sub-random) sequence was used for all\n          non-profile parameters.  Now, for each profile slice, a\n          distinct set of points is generated.\n\n        • ‘profileDesign’, ‘sliceDesign’, ‘runifDesign’, and\n          ‘sobolDesign’ have been deprecated and will be removed in a\n          future release.  They are replaced by ‘profile_design’,\n          ‘slice_design’, ‘runif_design’, and ‘sobol_design’,\n          respectively.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b3._\b0._\b3:\n\n        • A new ‘saved.states’ method allows one to extract the saved\n          states from a particle filter computation.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b3._\b0._\b2:\n\n        • All instances of ‘cond.loglik’ have been changed to\n          ‘cond.logLik’, to remove a common source of typographical\n          error.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b3._\b0._\b1:\n\n        • A new sequential importance sampling algorithm has been\n          implemented as ‘wpfilter’.  This is a generalization of the\n          algorithm in ‘pfilter’ in that it tracks the weights of the\n          particles and allows the user to customize the resampling\n          scheme.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b3._\b0._\b0:\n\n        • In ‘mif2’, the specification of particle numbers, ‘Np’, has\n          changed.  When ‘Np’ is supplied as a function, ‘Np(0)’ is the\n          requested number of particles at the beginning of the time\n          series.  The previous behavior was that ‘Np(1)’ specified the\n          requested number of particles.  This behavior now matches\n          that of the other particle filtering algorithms, ‘pfilter’,\n          ‘bsmc2’, and ‘pmcmc’.\n\n        • ‘bsmc2’ can now accept a variable number of particles, as do\n          the other particle-filter based algorithms ‘pfilter’,\n          ‘pmcmc’, and ‘mif2’.\n\n        • The internal ‘systematic_resample’ function now allows the\n          user to specify the number of samples desired.  Previously,\n          these were always equal to the number of weights supplied.\n\n        • As promised from version 2.4.1, the ‘tol’ and ‘max.fail’\n          arguments have been removed completely from all\n          particle-filtering algorithms, including ‘pfilter’, ‘pmcmc’,\n          ‘bsmc2’, and ‘mif2’.  See the ‘pomp’ news blog\n          (<https://kingaa.github.io/pomp/blog.html>) for more\n          information.\n\n        • The long-deprecated functions ‘onestep.dens’, ‘onestep.sim’,\n          ‘discrete.time.sim’, ‘euler.sim’, ‘gillespie.sim’,\n          ‘gillespie.hl.sim’, ‘conv.rec’, and ‘values’ have been\n          removed.  These have been replaced as follows\n\n            ‘onestep.dens’       direct specification of ‘dprocess’ component \n            ‘onestep.sim’        ‘onestep’                                    \n            ‘discrete.time.sim’  ‘discrete_time’                              \n            ‘euler.sim’          ‘euler’                                      \n            ‘gillespie.sim’      ‘gillespie’                                  \n            ‘gillespie.hl.sim’   ‘gillespie_hl’                               \n            ‘conv.rec’           ‘traces’                                     \n            ‘values’             ‘as.data.frame’ or ‘as(x,\"data.frame\")’      \n           \n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b8._\b0:\n\n        • Trap error from non-finite likelihoods in ‘pmcmc’.\n\n        • New test of ‘pmcmc’ codes in ‘tests/issue109.R’.\n\n        • Trap error from missing accumulator variables in\n          ‘trajectory’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b7._\b2:\n\n        • The Euler step size in ‘sir’ is now adjustable.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b7._\b1:\n\n        • As promised, the default value of ‘tol’ in the\n          particle-filtering algorithms ‘pfilter’, ‘pmcmc’, ‘mif2’, and\n          ‘bsmc2’ has been changed to zero.  A warning continues to be\n          issued if ‘tol’ is set to anything other than 0.  In a future\n          release, the option to choose a nonzero tolerance will be\n          removed entirely.\n\n        • In traces and diagnostic plotting methods, the ‘nfail’\n          variable (tracking numbers of filtering failures) has been\n          dropped.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b6._\b0:\n\n        • Another documentation bug was fixed.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b5._\b0:\n\n        • A documentation bug, identified by K. Hornik, was fixed.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b4._\b1:\n\n        • In anticipation of forthcoming algorithmic changes, the ‘tol’\n          and ‘max.fail’ arguments of ‘pfilter’, ‘bsmc2’, ‘pmcmc’, and\n          ‘mif2’ are now deprecated.  A warning is issued if ‘tol’ is\n          set to anything other than 0.  In a future release, these\n          options will be removed entirely: the behavior will be\n          similar to that obtained in the present release by setting\n          ‘tol=0’.\n\n        • A new example illustrating the ‘accumvars’ argument has been\n          provided.\n\n        • Internal computations now use increased precision for means,\n          variances, and certain calculations with likelihoods.\n\n        • A new help page, ‘pomp_examples’, lists the various example\n          datasets and pomp objects provided with the package.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b3._\b0:\n\n        • The source codes underlying specification of basic model\n          components via R functions has been reworked to remove\n          reliance on deep ‘PROTECT’ stacks.  Thanks to Thomas Kalibera\n          for showing the way!\n\n        • A bug in the documentation for ‘filter.traj’, pointed out by\n          Pierre Jacob, has been fixed.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b2._\b2:\n\n        • The C API for ‘pomp’ is no longer explained only in comments\n          in the “pomp.h” header file.  It is now described and\n          explained in the new C API vignette.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b2._\b1:\n\n        • The new ‘pomp_cdir’ global option allows one to set the\n          directory holding C snippet files globally.\n\n        • A bug caused by re-use of the ‘cfile’ argument has been\n          fixed.  Re-use now triggers an error, with an informative\n          message.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b2._\b0:\n\n        • Some documentation improvements.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b1._\b2:\n\n        • A bug in ‘runifDesign’ (and therefore ‘profileDesign’ when\n          ‘type=\"runif\"’) has been fixed.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b1._\b1:\n\n        • There are now ‘plot’ methods for objects of classes\n          ‘probe_match_objfun’ and ‘spect_match_objfun’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b1._\b0:\n\n        • Released to CRAN.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b0._\b1_\b4:\n\n        • The ‘melt’ function can now be applied to arbitrary ‘pomp’\n          objects.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b0._\b1_\b3:\n\n        • A new function, ‘runifDesign’ allows construction of design\n          matrices using samples from multivariate uniform\n          distributions.\n\n        • The ‘profileDesign’ function takes a new argument, ‘type’,\n          with two options: ‘\"sobol\"’, the default, constructs the\n          design using ‘sobolDesign’, as before.  ‘\"runif\"’ uses the\n          new ‘runifDesign’ function.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b0._\b1_\b2:\n\n        • A new example, comprising models and data for the 2014--2016\n          west African Ebola virus disease outbreak, is included.  See\n          ‘?ebola’ for details.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b0._\b1_\b1:\n\n        • It is now possible to adjust the observation times and\n          zero-time in the ‘sir’ and ‘sir2’ examples.  One can also\n          change the default RNG seed used in generating the simulated\n          data.\n\n        • The codes underlying the ‘rprocess’ workhorse have been\n          streamlined to obviate an unnecessary copy operation.  As a\n          result, the interface to the ‘rprocess’ workhorse has been\n          changed.\n\n        • The interface to the new ‘flow’ workhorse has been changed to\n          match.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b0._\b1_\b0:\n\n        • The new ‘flow’ workhorse allows integration/iteration of the\n          deterministic skeleton at arbitrary times from an arbitrary\n          initial condition.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b0._\b9:\n\n        • When ‘coef’ is applied to a ‘listie’, the result can be more\n          usefully ‘melt’ed.\n\n        • The probe-names returned by ‘probe.acf’ and ‘probe.ccf’ have\n          changed.\n\n        • A bug, whereby the ‘coef’ method from other packages was\n          masked, has been fixed.\n\n        • Errors in the documentation have been corrected.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b0._\b8:\n\n        • There is a new ‘as.data.frame’ method for ‘listie’s.\n\n        • Some problems with the exposure of internal objects for\n          package developers have been corrected.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b0._\b7:\n\n        • The ‘magrittr’ pipe operator, ‘%>%’, is now re-exported.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b0._\b6:\n\n        • More examples have been included.\n\n        • Minor changes to error messages.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b0._\b5:\n\n        • The names of the ‘objfun’ methods have been changed to\n          ‘probe_objfun’, ‘spect_objfun’, ‘traj_objfun’, and\n          ‘nlf_objfun’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b0._\b4:\n\n        • The package directory structure has been modified to include\n          a new ‘examples’ directory, which holds the examples used in\n          the documentation.\n\n        • The names of the ‘objfun’ methods have been shortened.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b0._\b3:\n\n        • It is now permissible that the sequence of observation times\n          (and sequences of covariate times) be merely non-decreasing\n          sequences.  Previously, ‘pomp’ insisted on strictly\n          increasing time sequences.\n\n        • The default cooling schedule (‘cooling.type’) in ‘mif2’ is\n          now “geometric”, in contrast to “hyperbolic”, as before.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b0._\b2:\n\n        • ‘pomp’ now requires at least R version 3.5.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b0._\b1:\n\n        • The ‘zeronames’ argument has been renamed ‘accumvars’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b2._\b0._\b0:\n\n        • In the course of ordinary work, one should never need to\n          interact with the low-level ‘pomp’ constructor function now.\n\n        • The ‘pompExample’ function has been dropped.  The various\n          examples are now included as regular functions that construct\n          ‘pomp’ objects.\n\n        • The ‘bbs’ example has been dropped.\n\n        • One can now modify basic model components at (almost) any\n          stage in a pipeline of ‘pomp’ computations.  All the\n          top-level inference functions, plus ‘probe’, ‘pfilter’, and\n          ‘simulate’ now allow modification of basic model components.\n\n        • The ‘rprocess’ plugins ‘onestep.sim’, ‘discrete.time.sim’,\n          ‘euler.sim’, ‘gillespie.sim’, and ‘gillespie.hl.sim’ have\n          been renamed ‘onestep’, ‘discrete_time’, ‘euler’,\n          ‘gillespie’, and ‘gillespie_hl’, respectively.  The old usage\n          is available but deprecated.\n\n        • One can now call ‘simulate’ on a model without reference to\n          any data.\n\n        • The covariate table facility (‘covariate_table’) now supports\n          piecewise constant interpolation.\n\n        • The syntax with which one includes covariates via\n          ‘covariate_table’ has become more flexible.  Specifically,\n          the arguments to ‘covariate_table’ are now evaluated\n          sequentially, so that later ones can depend on earlier ones.\n          Once evaluated, the covariates are bound column-wise into a\n          single data frame.\n\n        • The manner in which one writes R functions to specify basic\n          model components has been totally changed.  Before, one wrote\n          functions that took specific arguments such as 'x', 'params',\n          and 'covars'.  Now, one writes such functions with any or all\n          state variables, observables, covariates, and/or time as\n          arguments.\n\n        • ‘simulate’ now returns more informative results when\n          simulations from multiple parameter sets are simultaneously\n          computed.  Specifically, if ‘params’ has column names, these\n          are used to identify the resulting simulations.  Thus when\n          ‘format = \"pomps\"’ (the default), the names of the resulting\n          list will be constructed from the column names of ‘params’.\n          Likewise, when ‘format = \"arrays\"’, the resulting arrays will\n          have informative column names; When ‘format = \"data.frame\"’,\n          the identifier variable will make use of the column names.\n\n        • The basic particle filter, ‘pfilter’, has a simpler mode of\n          operation: ‘params’ should be a single parameter set only.\n          That is, it is no longer possible to pass a matrix of\n          parameters to ‘pfilter’.\n\n        • The Liu-West algorithm, ‘bsmc2’, has a simpler mode of\n          operation: ‘params’ should be a single parameter set only:\n          the SMC particles are drawn from ‘rprior’.\n\n        • The ‘as.data.frame’, ‘states’, and ‘obs’ options for\n          ‘simulate’ have been done away with.  One now chooses the\n          format of the returned simulations via the ‘format’ argument.\n          When one simulates at multiple parameter sets, list names,\n          array ‘dimnames’, or identifying variables in the output data\n          frame help to correlate simulations with parameter sets.\n\n        • The ‘as.data.frame’ argument to ‘trajectory’ has been removed\n          in favor of a new ‘format’ argument that allows one to choose\n          between receiving the results in the form of an ‘\"array\"’ or\n          a ‘\"data.frame\"’.\n\n        • All the basic model components now have defaults.\n\n            • The default ‘rinit’ behavior remains as it was: it\n              assumes the initial state distribution is concentrated at\n              a point mass determined by parameters with “‘.0’” or\n              “‘_0’” suffices.\n\n            • The default process model is “missing”: calls to\n              ‘dprocess’ and ‘rprocess’ will result in missing values\n              (‘NA’).\n\n            • The default measurement model is “missing” as well.\n\n            • The default prior is flat and improper: all calls to the\n              default ‘dprior’ result in ‘1’ (‘0’ if ‘log = TRUE’, and\n              all calls to ‘rprior’ result in ‘NA’.\n\n            • The default skeleton is missing.\n\n            • The default parameter transformations remain the\n              identity.\n\n        • The ‘transform’ argument present in many ‘pomp’ algorithms\n          has been removed.  Parameter transformations are now\n          automatically performed when appropriate.  The default\n          parameter transformation remains the identity.\n\n        • The old ‘probe.match’ and ‘traj.match’ functions have been\n          removed.  The new approach to parameter estimation based on\n          numerical optimization involves constructing stateful\n          objective functions.  There are now three of these:\n          ‘traj.match.objfun’, ‘probe.match.objfun’, and\n          ‘spect.match.objfun’.\n\n        • The documentation system has been thoroughly overhauled.\n\n        • In ‘skeleton’, the ‘t’ argument has been replaced by ‘times’,\n          to make this uniform with the other workhorse functions.\n\n        • Covariates are now included using the ‘covariate_table’\n          construction, passed via the ‘covar’ argument to ‘pomp’.  The\n          ‘tcovar’ argument is no longer used.\n\n        • Instead of providing separate ‘fromEstimationScale’ and\n          ‘toEstimationScale’ arguments to ‘pomp’, one now provides a\n          single ‘partrans’ argument constructed by means of the new\n          function ‘parameter_trans’.  In addition, references to\n          “fromEstimationScale” and “toEstimationScale” have been\n          abbreviated to “fromEst” and “toEst”, respectively,\n          throughout the package.\n\n        • When writing C snippets for parameter transformations, the\n          notation ‘T_p’ refers to the value of ‘p’ on the estimation\n          scale.  Thus, if parameter alpha is to be log-transformed for\n          estimation, the ‘toEst’ snippet would contain the line\n          ‘T_alpha = log(alpha);’ and the ‘fromEst’ snippet would\n          include ‘alpha = exp(T_alpha);’.\n\n        • The ‘parameter_trans’ function now takes optional arguments\n          ‘log’, ‘logit’, and ‘barycentric’, with names of parameters\n          to be log-, logit-, and log-barycentric transformed,\n          respectively.\n\n        • The ‘measurement.model’ argument to ‘pomp’ has been removed.\n          It is now necessary to specify the measurement model directly\n          using ‘rmeasure’ and/or ‘dmeasure’.\n\n        • The ‘initializer’ is no longer referred to by that name.  It\n          is now ‘rinit’, since it draws from the distribution of the\n          latent state at the initial time.  The low-level function\n          ‘init.state’ has been replaced by ‘rinit’.\n\n        • The ‘conv.rec’ method has been deprecated, replaced by the\n          new ‘traces’ method.\n\n        • The ‘euler.sir’ example has been renamed ‘sir’.\n\n        • The ‘gillespie.sir’ example has been renamed ‘sir2’.\n\n        • The ‘covmat’ method can now be applied to a ‘probed.pomp’\n          object.  It returns the estimated covariance matrix of the\n          probes.\n\n        • When ‘trajectory’ calls on ‘deSolve’ routines to numerically\n          integrate a model vectorfield, more informative error\n          messages are generated, and diagnostics are printed when\n          ‘verbose = TRUE’.\n\n        • The ‘show’ method applied to pomp objects is now quite terse.\n          To obtain detailed information, the ‘spy’ method is\n          available.\n\n        • The ‘spy’ method now returns the information formerly\n          displayed in a call to ‘show’, in addition to the C files\n          associated with any C snippets.\n\n        • The use of ‘$’ methods to access the slots of ‘pomp’ S4\n          objects has now been removed.  These classes are no longer\n          exported (for the most part).\n\n        • The ‘transform’ argument to the ‘probe.quantile’ function has\n          been removed (as it is entirely redundant!).\n\n        • The old and deprecated ‘mif’ and ‘bsmc’ methods have been\n          removed.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b8._\b8:\n\n        • The ‘obs’ and ‘states’ arguments of ‘simulate’ are deprecated\n          and will be removed in a forthcoming release.\n\n        • The C-level interface for ‘apply_probe_sims’ has changed: the\n          new argument ‘rho’ must be the “package:pomp” environment.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b8._\b7:\n\n        • A bug in ‘pfilter’ (and hence ‘pmcmc’) when\n          ‘filter.traj=TRUE’ was discovered and fixed.  In the buggy\n          version, the filter trajectory was sampled with incorrect\n          weights.\n\n        • Timo Voipio contributed a pull request that traps the error\n          resulting from ‘sannbox’ being passed a ‘candidate.dist’ that\n          is not a function.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b8._\b6:\n\n        • ‘show’ and ‘print’ methods have been made very terse: they\n          simply report on the class of the object in question.  To see\n          more detailed information about a ‘pomp’ object, use ‘spy’.\n\n        • New (unexported) ‘solibs<-’ method allows developers of\n          packages extending ‘pomp’ to incorporate C snippets into\n          object that contain ‘pomp’ objects.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b8._\b5:\n\n        • New ‘verbose’ option in ‘trajectory’ gives diagnostic\n          information from ‘deSolve’ integration routines.  Of course,\n          this is pertinent only if the model skeleton is a\n          vectorfield.\n\n        • Bug in the display of ‘istate’ when ‘deSolve::ode’ errors has\n          been fixed.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b8._\b4:\n\n        • New ‘hitch’ function facilitates construction of ‘pomp.fun’\n          objects from R functions, C snippets, and links to external\n          libraries.\n\n        • Native routines needed to access ‘pomp.fun’ objects in C are\n          now registered for use by other packages.\n\n        • ‘coef(object) <- NULL’, where ‘object’ is of class ‘pomp’,\n          erases any parameters stored in ‘object’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b8._\b3:\n\n        • The ‘euler.sir’, ‘gillespie.sir’, ‘blowflies’, ‘ricker’,\n          ‘bbs’, ‘dacca’, and ‘rw2’ examples are all now implemented\n          using C snippets.\n\n        • A new ‘pomp_defines.h’ header is provided for developers of\n          packages that depend on ‘pomp’.\n\n        • Internally, ‘rprocess’ is no longer stored as an R function.\n          The use of plugins is now required for the implementation of\n          the ‘rprocess’ component.  Currently, there are five plugins\n          available: ‘onestep.sim’, ‘discrete.time.sim’, ‘euler.sim’,\n          ‘gillespie.sim’, and ‘gillespie.hl.sim’.\n\n        • The new ‘hitch’ function automates the building and linking\n          of C snippets and R functions into ‘pomp.fun’s.\n\n        • The handling of ‘dprocess’ has changed.  The ‘onestep.dens’\n          plugin is now deprecated and will soon be removed.\n          ‘dprocess’ is now specified directly using either a C snippet\n          or an R function, in much the same way that, for example,\n          ‘dmeasure’ is specified.\n\n        • The old ‘forward’ and ‘inverse’ options for the ‘dir’\n          argument of ‘partrans’ have been dispensed with.  The much\n          more descriptive options ‘toEstimationScale’ and\n          ‘fromEstimationScale’ remain.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b8._\b2:\n\n        • The C snippet compiling facilities have been thoroughly\n          reworked.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b8._\b1:\n\n        • ‘onestep.dens’ can now take a ‘Csnippet’ specification of the\n          process-model transition density.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b7._\b4:\n\n        • All inference functions can now take a list in the ‘start’ or\n          ‘params’ arguments.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b7._\b3:\n\n        • When altering parameters in a call to ‘probe’ on a\n          ‘probed.pomp’ object, the new parameters were ignored.  This\n          bug has been fixed.\n\n        • ‘mif2’, ‘pfilter’, ‘probe’, ‘probe.match’, and\n          ‘probe.match.objfun’ can now gracefully handle a list in the\n          ‘start’ or ‘params’ arguments.\n\n        • New ‘spy’ method displays the C snippet file(s) associated\n          with a ‘pomp’ object.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b7._\b2:\n\n        • The long-deprecated ‘seed’ argument to ‘bsmc’ and ‘bsmc2’ has\n          been removed.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b7._\b1:\n\n        • More work to obviate warnings generated by T. Kalibera's\n          latest ‘rchk’ checks.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b6._\b4:\n\n        • Messages from the compiler resulting from attempts to compile\n          C snippets are now suppressed on all platforms except in case\n          of failure.  Setting ‘verbose=TRUE’ forces display of these\n          messages.\n\n        • Source codes have been revisited to obviate warnings\n          generated by T. Kalibera's latest ‘rchk’ checks.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b6._\b3:\n\n        • Fix a minor bugs in ‘spect’.\n\n        • Improve test coverage.\n\n        • ‘spect.match’ has been refactored, with small changes to the\n          interface.\n\n        • ‘pomp’ now handles specification of workhorse functions\n          (i.e., ‘rprocess’, ‘dprocess’, ‘rmeasure’, ‘dmeasure’,\n          ‘initializer’, ‘skeleton’, ‘rprior’, ‘dprior’,\n          ‘fromEstimationScale’, ‘toEstimationScale’) as ‘NULL’ more\n          consistently.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b6._\b2:\n\n        • Fix bug in systematic resampler when ‘np != nw’.\n\n        • Fix bug in ‘conv.rec’ when only one parameter is requested.\n\n        • Correct and improve documentation for ‘conv.rec’.\n\n        • ‘coef<-’ can now take a list of parameters: it simply applies\n          ‘unlist’ to turn the list into a numeric vector.\n\n        • Simplify ‘conv.rec’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b6._\b1:\n\n        • In ‘pfilter’, ‘Np’ is now a required argument unless ‘params’\n          is specified as a matrix of particles.  Thanks to Carles\n          Breto for catching the unintended behavior.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b5._\b4:\n\n        • The bug reported in issue #57 has been fixed.\n\n        • A bug arising when building pomp objects with Csnippets in\n          certain Windows configurations has been fixed.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b5._\b3:\n\n        • Issue #56, in which covariate names are discarded when\n          coercing a pomp object to a data frame, has been fixed.\n          Thanks to Eamon O'Dea for reporting this bug.\n\n        • More informative error messages are given when ‘bake’ or\n          ‘freeze’ return ‘NULL’.  In such a case, these functions now\n          generate a warning and return a character-string message,\n          with attributes.\n\n        • Improve documentation of ‘traj.match’, in response to Issue\n          #57.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b5._\b2:\n\n        • A new facility, ‘gillespie.hl.sim’, allows implementation of\n          Gillespie's algorithm for exact stochastic simulation of\n          continuous-time Markov processes via a streamlined C snippet\n          interface.\n\n        • The old facility for Gillespie simulations, ‘gillespie.sim’,\n          now accepts C snippets for faster calculation of event rates.\n\n        • The old ‘skeleton.type’ and ‘skelmap.delta.t’ arguments of\n          the ‘pomp’ constructor, which have generated error messages\n          since version 1.9.2, have been done away with completely.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b5._\b1:\n\n        • Eamon O'Dea identified a bug (Issue #54) occurring when\n          ‘pomp’ is called with a single-row data frame.  This has been\n          fixed using his contributed patch.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b4._\b2:\n\n        • A new ‘dmultinom’ function is provided in ‘pomp.h’.  This\n          provides the probability distribution function for the\n          multinomial distribution.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b4._\b1:\n\n        • Improved tests.\n\n        • Fixed bugs emerging in R-devel due to refactoring of\n          underlying R source code.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b3._\b4:\n\n        • Eamon O'Dea pointed out that the bug in ‘gillespie.sim’,\n          addressed by version 1.12.3, was not completely fixed.  This\n          problem has now been resolved.  In addition, covariates are\n          now guaranteed to be evaluated at least once per observation\n          interval.\n\n        • The new argument ‘hmax’ to ‘gillespie.sim’ allows the user to\n          specify the maximum step size that will be taken before\n          covariates are evaluated.\n\n        • The K-leap method has been removed.  Its accuracy is low on\n          test problems and it is difficult to make it compatible with\n          the pomp paradigm.  In particular, it does not readily\n          accomodate time-varying covariates in a sensible way, nor\n          does it lend itself to simulations at pre-specified times.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b3._\b3:\n\n        • ‘bspline.basis’ and ‘periodic.bspline.basis’ now take an\n          optional non-negative integer argument ‘deriv’.  When ‘deriv\n          > 0’, the order-‘deriv’ derivative of each basis function is\n          returned.\n\n        • A new function, ‘periodic_bspline_basis_eval_deriv’, has been\n          added to the C API.  This function gives access, at the C\n          level, to evaluation of the derivatives of periodic\n          B-splines.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b3._\b2:\n\n        • Upgrade license to GPL version 3.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b3._\b1:\n\n        • Fix buffer-flow problem identified by ‘valgrind’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b2._\b3:\n\n        • Fix bug found by Eamon O'Dea in ‘gillespie.sim’.\n\n        • Fix bug in ‘onestep.sim’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b2._\b2:\n\n        • The Ricker example has a new parameter, c, which scales the\n          (unobserved) population size.  By default, c=1, so that the\n          behavior is as before.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b2._\b1:\n\n        • Improved error trapping.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b1._\b3:\n\n        • Some changes have been made to the use of random numbers in\n          some codes (the stochastic simulations in ‘gillespie.sim’ and\n          the resampling in the particle-filtering codes).  These\n          changes will mean that calculations performed before will not\n          be reproducible in perfect detail, but will be statistically\n          equivalent.\n\n        • Minor changes in C codes to obviate warnings generated by T.\n          Kalibera's ‘rchk’ checks.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b1._\b2:\n\n        • The rare and fascinating “Bug of St. Patrick” has been fixed.\n          Thanks to Carles Breto for finding the bug and helping to\n          isolate it.\n\n        • More informative error messages are generated when ‘dmeasure’\n          returns a non-finite likelihood in any of the particle\n          filtering codes.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b1._\b1:\n\n        • Some streamlining of codes.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b0._\b6:\n\n        • Callable routines are now registered.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b0._\b5:\n\n        • More verbosity is provided with ‘verbose=TRUE’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b0._\b4:\n\n        • The functions ‘bake’, ‘stew’, and ‘freeze’ now preserve\n          information about the system time used in computation as an\n          attribute of the returned object.  In addition, these\n          functions store information about the RNG settings.\n\n        • Some documentation improvements, courtesy of Sebastian Funk.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b0._\b3:\n\n        • Documentation improvements.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b0._\b2:\n\n        • More verbosity in building of Csnippets.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1_\b0._\b1:\n\n        • Better handling of ‘pomp’'s ‘times’ argument.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b9._\b3:\n\n        • New ‘logLik’ method for ‘pmcmcList’ objects.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b9._\b2:\n\n        • The deprecated options to supply a matrix or numeric vector\n          as the ‘data’ argument to ‘pomp’ have been removed and doing\n          so now generates an error.  The first argument to ‘pomp’,\n          ‘data’, must now be provided either as a data frame or as an\n          object of class ‘pomp’.  See ‘?pomp’ for details.\n\n        • The deprecated ‘skeleton.type’ and ‘skelmap.delta.t’\n          arguments to ‘pomp’ have been removed.  Using these arguments\n          will now generate an error message.  The correct method of\n          specifying the deterministic skeleton is now explained in the\n          help pages (‘?pomp’).\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b9._\b1:\n\n        • Source code fixes to eliminate warnings during compilation.\n\n        • Improved test suite.\n\n        • Minor documentation correction.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b8._\b1_\b1:\n\n        • During particle filtering, when non-finite ‘dmeasure’ values\n          are generated, an error is generated and the offending\n          parameters, states, data, and time are reported.  In methods\n          that use parameter transformations (‘transform=TRUE’), the\n          reported parameters were on the transformed (estimation)\n          scale, which can be confusing.  The error message now gives\n          the parameters on the natural (model) scale.\n\n        • Modified ‘src/ssa.c’ to fix UBSAN errors.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b8._\b1_\b0:\n\n        • C codes have been modified to take advantage of changes to\n          the R API (R SVN REVISION 71180).\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b8._\b9:\n\n        • A bug in ‘mif2’ arising when filtering fails in the final\n          timestep has been fixed.  In this case, when all particles\n          are deemed inconsistent with the data, we use an unweighted\n          mean (with a warning) in place of the default weighted mean.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b7._\b7:\n\n        • The stochastic simulation algorithms underlying the Gillespie\n          and K-leap methods (‘gillespie.sim’, ‘kleap.sim’) have been\n          refactored in C.  In addition, errors due to accumulation of\n          round-off error have been repaired.  The result will be more\n          accurate, but somewhat slower when there are a very large\n          number of reactions.\n\n        • Further improvements to the test suite.  Code coverage is now\n          100%.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b7._\b6:\n\n        • In Sobol' sequence generation (‘sobolDesign’,\n          ‘profileDesign’), we now use the suggestion of Joe & Kuo\n          (2003) to choose a better sequence start point.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b7._\b5:\n\n        • The generation of Sobol' sequences (‘sobolDesign’,\n          ‘profileDesign’) is now performed using the ‘NLopt’ routines\n          written in C instead of the original TOMS 659 FORTRAN codes.\n          The copyright notices are located in the source code.\n\n        • Improved testing suite.\n\n        • Made ‘rw.sd’ even more robust via new ‘safecall’ class.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b7._\b4:\n\n        • Refactored ‘rw.sd’ for greater stability.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b7._\b3:\n\n        • Fixed a bug in ‘plot’ on ‘pomp’ objects with more than 10\n          variables to plot.\n\n        • Added the ‘shlib.args’ option to ‘pomp’, allowing arbitrary\n          options to be passed to the compiler when C snippets are\n          used.\n\n        • Modified the “dacca” example to use C snippets.\n\n        • Refactored ‘rw.sd’ for greater stability.\n\n        • Made Sobol' codes more robust.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b7._\b2:\n\n        • Modified the demos to use best practices.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b7._\b1:\n\n        • Improved the test suite.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b6._\b7:\n\n        • Improve the test suite and error messages.\n\n        • Replace the automatic “verbose” setting during compilation\n          under Windows.  This was dropped in version 1.6.4.3, when it\n          no longer appeared to be necessary.  Apparently, it is, at\n          least under some Windows OS/R combinations.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b6._\b6:\n\n        • Fix ‘probe’ bug introduced in version 1.6.5.9.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b6._\b5:\n\n        • Several obscure bug-fixes.\n\n        • Improvement of the test suite and of error messages.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b6._\b4:\n\n        • Remove the automatic “verbose” setting during compilation\n          under Windows.  This was introduced in version 0.63-6 as a\n          workaround.  It appears no longer to be necessary.\n\n        • Improve the ‘show’ method for ‘pomp’ objects.\n\n        • Change the ‘print’ method for ‘pomp’ objects.\n\n        • Improve messages for plugin errors.\n\n        • Some internal refactoring.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b6._\b3:\n\n        • Improve error messages for missing basic components.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b6._\b2:\n\n        • Fix typos in one of the help-page examples.\n\n        • Add some references.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b6._\b1:\n\n        • Major revisions to the package help pages and manual.  The\n          separate documentation on C snippets and process-model\n          plugins has been merged into the main ‘pomp’ help page, which\n          now has comprehensive instructions on building a ‘pomp’\n          object.\n\n        • Update to the package help page.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b5._\b1_\b0:\n\n        • The matrix and numeric vector options for the ‘data’ argument\n          to ‘pomp’ are now deprecated and will be removed in a future\n          release.  In calls to ‘pomp’, ‘data’ should be either a data\n          frame or a ‘pomp’-class object.\n\n        • Many more errors are now trapped and reported with more\n          informative messages.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b5._\b9:\n\n        • Redundant ‘bootstrap’ argument to ‘nlf’ has been removed.\n\n        • More improvements to the testing suite.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b5._\b8:\n\n        • Major improvements to error and warning handling.\n\n        • Fix bugs that might arise in rare circumstances in ‘simulate’\n          and ‘eulermultinom’ functions.\n\n        • More improvements to the testing suite.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b5._\b7:\n\n        • Many improvements to the test suite.\n\n        • Fixed a bug in ‘pompExample’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b5._\b6:\n\n        • Major overhaul of error handling system and error messages.\n\n        • There is a new plugin for ‘rprocess’ called ‘kleap.sim’.\n          This implements the so-called “K-leap method” of Cai & Xu\n          (2007).\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b5._\b5:\n\n        • Many improvements to the test suite.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b5._\b4:\n\n        • More improvements to the test suite.\n\n        • Fixed bugs found as a result of improved testing.\n\n        • In ‘mif2’, it is now required that ‘Nmif>0’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b5._\b3:\n\n        • More improvements to the test suite.\n\n        • Fixed bugs found as a result of improved testing.\n\n        • Fixed bug in specification of skeleton in pompExamples.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b5._\b2:\n\n        • Improved the test suite to obtain better code coverage.\n\n        • ‘pomp’ is no longer an S4 method.  Its new status as an\n          ordinary function abbreviates and consolidates the code and\n          simplifies the documentation.\n\n        • Some minor improvements to error messages.\n\n        • A bug restricting access in C code to ‘userdata’ has been\n          fixed.\n\n        • Fixed bug in ‘pompExample(...,show=TRUE)’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b5._\b1:\n\n        • New methods for the Ensemble Kalman Filter (‘enkf’) and\n          Ensemble Adjustment Kalman Filter (‘eakf’) have been added to\n          the package.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b4._\b9:\n\n        • A better interface for specifying a model's deterministic\n          skeleton is provided.  One specifies\n          ‘skeleton=map(f,delta.t)’ for a discrete-time skeleton (a\n          map) and ‘skeleton=vectorfield(f)’ for a continuous-time\n          skeleton (a vectorfield).  The old arguments ‘skeleton.type’\n          and ‘skelmap.delta.t’ are deprecated and will be removed in a\n          future release.\n\n        • The ‘pfilter’ help page has been improved.  Specifically, the\n          discussion of filtering failures is better.\n\n        • Miscellaneous improvements to the help pages.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b4._\b8:\n\n        • ‘mif2’ no longer computes filter means.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b4._\b7:\n\n        • The new argument ‘show’ of ‘pompExamples’ allows one to\n          display the example code instead of executing it.\n\n        • The minimum version of R supported is now 3.1.2.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b4._\b6:\n\n        • ‘init.state’ now has the optional argument ‘nsim’.  Using\n          this, one can request multiple initial state vectors per\n          parameter vector.\n\n        • ‘pfilter’ now uses less memory when it is asked to run at a\n          single point in parameter space.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b4._\b5:\n\n        • A bug associated with the ‘rw.sd’ argument to ‘mif2’ on\n          Windows platforms has been fixed.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b4._\b4:\n\n        • The ‘method=\"mif2\"’ option to ‘mif’ has been removed.  Use\n          ‘mif2’ instead.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b4._\b3:\n\n        • The ‘particles’ method (rarely if ever used), has been\n          removed to streamline the ‘mif’ codes.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b4._\b2:\n\n        • The ‘method=\"mif2\"’ option to ‘mif’ is now deprecated.  It\n          will be removed in a future release.  Use ‘mif2’ instead.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b4._\b1:\n\n        • Following the publication of the Journal of Statistical\n          Software announcement paper, the ‘CITATION’ has been modified\n          to include the appropriate citation.  Please use\n          ‘citation(\"pomp\")’ to learn about how to cite ‘pomp’\n          correctly.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b3._\b4:\n\n        • ‘conv.rec’ on the results of a ‘mif2’ computation now play\n          nicely with ‘reshape2::melt’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b3._\b3:\n\n        • It is now possible to direct ‘pomp’ to place ‘Csnippet’ codes\n          in a specified location.  This is accomplished via the new\n          ‘cdir’ and ‘cfile’ arguments to ‘pomp’.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b3._\b2:\n\n        • When several concurrent R processes attempt to simultaneously\n          compile ‘Csnipet’ code from copies of a ‘pomp’ object on the\n          same machine, a race condition exists.  This release fixes\n          this by ensuring that ‘Csnippet’ codes are written and\n          compiled in a process-specific directory.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b3._\b1:\n\n     This release removes several long-deprecated features.\n\n        • The ‘seed’ argument to ‘pfilter’ has been removed.  Use\n          ‘freeze’ to obtain similar functionality.\n\n        • The redundant ‘pars’ argument to ‘mif’ has been removed.\n          Names of parameters to be estimated are taken from the\n          nonzero entries of ‘rw.sd’.  Initial-value parameters are\n          designated using the ‘ivps’ argument.\n\n        • The old ‘parameter.transform’ and ‘parameter.inv.transform’\n          arguments to ‘pomp’ have been removed.  They were superseded\n          by the arguments ‘fromEstimationScale’ and\n          ‘toEstimationScale’ in version 0.65-1.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b2._\b2:\n\n        • Some internal changes to ‘mif2’ by C. Breto, in support of\n          panel methods under development.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b2._\b1:\n\n        • Bug fix: for POMPs with a scalar state variable, the\n          ‘filter.mean’, ‘pred.mean’, and ‘pred.var’ methods dropped\n          the singleton dimension of the respective arrays, in conflict\n          with the assumptions of certain ‘plot’ methods.  This\n          resolves issue #3.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1._\b4:\n\n        • Documentation improvements.  Specifically, the details of how\n          step-sizes are chosen in the ‘euler.sim’,\n          ‘discrete.time.sim’, and ‘onestep.sim’ plugins has been\n          spelled out explicitly.  Also, incompleteness in the\n          ‘sannbox’ documentation has been corrected.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1._\b3:\n\n        • Provide ‘filter.traj’ method for ‘pmcmcList’ objects.\n\n_\bC_\bh_\ba_\bn_\bg_\be_\bs _\bi_\bn '_\bp_\bo_\bm_\bp' _\bv_\be_\br_\bs_\bi_\bo_\bn _\b1._\b1._\b2:\n\n        • Fixed a bug in ‘mif’ and ‘mif2’ when\n          ‘cooling.type=\"hyperbolic\"’ and ‘cooling.fraction.50=1’.\n\n"
  },
  {
    "path": "inst/NEWS.Rd",
    "content": "\\name{NEWS}\n\\title{News for package `pomp'}\n\\section{Changes in \\pkg{pomp} version 6.3.1}{\n  \\itemize{\n    \\item \\code{coef} can now extract parameters by name from a \\sQuote{listie}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 6.2.1}{\n  \\itemize{\n    \\item The built-in examples that use simulated data add a \\code{seed} argument to allow changing the simulated data.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 6.1.1}{\n  \\itemize{\n    \\item The basic Kalman filter (\\code{kalmanFilter}) has been refactored, with a roughly 3-fold speed up.\n    \\item Some internal changes have been made in anticipation of changes to the C API for R.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 6.0.5}{\n  \\itemize{\n    \\item It is now possible to specify more than one lag in the \\code{ivp} function, which is evaluated only when the \\code{mif2} perturbations are specified.\n    See \\code{?mif2}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 6.0.4}{\n  \\itemize{\n    \\item The new function \\code{append_data} appends a data frame to an existing CSV file (creating the file if it does not exist).\n    This facilitates keeping a database of parameter-space explorations.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 6.0.3}{\n  \\itemize{\n    \\item The new function \\code{eeulermultinom} gives the expectation of an Euler-multinomial random variable.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 6.0.2}{\n  \\itemize{\n    \\item The \\code{save.states} option to \\code{pfilter} has changed.\n    See \\code{?pfilter} and \\code{?saved_states} for details.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 6.0.1}{\n  \\itemize{\n    \\item In calls to \\pkg{pomp} elementary and inference algorithms, it is now necessary to pass all arguments by name.\n    This has always been good practice, but from this release, calls that rely on the position of arguments will typically generate errors.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 6.0.0}{\n  \\itemize{\n    \\item From version 5.8.4, the manner in which extra model elements (\\code{userdata}) are supplied has changed.\n    As of that version, use of the old method generated a warning.\n    As of this version, an error will be generated.\n    To supply additional elements (i.e., beyond parameters, latent-state variables, observations, and covariates) to the basic model components, provide them as a list via the \\code{userdata} argument.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.11.1}{\n  \\itemize{\n    \\item A new addition to the C API allows one to easily compute the expectation of the Euler-multinomial.\n    The function is \\code{eeulermultinom}.\n    \\item The help-page discussion of accumulator variables has been expanded and clarified.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.10.1}{\n  \\itemize{\n    \\item An improper typecast in the C snippet system, which was resolvable by many compilers but threw an error under recent versions of \\pkg{clang} on MacOS, has been repaired.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.9.1}{\n  \\itemize{\n    \\item The rprocess plugin \\code{onestep} now always takes exactly one step to get from one observation time to the next, even when the interval between them is zero.\n    That is, if \\code{P} is a \\sQuote{pomp} object with an rprocess built using \\code{rprocess=onestep(f)}, \\code{t0=timezero(P)}, and \\code{t=time(P)}, then \\code{f} will be called exactly once for the interval (\\code{t0},\\code{t[1]}) and once for each of the intervals (\\code{t[i-1]},\\code{t[i]}), \\code{i=2,...,length(t)}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.8.4}{\n  \\itemize{\n    \\item To add additional elements for use by the basic model components (i.e., \\dQuote{userdata}), the \\code{userdata} argument should now be used.\n    The old behavior will still work, but will generate a warning.\n    In a future release, this will become an error.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.8.3}{\n  \\itemize{\n    \\item Internally, \\pkg{pomp} codes no longer include \\file{Rinternal.h}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.8.2}{\n  \\itemize{\n    \\item A bug in covariate-table extrapolation for the case \\code{order=\"constant\"} has been fixed.\n    \\item A new experimental function \\code{repair_lookup_table} is provided to help eliminate unnecessary warnings about extrapolation.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.8.1}{\n  \\itemize{\n    \\item Functions with names that include dots (\\code{.}), which have been defunct since version 4.7, have been expunged.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.7.1}{\n  \\itemize{\n    \\item The \\code{err()} and \\code{warn()} C-level macros have been redefined to forestall problems that would arise when these macros are included in C++ code under forthcoming versions of \\R.\n    \\item More changes in C codes to forestall issues detected by \\pkg{rchk}.\n    \\item Minor corrections to documentation.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.6.1}{\n  \\itemize{\n    \\item Minor corrections to documentation.\n    \\item Changes in some C codes to avoid issues detected by \\pkg{rchk}.\n    \\item Fixed bug in \\code{wquant} introduced by changes in \\code{pbeta} with \\R version 4.3.3.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.5.2}{\n  \\itemize{\n    \\item Minor corrections to documentation.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.5.1}{\n  \\itemize{\n    \\item C-level functions \\code{set_pomp_userdata} and \\code{unset_pomp_userdata} are no longer exported.\n    \\item \\code{bspline_eval} is no longer exported.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.4.4}{\n  \\itemize{\n    \\item C-level functions \\code{set_pomp_userdata} and \\code{unset_pomp_userdata} have been temporarily restored.\n    The latter generates a warning.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.4.3}{\n  \\itemize{\n    \\item There is now access to ordinary B-spline basis functions (and their derivatives) at the C snippet level.\n    It will still almost always be preferable to construct a spline basis once and pass it to \\pkg{pomp} functions as part of a \\code{covariate_table}, but this functionality may occasionally be useful.\n    \\item \\code{bspline_eval} is now deprecated as part of the \\pkg{pomp} C API.\n    \\item The formatting of some printed messages has been modified to forestall warnings in the latest R-devel.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.4.2}{\n  \\itemize{\n    \\item Stateful objective functions (class \\sQuote{objfun}) now behave as if they are \\sQuote{pomp} objects.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.4.1}{\n  \\itemize{\n    \\item C-level functions \\code{set_pomp_userdata} and \\code{unset_pomp_userdata} are no longer exported.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.3.1}{\n  \\itemize{\n    \\item \\code{stew} now returns timing information by default.\n    \\item The spurious warnings associated with NULL \\code{userdata} have been eliminated.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.2.5}{\n  \\itemize{\n    \\item The new option \\code{on_load} allows one to specify a C snippet that will be executed at the time the C snippet library is loaded.\n    \\item Internally, the \\code{userdata} are made available via calls to \\code{pompLoad} rather than within each call to a \\pkg{pomp} workhorse.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.2.4}{\n  \\itemize{\n    \\item The data frames returned by \\code{cond_logLik} and \\code{eff_sample_size} when \\code{format=\"data.frame\"} have been improved.\n    In particular, they contain (as variable \\code{time}) the times (rather than the index of the time vector as before).\n    \\item Changes to the report generated by \\code{spy}.\n    \\item Some documentation improvements.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.2.3}{\n  \\itemize{\n    \\item The manual pages have been reorganized, with improved cross-linking.\n    \\item A bug in \\code{filter_traj} etc. arising when not all state variables have names was fixed.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.2.2}{\n  \\itemize{\n    \\item This version adds the new basic component \\code{dinit} for evaluating the probability density function of the initial-state distribution.\n    There is a corresponding workhorse function, \\code{dinit()}.\n    \\item The constructor \\code{pomp} now takes the optional argument \\code{nstatevars}, which can be used to increase the dimension of the latent state-vectors created by \\code{rinit}.\n    By default, \\code{nstatevars = length(statenames)}, and \\code{nstatevars} can only be used to \\emph{increase}, not to decrease, the dimension of the latent state process.\n    Moreover, \\code{nstatevars} has no effect if the \\code{rinit} basic component is furnished as an \\R function.\n    \\item Name checking on internally-created vectors and arrays is less strict than previously.\n    In particular, it is possible to have variables without names (i.e., \\code{\"\"}).\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.2.1}{\n  \\itemize{\n    \\item \\code{reulermultinom} now returns \\code{NA} rather than \\code{NaN}, in keeping with the behavior of \\code{rbinom}.\n    Thanks to John Drake for calling attention to this issue.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.1.1}{\n  \\itemize{\n    \\item A bug in \\code{stew} resulting in namespace conflicts has been repaired.\n    \\item We no longer import directly from \\pkg{tidyverse} functions.\n    This reduces the list of packages upon which \\pkg{pomp} depends from 20 to 5.\n    This does introduce a dependency on the \\pkg{data.table} package.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.0.1}{\n  \\itemize{\n    \\item When the archive directory does not exist, \\code{bake} and \\code{stew} now create it.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 5.0.0}{\n  \\itemize{\n    \\item We no longer import from \\pkg{plyr}.\n    \\item The \\code{dimnames} attributes of various arrays that appear in \\pkg{pomp}, including arrays of observables, state variables, parameters, covariates, and so on, have been made uniform.\n    In particular, when a dimension of an array corresponds to variables with different names, this dimension is itself named \\dQuote{name}.\n    Previously, its name was sometimes \\dQuote{variable} and sometimes \\dQuote{parameter}.\n    This change is meant to streamline interaction with the \\pkg{tidyverse}.\n    \\item Some minor bugfixes.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.7.0}{\n  \\itemize{\n    \\item Functions with names.that.contain.dots that have been deprecated since version 4.5.1 are now defunct.\n    Attempts to use such functions will generate an error with a message indicating the replacement function.\n    \\item \\code{plot} now removes \\code{NA}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.6.4}{\n  \\itemize{\n    \\item Better handling of \\sQuote{listie}s (lists of \\sQuote{pomp} objects).\n    \\item New \\code{concat} function to turn lists of \\sQuote{pomp} objects into \\sQuote{listies}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.6.3}{\n  \\itemize{\n    \\item Bug fix in \\code{filter_traj} applied to \\sQuote{pfilterList} and \\sQuote{pmcmcList} objects.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.6.2}{\n  \\itemize{\n    \\item The \\code{states} and \\code{obs} methods take a new optional argument, \\code{format}.\n    Setting \\code{format=\"data.frame\"} causes the method to return the states or data in a convenient data-frame format.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.6.1}{\n  \\itemize{\n    \\item When \\code{melt} is applied to a list, the identifier variable is now \\dQuote{\\code{.Lx}}, where \\code{x} denotes the level.\n    This applies when \\code{as.data.frame} is used to coerce a list of \\sQuote{pomp} objects, and when \\code{saved_states} is used to extract the particles from a list of \\sQuote{pfilterd_pomp} objects.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.5.3}{\n  \\itemize{\n    \\item \\code{logmeanexp} can now compute the effective sample size, which can be useful in determining the reliability of its estimate.\n    To do so, set \\code{ess=TRUE} in a call to \\code{logmeanexp}.\n    \\item \\code{logmeanexp} now returns a fully-named vector when either \\code{se=TRUE} or \\code{ess=TRUE}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.5.2}{\n  \\itemize{\n    \\item A new \\code{format} argument has been added to the extractor functions \\code{cond_logLik}, \\code{eff_sample_size}, \\code{filter_mean}, \\code{filter_traj}, \\code{forecast}, \\code{pred_mean}, \\code{pred_var}, and \\code{saved_states}.\n    This allows the user to extract the relevant elements in data-frame format if desired.\n    \\item \\pkg{pomp} no longer depends on the superseded package \\pkg{reshape2}.\n    The \\code{melt} function for converting arrays and nested lists into data frames is accordingly no longer re-exported from \\pkg{reshape2}.\n    It has been replaced by a stricter version of \\code{melt}.\n\n    \\item The \\pkg{magrittr} pipe \\code{\\%>\\%} is no longer re-exported by \\pkg{pomp}: use the native \\R pipe \\code{|>} instead.\n    \\item The package now requires \\R version 4.1 at least.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.5.1}{\n  \\itemize{\n    \\item All \\pkg{pomp} functions with names.that.contain.dots have been deprecated in favor of functions in \\sQuote{snake_case}.\n    This is to avoid anticipated problems with CRAN checks, which (falsely) assume that certain functions with dotted.names are S3 methods.\n    From this point, no exported \\pkg{pomp} function has such a name.\n    \\item The \\code{dimnames} attributes for some of the arrays computed in \\code{pfilter} and \\code{pmcmc} computations have changed.\n    In particular, whereas in previous versions, the \\code{time} dimension was given names that were character strings composed of decimal representations of the time (difficult to work with and prone to roundoff error), the \\code{time} dimension now is not given names.\n    \\item A bug that resulted in \\code{gompertz} giving different simulations on Windows machines has been fixed.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.4.3}{\n  \\itemize{\n    \\item A bug in trajectory computation for maps (discrete-time dynamical systems) has been fixed.\n    Thanks to Felicia Magpantay for noticing it and tracking it down.\n    \\item Minor documentation improvements.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.4.2}{\n  \\itemize{\n    \\item The weighted quantile function \\code{wquant} now uses the Harrell-Davis estimator instead of the type-7 estimator used previously.\n    This eliminates bugs associated with non-integer weights.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.4.1}{\n  \\itemize{\n    \\item It is now possible to retrieve the weighted particles computed in the course of a \\code{pfilter} computation.\n    To accomplish this, set \\code{save.states=\"weighted\"} in the call to \\code{pfilter} and retrieve the particles and their weights using \\code{saved.states}.\n    Previously, one could obtain only the unweighted particles.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.4.0}{\n  \\itemize{\n    \\item Some documentation improvements.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.3.4}{\n  \\itemize{\n    \\item The new function \\code{wquant} computes weighted quantiles.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.3.3}{\n  \\itemize{\n    \\item The precise order in which the \\code{pmcmc} function computes prior and likelihood of furnished and proposed parameters has changed slightly.\n    This prevents proposals that are incompatible with the prior from being passed to \\code{pfilter} and forestalls an associated class of errors.\n    A consequence of this change, \\code{pmcmc} computations using the new version will differ very slightly from previous computations, even with the RNG seed fixed at its previous values.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.3.2}{\n  \\itemize{\n    \\item There is now a \\proglang{C} interface to the \\code{bspline_eval} function.\n    See the \\href{https://kingaa.github.io/pomp/vignettes/C_API.html}{\\pkg{pomp} \\proglang{C} API documentation} for details.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.3.1}{\n  \\itemize{\n    \\item The \\code{bspline.basis} function now takes the optional argument \\code{rg} which allows one to specify the range over which the basis will be constructed.\n    By default, this is \\code{range(x)}, which agrees with the behavior in earlier versions.\n    \\item Documentation improvements.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.2.2}{\n  \\itemize{\n    \\item The archiving functions \\code{bake} and \\code{stew} now use a slightly less exacting comparison of the expression, \\code{expr}, they are furnished.\n    \\strong{NB:} Running \\code{bake} or \\code{stew} with archives created by earlier versions may result in recomputation.\n    \\item The \\code{time} method has been extended to \\code{pompList} and related objects.\n    \\item All workhorse functions except \\code{partrans} have new default arguments.\n    \\item Some documentation improvements.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.2.1}{\n  \\itemize{\n    \\item The archiving functions \\code{bake} and \\code{stew} now take the argument \\code{dir}, which is the directory holding the archive files.\n    By default, this is the current working directory or the value of the global option \\code{pomp.archive.dir}.\n    \\item A new global option, \\code{pomp_archive_dir}, can be used to specify the locations of archive files used by \\code{bake} and \\code{stew}.\n    \\item Documentation repair of issue flagged by Kurt Hornik (9 June 2022).\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.2.0}{\n  \\itemize{\n    \\item Minor changes, invisible to the user.\n    \\item Minor changes to the \\proglang{C} codes to keep up with R-devel.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.1.0}{\n  \\itemize{\n    \\item Minor changes to the \\proglang{C} codes to keep up with R-devel.\n    \\item Minor changes in the implementation of \\code{bake} and \\code{stew}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.0.11}{\n  \\itemize{\n    \\item Change in the names of the variables returned by \\code{as.data.frame} applied to a \\sQuote{pfilterd.pomp} object.\n    \\item Fixed bug found by Jesse Wheeler and Ed Ionides, to do with `simulate()` with `include.data=TRUE`.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.0.10}{\n  \\itemize{\n    \\item It is now possible to plot lists of \\sQuote{pomp} and \\sQuote{pomp}-derived objects using a single call to \\code{plot}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.0.9}{\n  \\itemize{\n    \\item The \\code{rbetabinom} and \\code{dbetabinom} functions, long present as part of the \\href{https://kingaa.github.io/pomp/vignettes/C_API.html}{\\proglang{C} API}, are now available as \\R functions.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.0.8}{\n  \\itemize{\n    \\item The SIR examples \\code{sir()} and \\code{sir2()} now use a negative binomial measurement model.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.0.7}{\n  \\itemize{\n    \\item \\code{parmat} can now take a data frame of parameters and convert it into a matrix suitable for furnishing to the \\code{params} argument of any \\pkg{pomp} function.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.0.6}{\n  \\itemize{\n    \\item It is now possible to change the parameters in an \\sQuote{objfun} (objective function) object using \\code{coef(object)<-value}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.0.5}{\n  \\itemize{\n    \\item \\code{parmat} now takes an optional argument, \\code{names}, which allows the user to name the parameter sets.\n    \\item Independent realizations of the stochastic processes modeled in \\pkg{pomp} are now distinguished by different values of \\code{.id}.\n    This behavior is now uniform throughout.\n    \\item \\code{bake} and \\code{stew} now send messages instead of warnings when they recompute an archive due to a change in code or dependencies.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.0.4}{\n  \\itemize{\n    \\item The ensemble adjusted Kalman filter (\\code{eakf}) has been refactored.\n    It now makes use of the \\code{emeasure} and \\code{vmeasure} basic components to compute an approximation of the linear relationship between the latent state and the observed variables.\n    \\item The \\code{forecast} method now works for \\code{pfiterd_pomp} objects (i.e., results of \\code{pfilter}, \\code{pmcmc}, or \\code{mif2} computations).\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.0.3}{\n  \\itemize{\n    \\item Two new basic model components have been introduced.\n    These are:\n    \\describe{\n      \\item{emeasure,}{which computes the expectation of the observable variables conditional on the latent state;}\n      \\item{vmeasure,}{which computes the covariance matrix of the observables given the latent state.}\n    }\n    These are used by the newly refactored ensemble Kalman filter, \\code{enkf}.\n    \\item The basic (linear, Gaussian) Kalman filter is now available as \\code{kalmanFilter}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.0.2}{\n  \\itemize{\n    \\item Computation of Monte Carlo-adjusted profile likelihood is now facilitated by the new \\code{mcap} function.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.0.1}{\n  \\itemize{\n    \\item The default return-value format for \\code{trajectory} now matches that of \\code{simulate}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 4.0.0}{\n  Version 4 contains a few changes that are not backward compatible.\n  These are all to do with the elementary function \\code{trajectory}, which computes trajectories of the deterministic dynamical skeleton.\n  See below for details.\n  \\itemize{\n    \\item The behavior of \\code{trajectory} now fully conforms to the behavior of other \\pkg{pomp} elementary functions.\n    In particular, one can now add, remove, or modify basic model components in a call to \\code{trajectory} just as one can with \\code{simulate}, \\code{pfilter}, \\code{probe}, etc.\n    Before version 4, additional arguments to \\code{trajectory} (i.e., those passed via \\code{...}) were passed on to the ODE integrator in the case of continuous-time deterministic skeletons (i.e., vectorfields) and ignored in the case of discrete-time skeletons (i.e., maps).\n    As of version 4, in order to adjust ODE integrator settings it is necessary to use the \\code{ode_control} argument of \\code{trajectory}.\n    This behavior matches that of \\code{traj_objfun}.\n    \\item It is now possible to create a \\sQuote{pomp} object from scratch using \\code{trajectory}, together with a specification of the rinit and skeleton components.\n    Prior to version 4, in order to do so, it was necessary to first create a dummy data set, then call \\code{pomp}, and then pass the resulting \\sQuote{pomp} object to \\code{trajectory}.\n    This can now be achieved in one call.\n    \\item The user now has the option, in a call to \\code{trajectory}, to have the results returned as one or \\sQuote{pomp} objects.\n    In this regard, its behavior matches that of \\code{simulate}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 3.5.6}{\n  \\itemize{\n    \\item The \\code{states} and \\code{obs} methods now work for lists of \\sQuote{pomp} objects (\\sQuote{listies}).\n  }\n}\n\\section{Changes in \\pkg{pomp} version 3.5.5}{\n  \\itemize{\n    \\item The workhorse function \\code{flow} now has default arguments.\n    \\item The stateful objective function created by \\code{traj_objfun} has been refactored so that it is independent of \\code{trajectory}.\n    This change is invisible to the user, but lays the groundwork for future changes in \\code{trajectory}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 3.5.4}{\n  \\itemize{\n    \\item Stateful objective functions created by \\code{traj_objfun}, \\code{nlf_objfun}, \\code{probe_objfun}, and \\code{spect_objfun} now have default arguments.\n    In particular, the default is argument is a zero-length numeric vector.\n    Calling such a function with no arguments is valid if and only if the objective function was created with no variables to estimate (empty \\code{est}).\n  }\n}\n\\section{Changes in \\pkg{pomp} version 3.5.3}{\n  \\itemize{\n    \\item Fixed bug in \\code{rprior} arising with integer-valued return vectors.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 3.5.2}{\n  \\itemize{\n    \\item Major improvements to the package manual, including richer cross-linking and better organization.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 3.5.1}{\n  \\itemize{\n    \\item When \\code{simulate} is called with \\code{format=\"data.frame\"} and \\code{include.data=TRUE}, the interpolated covariates are now included in the data frame that is returned.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 3.4.6}{\n  \\itemize{\n    \\item \\code{bake} takes a new option, \\code{timing}, that controls whether information on the timing is returned or merely stored.\n    By default, this is set to \\code{TRUE}, though this default behavior may change in future.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 3.4.5}{\n  \\itemize{\n    \\item When they encounter an archive produced by an older version, \\code{bake} and \\code{stew} now update the archive in the new format.\n    Recomputation should never be triggered in this case:\n    If recomputation is desired, delete the archive file.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 3.4.4}{\n  \\itemize{\n    \\item \\code{bake} and \\code{stew} now archive a digest of the code in \\code{expr} and on subsequent calls check to see if the archived version matches the current version.\n    Thus, changes to the code automatically trigger recomputation.\n    \\item \\code{bake} and \\code{stew} take the new argument \\code{dependson}.\n    Using this argument, the user can specify objects upon which the computation depends.\n    These should be passed as unquoted variables;\n    if there are multiple dependencies, they can be passed using \\code{c} or \\code{list}.\n    Digests of these objects will be archived and checked against current values on subsequent calls.\n    Thus, changing any dependency will automatically trigger recomputation.\n    \\item \\code{bake} now archives the information pertinent to the \\code{bake} call;\n    this information is no longer returned along with the result of the computation (unless \\code{info=TRUE}).\n    Similarly, \\code{stew} stores a list, \\dQuote{.ingredients}, in the file it creates.\n    In the \\code{stew} case, unlike all the other objects that are created by \\code{expr}, this list is \\emph{not} by default loaded into the calling environment (e.g., the user's workspace).\n    It will be loaded if the \\code{info} flag is set to \\code{TRUE}.\n    \\item \\code{freeze} no longer stores the details of the RNG seed and kind as an attribute of the returned object.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 3.4.2}{\n  \\itemize{\n    \\item Fix bug in \\code{bsmc2} arising when some particles have zero likelihood.\n    This is Issue #152.\n    Thanks to Hola-Kwame Adrakey for reporting it.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 3.4.1}{\n  \\itemize{\n    \\item It is now possible to call \\code{partrans} directly on an objective function, such as those created by \\code{traj_objfun}, \\code{nlf_objfun}, \\code{probe_objfun}, or \\code{spect_objfun}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 3.3.1}{\n  \\itemize{\n    \\item The package manual and help pages has been streamlined.\n    \\item The \\code{mif2} diagnostic plots have been made more flexible.\n    \\item Some deprecated functions have been removed.\n    These include \\code{cond.loglik}, \\code{sliceDesign}, \\code{runifDesign}, \\code{sobolDesign}, and \\code{profileDesign}, which have been replaced by \\code{code.logLik}, \\code{slice_design}, \\code{runif_design}, \\code{sobol_design}, and \\code{profile_design}, respectively.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 3.3.0}{\n  \\itemize{\n    \\item A bug in \\code{rgammawn} has been fixed.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 3.2.0}{\n  \\itemize{\n    \\item The \\pkg{pomp} \\proglang{C} API has been expanded a bit, to facilitate other packages' linking to the \\pkg{pomp} library.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 3.1.1}{\n  \\itemize{\n    \\item The help pages have been improved, with an description of the overall package structure and pages on basic model components, elementary algorithms, and estimation algorithms.\n    \\item A note to Windows users on avoiding certain \\proglang{C} snippet compilation errors has been added to the help pages.\n    \\item The behavior of \\code{profile_design} has changed.\n    Previously, the same random (or sub-random) sequence was used for all non-profile parameters.\n    Now, for each profile slice, a distinct set of points is generated.\n    \\item \\code{profileDesign}, \\code{sliceDesign}, \\code{runifDesign}, and \\code{sobolDesign} have been deprecated and will be removed in a future release.\n    They are replaced by \\code{profile_design}, \\code{slice_design}, \\code{runif_design}, and \\code{sobol_design}, respectively.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 3.0.3}{\n  \\itemize{\n    \\item A new \\code{saved.states} method allows one to extract the saved states from a particle filter computation.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 3.0.2}{\n  \\itemize{\n    \\item All instances of \\code{cond.loglik} have been changed to \\code{cond.logLik}, to remove a common source of typographical error.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 3.0.1}{\n  \\itemize{\n    \\item A new sequential importance sampling algorithm has been implemented as \\code{wpfilter}.\n    This is a generalization of the algorithm in \\code{pfilter} in that it tracks the weights of the particles and allows the user to customize the resampling scheme.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 3.0.0}{\n  \\itemize{\n    \\item In \\code{mif2}, the specification of particle numbers, \\code{Np}, has changed.\n    When \\code{Np} is supplied as a function, \\code{Np(0)} is the requested number of particles at the beginning of the time series.\n    The previous behavior was that \\code{Np(1)} specified the requested number of particles.\n    This behavior now matches that of the other particle filtering algorithms, \\code{pfilter}, \\code{bsmc2}, and \\code{pmcmc}.\n    \\item \\code{bsmc2} can now accept a variable number of particles, as do the other particle-filter based algorithms \\code{pfilter}, \\code{pmcmc}, and \\code{mif2}.\n    \\item The internal \\code{systematic_resample} function now allows the user to specify the number of samples desired.\n    Previously, these were always equal to the number of weights supplied.\n    \\item As promised from version 2.4.1, the \\code{tol} and \\code{max.fail} arguments have been removed completely from all particle-filtering algorithms, including \\code{pfilter}, \\code{pmcmc}, \\code{bsmc2}, and \\code{mif2}.\n    See the \\href{https://kingaa.github.io/pomp/blog.html}{\\pkg{pomp} news blog} (\\url{https://kingaa.github.io/pomp/blog.html}) for more information.\n    \\item The long-deprecated functions \\code{onestep.dens}, \\code{onestep.sim}, \\code{discrete.time.sim}, \\code{euler.sim}, \\code{gillespie.sim}, \\code{gillespie.hl.sim}, \\code{conv.rec}, and \\code{values}  have been removed.\n    These have been replaced as follows\n    \\tabular{ll}{\n      \\code{onestep.dens} \\tab direct specification of \\code{dprocess} component \\cr\n      \\code{onestep.sim} \\tab \\code{onestep} \\cr\n      \\code{discrete.time.sim} \\tab \\code{discrete_time} \\cr\n      \\code{euler.sim} \\tab \\code{euler} \\cr\n      \\code{gillespie.sim} \\tab \\code{gillespie} \\cr\n      \\code{gillespie.hl.sim} \\tab \\code{gillespie_hl} \\cr\n      \\code{conv.rec} \\tab \\code{traces} \\cr\n      \\code{values} \\tab \\code{as.data.frame} or \\code{as(x,\"data.frame\")} \\cr\n    }\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.8.0}{\n  \\itemize{\n    \\item Trap error from non-finite likelihoods in \\code{pmcmc}.\n    \\item New test of \\code{pmcmc} codes in \\file{tests/issue109.R}.\n    \\item Trap error from missing accumulator variables in \\code{trajectory}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.7.2}{\n  \\itemize{\n    \\item The Euler step size in \\code{sir} is now adjustable.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.7.1}{\n  \\itemize{\n    \\item As promised, the default value of \\code{tol} in the particle-filtering algorithms \\code{pfilter}, \\code{pmcmc}, \\code{mif2}, and \\code{bsmc2} has been changed to zero.\n    A warning continues to be issued if \\code{tol} is set to anything other than 0.\n    In a future release, the option to choose a nonzero tolerance will be removed entirely.\n    \\item In traces and diagnostic plotting methods, the \\code{nfail} variable (tracking numbers of filtering failures) has been dropped.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.6.0}{\n  \\itemize{\n    \\item Another documentation bug was fixed.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.5.0}{\n  \\itemize{\n    \\item A documentation bug, identified by K. Hornik, was fixed.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.4.1}{\n  \\itemize{\n    \\item In anticipation of forthcoming algorithmic changes, the \\code{tol} and \\code{max.fail} arguments of \\code{pfilter}, \\code{bsmc2}, \\code{pmcmc}, and \\code{mif2} are now deprecated.\n    A warning is issued if \\code{tol} is set to anything other than 0.\n    In a future release, these options will be removed entirely: the behavior will be similar to that obtained in the present release by setting \\code{tol=0}.\n    \\item A new example illustrating the \\code{accumvars} argument has been provided.\n    \\item Internal computations now use increased precision for means, variances, and certain calculations with likelihoods.\n    \\item A new help page, \\code{pomp_examples}, lists the various example datasets and pomp objects provided with the package.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.3.0}{\n  \\itemize{\n    \\item The source codes underlying specification of basic model components via \\R functions has been reworked to remove reliance on deep \\code{PROTECT} stacks.\n    Thanks to Thomas Kalibera for showing the way!\n    \\item A bug in the documentation for \\code{filter.traj}, pointed out by Pierre Jacob, has been fixed.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.2.2}{\n  \\itemize{\n    \\item The \\proglang{C} API for \\pkg{pomp} is no longer explained only in comments in the \\dQuote{pomp.h} header file.\n    It is now described and explained in the new \\href{https://kingaa.github.io/pomp/vignettes/C_API.html}{\\proglang{C} API vignette}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.2.1}{\n  \\itemize{\n    \\item The new \\code{pomp_cdir} global option allows one to set the directory holding \\proglang{C} snippet files globally.\n    \\item A bug caused by re-use of the \\code{cfile} argument has been fixed.\n    Re-use now triggers an error, with an informative message.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.2.0}{\n  \\itemize{\n    \\item Some documentation improvements.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.1.2}{\n  \\itemize{\n    \\item A bug in \\code{runifDesign} (and therefore \\code{profileDesign} when \\code{type=\"runif\"}) has been fixed.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.1.1}{\n  \\itemize{\n    \\item There are now \\code{plot} methods for objects of classes \\sQuote{probe_match_objfun} and \\sQuote{spect_match_objfun}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.1.0}{\n  \\itemize{\n    \\item Released to CRAN.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.0.14}{\n  \\itemize{\n    \\item The \\code{melt} function can now be applied to arbitrary \\sQuote{pomp} objects.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.0.13}{\n  \\itemize{\n    \\item A new function, \\code{runifDesign} allows construction of design matrices using samples from multivariate uniform distributions.\n    \\item The \\code{profileDesign} function takes a new argument, \\code{type}, with two options:\n    \\code{\"sobol\"}, the default, constructs the design using \\code{sobolDesign}, as before.\n    \\code{\"runif\"} uses the new \\code{runifDesign} function.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.0.12}{\n  \\itemize{\n    \\item A new example, comprising models and data for the 2014--2016 west African Ebola virus disease outbreak, is included.\n    See \\code{?ebola} for details.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.0.11}{\n  \\itemize{\n    \\item It is now possible to adjust the observation times and zero-time in the \\code{sir} and \\code{sir2} examples.\n    One can also change the default RNG seed used in generating the simulated data.\n    \\item The codes underlying the \\code{rprocess} workhorse have been streamlined to obviate an unnecessary copy operation.\n    As a result, the interface to the \\code{rprocess} workhorse has been changed.\n    \\item The interface to the new \\code{flow} workhorse has been changed to match.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.0.10}{\n  \\itemize{\n    \\item The new \\code{flow} workhorse allows integration/iteration of the deterministic skeleton at arbitrary times from an arbitrary initial condition.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.0.9}{\n  \\itemize{\n    \\item When \\code{coef} is applied to a \\sQuote{listie}, the result can be more usefully \\code{melt}ed.\n    \\item The probe-names returned by \\code{probe.acf} and \\code{probe.ccf} have changed.\n    \\item A bug, whereby the \\sQuote{coef} method from other packages was masked, has been fixed.\n    \\item Errors in the documentation have been corrected.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.0.8}{\n  \\itemize{\n    \\item There is a new \\code{as.data.frame} method for \\sQuote{listie}s.\n    \\item Some problems with the exposure of internal objects for package developers have been corrected.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.0.7}{\n  \\itemize{\n    \\item The \\pkg{magrittr} pipe operator, \\code{\\%>\\%}, is now re-exported.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.0.6}{\n  \\itemize{\n    \\item More examples have been included.\n    \\item Minor changes to error messages.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.0.5}{\n  \\itemize{\n    \\item The names of the \\sQuote{objfun} methods have been changed to \\code{probe_objfun}, \\code{spect_objfun}, \\code{traj_objfun}, and \\code{nlf_objfun}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.0.4}{\n  \\itemize{\n    \\item The package directory structure has been modified to include a new \\file{examples} directory, which holds the examples used in the documentation.\n    \\item The names of the \\sQuote{objfun} methods have been shortened.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.0.3}{\n  \\itemize{\n    \\item It is now permissible that the sequence of observation times (and sequences of covariate times) be merely non-decreasing sequences.\n    Previously, \\pkg{pomp} insisted on strictly increasing time sequences.\n    \\item The default cooling schedule (\\code{cooling.type}) in \\code{mif2} is now \\dQuote{geometric}, in contrast to \\dQuote{hyperbolic}, as before.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.0.2}{\n  \\itemize{\n    \\item \\pkg{pomp} now requires at least \\R version 3.5.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.0.1}{\n  \\itemize{\n    \\item The \\code{zeronames} argument has been renamed \\code{accumvars}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 2.0.0}{\n  \\itemize{\n    \\item In the course of ordinary work, one should never need to interact with the low-level \\code{pomp} constructor function now.\n    \\item The \\code{pompExample} function has been dropped.\n    The various examples are now included as regular functions that construct \\sQuote{pomp} objects.\n    \\item The \\code{bbs} example has been dropped.\n    \\item One can now modify basic model components at (almost) any stage in a pipeline of \\pkg{pomp} computations.\n    All the top-level inference functions, plus \\code{probe}, \\code{pfilter}, and \\code{simulate} now allow modification of basic model components.\n    \\item The \\code{rprocess} plugins \\code{onestep.sim}, \\code{discrete.time.sim}, \\code{euler.sim}, \\code{gillespie.sim}, and \\code{gillespie.hl.sim} have been renamed \\code{onestep}, \\code{discrete_time}, \\code{euler}, \\code{gillespie}, and \\code{gillespie_hl}, respectively.\n    The old usage is available but deprecated.\n    \\item One can now call \\code{simulate} on a model without reference to any data.\n    \\item The covariate table facility (\\code{covariate_table}) now supports piecewise constant interpolation.\n    \\item The syntax with which one includes covariates via \\code{covariate_table} has become more flexible.\n    Specifically, the arguments to \\code{covariate_table} are now evaluated sequentially, so that later ones can depend on earlier ones.\n    Once evaluated, the covariates are bound column-wise into a single data frame.\n    \\item The manner in which one writes \\R functions to specify basic model components has been totally changed.\n    Before, one wrote functions that took specific arguments such as 'x', 'params', and 'covars'.\n    Now, one writes such functions with any or all state variables, observables, covariates, and/or time as arguments.\n    \\item \\code{simulate} now returns more informative results when simulations from multiple parameter sets are simultaneously computed.\n    Specifically, if \\code{params} has column names, these are used to identify the resulting simulations.\n    Thus when \\code{format = \"pomps\"} (the default), the names of the resulting list will be constructed from the column names of \\code{params}.\n    Likewise, when \\code{format = \"arrays\"}, the resulting arrays will have informative column names;\n    When \\code{format = \"data.frame\"}, the identifier variable will make use of the column names.\n    \\item The basic particle filter, \\code{pfilter}, has a simpler mode of operation:\n    \\code{params} should be a single parameter set only.\n    That is, it is no longer possible to pass a matrix of parameters to \\code{pfilter}.\n    \\item The Liu-West algorithm, \\code{bsmc2}, has a simpler mode of operation:\n    \\code{params} should be a single parameter set only:\n    the SMC particles are drawn from \\code{rprior}.\n    \\item The \\code{as.data.frame}, \\code{states}, and \\code{obs} options for \\code{simulate} have been done away with.\n    One now chooses the format of the returned simulations via the \\code{format} argument.\n    When one simulates at multiple parameter sets, list names, array \\code{dimnames}, or identifying variables in the output data frame help to correlate simulations with parameter sets.\n    \\item The \\code{as.data.frame} argument to \\code{trajectory} has been removed in favor of a new \\code{format} argument that allows one to choose between receiving the results in the form of an \\code{\"array\"} or a \\code{\"data.frame\"}.\n    \\item All the basic model components now have defaults.\n    \\itemize{\n      \\item The default \\code{rinit} behavior remains as it was:\n      it assumes the initial state distribution is concentrated at a point mass determined by parameters with \\dQuote{\\code{.0}} or \\dQuote{\\code{_0}} suffices.\n\n      \\item The default process model is \\dQuote{missing}: calls to \\code{dprocess} and \\code{rprocess} will result in missing values (\\code{NA}).\n      \\item The default measurement model is \\dQuote{missing} as well.\n      \\item The default prior is flat and improper:\n      all calls to the default \\code{dprior} result in \\code{1} (\\code{0} if \\code{log = TRUE}, and all calls to \\code{rprior} result in \\code{NA}.\n      \\item The default skeleton is missing.\n      \\item The default parameter transformations remain the identity.\n    }\n    \\item The \\code{transform} argument present in many \\pkg{pomp} algorithms has been removed.\n    Parameter transformations are now automatically performed when appropriate.\n    The default parameter transformation remains the identity.\n    \\item The old \\code{probe.match} and \\code{traj.match} functions have been removed.\n    The new approach to parameter estimation based on numerical optimization involves constructing stateful objective functions.\n    There are now three of these: \\code{traj.match.objfun}, \\code{probe.match.objfun}, and \\code{spect.match.objfun}.\n    \\item The documentation system has been thoroughly overhauled.\n    \\item In \\code{skeleton}, the \\code{t} argument has been replaced by \\code{times}, to make this uniform with the other workhorse functions.\n    \\item Covariates are now included using the \\code{covariate_table} construction, passed via the \\code{covar} argument to \\code{pomp}.\n    The \\code{tcovar} argument is no longer used.\n    \\item Instead of providing separate \\code{fromEstimationScale} and \\code{toEstimationScale} arguments to \\code{pomp}, one now provides a single \\code{partrans} argument constructed by means of the new function \\code{parameter_trans}.\n    In addition, references to \\dQuote{fromEstimationScale} and \\dQuote{toEstimationScale} have been abbreviated to \\dQuote{fromEst} and \\dQuote{toEst}, respectively, throughout the package.\n    \\item When writing \\proglang{C} snippets for parameter transformations, the notation \\code{T_p} refers to the value of \\code{p} on the estimation scale.\n    Thus, if parameter \\eqn{alpha} is to be log-transformed for estimation, the \\code{toEst} snippet would contain the line \\code{T_alpha = log(alpha);} and the \\code{fromEst} snippet would include \\code{alpha = exp(T_alpha);}.\n    \\item The \\code{parameter_trans} function now takes optional arguments \\code{log}, \\code{logit}, and \\code{barycentric}, with names of parameters to be log-, logit-, and log-barycentric transformed, respectively.\n    \\item The \\code{measurement.model} argument to \\code{pomp} has been removed.\n    It is now necessary to specify the measurement model directly using \\code{rmeasure} and/or \\code{dmeasure}.\n    \\item The \\code{initializer} is no longer referred to by that name.\n    It is now \\code{rinit}, since it draws from the distribution of the latent state at the initial time.\n    The low-level function \\code{init.state} has been replaced by \\code{rinit}.\n    \\item The \\code{conv.rec} method has been deprecated, replaced by the new \\code{traces} method.\n    \\item The \\code{euler.sir} example has been renamed \\code{sir}.\n    \\item The \\code{gillespie.sir} example has been renamed \\code{sir2}.\n    \\item The \\code{covmat} method can now be applied to a \\code{probed.pomp} object.\n    It returns the estimated covariance matrix of the probes.\n    \\item When \\code{trajectory} calls on \\pkg{deSolve} routines to numerically integrate a model vectorfield, more informative error messages are generated, and diagnostics are printed when \\code{verbose = TRUE}.\n    \\item The \\code{show} method applied to pomp objects is now quite terse.\n    To obtain detailed information, the \\code{spy} method is available.\n    \\item The \\code{spy} method now returns the information formerly displayed in a call to \\code{show}, in addition to the \\proglang{C} files associated with any \\proglang{C} snippets.\n    \\item The use of \\code{$} methods to access the slots of \\pkg{pomp} S4 objects has now been removed.\n    These classes are no longer exported (for the most part).\n    \\item The \\code{transform} argument to the \\code{probe.quantile} function has been removed (as it is entirely redundant!).\n    \\item The old and deprecated \\code{mif} and \\code{bsmc} methods have been removed.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.18.8}{\n  \\itemize{\n    \\item The \\code{obs} and \\code{states} arguments of \\code{simulate} are deprecated and will be removed in a forthcoming release.\n    \\item The C-level interface for \\code{apply_probe_sims} has changed: the new argument \\code{rho} must be the \\dQuote{package:pomp} environment.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.18.7}{\n  \\itemize{\n    \\item A bug in \\code{pfilter} (and hence \\code{pmcmc}) when \\code{filter.traj=TRUE} was discovered and fixed.\n    In the buggy version, the filter trajectory was sampled with incorrect weights.\n    \\item Timo Voipio contributed a pull request that traps the error resulting from \\code{sannbox} being passed a \\code{candidate.dist} that is not a function.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.18.6}{\n  \\itemize{\n    \\item \\code{show} and \\code{print} methods have been made very terse:\n    they simply report on the class of the object in question.\n    To see more detailed information about a \\sQuote{pomp} object, use \\code{spy}.\n    \\item New (unexported) \\code{solibs<-} method allows developers of packages extending \\pkg{pomp} to incorporate \\proglang{C} snippets into object that contain \\sQuote{pomp} objects.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.18.5}{\n  \\itemize{\n    \\item New \\code{verbose} option in \\code{trajectory} gives diagnostic information from \\pkg{deSolve} integration routines.\n    Of course, this is pertinent only if the model skeleton is a vectorfield.\n    \\item Bug in the display of \\code{istate} when \\code{deSolve::ode} errors has been fixed.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.18.4}{\n  \\itemize{\n    \\item New \\code{hitch} function facilitates construction of \\code{pomp.fun} objects from \\R functions, \\proglang{C} snippets, and links to external libraries.\n    \\item Native routines needed to access \\code{pomp.fun} objects in \\proglang{C} are now registered for use by other packages.\n    \\item \\code{coef(object) <- NULL}, where \\code{object} is of class \\sQuote{pomp}, erases any parameters stored in \\code{object}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.18.3}{\n  \\itemize{\n    \\item The \\code{euler.sir}, \\code{gillespie.sir}, \\code{blowflies}, \\code{ricker}, \\code{bbs}, \\code{dacca}, and \\code{rw2} examples are all now implemented using \\proglang{C} snippets.\n    \\item A new \\file{pomp_defines.h} header is provided for developers of packages that depend on \\pkg{pomp}.\n    \\item Internally, \\code{rprocess} is no longer stored as an \\R function.\n    The use of plugins is now required for the implementation of the \\code{rprocess} component.\n    Currently, there are five plugins available:\n    \\code{onestep.sim}, \\code{discrete.time.sim}, \\code{euler.sim}, \\code{gillespie.sim}, and \\code{gillespie.hl.sim}.\n    \\item The new \\code{hitch} function automates the building and linking of \\proglang{C} snippets and \\R functions into \\code{pomp.fun}s.\n    \\item The handling of \\code{dprocess} has changed.\n    The \\code{onestep.dens} plugin is now deprecated and will soon be removed.\n    \\code{dprocess} is now specified directly using either a \\proglang{C} snippet or an \\R function, in much the same way that, for example, \\code{dmeasure} is specified.\n    \\item The old \\sQuote{forward} and \\sQuote{inverse} options for the \\code{dir} argument of \\code{partrans} have been dispensed with.\n    The much more descriptive options \\sQuote{toEstimationScale} and \\sQuote{fromEstimationScale} remain.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.18.2}{\n  \\itemize{\n    \\item The \\proglang{C} snippet compiling facilities have been thoroughly reworked.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.18.1}{\n  \\itemize{\n    \\item \\code{onestep.dens} can now take a \\code{Csnippet} specification of the process-model transition density.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.17.4}{\n  \\itemize{\n    \\item All inference functions can now take a list in the \\code{start} or \\code{params} arguments.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.17.3}{\n  \\itemize{\n    \\item When altering parameters in a call to \\code{probe} on a \\code{probed.pomp} object, the new parameters were ignored.\n    This bug has been fixed.\n    \\item \\code{mif2}, \\code{pfilter}, \\code{probe}, \\code{probe.match}, and \\code{probe.match.objfun} can now gracefully handle a list in the \\code{start} or \\code{params} arguments.\n    \\item New \\code{spy} method displays the \\proglang{C} snippet file(s) associated with a \\code{pomp} object.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.17.2}{\n  \\itemize{\n    \\item The long-deprecated \\code{seed} argument to \\code{bsmc} and \\code{bsmc2} has been removed.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.17.1}{\n  \\itemize{\n    \\item More work to obviate warnings generated by T. Kalibera's latest \\code{rchk} checks.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.16.4}{\n  \\itemize{\n    \\item Messages from the compiler resulting from attempts to compile \\proglang{C} snippets are now suppressed on all platforms except in case of failure.\n    Setting \\code{verbose=TRUE} forces display of these messages.\n    \\item Source codes have been revisited to obviate warnings generated by T. Kalibera's latest \\code{rchk} checks.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.16.3}{\n  \\itemize{\n    \\item Fix a minor bugs in \\code{spect}.\n    \\item Improve test coverage.\n    \\item \\code{spect.match} has been refactored, with small changes to the interface.\n    \\item \\code{pomp} now handles specification of workhorse functions (i.e., \\code{rprocess}, \\code{dprocess}, \\code{rmeasure}, \\code{dmeasure}, \\code{initializer}, \\code{skeleton}, \\code{rprior}, \\code{dprior}, \\code{fromEstimationScale}, \\code{toEstimationScale}) as \\code{NULL} more consistently.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.16.2}{\n  \\itemize{\n    \\item Fix bug in systematic resampler when \\code{np != nw}.\n    \\item Fix bug in \\code{conv.rec} when only one parameter is requested.\n    \\item Correct and improve documentation for \\code{conv.rec}.\n    \\item \\code{coef<-} can now take a list of parameters:\n    it simply applies \\code{unlist} to turn the list into a numeric vector.\n    \\item Simplify \\code{conv.rec}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.16.1}{\n  \\itemize{\n    \\item In \\code{pfilter}, \\code{Np} is now a required argument unless \\code{params} is specified as a matrix of particles.\n    Thanks to Carles Breto for catching the unintended behavior.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.15.4}{\n  \\itemize{\n    \\item The bug reported in issue #57 has been fixed.\n    \\item A bug arising when building pomp objects with Csnippets in certain Windows configurations has been fixed.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.15.3}{\n  \\itemize{\n    \\item Issue #56, in which covariate names are discarded when coercing a pomp object to a data frame, has been fixed.\n    Thanks to Eamon O'Dea for reporting this bug.\n    \\item More informative error messages are given when \\code{bake} or \\code{freeze} return \\code{NULL}.\n    In such a case, these functions now generate a warning and return a character-string message, with attributes.\n    \\item Improve documentation of \\code{traj.match}, in response to Issue #57.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.15.2}{\n  \\itemize{\n    \\item A new facility, \\code{gillespie.hl.sim}, allows implementation of Gillespie's algorithm for exact stochastic simulation of continuous-time Markov processes via a streamlined \\proglang{C} snippet interface.\n    \\item The old facility for Gillespie simulations, \\code{gillespie.sim}, now accepts \\proglang{C} snippets for faster calculation of event rates.\n    \\item The old \\code{skeleton.type} and \\code{skelmap.delta.t} arguments of the \\code{pomp} constructor, which have generated error messages since version 1.9.2, have been done away with completely.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.15.1}{\n  \\itemize{\n    \\item Eamon O'Dea identified a bug (Issue #54) occurring when \\code{pomp} is called with a single-row data frame.\n    This has been fixed using his contributed patch.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.14.2}{\n  \\itemize{\n    \\item A new \\code{dmultinom} function is provided in \\sQuote{pomp.h}.\n    This provides the probability distribution function for the multinomial distribution.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.14.1}{\n  \\itemize{\n    \\item Improved tests.\n    \\item Fixed bugs emerging in R-devel due to refactoring of underlying \\R source code.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.13.4}{\n  \\itemize{\n    \\item Eamon O'Dea pointed out that the bug in \\code{gillespie.sim}, addressed by version 1.12.3, was not completely fixed.\n    This problem has now been resolved.\n    In addition, covariates are now guaranteed to be evaluated at least once per observation interval.\n    \\item The new argument \\code{hmax} to \\code{gillespie.sim} allows the user to specify the maximum step size that will be taken before covariates are evaluated.\n    \\item The K-leap method has been removed.\n    Its accuracy is low on test problems and it is difficult to make it compatible with the pomp paradigm.\n    In particular, it does not readily accomodate time-varying covariates in a sensible way, nor does it lend itself to simulations at pre-specified times.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.13.3}{\n  \\itemize{\n    \\item \\code{bspline.basis} and \\code{periodic.bspline.basis} now take an optional non-negative integer argument \\code{deriv}.\n    When \\code{deriv > 0}, the order-\\code{deriv} derivative of each basis function is returned.\n    \\item A new function, \\code{periodic_bspline_basis_eval_deriv}, has been added to the \\proglang{C} API.\n    This function gives access, at the \\proglang{C} level, to evaluation of the derivatives of periodic B-splines.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.13.2}{\n  \\itemize{\n    \\item Upgrade license to GPL version 3.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.13.1}{\n  \\itemize{\n    \\item Fix buffer-flow problem identified by \\code{valgrind}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.12.3}{\n  \\itemize{\n    \\item Fix bug found by Eamon O'Dea in \\code{gillespie.sim}.\n    \\item Fix bug in \\code{onestep.sim}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.12.2}{\n  \\itemize{\n    \\item The Ricker example has a new parameter, \\eqn{c}, which scales the (unobserved) population size.\n    By default, \\eqn{c=1}, so that the behavior is as before.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.12.1}{\n  \\itemize{\n    \\item Improved error trapping.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.11.3}{\n  \\itemize{\n    \\item Some changes have been made to the use of random numbers in some codes (the stochastic simulations in \\code{gillespie.sim} and the resampling in the particle-filtering codes).\n    These changes will mean that calculations performed before will not be reproducible in perfect detail, but will be statistically equivalent.\n    \\item Minor changes in \\proglang{C} codes to obviate warnings generated by T. Kalibera's \\code{rchk} checks.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.11.2}{\n  \\itemize{\n    \\item The rare and fascinating \\dQuote{Bug of St. Patrick} has been fixed.\n    Thanks to Carles Breto for finding the bug and helping to isolate it.\n    \\item More informative error messages are generated when \\code{dmeasure} returns a non-finite likelihood in any of the particle filtering codes.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.11.1}{\n  \\itemize{\n    \\item Some streamlining of codes.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.10.6}{\n  \\itemize{\n    \\item Callable routines are now registered.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.10.5}{\n  \\itemize{\n    \\item More verbosity is provided with \\code{verbose=TRUE}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.10.4}{\n  \\itemize{\n    \\item The functions \\code{bake}, \\code{stew}, and \\code{freeze} now preserve information about the system time used in computation as an attribute of the returned object.\n    In addition, these functions store information about the RNG settings.\n    \\item Some documentation improvements, courtesy of Sebastian Funk.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.10.3}{\n  \\itemize{\n    \\item Documentation improvements.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.10.2}{\n  \\itemize{\n    \\item More verbosity in building of Csnippets.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.10.1}{\n  \\itemize{\n    \\item Better handling of \\code{pomp}'s \\code{times} argument.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.9.3}{\n  \\itemize{\n    \\item New \\code{logLik} method for \\code{pmcmcList} objects.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.9.2}{\n  \\itemize{\n    \\item The deprecated options to supply a matrix or numeric vector as the \\code{data} argument to \\code{pomp} have been removed and doing so now generates an error.\n    The first argument to \\code{pomp}, \\code{data}, must now be provided either as a data frame or as an object of class \\code{pomp}.\n    See \\code{?pomp} for details.\n    \\item The deprecated \\code{skeleton.type} and \\code{skelmap.delta.t} arguments to \\code{pomp} have been removed.\n    Using these arguments will now generate an error message.\n    The correct method of specifying the deterministic skeleton is now explained in the help pages (\\code{?pomp}).\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.9.1}{\n  \\itemize{\n    \\item Source code fixes to eliminate warnings during compilation.\n    \\item Improved test suite.\n    \\item Minor documentation correction.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.8.11}{\n  \\itemize{\n    \\item During particle filtering, when non-finite \\code{dmeasure} values are generated, an error is generated and the offending parameters, states, data, and time are reported.\n    In methods that use parameter transformations (\\code{transform=TRUE}), the reported parameters were on the transformed (estimation) scale, which can be confusing.\n    The error message now gives the parameters on the natural (model) scale.\n    \\item Modified \\file{src/ssa.c} to fix UBSAN errors.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.8.10}{\n  \\itemize{\n    \\item \\proglang{C} codes have been modified to take advantage of changes to the \\R API (R SVN REVISION 71180).\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.8.9}{\n  \\itemize{\n    \\item A bug in \\code{mif2} arising when filtering fails in the final timestep has been fixed.\n    In this case, when all particles are deemed inconsistent with the data, we use an unweighted mean (with a warning) in place of the default weighted mean.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.7.7}{\n  \\itemize{\n    \\item The stochastic simulation algorithms underlying the Gillespie and K-leap methods (\\code{gillespie.sim}, \\code{kleap.sim}) have been refactored in C.\n    In addition, errors due to accumulation of round-off error have been repaired.\n    The result will be more accurate, but somewhat slower when there are a very large number of reactions.\n    \\item Further improvements to the test suite.\n    Code coverage is now 100\\%.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.7.6}{\n  \\itemize{\n    \\item In Sobol' sequence generation (\\code{sobolDesign}, \\code{profileDesign}), we now use the suggestion of Joe & Kuo (2003) to choose a better sequence start point.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.7.5}{\n  \\itemize{\n    \\item The generation of Sobol' sequences (\\code{sobolDesign}, \\code{profileDesign}) is now performed using the \\pkg{NLopt} routines written in \\proglang{C} instead of the original \\acronym{TOMS} 659 \\proglang{FORTRAN} codes.\n    The copyright notices are located in the source code.\n    \\item Improved testing suite.\n    \\item Made \\code{rw.sd} even more robust via new \\code{safecall} class.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.7.4}{\n  \\itemize{\n    \\item Refactored \\code{rw.sd} for greater stability.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.7.3}{\n  \\itemize{\n    \\item Fixed a bug in \\code{plot} on \\code{pomp} objects with more than 10 variables to plot.\n    \\item Added the \\code{shlib.args} option to \\code{pomp}, allowing arbitrary options to be passed to the compiler when \\proglang{C} snippets are used.\n    \\item Modified the \\dQuote{dacca} example to use \\proglang{C} snippets.\n    \\item Refactored \\code{rw.sd} for greater stability.\n    \\item Made Sobol' codes more robust.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.7.2}{\n  \\itemize{\n    \\item Modified the demos to use best practices.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.7.1}{\n  \\itemize{\n    \\item Improved the test suite.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.6.7}{\n  \\itemize{\n    \\item Improve the test suite and error messages.\n    \\item Replace the automatic \\dQuote{verbose} setting during compilation under Windows.\n    This was dropped in version 1.6.4.3, when it no longer appeared to be necessary.\n    Apparently, it is, at least under some Windows OS/R combinations.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.6.6}{\n  \\itemize{\n    \\item Fix \\code{probe} bug introduced in version 1.6.5.9.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.6.5}{\n  \\itemize{\n    \\item Several obscure bug-fixes.\n    \\item Improvement of the test suite and of error messages.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.6.4}{\n  \\itemize{\n    \\item Remove the automatic \\dQuote{verbose} setting during compilation under Windows.\n    This was introduced in version 0.63-6 as a workaround.\n    It appears no longer to be necessary.\n    \\item Improve the \\code{show} method for \\code{pomp} objects.\n    \\item Change the \\code{print} method for \\code{pomp} objects.\n    \\item Improve messages for plugin errors.\n    \\item Some internal refactoring.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.6.3}{\n  \\itemize{\n    \\item Improve error messages for missing basic components.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.6.2}{\n  \\itemize{\n    \\item Fix typos in one of the help-page examples.\n    \\item Add some references.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.6.1}{\n  \\itemize{\n    \\item Major revisions to the package help pages and manual.\n    The separate documentation on \\proglang{C} snippets and process-model plugins has been merged into the main \\code{pomp} help page, which now has comprehensive instructions on building a \\code{pomp} object.\n    \\item Update to the package help page.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.5.10}{\n  \\itemize{\n    \\item The matrix and numeric vector options for the \\code{data} argument to \\code{pomp} are now deprecated and will be removed in a future release.\n    In calls to \\code{pomp}, \\code{data} should be either a data frame or a \\code{pomp}-class object.\n    \\item Many more errors are now trapped and reported with more informative messages.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.5.9}{\n  \\itemize{\n    \\item Redundant \\code{bootstrap} argument to \\code{nlf} has been removed.\n    \\item More improvements to the testing suite.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.5.8}{\n  \\itemize{\n    \\item Major improvements to error and warning handling.\n    \\item Fix bugs that might arise in rare circumstances in \\code{simulate} and \\code{eulermultinom} functions.\n    \\item More improvements to the testing suite.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.5.7}{\n  \\itemize{\n    \\item Many improvements to the test suite.\n    \\item Fixed a bug in \\code{pompExample}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.5.6}{\n  \\itemize{\n    \\item Major overhaul of error handling system and error messages.\n    \\item There is a new plugin for \\code{rprocess} called \\code{kleap.sim}.\n    This implements the so-called \\dQuote{K-leap method} of Cai & Xu (2007).\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.5.5}{\n  \\itemize{\n    \\item Many improvements to the test suite.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.5.4}{\n  \\itemize{\n    \\item More improvements to the test suite.\n    \\item Fixed bugs found as a result of improved testing.\n    \\item In \\code{mif2}, it is now required that \\code{Nmif>0}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.5.3}{\n  \\itemize{\n    \\item More improvements to the test suite.\n    \\item Fixed bugs found as a result of improved testing.\n    \\item Fixed bug in specification of skeleton in pompExamples.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.5.2}{\n  \\itemize{\n    \\item Improved the test suite to obtain better code coverage.\n    \\item \\code{pomp} is no longer an S4 method.\n    Its new status as an ordinary function abbreviates and consolidates the code and simplifies the documentation.\n    \\item Some minor improvements to error messages.\n    \\item A bug restricting access in \\proglang{C} code to \\code{userdata} has been fixed.\n    \\item Fixed bug in \\code{pompExample(...,show=TRUE)}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.5.1}{\n  \\itemize{\n    \\item New methods for the Ensemble Kalman Filter (\\code{enkf}) and Ensemble Adjustment Kalman Filter (\\code{eakf}) have been added to the package.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.4.9}{\n  \\itemize{\n    \\item A better interface for specifying a model's deterministic skeleton is provided.\n    One specifies \\code{skeleton=map(f,delta.t)} for a discrete-time skeleton (a map) and \\code{skeleton=vectorfield(f)} for a continuous-time skeleton (a vectorfield).\n    The old arguments \\code{skeleton.type} and \\code{skelmap.delta.t} are deprecated and will be removed in a future release.\n    \\item The \\code{pfilter} help page has been improved.\n    Specifically, the discussion of filtering failures is better.\n    \\item Miscellaneous improvements to the help pages.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.4.8}{\n  \\itemize{\n    \\item \\code{mif2} no longer computes filter means.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.4.7}{\n  \\itemize{\n    \\item The new argument \\code{show} of \\code{pompExamples} allows one to display the example code instead of executing it.\n    \\item The minimum version of \\R supported is now 3.1.2.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.4.6}{\n  \\itemize{\n    \\item \\code{init.state} now has the optional argument \\code{nsim}.\n    Using this, one can request multiple initial state vectors per parameter vector.\n    \\item \\code{pfilter} now uses less memory when it is asked to run at a single point in parameter space.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.4.5}{\n  \\itemize{\n    \\item A bug associated with the \\code{rw.sd} argument to \\code{mif2} on Windows platforms has been fixed.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.4.4}{\n  \\itemize{\n    \\item The \\code{method=\"mif2\"} option to \\code{mif} has been removed.\n    Use \\code{mif2} instead.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.4.3}{\n  \\itemize{\n    \\item The \\code{particles} method (rarely if ever used), has been removed to streamline the \\code{mif} codes.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.4.2}{\n  \\itemize{\n    \\item The \\code{method=\"mif2\"} option to \\code{mif} is now deprecated.\n    It will be removed in a future release.\n    Use \\code{mif2} instead.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.4.1}{\n  \\itemize{\n    \\item Following the publication of the Journal of Statistical Software announcement paper, the \\file{CITATION} has been modified to include the appropriate citation.\n    Please use \\code{citation(\"pomp\")} to learn about how to cite \\pkg{pomp} correctly.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.3.4}{\n  \\itemize{\n    \\item \\code{conv.rec} on the results of a \\code{mif2} computation now play nicely with \\code{reshape2::melt}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.3.3}{\n  \\itemize{\n    \\item It is now possible to direct \\code{pomp} to place \\code{Csnippet} codes in a specified location.\n    This is accomplished via the new \\code{cdir} and \\code{cfile} arguments to \\code{pomp}.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.3.2}{\n  \\itemize{\n    \\item When several concurrent \\R processes attempt to simultaneously compile \\code{Csnipet} code from copies of a \\code{pomp} object on the same machine, a race condition exists.\n    This release fixes this by ensuring that \\code{Csnippet} codes are written and compiled in a process-specific directory.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.3.1}{\n  This release removes several long-deprecated features.\n  \\itemize{\n    \\item The \\code{seed} argument to \\code{pfilter} has been removed.\n    Use \\code{freeze} to obtain similar functionality.\n    \\item The redundant \\code{pars} argument to \\code{mif} has been removed.\n    Names of parameters to be estimated are taken from the nonzero entries of \\code{rw.sd}.\n    Initial-value parameters are designated using the \\code{ivps} argument.\n    \\item The old \\code{parameter.transform} and \\code{parameter.inv.transform} arguments to \\code{pomp} have been removed.\n    They were superseded by the arguments \\code{fromEstimationScale} and \\code{toEstimationScale} in version 0.65-1.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.2.2}{\n  \\itemize{\n    \\item Some internal changes to \\code{mif2} by C. Breto, in support of panel methods under development.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.2.1}{\n  \\itemize{\n    \\item Bug fix: for POMPs with a scalar state variable, the \\code{filter.mean}, \\code{pred.mean}, and \\code{pred.var} methods dropped the singleton dimension of the respective arrays, in conflict with the assumptions of certain \\code{plot} methods.\n    This resolves issue #3.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.1.4}{\n  \\itemize{\n    \\item Documentation improvements.\n    Specifically, the details of how step-sizes are chosen in the \\code{euler.sim}, \\code{discrete.time.sim}, and \\code{onestep.sim} plugins has been spelled out explicitly.\n    Also, incompleteness in the \\code{sannbox} documentation has been corrected.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.1.3}{\n  \\itemize{\n    \\item Provide \\code{filter.traj} method for \\code{pmcmcList} objects.\n  }\n}\n\\section{Changes in \\pkg{pomp} version 1.1.2}{\n  \\itemize{\n    \\item Fixed a bug in \\code{mif} and \\code{mif2} when \\code{cooling.type=\"hyperbolic\"} and \\code{cooling.fraction.50=1}.\n  }\n}\n"
  },
  {
    "path": "inst/doc/Makefile",
    "content": "RM = rm -f\nCP = cp\nTOUCH = touch\nINSTALL = install\nPANDOC = pandoc\n\ndefault: index.html\n\n%.tex: %.Rnw\n\t$(RSCRIPT) -e \"library(knitr); knit(\\\"$*.Rnw\\\")\"\n\n%.R: %.Rnw\n\t$(RSCRIPT) -e \"library(knitr); purl(\\\"$*.Rnw\\\")\"\n\n%.pdf: %.tex\n\t$(PDFLATEX) $*\n\t-$(BIBTEX) $*\n\t$(PDFLATEX) $*\n\t$(PDFLATEX) $*\n\n%.bbl: %.tex\n\t-$(PDFLATEX) $*\n\t$(BIBTEX) $*\n\n%.idx: %.tex\n\t-$(PDFLATEX) $*\n\n%.ind: %.idx\n\t$(MAKEIDX) $*\n\n%.html: %.Rmd\n\tRscript --vanilla -e \"rmarkdown::render(\\\"$*.Rmd\\\",output_format=\\\"html_document\\\")\"\n\n%.html: %.md\n\t$(PANDOC) $^ -o $@\n\n%.R: %.Rmd\n\tRscript --vanilla -e \"knitr::purl(\\\"$*.Rmd\\\",output=\\\"$*.R\\\",documentation=2)\"\n\nclean:\n\t$(RM) -r figure cache tmp\n"
  },
  {
    "path": "inst/doc/index.html",
    "content": "<style>\nhtml {\n    overflow-y: scroll;\n}\n\nbody {\n    color: #000000;\n    background: #ffffff;\n    font-family: \"DejaVu Sans\", \"Arial Sans\", Arial, sans;\n}\n\ncode {\n    font-family: monospace;\n    font-size: 1.125em;\n}\n\nh1, h2, h3, h4 {\n    font-family: \"DejaVu Sans\", \"Arial Sans\", Arial, sans;\n    font-weight: bold;\n    font-variant: normal;\n}\n\nh1 {\n    font-size: 1.5em;\n}\n\nh2 {\n    font-size: 1.375em;\n}\n\nh3 {\n    font-size: 1.25em;\n    text-decoration: underline;\n}\n\nh4 {\n    font-size: 1.125em;\n}\n\np, ul, ol {\n    text-align: left;\n}\n\ntd {\n    vertical-align: top;\n}\n\na:link, a:visited {\n    color: #0000ff;\n    text-decoration: none;\n}\na:hover, a:active {\n    color: #cc3333; \n    text-decoration: none;\n}\na.activated {\n    text-decoration: underline;\n}\n\nthead {\n    display: table-header-group;\n}\n\ndl, ul, ol, dd {\n    page-break-before: avoid;\n}\n\ndt, dd, tr, h1, h2, h3, h4, li, p {\n    page-break-inside: avoid;\n}\n\ndt, h1, h2, h3, h4 {\n    page-break-after: avoid;\n}\n\ndt, dd {\n    text-align: left;\n}\n\ndt {\n    font-weight: bold;\n}\n\n.emph {\n    color: #cc3333; \n    font-weight: bold;\n}\n\n.emph1 {\n    color: #3333ff; \n    font-weight: bold;\n}\n\n.firstcharacter { \n    float: left; \n    color: #3333ff; \n    font-size: 2.5em;\n    line-height: 0.8em;\n    vertical-align: top;\n    padding-right: 5px;\n}\n</style>\n<ul>\n<li><p><a\nhref=\"https://kingaa.github.io/pomp/docs.html\"><strong>pomp</strong>\nwebsite</a></p></li>\n<li><p><a\nhref=\"https://kingaa.github.io/pomp/FAQ.html\"><strong>pomp</strong>\nFAQ</a></p></li>\n<li><p><a\nhref=\"https://kingaa.github.io/pomp/vignettes/getting_started.html\">Getting\nstarted with <strong>pomp</strong></a></p></li>\n<li><p><a href=\"https://kingaa.github.io/pomp/docs.html\">Tutorials and\nother documentation</a></p></li>\n<li><p><a href=\"https://kingaa.github.io/pomp/NEWS/\">Package\nNEWS</a></p></li>\n<li><p><a href=\"https://kingaa.github.io/pomp/manual/\">Package\nmanual</a></p></li>\n<li><p><a href=\"https://kingaa.github.io/pomp/C_API.html\">Guide to the\n<strong>pomp</strong> C API</a></p></li>\n<li><p><a href=\"https://github.com/kingaa/pomp/discussions\">Community\ndiscussions</a></p></li>\n<li><p><a href=\"https://github.com/kingaa/pomp/issues\">Report issues\nwith the package</a></p></li>\n<li><p><a href=\"#\" onclick=\"window.history.back()\">Back to the previous\npage</a></p></li>\n<li><p><a href=\"#\" onclick=\"window.close()\">Close window</a></p></li>\n</ul>\n"
  },
  {
    "path": "inst/doc/index.md",
    "content": "---\ntitle: \"pomp\"\nsubtitle: \"user guides, vignettes, and tutorials\"\n---\n\n<style>\nhtml {\n    overflow-y: scroll;\n}\n\nbody {\n    color: #000000;\n    background: #ffffff;\n    font-family: \"DejaVu Sans\", \"Arial Sans\", Arial, sans;\n}\n\ncode {\n    font-family: monospace;\n    font-size: 1.125em;\n}\n\nh1, h2, h3, h4 {\n    font-family: \"DejaVu Sans\", \"Arial Sans\", Arial, sans;\n    font-weight: bold;\n    font-variant: normal;\n}\n\nh1 {\n    font-size: 1.5em;\n}\n\nh2 {\n    font-size: 1.375em;\n}\n\nh3 {\n    font-size: 1.25em;\n    text-decoration: underline;\n}\n\nh4 {\n    font-size: 1.125em;\n}\n\np, ul, ol {\n    text-align: left;\n}\n\ntd {\n    vertical-align: top;\n}\n\na:link, a:visited {\n    color: #0000ff;\n    text-decoration: none;\n}\na:hover, a:active {\n    color: #cc3333; \n    text-decoration: none;\n}\na.activated {\n    text-decoration: underline;\n}\n\nthead {\n    display: table-header-group;\n}\n\ndl, ul, ol, dd {\n    page-break-before: avoid;\n}\n\ndt, dd, tr, h1, h2, h3, h4, li, p {\n    page-break-inside: avoid;\n}\n\ndt, h1, h2, h3, h4 {\n    page-break-after: avoid;\n}\n\ndt, dd {\n    text-align: left;\n}\n\ndt {\n    font-weight: bold;\n}\n\n.emph {\n    color: #cc3333; \n    font-weight: bold;\n}\n\n.emph1 {\n    color: #3333ff; \n    font-weight: bold;\n}\n\n.firstcharacter { \n    float: left; \n    color: #3333ff; \n    font-size: 2.5em;\n    line-height: 0.8em;\n    vertical-align: top;\n    padding-right: 5px;\n}\n</style>\n\n- [**pomp** website](https://kingaa.github.io/pomp/docs.html)\n\n- [**pomp** FAQ](https://kingaa.github.io/pomp/FAQ.html)\n\n- [Getting started with **pomp**](https://kingaa.github.io/pomp/vignettes/getting_started.html)\n\n- [Tutorials and other documentation](https://kingaa.github.io/pomp/docs.html)\n\n- [Package NEWS](https://kingaa.github.io/pomp/NEWS/)\n\n- [Package manual](https://kingaa.github.io/pomp/manual/)\n\n- [Guide to the **pomp** C API](https://kingaa.github.io/pomp/C_API.html)\n\n- [Community discussions](https://github.com/kingaa/pomp/discussions)\n\n- [Report issues with the package](https://github.com/kingaa/pomp/issues)\n\n- <a href=\"#\" onclick=\"window.history.back()\">Back to the previous page</a>\n\n- <a href=\"#\" onclick=\"window.close()\">Close window</a>\n"
  },
  {
    "path": "inst/include/pomp.h",
    "content": "// -*- C++ -*-\n// Header for the C API for pomp.\n// Documentation: https://kingaa.github.io/pomp/C_API.html\n\n\n#ifndef _POMP_H_\n#define _POMP_H_\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n#define err(...) Rf_errorcall(R_NilValue,__VA_ARGS__)\n#define warn(...) Rf_warningcall(R_NilValue,__VA_ARGS__)\n\ntypedef\nvoid bspline_basis_eval_deriv_t\n(double x, double *knots, int degree,\n int nbasis, int deriv, double *y);\n\ntypedef\nvoid periodic_bspline_basis_eval_deriv_t\n(double x, double period, int degree,\n int nbasis, int deriv, double *y);\n\ntypedef const SEXP get_userdata_t (const char *name);\ntypedef const int *get_userdata_int_t (const char *name);\ntypedef const double *get_userdata_double_t (const char *name);\n\ntypedef\nvoid pomp_rinit\n(double *x, const double *p, double t0,\n const int *stateindex, const int *parindex,\n const int *covindex, const double *covars);\n\ntypedef\nvoid pomp_dinit\n(double *lik, const double *x, const double *p,\n double t0, const int *stateindex, const int *parindex,\n const int *covindex, const double *covars);\n\ntypedef\ndouble pomp_ssa_rate_fn\n(int event, double t, const double *x,\n const double *p, const int *stateindex,\n const int *parindex, const int *covindex,\n const double *covars);\n\ntypedef\nvoid pomp_onestep_sim\n(double *x, const double *p,\n const int *stateindex, const int *parindex,\n const int *covindex, const double *covars,\n double t, double dt);\n\ntypedef\nvoid pomp_dprocess\n(double *loglik, const double *x1, const double *x2,\n double t1, double t2, const double *p,\n const int *stateindex, const int *parindex,\n const int *covindex, const double *covars);\n\ntypedef\nvoid pomp_skeleton\n(double *f, const double *x, const double *p,\n const int *stateindex, const int *parindex,\n const int *covindex, const double *covars, double t);\n\ntypedef\nvoid pomp_rmeasure\n(double *y, const double *x, const double *p,\n const int *obsindex, const int *stateindex,\n const int *parindex, const int *covindex,\n const double *covars, double t);\n\ntypedef\nvoid pomp_dmeasure\n(double *lik, const double *y, const double *x,\n const double *p, int give_log, const int *obsindex,\n const int *stateindex, const int *parindex,\n const int *covindex, const double *covars, double t);\n\ntypedef\nvoid pomp_emeasure\n(double *f, const double *x, const double *p,\n const int *obsindex, const int *stateindex,\n const int *parindex, const int *covindex,\n const double *covars, double t);\n\ntypedef\nvoid pomp_vmeasure\n(double *f, const double *x, const double *p,\n const int *vmatindex, const int *stateindex,\n const int *parindex, const int *covindex,\n const double *covars, double t);\n\ntypedef\nvoid pomp_rprior\n(double *p, const int *parindex);\n\ntypedef\nvoid pomp_dprior\n(double *lik, const double *p, int give_log, const int *parindex);\n\ntypedef\nvoid pomp_transform\n(double *pt, const double *p, const int *parindex);\n\nstatic R_INLINE\ndouble logit (double p) {\n  return log(p/(1.0-p));\n}\n\nstatic R_INLINE\ndouble expit (double x) {\n  return 1.0/(1.0+exp(-x));\n}\n\nstatic R_INLINE\ndouble rgammawn\n(double sigma, double dt)\n{\n  double sigmasq;\n  sigmasq = sigma*sigma;\n  return (sigmasq > 0) ? rgamma(dt/sigmasq,sigmasq) : dt;\n}\n\nstatic R_INLINE\nvoid eeulermultinom\n(int m, double size, const double *rate, double dt, double *trans)\n{\n  double lambda = 0.0;\n  int j, k;\n  if (!R_FINITE(size) || size < 0.0 || !R_FINITE(dt) || dt < 0.0) {\n    for (k = 0; k < m; k++) trans[k] = R_NaReal;\n    warn(\"in 'eeulermultinom': NAs produced.\");\n    return;\n  }\n  for (k = 0; k < m; k++) {\n    if (!R_FINITE(rate[k]) || rate[k] < 0.0) {\n      for (j = 0; j < m; j++) trans[j] = R_NaReal;\n      warn(\"in 'eeulermultinom': NAs produced.\");\n      return;\n    }\n    lambda += rate[k];\n  }\n  if (lambda > 0.0) {\n    size = size*(1-exp(-lambda*dt));\n    for (k = 0; k < m; k++)\n      trans[k] = size*rate[k]/lambda;\n  } else {\n    for (k = 0; k < m; k++) trans[k] = 0.0;\n  }\n}\n\nstatic R_INLINE\nvoid reulermultinom\n(int m, double size, const double *rate, double dt, double *trans)\n{\n  double p = 0.0;\n  int j, k;\n  if ( !R_FINITE(size) || size < 0.0 || floor(size+0.5) != size ||\n       !R_FINITE(dt) || dt < 0.0) {\n    for (k = 0; k < m; k++) trans[k] = R_NaReal;\n    warn(\"in 'reulermultinom': NAs produced.\");\n    return;\n  }\n  for (k = 0; k < m; k++) {\n    if (!R_FINITE(rate[k]) || rate[k] < 0.0) {\n      for (j = 0; j < m; j++) trans[j] = R_NaReal;\n      warn(\"in 'reulermultinom': NAs produced.\");\n      return;\n    }\n    p += rate[k]; // total event rate\n  }\n  if (p > 0.0) {\n    size = rbinom(size,1-exp(-p*dt)); // total number of events\n    m -= 1;\n    for (k = 0; k < m; k++) {\n      if (rate[k] > p) p = rate[k];\n      trans[k] = ((size > 0) && (p > 0)) ? rbinom(size,rate[k]/p) : 0;\n      size -= trans[k];\n      p -= rate[k];\n    }\n    trans[m] = size;\n  } else {\n    for (k = 0; k < m; k++) trans[k] = 0.0;\n  }\n}\n\nstatic R_INLINE\ndouble deulermultinom\n(int m, double size, const double *rate, double dt, double *trans, int give_log)\n{\n  double p = 0.0;\n  double n = 0.0;\n  double ff = 0.0;\n  int k;\n  if ((dt < 0.0) || (size < 0.0) || (floor(size+0.5) != size)) {\n    warn(\"in 'deulermultinom': NaNs produced.\");\n    return R_NaN;\n  }\n  for (k = 0; k < m; k++) {\n    if (rate[k] < 0.0) {\n      warn(\"in 'deulermultinom': NaNs produced.\");\n      return R_NaN;\n    }\n    if (trans[k] < 0.0) {\n      ff = (give_log) ? R_NegInf: 0.0;\n      return ff;\n    }\n    p += rate[k]; // total event rate\n    n += trans[k]; // total number of events\n  }\n  if (n > size) {\n    ff = (give_log) ? R_NegInf: 0.0;\n    return ff;\n  }\n  ff = dbinom(n,size,1-exp(-p*dt),1); // total number of events\n  m -= 1;\n  for (k = 0; k < m; k++) {\n    if ((n > 0) && (p > 0)) {\n      if (rate[k] > p) p = rate[k];\n      ff += dbinom(trans[k],n,rate[k]/p,1);\n    }\n    n -= trans[k];\n    p -= rate[k];\n  }\n  ff = (give_log) ? ff : exp(ff);\n  return ff;\n}\n\nstatic R_INLINE\ndouble dmultinom\n(int m, const double *prob, double *x, int give_log)\n{\n  double p = 0.0;\n  double n = 0.0;\n  double ff = 0.0;\n  int k;\n  for (k = 0; k < m; k++) {\n    if (prob[k] < 0.0) {\n      warn(\"in 'dmultinom': NaNs produced.\");\n      return R_NaN;\n    }\n    if ((x[k] < 0.0) || (floor(x[k]+0.5) != x[k])) {\n      ff = (give_log) ? R_NegInf: 0.0;\n      return ff;\n    }\n    p += prob[k]; // sum of probabilities\n    n += x[k]; // total number of events\n  }\n  for (k = 0; k < m; k++) {\n    if ((n > 0) && (p > 0)) {\n      if (prob[k] > p) p = prob[k];\n      ff += dbinom(x[k],n,prob[k]/p,1);\n    } else if (x[k] < 0.0) {\n      ff = R_NegInf;\n      return ff;\n    }\n    n -= x[k];\n    p -= prob[k];\n  }\n  ff = (give_log) ? ff : exp(ff);\n  return ff;\n}\n\nstatic R_INLINE\nvoid to_log_barycentric\n(double *xt, const double *x, int n)\n{\n  double sum;\n  int i;\n  for (i = 0, sum = 0.0; i < n; i++) sum += x[i];\n  for (i = 0; i < n; i++) xt[i] = log(x[i]/sum);\n}\n\nstatic R_INLINE\nvoid from_log_barycentric\n(double *xt, const double *x, int n)\n{\n  double sum;\n  int i;\n  for (i = 0, sum = 0.0; i < n; i++) sum += (xt[i] = exp(x[i]));\n  for (i = 0; i < n; i++) xt[i] /= sum;\n}\n\nstatic R_INLINE\ndouble dot_product\n(int n, const double *x, const double *y)\n{\n  double p = 0.0;\n  for (int j = 0; j < n; j++) p += x[j]*y[j];\n  return p;\n}\n\nstatic R_INLINE\ndouble exp2geom_rate_correction\n(double R, double dt)\n{\n  return (dt > 0) ? log1p(R*dt)/dt : R;\n}\n\nstatic R_INLINE\ndouble rbetabinom\n(double size, double prob, double theta)\n{\n  return rbinom(size,rbeta(prob*theta,(1.0-prob)*theta));\n}\n\nstatic R_INLINE\ndouble dbetabinom\n(double x, double size, double prob, double theta, int give_log)\n{\n  double a = theta*prob;\n  double b = theta*(1.0-prob);\n  double f = lchoose(size,x)-lbeta(a,b)+lbeta(a+x,b+size-x);\n  return (give_log) ? f : exp(f);\n}\n\nstatic R_INLINE\ndouble rbetanbinom\n(double mu, double size, double theta)\n{\n  double p = size/(size+mu);\n  return rnbinom(size,rbeta(p*theta,(1.0-p)*theta));\n}\n\nstatic R_INLINE\ndouble dbetanbinom\n(double x, double mu, double size, double theta, int give_log)\n{\n  double p = size/(size+mu);\n  double a = theta*p;\n  double b = theta*(1.0-p);\n  double f = lchoose(size+x-1,size-1)-lbeta(a,b)+lbeta(a+size,b+x);\n  return (give_log) ? f : exp(f);\n}\n\n#endif\n"
  },
  {
    "path": "inst/include/pomp_defines.h",
    "content": "// -*- C++ -*-\n\n#ifndef _POMP_DEFINES_H_\n#define _POMP_DEFINES_H_\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n\n#include \"pomp.h\"\n\n# define MATCHROWNAMES(X,N,W) (matchnames(GET_ROWNAMES(GET_DIMNAMES(X)),(N),(W)))\n# define MATCHCOLNAMES(X,N,W) (matchnames(GET_COLNAMES(GET_DIMNAMES(X)),(N),(W)))\n\ntypedef enum {undef=0,Rfun=1,native=2,regNative=3} pompfunmode;\ntypedef enum {dflt=0,onestep=1,discrete=2,euler=3,gill=4} rprocmode;\n\n// lookup-table structure, as used internally\ntypedef struct {\n  int length, width;\n  int index;\n  int order;\n  double *x;\n  double *y;\n} lookup_table_t;\n\ntypedef SEXP pomp_fun_handler_t (SEXP pfun, SEXP gnsi, pompfunmode *mode, SEXP S, SEXP P, SEXP O, SEXP C);\ntypedef SEXP load_stack_incr_t (SEXP pack);\ntypedef SEXP load_stack_decr_t (SEXP pack);\ntypedef lookup_table_t make_covariate_table_t (SEXP object, int *ncovar);\ntypedef void table_lookup_t (lookup_table_t *tab, double x, double *y);\ntypedef SEXP apply_probe_data_t (SEXP object, SEXP probes);\ntypedef SEXP apply_probe_sim_t (SEXP object, SEXP nsim, SEXP params, SEXP probes, SEXP datval, SEXP gnsi);\ntypedef SEXP systematic_resampling_t (SEXP weights);\ntypedef void set_pomp_userdata_t (SEXP userdata);\ntypedef void unset_pomp_userdata_t (void);\ntypedef SEXP get_covariate_names_t (SEXP object);\n\nstatic R_INLINE SEXP makearray (int rank, const int *dim) {\n  int *dimp, k;\n  double *xp;\n  SEXP dimx, x;\n  PROTECT(dimx = NEW_INTEGER(rank));\n  dimp = INTEGER(dimx);\n  for (k = 0; k < rank; k++) dimp[k] = dim[k];\n  PROTECT(x = allocArray(REALSXP,dimx));\n  xp = REAL(x);\n  for (k = 0; k < length(x); k++) xp[k] = NA_REAL;\n  UNPROTECT(2);\n  return x;\n}\n\n// check if names exist and are nonempty\nstatic R_INLINE int invalid_names (SEXP names) {\n  return isNull(names);\n}\n\nstatic R_INLINE SEXP matchnames\n(\n SEXP provided, SEXP needed, const char *where\n ) {\n  int m = LENGTH(provided);\n  int n = length(needed);\n  SEXP index;\n  int *idx, i, j;\n  PROTECT(provided = AS_CHARACTER(provided));\n  PROTECT(needed = AS_CHARACTER(needed));\n  if (invalid_names(provided))\n    err(\"invalid variable names among the %s.\",where); // #nocov\n  PROTECT(index = NEW_INTEGER(n));\n  idx = INTEGER(index);\n  for (i = 0; i < n; i++) {\n    for (j = 0; j < m; j++) {\n      if (!strcmp(CHAR(STRING_ELT(provided,j)),CHAR(STRING_ELT(needed,i)))) {\n        idx[i] = j;\n        break;\n      }\n    }\n    if (j==m)\n      err(\"variable '%s' not found among the %s.\",CHAR(STRING_ELT(needed,i)),where);\n  }\n  UNPROTECT(3);\n  return index;\n}\n\nstatic R_INLINE void fillrownames (SEXP x, SEXP names) {\n  SEXP dim, dimnms;\n  int nr;\n  PROTECT(names = AS_CHARACTER(names));\n  PROTECT(dim = GET_DIM(x));\n  PROTECT(dimnms = allocVector(VECSXP,length(dim)));\n  nr = INTEGER(dim)[0];\n  if (nr > length(names)) {\n    SEXP nm;\n    int k;\n    PROTECT(nm = NEW_CHARACTER(nr));\n    for (k = 0; k < length(names); k++) {\n      SET_STRING_ELT(nm,k,STRING_ELT(names,k));\n    }\n    SET_ELEMENT(dimnms,0,nm);\n    UNPROTECT(1);\n  } else {\n    SET_ELEMENT(dimnms,0,names);\n  }\n  SET_DIMNAMES(x,dimnms);\n  UNPROTECT(3);\n}\n\nstatic R_INLINE void setrownames (SEXP x, SEXP names, int rank) {\n  SEXP dimnms, nm;\n  PROTECT(nm = AS_CHARACTER(names));\n  PROTECT(dimnms = allocVector(VECSXP,rank));\n  SET_ELEMENT(dimnms,0,nm);     // set row names\n  SET_DIMNAMES(x,dimnms);\n  UNPROTECT(2);\n}\n\n// This only works if the dimnames have already been created and set\n// e.g., with 'setrownames'\nstatic R_INLINE void setcolnames (SEXP x, SEXP names) {\n  SEXP dn;\n  PROTECT(dn = GET_DIMNAMES(x));\n  SET_ELEMENT(dn,1,names);\n  SET_DIMNAMES(x,dn);\n  UNPROTECT(1);\n}\n\nstatic R_INLINE void fixdimnames (SEXP x, const char **names, int n) {\n  int nprotect = 2;\n  int i;\n  SEXP dimnames, nm;\n  PROTECT(dimnames = GET_DIMNAMES(x));\n  if (isNull(dimnames)) {\n    PROTECT(dimnames = allocVector(VECSXP,n)); nprotect++;\n  }\n  PROTECT(nm = allocVector(VECSXP,n));\n  for (i = 0; i < n; i++)\n    SET_ELEMENT(nm,i,mkChar(names[i]));\n  SET_NAMES(dimnames,nm);\n  SET_DIMNAMES(x,dimnames);\n  UNPROTECT(nprotect);\n}\n\nstatic R_INLINE SEXP as_matrix (SEXP x) {\n  int nprotect = 1;\n  SEXP dim, names;\n  int *xdim, nrow, ncol;\n  PROTECT(dim = GET_DIM(x));\n  if (isNull(dim)) {\n    PROTECT(x = duplicate(x));\n    PROTECT(names = GET_NAMES(x));\n    nprotect += 2;\n    dim = NEW_INTEGER(2);\n    xdim = INTEGER(dim); xdim[0] = LENGTH(x); xdim[1] = 1;\n    SET_DIM(x,dim);\n    SET_NAMES(x,R_NilValue);\n    setrownames(x,names,2);\n  } else if (LENGTH(dim) == 1) {\n    PROTECT(x = duplicate(x));\n    PROTECT(names = GET_ROWNAMES(GET_DIMNAMES(x)));\n    nprotect += 2;\n    dim = NEW_INTEGER(2);\n    xdim = INTEGER(dim); xdim[0] = LENGTH(x); xdim[1] = 1;\n    SET_DIM(x,dim);\n    SET_NAMES(x,R_NilValue);\n    setrownames(x,names,2);\n  } else if (LENGTH(dim) > 2) {\n    PROTECT(x = duplicate(x));\n    PROTECT(names = GET_ROWNAMES(GET_DIMNAMES(x)));\n    nprotect += 2;\n    nrow = INTEGER(dim)[0]; ncol = LENGTH(x)/nrow;\n    dim = NEW_INTEGER(2);\n    xdim = INTEGER(dim); xdim[0] = nrow; xdim[1] = ncol;\n    SET_DIM(x,dim);\n    SET_NAMES(x,R_NilValue);\n    setrownames(x,names,2);\n  }\n  UNPROTECT(nprotect);\n  return x;\n}\n\nstatic R_INLINE SEXP as_state_array (SEXP x) {\n  int nprotect = 1;\n  SEXP dim, names;\n  int *xdim, nrow, ncol;\n  PROTECT(dim = GET_DIM(x));\n  if (isNull(dim)) {\n    PROTECT(x = duplicate(x));\n    PROTECT(names = GET_NAMES(x));\n    nprotect += 2;\n    dim = NEW_INTEGER(3);\n    xdim = INTEGER(dim); xdim[0] = LENGTH(x); xdim[1] = 1; xdim[2] = 1;\n    SET_DIM(x,dim);\n    SET_NAMES(x,R_NilValue);\n    setrownames(x,names,3);\n  } else if (LENGTH(dim) == 1) {\n    PROTECT(x = duplicate(x));\n    PROTECT(names = GET_ROWNAMES(GET_DIMNAMES(x)));\n    nprotect += 2;\n    dim = NEW_INTEGER(3);\n    xdim = INTEGER(dim); xdim[0] = LENGTH(x); xdim[1] = 1; xdim[2] = 1;\n    SET_DIM(x,dim);\n    SET_NAMES(x,R_NilValue);\n    setrownames(x,names,3);\n  } else if (LENGTH(dim) == 2) {\n    PROTECT(x = duplicate(x));\n    PROTECT(names = GET_ROWNAMES(GET_DIMNAMES(x)));\n    nprotect += 2;\n    xdim = INTEGER(dim); nrow = xdim[0]; ncol = xdim[1];\n    dim = NEW_INTEGER(3);\n    xdim = INTEGER(dim); xdim[0] = nrow; xdim[1] = 1; xdim[2] = ncol;\n    SET_DIM(x,dim);\n    SET_NAMES(x,R_NilValue);\n    setrownames(x,names,3);\n  } else if (LENGTH(dim) > 3) {\n    PROTECT(x = duplicate(x));\n    PROTECT(names = GET_ROWNAMES(GET_DIMNAMES(x)));\n    nprotect += 2;\n    xdim = INTEGER(dim); nrow = xdim[0]; ncol = xdim[1];\n    dim = NEW_INTEGER(3);\n    xdim = INTEGER(dim);\n    xdim[0] = nrow; xdim[1] = ncol; xdim[2] = LENGTH(x)/nrow/ncol;\n    SET_DIM(x,dim);\n    SET_NAMES(x,R_NilValue);\n    setrownames(x,names,3);\n  }\n  UNPROTECT(nprotect);\n  return x;\n}\n\nstatic R_INLINE SEXP getListElement (SEXP list, const char *str)\n{\n  SEXP elmt = R_NilValue;\n  SEXP names = getAttrib(list,R_NamesSymbol);\n  for (R_len_t i = 0; i < length(list); i++)\n    if (strcmp(CHAR(STRING_ELT(names,i)),str) == 0) {\n      elmt = VECTOR_ELT(list,i);\n      break;\n    }\n  return elmt;\n}\n\nstatic R_INLINE SEXP getPairListElement (SEXP list, const char *name)\n{\n  const char *tag;\n  while (list != R_NilValue) {\n    tag = CHAR(PRINTNAME(TAG(list)));\n    if (strcmp(tag,name)==0) break;\n    list = CDR(list);\n  }\n  return CAR(list);\n}\n\n#ifdef __cplusplus\n\ntemplate <class Scalar>\nclass view {\nprivate:\n  Scalar *data;\n  int dim[2];\npublic:\n  view (Scalar *x) {\n    data = x;\n    dim[0] = 0;\n    dim[1] = 0;\n  };\n  view (Scalar *x, int d1) {\n    data = x;\n    dim[0] = d1;\n    dim[1] = 0;\n  };\n  view (Scalar *x, int d1, int d2) {\n    data = x;\n    dim[0] = d1;\n    dim[1] = d2;\n  };\n  ~view (void) {};\n  inline Scalar& operator () (int d1) {\n    return(data[d1]);\n  };\n  inline Scalar& operator () (int d1, int d2) {\n    return(data[d1 + dim[0] * d2]);\n  };\n  inline Scalar& operator () (int d1, int d2, int d3) {\n    return(data[d1 + dim[0] * (d2 + dim[1] * d3)]);\n  };\n};\n\n#endif\n\n#endif\n"
  },
  {
    "path": "man/abc.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/abc.R\n\\docType{methods}\n\\name{abc}\n\\alias{abc}\n\\alias{abc,missing-method}\n\\alias{abc,ANY-method}\n\\alias{abc,data.frame-method}\n\\alias{abc,pomp-method}\n\\alias{abc,probed_pomp-method}\n\\alias{abc,abcd_pomp-method}\n\\title{Approximate Bayesian computation}\n\\usage{\n\\S4method{abc}{data.frame}(\n  data,\n  ...,\n  Nabc = 1,\n  proposal,\n  scale,\n  epsilon,\n  probes,\n  params,\n  rinit,\n  rprocess,\n  rmeasure,\n  dprior,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{abc}{pomp}(\n  data,\n  ...,\n  Nabc = 1,\n  proposal,\n  scale,\n  epsilon,\n  probes,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{abc}{probed_pomp}(data, ..., probes, verbose = getOption(\"verbose\", FALSE))\n\n\\S4method{abc}{abcd_pomp}(\n  data,\n  ...,\n  Nabc,\n  proposal,\n  scale,\n  epsilon,\n  probes,\n  verbose = getOption(\"verbose\", FALSE)\n)\n}\n\\arguments{\n\\item{data}{either a data frame holding the time series data,\nor an object of class \\sQuote{pomp},\ni.e., the output of another \\pkg{pomp} calculation.\nInternally, \\code{data} will be coerced to an array with storage-mode \\code{double}.}\n\n\\item{...}{additional arguments are passed to \\code{\\link{pomp}}.\nThis allows one to set, unset, or modify \\link[=basic_components]{basic model components} within a call to this function.}\n\n\\item{Nabc}{the number of ABC iterations to perform.}\n\n\\item{proposal}{optional function that draws from the proposal\ndistribution.  Currently, the proposal distribution must be symmetric for\nproper inference: it is the user's responsibility to ensure that it is.\nSeveral functions that construct appropriate proposal function are\nprovided: see \\link[=proposals]{MCMC proposals} for more information.}\n\n\\item{scale}{named numeric vector of scales.}\n\n\\item{epsilon}{ABC tolerance.}\n\n\\item{probes}{a single probe or a list of one or more probes.\nA probe is simply a scalar- or vector-valued function of one argument that can be applied to the data array of a \\sQuote{pomp}.\nA vector-valued probe must always return a vector of the same size.\nA number of useful probes are provided with the package:\nsee \\link[=basic_probes]{basic probes}.}\n\n\\item{params}{optional; named numeric vector of parameters.\nThis will be coerced internally to storage mode \\code{double}.}\n\n\\item{rinit}{simulator of the initial-state distribution.\nThis can be furnished either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rinit=NULL} sets the initial-state simulator to its default.\nFor more information, see \\link[=rinit_spec]{rinit specification}.}\n\n\\item{rprocess}{simulator of the latent state process, specified using one of the \\link[=rprocess_spec]{rprocess plugins}.\nSetting \\code{rprocess=NULL} removes the latent-state simulator.\nFor more information, see \\link[=rprocess_spec]{rprocess specification for the documentation on these plugins}.}\n\n\\item{rmeasure}{simulator of the measurement model, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rmeasure=NULL} removes the measurement model simulator.\nFor more information, see \\link[=rmeasure_spec]{rmeasure specification}.}\n\n\\item{dprior}{optional; prior distribution density evaluator, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nFor more information, see \\link[=prior_spec]{prior specification}.\nSetting \\code{dprior=NULL} resets the prior distribution to its default, which is a flat improper prior.}\n\n\\item{verbose}{logical; if \\code{TRUE}, diagnostic messages will be printed to the console.}\n}\n\\description{\nThe approximate Bayesian computation (ABC) algorithm for estimating the parameters of a partially-observed Markov process.\n}\n\\section{Running ABC}{\n\n\n\\code{abc} returns an object of class \\sQuote{abcd_pomp}.\nOne or more \\sQuote{abcd_pomp} objects can be joined to form an \\sQuote{abcList} object.\n}\n\n\\section{Re-running ABC iterations}{\n\n\nTo re-run a sequence of ABC iterations, one can use the \\code{abc} method on a \\sQuote{abcd_pomp} object.\nBy default, the same parameters used for the original ABC run are re-used (except for \\code{verbose}, the default of which is shown above).\nIf one does specify additional arguments, these will override the defaults.\n}\n\n\\section{Continuing ABC iterations}{\n\n\nOne can continue a series of ABC iterations from where one left off using the \\code{continue} method.\nA call to \\code{abc} to perform \\code{Nabc=m} iterations followed by a call to \\code{continue} to perform \\code{Nabc=n} iterations will produce precisely the same effect as a single call to \\code{abc} to perform \\code{Nabc=m+n} iterations.\nBy default, all the algorithmic parameters are the same as used in the original call to \\code{abc}.\nAdditional arguments will override the defaults.\n}\n\n\\section{Methods}{\n\nThe following can be applied to the output of an \\code{abc} operation:\n\\describe{\n\\item{\\code{abc}}{repeats the calculation, beginning with the last state}\n\\item{\\code{\\link{continue}}}{continues the \\code{abc} calculation}\n\\item{\\code{plot}}{produces a series of diagnostic plots}\n\\item{\\code{\\link{traces}}}{produces an \\code{\\link[coda]{mcmc}} object, to which the various \\pkg{coda} convergence diagnostics can be applied}\n}\n}\n\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\references{\n\\Marin2012\n\n\\Toni2010\n\n\\Toni2009\n}\n\\seealso{\nMore on methods based on summary statistics:\n\\code{\\link{basic_probes}},\n\\code{\\link{nlf}},\n\\code{\\link{probe}()},\n\\code{\\link{probe_match}},\n\\code{\\link{spect}()},\n\\code{\\link{spect_match}}\n\nMore on \\pkg{pomp} estimation algorithms:\n\\code{\\link{bsmc2}()},\n\\code{\\link{estimation_algorithms}},\n\\code{\\link{mif2}()},\n\\code{\\link{nlf}},\n\\code{\\link{pmcmc}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{probe_match}},\n\\code{\\link{spect_match}}\n\nMore on Markov chain Monte Carlo methods:\n\\code{\\link{pmcmc}()},\n\\code{\\link{proposals}}\n\nMore on Bayesian methods:\n\\code{\\link{bsmc2}()},\n\\code{\\link{dprior}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{prior_spec}},\n\\code{\\link{rprior}()}\n}\n\\author{\nEdward L. Ionides, Aaron A. King\n}\n\\concept{Bayesian methods}\n\\concept{MCMC methods}\n\\concept{approximate Bayesian computation}\n\\concept{estimation methods}\n\\concept{summary statistic-based methods}\n"
  },
  {
    "path": "man/accumvars.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/accumulators.R\n\\name{accumvars}\n\\alias{accumvars}\n\\title{accumulator variables}\n\\description{\nLatent state variables that accumulate quantities through time.\n}\n\\details{\nIn formulating models, one sometimes wishes to define a state variable that will accumulate some quantity over the interval between successive observations.\n\\pkg{pomp} provides a facility to make such features more convenient.\nSpecifically, if \\eqn{a} is a state-variable named in the \\code{pomp}'s \\code{accumvars} argument, then for each interval \\eqn{(t_k,t_{k+1})}{(t[k],t[k+1])}, \\eqn{k=0,1,2,\\dots}, \\eqn{a} will be set to zero at prior to any \\code{\\link{rprocess}} computation over that interval.\nDeterministic trajectory computation is handled slightly differently:\nsee \\code{\\link{flow}}.\nFor examples, see \\code{\\link{sir}} and the tutorials on the \\href{https://kingaa.github.io/pomp/}{package website}.\n}\n\\examples{\n\\donttest{\n  ## A simple SIR model.\n\n  ewmeas |>\n    subset(time < 1952) |>\n    pomp(\n      times=\"time\",t0=1948,\n      rprocess=euler(\n        Csnippet(\"\n        int nrate = 6;\n        double rate[nrate];     // transition rates\n        double trans[nrate];    // transition numbers\n        double dW;\n\n        // gamma noise, mean=dt, variance=(sigma^2 dt)\n        dW = rgammawn(sigma,dt);\n\n        // compute the transition rates\n        rate[0] = mu*pop;       // birth into susceptible class\n        rate[1] = (iota+Beta*I*dW/dt)/pop; // force of infection\n        rate[2] = mu;           // death from susceptible class\n        rate[3] = gamma;        // recovery\n        rate[4] = mu;           // death from infectious class\n        rate[5] = mu;           // death from recovered class\n\n        // compute the transition numbers\n        trans[0] = rpois(rate[0]*dt);   // births are Poisson\n        reulermultinom(2,S,&rate[1],dt,&trans[1]);\n        reulermultinom(2,I,&rate[3],dt,&trans[3]);\n        reulermultinom(1,R,&rate[5],dt,&trans[5]);\n\n        // balance the equations\n        S += trans[0]-trans[1]-trans[2];\n        I += trans[1]-trans[3]-trans[4];\n        R += trans[3]-trans[5];\n      \"),\n      delta.t=1/52/20\n      ),\n      rinit=Csnippet(\"\n        double m = pop/(S_0+I_0+R_0);\n        S = nearbyint(m*S_0);\n        I = nearbyint(m*I_0);\n        R = nearbyint(m*R_0);\n    \"),\n    paramnames=c(\"mu\",\"pop\",\"iota\",\"gamma\",\"Beta\",\"sigma\",\n      \"S_0\",\"I_0\",\"R_0\"),\n    statenames=c(\"S\",\"I\",\"R\"),\n    params=c(mu=1/50,iota=10,pop=50e6,gamma=26,Beta=400,sigma=0.1,\n      S_0=0.07,I_0=0.001,R_0=0.93)\n    ) -> ew1\n\n  ew1 |>\n    simulate() |>\n    plot(variables=c(\"S\",\"I\",\"R\"))\n\n  ## A simple SIR model that tracks cumulative incidence.\n\n  ew1 |>\n    pomp(\n      rprocess=euler(\n        Csnippet(\"\n        int nrate = 6;\n        double rate[nrate];     // transition rates\n        double trans[nrate];    // transition numbers\n        double dW;\n\n        // gamma noise, mean=dt, variance=(sigma^2 dt)\n        dW = rgammawn(sigma,dt);\n\n        // compute the transition rates\n        rate[0] = mu*pop;       // birth into susceptible class\n        rate[1] = (iota+Beta*I*dW/dt)/pop; // force of infection\n        rate[2] = mu;           // death from susceptible class\n        rate[3] = gamma;        // recovery\n        rate[4] = mu;           // death from infectious class\n        rate[5] = mu;           // death from recovered class\n\n        // compute the transition numbers\n        trans[0] = rpois(rate[0]*dt);   // births are Poisson\n        reulermultinom(2,S,&rate[1],dt,&trans[1]);\n        reulermultinom(2,I,&rate[3],dt,&trans[3]);\n        reulermultinom(1,R,&rate[5],dt,&trans[5]);\n\n        // balance the equations\n        S += trans[0]-trans[1]-trans[2];\n        I += trans[1]-trans[3]-trans[4];\n        R += trans[3]-trans[5];\n        H += trans[3];          // cumulative incidence\n      \"),\n      delta.t=1/52/20\n      ),\n      rmeasure=Csnippet(\"\n        double mean = H*rho;\n        double size = 1/tau;\n        reports = rnbinom_mu(size,mean);\n    \"),\n    rinit=Csnippet(\"\n        double m = pop/(S_0+I_0+R_0);\n        S = nearbyint(m*S_0);\n        I = nearbyint(m*I_0);\n        R = nearbyint(m*R_0);\n        H = 0;\n    \"),\n    paramnames=c(\"mu\",\"pop\",\"iota\",\"gamma\",\"Beta\",\"sigma\",\"tau\",\"rho\",\n      \"S_0\",\"I_0\",\"R_0\"),\n    statenames=c(\"S\",\"I\",\"R\",\"H\"),\n    params=c(mu=1/50,iota=10,pop=50e6,gamma=26,\n      Beta=400,sigma=0.1,tau=0.001,rho=0.6,\n      S_0=0.07,I_0=0.001,R_0=0.93)\n    ) -> ew2\n\n  ew2 |>\n    simulate() |>\n    plot()\n\n  ## A simple SIR model that tracks weekly incidence.\n\n  ew2 |>\n    pomp(accumvars=\"H\") -> ew3\n\n  ew3 |>\n    simulate() |>\n    plot()\n\n}\n}\n\\seealso{\n\\code{\\link{sir}}\n\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{basic_components}},\n\\code{\\link{betabinomial}},\n\\code{\\link{covariates}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{userdata}},\n\\code{\\link{vmeasure_spec}}\n}\n\\concept{implementation information}\n"
  },
  {
    "path": "man/as_data_frame.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/as_data_frame.R\n\\docType{methods}\n\\name{as.data.frame}\n\\alias{as.data.frame}\n\\alias{as.data.frame.pomp}\n\\alias{as.data.frame.pfilterd_pomp}\n\\alias{as.data.frame.probed_pomp}\n\\alias{as.data.frame.kalmand_pomp}\n\\alias{as.data.frame.bsmcd_pomp}\n\\alias{as.data.frame.pompList}\n\\alias{as.data.frame.pfilterList}\n\\alias{as.data.frame.abcList}\n\\alias{as.data.frame.mif2List}\n\\alias{as.data.frame.pmcmcList}\n\\alias{as.data.frame.wpfilterd_pomp}\n\\title{Coerce to data frame}\n\\usage{\n\\method{as.data.frame}{pomp}(x, ...)\n\n\\method{as.data.frame}{pfilterd_pomp}(x, ...)\n\n\\method{as.data.frame}{probed_pomp}(x, ...)\n\n\\method{as.data.frame}{kalmand_pomp}(x, ...)\n\n\\method{as.data.frame}{bsmcd_pomp}(x, ...)\n\n\\method{as.data.frame}{pompList}(x, ...)\n\n\\method{as.data.frame}{pfilterList}(x, ...)\n\n\\method{as.data.frame}{abcList}(x, ...)\n\n\\method{as.data.frame}{mif2List}(x, ...)\n\n\\method{as.data.frame}{pmcmcList}(x, ...)\n\n\\method{as.data.frame}{wpfilterd_pomp}(x, ...)\n}\n\\arguments{\n\\item{x}{any \\R object.}\n\n\\item{...}{additional arguments to be passed to or from methods.}\n}\n\\description{\nAll \\pkg{pomp} model objects can be recast as data frames.\nThe contents of the resulting data frame depend on the nature of the object.\n}\n\\details{\nWhen \\code{object} is a simple \\sQuote{pomp} object,\n\\code{as(object,\"data.frame\")} or \\code{as.data.frame(object)} results in a\ndata frame with the times, observables, states (if known), and\ninterpolated covariates (if any).\n\nWhen \\code{object} is a \\sQuote{pfilterd_pomp} object,\ncoercion to a data frame results in a data frame with the same content as for a simple \\sQuote{pomp},\nbut with conditional log likelihood and effective sample size estimates included, as well as filtering means, prediction means, and prediction variances, if these have been computed.\n\nWhen \\code{object} is a \\sQuote{probed_pomp} object,\ncoercion to a data frame results in a data frame with the values of the probes computed on the data and on simulations.\n\nWhen \\code{object} is a \\sQuote{kalmand_pomp} object,\ncoercion to a data frame results in a data frame with prediction means, filter means and forecasts, in addition to the data.\n\nWhen \\code{object} is a \\sQuote{bsmcd_pomp} object,\ncoercion to a data frame results in a data frame with samples from the prior and posterior distribution.\nThe \\code{.id} variable distinguishes them.\n\nWhen \\code{object} is a \\sQuote{wpfilterd_pomp} object,\ncoercion to a data frame results in a data frame with the same content as for a simple \\sQuote{pomp},\nbut with conditional log likelihood and effective sample size estimates included.\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/as_pomp.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/as_pomp.R\n\\docType{methods}\n\\name{as_pomp}\n\\alias{as_pomp}\n\\title{as.pomp}\n\\usage{\nas_pomp(object, ...)\n}\n\\arguments{\n\\item{object}{the object to be coerced}\n\n\\item{\\dots}{additional arguments}\n}\n\\description{\nCoerce to a \\sQuote{pomp} object\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/bake.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/bake.R\n\\name{reproducibility_tools}\n\\alias{reproducibility_tools}\n\\alias{bake}\n\\alias{stew}\n\\alias{freeze}\n\\alias{append_data}\n\\title{Tools for reproducible computations}\n\\usage{\nbake(\n  file,\n  expr,\n  seed = NULL,\n  kind = NULL,\n  normal.kind = NULL,\n  dependson = NULL,\n  info = FALSE,\n  timing = TRUE,\n  dir = getOption(\"pomp_archive_dir\", getwd())\n)\n\nstew(\n  file,\n  expr,\n  seed = NULL,\n  kind = NULL,\n  normal.kind = NULL,\n  dependson = NULL,\n  info = FALSE,\n  timing = TRUE,\n  dir = getOption(\"pomp_archive_dir\", getwd())\n)\n\nfreeze(\n  expr,\n  seed = NULL,\n  kind = NULL,\n  normal.kind = NULL,\n  envir = parent.frame(),\n  enclos = if (is.list(envir) || is.pairlist(envir)) parent.frame() else baseenv()\n)\n\nappend_data(\n  data,\n  file,\n  overwrite = FALSE,\n  dir = getOption(\"pomp_archive_dir\", getwd())\n)\n}\n\\arguments{\n\\item{file}{Name of the archive file in which the result will be stored or retrieved, as appropriate.\nFor \\code{bake}, this will contain a single object and hence be an RDS file (extension \\sQuote{rds});\nfor \\code{stew}, this will contain one or more named objects and hence be an RDA file (extension \\sQuote{rda});\nfor \\code{append_data}, this will be a CSV file.}\n\n\\item{expr}{Expression to be evaluated.}\n\n\\item{seed, kind, normal.kind}{optional.\nTo set the state and of the RNG.\nThe default, \\code{seed = NULL}, will not change the RNG state.\n\\code{seed} should be a single integer.\nSee \\code{\\link{set.seed}} for more information.}\n\n\\item{dependson}{arbitrary \\R object (optional).\nVariables on which the computation in \\code{expr} depends.\nA hash of these objects will be archived in \\code{file}, along with the results of evaluation \\code{expr}.\nWhen \\code{bake} or \\code{stew} are called and \\code{file} exists, the hash of these objects will be compared against the archived hash;\nrecomputation is forced when these do not match.\nThe dependencies should be specified as unquoted symbols:\nuse a list if there are multiple dependencies.\nSee the note below about avoiding using \\sQuote{pomp} objects as dependencies.}\n\n\\item{info}{logical.\nIf \\code{TRUE}, the \\dQuote{ingredients} of the calculation are returned as a list.\nIn the case of \\code{bake}, this list is the \\dQuote{ingredients} attribute of the returned object.\nIn the case of \\code{stew}, this list is a hidden object named \\dQuote{.ingredients}, located in the environment within which \\code{stew} was called.}\n\n\\item{timing}{logical.\nIf \\code{TRUE}, the time required for the computation is returned.\nThis is returned as the \\dQuote{system.time} attribute of the returned object.}\n\n\\item{dir}{Directory holding archive files;\nby default, this is the current working directory.\nThis can also be set using the global option \\code{pomp_archive_dir}.\nIf it does not exist, this directory will be created (with a message).}\n\n\\item{envir}{the \\code{\\link[base]{environment}} in which \\code{expr} is to\n    be evaluated.  May also be \\code{NULL}, a list, a data frame,\n    a pairlist or an integer as specified to \\code{\\link[base]{sys.call}}.}\n\n\\item{enclos}{relevant when \\code{envir} is a (pair)list or a data frame.\n    Specifies the enclosure, i.e., where \\R looks for objects not found\n    in \\code{envir}.  This can be \\code{NULL} (interpreted as the base\n    package environment, \\code{\\link[base]{baseenv}()}) or an environment.}\n\n\\item{data}{data frame}\n\n\\item{overwrite}{logical; if \\code{TRUE}, \\code{data} are written to \\code{file}, replacing any existing contents.\nIf \\code{FALSE}, the \\code{data} is appended to the existing contents of \\code{file}.}\n}\n\\value{\n\\code{bake} returns the value of the evaluated expression \\code{expr}.\nOther objects created in the evaluation of \\code{expr} are discarded along with the temporary, local environment created for the evaluation.\n\nThe latter behavior differs from that of \\code{stew}, which returns the names of the objects created during the evaluation of \\code{expr}.\nAfter \\code{stew} completes, these objects are copied into the environment in which \\code{stew} was called.\n\n\\code{freeze} returns the value of evaluated expression \\code{expr}.\nHowever, \\code{freeze} evaluates \\code{expr} within the parent environment, so other objects created in the evaluation of \\code{expr} will therefore exist after \\code{freeze} completes.\n\n\\code{bake} and \\code{stew} store information about the code executed, the dependencies, and the state of the random-number generator in the archive file.\nIn the case of \\code{bake}, this is recorded in the \\dQuote{ingredients} attribute (\\code{attr(.,\"ingredients\")});\nin the \\code{stew} case, this is recorded in an object, \\dQuote{.ingredients}, in the archive.\nThis information is returned only if \\code{info=TRUE}.\n\nThe time required for execution is also recorded.\n\\code{bake} stores this in the \\dQuote{system.time} attribute of the archived \\R object;\n\\code{stew} does so in a hidden variable named \\code{.system.time}.\nThe timing is obtained using \\code{\\link{system.time}}.\n\n\\code{append_data} returns a data frame containing the new contents of \\code{file}, invisibly.\n}\n\\description{\nArchiving of computations and control of the random-number generator.\n}\n\\details{\nOn cooking shows, recipes requiring lengthy baking or stewing are prepared beforehand.\nThe \\code{bake} and \\code{stew} functions perform analogously:\nan computation is performed and archived in a named file.\nIf the function is called again and the file is present, the computation is not executed.\nInstead, the results are loaded from the archive.\nMoreover, via their optional \\code{seed} argument, \\code{bake} and \\code{stew} can control the pseudorandom-number generator (RNG) for greater reproducibility.\nAfter the computation is finished, these functions restore the pre-existing RNG state to avoid side effects.\n\nThe \\code{freeze} function doesn't save results, but does set the RNG state to the specified value and restore it after the computation is complete.\n\nBoth \\code{bake} and \\code{stew} first test to see whether \\code{file} exists.\nIf it does, \\code{bake} reads it using \\code{\\link{readRDS}} and returns the resulting object.\nBy contrast, \\code{stew} loads the file using \\code{\\link{load}} and copies the objects it contains into the user's workspace (or the environment of the call to \\code{stew}).\n\nIf \\code{file} does not exist, then both \\code{bake} and \\code{stew} evaluate the expression \\code{expr};\nthey differ in the results that they save.\n\\code{bake} saves the value of the evaluated expression to \\code{file} as a single object.\nThe name of that object is not saved.\nBy contrast, \\code{stew} creates a local environment within which \\code{expr} is evaluated; all objects in that environment are saved (by name) in \\code{file}.\n\\code{bake} and \\code{stew} also store information about the code executed, the dependencies, and the state of the random-number generator (if the latter is controlled) in the archive file.\nRe-computation is triggered if any of these things change.\n}\n\\section{Avoid using \\sQuote{pomp} objects as dependencies}{\n\nNote that when a \\sQuote{pomp} object is built with one or more \\link[=Csnippet]{C snippets}, the resulting code is \\dQuote{salted} with a random element to prevent collisions in parallel computations.\nAs a result, two such \\sQuote{pomp} objects will never match perfectly, even if the codes and data used to construct them are identical.\nTherefore, avoid using \\sQuote{pomp} objects as dependencies in \\code{bake} and \\code{stew}.\n}\n\n\\section{Compatibility with older versions}{\n\nWith \\pkg{pomp} version 3.4.4.2, the behavior of \\code{bake} and \\code{stew} changed.\nIn particular, older versions did no dependency checking, and did not check to see whether \\code{expr} had changed.\nAccordingly, the archive files written by older versions have a format that is not compatible with the newer ones.\nWhen an archive file in the old format is encountered, it will be updated to the new format, with a warning message.\n\\strong{Note that this will overwrite existing archive files!}\nHowever, there will be no loss of information.\n}\n\n\\examples{\n\\dontrun{\n  bake(file=\"example1.rds\",{\n    x <- runif(1000)\n    mean(x)\n  })\n\n  bake(file=\"example1.rds\",{\n    x <- runif(1000)\n    mean(x)\n  })\n\n  bake(file=\"example1.rds\",{\n    a <- 3\n    x <- runif(1000)\n    mean(x)\n  })\n\n  a <- 5\n  b <- 2\n\n  stew(file=\"example2.rda\",\n    dependson=list(a,b),{\n      x <- runif(10)\n      y <- rnorm(n=10,mean=a*x+b,sd=2)\n    })\n\n  plot(x,y)\n\n  set.seed(11)\n  runif(2)\n  freeze(runif(3),seed=5886730)\n  runif(2)\n  freeze(runif(3),seed=5886730)\n  runif(2)\n\n  set.seed(11)\n  runif(2)\n  runif(2)\n  runif(2)\n\n}\n}\n\\author{\nAaron A. King\n}\n\\concept{reproducibility}\n"
  },
  {
    "path": "man/basic_components.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/basic_components.R\n\\name{basic_components}\n\\alias{basic_components}\n\\title{Basic POMP model components.}\n\\description{\nMathematically, the parts of a \\acronym{POMP} model include the latent-state process transition distribution, the measurement-process distribution, the initial-state distribution, and possibly a prior parameter distribution.\nAlgorithmically, each of these corresponds to at least two distinct operations.\nIn particular, for each of the above parts, one sometimes needs to make a random draw from the distribution and sometimes to evaluate the density function.\nAccordingly, for each such component, there are two basic model components, one prefixed by a \\sQuote{r}, the other by a \\sQuote{d}, following the usual \\R convention.\n}\n\\details{\nIn addition to the parts listed above, \\pkg{pomp} includes two additional basic model components: the deterministic skeleton, and parameter transformations that can be used to map the parameter space onto a Euclidean space for estimation purposes.\nThere are also basic model components for computing the mean and variance of the measurement process conditional on the latent-state process.\n\nThere are thus altogether twelve \\bold{basic model components}:\n\\enumerate{\n\\item \\link[=rprocess_spec]{rprocess}, which samples from the latent-state transition distribution,\n\\item \\link[=dprocess_spec]{dprocess}, which evaluates the latent-state transition density,\n\\item \\link[=rmeasure_spec]{rmeasure}, which samples from the measurement distribution,\n\\item \\link[=emeasure_spec]{emeasure}, which computes the conditional expectation of the measurements, given the latent states,\n\\item \\link[=vmeasure_spec]{vmeasure}, which computes the conditional covariance matrix of the measurements, given the latent states,\n\\item \\link[=dmeasure_spec]{dmeasure}, which evaluates the measurement density,\n\\item \\link[=prior_spec]{rprior}, which samples from the prior distribution,\n\\item \\link[=prior_spec]{dprior}, which evaluates the prior density,\n\\item \\link[=rinit_spec]{rinit}, which samples from the initial-state distribution,\n\\item \\link[=dinit_spec]{dinit}, which evaluates the initial-state density,\n\\item \\link[=skeleton_spec]{skeleton}, which evaluates the deterministic skeleton,\n\\item \\link[=parameter_trans]{partrans}, which evaluates the forward or inverse parameter transformations.\n}\n\nEach of these can be set or modified in the \\code{pomp} \\link[=pomp]{constructor function} or in any of the \\pkg{pomp} \\link[=elementary_algorithms]{elementary algorithms} or \\link[=estimation_algorithms]{estimation algorithms} using an argument that matches the basic model component.\nA basic model component can be unset by passing \\code{NULL} in the same way.\n\nHelp pages detailing each basic model component are provided.\n}\n\\seealso{\n\\link[=workhorses]{workhorse functions},\n\\link[=elementary_algorithms]{elementary algorithms},\n\\link[=estimation_algorithms]{estimation algorithms}.\n\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{accumvars}},\n\\code{\\link{betabinomial}},\n\\code{\\link{covariates}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{userdata}},\n\\code{\\link{vmeasure_spec}}\n}\n\\concept{basic model components}\n\\concept{implementation information}\n"
  },
  {
    "path": "man/basic_probes.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/basic_probes.R\n\\name{basic_probes}\n\\alias{basic_probes}\n\\alias{probe_mean}\n\\alias{probe_median}\n\\alias{probe_var}\n\\alias{probe_sd}\n\\alias{probe_period}\n\\alias{probe_quantile}\n\\alias{probe_acf}\n\\alias{probe_ccf}\n\\alias{probe_marginal}\n\\alias{probe_nlar}\n\\title{Useful probes for partially-observed Markov processes}\n\\usage{\nprobe_mean(var, trim = 0, transform = identity, na.rm = TRUE)\n\nprobe_median(var, na.rm = TRUE)\n\nprobe_var(var, transform = identity, na.rm = TRUE)\n\nprobe_sd(var, transform = identity, na.rm = TRUE)\n\nprobe_period(var, kernel.width, transform = identity)\n\nprobe_quantile(var, probs, ...)\n\nprobe_acf(\n  var,\n  lags,\n  type = c(\"covariance\", \"correlation\"),\n  transform = identity\n)\n\nprobe_ccf(\n  vars,\n  lags,\n  type = c(\"covariance\", \"correlation\"),\n  transform = identity\n)\n\nprobe_marginal(var, ref, order = 3, diff = 1, transform = identity)\n\nprobe_nlar(var, lags, powers, transform = identity)\n}\n\\arguments{\n\\item{var, vars}{character; the name(s) of the observed variable(s).}\n\n\\item{trim}{the fraction of observations to be trimmed (see \\code{\\link{mean}}).}\n\n\\item{transform}{transformation to be applied to the data before the probe is computed.}\n\n\\item{na.rm}{if \\code{TRUE}, remove all NA observations prior to computing the probe.}\n\n\\item{kernel.width}{width of modified Daniell smoothing kernel to be used\nin power-spectrum computation: see \\code{\\link[stats]{kernel}}.}\n\n\\item{probs}{the quantile or quantiles to compute: see \\code{\\link{quantile}}.}\n\n\\item{...}{additional arguments passed to the underlying algorithms.}\n\n\\item{lags}{In \\code{probe_ccf}, a vector of lags between time series.\nPositive lags correspond to \\code{x} advanced relative to \\code{y};\nnegative lags, to the reverse.\n\nIn \\code{probe_nlar}, a vector of lags present in the nonlinear\nautoregressive model that will be fit to the actual and simulated data.\nSee Details, below, for a precise description.}\n\n\\item{type}{Compute autocorrelation or autocovariance?}\n\n\\item{ref}{empirical reference distribution.  Simulated data will be\nregressed against the values of \\code{ref}, sorted and, optionally,\ndifferenced.  The resulting regression coefficients capture information\nabout the shape of the marginal distribution.  A good choice for \\code{ref}\nis the data itself.}\n\n\\item{order}{order of polynomial regression.}\n\n\\item{diff}{order of differencing to perform.}\n\n\\item{powers}{the powers of each term (corresponding to \\code{lags}) in the\nthe nonlinear autoregressive model that will be fit to the actual and\nsimulated data.  See Details, below, for a precise description.}\n}\n\\value{\nA call to any one of these functions returns a probe function,\nsuitable for use in \\code{\\link{probe}} or \\code{\\link{probe_objfun}}.  That\nis, the function returned by each of these takes a data array (such as\ncomes from a call to \\code{\\link{obs}}) as input and returns a single\nnumerical value.\n}\n\\description{\nSeveral simple and configurable probes are provided with in the package.\nThese can be used directly and as templates for custom probes.\n}\n\\references{\n\\Kendall1999\n\n\\Wood2010\n}\n\\seealso{\nMore on methods based on summary statistics:\n\\code{\\link{abc}()},\n\\code{\\link{nlf}},\n\\code{\\link{probe}()},\n\\code{\\link{probe_match}},\n\\code{\\link{spect}()},\n\\code{\\link{spect_match}}\n}\n\\author{\nDaniel C. Reuman, Aaron A. King\n}\n\\concept{diagnostics}\n\\concept{summary statistic-based methods}\n"
  },
  {
    "path": "man/betabinom.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/betabinom.R\n\\name{betabinomial}\n\\alias{betabinomial}\n\\alias{rbetabinom}\n\\alias{dbetabinom}\n\\title{Beta-binomial distribution}\n\\usage{\nrbetabinom(n = 1, size, prob, theta)\n\ndbetabinom(x, size, prob, theta, log = FALSE)\n}\n\\arguments{\n\\item{n}{integer; number of random variates to generate.}\n\n\\item{size}{\\code{size} parameter of the binomial distribution}\n\n\\item{prob}{mean of the Beta distribution}\n\n\\item{theta}{Beta distribution dispersion parameter}\n\n\\item{x}{vector of non-negative integer quantiles}\n\n\\item{log}{logical; if TRUE, return logarithm(s) of probabilities.}\n}\n\\value{\n\\item{rbetabinom}{\n   Returns a vector of length \\code{n} containing random variates drawn from the Beta-binomial distribution.\n}\n\\item{dbetabinom}{\n   Returns a vector (of length equal to the number of columns of \\code{x}) containing the probabilities of observing each column of \\code{x} given the specified parameters (\\code{size}, \\code{prob}, \\code{theta}).\n}\n}\n\\description{\nDensity and random generation for the Beta-binomial distribution with parameters \\code{size}, \\code{mu}, and \\code{theta}.\n}\n\\details{\nA variable \\eqn{X} is Beta-binomially distributed if\n\\eqn{X\\sim{\\mathrm{Binomial}(n,P)}}{X~{Binomial(n,P)}} where \\eqn{P\\sim{\\mathrm{Beta}(\\mu,\\theta)}}{P~Beta(mu,theta)}.\nUsing the standard \\eqn{(a,b)} parameterization, \\eqn{a=\\mu\\,\\theta}{a=mu*theta} and \\eqn{b=(1-\\mu)\\,\\theta}{b=(1-mu)*theta}.\n}\n\\section{C API}{\n\nAn interface for C codes using these functions is provided by the package.\nVisit the package homepage to view the \\href{https://kingaa.github.io/pomp/C_API.html}{\\pkg{pomp} C API document}.\n}\n\n\\seealso{\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{accumvars}},\n\\code{\\link{basic_components}},\n\\code{\\link{covariates}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{userdata}},\n\\code{\\link{vmeasure_spec}}\n}\n\\concept{implementation information}\n\\concept{probability distributions}\n"
  },
  {
    "path": "man/blowflies.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/blowflies.R\n\\docType{data}\n\\name{blowflies}\n\\alias{blowflies}\n\\alias{blowflies1}\n\\alias{blowflies2}\n\\title{Nicholson's blowflies.}\n\\usage{\nblowflies1(\n  P = 3.2838,\n  delta = 0.16073,\n  N0 = 679.94,\n  sigma.P = 1.3512,\n  sigma.d = 0.74677,\n  sigma.y = 0.026649\n)\n\nblowflies2(\n  P = 2.7319,\n  delta = 0.17377,\n  N0 = 800.31,\n  sigma.P = 1.442,\n  sigma.d = 0.76033,\n  sigma.y = 0.010846\n)\n}\n\\arguments{\n\\item{P}{reproduction parameter}\n\n\\item{delta}{death rate}\n\n\\item{N0}{population scale factor}\n\n\\item{sigma.P}{intensity of \\eqn{e} noise}\n\n\\item{sigma.d}{intensity of \\eqn{eps} noise}\n\n\\item{sigma.y}{measurement error s.d.}\n}\n\\value{\n\\code{blowflies1} and \\code{blowflies2} return \\sQuote{pomp} objects containing the actual data and two variants of the model.\n}\n\\description{\n\\code{blowflies} is a data frame containing the data from several of Nicholson's classic experiments with the Australian sheep blowfly, \\emph{Lucilia cuprina}.\n}\n\\details{\n\\code{blowflies1()} and \\code{blowflies2()} construct \\sQuote{pomp} objects encoding stochastic delay-difference equation models.\nThe data for these come from \"population I\", a control culture.\nThe experiment is described on pp. 163--4 of Nicholson (1957).\nUnlimited quantities of larval food were provided;\nthe adult food supply (ground liver) was constant at 0.4g per day.\nThe data were taken from the table provided by Brillinger et al. (1980).\n\nThe models are discrete delay equations:\n\\deqn{R(t+1) \\sim \\mathrm{Poisson}(P N(t-\\tau) \\exp{(-N(t-\\tau)/N_{0})} e(t+1) {\\Delta}t)}{R[t+1] ~ Poisson(P N[t-tau] exp(-N[t-tau]/N0) e[t+1] dt)}\n\\deqn{S(t+1) \\sim \\mathrm{Binomial}(N(t),\\exp{(-\\delta \\epsilon(t+1) {\\Delta}t)})}{S[t+1] ~ binomial(N[t],exp(-delta eps[t+1] dt))}\n\\deqn{N(t) = R(t)+S(t)}{N[t]=R[t]+S[t]}\nwhere \\eqn{e(t)}{e[t]} and \\eqn{\\epsilon(t)}{eps[t]} are Gamma-distributed i.i.d. random variables\nwith mean 1 and variances \\eqn{{\\sigma_P^2}/{{\\Delta}t}}{sigma.P^2/dt}, \\eqn{{\\sigma_d^2}/{{\\Delta}t}}{sigma.d^2/dt}, respectively.\n\\code{blowflies1} has a timestep (\\eqn{{\\Delta}t}{dt}) of 1 day; \\code{blowflies2} has a timestep of 2 days.\nThe process model in \\code{blowflies1} thus corresponds exactly to that studied by Wood (2010).\nThe measurement model in both cases is taken to be\n\\deqn{y(t) \\sim  \\mathrm{NegBin}(N(t),1/\\sigma_y^2)}{y[t] ~ negbin(N[t],1/sigma.y^2),}\ni.e., the observations are assumed to be negative-binomially distributed with\nmean \\eqn{N(t)}{N[t]} and variance \\eqn{N(t)+(\\sigma_y N(t))^2}{N[t]+(sigma.y N[t])^2}.\n\nDefault parameter values are the MLEs as estimated by Ionides (2011).\n}\n\\examples{\n\nplot(blowflies1())\nplot(blowflies2())\n\n}\n\\references{\n\\Nicholson1957\n\n\\Xia2011\n\n\\Ionides2011\n\n\\Wood2010\n\n\\Gurney1980a\n\n\\Brillinger1980\n}\n\\seealso{\nMore examples provided with \\pkg{pomp}:\n\\code{\\link{childhood_disease_data}},\n\\code{\\link{compartmental_models}},\n\\code{\\link{dacca}()},\n\\code{\\link{ebola}},\n\\code{\\link{gompertz}()},\n\\code{\\link{ou2}()},\n\\code{\\link{pomp_examples}},\n\\code{\\link{ricker}()},\n\\code{\\link{rw2}()},\n\\code{\\link{verhulst}()}\n\nMore data sets provided with \\pkg{pomp}:\n\\code{\\link{bsflu}},\n\\code{\\link{childhood_disease_data}},\n\\code{\\link{dacca}()},\n\\code{\\link{ebola}},\n\\code{\\link{parus}}\n}\n\\concept{pomp datasets}\n\\concept{pomp examples}\n\\keyword{models}\n"
  },
  {
    "path": "man/bsflu.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/bsflu.R\n\\name{bsflu}\n\\alias{bsflu}\n\\title{Influenza outbreak in a boarding school}\n\\description{\nAn outbreak of influenza in an all-boys boarding school.\n}\n\\details{\nData are recorded from a 1978 flu outbreak in a closed population.\nThe variable \\sQuote{B} refers to boys confined to bed on the corresponding day and \\sQuote{C} to boys in convalescence,\ni.e., not yet allowed back to class.\nIn total, 763 boys were at risk of infection and, over the course of the outbreak, 512 boys spent between 3 and 7 days away from class (either in bed or convalescent).\nThe index case was a boy who arrived at school from holiday six days before the next case.\n}\n\\examples{\nif (require(tidyr) && require(ggplot2)) {\n\n  bsflu |>\n    gather(variable,value,-date,-day) |>\n    ggplot(aes(x=date,y=value,color=variable))+\n    geom_line()+\n    labs(y=\"number of boys\",title=\"boarding school flu outbreak\")+\n    theme_bw()\n\n}\n}\n\\references{\n\\Anonymous1978\n}\n\\seealso{\n\\link[=compartmental_models]{compartmental models}\n\nMore data sets provided with \\pkg{pomp}:\n\\code{\\link{blowflies}},\n\\code{\\link{childhood_disease_data}},\n\\code{\\link{dacca}()},\n\\code{\\link{ebola}},\n\\code{\\link{parus}}\n}\n\\concept{pomp datasets}\n"
  },
  {
    "path": "man/bsmc2.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/bsmc2.R\n\\docType{methods}\n\\name{bsmc2}\n\\alias{bsmc2}\n\\alias{bsmc2,missing-method}\n\\alias{bsmc2,ANY-method}\n\\alias{bsmc2,data.frame-method}\n\\alias{bsmc2,pomp-method}\n\\title{The Liu and West Bayesian particle filter}\n\\usage{\n\\S4method{bsmc2}{data.frame}(\n  data,\n  ...,\n  Np,\n  smooth = 0.1,\n  params,\n  rprior,\n  rinit,\n  rprocess,\n  dmeasure,\n  partrans,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{bsmc2}{pomp}(data, ..., Np, smooth = 0.1, verbose = getOption(\"verbose\", FALSE))\n}\n\\arguments{\n\\item{data}{either a data frame holding the time series data,\nor an object of class \\sQuote{pomp},\ni.e., the output of another \\pkg{pomp} calculation.\nInternally, \\code{data} will be coerced to an array with storage-mode \\code{double}.}\n\n\\item{...}{additional arguments are passed to \\code{\\link{pomp}}.\nThis allows one to set, unset, or modify \\link[=basic_components]{basic model components} within a call to this function.}\n\n\\item{Np}{the number of particles to use.\nThis may be specified as a single positive integer, in which case the same number of particles will be used at each timestep.\nAlternatively, if one wishes the number of particles to vary across timesteps, one may specify \\code{Np} either as a vector of positive integers of length \\preformatted{length(time(object,t0=TRUE))} or as a function taking a positive integer argument.\nIn the latter case, \\code{Np(k)} must be a single positive integer, representing the number of particles to be used at the \\code{k}-th timestep:\n\\code{Np(0)} is the number of particles to use going from \\code{timezero(object)} to \\code{time(object)[1]},\n\\code{Np(1)}, from \\code{timezero(object)} to \\code{time(object)[1]},\nand so on,\nwhile when \\code{T=length(time(object))}, \\code{Np(T)} is the number of particles to sample at the end of the time-series.}\n\n\\item{smooth}{Kernel density smoothing parameter.\nThe compensating shrinkage factor will be \\code{sqrt(1-smooth^2)}.\nThus, \\code{smooth=0} means that no noise will be added to parameters.\nThe general recommendation is that the value of \\code{smooth} should be chosen close to 0 (e.g., \\code{shrink} ~ 0.1).}\n\n\\item{params}{optional; named numeric vector of parameters.\nThis will be coerced internally to storage mode \\code{double}.}\n\n\\item{rprior}{optional; prior distribution sampler, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nFor more information, see \\link[=prior_spec]{prior specification}.\nSetting \\code{rprior=NULL} removes the prior distribution sampler.}\n\n\\item{rinit}{simulator of the initial-state distribution.\nThis can be furnished either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rinit=NULL} sets the initial-state simulator to its default.\nFor more information, see \\link[=rinit_spec]{rinit specification}.}\n\n\\item{rprocess}{simulator of the latent state process, specified using one of the \\link[=rprocess_spec]{rprocess plugins}.\nSetting \\code{rprocess=NULL} removes the latent-state simulator.\nFor more information, see \\link[=rprocess_spec]{rprocess specification for the documentation on these plugins}.}\n\n\\item{dmeasure}{evaluator of the measurement model density, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{dmeasure=NULL} removes the measurement density evaluator.\nFor more information, see \\link[=dmeasure_spec]{dmeasure specification}.}\n\n\\item{partrans}{optional parameter transformations, constructed using \\code{\\link{parameter_trans}}.\n\nMany algorithms for parameter estimation search an unconstrained space of parameters.\nWhen working with such an algorithm and a model for which the parameters are constrained, it can be useful to transform parameters.\nOne should supply the \\code{partrans} argument via a call to \\code{\\link{parameter_trans}}.\nFor more information, see \\link[=parameter_trans]{parameter_trans}.\nSetting \\code{partrans=NULL} removes the parameter transformations, i.e., sets them to the identity transformation.}\n\n\\item{verbose}{logical; if \\code{TRUE}, diagnostic messages will be printed to the console.}\n}\n\\value{\nAn object of class \\sQuote{bsmcd_pomp}.\nThe following methods are avaiable:\n\\describe{\n\\item{\\code{\\link[=plot,bsmcd_pomp-method]{plot}}}{produces diagnostic plots}\n\\item{\\code{\\link{as.data.frame}}}{puts the prior and posterior samples into a data frame}\n}\n}\n\\description{\nModified version of the Liu & West (2001) algorithm.\n}\n\\details{\n\\code{bsmc2} uses a version of the original algorithm (Liu & West 2001), but discards the auxiliary particle filter.\nThe modification appears to give superior performance for the same amount of effort.\n\nSamples from the prior distribution are drawn using the \\code{rprior} component.\nThis is allowed to depend on elements of \\code{params}, i.e., some of the elements of \\code{params} can be treated as \\dQuote{hyperparameters}.\n\\code{Np} draws are made from the prior distribution.\n}\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\references{\n\\Liu2001b\n}\n\\seealso{\nMore on Bayesian methods:\n\\code{\\link{abc}()},\n\\code{\\link{dprior}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{prior_spec}},\n\\code{\\link{rprior}()}\n\nMore on full-information (i.e., likelihood-based) methods:\n\\code{\\link{mif2}()},\n\\code{\\link{pfilter}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{wpfilter}()}\n\nMore on sequential Monte Carlo methods:\n\\code{\\link{cond_logLik}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{kalman}},\n\\code{\\link{mif2}()},\n\\code{\\link{pfilter}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{wpfilter}()}\n\nMore on \\pkg{pomp} estimation algorithms:\n\\code{\\link{abc}()},\n\\code{\\link{estimation_algorithms}},\n\\code{\\link{mif2}()},\n\\code{\\link{nlf}},\n\\code{\\link{pmcmc}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{probe_match}},\n\\code{\\link{spect_match}}\n}\n\\author{\nMichael Lavine, Matthew Ferrari, Aaron A. King, Edward L. Ionides\n}\n\\concept{Bayesian methods}\n\\concept{estimation methods}\n\\concept{full-information methods}\n\\concept{particle filter methods}\n"
  },
  {
    "path": "man/bsplines.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/bsplines.R\n\\name{bsplines}\n\\alias{bsplines}\n\\alias{bspline_basis}\n\\alias{periodic_bspline_basis}\n\\title{B-spline bases}\n\\usage{\nbspline_basis(x, nbasis, degree = 3, deriv = 0, names = NULL, rg = range(x))\n\nperiodic_bspline_basis(\n  x,\n  nbasis,\n  degree = 3,\n  period = 1,\n  deriv = 0,\n  names = NULL\n)\n}\n\\arguments{\n\\item{x}{Vector at which the spline functions are to be evaluated.}\n\n\\item{nbasis}{The number of basis functions to return.}\n\n\\item{degree}{Degree of requested B-splines.}\n\n\\item{deriv}{The order of the derivative required.}\n\n\\item{names}{optional; the names to be given to the basis functions.  These\nwill be the column-names of the matrix returned.  If the names are\nspecified as a format string (e.g., \"basis\\%d\"), \\code{\\link{sprintf}} will\nbe used to generate the names from the column number.  If a single\nnon-format string is specified, the names will be generated by\n\\code{\\link{paste}}-ing \\code{name} to the column number.  One can also\nspecify each column name explicitly by giving a length-\\code{nbasis} string\nvector.  By default, no column-names are given.}\n\n\\item{rg}{numeric of length 2; range of the B-spline basis.\nTo be properly specified, we must have \\code{rg[1] < rg[2]}.}\n\n\\item{period}{The period of the requested periodic B-splines.}\n}\n\\value{\n\\item{bspline_basis}{ Returns a matrix with \\code{length(x)} rows\nand \\code{nbasis} columns.  Each column contains the values one of the\nspline basis functions.}\n\\item{periodic_bspline_basis}{ Returns a matrix with \\code{length(x)} rows\nand \\code{nbasis} columns.  The basis functions returned are periodic with\nperiod \\code{period}.}\nIf \\code{deriv>0}, the derivative of that order of each of the corresponding spline basis functions are returned.\n}\n\\description{\nThese functions generate B-spline basis functions.\n\\code{bspline_basis} gives a basis of spline functions.\n\\code{periodic_bspline_basis} gives a\nbasis of periodic spline functions.\n}\n\\section{C API}{\n\nAccess to the underlying C routines is available: see\n\\href{https://kingaa.github.io/pomp/C_API.html}{the \\pkg{pomp} C API document}.\nfor definition and documentation of the C API.\n}\n\n\\examples{\n\nx <- seq(0,2,by=0.01)\ny <- bspline_basis(x,degree=3,nbasis=9,names=\"basis\")\nmatplot(x,y,type='l',ylim=c(0,1.1))\nlines(x,apply(y,1,sum),lwd=2)\n\nx <- seq(-1,2,by=0.01)\ny <- periodic_bspline_basis(x,nbasis=5,names=\"spline\\%d\")\nmatplot(x,y,type='l')\n\n}\n\\seealso{\nMore on interpolation:\n\\code{\\link{covariates}},\n\\code{\\link{lookup}()}\n}\n\\author{\nAaron A. King\n}\n\\concept{interpolation}\n\\concept{splines}\n\\keyword{smooth}\n"
  },
  {
    "path": "man/childhood.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/childhood.R\n\\docType{data}\n\\name{childhood_disease_data}\n\\alias{childhood_disease_data}\n\\alias{LondonYorke}\n\\alias{ewmeas}\n\\alias{ewcitmeas}\n\\title{Historical childhood disease incidence data}\n\\description{\n\\code{LondonYorke} is a data frame containing the monthly number of reported cases of chickenpox, measles, and mumps from two American cities (Baltimore and New York) in the mid-20th century (1928--1972).\n\n\\code{ewmeas} and \\code{ewcitmeas} are data frames containing weekly reported cases of measles in England and Wales.\n\\code{ewmeas} records the total measles reports for the whole country, 1948--1966.\nOne questionable data point has been replaced with an NA.\n\\code{ewcitmeas} records the incidence in seven English cities 1948--1987.\nThese data were kindly provided by Ben Bolker, who writes:\n\\dQuote{Most of these data have been manually entered from published records by various people, and are prone to errors at several levels.\nAll data are provided as is; use at your own risk.}\n}\n\\examples{\n\nplot(cases~time,data=LondonYorke,subset=disease==\"measles\",type='n',main=\"measles\",bty='l')\nlines(cases~time,data=LondonYorke,subset=disease==\"measles\"&town==\"Baltimore\",col=\"red\")\nlines(cases~time,data=LondonYorke,subset=disease==\"measles\"&town==\"New York\",col=\"blue\")\nlegend(\"topright\",legend=c(\"Baltimore\",\"New York\"),lty=1,col=c(\"red\",\"blue\"),bty='n')\n\nplot(\n     cases~time,\n     data=LondonYorke,\n     subset=disease==\"chickenpox\"&town==\"New York\",\n     type='l',col=\"blue\",main=\"chickenpox, New York\",\n     bty='l'\n    )\n\nplot(\n     cases~time,\n     data=LondonYorke,\n     subset=disease==\"mumps\"&town==\"New York\",\n     type='l',col=\"blue\",main=\"mumps, New York\",\n     bty='l'\n    )\n\nplot(reports~time,data=ewmeas,type='l')\n\nplot(reports~date,data=ewcitmeas,subset=city==\"Liverpool\",type='l')\n\n}\n\\references{\n\\London1973\n}\n\\seealso{\n\\link[=compartmental_models]{compartmental models}, \\code{\\link{bsflu}}\n\nMore data sets provided with \\pkg{pomp}:\n\\code{\\link{blowflies}},\n\\code{\\link{bsflu}},\n\\code{\\link{dacca}()},\n\\code{\\link{ebola}},\n\\code{\\link{parus}}\n\nMore examples provided with \\pkg{pomp}:\n\\code{\\link{blowflies}},\n\\code{\\link{compartmental_models}},\n\\code{\\link{dacca}()},\n\\code{\\link{ebola}},\n\\code{\\link{gompertz}()},\n\\code{\\link{ou2}()},\n\\code{\\link{pomp_examples}},\n\\code{\\link{ricker}()},\n\\code{\\link{rw2}()},\n\\code{\\link{verhulst}()}\n}\n\\concept{pomp datasets}\n\\concept{pomp examples}\n"
  },
  {
    "path": "man/coef.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/coef.R, R/objfun.R\n\\docType{methods}\n\\name{coef}\n\\alias{coef}\n\\alias{coef<-}\n\\alias{coef<-,missing-method}\n\\alias{coef,listie-method}\n\\alias{coef,pomp-method}\n\\alias{coef<-,pomp-method}\n\\alias{coef,objfun-method}\n\\alias{coef<-,objfun-method}\n\\title{Extract, set, or alter coefficients}\n\\usage{\n\\S4method{coef}{listie}(object, ...)\n\n\\S4method{coef}{pomp}(object, pars, transform = FALSE, ...)\n\n\\S4method{coef}{pomp}(object, pars, transform = FALSE, ...) <- value\n\n\\S4method{coef}{objfun}(object, ...)\n\n\\S4method{coef}{objfun}(object, pars, transform = FALSE, ...) <- value\n}\n\\arguments{\n\\item{object}{an object of class \\sQuote{pomp}, or of a class extending \\sQuote{pomp}}\n\n\\item{\\dots}{ignored or passed to the more primitive function}\n\n\\item{pars}{optional character; names of parameters to be retrieved or set.}\n\n\\item{transform}{logical; perform parameter transformation?}\n\n\\item{value}{numeric vector or list; values to be assigned.\nIf \\code{value = NULL}, the parameters are unset.}\n}\n\\description{\nExtract, set, or modify the estimated parameters from a fitted model.\n}\n\\details{\n\\code{coef} allows one to extract the parameters from a fitted model.\n\n\\code{coef(object,transform=TRUE)} returns the parameters transformed onto\nthe estimation scale.\n\n\\code{coef(object) <- value} sets or alters the coefficients of a\n\\sQuote{pomp} object.\n\n\\code{coef(object,transform=TRUE) <- value} assumes that \\code{value} is on\nthe estimation scale, and applies the \\dQuote{from estimation scale}\nparameter transformation from \\code{object} before altering the\ncoefficients.\n}\n\\seealso{\nOther extraction methods: \n\\code{\\link{cond_logLik}()},\n\\code{\\link{covmat}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{forecast}()},\n\\code{\\link{logLik}},\n\\code{\\link{obs}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{spy}()},\n\\code{\\link{states}()},\n\\code{\\link{summary}()},\n\\code{\\link{time}()},\n\\code{\\link{timezero}()},\n\\code{\\link{traces}()}\n}\n\\concept{extraction methods}\n"
  },
  {
    "path": "man/conc.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/conc.R\n\\name{conc}\n\\alias{conc}\n\\alias{conc,Pomp-method}\n\\alias{conc,Pfilter-method}\n\\alias{conc,Abc-method}\n\\alias{conc,Mif2-method}\n\\alias{conc,Pmcmc-method}\n\\title{Concatenate}\n\\usage{\n\\S4method{conc}{Pomp}(...)\n\n\\S4method{conc}{Pfilter}(...)\n\n\\S4method{conc}{Abc}(...)\n\n\\S4method{conc}{Mif2}(...)\n\n\\S4method{conc}{Pmcmc}(...)\n}\n\\description{\nInternal methods to concatenate objects into useful listie.\n}\n\\details{\nNot exported.\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/concat.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/concat.R\n\\name{concat}\n\\alias{concat}\n\\alias{c}\n\\alias{c.Pomp}\n\\title{Concatenate}\n\\usage{\n\\method{c}{Pomp}(...)\n\nconcat(...)\n}\n\\arguments{\n\\item{...}{elements to be recursively combined into a \\sQuote{listie}}\n}\n\\description{\nConcatenate two or more \\sQuote{pomp} objects into a list-like \\sQuote{listie}.\n}\n\\details{\n\\code{concat} applied to one or more \\sQuote{pomp} objects or lists of \\sQuote{pomp} objects converts the list into a \\sQuote{listie}.\nIn particular, \\code{concat(A,B,C)} is equivalent to \\code{do.call(c,unlist(list(A,B,C)))}.\n}\n\\examples{\ngompertz(sigma=2,tau=1) -> g\nNp <- c(low=100,med=1000,high=10000)\nlapply(\n  Np,\n  \\(np) pfilter(g,Np=np)\n) |>\n  concat() -> pfs\n\npfs\ncoef(pfs)\nlogLik(pfs)\neff_sample_size(pfs)\ncond_logLik(pfs)\n\npfs |> plot()\n}\n"
  },
  {
    "path": "man/cond_logLik.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/cond_logLik.R\n\\docType{methods}\n\\name{cond_logLik}\n\\alias{cond_logLik}\n\\alias{cond_logLik,missing-method}\n\\alias{cond_logLik,ANY-method}\n\\alias{cond_logLik,kalmand_pomp-method}\n\\alias{cond_logLik,pfilterd_pomp-method}\n\\alias{cond_logLik,wpfilterd_pomp-method}\n\\alias{cond_logLik,bsmcd_pomp-method}\n\\alias{cond_logLik,pfilterList-method}\n\\title{Conditional log likelihood}\n\\usage{\n\\S4method{cond_logLik}{kalmand_pomp}(object, ..., format = c(\"numeric\", \"data.frame\"))\n\n\\S4method{cond_logLik}{pfilterd_pomp}(object, ..., format = c(\"numeric\", \"data.frame\"))\n\n\\S4method{cond_logLik}{wpfilterd_pomp}(object, ..., format = c(\"numeric\", \"data.frame\"))\n\n\\S4method{cond_logLik}{bsmcd_pomp}(object, ..., format = c(\"numeric\", \"data.frame\"))\n\n\\S4method{cond_logLik}{pfilterList}(object, ..., format = c(\"numeric\", \"data.frame\"))\n}\n\\arguments{\n\\item{object}{result of a filtering computation}\n\n\\item{...}{ignored}\n\n\\item{format}{format of the returned object}\n}\n\\value{\nThe numerical value of the conditional log likelihood.\nNote that some methods compute not the log likelihood itself but instead a related quantity.\nTo keep the code simple, the \\code{cond_logLik} function is nevertheless used to extract this quantity.\n\nWhen \\code{object} is of class \\sQuote{bsmcd_pomp}\n(i.e., the result of a \\code{bsmc2} computation),\n\\code{cond_logLik} returns the conditional log \\dQuote{evidence}\n(see \\code{\\link{bsmc2}}).\n}\n\\description{\nThe estimated conditional log likelihood from a fitted model.\n}\n\\details{\nThe conditional likelihood is defined to be the value of the density\nof \\deqn{Y(t_k) | Y(t_1),\\dots,Y(t_{k-1})}{Yk | Y1,\\dots,Y(k-1)} evaluated at \\eqn{Y(t_k) = y^*_k}{Yk = yk*}.\nHere, \\eqn{Y(t_k)}{Yk} is the observable process, and \\eqn{y^*_k}{yk*} the data, at time \\eqn{t_k}.\n\nThus the conditional log likelihood at time \\eqn{t_k} is\n\\deqn{\\ell_k(\\theta) = \\log f[Y(t_k)=y^*_k \\vert Y(t_1)=y^*_1, \\dots, Y(t_{k-1})=y^*_{k-1}],}{ell_k(theta)=log f[Yk = yk* | Y1=y1*, \\dots, Y(k-1)=y(k-1)*],}\nwhere \\eqn{f} is the probability density above.\n}\n\\seealso{\nMore on sequential Monte Carlo methods:\n\\code{\\link{bsmc2}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{kalman}},\n\\code{\\link{mif2}()},\n\\code{\\link{pfilter}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{wpfilter}()}\n\nOther extraction methods: \n\\code{\\link{coef}()},\n\\code{\\link{covmat}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{forecast}()},\n\\code{\\link{logLik}},\n\\code{\\link{obs}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{spy}()},\n\\code{\\link{states}()},\n\\code{\\link{summary}()},\n\\code{\\link{time}()},\n\\code{\\link{timezero}()},\n\\code{\\link{traces}()}\n}\n\\concept{extraction methods}\n\\concept{particle filter methods}\n"
  },
  {
    "path": "man/continue.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/continue.R, R/abc.R, R/pmcmc.R, R/mif2.R\n\\name{continue}\n\\alias{continue}\n\\alias{continue,missing-method}\n\\alias{continue,ANY-method}\n\\alias{continue,abcd_pomp-method}\n\\alias{continue,pmcmcd_pomp-method}\n\\alias{continue,mif2d_pomp-method}\n\\title{Continue an iterative calculation}\n\\usage{\n\\S4method{continue}{abcd_pomp}(object, ..., Nabc = 1)\n\n\\S4method{continue}{pmcmcd_pomp}(object, ..., Nmcmc = 1)\n\n\\S4method{continue}{mif2d_pomp}(object, ..., Nmif = 1)\n}\n\\arguments{\n\\item{object}{the result of an iterative \\pkg{pomp} computation}\n\n\\item{\\dots}{additional arguments will be passed to the underlying method.\nThis allows one to modify parameters used in the original computations.}\n\n\\item{Nabc}{positive integer; number of additional ABC iterations to perform}\n\n\\item{Nmcmc}{positive integer; number of additional PMCMC iterations to perform}\n\n\\item{Nmif}{positive integer; number of additional filtering iterations to perform}\n}\n\\description{\nContinue an iterative computation where it left off.\n}\n\\seealso{\n\\code{\\link{mif2}} \\code{\\link{pmcmc}} \\code{\\link{abc}}\n}\n"
  },
  {
    "path": "man/covariate_table.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/covariate_table.R, R/lookup.R\n\\name{covariates}\n\\alias{covariates}\n\\alias{covariate_table}\n\\alias{covariate_table,missing-method}\n\\alias{covariate_table,ANY-method}\n\\alias{covariate_table,numeric-method}\n\\alias{covariate_table,character-method}\n\\alias{repair_lookup_table}\n\\title{Covariates}\n\\usage{\n\\S4method{covariate_table}{numeric}(..., order = c(\"linear\", \"constant\"), times)\n\n\\S4method{covariate_table}{character}(..., order = c(\"linear\", \"constant\"), times)\n\nrepair_lookup_table(table, t, order)\n}\n\\arguments{\n\\item{\\dots}{numeric vectors or data frames containing time-varying covariates.\nIt must be possible to bind these into a data frame.}\n\n\\item{order}{the order of interpolation to be used.\nOptions are \\dQuote{linear} (the default) and \\dQuote{constant}.\nSetting \\code{order=\"linear\"} treats the covariates as piecewise linear functions of time;\n\\code{order=\"constant\"} treats them as right-continuous piecewise constant functions.}\n\n\\item{times}{the times corresponding to the covariates.\nThis may be given as a vector of (non-decreasing, finite) numerical values.\nAlternatively, one can specify by name which of the given variables is the time variable.}\n\n\\item{table}{a \\sQuote{covartable} object created by a call to \\code{\\link{covariate_table}}}\n\n\\item{t}{numeric vector;\ntimes at which interpolated values of the covariates in \\code{table} are required.}\n}\n\\value{\n\\code{covariate_table} returns a lookup table suitable for inclusion of covariates in a \\sQuote{pomp} object.\nSpecifically, this is an object of class \\sQuote{covartable}.\n\n\\code{repair_lookup_table} returns a lookup table with entries at the provided values of \\code{t}.\n}\n\\description{\nIncorporating time-varying covariates using lookup tables.\n}\n\\details{\nIf the \\sQuote{pomp} object contains covariates (specified via the \\code{covar} argument), then interpolated values of the covariates will be available to each of the model components whenever it is called.\nIn particular, variables with names as they appear in the \\code{covar} covariate table will be available to any C snippet.\nWhen a basic component is defined using an \\R function, that function will be called with an extra argument, \\code{covars}, which will be a named numeric vector containing the interpolated values from the covariate table.\n\nAn exception to this rule is the prior (\\code{rprior} and \\code{dprior}):\ncovariate-dependent priors are not allowed.\nNor are parameter transformations permitted to depend upon covariates.\n\n\\code{repair_lookup_table} applies \\code{\\link{lookup}} at the provided values of \\code{t} and returns the resulting lookup table.\nIf \\code{order} is unsupplied, the interpolation-order from \\code{table} is preserved.\n\\strong{\\code{repair_lookup_table} should be considered experimental: its interface may change without notice}.\n}\n\\section{Extrapolation}{\n\nIf \\code{t} is outside the range of the lookup table, the values will be extrapolated, and a warning will be issued.\nThe type of extrapolation performed will be constant or linear according to the \\code{order} flag used when creating the table.\n}\n\n\\seealso{\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{accumvars}},\n\\code{\\link{basic_components}},\n\\code{\\link{betabinomial}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{userdata}},\n\\code{\\link{vmeasure_spec}}\n\nMore on interpolation:\n\\code{\\link{bsplines}},\n\\code{\\link{lookup}()}\n}\n\\concept{covariates}\n\\concept{implementation information}\n\\concept{interpolation}\n"
  },
  {
    "path": "man/covmat.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/covmat.R\n\\name{covmat}\n\\alias{covmat}\n\\alias{covmat,missing-method}\n\\alias{covmat,ANY-method}\n\\alias{covmat,pmcmcd_pomp-method}\n\\alias{covmat,pmcmcList-method}\n\\alias{covmat,abcd_pomp-method}\n\\alias{covmat,abcList-method}\n\\alias{covmat,probed_pomp-method}\n\\title{Estimate a covariance matrix from algorithm traces}\n\\usage{\n\\S4method{covmat}{pmcmcd_pomp}(object, start = 1, thin = 1, expand = 2.38, ...)\n\n\\S4method{covmat}{pmcmcList}(object, start = 1, thin = 1, expand = 2.38, ...)\n\n\\S4method{covmat}{abcd_pomp}(object, start = 1, thin = 1, expand = 2.38, ...)\n\n\\S4method{covmat}{abcList}(object, start = 1, thin = 1, expand = 2.38, ...)\n\n\\S4method{covmat}{probed_pomp}(object, ...)\n}\n\\arguments{\n\\item{object}{an object extending \\sQuote{pomp}}\n\n\\item{start}{the first iteration number to be used in estimating the covariance matrix.\nSetting \\code{thin > 1} allows for a burn-in period.}\n\n\\item{thin}{factor by which the chains are to be thinned}\n\n\\item{expand}{the expansion factor}\n\n\\item{\\dots}{ignored}\n}\n\\value{\nWhen \\code{object} is the result of a \\code{pmcmc} or \\code{abc} computation,\n\\code{covmat(object)} gives the covariance matrix of the chains.\nThis can be useful, for example, in tuning the proposal distribution.\n\nWhen \\code{object} is a \\sQuote{probed_pomp} object (i.e., the result\nof a \\code{probe} computation), \\code{covmat(object)} returns the\ncovariance matrix of the probes, as applied to simulated data.\n}\n\\description{\nA helper function to extract a covariance matrix.\n}\n\\seealso{\n\\link[=proposals]{MCMC proposals}.\n\nOther extraction methods: \n\\code{\\link{coef}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{forecast}()},\n\\code{\\link{logLik}},\n\\code{\\link{obs}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{spy}()},\n\\code{\\link{states}()},\n\\code{\\link{summary}()},\n\\code{\\link{time}()},\n\\code{\\link{timezero}()},\n\\code{\\link{traces}()}\n}\n\\concept{extraction methods}\n"
  },
  {
    "path": "man/csnippet.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/csnippet.R\n\\name{Csnippet}\n\\alias{Csnippet}\n\\title{C snippets}\n\\usage{\nCsnippet(text)\n}\n\\arguments{\n\\item{text}{character; text written in the C language}\n}\n\\description{\nAccelerating computations through inline snippets of C code\n}\n\\details{\n\\pkg{pomp} provides a facility whereby users can define their model's components using inline C code.\nC snippets are written to a C file, by default located in the \\R session's temporary directory, which is then compiled (via \\code{\\link[=SHLIB]{R CMD SHLIB}}) into a dynamically loadable shared object file.\nThis is then loaded as needed.\n}\n\\section{Note to Windows and Mac users}{\n\n\nBy default, your \\R installation may not support \\code{\\link[=SHLIB]{R CMD SHLIB}}.\nThe \\href{https://kingaa.github.io/pomp/install.html}{package website contains installation instructions} that explain how to enable this powerful feature of \\R.\n}\n\n\\section{General rules for writing C snippets}{\n\n\nIn writing a C snippet one must bear in mind both the \\emph{goal} of the snippet, i.e., what computation it is intended to perform, and the \\emph{context} in which it will be executed.\nThese are explained here in the form of general rules.\nAdditional specific rules apply according to the function of the particular C snippet.\nIllustrative examples are given in the tutorials on the \\href{https://kingaa.github.io/pomp/}{package website}.\n\\enumerate{\n\\item C snippets must be valid C.\nThey will embedded verbatim in a template file which will then be compiled by a call to \\code{\\link[=SHLIB]{R CMD SHLIB}}.\nIf the resulting file does not compile, an error message will be generated.\nCompiler messages will be displayed, but no attempt will be made by \\pkg{pomp} to interpret them.\nTypically, compilation errors are due to either invalid C syntax or undeclared variables.\n\\item State variables, parameters, observables, and covariates must be left undeclared within the snippet.\nState variables and parameters are declared via the \\code{statenames} or \\code{paramnames} arguments to \\code{pomp}, respectively.\nCompiler errors that complain about undeclared state variables or parameters are usually due to failure to declare these in \\code{statenames} or \\code{paramnames}, as appropriate.\n\\item A C snippet can declare local variables.\nBe careful not to use names that match those of state variables, observables, or parameters.\nOne must never declare state variables, observables, covariates, or parameters within a C snippet.\n\\item Names of observables must match the names given given in the data.\nThey must be referred to in measurement model C snippets (\\code{rmeasure} and \\code{dmeasure}) by those names.\n\\item If the \\sQuote{pomp} object contains a table of covariates (see above), then the variables in the covariate table will be available, by their names, in the context within which the C snippet is executed.\n\\item Because the dot \\sQuote{.} has syntactic meaning in C, \\R variables with names containing dots (\\sQuote{.}) are replaced in the C codes by variable names in which all dots have been replaced by underscores (\\sQuote{_}).\n\\item The headers \\file{R.h} and \\file{Rmath.h}, provided with \\R, will be included in the generated C file, making all of the \\href{https://CRAN.R-project.org/doc/manuals/r-release/R-exts.html#The-R-API}{\\R C API} available for use in the C snippet.\nThis makes a great many useful functions available, including all of \\R's \\href{https://CRAN.R-project.org/doc/manuals/r-release/R-exts.html#Distribution-functions}{statistical distribution functions}.\n\\item The header \\href{https://github.com/kingaa/pomp/blob/master/inst/include/pomp.h}{\\file{pomp.h}}, provided with \\pkg{pomp}, will also be included, making all of the \\href{https://kingaa.github.io/pomp/C_API.html}{\\pkg{pomp} C API} available for use in every C snippet.\n\\item Snippets of C code passed to the \\code{globals} argument of \\code{pomp} will be included at the head of the generated C file.\nThis can be used to declare global variables, define useful functions, and include arbitrary header files.\n}\n}\n\n\\section{Linking to precompiled libraries}{\n\nIt is straightforward to link C snippets with precompiled C libraries.\nTo do so, one must make sure the library's header files are included;\nthe \\code{globals} argument can be used for this purpose.\nThe \\code{shlib.args} argument can then be used to specify additional arguments to be passed to \\code{\\link[=SHLIB]{R CMD SHLIB}}.\n\\href{https://kingaa.github.io/pomp/FAQ.html#linking-C-libraries}{FAQ 3.7} gives an example.\n}\n\n\\section{C snippets are salted}{\n\nTo prevent collisions in parallel computations, a \\sQuote{pomp} object built using C snippets is \\dQuote{salted} with the current time and a random number.\nA result is that two \\sQuote{pomp} objects, built on identical codes and data, will \\strong{not} be identical as \\R objects, though they will be functionally identical in every respect.\n}\n\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\seealso{\nspy\n\nMore on implementing POMP models:\n\\code{\\link{accumvars}},\n\\code{\\link{basic_components}},\n\\code{\\link{betabinomial}},\n\\code{\\link{covariates}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{userdata}},\n\\code{\\link{vmeasure_spec}}\n}\n\\concept{implementation information}\n"
  },
  {
    "path": "man/dacca.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/dacca.R\n\\docType{data}\n\\name{dacca}\n\\alias{dacca}\n\\title{Model of cholera transmission for historic Bengal.}\n\\usage{\ndacca(\n  gamma = 20.8,\n  eps = 19.1,\n  rho = 0,\n  delta = 0.02,\n  deltaI = 0.06,\n  clin = 1,\n  alpha = 1,\n  beta_trend = -0.00498,\n  logbeta = c(0.747, 6.38, -3.44, 4.23, 3.33, 4.55),\n  logomega = log(c(0.184, 0.0786, 0.0584, 0.00917, 0.000208, 0.0124)),\n  sd_beta = 3.13,\n  tau = 0.23,\n  S_0 = 0.621,\n  I_0 = 0.378,\n  Y_0 = 0,\n  R1_0 = 0.000843,\n  R2_0 = 0.000972,\n  R3_0 = 1.16e-07\n)\n}\n\\arguments{\n\\item{gamma}{recovery rate}\n\n\\item{eps}{rate of waning of immunity for severe infections}\n\n\\item{rho}{rate of waning of immunity for inapparent infections}\n\n\\item{delta}{baseline mortality rate}\n\n\\item{deltaI}{cholera mortality rate}\n\n\\item{clin}{fraction of infections that lead to severe infection}\n\n\\item{alpha}{transmission function exponent}\n\n\\item{beta_trend}{slope of secular trend in transmission}\n\n\\item{logbeta}{seasonal transmission rates}\n\n\\item{logomega}{seasonal environmental reservoir parameters}\n\n\\item{sd_beta}{environmental noise intensity}\n\n\\item{tau}{measurement error s.d.}\n\n\\item{S_0}{initial susceptible fraction}\n\n\\item{I_0}{initial fraction of population infected}\n\n\\item{Y_0}{initial fraction of the population in the Y class}\n\n\\item{R1_0, R2_0, R3_0}{initial fractions in the respective R classes}\n}\n\\value{\n\\code{dacca} returns a \\sQuote{pomp} object containing the model, data, and MLE\nparameters, as estimated by King et al. (2008).\n}\n\\description{\n\\code{dacca} constructs a \\sQuote{pomp} object containing census and cholera\nmortality data from the Dacca district of the former British province of\nBengal over the years 1891 to 1940 together with a stochastic differential\nequation transmission model.\nThe model is that of King et al. (2008).\nThe parameters are the MLE for the SIRS model with seasonal reservoir.\n}\n\\details{\nData are provided courtesy of Dr. Menno J. Bouma, London School of Tropical\nMedicine and Hygiene.\n}\n\\examples{\n\\donttest{ # takes too long for R CMD check\n  po <- dacca()\n  plot(po)\n  ## MLE:\n  coef(po)\n  plot(simulate(po))\n}\n}\n\\references{\n\\King2008\n}\n\\seealso{\nMore examples provided with \\pkg{pomp}:\n\\code{\\link{blowflies}},\n\\code{\\link{childhood_disease_data}},\n\\code{\\link{compartmental_models}},\n\\code{\\link{ebola}},\n\\code{\\link{gompertz}()},\n\\code{\\link{ou2}()},\n\\code{\\link{pomp_examples}},\n\\code{\\link{ricker}()},\n\\code{\\link{rw2}()},\n\\code{\\link{verhulst}()}\n\nMore data sets provided with \\pkg{pomp}:\n\\code{\\link{blowflies}},\n\\code{\\link{bsflu}},\n\\code{\\link{childhood_disease_data}},\n\\code{\\link{ebola}},\n\\code{\\link{parus}}\n}\n\\concept{pomp datasets}\n\\concept{pomp examples}\n\\keyword{models}\n"
  },
  {
    "path": "man/design.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/design.R, R/profile_design.R, R/runif_design.R,\n%   R/slice_design.R, R/sobol_design.R\n\\name{design}\n\\alias{design}\n\\alias{profile_design}\n\\alias{runif_design}\n\\alias{slice_design}\n\\alias{sobol_design}\n\\title{Design matrices for pomp calculations}\n\\usage{\nprofile_design(\n  ...,\n  lower,\n  upper,\n  nprof,\n  type = c(\"runif\", \"sobol\"),\n  stringsAsFactors = getOption(\"stringsAsFactors\", FALSE)\n)\n\nrunif_design(lower = numeric(0), upper = numeric(0), nseq)\n\nslice_design(center, ...)\n\nsobol_design(lower = numeric(0), upper = numeric(0), nseq)\n}\n\\arguments{\n\\item{...}{In \\code{profile_design}, additional arguments specify the parameters over which to profile and the values of these parameters.\nIn \\code{slice_design}, additional numeric vector arguments specify the locations of points along the slices.}\n\n\\item{lower, upper}{named numeric vectors giving the lower and upper bounds\nof the ranges, respectively.}\n\n\\item{nprof}{The number of points per profile point.}\n\n\\item{type}{the type of design to use.\n\\code{type=\"runif\"} uses \\code{\\link{runif_design}}.\n\\code{type=\"sobol\"} uses \\code{\\link{sobol_design}};}\n\n\\item{stringsAsFactors}{should character vectors be converted to factors?}\n\n\\item{nseq}{Total number of points requested.}\n\n\\item{center}{\\code{center} is a named numeric vector specifying the point\nthrough which the slice(s) is (are) to be taken.}\n}\n\\value{\n\\code{profile_design} returns a data frame with \\code{nprof} points per profile point.\n\n\\code{runif_design} returns a data frame with \\code{nseq} rows and one column for each variable named in \\code{lower} and \\code{upper}.\n\n\\code{slice_design} returns a data frame with one row per point.\nThe \\sQuote{slice} variable indicates which slice the point belongs to.\n\n\\code{sobol_design} returns a data frame with \\code{nseq} rows and one column for each variable named in \\code{lower} and \\code{upper}.\n}\n\\description{\nThese functions are useful for generating designs for the exploration of parameter space.\n\n\\code{profile_design} generates a data-frame where each row can be used as the starting point for a profile likelihood calculation.\n\n\\code{runif_design} generates a design based on random samples from a multivariate uniform distribution.\n\n\\code{slice_design} generates points along slices through a specified point.\n\n\\code{sobol_design} generates a Latin hypercube design based on the Sobol' low-discrepancy sequence.\n}\n\\details{\nThe Sobol' sequence generation is performed using codes from the \\pkg{NLopt} library by S. Johnson.\n}\n\\examples{\n## Sobol' low-discrepancy design\nplot(sobol_design(lower=c(a=0,b=100),upper=c(b=200,a=1),nseq=100))\n\n## Uniform random design\nplot(runif_design(lower=c(a=0,b=100),upper=c(b=200,a=1),100))\n\n## A one-parameter profile design:\nx <- profile_design(p=1:10,lower=c(a=0,b=0),upper=c(a=1,b=5),nprof=20)\ndim(x)\nplot(x)\n\n## A two-parameter profile design:\nx <- profile_design(p=1:10,q=3:5,lower=c(a=0,b=0),upper=c(b=5,a=1),nprof=200)\ndim(x)\nplot(x)\n\n## A two-parameter profile design with random points:\nx <- profile_design(p=1:10,q=3:5,lower=c(a=0,b=0),upper=c(b=5,a=1),nprof=200,type=\"runif\")\ndim(x)\nplot(x)\n\n## A single 11-point slice through the point c(A=3,B=8,C=0) along the B direction.\nx <- slice_design(center=c(A=3,B=8,C=0),B=seq(0,10,by=1))\ndim(x)\nplot(x)\n\n## Two slices through the same point along the A and C directions.\nx <- slice_design(c(A=3,B=8,C=0),A=seq(0,5,by=1),C=seq(0,5,length=11))\ndim(x)\nplot(x)\n\n}\n\\references{\n\\Kucherenko2005\n\n\\NLopt\n\n\\Bratley1988\n\n\\Joe2003\n}\n\\author{\nAaron A. King\n}\n\\concept{profile likelihood}\n\\concept{search design}\n"
  },
  {
    "path": "man/dinit.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/workhorses.R\n\\docType{methods}\n\\name{dinit}\n\\alias{dinit}\n\\alias{dinit,ANY-method}\n\\alias{dinit,missing-method}\n\\alias{dinit,pomp-method}\n\\title{dinit workhorse}\n\\usage{\n\\S4method{dinit}{pomp}(\n  object,\n  ...,\n  params = coef(object),\n  t0 = timezero(object),\n  x,\n  log = FALSE\n)\n}\n\\arguments{\n\\item{object}{an object of class \\sQuote{pomp}, or of a class that extends \\sQuote{pomp}.\nThis will typically be the output of \\code{pomp}, \\code{simulate}, or one of the \\pkg{pomp} inference algorithms.}\n\n\\item{...}{additional arguments are ignored.}\n\n\\item{params}{a \\code{npar} x \\code{nrep} matrix of parameters.\nEach column is treated as an independent parameter set, in correspondence with the corresponding column of \\code{x}.}\n\n\\item{t0}{the initial time, i.e., the time corresponding to the initial-state distribution.}\n\n\\item{x}{an array containing states of the unobserved process.\nThe dimensions of \\code{x} are \\code{nvars} x \\code{nrep} x \\code{ntimes},\nwhere \\code{nvars} is the number of state variables,\n\\code{nrep} is the number of replicates,\nand \\code{ntimes} is the length of \\code{times}.\nOne can also pass \\code{x} as a named numeric vector, which is equivalent to the \\code{nrep=1}, \\code{ntimes=1} case.}\n\n\\item{log}{if TRUE, log probabilities are returned.}\n}\n\\value{\n\\code{dinit} returns a 1-D numerical array containing the likelihoods (or log likelihoods if \\code{log=TRUE}).\nBy default, \\code{t0} is the initial time defined when the \\sQuote{pomp} object ws constructed.\n}\n\\description{\nEvaluates the initial-state density.\n}\n\\seealso{\nSpecification of the initial-state distribution: \\link{dinit_spec}\n\nMore on \\pkg{pomp} workhorse functions:\n\\code{\\link{dmeasure}()},\n\\code{\\link{dprior}()},\n\\code{\\link{dprocess}()},\n\\code{\\link{emeasure}()},\n\\code{\\link{flow}()},\n\\code{\\link{partrans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{rinit}()},\n\\code{\\link{rmeasure}()},\n\\code{\\link{rprior}()},\n\\code{\\link{rprocess}()},\n\\code{\\link{skeleton}()},\n\\code{\\link{vmeasure}()},\n\\code{\\link{workhorses}}\n}\n\\concept{extending the pomp package}\n\\concept{low-level interface}\n\\concept{pomp workhorses}\n"
  },
  {
    "path": "man/dinit_spec.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/dinit_spec.R\n\\name{dinit_spec}\n\\alias{dinit_spec}\n\\title{dinit specification}\n\\description{\nSpecification of the initial-state distribution density evaluator, dinit.\n}\n\\details{\nTo fully specify the unobserved Markov state process, one must give its distribution at the zero-time (\\code{t0}).\nOne specifies how to evaluate the log probability density function for this distribution using the \\code{dinit} argument.\nAs usual, this can be provided either as a C snippet or as an \\R function.\nIn the former case, bear in mind that:\n\\enumerate{\n  \\item The goal of a this snippet is computation of a log likelihood, to be put into a variable named \\code{loglik}.\n  \\item In addition to the state variables, parameters, and covariates (if any), the variable \\code{t}, containing the zero-time, will be defined in the context in which the snippet is executed.\n}\n\\link[=Csnippet]{General rules for writing C snippets can be found here}.\n\nIf an \\R function is to be used, pass\n\\preformatted{\n   dinit = f\n}\nto \\code{pomp}, where \\code{f} is a function with arguments that can include the time \\code{t}, any or all of the model state variables, parameters, and covariates.\nAs usual, \\code{f} may take additional arguments, provided these are passed along with it in the call to \\code{pomp}.\n\\code{f} must return a single numeric value, the log likelihood.\n}\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\seealso{\n\\code{\\link{dinit}}\n\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{accumvars}},\n\\code{\\link{basic_components}},\n\\code{\\link{betabinomial}},\n\\code{\\link{covariates}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{userdata}},\n\\code{\\link{vmeasure_spec}}\n}\n\\concept{implementation information}\n"
  },
  {
    "path": "man/dmeasure.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/workhorses.R\n\\docType{methods}\n\\name{dmeasure}\n\\alias{dmeasure}\n\\alias{dmeasure,ANY-method}\n\\alias{dmeasure,missing-method}\n\\alias{dmeasure,pomp-method}\n\\title{dmeasure workhorse}\n\\usage{\n\\S4method{dmeasure}{pomp}(\n  object,\n  ...,\n  y = obs(object),\n  x = states(object),\n  times = time(object),\n  params = coef(object),\n  log = FALSE\n)\n}\n\\arguments{\n\\item{object}{an object of class \\sQuote{pomp}, or of a class that extends \\sQuote{pomp}.\nThis will typically be the output of \\code{pomp}, \\code{simulate}, or one of the \\pkg{pomp} inference algorithms.}\n\n\\item{...}{additional arguments are ignored.}\n\n\\item{y}{a matrix containing observations.\nThe dimensions of \\code{y} are \\code{nobs} x \\code{ntimes}, where \\code{nobs} is the number of observables\nand \\code{ntimes} is the length of \\code{times}.}\n\n\\item{x}{an array containing states of the unobserved process.\nThe dimensions of \\code{x} are \\code{nvars} x \\code{nrep} x \\code{ntimes},\nwhere \\code{nvars} is the number of state variables,\n\\code{nrep} is the number of replicates,\nand \\code{ntimes} is the length of \\code{times}.\nOne can also pass \\code{x} as a named numeric vector, which is equivalent to the \\code{nrep=1}, \\code{ntimes=1} case.}\n\n\\item{times}{a numeric vector (length \\code{ntimes}) containing times.\nThese must be in non-decreasing order.}\n\n\\item{params}{a \\code{npar} x \\code{nrep} matrix of parameters.\nEach column is treated as an independent parameter set, in correspondence with the corresponding column of \\code{x}.}\n\n\\item{log}{if TRUE, log probabilities are returned.}\n}\n\\value{\n\\code{dmeasure} returns a matrix of dimensions \\code{nreps} x \\code{ntimes}.\nIf \\code{d} is the returned matrix, \\code{d[j,k]} is the likelihood (or log likelihood if \\code{log = TRUE}) of the observation \\code{y[,k]} at time \\code{times[k]} given the state \\code{x[,j,k]}.\n}\n\\description{\n\\code{dmeasure} evaluates the probability density of observations given states.\n}\n\\seealso{\nSpecification of the measurement density evaluator: \\link{dmeasure_spec}\n\nMore on \\pkg{pomp} workhorse functions:\n\\code{\\link{dinit}()},\n\\code{\\link{dprior}()},\n\\code{\\link{dprocess}()},\n\\code{\\link{emeasure}()},\n\\code{\\link{flow}()},\n\\code{\\link{partrans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{rinit}()},\n\\code{\\link{rmeasure}()},\n\\code{\\link{rprior}()},\n\\code{\\link{rprocess}()},\n\\code{\\link{skeleton}()},\n\\code{\\link{vmeasure}()},\n\\code{\\link{workhorses}}\n}\n\\concept{extending the pomp package}\n\\concept{low-level interface}\n\\concept{pomp workhorses}\n"
  },
  {
    "path": "man/dmeasure_spec.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/dmeasure_spec.R\n\\name{dmeasure_spec}\n\\alias{dmeasure_spec}\n\\title{dmeasure specification}\n\\description{\nSpecification of the measurement model density function, dmeasure.\n}\n\\details{\nThe measurement model is the link between the data and the unobserved state process.\nIt can be specified either by using one or both of the \\code{rmeasure} and \\code{dmeasure} arguments.\n\nSuppose you have a procedure to compute the probability density of an observation given the value of the latent state variables.\nThen you can furnish \\preformatted{\n   dmeasure = f}\nto \\pkg{pomp} algorithms,\nwhere \\code{f} is a C snippet or \\R function that implements your procedure.\n\nUsing a C snippet is much preferred, due to its much greater computational efficiency.\nSee \\code{\\link{Csnippet}} for general rules on writing C snippets.\nThe goal of a \\dfn{dmeasure} C snippet is to fill the variable \\code{lik} with the either the probability density or the log probability density, depending on the value of the variable \\code{give_log}.\n\nIn writing a \\code{dmeasure} C snippet, observe that:\n  \\enumerate{\n    \\item In addition to the states, parameters, covariates (if any), and observables, the variable \\code{t}, containing the time of the observation will be defined in the context in which the snippet is executed.\n    \\item Moreover, the Boolean variable \\code{give_log} will be defined.\n    \\item The goal of a dmeasure C snippet is to set the value of the predefined \\code{lik} variable to the likelihood of the data given the state, if \\code{give_log == 0}.\n    If \\code{give_log == 1}, \\code{lik} should be set to the log likelihood.\n  }\n\nIf \\code{dmeasure} is to be provided instead as an \\R function, this is accomplished by supplying \\preformatted{\n  dmeasure = f}\nto \\code{pomp}, where \\code{f} is a function.\nThe arguments of \\code{f} should be chosen from among the observables, state variables, parameters, covariates, and time.\nIt must also have the arguments \\code{\\dots}, and \\code{log}.\nIt can take additional arguments via the \\link[=userdata]{userdata facility}.\n\\code{f} must return a single numeric value, the probability density (or log probability density if \\code{log = TRUE}) of \\code{y} given \\code{x} at time \\code{t}.\n}\n\\section{Important note}{\n\n\\strong{It is a common error to fail to account for both \\code{log = TRUE} and \\code{log = FALSE} when writing the \\code{dmeasure} C snippet or function.}\n}\n\n\\section{Default behavior}{\n\nIf \\code{dmeasure} is left unspecified, calls to \\code{\\link{dmeasure}} will return missing values (\\code{NA}).\n}\n\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\examples{\n\\donttest{\n  ## We start with the pre-built Ricker example:\n  ricker() -> po\n\n  ## To change the measurement model density, dmeasure,\n  ## we use the 'dmeasure' argument in any 'pomp'\n  ## elementary or estimation function.\n  ## Here, we pass the dmeasure specification to 'pfilter'\n  ## as an R function.\n\n  po |>\n    pfilter(\n      dmeasure=function (y, N, phi, ..., log) {\n        dpois(y,lambda=phi*N,log=log)\n      },\n      Np=100\n    ) -> pf\n\n  ## We can also pass it as a C snippet:\n\n  po |>\n    pfilter(\n      dmeasure=Csnippet(\"lik = dpois(y,phi*N,give_log);\"),\n      paramnames=\"phi\",\n      statenames=\"N\",\n      Np=100\n    ) -> pf\n\n}\n}\n\\seealso{\n\\code{\\link{dmeasure}}\n\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{accumvars}},\n\\code{\\link{basic_components}},\n\\code{\\link{betabinomial}},\n\\code{\\link{covariates}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{userdata}},\n\\code{\\link{vmeasure_spec}}\n}\n\\concept{implementation information}\n"
  },
  {
    "path": "man/dprior.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/workhorses.R\n\\docType{methods}\n\\name{dprior}\n\\alias{dprior}\n\\alias{dprior,ANY-method}\n\\alias{dprior,missing-method}\n\\alias{dprior,pomp-method}\n\\title{dprior workhorse}\n\\usage{\n\\S4method{dprior}{pomp}(object, ..., params = coef(object), log = FALSE)\n}\n\\arguments{\n\\item{object}{an object of class \\sQuote{pomp}, or of a class that extends \\sQuote{pomp}.\nThis will typically be the output of \\code{pomp}, \\code{simulate}, or one of the \\pkg{pomp} inference algorithms.}\n\n\\item{...}{additional arguments are ignored.}\n\n\\item{params}{a \\code{npar} x \\code{nrep} matrix of parameters.\nEach column is treated as an independent parameter set, in correspondence with the corresponding column of \\code{x}.}\n\n\\item{log}{if TRUE, log probabilities are returned.}\n}\n\\value{\nThe required density (or log density), as a numeric vector.\n}\n\\description{\nEvaluates the prior probability density.\n}\n\\seealso{\nSpecification of the prior density evaluator: \\link{prior_spec}\n\nMore on \\pkg{pomp} workhorse functions:\n\\code{\\link{dinit}()},\n\\code{\\link{dmeasure}()},\n\\code{\\link{dprocess}()},\n\\code{\\link{emeasure}()},\n\\code{\\link{flow}()},\n\\code{\\link{partrans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{rinit}()},\n\\code{\\link{rmeasure}()},\n\\code{\\link{rprior}()},\n\\code{\\link{rprocess}()},\n\\code{\\link{skeleton}()},\n\\code{\\link{vmeasure}()},\n\\code{\\link{workhorses}}\n\nMore on Bayesian methods:\n\\code{\\link{abc}()},\n\\code{\\link{bsmc2}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{prior_spec}},\n\\code{\\link{rprior}()}\n}\n\\concept{Bayesian methods}\n\\concept{extending the pomp package}\n\\concept{low-level interface}\n\\concept{pomp workhorses}\n"
  },
  {
    "path": "man/dprocess.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/workhorses.R\n\\docType{methods}\n\\name{dprocess}\n\\alias{dprocess}\n\\alias{dprocess,ANY-method}\n\\alias{dprocess,missing-method}\n\\alias{dprocess,pomp-method}\n\\title{dprocess workhorse}\n\\usage{\n\\S4method{dprocess}{pomp}(\n  object,\n  ...,\n  x = states(object),\n  times = time(object),\n  params = coef(object),\n  log = FALSE\n)\n}\n\\arguments{\n\\item{object}{an object of class \\sQuote{pomp}, or of a class that extends \\sQuote{pomp}.\nThis will typically be the output of \\code{pomp}, \\code{simulate}, or one of the \\pkg{pomp} inference algorithms.}\n\n\\item{...}{additional arguments are ignored.}\n\n\\item{x}{an array containing states of the unobserved process.\nThe dimensions of \\code{x} are \\code{nvars} x \\code{nrep} x \\code{ntimes},\nwhere \\code{nvars} is the number of state variables,\n\\code{nrep} is the number of replicates,\nand \\code{ntimes} is the length of \\code{times}.\nOne can also pass \\code{x} as a named numeric vector, which is equivalent to the \\code{nrep=1}, \\code{ntimes=1} case.}\n\n\\item{times}{a numeric vector (length \\code{ntimes}) containing times.\nThese must be in non-decreasing order.}\n\n\\item{params}{a \\code{npar} x \\code{nrep} matrix of parameters.\nEach column is treated as an independent parameter set, in correspondence with the corresponding column of \\code{x}.}\n\n\\item{log}{if TRUE, log probabilities are returned.}\n}\n\\value{\n\\code{dprocess} returns a matrix of dimensions \\code{nrep} x \\code{ntimes-1}.\nIf \\code{d} is the returned matrix, \\code{d[j,k]} is the likelihood (or the log likelihood if \\code{log=TRUE}) of the transition from state \\code{x[,j,k-1]} at time \\code{times[k-1]} to state \\code{x[,j,k]} at time \\code{times[k]}.\n}\n\\description{\nEvaluates the probability density of a sequence of consecutive state transitions.\n}\n\\seealso{\nSpecification of the process-model density evaluator: \\link{dprocess_spec}\n\nMore on \\pkg{pomp} workhorse functions:\n\\code{\\link{dinit}()},\n\\code{\\link{dmeasure}()},\n\\code{\\link{dprior}()},\n\\code{\\link{emeasure}()},\n\\code{\\link{flow}()},\n\\code{\\link{partrans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{rinit}()},\n\\code{\\link{rmeasure}()},\n\\code{\\link{rprior}()},\n\\code{\\link{rprocess}()},\n\\code{\\link{skeleton}()},\n\\code{\\link{vmeasure}()},\n\\code{\\link{workhorses}}\n}\n\\concept{extending the pomp package}\n\\concept{low-level interface}\n\\concept{pomp workhorses}\n"
  },
  {
    "path": "man/dprocess_spec.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/dprocess_spec.R\n\\name{dprocess_spec}\n\\alias{dprocess_spec}\n\\title{dprocess specification}\n\\description{\nSpecification of the latent state process density function, dprocess.\n}\n\\details{\nSuppose you have a procedure that allows you to compute the probability density\nof an arbitrary transition from state \\eqn{x_1}{x1} at time \\eqn{t_1}{t1}\nto state \\eqn{x_2}{x2} at time \\eqn{t_2>t_1}{t2}\nunder the assumption that the state remains unchanged\nbetween \\eqn{t_1}{t1} and \\eqn{t_2}{t2}.\nThen you can furnish\n\\preformatted{\n    dprocess = f\n}\nto \\code{pomp}, where \\code{f} is a C snippet or \\R function that implements your procedure.\nSpecifically, \\code{f} should compute the \\emph{log} probability density.\n\nUsing a C snippet is much preferred, due to its much greater computational efficiency.\nSee \\code{\\link{Csnippet}} for general rules on writing C snippets.\nThe goal of a \\dfn{dprocess} C snippet is to fill the predefined variable \\code{loglik} with the log probability density.\nIn the context of such a C snippet, the parameters, and covariates will be defined, as will the times \\code{t_1} and \\code{t_2}.\nThe state variables at time \\code{t_1} will have their usual name (see \\code{statenames}) with a \\dQuote{\\code{_1}} appended.\nLikewise, the state variables at time \\code{t_2} will have a \\dQuote{\\code{_2}} appended.\n\nIf \\code{f} is given as an \\R function, it should take as arguments any or all of the state variables, parameter, covariates, and time.\nThe state-variable and time arguments will have suffices \\dQuote{\\code{_1}} and \\dQuote{\\code{_2}} appended.\nThus for example, if \\code{var} is a state variable, when \\code{f} is called, \\code{var_1} will value of state variable \\code{var} at time \\code{t_1}, \\code{var_2} will have the value of \\code{var} at time \\code{t_2}.\n\\code{f} should return the \\emph{log} likelihood of a transition from \\code{x1} at time \\code{t1} to \\code{x2} at time \\code{t2},\nassuming that no intervening transitions have occurred.\n\n  To see examples, consult the demos and the tutorials on the \\href{https://kingaa.github.io/pomp/}{package website}.\n}\n\\section{\\strong{Note}}{\n\nIt is not typically necessary (or even feasible) to define \\code{dprocess}.\nIn fact, no current \\pkg{pomp} inference algorithm makes use of \\code{dprocess}.\nThis functionality is provided only to support future algorithm development.\n}\n\n\\section{Default behavior}{\n\nBy default, \\code{dprocess} returns missing values (\\code{NA}).\n}\n\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\seealso{\n\\code{\\link{dprocess}}\n\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{accumvars}},\n\\code{\\link{basic_components}},\n\\code{\\link{betabinomial}},\n\\code{\\link{covariates}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{userdata}},\n\\code{\\link{vmeasure_spec}}\n}\n\\concept{implementation information}\n"
  },
  {
    "path": "man/ebola.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/ebola.R\n\\docType{data}\n\\name{ebola}\n\\alias{ebola}\n\\alias{ebolaWA2014}\n\\alias{ebolaModel}\n\\title{Ebola outbreak, West Africa, 2014-2016}\n\\usage{\nebolaModel(\n  country = c(\"GIN\", \"LBR\", \"SLE\"),\n  data = NULL,\n  timestep = 1/8,\n  nstageE = 3L,\n  R0 = 1.4,\n  rho = 0.2,\n  cfr = 0.7,\n  k = 0,\n  index_case = 10,\n  incubation_period = 11.4,\n  infectious_period = 7\n)\n}\n\\arguments{\n\\item{country}{ISO symbol for the country (GIN=Guinea, LBR=Liberia, SLE=Sierra Leone).}\n\n\\item{data}{if NULL, the situation report data (WHO Ebola Response Team 2014) for the appropriate country or region will be used.\nProviding a dataset here will override this behavior.}\n\n\\item{timestep}{duration (in days) of Euler timestep for the simulations.}\n\n\\item{nstageE}{integer; number of incubation stages.}\n\n\\item{R0}{basic reproduction ratio}\n\n\\item{rho}{case reporting efficiency}\n\n\\item{cfr}{case fatality rate}\n\n\\item{k}{dispersion parameter (negative binomial \\code{size} parameter)}\n\n\\item{index_case}{number of cases on day 0 (2014-04-01)}\n\n\\item{incubation_period, infectious_period}{mean duration (in days) of the incubation and infectious periods.}\n}\n\\description{\nData and models for the 2014--2016 outbreak of Ebola virus disease in West Africa.\n}\n\\details{\nThe data include monthly case counts and death reports derived from WHO situation reports, as reported by the U.S. CDC.\nThe models are described in King et al. (2015).\n\nThe data-cleaning script is included in the R source code file \\file{ebola.R}.\n}\n\\section{Model structure}{\n\nThe default incubation period is supposed to be Gamma distributed with shape parameter \\code{nstageE} and mean 11.4 days and the case-fatality ratio (`cfr`) is taken to be 0.7 (cf. WHO Ebola Response Team 2014).\nThe discrete-time formula is used to calculate the corresponding \\code{alpha} (cf. He et al. 2010).\n\nThe observation model is a hierarchical model for cases and deaths:\n  \\deqn{p(R_t, D_t| C_t) = p(R_t | C_t) p(D_t | C_t, R_t).}\nHere, \\eqn{p(R_t | C_t)} is negative binomial with mean \\eqn{\\rho C_t} and dispersion parameter \\eqn{1/k};\n\\eqn{p(D_t | C_t, R_t)} is binomial with size \\eqn{R_t} and probability equal to the case fatality rate \\code{cfr}.\n}\n\n\\examples{\n\\donttest{ # takes too long for R CMD check\n  if (require(ggplot2) && require(tidyr)) {\n    \n    ebolaWA2014 |>\n      pivot_longer(c(cases,deaths)) |>\n      ggplot(aes(x=date,y=value,group=name,color=name))+\n      geom_line()+\n      facet_grid(country~.,scales=\"free_y\")+\n      theme_bw()+\n      theme(axis.text=element_text(angle=-90))\n    \n  }\n  \n  plot(ebolaModel(country=\"SLE\"))\n  plot(ebolaModel(country=\"GIN\"))\n  plot(ebolaModel(country=\"LBR\"))\n}\n}\n\\references{\n\\King2015\n\n\\WHO2014\n\n\\He2010\n}\n\\seealso{\nMore data sets provided with \\pkg{pomp}:\n\\code{\\link{blowflies}},\n\\code{\\link{bsflu}},\n\\code{\\link{childhood_disease_data}},\n\\code{\\link{dacca}()},\n\\code{\\link{parus}}\n\nMore examples provided with \\pkg{pomp}:\n\\code{\\link{blowflies}},\n\\code{\\link{childhood_disease_data}},\n\\code{\\link{compartmental_models}},\n\\code{\\link{dacca}()},\n\\code{\\link{gompertz}()},\n\\code{\\link{ou2}()},\n\\code{\\link{pomp_examples}},\n\\code{\\link{ricker}()},\n\\code{\\link{rw2}()},\n\\code{\\link{verhulst}()}\n}\n\\concept{pomp datasets}\n\\concept{pomp examples}\n"
  },
  {
    "path": "man/eff_sample_size.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/eff_sample_size.R\n\\name{eff_sample_size}\n\\alias{eff_sample_size}\n\\alias{eff_sample_size,missing-method}\n\\alias{eff_sample_size,ANY-method}\n\\alias{eff_sample_size,bsmcd_pomp-method}\n\\alias{eff_sample_size,pfilterd_pomp-method}\n\\alias{eff_sample_size,wpfilterd_pomp-method}\n\\alias{eff_sample_size,pfilterList-method}\n\\title{Effective sample size}\n\\usage{\n\\S4method{eff_sample_size}{bsmcd_pomp}(object, ..., format = c(\"numeric\", \"data.frame\"))\n\n\\S4method{eff_sample_size}{pfilterd_pomp}(object, ..., format = c(\"numeric\", \"data.frame\"))\n\n\\S4method{eff_sample_size}{wpfilterd_pomp}(object, ..., format = c(\"numeric\", \"data.frame\"))\n\n\\S4method{eff_sample_size}{pfilterList}(object, ..., format = c(\"numeric\", \"data.frame\"))\n}\n\\arguments{\n\\item{object}{result of a filtering computation}\n\n\\item{...}{ignored}\n\n\\item{format}{format of the returned object}\n}\n\\description{\nEstimate the effective sample size of a Monte Carlo computation.\n}\n\\details{\nEffective sample size is computed as\n\\deqn{\\left(\\sum_i\\!w_{it}^2\\right)^{-1},}{1/(sum(w_it^2)),}\nwhere \\eqn{w_{it}}{w_it} is the normalized weight of particle \\eqn{i} at time \\eqn{t}.\n}\n\\seealso{\nMore on sequential Monte Carlo methods:\n\\code{\\link{bsmc2}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{kalman}},\n\\code{\\link{mif2}()},\n\\code{\\link{pfilter}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{wpfilter}()}\n\nOther extraction methods: \n\\code{\\link{coef}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{covmat}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{forecast}()},\n\\code{\\link{logLik}},\n\\code{\\link{obs}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{spy}()},\n\\code{\\link{states}()},\n\\code{\\link{summary}()},\n\\code{\\link{time}()},\n\\code{\\link{timezero}()},\n\\code{\\link{traces}()}\n}\n\\concept{extraction methods}\n\\concept{particle filter methods}\n"
  },
  {
    "path": "man/elementary_algorithms.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/elementary_algorithms.R\n\\name{elementary_algorithms}\n\\alias{elementary_algorithms}\n\\title{Elementary computations on POMP models.}\n\\description{\nIn \\pkg{pomp}, elementary algorithms perform POMP model operations.\nThese operations do not themselves estimate parameters, though they may be instrumental in inference methods.\n}\n\\details{\nThere are six elementary algorithms in \\pkg{pomp}:\n\\itemize{\n\\item \\code{\\link{simulate}} which simulates from the joint distribution of latent and observed variables,\n\\item \\code{\\link{pfilter}}, which performs a simple particle filter operation,\n\\item \\code{\\link{wpfilter}}, which performs a weighted particle filter operation,\n\\item \\code{\\link{probe}}, which computes a suite of user-specified summary statistics on actual and simulated data,\n\\item \\code{\\link{spect}}, which performs a power-spectral density function computation on actual and simulated data,\n\\item \\code{\\link{trajectory}}, which iterates or integrates the deterministic skeleton according to whether the latter is a (discrete-time) map or a (continuous-time) vectorfield.\n}\n\nHelp pages detailing each elementary algorithm component are provided.\n}\n\\seealso{\n\\link[=basic_components]{basic model components},\n\\link[=workhorses]{workhorse functions},\n\\link[=estimation_algorithms]{estimation algorithms}.\n\nMore on \\pkg{pomp} elementary algorithms:\n\\code{\\link{kalman}},\n\\code{\\link{pfilter}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{probe}()},\n\\code{\\link{simulate}()},\n\\code{\\link{spect}()},\n\\code{\\link{trajectory}()},\n\\code{\\link{wpfilter}()}\n}\n\\concept{elementary algorithms}\n"
  },
  {
    "path": "man/emeasure.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/workhorses.R\n\\docType{methods}\n\\name{emeasure}\n\\alias{emeasure}\n\\alias{emeasure,ANY-method}\n\\alias{emeasure,missing-method}\n\\alias{emeasure,pomp-method}\n\\title{emeasure workhorse}\n\\usage{\n\\S4method{emeasure}{pomp}(\n  object,\n  ...,\n  x = states(object),\n  times = time(object),\n  params = coef(object)\n)\n}\n\\arguments{\n\\item{object}{an object of class \\sQuote{pomp}, or of a class that extends \\sQuote{pomp}.\nThis will typically be the output of \\code{pomp}, \\code{simulate}, or one of the \\pkg{pomp} inference algorithms.}\n\n\\item{...}{additional arguments are ignored.}\n\n\\item{x}{an array containing states of the unobserved process.\nThe dimensions of \\code{x} are \\code{nvars} x \\code{nrep} x \\code{ntimes},\nwhere \\code{nvars} is the number of state variables,\n\\code{nrep} is the number of replicates,\nand \\code{ntimes} is the length of \\code{times}.\nOne can also pass \\code{x} as a named numeric vector, which is equivalent to the \\code{nrep=1}, \\code{ntimes=1} case.}\n\n\\item{times}{a numeric vector (length \\code{ntimes}) containing times.\nThese must be in non-decreasing order.}\n\n\\item{params}{a \\code{npar} x \\code{nrep} matrix of parameters.\nEach column is treated as an independent parameter set, in correspondence with the corresponding column of \\code{x}.}\n}\n\\value{\n\\code{emeasure} returns a rank-3 array of dimensions\n\\code{nobs} x \\code{nrep} x \\code{ntimes},\nwhere \\code{nobs} is the number of observed variables.\n}\n\\description{\nReturn the expected value of the observed variables, given values of the latent states and the parameters.\n}\n\\seealso{\nSpecification of the measurement-model expectation: \\link{emeasure_spec}\n\nMore on \\pkg{pomp} workhorse functions:\n\\code{\\link{dinit}()},\n\\code{\\link{dmeasure}()},\n\\code{\\link{dprior}()},\n\\code{\\link{dprocess}()},\n\\code{\\link{flow}()},\n\\code{\\link{partrans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{rinit}()},\n\\code{\\link{rmeasure}()},\n\\code{\\link{rprior}()},\n\\code{\\link{rprocess}()},\n\\code{\\link{skeleton}()},\n\\code{\\link{vmeasure}()},\n\\code{\\link{workhorses}}\n}\n\\concept{pomp workhorses}\n"
  },
  {
    "path": "man/emeasure_spec.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/emeasure_spec.R\n\\name{emeasure_spec}\n\\alias{emeasure_spec}\n\\title{emeasure specification}\n\\description{\nSpecification of the measurement-model conditional expectation, emeasure.\n}\n\\details{\nThe measurement model is the link between the data and the unobserved state process.\nSome algorithms require the conditional expectation of the measurement model, given the latent state and parameters.\nThis is supplied using the \\code{emeasure} argument.\n\nSuppose you have a procedure to compute this conditional expectation, given the value of the latent state variables.\nThen you can furnish \\preformatted{\n  emeasure = f}\nto \\pkg{pomp} algorithms,\nwhere \\code{f} is a C snippet or \\R function that implements your procedure.\n\nUsing a C snippet is much preferred, due to its much greater computational efficiency.\nSee \\code{\\link{Csnippet}} for general rules on writing C snippets.\n\nIn writing an \\code{emeasure} C snippet, bear in mind that:\n  \\enumerate{\n    \\item The goal of such a snippet is to fill variables named \\code{E_y} with the conditional expectations of observables \\code{y}.\n    Accordingly, there should be one assignment of \\code{E_y} for each observable \\code{y}.\n    \\item In addition to the states, parameters, and covariates (if any), the variable \\code{t}, containing the time of the observation, will be defined in the context in which the snippet is executed.\n  }\n\nThe demos and the tutorials on the \\href{https://kingaa.github.io/pomp/}{package website} give examples.\n\nIt is also possible, though less efficient, to specify \\code{emeasure} using an \\R function.\nIn this case, specify the measurement model expectation by furnishing \\preformatted{\n  emeasure = f}\nto \\code{pomp}, where \\code{f} is an \\R function.\nThe arguments of \\code{f} should be chosen from among the state variables, parameters, covariates, and time.\nIt must also have the argument \\code{...}.\n\\code{f} must return a named numeric vector of length equal to the number of observable variables.\nThe names should match those of the observable variables.\n}\n\\section{Default behavior}{\n\nThe default \\code{emeasure} is undefined.\nIt will yield missing values (\\code{NA}).\n}\n\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\seealso{\n\\code{\\link{emeasure}}\n\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{accumvars}},\n\\code{\\link{basic_components}},\n\\code{\\link{betabinomial}},\n\\code{\\link{covariates}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{userdata}},\n\\code{\\link{vmeasure_spec}}\n}\n\\concept{implementation information}\n"
  },
  {
    "path": "man/estimation_algorithms.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/estimation_algorithms.R\n\\name{estimation_algorithms}\n\\alias{estimation_algorithms}\n\\title{Parameter estimation algorithms for POMP models.}\n\\description{\n\\pkg{pomp} currently implements the following algorithms for estimating model parameters:\n\\itemize{\n\\item \\link[=mif2]{iterated filtering (IF2)}\n\\item \\link[=pmcmc]{particle Markov chain Monte Carlo (PMCMC)}\n\\item \\link[=abc]{approximate Bayesian computation (ABC)}\n\\item \\link[=probe_match]{probe-matching via synthetic likelihood}\n\\item \\link[=nlf]{nonlinear forecasting}\n\\item \\link[=spect_match]{power-spectrum matching}\n\\item \\link[=bsmc2]{Liu-West Bayesian sequential Monte Carlo}\n\\item \\link[=kalman]{Ensemble and ensemble-adjusted Kalman filters}\n}\n}\n\\details{\nHelp pages detailing each estimation algorithm are provided.\n}\n\\seealso{\n\\link[=basic_components]{basic model components},\n\\link[=workhorses]{workhorse functions},\n\\link[=elementary_algorithms]{elementary algorithms}.\n\nMore on \\pkg{pomp} estimation algorithms:\n\\code{\\link{abc}()},\n\\code{\\link{bsmc2}()},\n\\code{\\link{mif2}()},\n\\code{\\link{nlf}},\n\\code{\\link{pmcmc}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{probe_match}},\n\\code{\\link{spect_match}}\n}\n\\concept{estimation methods}\n"
  },
  {
    "path": "man/eulermultinom.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/eulermultinom.R\n\\name{eulermultinom}\n\\alias{eulermultinom}\n\\alias{reulermultinom}\n\\alias{deulermultinom}\n\\alias{eeulermultinom}\n\\alias{rgammawn}\n\\title{Eulermultinomial and Gamma-whitenoise distributions}\n\\usage{\nreulermultinom(n = 1, size, rate, dt)\n\ndeulermultinom(x, size, rate, dt, log = FALSE)\n\neeulermultinom(size, rate, dt)\n\nrgammawn(n = 1, sigma, dt)\n}\n\\arguments{\n\\item{n}{integer; number of random variates to generate.}\n\n\\item{size}{scalar integer; number of individuals at risk.}\n\n\\item{rate}{numeric vector of hazard rates.}\n\n\\item{dt}{numeric scalar; duration of Euler step.}\n\n\\item{x}{matrix or vector containing number of individuals that have\nsuccumbed to each death process.}\n\n\\item{log}{logical; if TRUE, return logarithm(s) of probabilities.}\n\n\\item{sigma}{numeric scalar; intensity of the Gamma white noise process.}\n}\n\\value{\n\\code{reulermultinom} returns a \\code{length(rate)} by \\code{n} matrix.\nEach column is a different random draw.\nEach row contains the numbers of individuals that have succumbed to the corresponding process.\n\n\\code{deulermultinom} returns a vector (of length equal to the number of columns of \\code{x}).\nThis contains the probabilities of observing each column of \\code{x} given the specified parameters (\\code{size}, \\code{rate}, \\code{dt}).\n\n\\code{eeulermultinom} returns a \\code{length(rate)}-vector\ncontaining the expected number of individuals to have succumbed to the corresponding process.\nWith the notation above, if\n\\preformatted{\n    dn <- eeulermultinom(size=N,rate=r,dt=dt),\n}\nthen the \\eqn{k}-th element of the vector \\code{dn} will be \\eqn{p_k N}{pk N}.\n\n\\code{rgammawn} returns a vector of length \\code{n} containing random increments of the integrated Gamma white noise process with intensity \\code{sigma}.\n}\n\\description{\n\\pkg{pomp} provides a number of probability distributions that have proved useful in modeling partially observed Markov processes.\nThese include the Euler-multinomial family of distributions and\nthe the Gamma white-noise processes.\n}\n\\details{\nIf \\eqn{N} individuals face constant hazards of death in \\eqn{K} ways\nat rates \\eqn{r_1, r_2, \\dots, r_K}{r1,r2,\\dots,rK},\nthen in an interval of duration \\eqn{\\Delta{t}}{dt},\nthe number of individuals remaining alive and dying in each way is multinomially distributed:\n\\deqn{(\\Delta{n_0}, \\Delta{n_1}, \\dots, \\Delta{n_K}) \\sim \\mathrm{Multinomial}(N;p_0,p_1,\\dots,p_K),}{(dn0, dn1, \\dots, dnK) ~ multinomial(N; p0, p1, \\dots, pK),}\nwhere \\eqn{\\Delta{n_0}=N-\\sum_{k=1}^K \\Delta{n_k}}{dn0 = N - sum(dnk,k=1:K)} is the number of individuals remaining alive and\n\\eqn{\\Delta{n_k}}{dnk} is the number of individuals dying in way \\eqn{k} over the interval.\nHere, the probability of remaining alive is \\deqn{p_0=\\exp(-\\sum_k r_k \\Delta{t})}{p0 = exp(-sum(rk, k=1:K)*dt)}\nand the probability of dying in way \\eqn{k} is \\deqn{p_k=\\frac{r_k}{\\sum_j r_j} (1-p_0).}{pk = (1-p0)*rk/sum(rj, j=1:K).}\nIn this case, we say that \\deqn{(\\Delta{n_1},\\dots,\\Delta{n_K})\\sim\\mathrm{Eulermultinom}(N,r,\\Delta t),}{(dn1,\\dots,dnK) ~ eulermultinom(N,r,dt),} where \\eqn{r=(r_1,\\dots,r_K)}{r=(r1,\\dots,rK)}.\nDraw \\eqn{m} random samples from this distribution by doing \\preformatted{\n    dn <- reulermultinom(n=m,size=N,rate=r,dt=dt),\n} where \\code{r} is the vector of rates.\nEvaluate the probability that \\eqn{x=(x_1,\\dots,x_K)}{x=(x1,\\dots,xK)} are the numbers of individuals who have died in each of the \\eqn{K} ways over the interval \\eqn{\\Delta t=}{dt=}\\code{dt},\nby doing \\preformatted{\n    deulermultinom(x=x,size=N,rate=r,dt=dt).\n}\n\nBretó & Ionides (2011) discuss how an infinitesimally overdispersed death process can be constructed by compounding a multinomial process with a Gamma white noise process.\nThe Euler approximation of the resulting process can be obtained as follows.\nLet the increments of the equidispersed process be given by\n\\preformatted{\n    reulermultinom(size=N,rate=r,dt=dt).\n}\nIn this expression, replace the rate \\eqn{r} with \\eqn{r\\,{\\Delta{W}}/{\\Delta t}}{r*dW/dt},\nwhere \\eqn{\\Delta{W} \\sim \\mathrm{Gamma}(\\Delta{t}/\\sigma^2,\\sigma^2)}{dW ~ Gamma(dt/sigma^2,sigma^2)}\nis the increment of an integrated Gamma white noise process with intensity \\eqn{\\sigma}{sigma}.\nThat is, \\eqn{\\Delta{W}}{dW} has mean \\eqn{\\Delta{t}}{dt} and variance \\eqn{\\sigma^2 \\Delta{t}}{sigma^2*dt}.\nThe resulting process is overdispersed and converges (as \\eqn{\\Delta{t}}{dt} goes to zero) to a well-defined process.\nThe following lines of code accomplish this:\n\\preformatted{\n    dW <- rgammawn(sigma=sigma,dt=dt)\n} \\preformatted{\n    dn <- reulermultinom(size=N,rate=r,dt=dW)\n} or\n\\preformatted{\n    dn <- reulermultinom(size=N,rate=r*dW/dt,dt=dt).\n}\nHe et al. (2010) use such overdispersed death processes in modeling measles and the \\href{https://kingaa.github.io/sbied/measles/}{\"Simulation-based Inference\" course} discusses the value of allowing for overdispersion more generally.\n\nFor all of the functions described here, access to the underlying C routines is available:\nsee below.\n}\n\\section{C API}{\n\nAn interface for C codes using these functions is provided by the package.\nVisit the package homepage to view the \\href{https://kingaa.github.io/pomp/C_API.html}{\\pkg{pomp} C API document}.\n}\n\n\\examples{\n## Simulate 5 realizations of Euler-multinomial random variable:\n\ndn <- reulermultinom(5,size=100,rate=c(a=1,b=2,c=3),dt=0.1)\ndn\n\n## Compute the probability mass function at each of the 5 realizations:\n\ndeulermultinom(x=dn,size=100,rate=c(1,2,3),dt=0.1)\n\n## Compute the expectation of an Euler-multinomial:\n\neeulermultinom(size=100,rate=c(a=1,b=2,c=3),dt=0.1)\n\n## An Euler-multinomial with overdispersed transitions:\n\ndt <- 0.1\ndW <- rgammawn(sigma=0.1,dt=dt)\nreulermultinom(5,size=100,rate=c(a=1,b=2,c=3),dt=dW)\n}\n\\references{\n\\Breto2011\n\\He2010\n}\n\\seealso{\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{accumvars}},\n\\code{\\link{basic_components}},\n\\code{\\link{betabinomial}},\n\\code{\\link{covariates}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{userdata}},\n\\code{\\link{vmeasure_spec}}\n}\n\\author{\nAaron A. King\n}\n\\concept{implementation information}\n\\concept{probability distributions}\n\\keyword{distribution}\n"
  },
  {
    "path": "man/filter_mean.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/filter_mean.R\n\\docType{methods}\n\\name{filter_mean}\n\\alias{filter_mean}\n\\alias{filter_mean,ANY-method}\n\\alias{filter_mean,missing-method}\n\\alias{filter_mean,kalmand_pomp-method}\n\\alias{filter_mean,pfilterd_pomp-method}\n\\title{Filtering mean}\n\\usage{\n\\S4method{filter_mean}{kalmand_pomp}(object, vars, ..., format = c(\"array\", \"data.frame\"))\n\n\\S4method{filter_mean}{pfilterd_pomp}(object, vars, ..., format = c(\"array\", \"data.frame\"))\n}\n\\arguments{\n\\item{object}{result of a filtering computation}\n\n\\item{vars}{optional character; names of variables}\n\n\\item{...}{ignored}\n\n\\item{format}{format of the returned object}\n}\n\\description{\nThe mean of the filtering distribution\n}\n\\details{\nThe filtering distribution is that of\n\\deqn{X(t_k) \\vert Y(t_1)=y^*_1,\\dots,Y(t_k)=y^*_k,}{Xk | Y1=y1*,\\dots,Yk=yk*,}\nwhere \\eqn{X(t_k)}{Xk}, \\eqn{Y(t_k)}{Yk} are the latent state and observable processes, respectively, and \\eqn{y^*_t}{yt*} is the data, at time \\eqn{t_k}{tk}.\n\nThe filtering mean is therefore the expectation of this distribution\n\\deqn{E[X(t_k) \\vert Y(t_1)=y^*_1,\\dots,Y(t_k)=y^*_k].}{E[Xk | Y1=y1*,\\dots,Yk=yk*].}\n}\n\\seealso{\nMore on sequential Monte Carlo methods:\n\\code{\\link{bsmc2}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{kalman}},\n\\code{\\link{mif2}()},\n\\code{\\link{pfilter}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{wpfilter}()}\n\nOther extraction methods: \n\\code{\\link{coef}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{covmat}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{forecast}()},\n\\code{\\link{logLik}},\n\\code{\\link{obs}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{spy}()},\n\\code{\\link{states}()},\n\\code{\\link{summary}()},\n\\code{\\link{time}()},\n\\code{\\link{timezero}()},\n\\code{\\link{traces}()}\n}\n\\concept{extraction methods}\n\\concept{particle filter methods}\n"
  },
  {
    "path": "man/filter_traj.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/filter_traj.R\n\\name{filter_traj}\n\\alias{filter_traj}\n\\alias{filter_traj,ANY-method}\n\\alias{filter_traj,missing-method}\n\\alias{filter_traj,pfilterd_pomp-method}\n\\alias{filter_traj,listie-method}\n\\alias{filter_traj,pmcmcd_pomp-method}\n\\title{Filtering trajectories}\n\\usage{\n\\S4method{filter_traj}{pfilterd_pomp}(object, vars, ..., format = c(\"array\", \"data.frame\"))\n\n\\S4method{filter_traj}{listie}(object, vars, ..., format = c(\"array\", \"data.frame\"))\n\n\\S4method{filter_traj}{pmcmcd_pomp}(object, vars, ...)\n}\n\\arguments{\n\\item{object}{result of a filtering computation}\n\n\\item{vars}{optional character; names of variables}\n\n\\item{...}{ignored}\n\n\\item{format}{format of the returned object}\n}\n\\description{\nDrawing from the smoothing distribution\n}\n\\details{\nThe smoothing distribution is the distribution of\n\\deqn{X(t_k) | Y(t_1)=y^*_1, \\dots, Y(t_n)=y^*_n,}{Xk | Y1=y1*, \\dots, Yn=yn*,}\nwhere \\eqn{X(t_k)}{Xk} is the latent state process and \\eqn{Y(t_k)}{Yk} is the observable process at time \\eqn{t_k}{tk}, and \\eqn{n} is the number of observations.\n\nTo draw samples from this distribution, one can run a number of independent particle filter (\\code{\\link{pfilter}}) operations, sampling the full trajectory of \\emph{one} randomly-drawn particle from each one.\nOne should view these as \\emph{weighted} samples from the smoothing distribution, where the weights are the \\emph{likelihoods} returned by each of the \\code{\\link{pfilter}} computations.\n\nOne accomplishes this by setting \\code{filter.traj = TRUE} in each \\code{\\link{pfilter}} computation and extracting the trajectory using the \\code{filter_traj} command.\n\nIn particle MCMC (\\code{\\link{pmcmc}}), the tracking of an individual trajectory is performed automatically.\n}\n\\seealso{\nMore on sequential Monte Carlo methods:\n\\code{\\link{bsmc2}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{kalman}},\n\\code{\\link{mif2}()},\n\\code{\\link{pfilter}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{wpfilter}()}\n\nOther extraction methods: \n\\code{\\link{coef}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{covmat}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{forecast}()},\n\\code{\\link{logLik}},\n\\code{\\link{obs}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{spy}()},\n\\code{\\link{states}()},\n\\code{\\link{summary}()},\n\\code{\\link{time}()},\n\\code{\\link{timezero}()},\n\\code{\\link{traces}()}\n}\n\\concept{extraction methods}\n\\concept{particle filter methods}\n"
  },
  {
    "path": "man/flow.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/flow.R\n\\name{flow}\n\\alias{flow}\n\\alias{flow,missing-method}\n\\alias{flow,ANY-method}\n\\alias{flow,pomp-method}\n\\title{flow workhorse}\n\\usage{\n\\S4method{flow}{pomp}(\n  object,\n  ...,\n  x0,\n  t0 = timezero(object),\n  times = time(object),\n  params = coef(object),\n  verbose = getOption(\"verbose\", FALSE)\n)\n}\n\\arguments{\n\\item{object}{an object of class \\sQuote{pomp}, or of a class that extends \\sQuote{pomp}.\nThis will typically be the output of \\code{pomp}, \\code{simulate}, or one of the \\pkg{pomp} inference algorithms.}\n\n\\item{...}{Additional arguments are passed to the ODE integrator (if the skeleton is a vectorfield) and are ignored if it is a map.\nSee \\code{\\link[deSolve]{ode}} for a description of the additional arguments accepted by the ODE integrator.\nBy default, this is the parameter vector stored in \\code{object} (see \\code{\\link[pomp]{coef}}).}\n\n\\item{x0}{an array with dimensions \\code{nvar} x \\code{nrep} giving the initial conditions of the trajectories to be computed.}\n\n\\item{t0}{the time at which the initial conditions are assumed to hold.\nBy default, this is the zero-time (see \\code{\\link{timezero}}).}\n\n\\item{times}{a numeric vector (length \\code{ntimes}) containing times at which the itineraries are desired.\nThese must be in non-decreasing order with \\code{times[1]>t0}.\nBy default, this is the full set of observation times (see \\code{\\link{time}}).}\n\n\\item{params}{a \\code{npar} x \\code{nrep} matrix of parameters.\nEach column is treated as an independent parameter set, in correspondence with the corresponding column of \\code{x}.}\n\n\\item{verbose}{logical; if \\code{TRUE}, diagnostic messages will be printed to the console.}\n}\n\\value{\n\\code{flow} returns an array of dimensions \\code{nvar} x \\code{nrep} x \\code{ntimes}.\nIf \\code{x} is the returned matrix, \\code{x[i,j,k]} is the i-th component of the state vector at time \\code{times[k]} given parameters \\code{params[,j]}.\n}\n\\description{\nCompute the flow generated by a deterministic vectorfield or map.\n}\n\\details{\nIn the case of a discrete-time system (map), \\code{flow} iterates the map to yield trajectories of the system.\nIn the case of a continuous-time system (vectorfield), \\code{flow} uses the numerical solvers in \\pkg{\\link[deSolve]{deSolve}} to integrate the vectorfield starting from given initial conditions.\n}\n\\section{Accumulator variables}{\n\nWhen there are accumulator variables (as determined by the \\code{\\link{accumvars}} argument), their handling in the continuous-time (vectorfield) case differs from that in the discrete-time (map) case.\nIn the latter, accumulator variables are set to zero at the beginning of each interval \\eqn{(t_k,t_{k+1})}{(t[k],t[k+1])}, \\eqn{k=0,1,2,\\dots} over which flow computation is required.\nIn the former, the flow computation proceeds over the entire set of intervals required, and accumulator variables are then differenced.\nThat is, the value \\eqn{a_k}{a[k]} of accumulator variable \\eqn{a} at times \\eqn{t_k}{t[k]}, \\eqn{k=1,2,\\dots} will be \\eqn{A_k-A_{k-1}}{A[k]-A[k-1]}, where \\eqn{A_k}{A[k]} is the solution of the corresponding differential equation at \\eqn{t_k}{t[k]}.\n}\n\n\\seealso{\nMore on \\pkg{pomp} workhorse functions:\n\\code{\\link{dinit}()},\n\\code{\\link{dmeasure}()},\n\\code{\\link{dprior}()},\n\\code{\\link{dprocess}()},\n\\code{\\link{emeasure}()},\n\\code{\\link{partrans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{rinit}()},\n\\code{\\link{rmeasure}()},\n\\code{\\link{rprior}()},\n\\code{\\link{rprocess}()},\n\\code{\\link{skeleton}()},\n\\code{\\link{vmeasure}()},\n\\code{\\link{workhorses}}\n\nMore on methods for deterministic process models:\n\\code{\\link{skeleton}()},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{traj_match}},\n\\code{\\link{trajectory}()}\n}\n\\concept{deterministic methods}\n\\concept{extending the pomp package}\n\\concept{low-level interface}\n\\concept{pomp workhorses}\n"
  },
  {
    "path": "man/forecast.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/forecast.R\n\\name{forecast}\n\\alias{forecast}\n\\alias{forecast,missing-method}\n\\alias{forecast,ANY-method}\n\\alias{forecast,kalmand_pomp-method}\n\\alias{forecast,pfilterd_pomp-method}\n\\title{Forecast mean}\n\\usage{\nforecast(object, ...)\n\n\\S4method{forecast}{kalmand_pomp}(object, vars, ..., format = c(\"array\", \"data.frame\"))\n\n\\S4method{forecast}{pfilterd_pomp}(object, vars, ..., format = c(\"array\", \"data.frame\"))\n}\n\\arguments{\n\\item{object}{result of a filtering computation}\n\n\\item{...}{ignored}\n\n\\item{vars}{optional character; names of variables}\n\n\\item{format}{format of the returned object}\n}\n\\description{\nMean of the one-step-ahead forecasting distribution.\n}\n\\seealso{\nOther extraction methods: \n\\code{\\link{coef}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{covmat}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{logLik}},\n\\code{\\link{obs}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{spy}()},\n\\code{\\link{states}()},\n\\code{\\link{summary}()},\n\\code{\\link{time}()},\n\\code{\\link{timezero}()},\n\\code{\\link{traces}()}\n}\n\\concept{extraction methods}\n"
  },
  {
    "path": "man/gompertz.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/gompertz.R\n\\docType{data}\n\\name{gompertz}\n\\alias{gompertz}\n\\title{Gompertz model with log-normal observations.}\n\\usage{\ngompertz(\n  K = 1,\n  r = 0.1,\n  sigma = 0.1,\n  tau = 0.1,\n  X_0 = 1,\n  times = 1:100,\n  t0 = 0,\n  seed = 299438676L\n)\n}\n\\arguments{\n\\item{K}{carrying capacity}\n\n\\item{r}{growth rate}\n\n\\item{sigma}{process noise intensity}\n\n\\item{tau}{measurement error s.d.}\n\n\\item{X_0}{value of the latent state variable \\code{X} at the zero time}\n\n\\item{times}{observation times}\n\n\\item{t0}{zero time}\n\n\\item{seed}{seed of the random number generator}\n}\n\\value{\nA \\sQuote{pomp} object with simulated data.\n}\n\\description{\n\\code{gompertz()} constructs a \\sQuote{pomp} object encoding a stochastic Gompertz population model with log-normal measurement error.\n}\n\\details{\nThe state process is\n\\deqn{X_{t+1} = K^{1-S} X_{t}^S \\epsilon_{t},}{X[t+1]=K^(1-S) X[t]^S eps[t],} where \\eqn{S=e^{-r}}{S=e^{-r}}\nand the \\eqn{\\epsilon_t}{eps[t]} are i.i.d. lognormal random deviates with\nvariance \\eqn{\\sigma^2}{sigma^2}.\nThe observed variables \\eqn{Y_t} are distributed as\n\\deqn{Y_t\\sim\\mathrm{Lognormal}(\\log{X_t},\\tau).}{Y[t]~Lognormal(log(X[t]),tau).}\nParameters include the per-capita growth rate \\eqn{r}, the carrying\ncapacity \\eqn{K}, the process noise s.d. \\eqn{\\sigma}{sigma}, the\nmeasurement error s.d. \\eqn{\\tau}{tau}, and the initial condition\n\\eqn{X_0}{X[0]}.  The \\sQuote{pomp} object includes parameter\ntransformations that log-transform the parameters for estimation purposes.\n}\n\\examples{\n\nplot(gompertz())\nplot(gompertz(K=2,r=0.01))\n\n}\n\\seealso{\nMore examples provided with \\pkg{pomp}:\n\\code{\\link{blowflies}},\n\\code{\\link{childhood_disease_data}},\n\\code{\\link{compartmental_models}},\n\\code{\\link{dacca}()},\n\\code{\\link{ebola}},\n\\code{\\link{ou2}()},\n\\code{\\link{pomp_examples}},\n\\code{\\link{ricker}()},\n\\code{\\link{rw2}()},\n\\code{\\link{verhulst}()}\n}\n\\concept{pomp examples}\n\\keyword{models}\n"
  },
  {
    "path": "man/hitch.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/builder.R\n\\docType{methods}\n\\name{hitch}\n\\alias{hitch}\n\\title{Hitching C snippets and R functions to pomp_fun objects}\n\\usage{\nhitch(\n  ...,\n  templates,\n  obsnames,\n  statenames,\n  paramnames,\n  covarnames,\n  PACKAGE,\n  globals,\n  cfile,\n  cdir = getOption(\"pomp_cdir\", NULL),\n  on_load,\n  shlib.args,\n  compile = TRUE,\n  verbose = getOption(\"verbose\", FALSE)\n)\n}\n\\arguments{\n\\item{\\dots}{named arguments representing the user procedures to be hitched.\nThese can be functions, character strings naming routines in external, dynamically-linked libraries, C snippets, or \\code{NULL}.\nThe first three are converted by \\code{hitch} to \\sQuote{pomp_fun} objects which perform the indicated computations.\n\\code{NULL} arguments are translated to default \\sQuote{pomp_fun} objects.\nIf any of these procedures are already \\sQuote{pomp_fun} objects, they are returned unchanged.}\n\n\\item{templates}{named list of templates.\nEach workhorse must have a corresponding template.\nSee \\code{pomp:::workhorse_templates} for a list.}\n\n\\item{obsnames, statenames, paramnames, covarnames}{character vectors\nspecifying the names of observable variables, latent state variables, parameters, and covariates, respectively.\nThese are only needed if one or more of the horses are furnished as C snippets.}\n\n\\item{PACKAGE}{optional character;\nthe name (without extension) of the external, dynamically loaded library in which any native routines are to be found.\nThis is only useful if one or more of the model components has been specified using a precompiled dynamically loaded library;\nit is not used for any component specified using C snippets.\n\\code{PACKAGE} can name at most one library.}\n\n\\item{globals}{optional character or C snippet;\narbitrary C code that will be hard-coded into the shared-object library created when C snippets are provided.\nIf no C snippets are used, \\code{globals} has no effect.}\n\n\\item{cfile}{optional character variable.\n\\code{cfile} gives the name of the file (in directory \\code{cdir}) into which C snippet codes will be written.\nBy default, a random filename is used.\nIf the chosen filename would result in over-writing an existing file, an error is generated.}\n\n\\item{cdir}{optional character variable.\n\\code{cdir} specifies the name of the directory within which C snippet code will be compiled.\nBy default, this is in a temporary directory specific to the \\R session.\nOne can also set this directory using the \\code{pomp_cdir} global option.}\n\n\\item{on_load}{optional character or C snippet:\narbitrary C code that will be executed when the C snippet file is loaded.\nIf no C snippets are used, \\code{on_load} has no effect.}\n\n\\item{shlib.args}{optional character variables.\nCommand-line arguments to the \\code{R CMD SHLIB} call that compiles the C snippets.\nOne can, for example, specify libraries against which the C snippets are to be linked.\nIn doing so, take care to make sure the appropriate header files are available to the C snippets, e.g., using the \\code{globals} argument.\nSee \\code{\\link{Csnippet}} for more information.}\n\n\\item{compile}{logical;\nif \\code{FALSE}, compilation of the C snippets will be postponed until they are needed.}\n\n\\item{verbose}{logical.\nSetting \\code{verbose=TRUE} will cause additional information to be displayed.}\n}\n\\value{\n\\code{hitch} returns a named list of length two.  The element named\n\\dQuote{funs} is itself a named list of \\sQuote{pomp_fun} objects, each of\nwhich corresponds to one of the horses passed in.  The element named\n\\dQuote{lib} contains information on the shared-object library created\nusing the C snippets (if any were passed to \\code{hitch}).  If no C\nsnippets were passed to \\code{hitch}, \\code{lib} is \\code{NULL}.\nOtherwise, it is a length-3 named list with the following elements:\n\\describe{\n\\item{name}{The name of the library created.}\n\\item{dir}{ The\ndirectory in which the library was created.  If this is \\code{NULL}, the\nlibrary was created in the session's temporary directory.  }\n\\item{src}{ A\ncharacter string with the full contents of the C snippet file.  } }\n}\n\\description{\nThe algorithms in \\pkg{pomp} are formulated using \\R functions that access the \\link[=basic_components]{basic model components}\n(\\code{rprocess}, \\code{dprocess}, \\code{rmeasure}, \\code{dmeasure}, etc.).\nFor short, we refer to these elementary functions as \\dQuote{\\link{workhorses}}.\nIn implementing a model, the user specifies basic model components\nusing functions, procedures in dynamically-linked libraries, or C snippets.\nEach component is then packaged into a \\sQuote{pomp_fun} objects, which gives a uniform interface.\nThe construction of \\sQuote{pomp_fun} objects is handled by the \\code{hitch} function,\nwhich conceptually \\dQuote{hitches} the workhorses to the user-defined procedures.\n}\n\\seealso{\n\\code{\\link{pomp}}, \\code{\\link{spy}}\n}\n\\author{\nAaron A. King\n}\n\\concept{extending the pomp package}\n\\concept{low-level interface}\n"
  },
  {
    "path": "man/kalman.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/kalman.R\n\\name{kalman}\n\\alias{kalman}\n\\alias{enkf,ANY-method}\n\\alias{enkf,missing-method}\n\\alias{eakf,ANY-method}\n\\alias{eakf,missing-method}\n\\alias{enkf,data.frame-method}\n\\alias{enkf}\n\\alias{enkf,pomp-method}\n\\alias{enkf,kalmand_pomp-method}\n\\alias{eakf,data.frame-method}\n\\alias{eakf}\n\\alias{eakf,pomp-method}\n\\title{Ensemble Kalman filters}\n\\usage{\n\\S4method{enkf}{data.frame}(\n  data,\n  ...,\n  Np,\n  params,\n  rinit,\n  rprocess,\n  emeasure,\n  vmeasure,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{enkf}{pomp}(data, ..., Np, verbose = getOption(\"verbose\", FALSE))\n\n\\S4method{enkf}{kalmand_pomp}(data, ..., Np, verbose = getOption(\"verbose\", FALSE))\n\n\\S4method{eakf}{data.frame}(\n  data,\n  ...,\n  Np,\n  params,\n  rinit,\n  rprocess,\n  emeasure,\n  vmeasure,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{eakf}{pomp}(data, ..., Np, verbose = getOption(\"verbose\", FALSE))\n}\n\\arguments{\n\\item{data}{either a data frame holding the time series data,\nor an object of class \\sQuote{pomp},\ni.e., the output of another \\pkg{pomp} calculation.\nInternally, \\code{data} will be coerced to an array with storage-mode \\code{double}.}\n\n\\item{...}{additional arguments are passed to \\code{\\link{pomp}}.\nThis allows one to set, unset, or modify \\link[=basic_components]{basic model components} within a call to this function.}\n\n\\item{Np}{integer; the number of particles to use, i.e., the size of the ensemble.}\n\n\\item{params}{optional; named numeric vector of parameters.\nThis will be coerced internally to storage mode \\code{double}.}\n\n\\item{rinit}{simulator of the initial-state distribution.\nThis can be furnished either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rinit=NULL} sets the initial-state simulator to its default.\nFor more information, see \\link[=rinit_spec]{rinit specification}.}\n\n\\item{rprocess}{simulator of the latent state process, specified using one of the \\link[=rprocess_spec]{rprocess plugins}.\nSetting \\code{rprocess=NULL} removes the latent-state simulator.\nFor more information, see \\link[=rprocess_spec]{rprocess specification for the documentation on these plugins}.}\n\n\\item{emeasure}{the expectation of the measured variables, conditional on the latent state.\nThis can be specified as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{emeasure=NULL} removes the emeasure component.\nFor more information, see \\link[=emeasure_spec]{emeasure specification}.}\n\n\\item{vmeasure}{the covariance of the measured variables, conditional on the latent state.\nThis can be specified as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{vmeasure=NULL} removes the vmeasure component.\nFor more information, see \\link[=vmeasure_spec]{vmeasure specification}.}\n\n\\item{verbose}{logical; if \\code{TRUE}, diagnostic messages will be printed to the console.}\n}\n\\value{\nAn object of class \\sQuote{kalmand_pomp}.\n}\n\\description{\nThe ensemble Kalman filter and ensemble adjustment Kalman filter.\n}\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\references{\n\\Evensen1994\n\n\\Anderson2001\n\n\\Evensen2009\n}\n\\seealso{\n\\code{\\link{kalmanFilter}}\n\nMore on sequential Monte Carlo methods:\n\\code{\\link{bsmc2}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{mif2}()},\n\\code{\\link{pfilter}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{wpfilter}()}\n\nMore on \\pkg{pomp} elementary algorithms:\n\\code{\\link{elementary_algorithms}},\n\\code{\\link{pfilter}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{probe}()},\n\\code{\\link{simulate}()},\n\\code{\\link{spect}()},\n\\code{\\link{trajectory}()},\n\\code{\\link{wpfilter}()}\n}\n\\author{\nAaron A. King\n}\n\\concept{Kalman filter}\n\\concept{elementary algorithms}\n\\concept{particle filter methods}\n"
  },
  {
    "path": "man/kf.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/kf.R\n\\name{kalmanFilter}\n\\alias{kalmanFilter}\n\\title{Kalman filter}\n\\usage{\nkalmanFilter(object, X0 = rinit(object), A, Q, C, R, tol = 1e-06)\n}\n\\arguments{\n\\item{object}{a pomp object containing data;}\n\n\\item{X0}{length-m vector containing initial state.\nThis is assumed known without uncertainty.}\n\n\\item{A}{\\eqn{m\\times m}{m x m} latent state-process transition matrix.\n\\eqn{E[X_{t+1} | X_t] = A.X_t}.}\n\n\\item{Q}{\\eqn{m\\times m}{m x m} latent state-process covariance matrix.\n\\eqn{Var[X_{t+1} | X_t] = Q}}\n\n\\item{C}{\\eqn{n\\times m}{n x m} link matrix.\n\\eqn{E[Y_t | X_t] = C.X_t}.}\n\n\\item{R}{\\eqn{n\\times n}{n x n} observation process covariance matrix.\n\\eqn{Var[Y_t | X_t] = R}}\n\n\\item{tol}{numeric;\nthe tolerance to be used in computing matrix pseudoinverses via singular-value decomposition.\nSingular values smaller than \\code{tol} are set to zero.}\n}\n\\value{\nA named list containing the following elements:\n\\describe{\n  \\item{object}{the \\sQuote{pomp} object}\n  \\item{A, Q, C, R}{as in the call}\n  \\item{filter.mean}{\\eqn{E[X_t|y^*_1,\\dots,y^*_t]}}\n  \\item{pred.mean}{\\eqn{E[X_t|y^*_1,\\dots,y^*_{t-1}]}}\n  \\item{forecast}{\\eqn{E[Y_t|y^*_1,\\dots,y^*_{t-1}]}}\n  \\item{cond.logLik}{\\eqn{f(y^*_t|y^*_1,\\dots,y^*_{t-1})}}\n  \\item{logLik}{\\eqn{f(y^*_1,\\dots,y^*_T)}}\n}\n}\n\\description{\nThe basic Kalman filter for multivariate, linear, Gaussian processes.\n}\n\\details{\nIf the latent state is \\eqn{X}, the observed variable is \\eqn{Y},\n\\eqn{X_t \\in R^m}, \\eqn{Y_t \\in R^n}, and\n\\deqn{X_t \\sim \\mathrm{MVN}(A X_{t-1}, Q)}{X_t ~ MVN(A X_{t-1}, Q)}\n\\deqn{Y_t \\sim \\mathrm{MVN}(C X_t, R)}{Y_t ~ MVN(C X_t, R)}\nwhere \\eqn{\\mathrm{MVN}(M,V)} denotes the multivariate normal distribution with mean \\eqn{M} and variance \\eqn{V}.\nThen the Kalman filter computes the exact likelihood of \\eqn{Y}\ngiven \\eqn{A}, \\eqn{C}, \\eqn{Q}, and \\eqn{R}.\n}\n\\examples{\nif (require(dplyr)) {\n\n  gompertz() -> po\n\n  po |>\n    as.data.frame() |>\n    mutate(\n      logY=log(Y)\n    ) |>\n    select(time,logY) |>\n    pomp(times=\"time\",t0=0) |>\n    kalmanFilter(\n      X0=c(logX=0),\n      A=matrix(exp(-0.1),1,1),\n      Q=matrix(0.01,1,1),\n      C=matrix(1,1,1),\n      R=matrix(0.01,1,1)\n    ) -> kf\n\n  po |>\n    pfilter(Np=1000) -> pf\n\n  kf$logLik\n  logLik(pf) + sum(log(obs(pf)))\n\n}\n}\n\\seealso{\n\\code{\\link{enkf}}, \\code{\\link{eakf}}\n}\n\\concept{Kalman filter}\n"
  },
  {
    "path": "man/listie.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/listie.R, R/extract.R\n\\name{listie}\n\\alias{listie}\n\\alias{[-listie}\n\\alias{[,listie-method}\n\\title{listie}\n\\usage{\n\\S4method{[}{listie}(x, i, j, ..., drop = TRUE)\n}\n\\description{\nList-like objects.\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/load.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/load.R, R/objfun.R\n\\docType{methods}\n\\name{load}\n\\alias{load}\n\\alias{pompLoad}\n\\alias{pompUnload}\n\\alias{solibs<-}\n\\alias{pompLoad,pomp-method}\n\\alias{pompUnload,pomp-method}\n\\alias{solibs<-,pomp-method}\n\\alias{pompLoad,objfun-method}\n\\alias{pompUnload,objfun-method}\n\\title{Loading and unloading shared-object libraries}\n\\usage{\n\\S4method{pompLoad}{pomp}(object, ...)\n\n\\S4method{pompUnload}{pomp}(object, ...)\n\n\\S4method{solibs}{pomp}(object, ...) <- value\n\n\\S4method{pompLoad}{objfun}(object, ...)\n\n\\S4method{pompUnload}{objfun}(object, ...)\n}\n\\arguments{\n\\item{object}{an object of class \\sQuote{pomp}, or extending this class.}\n}\n\\description{\n\\code{pompLoad} and \\code{pompUnload} cause compiled codes associated with \\code{object} to be dynamically linked or unlinked, respectively.\n\\code{solibs<-} is a helper function for developers of packages that extend \\pkg{pomp}.\n}\n\\details{\nWhen C snippets are used in the construction of a \\sQuote{pomp} object, the resulting shared-object library is dynamically loaded (linked) before each use, and unloaded afterward.\n\n\\code{solibs<-} prepends the \\sQuote{lib} generated by \\code{\\link{hitch}}\n to the \\sQuote{solibs} slot of a \\sQuote{pomp} object.\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/loglik.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/loglik.R\n\\name{logLik}\n\\alias{logLik}\n\\alias{logLik,ANY-method}\n\\alias{logLik,missing-method}\n\\alias{logLik,listie-method}\n\\alias{logLik,pfilterd_pomp-method}\n\\alias{logLik,wpfilterd_pomp-method}\n\\alias{logLik,probed_pomp-method}\n\\alias{logLik,kalmand_pomp-method}\n\\alias{logLik,pmcmcd_pomp-method}\n\\alias{logLik,bsmcd_pomp-method}\n\\alias{logLik,objfun-method}\n\\alias{logLik,spect_match_objfun-method}\n\\alias{logLik,nlf_objfun-method}\n\\title{Log likelihood}\n\\usage{\nlogLik(object, ...)\n\n\\S4method{logLik}{listie}(object, ...)\n\n\\S4method{logLik}{pfilterd_pomp}(object)\n\n\\S4method{logLik}{wpfilterd_pomp}(object)\n\n\\S4method{logLik}{probed_pomp}(object)\n\n\\S4method{logLik}{kalmand_pomp}(object)\n\n\\S4method{logLik}{pmcmcd_pomp}(object)\n\n\\S4method{logLik}{bsmcd_pomp}(object)\n\n\\S4method{logLik}{objfun}(object)\n\n\\S4method{logLik}{spect_match_objfun}(object)\n\n\\S4method{logLik}{nlf_objfun}(object, ...)\n}\n\\arguments{\n\\item{object}{fitted model object}\n\n\\item{\\dots}{ignored}\n}\n\\value{\nnumerical value of the log likelihood.\nNote that some methods compute not the log likelihood itself but instead a related quantity.\nTo keep the code simple, the \\code{logLik} function is nevertheless used to extract this quantity.\n\nWhen \\code{object} is of \\sQuote{pfilterd_pomp} class (i.e., the result of a \\code{wpfilter} computation), \\code{logLik} retrieves the estimated log likelihood.\n\nWhen \\code{object} is of \\sQuote{wpfilterd_pomp} class (i.e., the result of a \\code{wpfilter} computation), \\code{logLik} retrieves the estimated log likelihood.\n\nWhen \\code{object} is of \\sQuote{probed_pomp} class (i.e., the result of a \\code{\\link{probe}} computation), \\code{logLik} retrieves the \\dQuote{synthetic likelihood}.\n\nWhen \\code{object} is of \\sQuote{kalmand_pomp} class (i.e., the result of an \\code{\\link{eakf}} or \\code{\\link{enkf}} computation), \\code{logLik} retrieves the estimated log likelihood.\n\nWhen \\code{object} is of \\sQuote{pmcmcd_pomp} class (i.e., the result of a \\code{\\link{pmcmc}} computation), \\code{logLik} retrieves the estimated log likelihood as of the last particle filter operation.\n\nWhen \\code{object} is of \\sQuote{bsmcd_pomp} class (i.e., the result of a \\code{\\link{bsmc2}} computation), \\code{logLik} retrieves the \\dQuote{log evidence}.\n\nWhen \\code{object} is of \\sQuote{spect_match_objfun} class (i.e., an objective function constructed by \\code{\\link{spect_objfun}}), \\code{logLik} retrieves minus the spectrum mismatch.\n\nWhen \\code{object} is an NLF objective function, i.e., the result of a call to \\code{\\link{nlf_objfun}},\n\\code{logLik} retrieves the \\dQuote{quasi log likelihood}.\n}\n\\description{\nExtract the estimated log likelihood (or related quantity) from a fitted model.\n}\n\\seealso{\nOther extraction methods: \n\\code{\\link{coef}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{covmat}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{forecast}()},\n\\code{\\link{obs}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{spy}()},\n\\code{\\link{states}()},\n\\code{\\link{summary}()},\n\\code{\\link{time}()},\n\\code{\\link{timezero}()},\n\\code{\\link{traces}()}\n}\n\\concept{extraction methods}\n"
  },
  {
    "path": "man/logmeanexp.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/logmeanexp.R\n\\name{logmeanexp}\n\\alias{logmeanexp}\n\\title{The log-mean-exp trick}\n\\usage{\nlogmeanexp(x, se = FALSE, ess = FALSE)\n}\n\\arguments{\n\\item{x}{numeric}\n\n\\item{se}{logical; give approximate standard error?}\n\n\\item{ess}{logical; give effective sample size?}\n}\n\\value{\n\\code{log(mean(exp(x)))} computed so as to avoid over- or underflow.\nIf \\code{se = TRUE}, the approximate standard error is returned as well.\nIf \\code{ess = TRUE}, the effective sample size is returned also.\n}\n\\description{\n\\code{logmeanexp} computes\n\\deqn{\\log\\frac{1}{n}\\sum_{i=1}^n\\!e^{x_i},}{log(mean(exp(x))),}\navoiding over- and under-flow in doing so.\nIt can optionally return an estimate of the standard error in this quantity.\n}\n\\details{\nWhen \\code{se = TRUE}, \\code{logmeanexp} uses a jackknife estimate of the variance in \\eqn{log(x)}.\n\nWhen \\code{ess = TRUE}, \\code{logmeanexp} returns an estimate of the effective sample size.\n}\n\\examples{\n\\donttest{ # takes too long for R CMD check\n  ## an estimate of the log likelihood:\n  ricker() |>\n    pfilter(Np=1000) |>\n    logLik() |>\n    replicate(n=5) -> ll\n  logmeanexp(ll)\n  ## with standard error:\n  logmeanexp(ll,se=TRUE)\n  ## with effective sample size\n  logmeanexp(ll,ess=TRUE)\n}\n}\n\\author{\nAaron A. King\n}\n"
  },
  {
    "path": "man/lookup.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/lookup.R\n\\name{lookup}\n\\alias{lookup}\n\\title{Lookup table}\n\\usage{\nlookup(table, t)\n}\n\\arguments{\n\\item{table}{a \\sQuote{covartable} object created by a call to \\code{\\link{covariate_table}}}\n\n\\item{t}{numeric vector; times at which interpolated values of the covariates in \\code{table} are required.}\n}\n\\value{\nA numeric vector or matrix of the interpolated values.\n}\n\\description{\nInterpolate values from a lookup table\n}\n\\section{Extrapolation}{\n\nIf \\code{t} is outside the range of the lookup table, the values will be extrapolated, and a warning will be issued.\nThe type of extrapolation performed will be constant or linear according to the \\code{order} flag used when creating the table.\n}\n\n\\seealso{\nMore on interpolation:\n\\code{\\link{bsplines}},\n\\code{\\link{covariates}}\n}\n\\concept{interpolation}\n"
  },
  {
    "path": "man/macros/citations.Rd",
    "content": "% unlike in latex, new lines within \\newcommand end the command (even using %)\n\n\\newcommand{\\Akinshin2023}{A. Akinshin. Weighted quantile estimators. arXiv:2304.07265, 2023. \\doi{10.48550/arxiv.2304.07265}.}\n\n\\newcommand{\\Anderson2001}{J.L. Anderson. An ensemble adjustment Kalman filter for data assimilation. \\emph{Monthly Weather Review} \\bold{129}, 2884--2903, 2001. \\doi{10.1175/1520-0493(2001)129<2884:AEAKFF>2.0.CO;2}.}\n\n\\newcommand{\\Andrieu2009}{C. Andrieu and G.O. Roberts. The pseudo-marginal approach for computation. \\emph{Annals of Statistics} \\bold{37}, 697--725, 2009. \\doi{10.1214/07-aos574}.}\n\n\\newcommand{\\Andrieu2010}{C. Andrieu, A. Doucet, and R. Holenstein. Particle Markov chain Monte Carlo methods. \\emph{Journal of the Royal Statistical Society, Series B} \\bold{72}, 269--342, 2010. \\doi{10.1111/j.1467-9868.2009.00736.x}.}\n\n\\newcommand{\\Anonymous1978}{Anonymous. Influenza in a boarding school. \\emph{British Medical Journal} \\bold{1}, 587, 1978.}\n\n\\newcommand{\\Arulampalam2002}{M.S. Arulampalam, S. Maskell, N. Gordon, and T. Clapp. A tutorial on particle filters for online nonlinear, non-Gaussian Bayesian tracking. \\emph{IEEE Transactions on Signal Processing} \\bold{50}, 174--188, 2002. \\doi{10.1109/78.978374}.}\n\n\\newcommand{\\Bhadra2016}{A. Bhadra and E.L. Ionides. Adaptive particle allocation in iterated sequential Monte Carlo via approximating meta-models. \\emph{Statistics and Computing} \\bold{26}, 393--407, 2016. \\doi{10.1007/s11222-014-9513-x}.}\n\n\\newcommand{\\Bratley1988}{P. Bratley and B.L. Fox. Algorithm 659 Implementing Sobol's quasirandom sequence generator. \\emph{ACM Transactions on Mathematical Software} \\bold{14}, 88--100, 1988. \\doi{10.1145/42288.214372}.}\n\n\\newcommand{\\Breto2011}{C. Bretó and E. L. Ionides. Compound Markov counting processes and their applications to modeling infinitesimally over-dispersed systems. \\emph{Stochastic Processes and their Applications} \\bold{121}, 2571--2591, 2011. \\doi{10.1016/j.spa.2011.07.005}.}\n\n\\newcommand{\\Brillinger1980}{D.R. Brillinger, J. Guckenheimer, P. Guttorp, and G. Oster. Empirical modelling of population time series: The case of age and density dependent rates. In: G. Oster (ed.), \\emph{Some Questions in Mathematical Biology} vol. 13, pp. 65--90, American Mathematical Society, Providence, 1980. \\doi{10.1007/978-1-4614-1344-8_19}.}\n\n\\newcommand{\\Ellner1998}{S.P. Ellner, B.A. Bailey, G.V. Bobashev, A.R. Gallant, B.T. Grenfell, and D.W. Nychka. Noise and nonlinearity in measles epidemics: combining mechanistic and statistical approaches to population modeling. \\emph{American Naturalist} \\bold{151}, 425--440, 1998. \\doi{10.1086/286130}.}\n\n\\newcommand{\\Evensen1994}{G. Evensen. Sequential data assimilation with a nonlinear quasi-geostrophic model using Monte Carlo methods to forecast error statistics. \\emph{Journal of Geophysical Research: Oceans} \\bold{99}, 10143--10162, 1994. \\doi{10.1029/94JC00572}.}\n\n\\newcommand{\\Evensen2009}{G. Evensen. \\emph{Data assimilation: the ensemble Kalman filter}. Springer-Verlag, 2009. \\doi{10.1007/978-3-642-03711-5}.}\n\n\\newcommand{\\Gurney1980a}{W.S.C. Gurney, S.P. Blythe, and R.M. Nisbet. Nicholson's blowflies revisited. \\emph{Nature} \\bold{287}, 17--21, 1980. \\doi{10.1038/287017a0}.}\n\n\\newcommand{\\Harrell1982}{F. E. Harrell and C. E. Davis. A new distribution-free quantile estimator. \\emph{Biometrika} \\bold{69}, 635--640, 1982. \\doi{10.1093/biomet/69.3.635}.}\n\n\\newcommand{\\He2010}{D. He, E.L. Ionides, and A.A. King. Plug-and-play inference for disease dynamics: measles in large and small populations as a case study.  \\emph{Journal of the Royal Society Interface} \\bold{7}, 271--283, 2010. \\doi{10.1098/rsif.2009.0151}.}\n\n\\newcommand{\\Hyndman1996}{R. J. Hyndman and Y. Fan. Sample quantiles in statistical packages. \\emph{American Statistician} \\bold{50}, 361--365, 1996. \\doi{10.1080/00031305.1996.10473566}.}\n\n\\newcommand{\\Ionides2011}{E.L. Ionides. Discussion of \\dQuote{Feature matching in time series modeling} by Y. Xia and H. Tong. \\emph{Statistical Science} \\bold{26}, 49--52, 2011. \\doi{10.1214/11-sts345c}.}\n\n\\newcommand{\\Ionides2015}{E.L. Ionides, D. Nguyen, Y. Atchadé, S. Stoev, and A.A. King. Inference for dynamic and latent variable models via iterated, perturbed Bayes maps. \\emph{Proceedings of the National Academy of Sciences} \\bold{112}, 719--724, 2015. \\doi{10.1073/pnas.1410597112}.}\n\n\\newcommand{\\Ionides2017}{E. L. Ionides, C. Bretó, J. Park, R. A. Smith, and A. A. King. Monte Carlo profile confidence intervals for dynamic systems. \\emph{Journal of the Royal Society, Interface} \\bold{14}, 20170126, 2017. \\doi{10.1098/rsif.2017.0126}.}\n\n\\newcommand{\\Joe2003}{S. Joe and F.Y. Kuo. Remark on algorithm 659: Implementing Sobol' quasirandom sequence generator. \\emph{ACM Transactions on Mathematical Software} \\bold{29}, 49--57, 2003. \\doi{10.1145/641876.641879}.}\n\n\\newcommand{\\Kendall1999}{B.E. Kendall, C.J. Briggs, W.W. Murdoch, P. Turchin, S.P. Ellner, E. McCauley, R.M. Nisbet, and S.N. Wood. Why do populations cycle? A synthesis of statistical and mechanistic modeling approaches. \\emph{Ecology} \\bold{80}, 1789--1805, 1999. \\doi{10.2307/176658}.}\n\n\\newcommand{\\Kendall2005}{B.E. Kendall, S.P. Ellner, E. McCauley, S.N. Wood, C.J. Briggs, W.W. Murdoch, and P. Turchin. Population cycles in the pine looper moth (\\emph{Bupalus piniarius}): dynamical tests of mechanistic hypotheses. \\emph{Ecological Monographs} \\bold{75} 259--276, 2005. \\doi{10.1890/03-4056}.}\n\n\\newcommand{\\King2008}{A.A. King, E.L. Ionides, M. Pascual, and M.J. Bouma. Inapparent infections and cholera dynamics. \\emph{Nature} \\bold{454}, 877-880, 2008. \\doi{10.1038/nature07084}.}\n\n\\newcommand{\\King2015}{A.A. King, M. Domenech de Cellès, F.M.G. Magpantay, and P. Rohani. Avoidable errors in the modelling of outbreaks of emerging pathogens, with special reference to Ebola. \\emph{Proceedings of the Royal Society of London, Series B} \\bold{282}, 20150347, 2015. \\doi{10.1098/rspb.2015.0347}.}\n\n\\newcommand{\\King2016}{A. A. King, D. Nguyen, and E. L. Ionides. Statistical inference for partially observed Markov processes via the R package \\pkg{pomp}. \\emph{Journal of Statistical Software} \\bold{69}(12), 1--43, 2016. \\doi{10.18637/jss.v069.i12}. An updated version of this paper is available on the \\href{https://kingaa.github.io/pomp/docs.html}{\\pkg{pomp} package website}.}\n\n\\newcommand{\\Kucherenko2005}{S. Kucherenko and Y. Sytsko. Application of deterministic low-discrepancy sequences in global optimization. \\emph{Computational Optimization and Applications} \\bold{30}, 297--318, 2005. \\doi{10.1007/s10589-005-4615-1}.}\n\n\\newcommand{\\Liu2001b}{J. Liu and M. West. Combining parameter and state estimation in simulation-based filtering. In A. Doucet, N. de Freitas, and N. J. Gordon, (eds.), \\emph{Sequential Monte Carlo Methods in Practice}, pp. 197--224. Springer, New York, 2001. \\doi{10.1007/978-1-4757-3437-9_10}.}\n\n\\newcommand{\\London1973}{W. P. London and J. A. Yorke, Recurrent outbreaks of measles, chickenpox and mumps: I. Seasonal variation in contact rates. \\emph{American Journal of Epidemiology} \\bold{98}, 453--468, 1973. \\doi{10.1093/oxfordjournals.aje.a121575}.}\n\n\\newcommand{\\Marin2012}{J.-M. Marin, P. Pudlo, C. P. Robert, and R. J. Ryder. Approximate Bayesian computational methods. \\emph{Statistics and Computing} \\bold{22}, 1167--1180, 2012. \\doi{10.1007/s11222-011-9288-2}.}\n\n\\newcommand{\\McCleery1991}{R. McCleery and C. Perrins. Effects of predation on the numbers of Great Tits, \\emph{Parus major}. In: C.M. Perrins, J.-D. Lebreton, and G.J.M. Hirons (eds.), \\emph{Bird Population Studies}, pp. 129--147, Oxford. Univ. Press, 1991. \\doi{10.1093/oso/9780198577300.003.0006}.}\n\n\\newcommand{\\NLopt}{S.G. Johnson. The \\pkg{NLopt} nonlinear-optimization package. \\url{https://github.com/stevengj/nlopt/}.}\n\n\\newcommand{\\Nicholson1957}{A.J. Nicholson. The self-adjustment of populations to change. \\emph{Cold Spring Harbor Symposia on Quantitative Biology} \\bold{22}, 153--173, 1957. \\doi{10.1101/SQB.1957.022.01.017}.}\n\n\\newcommand{\\Reuman2006}{D.C. Reuman, R.A. Desharnais, R.F. Costantino, O. Ahmad, J.E. Cohen. Power spectra reveal the influence of stochasticity on nonlinear population dynamics. \\emph{Proceedings of the National Academy of Sciences} \\bold{103}, 18860-18865, 2006. \\doi{10.1073/pnas.0608571103}.}\n\n\\newcommand{\\Reuman2008}{D.C. Reuman, R.F. Costantino, R.A. Desharnais, J.E. Cohen. Color of environmental noise affects the nonlinear dynamics of cycling, stage-structured populations. \\emph{Ecology Letters} \\bold{11}, 820-830, 2008. \\doi{10.1111/j.1461-0248.2008.01194.x}.}\n\n\\newcommand{\\Roberts2009}{G.O. Roberts and J.S. Rosenthal. Examples of adaptive MCMC. \\emph{Journal of Computational and Graphical Statistics} \\bold{18}, 349--367, 2009. \\doi{10.1198/jcgs.2009.06134}.}\n\n\\newcommand{\\Toni2009}{T. Toni, D. Welch, N. Strelkowa, A. Ipsen, and M. P. H. Stumpf. Approximate Bayesian computation scheme for parameter inference and model selection in dynamical systems. \\emph{Journal of the Royal Society Interface} \\bold{6}, 187--202, 2009. \\doi{10.1098/rsif.2008.0172}.}\n\n\\newcommand{\\Toni2010}{T. Toni and M. P. H. Stumpf. Simulation-based model selection for dynamical systems in systems and population biology. \\emph{Bioinformatics} \\bold{26}, 104--110, 2010. \\doi{10.1093/bioinformatics/btp619}.}\n\n\\newcommand{\\WHO2014}{WHO Ebola Response Team. Ebola virus disease in West Africa---the first 9 months of the epidemic and forward projections. \\emph{New England Journal of Medicine} \\bold{371}, 1481--1495, 2014. \\doi{10.1056/NEJMoa1411100}.}\n\n\\newcommand{\\Wood2010}{S. N. Wood Statistical inference for noisy nonlinear ecological dynamic systems. \\emph{Nature} \\bold{466}, 1102--1104, 2010. \\doi{10.1038/nature09319}.}\n\n\\newcommand{\\Xia2011}{Y. Xia and H. Tong. Feature matching in time series modeling. \\emph{Statistical Science} \\bold{26}, 21--46, 2011. \\doi{10.1214/10-sts345}.}\n"
  },
  {
    "path": "man/mcap.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/mcap.R\n\\name{mcap}\n\\alias{mcap}\n\\title{Monte Carlo adjusted profile}\n\\usage{\nmcap(logLik, parameter, level = 0.95, span = 0.75, Ngrid = 1000)\n}\n\\arguments{\n\\item{logLik}{numeric; a vector of profile log likelihood evaluations.}\n\n\\item{parameter}{numeric; the corresponding values of the focal parameter.}\n\n\\item{level}{numeric; the confidence level required.}\n\n\\item{span}{numeric; the \\code{\\link[stats]{loess}} smoothing parameter.}\n\n\\item{Ngrid}{integer; the number of points to evaluate the smoothed profile.}\n}\n\\value{\n\\code{mcap} returns a list including the \\code{\\link[stats]{loess}}-smoothed\nprofile, a quadratic approximation, and the constructed confidence interval.\n}\n\\description{\nGiven a collection of points maximizing the likelihood over a range\nof fixed values of a focal parameter, this function constructs\na profile likelihood confidence interval accommodating both\nMonte Carlo error in the profile and statistical uncertainty present\nin the likelihood function.\n}\n\\references{\n\\Ionides2017\n}\n\\author{\nEdward L. Ionides\n}\n\\concept{profile likelihood}\n"
  },
  {
    "path": "man/melt.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/melt.R\n\\name{melt}\n\\alias{melt}\n\\alias{melt,ANY-method}\n\\alias{melt,missing-method}\n\\alias{melt,array-method}\n\\alias{melt,list-method}\n\\title{Melt}\n\\usage{\n\\S4method{melt}{ANY}(data, ...)\n\n\\S4method{melt}{array}(data, ...)\n\n\\S4method{melt}{list}(data, ..., level = 1)\n}\n\\arguments{\n\\item{data}{object to convert}\n\n\\item{...}{ignored}\n\n\\item{level}{integer; level of recursion}\n}\n\\description{\nConvert arrays, lists, and other objects to data frames.\n}\n\\details{\n\\code{melt} converts its first argument to a data frame.\nIt is a simplified version of the \\code{melt} command provided by the no-longer maintained \\pkg{reshape2} package.\n\nAn array can be melted into a data frame.\nIn this case, the data frame will have one row per entry in the array.\n\nA list can be melted into a data frame.\nThis operation is recursive.\nA variable will be appended to distinguish the separate list entries.\n}\n"
  },
  {
    "path": "man/mif2.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/mif2.R\n\\name{mif2}\n\\alias{mif2}\n\\alias{mif2,missing-method}\n\\alias{mif2,ANY-method}\n\\alias{mif2,data.frame-method}\n\\alias{mif2,pomp-method}\n\\alias{mif2,pfilterd_pomp-method}\n\\alias{mif2,mif2d_pomp-method}\n\\title{Iterated filtering: maximum likelihood by iterated, perturbed Bayes maps}\n\\usage{\n\\S4method{mif2}{data.frame}(\n  data,\n  ...,\n  Nmif = 1,\n  rw.sd,\n  cooling.type = c(\"geometric\", \"hyperbolic\"),\n  cooling.fraction.50,\n  Np,\n  params,\n  rinit,\n  rprocess,\n  dmeasure,\n  partrans,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{mif2}{pomp}(\n  data,\n  ...,\n  Nmif = 1,\n  rw.sd,\n  cooling.type = c(\"geometric\", \"hyperbolic\"),\n  cooling.fraction.50,\n  Np,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{mif2}{pfilterd_pomp}(data, ..., Nmif = 1, Np, verbose = getOption(\"verbose\", FALSE))\n\n\\S4method{mif2}{mif2d_pomp}(\n  data,\n  ...,\n  Nmif,\n  rw.sd,\n  cooling.type,\n  cooling.fraction.50,\n  verbose = getOption(\"verbose\", FALSE)\n)\n}\n\\arguments{\n\\item{data}{either a data frame holding the time series data,\nor an object of class \\sQuote{pomp},\ni.e., the output of another \\pkg{pomp} calculation.\nInternally, \\code{data} will be coerced to an array with storage-mode \\code{double}.}\n\n\\item{...}{additional arguments are passed to \\code{\\link{pomp}}.\nThis allows one to set, unset, or modify \\link[=basic_components]{basic model components} within a call to this function.}\n\n\\item{Nmif}{The number of filtering iterations to perform.}\n\n\\item{rw.sd}{specification of the magnitude of the random-walk perturbations that will be applied to some or all model parameters.\nParameters that are to be estimated should have positive perturbations specified here.\nThe specification is given using the \\code{\\link{rw_sd}} function, which creates a list of unevaluated expressions.\nThe latter are evaluated in a context where vector of observation times is visible (as \\sQuote{\\code{time}}).\nThe expression \\code{ivp(s)} can be used in this context as shorthand for \\preformatted{ifelse(time==time[1],s,0).}\nLikewise, \\code{ivp(s,lag)} is equivalent to \\preformatted{ifelse(time==time[lag],s,0).}\nSee below for some examples.\n\nThe perturbations that are applied are normally distributed with the specified s.d.\nIf parameter transformations have been supplied, then the perturbations are applied on the transformed (estimation) scale.}\n\n\\item{cooling.type, cooling.fraction.50}{specifications for the cooling schedule,\ni.e., the manner and rate with which the intensity of the parameter perturbations is reduced with successive filtering iterations.\n\\code{cooling.type} specifies the nature of the cooling schedule.\nSee below (under \\dQuote{Specifying the perturbations}) for more detail.}\n\n\\item{Np}{the number of particles to use.\nThis may be specified as a single positive integer, in which case the same number of particles will be used at each timestep.\nAlternatively, if one wishes the number of particles to vary across timesteps, one may specify \\code{Np} either as a vector of positive integers of length \\preformatted{length(time(object,t0=TRUE))} or as a function taking a positive integer argument.\nIn the latter case, \\code{Np(k)} must be a single positive integer, representing the number of particles to be used at the \\code{k}-th timestep:\n\\code{Np(0)} is the number of particles to use going from \\code{timezero(object)} to \\code{time(object)[1]},\n\\code{Np(1)}, from \\code{timezero(object)} to \\code{time(object)[1]},\nand so on,\nwhile when \\code{T=length(time(object))}, \\code{Np(T)} is the number of particles to sample at the end of the time-series.}\n\n\\item{params}{optional; named numeric vector of parameters.\nThis will be coerced internally to storage mode \\code{double}.}\n\n\\item{rinit}{simulator of the initial-state distribution.\nThis can be furnished either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rinit=NULL} sets the initial-state simulator to its default.\nFor more information, see \\link[=rinit_spec]{rinit specification}.}\n\n\\item{rprocess}{simulator of the latent state process, specified using one of the \\link[=rprocess_spec]{rprocess plugins}.\nSetting \\code{rprocess=NULL} removes the latent-state simulator.\nFor more information, see \\link[=rprocess_spec]{rprocess specification for the documentation on these plugins}.}\n\n\\item{dmeasure}{evaluator of the measurement model density, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{dmeasure=NULL} removes the measurement density evaluator.\nFor more information, see \\link[=dmeasure_spec]{dmeasure specification}.}\n\n\\item{partrans}{optional parameter transformations, constructed using \\code{\\link{parameter_trans}}.\n\nMany algorithms for parameter estimation search an unconstrained space of parameters.\nWhen working with such an algorithm and a model for which the parameters are constrained, it can be useful to transform parameters.\nOne should supply the \\code{partrans} argument via a call to \\code{\\link{parameter_trans}}.\nFor more information, see \\link[=parameter_trans]{parameter_trans}.\nSetting \\code{partrans=NULL} removes the parameter transformations, i.e., sets them to the identity transformation.}\n\n\\item{verbose}{logical; if \\code{TRUE}, diagnostic messages will be printed to the console.}\n}\n\\value{\nUpon successful completion, \\code{mif2} returns an object of class\n\\sQuote{mif2d_pomp}.\n}\n\\description{\nAn iterated filtering algorithm for estimating the parameters of a partially-observed Markov process.\nRunning \\code{mif2} causes the algorithm to perform a specified number of particle-filter iterations.\nAt each iteration, the particle filter is performed on a perturbed version of the model, in which the parameters to be estimated are subjected to random perturbations at each observation.\nThis extra variability effectively smooths the likelihood surface and combats particle depletion by introducing diversity into particle population.\nAs the iterations progress, the magnitude of the perturbations is diminished according to a user-specified cooling schedule.\nThe algorithm is presented and justified in Ionides et al. (2015).\n}\n\\section{Number of particles}{\n\nIf \\code{Np} is anything other than a constant, the user must take care that the number of particles requested at the end of the time series matches that requested at the beginning.\nIn particular, if \\code{T=length(time(object))}, then one should have \\code{Np[1]==Np[T+1]} when \\code{Np} is furnished as an integer vector and \\code{Np(0)==Np(T)} when \\code{Np} is furnished as a function.\n}\n\n\\section{Methods}{\n\nThe following methods are available for such an object:\n\\describe{\n\\item{\\code{\\link{continue}}}{ picks up where \\code{mif2} leaves off and performs more filtering iterations. }\n\\item{\\code{\\link{logLik}}}{ returns the so-called \\dfn{mif log likelihood} which is the log likelihood of the perturbed model, not of the focal model itself.\nTo obtain the latter, it is advisable to run several \\code{\\link{pfilter}} operations on the result of a \\code{mif2} computatation.}\n\\item{\\code{\\link{coef}}}{ extracts the point estimate }\n\\item{\\code{\\link{eff_sample_size}}}{ extracts the effective sample size of the final filtering iteration}\n}\nVarious other methods can be applied, including all the methods applicable to a \\code{\\link[=pfilter]{pfilterd_pomp}} object and all other \\pkg{pomp} estimation algorithms and diagnostic methods.\n}\n\n\\section{Specifying the perturbations}{\n\nThe \\code{rw_sd} function simply returns a list containing its arguments as unevaluated expressions.\nThese are then evaluated in a context in which the vector of observation times is defined (as \\sQuote{\\code{time}}).\nThis allows for easy specification of the structure of the perturbations that are to be applied.\nFor example,\n\\preformatted{\n    rw_sd(\n      a=0.05,\n      b=ifelse(time==time[1], 0.2, 0),\n      c=ivp(0.2),\n      d=ifelse(time==time[13], 0.2, 0),\n      e=ivp(0.2, lag=13),\n      f=ifelse(time<23, 0.02, 0),\n      g=ifelse(time>=23 & time<50, 0.02, 0),\n      h=ivp(0.1,lags=3:8)\n    )\n}\nresults in random perturbations of parameter \\code{a} with s.d. 0.05 at every time step, while parameters \\code{b} and \\code{c} both get perturbations of s.d. 0.2 only before the first observation (i.e., at the zero-time).\nParameters \\code{d} and \\code{e}, by contrast, get perturbations of s.d. 0.2 only before the thirteenth observation.\nParameter \\code{f} gets a random perturbation of size 0.02 before every observation falling before \\eqn{t=23},\nwhile \\code{g} gets perturbed before all observations that fall in the interval \\eqn{23\\le{t}<{50}}{23<=t<50}.\nFinally, the magnitude of the perturbation of parameter \\code{h} is applied before the third through eighth observations.\n\nOn the \\eqn{m}-th IF2 iteration, prior to time-point \\eqn{n}, the \\eqn{d}-th parameter is given a random increment normally distributed with mean \\eqn{0} and standard deviation \\eqn{c_{m,n} \\sigma_{d,n}}{c[m,n] sigma[d,n]}, where \\eqn{c} is the cooling schedule and \\eqn{\\sigma}{sigma} is specified using \\code{rw_sd}, as described above.\nLet \\eqn{N} be the length of the time series and \\eqn{\\alpha=}{alpha=}\\code{cooling.fraction.50}.\nThen, when \\code{cooling.type=\"geometric\"}, we have \\deqn{c_{m,n}=\\alpha^{\\frac{n-1+(m-1)N}{50N}}.}{c[m,n]=alpha^((n-1+(m-1)N)/(50N)).}\nWhen \\code{cooling.type=\"hyperbolic\"}, we have \\deqn{c_{m,n}=\\frac{s+1}{s+n+(m-1)N},}{c[m,n]=(s+1)/(s+n+(m-1)N),} where \\eqn{s} satisfies \\deqn{\\frac{s+1}{s+50N}=\\alpha.}{(s+1)/(s+50N)=alpha.}\nThus, in either case, the perturbations at the end of 50 IF2 iterations are a fraction \\eqn{\\alpha}{alpha} smaller than they are at first.\n}\n\n\\section{Re-running IF2 iterations}{\n\nTo re-run a sequence of IF2 iterations, one can use the \\code{mif2} method on a \\sQuote{mif2d_pomp} object.\nBy default, the same parameters used for the original IF2 run are re-used (except for \\code{verbose}, the default of which is shown above).\nIf one does specify additional arguments, these will override the defaults.\n}\n\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\references{\n\\Ionides2015\n}\n\\seealso{\nMore on full-information (i.e., likelihood-based) methods:\n\\code{\\link{bsmc2}()},\n\\code{\\link{pfilter}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{wpfilter}()}\n\nMore on sequential Monte Carlo methods:\n\\code{\\link{bsmc2}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{kalman}},\n\\code{\\link{pfilter}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{wpfilter}()}\n\nMore on \\pkg{pomp} estimation algorithms:\n\\code{\\link{abc}()},\n\\code{\\link{bsmc2}()},\n\\code{\\link{estimation_algorithms}},\n\\code{\\link{nlf}},\n\\code{\\link{pmcmc}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{probe_match}},\n\\code{\\link{spect_match}}\n\nMore on maximization-based estimation methods:\n\\code{\\link{nlf}},\n\\code{\\link{probe_match}},\n\\code{\\link{spect_match}},\n\\code{\\link{traj_match}}\n}\n\\author{\nAaron A. King, Edward L. Ionides, Dao Nguyen\n}\n\\concept{estimation methods}\n\\concept{full-information methods}\n\\concept{methods based on maximization}\n\\concept{particle filter methods}\n"
  },
  {
    "path": "man/nlf.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/nlf.R\n\\name{nlf}\n\\alias{nlf}\n\\alias{nlf_objfun}\n\\alias{nlf_objfun,missing-method}\n\\alias{nlf_objfun,ANY-method}\n\\alias{nlf_objfun,data.frame-method}\n\\alias{nlf_objfun,pomp-method}\n\\alias{nlf_objfun,nlf_objfun-method}\n\\title{Nonlinear forecasting}\n\\usage{\n\\S4method{nlf_objfun}{data.frame}(\n  data,\n  ...,\n  est = character(0),\n  lags,\n  nrbf = 4,\n  ti,\n  tf,\n  seed = NULL,\n  transform.data = identity,\n  period = NA,\n  tensor = TRUE,\n  fail.value = NA_real_,\n  params,\n  rinit,\n  rprocess,\n  rmeasure,\n  verbose = getOption(\"verbose\")\n)\n\n\\S4method{nlf_objfun}{pomp}(\n  data,\n  ...,\n  est = character(0),\n  lags,\n  nrbf = 4,\n  ti,\n  tf,\n  seed = NULL,\n  transform.data = identity,\n  period = NA,\n  tensor = TRUE,\n  fail.value = NA,\n  verbose = getOption(\"verbose\")\n)\n\n\\S4method{nlf_objfun}{nlf_objfun}(\n  data,\n  ...,\n  est,\n  lags,\n  nrbf,\n  ti,\n  tf,\n  seed = NULL,\n  period,\n  tensor,\n  transform.data,\n  fail.value,\n  verbose = getOption(\"verbose\", FALSE)\n)\n}\n\\arguments{\n\\item{data}{either a data frame holding the time series data,\nor an object of class \\sQuote{pomp},\ni.e., the output of another \\pkg{pomp} calculation.\nInternally, \\code{data} will be coerced to an array with storage-mode \\code{double}.}\n\n\\item{...}{additional arguments are passed to \\code{\\link{pomp}}.\nThis allows one to set, unset, or modify \\link[=basic_components]{basic model components} within a call to this function.}\n\n\\item{est}{character vector; the names of parameters to be estimated.}\n\n\\item{lags}{A vector specifying the lags to use when constructing the nonlinear autoregressive prediction model.\nThe first lag is the prediction interval.}\n\n\\item{nrbf}{integer scalar;\nthe number of radial basis functions to be used at each lag.}\n\n\\item{ti, tf}{required numeric values.\nNLF works by generating simulating long time series from the model.\nThe simulated time series will be from \\code{ti} to \\code{tf}, with the same sampling frequency as the data.\n\\code{ti} should be chosen large enough so that transient dynamics have died away.\n\\code{tf} should be chosen large enough so that sufficiently many data points are available to estimate the nonlinear forecasting model well.\nAn error will be generated unless the data-to-parameter ratio exceeds 10 and\na warning will be given if the ratio is smaller than 30.}\n\n\\item{seed}{integer.\nWhen fitting, it is often best to fix the seed of the random-number generator (RNG).\nThis is accomplished by setting \\code{seed} to an integer.\nBy default, \\code{seed = NULL}, which does not alter the RNG state.}\n\n\\item{transform.data}{optional function.\nIf specified, forecasting is performed using data and model simulations transformed by this function.\nBy default, \\code{transform.data} is the identity function,\ni.e., no transformation is performed.\nThe main purpose of \\code{transform.data} is to achieve approximately multivariate normal forecasting errors.\nIf the data are univariate, \\code{transform.data} should take a scalar and return a scalar.\nIf the data are multivariate, \\code{transform.data} should assume a vector input and return a vector of the same length.}\n\n\\item{period}{numeric; \\code{period=NA} means the model is nonseasonal.\n\\code{period > 0} is the period of seasonal forcing.\n\\code{period <= 0} is equivalent to \\code{period = NA}.}\n\n\\item{tensor}{logical;\nif FALSE, the fitted model is a generalized additive model with time mod period as one of the predictors,\ni.e., a gam with time-varying intercept.\nIf TRUE, the fitted model is a gam with lagged state variables as predictors and time-periodic coefficients, constructed using tensor products of basis functions of state variables with basis\nfunctions of time.}\n\n\\item{fail.value}{optional numeric scalar;\nif non-\\code{NA}, this value is substituted for non-finite values of the objective function.\nIt should be a large number (i.e., bigger than any legitimate values the objective function is likely to take).}\n\n\\item{params}{optional; named numeric vector of parameters.\nThis will be coerced internally to storage mode \\code{double}.}\n\n\\item{rinit}{simulator of the initial-state distribution.\nThis can be furnished either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rinit=NULL} sets the initial-state simulator to its default.\nFor more information, see \\link[=rinit_spec]{rinit specification}.}\n\n\\item{rprocess}{simulator of the latent state process, specified using one of the \\link[=rprocess_spec]{rprocess plugins}.\nSetting \\code{rprocess=NULL} removes the latent-state simulator.\nFor more information, see \\link[=rprocess_spec]{rprocess specification for the documentation on these plugins}.}\n\n\\item{rmeasure}{simulator of the measurement model, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rmeasure=NULL} removes the measurement model simulator.\nFor more information, see \\link[=rmeasure_spec]{rmeasure specification}.}\n\n\\item{verbose}{logical; if \\code{TRUE}, diagnostic messages will be printed to the console.}\n}\n\\value{\n\\code{nlf_objfun} constructs a stateful objective function for NLF estimation.\nSpecfically, \\code{nlf_objfun} returns an object of class \\sQuote{nlf_objfun}, which is a function suitable for use in an \\code{\\link[stats]{optim}}-like optimizer.\nIn particular, this function takes a single numeric-vector argument that is assumed to contain the parameters named in \\code{est}, in that order.\nWhen called, it will return the negative log quasilikelihood.\nIt is a stateful function:\nEach time it is called, it will remember the values of the parameters and its estimate of the log quasilikelihood.\n}\n\\description{\nParameter estimation by maximum simulated quasi-likelihood.\n}\n\\details{\nNonlinear forecasting (NLF) is an \\sQuote{indirect inference} method.\nThe NLF approximation to the log likelihood of the data series is computed by simulating data from a model, fitting a nonlinear autoregressive model to the simulated time series, and quantifying the ability of the resulting fitted model to predict the data time series.\nThe nonlinear autoregressive model is implemented as a generalized additive model (GAM), conditional on lagged values, for each observation variable.\nThe errors are assumed multivariate normal.\n\nThe NLF objective function constructed by \\code{nlf_objfun} simulates long time series (\\code{nasymp} is the number of observations in the simulated times series), perhaps after allowing for a transient period (\\code{ntransient} steps).\nIt then fits the GAM for the chosen lags to the simulated time series.\nFinally, it computes the quasi-likelihood of the data under the fitted GAM.\n\nNLF assumes that the observation frequency (equivalently the time between successive observations) is uniform.\n}\n\\section{Periodically-forced systems (seasonality)}{\n\nUnlike other \\pkg{pomp} estimation methods, NLF cannot accommodate general time-dependence in the model via explicit time-dependence or dependence on time-varying covariates.\nHowever, NLF can accommodate periodic forcing.\nIt does this by including forcing phase as a predictor in the nonlinear autoregressive model.\nTo accomplish this, one sets \\code{period} to the period of the forcing (a positive numerical value).\nIn this case, if \\code{tensor = FALSE}, the effect is to add a periodic intercept in the autoregressive model.\nIf \\code{tensor = TRUE}, by contrast, the fitted model includes time-periodic coefficients,\nconstructed using tensor products of basis functions of observables with\nbasis functions of time.\n}\n\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\section{Important Note}{\n\nSince \\pkg{pomp} cannot guarantee that the \\emph{final} call an optimizer makes to the function is a call \\emph{at} the optimum, it cannot guarantee that the parameters stored in the function are the optimal ones.\nTherefore, it is a good idea to evaluate the function on the parameters returned by the optimization routine, which will ensure that these parameters are stored.\n}\n\n\\section{Warning! Objective functions based on C snippets}{\n\nIf you use C snippets (see \\code{\\link{Csnippet}}), a dynamically loadable library will be built.\nAs a rule, \\pkg{pomp} functions load this library as needed and unload it when it is no longer needed.\nThe stateful objective functions are an exception to this rule.\nFor efficiency, calls to the objective function do not execute \\code{\\link{pompLoad}} or \\code{\\link{pompUnload}}:\nrather, it is assumed that \\code{\\link{pompLoad}} has been called before any call to the objective function.\nWhen a stateful objective function using one or more C snippets is created, \\code{\\link{pompLoad}} is called internally to build and load the library:\ntherefore, within a single \\R session, if one creates a stateful objective function, one can freely call that objective function and (more to the point) pass it to an optimizer that calls it freely, without needing to call \\code{\\link{pompLoad}}.\nOn the other hand, if one retrieves a stored objective function from a file, or passes one to another \\R session, one must call \\code{\\link{pompLoad}} before using it.\n\\strong{Failure to do this will typically result in a segmentation fault (i.e., it will crash the \\R session).}\n}\n\n\\examples{\n\\donttest{\n\n  if (require(subplex)) {\n\n    ricker() |>\n      nlf_objfun(est=c(\"r\",\"sigma\",\"N_0\"),lags=c(4,6),\n        partrans=parameter_trans(log=c(\"r\",\"sigma\",\"N_0\")),\n        paramnames=c(\"r\",\"sigma\",\"N_0\"),\n        ti=100,tf=2000,seed=426094906L) -> m1\n\n    subplex(par=log(c(20,0.5,5)),fn=m1,control=list(reltol=1e-4)) -> out\n\n    m1(out$par)\n    coef(m1)\n    plot(simulate(m1))\n\n  }\n}\n}\n\\references{\n\\Ellner1998\n\n\\Kendall1999\n\n\\Kendall2005\n}\n\\seealso{\n\\code{\\link[stats]{optim}} \\code{\\link[subplex]{subplex}} \\code{\\link[nloptr]{nloptr}}\n\nMore on \\pkg{pomp} estimation algorithms:\n\\code{\\link{abc}()},\n\\code{\\link{bsmc2}()},\n\\code{\\link{estimation_algorithms}},\n\\code{\\link{mif2}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{probe_match}},\n\\code{\\link{spect_match}}\n\nMore on methods based on summary statistics:\n\\code{\\link{abc}()},\n\\code{\\link{basic_probes}},\n\\code{\\link{probe}()},\n\\code{\\link{probe_match}},\n\\code{\\link{spect}()},\n\\code{\\link{spect_match}}\n\nMore on maximization-based estimation methods:\n\\code{\\link{mif2}()},\n\\code{\\link{probe_match}},\n\\code{\\link{spect_match}},\n\\code{\\link{traj_match}}\n}\n\\author{\nStephen P. Ellner, Bruce E. Kendall, Aaron A. King\n}\n\\concept{estimation methods}\n\\concept{methods based on maximization}\n\\concept{nonlinear forecasting}\n\\concept{summary statistic-based methods}\n"
  },
  {
    "path": "man/objfun.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/objfun.R\n\\name{objfun}\n\\alias{objfun}\n\\title{Objective functions}\n\\description{\nMethods common to \\pkg{pomp} stateful objective functions\n}\n\\section{Important Note}{\n\nSince \\pkg{pomp} cannot guarantee that the \\emph{final} call an optimizer makes to the function is a call \\emph{at} the optimum, it cannot guarantee that the parameters stored in the function are the optimal ones.\nTherefore, it is a good idea to evaluate the function on the parameters returned by the optimization routine, which will ensure that these parameters are stored.\n}\n\n\\section{Warning! Objective functions based on C snippets}{\n\nIf you use C snippets (see \\code{\\link{Csnippet}}), a dynamically loadable library will be built.\nAs a rule, \\pkg{pomp} functions load this library as needed and unload it when it is no longer needed.\nThe stateful objective functions are an exception to this rule.\nFor efficiency, calls to the objective function do not execute \\code{\\link{pompLoad}} or \\code{\\link{pompUnload}}:\nrather, it is assumed that \\code{\\link{pompLoad}} has been called before any call to the objective function.\nWhen a stateful objective function using one or more C snippets is created, \\code{\\link{pompLoad}} is called internally to build and load the library:\ntherefore, within a single \\R session, if one creates a stateful objective function, one can freely call that objective function and (more to the point) pass it to an optimizer that calls it freely, without needing to call \\code{\\link{pompLoad}}.\nOn the other hand, if one retrieves a stored objective function from a file, or passes one to another \\R session, one must call \\code{\\link{pompLoad}} before using it.\n\\strong{Failure to do this will typically result in a segmentation fault (i.e., it will crash the \\R session).}\n}\n\n\\keyword{internal}\n"
  },
  {
    "path": "man/obs.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/obs.R\n\\docType{methods}\n\\name{obs}\n\\alias{obs}\n\\alias{obs,ANY-method}\n\\alias{obs,missing-method}\n\\alias{obs,pomp-method}\n\\alias{obs,listie-method}\n\\title{obs}\n\\usage{\n\\S4method{obs}{pomp}(object, vars, ..., format = c(\"array\", \"data.frame\"))\n\n\\S4method{obs}{listie}(object, vars, ..., format = c(\"array\", \"data.frame\"))\n}\n\\arguments{\n\\item{object}{an object of class \\sQuote{pomp}, or of a class extending \\sQuote{pomp}}\n\n\\item{vars}{names of variables to retrieve}\n\n\\item{\\dots}{ignored}\n\n\\item{format}{format of the returned object}\n}\n\\description{\nExtract the data array from a \\sQuote{pomp} object.\n}\n\\seealso{\nOther extraction methods: \n\\code{\\link{coef}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{covmat}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{forecast}()},\n\\code{\\link{logLik}},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{spy}()},\n\\code{\\link{states}()},\n\\code{\\link{summary}()},\n\\code{\\link{time}()},\n\\code{\\link{timezero}()},\n\\code{\\link{traces}()}\n}\n\\concept{extraction methods}\n"
  },
  {
    "path": "man/ou2.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/ou2.R\n\\docType{data}\n\\name{ou2}\n\\alias{ou2}\n\\title{Two-dimensional discrete-time Ornstein-Uhlenbeck process}\n\\usage{\nou2(\n  alpha_1 = 0.8,\n  alpha_2 = -0.5,\n  alpha_3 = 0.3,\n  alpha_4 = 0.9,\n  sigma_1 = 3,\n  sigma_2 = -0.5,\n  sigma_3 = 2,\n  tau = 1,\n  x1_0 = -3,\n  x2_0 = 4,\n  times = 1:100,\n  t0 = 0,\n  seed = 787832394L\n)\n}\n\\arguments{\n\\item{alpha_1, alpha_2, alpha_3, alpha_4}{entries of the \\eqn{\\alpha} matrix, in column-major order.\nThat is, \\code{alpha_2} is in the lower-left position.}\n\n\\item{sigma_1, sigma_2, sigma_3}{entries of the lower-triangular \\eqn{\\sigma} matrix.\n\\code{sigma_2} is the entry in the lower-left position.}\n\n\\item{tau}{measurement error s.d.}\n\n\\item{x1_0, x2_0}{latent variable values at time \\code{t0}}\n\n\\item{times}{vector of observation times}\n\n\\item{t0}{the zero time}\n\n\\item{seed}{seed of the random number generator}\n}\n\\value{\nA \\sQuote{pomp} object with simulated data.\n}\n\\description{\n\\code{ou2()} constructs a \\sQuote{pomp} object encoding a bivariate discrete-time Ornstein-Uhlenbeck process with noisy observations.\n}\n\\details{\nIf the state process is \\eqn{X(t) = (X_{1}(t),X_{2}(t))}, then\n\\deqn{X(t+1) = \\alpha X(t) + \\sigma \\epsilon(t),}\nwhere \\eqn{\\alpha} and \\eqn{\\sigma} are 2x2 matrices,\n\\eqn{\\sigma} is lower-triangular, and\n\\eqn{\\epsilon(t)} is standard bivariate normal.\nThe observation process is \\eqn{Y(t) = (Y_1(t),Y_2(t))}, where\n\\eqn{Y_i(t) \\sim \\mathrm{normal}(X_i(t),\\tau)}.\n}\n\\examples{\npo <- ou2()\nplot(po)\ncoef(po)\nx <- simulate(po)\nplot(x)\npf <- pfilter(po,Np=1000)\nlogLik(pf)\n}\n\\seealso{\nMore examples provided with \\pkg{pomp}:\n\\code{\\link{blowflies}},\n\\code{\\link{childhood_disease_data}},\n\\code{\\link{compartmental_models}},\n\\code{\\link{dacca}()},\n\\code{\\link{ebola}},\n\\code{\\link{gompertz}()},\n\\code{\\link{pomp_examples}},\n\\code{\\link{ricker}()},\n\\code{\\link{rw2}()},\n\\code{\\link{verhulst}()}\n}\n\\concept{pomp examples}\n\\keyword{models}\n"
  },
  {
    "path": "man/pStop.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/pstop.R\n\\name{pStop}\n\\alias{pStop}\n\\alias{pStop_}\n\\alias{pWarn}\n\\alias{pWarn_}\n\\alias{pMess}\n\\alias{pMess_}\n\\title{pStop, pWarn, pMess}\n\\usage{\npStop(..., who = -1L)\n\npStop_(...)\n\npWarn(..., who = -1L)\n\npWarn_(...)\n\npMess(..., who = -1L)\n\npMess_(...)\n}\n\\arguments{\n\\item{\\dots}{message}\n\n\\item{who}{integer or character.\nIf \\code{who} is an integer, it is passed to \\code{\\link{sys.call}} to retrieve the name of the calling function.\nOne can also pass the name of the calling function in \\code{who}.\nIn either case, the name of the calling function is included in the message.}\n}\n\\description{\nCustom error, warning, and message functions.\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/parameter_trans.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/parameter_trans.R\n\\docType{methods}\n\\name{parameter_trans}\n\\alias{parameter_trans}\n\\alias{parameter_trans,missing,missing-method}\n\\alias{parameter_trans,ANY,ANY-method}\n\\alias{parameter_trans,ANY,missing-method}\n\\alias{parameter_trans,NULL,NULL-method}\n\\alias{parameter_trans,missing,ANY-method}\n\\alias{parameter_trans,pomp_fun,pomp_fun-method}\n\\alias{parameter_trans,Csnippet,Csnippet-method}\n\\alias{parameter_trans,character,character-method}\n\\alias{parameter_trans,function,function-method}\n\\title{parameter transformations}\n\\usage{\nparameter_trans(toEst, fromEst, ...)\n\n\\S4method{parameter_trans}{NULL,NULL}(toEst, fromEst, ...)\n\n\\S4method{parameter_trans}{pomp_fun,pomp_fun}(toEst, fromEst, ...)\n\n\\S4method{parameter_trans}{Csnippet,Csnippet}(toEst, fromEst, ..., log, logit, barycentric)\n\n\\S4method{parameter_trans}{character,character}(toEst, fromEst, ...)\n\n\\S4method{parameter_trans}{function,function}(toEst, fromEst, ...)\n}\n\\arguments{\n\\item{toEst, fromEst}{procedures that perform transformation of model parameters to and from the estimation scale, respectively.\nThese can be furnished using C snippets, \\R functions, or via procedures in an external, dynamically loaded library.}\n\n\\item{\\dots}{ignored.}\n\n\\item{log}{names of parameters to be log transformed.}\n\n\\item{logit}{names of parameters to be logit transformed.}\n\n\\item{barycentric}{names of parameters to be collectively transformed according to the log barycentric transformation.\n\\strong{Important note:} variables to be log-barycentrically transformed \\emph{must be adjacent} in the parameter vector.}\n}\n\\description{\nEquipping models with parameter transformations to facilitate searches in constrained parameter spaces.\n}\n\\details{\nWhen parameter transformations are desired, they can be integrated into the \\sQuote{pomp} object via the \\code{partrans} arguments using the \\code{parameter_trans} function.\nAs with the other \\link[=basic_components]{basic model components}, these should ordinarily be specified using C snippets.\nWhen doing so, note that:\n\\enumerate{\n  \\item The parameter transformation mapping a parameter vector from the scale used by the model codes to another scale, and the inverse transformation, are specified via a call to \\preformatted{parameter_trans(toEst,fromEst)}.\n  \\item The goal of these snippets is the transformation of the parameters from the natural scale to the estimation scale, and vice-versa.\n  If \\code{p} is the name of a variable on the natural scale, its value on the estimation scale is \\code{T_p}.\n  Thus the \\code{toEst} snippet computes \\code{T_p} given \\code{p} whilst the \\code{fromEst} snippet computes \\code{p} given \\code{T_p}.\n  \\item Time-, state-, and covariate-dependent transformations are not allowed.\n  Therefore, neither the time, nor any state variables, nor any of the covariates will be available in the context within which a parameter transformation snippet is executed.\n}\n\nThese transformations can also be specified using \\R functions with arguments chosen from among the parameters.\nSuch an \\R function must also have the argument \\sQuote{\\code{...}}.\nIn this case, \\code{toEst} should transform parameters from the scale that the basic components use internally to the scale used in estimation.\n\\code{fromEst} should be the inverse of \\code{toEst}.\n\nNote that it is the user's responsibility to make sure that the transformations are mutually inverse.\nIf \\code{obj} is the constructed \\sQuote{pomp} object, and \\code{coef(obj)} is non-empty, a simple check of this property is \\preformatted{\n  x <- coef(obj, transform = TRUE)\n  obj1 <- obj\n  coef(obj1, transform = TRUE) <- x\n  identical(coef(obj), coef(obj1))\n  identical(coef(obj1, transform=TRUE), x)}\n\nOne can use the \\code{log} and \\code{logit} arguments of \\code{parameter_trans} to name variables that should be log-transformed or logit-transformed, respectively.\nThe \\code{barycentric} argument can name sets of parameters that should be log-barycentric transformed.\n\nNote that using the \\code{log}, \\code{logit}, or \\code{barycentric} arguments causes C snippets to be generated.\nTherefore, you must make sure that variables named in any of these arguments are also mentioned in \\code{paramnames} at the same time.\n\nThe logit transform is defined by\n\\deqn{\\mathrm{logit}(\\theta)=\\log\\frac{\\theta}{1-\\theta}.}{logit(theta) = log(theta/(1-theta)).}\n\nThe log barycentric transformation of variables \\eqn{\\theta_1,\\dots,\\theta_n}{theta1,\\dots,thetan} is given by\n\\deqn{\\mathrm{logbarycentric}(\\theta_1,\\dots,\\theta_n)=\\left(\\log\\frac{\\theta_1}{\\sum_i \\theta_i},\\dots,\\log\\frac{\\theta_n}{\\sum_i \\theta_i}\\right).}{logbarycentric(theta1,\\dots,thetan)=(log(theta1/sum(theta)),\\dots,log(thetan/sum(theta))).}\n}\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\seealso{\n\\code{\\link{partrans}}\n\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{accumvars}},\n\\code{\\link{basic_components}},\n\\code{\\link{betabinomial}},\n\\code{\\link{covariates}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{pomp-package}},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{userdata}},\n\\code{\\link{vmeasure_spec}}\n}\n\\concept{implementation information}\n"
  },
  {
    "path": "man/parmat.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/parmat.R\n\\name{parmat}\n\\alias{parmat}\n\\alias{parmat,missing-method}\n\\alias{parmat,ANY-method}\n\\alias{parmat,numeric-method}\n\\alias{parmat,array-method}\n\\alias{parmat,data.frame-method}\n\\title{Create a matrix of parameters}\n\\usage{\nparmat(params, ...)\n\n\\S4method{parmat}{numeric}(params, nrep = 1, ..., names = NULL)\n\n\\S4method{parmat}{array}(params, nrep = 1, ..., names = NULL)\n\n\\S4method{parmat}{data.frame}(params, nrep = 1, ...)\n}\n\\arguments{\n\\item{params}{named numeric vector or matrix of parameters.}\n\n\\item{...}{additional arguments, currently ignored.}\n\n\\item{nrep}{number of replicates (columns) desired.}\n\n\\item{names}{optional character; column names.}\n}\n\\value{\n\\code{parmat} returns a matrix consisting of \\code{nrep} copies of\n\\code{params}.\n}\n\\description{\n\\code{parmat} is a utility that makes a vector of parameters suitable for\nuse in \\pkg{pomp} functions.\n}\n\\examples{\n\\donttest{ # takes too long for R CMD check\n  ## generate a bifurcation diagram for the Ricker map\n  p <- parmat(coef(ricker()),nrep=500)\n  p[\"r\",] <- exp(seq(from=1.5,to=4,length=500))\n  trajectory(\n    ricker(),\n    times=seq(from=1000,to=2000,by=1),\n    params=p,\n    format=\"array\"\n  ) -> x\n  matplot(p[\"r\",],x[\"N\",,],pch='.',col='black',\n    xlab=expression(log(r)),ylab=\"N\",log='x')\n}\n}\n\\author{\nAaron A. King\n}\n"
  },
  {
    "path": "man/partrans.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/workhorses.R, R/objfun.R\n\\docType{methods}\n\\name{partrans}\n\\alias{partrans}\n\\alias{partrans,ANY-method}\n\\alias{partrans,missing-method}\n\\alias{partrans,pomp-method}\n\\alias{partrans,objfun-method}\n\\title{partrans workhorse}\n\\usage{\n\\S4method{partrans}{pomp}(object, params, ..., dir = c(\"fromEst\", \"toEst\"))\n\n\\S4method{partrans}{objfun}(object, ...)\n}\n\\arguments{\n\\item{object}{an object of class \\sQuote{pomp}, or of a class that extends \\sQuote{pomp}.\nThis will typically be the output of \\code{pomp}, \\code{simulate}, or one of the \\pkg{pomp} inference algorithms.}\n\n\\item{params}{a \\code{npar} x \\code{nrep} matrix of parameters.\nEach column is treated as an independent parameter set, in correspondence with the corresponding column of \\code{x}.}\n\n\\item{...}{additional arguments are ignored.}\n\n\\item{dir}{the direction of the transformation to perform.}\n}\n\\value{\nIf \\code{dir=fromEst}, the parameters in \\code{params} are assumed to be on the estimation scale and are transformed onto the natural scale.\nIf \\code{dir=toEst}, they are transformed onto the estimation scale.\nIn both cases, the parameters are returned as a named numeric vector or an array with rownames, as appropriate.\n}\n\\description{\nPerforms parameter transformations.\n}\n\\seealso{\nSpecification of parameter transformations: \\code{\\link{parameter_trans}}\n\nMore on \\pkg{pomp} workhorse functions:\n\\code{\\link{dinit}()},\n\\code{\\link{dmeasure}()},\n\\code{\\link{dprior}()},\n\\code{\\link{dprocess}()},\n\\code{\\link{emeasure}()},\n\\code{\\link{flow}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{rinit}()},\n\\code{\\link{rmeasure}()},\n\\code{\\link{rprior}()},\n\\code{\\link{rprocess}()},\n\\code{\\link{skeleton}()},\n\\code{\\link{vmeasure}()},\n\\code{\\link{workhorses}}\n}\n\\concept{extending the pomp package}\n\\concept{low-level interface}\n\\concept{pomp workhorses}\n"
  },
  {
    "path": "man/parus.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/parus.R\n\\docType{data}\n\\name{parus}\n\\alias{parus}\n\\title{Parus major population dynamics}\n\\description{\nSize of a population of great tits (\\emph{Parus major}) from Wytham Wood, near Oxford.\n}\n\\details{\nProvenance: Global Population Dynamics Database dataset #10163.\n(NERC Centre for Population Biology, Imperial College (2010)\nThe Global Population Dynamics Database Version 2.\n\\url{https://www.imperial.ac.uk/cpb/gpdd2/}).\nOriginal source: McCleer and Perrins (1991).\n}\n\\examples{\n\\donttest{ # takes too long for R CMD check\n  parus |>\n    pfilter(Np=1000,times=\"year\",t0=1960,\n      params=c(K=190,r=2.7,sigma=0.2,theta=0.05,N.0=148),\n      rprocess=discrete_time(\n        function (r, K, sigma, N, ...) {\n          e <- rnorm(n=1,mean=0,sd=sigma)\n          c(N = exp(log(N)+r*(1-N/K)+e))\n        },\n        delta.t=1\n      ),\n      rmeasure=function (N, theta, ...) {\n        c(pop=rnbinom(n=1,size=1/theta,mu=N+1e-10))\n      },\n      dmeasure=function (pop, N, theta, ..., log) {\n        dnbinom(x=pop,mu=N+1e-10,size=1/theta,log=log)\n      },\n      partrans=parameter_trans(log=c(\"sigma\",\"theta\",\"N_0\",\"r\",\"K\")),\n      paramnames=c(\"sigma\",\"theta\",\"N_0\",\"r\",\"K\")\n    ) -> pf\n\n  pf |> logLik()\n\n  pf |> simulate() |> plot()\n}\n}\n\\references{\n\\McCleery1991\n}\n\\seealso{\nMore data sets provided with \\pkg{pomp}:\n\\code{\\link{blowflies}},\n\\code{\\link{bsflu}},\n\\code{\\link{childhood_disease_data}},\n\\code{\\link{dacca}()},\n\\code{\\link{ebola}}\n}\n\\concept{pomp datasets}\n"
  },
  {
    "path": "man/pfilter.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/pfilter.R, R/objfun.R\n\\name{pfilter}\n\\alias{pfilter}\n\\alias{pfilter,ANY-method}\n\\alias{pfilter,missing-method}\n\\alias{pfilter,data.frame-method}\n\\alias{pfilter,pomp-method}\n\\alias{pfilter,pfilterd_pomp-method}\n\\alias{pfilter,objfun-method}\n\\title{Particle filter}\n\\usage{\n\\S4method{pfilter}{data.frame}(\n  data,\n  ...,\n  Np,\n  params,\n  rinit,\n  rprocess,\n  dmeasure,\n  pred.mean = FALSE,\n  pred.var = FALSE,\n  filter.mean = FALSE,\n  filter.traj = FALSE,\n  save.states = c(\"no\", \"filter\", \"prediction\", \"weighted\", \"unweighted\", \"FALSE\",\n    \"TRUE\"),\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{pfilter}{pomp}(\n  data,\n  ...,\n  Np,\n  pred.mean = FALSE,\n  pred.var = FALSE,\n  filter.mean = FALSE,\n  filter.traj = FALSE,\n  save.states = c(\"no\", \"filter\", \"prediction\", \"weighted\", \"unweighted\", \"FALSE\",\n    \"TRUE\"),\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{pfilter}{pfilterd_pomp}(data, ..., Np, verbose = getOption(\"verbose\", FALSE))\n\n\\S4method{pfilter}{objfun}(data, ...)\n}\n\\arguments{\n\\item{data}{either a data frame holding the time series data,\nor an object of class \\sQuote{pomp},\ni.e., the output of another \\pkg{pomp} calculation.\nInternally, \\code{data} will be coerced to an array with storage-mode \\code{double}.}\n\n\\item{...}{additional arguments are passed to \\code{\\link{pomp}}.\nThis allows one to set, unset, or modify \\link[=basic_components]{basic model components} within a call to this function.}\n\n\\item{Np}{the number of particles to use.\nThis may be specified as a single positive integer, in which case the same number of particles will be used at each timestep.\nAlternatively, if one wishes the number of particles to vary across timesteps, one may specify \\code{Np} either as a vector of positive integers of length \\preformatted{length(time(object,t0=TRUE))} or as a function taking a positive integer argument.\nIn the latter case, \\code{Np(k)} must be a single positive integer, representing the number of particles to be used at the \\code{k}-th timestep:\n\\code{Np(0)} is the number of particles to use going from \\code{timezero(object)} to \\code{time(object)[1]},\n\\code{Np(1)}, from \\code{timezero(object)} to \\code{time(object)[1]},\nand so on,\nwhile when \\code{T=length(time(object))}, \\code{Np(T)} is the number of particles to sample at the end of the time-series.}\n\n\\item{params}{optional; named numeric vector of parameters.\nThis will be coerced internally to storage mode \\code{double}.}\n\n\\item{rinit}{simulator of the initial-state distribution.\nThis can be furnished either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rinit=NULL} sets the initial-state simulator to its default.\nFor more information, see \\link[=rinit_spec]{rinit specification}.}\n\n\\item{rprocess}{simulator of the latent state process, specified using one of the \\link[=rprocess_spec]{rprocess plugins}.\nSetting \\code{rprocess=NULL} removes the latent-state simulator.\nFor more information, see \\link[=rprocess_spec]{rprocess specification for the documentation on these plugins}.}\n\n\\item{dmeasure}{evaluator of the measurement model density, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{dmeasure=NULL} removes the measurement density evaluator.\nFor more information, see \\link[=dmeasure_spec]{dmeasure specification}.}\n\n\\item{pred.mean}{logical; if \\code{TRUE}, the prediction means are calculated for the state variables and parameters.}\n\n\\item{pred.var}{logical; if \\code{TRUE}, the prediction variances are calculated for the state variables and parameters.}\n\n\\item{filter.mean}{logical; if \\code{TRUE}, the filtering means are calculated for the state variables and parameters.}\n\n\\item{filter.traj}{logical; if \\code{TRUE}, a filtered trajectory is returned for the state variables and parameters.\nSee \\code{\\link{filter_traj}} for more information.}\n\n\\item{save.states}{character;\nIf \\code{save.states=\"no\"} (the default), information on the latent states is not saved.\nIf \\code{save.states=\"filter\"}, the state-vector for each filtered particle \\eqn{X_{n,j}^F} at each time \\eqn{n} is saved.\nIf \\code{save.states=\"prediction\"}, the state-vector for each prediction particle \\eqn{X_{n,j}^P} at each time \\eqn{n} is saved, along with the corresponding weight \\eqn{w_{n,j} = f_{Y_n|X_n}(y^*|X_{n, j}^P;\\theta)}.\nThe options \"unweighted\", \"weighted\", TRUE, and FALSE are deprecated and will issue a warning if used, mapping to the new values for backward compatibility.\nThe options \"unweighted\" and TRUE are synonymous with \"filter\";\nthe option \"weighted\" is synonymous with \"prediction\";\nthe option FALSE is synonymous with \"no\".\nTo retrieve the saved states, apply \\code{\\link{saved_states}} to the result of the \\code{pfilter} computation.}\n\n\\item{verbose}{logical; if \\code{TRUE}, diagnostic messages will be printed to the console.}\n}\n\\value{\nAn object of class \\sQuote{pfilterd_pomp}, which extends class \\sQuote{pomp}.\nInformation can be extracted from this object using the methods documented below.\n}\n\\description{\nA plain vanilla sequential Monte Carlo (particle filter) algorithm.\nResampling is performed at each observation.\n}\n\\section{Methods}{\n\n\\describe{\n\\item{\\code{\\link{logLik}}}{ the estimated log likelihood  }\n\\item{\\code{\\link{cond_logLik}}}{ the estimated conditional log likelihood }\n\\item{\\code{\\link{eff_sample_size}}}{\nthe (time-dependent) estimated effective sample size }\n\\item{\\code{\\link{pred_mean}}, \\code{\\link{pred_var}}}{ the mean and variance of the approximate prediction distribution }\n\\item{\\code{\\link{filter_mean}}}{ the mean of the filtering distribution }\n\\item{\\code{\\link{filter_traj}}}{\n  retrieve one particle trajectory.\n  Useful for building up the smoothing distribution.\n}\n\\item{\\code{\\link{saved_states}}}{retrieve saved states}\n\\item{\\code{\\link{as.data.frame}}}{coerce to a data frame}\n\\item{\\code{\\link{plot}}}{diagnostic plots}\n}\n}\n\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\examples{\npf <- pfilter(gompertz(),Np=1000)\t## use 1000 particles\n\nplot(pf)\nlogLik(pf)\ncond_logLik(pf)\t\t\t## conditional log-likelihoods\neff_sample_size(pf)             ## effective sample size\nlogLik(pfilter(pf))      \t## run it again with 1000 particles\n\n## run it again with 2000 particles\npf <- pfilter(pf,Np=2000,filter.mean=TRUE,filter.traj=TRUE,save.states=\"filter\")\nfm <- filter_mean(pf) ## extract the filtering means\nft <- filter_traj(pf) ## one draw from the smoothing distribution\nss <- saved_states(pf,format=\"d\") ## the latent-state portion of each particle\n\nas(pf,\"data.frame\") |> head()\n}\n\\references{\n\\Arulampalam2002\n\n\\Bhadra2016\n}\n\\seealso{\nMore on \\pkg{pomp} elementary algorithms:\n\\code{\\link{elementary_algorithms}},\n\\code{\\link{kalman}},\n\\code{\\link{pomp-package}},\n\\code{\\link{probe}()},\n\\code{\\link{simulate}()},\n\\code{\\link{spect}()},\n\\code{\\link{trajectory}()},\n\\code{\\link{wpfilter}()}\n\nMore on sequential Monte Carlo methods:\n\\code{\\link{bsmc2}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{kalman}},\n\\code{\\link{mif2}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{wpfilter}()}\n\nMore on full-information (i.e., likelihood-based) methods:\n\\code{\\link{bsmc2}()},\n\\code{\\link{mif2}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{wpfilter}()}\n}\n\\author{\nAaron A. King\n}\n\\concept{elementary algorithms}\n\\concept{full-information methods}\n\\concept{particle filter methods}\n"
  },
  {
    "path": "man/plot.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/plot.R, R/bsmc2.R, R/probe_match.R,\n%   R/spect_match.R\n\\name{plot}\n\\alias{plot}\n\\alias{plot,missing-method}\n\\alias{plot,pomp_plottable-method}\n\\alias{plot,pomp-method}\n\\alias{plot,Pmcmc-method}\n\\alias{plot,Abc-method}\n\\alias{plot,Mif2-method}\n\\alias{plot,probed_pomp-method}\n\\alias{plot,spectd_pomp-method}\n\\alias{plot,bsmcd_pomp-method}\n\\alias{plot,probe_match_objfun-method}\n\\alias{plot,spect_match_objfun-method}\n\\title{pomp plotting facilities}\n\\usage{\n\\S4method{plot}{pomp_plottable}(\n  x,\n  variables,\n  panel = lines,\n  nc = NULL,\n  yax.flip = FALSE,\n  mar = c(0, 5.1, 0, if (yax.flip) 5.1 else 2.1),\n  oma = c(6, 0, 5, 0),\n  axes = TRUE,\n  ...\n)\n\n\\S4method{plot}{Pmcmc}(x, ..., pars)\n\n\\S4method{plot}{Abc}(x, ..., pars, scatter = FALSE)\n\n\\S4method{plot}{Mif2}(x, ..., pars, transform = FALSE)\n\n\\S4method{plot}{probed_pomp}(x, y, ...)\n\n\\S4method{plot}{spectd_pomp}(\n  x,\n  ...,\n  max.plots.per.page = 4,\n  plot.data = TRUE,\n  quantiles = c(0.025, 0.25, 0.5, 0.75, 0.975),\n  quantile.styles = list(lwd = 1, lty = 1, col = \"gray70\"),\n  data.styles = list(lwd = 2, lty = 2, col = \"black\")\n)\n\n\\S4method{plot}{bsmcd_pomp}(x, pars, thin, ...)\n\n\\S4method{plot}{probe_match_objfun}(x, y, ...)\n\n\\S4method{plot}{spect_match_objfun}(x, y, ...)\n}\n\\arguments{\n\\item{x}{the object to plot}\n\n\\item{variables}{optional character; names of variables to be displayed}\n\n\\item{panel}{function of the form \\code{panel(x, col, bg, pch, type, ...)} which gives the action to be carried out in each panel of the display.}\n\n\\item{nc}{the number of columns to use.\nDefaults to 1 for up to 4 series, otherwise to 2.}\n\n\\item{yax.flip}{logical;\nif TRUE, the y-axis (ticks and numbering) should flip from side 2 (left) to 4 (right) from series to series.}\n\n\\item{mar, oma}{the \\code{\\link{par}} \\code{mar} and \\code{oma} settings.\nModify with care!}\n\n\\item{axes}{logical; indicates if x- and y- axes should be drawn}\n\n\\item{\\dots}{ignored or passed to low-level plotting functions}\n\n\\item{pars}{names of parameters.}\n\n\\item{scatter}{logical; if \\code{FALSE}, traces of the parameters named in \\code{pars} will be plotted against ABC iteration number.\nIf \\code{TRUE}, the traces will be displayed or as a scatterplot.}\n\n\\item{transform}{logical; should the parameter be transformed onto the estimation scale?}\n\n\\item{y}{ignored}\n\n\\item{max.plots.per.page}{positive integer; maximum number of plots on a page}\n\n\\item{plot.data}{logical; should the data spectrum be included?}\n\n\\item{quantiles}{numeric; quantiles to display}\n\n\\item{quantile.styles}{list; plot styles to use for quantiles}\n\n\\item{data.styles}{list; plot styles to use for data}\n\n\\item{thin}{integer; when the number of samples is very large, it can be helpful to plot a random subsample:\n\\code{thin} specifies the size of this subsample.}\n}\n\\description{\nDiagnostic plots.\n}\n"
  },
  {
    "path": "man/pmcmc.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/pmcmc.R\n\\name{pmcmc}\n\\alias{pmcmc}\n\\alias{pmcmc,ANY-method}\n\\alias{pmcmc,missing-method}\n\\alias{pmcmc,data.frame-method}\n\\alias{pmcmc,pomp-method}\n\\alias{pmcmc,pfilterd_pomp-method}\n\\alias{pmcmc,pmcmcd_pomp-method}\n\\title{The particle Markov chain Metropolis-Hastings algorithm}\n\\usage{\n\\S4method{pmcmc}{data.frame}(\n  data,\n  ...,\n  Nmcmc = 1,\n  proposal,\n  Np,\n  params,\n  rinit,\n  rprocess,\n  dmeasure,\n  dprior,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{pmcmc}{pomp}(\n  data,\n  ...,\n  Nmcmc = 1,\n  proposal,\n  Np,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{pmcmc}{pfilterd_pomp}(\n  data,\n  ...,\n  Nmcmc = 1,\n  proposal,\n  Np,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{pmcmc}{pmcmcd_pomp}(data, ..., Nmcmc, proposal, verbose = getOption(\"verbose\", FALSE))\n}\n\\arguments{\n\\item{data}{either a data frame holding the time series data,\nor an object of class \\sQuote{pomp},\ni.e., the output of another \\pkg{pomp} calculation.\nInternally, \\code{data} will be coerced to an array with storage-mode \\code{double}.}\n\n\\item{...}{additional arguments are passed to \\code{\\link{pomp}}.\nThis allows one to set, unset, or modify \\link[=basic_components]{basic model components} within a call to this function.}\n\n\\item{Nmcmc}{The number of PMCMC iterations to perform.}\n\n\\item{proposal}{optional function that draws from the proposal\ndistribution.  Currently, the proposal distribution must be symmetric for\nproper inference: it is the user's responsibility to ensure that it is.\nSeveral functions that construct appropriate proposal function are\nprovided: see \\link[=proposals]{MCMC proposals} for more information.}\n\n\\item{Np}{the number of particles to use.\nThis may be specified as a single positive integer, in which case the same number of particles will be used at each timestep.\nAlternatively, if one wishes the number of particles to vary across timesteps, one may specify \\code{Np} either as a vector of positive integers of length \\preformatted{length(time(object,t0=TRUE))} or as a function taking a positive integer argument.\nIn the latter case, \\code{Np(k)} must be a single positive integer, representing the number of particles to be used at the \\code{k}-th timestep:\n\\code{Np(0)} is the number of particles to use going from \\code{timezero(object)} to \\code{time(object)[1]},\n\\code{Np(1)}, from \\code{timezero(object)} to \\code{time(object)[1]},\nand so on,\nwhile when \\code{T=length(time(object))}, \\code{Np(T)} is the number of particles to sample at the end of the time-series.}\n\n\\item{params}{optional; named numeric vector of parameters.\nThis will be coerced internally to storage mode \\code{double}.}\n\n\\item{rinit}{simulator of the initial-state distribution.\nThis can be furnished either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rinit=NULL} sets the initial-state simulator to its default.\nFor more information, see \\link[=rinit_spec]{rinit specification}.}\n\n\\item{rprocess}{simulator of the latent state process, specified using one of the \\link[=rprocess_spec]{rprocess plugins}.\nSetting \\code{rprocess=NULL} removes the latent-state simulator.\nFor more information, see \\link[=rprocess_spec]{rprocess specification for the documentation on these plugins}.}\n\n\\item{dmeasure}{evaluator of the measurement model density, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{dmeasure=NULL} removes the measurement density evaluator.\nFor more information, see \\link[=dmeasure_spec]{dmeasure specification}.}\n\n\\item{dprior}{optional; prior distribution density evaluator, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nFor more information, see \\link[=prior_spec]{prior specification}.\nSetting \\code{dprior=NULL} resets the prior distribution to its default, which is a flat improper prior.}\n\n\\item{verbose}{logical; if \\code{TRUE}, diagnostic messages will be printed to the console.}\n}\n\\value{\nAn object of class \\sQuote{pmcmcd_pomp}.\n}\n\\description{\nThe Particle MCMC algorithm for estimating the parameters of a\npartially-observed Markov process.  Running \\code{pmcmc} causes a particle\nrandom-walk Metropolis-Hastings Markov chain algorithm to run for the\nspecified number of proposals.\n}\n\\section{Methods}{\n\nThe following can be applied to the output of a \\code{pmcmc} operation:\n\\describe{\n\\item{\\code{pmcmc}}{repeats the calculation, beginning with the last state}\n\\item{\\code{\\link{continue}}}{continues the \\code{pmcmc} calculation}\n\\item{\\code{plot}}{produces a series of diagnostic plots}\n\\item{\\code{\\link{filter_traj}}}{extracts a random sample from the smoothing distribution}\n\\item{\\code{\\link{traces}}}{produces an \\code{\\link[coda]{mcmc}} object, to which the various \\pkg{coda} convergence diagnostics can be applied}\n}\n}\n\n\\section{Re-running PMCMC Iterations}{\n\nTo re-run a sequence of PMCMC\niterations, one can use the \\code{pmcmc} method on a \\sQuote{pmcmc} object.\nBy default, the same parameters used for the original PMCMC run are re-used\n(except for \\code{verbose}, the default of which is shown above).  If one\ndoes specify additional arguments, these will override the defaults.\n}\n\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\references{\n\\Andrieu2010\n}\n\\seealso{\nMore on \\pkg{pomp} estimation algorithms:\n\\code{\\link{abc}()},\n\\code{\\link{bsmc2}()},\n\\code{\\link{estimation_algorithms}},\n\\code{\\link{mif2}()},\n\\code{\\link{nlf}},\n\\code{\\link{pomp-package}},\n\\code{\\link{probe_match}},\n\\code{\\link{spect_match}}\n\nMore on sequential Monte Carlo methods:\n\\code{\\link{bsmc2}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{kalman}},\n\\code{\\link{mif2}()},\n\\code{\\link{pfilter}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{wpfilter}()}\n\nMore on full-information (i.e., likelihood-based) methods:\n\\code{\\link{bsmc2}()},\n\\code{\\link{mif2}()},\n\\code{\\link{pfilter}()},\n\\code{\\link{wpfilter}()}\n\nMore on Markov chain Monte Carlo methods:\n\\code{\\link{abc}()},\n\\code{\\link{proposals}}\n\nMore on Bayesian methods:\n\\code{\\link{abc}()},\n\\code{\\link{bsmc2}()},\n\\code{\\link{dprior}()},\n\\code{\\link{prior_spec}},\n\\code{\\link{rprior}()}\n}\n\\author{\nEdward L. Ionides, Aaron A. King, Sebastian Funk\n}\n\\concept{Bayesian methods}\n\\concept{MCMC methods}\n\\concept{estimation methods}\n\\concept{full-information methods}\n\\concept{particle filter methods}\n"
  },
  {
    "path": "man/pomp-package.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/package.R\n\\docType{package}\n\\name{pomp-package}\n\\alias{pomp-package}\n\\alias{pomp,package}\n\\title{Inference for partially observed Markov processes}\n\\description{\nThe \\pkg{pomp} package provides facilities for inference on time series\ndata using partially-observed Markov process (\\acronym{POMP}) models.\nThese models are also known as state-space models, hidden Markov models, or\nnonlinear stochastic dynamical systems.  One can use \\pkg{pomp} to fit\nnonlinear, non-Gaussian dynamic models to time-series data.  The package is\nboth a set of tools for data analysis and a platform upon which statistical\ninference methods for \\acronym{POMP} models can be implemented.\n}\n\\section{Data analysis using \\pkg{pomp}}{\n\n\\pkg{pomp} provides algorithms for:\n\\enumerate{\n\\item Simulation of stochastic dynamical systems;\nsee \\code{\\link{simulate}}.\n\\item Particle filtering (AKA sequential Monte Carlo or sequential importance sampling);\nsee \\code{\\link{pfilter}} and \\code{\\link{wpfilter}}.\n\\item The iterated filtering methods of Ionides et al. (2006, 2011, 2015);\nsee \\code{\\link{mif2}}.\n\\item The nonlinear forecasting algorithm of Kendall et al. (2005);\nsee \\link{nlf}.\n\\item The particle MCMC approach of Andrieu et al. (2010);\nsee \\code{\\link{pmcmc}}.\n\\item The probe-matching method of Kendall et al. (1999, 2005);\nsee \\link{probe_match}.\n\\item Synthetic likelihood a la Wood (2010);\nsee \\code{\\link{probe}}.\n\\item A spectral probe-matching method (Reuman et al. 2006, 2008);\nsee \\link{spect_match}.\n\\item Approximate Bayesian computation (Toni et al. 2009);\nsee \\code{\\link{abc}}.\n\\item The approximate Bayesian sequential Monte Carlo scheme of Liu & West (2001);\nsee \\code{\\link{bsmc2}}.\n\\item Ensemble and ensemble adjusted Kalman filters;\nsee \\link{kalman}.\n\\item Simple trajectory matching;\nsee \\link{traj_match}.\n}\nThe package also provides various tools for plotting and extracting information on models and data.\n}\n\n\\section{Structure of the package}{\n\n\n\\pkg{pomp} algorithms are arranged into several levels.\nAt the top level, \\link[=estimation_algorithms]{estimation algorithms} estimate model parameters and return information needed for other aspects of inference.\n\\link[=elementary_algorithms]{Elementary algorithms} perform common operations on \\acronym{POMP} models, including simulation, filtering, and application of diagnostic probes;\nthese functions may be useful in inference, but they do not themselves perform estimation.\nAt the lowest level, \\link[=workhorses]{workhorse functions} provide the interface to \\link[=basic_components]{basic POMP model components}.\nBeyond these, \\pkg{pomp} provides a variety of auxiliary functions for manipulating and extracting information from \\sQuote{pomp} objects, producing diagnostic plots, \\link[=bake]{facilitating reproducible computations}, and so on.\n}\n\n\\section{Implementing a model}{\n\n\nThe basic structure at the heart of the package is the \\sQuote{pomp object}.\nThis is a container holding a time series of data (possibly multivariate) and a model.\nThe model is specified by specifying some or all of its \\link[=basic_components]{basic model components}.\nOne does this using the \\link[=basic_components]{basic component arguments} to the \\code{\\link{pomp}} constructor.\nOne can also add, modify, or delete basic model components \\dQuote{on the fly} in any \\pkg{pomp} function that accepts them.\n}\n\n\\section{Documentation and examples}{\n\n\nThe package contains a number of examples.\nSome of these are included in the help pages.\nIn addition, \\link[=pomp_examples]{several pre-built POMP models} are included with the package.\nTutorials and other documentation, including a \\href{https://kingaa.github.io/pomp/FAQ.html}{package FAQ}, are available from the \\href{https://kingaa.github.io/pomp/}{package website}.\n}\n\n\\section{Useful links}{\n\n\\itemize{\n \\item{\\pkg{pomp} homepage: \\url{https://kingaa.github.io/pomp/}}\n \\item{Report bugs to: \\url{https://github.com/kingaa/pomp/issues}}\n \\item{Frequently asked questions: \\url{https://kingaa.github.io/pomp/FAQ.html}}\n \\item{User guides and tutorials: \\url{https://kingaa.github.io/pomp/docs.html}}\n \\item{\\pkg{pomp} news: \\url{https://kingaa.github.io/pomp/blog.html}}\n}\n}\n\n\\section{Citing \\pkg{pomp}}{\n\nExecute \\code{citation(\"pomp\")} to view the correct citation for publications.\n}\n\n\\references{\n\\King2016\n\nSee \\href{https://kingaa.github.io/pomp/biblio.html}{the package website for more references}, including many publications that use \\pkg{pomp}.\n}\n\\seealso{\nUseful links:\n\\itemize{\n  \\item \\url{https://kingaa.github.io/pomp/}\n  \\item Report bugs at \\url{https://github.com/kingaa/pomp/issues/}\n}\n\n\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{accumvars}},\n\\code{\\link{basic_components}},\n\\code{\\link{betabinomial}},\n\\code{\\link{covariates}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{userdata}},\n\\code{\\link{vmeasure_spec}}\n\nMore on \\pkg{pomp} workhorse functions:\n\\code{\\link{dinit}()},\n\\code{\\link{dmeasure}()},\n\\code{\\link{dprior}()},\n\\code{\\link{dprocess}()},\n\\code{\\link{emeasure}()},\n\\code{\\link{flow}()},\n\\code{\\link{partrans}()},\n\\code{\\link{rinit}()},\n\\code{\\link{rmeasure}()},\n\\code{\\link{rprior}()},\n\\code{\\link{rprocess}()},\n\\code{\\link{skeleton}()},\n\\code{\\link{vmeasure}()},\n\\code{\\link{workhorses}}\n\nMore on \\pkg{pomp} estimation algorithms:\n\\code{\\link{abc}()},\n\\code{\\link{bsmc2}()},\n\\code{\\link{estimation_algorithms}},\n\\code{\\link{mif2}()},\n\\code{\\link{nlf}},\n\\code{\\link{pmcmc}()},\n\\code{\\link{probe_match}},\n\\code{\\link{spect_match}}\n\nMore on \\pkg{pomp} elementary algorithms:\n\\code{\\link{elementary_algorithms}},\n\\code{\\link{kalman}},\n\\code{\\link{pfilter}()},\n\\code{\\link{probe}()},\n\\code{\\link{simulate}()},\n\\code{\\link{spect}()},\n\\code{\\link{trajectory}()},\n\\code{\\link{wpfilter}()}\n}\n\\author{\nAaron A. King\n}\n\\concept{elementary algorithms}\n\\concept{estimation methods}\n\\concept{implementation information}\n\\concept{pomp workhorses}\n\\keyword{models}\n\\keyword{multivariate}\n\\keyword{ts}\n"
  },
  {
    "path": "man/pomp.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/pomp.R\n\\name{pomp_constructor}\n\\alias{pomp_constructor}\n\\alias{pomp}\n\\title{Constructor of the basic pomp object}\n\\usage{\npomp(\n  data,\n  ...,\n  times,\n  t0,\n  rinit,\n  dinit,\n  rprocess,\n  dprocess,\n  rmeasure,\n  dmeasure,\n  emeasure,\n  vmeasure,\n  skeleton,\n  rprior,\n  dprior,\n  partrans,\n  covar,\n  params,\n  accumvars,\n  obsnames,\n  statenames,\n  paramnames,\n  covarnames,\n  nstatevars,\n  PACKAGE,\n  globals,\n  on_load,\n  userdata,\n  cdir = getOption(\"pomp_cdir\", NULL),\n  cfile,\n  shlib.args,\n  compile = TRUE,\n  verbose = getOption(\"verbose\", FALSE)\n)\n}\n\\arguments{\n\\item{data}{either a data frame holding the time series data,\nor an object of class \\sQuote{pomp},\ni.e., the output of another \\pkg{pomp} calculation.\nInternally, \\code{data} will be coerced to an array with storage-mode \\code{double}.}\n\n\\item{...}{additional arguments will generate an error.}\n\n\\item{times}{the sequence of observation times.\n\\code{times} must indicate the column of observation times by name or index.\nThe time vector must be numeric and non-decreasing.}\n\n\\item{t0}{The zero-time, i.e., the time of the initial state.\nThis must be no later than the time of the first observation, i.e., \\code{t0 <= times[1]}.}\n\n\\item{rinit}{simulator of the initial-state distribution.\nThis can be furnished either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rinit=NULL} sets the initial-state simulator to its default.\nFor more information, see \\link[=rinit_spec]{rinit specification}.}\n\n\\item{dinit}{evaluator of the initial-state density.\nThis can be furnished either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{dinit=NULL} removes this basic component.\nFor more information, see \\link[=dinit_spec]{dinit specification}.}\n\n\\item{rprocess}{simulator of the latent state process, specified using one of the \\link[=rprocess_spec]{rprocess plugins}.\nSetting \\code{rprocess=NULL} removes the latent-state simulator.\nFor more information, see \\link[=rprocess_spec]{rprocess specification for the documentation on these plugins}.}\n\n\\item{dprocess}{evaluator of the probability density of transitions of the unobserved state process.\nSetting \\code{dprocess=NULL} removes the latent-state density evaluator.\nFor more information, see \\link[=dprocess_spec]{dprocess specification}.}\n\n\\item{rmeasure}{simulator of the measurement model, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rmeasure=NULL} removes the measurement model simulator.\nFor more information, see \\link[=rmeasure_spec]{rmeasure specification}.}\n\n\\item{dmeasure}{evaluator of the measurement model density, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{dmeasure=NULL} removes the measurement density evaluator.\nFor more information, see \\link[=dmeasure_spec]{dmeasure specification}.}\n\n\\item{emeasure}{the expectation of the measured variables, conditional on the latent state.\nThis can be specified as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{emeasure=NULL} removes the emeasure component.\nFor more information, see \\link[=emeasure_spec]{emeasure specification}.}\n\n\\item{vmeasure}{the covariance of the measured variables, conditional on the latent state.\nThis can be specified as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{vmeasure=NULL} removes the vmeasure component.\nFor more information, see \\link[=vmeasure_spec]{vmeasure specification}.}\n\n\\item{skeleton}{optional; the deterministic skeleton of the unobserved state process.\nDepending on whether the model operates in continuous or discrete time, this is either a vectorfield or a map.\nAccordingly, this is supplied using either the \\code{\\link[=skeleton_spec]{vectorfield}} or \\code{\\link[=skeleton_spec]{map}} fnctions.\nFor more information, see \\link[=skeleton_spec]{skeleton specification}.\nSetting \\code{skeleton=NULL} removes the deterministic skeleton.}\n\n\\item{rprior}{optional; prior distribution sampler, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nFor more information, see \\link[=prior_spec]{prior specification}.\nSetting \\code{rprior=NULL} removes the prior distribution sampler.}\n\n\\item{dprior}{optional; prior distribution density evaluator, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nFor more information, see \\link[=prior_spec]{prior specification}.\nSetting \\code{dprior=NULL} resets the prior distribution to its default, which is a flat improper prior.}\n\n\\item{partrans}{optional parameter transformations, constructed using \\code{\\link{parameter_trans}}.\n\nMany algorithms for parameter estimation search an unconstrained space of parameters.\nWhen working with such an algorithm and a model for which the parameters are constrained, it can be useful to transform parameters.\nOne should supply the \\code{partrans} argument via a call to \\code{\\link{parameter_trans}}.\nFor more information, see \\link[=parameter_trans]{parameter_trans}.\nSetting \\code{partrans=NULL} removes the parameter transformations, i.e., sets them to the identity transformation.}\n\n\\item{covar}{optional covariate table, constructed using \\code{\\link{covariate_table}}.\n\nIf a covariate table is supplied, then the value of each of the covariates is interpolated as needed.\nThe resulting interpolated values are made available to the appropriate basic components.\nSee the documentation for \\code{\\link{covariate_table}} for details.}\n\n\\item{params}{optional; named numeric vector of parameters.\nThis will be coerced internally to storage mode \\code{double}.}\n\n\\item{accumvars}{optional character vector;\ncontains the names of accumulator variables.\nSee \\link{accumvars} for a definition and discussion of accumulator variables.}\n\n\\item{obsnames}{optional character vector;\nnames of the observables.\nIt is not usually necessary to specify \\code{obsnames} since, by default,\nthese are read from the names of the data variables.}\n\n\\item{statenames}{optional character vector;\nnames of the latent state variables.\nIt is typically only necessary to supply \\code{statenames} when C snippets are in use.\nSee also \\code{nstatevars}.}\n\n\\item{paramnames}{optional character vector;\nnames of model parameters.\nIt is typically only necessary to supply \\code{paramnames} when C snippets are in use.}\n\n\\item{covarnames}{optional character vector;\nnames of the covariates.\nIt is not usually necessary to specify \\code{covarnames} since, by default,\nthese are read from the names of the covariates.}\n\n\\item{nstatevars}{optional integer scalar;\nIf C snippets or native routines are used, one can specify the number of state variables with this argument.\nBy default, \\code{nstatevars = length(statenames)}.}\n\n\\item{PACKAGE}{optional character;\nthe name (without extension) of the external, dynamically loaded library in which any native routines are to be found.\nThis is only useful if one or more of the model components has been specified using a precompiled dynamically loaded library;\nit is not used for any component specified using C snippets.\n\\code{PACKAGE} can name at most one library.}\n\n\\item{globals}{optional character or C snippet;\narbitrary C code that will be hard-coded into the shared-object library created when C snippets are provided.\nIf no C snippets are used, \\code{globals} has no effect.}\n\n\\item{on_load}{optional character or C snippet:\narbitrary C code that will be executed when the C snippet file is loaded.\nIf no C snippets are used, \\code{on_load} has no effect.}\n\n\\item{userdata}{optional list; the elements of this list will be available to basic model components.\nThis allows the user to pass information to the basic components outside of the usual routes of covariates (\\code{covar}) and model parameters (\\code{params}).\nSee \\link[=userdata]{userdata} for information on how to use this facility.}\n\n\\item{cdir}{optional character variable.\n\\code{cdir} specifies the name of the directory within which C snippet code will be compiled.\nBy default, this is in a temporary directory specific to the \\R session.\nOne can also set this directory using the \\code{pomp_cdir} global option.}\n\n\\item{cfile}{optional character variable.\n\\code{cfile} gives the name of the file (in directory \\code{cdir}) into which C snippet codes will be written.\nBy default, a random filename is used.\nIf the chosen filename would result in over-writing an existing file, an error is generated.}\n\n\\item{shlib.args}{optional character variables.\nCommand-line arguments to the \\code{R CMD SHLIB} call that compiles the C snippets.\nOne can, for example, specify libraries against which the C snippets are to be linked.\nIn doing so, take care to make sure the appropriate header files are available to the C snippets, e.g., using the \\code{globals} argument.\nSee \\code{\\link{Csnippet}} for more information.}\n\n\\item{compile}{logical;\nif \\code{FALSE}, compilation of the C snippets will be postponed until they are needed.}\n\n\\item{verbose}{logical; if \\code{TRUE}, diagnostic messages will be printed to the console.}\n}\n\\value{\nThe \\code{pomp} constructor function returns an object, call it \\code{P}, of class \\sQuote{pomp}.\n\\code{P} contains, in addition to the data, any elements of the model that have been specified as arguments to the \\code{pomp} constructor function.\nOne can add or modify elements of \\code{P} by means of further calls to \\code{pomp}, using \\code{P} as the first argument in such calls.\nOne can pass \\code{P} to most of the \\pkg{pomp} package methods via their \\code{data} argument.\n}\n\\description{\nThis function constructs a \\sQuote{pomp} object, encoding a partially-observed Markov process (\\acronym{POMP}) model together with a uni- or multi-variate time series.\nAs such, it is central to all the package's functionality.\nOne implements the \\acronym{POMP} model by specifying some or all of its \\emph{basic components}.\nThese comprise:\n\\describe{\n\\item{rinit}{which samples from the distribution of the state process at the zero-time;}\n\\item{dinit}{which evaluates the density of the state process at the zero-time;}\n\\item{rprocess}{the simulator of the unobserved Markov state process;}\n\\item{dprocess}{the evaluator of the probability density function for transitions of the unobserved Markov state process;}\n\\item{rmeasure}{the simulator of the observed process, conditional on the unobserved state;}\n\\item{dmeasure}{the evaluator of the measurement model probability density function;}\n\\item{emeasure}{the expectation of the measurements, conditional on the latent state;}\n\\item{vmeasure}{the covariance matrix of the measurements, conditional on the latent state;}\n\\item{rprior}{which samples from a prior probability distribution on the parameters;}\n\\item{dprior}{which evaluates the prior probability density function;}\n\\item{skeleton}{which computes the deterministic skeleton of the unobserved state process;}\n\\item{partrans}{which performs parameter transformations.}\n}\nThe basic structure and its rationale are described in the \\emph{Journal of Statistical Software} paper, an updated version of which is to be found on the \\href{https://kingaa.github.io/pomp/}{package website}.\n}\n\\details{\nEach basic component is supplied via an argument of the same name.\nThese can be given in the call to \\code{pomp}, or to many of the package's other functions.\nIn any case, the effect is the same: to add, remove, or modify the basic component.\n\nEach basic component can be furnished using C snippets, \\R functions, or pre-compiled native routine available in user-provided dynamically loaded libraries.\n}\n\\section{Note}{\n\n\nIt is not typically necessary (or indeed feasible) to define all of the basic components for any given purpose.\nHowever, each \\pkg{pomp} algorithm makes use of only a subset of these components.\nWhen an algorithm requires a basic component that has not been furnished, an error is generated to let you know that you must provide the needed component to use the algorithm.\n}\n\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\references{\n\\King2016\n}\n\\seealso{\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{accumvars}},\n\\code{\\link{basic_components}},\n\\code{\\link{betabinomial}},\n\\code{\\link{covariates}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{userdata}},\n\\code{\\link{vmeasure_spec}}\n}\n\\author{\nAaron A. King\n}\n\\concept{implementation information}\n"
  },
  {
    "path": "man/pomp_class.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/pomp_class.R\n\\docType{class}\n\\name{pomp-class}\n\\alias{pomp-class}\n\\title{The basic pomp class}\n\\description{\nThe basic class implementing a \\acronym{POMP} model with data\n}\n\\seealso{\n\\link{pomp_constructor}\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/pomp_examp.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/pomp_examp.R\n\\docType{data}\n\\name{pomp_examples}\n\\alias{pomp_examples}\n\\title{pre-built pomp examples}\n\\description{\nExamples of pomp objects containing models and data.\n}\n\\details{\n\\pkg{pomp} includes a number of pre-built examples of pomp objects and data that can be analyzed using \\pkg{pomp} methods.\nThese include:\n\\describe{\n\\item{\\code{\\link{blowflies}}}{Data from Nicholson's experiments with sheep blowfly populations}\n\\item{\\code{\\link{blowflies1}()}}{A pomp object with some of the blowfly data together with a discrete delay equation model.}\n\\item{\\code{\\link{blowflies2}()}}{A variant of \\code{blowflies1}.}\n\\item{\\code{\\link{bsflu}}}{Data from an outbreak of influenza in a boarding school.}\n\\item{\\code{\\link{dacca}()}}{Fifty years of census and cholera mortality data, together with a stochastic differential equation transmission model (King et al. 2008).}\n\\item{\\code{\\link{ebolaModel}()}}{Data from the 2014 West Africa outbreak of Ebola virus disease, together with simple transmission models (King et al. 2015).}\n\\item{\\code{\\link{gompertz}()}}{The Gompertz population dynamics model, with simulated data.}\n\\item{\\code{\\link{LondonYorke}}}{Data on incidence of several childhood diseases (London and Yorke 1973)}\n\\item{\\code{\\link{ewmeas}}}{Measles incidence data from England and Wales}\n\\item{\\code{\\link{ewcitmeas}}}{Measles incidence data from 7 English cities}\n\\item{\\code{\\link{ou2}()}}{A 2-D Ornstein-Uhlenbeck process with simulated data}\n\\item{\\code{\\link{parus}}}{Population censuses of a \\emph{Parus major} population in Wytham Wood, England.}\n\\item{\\code{\\link{ricker}}}{The Ricker population dynamics model, with simulated data}\n\\item{\\code{\\link{rw2}}}{A 2-D Brownian motion model, with simulated data.}\n\\item{\\code{\\link{sir}()}}{A simple continuous-time Markov chain SIR model, coded using Euler-multinomial steps, with simulated data.}\n\\item{\\code{\\link{sir2}()}}{A simple continuous-time Markov chain SIR model, coded using Gillespie's algorithm, with simulated data.}\n\\item{\\code{\\link{verhulst}()}}{The Verhulst-Pearl (logistic) model, a continuous-time model of population dynamics, with simulated data}\n}\n\nSee also the tutorials on the \\href{https://kingaa.github.io/pomp/}{package website} for more examples.\n}\n\\references{\n\\Anonymous1978\n\n\\King2008\n\n\\King2015\n\n\\London1973\n\n\\Nicholson1957\n}\n\\seealso{\nMore examples provided with \\pkg{pomp}:\n\\code{\\link{blowflies}},\n\\code{\\link{childhood_disease_data}},\n\\code{\\link{compartmental_models}},\n\\code{\\link{dacca}()},\n\\code{\\link{ebola}},\n\\code{\\link{gompertz}()},\n\\code{\\link{ou2}()},\n\\code{\\link{ricker}()},\n\\code{\\link{rw2}()},\n\\code{\\link{verhulst}()}\n}\n\\concept{pomp examples}\n\\keyword{models}\n"
  },
  {
    "path": "man/pomp_fun.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/pomp_fun.R\n\\docType{methods}\n\\name{pomp_fun}\n\\alias{pomp_fun}\n\\alias{pomp_fun,missing-method}\n\\alias{pomp_fun,function-method}\n\\alias{pomp_fun,character-method}\n\\alias{pomp_fun,Csnippet-method}\n\\alias{pomp_fun,pomp_fun-method}\n\\title{The \"pomp_fun\" class}\n\\usage{\n\\S4method{pomp_fun}{missing}(\n  slotname = NULL,\n  obsnames = character(0),\n  statenames = character(0),\n  paramnames = character(0),\n  covarnames = character(0),\n  ...\n)\n\n\\S4method{pomp_fun}{function}(f, proto = NULL, slotname = NULL, ...)\n\n\\S4method{pomp_fun}{character}(\n  f,\n  PACKAGE = NULL,\n  obsnames = character(0),\n  statenames = character(0),\n  paramnames = character(0),\n  covarnames = character(0),\n  slotname = NULL,\n  ...\n)\n\n\\S4method{pomp_fun}{Csnippet}(\n  f,\n  slotname = NULL,\n  libname = NULL,\n  obsnames = character(0),\n  statenames = character(0),\n  paramnames = character(0),\n  covarnames = character(0),\n  Cname,\n  ...\n)\n\n\\S4method{pomp_fun}{pomp_fun}(f, ...)\n}\n\\arguments{\n\\item{f}{A function or the name of a native routine.}\n\n\\item{proto}{optional string; a prototype against which \\code{f} will be\nchecked.}\n\n\\item{PACKAGE}{optional; the name of the dynamically-loadable library in\nwhich the native function \\code{f} can be found.}\n}\n\\description{\nDefinition and methods of the \\sQuote{pomp_fun} class.\n}\n\\details{\nThe \\sQuote{pomp_fun} class implements a common interface for user-defined procedures that can be defined in terms of R code or by compiled native routines.\n}\n\\seealso{\n\\code{\\link{pomp}}\n}\n\\author{\nAaron A. King\n}\n\\concept{extending the pomp package}\n\\concept{low-level interface}\n\\keyword{internal}\n"
  },
  {
    "path": "man/pred_mean.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/pred_mean.R\n\\name{pred_mean}\n\\alias{pred_mean}\n\\alias{pred_mean,ANY-method}\n\\alias{pred_mean,missing-method}\n\\alias{pred_mean,kalmand_pomp-method}\n\\alias{pred_mean,pfilterd_pomp-method}\n\\title{Prediction mean}\n\\usage{\n\\S4method{pred_mean}{kalmand_pomp}(object, vars, ..., format = c(\"array\", \"data.frame\"))\n\n\\S4method{pred_mean}{pfilterd_pomp}(object, vars, ..., format = c(\"array\", \"data.frame\"))\n}\n\\arguments{\n\\item{object}{result of a filtering computation}\n\n\\item{vars}{optional character; names of variables}\n\n\\item{...}{ignored}\n\n\\item{format}{format of the returned object}\n}\n\\description{\nThe mean of the prediction distribution\n}\n\\details{\nThe prediction distribution is that of\n\\deqn{X(t_k) \\vert Y(t_1)=y^*_1,\\dots,Y(t_{k-1})=y^*_{k-1},}{Xk | Y1=y1*,\\dots,Y(k-1)=y(k-1)*,}\nwhere \\eqn{X(t_k)}{Xk}, \\eqn{Y(t_k)}{Yk} are the latent state and observable processes, respectively, and \\eqn{y^*_k}{yk*} is the data, at time \\eqn{t_k}{tk}.\n\nThe prediction mean is therefore the expectation of this distribution\n\\deqn{E[X(t_k) \\vert Y(t_1)=y^*_1,\\dots,Y(t_{k-1})=y^*_{k-1}].}{E[Xk | Y1=y1*,\\dots,Y(k-1)=y(k-1)*].}\n}\n\\seealso{\nMore on sequential Monte Carlo methods:\n\\code{\\link{bsmc2}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{kalman}},\n\\code{\\link{mif2}()},\n\\code{\\link{pfilter}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{wpfilter}()}\n\nOther extraction methods: \n\\code{\\link{coef}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{covmat}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{forecast}()},\n\\code{\\link{logLik}},\n\\code{\\link{obs}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{spy}()},\n\\code{\\link{states}()},\n\\code{\\link{summary}()},\n\\code{\\link{time}()},\n\\code{\\link{timezero}()},\n\\code{\\link{traces}()}\n}\n\\concept{extraction methods}\n\\concept{particle filter methods}\n"
  },
  {
    "path": "man/pred_var.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/pred_var.R\n\\name{pred_var}\n\\alias{pred_var}\n\\alias{pred_var,ANY-method}\n\\alias{pred_var,missing-method}\n\\alias{pred_var,pfilterd_pomp-method}\n\\title{Prediction variance}\n\\usage{\n\\S4method{pred_var}{pfilterd_pomp}(object, vars, ..., format = c(\"array\", \"data.frame\"))\n}\n\\arguments{\n\\item{object}{result of a filtering computation}\n\n\\item{vars}{optional character; names of variables}\n\n\\item{...}{ignored}\n\n\\item{format}{format of the returned object}\n}\n\\description{\nThe variance of the prediction distribution\n}\n\\details{\nThe prediction distribution is that of\n\\deqn{X(t_k) \\vert Y(t_1)=y^*_1,\\dots,Y(t_{k-1})=y^*_{k-1},}{Xk | Y1=y1*,\\dots,Y(k-1)=y(k-1)*,}\nwhere \\eqn{X(t_k)}{Xk}, \\eqn{Y(t_k)}{Yk} are the latent state and observable processes, respectively, and \\eqn{y^*_k}{yk*} is the data, at time \\eqn{t_k}{tk}.\n\nThe prediction variance is therefore the variance of this distribution\n\\deqn{\\mathrm{Var}[X(t_k) \\vert Y(t_1)=y^*_1,\\dots,Y(t_{k-1})=y^*_{k-1}].}{Var[Xk | Y1=y1*,\\dots,Y(k-1)=y(k-1)*].}\n}\n\\seealso{\nMore on sequential Monte Carlo methods:\n\\code{\\link{bsmc2}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{kalman}},\n\\code{\\link{mif2}()},\n\\code{\\link{pfilter}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{wpfilter}()}\n\nOther extraction methods: \n\\code{\\link{coef}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{covmat}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{forecast}()},\n\\code{\\link{logLik}},\n\\code{\\link{obs}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{spy}()},\n\\code{\\link{states}()},\n\\code{\\link{summary}()},\n\\code{\\link{time}()},\n\\code{\\link{timezero}()},\n\\code{\\link{traces}()}\n}\n\\concept{extraction methods}\n\\concept{particle filter methods}\n"
  },
  {
    "path": "man/print.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/print.R\n\\name{print}\n\\alias{print}\n\\alias{print,unshowable-method}\n\\alias{print,listie-method}\n\\alias{print,pomp_fun-method}\n\\title{Print methods}\n\\usage{\n\\S4method{print}{unshowable}(x, ...)\n\n\\S4method{print}{listie}(x, ...)\n\n\\S4method{print}{pomp_fun}(x, ...)\n}\n\\arguments{\n\\item{x}{object to print}\n\n\\item{...}{ignored}\n}\n\\description{\nThese methods print their argument and return it *invisibly*.\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/prior_spec.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/prior_spec.R\n\\name{prior_spec}\n\\alias{prior_spec}\n\\alias{priors}\n\\title{prior specification}\n\\description{\nSpecification of prior distributions via the rprior and dprior components.\n}\n\\details{\nA prior distribution on parameters is specified by means of the \\code{rprior} and/or \\code{dprior} arguments to \\code{pomp}.\nAs with the other \\link[=basic_components]{basic model components}, it is preferable to specify these using C snippets.\nIn writing a C snippet for the prior sampler (\\code{rprior}), keep in mind that:\n\\enumerate{\n  \\item Within the context in which the snippet will be evaluated, only the parameters will be defined.\n  \\item The goal of such a snippet is the replacement of parameters with values drawn from the prior distribution.\n  \\item Hyperparameters can be included in the ordinary parameter list.\n  Obviously, hyperparameters should not be replaced with random draws.\n}\nIn writing a C snippet for the prior density function (\\code{dprior}), observe that:\n\\enumerate{\n  \\item Within the context in which the snippet will be evaluated, only the parameters and \\code{give_log} will be defined.\n  \\item The goal of such a snippet is computation of the prior probability density, or the log of same, at a given point in parameter space.\n  This scalar value should be returned in the variable \\code{lik}.\n  When \\code{give_log == 1}, \\code{lik} should contain the log of the prior probability density.\n  \\item Hyperparameters can be included in the ordinary parameter list.\n}\n\\link[=Csnippet]{General rules for writing C snippets can be found here}.\n\nAlternatively, one can furnish \\R functions for one or both of these arguments.\nIn this case, \\code{rprior} must be a function that makes a draw from\nthe prior distribution of the parameters and returns a named vector\ncontaining all the parameters.\nThe only required argument of this function is \\code{...}.\n\nSimilarly, the \\code{dprior} function must evaluate the prior probability\ndensity (or log density if \\code{log == TRUE}) and return that single\nscalar value.\nThe only required arguments of this function are \\code{...} and \\code{log}.\n}\n\\section{Default behavior}{\n\nBy default, the prior is assumed flat and improper.\nIn particular, \\code{dprior} returns \\code{1} (\\code{0} if \\code{log = TRUE}) for every parameter set.\nSince it is impossible to simulate from a flat improper prior, \\code{rprocess} returns missing values (\\code{NA}s).\n}\n\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\examples{\n\\donttest{ # takes too long for R CMD check\n  ## Starting with an existing pomp object:\n  verhulst() |> window(end=30) -> po\n  \n  ## We add or change prior distributions using the two\n  ## arguments 'rprior' and 'dprior'. Here, we introduce\n  ## a Gamma prior on the 'r' parameter.\n  ## We construct 'rprior' and 'dprior' using R functions.\n\n  po |>\n    bsmc2(\n      rprior=function (n_0, K0, K1, sigma, tau, r0, r1, ...) {\n        c(\n          n_0 = n_0,\n          K = rgamma(n=1,shape=K0,scale=K1),\n          r = rgamma(n=1,shape=r0,scale=r1),\n          sigma = sigma,\n          tau = tau\n        )\n      },\n      dprior=function(K, K0, K1, r, r0, r1, ..., log) {\n        p <- dgamma(x=c(K,r),shape=c(K0,r0),scale=c(K1,r1),log=log)\n        if (log) sum(p) else prod(p)\n      },\n      params=c(n_0=10000,K=10000,K0=10,K1=1000,\n        r=0.9,r0=0.9,r1=1,sigma=0.5,tau=0.3),\n      Np=1000\n    ) -> B\n\n  ## We can also pass them as C snippets:\n\n  po |>\n    bsmc2(\n      rprior=Csnippet(\"\n         K = rgamma(K0,K1);\n         r = rgamma(r0,r1);\"\n      ),\n      dprior=Csnippet(\"\n         double lik1 = dgamma(K,K0,K1,give_log);\n         double lik2 = dgamma(r,r0,r1,give_log);\n         lik = (give_log) ? lik1+lik2 : lik1*lik2;\"\n      ),\n      paramnames=c(\"K\",\"K0\",\"K1\",\"r\",\"r0\",\"r1\"),\n      params=c(n_0=10000,K=10000,K0=10,K1=1000,\n        r=0.9,r0=0.9,r1=1,sigma=0.5,tau=0.3),\n      Np=10000\n    ) -> B\n\n  ## The prior is plotted in grey; the posterior, in blue.\n  plot(B)\n\n  B |>\n    pmcmc(Nmcmc=100,Np=1000,proposal=mvn_diag_rw(c(r=0.01,K=10))) -> Bb\n\n  plot(Bb,pars=c(\"loglik\",\"log.prior\",\"r\",\"K\"))\n\n}\n}\n\\seealso{\n\\code{\\link{dprior}} \\code{\\link{rprior}}\n\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{accumvars}},\n\\code{\\link{basic_components}},\n\\code{\\link{betabinomial}},\n\\code{\\link{covariates}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{userdata}},\n\\code{\\link{vmeasure_spec}}\n\nMore on Bayesian methods:\n\\code{\\link{abc}()},\n\\code{\\link{bsmc2}()},\n\\code{\\link{dprior}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{rprior}()}\n}\n\\concept{Bayesian methods}\n\\concept{implementation information}\n"
  },
  {
    "path": "man/probe.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/probe.R, R/probe_match.R, R/objfun.R\n\\docType{methods}\n\\name{probe}\n\\alias{probe}\n\\alias{probe,missing-method}\n\\alias{probe,ANY-method}\n\\alias{probe,data.frame-method}\n\\alias{probe,pomp-method}\n\\alias{probe,probed_pomp-method}\n\\alias{probe,probe_match_objfun-method}\n\\alias{probe,objfun-method}\n\\title{Probes (AKA summary statistics)}\n\\usage{\n\\S4method{probe}{data.frame}(\n  data,\n  ...,\n  probes,\n  nsim,\n  seed = NULL,\n  params,\n  rinit,\n  rprocess,\n  rmeasure,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{probe}{pomp}(\n  data,\n  ...,\n  probes,\n  nsim,\n  seed = NULL,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{probe}{probed_pomp}(\n  data,\n  ...,\n  probes,\n  nsim,\n  seed = NULL,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{probe}{probe_match_objfun}(data, ..., seed, verbose = getOption(\"verbose\", FALSE))\n\n\\S4method{probe}{objfun}(data, ..., seed = NULL)\n}\n\\arguments{\n\\item{data}{either a data frame holding the time series data,\nor an object of class \\sQuote{pomp},\ni.e., the output of another \\pkg{pomp} calculation.\nInternally, \\code{data} will be coerced to an array with storage-mode \\code{double}.}\n\n\\item{...}{additional arguments are passed to \\code{\\link{pomp}}.\nThis allows one to set, unset, or modify \\link[=basic_components]{basic model components} within a call to this function.}\n\n\\item{probes}{a single probe or a list of one or more probes.\nA probe is simply a scalar- or vector-valued function of one argument that can be applied to the data array of a \\sQuote{pomp}.\nA vector-valued probe must always return a vector of the same size.\nA number of useful probes are provided with the package:\nsee \\link[=basic_probes]{basic probes}.}\n\n\\item{nsim}{the number of model simulations to be computed.}\n\n\\item{seed}{optional integer;\nif set, the pseudorandom number generator (RNG) will be initialized with \\code{seed}.\nThe RNG will be restored to its original state afterward.}\n\n\\item{params}{optional; named numeric vector of parameters.\nThis will be coerced internally to storage mode \\code{double}.}\n\n\\item{rinit}{simulator of the initial-state distribution.\nThis can be furnished either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rinit=NULL} sets the initial-state simulator to its default.\nFor more information, see \\link[=rinit_spec]{rinit specification}.}\n\n\\item{rprocess}{simulator of the latent state process, specified using one of the \\link[=rprocess_spec]{rprocess plugins}.\nSetting \\code{rprocess=NULL} removes the latent-state simulator.\nFor more information, see \\link[=rprocess_spec]{rprocess specification for the documentation on these plugins}.}\n\n\\item{rmeasure}{simulator of the measurement model, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rmeasure=NULL} removes the measurement model simulator.\nFor more information, see \\link[=rmeasure_spec]{rmeasure specification}.}\n\n\\item{verbose}{logical; if \\code{TRUE}, diagnostic messages will be printed to the console.}\n}\n\\value{\n\\code{probe} returns an object of class \\sQuote{probed_pomp}, which contains the data and the model, together with the results of the \\code{probe} calculation.\n}\n\\description{\nProbe a partially-observed Markov process by computing summary statistics\nand the synthetic likelihood.\n}\n\\details{\n\\code{probe} applies one or more \\dQuote{probes} to time series data and\nmodel simulations and compares the results.  It can be used to diagnose\ngoodness of fit and/or as the basis for \\dQuote{probe-matching}, a\ngeneralized method-of-moments approach to parameter estimation.\n\nA call to \\code{probe} results in the evaluation of the probe(s) in\n\\code{probes} on the data.  Additionally, \\code{nsim} simulated data sets\nare generated (via a call to \\code{\\link{simulate}}) and\nthe probe(s) are applied to each of these.  The results of the probe\ncomputations on real and simulated data are stored in an object of class\n\\sQuote{probed_pomp}.\n\nWhen \\code{probe} operates on a probe-matching objective function (a \\sQuote{probe_match_objfun} object), by default, the\nrandom-number generator seed is fixed at the value given when the objective function was constructed.\nSpecifying \\code{NULL} or an integer for \\code{seed} overrides this behavior.\n}\n\\section{Methods}{\n\nThe following methods are available.\n\\describe{\n\\item{\\code{plot}}{ displays diagnostic plots.  }\n\\item{\\code{summary}}{ displays summary information.\nThe summary includes quantiles (fractions of simulations with probe values less than those realized on the data) and the corresponding two-sided p-values.\nIn addition, the \\dQuote{synthetic likelihood} (Wood 2010) is computed,\nunder the assumption that the probe values are multivariate-normally distributed.  }\n\\item{\\code{logLik}}{ returns the synthetic likelihood for the probes.\nNB: in general, this is not the same as the likelihood.  }\n\\item{\\code{as.data.frame}}{\n coerces a \\sQuote{probed_pomp} to a \\sQuote{data.frame}.\n The latter contains the realized values of the probes on the data and on the simulations.\nThe variable \\code{.id} indicates whether the probes are from the data or simulations.  }\n}\n}\n\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\references{\n\\Kendall1999\n\n\\Wood2010\n}\n\\seealso{\nMore on \\pkg{pomp} elementary algorithms:\n\\code{\\link{elementary_algorithms}},\n\\code{\\link{kalman}},\n\\code{\\link{pfilter}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{simulate}()},\n\\code{\\link{spect}()},\n\\code{\\link{trajectory}()},\n\\code{\\link{wpfilter}()}\n\nMore on methods based on summary statistics:\n\\code{\\link{abc}()},\n\\code{\\link{basic_probes}},\n\\code{\\link{nlf}},\n\\code{\\link{probe_match}},\n\\code{\\link{spect}()},\n\\code{\\link{spect_match}}\n}\n\\author{\nDaniel C. Reuman, Aaron A. King\n}\n\\concept{elementary algorithms}\n\\concept{summary statistic-based methods}\n\\concept{synthetic likelihood}\n"
  },
  {
    "path": "man/probe_match.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/probe_match.R\n\\docType{methods}\n\\name{probe_match}\n\\alias{probe_match}\n\\alias{probe_objfun}\n\\alias{probe_objfun,missing-method}\n\\alias{probe_objfun,ANY-method}\n\\alias{probe_objfun,data.frame-method}\n\\alias{probe_objfun,pomp-method}\n\\alias{probe_objfun,probed_pomp-method}\n\\alias{probe_objfun,probe_match_objfun-method}\n\\title{Probe matching}\n\\usage{\n\\S4method{probe_objfun}{data.frame}(\n  data,\n  ...,\n  est = character(0),\n  fail.value = NA,\n  probes,\n  nsim,\n  seed = NULL,\n  params,\n  rinit,\n  rprocess,\n  rmeasure,\n  partrans,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{probe_objfun}{pomp}(\n  data,\n  ...,\n  est = character(0),\n  fail.value = NA,\n  probes,\n  nsim,\n  seed = NULL,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{probe_objfun}{probed_pomp}(\n  data,\n  ...,\n  est = character(0),\n  fail.value = NA,\n  probes,\n  nsim,\n  seed = NULL,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{probe_objfun}{probe_match_objfun}(\n  data,\n  ...,\n  est,\n  fail.value,\n  seed = NULL,\n  verbose = getOption(\"verbose\", FALSE)\n)\n}\n\\arguments{\n\\item{data}{either a data frame holding the time series data,\nor an object of class \\sQuote{pomp},\ni.e., the output of another \\pkg{pomp} calculation.\nInternally, \\code{data} will be coerced to an array with storage-mode \\code{double}.}\n\n\\item{...}{additional arguments are passed to \\code{\\link{pomp}}.\nThis allows one to set, unset, or modify \\link[=basic_components]{basic model components} within a call to this function.}\n\n\\item{est}{character vector; the names of parameters to be estimated.}\n\n\\item{fail.value}{optional numeric scalar;\nif non-\\code{NA}, this value is substituted for non-finite values of the objective function.\nIt should be a large number (i.e., bigger than any legitimate values the objective function is likely to take).}\n\n\\item{probes}{a single probe or a list of one or more probes.\nA probe is simply a scalar- or vector-valued function of one argument that can be applied to the data array of a \\sQuote{pomp}.\nA vector-valued probe must always return a vector of the same size.\nA number of useful probes are provided with the package:\nsee \\link[=basic_probes]{basic probes}.}\n\n\\item{nsim}{the number of model simulations to be computed.}\n\n\\item{seed}{integer.\nWhen fitting, it is often best to fix the seed of the random-number generator (RNG).\nThis is accomplished by setting \\code{seed} to an integer.\nBy default, \\code{seed = NULL}, which does not alter the RNG state.}\n\n\\item{params}{optional; named numeric vector of parameters.\nThis will be coerced internally to storage mode \\code{double}.}\n\n\\item{rinit}{simulator of the initial-state distribution.\nThis can be furnished either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rinit=NULL} sets the initial-state simulator to its default.\nFor more information, see \\link[=rinit_spec]{rinit specification}.}\n\n\\item{rprocess}{simulator of the latent state process, specified using one of the \\link[=rprocess_spec]{rprocess plugins}.\nSetting \\code{rprocess=NULL} removes the latent-state simulator.\nFor more information, see \\link[=rprocess_spec]{rprocess specification for the documentation on these plugins}.}\n\n\\item{rmeasure}{simulator of the measurement model, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rmeasure=NULL} removes the measurement model simulator.\nFor more information, see \\link[=rmeasure_spec]{rmeasure specification}.}\n\n\\item{partrans}{optional parameter transformations, constructed using \\code{\\link{parameter_trans}}.\n\nMany algorithms for parameter estimation search an unconstrained space of parameters.\nWhen working with such an algorithm and a model for which the parameters are constrained, it can be useful to transform parameters.\nOne should supply the \\code{partrans} argument via a call to \\code{\\link{parameter_trans}}.\nFor more information, see \\link[=parameter_trans]{parameter_trans}.\nSetting \\code{partrans=NULL} removes the parameter transformations, i.e., sets them to the identity transformation.}\n\n\\item{verbose}{logical; if \\code{TRUE}, diagnostic messages will be printed to the console.}\n}\n\\value{\n\\code{probe_objfun} constructs a stateful objective function for probe matching.\nSpecifically, \\code{probe_objfun} returns an object of class \\sQuote{probe_match_objfun}, which is a function suitable for use in an \\code{\\link[stats]{optim}}-like optimizer.\nIn particular, this function takes a single numeric-vector argument that is assumed to contain the parameters named in \\code{est}, in that order.\nWhen called, it will return the negative synthetic log likelihood for the probes specified.\nIt is a stateful function:\nEach time it is called, it will remember the values of the parameters and its estimate of the synthetic likelihood.\n}\n\\description{\nEstimation of parameters by maximum synthetic likelihood\n}\n\\details{\nIn probe-matching, one attempts to minimize the discrepancy between simulated and actual data, as measured by a set of summary statistics called \\emph{probes}.\nIn \\pkg{pomp}, this discrepancy is measured using the \\dQuote{synthetic likelihood} as defined by Wood (2010).\n}\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\section{Important Note}{\n\nSince \\pkg{pomp} cannot guarantee that the \\emph{final} call an optimizer makes to the function is a call \\emph{at} the optimum, it cannot guarantee that the parameters stored in the function are the optimal ones.\nTherefore, it is a good idea to evaluate the function on the parameters returned by the optimization routine, which will ensure that these parameters are stored.\n}\n\n\\section{Warning! Objective functions based on C snippets}{\n\nIf you use C snippets (see \\code{\\link{Csnippet}}), a dynamically loadable library will be built.\nAs a rule, \\pkg{pomp} functions load this library as needed and unload it when it is no longer needed.\nThe stateful objective functions are an exception to this rule.\nFor efficiency, calls to the objective function do not execute \\code{\\link{pompLoad}} or \\code{\\link{pompUnload}}:\nrather, it is assumed that \\code{\\link{pompLoad}} has been called before any call to the objective function.\nWhen a stateful objective function using one or more C snippets is created, \\code{\\link{pompLoad}} is called internally to build and load the library:\ntherefore, within a single \\R session, if one creates a stateful objective function, one can freely call that objective function and (more to the point) pass it to an optimizer that calls it freely, without needing to call \\code{\\link{pompLoad}}.\nOn the other hand, if one retrieves a stored objective function from a file, or passes one to another \\R session, one must call \\code{\\link{pompLoad}} before using it.\n\\strong{Failure to do this will typically result in a segmentation fault (i.e., it will crash the \\R session).}\n}\n\n\\examples{\n\\donttest{\n  gompertz() -> po\n  \n  ## A list of probes:\n  plist <- list(\n    mean=probe_mean(\"Y\",trim=0.1,transform=sqrt),\n    sd=probe_sd(\"Y\",transform=sqrt),\n    probe_marginal(\"Y\",ref=obs(po)),\n    probe_acf(\"Y\",lags=c(1,3,5),type=\"correlation\",transform=sqrt),\n    probe_quantile(\"Y\",prob=c(0.25,0.75),na.rm=TRUE)\n  )\n\n  ## Construct the probe-matching objective function.\n  ## Here, we just want to estimate 'K'.\n  po |>\n    probe_objfun(probes=plist,nsim=100,seed=5069977,\n      est=\"K\") -> f\n\n  ## Any numerical optimizer can be used to minimize 'f'.\n  if (require(subplex)) {\n\n    subplex(fn=f,par=0.4,control=list(reltol=1e-5)) -> out\n\n  } else {\n\n    optim(fn=f,par=0.4,control=list(reltol=1e-5)) -> out\n\n  }\n\n  ## Call the objective one last time on the optimal parameters:\n  f(out$par)\n  coef(f)\n\n  ## There are 'plot' and 'summary' methods:\n  f |> as(\"probed_pomp\") |> plot()\n  f |> summary()\n\n  ## One can convert an objective function to a data frame:\n  f |> as(\"data.frame\") |> head()\n  f |> as(\"probed_pomp\") |> as(\"data.frame\") |> head()\n\n  f |> probe() |> plot()\n\n  ## One can modify the objective function with another call\n  ## to 'probe_objfun':\n\n  f |> probe_objfun(est=c(\"r\",\"K\")) -> f1\n  optim(fn=f1,par=c(0.3,0.3),control=list(reltol=1e-5)) -> out\n  f1(out$par)\n  coef(f1)\n}\n}\n\\references{\n\\Kendall1999\n\n\\Wood2010\n}\n\\seealso{\n\\code{\\link[stats]{optim}} \\code{\\link[subplex]{subplex}} \\code{\\link[nloptr]{nloptr}}\n\nMore on methods based on summary statistics:\n\\code{\\link{abc}()},\n\\code{\\link{basic_probes}},\n\\code{\\link{nlf}},\n\\code{\\link{probe}()},\n\\code{\\link{spect}()},\n\\code{\\link{spect_match}}\n\nMore on \\pkg{pomp} estimation algorithms:\n\\code{\\link{abc}()},\n\\code{\\link{bsmc2}()},\n\\code{\\link{estimation_algorithms}},\n\\code{\\link{mif2}()},\n\\code{\\link{nlf}},\n\\code{\\link{pmcmc}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{spect_match}}\n\nMore on maximization-based estimation methods:\n\\code{\\link{mif2}()},\n\\code{\\link{nlf}},\n\\code{\\link{spect_match}},\n\\code{\\link{traj_match}}\n}\n\\author{\nAaron A. King\n}\n\\concept{estimation methods}\n\\concept{methods based on maximization}\n\\concept{probe matching}\n\\concept{summary statistic-based methods}\n\\concept{synthetic likelihood}\n"
  },
  {
    "path": "man/proposals.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/proposals.R\n\\name{proposals}\n\\alias{proposals}\n\\alias{mvn_diag_rw}\n\\alias{mvn_rw}\n\\alias{mvn_rw_adaptive}\n\\title{MCMC proposal distributions}\n\\usage{\nmvn_diag_rw(rw.sd)\n\nmvn_rw(rw.var)\n\nmvn_rw_adaptive(\n  rw.sd,\n  rw.var,\n  scale.start = NA,\n  scale.cooling = 0.999,\n  shape.start = NA,\n  target = 0.234,\n  max.scaling = 50\n)\n}\n\\arguments{\n\\item{rw.sd}{named numeric vector; random-walk SDs for a multivariate\nnormal random-walk proposal with diagonal variance-covariance matrix.}\n\n\\item{rw.var}{square numeric matrix with row- and column-names.  Specifies\nthe variance-covariance matrix for a multivariate normal random-walk\nproposal distribution.}\n\n\\item{scale.start, scale.cooling, shape.start, target, max.scaling}{parameters\nto control the proposal adaptation algorithm.  Beginning with MCMC\niteration \\code{scale.start}, the scale of the proposal covariance matrix\nwill be adjusted in an effort to match the \\code{target} acceptance ratio.\nThis initial scale adjustment is \\dQuote{cooled}, i.e., the adjustment\ndiminishes as the chain moves along.  The parameter \\code{scale.cooling}\nspecifies the cooling schedule: at n iterations after \\code{scale.start},\nthe current scaling factor is multiplied with \\code{scale.cooling^n}.  The\nmaximum scaling factor allowed at any one iteration is \\code{max.scaling}.\nAfter \\code{shape.start} accepted proposals have accumulated, a scaled\nempirical covariance matrix will be used for the proposals, following\nRoberts and Rosenthal (2009).}\n}\n\\value{\nEach of these calls constructs a function suitable for use as the\n\\code{proposal} argument of \\code{pmcmc} or \\code{abc}.  Given a parameter\nvector, each such function returns a single draw from the corresponding\nproposal distribution.\n}\n\\description{\nFunctions to construct proposal distributions for use with MCMC methods.\n}\n\\references{\n\\Roberts2009\n}\n\\seealso{\nMore on Markov chain Monte Carlo methods:\n\\code{\\link{abc}()},\n\\code{\\link{pmcmc}()}\n}\n\\author{\nAaron A. King, Sebastian Funk\n}\n\\concept{MCMC methods}\n"
  },
  {
    "path": "man/resample.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/resample.R\n\\name{resample}\n\\alias{resample}\n\\alias{systematic_resample}\n\\title{Resample}\n\\usage{\nsystematic_resample(weights, Np = length(weights))\n}\n\\arguments{\n\\item{weights}{numeric; vector of weights.}\n\n\\item{Np}{integer scalar; number of samples to draw.}\n}\n\\value{\nA vector of integers containing the indices of the resample.\n}\n\\description{\nSystematic resampling.\n}\n\\concept{sampling}\n\\keyword{internal}\n"
  },
  {
    "path": "man/ricker.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/ricker.R\n\\docType{data}\n\\name{ricker}\n\\alias{ricker}\n\\title{Ricker model with Poisson observations.}\n\\usage{\nricker(r = exp(3.8), sigma = 0.3, phi = 10, c = 1, N_0 = 7)\n}\n\\arguments{\n\\item{r}{intrinsic growth rate}\n\n\\item{sigma}{environmental process noise s.d.}\n\n\\item{phi}{sampling rate}\n\n\\item{c}{density dependence parameter}\n\n\\item{N_0}{initial condition}\n}\n\\value{\nA \\sQuote{pomp} object containing the Ricker model and simulated data.\n}\n\\description{\n\\code{ricker} is a \\sQuote{pomp} object encoding a stochastic Ricker model\nwith Poisson measurement error.\n}\n\\details{\nThe state process is \\eqn{N_{t+1} = r N_{t} \\exp(-c N_{t}+e_{t})}{N[t+1] =\nr N[t] exp(-c N[t]+e[t])}, where the \\eqn{e_t}{e[t]} are i.i.d. normal\nrandom deviates with zero mean and variance \\eqn{\\sigma^2}{sigma^2}.  The\nobserved variables \\eqn{y_t}{y[t]} are distributed as\n\\eqn{\\mathrm{Poisson}(\\phi N_t)}{Poisson(phi N[t])}.\n}\n\\examples{\npo <- ricker()\nplot(po)\ncoef(po)\nsimulate(po) |> plot()\n\\donttest{ # takes too long for R CMD check\n  ## generate a bifurcation diagram for the Ricker map\n  p <- parmat(coef(ricker()),nrep=500)\n  p[\"r\",] <- exp(seq(from=1.5,to=4,length=500))\n  trajectory(\n    ricker(),\n    times=seq(from=1000,to=2000,by=1),\n    params=p,\n    format=\"array\"\n  ) -> x\n  matplot(p[\"r\",],x[\"N\",,],pch='.',col='black',\n    xlab=expression(log(r)),ylab=\"N\",log='x')\n}\n}\n\\seealso{\nMore examples provided with \\pkg{pomp}:\n\\code{\\link{blowflies}},\n\\code{\\link{childhood_disease_data}},\n\\code{\\link{compartmental_models}},\n\\code{\\link{dacca}()},\n\\code{\\link{ebola}},\n\\code{\\link{gompertz}()},\n\\code{\\link{ou2}()},\n\\code{\\link{pomp_examples}},\n\\code{\\link{rw2}()},\n\\code{\\link{verhulst}()}\n}\n\\concept{pomp examples}\n\\keyword{models}\n"
  },
  {
    "path": "man/rinit.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/workhorses.R\n\\docType{methods}\n\\name{rinit}\n\\alias{rinit}\n\\alias{rinit,ANY-method}\n\\alias{rinit,missing-method}\n\\alias{rinit,pomp-method}\n\\title{rinit workhorse}\n\\usage{\n\\S4method{rinit}{pomp}(object, ..., params = coef(object), t0 = timezero(object), nsim = 1)\n}\n\\arguments{\n\\item{object}{an object of class \\sQuote{pomp}, or of a class that extends \\sQuote{pomp}.\nThis will typically be the output of \\code{pomp}, \\code{simulate}, or one of the \\pkg{pomp} inference algorithms.}\n\n\\item{...}{additional arguments are ignored.}\n\n\\item{params}{a \\code{npar} x \\code{nrep} matrix of parameters.\nEach column is treated as an independent parameter set, in correspondence with the corresponding column of \\code{x}.}\n\n\\item{t0}{the initial time, i.e., the time corresponding to the initial-state distribution.}\n\n\\item{nsim}{optional integer; the number of initial states to simulate per column of \\code{params}.}\n}\n\\value{\n\\code{rinit} returns an \\code{nvar} x \\code{nsim*ncol(params)} matrix of state-process initial conditions when given an \\code{npar} x \\code{nsim} matrix of parameters, \\code{params}, and an initial time \\code{t0}.\nBy default, \\code{t0} is the initial time defined when the \\sQuote{pomp} object ws constructed.\n}\n\\description{\nSamples from the initial-state distribution.\n}\n\\seealso{\n_spec of the initial-state distribution: \\link{rinit_spec}\n\nMore on \\pkg{pomp} workhorse functions:\n\\code{\\link{dinit}()},\n\\code{\\link{dmeasure}()},\n\\code{\\link{dprior}()},\n\\code{\\link{dprocess}()},\n\\code{\\link{emeasure}()},\n\\code{\\link{flow}()},\n\\code{\\link{partrans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{rmeasure}()},\n\\code{\\link{rprior}()},\n\\code{\\link{rprocess}()},\n\\code{\\link{skeleton}()},\n\\code{\\link{vmeasure}()},\n\\code{\\link{workhorses}}\n}\n\\concept{extending the pomp package}\n\\concept{low-level interface}\n\\concept{pomp workhorses}\n"
  },
  {
    "path": "man/rinit_spec.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/rinit_spec.R\n\\name{rinit_spec}\n\\alias{rinit_spec}\n\\title{rinit specification}\n\\description{\nSpecification of the initial-state distribution simulator, rinit.\n}\n\\details{\nTo fully specify the unobserved Markov state process, one must give its distribution at the zero-time (\\code{t0}).\nOne does this by furnishing a value for the \\code{rinit} argument.\nAs usual, this can be provided either as a C snippet or as an \\R function.\nIn the former case, bear in mind that:\n\\enumerate{\n  \\item The goal of a this snippet is the construction of a state vector, i.e., the setting of the dynamical states at time \\eqn{t_0}{t0}.\n  \\item In addition to the parameters and covariates (if any), the variable \\code{t}, containing the zero-time, will be defined in the context in which the snippet is executed.\n  \\item \\strong{NB:} The \\code{statenames} argument plays a particularly important role when the rinit is specified using a C snippet.\n   In particular, every state variable must be named in \\code{statenames}.\n   \\strong{Failure to follow this rule will result in undefined behavior.}\n }\n\\link[=Csnippet]{General rules for writing C snippets can be found here}.\n\nIf an \\R function is to be used, pass\n\\preformatted{\n   rinit = f\n}\nto \\code{pomp}, where \\code{f} is a function with arguments that can include the initial time \\code{t0}, any of the model parameters, and any covariates.\nAs usual, \\code{f} may take additional arguments, provided these are passed along with it in the call to \\code{pomp}.\n\\code{f} must return a named numeric vector of initial states.\nIt is of course important that the names of the states match the expectations of the other basic components.\n\nNote that the state-process \\code{rinit} can be either deterministic (as in the default) or stochastic.\nIn the latter case, it samples from the distribution of the state process at the zero-time, \\code{t0}.\n}\n\\section{Default behavior}{\n\nBy default, \\code{pomp} assumes that the initial distribution is concentrated on a single point.\nIn particular, any parameters in \\code{params}, the names of which end in \\dQuote{\\code{_0}} or \\dQuote{\\code{.0}}, are assumed to be initial values of states.\nWhen the state process is initialized, these are simply copied over as initial conditions.\nThe names of the resulting state variables are obtained by dropping the suffix.\n}\n\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\examples{\n\\donttest{\n  ## Starting with an existing pomp object\n\n  verhulst() -> po\n  \n  ## we add or change the initial-state simulator,\n  ## rinit, using the 'rinit' argument in any 'pomp'\n  ## elementary or estimation function (or in the\n  ## 'pomp' constructor itself).\n  ## Here, we pass the rinit specification to 'simulate'\n  ## as an R function.\n\n  po |>\n    simulate(\n      rinit=function (n_0, ...) {\n        c(n=rpois(n=1,lambda=n_0))\n      }\n    ) -> sim\n\n  ## We can also pass it as a C snippet:\n\n  po |>\n    simulate(\n      rinit=Csnippet(\"n = rpois(n_0);\"),\n      paramnames=\"n_0\",\n      statenames=\"n\"\n    ) -> sim\n\n}\n}\n\\seealso{\n\\code{\\link{rinit}}\n\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{accumvars}},\n\\code{\\link{basic_components}},\n\\code{\\link{betabinomial}},\n\\code{\\link{covariates}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{userdata}},\n\\code{\\link{vmeasure_spec}}\n}\n\\concept{implementation information}\n"
  },
  {
    "path": "man/rmeasure.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/workhorses.R\n\\docType{methods}\n\\name{rmeasure}\n\\alias{rmeasure}\n\\alias{rmeasure,ANY-method}\n\\alias{rmeasure,missing-method}\n\\alias{rmeasure,pomp-method}\n\\title{rmeasure workhorse}\n\\usage{\n\\S4method{rmeasure}{pomp}(\n  object,\n  ...,\n  x = states(object),\n  times = time(object),\n  params = coef(object)\n)\n}\n\\arguments{\n\\item{object}{an object of class \\sQuote{pomp}, or of a class that extends \\sQuote{pomp}.\nThis will typically be the output of \\code{pomp}, \\code{simulate}, or one of the \\pkg{pomp} inference algorithms.}\n\n\\item{...}{additional arguments are ignored.}\n\n\\item{x}{an array containing states of the unobserved process.\nThe dimensions of \\code{x} are \\code{nvars} x \\code{nrep} x \\code{ntimes},\nwhere \\code{nvars} is the number of state variables,\n\\code{nrep} is the number of replicates,\nand \\code{ntimes} is the length of \\code{times}.\nOne can also pass \\code{x} as a named numeric vector, which is equivalent to the \\code{nrep=1}, \\code{ntimes=1} case.}\n\n\\item{times}{a numeric vector (length \\code{ntimes}) containing times.\nThese must be in non-decreasing order.}\n\n\\item{params}{a \\code{npar} x \\code{nrep} matrix of parameters.\nEach column is treated as an independent parameter set, in correspondence with the corresponding column of \\code{x}.}\n}\n\\value{\n\\code{rmeasure} returns a rank-3 array of dimensions\n\\code{nobs} x \\code{nrep} x \\code{ntimes},\nwhere \\code{nobs} is the number of observed variables.\n}\n\\description{\nSample from the measurement model distribution, given values of the latent states and the parameters.\n}\n\\seealso{\nSpecification of the measurement-model simulator: \\link{rmeasure_spec}\n\nMore on \\pkg{pomp} workhorse functions:\n\\code{\\link{dinit}()},\n\\code{\\link{dmeasure}()},\n\\code{\\link{dprior}()},\n\\code{\\link{dprocess}()},\n\\code{\\link{emeasure}()},\n\\code{\\link{flow}()},\n\\code{\\link{partrans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{rinit}()},\n\\code{\\link{rprior}()},\n\\code{\\link{rprocess}()},\n\\code{\\link{skeleton}()},\n\\code{\\link{vmeasure}()},\n\\code{\\link{workhorses}}\n}\n\\concept{extending the pomp package}\n\\concept{low-level interface}\n\\concept{pomp workhorses}\n"
  },
  {
    "path": "man/rmeasure_spec.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/rmeasure_spec.R\n\\name{rmeasure_spec}\n\\alias{rmeasure_spec}\n\\title{rmeasure specification}\n\\description{\nSpecification of the measurement-model simulator, rmeasure.\n}\n\\details{\nThe measurement model is the link between the data and the unobserved state process.\nIt can be specified either by using one or both of the \\code{rmeasure} and \\code{dmeasure} arguments.\n\nSuppose you have a procedure to simulate observations given the value of the latent state variables.\nThen you can furnish \\preformatted{\n  rmeasure = f}\nto \\pkg{pomp} algorithms,\nwhere \\code{f} is a C snippet or \\R function that implements your procedure.\n\nUsing a C snippet is much preferred, due to its much greater computational efficiency.\nSee \\code{\\link{Csnippet}} for general rules on writing C snippets.\n\nIn writing an \\code{rmeasure} C snippet, bear in mind that:\n  \\enumerate{\n    \\item The goal of such a snippet is to fill the observables with random values drawn from the measurement model distribution.\n    Accordingly, each observable should be assigned a new value.\n    \\item In addition to the states, parameters, and covariates (if any), the variable \\code{t}, containing the time of the observation, will be defined in the context in which the snippet is executed.\n  }\n\nThe demos and the tutorials on the \\href{https://kingaa.github.io/pomp/}{package website} give examples.\n\nIt is also possible, though far less efficient, to specify \\code{rmeasure} using an \\R function.\nIn this case, specify the measurement model simulator by furnishing \\preformatted{\n  rmeasure = f}\nto \\code{pomp}, where \\code{f} is an \\R function.\nThe arguments of \\code{f} should be chosen from among the state variables, parameters, covariates, and time.\nIt must also have the argument \\code{...}.\n\\code{f} must return a named numeric vector of length equal to the number of observable variables.\n}\n\\section{Default behavior}{\n\nThe default \\code{rmeasure} is undefined.\nIt will yield missing values (\\code{NA}).\n}\n\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\examples{\n\\donttest{\n  ## We start with the pre-built Ricker example:\n  \n  ricker() -> po\n\n  ## To change the measurement model simulator, rmeasure,\n  ## we use the 'rmeasure' argument in any 'pomp'\n  ## elementary or estimation function.\n  ## Here, we pass the rmeasure specification to 'simulate'\n  ## as an R function.\n\n  po |>\n    simulate(\n      rmeasure=function (N, phi, ...) {\n        c(y=rpois(n=1,lambda=phi*N))\n      }\n    ) -> sim\n\n  ## We can also pass it as a C snippet:\n\n  po |>\n    simulate(\n      rmeasure=Csnippet(\"y = rpois(phi*N);\"),\n      paramnames=\"phi\",\n      statenames=\"N\"\n    ) -> sim\n\n}\n}\n\\seealso{\n\\code{\\link{rmeasure}}\n\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{accumvars}},\n\\code{\\link{basic_components}},\n\\code{\\link{betabinomial}},\n\\code{\\link{covariates}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{userdata}},\n\\code{\\link{vmeasure_spec}}\n}\n\\concept{implementation information}\n"
  },
  {
    "path": "man/roxygen/meta.R",
    "content": "list(\n  rd_family_title = list(\n    `interpolation`=\"More on interpolation:\",\n    `methods based on maximization`=\"More on maximization-based estimation methods:\",\n    `full-information methods`=\"More on full-information (i.e., likelihood-based) methods:\",\n    `Bayesian methods`=\"More on Bayesian methods:\",\n    `MCMC methods`=\"More on Markov chain Monte Carlo methods:\",\n    `estimation methods`=\"More on \\\\pkg{pomp} estimation algorithms:\",\n    `elementary algorithms`=\"More on \\\\pkg{pomp} elementary algorithms: \",\n    `pomp workhorses`=\"More on \\\\pkg{pomp} workhorse functions: \",\n    `implementation information`=\"More on implementing POMP models: \",\n    `pomp datasets`=\"More data sets provided with \\\\pkg{pomp}: \",\n    `pomp examples`=\"More examples provided with \\\\pkg{pomp}: \",\n    `particle filter methods`=\"More on sequential Monte Carlo methods: \",\n    `summary statistic-based methods`=\"More on methods based on summary statistics: \",\n    `deterministic methods`=\"More on methods for deterministic process models: \"\n  )\n)\n"
  },
  {
    "path": "man/rprior.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/workhorses.R\n\\docType{methods}\n\\name{rprior}\n\\alias{rprior}\n\\alias{rprior,ANY-method}\n\\alias{rprior,missing-method}\n\\alias{rprior,pomp-method}\n\\title{rprior workhorse}\n\\usage{\n\\S4method{rprior}{pomp}(object, ..., params = coef(object))\n}\n\\arguments{\n\\item{object}{an object of class \\sQuote{pomp}, or of a class that extends \\sQuote{pomp}.\nThis will typically be the output of \\code{pomp}, \\code{simulate}, or one of the \\pkg{pomp} inference algorithms.}\n\n\\item{...}{additional arguments are ignored.}\n\n\\item{params}{a \\code{npar} x \\code{nrep} matrix of parameters.\nEach column is treated as an independent parameter set, in correspondence with the corresponding column of \\code{x}.}\n}\n\\value{\nA numeric matrix containing the required samples.\n}\n\\description{\nSample from the prior probability distribution.\n}\n\\seealso{\nSpecification of the prior distribution simulator: \\link{prior_spec}\n\nMore on \\pkg{pomp} workhorse functions:\n\\code{\\link{dinit}()},\n\\code{\\link{dmeasure}()},\n\\code{\\link{dprior}()},\n\\code{\\link{dprocess}()},\n\\code{\\link{emeasure}()},\n\\code{\\link{flow}()},\n\\code{\\link{partrans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{rinit}()},\n\\code{\\link{rmeasure}()},\n\\code{\\link{rprocess}()},\n\\code{\\link{skeleton}()},\n\\code{\\link{vmeasure}()},\n\\code{\\link{workhorses}}\n\nMore on Bayesian methods:\n\\code{\\link{abc}()},\n\\code{\\link{bsmc2}()},\n\\code{\\link{dprior}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{prior_spec}}\n}\n\\concept{Bayesian methods}\n\\concept{extending the pomp package}\n\\concept{low-level interface}\n\\concept{pomp workhorses}\n"
  },
  {
    "path": "man/rprocess.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/workhorses.R\n\\docType{methods}\n\\name{rprocess}\n\\alias{rprocess}\n\\alias{rprocess,ANY-method}\n\\alias{rprocess,missing-method}\n\\alias{rprocess,pomp-method}\n\\title{rprocess workhorse}\n\\usage{\n\\S4method{rprocess}{pomp}(\n  object,\n  ...,\n  x0 = rinit(object),\n  t0 = timezero(object),\n  times = time(object),\n  params = coef(object)\n)\n}\n\\arguments{\n\\item{object}{an object of class \\sQuote{pomp}, or of a class that extends \\sQuote{pomp}.\nThis will typically be the output of \\code{pomp}, \\code{simulate}, or one of the \\pkg{pomp} inference algorithms.}\n\n\\item{...}{additional arguments are ignored.}\n\n\\item{x0}{an \\code{nvar} x \\code{nrep} matrix containing the starting state of the system.\nColumns of \\code{x0} correspond to states;\nrows to components of the state vector.\nOne independent simulation will be performed for each column.\nNote that in this case, \\code{params} must also have \\code{nrep} columns.}\n\n\\item{t0}{the initial time, i.e., the time corresponding to the state in \\code{x0}.}\n\n\\item{times}{a numeric vector (length \\code{ntimes}) containing times.\nThese must be in non-decreasing order.}\n\n\\item{params}{a \\code{npar} x \\code{nrep} matrix of parameters.\nEach column is treated as an independent parameter set, in correspondence with the corresponding column of \\code{x0}.}\n}\n\\value{\n\\code{rprocess} returns a rank-3 array with rownames.\nSuppose \\code{x} is the array returned.\nThen \\preformatted{dim(x)=c(nvars,nrep,ntimes),}\nwhere \\code{nvars} is the number of state variables (=\\code{nrow(x0)}),\n\\code{nrep} is the number of independent realizations simulated (=\\code{ncol(x0)}), and\n\\code{ntimes} is the length of the vector \\code{times}.\n\\code{x[,j,k]} is the value of the state process in the \\code{j}-th realization at time \\code{times[k]}.\nThe rownames of \\code{x} will correspond to those of \\code{x0}.\n}\n\\description{\n\\code{rprocess} simulates the process-model portion of partially-observed Markov process.\n}\n\\details{\nWhen \\code{rprocess} is called, \\code{t0} is taken to be the initial time (i.e., that corresponding to \\code{x0}).\nThe values in \\code{times} are the times at which the state of the simulated processes are required.\n}\n\\seealso{\nSpecification of the process-model simulator: \\link{rprocess_spec}\n\nMore on \\pkg{pomp} workhorse functions:\n\\code{\\link{dinit}()},\n\\code{\\link{dmeasure}()},\n\\code{\\link{dprior}()},\n\\code{\\link{dprocess}()},\n\\code{\\link{emeasure}()},\n\\code{\\link{flow}()},\n\\code{\\link{partrans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{rinit}()},\n\\code{\\link{rmeasure}()},\n\\code{\\link{rprior}()},\n\\code{\\link{skeleton}()},\n\\code{\\link{vmeasure}()},\n\\code{\\link{workhorses}}\n}\n\\concept{extending the pomp package}\n\\concept{low-level interface}\n\\concept{pomp workhorses}\n"
  },
  {
    "path": "man/rprocess_spec.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/rprocess_spec.R\n\\docType{methods}\n\\name{rprocess_spec}\n\\alias{rprocess_spec}\n\\alias{onestep}\n\\alias{discrete_time}\n\\alias{euler}\n\\alias{gillespie}\n\\alias{gillespie_hl}\n\\title{rprocess specification}\n\\usage{\nonestep(step.fun)\n\ndiscrete_time(step.fun, delta.t = 1)\n\neuler(step.fun, delta.t)\n\ngillespie(rate.fun, v, hmax = Inf)\n\ngillespie_hl(..., .pre = \"\", .post = \"\", hmax = Inf)\n}\n\\arguments{\n\\item{step.fun}{a C snippet, an R function, or\nthe name of a native routine in a shared-object library.\nThis gives a procedure by which one simulates a single step of the latent state process.}\n\n\\item{delta.t}{positive numerical value; for \\code{euler} and \\code{discrete_time}, the size of the step to take}\n\n\\item{rate.fun}{a C snippet, an R function, or\nthe name of a native routine in a shared-object library.\nThis gives a procedure by which one computes the event-rate of the elementary events in the continuous-time latent Markov chain.}\n\n\\item{v}{integer matrix; giving the stoichiometry of the continuous-time latent Markov process.\nIt should have dimensions \\code{nvar} x \\code{nevent}, where \\code{nvar} is the number of state variables and \\code{nevent} is the number of elementary events.\n\\code{v} describes the changes that occur in each elementary event:\nit will usually comprise the values 1, -1, and 0 according to whether a state variable is incremented, decremented, or unchanged in an elementary event.\nThe rows of \\code{v} may be unnamed or named.\nIf the rows are unnamed, they are assumed to be in the same order as the vector of state variables returned by \\code{rinit}.\nIf the rows are named,\nthe names of the state variables returned by \\code{rinit} will be matched\nto the rows of \\code{v} to ensure a correct mapping.\nIf any of the row names of \\code{v} cannot be found among the state variables or if any row names of \\code{v} are duplicated, an error will occur.}\n\n\\item{hmax}{maximum time step allowed (see below)}\n\n\\item{\\dots}{individual C snippets corresponding to elementary events}\n\n\\item{.pre, .post}{C snippets (see Details)}\n}\n\\description{\nSpecification of the latent state process simulator, rprocess.\n}\n\\section{Discrete-time processes}{\n\nIf the state process evolves in discrete time, specify \\code{rprocess} using the \\code{discrete_time} plug-in.\nSpecifically, provide\n\\preformatted{\n    rprocess = discrete_time(step.fun = f, delta.t),\n}\nwhere \\code{f} is a C snippet or \\R function that simulates one step of the state process.\nThe former is the preferred option, due to its much greater computational efficiency.\nThe goal of such a C snippet is to replace the state variables with their new random values at the end of the time interval.\nAccordingly, each state variable should be over-written with its new value.\nIn addition to the states, parameters, covariates (if any), and observables, the variables \\code{t} and \\code{dt}, containing respectively the time at the beginning of the step and the step's duration, will be defined in the context in which the C snippet is executed.\nSee \\code{\\link{Csnippet}} for general rules on writing C snippets.\nExamples are to be found in the tutorials on the \\href{https://kingaa.github.io/pomp/}{package website}.\n\nIf \\code{f} is given as an \\R function, its arguments should come from the state variables, parameters, covariates, and time.\nIt may also take the argument \\sQuote{\\code{delta.t}};\nwhen called, the latter will be the timestep.\nIt must also have the argument \\sQuote{\\code{...}}.\nIt should return a named vector of length equal to the number of state variables, representing a draw from the distribution of the state process at time \\code{t+delta.t} conditional on its value at time \\code{t}.\n}\n\n\\section{Continuous-time processes}{\n\nIf the state process evolves in continuous time, but you can use an Euler approximation, implement \\code{rprocess} using the \\code{euler} plug-in.\nSpecify\n\\preformatted{\n    rprocess = euler(step.fun = f, delta.t)\n}\nin this case.\nAs before, \\code{f} can be provided either as a C snippet or as an \\R function, the former resulting in much quicker computations.\nThe form of \\code{f} will be the same as above (in the discrete-time case).\n\nIf you have a procedure that allows you, given the value of the state process at any time,\nto simulate it at an arbitrary time in the future, use the \\code{onestep} plug-in.\nTo do so, specify\n\\preformatted{\n    rprocess = onestep(step.fun = f).\n}\nAgain, \\code{f} can be provided either as a C snippet or as an \\R function, the former resulting in much quicker computations.\nThe form of \\code{f} should be as above (in the discrete-time or Euler cases).\n}\n\n\\section{Size of time step}{\n\nThe simulator plug-ins \\code{discrete_time}, \\code{euler}, and \\code{onestep} all work by taking discrete time steps.\nThey differ as to how this is done.\nSpecifically,\n\\enumerate{\n\\item \\code{onestep} takes a single step to go from any given time \\code{t1} to any later time \\code{t2} (\\code{t1 <= t2}).\nThus, this plug-in is designed for use in situations where a closed-form solution to the process exists.\n\\item To go from \\code{t1} to \\code{t2}, \\code{euler} takes \\code{n} steps of equal size, where\n\\preformatted{\n    n = ceiling((t2-t1)/delta.t).\n}\n\\item \\code{discrete_time} assumes that the process evolves in discrete time, where the interval between successive times is \\code{delta.t}.\nThus, to go from \\code{t1} to \\code{t2}, \\code{discrete_time} takes \\code{n} steps of size exactly \\code{delta.t}, where\n\\preformatted{\n    n = floor((t2-t1)/delta.t).\n}\n}\n}\n\n\\section{Exact (event-driven) simulations}{\n\nIf you desire exact simulation of certain continuous-time Markov chains, an implementation of Gillespie's algorithm (Gillespie 1977) is available,\nvia the \\code{gillespie} and \\code{gillespie_hl} plug-ins.\nThe former allows for the rate function to be provided as an \\R function or a single C snippet,\nwhile the latter provides a means of specifying the elementary events via a list of C snippets.\n\nA high-level interface to the simulator is provided by \\code{gillespie_hl}.\nTo use it, supply\n\\preformatted{\n    rprocess = gillespie_hl(..., .pre = \"\", .post = \"\", hmax = Inf)\n}\nto \\code{pomp}.\nEach argument in \\code{...} corresponds to a single elementary event and should be a list containing two elements.\nThe first should be a string or C snippet;\nthe second should be a named integer vector.\nThe variable \\code{rate} will exist in the context of the C snippet, as will the parameter, state variables, covariates, and the time \\code{t}.\nThe C snippet should assign to the variable \\code{rate} the corresponding elementary event rate.\n\nThe named integer vector specifies the changes to the state variables corresponding to the elementary event.\nThere should be named value for each of the state variables returned by \\code{rinit}.\nThe arguments \\code{.pre} and \\code{.post} can be used to provide C code that will run respectively before and after the elementary-event snippets.\nThese hooks can be useful for avoiding duplication of code that performs calculations needed to obtain several of the different event rates.\n\nHere's how a simple birth-death model might be specified:\n\\preformatted{\n    gillespie_hl(\n        birth=list(\"rate = b*N;\",c(N=1)),\n        death=list(\"rate = m*N;\",c(N=-1))\n    )\n}\nIn the above, the state variable \\code{N} represents the population size and parameters \\code{b}, \\code{m} are the birth and death rates, respectively.\n\nTo use the lower-level \\code{gillespie} interface, furnish\n\\preformatted{\n    rprocess = gillespie(rate.fun = f, v, hmax = Inf)\n}\nto \\code{pomp}, where \\code{f} gives the rates of the elementary events.\nHere, \\code{f} may be furnished as an \\R function or as a C snippet.\nIf \\code{f} is an \\R function, its arguments should come from the state variables, parameters, covariates, and time.\nIt must also have the arguments \\sQuote{\\code{j}} and \\sQuote{\\code{...}}.\nWhen \\code{f} is called,\nthe integer \\code{j} will indicate the elementary event (corresponding to the column the matrix \\code{v}, see below).\n\\code{f} should return a single numerical value, representing the rate of that elementary event at that point in state space and time.\nIf \\code{f} is supplied as a C snippet, the parameters, latent state variables, covariates, and time will be visible in the context wherein the snippet is executed, as will the integer \\sQuote{\\code{j}}.\nThe purpose of the C snippet is to fill the double-precision variable \\sQuote{\\code{rate}} with the corresponding event rate.\n\nHere, the stoichiometric matrix \\code{v} specifies the continuous-time Markov process in terms of its elementary events.\nIt should have dimensions \\code{nvar} x \\code{nevent}, where \\code{nvar} is the number of state variables and \\code{nevent} is the number of elementary events.\n\\code{v} describes the changes that occur in each elementary event:\nit will usually comprise the values 1, -1, and 0 according to whether a state variable is incremented, decremented, or unchanged in an elementary event.\nThe rows of \\code{v} should have names corresponding to the state variables.\nIf any of the row names of \\code{v} cannot be found among the state variables or if any row names of \\code{v} are duplicated, an error will occur.\n\nThis lower-level interface may be preferable if it is easier to write code that calculates the correct rate based on \\code{j} rather than to write a snippet for each possible value of \\code{j}.\nFor example, if the number of possible values of \\code{j} is large and the rates vary according to a few simple rules, the lower-level interface may provide the easier way of specifying the model.\n\nWhen the process is non-autonomous (i.e., the event rates depend explicitly on time), it can be useful to set \\code{hmax} to the maximum step that will be taken.\nBy default, the elementary event rates will be recomputed at least once per observation interval.\n}\n\n\\section{Default behavior}{\n\nThe default \\code{rprocess} is undefined.\nIt will yield missing values (\\code{NA}) for all state variables.\n}\n\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\seealso{\n\\code{\\link{rprocess}}\n\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{accumvars}},\n\\code{\\link{basic_components}},\n\\code{\\link{betabinomial}},\n\\code{\\link{covariates}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{userdata}},\n\\code{\\link{vmeasure_spec}}\n}\n\\concept{implementation information}\n"
  },
  {
    "path": "man/rw2.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/rw2.R\n\\docType{data}\n\\name{rw2}\n\\alias{rw2}\n\\title{Two-dimensional random-walk process}\n\\usage{\nrw2(\n  x1_0 = 0,\n  x2_0 = 0,\n  s1 = 1,\n  s2 = 3,\n  tau = 1,\n  times = 1:100,\n  t0 = 0,\n  seed = 1376784970L\n)\n}\n\\arguments{\n\\item{x1_0, x2_0}{initial conditions (i.e., latent state variable values at the zero time \\code{t0})}\n\n\\item{s1, s2}{random walk intensities}\n\n\\item{tau}{observation error s.d.}\n\n\\item{times}{observation times}\n\n\\item{t0}{zero time}\n\n\\item{seed}{seed of the random number generator}\n}\n\\value{\nA \\sQuote{pomp} object containing simulated data.\n}\n\\description{\n\\code{rw2} constructs a \\sQuote{pomp} object encoding a 2-D Gaussian random walk.\n}\n\\details{\nThe random-walk process is fully but noisily observed.\n}\n\\examples{\n\\donttest{\n\n  if (require(ggplot2)) {\n\n    rw2() |> plot()\n\n    rw2(s1=1,s2=1,tau=0.1) |>\n      simulate(nsim=10,format=\"d\") |>\n      ggplot(aes(x=y1,y=y2,group=.id,color=.id))+\n      geom_path()+\n      guides(color=\"none\")+\n      theme_bw()\n\n  }\n}\n}\n\\seealso{\nMore examples provided with \\pkg{pomp}:\n\\code{\\link{blowflies}},\n\\code{\\link{childhood_disease_data}},\n\\code{\\link{compartmental_models}},\n\\code{\\link{dacca}()},\n\\code{\\link{ebola}},\n\\code{\\link{gompertz}()},\n\\code{\\link{ou2}()},\n\\code{\\link{pomp_examples}},\n\\code{\\link{ricker}()},\n\\code{\\link{verhulst}()}\n}\n\\concept{pomp examples}\n\\keyword{models}\n"
  },
  {
    "path": "man/rw_sd.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/mif2.R\n\\name{rw_sd}\n\\alias{rw_sd}\n\\title{rw_sd}\n\\usage{\nrw_sd(...)\n}\n\\arguments{\n\\item{\\dots}{Specification of the random-walk intensities (as standard deviations).}\n}\n\\description{\nSpecifying random-walk intensities.\n}\n\\details{\nSee \\code{\\link{mif2}} for details.\n}\n\\seealso{\n\\code{\\link{mif2}}\n}\n"
  },
  {
    "path": "man/sannbox.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/sannbox.R\n\\name{sannbox}\n\\alias{sannbox}\n\\title{Simulated annealing with box constraints.}\n\\usage{\nsannbox(par, fn, control = list(), ...)\n}\n\\arguments{\n\\item{par}{Initial values for the parameters to be optimized over.}\n\n\\item{fn}{A function to be minimized, with first argument the vector of\nparameters over which minimization is to take place.  It should return a\nscalar result.}\n\n\\item{control}{A named list of control parameters.  See \\sQuote{Details}.}\n\n\\item{\\dots}{ignored.}\n}\n\\value{\n\\code{sannbox} returns a list with components:\n\\describe{\n\\item{counts}{\ntwo-element integer vector.\nThe first number gives the number of calls made to \\code{fn}.\nThe second number is provided for compatibility with \\code{\\link[stats]{optim}} and will always be NA.\n}\n\\item{convergence}{\nprovided for compatibility with \\code{\\link[stats]{optim}};\nwill always be 0.\n}\n\\item{final.params}{last tried value of \\code{par}.}\n\\item{final.value}{value of \\code{fn} corresponding to\n\\code{final.params}.}\n\\item{par}{best tried value of \\code{par}.}\n\\item{value}{value of \\code{fn} corresponding to \\code{par}.} }\n}\n\\description{\nA straightforward implementation of simulated annealing with box constraints.\n}\n\\details{\nThe \\code{control} argument is a list that can supply any of the following components:\n\\describe{\n\\item{trace}{ Non-negative integer.\nIf positive, tracing information on the progress of the optimization is\nproduced.  Higher values may produce more tracing information.  }\n\\item{fnscale}{ An overall scaling to be applied to the value of\n\\code{fn} during optimization.  If negative, turns the problem into a\nmaximization problem.  Optimization is performed on \\code{fn(par)/fnscale}.}\n\\item{parscale}{ A vector of scaling values for the parameters.\nOptimization is performed on \\code{par/parscale} and these should be\ncomparable in the sense that a unit change in any element produces about a\nunit change in the scaled value.  }\n\\item{maxit}{ The total number of function evaluations: there is no\nother stopping criterion.  Defaults to \\code{10000}.  }\n\\item{temp}{ starting temperature for the cooling\nschedule.  Defaults to \\code{1}.  }\n\\item{tmax}{ number of function evaluations at each temperature.\nDefaults to \\code{10}.  }\n\\item{candidate.dist}{ function to randomly select a new candidate\nparameter vector.  This should be a function with three arguments, the\nfirst being the current parameter vector, the second the temperature, and\nthe third the parameter scaling.  By default, \\code{candidate.dist} is\n\\preformatted{function(par,temp,scale)\n                rnorm(n=length(par),mean=par,sd=scale*temp).} }\n\\item{sched}{ cooling schedule.  A function of a three arguments giving the\ntemperature as a function of iteration number and the control parameters\n\\code{temp} and \\code{tmax}.\nBy default, \\code{sched} is\n\\preformatted{function(k,temp,tmax) temp/log(((k-1)\\%/\\%tmax)*tmax+exp(1)).}\nAlternatively, one can supply a numeric vector of temperatures.\nThis must be of length at least \\code{maxit}. }\n\\item{lower,upper}{ optional\nnumeric vectors.  These describe the lower and upper box constraints,\nrespectively.  Each can be specified either as a single scalar (common to\nall parameters) or as a vector of the same length as \\code{par}.  By\ndefault, \\code{lower=-Inf} and \\code{upper=Inf}, i.e., there are no\nconstraints.} }\n}\n\\seealso{\n\\link[=traj_match]{trajectory matching}, \\link[=probe_match]{probe matching}, \\link[=spect_match]{spectrum matching}, \\link[=nlf]{nonlinear forecasting}.\n}\n\\author{\nDaniel Reuman, Aaron A. King\n}\n\\keyword{optimize}\n"
  },
  {
    "path": "man/saved_states.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/saved_states.R\n\\name{saved_states}\n\\alias{saved_states}\n\\alias{saved_states,ANY-method}\n\\alias{saved_states,missing-method}\n\\alias{saved_states,pfilterd_pomp-method}\n\\alias{saved_states,pfilterList-method}\n\\title{Saved states}\n\\usage{\n\\S4method{saved_states}{pfilterd_pomp}(object, ..., format = c(\"list\", \"data.frame\"))\n\n\\S4method{saved_states}{pfilterList}(object, ..., format = c(\"list\", \"data.frame\"))\n}\n\\arguments{\n\\item{object}{result of a filtering computation}\n\n\\item{...}{ignored}\n\n\\item{format}{character;\nformat of the returned object (see below).}\n}\n\\value{\nAccording to the \\code{format} argument, the saved states are returned either as a list or a data frame.\n\nIf \\code{format=\"data.frame\"}, then the returned data frame holds the state variables and (optionally) the unnormalized log weight of each particle at each observation time.\nThe \\code{.id} variable distinguishes particles.\n\nIf \\code{format=\"list\"} and \\code{\\link{pfilter}} was called with \\code{save.states=\"unweighted\"} or \\code{save.states=\"TRUE\"}, the returned list contains one element per observation time.\nEach element consists of a matrix, with one row for each state variable and one column for each particle.\nIf \\code{\\link{pfilter}} was called with \\code{save.states=\"weighted\"}, the list itself contains two lists:\nthe first holds the particles as above, the second holds the corresponding unnormalized log weights.\nIn particular, it has one element per observation time; each element is the vector of per-particle log weights.\n}\n\\description{\nRetrieve latent state trajectories from a particle filter calculation.\n}\n\\details{\nWhen one calls \\code{\\link{pfilter}} with \\code{save.states=\"filter\"} or \\code{save.states=\"prediction\"}, the latent state vector associated with each particle is saved.\nThis can be extracted by calling \\code{saved_states} on the \\sQuote{pfilterd.pomp} object.\nIf the filtered particles are saved, these particles are \\emph{unweighted}, saved \\emph{after} resampling using their normalized weights.\nIf the argument  \\code{save.states=\"prediction\"} was used, the particles correspond to simulations from \\code{rprocess}, and their corresponding unnormalized weights are included in the output.\n}\n\\seealso{\nMore on sequential Monte Carlo methods:\n\\code{\\link{bsmc2}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{kalman}},\n\\code{\\link{mif2}()},\n\\code{\\link{pfilter}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{wpfilter}()}\n\nOther extraction methods: \n\\code{\\link{coef}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{covmat}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{forecast}()},\n\\code{\\link{logLik}},\n\\code{\\link{obs}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{spy}()},\n\\code{\\link{states}()},\n\\code{\\link{summary}()},\n\\code{\\link{time}()},\n\\code{\\link{timezero}()},\n\\code{\\link{traces}()}\n}\n\\concept{extraction methods}\n\\concept{particle filter methods}\n"
  },
  {
    "path": "man/show.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/show.R\n\\docType{methods}\n\\name{show}\n\\alias{show}\n\\alias{show,unshowable-method}\n\\alias{show,listie-method}\n\\alias{show,rprocPlugin-method}\n\\alias{show,onestepRprocPlugin-method}\n\\alias{show,discreteRprocPlugin-method}\n\\alias{show,eulerRprocPlugin-method}\n\\alias{show,gillespieRprocPlugin-method}\n\\alias{show,pomp_fun-method}\n\\alias{show,partransPlugin-method}\n\\alias{show,covartable-method}\n\\alias{show,skelPlugin-method}\n\\alias{show,vectorfieldPlugin-method}\n\\alias{show,mapPlugin-method}\n\\title{Show methods}\n\\usage{\n\\S4method{show}{unshowable}(object)\n\n\\S4method{show}{listie}(object)\n\n\\S4method{show}{rprocPlugin}(object)\n\n\\S4method{show}{onestepRprocPlugin}(object)\n\n\\S4method{show}{discreteRprocPlugin}(object)\n\n\\S4method{show}{eulerRprocPlugin}(object)\n\n\\S4method{show}{gillespieRprocPlugin}(object)\n\n\\S4method{show}{pomp_fun}(object)\n\n\\S4method{show}{partransPlugin}(object)\n\n\\S4method{show}{covartable}(object)\n\n\\S4method{show}{skelPlugin}(object)\n\n\\S4method{show}{vectorfieldPlugin}(object)\n\n\\S4method{show}{mapPlugin}(object)\n}\n\\description{\nDisplay the object, according to its class.\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/simulate.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/simulate.R, R/objfun.R\n\\docType{methods}\n\\name{simulate}\n\\alias{simulate}\n\\alias{simulate,missing-method}\n\\alias{simulate,data.frame-method}\n\\alias{simulate,pomp-method}\n\\alias{simulate,objfun-method}\n\\title{Simulations of a partially-observed Markov process}\n\\usage{\n\\S4method{simulate}{missing}(\n  object,\n  nsim = 1,\n  seed = NULL,\n  ...,\n  times,\n  t0,\n  params,\n  rinit,\n  rprocess,\n  rmeasure,\n  format = c(\"pomps\", \"arrays\", \"data.frame\"),\n  include.data = FALSE,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{simulate}{data.frame}(\n  object,\n  nsim = 1,\n  seed = NULL,\n  ...,\n  times,\n  t0,\n  params,\n  rinit,\n  rprocess,\n  rmeasure,\n  format = c(\"pomps\", \"arrays\", \"data.frame\"),\n  include.data = FALSE,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{simulate}{pomp}(\n  object,\n  nsim = 1,\n  seed = NULL,\n  ...,\n  format = c(\"pomps\", \"arrays\", \"data.frame\"),\n  include.data = FALSE,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{simulate}{objfun}(object, nsim = 1, seed = NULL, ...)\n}\n\\arguments{\n\\item{object}{optional;\nif present, it should be a data frame or a \\sQuote{pomp} object.}\n\n\\item{nsim}{The number of simulations to perform.\nNote that the number of replicates will be \\code{nsim} times \\code{ncol(params)}.}\n\n\\item{seed}{optional integer;\nif set, the pseudorandom number generator (RNG) will be initialized with \\code{seed}.\nThe RNG will be restored to its original state afterward.}\n\n\\item{...}{additional arguments are passed to \\code{\\link{pomp}}.}\n\n\\item{times}{the sequence of observation times.\n\\code{times} must indicate the column of observation times by name or index.\nThe time vector must be numeric and non-decreasing.}\n\n\\item{t0}{The zero-time, i.e., the time of the initial state.\nThis must be no later than the time of the first observation, i.e., \\code{t0 <= times[1]}.}\n\n\\item{params}{a named numeric vector or a matrix with rownames\ncontaining the parameters at which the simulations are to be performed.}\n\n\\item{rinit}{simulator of the initial-state distribution.\nThis can be furnished either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rinit=NULL} sets the initial-state simulator to its default.\nFor more information, see \\link[=rinit_spec]{rinit specification}.}\n\n\\item{rprocess}{simulator of the latent state process, specified using one of the \\link[=rprocess_spec]{rprocess plugins}.\nSetting \\code{rprocess=NULL} removes the latent-state simulator.\nFor more information, see \\link[=rprocess_spec]{rprocess specification for the documentation on these plugins}.}\n\n\\item{rmeasure}{simulator of the measurement model, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rmeasure=NULL} removes the measurement model simulator.\nFor more information, see \\link[=rmeasure_spec]{rmeasure specification}.}\n\n\\item{format}{the format in which to return the results.\n\n\\code{format = \"pomps\"} causes the results to be returned as a single \\dQuote{pomp} object, if \\code{params} is a vector, or a list of \\dQuote{pomp} objects, if \\code{params} is a matrix with more than one column.\nEach of these will be identical to \\code{object} except in that the latent states and observations will have been replaced by their simulated values.\n\n\\code{format = \"arrays\"} causes the results to be returned as a list of two arrays.\nThe \\dQuote{states} element will contain the simulated state trajectories in a rank-3 array with dimensions\n\\code{nvar} x \\code{(ncol(params)*nsim)} x \\code{ntimes}.\nHere, \\code{nvar} is the number of state variables and \\code{ntimes} the length of the argument \\code{times}.\nThe \\dQuote{obs} element will contain the simulated data, returned as a rank-3 array with dimensions\n\\code{nobs} x \\code{(ncol(params)*nsim)} x \\code{ntimes}.\nHere, \\code{nobs} is the number of observables.\n\n\\code{format = \"data.frame\"} causes the results to be returned as a single data frame containing\nthe time, states, and observations.\nAn ordered factor variable, \\sQuote{.id}, distinguishes one simulation from another.}\n\n\\item{include.data}{if \\code{TRUE}, the original data and covariates (if any) are included (with \\code{.id = \"data\"}).\nThis option is ignored unless \\code{format = \"data.frame\"}.}\n\n\\item{verbose}{logical; if \\code{TRUE}, diagnostic messages will be printed to the console.}\n}\n\\value{\nA single \\dQuote{pomp} object,\na \\dQuote{pompList} object,\na named list of two arrays,\nor a data frame, according to the \\code{format} option.\n\nIf \\code{params} is a matrix, each column is treated as a distinct parameter set.\nIn this case, if \\code{nsim=1},\nthen \\code{simulate} will return one simulation for each parameter set.\nIf \\code{nsim>1},\nthen \\code{simulate} will yield \\code{nsim} simulations for each parameter set.\nThese will be ordered such that\nthe first \\code{ncol(params)} simulations represent one simulation\nfrom each of the distinct parameter sets,\nthe second \\code{ncol(params)} simulations represent a second simulation from each,\nand so on.\n\nAdding column names to \\code{params} can be helpful.\n}\n\\description{\n\\code{simulate} generates simulations of the state and measurement\nprocesses.\n}\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\seealso{\nMore on \\pkg{pomp} elementary algorithms:\n\\code{\\link{elementary_algorithms}},\n\\code{\\link{kalman}},\n\\code{\\link{pfilter}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{probe}()},\n\\code{\\link{spect}()},\n\\code{\\link{trajectory}()},\n\\code{\\link{wpfilter}()}\n}\n\\author{\nAaron A. King\n}\n\\concept{elementary algorithms}\n"
  },
  {
    "path": "man/sir.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/sir.R\n\\docType{data}\n\\name{compartmental_models}\n\\alias{compartmental_models}\n\\alias{SIR_models}\n\\alias{sir}\n\\alias{sir2}\n\\title{Compartmental epidemiological models}\n\\usage{\nsir(\n  gamma = 26,\n  mu = 0.02,\n  iota = 0.01,\n  beta1 = 400,\n  beta2 = 480,\n  beta3 = 320,\n  beta_sd = 0.001,\n  rho = 0.6,\n  k = 0.1,\n  pop = 2100000,\n  S_0 = 26/400,\n  I_0 = 0.001,\n  R_0 = 1 - S_0 - I_0,\n  t0 = 0,\n  times = seq(from = t0 + 1/52, to = t0 + 4, by = 1/52),\n  seed = 329343545,\n  delta.t = 1/52/20\n)\n\nsir2(\n  gamma = 24,\n  mu = 1/70,\n  iota = 0.1,\n  beta1 = 330,\n  beta2 = 410,\n  beta3 = 490,\n  rho = 0.1,\n  k = 0.1,\n  pop = 1e+06,\n  S_0 = 0.05,\n  I_0 = 1e-04,\n  R_0 = 1 - S_0 - I_0,\n  t0 = 0,\n  times = seq(from = t0 + 1/12, to = t0 + 10, by = 1/12),\n  seed = 1772464524\n)\n}\n\\arguments{\n\\item{gamma}{recovery rate}\n\n\\item{mu}{death rate (assumed equal to the birth rate)}\n\n\\item{iota}{infection import rate}\n\n\\item{beta1, beta2, beta3}{seasonal contact rates}\n\n\\item{beta_sd}{environmental noise intensity}\n\n\\item{rho}{reporting efficiency}\n\n\\item{k}{reporting overdispersion parameter (reciprocal of the negative-binomial \\emph{size} parameter)}\n\n\\item{pop}{overall host population size}\n\n\\item{S_0, I_0, R_0}{the fractions of the host population that are susceptible, infectious, and recovered, respectively, at time zero.}\n\n\\item{t0}{zero time}\n\n\\item{times}{observation times}\n\n\\item{seed}{seed of the random number generator}\n\n\\item{delta.t}{Euler step size}\n}\n\\value{\nThese functions return \\sQuote{pomp} objects containing simulated data.\n}\n\\description{\nSimple SIR-type models implemented in various ways.\n}\n\\details{\n\\code{sir()} producees a \\sQuote{pomp} object encoding a simple seasonal SIR model with simulated data.\nSimulation is performed using an Euler multinomial approximation.\n\n\\code{sir2()} has the same model implemented using Gillespie's algorithm.\n\nIn both cases the measurement model is negative binomial:\n\\code{reports} is distributed as a negative binomial random variable with mean equal to \\code{rho*cases} and size equal to \\code{1/k}.\n\nThis and similar examples are discussed and constructed in tutorials\navailable on the \\href{https://kingaa.github.io/pomp/}{package website}.\n}\n\\examples{\n\\donttest{\n  po <- sir()\n  plot(po)\n  coef(po)\n  \n  po <- sir2()\n  plot(po)\n  plot(simulate(window(po,end=3)))\n  coef(po)\n  \n  po |> as.data.frame() |> head()\n}\n}\n\\seealso{\nMore examples provided with \\pkg{pomp}:\n\\code{\\link{blowflies}},\n\\code{\\link{childhood_disease_data}},\n\\code{\\link{dacca}()},\n\\code{\\link{ebola}},\n\\code{\\link{gompertz}()},\n\\code{\\link{ou2}()},\n\\code{\\link{pomp_examples}},\n\\code{\\link{ricker}()},\n\\code{\\link{rw2}()},\n\\code{\\link{verhulst}()}\n}\n\\concept{pomp examples}\n\\keyword{models}\n"
  },
  {
    "path": "man/skeleton.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/workhorses.R\n\\docType{methods}\n\\name{skeleton}\n\\alias{skeleton}\n\\alias{skeleton,ANY-method}\n\\alias{skeleton,missing-method}\n\\alias{skeleton,pomp-method}\n\\title{skeleton workhorse}\n\\usage{\n\\S4method{skeleton}{pomp}(\n  object,\n  ...,\n  x = states(object),\n  times = time(object),\n  params = coef(object)\n)\n}\n\\arguments{\n\\item{object}{an object of class \\sQuote{pomp}, or of a class that extends \\sQuote{pomp}.\nThis will typically be the output of \\code{pomp}, \\code{simulate}, or one of the \\pkg{pomp} inference algorithms.}\n\n\\item{...}{additional arguments are ignored.}\n\n\\item{x}{an array containing states of the unobserved process.\nThe dimensions of \\code{x} are \\code{nvars} x \\code{nrep} x \\code{ntimes},\nwhere \\code{nvars} is the number of state variables,\n\\code{nrep} is the number of replicates,\nand \\code{ntimes} is the length of \\code{times}.\nOne can also pass \\code{x} as a named numeric vector, which is equivalent to the \\code{nrep=1}, \\code{ntimes=1} case.}\n\n\\item{times}{a numeric vector (length \\code{ntimes}) containing times.\nThese must be in non-decreasing order.}\n\n\\item{params}{a \\code{npar} x \\code{nrep} matrix of parameters.\nEach column is treated as an independent parameter set, in correspondence with the corresponding column of \\code{x}.}\n}\n\\value{\n\\code{skeleton} returns an array of dimensions \\code{nvar} x \\code{nrep} x \\code{ntimes}.\nIf \\code{f} is the returned matrix, \\code{f[i,j,k]} is the i-th component of the deterministic skeleton at time \\code{times[k]} given the state \\code{x[,j,k]} and parameters \\code{params[,j]}.\n}\n\\description{\nEvaluates the deterministic skeleton at a point or points in state space, given parameters.\nIn the case of a discrete-time system, the skeleton is a map.\nIn the case of a continuous-time system, the skeleton is a vectorfield.\nNB: \\code{skeleton} just evaluates the deterministic skeleton;\nit does not iterate or integrate (see \\code{\\link{flow}} and \\code{\\link{trajectory}} for this).\n}\n\\seealso{\nSpecification of the deterministic skeleton: \\link{skeleton_spec}\n\nMore on \\pkg{pomp} workhorse functions:\n\\code{\\link{dinit}()},\n\\code{\\link{dmeasure}()},\n\\code{\\link{dprior}()},\n\\code{\\link{dprocess}()},\n\\code{\\link{emeasure}()},\n\\code{\\link{flow}()},\n\\code{\\link{partrans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{rinit}()},\n\\code{\\link{rmeasure}()},\n\\code{\\link{rprior}()},\n\\code{\\link{rprocess}()},\n\\code{\\link{vmeasure}()},\n\\code{\\link{workhorses}}\n\nMore on methods for deterministic process models:\n\\code{\\link{flow}()},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{traj_match}},\n\\code{\\link{trajectory}()}\n}\n\\concept{deterministic methods}\n\\concept{extending the pomp package}\n\\concept{low-level interface}\n\\concept{pomp workhorses}\n"
  },
  {
    "path": "man/skeleton_spec.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/skeleton_spec.R\n\\docType{methods}\n\\name{skeleton_spec}\n\\alias{skeleton_spec}\n\\alias{vectorfield}\n\\alias{map}\n\\title{skeleton specification}\n\\usage{\nvectorfield(f)\n\nmap(f, delta.t = 1)\n}\n\\arguments{\n\\item{f}{procedure for evaluating the deterministic skeleton\nThis can be a C snippet, an \\R function, or the name of a native routine in a dynamically linked library.}\n\n\\item{delta.t}{positive numerical value; the size of the discrete time step corresponding to an application of the map}\n}\n\\description{\nSpecification of the deterministic skeleton.\n}\n\\details{\nThe skeleton is a dynamical system that expresses the central tendency of the unobserved Markov state process.\nAs such, it is not uniquely defined, but can be both interesting in itself and useful in practice.\nIn \\pkg{pomp}, the skeleton is used by \\code{\\link{trajectory}} and \\code{\\link{traj_objfun}}.\n\nIf the state process is a discrete-time stochastic process, then the skeleton is a discrete-time map.\nTo specify it, provide \\preformatted{\n  skeleton = map(f, delta.t)}\nto \\code{pomp}, where \\code{f} implements the map and \\code{delta.t} is the size of the timestep covered at one map iteration.\n\nIf the state process is a continuous-time stochastic process, then the skeleton is a vectorfield (i.e., a system of ordinary differential equations).\nTo specify it, supply \\preformatted{\n  skeleton = vectorfield(f)}\nto \\code{pomp}, where \\code{f} implements the vectorfield, i.e., the right-hand-size of the differential equations.\n\nIn either case, \\code{f} can be furnished either as a C snippet (the preferred choice), or an \\R function.\n\\link[=Csnippet]{General rules for writing C snippets can be found here}.\nIn writing a \\code{skeleton} C snippet, be aware that:\n\\enumerate{\n  \\item For each state variable, there is a corresponding component of the deterministic skeleton.\n  The goal of such a snippet is to compute all the components.\n  \\item When the skeleton is a map, the component corresponding to state variable \\code{x} is named \\code{Dx} and is the new value of \\code{x} after one iteration of the map.\n  \\item When the skeleton is a vectorfield, the component corresponding to state variable \\code{x} is named \\code{Dx} and is the value of \\eqn{dx/dt}.\n  \\item As with the other C snippets, all states, parameters and covariates, as well as the current time, \\code{t}, will be defined in the context within which the snippet is executed.\n  \\item \\bold{NB:} When the skeleton is a map, the duration of the timestep will \\bold{not} be defined in the context within which the snippet is executed.\n  When the skeleton is a vectorfield, of course, no timestep is defined.\n  In this regard, C snippets for the skeleton and rprocess components differ.\n}\nThe tutorials on the \\href{https://kingaa.github.io/pomp/}{package website} give some examples.\n\nIf \\code{f} is an \\R function, its arguments should be taken from among the state variables, parameters, covariates, and time.\nIt must also take the argument \\sQuote{\\code{...}}.\nAs with the other basic components, \\code{f} may take additional arguments, provided these are passed along with it in the call to \\code{pomp}.\nThe function \\code{f} must return a numeric vector of the same length as the number of state variables, which contains the value of the map or vectorfield at the required point and time.\n}\n\\section{Masking of \\code{map}}{\n\nOther packages (most notably the \\pkg{tidyverse} package \\pkg{purrr}) have functions named \\sQuote{map}.\nBeware that, if you load one of these packages after you load \\pkg{pomp}, the \\pkg{pomp} function \\code{map} described here will be masked.\nYou can always access the \\pkg{pomp} function by calling \\code{pomp::map}.\n}\n\n\\section{Default behavior}{\n\nThe default \\code{skeleton} is undefined.\nIt will yield missing values (\\code{NA}) for all state variables.\n}\n\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\examples{\n\\donttest{\n  ## Starting with an existing pomp object,\n  ## e.g., the continuous-time Verhulst-Pearl model,\n\n  verhulst() -> po\n  \n  ## we add or change the deterministic skeleton\n  ## using the 'skeleton' argument in any 'pomp'\n  ## elementary or estimation function\n  ## (or in the 'pomp' constructor itself).\n  ## Here, we pass the skeleton specification\n  ## to 'trajectory' as an R function.\n  ## Since this is a continuous-time POMP, the\n  ## skeleton is a vectorfield.\n\n  po |>\n    trajectory(\n      skeleton=vectorfield(\n        function(r, K, n, ...) {\n          c(n=r*n*(1-n/K))\n        }\n      ),\n      format=\"data.frame\"\n    ) -> traj\n\n  ## We can also pass it as a C snippet:\n\n  po |>\n    traj_objfun(\n      skeleton=vectorfield(Csnippet(\"Dn=r*n*(1-n/K);\")),\n      paramnames=c(\"r\",\"K\"),\n      statenames=\"n\"\n    ) -> ofun\n\n  ofun()\n\n  ## For a discrete-time POMP, the deterministic skeleton\n  ## is a map.  For example,\n\n  gompertz() -> po\n\n  po |>\n    traj_objfun(\n      skeleton=map(\n        Csnippet(\"\n          double dt = 1.0;\n          double s = exp(-r*dt);\n          DX = pow(K,(1-s))*pow(X,s);\"\n        ), delta.t=1\n      ),\n      paramnames=c(\"r\",\"K\"),\n      statenames=c(\"X\")\n    ) -> ofun\n\n  ofun()\n\n}\n}\n\\seealso{\n\\code{\\link{skeleton}}\n\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{accumvars}},\n\\code{\\link{basic_components}},\n\\code{\\link{betabinomial}},\n\\code{\\link{covariates}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{userdata}},\n\\code{\\link{vmeasure_spec}}\n\nMore on methods for deterministic process models:\n\\code{\\link{flow}()},\n\\code{\\link{skeleton}()},\n\\code{\\link{traj_match}},\n\\code{\\link{trajectory}()}\n}\n\\concept{deterministic methods}\n\\concept{implementation information}\n"
  },
  {
    "path": "man/spect.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/spect.R, R/spect_match.R, R/objfun.R\n\\docType{methods}\n\\name{spect}\n\\alias{spect}\n\\alias{spect,missing-method}\n\\alias{spect,ANY-method}\n\\alias{spect,data.frame-method}\n\\alias{spect,pomp-method}\n\\alias{spect,spectd_pomp-method}\n\\alias{spect,spect_match_objfun-method}\n\\alias{spect,objfun-method}\n\\title{Power spectrum}\n\\usage{\n\\S4method{spect}{data.frame}(\n  data,\n  ...,\n  vars,\n  kernel.width,\n  nsim,\n  seed = NULL,\n  transform.data = identity,\n  detrend = c(\"none\", \"mean\", \"linear\", \"quadratic\"),\n  params,\n  rinit,\n  rprocess,\n  rmeasure,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{spect}{pomp}(\n  data,\n  ...,\n  vars,\n  kernel.width,\n  nsim,\n  seed = NULL,\n  transform.data = identity,\n  detrend = c(\"none\", \"mean\", \"linear\", \"quadratic\"),\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{spect}{spectd_pomp}(\n  data,\n  ...,\n  vars,\n  kernel.width,\n  nsim,\n  seed = NULL,\n  transform.data,\n  detrend,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{spect}{spect_match_objfun}(data, ..., seed, verbose = getOption(\"verbose\", FALSE))\n\n\\S4method{spect}{objfun}(data, ..., seed = NULL)\n}\n\\arguments{\n\\item{data}{either a data frame holding the time series data,\nor an object of class \\sQuote{pomp},\ni.e., the output of another \\pkg{pomp} calculation.\nInternally, \\code{data} will be coerced to an array with storage-mode \\code{double}.}\n\n\\item{...}{additional arguments are passed to \\code{\\link{pomp}}.\nThis allows one to set, unset, or modify \\link[=basic_components]{basic model components} within a call to this function.}\n\n\\item{vars}{optional; names of observed variables for which the power spectrum will be computed.\nBy default, the spectrum will be computed for all observables.}\n\n\\item{kernel.width}{width parameter for the smoothing kernel used for\ncalculating the estimate of the spectrum.}\n\n\\item{nsim}{number of model simulations to be computed.}\n\n\\item{seed}{optional; if non-\\code{NULL}, the random number generator will\nbe initialized with this seed for simulations.\nSee \\code{\\link{simulate}}.}\n\n\\item{transform.data}{function; this transformation will be applied to the\nobservables prior to estimation of the spectrum, and prior to any\ndetrending.}\n\n\\item{detrend}{de-trending operation to perform.  Options include no\ndetrending, and subtraction of constant, linear, and quadratic trends from\nthe data.  Detrending is applied to each data series and to each model\nsimulation independently.}\n\n\\item{params}{optional; named numeric vector of parameters.\nThis will be coerced internally to storage mode \\code{double}.}\n\n\\item{rinit}{simulator of the initial-state distribution.\nThis can be furnished either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rinit=NULL} sets the initial-state simulator to its default.\nFor more information, see \\link[=rinit_spec]{rinit specification}.}\n\n\\item{rprocess}{simulator of the latent state process, specified using one of the \\link[=rprocess_spec]{rprocess plugins}.\nSetting \\code{rprocess=NULL} removes the latent-state simulator.\nFor more information, see \\link[=rprocess_spec]{rprocess specification for the documentation on these plugins}.}\n\n\\item{rmeasure}{simulator of the measurement model, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rmeasure=NULL} removes the measurement model simulator.\nFor more information, see \\link[=rmeasure_spec]{rmeasure specification}.}\n\n\\item{verbose}{logical; if \\code{TRUE}, diagnostic messages will be printed to the console.}\n}\n\\value{\nAn object of class \\sQuote{spectd_pomp}, which contains the model, the data, and the results of the \\code{spect} computation.\nThe following methods are available:\n\\describe{\n\\item{plot}{produces some diagnostic plots}\n\\item{summary}{displays a summary}\n\\item{logLik}{gives a measure of the agreement of the power spectra}\n}\n}\n\\description{\nPower spectrum computation and spectrum-matching for partially-observed\nMarkov processes.\n}\n\\details{\n\\code{spect} estimates the power spectrum of time series data and model\nsimulations and compares the results.  It can be used to diagnose goodness\nof fit and/or as the basis for frequency-domain parameter estimation\n(\\code{spect.match}).\n\nA call to \\code{spect} results in the estimation of the power spectrum for\nthe (transformed, detrended) data and \\code{nsim} model simulations.  The\nresults of these computations are stored in an object of class\n\\sQuote{spectd_pomp}.\n\nWhen \\code{spect} operates on a spectrum-matching objective function (a \\sQuote{spect_match_objfun} object), by default, the\nrandom-number generator seed is fixed at the value given when the objective function was constructed.\nSpecifying \\code{NULL} or an integer for \\code{seed} overrides this behavior.\n}\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\references{\n\\Reuman2006\n\n\\Reuman2008\n}\n\\seealso{\nMore on methods based on summary statistics:\n\\code{\\link{abc}()},\n\\code{\\link{basic_probes}},\n\\code{\\link{nlf}},\n\\code{\\link{probe}()},\n\\code{\\link{probe_match}},\n\\code{\\link{spect_match}}\n\nMore on \\pkg{pomp} elementary algorithms:\n\\code{\\link{elementary_algorithms}},\n\\code{\\link{kalman}},\n\\code{\\link{pfilter}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{probe}()},\n\\code{\\link{simulate}()},\n\\code{\\link{trajectory}()},\n\\code{\\link{wpfilter}()}\n}\n\\author{\nDaniel C. Reuman, Cai GoGwilt, Aaron A. King\n}\n\\concept{elementary algorithms}\n\\concept{summary statistic-based methods}\n"
  },
  {
    "path": "man/spect_match.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/spect_match.R\n\\docType{methods}\n\\name{spect_match}\n\\alias{spect_match}\n\\alias{spect_objfun}\n\\alias{spect_objfun,missing-method}\n\\alias{spect_objfun,ANY-method}\n\\alias{spect_objfun,data.frame-method}\n\\alias{spect_objfun,pomp-method}\n\\alias{spect_objfun,spectd_pomp-method}\n\\alias{spect_objfun,spect_match_objfun-method}\n\\title{Spectrum matching}\n\\usage{\n\\S4method{spect_objfun}{data.frame}(\n  data,\n  ...,\n  est = character(0),\n  weights = 1,\n  fail.value = NA,\n  vars,\n  kernel.width,\n  nsim,\n  seed = NULL,\n  transform.data = identity,\n  detrend = c(\"none\", \"mean\", \"linear\", \"quadratic\"),\n  params,\n  rinit,\n  rprocess,\n  rmeasure,\n  partrans,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{spect_objfun}{pomp}(\n  data,\n  ...,\n  est = character(0),\n  weights = 1,\n  fail.value = NA,\n  vars,\n  kernel.width,\n  nsim,\n  seed = NULL,\n  transform.data = identity,\n  detrend = c(\"none\", \"mean\", \"linear\", \"quadratic\"),\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{spect_objfun}{spectd_pomp}(\n  data,\n  ...,\n  est = character(0),\n  weights = 1,\n  fail.value = NA,\n  vars,\n  kernel.width,\n  nsim,\n  seed = NULL,\n  transform.data = identity,\n  detrend,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{spect_objfun}{spect_match_objfun}(\n  data,\n  ...,\n  est,\n  weights,\n  fail.value,\n  seed = NULL,\n  verbose = getOption(\"verbose\", FALSE)\n)\n}\n\\arguments{\n\\item{data}{either a data frame holding the time series data,\nor an object of class \\sQuote{pomp},\ni.e., the output of another \\pkg{pomp} calculation.\nInternally, \\code{data} will be coerced to an array with storage-mode \\code{double}.}\n\n\\item{...}{additional arguments are passed to \\code{\\link{pomp}}.\nThis allows one to set, unset, or modify \\link[=basic_components]{basic model components} within a call to this function.}\n\n\\item{est}{character vector; the names of parameters to be estimated.}\n\n\\item{weights}{optional numeric or function.\nThe mismatch between model and data is measured by a weighted average of mismatch at each frequency.\nBy default, all frequencies are weighted equally.\n\\code{weights} can be specified either as a vector (which must have length equal to the number of frequencies) or as a function of frequency.\nIf the latter, \\code{weights(freq)} must return a nonnegative weight for each frequency.}\n\n\\item{fail.value}{optional numeric scalar;\nif non-\\code{NA}, this value is substituted for non-finite values of the objective function.\nIt should be a large number (i.e., bigger than any legitimate values the objective function is likely to take).}\n\n\\item{vars}{optional; names of observed variables for which the power spectrum will be computed.\nBy default, the spectrum will be computed for all observables.}\n\n\\item{kernel.width}{width parameter for the smoothing kernel used for\ncalculating the estimate of the spectrum.}\n\n\\item{nsim}{the number of model simulations to be computed.}\n\n\\item{seed}{integer.\nWhen fitting, it is often best to fix the seed of the random-number generator (RNG).\nThis is accomplished by setting \\code{seed} to an integer.\nBy default, \\code{seed = NULL}, which does not alter the RNG state.}\n\n\\item{transform.data}{function; this transformation will be applied to the\nobservables prior to estimation of the spectrum, and prior to any\ndetrending.}\n\n\\item{detrend}{de-trending operation to perform.  Options include no\ndetrending, and subtraction of constant, linear, and quadratic trends from\nthe data.  Detrending is applied to each data series and to each model\nsimulation independently.}\n\n\\item{params}{optional; named numeric vector of parameters.\nThis will be coerced internally to storage mode \\code{double}.}\n\n\\item{rinit}{simulator of the initial-state distribution.\nThis can be furnished either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rinit=NULL} sets the initial-state simulator to its default.\nFor more information, see \\link[=rinit_spec]{rinit specification}.}\n\n\\item{rprocess}{simulator of the latent state process, specified using one of the \\link[=rprocess_spec]{rprocess plugins}.\nSetting \\code{rprocess=NULL} removes the latent-state simulator.\nFor more information, see \\link[=rprocess_spec]{rprocess specification for the documentation on these plugins}.}\n\n\\item{rmeasure}{simulator of the measurement model, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rmeasure=NULL} removes the measurement model simulator.\nFor more information, see \\link[=rmeasure_spec]{rmeasure specification}.}\n\n\\item{partrans}{optional parameter transformations, constructed using \\code{\\link{parameter_trans}}.\n\nMany algorithms for parameter estimation search an unconstrained space of parameters.\nWhen working with such an algorithm and a model for which the parameters are constrained, it can be useful to transform parameters.\nOne should supply the \\code{partrans} argument via a call to \\code{\\link{parameter_trans}}.\nFor more information, see \\link[=parameter_trans]{parameter_trans}.\nSetting \\code{partrans=NULL} removes the parameter transformations, i.e., sets them to the identity transformation.}\n\n\\item{verbose}{logical; if \\code{TRUE}, diagnostic messages will be printed to the console.}\n}\n\\value{\n\\code{spect_objfun} constructs a stateful objective function for spectrum matching.\nSpecifically, \\code{spect_objfun} returns an object of class \\sQuote{spect_match_objfun}, which is a function suitable for use in an \\code{\\link[stats]{optim}}-like optimizer.\nThis function takes a single numeric-vector argument that is assumed to contain the parameters named in \\code{est}, in that order.\nWhen called, it will return the (optionally weighted) \\eqn{L^2}{L2} distance between the data spectrum and simulated spectra.\nIt is a stateful function:\nEach time it is called, it will remember the values of the parameters and the discrepancy measure.\n}\n\\description{\nEstimation of parameters by matching power spectra\n}\n\\details{\nIn spectrum matching, one attempts to minimize the discrepancy between a \\acronym{POMP} model's predictions and data, as measured in the frequency domain by the power spectrum.\n\n\\code{spect_objfun} constructs an objective function that measures the discrepancy.\nIt can be passed to any one of a variety of numerical optimization routines, which will adjust model parameters to minimize the discrepancies between the power spectrum of model simulations and that of the data.\n}\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\section{Important Note}{\n\nSince \\pkg{pomp} cannot guarantee that the \\emph{final} call an optimizer makes to the function is a call \\emph{at} the optimum, it cannot guarantee that the parameters stored in the function are the optimal ones.\nTherefore, it is a good idea to evaluate the function on the parameters returned by the optimization routine, which will ensure that these parameters are stored.\n}\n\n\\section{Warning! Objective functions based on C snippets}{\n\nIf you use C snippets (see \\code{\\link{Csnippet}}), a dynamically loadable library will be built.\nAs a rule, \\pkg{pomp} functions load this library as needed and unload it when it is no longer needed.\nThe stateful objective functions are an exception to this rule.\nFor efficiency, calls to the objective function do not execute \\code{\\link{pompLoad}} or \\code{\\link{pompUnload}}:\nrather, it is assumed that \\code{\\link{pompLoad}} has been called before any call to the objective function.\nWhen a stateful objective function using one or more C snippets is created, \\code{\\link{pompLoad}} is called internally to build and load the library:\ntherefore, within a single \\R session, if one creates a stateful objective function, one can freely call that objective function and (more to the point) pass it to an optimizer that calls it freely, without needing to call \\code{\\link{pompLoad}}.\nOn the other hand, if one retrieves a stored objective function from a file, or passes one to another \\R session, one must call \\code{\\link{pompLoad}} before using it.\n\\strong{Failure to do this will typically result in a segmentation fault (i.e., it will crash the \\R session).}\n}\n\n\\examples{\n\\donttest{\n\n  ricker() |>\n    spect_objfun(\n      est=c(\"r\",\"sigma\",\"N_0\"),\n      partrans=parameter_trans(log=c(\"r\",\"sigma\",\"N_0\")),\n      paramnames=c(\"r\",\"sigma\",\"N_0\"),\n      kernel.width=3,\n      nsim=100,\n      seed=5069977\n    ) -> f\n\n  f(log(c(20,0.3,10)))\n  f |> spect() |> plot()\n\n  if (require(subplex)) {\n    subplex(fn=f,par=log(c(20,0.3,10)),control=list(reltol=1e-5)) -> out\n  } else {\n    optim(fn=f,par=log(c(20,0.3,10)),control=list(reltol=1e-5)) -> out\n  }\n  f(out$par)\n\n  f |> summary()\n\n  f |> spect() |> plot()\n\n}\n}\n\\references{\n\\Reuman2006\n\n\\Reuman2008\n}\n\\seealso{\n\\code{\\link{spect}} \\code{\\link[stats]{optim}}\n\\code{\\link[subplex]{subplex}} \\code{\\link[nloptr]{nloptr}}\n\nMore on \\pkg{pomp} estimation algorithms:\n\\code{\\link{abc}()},\n\\code{\\link{bsmc2}()},\n\\code{\\link{estimation_algorithms}},\n\\code{\\link{mif2}()},\n\\code{\\link{nlf}},\n\\code{\\link{pmcmc}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{probe_match}}\n\nMore on methods based on summary statistics:\n\\code{\\link{abc}()},\n\\code{\\link{basic_probes}},\n\\code{\\link{nlf}},\n\\code{\\link{probe}()},\n\\code{\\link{probe_match}},\n\\code{\\link{spect}()}\n\nMore on maximization-based estimation methods:\n\\code{\\link{mif2}()},\n\\code{\\link{nlf}},\n\\code{\\link{probe_match}},\n\\code{\\link{traj_match}}\n}\n\\concept{estimation methods}\n\\concept{methods based on maximization}\n\\concept{power-spectrum matching}\n\\concept{summary statistic-based methods}\n"
  },
  {
    "path": "man/spy.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/spy.R\n\\name{spy}\n\\alias{spy}\n\\alias{spy,missing-method}\n\\alias{spy,ANY-method}\n\\alias{spy,pomp-method}\n\\title{Spy}\n\\usage{\n\\S4method{spy}{pomp}(object)\n}\n\\arguments{\n\\item{object}{the object whose structure we wish to examine}\n}\n\\description{\nPeek into the inside of one of \\pkg{pomp}'s objects.\n}\n\\examples{\n\\donttest{\n\n  ricker() |> spy()\n\n  sir() |> spy()\n\n  sir2() |> spy()\n\n}\n}\n\\seealso{\nCsnippet\n\nOther extraction methods: \n\\code{\\link{coef}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{covmat}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{forecast}()},\n\\code{\\link{logLik}},\n\\code{\\link{obs}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{states}()},\n\\code{\\link{summary}()},\n\\code{\\link{time}()},\n\\code{\\link{timezero}()},\n\\code{\\link{traces}()}\n}\n\\concept{extraction methods}\n"
  },
  {
    "path": "man/states.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/states.R\n\\docType{methods}\n\\name{states}\n\\alias{states}\n\\alias{states,ANY-method}\n\\alias{states,missing-method}\n\\alias{states,pomp-method}\n\\alias{states,listie-method}\n\\title{Latent states}\n\\usage{\n\\S4method{states}{pomp}(object, vars, ..., format = c(\"array\", \"data.frame\"))\n\n\\S4method{states}{listie}(object, vars, ..., format = c(\"array\", \"data.frame\"))\n}\n\\arguments{\n\\item{object}{an object of class \\sQuote{pomp}, or of a class extending \\sQuote{pomp}}\n\n\\item{vars}{names of variables to retrieve}\n\n\\item{...}{ignored}\n\n\\item{format}{format of the returned object}\n}\n\\description{\nExtract the latent states from a \\sQuote{pomp} object.\n}\n\\seealso{\nOther extraction methods: \n\\code{\\link{coef}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{covmat}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{forecast}()},\n\\code{\\link{logLik}},\n\\code{\\link{obs}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{spy}()},\n\\code{\\link{summary}()},\n\\code{\\link{time}()},\n\\code{\\link{timezero}()},\n\\code{\\link{traces}()}\n}\n\\concept{extraction methods}\n"
  },
  {
    "path": "man/summary.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/summary.R, R/probe.R, R/spect.R, R/objfun.R\n\\name{summary}\n\\alias{summary}\n\\alias{summary,probed_pomp-method}\n\\alias{summary,spectd_pomp-method}\n\\alias{summary,objfun-method}\n\\title{Summary methods}\n\\usage{\n\\S4method{summary}{probed_pomp}(object, ...)\n\n\\S4method{summary}{spectd_pomp}(object, ...)\n\n\\S4method{summary}{objfun}(object, ...)\n}\n\\arguments{\n\\item{object}{a fitted model object}\n\n\\item{\\dots}{ignored or passed to the more primitive function}\n}\n\\description{\nDisplay a summary of a fitted model object.\n}\n\\seealso{\nOther extraction methods: \n\\code{\\link{coef}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{covmat}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{forecast}()},\n\\code{\\link{logLik}},\n\\code{\\link{obs}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{spy}()},\n\\code{\\link{states}()},\n\\code{\\link{time}()},\n\\code{\\link{timezero}()},\n\\code{\\link{traces}()}\n}\n\\concept{extraction methods}\n"
  },
  {
    "path": "man/time.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/time.R\n\\name{time}\n\\alias{time}\n\\alias{time<-}\n\\alias{time,missing-method}\n\\alias{time,pomp-method}\n\\alias{time<-,pomp-method}\n\\alias{time,listie-method}\n\\title{Methods to extract and manipulate the obseration times}\n\\usage{\n\\S4method{time}{pomp}(x, t0 = FALSE, ...)\n\n\\S4method{time}{pomp}(object, t0 = FALSE, ...) <- value\n\n\\S4method{time}{listie}(x, t0 = FALSE, ...)\n}\n\\arguments{\n\\item{x}{a \\sQuote{pomp} object}\n\n\\item{t0}{logical; should the zero time be included?}\n\n\\item{...}{ignored or passed to the more primitive function}\n\n\\item{object}{a \\sQuote{pomp} object}\n\n\\item{value}{numeric vector; the new vector of times}\n}\n\\description{\nGet and set the vector of observation times.\n}\n\\details{\n\\code{time(object)} returns the vector of observation times.\n\\code{time(object,t0=TRUE)} returns the vector of observation\ntimes with the zero-time \\code{t0} prepended.\n\n\\code{time(object) <- value} replaces the observation times slot (\\code{times}) of \\code{object} with \\code{value}.\n\\code{time(object,t0=TRUE) <- value} has the same effect, but the first element in \\code{value} is taken to be the initial time.\nThe second and subsequent elements of \\code{value} are taken to be the observation times.\nThose data and states (if they exist) corresponding to the new times are retained.\n}\n\\seealso{\nOther extraction methods: \n\\code{\\link{coef}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{covmat}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{forecast}()},\n\\code{\\link{logLik}},\n\\code{\\link{obs}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{spy}()},\n\\code{\\link{states}()},\n\\code{\\link{summary}()},\n\\code{\\link{timezero}()},\n\\code{\\link{traces}()}\n}\n\\concept{extraction methods}\n"
  },
  {
    "path": "man/timezero.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/timezero.R\n\\docType{methods}\n\\name{timezero}\n\\alias{timezero}\n\\alias{timezero<-}\n\\alias{timezero,missing-method}\n\\alias{timezero,ANY-method}\n\\alias{timezero<-,missing-method}\n\\alias{timezero<-,ANY-method}\n\\alias{timezero,pomp-method}\n\\alias{timezero<-,pomp-method}\n\\title{The zero time}\n\\usage{\n\\S4method{timezero}{pomp}(object, ...)\n\n\\S4method{timezero}{pomp}(object, ...) <- value\n}\n\\arguments{\n\\item{object}{an object of class \\sQuote{pomp}, or of a class that extends \\sQuote{pomp}}\n\n\\item{\\dots}{ignored or passed to the more primitive function}\n\n\\item{value}{numeric; the new zero-time value}\n}\n\\value{\nthe value of the zero time\n}\n\\description{\nGet and set the zero-time.\n}\n\\seealso{\nOther extraction methods: \n\\code{\\link{coef}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{covmat}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{forecast}()},\n\\code{\\link{logLik}},\n\\code{\\link{obs}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{spy}()},\n\\code{\\link{states}()},\n\\code{\\link{summary}()},\n\\code{\\link{time}()},\n\\code{\\link{traces}()}\n}\n\\concept{extraction methods}\n"
  },
  {
    "path": "man/traces.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/traces.R\n\\name{traces}\n\\alias{traces}\n\\alias{traces,missing-method}\n\\alias{traces,ANY-method}\n\\alias{traces,mif2d_pomp-method}\n\\alias{traces,mif2List-method}\n\\alias{traces,abcd_pomp-method}\n\\alias{traces,abcList-method}\n\\alias{traces,pmcmcd_pomp-method}\n\\alias{traces,pmcmcList-method}\n\\title{Traces}\n\\usage{\n\\S4method{traces}{mif2d_pomp}(object, pars, transform = FALSE, ...)\n\n\\S4method{traces}{mif2List}(object, pars, ...)\n\n\\S4method{traces}{abcd_pomp}(object, pars, ...)\n\n\\S4method{traces}{abcList}(object, pars, ...)\n\n\\S4method{traces}{pmcmcd_pomp}(object, pars, ...)\n\n\\S4method{traces}{pmcmcList}(object, pars, ...)\n}\n\\arguments{\n\\item{object}{an object of class extending \\sQuote{pomp}, the result of the application of a parameter estimation algorithm}\n\n\\item{pars}{names of parameters}\n\n\\item{transform}{logical; should the traces be transformed back onto the natural scale?}\n\n\\item{\\dots}{ignored or passed to the more primitive function}\n}\n\\value{\nWhen \\code{object} is the result of a \\code{\\link{mif2}} calculation,\n\\code{traces(object, pars)} returns the traces of the parameters named in \\code{pars}.\nBy default, the traces of all parameters are returned.\nIf \\code{transform=TRUE}, the parameters are transformed from the natural scale to the estimation scale.\n\nWhen \\code{object} is a \\sQuote{abcd_pomp}, \\code{traces(object)}\nextracts the traces as a \\code{coda::mcmc}.\n\nWhen \\code{object} is a \\sQuote{abcList}, \\code{traces(object)}\nextracts the traces as a \\code{coda::mcmc.list}.\n\nWhen \\code{object} is a \\sQuote{pmcmcd_pomp}, \\code{traces(object)}\nextracts the traces as a \\code{coda::mcmc}.\n\nWhen \\code{object} is a \\sQuote{pmcmcList}, \\code{traces(object)}\nextracts the traces as a \\code{coda::mcmc.list}.\n}\n\\description{\nRetrieve the history of an iterative calculation.\n}\n\\details{\nNote that \\code{\\link{pmcmc}} does not currently support parameter transformations.\n}\n\\seealso{\nOther extraction methods: \n\\code{\\link{coef}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{covmat}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{forecast}()},\n\\code{\\link{logLik}},\n\\code{\\link{obs}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()},\n\\code{\\link{spy}()},\n\\code{\\link{states}()},\n\\code{\\link{summary}()},\n\\code{\\link{time}()},\n\\code{\\link{timezero}()}\n}\n\\concept{extraction methods}\n"
  },
  {
    "path": "man/traj_match.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/traj_match.R\n\\docType{methods}\n\\name{traj_match}\n\\alias{traj_match}\n\\alias{traj_objfun}\n\\alias{traj_objfun,missing-method}\n\\alias{traj_objfun,ANY-method}\n\\alias{traj_objfun,data.frame-method}\n\\alias{traj_objfun,pomp-method}\n\\alias{traj_objfun,traj_match_objfun-method}\n\\title{Trajectory matching}\n\\usage{\n\\S4method{traj_objfun}{data.frame}(\n  data,\n  ...,\n  est = character(0),\n  fail.value = NA,\n  ode_control = list(),\n  params,\n  rinit,\n  skeleton,\n  dmeasure,\n  partrans,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{traj_objfun}{pomp}(\n  data,\n  ...,\n  est = character(0),\n  fail.value = NA,\n  ode_control = list(),\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{traj_objfun}{traj_match_objfun}(\n  data,\n  ...,\n  est,\n  fail.value,\n  ode_control,\n  verbose = getOption(\"verbose\", FALSE)\n)\n}\n\\arguments{\n\\item{data}{either a data frame holding the time series data,\nor an object of class \\sQuote{pomp},\ni.e., the output of another \\pkg{pomp} calculation.\nInternally, \\code{data} will be coerced to an array with storage-mode \\code{double}.}\n\n\\item{\\dots}{additional arguments will modify the model structure}\n\n\\item{est}{character vector; the names of parameters to be estimated.}\n\n\\item{fail.value}{optional numeric scalar;\nif non-\\code{NA}, this value is substituted for non-finite values of the objective function.\nIt should be a large number (i.e., bigger than any legitimate values the objective function is likely to take).}\n\n\\item{ode_control}{optional list;\nthe elements of this list will be passed to \\code{\\link[deSolve]{ode}} if the skeleton is a vectorfield, and ignored if it is a map.}\n\n\\item{params}{optional; named numeric vector of parameters.\nThis will be coerced internally to storage mode \\code{double}.}\n\n\\item{rinit}{simulator of the initial-state distribution.\nThis can be furnished either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rinit=NULL} sets the initial-state simulator to its default.\nFor more information, see \\link[=rinit_spec]{rinit specification}.}\n\n\\item{skeleton}{optional; the deterministic skeleton of the unobserved state process.\nDepending on whether the model operates in continuous or discrete time, this is either a vectorfield or a map.\nAccordingly, this is supplied using either the \\code{\\link[=skeleton_spec]{vectorfield}} or \\code{\\link[=skeleton_spec]{map}} fnctions.\nFor more information, see \\link[=skeleton_spec]{skeleton specification}.\nSetting \\code{skeleton=NULL} removes the deterministic skeleton.}\n\n\\item{dmeasure}{evaluator of the measurement model density, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{dmeasure=NULL} removes the measurement density evaluator.\nFor more information, see \\link[=dmeasure_spec]{dmeasure specification}.}\n\n\\item{partrans}{optional parameter transformations, constructed using \\code{\\link{parameter_trans}}.\n\nMany algorithms for parameter estimation search an unconstrained space of parameters.\nWhen working with such an algorithm and a model for which the parameters are constrained, it can be useful to transform parameters.\nOne should supply the \\code{partrans} argument via a call to \\code{\\link{parameter_trans}}.\nFor more information, see \\link[=parameter_trans]{parameter_trans}.\nSetting \\code{partrans=NULL} removes the parameter transformations, i.e., sets them to the identity transformation.}\n\n\\item{verbose}{logical; if \\code{TRUE}, diagnostic messages will be printed to the console.}\n}\n\\value{\n\\code{traj_objfun} constructs a stateful objective function for spectrum matching.\nSpecifically, \\code{traj_objfun} returns an object of class \\sQuote{traj_match_objfun}, which is a function suitable for use in an \\code{\\link[stats]{optim}}-like optimizer.\nIn particular, this function takes a single numeric-vector argument that is assumed to contain the parameters named in \\code{est}, in that order.\nWhen called, it will return the negative log likelihood.\nIt is a stateful function:\nEach time it is called, it will remember the values of the parameters and its estimate of the log likelihood.\n}\n\\description{\nEstimation of parameters for deterministic \\acronym{POMP} models via trajectory matching.\n}\n\\details{\nIn trajectory matching, one attempts to minimize the discrepancy between a \\acronym{POMP} model's predictions and data under the assumption that the latent state process is deterministic and all discrepancies between model and data are due to measurement error.\nThe measurement model likelihood (\\code{dmeasure}), or rather its negative, is the natural measure of the discrepancy.\n\nTrajectory matching is a generalization of the traditional nonlinear least squares approach.\nIn particular, if, on some scale, measurement errors are normal with constant variance, then trajectory matching is equivalent to least squares on that particular scale.\n\n\\code{traj_objfun} constructs an objective function that evaluates the likelihood function.\nIt can be passed to any one of a variety of numerical optimization routines, which will adjust model parameters to minimize the discrepancies between the power spectrum of model simulations and that of the data.\n}\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\section{Important Note}{\n\nSince \\pkg{pomp} cannot guarantee that the \\emph{final} call an optimizer makes to the function is a call \\emph{at} the optimum, it cannot guarantee that the parameters stored in the function are the optimal ones.\nTherefore, it is a good idea to evaluate the function on the parameters returned by the optimization routine, which will ensure that these parameters are stored.\n}\n\n\\section{Warning! Objective functions based on C snippets}{\n\nIf you use C snippets (see \\code{\\link{Csnippet}}), a dynamically loadable library will be built.\nAs a rule, \\pkg{pomp} functions load this library as needed and unload it when it is no longer needed.\nThe stateful objective functions are an exception to this rule.\nFor efficiency, calls to the objective function do not execute \\code{\\link{pompLoad}} or \\code{\\link{pompUnload}}:\nrather, it is assumed that \\code{\\link{pompLoad}} has been called before any call to the objective function.\nWhen a stateful objective function using one or more C snippets is created, \\code{\\link{pompLoad}} is called internally to build and load the library:\ntherefore, within a single \\R session, if one creates a stateful objective function, one can freely call that objective function and (more to the point) pass it to an optimizer that calls it freely, without needing to call \\code{\\link{pompLoad}}.\nOn the other hand, if one retrieves a stored objective function from a file, or passes one to another \\R session, one must call \\code{\\link{pompLoad}} before using it.\n\\strong{Failure to do this will typically result in a segmentation fault (i.e., it will crash the \\R session).}\n}\n\n\\examples{\n\\donttest{\n\n  ricker() |>\n    traj_objfun(\n      est=c(\"r\",\"sigma\",\"N_0\"),\n      partrans=parameter_trans(log=c(\"r\",\"sigma\",\"N_0\")),\n      paramnames=c(\"r\",\"sigma\",\"N_0\")\n      ) -> f\n\n  f(log(c(20,0.3,10)))\n\n  if (require(subplex)) {\n    subplex(fn=f,par=log(c(20,0.3,10)),control=list(reltol=1e-5)) -> out\n  } else {\n    optim(fn=f,par=log(c(20,0.3,10)),control=list(reltol=1e-5)) -> out\n  }\n\n  f(out$par)\n\n  if (require(ggplot2)) {\n\n    f |>\n      trajectory(format=\"data.frame\") |>\n      ggplot(aes(x=time,y=N))+geom_line()+theme_bw()\n\n  }\n\n}\n}\n\\seealso{\n\\code{\\link[stats]{optim}}, \\code{\\link[subplex]{subplex}}, \\code{\\link[nloptr]{nloptr}}\n\nMore on methods for deterministic process models:\n\\code{\\link{flow}()},\n\\code{\\link{skeleton}()},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{trajectory}()}\n\nMore on maximization-based estimation methods:\n\\code{\\link{mif2}()},\n\\code{\\link{nlf}},\n\\code{\\link{probe_match}},\n\\code{\\link{spect_match}}\n}\n\\concept{deterministic methods}\n\\concept{methods based on maximization}\n\\concept{trajectory matching}\n"
  },
  {
    "path": "man/trajectory.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/trajectory.R, R/traj_match.R\n\\name{trajectory}\n\\alias{trajectory}\n\\alias{trajectory,missing-method}\n\\alias{trajectory,ANY-method}\n\\alias{trajectory,data.frame-method}\n\\alias{trajectory,pomp-method}\n\\alias{trajectory,traj_match_objfun-method}\n\\title{Trajectory of a deterministic model}\n\\usage{\n\\S4method{trajectory}{missing}(\n  ...,\n  t0,\n  times,\n  params,\n  skeleton,\n  rinit,\n  ode_control = list(),\n  format = c(\"pomps\", \"array\", \"data.frame\"),\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{trajectory}{data.frame}(\n  object,\n  ...,\n  t0,\n  times,\n  params,\n  skeleton,\n  rinit,\n  ode_control = list(),\n  format = c(\"pomps\", \"array\", \"data.frame\"),\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{trajectory}{pomp}(\n  object,\n  ...,\n  params,\n  skeleton,\n  rinit,\n  ode_control = list(),\n  format = c(\"pomps\", \"array\", \"data.frame\"),\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{trajectory}{traj_match_objfun}(object, ..., verbose = getOption(\"verbose\", FALSE))\n}\n\\arguments{\n\\item{...}{additional arguments are passed to \\code{\\link{pomp}}.}\n\n\\item{t0}{The zero-time, i.e., the time of the initial state.\nThis must be no later than the time of the first observation, i.e., \\code{t0 <= times[1]}.}\n\n\\item{times}{the sequence of observation times.\n\\code{times} must indicate the column of observation times by name or index.\nThe time vector must be numeric and non-decreasing.}\n\n\\item{params}{a named numeric vector or a matrix with rownames\ncontaining the parameters at which the simulations are to be performed.}\n\n\\item{skeleton}{optional; the deterministic skeleton of the unobserved state process.\nDepending on whether the model operates in continuous or discrete time, this is either a vectorfield or a map.\nAccordingly, this is supplied using either the \\code{\\link[=skeleton_spec]{vectorfield}} or \\code{\\link[=skeleton_spec]{map}} fnctions.\nFor more information, see \\link[=skeleton_spec]{skeleton specification}.\nSetting \\code{skeleton=NULL} removes the deterministic skeleton.}\n\n\\item{rinit}{simulator of the initial-state distribution.\nThis can be furnished either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rinit=NULL} sets the initial-state simulator to its default.\nFor more information, see \\link[=rinit_spec]{rinit specification}.}\n\n\\item{ode_control}{optional list;\nthe elements of this list will be passed to \\code{\\link[deSolve]{ode}} if the skeleton is a vectorfield, and ignored if it is a map.}\n\n\\item{format}{the format in which to return the results.\n\n\\code{format = \"pomps\"} causes the trajectories to be returned as a single \\sQuote{pomp} object (if a single parameter vector has been furnished to \\code{trajectory}) or as a \\sQuote{pompList} object (if a matrix of parameters have been furnished).\nIn each of these, the \\code{states} slot will have been replaced by the computed trajectory.\nUse \\code{\\link{states}} to view these.\n\n\\code{format = \"array\"} causes the trajectories to be returned\nin a rank-3 array with dimensions\n\\code{nvar} x \\code{ncol(params)} x \\code{ntimes}.\nHere, \\code{nvar} is the number of state variables and \\code{ntimes} the length of the argument \\code{times}.\nThus if \\code{x} is the returned array, \\code{x[i,j,k]} is the i-th component of the state vector at time \\code{times[k]} given parameters \\code{params[,j]}.\n\n\\code{format = \"data.frame\"} causes the results to be returned as a single data frame containing the time and states.\nAn ordered factor variable, \\sQuote{.id}, distinguishes the trajectories from one another.}\n\n\\item{verbose}{logical; if \\code{TRUE}, diagnostic messages will be printed to the console.}\n\n\\item{object}{optional;\nif present, it should be a data frame or a \\sQuote{pomp} object.}\n}\n\\value{\nThe \\code{format} option controls the nature of the return value of \\code{trajectory}.\nSee above for details.\n}\n\\description{\nCompute trajectories of the deterministic skeleton of a Markov process.\n}\n\\details{\nIn the case of a discrete-time system, the deterministic skeleton is a map and a trajectory is obtained by iterating the map.\nIn the case of a continuous-time system, the deterministic skeleton is a vector-field;\n\\code{trajectory} uses the numerical solvers in \\pkg{\\link[deSolve]{deSolve}} to integrate the vectorfield.\n}\n\\examples{\n\\donttest{\n  ## The basic components needed to compute trajectories\n  ## of a deterministic dynamical system are\n  ## rinit and skeleton.\n\n  ## The following specifies these for a simple continuous-time\n  ## model: dx/dt = r (1+e cos(t)) x\n\n  trajectory(\n    t0 = 0, times = seq(1,30,by=0.1),\n    rinit = function (x0, ...) {\n      c(x = x0)\n    },\n    skeleton = vectorfield(\n      function (r, e, t, x, ...) {\n        c(x=r*(1+e*cos(t))*x)\n      }\n    ),\n    params = c(r=1,e=3,x0=1)\n  ) -> po\n\n  plot(po,log='y')\n\n  ## In the case of a discrete-time skeleton,\n  ## we use the 'map' function.  For example,\n  ## the following computes a trajectory from\n  ## the dynamical system with skeleton\n  ## x -> x exp(r sin(omega t)).\n\n  trajectory(\n    t0 = 0, times=seq(1,100),\n    rinit = function (x0, ...) {\n      c(x = x0)\n    },\n    skeleton = map(\n      function (r, t, x, omega, ...) {\n        c(x=x*exp(r*sin(omega*t)))\n      },\n      delta.t=1\n    ),\n    params = c(r=1,x0=1,omega=4)\n  ) -> po\n\n  plot(po)\n\n}\n\\donttest{ # takes too long for R CMD check\n  ## generate a bifurcation diagram for the Ricker map\n  p <- parmat(coef(ricker()),nrep=500)\n  p[\"r\",] <- exp(seq(from=1.5,to=4,length=500))\n  trajectory(\n    ricker(),\n    times=seq(from=1000,to=2000,by=1),\n    params=p,\n    format=\"array\"\n  ) -> x\n  matplot(p[\"r\",],x[\"N\",,],pch='.',col='black',\n    xlab=expression(log(r)),ylab=\"N\",log='x')\n}\n}\n\\seealso{\nMore on \\pkg{pomp} elementary algorithms:\n\\code{\\link{elementary_algorithms}},\n\\code{\\link{kalman}},\n\\code{\\link{pfilter}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{probe}()},\n\\code{\\link{simulate}()},\n\\code{\\link{spect}()},\n\\code{\\link{wpfilter}()}\n\nMore on methods for deterministic process models:\n\\code{\\link{flow}()},\n\\code{\\link{skeleton}()},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{traj_match}}\n}\n\\concept{deterministic methods}\n\\concept{elementary algorithms}\n"
  },
  {
    "path": "man/transformations.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/transformations.R\n\\name{transformations}\n\\alias{transformations}\n\\alias{logit}\n\\alias{expit}\n\\alias{log_barycentric}\n\\alias{inv_log_barycentric}\n\\title{Transformations}\n\\usage{\nlogit(p)\n\nexpit(x)\n\nlog_barycentric(X)\n\ninv_log_barycentric(Y)\n}\n\\arguments{\n\\item{p}{numeric; a quantity in [0,1].}\n\n\\item{x}{numeric; the log odds ratio.}\n\n\\item{X}{numeric; a vector containing the quantities to be transformed according to the log-barycentric transformation.}\n\n\\item{Y}{numeric; a vector containing the log fractions.}\n}\n\\description{\nSome useful parameter transformations.\n}\n\\details{\nParameter transformations can be used in many cases to recast constrained optimization problems as unconstrained problems.\nAlthough there are no limits to the transformations one can implement using the \\code{\\link{parameter_trans}} facilty, \\pkg{pomp} provides a few ready-built functions to implement some very commonly useful ones.\n\nThe logit transformation takes a probability \\eqn{p} to its log odds, \\eqn{\\log\\frac{p}{1-p}}{log(p/(1-p))}.\nIt maps the unit interval \\eqn{[0,1]} into the extended real line \\eqn{[-\\infty,\\infty]}.\n\nThe inverse of the logit transformation is the expit transformation.\n\nThe log-barycentric transformation takes a vector \\eqn{X\\in{R^{n}_+}}{X in the non-negative cone of R^n}, to a vector \\eqn{Y\\in{R^n}}{Y in R^n}, where \\deqn{Y_i = \\log\\frac{X_i}{\\sum_j X_j}.}{Yi = log(Xi/sum(X)).}\nThe transformation is not one-to-one.\nHowever, for each \\eqn{c>0}, it maps the simplex \\eqn{\\{X\\in{R^n_+}:\\sum_i X_i = c\\}}{sum(X)=c} bijectively onto \\eqn{n}-dimensional Euclidean space \\eqn{R^n}.\n\nThe inverse of the log-barycentric transformation is implemented as \\code{inv_log_barycentric}.\nNote that it is not a true inverse, in the sense that it takes \\eqn{R^n} to the \\emph{unit} simplex, \\eqn{\\{X\\in{R^n_+}:\\sum_i X_i = 1\\}}{sum(X)=1}.\nThus, \\preformatted{\n    log_barycentric(inv_log_barycentric(Y)) == Y,\n} but \\preformatted{\n    inv_log_barycentric(log_barycentric(X)) == X\n} only if \\code{sum(X) == 1}.\n}\n\\seealso{\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{accumvars}},\n\\code{\\link{basic_components}},\n\\code{\\link{betabinomial}},\n\\code{\\link{covariates}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{userdata}},\n\\code{\\link{vmeasure_spec}}\n}\n\\concept{implementation information}\n\\concept{parameter transformations}\n"
  },
  {
    "path": "man/undefined.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/undefined.R, R/pomp_fun.R, R/skeleton_spec.R,\n%   R/rprocess_spec.R\n\\name{undefined}\n\\alias{undefined}\n\\alias{undefined,pomp_fun-method}\n\\alias{undefined,skelPlugin-method}\n\\alias{undefined,rprocPlugin-method}\n\\title{Undefined}\n\\usage{\n\\S4method{undefined}{pomp_fun}(object, ...)\n\n\\S4method{undefined}{skelPlugin}(object, ...)\n\n\\S4method{undefined}{rprocPlugin}(object, ...)\n}\n\\arguments{\n\\item{object}{object to test.}\n\n\\item{...}{currently ignored.}\n}\n\\value{\nReturns \\code{TRUE} if the \\pkg{pomp} workhorse method is undefined,\n\\code{FALSE} if it is defined,\nand \\code{NA} if the question is inapplicable.\n}\n\\description{\nCheck for undefined methods.\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/userdata.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/userdata.R\n\\name{userdata}\n\\alias{userdata}\n\\title{Facilities for making additional information available to basic model components}\n\\description{\nWhen \\acronym{POMP} basic components need information they can't get from parameters or covariates.\n}\n\\details{\nIt can happen that one desires to pass information to one of the \\acronym{POMP} model \\dfn{basic components} (see \\link[=basic_components]{here for a definition of this term}) outside of the standard routes (i.e., via model parameters or covariates).\n\\pkg{pomp} provides facilities for this purpose.\nWe refer to the objects one wishes to pass in this way as \\dfn{user data}.\n\nThe following will apply to every \\link[=basic_components]{basic model component}.\nFor the sake of definiteness, however, we'll use the \\code{rmeasure} component as an example.\nTo be even more specific, the measurement model we wish to implement is\n\\preformatted{\n      y1 ~ Poisson(x1+theta),  y2 ~ Poisson(x2+theta),}\nwhere \\code{theta} is a parameter.\nAlthough it would be very easy (and indeed far preferable) to include \\code{theta} among the ordinary parameters (by including it in \\code{params}), we will assume here that we have some reason for not wanting to do so.\n\nNow, we have the choice of providing \\code{rmeasure} in one of three ways:\n\\enumerate{\n  \\item as an \\R function,\n  \\item as a C snippet, or\n  \\item as a procedure in an external, dynamically loaded library.\n}\nWe'll deal with these three cases in turn.\n}\n\\section{When the basic component is specified as an \\R function}{\n\nWe can implement a simulator for the aforementioned measurement model so: \\preformatted{\n   f <- function (t, x, params, theta, ...) {\n      y <- rpois(n=2,x[c(\"x1\",\"x2\")]+theta)\n      setNames(y,c(\"y1\",\"y2\"))\n   }}\nSo far, so good, but how do we get \\code{theta} to this function?\nWe simply provide an additional argument to whichever \\pkg{pomp} algorithm we are employing (e.g., \\code{\\link{simulate}}, \\code{\\link{pfilter}}, \\code{\\link{mif2}}, \\code{\\link{abc}}, etc.).\nFor example:\n\\preformatted{\n    simulate(..., rmeasure = f, userdata = list(theta = 42), ...)\n}\nwhere the \\code{\\dots} represent other arguments.\n}\n\n\\section{When the basic component is specified via a C snippet}{\n\nA C snippet implementation of the aforementioned measurement model is:\n\\preformatted{\n    f <- Csnippet(r\"{\n     double theta = *get_userdata_double(\"theta\");\n     y1 = rpois(x1+theta); y2 = rpois(x2+theta);\n    }\")}\nHere, the call to \\code{get_userdata_double} retrieves a \\emph{pointer} to the stored value of \\code{theta}.\nNote that, by using \\R string literals (\\code{r\"{}\"}) we avoid the need to escape the quotes in the C snippet text.\n\nIt is possible to store and retrieve integer objects also, using \\code{get_userdata_int}.\n\nOne must take care that one stores the user data with the appropriate storage type.\nFor example, it is wise to wrap floating point scalars and vectors with \\code{as.double} and integers with \\code{as.integer}.\nIn the present example, our call to simulate might look like\n\\preformatted{\n    simulate(..., rmeasure = f, userdata = list(theta = as.double(42)), ...)\n}\n\nSince the two functions \\code{get_userdata_double} and \\code{get_userdata_int} return pointers, it is trivial to pass vectors of double-precision and integers.\n\nA simpler and more elegant approach is afforded by the \\code{globals} argument (see below).\n}\n\n\\section{When the basic component is specified via an external library}{\n\n\nThe rules are essentially the same as for C snippets.\n\\code{typedef} declarations for the \\code{get_userdata_double} and \\code{get_userdata_int} are given in the \\file{pomp.h} header file and these two routines are registered so that they can be retrieved via a call to \\code{R_GetCCallable}.\nSee the \\href{https://cran.r-project.org/doc/manuals/R-exts.html}{Writing \\R extensions manual} for more information.\n}\n\n\\section{Setting \\code{globals}}{\n\n\nThe use of the userdata facilities incurs a run-time cost.\nIt is often more efficient, when using C snippets, to put the needed objects directly into the C snippet library.\nThe \\code{globals} argument does this.\nSee the example below.\n}\n\n\\examples{\n\\donttest{\n  ## The familiar Ricker example.\n  ## Suppose that for some reason we wish to pass 'phi'\n  ## via the userdata facility instead of as a parameter.\n\n  ## C snippet approach:\n\n  simulate(times=1:100,t0=0,\n    userdata=list(phi=as.double(100)),\n    params=c(r=3.8,sigma=0.3,N.0=7),\n    rprocess=discrete_time(\n      step.fun=Csnippet(r\"{\n      double e = (sigma > 0.0) ? rnorm(0,sigma) : 0.0;\n      N = r*N*exp(-N+e);}\"\n      ),\n      delta.t=1\n    ),\n    rmeasure=Csnippet(r\"{\n       double phi = *get_userdata_double(\"phi\");\n       y = rpois(phi*N);}\"\n    ),\n    paramnames=c(\"r\",\"sigma\"),\n    statenames=\"N\",\n    obsnames=\"y\"\n  ) -> rick1\n\n  ## The same problem solved using 'globals':\n  simulate(times=1:100,t0=0,\n    globals=Csnippet(\"static double phi = 100;\"),\n    params=c(r=3.8,sigma=0.3,N.0=7),\n    rprocess=discrete_time(\n      step.fun=Csnippet(r\"{\n      double e = (sigma > 0.0) ? rnorm(0,sigma) : 0.0;\n      N = r*N*exp(-N+e);}\"\n      ),\n      delta.t=1\n    ),\n    rmeasure=Csnippet(\"\n       y = rpois(phi*N);\"\n    ),\n    paramnames=c(\"r\",\"sigma\"),\n    statenames=\"N\",\n    obsnames=\"y\"\n  ) -> rick2\n\n  ## Finally, the R function approach:\n\n  simulate(times=1:100,t0=0,\n    userdata=list(phi=100),\n    params=c(r=3.8,sigma=0.3,N_0=7),\n    rprocess=discrete_time(\n      step.fun=function (r, N, sigma, ...) {\n        e <- rnorm(n=1,mean=0,sd=sigma)\n        c(N=r*N*exp(-N+e))\n      },\n      delta.t=1\n    ),\n    rmeasure=function (phi, N, ...) {\n      c(y=rpois(n=1,lambda=phi*N))\n    }\n  ) -> rick3\n\n}\n}\n\\seealso{\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{accumvars}},\n\\code{\\link{basic_components}},\n\\code{\\link{betabinomial}},\n\\code{\\link{covariates}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{vmeasure_spec}}\n}\n\\concept{implementation information}\n"
  },
  {
    "path": "man/verhulst.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/verhulst.R\n\\docType{data}\n\\name{verhulst}\n\\alias{verhulst}\n\\title{Verhulst-Pearl model}\n\\usage{\nverhulst(\n  n_0 = 10000,\n  K = 10000,\n  r = 0.9,\n  sigma = 0.4,\n  tau = 0.1,\n  dt = 0.01,\n  seed = 73658676L\n)\n}\n\\arguments{\n\\item{n_0}{initial condition}\n\n\\item{K}{carrying capacity}\n\n\\item{r}{intrinsic growth rate}\n\n\\item{sigma}{environmental process noise s.d.}\n\n\\item{tau}{measurement error s.d.}\n\n\\item{dt}{Euler timestep}\n\n\\item{seed}{seed of the random number generator}\n}\n\\value{\nA \\sQuote{pomp} object containing the model and simulated data.\nThe following basic components are included in the \\sQuote{pomp} object:\n\\sQuote{rinit}, \\sQuote{rprocess}, \\sQuote{rmeasure}, \\sQuote{dmeasure}, and \\sQuote{skeleton}.\n}\n\\description{\nThe Verhulst-Pearl (logistic) model of population growth.\n}\n\\details{\nA stochastic version of the Verhulst-Pearl logistic model.\nThis evolves in continuous time, according to the stochastic differential equation\n\\deqn{dn_t = r\\,n_t\\,\\left(1-\\frac{n_t}{K}\\right)\\,dt+\\sigma\\,n_t\\,dW_t.}{dn[t] = r n[t] (1-n[t]/K) dt + sigma n[t] dW[t].}\n\nNumerically, we simulate the stochastic dynamics using an Euler approximation.\n\nThe measurements are assumed to be log-normally distributed:\n\\deqn{N_t \\sim \\mathrm{Lognormal}\\left(\\log{n_t},\\tau\\right).}{N[t] ~ Lognormal(log(n[t]),tau).}\n}\n\\examples{\n\\donttest{ # takes too long for R CMD check\n  verhulst() -> po\n  plot(po)\n  plot(simulate(po))\n  pfilter(po,Np=1000) -> pf\n  logLik(pf)\n  spy(po)\n}\n}\n\\seealso{\nMore examples provided with \\pkg{pomp}:\n\\code{\\link{blowflies}},\n\\code{\\link{childhood_disease_data}},\n\\code{\\link{compartmental_models}},\n\\code{\\link{dacca}()},\n\\code{\\link{ebola}},\n\\code{\\link{gompertz}()},\n\\code{\\link{ou2}()},\n\\code{\\link{pomp_examples}},\n\\code{\\link{ricker}()},\n\\code{\\link{rw2}()}\n}\n\\concept{pomp examples}\n"
  },
  {
    "path": "man/vmeasure.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/workhorses.R\n\\docType{methods}\n\\name{vmeasure}\n\\alias{vmeasure}\n\\alias{vmeasure,ANY-method}\n\\alias{vmeasure,missing-method}\n\\alias{vmeasure,pomp-method}\n\\title{vmeasure workhorse}\n\\usage{\n\\S4method{vmeasure}{pomp}(\n  object,\n  ...,\n  x = states(object),\n  times = time(object),\n  params = coef(object)\n)\n}\n\\arguments{\n\\item{object}{an object of class \\sQuote{pomp}, or of a class that extends \\sQuote{pomp}.\nThis will typically be the output of \\code{pomp}, \\code{simulate}, or one of the \\pkg{pomp} inference algorithms.}\n\n\\item{...}{additional arguments are ignored.}\n\n\\item{x}{an array containing states of the unobserved process.\nThe dimensions of \\code{x} are \\code{nvars} x \\code{nrep} x \\code{ntimes},\nwhere \\code{nvars} is the number of state variables,\n\\code{nrep} is the number of replicates,\nand \\code{ntimes} is the length of \\code{times}.\nOne can also pass \\code{x} as a named numeric vector, which is equivalent to the \\code{nrep=1}, \\code{ntimes=1} case.}\n\n\\item{times}{a numeric vector (length \\code{ntimes}) containing times.\nThese must be in non-decreasing order.}\n\n\\item{params}{a \\code{npar} x \\code{nrep} matrix of parameters.\nEach column is treated as an independent parameter set, in correspondence with the corresponding column of \\code{x}.}\n}\n\\value{\n\\code{vmeasure} returns a rank-4 array of dimensions\n\\code{nobs} x \\code{nobs} x \\code{nrep} x \\code{ntimes},\nwhere \\code{nobs} is the number of observed variables.\nIf \\code{v} is the returned array, \\code{v[,,j,k]} contains the\ncovariance matrix at time \\code{times[k]} given the state \\code{x[,j,k]}.\n}\n\\description{\nReturn the covariance matrix of the observed variables, given values of the latent states and the parameters.\n}\n\\seealso{\nSpecification of the measurement-model covariance matrix: \\link{vmeasure_spec}\n\nMore on \\pkg{pomp} workhorse functions:\n\\code{\\link{dinit}()},\n\\code{\\link{dmeasure}()},\n\\code{\\link{dprior}()},\n\\code{\\link{dprocess}()},\n\\code{\\link{emeasure}()},\n\\code{\\link{flow}()},\n\\code{\\link{partrans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{rinit}()},\n\\code{\\link{rmeasure}()},\n\\code{\\link{rprior}()},\n\\code{\\link{rprocess}()},\n\\code{\\link{skeleton}()},\n\\code{\\link{workhorses}}\n}\n\\concept{pomp workhorses}\n"
  },
  {
    "path": "man/vmeasure_spec.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/vmeasure_spec.R\n\\name{vmeasure_spec}\n\\alias{vmeasure_spec}\n\\title{vmeasure specification}\n\\description{\nSpecification of the measurement-model covariance  matrix, vmeasure.\n}\n\\details{\nThe measurement model is the link between the data and the unobserved state process.\nSome algorithms require the conditional covariance of the measurement model, given the latent state and parameters.\nThis is supplied using the \\code{vmeasure} argument.\n\nSuppose you have a procedure to compute this conditional covariance matrix, given the value of the latent state variables.\nThen you can furnish \\preformatted{\n  vmeasure = f}\nto \\pkg{pomp} algorithms,\nwhere \\code{f} is a C snippet or \\R function that implements your procedure.\n\nUsing a C snippet is much preferred, due to its much greater computational efficiency.\nSee \\code{\\link{Csnippet}} for general rules on writing C snippets.\n\nIn writing a \\code{vmeasure} C snippet, bear in mind that:\n  \\enumerate{\n    \\item The goal of such a snippet is to fill variables named \\code{V_y_z} with the conditional covariances of observables \\code{y}, \\code{z}.\n    Accordingly, there should be one assignment of \\code{V_y_z} and one assignment of \\code{V_z_y} for each pair of observables \\code{y} and \\code{z}.\n    \\item In addition to the states, parameters, and covariates (if any), the variable \\code{t}, containing the time of the observation, will be defined in the context in which the snippet is executed.\n  }\n\nThe demos and the tutorials on the \\href{https://kingaa.github.io/pomp/}{package website} give examples.\n\nIt is also possible, though less efficient, to specify \\code{vmeasure} using an \\R function.\nIn this case, specify it by furnishing \\preformatted{\n  vmeasure = f}\nto \\code{pomp}, where \\code{f} is an \\R function.\nThe arguments of \\code{f} should be chosen from among the state variables, parameters, covariates, and time.\nIt must also have the argument \\code{...}.\n\\code{f} must return a square matrix of dimension equal to the number of observable variables.\nThe row- and column-names of this matrix should match the names of the observable variables.\nThe matrix should of course be symmetric.\n}\n\\section{Default behavior}{\n\nThe default \\code{vmeasure} is undefined.\nIt will yield missing values (\\code{NA}).\n}\n\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\seealso{\n\\code{\\link{vmeasure}}\n\nMore on implementing POMP models:\n\\code{\\link{Csnippet}},\n\\code{\\link{accumvars}},\n\\code{\\link{basic_components}},\n\\code{\\link{betabinomial}},\n\\code{\\link{covariates}},\n\\code{\\link{dinit_spec}},\n\\code{\\link{dmeasure_spec}},\n\\code{\\link{dprocess_spec}},\n\\code{\\link{emeasure_spec}},\n\\code{\\link{eulermultinom}},\n\\code{\\link{parameter_trans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{pomp_constructor}},\n\\code{\\link{prior_spec}},\n\\code{\\link{rinit_spec}},\n\\code{\\link{rmeasure_spec}},\n\\code{\\link{rprocess_spec}},\n\\code{\\link{skeleton_spec}},\n\\code{\\link{transformations}},\n\\code{\\link{userdata}}\n}\n\\concept{implementation information}\n"
  },
  {
    "path": "man/window.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/window.R\n\\docType{methods}\n\\name{window}\n\\alias{window}\n\\alias{window,pomp-method}\n\\title{Window}\n\\usage{\n\\S4method{window}{pomp}(x, start, end, ...)\n}\n\\arguments{\n\\item{x}{a \\sQuote{pomp} object or object of class extending \\sQuote{pomp}}\n\n\\item{start, end}{the left and right ends of the window, in units of time}\n\n\\item{\\dots}{ignored}\n}\n\\description{\nRestrict to a portion of a time series.\n}\n"
  },
  {
    "path": "man/workhorses.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/workhorses.R\n\\docType{methods}\n\\name{workhorses}\n\\alias{workhorses}\n\\title{Workhorse functions for the \\pkg{pomp} algorithms.}\n\\description{\nThese functions mediate the interface between the user's model and the package algorithms.\nThey are low-level functions that do the work needed by the package's inference methods.\n}\n\\details{\nThey include \\describe{\n\\item{\\code{\\link{rinit}}}{which samples from the initial-state distribution,}\n\\item{\\code{\\link{dinit}}}{which evaluates the initial-state density,}\n\\item{\\code{\\link{dmeasure}}}{which evaluates the measurement model density,}\n\\item{\\code{\\link{rmeasure}}}{which samples from the measurement model distribution,}\n\\item{\\code{\\link{emeasure}}}{which computes the expectation of the observed variables conditional on the latent state,}\n\\item{\\code{\\link{vmeasure}}}{which computes the covariance matrix of the observed variables conditional on the latent state,}\n\\item{\\code{\\link{dprocess}}}{which evaluates the process model density,}\n\\item{\\code{\\link{rprocess}}}{which samples from the process model distribution,}\n\\item{\\code{\\link{dprior}}}{which evaluates the prior probability density,}\n\\item{\\code{\\link{rprior}}}{which samples from the prior distribution,}\n\\item{\\code{\\link{skeleton}}}{which evaluates the model's deterministic skeleton,}\n\\item{\\code{\\link{flow}}}{which iterates or integrates the deterministic skeleton to yield trajectories,}\n\\item{\\code{\\link{partrans}}}{which performs parameter transformations associated with the model.}\n}\n}\n\\seealso{\n\\link[=basic_components]{basic model components},\n\\link[=elementary_algorithms]{elementary algorithms},\n\\link[=estimation_algorithms]{estimation algorithms}\n\nMore on \\pkg{pomp} workhorse functions:\n\\code{\\link{dinit}()},\n\\code{\\link{dmeasure}()},\n\\code{\\link{dprior}()},\n\\code{\\link{dprocess}()},\n\\code{\\link{emeasure}()},\n\\code{\\link{flow}()},\n\\code{\\link{partrans}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{rinit}()},\n\\code{\\link{rmeasure}()},\n\\code{\\link{rprior}()},\n\\code{\\link{rprocess}()},\n\\code{\\link{skeleton}()},\n\\code{\\link{vmeasure}()}\n}\n\\author{\nAaron A. King\n}\n\\concept{extending the pomp package}\n\\concept{low-level interface}\n\\concept{pomp workhorses}\n"
  },
  {
    "path": "man/wpfilter.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/wpfilter.R\n\\name{wpfilter}\n\\alias{wpfilter}\n\\alias{wpfilter,ANY-method}\n\\alias{wpfilter,missing-method}\n\\alias{wpfilter,data.frame-method}\n\\alias{wpfilter,pomp-method}\n\\alias{wpfilter,wpfilterd_pomp-method}\n\\title{Weighted particle filter}\n\\usage{\n\\S4method{wpfilter}{data.frame}(\n  data,\n  ...,\n  Np,\n  params,\n  rinit,\n  rprocess,\n  dmeasure,\n  trigger = 1,\n  target = 0.5,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{wpfilter}{pomp}(\n  data,\n  ...,\n  Np,\n  trigger = 1,\n  target = 0.5,\n  verbose = getOption(\"verbose\", FALSE)\n)\n\n\\S4method{wpfilter}{wpfilterd_pomp}(data, ..., Np, trigger, target, verbose = getOption(\"verbose\", FALSE))\n}\n\\arguments{\n\\item{data}{either a data frame holding the time series data,\nor an object of class \\sQuote{pomp},\ni.e., the output of another \\pkg{pomp} calculation.\nInternally, \\code{data} will be coerced to an array with storage-mode \\code{double}.}\n\n\\item{...}{additional arguments are passed to \\code{\\link{pomp}}.\nThis allows one to set, unset, or modify \\link[=basic_components]{basic model components} within a call to this function.}\n\n\\item{Np}{the number of particles to use.\nThis may be specified as a single positive integer, in which case the same number of particles will be used at each timestep.\nAlternatively, if one wishes the number of particles to vary across timesteps, one may specify \\code{Np} either as a vector of positive integers of length \\preformatted{length(time(object,t0=TRUE))} or as a function taking a positive integer argument.\nIn the latter case, \\code{Np(k)} must be a single positive integer, representing the number of particles to be used at the \\code{k}-th timestep:\n\\code{Np(0)} is the number of particles to use going from \\code{timezero(object)} to \\code{time(object)[1]},\n\\code{Np(1)}, from \\code{timezero(object)} to \\code{time(object)[1]},\nand so on,\nwhile when \\code{T=length(time(object))}, \\code{Np(T)} is the number of particles to sample at the end of the time-series.}\n\n\\item{params}{optional; named numeric vector of parameters.\nThis will be coerced internally to storage mode \\code{double}.}\n\n\\item{rinit}{simulator of the initial-state distribution.\nThis can be furnished either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{rinit=NULL} sets the initial-state simulator to its default.\nFor more information, see \\link[=rinit_spec]{rinit specification}.}\n\n\\item{rprocess}{simulator of the latent state process, specified using one of the \\link[=rprocess_spec]{rprocess plugins}.\nSetting \\code{rprocess=NULL} removes the latent-state simulator.\nFor more information, see \\link[=rprocess_spec]{rprocess specification for the documentation on these plugins}.}\n\n\\item{dmeasure}{evaluator of the measurement model density, specified either as a C snippet, an \\R function, or the name of a pre-compiled native routine available in a dynamically loaded library.\nSetting \\code{dmeasure=NULL} removes the measurement density evaluator.\nFor more information, see \\link[=dmeasure_spec]{dmeasure specification}.}\n\n\\item{trigger}{numeric; if the effective sample size becomes smaller than \\code{trigger * Np}, resampling is triggered.}\n\n\\item{target}{numeric; target power.}\n\n\\item{verbose}{logical; if \\code{TRUE}, diagnostic messages will be printed to the console.}\n}\n\\value{\nAn object of class \\sQuote{wpfilterd_pomp}, which extends class \\sQuote{pomp}.\nInformation can be extracted from this object using the methods documented below.\n}\n\\description{\nA sequential importance sampling (particle filter) algorithm.\nUnlike in \\code{pfilter}, resampling is performed only when triggered by\ndeficiency in the effective sample size.\n}\n\\details{\n\\bold{This function is experimental and should be considered in alpha stage.\nBoth interface and underlying algorithms may change without warning at any time.\nPlease explore the function and give feedback via the \\pkg{pomp} Issues page.}\n}\n\\section{Methods}{\n\n\\describe{\n\\item{\\code{\\link{logLik}}}{ the estimated log likelihood}\n\\item{\\code{\\link{cond_logLik}}}{ the estimated conditional log likelihood}\n\\item{\\code{\\link{eff_sample_size}}}{the (time-dependent) estimated effective sample size}\n\\item{\\code{\\link{as.data.frame}}}{ coerce to a data frame}\n\\item{\\code{\\link{plot}}}{diagnostic plots}\n}\n}\n\n\\section{Note for Windows users}{\n\n\nSome Windows users report problems when using C snippets in parallel computations.\nThese appear to arise when the temporary files created during the C snippet compilation process are not handled properly by the operating system.\nTo circumvent this problem, use the \\code{\\link[=pomp]{cdir}} and \\code{\\link[=pomp]{cfile}} options to cause the C snippets to be written to a file of your choice, thus avoiding the use of temporary files altogether.\n}\n\n\\references{\n\\Arulampalam2002\n}\n\\seealso{\nMore on \\pkg{pomp} elementary algorithms:\n\\code{\\link{elementary_algorithms}},\n\\code{\\link{kalman}},\n\\code{\\link{pfilter}()},\n\\code{\\link{pomp-package}},\n\\code{\\link{probe}()},\n\\code{\\link{simulate}()},\n\\code{\\link{spect}()},\n\\code{\\link{trajectory}()}\n\nMore on sequential Monte Carlo methods:\n\\code{\\link{bsmc2}()},\n\\code{\\link{cond_logLik}()},\n\\code{\\link{eff_sample_size}()},\n\\code{\\link{filter_mean}()},\n\\code{\\link{filter_traj}()},\n\\code{\\link{kalman}},\n\\code{\\link{mif2}()},\n\\code{\\link{pfilter}()},\n\\code{\\link{pmcmc}()},\n\\code{\\link{pred_mean}()},\n\\code{\\link{pred_var}()},\n\\code{\\link{saved_states}()}\n\nMore on full-information (i.e., likelihood-based) methods:\n\\code{\\link{bsmc2}()},\n\\code{\\link{mif2}()},\n\\code{\\link{pfilter}()},\n\\code{\\link{pmcmc}()}\n}\n\\author{\nAaron A. King\n}\n\\concept{elementary algorithms}\n\\concept{full-information methods}\n\\concept{particle filter methods}\n"
  },
  {
    "path": "man/wquant.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/wquant.R\n\\name{wquant}\n\\alias{wquant}\n\\title{Weighted quantile function}\n\\usage{\nwquant(\n  x,\n  weights = rep(1, length(x)),\n  probs = c(`0\\%` = 0, `25\\%` = 0.25, `50\\%` = 0.5, `75\\%` = 0.75, `100\\%` = 1)\n)\n}\n\\arguments{\n\\item{x}{numeric; a vector of data.}\n\n\\item{weights}{numeric; vector of weights.}\n\n\\item{probs}{numeric; desired quantiles.}\n}\n\\value{\n\\code{wquant} returns a vector containing the estimated quantiles.\nIf \\code{probs} has names, these are inherited.\n}\n\\description{\nEstimate weighted quantiles.\n}\n\\details{\n\\code{wquant} estimates quantiles of weighted data using the estimator of Harrell & Davis (1982), with improvements recommended by Andrey Akinshin (2023).\n}\n\\examples{\nx <- c(1,1,1,2,2,3,3,3,3,4,5,5,6,6,6)\nquantile(x)\nwquant(x)\nwquant(c(1,2,3,4,5,6),weights=c(3,2,4,1,2,3))\nwquant(c(1,2,3,4,5),c(1,0,0,1,1))\n}\n\\references{\n\\Harrell1982\n\n\\Akinshin2023\n}\n\\author{\nAaron A. King\n}\n"
  },
  {
    "path": "revdep/.gitignore",
    "content": "*.tar.gz\n*.Rcheck\nLibrary/\nPACKAGES*\n"
  },
  {
    "path": "revdep/Makefile",
    "content": "clean:\n\t$(RM) -r *.Rcheck Library *.tar.gz\n\t$(RM) Outputs/install*.out\n"
  },
  {
    "path": "revdep/timings.tab",
    "content": "\"user\" \"system\" \"elapsed\"\n\"pomp\" 111.108 48.259 137.278\n\"CollocInfer\" 123.751 76.234 135.114\n\"DTAT\" 126.728 52.866 153.794\n\"epimdr\" 57.984 35.738 74.689\n\"epimdr2\" 83.161 38.813 105.265\n\"spaero\" 55.888 48.234 75.088\n\"spatPomp\" 143.034 127.359 160.487\n\"stops\" 142.311 67.553 166.941\n\"circumstance\" 78.879 38.082 95.137\n\"hte\" 142.903 91.302 159.014\n\"panelPomp\" 105.483 104.443 130.351\n\"phylopomp\" 207.219 70.173 229.625\n"
  },
  {
    "path": "rules.mk",
    "content": "REXE = $(shell which R) -s\nRCMD = $(REXE) CMD\nMANUALDIR = $(REPODIR)/manuals/$(PKG)\n\nPDFLATEX = pdflatex\nBIBTEX = bibtex\nMAKEIDX = makeindex\n\nRM = rm -f\nCP = cp\nTOUCH = touch\nINSTALL = install\n\nPKG = $(shell perl -ne 'print $$1 if /Package:\\s+((\\w+[-\\.]?)+)/;' DESCRIPTION)\nVERSION = $(shell perl -ne 'print $$1 if /Version:\\s+((\\d+[-\\.]?)+)/;' DESCRIPTION)\nPKGVERS = $(PKG)_$(VERSION)\nTARBALL = $(PKGVERS).tar.gz\nSOURCE = $(sort $(wildcard R/*R src/*.c src/*.cc src/*.h data/* examples/*))\nCSOURCE = $(sort $(wildcard src/*.c))\nTESTS = $(sort $(wildcard tests/*R))\nINSTDOCS = $(sort $(wildcard inst/doc/*))\n\n.PHONY: .check check clean covr debug default fresh \\\nhtmlhelp manual publish qcheck qqcheck rchk revdeps \\\nrhub rsession session www win wind xcheck xcovr vcheck ycheck\n\n.dist manual www: export R_QPDF=qpdf\n.headers: export LC_COLLATE=C\n.roxy .headers .dist manual www: export R_HOME=$(shell $(REXE) RHOME)\n.check: export FULL_TESTS=yes\n.dist .tests .session .check: export R_KEEP_PKG_SOURCE=yes\nrevdeps .session .tests .check: export R_PROFILE_USER=$(CURDIR)/.Rprofile\n.tests .session vcheck www manual: export R_LIBS=$(CURDIR)/library\ndebug .check: export PKG_CPPFLAGS=-UNDEBUG\n.check: export R_CHECK_ENVIRON=$(CURDIR)/tools/check.env\nsession: RSESSION = emacs -f R\ndebug: RSESSION = R -d gdb\nrsession: RSESSION = R\n\ndefault: .roxy .NEWS .instdocs .source .includes .headers\n\t@echo $(PKGVERS)\n\nversion:\n\t@echo $(PKGVERS)\n\nroxy: .roxy\n\ndist: .dist\n\ninstall: .install\n\ninstdocs: .instdocs\n\nCOMMON_CHECK_ARGS = document=FALSE,vignettes=FALSE,clean_doc=FALSE,check_dir=\"check\"\n\ncheck: CHECK = devtools::check($(COMMON_CHECK_ARGS),cran=FALSE)\nqcheck: CHECK = devtools::check($(COMMON_CHECK_ARGS),cran=FALSE,\\\nargs=c(\"--no-tests\"))\nqqcheck: CHECK = devtools::check($(COMMON_CHECK_ARGS),cran=FALSE,\\\nargs=c(\"--no-tests\",\"--no-codoc\",\"--no-examples\"))\nxcheck: CHECK = devtools::check($(COMMON_CHECK_ARGS),cran=TRUE)\nycheck: CHECK = devtools::check($(COMMON_CHECK_ARGS),cran=TRUE,\\\nargs=c(\"--run-dontrun\",\"--run-donttest\"))\n\nINSTALLCMD = devtools::install(args=c(\"--preclean\",\"--html\",\"--library=library\"))\n\ncheck xcheck ycheck qcheck qqcheck: .check\n\nvcheck: check \n\t$(REXE) -d \"valgrind -s --tool=memcheck --track-origins=yes --leak-check=full\"\\\n\t< check/$(PKG).Rcheck/$(PKG)-Ex.R 2>&1 | tee $(PKG)-Ex.Rout\n\nNEWS: .NEWS\n\n.instdocs: $(INSTDOCS)\n\t$(MAKE) -C inst/doc\n\t$(TOUCH) $@\n\n.NEWS: inst/NEWS\n\t$(TOUCH) $@\n\n.headers: $(HEADERS)\n\t$(TOUCH) $@\n\n.includes: $(INCLUDES)\n\t$(TOUCH) $@\n\n.source: $(SOURCE)\n\t$(TOUCH) $@\n\n.testsource: $(TESTS)\n\t$(TOUCH) $@\n\n.roxy: .source .headers\n\t$(REXE) -e \"devtools::document()\"\n\t$(TOUCH) $@\n\n.check: .roxy .NEWS .instdocs .includes\n\t$(REXE) -e '$(CHECK)'\n\n.dist: .roxy .NEWS .instdocs .testsource .includes\n\t$(RCMD) build --force --no-manual --resave-data --compact-vignettes=both --md5 .\n\t$(TOUCH) $@\n\n.install: .roxy .NEWS .instdocs .source .includes .headers\n\tmkdir -p library\n\t$(REXE) -e '$(INSTALLCMD)'\n\t$(RCMD) Rdconv -t html inst/NEWS.Rd -o library/$(PKG)/html/NEWS.html\n\t$(TOUCH) .install\n\n.session: .install\n\texport R_DEFAULT_PACKAGES=$(SESSION_PKGS) && \\\n\texec $(RSESSION)\n\ninst/NEWS: inst/NEWS.Rd\n\t$(RCMD) Rdconv -t txt $^ -o $@\n\nhtmlhelp: install manual\n\tmkdir -p $(MANUALDIR)/source\n\tdoxygen\n\trsync --delete -a library/$(PKG)/html/ $(MANUALDIR)/html\n\trsync --delete --exclude=aliases.rds --exclude=paths.rds --exclude=$(PKG).rdb --exclude=$(PKG).rdx --exclude=macros -a library/$(PKG)/help/ $(MANUALDIR)/help\n\t(cd $(MANUALDIR); (cat links.ed && echo w ) | ed - html/00Index.html)\n\t$(CP) $(PKG).pdf $(MANUALDIR)\n\t$(CP) $(REPODIR)/assets/R.css $(MANUALDIR)/html\n\nwww: install\n\t$(MAKE)\t-C www\n\nsession debug rsession: .session\n\nrchk: .rchk\n\n.rchk: .dist\n\tmkdir -p rchk\n\t$(CP) $(TARBALL) rchk\n\tdocker run -v $(PWD)/rchk:/rchk/packages kalibera/rchk:latest /rchk/packages/$(TARBALL) | tee rchk.out\n\nrevdeps: .dist\n\tmkdir -p revdep\n\t$(CP) $(TARBALL) revdep\n\t$(REXE) -e \"tools::check_packages_in_dir(\\\"revdep\\\",check_args=\\\"--as-cran --no-vignettes --ignore-vignettes\\\",reverse=list(which=\\\"most\\\"))\"\n\npublish: dist manual htmlhelp\n\t$(REXE) -e 'drat::insertPackage(\"$(PKGVERS).tar.gz\",repodir=\"$(REPODIR)\",action=\"prune\")'\n\t-$(REXE) -e 'drat::insertPackage(\"$(PKGVERS).tgz\",repodir=\"$(REPODIR)\",action=\"prune\")'\n\t-$(REXE) -e 'drat::insertPackage(\"$(PKGVERS).zip\",repodir=\"$(REPODIR)\",action=\"prune\")'\n\nrhub:\n\t$(REXE) -e 'library(rhub); check_for_cran(); check_on_windows(); check(platform=\"macos-highsierra-release-cran\");'\n\ncovr: covr.rds\n\ncovr.rds: DESCRIPTION\n\t$(REXE) -e 'library(covr); package_coverage(type=\"all\") -> cov; saveRDS(cov,file=\"covr.rds\")'\n\nxcovr: covr\n\t$(REXE) -e 'library(covr); readRDS(\"covr.rds\") -> cov; codecov(coverage=cov,quiet=FALSE)'\n\nvcovr: covr\n\t$(REXE) -e 'library(covr); readRDS(\"covr.rds\") -> cov; report(cov,file=\"covr.html\",browse=TRUE)'\n\nwin: dist\n\tcurl -T $(TARBALL) ftp://win-builder.r-project.org/R-release/\n\nwind: dist\n\tcurl -T $(TARBALL) ftp://win-builder.r-project.org/R-devel/\n\nmanual: install $(PKG).pdf\n\n$(PKG).pdf: $(SOURCE)\n\t$(RCMD) Rd2pdf --internals --no-description --no-preview --pdf --force -o $(PKG).pdf .\n\t$(REXE) -e \"tools::compactPDF(\\\"$(PKG).pdf\\\")\";\n\ntests: .tests\n\n.tests: .install .testsource\n\t$(MAKE) -j10 -C tests\n\t$(TOUCH) $@\n\ninstall: .install\n\ninst/include/%.h: src/%.h\n\tperl -ne 'print if not /^\\/\\/\\!/' $^ > $@\n\n%.tex: %.Rnw\n\t$(REXE) -e \"library(knitr); knit(\\\"$*.Rnw\\\")\"\n\n%.R: %.Rnw\n\t$(REXE) -e \"library(knitr); purl(\\\"$*.Rnw\\\")\"\n\n%.pdf: %.tex\n\t$(PDFLATEX) $*\n\t-$(BIBTEX) $*\n\t$(PDFLATEX) $*\n\t$(PDFLATEX) $*\n\n%.bbl: %.tex\n\t-$(PDFLATEX) $*\n\t$(BIBTEX) $*\n\n%.idx: %.tex\n\t-$(PDFLATEX) $*\n\n%.ind: %.idx\n\t$(MAKEIDX) $*\n\n%.html: %.Rmd\n\tRscript --vanilla -e \"rmarkdown::render(\\\"$*.Rmd\\\")\"\n\n%.html: %.md\n\tRscript --vanilla -e \"rmarkdown::render(\\\"$*.md\\\")\"\n\n%.R: %.Rmd\n\tRscript --vanilla -e \"knitr::purl(\\\"$*.Rmd\\\",output=\\\"$*.R\\\",documentation=2)\"\n\nclean:\n\t$(RM) -r check\n\t$(RM) src/*.o src/*.so src/symbols.rds\n\t$(RM) -r lib\n\t$(RM) -r *-Ex.Rout *-Ex.timings *-Ex.pdf Rplots.*\n\t$(RM) *.tar.gz $(PKGVERS).zip $(PKGVERS).tgz $(PKG).pdf\n\t$(MAKE) -C www clean\n\t$(MAKE) -C inst/doc clean\n\t$(MAKE) -C tests clean\n\t$(MAKE) -C revdep clean\n\t$(RM) .dist\n\nfresh: clean\n\t$(RM) .headers .includes .NEWS .instdocs\n\t$(RM) .install .roxy .source .testsource .roxy .tests\n\t$(RM) -r library rchk\n"
  },
  {
    "path": "src/Makevars",
    "content": "PKG_LIBS = $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS)\n"
  },
  {
    "path": "src/backports.h",
    "content": "// -*- C++ -*-\n\n#ifndef _POMP_BACKPORTS_H_\n#define _POMP_BACKPORTS_H_\n\n#include <Rversion.h>\n\n// Some backports needed for older versions of R.\n// Taken from\n// https://cran.r-project.org/doc/manuals/r-devel/R-exts.html#Some-backports\n// These are not necessarily all used in the package code.\n\n#if R_VERSION < R_Version(4, 5, 0)\n\n# define isDataFrame(x) Rf_isFrame(x)\n# define R_ClosureFormals(x) FORMALS(x)\n# define R_ClosureEnv(x) CLOENV(x)\n# define R_ParentEnv(x) ENCLOS(x)\n\n#endif\n\n#endif\n"
  },
  {
    "path": "src/bspline.c",
    "content": "// -*- C++ -*-\n\n#include \"internal.h\"\n\n// The following function computes the derivative of order 'deriv' of the i-th\n// B-spline of given degree with given knots at each of the nx points in x.\n// knots must point to an array of length nbasis+degree+1\n// The results are stored in y.\nstatic void bspline_eval\n(double *y, const double *x, int nx, int i,\n int degree, int deriv, const double *knots)\n{\n  int j;\n  if (deriv > degree) {\n    for (j = 0; j < nx; j++) y[j] = 0.0;\n  } else if (deriv > 0) {\n    int i2 = i+1, p2 = degree-1, d2 = deriv-1;\n    double *y1 = (double *) R_Calloc(nx,double);\n    double *y2 = (double *) R_Calloc(nx,double);\n    double a, b;\n    bspline_eval(y1,x,nx,i,p2,d2,knots);\n    bspline_eval(y2,x,nx,i2,p2,d2,knots);\n    for (j = 0; j < nx; j++) {\n      a = degree / (knots[i+degree]-knots[i]);\n      b = degree / (knots[i2+degree]-knots[i2]);\n      y[j] = a * y1[j] - b * y2[j];\n    }\n    R_Free(y1); R_Free(y2);\n  } else { // deriv == 0\n    int i2 = i+1, p2 = degree-1;\n    if (degree > 0) {  // case deriv < degree\n      double *y1 = (double *) R_Calloc(nx,double);\n      double *y2 = (double *) R_Calloc(nx,double);\n      double a, b;\n      bspline_eval(y1,x,nx,i,p2,deriv,knots);\n      bspline_eval(y2,x,nx,i2,p2,deriv,knots);\n      for (j = 0; j < nx; j++) {\n        a = (x[j]-knots[i]) / (knots[i+degree]-knots[i]);\n        b = (knots[i2+degree]-x[j]) / (knots[i2+degree]-knots[i2]);\n        y[j] = a * y1[j] + b * y2[j];\n      }\n      R_Free(y1); R_Free(y2);\n    } else if (degree == 0) { // case deriv == degree\n      for (j = 0; j < nx; j++)\n        y[j] = (double) ((knots[i] <= x[j]) && (x[j] < knots[i2]));\n    }\n  }\n}\n\n// B-spline basis\nSEXP bspline_basis (SEXP range, SEXP x, SEXP nbasis, SEXP degree, SEXP deriv) {\n  SEXP y, xr;\n  int nx = LENGTH(x);\n  int nb = INTEGER_VALUE(nbasis);\n  int deg = INTEGER_VALUE(degree);\n  int d = INTEGER_VALUE(deriv);\n  int nk = nb+deg+1;\n  double dx, minx, maxx;\n  double *knots = NULL;\n  double *xdata, *ydata;\n  int i;\n  if (deg < 0) err(\"must have degree > 0\");\n  if (nb <= deg) err(\"must have nbasis > degree\");\n  if (d < 0) err(\"must have deriv >= 0\");\n  knots = (double *) R_Calloc(nk,double);\n  PROTECT(xr = AS_NUMERIC(x));\n  PROTECT(y = allocMatrix(REALSXP,nx,nb));\n  xdata = REAL(xr);\n  ydata = REAL(y);\n  minx = REAL(range)[0];\n  maxx = REAL(range)[1];\n  if (minx >= maxx) err(\"improper range 'rg'\");\n  dx = (maxx-minx)/((double) (nb-deg));\n  knots[0] = minx-deg*dx;\n  for (i = 1; i < nk; i++) knots[i] = knots[i-1]+dx;\n  for (i = 0; i < nb; i++) {\n    bspline_eval(ydata,xdata,nx,i,deg,d,&knots[0]);\n    ydata += nx;\n  }\n  R_Free(knots);\n  UNPROTECT(2);\n  return(y);\n}\n\nSEXP periodic_bspline_basis (SEXP x, SEXP nbasis, SEXP degree, SEXP period,\n                             SEXP deriv) {\n\n  SEXP y, xr;\n  int nx = LENGTH(x);\n  int nb = INTEGER_VALUE(nbasis);\n  int deg = INTEGER_VALUE(degree);\n  int d = INTEGER_VALUE(deriv);\n  double pd = NUMERIC_VALUE(period);\n  int j, k;\n  double *xrd, *ydata, *val;\n  PROTECT(xr = AS_NUMERIC(x));\n  xrd = REAL(xr);\n  PROTECT(y = allocMatrix(REALSXP,nx,nb));\n  ydata = REAL(y);\n  val = (double *) R_alloc(nb,sizeof(double));\n  for (j = 0; j < nx; j++) {\n    periodic_bspline_basis_eval_deriv(xrd[j],pd,deg,nb,d,val);\n    for (k = 0; k < nb; k++) ydata[j+nx*k] = val[k];\n  }\n  UNPROTECT(2);\n  return y;\n}\n\n// The following function computes value at x of all the\n// nbasis B-spline basis functions of\n// the specified degree with the given knots.\n// If deriv>0, the deriv-order derivative is given.\n// 'knots' must point to an array of length nbasis+degree+1\n// The results are stored in y.\nvoid bspline_basis_eval_deriv (double x, double *knots, int degree,\n                               int nbasis, int deriv, double *y) {\n  for (int i = 0; i < nbasis; i++) {\n    bspline_eval(&y[i],&x,1,i,degree,deriv,knots);\n  }\n}\n\nvoid periodic_bspline_basis_eval_deriv (double x, double period, int degree,\n                                        int nbasis, int deriv, double *y)\n{\n  int nknots = nbasis+2*degree+1;\n  int shift = (degree-1)/2;\n  double *knots = NULL, *yy = NULL;\n  double dx;\n  int j, k;\n\n  if (period <= 0.0) err(\"must have period > 0\");\n  if (nbasis <= 0) err(\"must have nbasis > 0\");\n  if (degree < 0) err(\"must have degree >= 0\");\n  if (nbasis < degree) err(\"must have nbasis >= degree\");\n  if (deriv < 0) err(\"must have deriv >= 0\");\n\n  knots = (double *) R_Calloc(nknots+degree+1,double);\n  yy = (double *) R_Calloc(nknots,double);\n\n  dx = period/((double) nbasis);\n  for (k = -degree; k <= nbasis+degree; k++) {\n    knots[degree+k] = k*dx;\n  }\n  x = fmod(x,period);\n  if (x < 0.0) x += period;\n  for (k = 0; k < nknots; k++) {\n    bspline_eval(&yy[k],&x,1,k,degree,deriv,knots);\n  }\n  for (k = 0; k < degree; k++) yy[k] += yy[nbasis+k];\n  for (k = 0; k < nbasis; k++) {\n    j = (shift+k)%nbasis;\n    y[k] = yy[j];\n  }\n  R_Free(yy); R_Free(knots);\n}\n"
  },
  {
    "path": "src/decls.h",
    "content": "/* src/bspline.c */\nextern SEXP bspline_basis(SEXP, SEXP, SEXP, SEXP, SEXP);\nextern SEXP periodic_bspline_basis(SEXP, SEXP, SEXP, SEXP, SEXP);\nextern void bspline_basis_eval_deriv(double, double *, int, int, int, double *);\nextern void periodic_bspline_basis_eval_deriv(double, double, int, int, int, double *);\n/* src/dinit.c */\nextern SEXP do_dinit(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP);\n/* src/distributions.c */\nextern SEXP R_Euler_Multinom(SEXP, SEXP, SEXP, SEXP);\nextern SEXP D_Euler_Multinom(SEXP, SEXP, SEXP, SEXP, SEXP);\nextern SEXP E_Euler_Multinom(SEXP, SEXP, SEXP);\nextern SEXP R_GammaWN(SEXP, SEXP, SEXP);\nextern SEXP R_BetaBinom(SEXP, SEXP, SEXP, SEXP);\nextern SEXP D_BetaBinom(SEXP, SEXP, SEXP, SEXP, SEXP);\n/* src/dmeasure.c */\nextern SEXP do_dmeasure(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP);\n/* src/dprior.c */\nextern SEXP do_dprior(SEXP, SEXP, SEXP, SEXP);\n/* src/dprocess.c */\nextern SEXP do_dprocess(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP);\n/* src/emeasure.c */\nextern SEXP do_emeasure(SEXP, SEXP, SEXP, SEXP, SEXP);\n/* src/euler.c */\nextern SEXP euler_simulator(SEXP, SEXP, SEXP, SEXP, SEXP, double, rprocmode, SEXP, SEXP, SEXP, SEXP);\nextern int num_euler_steps(double, double, double *);\nextern int num_map_steps(double, double, double);\n/* src/gompertz.c */\nextern void _gompertz_normal_dmeasure(double *, double *, double *, double *, int, int *, int *, int *, int *, double *, double);\nextern void _gompertz_normal_rmeasure(double *, double *, double *, int *, int *, int *, int *, double *, double);\nextern void _gompertz_normal_emeasure(double *, double *, double *, int *, int *, int *, int *, double *, double);\nextern void _gompertz_normal_vmeasure(double *, double *, double *, int *, int *, int *, int *, double *, double);\nextern void _gompertz_step(double *, const double *, const int *, const int *, const int *, const double *, double, double);\nextern void _gompertz_skeleton(double *, double *, const double *, const int *, const int *, const int *, const double *, double);\nextern void _gompertz_to_trans(double *, const double *, const int *);\nextern void _gompertz_from_trans(double *, const double *, const int *);\n/* src/init.c */\nextern void R_init_pomp(DllInfo *);\n/* src/logmeanexp.c */\nextern SEXP logmeanexp(const SEXP, const SEXP);\n/* src/lookup_table.c */\nextern SEXP get_covariate_names(SEXP);\nextern lookup_table_t make_covariate_table(SEXP, int *);\nextern SEXP lookup_in_table(SEXP, SEXP);\nextern void table_lookup(lookup_table_t *, double, double *);\n/* src/mif2.c */\nextern SEXP randwalk_perturbation(SEXP, SEXP);\n/* src/ou2.c */\nextern void _ou2_step(double *, const double *, const int *, const int *, const int *, const double *, double, double);\nextern void _ou2_pdf(double *, double *, double *, double, double, const double *, const int *, const int *, const int *, const double *);\nextern void _ou2_skel(double *, double *, double *, int *, int *, int *, double *, double);\nextern void _ou2_dmeasure(double *, double *, double *, double *, int, int *, int *, int *, int *, double *, double);\nextern void _ou2_rmeasure(double *, double *, double *, int *, int *, int *, int *, double *, double);\nextern void _ou2_emeasure(double *, double *, double *, int *, int *, int *, int *, double *, double);\nextern void _ou2_vmeasure(double *, double *, double *, int *, int *, int *, int *, double *, double);\n/* src/partrans.c */\nextern SEXP do_partrans(SEXP, SEXP, SEXP, SEXP);\n/* src/pfilter.c */\nextern SEXP pfilter(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP);\n/* src/pomp_fun.c */\nextern SEXP pomp_fun_handler(SEXP, SEXP, pompfunmode *, SEXP, SEXP, SEXP, SEXP);\nextern SEXP load_stack_incr(SEXP);\nextern SEXP load_stack_decr(SEXP);\n/* src/probe.c */\nextern SEXP apply_probe_data(SEXP, SEXP);\nextern SEXP apply_probe_sim(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP);\n/* src/probe_acf.c */\nextern SEXP probe_acf(SEXP, SEXP, SEXP);\nextern SEXP probe_ccf(SEXP, SEXP, SEXP, SEXP);\n/* src/probe_marginal.c */\nextern SEXP probe_marginal_setup(SEXP, SEXP, SEXP);\nextern SEXP probe_marginal_solve(SEXP, SEXP, SEXP);\n/* src/probe_nlar.c */\nextern SEXP probe_nlar(SEXP, SEXP, SEXP);\n/* src/resample.c */\nextern SEXP systematic_resampling(SEXP, SEXP);\nextern void nosort_resamp(int, double *, int, int *, int);\n/* src/rinit.c */\nextern SEXP do_rinit(SEXP, SEXP, SEXP, SEXP, SEXP);\n/* src/rmeasure.c */\nextern SEXP do_rmeasure(SEXP, SEXP, SEXP, SEXP, SEXP);\n/* src/rprior.c */\nextern SEXP do_rprior(SEXP, SEXP, SEXP);\n/* src/rprocess.c */\nextern SEXP do_rprocess(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP);\n/* src/simulate.c */\nextern SEXP do_simulate(SEXP, SEXP, SEXP, SEXP, SEXP);\n/* src/skeleton.c */\nextern SEXP add_skel_args(SEXP, SEXP, SEXP, SEXP);\nextern void eval_skeleton_R(double *, double *, double *, double *, SEXP, SEXP, SEXP, int, int, int, int, int, int, int, lookup_table_t *, double *);\nextern void iterate_skeleton_R(double *, double, double, double *, double *, double *, SEXP, SEXP, SEXP, int, int, int, int, int, int, int, lookup_table_t *, int *, double *);\nextern void eval_skeleton_native(double *, double *, double *, double *, int, int, int, int, int, int, int, int *, int *, int *, lookup_table_t *, pomp_skeleton *, SEXP, double *);\nextern void iterate_skeleton_native(double *, double, double, double *, double *, double *, int, int, int, int, int, int, int, int *, int *, int *, lookup_table_t *, int *, pomp_skeleton *, SEXP, double *);\nextern SEXP do_skeleton(SEXP, SEXP, SEXP, SEXP, SEXP);\n/* src/sobolseq.c */\nextern SEXP sobol_sequence(SEXP, SEXP);\n/* src/ssa.c */\nextern SEXP SSA_simulator(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP);\n/* src/synth_lik.c */\nextern SEXP synth_loglik(SEXP, SEXP);\n/* src/trajectory.c */\nextern SEXP iterate_map(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP);\nextern SEXP pomp_desolve_setup(SEXP, SEXP, SEXP, SEXP);\nextern void pomp_vf_eval(int *, double *, double *, double *, double *, int *);\nextern SEXP pomp_desolve_takedown(void);\n/* src/transformations.c */\nextern SEXP LogitTransform(SEXP);\nextern SEXP ExpitTransform(SEXP);\nextern SEXP LogBarycentricTransform(SEXP);\nextern SEXP InverseLogBarycentricTransform(SEXP);\n/* src/userdata.c */\nextern SEXP set_pomp_userdata(SEXP);\nextern const SEXP get_userdata(const char *);\nextern const int *get_userdata_int(const char *);\nextern const double *get_userdata_double(const char *);\n/* src/vmeasure.c */\nextern SEXP do_vmeasure(SEXP, SEXP, SEXP, SEXP, SEXP);\n/* src/wpfilter.c */\nextern SEXP wpfilter(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP);\n"
  },
  {
    "path": "src/dinit.c",
    "content": "// dear emacs, please treat this as -*- C++ -*-\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n\n#include \"internal.h\"\n\nstatic R_INLINE SEXP add_args\n(\n SEXP args, SEXP Snames, SEXP Pnames, SEXP Cnames\n ) {\n\n  SEXP var;\n  int v;\n\n  PROTECT(args = VectorToPairList(args));\n\n  // Covariates\n  for (v = LENGTH(Cnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Cnames,v)));\n  }\n\n  // Parameters\n  for (v = LENGTH(Pnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Pnames,v)));\n  }\n\n  // Latent state variables\n  for (v = LENGTH(Snames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Snames,v)));\n  }\n\n  // Time\n  var = NEW_NUMERIC(1);\n  args = LCONS(var,args);\n  UNPROTECT(1);\n  PROTECT(args);\n  SET_TAG(args,install(\"t0\"));\n\n  UNPROTECT(1);\n  return args;\n\n}\n\nstatic R_INLINE SEXP eval_call\n(\n SEXP fn, SEXP args,\n double *t0,\n double *x, int nvar,\n double *p, int npar,\n double *c, int ncov\n ) {\n\n  SEXP var = args, ans, ob;\n  int v;\n\n  *(REAL(CAR(var))) = *t0; var = CDR(var);\n  for (v = 0; v < nvar; v++, x++) {\n    *(REAL(CAR(var))) = *x; var = CDR(var);\n  }\n  for (v = 0; v < npar; v++, p++, var=CDR(var)) *(REAL(CAR(var))) = *p;\n  for (v = 0; v < ncov; v++, c++, var=CDR(var)) *(REAL(CAR(var))) = *c;\n\n  PROTECT(ob = LCONS(fn,args));\n  PROTECT(ans = eval(ob,R_ClosureEnv(fn)));\n\n  UNPROTECT(2);\n  return ans;\n\n}\n\nstatic R_INLINE SEXP ret_array (int nreps)\n{\n  int dim[1] = {nreps};\n  const char *dimnm[1] = {\".id\"};\n  SEXP F;\n  PROTECT(F = makearray(1,dim));\n  fixdimnames(F,dimnm,1);\n  UNPROTECT(1);\n  return F;\n}\n\nstatic SEXP init_density\n(\n SEXP func, SEXP X, SEXP t0, SEXP params, SEXP covar,\n SEXP log, SEXP args, SEXP gnsi\n ) {\n\n  pompfunmode mode = undef;\n  int give_log;\n  int nvars, npars, nrepsx, nrepsp, nreps, ncovars;\n  SEXP Snames, Pnames, Cnames;\n  SEXP fn, ans;\n  SEXP F, cvec;\n  double *cov;\n  int *dim;\n\n  dim = INTEGER(GET_DIM(X)); nvars = dim[0]; nrepsx = dim[1];\n  dim = INTEGER(GET_DIM(params)); npars = dim[0]; nrepsp = dim[1];\n\n  give_log = *(INTEGER(AS_INTEGER(log)));\n\n  // handle case with different numbers of states and parameters\n  if (nrepsx != nrepsp && nrepsx % nrepsp != 0 && nrepsp % nrepsx != 0) {\n    err(\"the larger number of replicates is not a multiple of smaller.\");\n  } else {\n    nreps = (nrepsx > nrepsp) ? nrepsx : nrepsp;\n  }\n\n  PROTECT(Snames = GET_ROWNAMES(GET_DIMNAMES(X)));\n  PROTECT(Pnames = GET_ROWNAMES(GET_DIMNAMES(params)));\n  PROTECT(Cnames = get_covariate_names(covar));\n  PROTECT(F = ret_array(nreps));\n\n  // set up the covariate table\n  lookup_table_t covariate_table = make_covariate_table(covar,&ncovars);\n  PROTECT(cvec = NEW_NUMERIC(ncovars));\n  cov = REAL(cvec);\n\n  // process the pomp_fun\n  PROTECT(fn = pomp_fun_handler(func,gnsi,&mode,Snames,Pnames,NA_STRING,Cnames));\n\n  int nprotect = 6;\n\n  switch (mode) {\n\n  case Rfun: {\n\n    double *t = REAL(t0);\n    double *ft = REAL(F);\n\n    PROTECT(args = add_args(args,Snames,Pnames,Cnames)); nprotect++;\n\n    // interpolate the covariates at time t1\n    table_lookup(&covariate_table,*t,cov);\n\n    for (int j = 0; j < nreps; j++, ft++) {\n\n      double *xs = REAL(X)+nvars*(j%nrepsx);\n      double *ps = REAL(params)+npars*(j%nrepsp);\n\n      PROTECT(ans = eval_call(fn,args,t,xs,nvars,ps,npars,cov,ncovars));\n\n      *ft = *REAL(AS_NUMERIC(ans));\n\n      UNPROTECT(1);\n\n      if (!give_log) *ft = exp(*ft);\n\n    }\n\n\n  }\n\n    break;\n\n  case native: case regNative: {\n\n    int *sidx, *pidx, *cidx;\n    double *t = REAL(t0);\n    double *ft = REAL(F);\n    pomp_dinit *ff = NULL;\n\n    sidx = INTEGER(GET_SLOT(func,install(\"stateindex\")));\n    pidx = INTEGER(GET_SLOT(func,install(\"paramindex\")));\n    cidx = INTEGER(GET_SLOT(func,install(\"covarindex\")));\n\n    *((void **) (&ff)) = R_ExternalPtrAddr(fn);\n\n    // interpolate the covariates\n    table_lookup(&covariate_table,*t,cov);\n\n    for (int j = 0; j < nreps; j++, ft++) {\n\n      double *xs = REAL(X)+nvars*(j%nrepsx);\n      double *ps = REAL(params)+npars*(j%nrepsp);\n\n      (*ff)(ft,xs,ps,*t,sidx,pidx,cidx,cov);\n\n      if (!give_log) *ft = exp(*ft);\n\n    }\n\n  }\n\n    break;\n\n  default: {\n    double *ft = REAL(F);\n    int j;\n\n    for (j = 0; j < nreps; j++, ft++) { // loop over replicates\n      *ft = R_NaReal;\n    }\n\n    warn(\"'dinit' unspecified: likelihood undefined.\");\n\n  }\n\n  }\n\n  UNPROTECT(nprotect);\n  return F;\n}\n\nSEXP do_dinit\n(\n SEXP object, SEXP t0, SEXP x, SEXP params, SEXP log, SEXP gnsi\n ) {\n  SEXP F, fn, args, covar;\n  PROTECT(t0=AS_NUMERIC(t0));\n  PROTECT(x = as_matrix(x));\n  PROTECT(params = as_matrix(params));\n  // extract the process function\n  PROTECT(fn = GET_SLOT(object,install(\"dinit\")));\n  // extract other arguments\n  PROTECT(args = GET_SLOT(object,install(\"userdata\")));\n  PROTECT(covar = GET_SLOT(object,install(\"covar\")));\n  // evaluate the density\n  PROTECT(F = init_density(fn,x,t0,params,covar,log,args,gnsi));\n  UNPROTECT(7);\n  return F;\n}\n"
  },
  {
    "path": "src/distributions.c",
    "content": "#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n#include \"internal.h\"\n\nstatic void reulermultinom_multi (int m, int n, double *size, double *rate, double *deltat, double *trans) {\n  int k;\n  for (k = 0; k < n; k++) {\n    reulermultinom(m,*size,rate,*deltat,trans);\n    trans += m;\n  }\n}\n\nstatic void deulermultinom_multi (int m, int n, double *size, double *rate, double *deltat, double *trans, int *give_log, double *f) {\n  int k;\n  for (k = 0; k < n; k++) {\n    f[k] = deulermultinom(m,*size,rate,*deltat,trans,*give_log);\n    trans += m;\n  }\n}\n\nSEXP R_Euler_Multinom (SEXP n, SEXP size, SEXP rate, SEXP deltat) {\n  int ntrans = length(rate);\n  int dim[2];\n  SEXP x, nm;\n  if (length(size)>1)\n    warn(\"in 'reulermultinom': only the first element of 'size' is meaningful\");\n  if (length(deltat)>1)\n    warn(\"in 'reulermultinom': only the first element of 'dt' is meaningful\");\n  PROTECT(n = AS_INTEGER(n));\n  PROTECT(size = AS_NUMERIC(size));\n  PROTECT(rate = AS_NUMERIC(rate));\n  PROTECT(deltat = AS_NUMERIC(deltat));\n  dim[0] = ntrans;\n  dim[1] = *INTEGER(n);\n  if (dim[1] == NA_INTEGER || dim[1] < 0)\n    err(\"in 'reulermultinom': 'n' must be a non-negative integer.\");\n  PROTECT(x = makearray(2,dim));\n  PROTECT(nm = GET_NAMES(rate));\n  setrownames(x,nm,2);\n  GetRNGstate();\n  reulermultinom_multi(dim[0],dim[1],REAL(size),REAL(rate),REAL(deltat),REAL(x));\n  PutRNGstate();\n  UNPROTECT(6);\n  return x;\n}\n\nSEXP D_Euler_Multinom (SEXP x, SEXP size, SEXP rate, SEXP deltat, SEXP log) {\n  int ntrans = length(rate);\n  int *dim, n;\n  SEXP f;\n  dim = INTEGER(GET_DIM(x));\n  if (dim[0] != ntrans)\n    err(\"NROW('x') should match length of 'rate'\");\n  n = dim[1];\n  if (length(size)>1)\n    warn(\"in 'deulermultinom': only the first element of 'size' is meaningful\");\n  if (length(deltat)>1)\n    warn(\"in 'deulermultinom': only the first element of 'dt' is meaningful\");\n  PROTECT(f = NEW_NUMERIC(n));\n  PROTECT(size = AS_NUMERIC(size));\n  PROTECT(rate = AS_NUMERIC(rate));\n  PROTECT(deltat = AS_NUMERIC(deltat));\n  PROTECT(log = AS_LOGICAL(log));\n  deulermultinom_multi(ntrans,n,REAL(size),REAL(rate),REAL(deltat),REAL(x),INTEGER(log),REAL(f));\n  UNPROTECT(5);\n  return f;\n}\n\nSEXP E_Euler_Multinom (SEXP size, SEXP rate, SEXP deltat) {\n  int ntrans = length(rate);\n  SEXP x;\n  if (length(size)>1)\n    warn(\"in 'eeulermultinom': only the first element of 'size' is meaningful\");\n  if (length(deltat)>1)\n    warn(\"in 'eeulermultinom': only the first element of 'dt' is meaningful\");\n  PROTECT(size = AS_NUMERIC(size));\n  PROTECT(rate = AS_NUMERIC(rate));\n  PROTECT(deltat = AS_NUMERIC(deltat));\n  PROTECT(x = duplicate(rate));\n  eeulermultinom(ntrans,*REAL(size),REAL(rate),*REAL(deltat),REAL(x));\n  UNPROTECT(4);\n  return x;\n}\n\n// This function draws a random increment of a gamma whitenoise process.\n// This will have expectation=dt and variance=(sigma^2*dt)\n// If dW = rgammawn(sigma,dt), then\n// mu dW/dt is a candidate for a random rate process within an\n// Euler-multinomial context, i.e.,\n// E[mu*dW] = mu*dt and Var[mu*dW] = mu*sigma^2*dt\nSEXP R_GammaWN (SEXP n, SEXP sigma, SEXP deltat) {\n  int k, nval, nsig, ndt;\n  double *x, *sig, *dt;\n  SEXP ans;\n  PROTECT(n = AS_INTEGER(n));\n  nval = INTEGER(n)[0];\n  PROTECT(sigma = AS_NUMERIC(sigma));\n  nsig = LENGTH(sigma);\n  sig = REAL(sigma);\n  PROTECT(deltat = AS_NUMERIC(deltat));\n  ndt = LENGTH(deltat);\n  dt = REAL(deltat);\n  PROTECT(ans = NEW_NUMERIC(nval));\n  x = REAL(ans);\n  GetRNGstate();\n  for (k = 0; k < nval; k++) {\n    x[k] = rgammawn(sig[k%nsig],dt[k%ndt]);\n  }\n  PutRNGstate();\n  UNPROTECT(4);\n  return ans;\n}\n\n// This function draws a random variate from a beta-binomial distribution.\n// The binomial has size n and probability P ~ Beta(mu,theta).\n// That is, E[P] = mu and Var[P] =\nSEXP R_BetaBinom (SEXP n, SEXP size, SEXP prob, SEXP theta) {\n  int k, nval, ns, np, nt;\n  double *X, *S, *P, *T;\n  SEXP ans;\n  PROTECT(n = AS_INTEGER(n)); nval = INTEGER(n)[0];\n  PROTECT(size = AS_NUMERIC(size)); ns = LENGTH(size); S = REAL(size);\n  PROTECT(prob = AS_NUMERIC(prob)); np = LENGTH(prob); P = REAL(prob);\n  PROTECT(theta = AS_NUMERIC(theta)); nt = LENGTH(theta); T = REAL(theta);\n  PROTECT(ans = NEW_NUMERIC(nval)); X = REAL(ans);\n  GetRNGstate();\n  for (k = 0; k < nval; k++) {\n    X[k] = rbetabinom(S[k%ns],P[k%np],T[k%nt]);\n  }\n  PutRNGstate();\n  UNPROTECT(5);\n  return ans;\n}\n\nSEXP D_BetaBinom (SEXP x, SEXP size, SEXP prob, SEXP theta, SEXP log) {\n  int k, n, nx, ns, np, nt;\n  double *F, *X, *S, *P, *T;\n  SEXP f;\n  PROTECT(x = AS_NUMERIC(x)); nx = LENGTH(x); X = REAL(x);\n  PROTECT(size = AS_NUMERIC(size)); ns = LENGTH(size); S = REAL(size);\n  PROTECT(prob = AS_NUMERIC(prob)); np = LENGTH(prob); P = REAL(prob);\n  PROTECT(theta = AS_NUMERIC(theta)); nt = LENGTH(theta); T = REAL(theta);\n  PROTECT(log = AS_INTEGER(log));\n  n = (nx > ns) ? nx : ns;\n  n = (n > np) ? n : np;\n  n = (n > nt) ? n : nt;\n  PROTECT(f = NEW_NUMERIC(n)); F = REAL(f);\n  for (k = 0; k < n; k++) {\n    F[k] = dbetabinom(X[k%nx],S[k%ns],P[k%np],T[k%nt],INTEGER(log)[0]);\n  }\n  UNPROTECT(6);\n  return f;\n}\n"
  },
  {
    "path": "src/dmeasure.c",
    "content": "// dear emacs, please treat this as -*- C++ -*-\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n\n#include \"internal.h\"\n\nstatic R_INLINE SEXP add_args\n(\n SEXP args, SEXP Onames, SEXP Snames,\n SEXP Pnames, SEXP Cnames, SEXP log\n ) {\n  SEXP var;\n  int v;\n\n  // we construct the call from end to beginning\n  // 'log', covariates, parameter, states, observables, then time\n\n  // 'log' is a needed argument\n  PROTECT(log = AS_LOGICAL(log));\n  PROTECT(args = VectorToPairList(args));\n  PROTECT(args = LCONS(log,args));\n  SET_TAG(args,install(\"log\"));\n\n  // Covariates\n  for (v = LENGTH(Cnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Cnames,v)));\n  }\n\n  // Parameters\n  for (v = LENGTH(Pnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Pnames,v)));\n  }\n\n  // Latent state variables\n  for (v = LENGTH(Snames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Snames,v)));\n  }\n\n  // Observables\n  for (v = LENGTH(Onames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Onames,v)));\n  }\n\n  // Time\n  var = NEW_NUMERIC(1);\n  args = LCONS(var,args);\n  UNPROTECT(1);\n  PROTECT(args);\n  SET_TAG(args,install(\"t\"));\n\n  UNPROTECT(3);\n  return args;\n\n}\n\nstatic R_INLINE SEXP eval_call (\n                                SEXP fn, SEXP args,\n                                double *t,\n                                double *y, int nobs,\n                                double *x, int nvar,\n                                double *p, int npar,\n                                double *c, int ncov)\n{\n\n  SEXP var = args, ans, ob;\n  int v;\n\n  *(REAL(CAR(var))) = *t; var = CDR(var);\n  for (v = 0; v < nobs; v++, y++, var=CDR(var)) *(REAL(CAR(var))) = *y;\n  for (v = 0; v < nvar; v++, x++, var=CDR(var)) *(REAL(CAR(var))) = *x;\n  for (v = 0; v < npar; v++, p++, var=CDR(var)) *(REAL(CAR(var))) = *p;\n  for (v = 0; v < ncov; v++, c++, var=CDR(var)) *(REAL(CAR(var))) = *c;\n\n  PROTECT(ob = LCONS(fn,args));\n  PROTECT(ans = eval(ob,R_ClosureEnv(fn)));\n\n  UNPROTECT(2);\n  return ans;\n\n}\n\nstatic R_INLINE SEXP ret_array (int nreps, int ntimes) {\n  int dim[2] = {nreps, ntimes};\n  const char *dimnm[2] = {\".id\",\"time\"};\n  SEXP F;\n  PROTECT(F = makearray(2,dim));\n  fixdimnames(F,dimnm,2);\n  UNPROTECT(1);\n  return F;\n}\n\nSEXP do_dmeasure (SEXP object, SEXP y, SEXP x, SEXP times, SEXP params, SEXP log, SEXP gnsi)\n{\n\n  pompfunmode mode = undef;\n  int ntimes, nvars, npars, ncovars, nreps, nrepsx, nrepsp, nobs;\n  SEXP Snames, Pnames, Cnames, Onames;\n  SEXP cvec, pompfun;\n  SEXP fn, args, ans;\n  SEXP F;\n  int *dim;\n  lookup_table_t covariate_table;\n  double *cov;\n\n  PROTECT(times = AS_NUMERIC(times));\n  ntimes = length(times);\n  if (ntimes < 1) err(\"length('times') = 0, no work to do.\");\n\n  PROTECT(y = as_matrix(y));\n  dim = INTEGER(GET_DIM(y));\n  nobs = dim[0];\n\n  if (ntimes != dim[1])\n    err(\"length of 'times' and 2nd dimension of 'y' do not agree.\");\n\n  PROTECT(x = as_state_array(x));\n  dim = INTEGER(GET_DIM(x));\n  nvars = dim[0]; nrepsx = dim[1];\n\n  if (ntimes != dim[2])\n    err(\"length of 'times' and 3rd dimension of 'x' do not agree.\");\n\n  PROTECT(params = as_matrix(params));\n  dim = INTEGER(GET_DIM(params));\n  npars = dim[0]; nrepsp = dim[1];\n\n  nreps = (nrepsp > nrepsx) ? nrepsp : nrepsx;\n\n  if ((nreps % nrepsp != 0) || (nreps % nrepsx != 0))\n    err(\"larger number of replicates is not a multiple of smaller.\");\n\n  PROTECT(Onames = GET_ROWNAMES(GET_DIMNAMES(y)));\n  PROTECT(Snames = GET_ROWNAMES(GET_DIMNAMES(x)));\n  PROTECT(Pnames = GET_ROWNAMES(GET_DIMNAMES(params)));\n  PROTECT(Cnames = get_covariate_names(GET_SLOT(object,install(\"covar\"))));\n\n  // set up the covariate table\n  covariate_table = make_covariate_table(GET_SLOT(object,install(\"covar\")),&ncovars);\n  PROTECT(cvec = NEW_NUMERIC(ncovars));\n  cov = REAL(cvec);\n\n  // extract the user-defined function\n  PROTECT(pompfun = GET_SLOT(object,install(\"dmeasure\")));\n  PROTECT(fn = pomp_fun_handler(pompfun,gnsi,&mode,Snames,Pnames,Onames,Cnames));\n\n  // extract 'userdata' as pairlist\n  PROTECT(args = GET_SLOT(object,install(\"userdata\")));\n\n  // create array to store results\n  PROTECT(F = ret_array(nreps,ntimes));\n\n  int nprotect = 13;\n\n  switch (mode) {\n\n  case Rfun: {\n\n    double *ys = REAL(y), *xs = REAL(x), *ps = REAL(params), *time = REAL(times);\n    double *ft = REAL(F);\n    int j, k;\n\n    // build argument list\n    PROTECT(args = add_args(args,Onames,Snames,Pnames,Cnames,log)); nprotect++;\n\n    for (k = 0; k < ntimes; k++, time++, ys += nobs) { // loop over times\n\n      R_CheckUserInterrupt();   // check for user interrupt\n\n      table_lookup(&covariate_table,*time,cov); // interpolate the covariates\n\n      for (j = 0; j < nreps; j++, ft++) { // loop over replicates\n\n        // evaluate the call\n        PROTECT(\n                ans = eval_call(\n                                fn,args,\n                                time,\n                                ys,nobs,\n                                xs+nvars*((j%nrepsx)+nrepsx*k),nvars,\n                                ps+npars*(j%nrepsp),npars,\n                                cov,ncovars\n                                )\n                );\n\n        if (k == 0 && j == 0 && LENGTH(ans) != 1)\n          err(\"user 'dmeasure' returns a vector of length %d when it should return a scalar.\",LENGTH(ans));\n\n        *ft = *(REAL(AS_NUMERIC(ans)));\n\n        UNPROTECT(1);\n\n      }\n    }\n  }\n\n    break;\n\n  case native: case regNative: {\n    int *oidx, *sidx, *pidx, *cidx;\n    int give_log;\n    pomp_dmeasure *ff = NULL;\n    double *yp = REAL(y), *xs = REAL(x), *ps = REAL(params), *time = REAL(times);\n    double *ft = REAL(F);\n    double *xp, *pp;\n    int j, k;\n\n    // extract state, parameter, covariate, observable indices\n    sidx = INTEGER(GET_SLOT(pompfun,install(\"stateindex\")));\n    pidx = INTEGER(GET_SLOT(pompfun,install(\"paramindex\")));\n    oidx = INTEGER(GET_SLOT(pompfun,install(\"obsindex\")));\n    cidx = INTEGER(GET_SLOT(pompfun,install(\"covarindex\")));\n\n    give_log = *(INTEGER(AS_INTEGER(log)));\n\n    // address of native routine\n    *((void **) (&ff)) = R_ExternalPtrAddr(fn);\n\n    for (k = 0; k < ntimes; k++, time++, yp += nobs) { // loop over times\n\n      R_CheckUserInterrupt();   // check for user interrupt\n\n      // interpolate the covar functions for the covariates\n      table_lookup(&covariate_table,*time,cov);\n\n      for (j = 0; j < nreps; j++, ft++) { // loop over replicates\n\n        xp = &xs[nvars*((j%nrepsx)+nrepsx*k)];\n        pp = &ps[npars*(j%nrepsp)];\n\n        (*ff)(ft,yp,xp,pp,give_log,oidx,sidx,pidx,cidx,cov,*time);\n\n      }\n    }\n\n  }\n\n    break;\n\n  default: {\n    double *ft = REAL(F);\n    int j, k;\n\n    for (k = 0; k < ntimes; k++) { // loop over times\n      for (j = 0; j < nreps; j++, ft++) { // loop over replicates\n        *ft = R_NaReal;\n      }\n    }\n\n    warn(\"'dmeasure' unspecified: likelihood undefined.\");\n\n  }\n\n  }\n\n  UNPROTECT(nprotect);\n  return F;\n}\n"
  },
  {
    "path": "src/dprior.c",
    "content": "// dear emacs, please treat this as -*- C++ -*-\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n\n#include \"internal.h\"\n\nstatic R_INLINE SEXP add_args (SEXP names, SEXP log, SEXP args)\n{\n\n  SEXP var;\n  int v;\n\n  PROTECT(log = AS_LOGICAL(log));\n  PROTECT(args = VectorToPairList(args));\n  PROTECT(args = LCONS(log,args));\n  SET_TAG(args,install(\"log\"));\n\n  for (v = LENGTH(names)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(names,v)));\n  }\n\n  UNPROTECT(3);\n  return args;\n\n}\n\nstatic R_INLINE SEXP eval_call (SEXP fn, SEXP args, double *p, int n)\n{\n\n  SEXP var = args, ans, ob;\n  int v;\n\n  for (v = 0; v < n; v++, p++, var=CDR(var))\n    *(REAL(CAR(var))) = *p;\n\n  PROTECT(ob = LCONS(fn,args));\n  PROTECT(ans = eval(ob,R_ClosureEnv(fn)));\n\n  UNPROTECT(2);\n  return ans;\n\n}\n\nSEXP do_dprior (SEXP object, SEXP params, SEXP log, SEXP gnsi)\n{\n\n  pompfunmode mode = undef;\n  int npars, nreps;\n  SEXP Pnames, pompfun, fn, args, F;\n  int *dim;\n\n  PROTECT(params = as_matrix(params));\n  dim = INTEGER(GET_DIM(params));\n  npars = dim[0]; nreps = dim[1];\n\n  PROTECT(Pnames = GET_ROWNAMES(GET_DIMNAMES(params)));\n\n  // extract the user-defined function\n  PROTECT(pompfun = GET_SLOT(object,install(\"dprior\")));\n  PROTECT(fn = pomp_fun_handler(pompfun,gnsi,&mode,NA_STRING,Pnames,NA_STRING,NA_STRING));\n\n  // extract 'userdata' as pairlist\n  PROTECT(args = GET_SLOT(object,install(\"userdata\")));\n\n  // to store results\n  PROTECT(F = NEW_NUMERIC(nreps));\n\n  int nprotect = 6;\n\n  switch (mode) {\n  case Rfun: {\n    SEXP ans;\n    double *ps, *pt;\n    int j;\n\n    PROTECT(args = add_args(Pnames,log,args)); nprotect++;\n\n    for (j = 0, ps = REAL(params), pt = REAL(F); j < nreps; j++, ps += npars, pt++) {\n\n      PROTECT(ans = eval_call(fn,args,ps,npars));\n      *pt = *(REAL(AS_NUMERIC(ans)));\n      UNPROTECT(1);\n\n    }\n  }\n\n    break;\n\n  case native: case regNative: {\n    int give_log, *pidx = 0;\n    pomp_dprior *ff = NULL;\n    double *ps, *pt;\n    int j;\n\n    // construct state, parameter, covariate, observable indices\n    pidx = INTEGER(GET_SLOT(pompfun,install(\"paramindex\")));\n\n    // address of native routine\n    *((void **) (&ff)) = R_ExternalPtrAddr(fn);\n\n    give_log = *(INTEGER(AS_INTEGER(log)));\n\n    R_CheckUserInterrupt();     // check for user interrupt\n\n    // loop over replicates\n    for (j = 0, pt = REAL(F), ps = REAL(params); j < nreps; j++, ps += npars, pt++)\n      (*ff)(pt,ps,give_log,pidx);\n\n  }\n\n    break;\n\n  default: {\n    int give_log, j;\n    double *pt;\n\n    give_log = *(INTEGER(AS_INTEGER(log)));\n\n    // loop over replicates\n    for (j = 0, pt = REAL(F); j < nreps; j++, pt++)\n      *pt = (give_log) ? 0.0 : 1.0;\n\n  }\n\n  }\n\n  UNPROTECT(nprotect);\n  return F;\n}\n"
  },
  {
    "path": "src/dprocess.c",
    "content": "// dear emacs, please treat this as -*- C++ -*-\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n\n#include \"internal.h\"\n\nstatic R_INLINE SEXP paste0 (SEXP a, SEXP b) {\n  SEXP p, v;\n  PROTECT(p = lang3(install(\"paste0\"),a,b));\n  PROTECT(v = eval(p,R_BaseEnv));\n  UNPROTECT(2);\n  return v;\n}\n\nstatic R_INLINE SEXP add_args (SEXP args, SEXP Snames, SEXP Pnames, SEXP Cnames)\n{\n\n  SEXP S1names, S2names;\n  SEXP s1, s2;\n  SEXP var;\n  int v;\n\n  PROTECT(s1 = mkString(\"_1\"));\n  PROTECT(s2 = mkString(\"_2\"));\n  PROTECT(S1names = paste0(Snames,s1));\n  PROTECT(S2names = paste0(Snames,s2));\n\n  PROTECT(args = VectorToPairList(args));\n\n  // Covariates\n  for (v = LENGTH(Cnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Cnames,v)));\n  }\n\n  // Parameters\n  for (v = LENGTH(Pnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Pnames,v)));\n  }\n\n  // Latent state variables\n  for (v = LENGTH(Snames)-1; v >= 0; v--) {\n\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(S2names,v)));\n\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(S1names,v)));\n\n  }\n\n  // Time\n  var = NEW_NUMERIC(1);\n  args = LCONS(var,args);\n  UNPROTECT(1);\n  PROTECT(args);\n  SET_TAG(args,install(\"t_2\"));\n\n  var = NEW_NUMERIC(1);\n  args = LCONS(var,args);\n  UNPROTECT(1);\n  PROTECT(args);\n  SET_TAG(args,install(\"t_1\"));\n\n  UNPROTECT(5);\n  return args;\n\n}\n\nstatic R_INLINE SEXP eval_call\n(\n SEXP fn, SEXP args,\n double *t1, double *t2,\n double *x1, double *x2, int nvar,\n double *p, int npar,\n double *c, int ncov\n ) {\n\n  SEXP var = args, ans, ob;\n  int v;\n\n  *(REAL(CAR(var))) = *t1; var = CDR(var);\n  *(REAL(CAR(var))) = *t2; var = CDR(var);\n  for (v = 0; v < nvar; v++, x1++, x2++) {\n    *(REAL(CAR(var))) = *x1; var = CDR(var);\n    *(REAL(CAR(var))) = *x2; var = CDR(var);\n  }\n  for (v = 0; v < npar; v++, p++, var=CDR(var)) *(REAL(CAR(var))) = *p;\n  for (v = 0; v < ncov; v++, c++, var=CDR(var)) *(REAL(CAR(var))) = *c;\n\n  PROTECT(ob = LCONS(fn,args));\n  PROTECT(ans = eval(ob,R_ClosureEnv(fn)));\n\n  UNPROTECT(2);\n  return ans;\n\n}\n\nstatic R_INLINE SEXP ret_array (int nreps, int ntimes)\n{\n  int dim[2] = {nreps, ntimes};\n  const char *dimnm[2] = {\".id\",\"time\"};\n  SEXP F;\n  PROTECT(F = makearray(2,dim));\n  fixdimnames(F,dimnm,2);\n  UNPROTECT(1);\n  return F;\n}\n\n// compute pdf of a sequence of elementary steps\nstatic SEXP onestep_density\n(\n SEXP func, SEXP x, SEXP times, SEXP params, SEXP covar,\n SEXP log, SEXP args, SEXP gnsi\n ) {\n\n  pompfunmode mode = undef;\n  int give_log;\n  int nvars, npars, nrepsx, nrepsp, nreps, ntimes, ncovars;\n  SEXP Snames, Pnames, Cnames;\n  SEXP fn, ans;\n  SEXP F, cvec;\n  double *cov;\n  int *dim;\n\n  ntimes = LENGTH(times);\n  dim = INTEGER(GET_DIM(x)); nvars = dim[0]; nrepsx = dim[1];\n  if (ntimes < 2)\n    err(\"length(times) < 2: with no transitions, there is no work to do.\");\n  if (ntimes != dim[2])\n    err(\"the length of 'times' and 3rd dimension of 'x' do not agree.\");\n  dim = INTEGER(GET_DIM(params)); npars = dim[0]; nrepsp = dim[1];\n\n  give_log = *(INTEGER(AS_INTEGER(log)));\n\n  // handle case with different numbers of states and parameters\n  if (nrepsx != nrepsp && nrepsx % nrepsp != 0 && nrepsp % nrepsx != 0) {\n    err(\"the larger number of replicates is not a multiple of smaller.\");\n  } else {\n    nreps = (nrepsx > nrepsp) ? nrepsx : nrepsp;\n  }\n\n  PROTECT(Snames = GET_ROWNAMES(GET_DIMNAMES(x)));\n  PROTECT(Pnames = GET_ROWNAMES(GET_DIMNAMES(params)));\n  PROTECT(Cnames = get_covariate_names(covar));\n\n  PROTECT(F = ret_array(nreps,ntimes-1));\n\n  // set up the covariate table\n  lookup_table_t covariate_table = make_covariate_table(covar,&ncovars);\n  PROTECT(cvec = NEW_NUMERIC(ncovars));\n  cov = REAL(cvec);\n\n  PROTECT(fn = pomp_fun_handler(func,gnsi,&mode,Snames,Pnames,NA_STRING,Cnames));\n\n  int nprotect = 6;\n  double *t1 = REAL(times), *t2 = REAL(times)+1;\n  double *x1p = REAL(x);\n  double *x2p = REAL(x)+nrepsx*nvars;\n  double *ft = REAL(F);\n\n  switch (mode) {\n\n  case Rfun: {\n\n    PROTECT(args = add_args(args,Snames,Pnames,Cnames)); nprotect++;\n\n    for (int k = 0; k < ntimes-1; k++, t1++, t2++) { // loop over times\n\n      R_CheckUserInterrupt();\n\n      // interpolate the covariates at time t1\n      table_lookup(&covariate_table,*t1,cov);\n\n      for (int j = 0; j < nreps; j++, ft++) {\n\n        double *p = REAL(params)+npars*(j%nrepsp);\n        double *x1 = x1p+nvars*(j%nrepsx);\n        double *x2 = x2p+nvars*(j%nrepsx);\n\n        PROTECT(ans = eval_call(fn,args,t1,t2,x1,x2,nvars,p,npars,cov,ncovars));\n        *ft = *REAL(AS_NUMERIC(ans));\n        UNPROTECT(1);\n\n        if (!give_log) *ft = exp(*ft);\n\n      }\n\n      x1p = x2p;\n      x2p += nrepsx*nvars;\n\n    }\n\n  }\n\n    break;\n\n  case native: case regNative: {\n\n    int *sidx, *pidx, *cidx;\n    pomp_dprocess *ff = NULL;\n\n    sidx = INTEGER(GET_SLOT(func,install(\"stateindex\")));\n    pidx = INTEGER(GET_SLOT(func,install(\"paramindex\")));\n    cidx = INTEGER(GET_SLOT(func,install(\"covarindex\")));\n\n    *((void **) (&ff)) = R_ExternalPtrAddr(fn);\n\n    for (int k = 0; k < ntimes-1; k++, t1++, t2++) {\n\n      R_CheckUserInterrupt();\n\n      // interpolate the covariates at time t1\n      table_lookup(&covariate_table,*t1,cov);\n\n      for (int j = 0; j < nreps; j++, ft++) {\n\n        double *p = REAL(params)+npars*(j%nrepsp);\n        double *x1 = x1p+nvars*(j%nrepsx);\n        double *x2 = x2p+nvars*(j%nrepsx);\n\n        (*ff)(ft,x1,x2,*t1,*t2,p,sidx,pidx,cidx,cov);\n\n        if (!give_log) *ft = exp(*ft);\n\n      }\n\n      x1p = x2p;\n      x2p += nrepsx*nvars;\n\n    }\n\n  }\n\n    break;\n\n  default: {\n    double *ft = REAL(F);\n    int j, k;\n\n    for (k = 0; k < ntimes-1; k++) { // loop over times\n      for (j = 0; j < nreps; j++, ft++) { // loop over replicates\n        *ft = R_NaReal;\n      }\n    }\n\n    warn(\"'dprocess' unspecified: likelihood undefined.\");\n\n  }\n\n  }\n\n  UNPROTECT(nprotect);\n  return F;\n}\n\nSEXP do_dprocess (SEXP object, SEXP x, SEXP times, SEXP params, SEXP log, SEXP gnsi)\n{\n  SEXP X, fn, args, covar;\n  PROTECT(times=AS_NUMERIC(times));\n  PROTECT(x = as_state_array(x));\n  PROTECT(params = as_matrix(params));\n  // extract the process function\n  PROTECT(fn = GET_SLOT(object,install(\"dprocess\")));\n  // extract other arguments\n  PROTECT(args = GET_SLOT(object,install(\"userdata\")));\n  PROTECT(covar = GET_SLOT(object,install(\"covar\")));\n  // evaluate the density\n  PROTECT(X = onestep_density(fn,x,times,params,covar,log,args,gnsi));\n  UNPROTECT(7);\n  return X;\n}\n"
  },
  {
    "path": "src/emeasure.c",
    "content": "// dear emacs, please treat this as -*- C++ -*-\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n\n#include \"internal.h\"\n\nstatic R_INLINE SEXP add_args (SEXP args, SEXP Snames, SEXP Pnames, SEXP Cnames)\n{\n\n  SEXP var;\n  int v;\n\n  PROTECT(args = VectorToPairList(args));\n\n  // we construct the call from end to beginning\n  // covariates, parameter, states, then time\n\n  // Covariates\n  for (v = LENGTH(Cnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Cnames,v)));\n  }\n\n  // Parameters\n  for (v = LENGTH(Pnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Pnames,v)));\n  }\n\n  // Latent state variables\n  for (v = LENGTH(Snames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Snames,v)));\n  }\n\n  // Time\n  var = NEW_NUMERIC(1);\n  args = LCONS(var,args);\n  UNPROTECT(1);\n  PROTECT(args);\n  SET_TAG(args,install(\"t\"));\n\n  UNPROTECT(1);\n  return args;\n\n}\n\nstatic R_INLINE SEXP eval_call (\n                                SEXP fn, SEXP args,\n                                double *t,\n                                double *x, int nvar,\n                                double *p, int npar,\n                                double *c, int ncov)\n{\n\n  SEXP var = args, ans, ob;\n  int v;\n\n  *(REAL(CAR(var))) = *t; var = CDR(var);\n  for (v = 0; v < nvar; v++, x++, var=CDR(var)) *(REAL(CAR(var))) = *x;\n  for (v = 0; v < npar; v++, p++, var=CDR(var)) *(REAL(CAR(var))) = *p;\n  for (v = 0; v < ncov; v++, c++, var=CDR(var)) *(REAL(CAR(var))) = *c;\n\n  PROTECT(ob = LCONS(fn,args));\n  PROTECT(ans = eval(ob,R_ClosureEnv(fn)));\n\n  UNPROTECT(2);\n  return ans;\n\n}\n\nstatic R_INLINE SEXP ret_array (int n, int nreps, int ntimes, SEXP names) {\n  int dim[3] = {n, nreps, ntimes};\n  const char *dimnm[3] = {\"name\", \".id\", \"time\"};\n  SEXP Y;\n\n  PROTECT(Y = makearray(3,dim));\n  setrownames(Y,names,3);\n  fixdimnames(Y,dimnm,3);\n\n  UNPROTECT(1);\n  return Y;\n\n}\n\nSEXP do_emeasure (SEXP object, SEXP x, SEXP times, SEXP params, SEXP gnsi)\n{\n  pompfunmode mode = undef;\n  int ntimes, nvars, npars, ncovars, nreps, nrepsx, nrepsp;\n  int nobs = 0;\n  SEXP Snames, Pnames, Cnames, Onames = R_NilValue;\n  SEXP fn, args;\n  SEXP pompfun;\n  SEXP Y = R_NilValue;\n  int *dim;\n  lookup_table_t covariate_table;\n  SEXP cvec;\n  double *cov;\n\n  PROTECT(times = AS_NUMERIC(times));\n  ntimes = length(times);\n  if (ntimes < 1)\n    err(\"length('times') = 0, no work to do.\");\n\n  PROTECT(x = as_state_array(x));\n  dim = INTEGER(GET_DIM(x));\n  nvars = dim[0]; nrepsx = dim[1];\n\n  if (ntimes != dim[2])\n    err(\"length of 'times' and 3rd dimension of 'x' do not agree.\");\n\n  PROTECT(params = as_matrix(params));\n  dim = INTEGER(GET_DIM(params));\n  npars = dim[0]; nrepsp = dim[1];\n\n  nreps = (nrepsp > nrepsx) ? nrepsp : nrepsx;\n\n  if ((nreps % nrepsp != 0) || (nreps % nrepsx != 0))\n    err(\"larger number of replicates is not a multiple of smaller.\");\n\n  PROTECT(pompfun = GET_SLOT(object,install(\"emeasure\")));\n\n  PROTECT(Snames = GET_ROWNAMES(GET_DIMNAMES(x)));\n  PROTECT(Pnames = GET_ROWNAMES(GET_DIMNAMES(params)));\n  PROTECT(Cnames = get_covariate_names(GET_SLOT(object,install(\"covar\"))));\n  PROTECT(Onames = GET_SLOT(pompfun,install(\"obsnames\")));\n\n  // set up the covariate table\n  covariate_table = make_covariate_table(GET_SLOT(object,install(\"covar\")),&ncovars);\n  PROTECT(cvec = NEW_NUMERIC(ncovars));\n  cov = REAL(cvec);\n\n  // extract the user-defined function\n  PROTECT(fn = pomp_fun_handler(pompfun,gnsi,&mode,Snames,Pnames,Onames,Cnames));\n\n  // extract 'userdata' as pairlist\n  PROTECT(args = GET_SLOT(object,install(\"userdata\")));\n\n  int nprotect = 11;\n  int first = 1;\n\n  // first do setup\n  switch (mode) {\n\n  case Rfun: {\n    double *ys, *yt = 0;\n    double *time = REAL(times), *xs = REAL(x), *ps = REAL(params);\n    SEXP ans;\n    int j, k;\n\n    PROTECT(args = add_args(args,Snames,Pnames,Cnames)); nprotect++;\n\n    for (k = 0; k < ntimes; k++, time++) { // loop over times\n\n      R_CheckUserInterrupt();   // check for user interrupt\n\n      table_lookup(&covariate_table,*time,cov); // interpolate the covariates\n\n      for (j = 0; j < nreps; j++) { // loop over replicates\n\n        if (first) {\n\n          PROTECT(\n                  ans = eval_call(\n                                  fn,args,\n                                  time,\n                                  xs+nvars*((j%nrepsx)+nrepsx*k),nvars,\n                                  ps+npars*(j%nrepsp),npars,\n                                  cov,ncovars\n                                  )\n                  );\n\n          nobs = LENGTH(ans);\n\n          PROTECT(Onames = GET_NAMES(ans));\n          if (invalid_names(Onames))\n            err(\"'emeasure' must return a named numeric vector.\");\n\n          PROTECT(Y = ret_array(nobs,nreps,ntimes,Onames));\n\n          nprotect += 3;\n\n          yt = REAL(Y);\n          ys = REAL(AS_NUMERIC(ans));\n\n          memcpy(yt,ys,nobs*sizeof(double));\n          yt += nobs;\n\n          first = 0;\n\n        } else {\n\n          PROTECT(\n                  ans = eval_call(\n                                  fn,args,\n                                  time,\n                                  xs+nvars*((j%nrepsx)+nrepsx*k),nvars,\n                                  ps+npars*(j%nrepsp),npars,\n                                  cov,ncovars\n                                  )\n                  );\n\n          if (LENGTH(ans) != nobs)\n            err(\"'emeasure' returns variable-length results.\");\n\n          ys = REAL(AS_NUMERIC(ans));\n\n          memcpy(yt,ys,nobs*sizeof(double));\n          yt += nobs;\n\n          UNPROTECT(1);\n\n        }\n\n      }\n    }\n\n  }\n\n    break;\n\n  case native: case regNative: {\n    double *yt = 0, *xp, *pp;\n    double *time = REAL(times), *xs = REAL(x), *ps = REAL(params);\n    int *oidx, *sidx, *pidx, *cidx;\n    pomp_emeasure *ff = NULL;\n    int j, k;\n\n    nobs = LENGTH(Onames);\n    // extract observable, state, parameter covariate indices\n    sidx = INTEGER(GET_SLOT(pompfun,install(\"stateindex\")));\n    pidx = INTEGER(GET_SLOT(pompfun,install(\"paramindex\")));\n    oidx = INTEGER(GET_SLOT(pompfun,install(\"obsindex\")));\n    cidx = INTEGER(GET_SLOT(pompfun,install(\"covarindex\")));\n\n    // address of native routine\n    *((void **) (&ff)) = R_ExternalPtrAddr(fn);\n\n    PROTECT(Y = ret_array(nobs,nreps,ntimes,Onames)); nprotect++;\n    yt = REAL(Y);\n\n    for (k = 0; k < ntimes; k++, time++) { // loop over times\n\n      R_CheckUserInterrupt();   // check for user interrupt\n\n      // interpolate the covar functions for the covariates\n      table_lookup(&covariate_table,*time,cov);\n\n      for (j = 0; j < nreps; j++, yt += nobs) { // loop over replicates\n\n        xp = &xs[nvars*((j%nrepsx)+nrepsx*k)];\n        pp = &ps[npars*(j%nrepsp)];\n\n        (*ff)(yt,xp,pp,oidx,sidx,pidx,cidx,cov,*time);\n\n      }\n    }\n\n  }\n\n    break;\n\n  default: {\n    nobs = LENGTH(Onames);\n    int dim[3] = {nobs, nreps, ntimes};\n    const char *dimnm[3] = {\"name\",\".id\",\"time\"};\n    double *yt = 0;\n    int i, n = nobs*nreps*ntimes;\n\n    PROTECT(Y = makearray(3,dim)); nprotect++;\n    setrownames(Y,Onames,3);\n    fixdimnames(Y,dimnm,3);\n\n    for (i = 0, yt = REAL(Y); i < n; i++, yt++) *yt = R_NaReal;\n\n    warn(\"'emeasure' unspecified: NAs generated.\");\n  }\n\n  }\n\n  UNPROTECT(nprotect);\n  return Y;\n}\n"
  },
  {
    "path": "src/euler.c",
    "content": "// -*- C++ -*-\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n\n#include \"internal.h\"\n\nstatic R_INLINE SEXP add_args (SEXP args, SEXP Snames, SEXP Pnames, SEXP Cnames)\n{\n\n  SEXP var;\n  int v;\n\n  PROTECT(args = VectorToPairList(args));\n\n  // we construct the call from end to beginning\n  // delta.t, covariates, parameter, states, then time\n\n  // 'delta.t'\n  var = NEW_NUMERIC(1);\n  args = LCONS(var,args);\n  UNPROTECT(1);\n  PROTECT(args);\n  SET_TAG(args,install(\"delta.t\"));\n\n  // Covariates\n  for (v = LENGTH(Cnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Cnames,v)));\n  }\n\n  // Parameters\n  for (v = LENGTH(Pnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Pnames,v)));\n  }\n\n  // Latent state variables\n  for (v = LENGTH(Snames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Snames,v)));\n  }\n\n  // Time\n  var = NEW_NUMERIC(1);\n  args = LCONS(var,args);\n  UNPROTECT(1);\n  PROTECT(args);\n  SET_TAG(args,install(\"t\"));\n\n  UNPROTECT(1);\n  return args;\n\n}\n\nstatic R_INLINE SEXP eval_call (\n                                SEXP fn, SEXP args,\n                                double *t, double *dt,\n                                double *x, int nvar,\n                                double *p, int npar,\n                                double *c, int ncov)\n{\n\n  SEXP var = args, ans, ob;\n  int v;\n\n  *(REAL(CAR(var))) = *t; var = CDR(var);\n  for (v = 0; v < nvar; v++, x++, var=CDR(var)) *(REAL(CAR(var))) = *x;\n  for (v = 0; v < npar; v++, p++, var=CDR(var)) *(REAL(CAR(var))) = *p;\n  for (v = 0; v < ncov; v++, c++, var=CDR(var)) *(REAL(CAR(var))) = *c;\n  *(REAL(CAR(var))) = *dt; var = CDR(var);\n\n  PROTECT(ob = LCONS(fn,args));\n  PROTECT(ans = eval(ob,R_ClosureEnv(fn)));\n\n  UNPROTECT(2);\n  return ans;\n\n}\n\nstatic R_INLINE SEXP ret_array (int n, int nreps, int ntimes, SEXP names)\n{\n  int dim[3] = {n, nreps, ntimes};\n  const char *dimnm[3] = {\"name\", \".id\", \"time\"};\n  SEXP Y;\n\n  PROTECT(Y = makearray(3,dim));\n  setrownames(Y,names,3);\n  fixdimnames(Y,dimnm,3);\n\n  UNPROTECT(1);\n  return Y;\n\n}\n\nSEXP euler_simulator\n(\n SEXP func, SEXP xstart, SEXP tstart, SEXP times, SEXP params,\n double deltat, rprocmode method, SEXP accumvars, SEXP covar,\n SEXP args, SEXP gnsi\n ) {\n\n  pompfunmode mode = undef;\n  int nvars, npars, nreps, ntimes, nzeros, ncovars;\n  double *cov, t0;\n  SEXP cvec, X, fn;\n\n  if (deltat <= 0) err(\"'delta.t' should be a positive number.\"); // #nocov\n\n  int *dim;\n  dim = INTEGER(GET_DIM(xstart)); nvars = dim[0]; nreps = dim[1];\n  dim = INTEGER(GET_DIM(params)); npars = dim[0];\n  ntimes = LENGTH(times);\n\n  PROTECT(tstart = AS_NUMERIC(tstart));\n  PROTECT(times = AS_NUMERIC(times));\n  t0 = *(REAL(tstart));\n  if (t0 > *(REAL(times))) err(\"'t0' must be no later than 'times[1]'.\");\n\n  SEXP Snames, Pnames, Cnames;\n  PROTECT(Snames = GET_ROWNAMES(GET_DIMNAMES(xstart)));\n  PROTECT(Pnames = GET_ROWNAMES(GET_DIMNAMES(params)));\n  PROTECT(Cnames = get_covariate_names(covar));\n\n  // set up the covariate table\n  lookup_table_t covariate_table = make_covariate_table(covar,&ncovars);\n  PROTECT(cvec = NEW_NUMERIC(ncovars));\n  cov = REAL(cvec);\n\n  // indices of accumulator variables\n  nzeros = LENGTH(accumvars);\n  int *zidx = INTEGER(PROTECT(matchnames(Snames,accumvars,\"state variables\")));\n\n  // extract user function\n  PROTECT(fn = pomp_fun_handler(func,gnsi,&mode,Snames,Pnames,NA_STRING,Cnames));\n\n  // array to hold results\n  PROTECT(X = ret_array(nvars,nreps,ntimes,Snames));\n\n  // copy the start values into the result array\n  memcpy(REAL(X),REAL(xstart),nvars*nreps*sizeof(double));\n\n  // set up\n\n  int nprotect = 9;\n  int *pidx = 0, *sidx = 0, *cidx = 0;\n  pomp_onestep_sim *ff = NULL;\n\n  switch (mode) {\n\n  case Rfun:\n    // construct list of all arguments\n    PROTECT(args = add_args(args,Snames,Pnames,Cnames)); nprotect++;\n    break;\n\n  case native: case regNative:\n    // construct state, parameter, covariate indices\n    sidx = INTEGER(GET_SLOT(func,install(\"stateindex\")));\n    pidx = INTEGER(GET_SLOT(func,install(\"paramindex\")));\n    cidx = INTEGER(GET_SLOT(func,install(\"covarindex\")));\n\n    *((void **) (&ff)) = R_ExternalPtrAddr(fn);\n\n    GetRNGstate();\n    break;\n\n  default: // #nocov\n    err(\"unrecognized 'mode' %d\",mode); // #nocov\n    break;                              // #nocov\n  }\n\n  // main computation loop\n  int step;\n  double *xt, *time, t;\n  int first = 1;\n\n  for (\n       step = 0, xt = REAL(X), time = REAL(times), t = t0;\n       step < ntimes;\n       step++, xt += nvars*nreps\n       ) {\n\n    double dt;\n    int nstep = 0;\n    int i, j, k;\n\n    R_CheckUserInterrupt();\n\n    if (t > time[step]) err(\"'times' must be an increasing sequence.\");  // #nocov\n\n    // set accumulator variables to zero\n    for (j = 0; j < nreps; j++)\n      for (i = 0; i < nzeros; i++)\n        xt[zidx[i]+nvars*j] = 0.0;\n\n    // determine size and number of time-steps\n    switch (method) {\n    case onestep: default:      // one step\n      dt = time[step]-t;\n      nstep = 1;\n      break;\n    case discrete:              // fixed step\n      dt = deltat;\n      nstep = num_map_steps(t,time[step],dt);\n      break;\n    case euler:                 // Euler method\n      dt = deltat;\n      nstep = num_euler_steps(t,time[step],&dt);\n      break;\n    }\n\n    // loop over individual steps\n    for (k = 0; k < nstep; k++) {\n\n      // interpolate the covar functions for the covariates\n      table_lookup(&covariate_table,t,cov);\n\n      // loop over replicates\n      double *ap, *pm, *xm, *ps = REAL(params);\n\n      for (j = 0, pm = ps, xm = xt; j < nreps; j++, pm += npars, xm += nvars) {\n\n        switch (mode) {\n\n        case Rfun:\n          {\n            SEXP ans, nm;\n\n            if (first) {\n\n              PROTECT(ans = eval_call(fn,args,&t,&dt,xm,nvars,pm,npars,cov,ncovars));\n\n              PROTECT(nm = GET_NAMES(ans));\n              if (invalid_names(nm))\n                err(\"'rprocess' must return a named numeric vector.\");\n              pidx = INTEGER(PROTECT(matchnames(nm,Snames,\"state variables\")));\n\n              nprotect += 3;\n\n              ap = REAL(AS_NUMERIC(ans));\n              for (i = 0; i < nvars; i++) xm[pidx[i]] = ap[i];\n\n              first = 0;\n\n            } else {\n\n              PROTECT(ans = eval_call(fn,args,&t,&dt,xm,nvars,pm,npars,cov,ncovars));\n\n              ap = REAL(AS_NUMERIC(ans));\n              for (i = 0; i < nvars; i++) xm[pidx[i]] = ap[i];\n\n              UNPROTECT(1);\n\n            }\n          }\n          break;\n\n        case native: case regNative:\n          (*ff)(xm,pm,sidx,pidx,cidx,cov,t,dt);\n          break;\n\n        default:                              // #nocov\n          err(\"unrecognized 'mode' %d\",mode); // #nocov\n          break;                              // #nocov\n\n        }\n\n      }\n\n      t += dt;\n\n      if ((method == euler) && (k == nstep-2)) { // penultimate step\n        dt = time[step]-t;\n        t = time[step]-dt;\n      }\n\n    }\n\n    if (step < ntimes-1)\n      memcpy(xt+nvars*nreps,xt,nreps*nvars*sizeof(double));\n\n  }\n\n  // clean up\n  switch (mode) {\n\n  case native: case regNative: {\n\n    PutRNGstate();\n\n  }\n\n    break;\n\n  case Rfun: default:\n\n    break;\n\n  }\n\n  UNPROTECT(nprotect);\n  return X;\n\n}\n\nint num_euler_steps (double t1, double t2, double *deltat) {\n  double tol = sqrt(DBL_EPSILON);\n  int nstep;\n  // nstep will be the number of Euler steps to take in going from t1 to t2.\n  // note also that the stepsize changes.\n  // this choice is meant to be conservative\n  // (i.e., so that the actual deltat does not exceed the specified deltat\n  // by more than the relative tolerance 'tol')\n  // and to counteract roundoff error.\n  // It seems to work well, but is not guaranteed:\n  // suggestions would be appreciated.\n\n  if (t1 >= t2) {\n    *deltat = 0.0;\n    nstep = 0;\n  } else if (t1+*deltat >= t2) {\n    *deltat = t2-t1;\n    nstep = 1;\n  } else {\n    nstep = (int) ceil((t2-t1)/(*deltat)/(1+tol));\n    *deltat = (t2-t1)/((double) nstep);\n  }\n  return nstep;\n}\n\nint num_map_steps (double t1, double t2, double deltat) {\n  double tol = sqrt(DBL_EPSILON);\n  int nstep;\n  // nstep will be the number of discrete-time steps to take in going from t1 to t2.\n  nstep = (int) floor((t2-t1)/deltat/(1-tol));\n  return (nstep > 0) ? nstep : 0;\n}\n"
  },
  {
    "path": "src/gompertz.c",
    "content": "// dear emacs, please treat this as -*- C++ -*-\n\n#include <Rmath.h>\n\n#include \"pomp.h\" // in R, do 'system.file(\"include/pomp.h\",package=\"pomp\")' to find this header file\n\n// define some macros to make the code easier to read\n#define R       (p[parindex[0]]) // growth rate\n#define K       (p[parindex[1]]) // carrying capacity\n#define SIGMA   (p[parindex[2]]) // process noise level\n#define TAU     (p[parindex[3]]) // measurement noise level\n\n#define Y           (y[obsindex[0]])   // observed population size\n#define X           (x[stateindex[0]]) // actual population size\n#define XPRIME      (f[stateindex[0]]) // new population size\n#define EY          (f[obsindex[0]])   // expectation\n#define VY          (f[vmatindex[0]])  // variance\n\n// normal measurement model density\nvoid _gompertz_normal_dmeasure\n(\n double *lik, double *y, double *x, double *p, int give_log,\n int *obsindex, int *stateindex, int *parindex, int *covindex,\n double *covars, double t\n ) {\n  *lik = dlnorm(Y,log(X),TAU,give_log);\n}\n\n// normal measurement model simulator\nvoid _gompertz_normal_rmeasure\n(\n double *y, double *x, double *p,\n int *obsindex, int *stateindex, int *parindex, int *covindex,\n double *covars, double t\n ) {\n  Y = rlnorm(log(X),TAU);\n}\n\n// measurement model expectation\nvoid _gompertz_normal_emeasure\n(\n double *f, double *x, double *p,\n int *obsindex, int *stateindex, int *parindex, int *covindex,\n double *covars, double t\n ) {\n  EY = X*exp(TAU*TAU/2);\n}\n\n// measurement model variance\nvoid _gompertz_normal_vmeasure (double *f, double *x, double *p,\n                                int *vmatindex, int *stateindex, int *parindex, int *covindex,\n                                double *covars, double t) {\n  double et = exp(TAU*TAU);\n  VY = X*X*et*(et-1);\n}\n\n// stochastic Gompertz model with log-normal process noise\nvoid _gompertz_step\n(\n double *x, const double *p,\n const int *stateindex, const int *parindex, const int *covindex,\n const double *covar, double t, double deltat\n ) {\n  double S = exp(-R*deltat);\n  double eps = (SIGMA > 0.0) ? exp(rnorm(0,SIGMA)) : 1.0;\n  X = R_pow(K,1-S)*R_pow(X,S)*eps; // note X is over-written by this line\n}\n\n// the deterministic skeleton\nvoid _gompertz_skeleton\n(\n double *f, double *x, const double *p,\n const int *stateindex, const int *parindex, const int *covindex,\n const double *covar, double t\n ) {\n  double deltat = 1.0;\n  double S = exp(-R*deltat);\n  XPRIME = R_pow(K,1-S)*R_pow(X,S); // X is not over-written in the skeleton function\n}\n\n#undef R\n#undef K\n#undef SIGMA\n#undef TAU\n#undef Y\n#undef X\n#undef XPRIME\n#undef EY\n#undef VY\n\n#define r               (__p[__parindex[0]])\n#define K               (__p[__parindex[1]])\n#define sigma           (__p[__parindex[2]])\n#define tau             (__p[__parindex[3]])\n#define X_0             (__p[__parindex[4]])\n#define T_r             (__pt[__parindex[0]])\n#define T_K             (__pt[__parindex[1]])\n#define T_sigma         (__pt[__parindex[2]])\n#define T_tau           (__pt[__parindex[3]])\n#define T_X_0           (__pt[__parindex[4]])\n\nvoid _gompertz_to_trans\n(\n double *__pt, const double *__p, const int *__parindex\n ) {\n  T_r = log(r);\n  T_K = log(K);\n  T_sigma = log(sigma);\n  T_tau = log(tau);\n  T_X_0 = log(X_0);\n}\n\nvoid _gompertz_from_trans\n(\n double *__p, const double *__pt, const int *__parindex\n ) {\n  r = exp(T_r);\n  K = exp(T_K);\n  sigma = exp(T_sigma);\n  tau = exp(T_tau);\n  X_0 = exp(T_X_0);\n}\n\n#undef r\n#undef K\n#undef sigma\n#undef tau\n#undef X_0\n#undef T_r\n#undef T_K\n#undef T_sigma\n#undef T_tau\n#undef T_X_0\n"
  },
  {
    "path": "src/init.c",
    "content": "#include \"internal.h\"\n#include <R_ext/Rdynload.h>\n\nstatic const R_CallMethodDef callMethods[] = {\n  {\"set_userdata\", (DL_FUNC) &set_pomp_userdata, 1},\n  {\"logmeanexp\", (DL_FUNC) &logmeanexp, 2},\n  {\"bspline_basis\", (DL_FUNC) &bspline_basis, 5},\n  {\"periodic_bspline_basis\", (DL_FUNC) &periodic_bspline_basis, 5},\n  {\"systematic_resampling\", (DL_FUNC) &systematic_resampling, 2},\n  {\"lookup_in_table\", (DL_FUNC) &lookup_in_table, 2},\n  {\"load_stack_incr\", (DL_FUNC) &load_stack_incr, 1},\n  {\"load_stack_decr\", (DL_FUNC) &load_stack_decr, 1},\n  {\"R_Euler_Multinom\", (DL_FUNC) &R_Euler_Multinom, 4},\n  {\"D_Euler_Multinom\", (DL_FUNC) &D_Euler_Multinom, 5},\n  {\"E_Euler_Multinom\", (DL_FUNC) &E_Euler_Multinom, 3},\n  {\"R_GammaWN\", (DL_FUNC) &R_GammaWN, 3},\n  {\"R_BetaBinom\", (DL_FUNC) &R_BetaBinom, 4},\n  {\"D_BetaBinom\", (DL_FUNC) &D_BetaBinom, 5},\n  {\"pfilter_computations\", (DL_FUNC) &pfilter, 10},\n  {\"wpfilter_comps\", (DL_FUNC) &wpfilter, 7},\n  {\"randwalk_perturbation\", (DL_FUNC) &randwalk_perturbation, 2},\n  {\"do_simulate\", (DL_FUNC) &do_simulate, 5},\n  {\"iterate_map\", (DL_FUNC) &iterate_map, 6},\n  {\"pomp_desolve_setup\", (DL_FUNC) &pomp_desolve_setup, 4},\n  {\"pomp_desolve_takedown\", (DL_FUNC) &pomp_desolve_takedown, 0},\n  {\"apply_probe_data\", (DL_FUNC) &apply_probe_data, 2},\n  {\"apply_probe_sim\", (DL_FUNC) &apply_probe_sim, 6},\n  {\"probe_marginal_setup\", (DL_FUNC) &probe_marginal_setup, 3},\n  {\"probe_marginal_solve\", (DL_FUNC) &probe_marginal_solve, 3},\n  {\"probe_acf\", (DL_FUNC) &probe_acf, 3},\n  {\"probe_ccf\", (DL_FUNC) &probe_ccf, 4},\n  {\"probe_nlar\", (DL_FUNC) &probe_nlar, 3},\n  {\"synth_loglik\", (DL_FUNC) &synth_loglik, 2},\n  {\"sobol_sequence\", (DL_FUNC) &sobol_sequence, 2},\n  {\"do_partrans\", (DL_FUNC) &do_partrans, 4},\n  {\"do_rprocess\", (DL_FUNC) &do_rprocess, 6},\n  {\"do_dprocess\", (DL_FUNC) &do_dprocess, 6},\n  {\"do_rmeasure\", (DL_FUNC) &do_rmeasure, 5},\n  {\"do_dmeasure\", (DL_FUNC) &do_dmeasure, 7},\n  {\"do_emeasure\", (DL_FUNC) &do_emeasure, 5},\n  {\"do_vmeasure\", (DL_FUNC) &do_vmeasure, 5},\n  {\"do_rprior\", (DL_FUNC) &do_rprior, 3},\n  {\"do_dprior\", (DL_FUNC) &do_dprior, 4},\n  {\"do_skeleton\", (DL_FUNC) &do_skeleton, 5},\n  {\"do_rinit\", (DL_FUNC) &do_rinit, 5},\n  {\"do_dinit\", (DL_FUNC) &do_dinit, 6},\n  {\"LogitTransform\", (DL_FUNC) &LogitTransform, 1},\n  {\"ExpitTransform\", (DL_FUNC) &ExpitTransform, 1},\n  {\"LogBarycentricTransform\", (DL_FUNC) &LogBarycentricTransform, 1},\n  {\"InverseLogBarycentricTransform\", (DL_FUNC) &InverseLogBarycentricTransform, 1},\n  {NULL, NULL, 0}\n};\n\nvoid R_init_pomp (DllInfo *info) {\n  // C functions provided for users\n  R_RegisterCCallable(\"pomp\",\"bspline_basis_eval_deriv\",(DL_FUNC) &bspline_basis_eval_deriv);\n  R_RegisterCCallable(\"pomp\",\"periodic_bspline_basis_eval_deriv\",(DL_FUNC) &periodic_bspline_basis_eval_deriv);\n  R_RegisterCCallable(\"pomp\",\"get_userdata\",(DL_FUNC) &get_userdata);\n  R_RegisterCCallable(\"pomp\",\"get_userdata_int\",(DL_FUNC) &get_userdata_int);\n  R_RegisterCCallable(\"pomp\",\"get_userdata_double\",(DL_FUNC) &get_userdata_double);\n  R_RegisterCCallable(\"pomp\",\"pomp_fun_handler\",(DL_FUNC) &pomp_fun_handler);\n  R_RegisterCCallable(\"pomp\",\"load_stack_incr\",(DL_FUNC) &load_stack_incr);\n  R_RegisterCCallable(\"pomp\",\"load_stack_decr\",(DL_FUNC) &load_stack_decr);\n  R_RegisterCCallable(\"pomp\",\"make_covariate_table\",(DL_FUNC) &make_covariate_table);\n  R_RegisterCCallable(\"pomp\",\"get_covariate_names\",(DL_FUNC) &get_covariate_names);\n  R_RegisterCCallable(\"pomp\",\"table_lookup\",(DL_FUNC) &table_lookup);\n  R_RegisterCCallable(\"pomp\",\"lookup_in_table\",(DL_FUNC) &lookup_in_table);\n  R_RegisterCCallable(\"pomp\",\"apply_probe_data\",(DL_FUNC) &apply_probe_data);\n  R_RegisterCCallable(\"pomp\",\"apply_probe_sim\",(DL_FUNC) &apply_probe_sim);\n  R_RegisterCCallable(\"pomp\",\"systematic_resampling\",(DL_FUNC) &systematic_resampling);\n  R_RegisterCCallable(\"pomp\",\"randwalk_perturbation\", (DL_FUNC) &randwalk_perturbation);\n\n  // Register routines\n  R_registerRoutines(info,NULL,callMethods,NULL,NULL);\n  R_useDynamicSymbols(info,TRUE);\n  R_forceSymbols(info,FALSE);\n}\n"
  },
  {
    "path": "src/internal.h",
    "content": "// -*- C++ -*-\n\n#ifndef _POMP_INTERNAL_H_\n#define _POMP_INTERNAL_H_\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n#include \"pomp_defines.h\"\n#include \"decls.h\"\n#include \"backports.h\"\n\n#endif\n"
  },
  {
    "path": "src/logmeanexp.c",
    "content": "// -*- C++ -*-\n\n#include \"internal.h\"\n\n// Compute log(mean(exp(X))) accurately,\n// optionally with one element dropped\nSEXP logmeanexp (const SEXP X, const SEXP Drop) {\n  int j, n = LENGTH(X);\n  int k = *INTEGER(Drop)-1;     // zero-based index\n  double *x = REAL(X);\n  long double m = R_NegInf;\n  long double s = 0;\n  for (j = 0; j < n; j++) {\n    if (j != k)\n      m = (x[j] > m) ? (long double) x[j] : m;\n  }\n  for (j = 0; j < n; j++) {\n    if (j != k)\n      s += expl((long double) x[j] - m);\n  }\n  if (k >= 0 && k < n) n--;\n  return ScalarReal(m + log(s/n));\n}\n"
  },
  {
    "path": "src/lookup_table.c",
    "content": "#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n#include \"internal.h\"\n\nSEXP get_covariate_names (SEXP object) {\n  return GET_ROWNAMES(GET_DIMNAMES(GET_SLOT(object,install(\"table\"))));\n}\n\nlookup_table_t make_covariate_table (SEXP object, int *ncovar) {\n  lookup_table_t tab;\n  int *dim;\n  dim = INTEGER(GET_DIM(GET_SLOT(object,install(\"table\"))));\n  *ncovar = tab.width = dim[0];\n  tab.length = dim[1];\n  tab.index = 0;\n  tab.x = REAL(GET_SLOT(object,install(\"times\")));\n  tab.y = REAL(GET_SLOT(object,install(\"table\")));\n  tab.order = *(INTEGER(GET_SLOT(object,install(\"order\"))));\n  return tab;\n}\n\nSEXP lookup_in_table (SEXP covar, SEXP t) {\n  int xdim[2], nvar;\n  int j, nt;\n  double *tp, *xp;\n  SEXP Cnames, X;\n\n  PROTECT(t = AS_NUMERIC(t));\n  nt = LENGTH(t);\n  PROTECT(Cnames = get_covariate_names(covar));\n\n  lookup_table_t tab = make_covariate_table(covar,&nvar);\n\n  if (nt > 1) {\n    xdim[0] = nvar; xdim[1] = nt;\n    PROTECT(X = makearray(2,xdim));\n    setrownames(X,Cnames,2);\n  } else {\n    PROTECT(X = NEW_NUMERIC(nvar));\n    SET_NAMES(X,Cnames);\n  }\n\n  for (j = 0, tp = REAL(t), xp = REAL(X); j < nt; j++, tp++, xp += nvar)\n    table_lookup(&tab,*tp,xp);\n\n  UNPROTECT(3);\n  return X;\n}\n\n// linear interpolation on a lookup table\nvoid table_lookup (lookup_table_t *tab, double x, double *y)\n{\n  int flag = 0;\n  int j, k, n;\n  double e;\n  if ((tab == 0) || (tab->length < 1) || (tab->width < 1)) return;\n  tab->index = findInterval(tab->x,tab->length,x,1,1,tab->index,&flag);\n  // warn only if we are *outside* the interval\n  if ((x < tab->x[0]) || (x > tab->x[tab->length-1]))\n    warn(\"in 'table_lookup': extrapolating at %le.\", x);\n  switch (tab->order) {\n  case 1: default: // linear interpolation\n    e = (x - tab->x[tab->index-1]) / (tab->x[tab->index] - tab->x[tab->index-1]);\n    for (j = 0, k = tab->index*tab->width, n = k-tab->width; j < tab->width; j++, k++, n++) {\n      y[j] = e*(tab->y[k])+(1-e)*(tab->y[n]);\n    }\n    break;\n  case 0: // piecewise constant\n    if (flag < 0) n = 0;\n    else if (flag > 0) n = tab->index;\n    else n = tab->index-1;\n    for (j = 0, k = n*tab->width; j < tab->width; j++, k++) {\n      y[j] = tab->y[k];\n    }\n    break;\n  }\n}\n"
  },
  {
    "path": "src/mif2.c",
    "content": "// -*- C++ -*-\n\n#include \"internal.h\"\n#include <Rdefines.h>\n\nSEXP randwalk_perturbation (SEXP params, SEXP rw_sd)\n{\n  double *xp = 0, *rw, *xrw, *xs;\n  SEXP Pnames, rwnames, pindex;\n  int *dim, *pidx;\n  int nrw = 0, npars, nreps;\n  int j, k;\n\n  PROTECT(params = duplicate(params));\n\n  // unpack parameter matrix\n  xp = REAL(params);\n  dim = INTEGER(GET_DIM(params)); npars = dim[0]; nreps = dim[1];\n  PROTECT(Pnames = GET_ROWNAMES(GET_DIMNAMES(params)));\n\n  // names of parameters undergoing random walk\n  PROTECT(rwnames = GET_NAMES(rw_sd));\n  nrw = LENGTH(rwnames); rw = REAL(rw_sd);\n\n  // indices of parameters undergoing random walk\n  PROTECT(pindex = matchnames(Pnames,rwnames,\"parameters\"));\n  pidx = INTEGER(pindex);\n\n  GetRNGstate();\n\n  for (j = 0, xrw = rw; j < nrw; j++, pidx++, xrw++) {\n    for (k = 0, xs = xp+(*pidx); k < nreps; k++, xs += npars) {\n      *xs += *xrw * norm_rand();\n    }\n  }\n\n  PutRNGstate();\n\n  UNPROTECT(4);\n  return(params);\n}\n"
  },
  {
    "path": "src/ou2.c",
    "content": "// -*- C++ -*-\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n#include \"internal.h\"\n\n// simple 2D Ornstein-Uhlenbeck process simulation\nstatic void sim_ou2\n(\n double *x1, double *x2,\n double alpha1, double alpha2, double alpha3, double alpha4,\n double sigma1, double sigma2, double sigma3\n ) {\n  double eps[2], xnew[2];\n\n  eps[0] = rnorm(0,1);\n  eps[1] = rnorm(0,1);\n\n  xnew[0] = alpha1*(*x1)+alpha3*(*x2)+sigma1*eps[0];\n  xnew[1] = alpha2*(*x1)+alpha4*(*x2)+sigma2*eps[0]+sigma3*eps[1];\n\n  *x1 = xnew[0];\n  *x2 = xnew[1];\n}\n\n// simple 2D Ornstein-Uhlenbeck process transition density\n// transition (x1,x2) -> (z1,z2) in 1 unit of time\nstatic double dens_ou2\n(\n double x1, double x2, double z1, double z2,\n double alpha1, double alpha2, double alpha3, double alpha4,\n double sigma1, double sigma2, double sigma3, int give_log\n ) {\n  double eps[2], val;\n\n  // compute residuals\n  eps[0] = z1-alpha1*x1-alpha3*x2;\n  eps[1] = z2-alpha2*x1-alpha4*x2;\n\n  // backsolve\n  eps[0] /= sigma1;\n  eps[1] -= sigma2*eps[0];\n  eps[1] /= sigma3;\n\n  val = dnorm(eps[0],0.0,1.0,1)+dnorm(eps[1],0.0,1.0,1)-log(sigma1)-log(sigma3);\n  return ((give_log) ? val : exp(val));\n}\n\n#define ALPHA1     (p[parindex[0]])\n#define ALPHA2     (p[parindex[1]])\n#define ALPHA3     (p[parindex[2]])\n#define ALPHA4     (p[parindex[3]])\n#define SIGMA1     (p[parindex[4]])\n#define SIGMA2     (p[parindex[5]])\n#define SIGMA3     (p[parindex[6]])\n#define TAU        (p[parindex[7]])\n\n#define X1    (stateindex[0])\n#define X2    (stateindex[1])\n\n#define Y1    (y[obsindex[0]])\n#define Y2    (y[obsindex[1]])\n\n#define V11   (f[vmatindex[0]])\n#define V21   (f[vmatindex[1]])\n#define V12   (f[vmatindex[2]])\n#define V22   (f[vmatindex[3]])\n\n// onestep simulator for use in 'discrete.time.sim' plug-in\nvoid _ou2_step\n(\n double *x, const double *p,\n const int *stateindex, const int *parindex, const int *covindex,\n const double *covars, double t, double deltat\n ) {\n  sim_ou2(&x[X1],&x[X2],ALPHA1,ALPHA2,ALPHA3,ALPHA4,SIGMA1,SIGMA2,SIGMA3);\n}\n\n// onestep transition probability density for use in 'onestep.dens' plug-in\n// transition from x to z as time goes from t1 to t2\nvoid _ou2_pdf\n(\n double *f,\n double *x, double *z, double t1, double t2, const double *p,\n const int *stateindex, const int *parindex, const int *covindex,\n const double *covars\n ) {\n  if (t2-t1 != 1)\n    err(\"ou2_pdf error: transitions must be consecutive\");\n  f[0] = dens_ou2(x[X1],x[X2],z[X1],z[X2],ALPHA1,ALPHA2,ALPHA3,ALPHA4,\n                  SIGMA1,SIGMA2,SIGMA3,1);\n}\n\nvoid _ou2_skel\n(\n double *f, double *x, double *p,\n int *stateindex, int *parindex, int *covindex,\n double *covars, double t\n ) {\n  f[X1] = ALPHA1*x[X1]+ALPHA3*x[X2];\n  f[X2] = ALPHA2*x[X1]+ALPHA4*x[X2];\n}\n\n// bivariate normal measurement error density\nvoid _ou2_dmeasure\n(\n double *lik, double *y, double *x, double *p, int give_log,\n int *obsindex, int *stateindex, int *parindex, int *covindex,\n double *covar, double t\n ) {\n  double sd = fabs(TAU);\n  double f = 0.0;\n  f += (ISNA(Y1)) ? 0.0 : dnorm(Y1,x[X1],sd,1);\n  f += (ISNA(Y2)) ? 0.0 : dnorm(Y2,x[X2],sd,1);\n  *lik = (give_log) ? f : exp(f);\n}\n\n// bivariate normal measurement error simulator\nvoid _ou2_rmeasure\n(\n double *y, double *x, double *p,\n int *obsindex, int *stateindex, int *parindex, int *covindex,\n double *covar, double t\n ) {\n  double sd = fabs(TAU);\n  Y1 = rnorm(x[X1],sd);\n  Y2 = rnorm(x[X2],sd);\n}\n\n// bivariate normal measurement error expectation\nvoid _ou2_emeasure\n(\n double *y, double *x, double *p,\n int *obsindex, int *stateindex, int *parindex, int *covindex,\n double *covar, double t\n ) {\n  Y1 = x[X1];\n  Y2 = x[X2];\n}\n\n// bivariate normal measurement variance\nvoid _ou2_vmeasure\n(\n double *f, double *x, double *p,\n int *vmatindex, int *stateindex, int *parindex, int *covindex,\n double *covar, double t\n ) {\n  double sd = fabs(TAU);\n  V11 = V22 = sd*sd;\n  V12 = V21 = 0;\n}\n\n#undef ALPHA1\n#undef ALPHA2\n#undef ALPHA3\n#undef ALPHA4\n#undef SIGMA1\n#undef SIGMA2\n#undef SIGMA3\n#undef TAU\n\n#undef X1\n#undef X2\n#undef Y1\n#undef Y2\n\n#undef V11\n#undef V21\n#undef V12\n#undef V22\n"
  },
  {
    "path": "src/partrans.c",
    "content": "// dear emacs, please treat this as -*- C++ -*-\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n\n#include \"internal.h\"\n\ntypedef enum {to = 1, from = -1} direction_t;\n\nstatic R_INLINE SEXP add_args (SEXP args, SEXP names)\n{\n\n  SEXP var;\n  int v;\n\n  PROTECT(args = VectorToPairList(args));\n\n  for (v = LENGTH(names)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(names,v)));\n  }\n\n  UNPROTECT(1);\n  return args;\n\n}\n\nstatic R_INLINE SEXP eval_call (SEXP fn, SEXP args, double *p, int n)\n{\n\n  SEXP var = args, ans, ob;\n  int v;\n\n  for (v = 0; v < n; v++, p++, var=CDR(var)) *(REAL(CAR(var))) = *p;\n\n  PROTECT(ob = LCONS(fn,args));\n  PROTECT(ans = eval(ob,R_ClosureEnv(fn)));\n\n  UNPROTECT(2);\n  return ans;\n\n}\n\nSEXP do_partrans (SEXP object, SEXP params, SEXP dir, SEXP gnsi)\n{\n\n  SEXP Pnames, tparams, pompfun, fn, args, ob;\n  pompfunmode mode = undef;\n  direction_t direc;\n  int qvec, npars, nreps;\n  int *dim;\n\n  qvec = isNull(GET_DIM(params)); // is 'params' a vector?\n\n  PROTECT(tparams = duplicate(params));\n\n  // coerce 'params' to matrix\n  PROTECT(tparams = as_matrix(tparams));\n  dim = INTEGER(GET_DIM(tparams));\n  npars = dim[0]; nreps = dim[1];\n\n  PROTECT(Pnames = GET_ROWNAMES(GET_DIMNAMES(tparams)));\n\n  // determine direction of transformation and extract corresponding pomp_fun\n  direc = (direction_t) *(INTEGER(dir));\n  PROTECT(ob = GET_SLOT(object,install(\"partrans\")));\n  switch (direc) {\n  case from: default:   // from estimation scale\n    PROTECT(pompfun = GET_SLOT(ob,install(\"from\")));\n    break;\n  case to:                      // to estimation scale\n    PROTECT(pompfun = GET_SLOT(ob,install(\"to\")));\n    break;\n  }\n\n  PROTECT(fn = pomp_fun_handler(pompfun,gnsi,&mode,NA_STRING,Pnames,NA_STRING,NA_STRING));\n\n  // extract 'userdata' as pairlist\n  PROTECT(args = GET_SLOT(object,install(\"userdata\")));\n\n  int nprotect = 7;\n\n  switch (mode) {\n\n  case Rfun: {\n\n    SEXP ans, nm;\n    double *pa, *ps = REAL(tparams);\n    int *posn;\n    int i, j;\n\n    PROTECT(args = add_args(args,Pnames));\n    PROTECT(ans = eval_call(fn,args,ps,npars));\n\n    PROTECT(nm = GET_NAMES(ans));\n    if (invalid_names(nm))\n      err(\"user transformation functions must return named numeric vectors.\");\n    posn = INTEGER(PROTECT(matchnames(Pnames,nm,\"parameters\")));\n\n    nprotect += 4;\n\n    pa = REAL(AS_NUMERIC(ans));\n\n    for (i = 0; i < LENGTH(ans); i++) ps[posn[i]] = pa[i];\n\n    for (j = 1, ps += npars; j < nreps; j++, ps += npars) {\n\n      PROTECT(ans = eval_call(fn,args,ps,npars));\n      pa = REAL(AS_NUMERIC(ans));\n      for (i = 0; i < LENGTH(ans); i++) ps[posn[i]] = pa[i];\n      UNPROTECT(1);\n\n    }\n\n  }\n\n    break;\n\n  case native: case regNative: {\n\n    pomp_transform *ff;\n    double *ps, *pt;\n    int *idx;\n    int j;\n\n    *((void **) (&ff)) = R_ExternalPtrAddr(fn);\n\n    R_CheckUserInterrupt();\n\n    idx = INTEGER(GET_SLOT(pompfun,install(\"paramindex\")));\n\n    for (j = 0, ps = REAL(params), pt = REAL(tparams); j < nreps; j++, ps += npars, pt += npars)\n      (*ff)(pt,ps,idx);\n\n  }\n\n    break;\n\n  default:  // #nocov\n\n    break;  // #nocov\n\n  }\n\n  if (qvec) {\n    PROTECT(Pnames = GET_ROWNAMES(GET_DIMNAMES(tparams))); nprotect++;\n    SET_DIM(tparams,R_NilValue);\n    SET_NAMES(tparams,Pnames);\n  }\n\n  UNPROTECT(nprotect);\n  return tparams;\n\n}\n"
  },
  {
    "path": "src/pfilter.c",
    "content": "// -*- C++ -*-\n\n#include \"internal.h\"\n#include <Rdefines.h>\n\nstatic void pred_mean_var (int, int, int, const double *, double *, double *);\nstatic void filt_mean (int, int, int, long double, const double *, const double *, double *);\n\n// computes conditional log likelihood and effective sample size.\n// computes (if desired) prediction mean, prediction variance, filtering mean.\n// it is assumed that ncol(x) == ncol(params).\n// weights are used in filtering mean computation.\n// if length(weights) == 1, an unweighted average is computed.\n// tracks ancestry of particles if desired.\n// returns all of the above in a named list.\nSEXP pfilter (SEXP x, SEXP params, SEXP Np,\n              SEXP predmean, SEXP predvar,\n              SEXP filtmean, SEXP trackancestry, SEXP doparRS,\n              SEXP weights, SEXP wave)\n{\n\n  SEXP pm = R_NilValue, pv = R_NilValue, fm = R_NilValue;\n  SEXP anc = R_NilValue, wmean = R_NilValue;\n  SEXP ess, loglik;\n  SEXP newstates = R_NilValue, newparams = R_NilValue;\n  SEXP retval, retvalnames;\n  const char *dimnm[2] = {\"name\",\".id\"};\n  double *xw = 0;\n  long double w = 0, ws, maxw, sum;\n  int *xanc = 0;\n  SEXP dimX, dimP, newdim, Xnames, Pnames;\n  int *dim, np;\n  int nvars, npars = 0, nreps;\n  int do_pm, do_pv, do_fm, do_ta, do_pr, do_wave, all_fail = 0;\n  int j, k;\n\n  PROTECT(dimX = GET_DIM(x));\n  dim = INTEGER(dimX);\n  nvars = dim[0]; nreps = dim[1];\n  PROTECT(Xnames = GET_ROWNAMES(GET_DIMNAMES(x)));\n\n  PROTECT(params = as_matrix(params));\n  PROTECT(dimP = GET_DIM(params));\n  dim = INTEGER(dimP);\n  npars = dim[0];\n  if (nreps % dim[1] != 0)\n    err(\"ncol('states') should be a multiple of ncol('params')\"); // # nocov\n  PROTECT(Pnames = GET_ROWNAMES(GET_DIMNAMES(params)));\n\n  PROTECT(weights = duplicate(weights));\n\n  np = *(INTEGER(AS_INTEGER(Np))); // number of particles to resample\n\n  do_pm = *(LOGICAL(AS_LOGICAL(predmean))); // calculate prediction means?\n  do_pv = *(LOGICAL(AS_LOGICAL(predvar)));  // calculate prediction variances?\n  do_fm = *(LOGICAL(AS_LOGICAL(filtmean))); // calculate filtering means?\n  do_ta = *(LOGICAL(AS_LOGICAL(trackancestry))); // track ancestry?\n  // Do we need to do parameter resampling?\n  do_pr = *(LOGICAL(AS_LOGICAL(doparRS)));\n  // Do we need to take a weighted average over the parameters?\n  do_wave = *(LOGICAL(AS_LOGICAL(wave)));\n\n  if (do_pr) {\n    if (dim[1] != nreps)\n      err(\"ncol('states') should be equal to ncol('params')\"); // # nocov\n  }\n\n  PROTECT(ess = NEW_NUMERIC(1));    // effective sample size\n  PROTECT(loglik = NEW_NUMERIC(1)); // log likelihood\n\n  int nprotect = 8;\n\n  xw = REAL(weights);\n\n  // check and normalize the weights\n  for (k = 0, maxw = R_NegInf; k < nreps; k++) {\n\n    if (ISNAN(xw[k]) || xw[k] == R_PosInf) { // check the weights\n      PROTECT(retval = NEW_INTEGER(1)); nprotect++;\n      *INTEGER(retval) = k+1; // return the index of the peccant particle\n      UNPROTECT(nprotect);\n      return retval;\n    }\n\n    if (maxw < xw[k]) maxw = xw[k];\n\n  }\n\n  if (maxw == R_NegInf) all_fail = 1;\n\n  if (all_fail) {\n\n    *(REAL(loglik)) = R_NegInf;\n    *(REAL(ess)) = 0;             // zero effective sample size\n\n  } else {\n\n    // compute sum and sum of squares\n    for (k = 0, w = 0, ws = 0; k < nreps; k++) {\n      xw[k] = exp(xw[k]-maxw);\n      if (xw[k] != 0) {\n        w += xw[k];\n        ws += xw[k]*xw[k];\n      }\n    }\n\n    *(REAL(loglik)) = maxw + log(w/((long double) nreps)); // mean of weights is likelihood\n    *(REAL(ess)) = w*w/ws;      // effective sample size\n  }\n\n  if (do_pm || do_pv) {\n    PROTECT(pm = NEW_NUMERIC(nvars)); nprotect++;\n  }\n\n  if (do_pv) {\n    PROTECT(pv = NEW_NUMERIC(nvars)); nprotect++;\n  }\n\n  if (do_fm) {\n    PROTECT(fm = NEW_NUMERIC(nvars)); nprotect++;\n  }\n\n  if (do_ta) {\n    PROTECT(anc = NEW_INTEGER(np)); nprotect++;\n    xanc = INTEGER(anc);\n  }\n\n  if (do_wave) {\n    PROTECT(wmean = NEW_NUMERIC(npars)); nprotect++;\n    SET_NAMES(wmean,Pnames);\n  }\n\n  if (do_pm || do_pv) {\n    double *tmp = (do_pv) ? REAL(pv) : 0;\n    pred_mean_var(nvars,nreps,do_pv,REAL(x),REAL(pm),tmp);\n  }\n\n  //  compute filter mean\n  if (do_fm) {\n    filt_mean(nvars,nreps,all_fail,w,xw,REAL(x),REAL(fm));\n  }\n\n  // compute weighted average of parameters\n  if (do_wave) {\n    if (all_fail)\n      warn(\"%s %s\",\"filtering failure at last filter iteration:\",\n           \"using unweighted mean for point estimate.\");\n    double *xwm = REAL(wmean);\n    for (j = 0; j < npars; j++, xwm++) {\n      double *xp = REAL(params)+j;\n      if (all_fail) {           // unweighted average\n        for (k = 0, sum = 0; k < nreps; k++, xp += npars) sum += *xp;\n        *xwm = sum/((long double) nreps);\n      } else {\n        for (k = 0, sum = 0; k < nreps; k++, xp += npars) {\n          if (xw[k]!=0) sum += xw[k]*(*xp);\n        }\n        *xwm = sum/w;\n      }\n    }\n  }\n\n  GetRNGstate();\n\n  if (!all_fail) { // resample the particles unless we have filtering failure\n    int xdim[2];\n    int sample[np];\n    double *ss = 0, *st = 0, *ps = 0, *pt = 0;\n\n    // create storage for new states\n    xdim[0] = nvars; xdim[1] = np;\n    PROTECT(newstates = makearray(2,xdim)); nprotect++;\n    setrownames(newstates,Xnames,2);\n    fixdimnames(newstates,dimnm,2);\n    ss = REAL(x);\n    st = REAL(newstates);\n\n    // create storage for new parameters\n    if (do_pr) {\n      xdim[0] = npars; xdim[1] = np;\n      PROTECT(newparams = makearray(2,xdim)); nprotect++;\n      setrownames(newparams,Pnames,2);\n      fixdimnames(newparams,dimnm,2);\n      ps = REAL(params);\n      pt = REAL(newparams);\n    }\n\n    // resample\n    nosort_resamp(nreps,REAL(weights),np,sample,0);\n    for (k = 0; k < np; k++) { // copy the particles\n      int sp = sample[k];\n      double *xx, *xp;\n      for (j = 0, xx = ss+nvars*sp; j < nvars; j++, st++, xx++)\n        *st = *xx;\n      if (do_pr) {\n        for (j = 0, xp = ps+npars*sp; j < npars; j++, pt++, xp++)\n          *pt = *xp;\n      }\n      if (do_ta) xanc[k] = sp+1;\n    }\n\n  } else { // don't resample: just drop 3rd dimension in x prior to return\n\n    PROTECT(newdim = NEW_INTEGER(2)); nprotect++;\n    dim = INTEGER(newdim);\n    dim[0] = nvars; dim[1] = nreps;\n    SET_DIM(x,newdim);\n    setrownames(x,Xnames,2);\n    fixdimnames(x,dimnm,2);\n\n    if (do_ta)\n      for (k = 0; k < np; k++) xanc[k] = k+1;\n  }\n\n  PutRNGstate();\n\n  PROTECT(retval = NEW_LIST(9));\n  PROTECT(retvalnames = NEW_CHARACTER(9));\n  nprotect += 2;\n  SET_STRING_ELT(retvalnames,0,mkChar(\"loglik\"));\n  SET_STRING_ELT(retvalnames,1,mkChar(\"ess\"));\n  SET_STRING_ELT(retvalnames,2,mkChar(\"states\"));\n  SET_STRING_ELT(retvalnames,3,mkChar(\"params\"));\n  SET_STRING_ELT(retvalnames,4,mkChar(\"pm\"));\n  SET_STRING_ELT(retvalnames,5,mkChar(\"pv\"));\n  SET_STRING_ELT(retvalnames,6,mkChar(\"fm\"));\n  SET_STRING_ELT(retvalnames,7,mkChar(\"ancestry\"));\n  SET_STRING_ELT(retvalnames,8,mkChar(\"wmean\"));\n  SET_NAMES(retval,retvalnames);\n\n  SET_ELEMENT(retval,0,loglik);\n  SET_ELEMENT(retval,1,ess);\n\n  if (all_fail) {\n    SET_ELEMENT(retval,2,x);\n  } else {\n    SET_ELEMENT(retval,2,newstates);\n  }\n\n  if (all_fail || !do_pr) {\n    SET_ELEMENT(retval,3,params);\n  } else {\n    SET_ELEMENT(retval,3,newparams);\n  }\n\n  if (do_pm) {\n    SET_ELEMENT(retval,4,pm);\n  }\n  if (do_pv) {\n    SET_ELEMENT(retval,5,pv);\n  }\n  if (do_fm) {\n    SET_ELEMENT(retval,6,fm);\n  }\n  if (do_ta) {\n    SET_ELEMENT(retval,7,anc);\n  }\n  if (do_wave) {\n    SET_ELEMENT(retval,8,wmean);\n  }\n\n  UNPROTECT(nprotect);\n  return(retval);\n}\n\nstatic void pred_mean_var (int nvars, int nreps, int do_pv,\n                           const double *x,\n                           double *pm, double *pv)\n{\n  long double sum, sumsq, vsq;\n  const double *xx;\n  int j, k;\n\n  for (j = 0; j < nvars; j++, pm++, pv++) {\n\n    xx = x+j;\n\n    // compute prediction mean\n    for (k = 0, sum = 0; k < nreps; k++, xx += nvars) sum += *xx;\n    *pm = sum/((long double) nreps);\n\n    // compute prediction variance\n    if (do_pv) {\n      xx = x+j;\n      for (k = 0, sumsq = 0; k < nreps; k++, xx += nvars) {\n        vsq = *xx - sum;\n        sumsq += vsq*vsq;\n      }\n      *pv = sumsq/((long double) (nreps - 1));\n    }\n  }\n}\n\nstatic void filt_mean (int nvars, int nreps, int all_fail, long double wsum,\n                       const double *w, const double *x, double *fm)\n{\n  long double sum;\n  const double *xx;\n  int j, k;\n  for (j = 0; j < nvars; j++, fm++) {\n    xx = x+j;\n    if (all_fail) {           // unweighted average\n      for (k = 0, sum = 0; k < nreps; k++, xx += nvars) sum += *xx;\n      *fm = sum/((long double) nreps);\n    } else {                  // weighted average\n      for (k = 0, sum = 0; k < nreps; k++, xx += nvars) sum += w[k]*(*xx);\n      *fm = sum/wsum;\n    }\n  }\n}\n"
  },
  {
    "path": "src/pomp.h",
    "content": "// -*- C++ -*-\n// Header for the C API for pomp.\n// Documentation: https://kingaa.github.io/pomp/C_API.html\n\n//! \\mainpage C source codes for **pomp**\n//!\n//! These codes are part of **pomp**, an **R** package for partially observed Markov processes, described in a [2016 *Journal of Statistical Software* paper](https://doi.org/10.18637/jss.v069.i12).\n//!\n//! See the [package homepage](https://kingaa.github.io/pomp/) and the [manual](https://kingaa.github.io/manuals/pomp/) for more information.\n//!\n//! The **pomp** C API is [documented here](https://kingaa.github.io/pomp/C_API.html).\n//!\n\n#ifndef _POMP_H_\n#define _POMP_H_\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n#define err(...) Rf_errorcall(R_NilValue,__VA_ARGS__)\n#define warn(...) Rf_warningcall(R_NilValue,__VA_ARGS__)\n\ntypedef\nvoid bspline_basis_eval_deriv_t\n(double x, double *knots, int degree,\n int nbasis, int deriv, double *y);\n\ntypedef\nvoid periodic_bspline_basis_eval_deriv_t\n(double x, double period, int degree,\n int nbasis, int deriv, double *y);\n\ntypedef const SEXP get_userdata_t (const char *name);\ntypedef const int *get_userdata_int_t (const char *name);\ntypedef const double *get_userdata_double_t (const char *name);\n\ntypedef\nvoid pomp_rinit\n(double *x, const double *p, double t0,\n const int *stateindex, const int *parindex,\n const int *covindex, const double *covars);\n\ntypedef\nvoid pomp_dinit\n(double *lik, const double *x, const double *p,\n double t0, const int *stateindex, const int *parindex,\n const int *covindex, const double *covars);\n\ntypedef\ndouble pomp_ssa_rate_fn\n(int event, double t, const double *x,\n const double *p, const int *stateindex,\n const int *parindex, const int *covindex,\n const double *covars);\n\ntypedef\nvoid pomp_onestep_sim\n(double *x, const double *p,\n const int *stateindex, const int *parindex,\n const int *covindex, const double *covars,\n double t, double dt);\n\ntypedef\nvoid pomp_dprocess\n(double *loglik, const double *x1, const double *x2,\n double t1, double t2, const double *p,\n const int *stateindex, const int *parindex,\n const int *covindex, const double *covars);\n\ntypedef\nvoid pomp_skeleton\n(double *f, const double *x, const double *p,\n const int *stateindex, const int *parindex,\n const int *covindex, const double *covars, double t);\n\ntypedef\nvoid pomp_rmeasure\n(double *y, const double *x, const double *p,\n const int *obsindex, const int *stateindex,\n const int *parindex, const int *covindex,\n const double *covars, double t);\n\ntypedef\nvoid pomp_dmeasure\n(double *lik, const double *y, const double *x,\n const double *p, int give_log, const int *obsindex,\n const int *stateindex, const int *parindex,\n const int *covindex, const double *covars, double t);\n\ntypedef\nvoid pomp_emeasure\n(double *f, const double *x, const double *p,\n const int *obsindex, const int *stateindex,\n const int *parindex, const int *covindex,\n const double *covars, double t);\n\ntypedef\nvoid pomp_vmeasure\n(double *f, const double *x, const double *p,\n const int *vmatindex, const int *stateindex,\n const int *parindex, const int *covindex,\n const double *covars, double t);\n\ntypedef\nvoid pomp_rprior\n(double *p, const int *parindex);\n\ntypedef\nvoid pomp_dprior\n(double *lik, const double *p, int give_log, const int *parindex);\n\ntypedef\nvoid pomp_transform\n(double *pt, const double *p, const int *parindex);\n\nstatic R_INLINE\ndouble logit (double p) {\n  return log(p/(1.0-p));\n}\n\nstatic R_INLINE\ndouble expit (double x) {\n  return 1.0/(1.0+exp(-x));\n}\n\nstatic R_INLINE\ndouble rgammawn\n(double sigma, double dt)\n{\n  double sigmasq;\n  sigmasq = sigma*sigma;\n  return (sigmasq > 0) ? rgamma(dt/sigmasq,sigmasq) : dt;\n}\n\nstatic R_INLINE\nvoid eeulermultinom\n(int m, double size, const double *rate, double dt, double *trans)\n{\n  double lambda = 0.0;\n  int j, k;\n  if (!R_FINITE(size) || size < 0.0 || !R_FINITE(dt) || dt < 0.0) {\n    for (k = 0; k < m; k++) trans[k] = R_NaReal;\n    warn(\"in 'eeulermultinom': NAs produced.\");\n    return;\n  }\n  for (k = 0; k < m; k++) {\n    if (!R_FINITE(rate[k]) || rate[k] < 0.0) {\n      for (j = 0; j < m; j++) trans[j] = R_NaReal;\n      warn(\"in 'eeulermultinom': NAs produced.\");\n      return;\n    }\n    lambda += rate[k];\n  }\n  if (lambda > 0.0) {\n    size = size*(1-exp(-lambda*dt));\n    for (k = 0; k < m; k++)\n      trans[k] = size*rate[k]/lambda;\n  } else {\n    for (k = 0; k < m; k++) trans[k] = 0.0;\n  }\n}\n\nstatic R_INLINE\nvoid reulermultinom\n(int m, double size, const double *rate, double dt, double *trans)\n{\n  double p = 0.0;\n  int j, k;\n  if ( !R_FINITE(size) || size < 0.0 || floor(size+0.5) != size ||\n       !R_FINITE(dt) || dt < 0.0) {\n    for (k = 0; k < m; k++) trans[k] = R_NaReal;\n    warn(\"in 'reulermultinom': NAs produced.\");\n    return;\n  }\n  for (k = 0; k < m; k++) {\n    if (!R_FINITE(rate[k]) || rate[k] < 0.0) {\n      for (j = 0; j < m; j++) trans[j] = R_NaReal;\n      warn(\"in 'reulermultinom': NAs produced.\");\n      return;\n    }\n    p += rate[k]; // total event rate\n  }\n  if (p > 0.0) {\n    size = rbinom(size,1-exp(-p*dt)); // total number of events\n    m -= 1;\n    for (k = 0; k < m; k++) {\n      if (rate[k] > p) p = rate[k];\n      trans[k] = ((size > 0) && (p > 0)) ? rbinom(size,rate[k]/p) : 0;\n      size -= trans[k];\n      p -= rate[k];\n    }\n    trans[m] = size;\n  } else {\n    for (k = 0; k < m; k++) trans[k] = 0.0;\n  }\n}\n\nstatic R_INLINE\ndouble deulermultinom\n(int m, double size, const double *rate, double dt, double *trans, int give_log)\n{\n  double p = 0.0;\n  double n = 0.0;\n  double ff = 0.0;\n  int k;\n  if ((dt < 0.0) || (size < 0.0) || (floor(size+0.5) != size)) {\n    warn(\"in 'deulermultinom': NaNs produced.\");\n    return R_NaN;\n  }\n  for (k = 0; k < m; k++) {\n    if (rate[k] < 0.0) {\n      warn(\"in 'deulermultinom': NaNs produced.\");\n      return R_NaN;\n    }\n    if (trans[k] < 0.0) {\n      ff = (give_log) ? R_NegInf: 0.0;\n      return ff;\n    }\n    p += rate[k]; // total event rate\n    n += trans[k]; // total number of events\n  }\n  if (n > size) {\n    ff = (give_log) ? R_NegInf: 0.0;\n    return ff;\n  }\n  ff = dbinom(n,size,1-exp(-p*dt),1); // total number of events\n  m -= 1;\n  for (k = 0; k < m; k++) {\n    if ((n > 0) && (p > 0)) {\n      if (rate[k] > p) p = rate[k];\n      ff += dbinom(trans[k],n,rate[k]/p,1);\n    }\n    n -= trans[k];\n    p -= rate[k];\n  }\n  ff = (give_log) ? ff : exp(ff);\n  return ff;\n}\n\nstatic R_INLINE\ndouble dmultinom\n(int m, const double *prob, double *x, int give_log)\n{\n  double p = 0.0;\n  double n = 0.0;\n  double ff = 0.0;\n  int k;\n  for (k = 0; k < m; k++) {\n    if (prob[k] < 0.0) {\n      warn(\"in 'dmultinom': NaNs produced.\");\n      return R_NaN;\n    }\n    if ((x[k] < 0.0) || (floor(x[k]+0.5) != x[k])) {\n      ff = (give_log) ? R_NegInf: 0.0;\n      return ff;\n    }\n    p += prob[k]; // sum of probabilities\n    n += x[k]; // total number of events\n  }\n  for (k = 0; k < m; k++) {\n    if ((n > 0) && (p > 0)) {\n      if (prob[k] > p) p = prob[k];\n      ff += dbinom(x[k],n,prob[k]/p,1);\n    } else if (x[k] < 0.0) {\n      ff = R_NegInf;\n      return ff;\n    }\n    n -= x[k];\n    p -= prob[k];\n  }\n  ff = (give_log) ? ff : exp(ff);\n  return ff;\n}\n\nstatic R_INLINE\nvoid to_log_barycentric\n(double *xt, const double *x, int n)\n{\n  double sum;\n  int i;\n  for (i = 0, sum = 0.0; i < n; i++) sum += x[i];\n  for (i = 0; i < n; i++) xt[i] = log(x[i]/sum);\n}\n\nstatic R_INLINE\nvoid from_log_barycentric\n(double *xt, const double *x, int n)\n{\n  double sum;\n  int i;\n  for (i = 0, sum = 0.0; i < n; i++) sum += (xt[i] = exp(x[i]));\n  for (i = 0; i < n; i++) xt[i] /= sum;\n}\n\nstatic R_INLINE\ndouble dot_product\n(int n, const double *x, const double *y)\n{\n  double p = 0.0;\n  for (int j = 0; j < n; j++) p += x[j]*y[j];\n  return p;\n}\n\nstatic R_INLINE\ndouble exp2geom_rate_correction\n(double R, double dt)\n{\n  return (dt > 0) ? log1p(R*dt)/dt : R;\n}\n\nstatic R_INLINE\ndouble rbetabinom\n(double size, double prob, double theta)\n{\n  return rbinom(size,rbeta(prob*theta,(1.0-prob)*theta));\n}\n\nstatic R_INLINE\ndouble dbetabinom\n(double x, double size, double prob, double theta, int give_log)\n{\n  double a = theta*prob;\n  double b = theta*(1.0-prob);\n  double f = lchoose(size,x)-lbeta(a,b)+lbeta(a+x,b+size-x);\n  return (give_log) ? f : exp(f);\n}\n\nstatic R_INLINE\ndouble rbetanbinom\n(double mu, double size, double theta)\n{\n  double p = size/(size+mu);\n  return rnbinom(size,rbeta(p*theta,(1.0-p)*theta));\n}\n\nstatic R_INLINE\ndouble dbetanbinom\n(double x, double mu, double size, double theta, int give_log)\n{\n  double p = size/(size+mu);\n  double a = theta*p;\n  double b = theta*(1.0-p);\n  double f = lchoose(size+x-1,size-1)-lbeta(a,b)+lbeta(a+size,b+x);\n  return (give_log) ? f : exp(f);\n}\n\n#endif\n"
  },
  {
    "path": "src/pomp_defines.h",
    "content": "// -*- C++ -*-\n\n#ifndef _POMP_DEFINES_H_\n#define _POMP_DEFINES_H_\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n\n#include \"pomp.h\"\n\n# define MATCHROWNAMES(X,N,W) (matchnames(GET_ROWNAMES(GET_DIMNAMES(X)),(N),(W)))\n# define MATCHCOLNAMES(X,N,W) (matchnames(GET_COLNAMES(GET_DIMNAMES(X)),(N),(W)))\n\ntypedef enum {undef=0,Rfun=1,native=2,regNative=3} pompfunmode;\ntypedef enum {dflt=0,onestep=1,discrete=2,euler=3,gill=4} rprocmode;\n\n// lookup-table structure, as used internally\ntypedef struct {\n  int length, width;\n  int index;\n  int order;\n  double *x;\n  double *y;\n} lookup_table_t;\n\ntypedef SEXP pomp_fun_handler_t (SEXP pfun, SEXP gnsi, pompfunmode *mode, SEXP S, SEXP P, SEXP O, SEXP C);\ntypedef SEXP load_stack_incr_t (SEXP pack);\ntypedef SEXP load_stack_decr_t (SEXP pack);\ntypedef lookup_table_t make_covariate_table_t (SEXP object, int *ncovar);\ntypedef void table_lookup_t (lookup_table_t *tab, double x, double *y);\ntypedef SEXP apply_probe_data_t (SEXP object, SEXP probes);\ntypedef SEXP apply_probe_sim_t (SEXP object, SEXP nsim, SEXP params, SEXP probes, SEXP datval, SEXP gnsi);\ntypedef SEXP systematic_resampling_t (SEXP weights);\ntypedef void set_pomp_userdata_t (SEXP userdata);\ntypedef void unset_pomp_userdata_t (void);\ntypedef SEXP get_covariate_names_t (SEXP object);\n\nstatic R_INLINE SEXP makearray (int rank, const int *dim) {\n  int *dimp, k;\n  double *xp;\n  SEXP dimx, x;\n  PROTECT(dimx = NEW_INTEGER(rank));\n  dimp = INTEGER(dimx);\n  for (k = 0; k < rank; k++) dimp[k] = dim[k];\n  PROTECT(x = allocArray(REALSXP,dimx));\n  xp = REAL(x);\n  for (k = 0; k < length(x); k++) xp[k] = NA_REAL;\n  UNPROTECT(2);\n  return x;\n}\n\n// check if names exist and are nonempty\nstatic R_INLINE int invalid_names (SEXP names) {\n  return isNull(names);\n}\n\nstatic R_INLINE SEXP matchnames\n(\n SEXP provided, SEXP needed, const char *where\n ) {\n  int m = LENGTH(provided);\n  int n = length(needed);\n  SEXP index;\n  int *idx, i, j;\n  PROTECT(provided = AS_CHARACTER(provided));\n  PROTECT(needed = AS_CHARACTER(needed));\n  if (invalid_names(provided))\n    err(\"invalid variable names among the %s.\",where); // #nocov\n  PROTECT(index = NEW_INTEGER(n));\n  idx = INTEGER(index);\n  for (i = 0; i < n; i++) {\n    for (j = 0; j < m; j++) {\n      if (!strcmp(CHAR(STRING_ELT(provided,j)),CHAR(STRING_ELT(needed,i)))) {\n        idx[i] = j;\n        break;\n      }\n    }\n    if (j==m)\n      err(\"variable '%s' not found among the %s.\",CHAR(STRING_ELT(needed,i)),where);\n  }\n  UNPROTECT(3);\n  return index;\n}\n\nstatic R_INLINE void fillrownames (SEXP x, SEXP names) {\n  SEXP dim, dimnms;\n  int nr;\n  PROTECT(names = AS_CHARACTER(names));\n  PROTECT(dim = GET_DIM(x));\n  PROTECT(dimnms = allocVector(VECSXP,length(dim)));\n  nr = INTEGER(dim)[0];\n  if (nr > length(names)) {\n    SEXP nm;\n    int k;\n    PROTECT(nm = NEW_CHARACTER(nr));\n    for (k = 0; k < length(names); k++) {\n      SET_STRING_ELT(nm,k,STRING_ELT(names,k));\n    }\n    SET_ELEMENT(dimnms,0,nm);\n    UNPROTECT(1);\n  } else {\n    SET_ELEMENT(dimnms,0,names);\n  }\n  SET_DIMNAMES(x,dimnms);\n  UNPROTECT(3);\n}\n\nstatic R_INLINE void setrownames (SEXP x, SEXP names, int rank) {\n  SEXP dimnms, nm;\n  PROTECT(nm = AS_CHARACTER(names));\n  PROTECT(dimnms = allocVector(VECSXP,rank));\n  SET_ELEMENT(dimnms,0,nm);     // set row names\n  SET_DIMNAMES(x,dimnms);\n  UNPROTECT(2);\n}\n\n// This only works if the dimnames have already been created and set\n// e.g., with 'setrownames'\nstatic R_INLINE void setcolnames (SEXP x, SEXP names) {\n  SEXP dn;\n  PROTECT(dn = GET_DIMNAMES(x));\n  SET_ELEMENT(dn,1,names);\n  SET_DIMNAMES(x,dn);\n  UNPROTECT(1);\n}\n\nstatic R_INLINE void fixdimnames (SEXP x, const char **names, int n) {\n  int nprotect = 2;\n  int i;\n  SEXP dimnames, nm;\n  PROTECT(dimnames = GET_DIMNAMES(x));\n  if (isNull(dimnames)) {\n    PROTECT(dimnames = allocVector(VECSXP,n)); nprotect++;\n  }\n  PROTECT(nm = allocVector(VECSXP,n));\n  for (i = 0; i < n; i++)\n    SET_ELEMENT(nm,i,mkChar(names[i]));\n  SET_NAMES(dimnames,nm);\n  SET_DIMNAMES(x,dimnames);\n  UNPROTECT(nprotect);\n}\n\nstatic R_INLINE SEXP as_matrix (SEXP x) {\n  int nprotect = 1;\n  SEXP dim, names;\n  int *xdim, nrow, ncol;\n  PROTECT(dim = GET_DIM(x));\n  if (isNull(dim)) {\n    PROTECT(x = duplicate(x));\n    PROTECT(names = GET_NAMES(x));\n    nprotect += 2;\n    dim = NEW_INTEGER(2);\n    xdim = INTEGER(dim); xdim[0] = LENGTH(x); xdim[1] = 1;\n    SET_DIM(x,dim);\n    SET_NAMES(x,R_NilValue);\n    setrownames(x,names,2);\n  } else if (LENGTH(dim) == 1) {\n    PROTECT(x = duplicate(x));\n    PROTECT(names = GET_ROWNAMES(GET_DIMNAMES(x)));\n    nprotect += 2;\n    dim = NEW_INTEGER(2);\n    xdim = INTEGER(dim); xdim[0] = LENGTH(x); xdim[1] = 1;\n    SET_DIM(x,dim);\n    SET_NAMES(x,R_NilValue);\n    setrownames(x,names,2);\n  } else if (LENGTH(dim) > 2) {\n    PROTECT(x = duplicate(x));\n    PROTECT(names = GET_ROWNAMES(GET_DIMNAMES(x)));\n    nprotect += 2;\n    nrow = INTEGER(dim)[0]; ncol = LENGTH(x)/nrow;\n    dim = NEW_INTEGER(2);\n    xdim = INTEGER(dim); xdim[0] = nrow; xdim[1] = ncol;\n    SET_DIM(x,dim);\n    SET_NAMES(x,R_NilValue);\n    setrownames(x,names,2);\n  }\n  UNPROTECT(nprotect);\n  return x;\n}\n\nstatic R_INLINE SEXP as_state_array (SEXP x) {\n  int nprotect = 1;\n  SEXP dim, names;\n  int *xdim, nrow, ncol;\n  PROTECT(dim = GET_DIM(x));\n  if (isNull(dim)) {\n    PROTECT(x = duplicate(x));\n    PROTECT(names = GET_NAMES(x));\n    nprotect += 2;\n    dim = NEW_INTEGER(3);\n    xdim = INTEGER(dim); xdim[0] = LENGTH(x); xdim[1] = 1; xdim[2] = 1;\n    SET_DIM(x,dim);\n    SET_NAMES(x,R_NilValue);\n    setrownames(x,names,3);\n  } else if (LENGTH(dim) == 1) {\n    PROTECT(x = duplicate(x));\n    PROTECT(names = GET_ROWNAMES(GET_DIMNAMES(x)));\n    nprotect += 2;\n    dim = NEW_INTEGER(3);\n    xdim = INTEGER(dim); xdim[0] = LENGTH(x); xdim[1] = 1; xdim[2] = 1;\n    SET_DIM(x,dim);\n    SET_NAMES(x,R_NilValue);\n    setrownames(x,names,3);\n  } else if (LENGTH(dim) == 2) {\n    PROTECT(x = duplicate(x));\n    PROTECT(names = GET_ROWNAMES(GET_DIMNAMES(x)));\n    nprotect += 2;\n    xdim = INTEGER(dim); nrow = xdim[0]; ncol = xdim[1];\n    dim = NEW_INTEGER(3);\n    xdim = INTEGER(dim); xdim[0] = nrow; xdim[1] = 1; xdim[2] = ncol;\n    SET_DIM(x,dim);\n    SET_NAMES(x,R_NilValue);\n    setrownames(x,names,3);\n  } else if (LENGTH(dim) > 3) {\n    PROTECT(x = duplicate(x));\n    PROTECT(names = GET_ROWNAMES(GET_DIMNAMES(x)));\n    nprotect += 2;\n    xdim = INTEGER(dim); nrow = xdim[0]; ncol = xdim[1];\n    dim = NEW_INTEGER(3);\n    xdim = INTEGER(dim);\n    xdim[0] = nrow; xdim[1] = ncol; xdim[2] = LENGTH(x)/nrow/ncol;\n    SET_DIM(x,dim);\n    SET_NAMES(x,R_NilValue);\n    setrownames(x,names,3);\n  }\n  UNPROTECT(nprotect);\n  return x;\n}\n\nstatic R_INLINE SEXP getListElement (SEXP list, const char *str)\n{\n  SEXP elmt = R_NilValue;\n  SEXP names = getAttrib(list,R_NamesSymbol);\n  for (R_len_t i = 0; i < length(list); i++)\n    if (strcmp(CHAR(STRING_ELT(names,i)),str) == 0) {\n      elmt = VECTOR_ELT(list,i);\n      break;\n    }\n  return elmt;\n}\n\nstatic R_INLINE SEXP getPairListElement (SEXP list, const char *name)\n{\n  const char *tag;\n  while (list != R_NilValue) {\n    tag = CHAR(PRINTNAME(TAG(list)));\n    if (strcmp(tag,name)==0) break;\n    list = CDR(list);\n  }\n  return CAR(list);\n}\n\n#ifdef __cplusplus\n\ntemplate <class Scalar>\nclass view {\nprivate:\n  Scalar *data;\n  int dim[2];\npublic:\n  view (Scalar *x) {\n    data = x;\n    dim[0] = 0;\n    dim[1] = 0;\n  };\n  view (Scalar *x, int d1) {\n    data = x;\n    dim[0] = d1;\n    dim[1] = 0;\n  };\n  view (Scalar *x, int d1, int d2) {\n    data = x;\n    dim[0] = d1;\n    dim[1] = d2;\n  };\n  ~view (void) {};\n  inline Scalar& operator () (int d1) {\n    return(data[d1]);\n  };\n  inline Scalar& operator () (int d1, int d2) {\n    return(data[d1 + dim[0] * d2]);\n  };\n  inline Scalar& operator () (int d1, int d2, int d3) {\n    return(data[d1 + dim[0] * (d2 + dim[1] * d3)]);\n  };\n};\n\n#endif\n\n#endif\n"
  },
  {
    "path": "src/pomp_fun.c",
    "content": "// dear emacs, please treat this as -*- C++ -*-\n\n#include <R.h>\n#include <Rdefines.h>\n\n#include <R_ext/Rdynload.h>\n\n#include \"internal.h\"\n\nstatic R_INLINE SEXP name_index (SEXP provided, SEXP object, const char *slot, const char *humanreadable) {\n  SEXP slotnames, index;\n  PROTECT(slotnames = GET_SLOT(object,install(slot)));\n  if (LENGTH(slotnames) > 0) {\n    PROTECT(index = matchnames(provided,slotnames,humanreadable));\n  } else {\n    PROTECT(index = NEW_INTEGER(0));\n  }\n  UNPROTECT(2);\n  return index;\n}\n\n// Returns either the R function or the address of the native routine.\n// On return, mode indicates the mode of the 'pomp_fun'\n// (i.e., R function, external function, or C snippet).\n// If 'gnsi' is set to TRUE, we look up the native symbol information in the DLL,\n// storing it in the 'address' slot.\n// If 'gsni' is TRUE, and there are names in one or more of the S,P,O,C arguments, we look up the\n// names in the corresponding 'pomp_fun' slots and storing the corresponding index\n// inside the 'pomp_fun'.\nSEXP pomp_fun_handler (SEXP pfun, SEXP gnsi, pompfunmode *mode,\n                       SEXP S, SEXP P, SEXP O, SEXP C)\n{\n  int nprotect = 0;\n  SEXP f = R_NilValue;\n  SEXP sidx, pidx, oidx, cidx;\n\n  *mode = *(INTEGER(GET_SLOT(pfun,install(\"mode\"))));\n\n  switch (*mode) {\n\n  case Rfun:                    // R function\n\n    PROTECT(f = GET_SLOT(pfun,install(\"R.fun\"))); nprotect++;\n\n    break;\n\n  case native: case regNative:  // native code\n\n    if (*(LOGICAL(gnsi))) {     // get native symbol information?\n\n      SEXP nf, pack;\n      PROTECT(nf = GET_SLOT(pfun,install(\"native.fun\")));\n      PROTECT(pack = GET_SLOT(pfun,install(\"PACKAGE\")));\n      nprotect += 2;\n\n      if (LENGTH(pack) < 1) {\n        PROTECT(pack = mkString(\"\")); nprotect++; // #nocov\n      }\n\n      if (*mode == native) {\n\n        SEXP nsi;\n        PROTECT(nsi = eval(PROTECT(lang3(install(\"getNativeSymbolInfo\"),nf,pack)),R_BaseEnv));\n        PROTECT(f = getListElement(nsi,\"address\"));\n        nprotect += 3;\n\n      } else if (*mode == regNative) {\n\n        const char *fname, *pkg;\n        fname = (const char *) CHAR(STRING_ELT(nf,0));\n        pkg = (const char *) CHAR(STRING_ELT(pack,0));\n        DL_FUNC fn;\n        fn = R_GetCCallable(pkg,fname);\n        PROTECT(f = R_MakeExternalPtrFn(fn,R_NilValue,R_NilValue)); nprotect++;\n\n      }\n\n      SET_SLOT(pfun,install(\"address\"),f);\n\n      if (S != NA_STRING) {\n        PROTECT(sidx = name_index(S,pfun,\"statenames\",\"state variables\")); nprotect++;\n        SET_SLOT(pfun,install(\"stateindex\"),sidx);\n      }\n\n      if (P != NA_STRING) {\n        PROTECT(pidx = name_index(P,pfun,\"paramnames\",\"parameters\")); nprotect++;\n        SET_SLOT(pfun,install(\"paramindex\"),pidx);\n      }\n\n      if (O != NA_STRING) {\n        PROTECT(oidx = name_index(O,pfun,\"obsnames\",\"observables\")); nprotect++;\n        SET_SLOT(pfun,install(\"obsindex\"),oidx);\n      }\n\n      if (C != NA_STRING) {\n        PROTECT(cidx = name_index(C,pfun,\"covarnames\",\"covariates\")); nprotect++;\n        SET_SLOT(pfun,install(\"covarindex\"),cidx);\n      }\n\n    } else {                    // native symbol info is stored\n\n      PROTECT(f = GET_SLOT(pfun,install(\"address\"))); nprotect++;\n\n    }\n\n    break;\n\n  case undef: default:\n\n    PROTECT(f = R_NilValue); nprotect++;\n    *mode = undef;\n\n    break;\n\n  }\n\n  UNPROTECT(nprotect);\n  return f;\n}\n\nSEXP load_stack_incr (SEXP pack) {\n  const char *pkg;\n  void (*ff)(void);\n  pkg = (const char *) CHAR(STRING_ELT(pack,0));\n  ff = (void (*)(void)) R_GetCCallable(pkg,\"__pomp_load_stack_incr\");\n  ff();\n  return R_NilValue;\n}\n\nSEXP load_stack_decr (SEXP pack) {\n  SEXP s;\n  const char *pkg;\n  void (*ff)(int *);\n  PROTECT(s = ScalarInteger(NA_INTEGER));\n  pkg = (const char *) CHAR(STRING_ELT(pack,0));\n  ff = (void (*)(int *)) R_GetCCallable(pkg,\"__pomp_load_stack_decr\");\n  ff(INTEGER(s));\n  if (*(INTEGER(s)) < 0) err(\"impossible!\");\n  UNPROTECT(1);\n  return s;\n}\n"
  },
  {
    "path": "src/pomp_mat.h",
    "content": "#ifndef _POMP_MAT_H_\n#define _POMP_MAT_H_\n\n#include <Rconfig.h>\n#include <R_ext/Lapack.h>\n#ifndef FCONE\n#define FCONE\n#endif\n#include \"internal.h\"\n\nstatic R_INLINE void pomp_backsolve\n(\n double *a, int lda, int n, double *x, int incx,\n char *uplo, char *transpose, char *unit\n ) {\n  // Level 2 BLAS triangular-matrix solver DTRSV(UPLO,TRANS,DIAG,N,A,LDA,X,INCX)\n  // DTRSV:  x <- A ^{-1} x -or- x <- A ^{-T} x, A triangular\n  // N is the order of A\n  // LDA is A's leading dimension\n  // INCX is the increment between successive X locations\n  // UPLO is \"U\" or \"L\" depending on whether A is upper or lower triangular\n  // TRANSPOSE is \"T\" or \"N\" depending on whether the transpose is desired\n  // DIAG is \"U\" or \"N\" depending on whether A is unit triangular or not\n  F77_CALL(dtrsv)(uplo,transpose,unit,&n,a,&lda,x,&incx FCONE FCONE FCONE);\n}\n\nstatic R_INLINE void pomp_qr\n(\n double *a, int m, int n, int *pivot, double *tau\n ) {\n  int info, j, lwork = -1;\n  double work1;\n  // zero out the pivots (assumed by DGEQP3)\n  for (j = 0; j < n; j++) pivot[j] = 0;\n  // LAPACK QR decomposition routine\n  // DGEQP3(M,N,A,LDA,JPVT,TAU,WORK,LWORK,INFO)\n  F77_CALL(dgeqp3)(&m,&n,a,&m,pivot,tau,&work1,&lwork,&info); // workspace query\n  lwork = (int) ceil(work1);\n  {\n    double work[lwork];\n    F77_CALL(dgeqp3)(&m,&n,a,&m,pivot,tau,work,&lwork,&info); // actual call\n  }\n  for (j = 0; j < n; j++) pivot[j]--;\n}\n\nstatic R_INLINE void pomp_qrqy\n(\n double *c, double *a, int lda, double *tau,\n int m, int n, int k, char *side, char *transpose\n ) {\n  int info, lwork = -1;\n  double work1;\n  // workspace query\n  // DORMQR(SIDE,TRANS,M,N,K,A,LDA,TAU,C,LDC,WORK,LWORK,INFO)\n  F77_CALL(dormqr)(side,transpose,&m,&n,&k,a,&lda,tau,c,&m,&work1,&lwork,&info FCONE FCONE);\n  lwork = (int) ceil(work1);\n  {                             // actual call\n    double work[lwork];\n    F77_CALL(dormqr)(side,transpose,&m,&n,&k,a,&lda,tau,c,&m,work,&lwork,&info FCONE FCONE);\n  }\n}\n\n#endif\n"
  },
  {
    "path": "src/probe.c",
    "content": "// -*- mode: C++; -*-\n#include \"internal.h\"\n\nSEXP apply_probe_data (SEXP object, SEXP probes) {\n  SEXP retval, data, vals;\n  int nprobe;\n  int i;\n\n  nprobe = LENGTH(probes);\n  PROTECT(data = GET_SLOT(object,install(\"data\")));\n  PROTECT(vals = NEW_LIST(nprobe));\n  SET_NAMES(vals,GET_NAMES(probes));\n\n  for (i = 0; i < nprobe; i++) {\n    SET_ELEMENT(vals,i,eval(PROTECT(lang2(VECTOR_ELT(probes,i),data)),\n                            R_ClosureEnv(VECTOR_ELT(probes,i))));\n    if (!IS_NUMERIC(VECTOR_ELT(vals,i))) {\n      err(\"probe %d returns a non-numeric result\",i+1);\n    }\n    UNPROTECT(1);\n  }\n  PROTECT(vals = VectorToPairList(vals));\n  PROTECT(retval = eval(PROTECT(LCONS(install(\"c\"),vals)),R_BaseEnv));\n\n  UNPROTECT(5);\n  return retval;\n}\n\nSEXP apply_probe_sim (SEXP object, SEXP nsim, SEXP params,\n                      SEXP probes, SEXP datval, SEXP gnsi) {\n  SEXP x, y, names, sims;\n  SEXP returntype, retval, val, valnames;\n  int nprobe, nsims, nobs, ntimes, nvals;\n  int xdim[2];\n  double *xp, *yp;\n  int p, s, i, j, k, len0 = 0, len = 0;\n\n  PROTECT(nsim = AS_INTEGER(nsim));\n  if ((LENGTH(nsim)!=1) || (INTEGER(nsim)[0]<=0))\n    err(\"'nsim' must be a positive integer.\"); // #nocov\n\n  PROTECT(gnsi = duplicate(gnsi));\n\n  // 'names' holds the names of the probe values\n  // we get these from a previous call to 'apply_probe_data'\n  nprobe = LENGTH(probes);\n  nvals = LENGTH(datval);\n  PROTECT(names = GET_NAMES(datval));\n  PROTECT(returntype = NEW_INTEGER(1));\n  *(INTEGER(returntype)) = 0;\n  PROTECT(sims = do_simulate(object,params,nsim,returntype,gnsi));\n  PROTECT(y = VECTOR_ELT(sims,1));\n  *(INTEGER(gnsi)) = 0;\n\n  nobs = INTEGER(GET_DIM(y))[0];\n  nsims = INTEGER(GET_DIM(y))[1];\n  ntimes = INTEGER(GET_DIM(y))[2];\n  // set up temporary storage\n  xdim[0] = nobs; xdim[1] = ntimes;\n  PROTECT(x = makearray(2,xdim));\n  setrownames(x,GET_ROWNAMES(GET_DIMNAMES(y)),2);\n\n  // set up matrix to hold results\n  xdim[0] = nsims; xdim[1] = nvals;\n  PROTECT(retval = makearray(2,xdim));\n  PROTECT(valnames = NEW_LIST(2));\n  SET_ELEMENT(valnames,1,names);        // set column names\n  SET_DIMNAMES(retval,valnames);\n\n  for (p = 0, k = 0; p < nprobe; p++, k += len) { // loop over probes\n\n    R_CheckUserInterrupt();\n\n    for (s = 0; s < nsims; s++) { // loop over simulations\n\n      // copy the data from y[,s,] to x[,]\n      xp = REAL(x);\n      yp = REAL(y)+nobs*s;\n      for (j = 0; j < ntimes; j++, yp += nobs*nsims) {\n        for (i = 0; i < nobs; i++, xp++) *xp = yp[i];\n      }\n\n      // evaluate the probe on the simulated data\n      PROTECT(val = eval(PROTECT(lang2(VECTOR_ELT(probes,p),x)),\n                         R_ClosureEnv(VECTOR_ELT(probes,p))));\n      if (!IS_NUMERIC(val)) {\n        err(\"probe %d returns a non-numeric result.\",p+1);\n      }\n\n      len = LENGTH(val);\n      if (s == 0)\n        len0 = len;\n      else if (len != len0) {\n        err(\"variable-sized results returned by probe %d.\",p+1);\n      }\n      if (k+len > nvals)\n        err(\"probes return different number of values on different datasets.\");\n\n      xp = REAL(retval); yp = REAL(val);\n      for (i = 0; i < len; i++) xp[s+nsims*(i+k)] = yp[i];\n\n      UNPROTECT(2);\n    }\n\n  }\n  if (k != nvals)\n    err(\"probes return different number of values on different datasets.\"); // #nocov\n\n  UNPROTECT(9);\n  return retval;\n}\n"
  },
  {
    "path": "src/probe_acf.c",
    "content": "// -*- mode: C++ -*-\n\n#include \"internal.h\"\n#include <stdio.h>\n\n// vectorized routine for ACF calculation\n// thanks to Simon N. Wood for the original version of this code.\n// modifications due to AAK.\n// Note that the behavior of this ACF is slightly different from that of R's 'acf' function\n// we first center the series and then compute means of products.\nstatic void pomp_acf_compute (double *acf, double *x, int n, int nvars, int *lags, int nlag) {\n  double *p, *p0, *p1, *p2;\n  long double xx;\n  int i, j, k, lag, ct;\n\n  // first center each row\n  for (j = 0, p = x; j < nvars; j++, p++) {\n    for (k = 0, p0 = p, xx = 0, ct = 0; k < n; p0 += nvars, k++) {\n      if (R_FINITE(*p0)) {\n        xx += *p0;\n        ct++;\n      }\n    }\n    if (ct < 1) err(\"series %d has no data\",j+1);\n    xx /= ct;                   // mean of x[j,]\n    for (k = 0, p0 = p; k < n; p0 += nvars, k++)\n      if (R_FINITE(*p0)) *p0 -= xx;\n  }\n\n  // compute covariances\n  for (j = 0, p0 = x, p = acf; j < nvars; j++, p0++) { // loop over series\n    for (i = 0; i < nlag; i++, p++) { // loop over lags\n      lag = lags[i];                  // i-th lag\n      for (k = 0, ct = 0, xx = 0, p1 = p0, p2 = p0+lag*nvars; k < n-lag; k++, p1 += nvars, p2 += nvars)\n        if (R_FINITE(*p1) && R_FINITE(*p2)) {\n          xx += (*p1)*(*p2);\n          ct++;\n        }\n      *p = (ct > 0) ? xx/ct : R_NaReal;\n    }\n  }\n\n}\n\n// vectorized routine for CCF calculation\n// we first center the series and then compute means of products\nstatic void pomp_ccf_compute (double *ccf, double *x, double *y, int n, int *lags, int nlag) {\n  double *p, *p1, *p2;\n  long double xx;\n  int j, k, lag, ct;\n\n  // first center x\n  for (k = 0, xx = 0, ct = 0, p = x; k < n; k++, p++) {\n    if (R_FINITE(*p)) {\n      xx += *p;\n      ct++;\n    }\n  }\n  if (ct < 1) err(\"series 1 has no data\");\n  xx /= ct;                     // mean of x[j]\n  for (k = 0, p = x; k < n; k++, p++) {\n    if (R_FINITE(*p)) *p -= xx;\n  }\n\n  // now center y\n  for (k = 0, xx = 0, ct = 0, p = y; k < n; k++, p++) {\n    if (R_FINITE(*p)) {\n      xx += *p;\n      ct++;\n    }\n  }\n  if (ct < 1) err(\"series 2 has no data\");\n  xx /= ct;                     // mean of y[j]\n  for (k = 0, p = y; k < n; k++, p++) {\n    if (R_FINITE(*p)) *p -= xx;\n  }\n\n  // compute covariances\n  for (j = 0, p = ccf; j < nlag; j++, p++) { // loop over lags\n    lag = lags[j];\n    if (lag < 0) {\n      for (k = 0, xx = 0, ct = 0, p1 = x-lag, p2 = y; k < n+lag; k++, p1++, p2++)\n        if (R_FINITE(*p1) && R_FINITE(*p1)) {\n          xx += (*p1)*(*p2);\n          ct++;\n        }\n      *p = (ct > 0) ? xx/ct : R_NaReal;\n    } else {\n      for (k = 0, xx = 0, ct = 0, p1 = x, p2 = y+lag; k < n-lag; k++, p1++, p2++)\n        if (R_FINITE(*p1) && R_FINITE(*p1)) {\n          xx += (*p1)*(*p2);\n          ct++;\n        }\n      *p = (ct > 0) ? xx/ct : R_NaReal;\n    }\n  }\n\n}\n\nSEXP probe_acf (SEXP x, SEXP lags, SEXP corr) {\n  SEXP ans, ans_names;\n  SEXP X;\n  int nlag, correlation, nvars, n;\n  int j, k, l;\n  double *p, *p1, *cov;\n  int *lag;\n  char tmp[BUFSIZ];\n\n  nlag = LENGTH(lags);                        // number of lags\n  PROTECT(lags = AS_INTEGER(lags));\n  lag = INTEGER(lags);\n  correlation = *(INTEGER(AS_INTEGER(corr))); // correlation, or covariance?\n\n  nvars = INTEGER(GET_DIM(x))[0];       // number of variables\n  n = INTEGER(GET_DIM(x))[1];               // number of observations\n\n  PROTECT(X = duplicate(AS_NUMERIC(x)));\n\n  PROTECT(ans = NEW_NUMERIC(nlag*nvars));\n\n  pomp_acf_compute(REAL(ans),REAL(X),n,nvars,lag,nlag);\n\n  if (correlation) {\n    l = 0;\n    cov = (double *) R_alloc(nvars,sizeof(double));\n    pomp_acf_compute(cov,REAL(X),n,nvars,&l,1); // compute lag-0 covariance\n    for (j = 0, p = REAL(ans), p1 = cov; j < nvars; j++, p1++)\n      for (k = 0; k < nlag; k++, p++)\n        *p /= *p1;\n  }\n\n  PROTECT(ans_names = NEW_STRING(nlag*nvars));\n  for (j = 0, l = 0; j < nvars; j++) {\n    for (k = 0; k < nlag; k++, l++) {\n      snprintf(tmp,BUFSIZ,\"acf[%d]\",lag[k]);\n      SET_STRING_ELT(ans_names,l,mkChar(tmp));\n    }\n  }\n  SET_NAMES(ans,ans_names);\n\n  UNPROTECT(4);\n  return ans;\n}\n\nSEXP probe_ccf (SEXP x, SEXP y, SEXP lags, SEXP corr) {\n  SEXP ans, ans_names;\n  SEXP X, Y;\n  double cov[2], xx, *p;\n  int nlag, n, correlation;\n  int k;\n  char tmp[BUFSIZ];\n\n  nlag = LENGTH(lags);\n  PROTECT(lags = AS_INTEGER(lags));\n  correlation = *(INTEGER(AS_INTEGER(corr))); // correlation, or covariance?\n\n  n = LENGTH(x);                // n = # of observations\n  if (n != LENGTH(y)) err(\"'x' and 'y' must have equal lengths\"); // #nocov\n\n  PROTECT(X = duplicate(AS_NUMERIC(x)));\n  PROTECT(Y = duplicate(AS_NUMERIC(y)));\n\n  PROTECT(ans = NEW_NUMERIC(nlag));\n\n  pomp_ccf_compute(REAL(ans),REAL(X),REAL(Y),n,INTEGER(lags),nlag);\n\n  if (correlation) {\n    k = 0;\n    pomp_acf_compute(&cov[0],REAL(X),n,1,&k,1); // compute lag-0 covariance of x\n    pomp_acf_compute(&cov[1],REAL(Y),n,1,&k,1); // compute lag-0 covariance of y\n    xx = sqrt(cov[0]*cov[1]);\n    for (k = 0, p = REAL(ans); k < nlag; k++, p++) *p /= xx; // convert to correlation\n  }\n\n  PROTECT(ans_names = NEW_STRING(nlag));\n  for (k = 0; k < nlag; k++) {\n    snprintf(tmp,BUFSIZ,\"ccf[%d]\",INTEGER(lags)[k]);\n    SET_STRING_ELT(ans_names,k,mkChar(tmp));\n  }\n  SET_NAMES(ans,ans_names);\n\n  UNPROTECT(5);\n  return ans;\n}\n"
  },
  {
    "path": "src/probe_marginal.c",
    "content": "// -*- mode: C++ -*-\n\n#include \"internal.h\"\n#include \"pomp_mat.h\"\n#include <stdio.h>\n\nstatic void order_reg_solve (double *beta, double *x, double *mm, double *tau, int *pivot, int n, int np, int diff);\nstatic void order_reg_model_matrix (double *z, double *X, double *tau, int *pivot, int n, int np, int diff);\n\nSEXP probe_marginal_setup (SEXP ref, SEXP order, SEXP diff) {\n  SEXP z, mm, tau, pivot, retval, retvalnames;\n  int n, nx, np, df, dim[2];\n\n  np = *(INTEGER(AS_INTEGER(order))); // order of polynomial regression\n  df = *(INTEGER(AS_INTEGER(diff)));  // order of differencing\n  n = LENGTH(ref);                    // n = number of observations\n  nx = n - df;                        // nx = rows in model matrix\n  dim[0] = nx; dim[1] = np;           // dimensions of model matrix\n\n  if (nx < 1) err(\"must have diff < number of observations\");\n\n  PROTECT(z = duplicate(AS_NUMERIC(ref)));\n  PROTECT(mm = makearray(2,dim));\n  PROTECT(tau = NEW_NUMERIC(np));\n  PROTECT(pivot = NEW_INTEGER(np));\n\n  PROTECT(retval = NEW_LIST(3));\n  PROTECT(retvalnames = NEW_CHARACTER(3));\n  SET_STRING_ELT(retvalnames,0,mkChar(\"mm\"));\n  SET_STRING_ELT(retvalnames,1,mkChar(\"tau\"));\n  SET_STRING_ELT(retvalnames,2,mkChar(\"pivot\"));\n  SET_ELEMENT(retval,0,mm);\n  SET_ELEMENT(retval,1,tau);\n  SET_ELEMENT(retval,2,pivot);\n  SET_NAMES(retval,retvalnames);\n\n  order_reg_model_matrix(REAL(z),REAL(mm),REAL(tau),INTEGER(pivot),n,np,df);\n\n  UNPROTECT(6);\n  return(retval);\n}\n\nSEXP probe_marginal_solve (SEXP x, SEXP setup, SEXP diff) {\n  SEXP X, mm, tau, pivot, beta, beta_names;\n  int n, nx, np, df;\n  int i;\n  char tmp[BUFSIZ];\n\n  df = *(INTEGER(AS_INTEGER(diff)));  // order of differencing\n  n = LENGTH(x);                      // n = number of observations\n\n  // unpack the setup information\n  PROTECT(mm = VECTOR_ELT(setup,0));    //  QR-decomposed model matrix\n  PROTECT(tau = VECTOR_ELT(setup,1));   // diagonals\n  PROTECT(pivot = VECTOR_ELT(setup,2)); // pivots\n\n  nx = INTEGER(GET_DIM(mm))[0]; // nx = number of rows in model matrix\n  np = INTEGER(GET_DIM(mm))[1]; // np = order of polynomial\n\n  if (n-df != nx) err(\"length of 'ref' must equal length of data\");\n  PROTECT(X = duplicate(AS_NUMERIC(x)));\n\n  PROTECT(beta = NEW_NUMERIC(np));\n  PROTECT(beta_names = NEW_STRING(np));\n  for (i = 0; i < np; i++) {\n    snprintf(tmp,BUFSIZ,\"marg.%d\",i+1);\n    SET_STRING_ELT(beta_names,i,mkChar(tmp));\n  }\n  SET_NAMES(beta,beta_names);\n\n  order_reg_solve(REAL(beta),REAL(X),REAL(mm),REAL(tau),INTEGER(pivot),n,np,df);\n\n  UNPROTECT(6);\n  return(beta);\n}\n\n// thanks to Simon N. Wood for the original version of the following code\nstatic void order_reg_model_matrix (double *z, double *X, double *tau, int *pivot, int n, int np, int diff) {\n  //   z is an n vector, containing no NAs\n  //   X is an (n-diff) by np double matrix\n  //   pivot is an (n-diff) integer vector\n  //   tau is an (n-diff) double vector\n  //   This routine first differences z 'diff' times.\n  //   z is centred and sorted\n  //   then the model matrix is set up and QR decomposed\n  int nx;\n  double *X1, *X2, xx;\n  int i, j;\n\n  for (i = 0, nx = n; i < diff; i++) { // differencing loop\n    nx--;\n    for (j = 0; j < nx; j++) z[j] = z[j+1] - z[j];\n  }\n  // nx = number of rows in model matrix\n  // z is now an nx-vector\n\n  // center z\n  for (j = 0, xx = 0.0; j < nx; j++) xx += z[j];\n  xx /= nx; // xx = mean(z)\n  for (j = 0; j < nx; j++) z[j] -= xx;\n\n  // now sort\n  R_qsort(z,1,nx);\n\n  // Now create the model matrix, using contents of z\n  if (np < 1) np = 1;\n  for (j = 0; j < nx; j++) X[j] = z[j]; // first column\n  for (i = 1, X1 = X, X2 = X+nx; i < np; i++, X1 += nx, X2 += nx)\n    for (j = 0; j < nx; j++) X2[j] = X1[j]*z[j];\n\n  // QR decompose the model matrix\n  pomp_qr(X,nx,np,pivot,tau);\n\n}\n\n// thanks to Simon N. Wood for the original version of the following code\nstatic void order_reg_solve (double *beta, double *x, double *mm, double *tau, int *pivot, int n, int np, int diff) {\n  int nx;\n  double xx;\n  int i, j;\n\n  for (i = 0, nx = n; i < diff; i++) { // differencing loop\n    nx--;\n    for (j = 0; j < nx; j++) x[j] = x[j+1] - x[j];\n  }\n  // nx = number of rows in model matrix\n  // x is now an nx-vector\n\n  // center x\n  for (j = 0, xx = 0.0; j < nx; j++) xx += x[j];\n  xx /= nx; // xx = mean(x)\n  for (j = 0; j < nx; j++) x[j] -= xx;\n\n  // now sort\n  R_qsort(x,1,nx);\n\n  // solve R b = Q'x for b\n  pomp_qrqy(x,mm,nx,tau,nx,1,np,\"left\",\"transpose\"); // y <- Q'y\n  pomp_backsolve(mm,nx,np,x,1,\"Upper\",\"No transpose\",\"Non-unit\");   // y <- R^{-1} y\n\n  // unpivot and store the coefficients in beta\n  for (i = 0; i < np; i++) beta[pivot[i]] = x[i];\n\n}\n"
  },
  {
    "path": "src/probe_nlar.c",
    "content": "// -*- mode: C++; -*-\n\n#include \"internal.h\"\n#include \"pomp_mat.h\"\n#include <stdio.h>\n\nstatic void poly_nlar_fit(double *beta, double *y, int n, int nterms, int *lag, int *power, double *X);\n\nSEXP probe_nlar (SEXP x, SEXP lags, SEXP powers) {\n  SEXP y, beta, beta_names;\n  int n, nterms;\n  int k;\n  double *mm;\n  char tmp[BUFSIZ];\n\n  n = LENGTH(x);                // n = # of observations\n  nterms = LENGTH(lags);\n\n  PROTECT(y = duplicate(AS_NUMERIC(x)));\n  PROTECT(beta = NEW_NUMERIC(nterms));\n\n  mm = (double *) R_alloc(n*nterms,sizeof(double)); // storage for the model matrix\n  poly_nlar_fit(REAL(beta),REAL(y),n,nterms,INTEGER(lags),INTEGER(powers),mm);\n\n  PROTECT(beta_names = NEW_STRING(nterms));\n  for (k = 0; k < nterms; k++) {\n    snprintf(tmp,BUFSIZ,\"nlar.%d^%d\",INTEGER(lags)[k],INTEGER(powers)[k]);\n    SET_STRING_ELT(beta_names,k,mkChar(tmp));\n  }\n  SET_NAMES(beta,beta_names);\n\n  UNPROTECT(3);\n  return beta;\n}\n\n// Code for polynomial auto-regression\n// The original version of the following code is due to Simon N. Wood.\n// Modifications by AAK.\nstatic void poly_nlar_fit (double *beta, double *y, int n,\n                           int nterms, int *lag, int *power, double *X) {\n  // 'x' is an n vector of data.\n  // 'nterms' gives the number of terms on the rhs of the autoregression.\n  // 'lag[i]' gives the lag of the ith term on the rhs.\n  // 'power[i]' gives the power to which the ith rhs term should be raised.\n  // 'beta' contains the ar coefficients\n\n  int maxlag, nx, ny, ok, ct;\n  int i, j, k;\n  double xx, *yp;\n  double obs1;\n\n  // find maxlag\n  for (maxlag = 0, i = 0; i < nterms; i++)\n    maxlag = (lag[i] > maxlag) ? lag[i] : maxlag;\n  ny = n - maxlag;              // maximum response vector length\n\n  // compute the series mean\n  for (j = 0, ct = 0, xx = 0.0; j < n; j++)\n    if (R_FINITE(y[j])) {\n      xx += y[j];\n      ct++;\n    }\n  xx /= ct; // series mean\n\n  // center the whole series\n  // also check to see if there is any variability in the predictors\n  ok = 0;\n  obs1 = R_NaReal;\n  for (j = 0; j < n; j++) {\n    if (R_FINITE(y[j])) {\n      if (!ok && (j < ny)) {    // j < ny means x[j] is a predictor\n        if (!R_FINITE(obs1)) obs1 = y[j];\n        else if (y[j] != obs1) ok = 1;\n      }\n      y[j] -= xx;               // subtracting series mean\n    }\n  }\n\n  if (!ok) {                    // data had no variability\n\n    for (i = 0; i < nterms; i++) beta[i] = 0.0;\n\n  } else {                      // data not all the same\n\n    double *Xp;\n    int finite[ny];\n\n    // test for NA rows in model matrix and response vector\n    for (nx = 0, yp = y+maxlag, j = 0; j < ny; j++) {\n      finite[j] = (R_FINITE(yp[j])) ? 1 : 0; // finite response?\n      for (i = 0; i < nterms; i++)\n        finite[j] = (R_FINITE(yp[j-lag[i]])) ? finite[j] : 0; // finite in model matrix row j, column i\n      if (finite[j]) nx++;\n    }\n    // nx is now the number of non-NA rows in the model matrix\n\n    // build the model matrix, omitting NA rows\n    for (Xp = X, i = 0; i < nterms; i++) { // work through the terms\n      for (j = 0; j < ny; j++) {\n        if (finite[j]) {\n          xx = yp[j-lag[i]];    // current predictor\n          *Xp = xx;\n          for (k = 1; k < power[i]; k++) *Xp *= xx; // raise to the appropriate power\n          Xp++;\n        }\n      }\n    }\n    // X is now the nx by nterms model matrix\n\n    // drop the NA rows from the response data\n    for (i = 0, j = 0; j < ny; j++)\n      if (finite[j]) yp[i++] = yp[j]; // keep this row\n    // response vector is now length nx\n\n    {\n      double tau[nterms];\n      int pivot[nterms];\n\n      // first QR decompose the model matrix\n      pomp_qr(X,nx,nterms,pivot,tau);\n      // then solve R b = Q'y for b\n      pomp_qrqy(yp,X,nx,tau,nx,1,nterms,\"left\",\"transpose\"); // y <- Q'y\n      pomp_backsolve(X,nx,nterms,yp,1,\"Upper\",\"No transpose\",\"Non-unit\");   // y <- R^{-1} y\n\n      // unpivot and store coefficients in beta\n      for (i = 0; i < nterms; i++) beta[pivot[i]] = yp[i];\n\n    }\n\n  }\n\n}\n"
  },
  {
    "path": "src/resample.c",
    "content": "// -*- C++ -*-\n\n#include <Rdefines.h>\n#include \"internal.h\"\n\nSEXP systematic_resampling(SEXP weights, SEXP np);\nvoid nosort_resamp(int nw, double *w, int np, int *p, int offset);\n\nSEXP systematic_resampling (SEXP weights, SEXP np)\n{\n  int m, n;\n  SEXP perm;\n\n  m = *(INTEGER(AS_INTEGER(np)));\n  n = LENGTH(weights);\n  PROTECT(perm = NEW_INTEGER(m));\n  PROTECT(weights = AS_NUMERIC(weights));\n  GetRNGstate();\n  nosort_resamp(n,REAL(weights),m,INTEGER(perm),1);\n  PutRNGstate();\n  UNPROTECT(2);\n  return(perm);\n}\n\nvoid nosort_resamp (int nw, double *w, int np, int *p, int offset)\n{\n  int i, j;\n  double du, u;\n\n  for (j = 1; j < nw; j++) w[j] += w[j-1];\n\n  if (w[nw-1] <= 0.0)\n    err(\"in 'systematic_resampling': non-positive sum of weights\");\n\n  du = w[nw-1] / ((double) np);\n  u = -du*unif_rand();\n\n  for (i = 0, j = 0; j < np; j++) {\n    u += du;\n    // In the following line, the second test is needed to correct\n    // the infamous Bug of St. Patrick, 2017-03-17.\n    while ((u > w[i]) && (i < nw-1)) i++;\n    p[j] = i;\n  }\n  if (offset)                   // add offset if needed\n    for (j = 0; j < np; j++) p[j] += offset;\n\n}\n"
  },
  {
    "path": "src/rinit.c",
    "content": "// dear emacs, please treat this as -*- C++ -*-\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n\n#include \"internal.h\"\n\nstatic R_INLINE SEXP paste0 (SEXP a, SEXP b, SEXP c) {\n  SEXP p, v;\n  PROTECT(p = lang4(install(\"paste0\"),a,b,c));\n  PROTECT(v = eval(p,R_BaseEnv));\n  UNPROTECT(2);\n  return v;\n}\n\nstatic SEXP pomp_default_rinit(SEXP params, SEXP Pnames,\n                               int npar, int nrep, int nsim);\n\nstatic R_INLINE SEXP add_args (SEXP args, SEXP Pnames, SEXP Cnames)\n{\n  SEXP var;\n  int v;\n\n  PROTECT(args = VectorToPairList(args));\n\n  // Covariates\n  for (v = LENGTH(Cnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Cnames,v)));\n  }\n\n  // Parameters\n  for (v = LENGTH(Pnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Pnames,v)));\n  }\n\n  // Time\n  var = NEW_NUMERIC(1);\n  args = LCONS(var,args);\n  UNPROTECT(1);\n  PROTECT(args);\n  SET_TAG(args,install(\"t0\"));\n\n  UNPROTECT(1);\n  return args;\n\n}\n\nstatic R_INLINE SEXP eval_call\n(\n SEXP fn, SEXP args,\n double *t0, double *p, int npar, double *c, int ncov\n ) {\n\n  SEXP var = args, ans, ob;\n  int v;\n\n  *(REAL(CAR(var))) = *t0; var = CDR(var);\n  for (v = 0; v < npar; v++, p++, var=CDR(var)) *(REAL(CAR(var))) = *p;\n  for (v = 0; v < ncov; v++, c++, var=CDR(var)) *(REAL(CAR(var))) = *c;\n\n  PROTECT(ob = LCONS(fn,args));\n  PROTECT(ans = eval(ob,R_ClosureEnv(fn)));\n\n  UNPROTECT(2);\n  return ans;\n\n}\n\nstatic R_INLINE SEXP ret_array (int m, int n, SEXP names)\n{\n  int dim[2] = {m, n};\n  const char *dimnm[2] = {\"name\",\".id\"};\n  SEXP X;\n  PROTECT(X = makearray(2,dim));\n  fillrownames(X,names);\n  fixdimnames(X,dimnm,2);\n  UNPROTECT(1);\n  return X;\n}\n\nSEXP do_rinit (SEXP object, SEXP params, SEXP t0, SEXP nsim, SEXP gnsi)\n{\n\n  SEXP Pnames, Cnames, Snames, pcnames;\n  SEXP x = R_NilValue;\n  SEXP pompfun, fn, args;\n  pompfunmode mode = undef;\n  lookup_table_t covariate_table;\n  SEXP cvec;\n  double *cov;\n  int *dim;\n  int npar, nrep, nvar, ncovars, nsims, ns;\n\n  nsims = *(INTEGER(AS_INTEGER(nsim)));\n  PROTECT(params = as_matrix(params));\n  PROTECT(Pnames = GET_ROWNAMES(GET_DIMNAMES(params)));\n  PROTECT(pcnames = GET_COLNAMES(GET_DIMNAMES(params)));\n\n  dim = INTEGER(GET_DIM(params));\n  npar = dim[0]; nrep = dim[1];\n  ns = nsims*nrep;\n\n  // set up the covariate table\n  covariate_table = make_covariate_table(GET_SLOT(object,install(\"covar\")),&ncovars);\n  PROTECT(Cnames = get_covariate_names(GET_SLOT(object,install(\"covar\"))));\n  PROTECT(cvec = NEW_NUMERIC(ncovars));\n  cov = REAL(cvec);\n\n  table_lookup(&covariate_table,*(REAL(t0)),cov);\n\n  // extract userdata\n  PROTECT(args = GET_SLOT(object,install(\"userdata\")));\n\n  PROTECT(pompfun = GET_SLOT(object,install(\"rinit\")));\n  PROTECT(Snames = GET_SLOT(pompfun,install(\"statenames\")));\n\n  PROTECT(fn = pomp_fun_handler(pompfun,gnsi,&mode,Snames,Pnames,NA_STRING,Cnames));\n\n  int nprotect = 9;\n\n  switch (mode) {\n  case Rfun: {\n\n    SEXP ans;\n    double *time = REAL(AS_NUMERIC(t0));\n    double *ps = REAL(params);\n    double *xs, *xt = NULL;\n    int *midx;\n    int j;\n\n    PROTECT(args = add_args(args,Pnames,Cnames));\n    PROTECT(ans = eval_call(fn,args,time,ps,npar,cov,ncovars));\n    PROTECT(ans = AS_NUMERIC(ans));\n    PROTECT(Snames = GET_NAMES(ans));\n\n    if (invalid_names(Snames))\n      err(\"user 'rinit' must return a named numeric vector.\");\n\n    nvar = LENGTH(ans);\n    xs = REAL(ans);\n    midx = INTEGER(PROTECT(match(Pnames,Snames,0)));\n\n    for (j = 0; j < nvar; j++) {\n      if (midx[j] != 0)\n        err(\"a state variable and a parameter share the name: '%s'.\",CHAR(STRING_ELT(Snames,j)));\n    }\n\n    PROTECT(x = ret_array(nvar,ns,Snames));\n    xt = REAL(x);\n\n    memcpy(xt,xs,nvar*sizeof(double));\n\n    nprotect += 6;\n\n    for (j = 1, xt += nvar; j < ns; j++, xt += nvar) {\n      PROTECT(ans = eval_call(fn,args,time,ps+npar*(j%nrep),npar,cov,ncovars));\n      xs = REAL(ans);\n      if (LENGTH(ans) != nvar)\n        err(\"user 'rinit' returns vectors of variable length.\");\n      memcpy(xt,xs,nvar*sizeof(double));\n      UNPROTECT(1);\n    }\n\n  }\n\n    break;\n\n  case native: case regNative: {\n\n    int *sidx, *pidx, *cidx;\n    double *xt, *ps, time;\n    pomp_rinit *ff = NULL;\n    int j;\n\n    nvar = *INTEGER(GET_SLOT(object,install(\"nstatevars\")));\n    PROTECT(x = ret_array(nvar,ns,Snames)); nprotect++;\n\n    sidx = INTEGER(GET_SLOT(pompfun,install(\"stateindex\")));\n    pidx = INTEGER(GET_SLOT(pompfun,install(\"paramindex\")));\n    cidx = INTEGER(GET_SLOT(pompfun,install(\"covarindex\")));\n\n    // address of native routine\n    *((void **) (&ff)) = R_ExternalPtrAddr(fn);\n\n    GetRNGstate();\n\n    time = *(REAL(t0));\n\n    // loop over replicates\n    for (j = 0, xt = REAL(x), ps = REAL(params); j < ns; j++, xt += nvar)\n      (*ff)(xt,ps+npar*(j%nrep),time,sidx,pidx,cidx,cov);\n\n    PutRNGstate();\n\n  }\n\n    break;\n\n  default: {\n\n    PROTECT(x = pomp_default_rinit(params,Pnames,npar,nrep,ns)); nprotect++;\n\n  }\n\n    break;\n\n  }\n\n  // now add column names\n  if (nrep > 1) {\n    SEXP dn, xn;\n    int k, *p;\n\n    if (isNull(pcnames)) {\n      PROTECT(pcnames = NEW_INTEGER(nrep)); nprotect++;\n      for (k = 0, p = INTEGER(pcnames); k < nrep; k++, p++) *p = k+1;\n    }\n\n    if (nsims > 1) {\n      int k, *sp;\n      SEXP us;\n      PROTECT(us = mkString(\"_\"));\n      PROTECT(xn = NEW_INTEGER(ns));\n      for (k = 0, sp = INTEGER(xn); k < ns; k++, sp++) *sp = (k/nrep)+1;\n      PROTECT(xn = paste0(pcnames,us,xn));\n      PROTECT(dn = GET_DIMNAMES(x));\n      nprotect += 4;\n      SET_ELEMENT(dn,1,xn);\n      SET_DIMNAMES(x,dn);\n\n    } else {\n\n      PROTECT(dn = GET_DIMNAMES(x)); nprotect++;\n      SET_ELEMENT(dn,1,pcnames);\n      SET_DIMNAMES(x,dn);\n\n    }\n  }\n\n  UNPROTECT(nprotect);\n  return x;\n}\n\nstatic SEXP pomp_default_rinit (SEXP params, SEXP Pnames,\n                                int npar, int nrep, int nsim)\n{\n\n  SEXP fcall, pat, ivpnames, statenames, x;\n  int *pidx;\n  int nvar, j, k;\n  double *xp, *pp;\n\n  // extract names of IVPs using 'grep'\n  PROTECT(pat = mkString(\"[\\\\_\\\\.]0$\"));\n  PROTECT(fcall = LCONS(ScalarLogical(1),R_NilValue));\n  SET_TAG(fcall,install(\"value\"));\n  PROTECT(fcall = LCONS(Pnames,fcall));\n  SET_TAG(fcall,install(\"x\"));\n  PROTECT(fcall = LCONS(pat,fcall));\n  SET_TAG(fcall,install(\"pattern\"));\n  PROTECT(fcall = LCONS(install(\"grep\"),fcall));\n  PROTECT(ivpnames = eval(fcall,R_BaseEnv));\n\n  nvar = LENGTH(ivpnames);\n  if (nvar < 1)\n    warn(\"in default 'rinit': there are no parameters with suffix '.0' or '_0'. See '?rinit_spec'.\");\n\n  pidx = INTEGER(PROTECT(match(Pnames,ivpnames,0)));\n  for (k = 0; k < nvar; k++) pidx[k]--;\n\n  // construct names of state variables using 'sub'\n  PROTECT(fcall = LCONS(ivpnames,R_NilValue));\n  SET_TAG(fcall,install(\"x\"));\n  PROTECT(fcall = LCONS(mkString(\"\"),fcall));\n  SET_TAG(fcall,install(\"replacement\"));\n  PROTECT(fcall = LCONS(pat,fcall));\n  SET_TAG(fcall,install(\"pattern\"));\n  PROTECT(fcall = LCONS(install(\"sub\"),fcall));\n  PROTECT(statenames = eval(fcall,R_BaseEnv));\n\n  PROTECT(x = ret_array(nvar,nsim,statenames));\n\n  for (j = 0, xp = REAL(x); j < nsim; j++) {\n    pp = REAL(params) + npar*(j%nrep);\n    for (k = 0; k < nvar; k++, xp++) *xp = pp[pidx[k]];\n  }\n\n  UNPROTECT(13);\n  return x;\n}\n"
  },
  {
    "path": "src/rmeasure.c",
    "content": "// dear emacs, please treat this as -*- C++ -*-\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n\n#include \"internal.h\"\n\nstatic R_INLINE SEXP add_args (SEXP args, SEXP Snames, SEXP Pnames, SEXP Cnames)\n{\n\n  SEXP var;\n  int v;\n\n  PROTECT(args = VectorToPairList(args));\n\n  // we construct the call from end to beginning\n  // covariates, parameter, states, then time\n\n  // Covariates\n  for (v = LENGTH(Cnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Cnames,v)));\n  }\n\n  // Parameters\n  for (v = LENGTH(Pnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Pnames,v)));\n  }\n\n  // Latent state variables\n  for (v = LENGTH(Snames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Snames,v)));\n  }\n\n  // Time\n  var = NEW_NUMERIC(1);\n  args = LCONS(var,args);\n  UNPROTECT(1);\n  PROTECT(args);\n  SET_TAG(args,install(\"t\"));\n\n  UNPROTECT(1);\n  return args;\n\n}\n\nstatic R_INLINE SEXP eval_call (\n                                SEXP fn, SEXP args,\n                                double *t,\n                                double *x, int nvar,\n                                double *p, int npar,\n                                double *c, int ncov)\n{\n\n  SEXP var = args, ans, ob;\n  int v;\n\n  *(REAL(CAR(var))) = *t; var = CDR(var);\n  for (v = 0; v < nvar; v++, x++, var=CDR(var)) *(REAL(CAR(var))) = *x;\n  for (v = 0; v < npar; v++, p++, var=CDR(var)) *(REAL(CAR(var))) = *p;\n  for (v = 0; v < ncov; v++, c++, var=CDR(var)) *(REAL(CAR(var))) = *c;\n\n  PROTECT(ob = LCONS(fn,args));\n  PROTECT(ans = eval(ob,R_ClosureEnv(fn)));\n\n  UNPROTECT(2);\n  return ans;\n\n}\n\nstatic R_INLINE SEXP ret_array (int n, int nreps, int ntimes, SEXP names) {\n  int dim[3] = {n, nreps, ntimes};\n  const char *dimnm[3] = {\"name\", \".id\", \"time\"};\n  SEXP Y;\n\n  PROTECT(Y = makearray(3,dim));\n  setrownames(Y,names,3);\n  fixdimnames(Y,dimnm,3);\n\n  UNPROTECT(1);\n  return Y;\n\n}\n\nSEXP do_rmeasure (SEXP object, SEXP x, SEXP times, SEXP params, SEXP gnsi)\n{\n  pompfunmode mode = undef;\n  int ntimes, nvars, npars, ncovars, nreps, nrepsx, nrepsp;\n  int nobs = 0;\n  SEXP Snames, Pnames, Cnames, Onames = R_NilValue;\n  SEXP fn, args;\n  SEXP pompfun;\n  SEXP Y = R_NilValue;\n  int *dim;\n  lookup_table_t covariate_table;\n  SEXP cvec;\n  double *cov;\n\n  PROTECT(times = AS_NUMERIC(times));\n  ntimes = length(times);\n  if (ntimes < 1)\n    err(\"length('times') = 0, no work to do.\");\n\n  PROTECT(x = as_state_array(x));\n  dim = INTEGER(GET_DIM(x));\n  nvars = dim[0]; nrepsx = dim[1];\n\n  if (ntimes != dim[2])\n    err(\"length of 'times' and 3rd dimension of 'x' do not agree.\");\n\n  PROTECT(params = as_matrix(params));\n  dim = INTEGER(GET_DIM(params));\n  npars = dim[0]; nrepsp = dim[1];\n\n  nreps = (nrepsp > nrepsx) ? nrepsp : nrepsx;\n\n  if ((nreps % nrepsp != 0) || (nreps % nrepsx != 0))\n    err(\"larger number of replicates is not a multiple of smaller.\");\n\n  PROTECT(pompfun = GET_SLOT(object,install(\"rmeasure\")));\n\n  PROTECT(Snames = GET_ROWNAMES(GET_DIMNAMES(x)));\n  PROTECT(Pnames = GET_ROWNAMES(GET_DIMNAMES(params)));\n  PROTECT(Cnames = get_covariate_names(GET_SLOT(object,install(\"covar\"))));\n  PROTECT(Onames = GET_SLOT(pompfun,install(\"obsnames\")));\n\n  // set up the covariate table\n  covariate_table = make_covariate_table(GET_SLOT(object,install(\"covar\")),&ncovars);\n  PROTECT(cvec = NEW_NUMERIC(ncovars));\n  cov = REAL(cvec);\n\n  // extract the user-defined function\n  PROTECT(fn = pomp_fun_handler(pompfun,gnsi,&mode,Snames,Pnames,Onames,Cnames));\n\n  // extract 'userdata' as pairlist\n  PROTECT(args = GET_SLOT(object,install(\"userdata\")));\n\n  int nprotect = 11;\n  int first = 1;\n\n  // first do setup\n  switch (mode) {\n\n  case Rfun: {\n    double *ys, *yt = 0;\n    double *time = REAL(times), *xs = REAL(x), *ps = REAL(params);\n    SEXP ans;\n    int j, k;\n\n    PROTECT(args = add_args(args,Snames,Pnames,Cnames)); nprotect++;\n\n    for (k = 0; k < ntimes; k++, time++) { // loop over times\n\n      R_CheckUserInterrupt();   // check for user interrupt\n\n      table_lookup(&covariate_table,*time,cov); // interpolate the covariates\n\n      for (j = 0; j < nreps; j++) { // loop over replicates\n\n        if (first) {\n\n          PROTECT(\n                  ans = eval_call(\n                                  fn,args,\n                                  time,\n                                  xs+nvars*((j%nrepsx)+nrepsx*k),nvars,\n                                  ps+npars*(j%nrepsp),npars,\n                                  cov,ncovars\n                                  )\n                  );\n\n          nobs = LENGTH(ans);\n\n          PROTECT(Onames = GET_NAMES(ans));\n          if (invalid_names(Onames))\n            err(\"'rmeasure' must return a named numeric vector.\");\n\n          PROTECT(Y = ret_array(nobs,nreps,ntimes,Onames));\n\n          nprotect += 3;\n\n          yt = REAL(Y);\n          ys = REAL(AS_NUMERIC(ans));\n\n          memcpy(yt,ys,nobs*sizeof(double));\n          yt += nobs;\n\n          first = 0;\n\n        } else {\n\n          PROTECT(\n                  ans = eval_call(\n                                  fn,args,\n                                  time,\n                                  xs+nvars*((j%nrepsx)+nrepsx*k),nvars,\n                                  ps+npars*(j%nrepsp),npars,\n                                  cov,ncovars\n                                  )\n                  );\n\n          if (LENGTH(ans) != nobs)\n            err(\"'rmeasure' returns variable-length results.\");\n\n          ys = REAL(AS_NUMERIC(ans));\n\n          memcpy(yt,ys,nobs*sizeof(double));\n          yt += nobs;\n\n          UNPROTECT(1);\n\n        }\n\n      }\n    }\n\n  }\n\n    break;\n\n  case native: case regNative: {\n    double *yt = 0, *xp, *pp;\n    double *time = REAL(times), *xs = REAL(x), *ps = REAL(params);\n    int *oidx, *sidx, *pidx, *cidx;\n    pomp_rmeasure *ff = NULL;\n    int j, k;\n\n    nobs = LENGTH(Onames);\n    // extract observable, state, parameter covariate indices\n    sidx = INTEGER(GET_SLOT(pompfun,install(\"stateindex\")));\n    pidx = INTEGER(GET_SLOT(pompfun,install(\"paramindex\")));\n    oidx = INTEGER(GET_SLOT(pompfun,install(\"obsindex\")));\n    cidx = INTEGER(GET_SLOT(pompfun,install(\"covarindex\")));\n\n    // address of native routine\n    *((void **) (&ff)) = R_ExternalPtrAddr(fn);\n\n    PROTECT(Y = ret_array(nobs,nreps,ntimes,Onames)); nprotect++;\n    yt = REAL(Y);\n\n    GetRNGstate();\n\n    for (k = 0; k < ntimes; k++, time++) { // loop over times\n\n      R_CheckUserInterrupt();   // check for user interrupt\n\n      // interpolate the covar functions for the covariates\n      table_lookup(&covariate_table,*time,cov);\n\n      for (j = 0; j < nreps; j++, yt += nobs) { // loop over replicates\n\n        xp = &xs[nvars*((j%nrepsx)+nrepsx*k)];\n        pp = &ps[npars*(j%nrepsp)];\n\n        (*ff)(yt,xp,pp,oidx,sidx,pidx,cidx,cov,*time);\n\n      }\n    }\n\n    PutRNGstate();\n\n  }\n\n    break;\n\n  default: {\n    nobs = LENGTH(Onames);\n    int dim[3] = {nobs, nreps, ntimes};\n    const char *dimnm[3] = {\"name\",\".id\",\"time\"};\n    double *yt = 0;\n    int i, n = nobs*nreps*ntimes;\n\n    PROTECT(Y = makearray(3,dim)); nprotect++;\n    setrownames(Y,Onames,3);\n    fixdimnames(Y,dimnm,3);\n\n    for (i = 0, yt = REAL(Y); i < n; i++, yt++) *yt = R_NaReal;\n\n    warn(\"'rmeasure' unspecified: NAs generated.\");\n  }\n\n  }\n\n  UNPROTECT(nprotect);\n  return Y;\n}\n"
  },
  {
    "path": "src/rprior.c",
    "content": "// dear emacs, please treat this as -*- C++ -*-\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n\n#include \"internal.h\"\n\nstatic R_INLINE SEXP add_args (SEXP args, SEXP names)\n{\n\n  SEXP var;\n  int v;\n\n  PROTECT(args = VectorToPairList(args));\n\n  for (v = LENGTH(names)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(names,v)));\n  }\n\n  UNPROTECT(1);\n  return args;\n\n}\n\nstatic R_INLINE SEXP eval_call (SEXP fn, SEXP args, double *p, int n)\n{\n\n  SEXP var = args, ans, ob;\n  int v;\n\n  for (v = 0; v < n; v++, p++, var=CDR(var)) *(REAL(CAR(var))) = *p;\n\n  PROTECT(ob = LCONS(fn,args));\n  PROTECT(ans = eval(ob,R_ClosureEnv(fn)));\n\n  UNPROTECT(2);\n  return ans;\n\n}\n\nstatic R_INLINE SEXP ret_array (SEXP params)\n{\n  const char *dimnm[2] = {\"name\", \".id\"};\n  SEXP P;\n  PROTECT(P = as_matrix(params));\n  fixdimnames(P,dimnm,2);\n  UNPROTECT(1);\n  return P;\n\n}\n\nSEXP do_rprior (SEXP object, SEXP params, SEXP gnsi)\n{\n\n  pompfunmode mode = undef;\n  int npars, nreps;\n  SEXP Pnames, pompfun, fn, args;\n  int *dim;\n\n  PROTECT(params = ret_array(params));\n  dim = INTEGER(GET_DIM(params));\n  npars = dim[0]; nreps = dim[1];\n\n  PROTECT(Pnames = GET_ROWNAMES(GET_DIMNAMES(params)));\n\n  // extract the user-defined function\n  PROTECT(pompfun = GET_SLOT(object,install(\"rprior\")));\n  PROTECT(fn = pomp_fun_handler(pompfun,gnsi,&mode,NA_STRING,Pnames,NA_STRING,NA_STRING));\n\n  // extract 'userdata' as pairlist\n  PROTECT(args = GET_SLOT(object,install(\"userdata\")));\n\n  int nprotect = 5;\n  int first = 1;\n\n  switch (mode) {\n\n  case Rfun: {\n\n    SEXP ans, nm;\n    double *pa, *p = REAL(params);\n    int *posn = NULL;\n    int i, j;\n\n    // set up the function call\n    PROTECT(args = add_args(args,Pnames)); nprotect++;\n\n    for (j = 0; j < nreps; j++, p += npars) {\n\n      if (first) {\n\n        PROTECT(ans = eval_call(fn,args,p,npars));\n        PROTECT(ans = AS_NUMERIC(ans));\n\n        PROTECT(nm = GET_NAMES(ans));\n        if (invalid_names(nm))\n          err(\"'rprior' must return a named numeric vector.\");\n        posn = INTEGER(PROTECT(matchnames(Pnames,nm,\"parameters\")));\n\n        nprotect += 4;\n\n        pa = REAL(ans);\n        for (i = 0; i < LENGTH(ans); i++) p[posn[i]] = pa[i];\n\n        first = 0;\n\n      } else {\n\n        PROTECT(ans = eval_call(fn,args,p,npars));\n        PROTECT(ans = AS_NUMERIC(ans));\n\n        pa = REAL(ans);\n        for (i = 0; i < LENGTH(ans); i++) p[posn[i]] = pa[i];\n\n        UNPROTECT(2);\n\n      }\n    }\n  }\n\n    break;\n\n  case native: case regNative: {\n\n    double *p;\n    int *pidx = 0;\n    pomp_rprior *ff = NULL;\n    int j;\n\n    // extract parameter index\n    pidx = INTEGER(GET_SLOT(pompfun,install(\"paramindex\")));\n\n    // address of native routine\n    *((void **) (&ff)) = R_ExternalPtrAddr(fn);\n\n    R_CheckUserInterrupt();     // check for user interrupt\n\n    GetRNGstate();\n\n    // loop over replicates\n    for (j = 0, p = REAL(params); j < nreps; j++, p += npars)\n      (*ff)(p,pidx);\n\n    PutRNGstate();\n\n  }\n\n    break;\n\n  default: // just duplicate\n\n    warn(\"'rprior' unspecified: duplicating parameters.\");\n\n  }\n\n  UNPROTECT(nprotect);\n  return params;\n}\n"
  },
  {
    "path": "src/rprocess.c",
    "content": "// dear emacs, please treat this as -*- C++ -*-\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n\n#include \"internal.h\"\n\nstatic SEXP pomp_default_rprocess (SEXP xstart, int nvars, int nreps, int ntimes)\n{\n  SEXP Snames, X;\n  int dim[3] = {nvars, nreps, ntimes};\n  int i, n = nvars*nreps*ntimes;\n  double *xp = 0;\n  PROTECT(Snames = GET_ROWNAMES(GET_DIMNAMES(xstart)));\n  PROTECT(X = makearray(3,dim));\n  setrownames(X,Snames,3);\n  for (i= 0, xp = REAL(X); i < n; i++, xp++) *xp = R_NaReal;\n  warn(\"'rprocess' unspecified: NAs generated.\");\n  UNPROTECT(2);\n  return X;\n}\n\nSEXP do_rprocess (SEXP object, SEXP xstart, SEXP tstart, SEXP times, SEXP params, SEXP gnsi)\n{\n\n  int *xdim, type, nvars, npars, nreps, nrepsx, ntimes;\n  SEXP X, copy, rproc, args, accumvars, covar;\n  SEXP dimXstart, dimP;\n  const char *dimnm[3] = {\"name\",\".id\",\"time\"};\n\n  PROTECT(gnsi = duplicate(gnsi));\n\n  PROTECT(tstart = AS_NUMERIC(tstart));\n\n  PROTECT(times = AS_NUMERIC(times));\n  ntimes = length(times);\n  if (ntimes < 1) {\n    err(\"length(times) < 1: no work to do.\");\n  }\n\n  PROTECT(xstart = as_matrix(xstart));\n  PROTECT(dimXstart = GET_DIM(xstart));\n  xdim = INTEGER(dimXstart);\n  nvars = xdim[0]; nrepsx = xdim[1];\n\n  PROTECT(params = as_matrix(params));\n  PROTECT(dimP = GET_DIM(params));\n  xdim = INTEGER(dimP);\n  npars = xdim[0]; nreps = xdim[1];\n\n  int nprotect = 7;\n\n  if (nrepsx > nreps) {         // more ICs than parameters\n    if (nrepsx % nreps != 0) {\n      err(\"the larger number of replicates is not a multiple of smaller.\");\n    } else {\n      double *src, *tgt;\n      int dims[2];\n      int j, k;\n      dims[0] = npars; dims[1] = nrepsx;\n      PROTECT(copy = duplicate(params));\n      PROTECT(params = makearray(2,dims));\n      nprotect += 2;\n      setrownames(params,GET_ROWNAMES(GET_DIMNAMES(copy)),2);\n      src = REAL(copy);\n      tgt = REAL(params);\n      for (j = 0; j < nrepsx; j++) {\n        for (k = 0; k < npars; k++, tgt++) {\n          *tgt = src[k+npars*(j%nreps)];\n        }\n      }\n    }\n    nreps = nrepsx;\n  } else if (nrepsx < nreps) {  // more parameters than ICs\n    if (nreps % nrepsx != 0) {\n      err(\"the larger number of replicates is not a multiple of smaller.\");\n    } else {\n      double *src, *tgt;\n      int dims[2];\n      int j, k;\n      dims[0] = nvars; dims[1] = nreps;\n      PROTECT(copy = duplicate(xstart));\n      PROTECT(xstart = makearray(2,dims));\n      nprotect += 2;\n      setrownames(xstart,GET_ROWNAMES(GET_DIMNAMES(copy)),2);\n      src = REAL(copy);\n      tgt = REAL(xstart);\n      for (j = 0; j < nreps; j++) {\n        for (k = 0; k < nvars; k++, tgt++) {\n          *tgt = src[k+nvars*(j%nrepsx)];\n        }\n      }\n    }\n  }\n\n  PROTECT(rproc = GET_SLOT(object,install(\"rprocess\")));\n  PROTECT(args = GET_SLOT(object,install(\"userdata\")));\n  PROTECT(accumvars = GET_SLOT(object,install(\"accumvars\")));\n  PROTECT(covar = GET_SLOT(object,install(\"covar\")));\n\n  nprotect += 4;\n\n  // extract the process function\n  type = *(INTEGER(GET_SLOT(rproc,install(\"type\"))));\n  switch (type) {\n  case onestep: // one-step simulator\n    {\n      SEXP fn;\n      double deltat = 1.0;\n      PROTECT(fn = GET_SLOT(rproc,install(\"step.fn\")));\n      PROTECT(X = euler_simulator(fn,xstart,tstart,times,params,deltat,type,\n                                  accumvars,covar,args,gnsi));\n      nprotect += 2;\n    }\n    break;\n  case discrete: case euler: // discrete-time and Euler\n    {\n      SEXP fn;\n      double deltat;\n      PROTECT(fn = GET_SLOT(rproc,install(\"step.fn\")));\n      deltat = *(REAL(AS_NUMERIC(GET_SLOT(rproc,install(\"delta.t\")))));\n      PROTECT(X = euler_simulator(fn,xstart,tstart,times,params,deltat,type,\n                                  accumvars,covar,args,gnsi));\n      nprotect += 2;\n    }\n    break;\n  case gill: // Gillespie's method\n    {\n      SEXP fn, vmatrix, hmax;\n      PROTECT(fn = GET_SLOT(rproc,install(\"rate.fn\")));\n      PROTECT(vmatrix = GET_SLOT(rproc,install(\"v\")));\n      PROTECT(hmax = GET_SLOT(rproc,install(\"hmax\")));\n      PROTECT(X = SSA_simulator(fn,xstart,tstart,times,params,vmatrix,covar,\n                                accumvars,hmax,args,gnsi));\n      nprotect += 4;\n    }\n    break;\n  case dflt: default:\n    PROTECT(X = pomp_default_rprocess(xstart,nvars,nreps,ntimes));\n    nprotect++;\n    break;\n  }\n\n  fixdimnames(X,dimnm,3);\n  UNPROTECT(nprotect);\n  return X;\n\n}\n"
  },
  {
    "path": "src/simulate.c",
    "content": "// -*- C++ -*-\n\n#include <Rdefines.h>\n#include \"internal.h\"\n\nSEXP do_simulate (SEXP object, SEXP params, SEXP nsim, SEXP rettype, SEXP gnsi)\n{\n\n  SEXP t0, times, x0, x, y;\n  SEXP ans = R_NilValue, ans_names = R_NilValue;\n  SEXP simnames;\n  int return_type = *(INTEGER(rettype)); // 0 = array, 1 = pomps\n\n  if (LENGTH(nsim) != 1) err(\"'nsim' must be a single integer\"); // #nocov\n\n  PROTECT(params = as_matrix(params));\n\n  PROTECT(t0 = GET_SLOT(object,install(\"t0\")));\n  PROTECT(times = GET_SLOT(object,install(\"times\")));\n\n  // initialize the simulations\n  PROTECT(x0 = do_rinit(object,params,t0,nsim,gnsi));\n  PROTECT(simnames = GET_COLNAMES(GET_DIMNAMES(x0)));\n\n  // call 'rprocess' to simulate state process\n  PROTECT(x = do_rprocess(object,x0,t0,times,params,gnsi));\n\n  // call 'rmeasure' to simulate the measurement process\n  PROTECT(y = do_rmeasure(object,x,times,params,gnsi));\n\n  setcolnames(x,simnames);\n  setcolnames(y,simnames);\n\n  int nprotect = 7;\n\n  switch (return_type) {\n\n  case 0:  // return a list of arrays\n\n    PROTECT(ans = NEW_LIST(2));\n    PROTECT(ans_names = NEW_CHARACTER(2));\n    nprotect += 2;\n    SET_STRING_ELT(ans_names,0,mkChar(\"states\"));\n    SET_STRING_ELT(ans_names,1,mkChar(\"obs\"));\n    SET_NAMES(ans,ans_names);\n    SET_ELEMENT(ans,0,x);\n    SET_ELEMENT(ans,1,y);\n\n    break;\n\n  case 1: default:\n\n    // a list to hold the pomp objects\n    {\n      SEXP pp, xx, yy, po;\n      const int *xdim;\n      int nvar, npar, nobs, nsim, ntim, nparsets;\n      int dim[2], i, j, k;\n\n      PROTECT(po = duplicate(object));\n      SET_SLOT(po,install(\"t0\"),t0);\n      SET_SLOT(po,install(\"times\"),times);\n\n      xdim = INTEGER(GET_DIM(x));\n      nvar = xdim[0]; nsim = xdim[1]; ntim = xdim[2];\n\n      xdim = INTEGER(GET_DIM(y));\n      nobs = xdim[0]; // second dimensions of 'x' and 'y' must agree\n\n      xdim = INTEGER(GET_DIM(params));\n      npar = xdim[0]; nparsets = xdim[1];\n\n      dim[0] = nvar; dim[1] = ntim;\n      PROTECT(xx = makearray(2,dim));\n      setrownames(xx,GET_ROWNAMES(GET_DIMNAMES(x)),2);\n      SET_SLOT(po,install(\"states\"),xx);\n\n      dim[0] = nobs; dim[1] = ntim;\n      PROTECT(yy = makearray(2,dim));\n      setrownames(yy,GET_ROWNAMES(GET_DIMNAMES(y)),2);\n      SET_SLOT(po,install(\"data\"),yy);\n\n      PROTECT(pp = NEW_NUMERIC(npar));\n      SET_NAMES(pp,GET_ROWNAMES(GET_DIMNAMES(params)));\n      SET_SLOT(po,install(\"params\"),pp);\n\n      PROTECT(ans = NEW_LIST(nsim));\n      SET_NAMES(ans,simnames);\n\n      nprotect += 5;\n\n      for (k = 0; k < nsim; k++) {\n\n        SEXP po2;\n        double *xs = REAL(x), *ys = REAL(y), *ps = REAL(params);\n        double *xt, *yt, *pt;\n\n        PROTECT(po2 = duplicate(po));\n        xt = REAL(GET_SLOT(po2,install(\"states\")));\n        yt = REAL(GET_SLOT(po2,install(\"data\")));\n        pt = REAL(GET_SLOT(po2,install(\"params\")));\n\n        memcpy(pt,ps+npar*(k%nparsets),npar*sizeof(double));\n\n        // copy x[,k,] and y[,k,] into po2\n        for (j = 0; j < ntim; j++) {\n          for (i = 0; i < nvar; i++, xt++) *xt = xs[i+nvar*(k+nsim*j)];\n          for (i = 0; i < nobs; i++, yt++) *yt = ys[i+nobs*(k+nsim*j)];\n        }\n\n        SET_ELEMENT(ans,k,po2);\n        UNPROTECT(1);\n\n      }\n\n      break;\n\n    }\n\n  }\n\n  UNPROTECT(nprotect);\n  return ans;\n\n}\n"
  },
  {
    "path": "src/skeleton.c",
    "content": "// dear emacs, please treat this as -*- C++ -*-\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n\n#include \"internal.h\"\n\nSEXP add_skel_args (SEXP args, SEXP Snames, SEXP Pnames, SEXP Cnames)\n{\n\n  SEXP var;\n  int v;\n\n  PROTECT(args = VectorToPairList(args));\n\n  // Covariates\n  for (v = LENGTH(Cnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Cnames,v)));\n  }\n\n  // Parameters\n  for (v = LENGTH(Pnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Pnames,v)));\n  }\n\n  // Latent state variables\n  for (v = LENGTH(Snames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Snames,v)));\n  }\n\n  // Time\n  var = NEW_NUMERIC(1);\n  args = LCONS(var,args);\n  UNPROTECT(1);\n  PROTECT(args);\n  SET_TAG(args,install(\"t\"));\n\n  UNPROTECT(1);\n  return args;\n\n}\n\nstatic R_INLINE SEXP eval_call (\n                                SEXP fn, SEXP args,\n                                double *t,\n                                double *x, int nvar,\n                                double *p, int npar,\n                                double *c, int ncov)\n{\n\n  SEXP var = args, ans, ob;\n  int v;\n\n  *(REAL(CAR(var))) = *t; var = CDR(var);\n  for (v = 0; v < nvar; v++, x++, var=CDR(var)) *(REAL(CAR(var))) = *x;\n  for (v = 0; v < npar; v++, p++, var=CDR(var)) *(REAL(CAR(var))) = *p;\n  for (v = 0; v < ncov; v++, c++, var=CDR(var)) *(REAL(CAR(var))) = *c;\n\n  PROTECT(ob = LCONS(fn,args));\n  PROTECT(ans = eval(ob,R_ClosureEnv(fn)));\n\n  UNPROTECT(2);\n  return ans;\n\n}\n\nstatic R_INLINE SEXP ret_array (int nvars, int nreps, int ntimes, SEXP Snames)\n{\n  SEXP X;\n  int dim[3] = {nvars, nreps, ntimes};\n  const char *dimnms[3] = {\"name\",\".id\",\"time\"};\n  PROTECT(X = makearray(3,dim));\n  setrownames(X,Snames,3);\n  fixdimnames(X,dimnms,3);\n  UNPROTECT(1);\n  return X;\n}\n\nvoid eval_skeleton_R\n(\n double *f, double *time, double *x, double *p,\n SEXP fn, SEXP args, SEXP Snames,\n int nvars, int npars, int ncovars, int ntimes,\n int nrepx, int nrepp, int nreps,\n lookup_table_t *covar_table, double *cov\n ) {\n\n  SEXP ans, nm;\n  double *fs;\n  int *posn = 0;\n  int i, j, k;\n  int first = 1;\n  int nprotect = 0;\n\n  for (k = 0; k < ntimes; k++, time++) {\n\n    R_CheckUserInterrupt();\n\n    // interpolate the covar functions for the covariates\n    table_lookup(covar_table,*time,cov);\n\n    for (j = 0; j < nreps; j++, f += nvars) {\n\n      if (first) {\n\n        PROTECT(ans = eval_call(fn,args,time,\n                                x+nvars*((j%nrepx)+nrepx*k),nvars,\n                                p+npars*(j%nrepp),npars,\n                                cov,ncovars));\n\n        if (LENGTH(ans)!=nvars)\n          err(\"'skeleton' returns a vector of %d state variables but %d are expected.\",LENGTH(ans),nvars);\n\n        // get name information to fix alignment problems\n        PROTECT(nm = GET_NAMES(ans));\n        if (invalid_names(nm))\n          err(\"'skeleton' must return a named numeric vector.\");\n        posn = INTEGER(PROTECT(matchnames(Snames,nm,\"state variables\")));\n\n        fs = REAL(AS_NUMERIC(ans));\n        for (i = 0; i < nvars; i++) f[posn[i]] = fs[i];\n\n        nprotect += 3;\n        first = 0;\n\n      } else {\n\n        PROTECT(ans = eval_call(fn,args,time,\n                                x+nvars*((j%nrepx)+nrepx*k),nvars,\n                                p+npars*(j%nrepp),npars,\n                                cov,ncovars));\n\n        fs = REAL(AS_NUMERIC(ans));\n        for (i = 0; i < nvars; i++) f[posn[i]] = fs[i];\n\n        UNPROTECT(1);\n\n      }\n\n    }\n  }\n\n  UNPROTECT(nprotect);\n\n}\n\nvoid iterate_skeleton_R (\n                         double *X, double t, double deltat,\n                         double *time, double *x, double *p,\n                         SEXP fn, SEXP args, SEXP Snames,\n                         int nvars, int npars, int ncovars, int ntimes,\n                         int nrepp, int nreps, int nzeros,\n                         lookup_table_t *covar_table, int *zeroindex,\n                         double *cov)\n{\n\n  SEXP ans, nm;\n  double *ap, *xs;\n  int nsteps;\n  int *posn = 0;\n  int h, i, j, k;\n  int first = 1;\n  int nprotect = 0;\n\n  for (k = 0; k < ntimes; k++, time++, X += nvars*nreps) {\n\n    R_CheckUserInterrupt();\n\n    // compute number of steps needed\n    nsteps = num_map_steps(t,*time,deltat);\n\n    // set accumulator variables to zero\n    for (i = 0; i < nzeros; i++)\n      for (j = 0, xs = &x[zeroindex[i]]; j < nreps; j++, xs += nvars)\n        *xs = 0.0;\n\n    for (h = 0; h < nsteps; h++) {\n\n      // interpolate the covariates\n      table_lookup(covar_table,t,cov);\n\n      for (j = 0, xs = x; j < nreps; j++, xs += nvars) {\n\n        if (first) {\n\n          PROTECT(ans = eval_call(fn,args,&t,xs,nvars,p+npars*(j%nrepp),npars,cov,ncovars));\n\n          if (LENGTH(ans) != nvars)\n            err(\"'skeleton' returns a vector of %d state variables but %d are expected.\",LENGTH(ans),nvars);\n\n          // get name information to fix alignment problems\n          PROTECT(nm = GET_NAMES(ans));\n          if (invalid_names(nm)) err(\"'skeleton' must return a named numeric vector.\");\n          posn = INTEGER(PROTECT(matchnames(Snames,nm,\"state variables\")));\n\n          ap = REAL(AS_NUMERIC(ans));\n          for (i = 0; i < nvars; i++) xs[posn[i]] = ap[i];\n\n          nprotect += 3;\n          first = 0;\n\n        } else {\n\n          PROTECT(ans = eval_call(fn,args,&t,xs,nvars,p+npars*(j%nrepp),npars,cov,ncovars));\n\n          ap = REAL(AS_NUMERIC(ans));\n          for (i = 0; i < nvars; i++) xs[posn[i]] = ap[i];\n\n          UNPROTECT(1);\n\n        }\n\n      }\n\n      if (h != nsteps-1) {\n        t += deltat;\n      } else {\n        t = *time;\n      }\n\n    }\n\n    memcpy(X,x,nvars*nreps*sizeof(double));\n\n  }\n\n  UNPROTECT(nprotect);\n\n}\n\nvoid eval_skeleton_native (\n                           double *f, double *time, double *x, double *p,\n                           int nvars, int npars, int ncovars, int ntimes,\n                           int nrepx, int nrepp, int nreps,\n                           int *sidx, int *pidx, int *cidx,\n                           lookup_table_t *covar_table, pomp_skeleton *fun, SEXP args,\n                           double *cov)\n{\n  double *xp, *pp;\n  int j, k;\n\n  for (k = 0; k < ntimes; k++, time++) {\n\n    R_CheckUserInterrupt();\n\n    table_lookup(covar_table,*time,cov);\n\n    for (j = 0; j < nreps; j++, f += nvars) {\n\n      xp = &x[nvars*((j%nrepx)+nrepx*k)];\n      pp = &p[npars*(j%nrepp)];\n\n      (*fun)(f,xp,pp,sidx,pidx,cidx,cov,*time);\n\n    }\n  }\n\n}\n\nvoid iterate_skeleton_native (\n                              double *X, double t, double deltat,\n                              double *time, double *x, double *p,\n                              int nvars, int npars, int ncovars, int ntimes,\n                              int nrepp, int nreps, int nzeros,\n                              int *sidx, int *pidx, int *cidx,\n                              lookup_table_t *covar_table, int *zeroindex,\n                              pomp_skeleton *fun, SEXP args, double *cov)\n{\n  int nsteps;\n  double *xs, *Xs;\n  int h, i, j, k;\n\n  for (k = 0; k < ntimes; k++, time++, X += nvars*nreps) {\n\n    R_CheckUserInterrupt();\n\n    // compute number of steps needed\n    nsteps = num_map_steps(t,*time,deltat);\n\n    // set accumulator variables to zero\n    for (i = 0; i < nzeros; i++)\n      for (j = 0, xs = &x[zeroindex[i]]; j < nreps; j++, xs += nvars)\n        *xs = 0.0;\n\n    for (h = 0; h < nsteps; h++) {\n\n      // interpolate the covariates\n      table_lookup(covar_table,t,cov);\n\n      for (j = 0, Xs = X, xs = x; j < nreps; j++, Xs += nvars, xs += nvars) {\n\n        (*fun)(Xs,xs,p+npars*(j%nrepp),sidx,pidx,cidx,cov,t);\n\n      }\n\n      memcpy(x,X,nvars*nreps*sizeof(double));\n\n      if (h != nsteps-1) {\n        t += deltat;\n      } else {\n        t = *time;\n      }\n\n    }\n\n    if (nsteps == 0) memcpy(X,x,nvars*nreps*sizeof(double));\n\n  }\n\n}\n\nSEXP do_skeleton (SEXP object, SEXP x, SEXP t, SEXP params, SEXP gnsi)\n{\n\n  int nvars, npars, nrepp, nrepx, nreps, ntimes, ncovars;\n  pompfunmode mode = undef;\n  int *dim;\n  SEXP Snames, Cnames, Pnames;\n  SEXP pompfun, cov, ob;\n  SEXP fn, args, F;\n  lookup_table_t covariate_table;\n\n  PROTECT(t = AS_NUMERIC(t));\n  ntimes = LENGTH(t);\n\n  PROTECT(x = as_state_array(x));\n  dim = INTEGER(GET_DIM(x));\n  nvars = dim[0]; nrepx = dim[1];\n  if (ntimes != dim[2])\n    err(\"length of 'times' and 3rd dimension of 'x' do not agree.\");\n\n  PROTECT(params = as_matrix(params));\n  dim = INTEGER(GET_DIM(params));\n  npars = dim[0]; nrepp = dim[1];\n\n  // 2nd dimension of 'x' and 'params' need not agree\n  nreps = (nrepp > nrepx) ? nrepp : nrepx;\n  if ((nreps % nrepp != 0) || (nreps % nrepx != 0))\n    err(\"2nd dimensions of 'x' and 'params' are incompatible\");\n\n  PROTECT(Snames = GET_ROWNAMES(GET_DIMNAMES(x)));\n  PROTECT(Pnames = GET_ROWNAMES(GET_DIMNAMES(params)));\n  PROTECT(Cnames = get_covariate_names(GET_SLOT(object,install(\"covar\"))));\n\n  // set up the covariate table\n  covariate_table = make_covariate_table(GET_SLOT(object,install(\"covar\")),&ncovars);\n  PROTECT(cov = NEW_NUMERIC(ncovars));\n\n  // extract the user-defined function\n  PROTECT(ob = GET_SLOT(object,install(\"skeleton\")));\n  PROTECT(pompfun = GET_SLOT(ob,install(\"skel.fn\")));\n  PROTECT(fn = pomp_fun_handler(pompfun,gnsi,&mode,Snames,Pnames,NA_STRING,Cnames));\n\n  // extract 'userdata' as pairlist\n  PROTECT(args = GET_SLOT(object,install(\"userdata\")));\n\n  PROTECT(F = ret_array(nvars,nreps,ntimes,Snames));\n\n  int nprotect = 12;\n\n  switch (mode) {\n\n  case Rfun: {\n\n    PROTECT(args = add_skel_args(args,Snames,Pnames,Cnames)); nprotect++;\n\n    eval_skeleton_R(REAL(F),REAL(t),REAL(x),REAL(params),\n                    fn,args,Snames,\n                    nvars,npars,ncovars,ntimes,nrepx,nrepp,nreps,\n                    &covariate_table,REAL(cov));\n\n  }\n\n    break;\n\n  case native: case regNative: {\n    int *sidx, *pidx, *cidx;\n    pomp_skeleton *ff = NULL;\n\n    sidx = INTEGER(GET_SLOT(pompfun,install(\"stateindex\")));\n    pidx = INTEGER(GET_SLOT(pompfun,install(\"paramindex\")));\n    cidx = INTEGER(GET_SLOT(pompfun,install(\"covarindex\")));\n\n    *((void **) (&ff)) = R_ExternalPtrAddr(fn);\n\n    eval_skeleton_native(\n                         REAL(F),REAL(t),REAL(x),REAL(params),\n                         nvars,npars,ncovars,ntimes,nrepx,nrepp,nreps,\n                         sidx,pidx,cidx,&covariate_table,ff,args,REAL(cov));\n\n  }\n\n    break;\n\n  default: {\n\n    double *ft = REAL(F);\n    int i, n = nvars*nreps*ntimes;\n    for (i = 0; i < n; i++, ft++) *ft = R_NaReal;\n    warn(\"'skeleton' unspecified: NAs generated.\");\n\n  }\n\n  }\n\n  UNPROTECT(nprotect);\n  return F;\n}\n"
  },
  {
    "path": "src/soboldata.h",
    "content": "/* Copyright (c) 2007 Massachusetts Institute of Technology\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n * \n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \n */\n\n#ifndef SOBOLSEQ_H\n#define SOBOLSEQ_H\n\n/* Data on the primitive binary polynomials (a) and the corresponding\n   starting values m, for Sobol sequences in up to 1111 dimensions,\n   taken from:\n        P. Bratley and B. L. Fox, Algorithm 659, ACM Trans.\n\tMath. Soft. 14 (1), 88-100 (1988),\n   as modified by:\n        S. Joe and F. Y. Kuo, ACM Trans. Math. Soft 29 (1), 49-57 (2003). */\n\n#define MAXDIM 1111\n#define MAXDEG 12\n\n/* successive primitive binary-coefficient polynomials p(z)\n   = a_0 + a_1 z + a_2 z^2 + ... a_31 z^31, where a_i is the \n     i-th bit of sobol_a[j] for the j-th polynomial. */\nstatic const uint32_t sobol_a[MAXDIM-1] = {\n     3,7,11,13,19,25,37,59,47,61,55,41,67,97,91,\n     109,103,115,131,193,137,145,143,241,157,185,167,229,171,213,\n     191,253,203,211,239,247,285,369,299,301,333,351,355,357,361,\n     391,397,425,451,463,487,501,529,539,545,557,563,601,607,617,\n     623,631,637,647,661,675,677,687,695,701,719,721,731,757,761,\n     787,789,799,803,817,827,847,859,865,875,877,883,895,901,911,\n     949,953,967,971,973,981,985,995,1001,1019,1033,1051,1063,\n     1069,1125,1135,1153,1163,1221,1239,1255,1267,1279,1293,1305,\n     1315,1329,1341,1347,1367,1387,1413,1423,1431,1441,1479,1509,\n     1527,1531,1555,1557,1573,1591,1603,1615,1627,1657,1663,1673,\n     1717,1729,1747,1759,1789,1815,1821,1825,1849,1863,1869,1877,\n     1881,1891,1917,1933,1939,1969,2011,2035,2041,2053,2071,2091,\n     2093,2119,2147,2149,2161,2171,2189,2197,2207,2217,2225,2255,\n     2257,2273,2279,2283,2293,2317,2323,2341,2345,2363,2365,2373,\n     2377,2385,2395,2419,2421,2431,2435,2447,2475,2477,2489,2503,\n     2521,2533,2551,2561,2567,2579,2581,2601,2633,2657,2669,\n     2681,2687,2693,2705,2717,2727,2731,2739,\n     2741,2773,2783,2793,2799,2801,2811,2819,2825,2833,2867,2879,\n     2881,2891,2905,2911,2917,2927,2941,2951,2955,2963,2965,2991,\n     2999,3005,3017,3035,3037,3047,3053,3083,3085,3097,3103,3159,\n     3169,3179,3187,3205,3209,3223,3227,3229,3251,3263,3271,3277,\n     3283,3285,3299,3305,3319,3331,3343,3357,3367,3373,3393,3399,\n     3413,3417,3427,3439,3441,3475,3487,3497,3515,3517,3529,3543,\n     3547,3553,3559,3573,3589,3613,3617,3623,3627,3635,3641,3655,\n     3659,3669,3679,3697,3707,3709,3713,3731,3743,3747,3771,3791,\n     3805,3827,3833,3851,3865,3889,3895,3933,3947,3949,3957,3971,\n     3985,3991,3995,4007,4013,4021,4045,4051,4069,4073,4179,4201,\n     4219,4221,4249,4305,4331,4359,4383,4387,4411,4431,4439,4449,\n     4459,4485,4531,4569,4575,4621,4663,4669,4711,4723,4735,4793,\n     4801,4811,4879,4893,4897,4921,4927,4941,4977,5017,5027,5033,\n     5127,5169,5175,5199,5213,5223,5237,5287,5293,5331,5391,5405,\n     5453,5523,5573,5591,5597,5611,5641,5703,5717,5721,5797,5821,\n     5909,5913,\n     5955,5957,6005,6025,6061,6067,6079,6081,\n     6231,6237,6289,6295,6329,6383,6427,6453,6465,6501,6523,6539,\n     6577,6589,6601,6607,6631,6683,6699,6707,6761,6795,6865,6881,\n     6901,6923,6931,6943,6999,7057,7079,7103,7105,7123,7173,7185,\n     7191,7207,7245,7303,7327,7333,7355,7365,7369,7375,7411,7431,\n     7459,7491,7505,7515,7541,7557,7561,7701,7705,7727,7749,7761,\n     7783,7795,7823,7907,7953,7963,7975,8049,8089,8123,8125,8137,\n     8219,8231,8245,8275,8293,8303,8331,8333,8351,8357,8367,8379,\n     8381,8387,8393,8417,8435,8461,8469,8489,8495,8507,8515,8551,\n     8555,8569,8585,8599,8605,8639,8641,8647,8653,8671,8675,8689,\n     8699,8729,8741,8759,8765,8771,8795,8797,8825,8831,8841,8855,\n     8859,8883,8895,8909,8943,8951,8955,8965,8999,9003,9031,9045,\n     9049,9071,9073,9085,9095,9101,9109,9123,9129,9137,9143,9147,\n     9185,9197,9209,9227,9235,9247,9253,9257,9277,9297,9303,9313,\n     9325,9343,9347,9371,9373,9397,9407,9409,9415,9419,9443,9481,\n     9495,9501,9505,9517,9529,9555,9557,9571,9585,9591,9607,9611,\n     9621,9625,\n     9631,9647,9661,9669,9679,9687,9707,9731,\n     9733,9745,9773,9791,9803,9811,9817,9833,9847,9851,9863,9875,\n     9881,9905,9911,9917,9923,9963,9973,10003,10025,10043,10063,\n     10071,10077,10091,10099,10105,10115,10129,10145,10169,10183,\n     10187,10207,10223,10225,10247,10265,10271,10275,10289,10299,\n     10301,10309,10343,10357,10373,10411,10413,10431,10445,10453,\n     10463,10467,10473,10491,10505,10511,10513,10523,10539,10549,\n     10559,10561,10571,10581,10615,10621,10625,10643,10655,10671,\n     10679,10685,10691,10711,10739,10741,10755,10767,10781,10785,\n     10803,10805,10829,10857,10863,10865,10875,10877,10917,10921,\n     10929,10949,10967,10971,10987,10995,11009,11029,11043,11045,\n     11055,11063,11075,11081,11117,11135,11141,11159,11163,11181,\n     11187,11225,11237,11261,11279,11297,11307,11309,11327,11329,\n     11341,11377,11403,11405,11413,11427,11439,11453,11461,11473,\n     11479,11489,11495,11499,11533,11545,11561,11567,11575,11579,\n     11589,11611,11623,11637,11657,11663,11687,11691,11701,11747,\n     11761,11773,11783,11795,11797,11817,11849,11855,11867,11869,\n     11873,11883,11919,\n     11921,11927,11933,11947,11955,11961,\n     11999,12027,12029,12037,12041,12049,12055,12095,12097,12107,\n     12109,12121,12127,12133,12137,12181,12197,12207,12209,12239,\n     12253,12263,12269,12277,12287,12295,12309,12313,12335,12361,\n     12367,12391,12409,12415,12433,12449,12469,12479,12481,12499,\n     12505,12517,12527,12549,12559,12597,12615,12621,12639,12643,\n     12657,12667,12707,12713,12727,12741,12745,12763,12769,12779,\n     12781,12787,12799,12809,12815,12829,12839,12857,12875,12883,\n     12889,12901,12929,12947,12953,12959,12969,12983,12987,12995,\n     13015,13019,13031,13063,13077,13103,13137,13149,13173,13207,\n     13211,13227,13241,13249,13255,13269,13283,13285,13303,13307,\n     13321,13339,13351,13377,13389,13407,13417,13431,13435,13447,\n     13459,13465,13477,13501,13513,13531,13543,13561,13581,13599,\n     13605,13617,13623,13637,13647,13661,13677,13683,13695,13725,\n     13729,13753,13773,13781,13785,13795,13801,13807,13825,13835,\n     13855,13861,13871,13883,13897,13905,13915,13939,13941,13969,\n     13979,13981,13997,14027,14035,14037,14051,14063,14085,14095,\n     14107,14113,14125,14137,14145,\n     14151,14163,14193,14199,14219,14229,\n     14233,14243,14277,14287,14289,14295,14301,14305,14323,14339,\n     14341,14359,14365,14375,14387,14411,14425,14441,14449,14499,\n     14513,14523,14537,14543,14561,14579,14585,14593,14599,14603,\n     14611,14641,14671,14695,14701,14723,14725,14743,14753,14759,\n     14765,14795,14797,14803,14831,14839,14845,14855,14889,14895,\n     14909,14929,14941,14945,14951,14963,14965,14985,15033,15039,\n     15053,15059,15061,15071,15077,15081,15099,15121,15147,15149,\n     15157,15167,15187,15193,15203,15205,15215,15217,15223,15243,\n     15257,15269,15273,15287,15291,15313,15335,15347,15359,15373,\n     15379,15381,15391,15395,15397,15419,15439,15453,15469,15491,\n     15503,15517,15527,15531,15545,15559,15593,15611,15613,15619,\n     15639,15643,15649,15661,15667,15669,15681,15693,15717,15721,\n     15741,15745,15765,15793,15799,15811,15825,15835,15847,15851,\n     15865,15877,15881,15887,15899,15915,15935,15937,15955,15973,\n     15977,16011,16035,16061,16069,16087,16093,16097,16121,16141,\n     16153,16159,16165,16183,16189,16195,16197,16201,16209,16215,\n     16225,16259,16265,16273,16299,\n     16309,16355,16375,16381,\n};\n\n/* starting direction #'s m[i] = sobol_minit[i][j] for i=0..d of the\n * degree-d primitive polynomial sobol_a[j]. */\nstatic const uint32_t sobol_minit[MAXDEG+1][MAXDIM-1] = {\n     /* [0][*] */\n     { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 },\n     /* [1][*] */\n     { 0,\n       1,3,1,3,1,3,3,1,3,1,3,1,3,1,1,3,1,3,1,3,\n     1,3,3,1,1,1,3,1,3,1,3,3,1,3,1,1,1,3,1,3,1,1,1,3,3,1,3,3,1,1,\n     3,3,1,3,3,3,1,3,1,3,1,1,3,3,1,1,1,1,3,1,1,3,1,1,1,3,3,1,3,3,\n     1,3,3,3,1,3,3,3,1,3,3,1,3,3,3,1,3,1,3,1,1,3,3,1,3,3,1,1,1,3,\n     3,1,3,3,1,3,1,1,3,3,3,1,1,1,3,1,1,3,1,1,3,3,1,3,1,3,3,3,3,1,\n     1,1,3,3,1,1,3,1,1,1,1,1,1,3,1,3,1,1,1,3,1,3,1,3,3,3,1,1,3,3,\n     1,3,1,3,1,1,3,1,3,1,3,1,3,1,1,1,3,3,1,3,3,1,3,1,1,1,3,1,3,1,\n     1,3,1,1,3,3,1,1,3,3,3,1,3,3,3,1,3,1,3,1,1,1,3,1,1,1,3,1,1,1,\n     1,1,3,3,3,1,1,1,1,3,3,3,1,3,3,1,1,1,1,3,1,1,3,1,3,3,1,1,3,3,\n     1,1,1,1,3,1,3,3,1,3,3,1,1,1,3,3,3,1,3,3,1,3,3,1,3,1,3,3,3,1,\n     3,1,1,3,1,3,1,1,1,3,3,3,1,1,3,1,3,1,1,1,1,1,1,3,1,1,3,1,3,3,\n     1,1,1,1,3,1,3,1,3,1,1,1,1,3,3,1,1,1,1,1,3,3,3,1,1,3,3,3,3,3,\n     1,3,3,1,3,3,3,3,1,1,1,1,1,1,3,1,1,3,1,1,1,3,1,1,1,3,3,3,1,3,\n     1,1,3,3,3,1,3,3,1,3,1,3,3,1,3,3,3,1,1,\n     3,3,1,3,1,3,1,1,1,3,3,3,3,1,3,1,1,3,1,\n     3,1,1,1,3,1,3,1,3,1,3,3,3,3,3,3,3,3,1,3,3,3,3,3,1,3,1,3,3,3,\n     1,3,1,3,1,3,3,1,3,3,3,3,3,3,3,3,3,1,1,1,1,1,1,3,3,1,1,3,3,1,\n     1,1,3,3,1,1,3,3,3,3,1,1,3,1,3,3,1,3,3,1,1,1,3,3,3,1,1,3,3,3,\n     3,3,1,1,1,3,1,3,3,1,3,3,3,3,1,1,3,1,1,3,1,3,1,3,1,3,3,1,1,3,\n     3,1,3,3,1,3,3,1,1,3,1,3,3,1,1,3,1,3,1,3,1,1,3,3,1,1,1,3,3,1,\n     3,1,1,3,3,1,1,3,1,3,1,1,1,1,1,3,1,1,1,1,3,1,3,1,1,3,3,1,1,3,\n     1,3,1,3,3,3,1,3,3,3,1,1,3,3,3,1,1,1,1,3,1,3,1,3,1,1,3,3,1,1,\n     1,3,3,1,3,1,3,1,1,1,1,1,1,3,1,3,3,1,3,3,3,1,3,1,1,3,3,1,1,3,\n     3,1,1,1,3,1,3,3,1,1,3,1,1,3,1,3,1,1,1,3,3,3,3,1,1,3,3,1,1,1,\n     1,3,1,1,3,3,3,1,1,3,3,1,3,3,1,1,3,3,3,3,3,3,3,1,3,3,1,3,1,3,\n     1,1,3,3,1,1,1,3,1,3,3,1,3,3,1,3,1,1,3,3,3,1,1,1,3,1,1,1,3,3,\n     3,1,3,3,1,3,1,1,3,3,3,1,3,3,1,1,1,3,1,3,3,3,3,3,3,3,3,1,3,3,\n     1,3,1,1,3,3,3,1,3,3,3,3,3,1,3,3,3,1,1,1,\n     3,3,1,3,3,1,3,1,3,1,3,1,3,3,3,3,3,3,\n     1,1,3,1,3,1,1,1,1,1,3,1,1,1,3,1,3,1,1,3,3,3,1,3,1,3,1,1,3,1,\n     3,3,1,3,1,3,3,1,3,3,1,3,3,3,3,3,3,1,3,1,1,3,3,3,1,1,3,3,3,3,\n     3,3,3,1,3,3,3,3,1,3,1,3,3,3,1,3,1,3,1,1,1,3,3,1,3,1,1,3,3,1,\n     3,1,1,1,1,3,1,3,1,1,3,1,3,1,3,3,3,3,3,3,1,3,3,3,3,1,3,3,1,3,\n     3,3,3,3,1,1,1,1,3,3,3,1,3,3,1,1,3,3,1,1,3,3,1,3,1,1,3,1,3,3,\n     3,3,3,1,3,1,1,3,3,3,3,1,3,1,1,3,3,3,3,3,3,1,1,3,1,3,1,1,3,1,\n     1,1,1,3,3,1,1,3,1,1,1,3,1,3,1,1,3,3,1,3,1,1,3,3,3,3,3,1,3,1,\n     1,1,3,1,1,1,3,1,1,3,1,3,3,3,3,3,1,1,1,3,3,3,3,1,3,3,3,3,1,1,\n     3,3,3,1,3,1,1,3,3,1,3,3,1,1,1,1,1,3,1,1,3,3,1,1,1,3,1,1,3,3,\n     1,3,3,3,3,3,3,3,3,1,1,3,3,1,1,3,1,3,3,3,3,3,1},\n     /* [2][*] */\n     { 0,0,\n       7,5,1,3,3,7,5,5,7,7,1,3,3,7,5,1,1,5,3,7,\n     1,7,5,1,3,7,7,1,1,1,5,7,7,5,1,3,3,7,5,5,5,3,3,3,1,1,5,1,1,5,\n     3,3,3,3,1,3,7,5,7,3,7,1,3,3,5,1,3,5,5,7,7,7,1,1,3,3,1,1,5,1,\n     5,7,5,1,7,5,3,3,1,5,7,1,7,5,1,7,3,1,7,1,7,3,3,5,7,3,3,5,1,3,\n     3,1,3,5,1,3,3,3,7,1,1,7,3,1,3,7,5,5,7,5,5,3,1,3,3,3,1,3,3,7,\n     3,3,1,7,5,1,7,7,5,7,5,1,3,1,7,3,7,3,5,7,3,1,3,3,3,1,5,7,3,3,\n     7,7,7,5,3,1,7,1,3,7,5,3,3,3,7,1,1,3,1,5,7,1,3,5,3,5,3,3,7,5,\n     5,3,3,1,3,7,7,7,1,5,7,1,3,1,1,7,1,3,1,7,1,5,3,5,3,1,1,5,5,3,\n     3,5,7,1,5,3,7,7,3,5,3,3,1,7,3,1,3,5,7,1,3,7,1,5,1,3,1,5,3,1,\n     7,1,5,5,5,3,7,1,1,7,3,1,1,7,5,7,5,7,7,3,7,1,3,7,7,3,5,1,1,7,\n     1,5,5,5,1,5,1,7,5,5,7,1,1,7,1,7,7,1,1,3,3,3,7,7,5,3,7,3,1,3,\n     7,5,3,3,5,7,1,1,5,5,7,7,1,1,1,1,5,5,5,7,5,7,1,1,3,5,1,3,3,7,\n     3,7,5,3,5,3,1,7,1,7,7,1,1,7,7,7,5,5,1,1,7,5,5,7,5,1,1,5,5,5,\n     5,5,5,1,3,1,5,7,3,3,5,7,3,7,1,7,7,1,3,\n     5,1,5,5,3,7,3,7,7,5,7,5,7,1,1,5,3,5,1,\n     5,3,7,1,5,7,7,3,5,1,3,5,1,5,3,3,3,7,3,5,1,3,7,7,3,7,5,3,3,1,\n     7,5,1,1,3,7,1,7,1,7,3,7,3,5,7,3,5,3,1,1,1,5,7,7,3,3,1,1,1,5,\n     5,7,3,1,1,3,3,7,3,3,5,1,3,7,3,3,7,3,5,7,5,7,7,3,3,5,1,3,5,3,\n     1,3,5,1,1,3,7,7,1,5,1,3,7,3,7,3,5,1,7,1,1,3,5,3,7,1,5,5,1,1,\n     3,1,3,3,7,1,7,3,1,7,3,1,7,3,5,3,5,7,3,3,3,5,1,7,7,1,3,1,3,7,\n     7,1,3,7,3,1,5,3,1,1,1,5,3,3,7,1,5,3,5,1,3,1,3,1,5,7,7,1,1,5,\n     3,1,5,1,1,7,7,3,5,5,1,7,1,5,1,1,3,1,5,7,5,7,7,1,5,1,1,3,5,1,\n     5,5,3,1,3,1,5,5,3,3,3,3,1,1,3,1,3,5,5,7,5,5,7,5,7,1,3,7,7,3,\n     5,5,7,5,5,3,3,3,1,7,1,5,5,5,3,3,5,1,3,1,3,3,3,7,1,7,7,3,7,1,\n     1,5,7,1,7,1,7,7,1,3,7,5,1,3,5,5,5,1,1,7,1,7,1,7,7,3,1,1,5,1,\n     5,1,5,3,5,5,5,5,5,3,3,7,3,3,5,5,3,7,1,5,7,5,1,5,5,3,5,5,7,5,\n     3,5,5,5,1,5,5,5,5,1,3,5,3,1,7,5,5,7,1,5,3,3,1,5,3,7,1,7,5,1,\n     1,3,1,1,7,1,5,5,3,7,3,7,5,3,1,1,3,1,3,5,\n     5,7,5,3,7,7,7,3,7,3,7,1,3,1,7,7,1,7,\n     3,7,3,7,3,7,3,5,1,1,7,3,1,5,5,7,1,5,5,5,7,1,5,5,1,5,5,3,1,3,\n     1,7,3,1,3,5,7,7,7,1,1,7,3,1,5,5,5,1,1,1,1,1,5,3,5,1,3,5,3,1,\n     1,1,1,3,7,3,7,5,7,1,5,5,7,5,3,3,7,5,3,1,1,3,1,3,1,1,3,7,1,7,\n     1,1,5,1,7,5,3,7,3,5,3,1,1,5,5,1,7,7,3,7,3,7,1,5,1,5,3,7,3,5,\n     7,7,7,3,3,1,1,5,5,3,7,1,1,1,3,5,3,1,1,3,3,7,5,1,1,3,7,1,5,7,\n     3,7,5,5,7,3,5,3,1,5,3,1,1,7,5,1,7,3,7,5,1,7,1,7,7,1,1,7,1,5,\n     5,1,1,7,5,7,1,5,3,5,3,3,7,1,5,1,1,5,5,3,3,7,5,5,1,1,1,3,1,5,\n     7,7,1,7,5,7,3,7,3,1,3,7,3,1,5,5,3,5,1,3,5,5,5,1,1,7,7,1,5,5,\n     1,3,5,1,5,3,5,3,3,7,5,7,3,7,3,1,3,7,7,3,3,1,1,3,3,3,3,3,5,5,\n     3,3,3,1,3,5,7,7,1,5,7,3,7,1,1,3,5,7,5,3,3,3},\n     /* [3][*] */\n     { 0,0,0,0,\n       1,7,9,13,11,1,3,7,9,5,13,13,11,3,15,5,3,\n     15,7,9,13,9,1,11,7,5,15,1,15,11,5,11,1,7,9,7,7,1,15,15,15,13,\n     3,3,15,5,9,7,13,3,7,5,11,9,1,9,1,5,7,13,9,9,1,7,3,5,1,11,11,\n     13,7,7,9,9,1,1,3,9,15,1,5,13,1,9,9,9,9,9,13,11,3,5,11,11,13,\n     5,3,15,1,11,11,7,13,15,11,13,9,11,15,15,13,3,15,7,9,11,13,11,\n     9,9,5,13,9,1,13,7,7,7,7,7,5,9,7,13,11,9,11,15,3,13,11,1,11,3,\n     3,9,11,1,7,1,15,15,3,1,9,1,7,13,11,3,13,11,7,3,3,5,13,11,5,\n     11,1,3,9,7,15,7,5,13,7,9,13,15,13,9,7,15,7,9,5,11,11,13,13,9,\n     3,5,13,9,11,15,11,7,1,7,13,3,13,3,13,9,15,7,13,13,3,13,15,15,\n     11,9,13,9,15,1,1,15,11,11,7,1,11,13,9,13,3,5,11,13,9,9,13,1,\n     11,15,13,3,13,7,15,1,15,3,3,11,7,13,7,7,9,7,5,15,9,5,5,7,15,\n     13,15,5,15,5,3,1,11,7,1,5,7,9,3,11,1,15,1,3,15,11,13,5,13,1,\n     7,1,15,7,5,1,1,15,13,11,11,13,5,11,7,9,7,1,5,3,9,5,5,11,5,1,\n     7,1,11,7,9,13,15,13,3,1,11,13,15,1,1,11,9,13,3,13,11,15,13,9,\n     9,9,5,5,5,5,1,15,5,9,\n     11,7,15,5,3,13,5,3,11,5,1,11,13,9,11,\n     3,7,13,15,1,7,11,1,13,1,15,1,9,7,3,9,11,1,9,13,13,3,11,7,9,1,\n     7,15,9,1,5,13,5,11,3,9,15,11,13,5,1,7,7,5,13,7,7,9,5,11,11,1,\n     1,15,3,13,9,13,9,9,11,5,5,13,15,3,9,15,3,11,11,15,15,3,11,15,\n     15,3,1,3,1,3,3,1,3,13,1,11,5,15,7,15,9,1,7,1,9,11,15,1,13,9,\n     13,11,7,3,7,3,13,7,9,7,7,3,3,9,9,7,5,11,13,13,7,7,15,9,5,5,3,\n     3,13,3,9,3,1,11,1,3,11,15,11,11,11,9,13,7,9,15,9,11,1,3,3,9,\n     7,15,13,13,7,15,9,13,9,15,13,15,9,13,1,11,7,11,3,13,5,1,7,15,\n     3,13,7,13,13,11,3,5,3,13,11,9,9,3,11,11,7,9,13,11,7,15,13,7,\n     5,3,1,5,15,15,3,11,1,7,3,15,11,5,5,3,5,5,1,15,5,1,5,3,7,5,11,\n     3,13,9,13,15,5,3,5,9,5,3,11,1,13,9,15,3,5,11,9,1,3,15,9,9,9,\n     11,7,5,13,1,15,3,13,9,13,5,1,5,1,13,13,7,7,1,9,5,11,9,11,13,\n     3,15,15,13,15,7,5,7,9,7,9,9,9,11,9,3,11,15,13,13,5,9,15,1,1,\n     9,5,13,3,13,15,3,1,3,11,13,1,15,9,9,3,1,9,1,9,1,13,11,15,7,\n     11,15,13,15,1,9,9,7,\n     3,5,11,7,3,9,5,15,7,5,3,13,7,1,1,9,\n     15,15,15,11,3,5,15,13,7,15,15,11,11,9,5,15,9,7,3,13,1,1,5,1,\n     3,1,7,1,1,5,1,11,11,9,9,5,13,7,7,7,1,1,9,9,11,11,15,7,5,5,3,\n     11,1,3,7,13,7,7,7,3,15,15,11,9,3,9,3,15,13,5,3,3,3,5,9,15,9,\n     9,1,5,9,9,15,5,15,7,9,1,9,9,5,11,5,15,15,11,7,7,7,1,1,11,11,\n     13,15,3,13,5,1,7,1,11,3,13,15,3,5,3,5,7,3,9,9,5,1,7,11,9,3,5,\n     11,13,13,13,9,15,5,7,1,15,11,9,15,15,13,13,13,1,11,9,15,9,5,\n     15,5,7,3,11,3,15,7,13,11,7,3,7,13,5,13,15,5,13,9,1,15,11,5,5,\n     1,11,3,3,7,1,9,7,15,9,9,3,11,15,7,1,3,1,1,1,9,1,5,15,15,7,5,\n     5,7,9,7,15,13,13,11,1,9,11,1,13,1,7,15,15,5,5,1,11,3,9,11,9,\n     9,9,1,9,3,5,15,1,1,9,7,3,3,1,9,9,11,9,9,13,13,3,13,11,13,5,1,\n     5,5,9,9,3,13,13,9,15,9,11,7,11,9,13,9,1,15,9,7,7,1,7,9,9,15,\n     1,11,1,13,13,15,9,13,7,15,3,9,3,1,13,7,5,9,3,1,7,1,1,13,3,3,\n     11,1,7,13,15,15,5,7,13,13,15,11,13,1,13,13,3,9,15,15,11,15,9,\n     15,1,13,15,1,1,5,\n     11,5,1,11,11,5,3,9,1,3,5,13,9,7,7,1,\n     9,9,15,7,5,5,15,13,9,7,13,3,13,11,13,7,9,13,13,13,15,9,5,5,3,\n     3,3,1,3,15},\n     /* [4][*] */\n     { 0,0,0,0,0,0,\n       9,3,27,15,29,21,23,19,11,25,7,13,17,1,\n     25,29,3,31,11,5,23,27,19,21,5,1,17,13,7,15,9,31,25,3,5,23,7,\n     3,17,23,3,3,21,25,25,23,11,19,3,11,31,7,9,5,17,23,17,17,25,\n     13,11,31,27,19,17,23,7,5,11,19,19,7,13,21,21,7,9,11,1,5,21,\n     11,13,25,9,7,7,27,15,25,15,21,17,19,19,21,5,11,3,5,29,31,29,\n     5,5,1,31,27,11,13,1,3,7,11,7,3,23,13,31,17,1,27,11,25,1,23,\n     29,17,25,7,25,27,17,13,17,23,5,17,5,13,11,21,5,11,5,9,31,19,\n     17,9,9,27,21,15,15,1,1,29,5,31,11,17,23,19,21,25,15,11,5,5,1,\n     19,19,19,7,13,21,17,17,25,23,19,23,15,13,5,19,25,9,7,3,21,17,\n     25,1,27,25,27,25,9,13,3,17,25,23,9,25,9,13,17,17,3,15,7,7,29,\n     3,19,29,29,19,29,13,15,25,27,1,3,9,9,13,31,29,31,5,15,29,1,\n     19,5,9,19,5,15,3,5,7,15,17,17,23,11,9,23,19,3,17,1,27,9,9,17,\n     13,25,29,23,29,11,31,25,21,29,19,27,31,3,5,3,3,13,21,9,29,3,\n     17,11,11,9,21,19,7,17,31,25,1,27,5,15,27,29,29,29,25,27,25,3,\n     21,17,25,13,15,17,13,23,9,3,11,7,9,9,7,17,7,1,\n     27,1,9,5,31,21,25,25,21,11,1,23,19,27,\n     15,3,5,23,9,25,7,29,11,9,13,5,11,1,3,31,27,3,17,27,11,13,15,\n     29,15,1,15,23,25,13,21,15,3,29,29,5,25,17,11,7,15,5,21,7,31,\n     13,11,23,5,7,23,27,21,29,15,7,27,27,19,7,15,27,27,19,19,9,15,\n     1,3,29,29,5,27,31,9,1,7,3,19,19,29,9,3,21,31,29,25,1,3,9,27,\n     5,27,25,21,11,29,31,27,21,29,17,9,17,13,11,25,15,21,11,19,31,\n     3,19,5,3,3,9,13,13,3,29,7,5,9,23,13,21,23,21,31,11,7,7,3,23,\n     1,23,5,9,17,21,1,17,29,7,5,17,13,25,17,9,19,9,5,7,21,19,13,9,\n     7,3,9,3,15,31,29,29,25,13,9,21,9,31,7,15,5,31,7,15,27,25,19,\n     9,9,25,25,23,1,9,7,11,15,19,15,27,17,11,11,31,13,25,25,9,7,\n     13,29,19,5,19,31,25,13,25,15,5,9,29,31,9,29,27,25,27,11,17,5,\n     17,3,23,15,9,9,17,17,31,11,19,25,13,23,15,25,21,31,19,3,11,\n     25,7,15,19,7,5,3,13,13,1,23,5,25,11,25,15,13,21,11,23,29,5,\n     17,27,9,19,15,5,29,23,19,1,27,3,23,21,19,27,11,17,13,27,11,\n     31,23,5,9,21,31,29,11,21,17,15,7,15,7,9,21,27,25,\n     29,11,3,21,13,23,19,27,17,29,25,17,9,\n     1,19,23,5,23,1,17,17,13,27,23,7,7,11,13,17,13,11,21,13,23,1,\n     27,13,9,7,1,27,29,5,13,25,21,3,31,15,13,3,19,13,1,27,15,17,1,\n     3,13,13,13,31,29,27,7,7,21,29,15,17,17,21,19,17,3,15,5,27,27,\n     3,31,31,7,21,3,13,11,17,27,25,1,9,7,29,27,21,23,13,25,29,15,\n     17,29,9,15,3,21,15,17,17,31,9,9,23,19,25,3,1,11,27,29,1,31,\n     29,25,29,1,23,29,25,13,3,31,25,5,5,11,3,21,9,23,7,11,23,11,1,\n     1,3,23,25,23,1,23,3,27,9,27,3,23,25,19,29,29,13,27,5,9,29,29,\n     13,17,3,23,19,7,13,3,19,23,5,29,29,13,13,5,19,5,17,9,11,11,\n     29,27,23,19,17,25,13,1,13,3,11,1,17,29,1,13,17,9,17,21,1,11,\n     1,1,25,5,7,29,29,19,19,1,29,13,3,1,31,15,13,3,1,11,19,5,29,\n     13,29,23,3,1,31,13,19,17,5,5,1,29,23,3,19,25,19,27,9,27,13,\n     15,29,23,13,25,25,17,19,17,15,27,3,25,17,27,3,27,31,23,13,31,\n     11,15,7,21,19,27,19,21,29,7,31,13,9,9,7,21,13,11,9,11,29,19,\n     11,19,21,5,29,13,7,19,19,27,23,31,1,27,21,7,3,7,11,\n     23,13,29,11,31,19,1,5,5,11,5,3,27,5,\n     7,11,31,1,27,31,31,23,5,21,27,9,25,3,15,19,1,19,9,5,25,21,15,\n     25,29,15,21,11,19,15,3,7,13,11,25,17,1,5,31,13,29,23,9,5,29,\n     7,17,27,7,17,31,9,31,9,9,7,21,3,3,3,9,11,21,11,31,9,25,5,1,\n     31,13,29,9,29,1,11,19,7,27,13,31,7,31,7,25,23,21,29,11,11,13,\n     11,27,1,23,31,21,23,21,19,31,5,31,25,25,19,17,11,25,7,13,1,\n     29,17,23,15,7,29,17,13,3,17},\n     /* [5][*] */\n     { 0,0,0,0,0,0,0,0,0,0,0,0,\n       37,33,7,5,11,39,63,59,17,15,23,29,3,21,\n     13,31,25,9,49,33,19,29,11,19,27,15,25,63,55,17,63,49,19,41,\n     59,3,57,33,49,53,57,57,39,21,7,53,9,55,15,59,19,49,31,3,39,5,\n     5,41,9,19,9,57,25,1,15,51,11,19,61,53,29,19,11,9,21,19,43,13,\n     13,41,25,31,9,11,19,5,53,37,7,51,45,7,7,61,23,45,7,59,41,1,\n     29,61,37,27,47,15,31,35,31,17,51,13,25,45,5,5,33,39,5,47,29,\n     35,47,63,45,37,47,59,21,59,33,51,9,27,13,25,43,3,17,21,59,61,\n     27,47,57,11,17,39,1,63,21,59,17,13,31,3,31,7,9,27,37,23,31,9,\n     45,43,31,63,21,39,51,27,7,53,11,1,59,39,23,49,23,7,55,59,3,\n     19,35,13,9,13,15,23,9,7,43,55,3,19,9,27,33,27,49,23,47,19,7,\n     11,55,27,35,5,5,55,35,37,9,33,29,47,25,11,47,53,61,59,3,53,\n     47,5,19,59,5,47,23,45,53,3,49,61,47,39,29,17,57,5,17,31,23,\n     41,39,5,27,7,29,29,33,31,41,31,29,17,29,29,9,9,31,27,53,35,5,\n     61,1,49,13,57,29,5,21,43,25,57,49,37,27,11,61,37,49,5,63,63,\n     3,45,37,63,21,21,19,27,59,21,45,23,13,15,3,43,63,39,19,\n     63,31,41,41,15,43,63,53,1,63,31,7,17,\n     11,61,31,51,37,29,59,25,63,59,47,15,27,19,29,45,35,55,39,19,\n     43,21,19,13,17,51,37,5,33,35,49,25,45,1,63,47,9,63,15,25,25,\n     15,41,13,3,19,51,49,37,25,49,13,53,47,23,35,29,33,21,35,23,3,\n     43,31,63,9,1,61,43,3,11,55,11,35,1,63,35,49,19,45,9,57,51,1,\n     47,41,9,11,37,19,55,23,55,55,13,7,47,37,11,43,17,3,25,19,55,\n     59,37,33,43,1,5,21,5,63,49,61,21,51,15,19,43,47,17,9,53,45,\n     11,51,25,11,25,47,47,1,43,29,17,31,15,59,27,63,11,41,51,29,7,\n     27,63,31,43,3,29,39,3,59,59,1,53,63,23,63,47,51,23,61,39,47,\n     21,39,15,3,9,57,61,39,37,21,51,1,23,43,27,25,11,13,21,43,7,\n     11,33,55,1,37,35,27,61,39,5,19,61,61,57,59,21,59,61,57,25,55,\n     27,31,41,33,63,19,57,35,13,63,35,17,11,11,49,41,55,5,45,17,\n     35,5,31,31,37,17,45,51,1,39,49,55,19,41,13,5,51,5,49,1,21,13,\n     17,59,51,11,3,61,1,33,37,33,61,25,27,59,7,49,13,63,3,33,3,15,\n     9,13,35,39,11,59,59,1,57,11,5,57,13,31,13,11,55,45,9,55,55,\n     19,25,41,23,45,29,63,59,27,39,21,37,7,\n     61,49,35,39,9,29,7,25,23,57,5,19,15,33,49,37,25,17,45,29,15,\n     25,3,3,49,11,39,15,19,57,39,15,11,3,57,31,55,61,19,5,41,35,\n     59,61,39,41,53,53,63,31,9,59,13,35,55,41,49,5,41,25,27,43,5,\n     5,43,5,5,17,5,15,27,29,17,9,3,55,31,1,45,45,13,57,17,3,61,15,\n     49,15,47,9,37,45,9,51,61,21,33,11,21,63,63,47,57,61,49,9,59,\n     19,29,21,23,55,23,43,41,57,9,39,27,41,35,61,29,57,63,21,31,\n     59,35,49,3,49,47,49,33,21,19,21,35,11,17,37,23,59,13,37,35,\n     55,57,1,29,45,11,1,15,9,33,19,53,43,39,23,7,13,13,1,19,41,55,\n     1,13,15,59,55,15,3,57,37,31,17,1,3,21,29,25,55,9,37,33,53,41,\n     51,19,57,13,63,43,19,7,13,37,33,19,15,63,51,11,49,23,57,47,\n     51,15,53,41,1,15,37,61,11,35,29,33,23,55,11,59,19,61,61,45,\n     13,49,13,63,5,61,5,31,17,61,63,13,27,57,1,21,5,11,39,57,51,\n     53,39,25,41,39,37,23,31,25,33,17,57,29,27,23,47,41,29,19,47,\n     41,25,5,51,43,39,29,7,31,45,51,49,55,17,43,49,45,9,29,3,5,47,\n     9,15,19,\n     51,45,57,63,9,21,59,3,9,13,45,23,15,\n     31,21,15,51,35,9,11,61,23,53,29,51,45,31,29,5,35,29,53,35,17,\n     59,55,27,51,59,27,47,15,29,37,7,49,55,5,19,45,29,19,57,33,53,\n     45,21,9,3,35,29,43,31,39,3,45,1,41,29,5,59,41,33,35,27,19,13,\n     25,27,43,33,35,17,17,23,7,35,15,61,61,53,5,15,23,11,13,43,55,\n     47,25,43,15,57,45,1,49,63,57,15,31,31,7,53,27,15,47,23,7,29,\n     53,47,9,53,3,25,55,45,63,21,17,23,31,27,27,43,63,55,63,45,51,\n     15,27,5,37,43,11,27,5,27,59,21,7,39,27,63,35,47,55,17,17,17,\n     3,19,21,13,49,61,39,15},\n     /* [6][*] */\n     { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\n       13,33,115,41,79,17,29,119,75,73,105,7,\n     59,65,21,3,113,61,89,45,107,21,71,79,19,71,61,41,57,121,87,\n     119,55,85,121,119,11,23,61,11,35,33,43,107,113,101,29,87,119,\n     97,29,17,89,5,127,89,119,117,103,105,41,83,25,41,55,69,117,\n     49,127,29,1,99,53,83,15,31,73,115,35,21,89,5,1,91,53,35,95,\n     83,19,85,55,51,101,33,41,55,45,95,61,27,37,89,75,57,61,15,\n     117,15,21,27,25,27,123,39,109,93,51,21,91,109,107,45,15,93,\n     127,3,53,81,79,107,79,87,35,109,73,35,83,107,1,51,7,59,33,\n     115,43,111,45,121,105,125,87,101,41,95,75,1,57,117,21,27,67,\n     29,53,117,63,1,77,89,115,49,127,15,79,81,29,65,103,33,73,79,\n     29,21,113,31,33,107,95,111,59,99,117,63,63,99,39,9,35,63,125,\n     99,45,93,33,93,9,105,75,51,115,11,37,17,41,21,43,73,19,93,7,\n     95,81,93,79,81,55,9,51,63,45,89,73,19,115,39,47,81,39,5,5,45,\n     53,65,49,17,105,13,107,5,5,19,73,59,43,83,97,115,27,1,69,103,\n     3,99,103,63,67,25,121,97,77,13,83,103,41,11,27,81,37,33,125,\n     71,41,41,59,41,87,123,\n     43,101,63,45,39,21,97,15,97,111,21,49,\n     13,17,79,91,65,105,75,1,45,67,83,107,125,87,15,81,95,105,65,\n     45,59,103,23,103,99,67,99,47,117,71,89,35,53,73,9,115,49,37,\n     1,35,9,45,81,19,127,17,17,105,89,49,101,7,37,33,11,95,95,17,\n     111,105,41,115,5,69,101,27,27,101,103,53,9,21,43,79,91,65,\n     117,87,125,55,45,63,85,83,97,45,83,87,113,93,95,5,17,77,77,\n     127,123,45,81,85,121,119,27,85,41,49,15,107,21,51,119,11,87,\n     101,115,63,63,37,121,109,7,43,69,19,77,49,71,59,35,7,13,55,\n     101,127,103,85,109,29,61,67,21,111,67,23,57,75,71,101,123,41,\n     107,101,107,125,27,47,119,41,19,127,33,31,109,7,91,91,39,125,\n     105,47,125,123,91,9,103,45,23,117,9,125,73,11,37,61,79,21,5,\n     47,117,67,53,85,33,81,121,47,61,51,127,29,65,45,41,95,57,73,\n     33,117,61,111,59,123,65,47,105,23,29,107,37,81,67,29,115,119,\n     75,73,99,103,7,57,45,61,95,49,101,101,35,47,119,39,67,31,103,\n     7,61,127,87,3,35,29,73,95,103,71,75,51,87,57,97,11,105,87,41,\n     73,109,69,35,121,39,111,1,77,\n     39,47,53,91,3,17,51,83,39,125,85,111,\n     21,69,85,29,55,11,117,1,47,17,65,63,47,117,17,115,51,25,33,\n     123,123,83,51,113,95,121,51,91,109,43,55,35,55,87,33,37,5,3,\n     45,21,105,127,35,17,35,37,97,97,21,77,123,17,89,53,105,75,25,\n     125,13,47,21,125,23,55,63,61,5,17,93,57,121,69,73,93,121,105,\n     75,91,67,95,75,9,69,97,99,93,11,53,19,73,5,33,79,107,65,69,\n     79,125,25,93,55,61,17,117,69,97,87,111,37,93,59,79,95,53,115,\n     53,85,85,65,59,23,75,21,67,27,99,79,27,3,95,27,69,19,75,47,\n     59,41,85,77,99,55,49,93,93,119,51,125,63,13,15,45,61,19,105,\n     115,17,83,7,7,11,61,37,63,89,95,119,113,67,123,91,33,37,99,\n     43,11,33,65,81,79,81,107,63,63,55,89,91,25,93,101,27,55,75,\n     121,79,43,125,73,27,109,35,21,71,113,89,59,95,41,45,113,119,\n     113,39,59,73,15,13,59,67,121,27,7,105,15,59,59,35,91,89,23,\n     125,97,53,41,91,111,29,31,3,103,61,71,35,7,119,29,45,49,111,\n     41,109,59,125,13,27,19,79,9,75,83,81,33,91,109,33,29,107,111,\n     101,107,109,65,59,43,37,\n     1,9,15,109,37,111,113,119,79,73,65,\n     71,93,17,101,87,97,43,23,75,109,41,49,53,31,97,105,109,119,\n     51,9,53,113,97,73,89,79,49,61,105,13,99,53,71,7,87,21,101,5,\n     71,31,123,121,121,73,79,115,13,39,101,19,37,51,83,97,55,81,\n     91,127,105,89,63,47,49,75,37,77,15,49,107,23,23,35,19,69,17,\n     59,63,73,29,125,61,65,95,101,81,57,69,83,37,11,37,95,1,73,27,\n     29,57,7,65,83,99,69,19,103,43,95,25,19,103,41,125,97,71,105,\n     83,83,61,39,9,45,117,63,31,5,117,67,125,41,117,43,77,97,15,\n     29,5,59,25,63,87,39,39,77,85,37,81,73,89,29,125,109,21,23,\n     119,105,43,93,97,15,125,29,51,69,37,45,31,75,109,119,53,5,\n     101,125,121,35,29,7,63,17,63,13,69,15,105,51,127,105,9,57,95,\n     59,109,35,49,23,33,107,55,33,57,79,73,69,59,107,55,11,63,95,\n     103,23,125,91,31,91,51,65,61,75,69,107,65,101,59,35,15},\n     /* [7][*] */\n     { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\n       7,23,39,217,141,27,53,181,169,35,15,\n     207,45,247,185,117,41,81,223,151,81,189,61,95,185,23,73,113,\n     239,85,9,201,83,53,183,203,91,149,101,13,111,239,3,205,253,\n     247,121,189,169,179,197,175,217,249,195,95,63,19,7,5,75,217,\n     245,111,189,165,169,141,221,249,159,253,207,249,219,23,49,\n     127,237,5,25,177,37,103,65,167,81,87,119,45,79,143,57,79,187,\n     143,183,75,97,211,149,175,37,135,189,225,241,63,33,43,13,73,\n     213,57,239,183,117,21,29,115,43,205,223,15,3,159,51,101,127,\n     99,239,171,113,171,119,189,245,201,27,185,229,105,153,189,33,\n     35,137,77,97,17,181,55,197,201,155,37,197,137,223,25,179,91,\n     23,235,53,253,49,181,249,53,173,97,247,67,115,103,159,239,69,\n     173,217,95,221,247,97,91,123,223,213,129,181,87,239,85,89,\n     249,141,39,57,249,71,101,159,33,137,189,71,253,205,171,13,\n     249,109,131,199,189,179,31,99,113,41,173,23,189,197,3,135,9,\n     95,195,27,183,1,123,73,53,99,197,59,27,101,55,193,31,61,119,\n     11,7,255,233,53,157,193,97,83,65,81,239,167,69,71,109,\n     97,137,71,193,189,115,79,205,37,227,\n     53,33,91,229,245,105,77,229,161,103,93,13,161,229,223,69,15,\n     25,23,233,93,25,217,247,61,75,27,9,223,213,55,197,145,89,199,\n     41,201,5,149,35,119,183,53,11,13,3,179,229,43,55,187,233,47,\n     133,91,47,71,93,105,145,45,255,221,115,175,19,129,5,209,197,\n     57,177,115,187,119,77,211,111,33,113,23,87,137,41,7,83,43,\n     121,145,5,219,27,11,111,207,55,97,63,229,53,33,149,23,187,\n     153,91,193,183,59,211,93,139,59,179,163,209,77,39,111,79,229,\n     85,237,199,137,147,25,73,121,129,83,87,93,205,167,53,107,229,\n     213,95,219,109,175,13,209,97,61,147,19,13,123,73,35,141,81,\n     19,171,255,111,107,233,113,133,89,9,231,95,69,33,1,253,219,\n     253,247,129,11,251,221,153,35,103,239,7,27,235,181,5,207,53,\n     149,155,225,165,137,155,201,97,245,203,47,39,35,105,239,49,\n     15,253,7,237,213,55,87,199,27,175,49,41,229,85,3,149,179,129,\n     185,249,197,15,97,197,139,203,63,33,251,217,199,199,99,249,\n     33,229,177,13,209,147,97,31,125,177,137,\n     187,11,91,223,29,169,231,59,31,163,41,\n     57,87,247,25,127,101,207,187,73,61,105,27,91,171,243,33,3,1,\n     21,229,93,71,61,37,183,65,211,53,11,151,165,47,5,129,79,101,\n     147,169,181,19,95,77,139,197,219,97,239,183,143,9,13,209,23,\n     215,53,137,203,19,151,171,133,219,231,3,15,253,225,33,111,\n     183,213,169,119,111,15,201,123,121,225,113,113,225,161,165,1,\n     139,55,3,93,217,193,97,29,69,231,161,93,69,143,137,9,87,183,\n     113,183,73,215,137,89,251,163,41,227,145,57,81,57,11,135,145,\n     161,175,159,25,55,167,157,211,97,247,249,23,129,159,71,197,\n     127,141,219,5,233,131,217,101,131,33,157,173,69,207,239,81,\n     205,11,41,169,65,193,77,201,173,1,221,157,1,15,113,147,137,\n     205,225,73,45,49,149,113,253,99,17,119,105,117,129,243,75,\n     203,53,29,247,35,247,171,31,199,213,29,251,7,251,187,91,11,\n     149,13,205,37,249,137,139,9,7,113,183,205,187,39,3,79,155,\n     227,89,185,51,127,63,83,41,133,183,181,127,19,255,219,59,251,\n     3,187,57,217,115,217,229,181,185,149,83,115,11,\n     123,19,109,165,103,123,219,129,155,\n     207,177,9,49,181,231,33,233,67,155,41,9,95,123,65,117,249,85,\n     169,129,241,173,251,225,147,165,69,81,239,95,23,83,227,249,\n     143,171,193,9,21,57,73,97,57,29,239,151,159,191,47,51,1,223,\n     251,251,151,41,119,127,131,33,209,123,53,241,25,31,183,107,\n     25,115,39,11,213,239,219,109,185,35,133,123,185,27,55,245,61,\n     75,205,213,169,163,63,55,49,83,195,51,31,41,15,203,41,63,127,\n     161,5,143,7,199,251,95,75,101,15,43,237,197,117,167,155,21,\n     83,205,255,49,101,213,237,135,135,21,73,93,115,7,85,223,237,\n     79,89,5,57,239,67,65,201,155,71,85,195,89,181,119,135,147,\n     237,173,41,155,67,113,111,21,183,23,103,207,253,69,219,205,\n     195,43,197,229,139,177,129,69,97,201,163,189,11,99,91,253,\n     239,91,145,19,179,231,121,7,225,237,125,191,119,59,175,237,\n     131,79,43,45,205,199,251,153,207,37,179,113,255,107,217,61,7,\n     181,247,31,13,113,145,107,233,233,43,79,23,169,137,129,183,\n     53,91,55,103,223,87,177,157,79,213,139,\n     183,231,205,143,129,243,205,93,59,\n     15,89,9,11,47,133,227,75,9,91,19,171,163,79,7,103,5,119,155,\n     75,11,71,95,17,13,243,207,187},\n     /* [8][*] */\n     { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\n       235,307,495,417,57,151,19,119,375,451,\n     55,449,501,53,185,317,17,21,487,13,347,393,15,391,307,189,\n     381,71,163,99,467,167,433,337,257,179,47,385,23,117,369,425,\n     207,433,301,147,333,85,221,423,49,3,43,229,227,201,383,281,\n     229,207,21,343,251,397,173,507,421,443,399,53,345,77,385,317,\n     155,187,269,501,19,169,235,415,61,247,183,5,257,401,451,95,\n     455,49,489,75,459,377,87,463,155,233,115,429,211,419,143,487,\n     195,209,461,193,157,193,363,181,271,445,381,231,135,327,403,\n     171,197,181,343,113,313,393,311,415,267,247,425,233,289,55,\n     39,247,327,141,5,189,183,27,337,341,327,87,429,357,265,251,\n     437,201,29,339,257,377,17,53,327,47,375,393,369,403,125,429,\n     257,157,217,85,267,117,337,447,219,501,41,41,193,509,131,207,\n     505,421,149,111,177,167,223,291,91,29,305,151,177,337,183,\n     361,435,307,507,77,181,507,315,145,423,71,103,493,271,469,\n     339,237,437,483,31,219,61,131,391,233,219,69,57,459,225,421,\n     7,461,111,451,277,185,193,125,251,199,73,71,7,409,417,149,\n     193,53,437,29,467,229,31,35,75,105,\n     503,75,317,401,367,131,365,441,433,93,377,405,465,259,283,\n     443,143,445,3,461,329,309,77,323,155,347,45,381,315,463,207,\n     321,157,109,479,313,345,167,439,307,235,473,79,101,245,19,\n     381,251,35,25,107,187,115,113,321,115,445,61,77,293,405,13,\n     53,17,171,299,41,79,3,485,331,13,257,59,201,497,81,451,199,\n     171,81,253,365,75,451,149,483,81,453,469,485,305,163,401,15,\n     91,3,129,35,239,355,211,387,101,299,67,375,405,357,267,363,\n     79,83,437,457,39,97,473,289,179,57,23,49,79,71,341,287,95,\n     229,271,475,49,241,261,495,353,381,13,291,37,251,105,399,81,\n     89,265,507,205,145,331,129,119,503,249,1,289,463,163,443,63,\n     123,361,261,49,429,137,355,175,507,59,277,391,25,185,381,197,\n     39,5,429,119,247,177,329,465,421,271,467,151,45,429,137,471,\n     11,17,409,347,199,463,177,11,51,361,95,497,163,351,127,395,\n     511,327,353,49,105,151,321,331,329,509,107,109,303,467,287,\n     161,45,385,289,363,331,265,407,37,433,315,343,63,51,185,71,\n     27,267,\n     503,239,293,245,281,297,75,461,371,\n     129,189,189,339,287,111,111,379,93,27,185,347,337,247,507,\n     161,231,43,499,73,327,263,331,249,493,37,25,115,3,167,197,\n     127,357,497,103,125,191,165,55,101,95,79,351,341,43,125,135,\n     173,289,373,133,421,241,281,213,177,363,151,227,145,363,239,\n     431,81,397,241,67,291,255,405,421,399,75,399,105,329,41,425,\n     7,283,375,475,427,277,209,411,3,137,195,289,509,121,55,147,\n     275,251,19,129,285,415,487,491,193,219,403,23,97,65,285,75,\n     21,373,261,339,239,495,415,333,107,435,297,213,149,463,199,\n     323,45,19,301,121,499,187,229,63,425,99,281,35,125,349,87,\n     101,59,195,511,355,73,263,243,101,165,141,11,389,219,187,449,\n     447,393,477,305,221,51,355,209,499,479,265,377,145,411,173,\n     11,433,483,135,385,341,89,209,391,33,395,319,451,119,341,227,\n     375,61,331,493,411,293,47,203,375,167,395,155,5,237,361,489,\n     127,21,345,101,371,233,431,109,119,277,125,263,73,135,123,83,\n     123,405,69,75,287,401,23,283,393,41,379,431,11,475,505,19,\n     365,265,271,\n     499,489,443,165,91,83,291,319,199,\n     107,245,389,143,137,89,125,281,381,215,131,299,249,375,455,\n     43,73,281,217,297,229,431,357,81,357,171,451,481,13,387,491,\n     489,439,385,487,177,393,33,71,375,443,129,407,395,127,65,333,\n     309,119,197,435,497,373,71,379,509,387,159,265,477,463,449,\n     47,353,249,335,505,89,141,55,235,187,87,363,93,363,101,67,\n     215,321,331,305,261,411,491,479,65,307,469,415,131,315,487,\n     83,455,19,113,163,503,99,499,251,239,81,167,391,255,317,363,\n     359,395,419,307,251,267,171,461,183,465,165,163,293,477,223,\n     403,389,97,335,357,297,19,469,501,249,85,213,311,265,379,297,\n     283,393,449,463,289,159,289,499,407,129,137,221,43,89,403,\n     271,75,83,445,453,389,149,143,423,499,317,445,157,137,453,\n     163,87,23,391,119,427,323,173,89,259,377,511,249,31,363,229,\n     353,329,493,427,57,205,389,91,83,13,219,439,45,35,371,441,17,\n     267,501,53,25,333,17,201,475,257,417,345,381,377,55,403,77,\n     389,347,363,211,413,419,5,167,219,201,285,425,11,77,269,489,\n     281,403,79,\n     425,125,81,331,437,271,397,299,475,\n     271,249,413,233,261,495,171,69,27,409,21,421,367,81,483,255,\n     15,219,365,497,181,75,431,99,325,407,229,281,63,83,493,5,113,\n     15,271,37,87,451,299,83,451,311,441,47,455,47,253,13,109,369,\n     347,11,409,275,63,441,15},\n     /* [9][*] */\n     { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\n       519,307,931,1023,517,771,151,1023,\n     539,725,45,927,707,29,125,371,275,279,817,389,453,989,1015,\n     29,169,743,99,923,981,181,693,309,227,111,219,897,377,425,\n     609,227,19,221,143,581,147,919,127,725,793,289,411,835,921,\n     957,443,349,813,5,105,457,393,539,101,197,697,27,343,515,69,\n     485,383,855,693,133,87,743,747,475,87,469,763,721,345,479,\n     965,527,121,271,353,467,177,245,627,113,357,7,691,725,355,\n     889,635,737,429,545,925,357,873,187,351,677,999,921,477,233,\n     765,495,81,953,479,89,173,473,131,961,411,291,967,65,511,13,\n     805,945,369,827,295,163,835,259,207,331,29,315,999,133,967,\n     41,117,677,471,717,881,755,351,723,259,879,455,721,289,149,\n     199,805,987,851,423,597,129,11,733,549,153,285,451,559,377,\n     109,357,143,693,615,677,701,475,767,85,229,509,547,151,389,\n     711,785,657,319,509,99,1007,775,359,697,677,85,497,105,615,\n     891,71,449,835,609,377,693,665,627,215,911,503,729,131,19,\n     895,199,161,239,633,1013,537,255,23,149,679,1021,595,199,557,\n     659,251,829,727,439,495,647,223,\n     949,625,87,481,85,799,917,769,949,\n     739,115,499,945,547,225,1015,469,737,495,353,103,17,665,639,\n     525,75,447,185,43,729,577,863,735,317,99,17,477,893,537,519,\n     1017,375,297,325,999,353,343,729,135,489,859,267,141,831,141,\n     893,249,807,53,613,131,547,977,131,999,175,31,341,739,467,\n     675,241,645,247,391,583,183,973,433,367,131,467,571,309,385,\n     977,111,917,935,473,345,411,313,97,149,959,841,839,669,431,\n     51,41,301,247,1015,377,329,945,269,67,979,581,643,823,557,91,\n     405,117,801,509,347,893,303,227,783,555,867,99,703,111,797,\n     873,541,919,513,343,319,517,135,871,917,285,663,301,15,763,\n     89,323,757,317,807,309,1013,345,499,279,711,915,411,281,193,\n     739,365,315,375,809,469,487,621,857,975,537,939,585,129,625,\n     447,129,1017,133,83,3,415,661,53,115,903,49,79,55,385,261,\n     345,297,199,385,617,25,515,275,849,401,471,377,661,535,505,\n     939,465,225,929,219,955,659,441,117,527,427,515,287,191,33,\n     389,197,825,63,417,949,35,571,9,131,609,439,95,19,569,893,\n     451,397,971,801,\n     125,471,187,257,67,949,621,453,411,\n     621,955,309,783,893,597,377,753,145,637,941,593,317,555,375,\n     575,175,403,571,555,109,377,931,499,649,653,329,279,271,647,\n     721,665,429,957,803,767,425,477,995,105,495,575,687,385,227,\n     923,563,723,481,717,111,633,113,369,955,253,321,409,909,367,\n     33,967,453,863,449,539,781,911,113,7,219,725,1015,971,1021,\n     525,785,873,191,893,297,507,215,21,153,645,913,755,371,881,\n     113,903,225,49,587,201,927,429,599,513,97,319,331,833,325,\n     887,139,927,399,163,307,803,169,1019,869,537,907,479,335,697,\n     479,353,769,787,1023,855,493,883,521,735,297,1011,991,879,\n     855,591,415,917,375,453,553,189,841,339,211,601,57,765,745,\n     621,209,875,639,7,595,971,263,1009,201,23,77,621,33,535,963,\n     661,523,263,917,103,623,231,47,301,549,337,675,189,357,1005,\n     789,189,319,721,1005,525,675,539,191,813,917,51,167,415,579,\n     755,605,721,837,529,31,327,799,961,279,409,847,649,241,285,\n     545,407,161,591,73,313,811,17,663,269,261,37,783,127,917,231,\n     577,975,793,\n     921,343,751,139,221,79,817,393,545,\n     11,781,71,1,699,767,917,9,107,341,587,903,965,599,507,843,\n     739,579,397,397,325,775,565,925,75,55,979,931,93,957,857,753,\n     965,795,67,5,87,909,97,995,271,875,671,613,33,351,69,811,669,\n     729,401,647,241,435,447,721,271,745,53,775,99,343,451,427,\n     593,339,845,243,345,17,573,421,517,971,499,435,769,75,203,\n     793,985,343,955,735,523,659,703,303,421,951,405,631,825,735,\n     433,841,485,49,749,107,669,211,497,143,99,57,277,969,107,397,\n     563,551,447,381,187,57,405,731,769,923,955,915,737,595,341,\n     253,823,197,321,315,181,885,497,159,571,981,899,785,947,217,\n     217,135,753,623,565,717,903,581,955,621,361,869,87,943,907,\n     853,353,335,197,771,433,743,195,91,1023,63,301,647,205,485,\n     927,1003,987,359,577,147,141,1017,701,273,89,589,487,859,343,\n     91,847,341,173,287,1003,289,639,983,685,697,35,701,645,911,\n     501,705,873,763,745,657,559,699,315,347,429,197,165,955,859,\n     167,303,833,531,473,635,641,195,589,821,205,3,635,371,891,\n     249,123,\n     77,623,993,401,525,427,71,655,951,\n     357,851,899,535,493,323,1003,343,515,859,1017,5,423,315,1011,\n     703,41,777,163,95,831,79,975,235,633,723,297,589,317,679,981,\n     195,399,1003,121,501,155},\n     /* [10][*] */\n     { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\n       7,2011,1001,49,825,415,1441,383,1581,\n     623,1621,1319,1387,619,839,217,75,1955,505,281,1629,1379,53,\n     1111,1399,301,209,49,155,1647,631,129,1569,335,67,1955,1611,\n     2021,1305,121,37,877,835,1457,669,1405,935,1735,665,551,789,\n     1543,1267,1027,1,1911,163,1929,67,1975,1681,1413,191,1711,\n     1307,401,725,1229,1403,1609,2035,917,921,1789,41,2003,187,67,\n     1635,717,1449,277,1903,1179,363,1211,1231,647,1261,1029,1485,\n     1309,1149,317,1335,171,243,271,1055,1601,1129,1653,205,1463,\n     1681,1621,197,951,573,1697,1265,1321,1805,1235,1853,1307,945,\n     1197,1411,833,273,1517,1747,1095,1345,869,57,1383,221,1713,\n     335,1751,1141,839,523,1861,1105,389,1177,1877,805,93,1591,\n     423,1835,99,1781,1515,1909,1011,303,385,1635,357,973,1781,\n     1707,1363,1053,649,1469,623,1429,1241,1151,1055,503,921,3,\n     349,1149,293,45,303,877,1565,1583,1001,663,1535,395,1141,\n     1481,1797,643,1507,465,2027,1695,367,937,719,545,1991,83,819,\n     239,1791,1461,1647,1501,1161,1629,139,1595,1921,1267,1415,\n     509,347,777,1083,363,269,1015,\n     1809,1105,1429,1471,2019,381,2025,\n     1223,827,1733,887,1321,803,1951,1297,1995,833,1107,1135,1181,\n     1251,983,1389,1565,273,137,71,735,1005,933,67,1471,551,457,\n     1667,1729,919,285,1629,1815,653,1919,1039,531,393,1411,359,\n     221,699,1485,471,1357,1715,595,1677,153,1903,1281,215,781,\n     543,293,1807,965,1695,443,1985,321,879,1227,1915,839,1945,\n     1993,1165,51,557,723,1491,817,1237,947,1215,1911,1225,1965,\n     1889,1503,1177,73,1767,303,177,1897,1401,321,921,217,1779,\n     327,1889,333,615,1665,1825,1639,237,1205,361,129,1655,983,\n     1089,1171,401,677,643,749,303,1407,1873,1579,1491,1393,1247,\n     789,763,49,5,1607,1891,735,1557,1909,1765,1777,1127,813,695,\n     97,731,1503,1751,333,769,865,693,377,1919,957,1359,1627,1039,\n     1783,1065,1665,1917,1947,991,1997,841,459,221,327,1595,1881,\n     1269,1007,129,1413,475,1105,791,1983,1359,503,691,659,691,\n     343,1375,1919,263,1373,603,1383,297,781,145,285,767,1739,\n     1715,715,317,1333,85,831,1615,81,1667,1467,1457,1453,1825,\n     109,387,1207,2039,213,1351,1329,1173,\n     57,1769,951,183,23,451,1155,1551,\n     2037,811,635,1671,1451,863,1499,1673,363,1029,1077,1525,277,\n     1023,655,665,1869,1255,965,277,1601,329,1603,1901,395,65,\n     1307,2029,21,1321,543,1569,1185,1905,1701,413,2041,1697,725,\n     1417,1847,411,211,915,1891,17,1877,1699,687,1089,1973,1809,\n     851,1495,1257,63,1323,1307,609,881,1543,177,617,1505,1747,\n     1537,925,183,77,1723,1877,1703,397,459,521,257,1177,389,1947,\n     1553,1583,1831,261,485,289,1281,1543,1591,1123,573,821,1065,\n     1933,1373,2005,905,207,173,1573,1597,573,1883,1795,1499,1743,\n     553,335,333,1645,791,871,1157,969,557,141,223,1129,1685,423,\n     1069,391,99,95,1847,531,1859,1833,1833,341,237,1997,1799,409,\n     431,1917,363,335,1039,1085,1657,1975,1527,1111,659,389,899,\n     595,1439,1861,1979,1569,1087,1009,165,1895,1481,1583,29,1193,\n     1673,1075,301,1081,1377,1747,1497,1103,1789,887,739,1577,313,\n     1367,1299,1801,1131,1837,73,1865,1065,843,635,55,1655,913,\n     1037,223,1871,1161,461,479,511,1721,1107,389,151,35,375,1099,\n     937,1185,1701,769,639,1633,\n     1609,379,1613,2031,685,289,975,671,\n     1599,1447,871,647,99,139,1427,959,89,117,841,891,1959,223,\n     1697,1145,499,1435,1809,1413,1445,1675,171,1073,1349,1545,\n     2039,1027,1563,859,215,1673,1919,1633,779,411,1845,1477,1489,\n     447,1545,351,1989,495,183,1639,1385,1805,1097,1249,1431,1571,\n     591,697,1509,709,31,1563,165,513,1425,1299,1081,145,1841,\n     1211,941,609,845,1169,1865,1593,347,293,1277,157,211,93,1679,\n     1799,527,41,473,563,187,1525,575,1579,857,703,1211,647,709,\n     981,285,697,163,981,153,1515,47,1553,599,225,1147,381,135,\n     821,1965,609,1033,983,503,1117,327,453,2005,1257,343,1649,\n     1199,599,1877,569,695,1587,1475,187,973,233,511,51,1083,665,\n     1321,531,1875,1939,859,1507,1979,1203,1965,737,921,1565,1943,\n     819,223,365,167,1705,413,1577,745,1573,655,1633,1003,91,1123,\n     477,1741,1663,35,715,37,1513,815,941,1379,263,1831,1735,1111,\n     1449,353,1941,1655,1349,877,285,1723,125,1753,985,723,175,\n     439,791,1051,1261,717,1555,1757,1777,577,1583,1957,873,331,\n     1163,313,1,1963,963,1905,821,\n     1677,185,709,545,1723,215,1885,\n     1249,583,1803,839,885,485,413,1767,425,129,1035,329,1263,\n     1881,1779,1565,359,367,453,707,1419,831,1889,887,1871,1869,\n     747,223,1547,1799,433,1441,553,2021,1303,1505,1735,1619,1065,\n     1161,2047,347,867,881,1447,329,781,1065,219,589,645,1257,\n     1833,749,1841,1733,1179,1191,1025,1639,1955,1423,1685,1711,\n     493,549,783,1653,397,895,233,759,1505,677,1449,1573,1297,\n     1821,1691,791,289,1187,867,1535,575,183},\n     /* [11][*] */\n     { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\n       3915,97,3047,937,2897,953,127,1201,\n     3819,193,2053,3061,3759,1553,2007,2493,603,3343,3751,1059,\n     783,1789,1589,283,1093,3919,2747,277,2605,2169,2905,721,4069,\n     233,261,1137,3993,3619,2881,1275,3865,1299,3757,1193,733,993,\n     1153,2945,3163,3179,437,271,3493,3971,1005,2615,2253,1131,\n     585,2775,2171,2383,2937,2447,1745,663,1515,3767,2709,1767,\n     3185,3017,2815,1829,87,3341,793,2627,2169,1875,3745,367,3783,\n     783,827,3253,2639,2955,3539,1579,2109,379,2939,3019,1999,\n     2253,2911,3733,481,1767,1055,4019,4085,105,1829,2097,2379,\n     1567,2713,737,3423,3941,2659,3961,1755,3613,1937,1559,2287,\n     2743,67,2859,325,2601,1149,3259,2403,3947,2011,175,3389,3915,\n     1315,2447,141,359,3609,3933,729,2051,1755,2149,2107,1741,\n     1051,3681,471,1055,845,257,1559,1061,2803,2219,1315,1369,\n     3211,4027,105,11,1077,2857,337,3553,3503,3917,2665,3823,3403,\n     3711,2085,1103,1641,701,4095,2883,1435,653,2363,1597,767,869,\n     1825,1117,1297,501,505,149,873,2673,551,1499,2793,3277,2143,\n     3663,533,3991,575,1877,1009,3929,473,3009,2595,3249,675,3593,\n     2453,1567,973,595,1335,1715,589,85,\n     2265,3069,461,1659,2627,1307,1731,1501,1699,3545,3803,2157,\n     453,2813,2047,2999,3841,2361,1079,573,69,1363,1597,3427,2899,\n     2771,1327,1117,1523,3521,2393,2537,1979,3179,683,2453,453,\n     1227,779,671,3483,2135,3139,3381,3945,57,1541,3405,3381,2371,\n     2879,1985,987,3017,3031,3839,1401,3749,2977,681,1175,1519,\n     3355,907,117,771,3741,3337,1743,1227,3335,2755,1909,3603,\n     2397,653,87,2025,2617,3257,287,3051,3809,897,2215,63,2043,\n     1757,3671,297,3131,1305,293,3865,3173,3397,2269,3673,717,\n     3041,3341,3595,3819,2871,3973,1129,513,871,1485,3977,2473,\n     1171,1143,3063,3547,2183,3993,133,2529,2699,233,2355,231,\n     3241,611,1309,3829,1839,1495,301,1169,1613,2673,243,3601,\n     3669,2813,2671,2679,3463,2477,1795,617,2317,1855,1057,1703,\n     1761,2515,801,1205,1311,473,3963,697,1221,251,381,3887,1761,\n     3093,3721,2079,4085,379,3601,3845,433,1781,29,1897,1599,2163,\n     75,3475,3957,1641,3911,2959,2833,1279,1099,403,799,2183,2699,\n     1711,2037,727,289,1785,1575,3633,2367,1261,3953,1735,171,\n     1959,\n     2867,859,2951,3211,15,1279,1323,599,\n     1651,3951,1011,315,3513,3351,1725,3793,2399,287,4017,3571,\n     1007,541,3115,429,1585,1285,755,1211,3047,915,3611,2697,2129,\n     3669,81,3939,2437,915,779,3567,3701,2479,3807,1893,3927,2619,\n     2543,3633,2007,3857,3837,487,1769,3759,3105,2727,3155,2479,\n     1341,1657,2767,2541,577,2105,799,17,2871,3637,953,65,69,2897,\n     3841,3559,4067,2335,3409,1087,425,2813,1705,1701,1237,821,\n     1375,3673,2693,3925,1541,1871,2285,847,4035,1101,2029,855,\n     2733,2503,121,2855,1069,3463,3505,1539,607,1349,575,2301,\n     2321,1101,333,291,2171,4085,2173,2541,1195,925,4039,1379,699,\n     1979,275,953,1755,1643,325,101,2263,3329,3673,3413,1977,2727,\n     2313,1419,887,609,2475,591,2613,2081,3805,3435,2409,111,3557,\n     3607,903,231,3059,473,2959,2925,3861,2043,3887,351,2865,369,\n     1377,2639,1261,3625,3279,2201,2949,3049,449,1297,897,1891,\n     411,2773,749,2753,1825,853,2775,3547,3923,3923,987,3723,2189,\n     3877,3577,297,2763,1845,3083,2951,483,2169,3985,245,3655,\n     3441,1023,235,835,3693,3585,327,1003,543,3059,2637,\n     2923,87,3617,1031,1043,903,2913,\n     2177,2641,3279,389,2009,525,4085,3299,987,2409,813,2683,373,\n     2695,3775,2375,1119,2791,223,325,587,1379,2877,2867,3793,655,\n     831,3425,1663,1681,2657,1865,3943,2977,1979,2271,3247,1267,\n     1747,811,159,429,2001,1195,3065,553,1499,3529,1081,2877,3077,\n     845,1793,2409,3995,2559,4081,1195,2955,1117,1409,785,287,\n     1521,1607,85,3055,3123,2533,2329,3477,799,3683,3715,337,3139,\n     3311,431,3511,2299,365,2941,3067,1331,1081,1097,2853,2299,\n     495,1745,749,3819,619,1059,3559,183,3743,723,949,3501,733,\n     2599,3983,3961,911,1899,985,2493,1795,653,157,433,2361,3093,\n     3119,3679,2367,1701,1445,1321,2397,1241,3305,3985,2349,4067,\n     3805,3073,2837,1567,3783,451,2441,1181,487,543,1201,3735,\n     2517,733,1535,2175,3613,3019},\n     /* [12][*] */\n     {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\n     2319,653,1379,1675,1951,7075,2087,\n     7147,1427,893,171,2019,7235,5697,3615,1961,7517,6849,2893,\n     1883,2863,2173,4543,73,381,3893,6045,1643,7669,1027,1549,\n     3983,1985,6589,7497,2745,2375,7047,1117,1171,1975,5199,3915,\n     3695,8113,4303,3773,7705,6855,1675,2245,2817,1719,569,1021,\n     2077,5945,1833,2631,4851,6371,833,7987,331,1899,8093,6719,\n     6903,5903,5657,5007,2689,6637,2675,1645,1819,689,6709,7717,\n     6295,7013,7695,3705,7069,2621,3631,6571,6259,7261,3397,7645,\n     1115,4753,2047,7579,2271,5403,4911,7629,4225,1209,6955,6951,\n     1829,5579,5231,1783,4285,7425,599,5785,3275,5643,2263,657,\n     6769,6261,1251,3249,4447,4111,3991,1215,131,4397,3487,7585,\n     5565,7199,3573,7105,7409,1671,949,3889,5971,3333,225,3647,\n     5403,3409,7459,6879,5789,6567,5581,4919,1927,4407,8085,4691,\n     611,3005,591,753,589,171,5729,5891,1033,3049,6567,5257,8003,\n     1757,4489,4923,6379,5171,1757,689,3081,1389,4113,455,2761,\n     847,7575,5829,633,6629,1103,7635,803,6175,6587,2711,3879,67,\n     1179,4761,7281,1557,3379,2459,4273,4127,7147,35,\n     3549,395,3735,5787,4179,5889,5057,\n     7473,4713,2133,2897,1841,2125,1029,1695,6523,1143,5105,7133,\n     3351,2775,3971,4503,7589,5155,4305,1641,4717,2427,5617,1267,\n     399,5831,4305,4241,3395,3045,4899,1713,171,411,7099,5473,\n     5209,1195,1077,1309,2953,7343,4887,3229,6759,6721,6775,675,\n     4039,2493,7511,3269,4199,6625,7943,2013,4145,667,513,2303,\n     4591,7941,2741,987,8061,3161,5951,1431,831,5559,7405,1357,\n     4319,4235,5421,2559,4415,2439,823,1725,6219,4903,6699,5451,\n     349,7703,2927,7809,6179,1417,5987,3017,4983,3479,4525,4643,\n     4911,227,5475,2287,5581,6817,1937,1421,4415,7977,1789,3907,\n     6815,6789,6003,5609,4507,337,7427,7943,3075,6427,1019,7121,\n     4763,81,3587,2929,1795,8067,2415,1265,4025,5599,4771,3025,\n     2313,6129,7611,6881,5253,4413,7869,105,3173,1629,2537,1023,\n     4409,7209,4413,7107,7469,33,1955,2881,5167,6451,4211,179,\n     5573,7879,3387,7759,5455,7157,1891,5683,5689,6535,3109,6555,\n     6873,1249,4251,6437,49,2745,1201,7327,4179,6783,623,2779,\n     5963,2585,6927,5333,4033,285,7467,4443,4917,3,\n     4319,5517,3449,813,5499,2515,5771,\n     3357,2073,4395,4925,2643,7215,5817,1199,1597,1619,7535,4833,\n     609,4797,8171,6847,793,6757,8165,3371,2431,5235,4739,7703,\n     7223,6525,5891,5605,4433,3533,5267,5125,5037,225,6717,1121,\n     5741,2013,4327,4839,569,5227,7677,4315,2391,5551,859,3627,\n     6377,3903,4311,6527,7573,4905,7731,1909,1555,3279,1949,1887,\n     6675,5509,2033,5473,3539,5033,5935,6095,4761,1771,1271,1717,\n     4415,5083,6277,3147,7695,2461,4783,4539,5833,5583,651,1419,\n     2605,5511,3913,5795,2333,2329,4431,3725,6069,2699,7055,6879,\n     1017,3121,2547,4603,2385,6915,6103,5669,7833,2001,4287,6619,\n     955,2761,5711,6291,3415,3909,2841,5627,4939,7671,6059,6275,\n     6517,1931,4583,7301,1267,7509,1435,2169,6939,3515,2985,2787,\n     2123,1969,3307,353,4359,7059,5273,5873,6657,6765,6229,3179,\n     1583,6237,2155,371,273,7491,3309,6805,3015,6831,7819,713,\n     4747,3935,4109,1311,709,3089,7059,4247,2989,1509,4919,1841,\n     3045,3821,6929,4655,1333,6429,6649,2131,5265,1051,261,8057,\n     3379,2179,1993,5655,3063,6381,\n     3587,7417,1579,1541,2107,5085,2873,\n     6141,955,3537,2157,841,1999,1465,5171,5651,1535,7235,4349,\n     1263,1453,1005,6893,2919,1947,1635,3963,397,969,4569,655,\n     6737,2995,7235,7713,973,4821,2377,1673,1,6541}\n};\n\n#endif\n"
  },
  {
    "path": "src/sobolseq.c",
    "content": "// -*- C++ -*-\n/* Copyright (c) 2007 Massachusetts Institute of Technology\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n/* Generation of Sobol sequences in up to 1111 dimensions, based on the\n   algorithms described in:\n        P. Bratley and B. L. Fox, Algorithm 659, ACM Trans.\n\tMath. Soft. 14 (1), 88-100 (1988),\n   as modified by:\n        S. Joe and F. Y. Kuo, ACM Trans. Math. Soft 29 (1), 49-57 (2003).\n\n   Note that the code below was written without even looking at the\n   Fortran code from the TOMS paper, which is only semi-free (being\n   under the restrictive ACM copyright terms).  Then I went to the\n   Fortran code and took out the table of primitive polynomials and\n   starting direction #'s ... since this is just a table of numbers\n   generated by a deterministic algorithm, it is not copyrightable.\n   (Obviously, the format of these tables then necessitated some\n   slight modifications to the code.)\n\n   For the test integral of Joe and Kuo (see the main() program\n   below), I get exactly the same results for integrals up to 1111\n   dimensions compared to the table of published numbers (to the 5\n   published significant digits).\n\n   This is not to say that the authors above should not be credited for\n   their clear description of the algorithm (and their tabulation of\n   the critical numbers).  Please cite them.  Just that I needed\n   a free/open-source implementation. */\n\n/* AAK Notes:\n   I have removed the dependence on the NLOPT headers and on \"stdint.h\".\n   The assumption is (according to R_ext/Random.h) that Int32 is a 32-bit \n   integer. The fall-back to pseudo-random numbers for sequences of length \n   greater than 2^32-1 has also been removed. This case generates an error.\n*/\n\n#include \"internal.h\"\n\ntypedef Int32 uint32_t;\ntypedef struct nlopt_soboldata_s *nlopt_sobol;\nstatic nlopt_sobol nlopt_sobol_create(unsigned sdim);\nstatic void nlopt_sobol_destroy(nlopt_sobol s);\nstatic void nlopt_sobol_skip(nlopt_sobol s, unsigned n, double *x);\n\ntypedef struct nlopt_soboldata_s {\n  unsigned sdim; /* dimension of sequence being generated */\n  uint32_t *mdata; /* array of length 32 * sdim */\n  uint32_t *m[32]; /* more convenient pointers to mdata, of direction #s */\n  uint32_t *x; /* previous x = x_n, array of length sdim */\n  unsigned *b; /* position of fixed point in x[i] is after bit b[i] */\n  uint32_t n; /* number of x's generated so far */\n} soboldata;\n\n/* Return position (0, 1, ...) of rightmost (least-significant) zero bit in n.\n *\n * This code uses a 32-bit version of algorithm to find the rightmost\n * one bit in Knuth, _The Art of Computer Programming_, volume 4A\n * (draft fascicle), section 7.1.3, \"Bitwise tricks and\n * techniques.\"\n *\n * Assumes n has a zero bit, i.e. n < 2^32 - 1.\n *\n */\nstatic unsigned rightzero32 (uint32_t n)\n{\n  const uint32_t a = 0x05f66a47; /* magic number, found by brute force */\n  static const unsigned decode[32] = {0,1,2,26,23,3,15,27,24,21,19,4,12,16,28,6,31,25,22,14,20,18,11,5,30,13,17,10,29,9,8,7};\n  n = ~n; /* change to rightmost-one problem */\n  n = a * (n & (-n)); /* store in n to make sure mult. is 32 bits */\n  return decode[n >> 27];\n}\n\n/* generate the next term x_{n+1} in the Sobol sequence, as an array\n   x[sdim] of numbers in (0,1).  Returns 1 on success, 0 on failure\n   (if too many #'s generated) */\nstatic int sobol_gen (soboldata *sd, double *x)\n{\n  unsigned c, b, i, sdim;\n\n  if (sd->n == 4294967295U) return 0; /* n == 2^32 - 1 ... we would\n\t\t\t\t\t need to switch to a 64-bit version\n\t\t\t\t\t to generate more terms. */\n  c = rightzero32(sd->n++);\n  sdim = sd->sdim;\n  for (i = 0; i < sdim; ++i) {\n    b = sd->b[i];\n    if (b >= c) {\n      sd->x[i] ^= sd->m[c][i] << (b - c);\n      x[i] = ((double) (sd->x[i])) / (1U << (b+1));\n    }\n    else {\n      sd->x[i] = (sd->x[i] << (c - b)) ^ sd->m[c][i];\n      sd->b[i] = c;\n      x[i] = ((double) (sd->x[i])) / (1U << (c+1));\n    }\n  }\n  return 1;\n}\n\n#include \"soboldata.h\"\n\nstatic int sobol_init (soboldata *sd, unsigned sdim)\n{\n  unsigned i,j;\n\n  if (!sdim || sdim > MAXDIM) return 0;\n\n  sd->mdata = (uint32_t *) R_Calloc(sdim*32,uint32_t);\n  if (!sd->mdata) return 0;\n\n  for (j = 0; j < 32; ++j) {\n    sd->m[j] = sd->mdata + j * sdim;\n    sd->m[j][0] = 1; /* special-case Sobol sequence */\n  }\n  for (i = 1; i < sdim; ++i) {\n    uint32_t a = sobol_a[i-1];\n    unsigned d = 0, k;\n\n    while (a) {\n      ++d;\n      a >>= 1;\n    }\n    d--; /* d is now degree of poly */\n\n    /* set initial values of m from table */\n    for (j = 0; j < d; ++j)\n      sd->m[j][i] = sobol_minit[j][i-1];\n\n    /* fill in remaining values using recurrence */\n    for (j = d; j < 32; ++j) {\n      a = sobol_a[i-1];\n      sd->m[j][i] = sd->m[j - d][i];\n      for (k = 0; k < d; ++k) {\n\tsd->m[j][i] ^= ((a & 1) * sd->m[j-d+k][i]) << (d-k);\n\ta >>= 1;\n      }\n    }\n  }\n\n  sd->x = (uint32_t *) R_Calloc(sdim,uint32_t);\n  if (!sd->x) { R_Free(sd->mdata); return 0; }\n\n  sd->b = (unsigned *) R_Calloc(sdim,unsigned);\n  if (!sd->b) { R_Free(sd->x); R_Free(sd->mdata); return 0; }\n\n  for (i = 0; i < sdim; ++i) {\n    sd->x[i] = 0;\n    sd->b[i] = 0;\n  }\n\n  sd->n = 0;\n  sd->sdim = sdim;\n\n  return 1;\n}\n\nstatic void sobol_destroy (soboldata *sd)\n{\n  R_Free(sd->mdata);\n  R_Free(sd->x);\n  R_Free(sd->b);\n}\n\n/************************************************************************/\n/* NLopt API to Sobol sequence creation, which hides soboldata structure\n   behind an opaque pointer */\n\nstatic nlopt_sobol nlopt_sobol_create (unsigned sdim)\n{\n  nlopt_sobol s = (nlopt_sobol) R_Calloc(1,soboldata);\n  if (!s) return 0;\n  if (!sobol_init(s, sdim)) { R_Free(s); return NULL; }\n  return s;\n}\n\nstatic void nlopt_sobol_destroy (nlopt_sobol s)\n{\n  if (s) {\n    sobol_destroy(s);\n    R_Free(s);\n  }\n}\n\n/* next vector x[sdim] in Sobol sequence, with each x[i] in (0,1) */\n// void nlopt_sobol_next01 (nlopt_sobol s, double *x)\n// {\n//   if (!sobol_gen(s, x))\n//     err(\"too many points requested\");\n// }\n\n/* next vector in Sobol sequence, scaled to (lb[i], ub[i]) interval */\n// void nlopt_sobol_next (nlopt_sobol s, double *x,\n// \t\t       const double *lb, const double *ub)\n// {\n//   unsigned i, sdim;\n//   nlopt_sobol_next01(s, x);\n//   for (sdim = s->sdim, i = 0; i < sdim; ++i)\n//     x[i] = lb[i] + (ub[i] - lb[i]) * x[i];\n// }\n\n/* if we know in advance how many points (n) we want to compute, then\n   adopt the suggestion of the Joe and Kuo paper, which in turn\n   is taken from Acworth et al (1998), of skipping a number of\n   points equal to the largest power of 2 smaller than n */\nstatic void nlopt_sobol_skip(nlopt_sobol s, unsigned n, double *x)\n{\n  if (s) {\n    unsigned k = 1;\n    while (k*2 < n) k *= 2;\n    while (k-- > 0) sobol_gen(s, x);\n  }\n}\n\nSEXP sobol_sequence (SEXP dim, SEXP length)\n{\n  SEXP data;\n  unsigned int d = (unsigned int) INTEGER(dim)[0];\n  unsigned int n = (unsigned int) INTEGER(length)[0];\n  double *dp;\n  unsigned int k;\n  nlopt_sobol s = nlopt_sobol_create((unsigned int) d);\n  if (s==0) err(\"dimension is too high\");\n  PROTECT(data = allocMatrix(REALSXP,d,n)); dp = REAL(data);\n  nlopt_sobol_skip(s,n,dp);\n  for (k = 1; k < n; k++) sobol_gen(s,dp+k*d);\n  nlopt_sobol_destroy(s);\n  UNPROTECT(1);\n  return(data);\n}\n"
  },
  {
    "path": "src/ssa.c",
    "content": "// dear emacs, please treat this as -*- C++ -*-\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n#include \"internal.h\"\n\nstatic R_INLINE SEXP add_args (SEXP args, SEXP Snames, SEXP Pnames, SEXP Cnames)\n{\n\n  SEXP var;\n  int v;\n\n  PROTECT(args = VectorToPairList(args));\n\n  // we construct the call from end to beginning\n  // covariates, parameter, states, then time and 'j'\n\n  // Covariates\n  for (v = LENGTH(Cnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Cnames,v)));\n  }\n\n  // Parameters\n  for (v = LENGTH(Pnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Pnames,v)));\n  }\n\n  // Latent state variables\n  for (v = LENGTH(Snames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Snames,v)));\n  }\n\n  // Time\n  var = NEW_NUMERIC(1);\n  args = LCONS(var,args);\n  UNPROTECT(1);\n  PROTECT(args);\n  SET_TAG(args,install(\"t\"));\n\n  // 'j'\n  var = NEW_INTEGER(1);\n  args = LCONS(var,args);\n  UNPROTECT(1);\n  PROTECT(args);\n  SET_TAG(args,install(\"j\"));\n\n  UNPROTECT(1);\n  return args;\n\n}\n\nstatic void gillespie (double *t, double tmax, double *f, double *y,\n                       const double *v, int nvar, int nevent, Rboolean hasvname,\n                       const int *ivmat)\n{\n  double tstep, p;\n  double vv;\n  int i, j;\n\n  // Determine time interval and update time\n  double fsum = 0;\n  for (j = 0; j < nevent; j++) fsum += f[j];\n\n  if (fsum > 0.0) {\n    tstep = exp_rand()/fsum;\n    *t = *t+tstep;\n  } else {\n    *t = tmax;\n    return;\n  }\n\n  if (*t >= tmax) {\n\n    *t = tmax;\n\n  } else {\n\n    // Determine event, update pops & events\n    p = fsum*unif_rand();\n    int jevent = nevent-1;\n    for (j = 0; j < jevent; j++) {\n      if (p > f[j]) {\n        p -= f[j];\n      } else {\n        jevent = j;\n        break;\n      }\n    }\n\n    for (i = 0; i < nvar; i++) {\n      vv = v[i+nvar*jevent];\n      if (vv != 0) {\n        if (hasvname) {\n          y[ivmat[i]] += vv;\n        } else {\n          y[i] += vv;\n        }\n      }\n    }\n\n  }\n}\n\nstatic void SSA (pomp_ssa_rate_fn *ratefun, int irep,\n                 int nvar, int nevent, int npar, int nrep, int ntimes,\n                 double *xstart, double t, const double *times, const double *params, double *xout,\n                 const double *v, int nzero, const int *izero,\n                 const int *istate, const int *ipar, int ncovar, const int *icovar,\n                 Rboolean hasvname, const int *ivmat,\n                 int mcov, lookup_table_t *tab, const double *hmax)\n{\n  double tmax;\n  double *f = NULL;\n  double *covars = NULL;\n  const double *par;\n  double y[nvar];\n  int i, j;\n\n  if (mcov > 0) covars = (double *) R_Calloc(mcov,double);\n  if (nevent > 0) f = (double *) R_Calloc(nevent,double);\n\n  par = params+npar*irep;\n  // Copy state variables\n  memcpy(y,xstart+nvar*irep,nvar*sizeof(double));\n  // Set appropriate states to zero\n  for (i = 0; i < nzero; i++) y[izero[i]] = 0.0;\n  // Initialize the covariate vector\n  if (mcov > 0) table_lookup(tab,t,covars);\n  // Initialise propensity functions & tree\n  for (j = 0; j < nevent; j++) {\n    f[j] = ratefun(j+1,t,y,par,istate,ipar,icovar,covars);\n    if (f[j] < 0.0)\n      err(\"'rate.fun' returns a negative rate\");\n  }\n\n  int icount = 0;\n  while (icount < ntimes) {\n\n    R_CheckUserInterrupt();\n    tmax = t + *hmax;\n    tmax = (tmax > times[icount]) ? times[icount] : tmax;\n    gillespie(&t,tmax,f,y,v,nvar,nevent,hasvname,ivmat);\n\n    if (mcov > 0) table_lookup(tab,t,covars);\n\n    for (j = 0; j < nevent; j++) {\n      f[j] = ratefun(j+1,t,y,par,istate,ipar,icovar,covars);\n      if (f[j] < 0.0)\n        err(\"'rate.fun' returns a negative rate\");\n    }\n\n    // Record output at required time points\n    if (t >= times[icount]) {\n      memcpy(xout+nvar*(irep+nrep*icount),y,nvar*sizeof(double));\n      // Set appropriate states to zero at time of last observation\n      for (i = 0; i < nzero; i++) y[izero[i]] = 0;\n      icount++;\n    }\n\n  }\n\n  if (mcov > 0) R_Free(covars);\n  if (nevent > 0) R_Free(f);\n\n}\n\n// these global objects will pass the needed information to the user-defined function (see '__pomp_Rfun_ssa_ratefn')\n// each of these is allocated once, globally, and refilled many times\nstatic int  __ssa_nvar; // number of state variables\nstatic int  __ssa_npar; // number of parameters\nstatic int  __ssa_ncov; // number of covariates\nstatic SEXP __ssa_args; // function arguments\nstatic SEXP __ssa_ratefn;       // function itself\nstatic int  __ssa_first;        // first evaluation?\nstatic pomp_ssa_rate_fn *__ssa_rxrate; // function computing reaction rates\n\n#define NVAR    (__ssa_nvar)\n#define NPAR    (__ssa_npar)\n#define NCOV    (__ssa_ncov)\n#define ARGS    (__ssa_args)\n#define RATEFN  (__ssa_ratefn)\n#define FIRST   (__ssa_first)\n#define RXR     (__ssa_rxrate)\n\nstatic double __pomp_Rfun_ssa_ratefn (int j, double t, const double *x, const double *p,\n                                      int *stateindex, int *parindex, int *covindex, double *c)\n{\n  SEXP var = ARGS, ans, ob;\n  int v;\n  double rate;\n\n  *(INTEGER(CAR(var))) = j; var = CDR(var);\n  *(REAL(CAR(var))) = t; var = CDR(var);\n  for (v = 0; v < NVAR; v++, x++, var=CDR(var)) *(REAL(CAR(var))) = *x;\n  for (v = 0; v < NPAR; v++, p++, var=CDR(var)) *(REAL(CAR(var))) = *p;\n  for (v = 0; v < NCOV; v++, c++, var=CDR(var)) *(REAL(CAR(var))) = *c;\n\n  PROTECT(ob = LCONS(RATEFN,ARGS));\n  PROTECT(ans = eval(ob,R_ClosureEnv(RATEFN)));\n\n  if (FIRST) {\n    if (LENGTH(ans) != 1)\n      err(\"'rate.fun' must return a single numeric rate.\");\n    FIRST = 0;\n  }\n\n  rate = *(REAL(AS_NUMERIC(ans)));\n  UNPROTECT(2);\n  return rate;\n}\n\nSEXP SSA_simulator (SEXP func, SEXP xstart, SEXP tstart, SEXP times, SEXP params,\n                    SEXP vmatrix, SEXP covar, SEXP accumvars, SEXP hmax, SEXP args, SEXP gnsi)\n{\n\n  int *dim, xdim[3];\n  int nvar, nvarv, nevent, npar, nrep, ntimes;\n  SEXP statenames, paramnames, covarnames;\n  int ncovars, covdim;\n  int nzeros = LENGTH(accumvars);\n  pompfunmode mode = undef;\n  SEXP X, zindex, vindex;\n  int *sidx, *pidx, *cidx, *zidx, *vidx;\n  SEXP fn, Snames, Pnames, Cnames, Vnames;\n  lookup_table_t covariate_table;\n  Rboolean hasvnames;\n  double t0;\n\n  dim = INTEGER(GET_DIM(xstart)); nvar = dim[0]; nrep = dim[1];\n  dim = INTEGER(GET_DIM(params)); npar = dim[0];\n  dim = INTEGER(GET_DIM(vmatrix)); nvarv = dim[0]; nevent = dim[1];\n\n  if (nvarv != nvar)\n    err(\"number of state variables must equal the number of rows in 'v'.\");\n\n  ntimes = LENGTH(times);\n\n  PROTECT(tstart = AS_NUMERIC(tstart));\n  PROTECT(times = AS_NUMERIC(times));\n  t0 = *(REAL(tstart));\n  if (t0 > *(REAL(times))) err(\"'t0' must be no later than 'times[1]'.\");\n\n  PROTECT(Snames = GET_ROWNAMES(GET_DIMNAMES(xstart)));\n  PROTECT(Pnames = GET_ROWNAMES(GET_DIMNAMES(params)));\n  PROTECT(Cnames = get_covariate_names(covar));\n  PROTECT(Vnames = GET_ROWNAMES(GET_DIMNAMES(vmatrix)));\n\n  covariate_table = make_covariate_table(covar,&covdim);\n\n  PROTECT(statenames = GET_SLOT(func,install(\"statenames\")));\n  PROTECT(paramnames = GET_SLOT(func,install(\"paramnames\")));\n  PROTECT(covarnames = GET_SLOT(func,install(\"covarnames\")));\n\n  ncovars = LENGTH(covarnames);\n  hasvnames = !isNull(Vnames);\n\n  PROTECT(hmax = AS_NUMERIC(hmax));\n\n  PROTECT(fn = pomp_fun_handler(func,gnsi,&mode,Snames,Pnames,NA_STRING,Cnames));\n\n  int nprotect = 11;\n\n  switch (mode) {\n\n  case undef: default:  // #nocov\n\n    err(\"unrecognized 'mode' %d\",mode); // #nocov\n\n  case native: case regNative:\n\n    *((void **) (&(RXR))) = R_ExternalPtrAddr(fn);\n\n    break;\n\n  case Rfun:\n\n    RXR = (pomp_ssa_rate_fn *) __pomp_Rfun_ssa_ratefn;\n    NVAR = nvar;\n    NPAR = npar;\n    NCOV = covdim;\n    PROTECT(ARGS = add_args(args,Snames,Pnames,Cnames));\n    PROTECT(RATEFN = fn);\n    nprotect += 2;\n    FIRST = 1;\n\n    break;\n\n  }\n\n  xdim[0] = nvar; xdim[1] = nrep; xdim[2] = ntimes;\n  PROTECT(X = makearray(3,xdim)); nprotect++;\n  setrownames(X,Snames,3);\n\n  sidx = INTEGER(GET_SLOT(func,install(\"stateindex\")));\n  pidx = INTEGER(GET_SLOT(func,install(\"paramindex\")));\n  cidx = INTEGER(GET_SLOT(func,install(\"covarindex\")));\n\n  if (nzeros>0) {\n    PROTECT(zindex = MATCHROWNAMES(xstart,accumvars,\"state variables\")); nprotect++;\n    zidx = INTEGER(zindex);\n  } else {\n    zidx = 0;\n  }\n\n  if (hasvnames) {\n    PROTECT(vindex = MATCHROWNAMES(xstart,Vnames,\"state variables\")); nprotect++;\n    vidx = INTEGER(vindex);\n  } else {\n    vidx = 0;\n  }\n\n  GetRNGstate();\n  {\n    int i;\n    for (i = 0; i < nrep; i++) {\n      SSA(RXR,i,nvar,nevent,npar,nrep,ntimes,\n          REAL(xstart),t0,REAL(times),REAL(params),\n          REAL(X),REAL(vmatrix),\n          nzeros,zidx,sidx,pidx,ncovars,cidx,hasvnames,vidx,\n          covdim,&covariate_table,REAL(hmax));\n    }\n  }\n  PutRNGstate();\n\n  UNPROTECT(nprotect);\n  return X;\n}\n"
  },
  {
    "path": "src/synth_lik.c",
    "content": "// -*- mode: C++ -*-\n\n#include \"internal.h\"\n#include \"pomp_mat.h\"\n\n// Campbell's robust variance-covariance estimation approach\n// described on p. 231 of Krzanowski 1988\n// with additional pre-conditioning for numerical stability\n// translated into C from R code by Simon N. Wood\n\nstatic void robust_synth_loglik (double *y, int *dim, double *ydat, double *loglik) {\n  // 'ydat' is destroyed\n  // 'y' is preserved\n  int nrow = dim[0];\n  int ncol = dim[1];\n  double w[nrow], tau[ncol], work[ncol];\n  int info = 0;\n  double one = 1.0;\n  double *y1, *y2, *yp;\n  long double x, xx, wbar, d, d0, rss, half_log_det;\n  long double alpha = 2.0, beta = 1.25;\n  int i, j;\n\n  half_log_det = ncol*M_LN_SQRT_2PI;\n\n  y1 = (double *) R_alloc(nrow*ncol,sizeof(double));\n  y2 = (double *) R_alloc(nrow*ncol,sizeof(double));\n\n  if (nrow <= ncol)\n    err(\"'nsim' (=%d) should be (much) larger than the number of probes (=%d)\",nrow,ncol); // #nocov\n\n  // compute column means, center each column, precondition\n  memcpy(y1,y,nrow*ncol*sizeof(double));\n  for (yp = y1, j = 0; j < ncol; j++, yp += nrow) {\n    for (x = 0, i = 0; i < nrow; i++) x += yp[i];\n    x /= nrow;\n    for (i = 0; i < nrow; i++) yp[i] -= x; // center the column\n    for (x = 0, i = 0; i < nrow; i++) x += yp[i]*yp[i];\n    d = sqrt(x/(nrow-1));                  // column SD\n    for (i = 0; i < nrow; i++) yp[i] /= d; // precondition\n  }\n\n  // do first QR decomposition & backsolve\n  memcpy(y2,y1,nrow*ncol*sizeof(double));\n  // LAPACK QR decomposition without pivoting DGEQR2(M,N,A,LDA,TAU,WORK,INFO)\n  F77_CALL(dgeqr2)(&nrow,&ncol,y2,&nrow,tau,work,&info);\n  // Level-3 BLAS triangular matrix solver DTRSM(SIDE,UPLO,TRANS,DIAG,M,N,ALPHA,A,LDA,B,LDB)\n  F77_CALL(dtrsm)(\"right\",\"upper\",\"no transpose\",\"non-unit\",&nrow,&ncol,&one,y2,&nrow,y1,&nrow FCONE FCONE FCONE FCONE);\n\n  // create Campbell weight vector\n  d0 = sqrt(ncol)+alpha/sqrt(2.0);\n  for (wbar = 0, i = 0; i < nrow; i++) {\n    for (xx = 0, j = 0; j < ncol; j++) {\n      x = y1[i+nrow*j];\n      xx += x*x;\n    }\n    d = sqrt((nrow-1)*xx); // Mahalonobis distance of row i\n    if (d > d0) {\n      x = d-d0;\n      xx = exp(-0.5*x*x/beta)*d0/d;\n    } else {\n      xx = 1.0;\n    }\n    w[i] = xx;\n    wbar += xx*xx;\n  }\n  wbar = sqrt(wbar-1);\n\n  // compute weighted column means, center each column, precondition\n  memcpy(y1,y,nrow*ncol*sizeof(double));\n  for (yp = y1, j = 0; j < ncol; j++, yp += nrow) {\n    for (x = 0, xx = 0, i = 0; i < nrow; i++) {\n      x += w[i];\n      xx += w[i]*yp[i];\n    }\n    xx /= x;                    // column mean\n    for (i = 0; i < nrow; i++) yp[i] -= xx; // center the column\n    ydat[j] -= xx;              // subtract mean from realized probe\n    for (xx = 0, i = 0; i < nrow; i++) {\n      xx += yp[i]*yp[i];\n      yp[i] /= wbar;\n    }\n    d = sqrt(xx/(nrow-1)); // column SD\n    for (i = 0; i < nrow; i++) yp[i] *= (w[i]/d); // precondition & weight\n    ydat[j] /= d;\n    half_log_det += log(d); // sum up logs(diag(D))\n  }\n\n  // do second QR decomposition & backsolve\n  // LAPACK QR decomposition without pivoting DGEQR2(M,N,A,LDA,TAU,WORK,INFO)\n  F77_CALL(dgeqr2)(&nrow,&ncol,y1,&nrow,tau,work,&info);\n  pomp_backsolve(y1,nrow,ncol,ydat,1,\"upper\",\"transpose\",\"non-unit\");\n\n  // compute residual sum of squares and add up logs of diag(R)\n  for (yp = y1, rss = 0, i = nrow+1, j = 0; j < ncol; j++, yp += i) { // yp marches along the diagonal of R\n    x = ydat[j];\n    rss += x*x;\n    half_log_det += log(fabs(*yp)); // log(diag(R))\n  }\n\n  *loglik = -0.5*rss-half_log_det;\n}\n\nSEXP synth_loglik (SEXP ysim, SEXP ydat) {\n  SEXP loglik, dim, y;\n\n  PROTECT(y = duplicate(AS_NUMERIC(ydat)));\n  PROTECT(dim = GET_DIM(ysim));\n  PROTECT(ysim = AS_NUMERIC(ysim));\n  PROTECT(loglik = NEW_NUMERIC(1));\n\n  robust_synth_loglik(REAL(ysim),INTEGER(dim),REAL(y),REAL(loglik));\n\n  UNPROTECT(4);\n  return loglik;\n}\n"
  },
  {
    "path": "src/trajectory.c",
    "content": "// -*- C++ -*-\n\n#include <Rdefines.h>\n#include \"internal.h\"\n\nstatic R_INLINE SEXP ret_array (int nvars, int nreps, int ntimes, SEXP Snames, SEXP repnames)\n{\n  SEXP X;\n  int dim[3] = {nvars, nreps, ntimes};\n  const char *dimnms[3] = {\"name\",\".id\",\"time\"};\n  PROTECT(X = makearray(3,dim));\n  setrownames(X,Snames,3);\n  setcolnames(X,repnames);\n  fixdimnames(X,dimnms,3);\n  UNPROTECT(1);\n  return X;\n}\n\nSEXP iterate_map (SEXP object, SEXP times, SEXP t0, SEXP x0, SEXP params, SEXP gnsi)\n{\n\n  pompfunmode mode = undef;\n  SEXP fn, args;\n  SEXP X, cov;\n  SEXP Snames, Pnames, Cnames;\n  SEXP skel, pompfun;\n  SEXP accumvars;\n  SEXP repnames;\n  int *zidx = 0;\n  int nvars, npars, nreps, nrepp, ntimes, ncovars, nzeros;\n  int *dim;\n  lookup_table_t covariate_table;\n  double deltat, t;\n\n  PROTECT(skel = GET_SLOT(object,install(\"skeleton\")));\n  deltat = *(REAL(GET_SLOT(skel,install(\"delta.t\"))));\n  t = *(REAL(AS_NUMERIC(t0)));\n\n  PROTECT(x0 = duplicate(x0));\n  PROTECT(x0 = as_matrix(x0));\n  dim = INTEGER(GET_DIM(x0));\n  nvars = dim[0]; nreps = dim[1];\n\n  PROTECT(params = as_matrix(params));\n  dim = INTEGER(GET_DIM(params));\n  npars = dim[0]; nrepp = dim[1];\n  PROTECT(repnames = GET_COLNAMES(GET_DIMNAMES(params)));\n\n  PROTECT(times = AS_NUMERIC(times));\n  ntimes = LENGTH(times);\n\n  PROTECT(Snames = GET_ROWNAMES(GET_DIMNAMES(x0)));\n  PROTECT(Pnames = GET_ROWNAMES(GET_DIMNAMES(params)));\n  PROTECT(Cnames = get_covariate_names(GET_SLOT(object,install(\"covar\"))));\n\n  // set up the covariate table\n  covariate_table = make_covariate_table(GET_SLOT(object,install(\"covar\")),&ncovars);\n  PROTECT(cov = NEW_NUMERIC(ncovars));\n\n  // extract user-defined function\n  PROTECT(pompfun = GET_SLOT(skel,install(\"skel.fn\")));\n  PROTECT(fn = pomp_fun_handler(pompfun,gnsi,&mode,Snames,Pnames,NA_STRING,Cnames));\n\n  // extract 'userdata' as pairlist\n  PROTECT(args = GET_SLOT(object,install(\"userdata\")));\n\n  // create array to store results\n  PROTECT(X = ret_array(nvars,nreps,ntimes,Snames,repnames));\n\n  // get names and indices of accumulator variables\n  PROTECT(accumvars = GET_SLOT(object,install(\"accumvars\")));\n  nzeros = LENGTH(accumvars);\n\n  int nprotect = 15;\n\n  if (nzeros > 0) {\n    zidx = INTEGER(PROTECT(matchnames(Snames,accumvars,\"state variables\"))); nprotect++;\n  }\n\n  // set up the computations\n  switch (mode) {\n\n  case Rfun: {\n\n    PROTECT(args = add_skel_args(args,Snames,Pnames,Cnames)); nprotect++;\n\n    iterate_skeleton_R(REAL(X),t,deltat,REAL(times),REAL(x0),REAL(params),\n                       fn,args,Snames,nvars,npars,ncovars,ntimes,nrepp,nreps,nzeros,\n                       &covariate_table,zidx,REAL(cov));\n\n  }\n\n    break;\n\n  case native: case regNative: {\n    int *sidx, *pidx, *cidx;\n    pomp_skeleton *ff;\n\n    *((void **) (&ff)) = R_ExternalPtrAddr(fn);\n\n    // construct state, parameter, covariate indices\n    sidx = INTEGER(GET_SLOT(pompfun,install(\"stateindex\")));\n    pidx = INTEGER(GET_SLOT(pompfun,install(\"paramindex\")));\n    cidx = INTEGER(GET_SLOT(pompfun,install(\"covarindex\")));\n\n    iterate_skeleton_native(REAL(X),t,deltat,REAL(times),REAL(x0),REAL(params),\n                            nvars,npars,ncovars,ntimes,nrepp,nreps,nzeros,sidx,pidx,cidx,\n                            &covariate_table,zidx,ff,args,REAL(cov));\n\n  }\n\n    break;\n\n  default: // #nocov\n\n    break; // #nocov\n\n  }\n\n  UNPROTECT(nprotect);\n  return X;\n}\n\nstatic struct {\n  struct {\n    pompfunmode mode;\n    SEXP object;\n    SEXP params;\n    SEXP cov;\n    lookup_table_t covar_table;\n    int nvars;\n    int npars;\n    int ncovars;\n    int nreps;\n  } common;\n  union {\n    struct {\n      SEXP fn;\n      SEXP args;\n      SEXP Snames;\n    } R_fun;\n    struct {\n      SEXP args;\n      SEXP sindex;\n      SEXP pindex;\n      SEXP cindex;\n      pomp_skeleton *fun;\n    } native_code;\n  } shared;\n} _pomp_vf_eval_block;\n\n#define COMMON(X) (_pomp_vf_eval_block.common.X)\n#define RFUN(X)   (_pomp_vf_eval_block.shared.R_fun.X)\n#define NAT(X)    (_pomp_vf_eval_block.shared.native_code.X)\n\nSEXP pomp_desolve_setup (SEXP object, SEXP x0, SEXP params, SEXP gnsi) {\n\n  pompfunmode mode = undef;\n  SEXP fn, args;\n  SEXP Snames, Pnames, Cnames;\n  SEXP pompfun, ob;\n  int *dim;\n  int nvars, npars, nreps, ncovars;\n\n  // extract user-defined skeleton function\n  PROTECT(ob = GET_SLOT(object,install(\"skeleton\")));\n  PROTECT(pompfun = GET_SLOT(ob,install(\"skel.fn\")));\n  // extract 'userdata' as pairlist\n  PROTECT(args = GET_SLOT(object,install(\"userdata\")));\n\n  COMMON(object) = object;\n  COMMON(params) = params;\n  if (!isNull(COMMON(object))) R_ReleaseObject(COMMON(object));\n  if (!isNull(COMMON(params))) R_ReleaseObject(COMMON(params));\n  R_PreserveObject(COMMON(object));\n  R_PreserveObject(COMMON(params));\n\n  dim = INTEGER(GET_DIM(x0));\n  nvars = dim[0];\n  COMMON(nvars) = nvars;\n\n  dim = INTEGER(GET_DIM(params));\n  npars = dim[0]; nreps = dim[1];\n  COMMON(npars) = npars;\n  COMMON(nreps) = nreps;\n\n  // set up the covariate table\n  COMMON(covar_table) = make_covariate_table(GET_SLOT(object,install(\"covar\")),&ncovars);\n  COMMON(ncovars) = ncovars;\n  PROTECT(COMMON(cov) = NEW_NUMERIC(ncovars));\n  R_PreserveObject(COMMON(cov));\n\n  PROTECT(Snames = GET_ROWNAMES(GET_DIMNAMES(x0)));\n  PROTECT(Pnames = GET_ROWNAMES(GET_DIMNAMES(params)));\n  PROTECT(Cnames = get_covariate_names(GET_SLOT(object,install(\"covar\"))));\n\n  PROTECT(fn = pomp_fun_handler(pompfun,gnsi,&mode,Snames,Pnames,NA_STRING,Cnames));\n\n  COMMON(mode) = mode;\n\n  int nprotect = 8;\n\n  switch (COMMON(mode)) {\n\n  case Rfun: {\n\n    PROTECT(RFUN(fn) = fn);\n    PROTECT(RFUN(args) = add_skel_args(args,Snames,Pnames,Cnames));\n    PROTECT(RFUN(Snames) = Snames);\n    nprotect += 3;\n\n    if (!isNull(RFUN(fn))) R_ReleaseObject(RFUN(fn));\n    if (!isNull(RFUN(args))) R_ReleaseObject(RFUN(args));\n    if (!isNull(RFUN(Snames))) R_ReleaseObject(RFUN(Snames));\n\n    R_PreserveObject(RFUN(fn));\n    R_PreserveObject(RFUN(args));\n    R_PreserveObject(RFUN(Snames));\n\n  }\n\n    break;\n\n  case native: case regNative: {\n\n    NAT(args) = args;\n\n    PROTECT(NAT(sindex) = GET_SLOT(pompfun,install(\"stateindex\")));\n    PROTECT(NAT(pindex) = GET_SLOT(pompfun,install(\"paramindex\")));\n    PROTECT(NAT(cindex) = GET_SLOT(pompfun,install(\"covarindex\")));\n    nprotect += 3;\n\n    *((void **) (&(NAT(fun)))) = R_ExternalPtrAddr(fn);\n\n    if (!isNull(NAT(args))) R_ReleaseObject(NAT(args));\n    if (!isNull(NAT(sindex))) R_ReleaseObject(NAT(sindex));\n    if (!isNull(NAT(pindex))) R_ReleaseObject(NAT(pindex));\n    if (!isNull(NAT(cindex))) R_ReleaseObject(NAT(cindex));\n\n    R_PreserveObject(NAT(args));\n    R_PreserveObject(NAT(sindex));\n    R_PreserveObject(NAT(pindex));\n    R_PreserveObject(NAT(cindex));\n\n  }\n\n    break;\n\n  default: // #nocov\n\n    err(\"in 'pomp_desolve_setup': unrecognized 'mode'\"); // # nocov\n\n  }\n\n  UNPROTECT(nprotect);\n\n  return R_NilValue;\n}\n\nvoid pomp_vf_eval (int *neq, double *t, double *y, double *ydot, double *yout, int *ip)\n{\n  switch (COMMON(mode)) {\n\n  case Rfun:                    // R function\n\n    eval_skeleton_R(ydot,t,y,REAL(COMMON(params)),\n                    RFUN(fn),RFUN(args),RFUN(Snames),\n                    COMMON(nvars),COMMON(npars),COMMON(ncovars),1,\n                    COMMON(nreps),COMMON(nreps),COMMON(nreps),\n                    &COMMON(covar_table),REAL(COMMON(cov)));\n\n    break;\n\n  case native: case regNative:          // native code\n    eval_skeleton_native(ydot,t,y,REAL(COMMON(params)),\n                         COMMON(nvars),COMMON(npars),COMMON(ncovars),1,\n                         COMMON(nreps),COMMON(nreps),COMMON(nreps),\n                         INTEGER(NAT(sindex)),INTEGER(NAT(pindex)),INTEGER(NAT(cindex)),\n                         &COMMON(covar_table),NAT(fun),NAT(args),REAL(COMMON(cov)));\n\n    break;\n\n  default: // #nocov\n\n    err(\"in 'pomp_vf_eval': unrecognized 'mode'\"); // # nocov\n\n    break;\n\n  }\n}\n\nSEXP pomp_desolve_takedown (void) {\n  R_ReleaseObject(COMMON(object));\n  R_ReleaseObject(COMMON(params));\n  R_ReleaseObject(COMMON(cov));\n  COMMON(object) = R_NilValue;\n  COMMON(params) = R_NilValue;\n  COMMON(cov) = R_NilValue;\n  COMMON(nvars) = 0;\n  COMMON(npars) = 0;\n  COMMON(ncovars) = 0;\n  COMMON(nreps) = 0;\n\n  switch (COMMON(mode)) {\n\n  case Rfun: {\n\n    R_ReleaseObject(RFUN(fn));\n    R_ReleaseObject(RFUN(args));\n    R_ReleaseObject(RFUN(Snames));\n    RFUN(fn) = R_NilValue;\n    RFUN(args) = R_NilValue;\n    RFUN(Snames) = R_NilValue;\n\n  }\n\n    break;\n\n  case native: case regNative: {\n\n    NAT(fun) = 0;\n    R_ReleaseObject(NAT(args));\n    R_ReleaseObject(NAT(sindex));\n    R_ReleaseObject(NAT(pindex));\n    R_ReleaseObject(NAT(cindex));\n    NAT(args) = R_NilValue;\n    NAT(sindex) = R_NilValue;\n    NAT(pindex) = R_NilValue;\n    NAT(cindex) = R_NilValue;\n\n  }\n\n    break;\n\n  default: // #nocov\n\n    err(\"in 'pomp_desolve_takedown': unrecognized 'mode'\"); // # nocov\n\n    break;\n\n  }\n\n  COMMON(mode) = undef;\n\n  return R_NilValue;\n}\n\n#undef COMMON\n#undef RFUN\n#undef NAT\n"
  },
  {
    "path": "src/transformations.c",
    "content": "// -*- C++ -*-\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n#include \"internal.h\"\n\nSEXP LogitTransform(SEXP P);\nSEXP ExpitTransform(SEXP X);\nSEXP LogBarycentricTransform(SEXP X);\nSEXP InverseLogBarycentricTransform(SEXP Y);\n\nSEXP LogitTransform (SEXP P) {\n  double *p;\n  int k, n;\n  PROTECT(P = duplicate(AS_NUMERIC(P)));\n  p = REAL(P);\n  n = LENGTH(P);\n  for (k = 0; k < n; k++, p++)\n    *p = logit(*p);\n  UNPROTECT(1);\n  return P;\n}\n\nSEXP ExpitTransform (SEXP X) {\n  double *x;\n  int k, n;\n  PROTECT(X = duplicate(AS_NUMERIC(X)));\n  x = REAL(X);\n  n = LENGTH(X);\n  for (k = 0; k < n; k++, x++)\n    *x = 1.0/(1.0+exp(-(*x)));\n  UNPROTECT(1);\n  return X;\n}\n\nSEXP LogBarycentricTransform (SEXP X) {\n  SEXP Y;\n  PROTECT(X = AS_NUMERIC(X));\n  PROTECT(Y = NEW_NUMERIC(LENGTH(X)));\n  to_log_barycentric(REAL(Y),REAL(X),LENGTH(X));\n  UNPROTECT(2);\n  return Y;\n}\n\nSEXP InverseLogBarycentricTransform (SEXP Y) {\n  SEXP X;\n  PROTECT(Y = AS_NUMERIC(Y));\n  PROTECT(X = NEW_NUMERIC(LENGTH(Y)));\n  from_log_barycentric(REAL(X),REAL(Y),LENGTH(Y));\n  UNPROTECT(2);\n  return X;\n}\n"
  },
  {
    "path": "src/userdata.c",
    "content": "// dear emacs, please treat this as -*- C++ -*-\n\n#include \"internal.h\"\n\nstatic SEXP __pomp_ptr_userdata;\n#define USERDATA  (__pomp_ptr_userdata)\n\nSEXP set_pomp_userdata (SEXP userdata) {\n  USERDATA = userdata;\n  return R_NilValue;\n}\n\nconst SEXP get_userdata (const char *name) {\n  SEXP elt = getListElement(USERDATA,name);\n  if (isNull(elt)) err(\"no user-data element '%s' is found.\",name);\n  return elt;\n}\n\nconst int *get_userdata_int (const char *name) {\n  SEXP elt = getListElement(USERDATA,name);\n  if (isNull(elt)) err(\"no user-data element '%s' is found.\",name);\n  if (!isInteger(elt)) err(\"user-data element '%s' is not an integer.\",name);\n  return INTEGER(elt);\n}\n\nconst double *get_userdata_double (const char *name) {\n  SEXP elt = getListElement(USERDATA,name);\n  if (isNull(elt)) err(\"no user-data element '%s' is found.\",name);\n  if (!isReal(elt)) err(\"user-data element '%s' is not a numeric vector.\",name);\n  return REAL(elt);\n}\n"
  },
  {
    "path": "src/vmeasure.c",
    "content": "// dear emacs, please treat this as -*- C++ -*-\n\n#include <R.h>\n#include <Rmath.h>\n#include <Rdefines.h>\n\n\n#include \"internal.h\"\n\nstatic R_INLINE SEXP add_args (SEXP args, SEXP Snames, SEXP Pnames, SEXP Cnames)\n{\n\n  SEXP var;\n  int v;\n\n  PROTECT(args = VectorToPairList(args));\n\n  // we construct the call from end to beginning\n  // covariates, parameter, states, then time\n\n  // Covariates\n  for (v = LENGTH(Cnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Cnames,v)));\n  }\n\n  // Parameters\n  for (v = LENGTH(Pnames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Pnames,v)));\n  }\n\n  // Latent state variables\n  for (v = LENGTH(Snames)-1; v >= 0; v--) {\n    var = NEW_NUMERIC(1);\n    args = LCONS(var,args);\n    UNPROTECT(1);\n    PROTECT(args);\n    SET_TAG(args,installChar(STRING_ELT(Snames,v)));\n  }\n\n  // Time\n  var = NEW_NUMERIC(1);\n  args = LCONS(var,args);\n  UNPROTECT(1);\n  PROTECT(args);\n  SET_TAG(args,install(\"t\"));\n\n  UNPROTECT(1);\n  return args;\n\n}\n\nstatic R_INLINE SEXP eval_call (\n                                SEXP fn, SEXP args,\n                                double *t,\n                                double *x, int nvar,\n                                double *p, int npar,\n                                double *c, int ncov)\n{\n\n  SEXP var = args, ans, ob;\n  int v;\n\n  *(REAL(CAR(var))) = *t; var = CDR(var);\n  for (v = 0; v < nvar; v++, x++, var=CDR(var)) *(REAL(CAR(var))) = *x;\n  for (v = 0; v < npar; v++, p++, var=CDR(var)) *(REAL(CAR(var))) = *p;\n  for (v = 0; v < ncov; v++, c++, var=CDR(var)) *(REAL(CAR(var))) = *c;\n\n  PROTECT(ob = LCONS(fn,args));\n  PROTECT(ans = eval(ob,R_ClosureEnv(fn)));\n\n  UNPROTECT(2);\n  return ans;\n\n}\n\nstatic R_INLINE SEXP ret_array (int n, int nreps, int ntimes, SEXP names) {\n  int dim[4] = {n, n, nreps, ntimes};\n  const char *dimnm[4] = {\"var1\", \"var2\", \".id\", \"time\"};\n  SEXP Y;\n\n  PROTECT(Y = makearray(4,dim));\n  setrownames(Y,names,4);\n  setcolnames(Y,names);\n  fixdimnames(Y,dimnm,4);\n\n  UNPROTECT(1);\n  return Y;\n\n}\n\nSEXP do_vmeasure (SEXP object, SEXP x, SEXP times, SEXP params, SEXP gnsi)\n{\n  pompfunmode mode = undef;\n  int ntimes, nvars, npars, ncovars, nreps, nrepsx, nrepsp;\n  int nobs = 0, nans = 0;\n  SEXP Snames, Pnames, Cnames, Onames = R_NilValue;\n  SEXP fn, args;\n  SEXP pompfun;\n  SEXP Y = R_NilValue;\n  int *dim;\n  lookup_table_t covariate_table;\n  SEXP cvec;\n  double *cov;\n\n  PROTECT(times = AS_NUMERIC(times));\n  ntimes = length(times);\n  if (ntimes < 1)\n    err(\"length('times') = 0, no work to do.\");\n\n  PROTECT(x = as_state_array(x));\n  dim = INTEGER(GET_DIM(x));\n  nvars = dim[0]; nrepsx = dim[1];\n\n  if (ntimes != dim[2])\n    err(\"length of 'times' and 3rd dimension of 'x' do not agree.\");\n\n  PROTECT(params = as_matrix(params));\n  dim = INTEGER(GET_DIM(params));\n  npars = dim[0]; nrepsp = dim[1];\n\n  nreps = (nrepsp > nrepsx) ? nrepsp : nrepsx;\n\n  if ((nreps % nrepsp != 0) || (nreps % nrepsx != 0))\n    err(\"larger number of replicates is not a multiple of smaller.\");\n\n  PROTECT(pompfun = GET_SLOT(object,install(\"vmeasure\")));\n\n  PROTECT(Snames = GET_ROWNAMES(GET_DIMNAMES(x)));\n  PROTECT(Pnames = GET_ROWNAMES(GET_DIMNAMES(params)));\n  PROTECT(Cnames = get_covariate_names(GET_SLOT(object,install(\"covar\"))));\n  PROTECT(Onames = GET_SLOT(pompfun,install(\"obsnames\")));\n\n  // set up the covariate table\n  covariate_table = make_covariate_table(GET_SLOT(object,install(\"covar\")),&ncovars);\n  PROTECT(cvec = NEW_NUMERIC(ncovars));\n  cov = REAL(cvec);\n\n  // extract the user-defined function\n  PROTECT(fn = pomp_fun_handler(pompfun,gnsi,&mode,Snames,Pnames,Onames,Cnames));\n\n  // extract 'userdata' as pairlist\n  PROTECT(args = GET_SLOT(object,install(\"userdata\")));\n\n  int nprotect = 11;\n  int first = 1;\n\n  // first do setup\n  switch (mode) {\n\n  case Rfun: {\n    double *ys, *yt = 0;\n    double *time = REAL(times), *xs = REAL(x), *ps = REAL(params);\n    SEXP ans;\n    int j, k;\n\n    PROTECT(args = add_args(args,Snames,Pnames,Cnames)); nprotect++;\n\n    for (k = 0; k < ntimes; k++, time++) { // loop over times\n\n      R_CheckUserInterrupt();   // check for user interrupt\n\n      table_lookup(&covariate_table,*time,cov); // interpolate the covariates\n\n      for (j = 0; j < nreps; j++) { // loop over replicates\n\n        if (first) {\n\n          PROTECT(\n                  ans = eval_call(\n                                  fn,args,\n                                  time,\n                                  xs+nvars*((j%nrepsx)+nrepsx*k),nvars,\n                                  ps+npars*(j%nrepsp),npars,\n                                  cov,ncovars\n                                  )\n                  );\n\n          nans = LENGTH(ans);\n\n          nobs = (int) sqrt(nans);\n          if (nans != nobs*nobs)\n            err(\"'vmeasure' must return a symmetric square matrix.\");\n\n          PROTECT(Onames = GET_ROWNAMES(GET_DIMNAMES(ans)));\n          if (invalid_names(Onames))\n            err(\"'vmeasure' must return a matrix with row-names.\");\n\n          PROTECT(Y = ret_array(nobs,nreps,ntimes,Onames));\n\n          nprotect += 3;\n\n          yt = REAL(Y);\n          ys = REAL(AS_NUMERIC(ans));\n\n          memcpy(yt,ys,nans*sizeof(double));\n          yt += nans;\n\n          first = 0;\n\n        } else {\n\n          PROTECT(\n                  ans = eval_call(\n                                  fn,args,\n                                  time,\n                                  xs+nvars*((j%nrepsx)+nrepsx*k),nvars,\n                                  ps+npars*(j%nrepsp),npars,\n                                  cov,ncovars\n                                  )\n                  );\n\n          if (LENGTH(ans) != nans)\n            err(\"'vmeasure' returns variable-length results.\");\n\n          ys = REAL(AS_NUMERIC(ans));\n\n          memcpy(yt,ys,nans*sizeof(double));\n          yt += nans;\n\n          UNPROTECT(1);\n\n        }\n\n      }\n    }\n\n  }\n\n    break;\n\n  case native: case regNative: {\n    double *yt = 0, *xp, *pp;\n    double *time = REAL(times), *xs = REAL(x), *ps = REAL(params);\n    SEXP vmatindex;\n    int *oidx, *sidx, *pidx, *cidx, *vmidx;\n    pomp_vmeasure *ff = NULL;\n    int j, k;\n\n    nobs = LENGTH(Onames);\n    nans = nobs*nobs;\n    // extract observable, state, parameter covariate indices\n    sidx = INTEGER(GET_SLOT(pompfun,install(\"stateindex\")));\n    pidx = INTEGER(GET_SLOT(pompfun,install(\"paramindex\")));\n    oidx = INTEGER(GET_SLOT(pompfun,install(\"obsindex\")));\n    cidx = INTEGER(GET_SLOT(pompfun,install(\"covarindex\")));\n\n    PROTECT(vmatindex = NEW_INTEGER(nans)); nprotect++;\n    vmidx = INTEGER(vmatindex);\n    for (k = 0; k < nobs; k++) {\n      for (j = 0; j < nobs; j++) {\n        vmidx[j+nobs*k] = oidx[j]+nobs*oidx[k];\n      }\n    }\n\n    // address of native routine\n    *((void **) (&ff)) = R_ExternalPtrAddr(fn);\n\n    PROTECT(Y = ret_array(nobs,nreps,ntimes,Onames)); nprotect++;\n    yt = REAL(Y);\n\n    for (k = 0; k < ntimes; k++, time++) { // loop over times\n\n      R_CheckUserInterrupt();   // check for user interrupt\n\n      // interpolate the covar functions for the covariates\n      table_lookup(&covariate_table,*time,cov);\n\n      for (j = 0; j < nreps; j++, yt += nans) { // loop over replicates\n\n        xp = &xs[nvars*((j%nrepsx)+nrepsx*k)];\n        pp = &ps[npars*(j%nrepsp)];\n\n        (*ff)(yt,xp,pp,vmidx,sidx,pidx,cidx,cov,*time);\n\n      }\n    }\n\n  }\n\n    break;\n\n  default: {\n    nobs = LENGTH(Onames);\n    int dim[4] = {nobs, nobs, nreps, ntimes};\n    const char *dimnm[4] = {\"var1\",\"var2\",\".id\",\"time\"};\n    double *yt = 0;\n    int i, n = nobs*nobs*nreps*ntimes;\n\n    PROTECT(Y = makearray(4,dim)); nprotect++;\n    setrownames(Y,Onames,4);\n    setcolnames(Y,Onames);\n    fixdimnames(Y,dimnm,4);\n\n    for (i = 0, yt = REAL(Y); i < n; i++, yt++) *yt = R_NaReal;\n\n    warn(\"'vmeasure' unspecified: NAs generated.\");\n  }\n\n  }\n\n  UNPROTECT(nprotect);\n  return Y;\n}\n"
  },
  {
    "path": "src/wpfilter.c",
    "content": "// -*- C++ -*-\n\n#include <Rdefines.h>\n#include \"internal.h\"\n\n// examines weights for filtering failure.\n// computes conditional log likelihood and effective sample size.\n// returns a named list.\n// AT PRESENT, NO PARAMETER RESAMPLING IS PERFORMED.\nSEXP wpfilter (SEXP X, SEXP Params, SEXP Weights, SEXP W, SEXP Trigger, SEXP Target, SEXP Np)\n{\n\n  SEXP dimX, dimP, Xnames, Pnames;\n  int nvars, nreps, np;\n  // REVISIT THIS IF PARAMETER RESAMPLING IS IMPLEMENTED\n  //  int npars;\n  //  int do_pr = 0;  // do parameter resampling?  at the moment, we do not\n  int *dim, k;\n  const char *dimnm[] = {\"name\",\".id\"};\n\n  PROTECT(dimX = GET_DIM(X));\n  dim = INTEGER(dimX);\n  nvars = dim[0]; nreps = dim[1];\n  PROTECT(Xnames = GET_ROWNAMES(GET_DIMNAMES(X)));\n\n  PROTECT(Params = as_matrix(Params));\n  PROTECT(dimP = GET_DIM(Params));\n  dim = INTEGER(dimP);\n  //  npars = dim[0];\n  if (dim[1] > 1 && nreps != dim[1])                     // #nocov\n    err(\"ncol('params') does not match ncol('states')\"); // #nocov\n  PROTECT(Pnames = GET_ROWNAMES(GET_DIMNAMES(Params)));\n\n  np = *INTEGER(AS_INTEGER(Np));\n  // REVISIT THIS IF PARAMETER RESAMPLING IS IMPLEMENTED\n  //  do_pr = (dim[1] > 1);           // resample parameters as well as states\n\n  PROTECT(Weights = duplicate(AS_NUMERIC(Weights)));\n  PROTECT(W = duplicate(AS_NUMERIC(W)));\n\n  int nprotect = 7;\n\n  double trigger, target;\n  trigger = *REAL(AS_NUMERIC(Trigger));\n  target = *REAL(AS_NUMERIC(Target));\n\n  // add W to Weights. check weights for NAN or +Inf. find max of weights.\n  long double maxlogw = R_NegInf, oldw = 0;\n  double *xW = REAL(Weights);\n  double *xw = REAL(W);\n  for (k = 0; k < nreps; k++, xw++, xW++) {\n\n    oldw += exp(*xW);\n    *xW += *xw;\n\n    if (ISNAN(*xW) || *xW == R_PosInf) { // check the weights\n      SEXP rv;\n      PROTECT(rv = ScalarInteger(k+1)); nprotect++;\n      UNPROTECT(nprotect);\n      return rv;\n    }\n\n    if (maxlogw < *xW) maxlogw = *xW;\n\n  }\n\n  // set up return list\n  SEXP retval, retvalnames, newdim;\n\n  PROTECT(retval = NEW_LIST(5));\n  PROTECT(retvalnames = NEW_CHARACTER(5));\n  PROTECT(newdim = NEW_INTEGER(2));\n  nprotect += 3;\n\n  dim = INTEGER(newdim);\n  dim[0] = nvars; dim[1] = nreps;\n  SET_DIM(X,newdim);\n  setrownames(X,Xnames,2);\n  fixdimnames(X,dimnm,2);\n\n  SET_STRING_ELT(retvalnames,0,mkChar(\"states\"));\n  SET_STRING_ELT(retvalnames,1,mkChar(\"params\"));\n  SET_STRING_ELT(retvalnames,2,mkChar(\"weights\"));\n  SET_STRING_ELT(retvalnames,3,mkChar(\"ess\"));\n  SET_STRING_ELT(retvalnames,4,mkChar(\"loglik\"));\n  SET_NAMES(retval,retvalnames);\n\n  SEXP ess, loglik;\n  PROTECT(ess = NEW_NUMERIC(1));    // effective sample size\n  PROTECT(loglik = NEW_NUMERIC(1)); // conditional log likelihood\n  nprotect += 2;\n\n  if (maxlogw == R_NegInf) {    // all particles have zero likelihood\n    *REAL(ess) = 0;\n    *REAL(loglik) = R_NegInf;\n  } else {\n    // compute sum and sum of squares\n    long double w = 0, ws = 0;\n    xw = REAL(W);\n    xW = REAL(Weights);\n    for (k = 0; k < nreps; k++, xw++, xW++) {\n      *xW -= maxlogw;\n      *xw = exp(*xW);\n      if (*xw != 0) {\n        w += *xw;\n        ws += (*xw)*(*xw);\n      }\n    }\n    *(REAL(ess)) = w*w/ws;\n    *(REAL(loglik)) = maxlogw + log(w) - log(oldw);\n  }\n\n  SET_ELEMENT(retval,3,ess);\n  SET_ELEMENT(retval,4,loglik);\n\n  if (maxlogw == R_NegInf || (*REAL(ess) >= nreps*trigger && np == nreps)) { // do not resample\n\n    SET_ELEMENT(retval,0,X);\n    SET_ELEMENT(retval,1,Params);\n    SET_ELEMENT(retval,2,Weights);\n\n  } else {                      // no resampling\n\n    // create storage for new states\n    SEXP newstates = R_NilValue;\n    double *ss = 0, *st = 0;\n    {\n      int xdim[] = {nvars, np};\n      PROTECT(newstates = makearray(2,xdim)); nprotect++;\n      setrownames(newstates,Xnames,2);\n      fixdimnames(newstates,dimnm,2);\n      ss = REAL(X);\n      st = REAL(newstates);\n    }\n    SET_ELEMENT(retval,0,newstates);\n\n    // REVISIT THIS IF PARAMETER RESAMPLING IS IMPLEMENTED\n    // create storage for new parameters\n    //    SEXP newparams = R_NilValue;\n    //    double *ps = 0, *pt = 0;\n    // if (do_pr) {\n    //   int xdim[] = {npars, np};\n    //   PROTECT(newparams = makearray(2,xdim)); nprotect++;\n    //   setrownames(newparams,Pnames,2);\n    //   fixdimnames(newparams,dimnm,2);\n    //   ps = REAL(Params);\n    //   pt = REAL(newparams);\n    //   SET_ELEMENT(retval,1,newparams);\n    // } else {\n    SET_ELEMENT(retval,1,Params);\n    // }\n\n    // create storage for new weights\n    SEXP newweights = R_NilValue;\n    double *ws = 0, *wt = 0;\n    {\n      PROTECT(newweights = NEW_NUMERIC(np)); nprotect++;\n      ws = REAL(Weights);\n      wt = REAL(newweights);\n    }\n    SET_ELEMENT(retval,2,newweights);\n\n    // compute target resampling weights\n    for (k = 0, xw = REAL(W), xW = REAL(Weights); k < nreps; k++, xw++, xW++) {\n      *xw = *xW;\n      *xW *= target;\n      *xw = exp(*xw - *xW);\n    }\n\n    // do resampling\n    {\n      int sample[np];\n      GetRNGstate();\n      nosort_resamp(nreps,REAL(W),np,sample,0);\n      PutRNGstate();\n\n      for (k = 0; k < np; k++) { // copy the particles\n        int sp = sample[k], j;\n        double *xx;\n        //      double *xp;\n        for (j = 0, xx = ss+nvars*sp; j < nvars; j++, st++, xx++)\n          *st = *xx;\n        // REVISIT THIS IF PARAMETER RESAMPLING IS IMPLEMENTED\n        // if (do_pr) {\n        //   for (j = 0, xp = ps+npars*sp; j < npars; j++, pt++, xp++)\n        //     *pt = *xp;\n        // }\n        wt[k] = ws[sp];\n      }\n    }\n  }\n\n  UNPROTECT(nprotect);\n  return(retval);\n}\n"
  },
  {
    "path": "tests/Makefile",
    "content": "REXE = R\n\nSAVED = $(wildcard *.Rout.save *.Rout)\n\ndefault: $(SAVED) clean\n\n%.Rout.save: %.R\n\t$(REXE) < $*.R > $*.Rout.save 2>&1\n\n%.Rout: %.R\n\t$(REXE) < $*.R > $*.Rout 2>&1\n\nclean:\n\t$(RM) *.c *.o *.so \n\nfresh: clean\n\t$(RM) *.png\n"
  },
  {
    "path": "tests/R_v_C.R",
    "content": "options(digits=3)\npng(filename=\"R_v_C-%02d.png\",res=100)\n\n## ----packages------------------------------------------------------------\nlibrary(pomp)\nlibrary(tidyr)\nlibrary(ggplot2)\n\n## ----seed,echo=FALSE-----------------------------------------------------\nset.seed(56300069)\n\n## ----R1------------------------------------------------------------------\nsimulate(times=1:100,t0=0,\n  params=c(K=1,r=0.1,sigma=0.1,tau=0.1,X.0=1),\n  rprocess=discrete_time(\n    step.fun=function (X,r,K,sigma,...,delta.t) {\n      eps <- exp(rnorm(n=1,mean=0,sd=sigma))\n      S <- exp(-r*delta.t)\n      c(X=K^(1-S)*X^S*eps)\n    },\n    delta.t=1\n  ),\n  rmeasure=function (X, tau, ...) {\n    c(Y=rlnorm(n=1,meanlog=log(X),sdlog=tau))\n  },\n  dmeasure=function (tau, X, Y, ..., log) {\n    dlnorm(x=Y,meanlog=log(X),sdlog=tau,log=log)\n  },\n  partrans=parameter_trans(\n    toEst=function(r,K,sigma,tau,X.0,...){\n      log(c(r=r,K=K,sigma=sigma,tau=tau,X.0=X.0))\n    },\n    fromEst=function(r,K,sigma,tau,X.0,...){\n      exp(c(r=r,K=K,sigma=sigma,tau=tau,X.0=X.0))\n    }\n  )\n) -> gompertz\n\n## ----R2------------------------------------------------------------------\ngompertz |>\n  as.data.frame() |>\n  pivot_longer(cols=-time) |>\n  ggplot(aes(x=time,y=value,color=name))+\n  geom_line()+\n  labs(y=\"X, Y\")+\n  theme_bw()\n\n## ----C1------------------------------------------------------------------\nsimulate(times=0:100,t0=0,\n  params=c(K=1,r=0.1,sigma=0.1,tau=0.1,X.0=1),\n  dmeasure=Csnippet(\"\n    lik = dlnorm(Y,log(X),tau,give_log);\"\n  ),\n  rmeasure=Csnippet(\"\n    Y = rlnorm(log(X),tau);\"\n  ),\n  rprocess=discrete_time(\n    step.fun=Csnippet(\"\n    double S = exp(-r*dt);\n    double logeps = (sigma > 0.0) ? rnorm(0,sigma) : 0.0;\n    X = pow(K,(1-S))*pow(X,S)*exp(logeps);\"\n    ),\n    delta.t=1\n  ),\n  partrans=parameter_trans(log=c(\"r\",\"K\",\"sigma\",\"tau\",\"X.0\")),\n  paramnames=c(\"r\",\"K\",\"sigma\",\"X.0\",\"tau\"),\n  obsnames=\"Y\",\n  statenames=\"X\"\n) -> Gompertz\n\n## ----params--------------------------------------------------------------\np <- parmat(coef(Gompertz),4)\np[\"X.0\",] <- c(0.5,0.9,1.1,1.5)\n\n## ----sim1----------------------------------------------------------------\nsimulate(Gompertz,params=p,format=\"data.frame\") |>\n  ggplot(aes(x=time,y=X,group=.id,color=.id))+\n  geom_line()+\n  guides(color=\"none\")+\n  theme_bw()+\n  labs(title=\"Gompertz model\",subtitle=\"stochastic simulations\")\n\n## ----pf1-----------------------------------------------------------------\npf <- replicate(n=10,pfilter(Gompertz,Np=500))\n\nlogmeanexp(sapply(pf,logLik),se=TRUE)\n\n## ----comparison----------------------------------------------------------\nsystem.time(simulate(gompertz,nsim=10000,format=\"arrays\"))\nsystem.time(simulate(Gompertz,nsim=10000,format=\"arrays\"))\nsystem.time(pfilter(gompertz,Np=1000))\nsystem.time(pfilter(Gompertz,Np=1000))\n\ndev.off()\n"
  },
  {
    "path": "tests/R_v_C.Rout",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"R_v_C-%02d.png\",res=100)\n> \n> ## ----packages------------------------------------------------------------\n> library(pomp)\n> library(tidyr)\n> library(ggplot2)\n> \n> ## ----seed,echo=FALSE-----------------------------------------------------\n> set.seed(56300069)\n> \n> ## ----R1------------------------------------------------------------------\n> simulate(times=1:100,t0=0,\n+   params=c(K=1,r=0.1,sigma=0.1,tau=0.1,X.0=1),\n+   rprocess=discrete_time(\n+     step.fun=function (X,r,K,sigma,...,delta.t) {\n+       eps <- exp(rnorm(n=1,mean=0,sd=sigma))\n+       S <- exp(-r*delta.t)\n+       c(X=K^(1-S)*X^S*eps)\n+     },\n+     delta.t=1\n+   ),\n+   rmeasure=function (X, tau, ...) {\n+     c(Y=rlnorm(n=1,meanlog=log(X),sdlog=tau))\n+   },\n+   dmeasure=function (tau, X, Y, ..., log) {\n+     dlnorm(x=Y,meanlog=log(X),sdlog=tau,log=log)\n+   },\n+   partrans=parameter_trans(\n+     toEst=function(r,K,sigma,tau,X.0,...){\n+       log(c(r=r,K=K,sigma=sigma,tau=tau,X.0=X.0))\n+     },\n+     fromEst=function(r,K,sigma,tau,X.0,...){\n+       exp(c(r=r,K=K,sigma=sigma,tau=tau,X.0=X.0))\n+     }\n+   )\n+ ) -> gompertz\n> \n> ## ----R2------------------------------------------------------------------\n> gompertz |>\n+   as.data.frame() |>\n+   pivot_longer(cols=-time) |>\n+   ggplot(aes(x=time,y=value,color=name))+\n+   geom_line()+\n+   labs(y=\"X, Y\")+\n+   theme_bw()\n> \n> ## ----C1------------------------------------------------------------------\n> simulate(times=0:100,t0=0,\n+   params=c(K=1,r=0.1,sigma=0.1,tau=0.1,X.0=1),\n+   dmeasure=Csnippet(\"\n+     lik = dlnorm(Y,log(X),tau,give_log);\"\n+   ),\n+   rmeasure=Csnippet(\"\n+     Y = rlnorm(log(X),tau);\"\n+   ),\n+   rprocess=discrete_time(\n+     step.fun=Csnippet(\"\n+     double S = exp(-r*dt);\n+     double logeps = (sigma > 0.0) ? rnorm(0,sigma) : 0.0;\n+     X = pow(K,(1-S))*pow(X,S)*exp(logeps);\"\n+     ),\n+     delta.t=1\n+   ),\n+   partrans=parameter_trans(log=c(\"r\",\"K\",\"sigma\",\"tau\",\"X.0\")),\n+   paramnames=c(\"r\",\"K\",\"sigma\",\"X.0\",\"tau\"),\n+   obsnames=\"Y\",\n+   statenames=\"X\"\n+ ) -> Gompertz\n> \n> ## ----params--------------------------------------------------------------\n> p <- parmat(coef(Gompertz),4)\n> p[\"X.0\",] <- c(0.5,0.9,1.1,1.5)\n> \n> ## ----sim1----------------------------------------------------------------\n> simulate(Gompertz,params=p,format=\"data.frame\") |>\n+   ggplot(aes(x=time,y=X,group=.id,color=.id))+\n+   geom_line()+\n+   guides(color=\"none\")+\n+   theme_bw()+\n+   labs(title=\"Gompertz model\",subtitle=\"stochastic simulations\")\n> \n> ## ----pf1-----------------------------------------------------------------\n> pf <- replicate(n=10,pfilter(Gompertz,Np=500))\n> \n> logmeanexp(sapply(pf,logLik),se=TRUE)\n   est     se \n62.814  0.168 \n> \n> ## ----comparison----------------------------------------------------------\n> system.time(simulate(gompertz,nsim=10000,format=\"arrays\"))\n   user  system elapsed \n  2.836   0.005   2.841 \n> system.time(simulate(Gompertz,nsim=10000,format=\"arrays\"))\n   user  system elapsed \n  0.072   0.003   0.075 \n> system.time(pfilter(gompertz,Np=1000))\n   user  system elapsed \n  0.291   0.000   0.292 \n> system.time(pfilter(Gompertz,Np=1000))\n   user  system elapsed \n  0.012   0.000   0.012 \n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/abc.R",
    "content": "### OU2 test of abc for pomp\n\npng(filename=\"abc-%02d.png\",res=100)\n\nlibrary(pomp)\n\nou2() -> ou2\n\nset.seed(2079015564L)\n\nplist <- list(\n  y1.mean=probe_mean(var=\"y1\"),\n  y2.mean=probe_mean(var=\"y2\"),\n  probe_acf(var=\"y1\",lags=c(0,5)),\n  probe_acf(var=\"y2\",lags=c(0,5)),\n  probe_ccf(vars=c(\"y1\",\"y2\"),lags=0)\n)\n\nou2 |> probe(probes=plist,nsim=100) -> pb\n\nsqrt(diag(covmat(pb))) -> scale.dat\n\nou2 |>\n  abc(Nabc=100,probes=plist,scale=scale.dat,epsilon=1.7,\n    proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01)),\n    dprior=function(alpha_1,alpha_2,...,log) {\n      ll <- sum(dnorm(x=c(alpha_1,alpha_2),mean=c(0.6,0),sd=4,log=TRUE))\n      if (log) ll else exp(ll)\n    }) -> abc1\nplot(abc1)\nplot(abc1,scatter=TRUE)\n\ncrossprod(\n  array(data=c(0.1,0.02,0,0.1),dim=c(2,2),\n    dimnames=list(c(\"alpha_1\",\"alpha_2\"),c(\"alpha_1\",\"alpha_2\")))\n) -> sig\n\npb |> abc(Nabc=100,scale=scale.dat,epsilon=2,proposal=mvn_rw(sig)) -> abc2\nabc2 |> abc(Nabc=100) -> abc3\nabc1 |> abc(Nabc=80) |> continue(Nabc=20) -> abc4\n\nplot(c(abc1,abc2,abc3,abc4),y=\"bob\")\nplot(c(abc1,abc2,abc3,abc4),scatter=TRUE)\n\nc(a=c(abc1,abc2),b=abc3) -> abclist\nstopifnot(identical(abclist,c(a1=abc1,c(a2=abc2,b=abc3))))\nstopifnot(all(dim(traces(abc1))==c(101,10)))\nstopifnot(all(dim(traces(abc1,\"alpha_1\"))==c(101,1)))\ninvisible(traces(abc2))\ndim(as.data.frame(abclist))\n  \nc(abc1,abc2) |> traces() -> traces\ntraces |> length()\ntraces |> class()\ntraces |> sapply(dim)\ntry(abclist |> plot(pars=\"alpha_3\",scatter=TRUE))\n\nabc1 |>\n  abc(Nabc=500,dprior=Csnippet(\"\n    lik = dnorm(alpha_1,0.8,1,1)+dnorm(alpha_2,0.2,1,1);\n    lik = (give_log) ? lik : exp(lik);\"\n  ),paramnames=c(\"alpha_1\",\"alpha_2\")) -> abc5\n\nabc1 |> abc(Nabc=50,params=as.list(coef(ou2))) |> plot()\n\nabc4 |> abc(proposal=function(theta,...)theta) |> plot()\n\ntry(abc())\ntry(abc(3))\n\ns5 <- simulate(abc5)\nstopifnot(\n  is(abc5,\"abcd_pomp\"),\n  is(simulate(s5),\"pomp\"),\n  !is(simulate(s5),\"abcd_pomp\")\n)\n\ntry(abc(abc1,Nabc=-5))\nstopifnot(all(dim(traces(abc(abc1,Nabc=0))==c(1,10))))\n\ntry(abc(ou2,Nabc=50,scale=scale.dat[1:2],epsilon=1.7,\n  proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))))\ntry(abc(ou2,Nabc=50,probes=plist,scale=scale.dat[1:2],epsilon=1.7,\n  proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))))\npo <- ou2\ncoef(po) <- NULL\ntry(abc(po,Nabc=100,probes=plist,scale=scale.dat,epsilon=1.7,\n  proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))))\ntry(abc(ou2,params=numeric(0),Nabc=100,probes=plist,scale=scale.dat,\n  epsilon=1.7,proposal=\"mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))\"))\ntry(abc(ou2,params=NULL,Nabc=100,probes=plist,scale=scale.dat,epsilon=1.7,\n  proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))))\ntry(abc(ou2,Nabc=100,probes=plist,scale=scale.dat,epsilon=1.7,\n  proposal=\"mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))\"))\ntry(abc(ou2,Nabc=100,probes=plist,scale=scale.dat,epsilon=1.7,\n  proposal=function(...)stop(\"yikes!\")))\ntry(abc(ou2,Nabc=100,probes=plist,scale=scale.dat,epsilon=1.7,\n  proposal=function(...)3))\ntry(abc(ou2,Nabc=100,probes=plist,scale=scale.dat,epsilon=1.7))\ntry(abc(ou2,Nabc=100,proposal=function(theta,...)theta,probes=\"mary\",\n  scale=scale.dat,epsilon=1.7))\ntry(abc(ou2,Nabc=100,proposal=\"bob\",probes=\"mary\",epsilon=1.7))\ntry(abc(ou2,Nabc=100,probes=plist,epsilon=1.7,\n  proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))))\ntry(abc(ou2,Nabc=100,probes=plist,scale=scale.dat,\n  proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))))\ntry(abc(ou2,Nabc=100,probes=plist,scale=scale.dat,\n  proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01)),\n  epsilon=1,rprocess=NULL))\n\ntry(abc(abc1,Nabc=100,epsilon=NULL,scale=scale.dat))\ntry(abc(ou2,params=c(1,2,3),Nabc=100,probes=plist,scale=scale.dat,epsilon=1.7,\n  proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))))\ntry(abc(ou2,Nabc=100,probes=\"plist[[1]]\",scale=scale.dat[1],epsilon=1.7,\n  proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))))\ntry(abc(ou2,Nabc=100,probes=function(x,y)x+y,scale=scale.dat[1],epsilon=1.7,\n  proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))))\ntry(abc(abc1,dprior=function(log,...)stop(\"ouch!\")))\ntry(abc(abc1,dprior=function(log,...)Inf))\ntry(abc(abc1,probes=function(x)stop(\"piff!\")))\ncount <- 0\ndelayed.failure <- function (x) {count <<- count+1; if (count>2) stop(\"paff!\") else 1}\ntry(abc(abc1,scale=1,probes=delayed.failure))\ntry(abc(abc1,proposal=function(...)stop(\"urp!\")))\ncount <- 0\ndelayed.failure <- function (log,...) {count <<- count+1; if (count>5) stop(\"no sir!\") else 1}\ntry(abc(abc1,dprior=delayed.failure))\ncount <- 0\ndelayed.failure <- function (theta,...) {count <<- count+1; if (count>5) stop(\"'fraid not!\") else theta}\ntry(abc(abc1,proposal=delayed.failure))\n\ncoef(c(abc1,ou2)) -> theta\nstopifnot(dim(theta)==c(10,2),\n  rownames(theta)==c(\"alpha_1\",\"alpha_2\",\"alpha_3\",\"alpha_4\",\n    \"sigma_1\",\"sigma_2\",\"sigma_3\",\"tau\",\"x1_0\",\"x2_0\"),\n  apply(theta[c(\"alpha_3\",\"alpha_4\",\n    \"sigma_1\",\"sigma_2\",\"sigma_3\",\"tau\",\"x1_0\",\"x2_0\"),],1,diff)==0,\n  apply(theta[c(\"alpha_1\",\"alpha_2\"),],1,diff) != 0)\ntry(c(abc1,3))\n\nc(c(abc1,abc2),ou2)\nc(a=c(abc1,abc2),b=abc2)\nc(abc1)\nalist <- c(c(abc1,abc2))\nclass(alist[2])\ntry(alist[[3]])\nalist <- c(a=abc1,b=abc2)\nalist[\"b\"]\nalist[\"c\"]\nalist[[\"b\"]]\nalist[[\"c\"]]\nc(one=abc1,two=abc2,three=abc3)\nprint(c(one=abc1,two=abc2,three=abc3))\n\ncapture.output(abc(ou2,Nabc=100,probes=plist,scale=scale.dat,epsilon=1.7,\n  proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01)),\n  verbose=TRUE) -> abc1) -> out\nstopifnot(\n  length(out)==40,\n  sum(grepl(\"acceptance\",out))==20,\n  sum(grepl(\"ABC iteration\",out))==20\n)\n\ngompertz() -> gompertz\nset.seed(2079015564L)\n\ngompertz |>\n  as.data.frame() |>\n  abc(Nabc=20,times=\"time\",t0=0,\n    scale=1,epsilon=10,\n    probes=list(probe_mean(\"Y\"),probe_median(\"Y\")),\n    partrans=parameter_trans(log=c(\"r\",\"K\")),\n    paramnames=c(\"r\",\"K\"),\n    proposal=mvn_diag_rw(rw.sd=c(r=0.01,K=0.01)),\n    params=coef(gompertz),\n    rinit=function(...)c(X=1),\n    rprocess=discrete_time(function (X, r, K, ...) c(X=r*X*exp(-X/K))),\n    rmeasure=function (Y, X, ...) c(Y = rnorm(n=1,mean=X,sd=2))\n    ) |> plot()\n\ndev.off()\n"
  },
  {
    "path": "tests/abc.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> ### OU2 test of abc for pomp\n> \n> png(filename=\"abc-%02d.png\",res=100)\n> \n> library(pomp)\n> \n> ou2() -> ou2\n> \n> set.seed(2079015564L)\n> \n> plist <- list(\n+   y1.mean=probe_mean(var=\"y1\"),\n+   y2.mean=probe_mean(var=\"y2\"),\n+   probe_acf(var=\"y1\",lags=c(0,5)),\n+   probe_acf(var=\"y2\",lags=c(0,5)),\n+   probe_ccf(vars=c(\"y1\",\"y2\"),lags=0)\n+ )\n> \n> ou2 |> probe(probes=plist,nsim=100) -> pb\n> \n> sqrt(diag(covmat(pb))) -> scale.dat\n> \n> ou2 |>\n+   abc(Nabc=100,probes=plist,scale=scale.dat,epsilon=1.7,\n+     proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01)),\n+     dprior=function(alpha_1,alpha_2,...,log) {\n+       ll <- sum(dnorm(x=c(alpha_1,alpha_2),mean=c(0.6,0),sd=4,log=TRUE))\n+       if (log) ll else exp(ll)\n+     }) -> abc1\n> plot(abc1)\n> plot(abc1,scatter=TRUE)\n> \n> crossprod(\n+   array(data=c(0.1,0.02,0,0.1),dim=c(2,2),\n+     dimnames=list(c(\"alpha_1\",\"alpha_2\"),c(\"alpha_1\",\"alpha_2\")))\n+ ) -> sig\n> \n> pb |> abc(Nabc=100,scale=scale.dat,epsilon=2,proposal=mvn_rw(sig)) -> abc2\n> abc2 |> abc(Nabc=100) -> abc3\n> abc1 |> abc(Nabc=80) |> continue(Nabc=20) -> abc4\n> \n> plot(c(abc1,abc2,abc3,abc4),y=\"bob\")\n> plot(c(abc1,abc2,abc3,abc4),scatter=TRUE)\n> \n> c(a=c(abc1,abc2),b=abc3) -> abclist\n> stopifnot(identical(abclist,c(a1=abc1,c(a2=abc2,b=abc3))))\n> stopifnot(all(dim(traces(abc1))==c(101,10)))\n> stopifnot(all(dim(traces(abc1,\"alpha_1\"))==c(101,1)))\n> invisible(traces(abc2))\n> dim(as.data.frame(abclist))\n[1] 300   6\n>   \n> c(abc1,abc2) |> traces() -> traces\n> traces |> length()\n[1] 2\n> traces |> class()\n[1] \"mcmc.list\"\n> traces |> sapply(dim)\n     [,1] [,2]\n[1,]  101  101\n[2,]   10   10\n> try(abclist |> plot(pars=\"alpha_3\",scatter=TRUE))\nError : in 'plot': can't make a scatterplot with only one variable.\n> \n> abc1 |>\n+   abc(Nabc=500,dprior=Csnippet(\"\n+     lik = dnorm(alpha_1,0.8,1,1)+dnorm(alpha_2,0.2,1,1);\n+     lik = (give_log) ? lik : exp(lik);\"\n+   ),paramnames=c(\"alpha_1\",\"alpha_2\")) -> abc5\n> \n> abc1 |> abc(Nabc=50,params=as.list(coef(ou2))) |> plot()\n> \n> abc4 |> abc(proposal=function(theta,...)theta) |> plot()\n> \n> try(abc())\nError : in 'abc': 'data' is a required argument.\n> try(abc(3))\nError : 'abc' is undefined for 'data' of class 'numeric'.\n> \n> s5 <- simulate(abc5)\n> stopifnot(\n+   is(abc5,\"abcd_pomp\"),\n+   is(simulate(s5),\"pomp\"),\n+   !is(simulate(s5),\"abcd_pomp\")\n+ )\n> \n> try(abc(abc1,Nabc=-5))\nError : in 'abc': 'Nabc' must be a positive integer.\n> stopifnot(all(dim(traces(abc(abc1,Nabc=0))==c(1,10))))\n> \n> try(abc(ou2,Nabc=50,scale=scale.dat[1:2],epsilon=1.7,\n+   proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))))\nError : in 'abc': 'probes' must be specified.\n> try(abc(ou2,Nabc=50,probes=plist,scale=scale.dat[1:2],epsilon=1.7,\n+   proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))))\nError : in 'abc': 'scale' must have either length 1 or length equal to the number of probes (here, 7).\n> po <- ou2\n> coef(po) <- NULL\n> try(abc(po,Nabc=100,probes=plist,scale=scale.dat,epsilon=1.7,\n+   proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))))\nError : in 'abc': 'params' must be a named numeric vector.\n> try(abc(ou2,params=numeric(0),Nabc=100,probes=plist,scale=scale.dat,\n+   epsilon=1.7,proposal=\"mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))\"))\nError : in 'abc': 'params' must be a named numeric vector.\n> try(abc(ou2,params=NULL,Nabc=100,probes=plist,scale=scale.dat,epsilon=1.7,\n+   proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))))\nError : in 'abc': 'params' must be a named numeric vector.\n> try(abc(ou2,Nabc=100,probes=plist,scale=scale.dat,epsilon=1.7,\n+   proposal=\"mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))\"))\nError : in 'abc': 'proposal' must be a function.\n> try(abc(ou2,Nabc=100,probes=plist,scale=scale.dat,epsilon=1.7,\n+   proposal=function(...)stop(\"yikes!\")))\nError : in 'abc': in proposal function: yikes!\n> try(abc(ou2,Nabc=100,probes=plist,scale=scale.dat,epsilon=1.7,\n+   proposal=function(...)3))\nError : in 'abc': 'proposal' must return a named numeric vector.\n> try(abc(ou2,Nabc=100,probes=plist,scale=scale.dat,epsilon=1.7))\nError : in 'abc': 'proposal' must be specified.\n> try(abc(ou2,Nabc=100,proposal=function(theta,...)theta,probes=\"mary\",\n+   scale=scale.dat,epsilon=1.7))\nError : in 'abc': 'probes' must be a function or a list of functions.\n> try(abc(ou2,Nabc=100,proposal=\"bob\",probes=\"mary\",epsilon=1.7))\nError : in 'abc': 'proposal' must be a function.\n> try(abc(ou2,Nabc=100,probes=plist,epsilon=1.7,\n+   proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))))\nError : in 'abc': 'scale' must be specified.\n> try(abc(ou2,Nabc=100,probes=plist,scale=scale.dat,\n+   proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))))\nError : in 'abc': abc match criterion, 'epsilon', must be specified.\n> try(abc(ou2,Nabc=100,probes=plist,scale=scale.dat,\n+   proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01)),\n+   epsilon=1,rprocess=NULL))\nError : in 'abc': 'rprocess', 'rmeasure' are needed basic components.\n> \n> try(abc(abc1,Nabc=100,epsilon=NULL,scale=scale.dat))\nError : in 'abc': abc match criterion, 'epsilon', must be specified.\n> try(abc(ou2,params=c(1,2,3),Nabc=100,probes=plist,scale=scale.dat,epsilon=1.7,\n+   proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))))\nError : in 'abc': 'params' must be a named numeric vector.\n> try(abc(ou2,Nabc=100,probes=\"plist[[1]]\",scale=scale.dat[1],epsilon=1.7,\n+   proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))))\nError : in 'abc': 'probes' must be a function or a list of functions.\n> try(abc(ou2,Nabc=100,probes=function(x,y)x+y,scale=scale.dat[1],epsilon=1.7,\n+   proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01))))\nError : in 'abc': each probe must be a function of a single argument.\n> try(abc(abc1,dprior=function(log,...)stop(\"ouch!\")))\nError : in 'abc': in 'dprior': ouch!\n> try(abc(abc1,dprior=function(log,...)Inf))\nError : in 'abc': non-finite log prior at starting parameters.\n> try(abc(abc1,probes=function(x)stop(\"piff!\")))\nError : in 'abc': applying probes to data: piff!\n> count <- 0\n> delayed.failure <- function (x) {count <<- count+1; if (count>2) stop(\"paff!\") else 1}\n> try(abc(abc1,scale=1,probes=delayed.failure))\nError : in 'abc': applying probes to simulations: paff!\n> try(abc(abc1,proposal=function(...)stop(\"urp!\")))\nError : in 'abc': in proposal function: urp!\n> count <- 0\n> delayed.failure <- function (log,...) {count <<- count+1; if (count>5) stop(\"no sir!\") else 1}\n> try(abc(abc1,dprior=delayed.failure))\nError : in 'abc': in 'dprior': no sir!\n> count <- 0\n> delayed.failure <- function (theta,...) {count <<- count+1; if (count>5) stop(\"'fraid not!\") else theta}\n> try(abc(abc1,proposal=delayed.failure))\nError : in 'abc': in proposal function: 'fraid not!\n> \n> coef(c(abc1,ou2)) -> theta\n> stopifnot(dim(theta)==c(10,2),\n+   rownames(theta)==c(\"alpha_1\",\"alpha_2\",\"alpha_3\",\"alpha_4\",\n+     \"sigma_1\",\"sigma_2\",\"sigma_3\",\"tau\",\"x1_0\",\"x2_0\"),\n+   apply(theta[c(\"alpha_3\",\"alpha_4\",\n+     \"sigma_1\",\"sigma_2\",\"sigma_3\",\"tau\",\"x1_0\",\"x2_0\"),],1,diff)==0,\n+   apply(theta[c(\"alpha_1\",\"alpha_2\"),],1,diff) != 0)\n> try(c(abc1,3))\nError : 'c' is not defined for objects of classes 'abcd_pomp', 'numeric'.\n> \n> c(c(abc1,abc2),ou2)\n[[1]]\n<object of class 'pomp'>\n\n[[2]]\n<object of class 'pomp'>\n\n[[3]]\n<object of class 'pomp'>\n\n> c(a=c(abc1,abc2),b=abc2)\n$a1\n<object of class 'abcd_pomp'>\n\n$a2\n<object of class 'abcd_pomp'>\n\n$b\n<object of class 'abcd_pomp'>\n\n> c(abc1)\n[[1]]\n<object of class 'abcd_pomp'>\n\n> alist <- c(c(abc1,abc2))\n> class(alist[2])\n[1] \"abcList\"\nattr(,\"package\")\n[1] \"pomp\"\n> try(alist[[3]])\nError in alist[[3]] : subscript out of bounds\n> alist <- c(a=abc1,b=abc2)\n> alist[\"b\"]\n$b\n<object of class 'abcd_pomp'>\n\n> alist[\"c\"]\n[[1]]\nNULL\n\n> alist[[\"b\"]]\n<object of class 'abcd_pomp'>\n> alist[[\"c\"]]\nNULL\n> c(one=abc1,two=abc2,three=abc3)\n$one\n<object of class 'abcd_pomp'>\n\n$two\n<object of class 'abcd_pomp'>\n\n$three\n<object of class 'abcd_pomp'>\n\n> print(c(one=abc1,two=abc2,three=abc3))\n$one\n<object of class 'abcd_pomp'>\n\n$two\n<object of class 'abcd_pomp'>\n\n$three\n<object of class 'abcd_pomp'>\n\n> \n> capture.output(abc(ou2,Nabc=100,probes=plist,scale=scale.dat,epsilon=1.7,\n+   proposal=mvn_diag_rw(rw.sd=c(alpha_1=0.01,alpha_2=0.01)),\n+   verbose=TRUE) -> abc1) -> out\n> stopifnot(\n+   length(out)==40,\n+   sum(grepl(\"acceptance\",out))==20,\n+   sum(grepl(\"ABC iteration\",out))==20\n+ )\n> \n> gompertz() -> gompertz\n> set.seed(2079015564L)\n> \n> gompertz |>\n+   as.data.frame() |>\n+   abc(Nabc=20,times=\"time\",t0=0,\n+     scale=1,epsilon=10,\n+     probes=list(probe_mean(\"Y\"),probe_median(\"Y\")),\n+     partrans=parameter_trans(log=c(\"r\",\"K\")),\n+     paramnames=c(\"r\",\"K\"),\n+     proposal=mvn_diag_rw(rw.sd=c(r=0.01,K=0.01)),\n+     params=coef(gompertz),\n+     rinit=function(...)c(X=1),\n+     rprocess=discrete_time(function (X, r, K, ...) c(X=r*X*exp(-X/K))),\n+     rmeasure=function (Y, X, ...) c(Y = rnorm(n=1,mean=X,sd=2))\n+     ) |> plot()\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/baddm.R",
    "content": "options(digits=2)\n\nlibrary(pomp)\n\nset.seed(398585L)\n\ntry(\n  gompertz() |>\n    pfilter(Np=10,dmeasure=function(...,log) Inf)\n)\n\ntry(\n  gompertz() |>\n    mif2(\n      Np=10,Nmif=2,\n      dmeasure=function(...,log) NaN,\n      rw.sd=rw_sd(r=0.01),\n      cooling.fraction.50=0.1\n    )\n)\n\ntry(\n  gompertz() |>\n    bsmc2(\n      Np=10,\n      rprior=function(...)c(r=runif(n=1,min=0,max=1)),\n      dmeasure=function(...,log) NA_real_,\n      partrans=NULL\n    )\n)\n"
  },
  {
    "path": "tests/baddm.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=2)\n> \n> library(pomp)\n> \n> set.seed(398585L)\n> \n> try(\n+   gompertz() |>\n+     pfilter(Np=10,dmeasure=function(...,log) Inf)\n+ )\nError : in 'pfilter': 'dmeasure' with log=TRUE returns illegal value.\nLog likelihood, data, states, and parameters are:\n  time:            1\nloglik:          Inf\n     Y:      1.02624\n     X:     0.908756\n     K:            1\n     r:          0.1\n sigma:          0.1\n   tau:          0.1\n   X_0:            1\n> \n> try(\n+   gompertz() |>\n+     mif2(\n+       Np=10,Nmif=2,\n+       dmeasure=function(...,log) NaN,\n+       rw.sd=rw_sd(r=0.01),\n+       cooling.fraction.50=0.1\n+     )\n+ )\nError : in 'mif2': 'dmeasure' with log=TRUE returns illegal value.\nLog likelihood, data, states, and parameters are:\n  time:            1\nloglik:          NaN\n     Y:      1.02624\n     X:     0.934271\n     K:            1\n     r:     0.100409\n sigma:          0.1\n   tau:          0.1\n   X_0:            1\n> \n> try(\n+   gompertz() |>\n+     bsmc2(\n+       Np=10,\n+       rprior=function(...)c(r=runif(n=1,min=0,max=1)),\n+       dmeasure=function(...,log) NA_real_,\n+       partrans=NULL\n+     )\n+ )\nError : in 'bsmc2': 'dmeasure' with log=TRUE returns illegal value.\nLog likelihood, data, states, and parameters are:\n  time:            1\nloglik:           NA\n     Y:      1.02624\n     X:      1.09411\n     K:            1\n     r:     0.714618\n sigma:          0.1\n   tau:          0.1\n   X_0:            1\n> \n"
  },
  {
    "path": "tests/bake.R",
    "content": "### test of reproducibility utilities\n\nlibrary(pomp)\noptions(digits=2,pomp_archive_dir=tempdir())\n\nset.seed(5499)\nw1 <- runif(2)\nw4 <- freeze({runif(5)},seed=c(499586,588686,39995866))\nw2 <- runif(2)\nw5 <- freeze(runif(5),seed=499586)\nset.seed(5499)\nw3 <- runif(4)\nstopifnot(\n  identical(c(w1,w2),w3),\n  identical(w4,w5)\n)\n\nset.seed(32765883)\nx1 <- bake({runif(4)},file=\"bake1.rds\",timing=FALSE)\nx2 <- bake({runif(4)},file=\"bake2.rds\",seed=32765883,timing=FALSE)\nx3 <- bake({runif(4)},file=\"bake1.rds\",timing=FALSE)\nx3a <- bake({  runif(4)},file=\"bake1.rds\",timing=FALSE)\nrm(.Random.seed)\nx4 <- bake({runif(4)},file=\"bake3.rds\",seed=59566)\nx5 <- bake({runif(5)},file=\"bake1.rds\")\nx6 <- bake({runif(5)},file=\"bake1.rds\")\nx7 <- bake({x1+runif(1)},file=\"bake4.rds\")\nx8 <- bake({x1+runif(1)},file=\"bake4.rds\",dependson=x1)\nx9 <- bake({x1+runif(1)},file=\"bake4.rds\",dependson=x1)\nx10 <- bake({x1+runif(1)},file=\"bake4.rds\",dependson=list(x1,x6))\nc <- function(x) x+5\nx11 <- bake({x1+runif(1)},file=\"bake4.rds\",dependson=list(x1,c))\ntry(\n  x12 <- bake({x1+runif(1)},file=\"bake4.rds\",dependson=list(c,x1,x13))\n)\ntry(\n  x12 <- bake({x1+runif(1)},file=\"bake4.rds\",dependson=list(c,x1,x13,x14))\n)\nx13 <- bake({x1+runif(1)},seed=233,file=\"bake4.rds\",dependson=x1,info=TRUE)\nstopifnot(\n  identical(x1,x2),\n  identical(x1,x3),\n  identical(x3,x3a),\n  identical(x5,x6),\n  !identical(x3,x5),\n  !identical(x7,x8),\n  identical(x8,x9),\n  !identical(x9,x10),\n  !exists(\"x12\"),\n  length(attr(x13,\"ingredients\"))==5,\n  attr(x13,\"ingredients\")$seed==233\n)\n\nsaveRDS(x1,file=file.path(tempdir(),\"tmp.rds\"))\ntry(x1 <- bake({runif(4)},file=\"tmp.rds\"))\nsaveRDS(x6,file=file.path(tempdir(),\"tmp.rds\"))\ninvisible(bake({runif(4)},file=\"tmp.rds\"))\n\nset.seed(113848)\nstew({y1 <- runif(4)},file=\"stew1.rda\")\nstew({y2 <- runif(4)},file=\"stew2.rda\",seed=113848)\ny3 <- y1\nprint(stew({y1 <- runif(4)},file=\"stew1.rda\"))\nrm(.Random.seed)\nstew({y4 <- runif(4)},file=\"stew3.rda\",seed=59566)\ny5 <- y1+y2 \nstew({y6 <- y1+y2},dependson=list(y1,y2),file=\"stew3.rda\")\nstopifnot(\n  identical(y1,y2),\n  identical(y1,y3),\n  identical(y5,y6)\n)\ny1 <- 0\nstew({y6 <- y1+y2},dependson=list(y1,y2),file=\"stew3.rda\")\nstopifnot(\n  identical(y2,y6),\n  !exists(\".ingredients\"),\n  exists(\".system.time\")\n)\nstew({y6 <- y1+y2},info=TRUE,file=\"stew3.rda\")\nstopifnot(\n  identical(y2,y6),\n  is.list(.ingredients),\n  length(.ingredients)==5\n)\n\nwindow(sir2(),end=0.5) -> po\nsimulate(po,seed=1347484107L) -> x\nfreeze(simulate(po),seed=1347484107L) -> y\nstopifnot(identical(x,y))\n\nstopifnot(\n  is.null(freeze({rnorm(5); NULL},seed=3494995)),\n  is.list(bake({rnorm(5); NULL},seed=3494995,file=\"bake4.rds\"))\n)\n\nrm(.Random.seed)\ninvisible(bake({runif(4)},file=\"b99.rds\",seed=32765883))\nrm(.Random.seed)\nprint(stew({runif(4)},file=\"s99.rda\",seed=32765883))\nrm(.Random.seed)\ninvisible(freeze({runif(4)},seed=32765883))\ninvisible(freeze({runif(4)}))\n\nbake({runif(5)},file=\"tmp1.rds\",info=TRUE) -> x\nattr(x,\"ingredients\") <- NULL\nsaveRDS(x,file=file.path(tempdir(),\"tmp1.rds\"))\nbake({runif(5)},file=\"tmp1.rds\") -> y\nbake({runif(5)},file=\"tmp1.rds\") -> y\nstopifnot(identical(x,y))\n\nstew({x <- 33; y <- runif(5)},file=\"tmp1.rda\")\nxx <- x; yy <- y\nsave(x,y,file=file.path(tempdir(),\"tmp1.rda\"))\nstew({x <- 33; y <- runif(5)},file=\"tmp1.rda\")\nstew({x <- 33; y <- runif(5)},file=\"tmp1.rda\")\nstopifnot(\n  identical(x,xx),\n  identical(y,yy)\n)\n\nstew({x <- 33; y <- runif(5)},seed=99,file=\"tmp2.rda\")\nxx <- x; yy <- y\nsave(x,y,file=file.path(tempdir(),\"tmp2.rda\"))\nstew({x <- 33; y <- runif(5)},file=\"tmp2.rda\")\nstew({x <- 33; y <- runif(5)},seed=99,file=\"tmp2.rda\")\nstopifnot(\n  identical(x,xx),\n  identical(y,yy)\n)\n\ncapture.output(\n  {\n    bake(file=\"results/bob/mary/tmp.rds\",rnorm(5)) -> x1\n    bake(file=\"results/bob/mary/tmp.rds\",rnorm(5)) -> x2\n    bake(file=\"mary/tmp.rds\",rnorm(5),dir=file.path(tempdir(),\"results/bob\")) -> x3\n    op <- options(pomp_archive_dir=file.path(tempdir(),\"results\"))\n    bake(file=\"bob/mary/tmp.rds\",rnorm(5)) -> x4\n    bake(file=\"results/bob/mary/tmp.rds\",rnorm(5)) -> x5\n    options(op)\n    bake(file=\"results/results/bob/mary/tmp.rds\",rnorm(5)) -> x6\n  },\n  type=\"message\"\n) -> out\nstopifnot(\n  identical(x1,x2),\n  identical(x1,x3),\n  identical(x1,x4),\n  !identical(x1,x5),\n  identical(x5,x6),\n  length(out)==2,\n  grepl(\"^NOTE: creating archive directory\",out),\n  grepl(\"results/bob/mary.\",out),\n  grepl(\"results/results/bob/mary.\",out[2])\n)\n"
  },
  {
    "path": "tests/bake.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> ### test of reproducibility utilities\n> \n> library(pomp)\n> options(digits=2,pomp_archive_dir=tempdir())\n> \n> set.seed(5499)\n> w1 <- runif(2)\n> w4 <- freeze({runif(5)},seed=c(499586,588686,39995866))\n> w2 <- runif(2)\n> w5 <- freeze(runif(5),seed=499586)\n> set.seed(5499)\n> w3 <- runif(4)\n> stopifnot(\n+   identical(c(w1,w2),w3),\n+   identical(w4,w5)\n+ )\n> \n> set.seed(32765883)\n> x1 <- bake({runif(4)},file=\"bake1.rds\",timing=FALSE)\n> x2 <- bake({runif(4)},file=\"bake2.rds\",seed=32765883,timing=FALSE)\n> x3 <- bake({runif(4)},file=\"bake1.rds\",timing=FALSE)\n> x3a <- bake({  runif(4)},file=\"bake1.rds\",timing=FALSE)\n> rm(.Random.seed)\n> x4 <- bake({runif(4)},file=\"bake3.rds\",seed=59566)\n> x5 <- bake({runif(5)},file=\"bake1.rds\")\nNOTE: in 'bake': recomputing archive bake1.rds.\n> x6 <- bake({runif(5)},file=\"bake1.rds\")\n> x7 <- bake({x1+runif(1)},file=\"bake4.rds\")\n> x8 <- bake({x1+runif(1)},file=\"bake4.rds\",dependson=x1)\nNOTE: in 'bake': recomputing archive bake4.rds.\n> x9 <- bake({x1+runif(1)},file=\"bake4.rds\",dependson=x1)\n> x10 <- bake({x1+runif(1)},file=\"bake4.rds\",dependson=list(x1,x6))\nNOTE: in 'bake': recomputing archive bake4.rds.\n> c <- function(x) x+5\n> x11 <- bake({x1+runif(1)},file=\"bake4.rds\",dependson=list(x1,c))\nNOTE: in 'bake': recomputing archive bake4.rds.\n> try(\n+   x12 <- bake({x1+runif(1)},file=\"bake4.rds\",dependson=list(c,x1,x13))\n+ )\nError : in 'bake': cannot compute hash of dependencies: object 'x13' not found\n> try(\n+   x12 <- bake({x1+runif(1)},file=\"bake4.rds\",dependson=list(c,x1,x13,x14))\n+ )\nError : in 'bake': cannot compute hash of dependencies: object 'x13' not found\n> x13 <- bake({x1+runif(1)},seed=233,file=\"bake4.rds\",dependson=x1,info=TRUE)\nNOTE: in 'bake': recomputing archive bake4.rds.\n> stopifnot(\n+   identical(x1,x2),\n+   identical(x1,x3),\n+   identical(x3,x3a),\n+   identical(x5,x6),\n+   !identical(x3,x5),\n+   !identical(x7,x8),\n+   identical(x8,x9),\n+   !identical(x9,x10),\n+   !exists(\"x12\"),\n+   length(attr(x13,\"ingredients\"))==5,\n+   attr(x13,\"ingredients\")$seed==233\n+ )\n> \n> saveRDS(x1,file=file.path(tempdir(),\"tmp.rds\"))\n> try(x1 <- bake({runif(4)},file=\"tmp.rds\"))\nError : in 'bake': 'tmp.rds' lacks ingredients.\n> saveRDS(x6,file=file.path(tempdir(),\"tmp.rds\"))\n> invisible(bake({runif(4)},file=\"tmp.rds\"))\nNOTE: in 'bake': archive in old format detected. Updating....\n> \n> set.seed(113848)\n> stew({y1 <- runif(4)},file=\"stew1.rda\")\n> stew({y2 <- runif(4)},file=\"stew2.rda\",seed=113848)\n> y3 <- y1\n> print(stew({y1 <- runif(4)},file=\"stew1.rda\"))\n[1] \"y1\"\n> rm(.Random.seed)\n> stew({y4 <- runif(4)},file=\"stew3.rda\",seed=59566)\n> y5 <- y1+y2 \n> stew({y6 <- y1+y2},dependson=list(y1,y2),file=\"stew3.rda\")\nNOTE: in 'stew': recomputing archive stew3.rda.\n> stopifnot(\n+   identical(y1,y2),\n+   identical(y1,y3),\n+   identical(y5,y6)\n+ )\n> y1 <- 0\n> stew({y6 <- y1+y2},dependson=list(y1,y2),file=\"stew3.rda\")\nNOTE: in 'stew': recomputing archive stew3.rda.\n> stopifnot(\n+   identical(y2,y6),\n+   !exists(\".ingredients\"),\n+   exists(\".system.time\")\n+ )\n> stew({y6 <- y1+y2},info=TRUE,file=\"stew3.rda\")\nNOTE: in 'stew': recomputing archive stew3.rda.\n> stopifnot(\n+   identical(y2,y6),\n+   is.list(.ingredients),\n+   length(.ingredients)==5\n+ )\n> \n> window(sir2(),end=0.5) -> po\n> simulate(po,seed=1347484107L) -> x\n> freeze(simulate(po),seed=1347484107L) -> y\n> stopifnot(identical(x,y))\n> \n> stopifnot(\n+   is.null(freeze({rnorm(5); NULL},seed=3494995)),\n+   is.list(bake({rnorm(5); NULL},seed=3494995,file=\"bake4.rds\"))\n+ )\nNOTE: in 'bake': recomputing archive bake4.rds.\nWarning message:\nin 'bake': expression evaluates to NULL, an empty list will be returned. \n> \n> rm(.Random.seed)\n> invisible(bake({runif(4)},file=\"b99.rds\",seed=32765883))\n> rm(.Random.seed)\n> print(stew({runif(4)},file=\"s99.rda\",seed=32765883))\ncharacter(0)\n> rm(.Random.seed)\n> invisible(freeze({runif(4)},seed=32765883))\n> invisible(freeze({runif(4)}))\n> \n> bake({runif(5)},file=\"tmp1.rds\",info=TRUE) -> x\n> attr(x,\"ingredients\") <- NULL\n> saveRDS(x,file=file.path(tempdir(),\"tmp1.rds\"))\n> bake({runif(5)},file=\"tmp1.rds\") -> y\nNOTE: in 'bake': archive in old format detected. Updating....\n> bake({runif(5)},file=\"tmp1.rds\") -> y\n> stopifnot(identical(x,y))\n> \n> stew({x <- 33; y <- runif(5)},file=\"tmp1.rda\")\n> xx <- x; yy <- y\n> save(x,y,file=file.path(tempdir(),\"tmp1.rda\"))\n> stew({x <- 33; y <- runif(5)},file=\"tmp1.rda\")\nNOTE: in 'stew': archive in old format detected. Updating....\n> stew({x <- 33; y <- runif(5)},file=\"tmp1.rda\")\n> stopifnot(\n+   identical(x,xx),\n+   identical(y,yy)\n+ )\n> \n> stew({x <- 33; y <- runif(5)},seed=99,file=\"tmp2.rda\")\n> xx <- x; yy <- y\n> save(x,y,file=file.path(tempdir(),\"tmp2.rda\"))\n> stew({x <- 33; y <- runif(5)},file=\"tmp2.rda\")\nNOTE: in 'stew': archive in old format detected. Updating....\n> stew({x <- 33; y <- runif(5)},seed=99,file=\"tmp2.rda\")\nNOTE: in 'stew': recomputing archive tmp2.rda.\n> stopifnot(\n+   identical(x,xx),\n+   identical(y,yy)\n+ )\n> \n> capture.output(\n+   {\n+     bake(file=\"results/bob/mary/tmp.rds\",rnorm(5)) -> x1\n+     bake(file=\"results/bob/mary/tmp.rds\",rnorm(5)) -> x2\n+     bake(file=\"mary/tmp.rds\",rnorm(5),dir=file.path(tempdir(),\"results/bob\")) -> x3\n+     op <- options(pomp_archive_dir=file.path(tempdir(),\"results\"))\n+     bake(file=\"bob/mary/tmp.rds\",rnorm(5)) -> x4\n+     bake(file=\"results/bob/mary/tmp.rds\",rnorm(5)) -> x5\n+     options(op)\n+     bake(file=\"results/results/bob/mary/tmp.rds\",rnorm(5)) -> x6\n+   },\n+   type=\"message\"\n+ ) -> out\n> stopifnot(\n+   identical(x1,x2),\n+   identical(x1,x3),\n+   identical(x1,x4),\n+   !identical(x1,x5),\n+   identical(x5,x6),\n+   length(out)==2,\n+   grepl(\"^NOTE: creating archive directory\",out),\n+   grepl(\"results/bob/mary.\",out),\n+   grepl(\"results/results/bob/mary.\",out[2])\n+ )\n> \n"
  },
  {
    "path": "tests/basic_probes.R",
    "content": "options(digits=3)\n\nlibrary(pomp)\nsuppressPackageStartupMessages({\n  library(dplyr)\n  library(tidyr)\n  library(ggplot2)\n})\n\nset.seed(255066335)\n\nou2() -> ou2\n\nplist <- list(\n  mean=probe_mean(\"y1\"),\n  med=probe_median(\"y2\"),\n  v=probe_var(\"y1\"),\n  sd=probe_sd(\"y2\"),\n  pd=probe_period(\"y1\",kernel.width=5),\n  probe_quantile(\"y2\",prob=c(0.1,0.5,0.9)),\n  probe_acf(\"y1\",lags=c(1,3,6)),\n  probe_acf(\"y2\",lags=c(1,2,3),type=\"cor\"),\n  probe_ccf(c(\"y1\",\"y2\"),lags=c(0,1,2)),\n  probe_marginal(\"y1\",ref=obs(ou2,\"y1\")),\n  probe_nlar(\"y2\",lags=c(1,1,1,2,2),powers=c(1,2,3,1,2))\n)\n\nou2 |> probe(probes=plist,nsim=1000) -> pb\nsummary(pb) -> sm\nstopifnot(names(sm)==c(\"coef\",\"nsim\",\"quantiles\",\"pvals\",\"synth.loglik\"),\n  logLik(pb)==sm$synth.loglik,\n  length(sm$pvals)==25,length(sm$quantiles)==25)\n\ntry(probe_mean(c(\"y1\",\"y2\")))\ntry(probe_median(c(\"y1\",\"y2\")))\ntry(probe_var(c(\"y1\",\"y2\")))\ntry(probe_sd(c(\"y1\",\"y2\")))\ntry(probe_period(c(\"y1\",\"y2\")))\ntry(probe_quantile(c(\"y1\",\"y2\")))\ntry(probe_marginal(c(\"y1\",\"y2\")))\ntry(probe_ccf(\"y1\"))\ntry(probe_nlar(c(\"y1\",\"y2\")))\n\ntry(probe_acf(c(\"y1\",\"y2\"),lags=c(0,1),type=\"cor\"))\nprobe_acf(c(\"y1\",\"y2\"),lags=c(1,5),type=\"cor\") -> f\nou2 |> simulate() |> obs() |> f() -> v\nnames(v)\n\ntry(ou2 |> simulate(rmeasure=function(...) c(y=1)) |> obs() |> f())\ntry(ou2 |> simulate(rmeasure=function(...) c(y1=NA,y2=NA)) |> obs() |> f())\nou2 |> simulate(rmeasure=function(t,...) c(y1=-t,y2=t)) |> obs() |> f()\nprobe_ccf(c(\"y2\",\"y1\"),lags=c(0,1,2),type=\"cor\") -> f\nou2 |> simulate() |> obs() |> f()\ntry(ou2 |> simulate(rmeasure=function(...) c(y=1)) |> obs() |> f())\ntry(ou2 |> simulate(rmeasure=function(...) c(y1=NA,y2=NA)) |> obs() |> f())\nou2 |> simulate(times=1:10,rmeasure=function(t,...) c(y1=-t,y2=t)) |> obs() |> f()\n\nprobe_marginal(\"y1\",ref=obs(ou2,\"y1\"),order=6,diff=2) -> f\nou2 |> simulate() |> obs() |> f()\ntry(ou2 |> simulate(rmeasure=function(...) c(y=1)) |> obs() |> f())\nou2 |> simulate(rmeasure=function(...) c(y1=NA,y2=NA)) |> obs() |> f() -> x\nstopifnot(all(is.na(x)))\ntry(ou2 |> simulate(times=1:10,rmeasure=function(t,...) c(y1=-t,y2=t)) |> obs() |> f())\nou2 |> simulate(rmeasure=function(t,...) c(y1=-t,y2=t)) |> obs() |> f() -> x\nstopifnot(x==0)\n\ntry(probe_nlar(\"y1\",lags=c(0,-1)))\ntry(probe_nlar(\"y1\",lags=c(0,-1),powers=2))\ntry(probe_nlar(\"y1\",lags=c(0,1,2),powers=c(0,-1)))\ntry(probe_nlar(\"y1\",lags=c(0,1,NA),powers=c(0,1)))\ntry(probe_nlar(\"y1\",lags=c(0,1,2),powers=NA))\ntry(probe_nlar(\"y1\",lags=c(0,1,2),powers=NULL))\ntry(probe_nlar(\"y1\",lags=list(0,1,2),powers=1))\ntry(probe_nlar(\"y1\",lags=list(1,2),powers=c(1,2,3)))\ntry(probe_nlar(\"y1\",lags=list(1,2,3),powers=c(1,2)))\n\nplist <- list(\n  probe_nlar(\"y1\",lags=c(1,2,3),powers=2),\n  probe_nlar(\"y2\",lags=1,powers=c(1,2,3))\n)\nprobe_nlar(\"y2\",lags=1,powers=c(1,2,3)) -> f\nou2 |> simulate() |> obs() |> f()\ntry(ou2 |> simulate(rmeasure=function(...) c(y=1)) |> obs() |> f())\nou2 |> simulate(rmeasure=function(...) c(y1=NA,y2=NA)) |> obs() |> f() -> x\nstopifnot(x==0)\nou2 |> simulate(times=1:10,rmeasure=function(t,...) c(y1=-t,y2=t)) |> obs() |> f()\n"
  },
  {
    "path": "tests/basic_probes.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> \n> library(pomp)\n> suppressPackageStartupMessages({\n+   library(dplyr)\n+   library(tidyr)\n+   library(ggplot2)\n+ })\n> \n> set.seed(255066335)\n> \n> ou2() -> ou2\n> \n> plist <- list(\n+   mean=probe_mean(\"y1\"),\n+   med=probe_median(\"y2\"),\n+   v=probe_var(\"y1\"),\n+   sd=probe_sd(\"y2\"),\n+   pd=probe_period(\"y1\",kernel.width=5),\n+   probe_quantile(\"y2\",prob=c(0.1,0.5,0.9)),\n+   probe_acf(\"y1\",lags=c(1,3,6)),\n+   probe_acf(\"y2\",lags=c(1,2,3),type=\"cor\"),\n+   probe_ccf(c(\"y1\",\"y2\"),lags=c(0,1,2)),\n+   probe_marginal(\"y1\",ref=obs(ou2,\"y1\")),\n+   probe_nlar(\"y2\",lags=c(1,1,1,2,2),powers=c(1,2,3,1,2))\n+ )\n> \n> ou2 |> probe(probes=plist,nsim=1000) -> pb\n> summary(pb) -> sm\n> stopifnot(names(sm)==c(\"coef\",\"nsim\",\"quantiles\",\"pvals\",\"synth.loglik\"),\n+   logLik(pb)==sm$synth.loglik,\n+   length(sm$pvals)==25,length(sm$quantiles)==25)\n> \n> try(probe_mean(c(\"y1\",\"y2\")))\nError : 'probe_mean' is a univariate probe.\n> try(probe_median(c(\"y1\",\"y2\")))\nError : 'probe_median' is a univariate probe.\n> try(probe_var(c(\"y1\",\"y2\")))\nError : 'probe_var' is a univariate probe.\n> try(probe_sd(c(\"y1\",\"y2\")))\nError : 'probe_sd' is a univariate probe.\n> try(probe_period(c(\"y1\",\"y2\")))\nError : 'probe_period' is a univariate probe.\n> try(probe_quantile(c(\"y1\",\"y2\")))\nError : 'probe_quantile' is a univariate probe.\n> try(probe_marginal(c(\"y1\",\"y2\")))\nError : 'probe_marginal' is a univariate probe.\n> try(probe_ccf(\"y1\"))\nError : in 'probe_ccf': 'vars' must name two variables.\n> try(probe_nlar(c(\"y1\",\"y2\")))\nError : 'probe_nlar' is a univariate probe.\n> \n> try(probe_acf(c(\"y1\",\"y2\"),lags=c(0,1),type=\"cor\"))\nError : in 'probe_acf': lags must be positive integers.\n> probe_acf(c(\"y1\",\"y2\"),lags=c(1,5),type=\"cor\") -> f\n> ou2 |> simulate() |> obs() |> f() -> v\n> names(v)\n[1] \"acf[1]\" \"acf[5]\" \"acf[1]\" \"acf[5]\"\n> \n> try(ou2 |> simulate(rmeasure=function(...) c(y=1)) |> obs() |> f())\nError : in 'probe_acf': subscript out of bounds\n> try(ou2 |> simulate(rmeasure=function(...) c(y1=NA,y2=NA)) |> obs() |> f())\nError : in 'probe_acf': series 1 has no data\n> ou2 |> simulate(rmeasure=function(t,...) c(y1=-t,y2=t)) |> obs() |> f()\nacf[1] acf[5] acf[1] acf[5] \n 0.980  0.895  0.980  0.895 \n> probe_ccf(c(\"y2\",\"y1\"),lags=c(0,1,2),type=\"cor\") -> f\n> ou2 |> simulate() |> obs() |> f()\nccf[0] ccf[1] ccf[2] \n 0.159  0.515  0.700 \n> try(ou2 |> simulate(rmeasure=function(...) c(y=1)) |> obs() |> f())\nError : in 'probe_ccf': subscript out of bounds\n> try(ou2 |> simulate(rmeasure=function(...) c(y1=NA,y2=NA)) |> obs() |> f())\nError : in 'probe_ccf': series 1 has no data\n> ou2 |> simulate(times=1:10,rmeasure=function(t,...) c(y1=-t,y2=t)) |> obs() |> f()\nccf[0] ccf[1] ccf[2] \n-1.000 -0.778 -0.515 \n> \n> probe_marginal(\"y1\",ref=obs(ou2,\"y1\"),order=6,diff=2) -> f\n> ou2 |> simulate() |> obs() |> f()\n   marg.1    marg.2    marg.3    marg.4    marg.5    marg.6 \n 9.42e-01 -1.62e-02  2.14e-03  2.51e-05 -1.29e-05  3.64e-07 \n> try(ou2 |> simulate(rmeasure=function(...) c(y=1)) |> obs() |> f())\nError : in 'probe_marginal': subscript out of bounds\n> ou2 |> simulate(rmeasure=function(...) c(y1=NA,y2=NA)) |> obs() |> f() -> x\n> stopifnot(all(is.na(x)))\n> try(ou2 |> simulate(times=1:10,rmeasure=function(t,...) c(y1=-t,y2=t)) |> obs() |> f())\nError : in 'probe_marginal': length of 'ref' must equal length of data\n> ou2 |> simulate(rmeasure=function(t,...) c(y1=-t,y2=t)) |> obs() |> f() -> x\n> stopifnot(x==0)\n> \n> try(probe_nlar(\"y1\",lags=c(0,-1)))\nError : in 'probe_nlar': 'lags' and 'powers' are required arguments.\n> try(probe_nlar(\"y1\",lags=c(0,-1),powers=2))\nError : in 'probe_nlar': 'lags' and 'powers' must be positive integers.\n> try(probe_nlar(\"y1\",lags=c(0,1,2),powers=c(0,-1)))\nError : in 'probe_nlar': 'lags' and 'powers' must be positive integers.\n> try(probe_nlar(\"y1\",lags=c(0,1,NA),powers=c(0,1)))\nError : in 'probe_nlar': 'lags' and 'powers' must be positive integers.\n> try(probe_nlar(\"y1\",lags=c(0,1,2),powers=NA))\nError : in 'probe_nlar': 'lags' and 'powers' must be positive integers.\n> try(probe_nlar(\"y1\",lags=c(0,1,2),powers=NULL))\nError : in 'probe_nlar': 'lags' and 'powers' must be positive integers.\n> try(probe_nlar(\"y1\",lags=list(0,1,2),powers=1))\nError : in 'probe_nlar': 'lags' and 'powers' must be positive integers.\n> try(probe_nlar(\"y1\",lags=list(1,2),powers=c(1,2,3)))\nError : in 'probe_nlar': 'lags' must match 'powers' in length, or have length 1.\n> try(probe_nlar(\"y1\",lags=list(1,2,3),powers=c(1,2)))\nError : in 'probe_nlar': 'powers' must match 'lags' in length, or have length 1.\n> \n> plist <- list(\n+   probe_nlar(\"y1\",lags=c(1,2,3),powers=2),\n+   probe_nlar(\"y2\",lags=1,powers=c(1,2,3))\n+ )\n> probe_nlar(\"y2\",lags=1,powers=c(1,2,3)) -> f\n> ou2 |> simulate() |> obs() |> f()\nnlar.1^1 nlar.1^2 nlar.1^3 \n8.89e-01 1.78e-04 4.17e-05 \n> try(ou2 |> simulate(rmeasure=function(...) c(y=1)) |> obs() |> f())\nError : in 'probe_nlar': subscript out of bounds\n> ou2 |> simulate(rmeasure=function(...) c(y1=NA,y2=NA)) |> obs() |> f() -> x\n> stopifnot(x==0)\n> ou2 |> simulate(times=1:10,rmeasure=function(t,...) c(y1=-t,y2=t)) |> obs() |> f()\nnlar.1^1 nlar.1^2 nlar.1^3 \n  0.8815   0.0988   0.0149 \n> \n"
  },
  {
    "path": "tests/betabinom.R",
    "content": "library(pomp)\n\nfreeze(\n  rbetabinom(n=2000000,size=c(20,30),prob=0.5,theta=10000) |>\n    matrix(2),\n  seed=39596886L\n)  -> x1\n\nx1 |>\n  dbetabinom(size=c(20,30),prob=0.5,theta=100,log=TRUE) |>\n  matrix(2) |>\n  apply(1,mean) -> f1\n\nfreeze(\n  rbetabinom(n=3000000,size=10,prob=c(0.5,0.9,1),theta=10) |>\n    matrix(3,1000000),\n  seed=39596886L\n) -> x2\n\nx2[-3,] |>\n  dbetabinom(size=10,prob=c(0.5,0.9),theta=10,log=TRUE) |>\n  matrix(2) |>\n  apply(1,mean) -> f2\n\nstopifnot(\n  `m1 fail`={x1 |> apply(1,mean) |> all.equal(c(10,15),tolerance=0.001)},\n  `v1 fail`={x1 |> apply(1,var) |> all.equal(c(5,7.5),tolerance=0.005)},\n  `dcheck1`=all.equal(f1,c(-2.23,-2.44),tolerance=.005),\n  `m2 fail`={x2 |> apply(1,mean) |> all.equal(c(5,9,10),tolerance=0.001)},\n  `v2 fail`={x2 |> apply(1,var) |> all.equal(c(4.54,1.63,0),tolerance=0.005)},\n  `dcheck2`=all.equal(f2,c(-2.16,-1.38),tolerance=.005)\n)\n"
  },
  {
    "path": "tests/betabinom.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> \n> freeze(\n+   rbetabinom(n=2000000,size=c(20,30),prob=0.5,theta=10000) |>\n+     matrix(2),\n+   seed=39596886L\n+ )  -> x1\n> \n> x1 |>\n+   dbetabinom(size=c(20,30),prob=0.5,theta=100,log=TRUE) |>\n+   matrix(2) |>\n+   apply(1,mean) -> f1\n> \n> freeze(\n+   rbetabinom(n=3000000,size=10,prob=c(0.5,0.9,1),theta=10) |>\n+     matrix(3,1000000),\n+   seed=39596886L\n+ ) -> x2\n> \n> x2[-3,] |>\n+   dbetabinom(size=10,prob=c(0.5,0.9),theta=10,log=TRUE) |>\n+   matrix(2) |>\n+   apply(1,mean) -> f2\n> \n> stopifnot(\n+   `m1 fail`={x1 |> apply(1,mean) |> all.equal(c(10,15),tolerance=0.001)},\n+   `v1 fail`={x1 |> apply(1,var) |> all.equal(c(5,7.5),tolerance=0.005)},\n+   `dcheck1`=all.equal(f1,c(-2.23,-2.44),tolerance=.005),\n+   `m2 fail`={x2 |> apply(1,mean) |> all.equal(c(5,9,10),tolerance=0.001)},\n+   `v2 fail`={x2 |> apply(1,var) |> all.equal(c(4.54,1.63,0),tolerance=0.005)},\n+   `dcheck2`=all.equal(f2,c(-2.16,-1.38),tolerance=.005)\n+ )\n> \n"
  },
  {
    "path": "tests/blowflies.R",
    "content": "png(filename=\"blowflies-%02d.png\",res=100)\nset.seed(599688L)\n\nlibrary(pomp)\n\nlist(blowflies1(),blowflies2()) -> flies\n\nplot(flies[[1]])\nrinit(flies[[1]])\ncoef(flies[[1]])\nplot(simulate(flies[[1]],seed=599688L),var=c(\"y\",\"R\",\"S\",\"N15\"))\npf <- freeze(pfilter(flies[[1]],Np=1000),seed=599688L)\nplot(pf)\nlogLik(pf)\nstopifnot(\n  all.equal(\n    partrans(\n      flies[[1]],\n      partrans(flies[[1]],dir=\"to\",coef(flies[[1]])),\n      dir=\"from\"\n    ),\n    coef(flies[[1]])\n  ),\n  abs(logLik(pf)+1467.82)<0.05\n)\n\nplot(flies[[2]])\nrinit(flies[[2]])\ncoef(flies[[2]])\nplot(simulate(flies[[2]],seed=599688L),var=c(\"y\",\"R\",\"S\",\"N8\"))\npf <- freeze(pfilter(flies[[2]],Np=1000),seed=599688L)\nplot(pf)\nlogLik(pf)\nstopifnot(\n  all.equal(\n    partrans(\n      flies[[2]],\n      partrans(flies[[2]],dir=\"to\",coef(flies[[2]])),\n      dir=\"from\"\n    ),\n    coef(flies[[2]])\n  ),\n  abs(logLik(pf)+1473.66)<0.05\n)\n\ndev.off()\n"
  },
  {
    "path": "tests/blowflies.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> png(filename=\"blowflies-%02d.png\",res=100)\n> set.seed(599688L)\n> \n> library(pomp)\n> \n> list(blowflies1(),blowflies2()) -> flies\n> \n> plot(flies[[1]])\n> rinit(flies[[1]])\n     .id\nname   [,1]\n  N1  397.0\n  N2  450.5\n  N3  504.0\n  N4  590.0\n  N5  676.0\n  N6  738.5\n  N7  801.0\n  N8  829.5\n  N9  858.0\n  N10 884.5\n  N11 911.0\n  N12 926.5\n  N13 942.0\n  N14 945.0\n  N15 948.0\n  R     0.0\n  S     0.0\n  e     0.0\n  eps   0.0\n> coef(flies[[1]])\n         P      delta         N0    sigma.P    sigma.d    sigma.y \n  3.283800   0.160730 679.940000   1.351200   0.746770   0.026649 \n> plot(simulate(flies[[1]],seed=599688L),var=c(\"y\",\"R\",\"S\",\"N15\"))\n> pf <- freeze(pfilter(flies[[1]],Np=1000),seed=599688L)\n> plot(pf)\n> logLik(pf)\n[1] -1467.82\n> stopifnot(\n+   all.equal(\n+     partrans(\n+       flies[[1]],\n+       partrans(flies[[1]],dir=\"to\",coef(flies[[1]])),\n+       dir=\"from\"\n+     ),\n+     coef(flies[[1]])\n+   ),\n+   abs(logLik(pf)+1467.82)<0.05\n+ )\n> \n> plot(flies[[2]])\n> rinit(flies[[2]])\n     .id\nname  [,1]\n  N1   397\n  N2   504\n  N3   676\n  N4   801\n  N5   858\n  N6   911\n  N7   942\n  N8   948\n  R      0\n  S      0\n  e      0\n  eps    0\n> coef(flies[[2]])\n         P      delta         N0    sigma.P    sigma.d    sigma.y \n  2.731900   0.173770 800.310000   1.442000   0.760330   0.010846 \n> plot(simulate(flies[[2]],seed=599688L),var=c(\"y\",\"R\",\"S\",\"N8\"))\n> pf <- freeze(pfilter(flies[[2]],Np=1000),seed=599688L)\n> plot(pf)\n> logLik(pf)\n[1] -1473.661\n> stopifnot(\n+   all.equal(\n+     partrans(\n+       flies[[2]],\n+       partrans(flies[[2]],dir=\"to\",coef(flies[[2]])),\n+       dir=\"from\"\n+     ),\n+     coef(flies[[2]])\n+   ),\n+   abs(logLik(pf)+1473.66)<0.05\n+ )\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/bsmc2.R",
    "content": "png(filename=\"bsmc2-%02d.png\",res=100)\noptions(digits=2)\n\nlibrary(pomp)\nsuppressPackageStartupMessages({\n  library(dplyr)\n  library(tidyr)\n  library(ggplot2)\n})\n\ngompertz() -> gompertz\nset.seed(398585L)\n\ntime(gompertz) <- 1:10\n\nsmc <- bsmc2(\n  gompertz,\n  rprior=Csnippet(\"\n    K = runif(0.1,1);\n    r = rlnorm(log(0.2),1);\n    sigma = rlnorm(log(0.1),0.5);\"),\n  paramnames=c(\"r\",\"K\",\"sigma\"),\n  Np=1000,smooth=0.05\n)\n\nplot(smc,y=NA)\nplot(smc,pars=c(\"r\",\"K\"),thin=20)\ntry(plot(smc,pars=\"bob\"))\nplot(smc,pars=\"K\")\ntry(plot(smc,pars=NULL))\nstopifnot(\n  sum(cond_logLik(smc))==logLik(smc),\n  length(eff_sample_size(smc)) == 10\n)\nsmc |> eff_sample_size(format=\"d\") |> names()\nsmc |> eff_sample_size(format=\"d\") |> sapply(class)\nsmc |> cond_logLik(format=\"d\") |> names()\nsmc |> cond_logLik(format=\"d\") |> sapply(class)\n\ntry(bsmc2())\ntry(bsmc2(3L))\n\npo <- smc\ncoef(po) <- NULL\ntry(bsmc2(smc))\ntry(bsmc2(po))\ntry(bsmc2(po,params=NULL))\ntry(bsmc2(po,params=\"yes\"))\ntry(bsmc2(po,params=list()))\ntry(bsmc2(po,params=c(1,2,3)))\ntheta <- coef(smc)\ntry(bsmc2(po,params=as.list(theta)))\ntry(bsmc2(po,params=as.list(theta),Np=1))\ntry(bsmc2(smc,Np=-10))\ntry(bsmc2(smc,params=theta,Np=100,\n  dmeasure=Csnippet(\"error(\\\"whoa nelly!\\\");\")))\ntry(bsmc2(smc,Np=100,smooth=5))\ntry(bsmc2(smc,Np=100,smooth=NA))\ntry(bsmc2(smc,Np=100,smooth=-2))\ntry(bsmc2(smc,Np=100,smooth=NULL))\ntry(bsmc2(smc,Np=100,smooth=Inf))\ntry(bsmc2(smc,Np=100,smooth=\"yes\"))\ntry(bsmc2(smc,Np=100,smooth=c(1,2)))\ntry(bsmc2(smc,Np=100,smooth=list(1,2)))\ntry(bsmc2(smc,Np=100,rprocess=NULL))\ntry(bsmc2(smc,Np=100,params=NULL))\ntry(bsmc2(smc,Np=100,dmeasure=NULL))\ntry(bsmc2(smc,Np=100,rprior=NULL))\n\ntheta <- coef(gompertz)\ntheta[\"K\"] <- 1\ntry(capture.output(bsmc2(po,Np=2,params=theta,verbose=TRUE)) -> out)\n\nsmc |> as.data.frame() |>\n  filter(.id==\"posterior\") |>\n  select(-.id) -> pp\n\ngompertz |>\n  as.data.frame() |>\n  subset(select=-X) |>\n  bsmc2(\n    times=\"time\",t0=-5,\n    params=coef(gompertz),\n    Np=1000,smooth=0.1,\n    rprior=Csnippet(\"\n      K = runif(0.1,1);\n      r = rlnorm(log(0.2),1);\n      sigma = rlnorm(log(0.1),0.5);\"),\n    rprocess=gompertz@rprocess,\n    dmeasure=gompertz@dmeasure,\n    statenames=c(\"X\"),\n    paramnames=c(\"r\",\"K\",\"sigma\")) -> smc4\nsmc4 |> plot()\n\ntry(gompertz |>\n    as.data.frame() |>\n    subset(select=-X) |>\n    bsmc2(\n      times=\"time\",t0=-5,\n      params=coef(gompertz),\n      Np=1000,smooth=0.1,\n      rprior=3,\n      rprocess=gompertz@rprocess,\n      dmeasure=gompertz@dmeasure,\n      statenames=c(\"X\"),\n      paramnames=c(\"r\",\"K\",\"sigma\")))\n\nsmc |>\n  bsmc2(Np=seq(10,length=12,by=10)) |>\n  eff_sample_size()\n\ndev.off()\n"
  },
  {
    "path": "tests/bsmc2.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> png(filename=\"bsmc2-%02d.png\",res=100)\n> options(digits=2)\n> \n> library(pomp)\n> suppressPackageStartupMessages({\n+   library(dplyr)\n+   library(tidyr)\n+   library(ggplot2)\n+ })\n> \n> gompertz() -> gompertz\n> set.seed(398585L)\n> \n> time(gompertz) <- 1:10\n> \n> smc <- bsmc2(\n+   gompertz,\n+   rprior=Csnippet(\"\n+     K = runif(0.1,1);\n+     r = rlnorm(log(0.2),1);\n+     sigma = rlnorm(log(0.1),0.5);\"),\n+   paramnames=c(\"r\",\"K\",\"sigma\"),\n+   Np=1000,smooth=0.05\n+ )\n> \n> plot(smc,y=NA)\n> plot(smc,pars=c(\"r\",\"K\"),thin=20)\n> try(plot(smc,pars=\"bob\"))\nError : in 'plot': unrecognized parameters: 'bob'\n> plot(smc,pars=\"K\")\n> try(plot(smc,pars=NULL))\nError : in 'plot': no parameters to plot.\n> stopifnot(\n+   sum(cond_logLik(smc))==logLik(smc),\n+   length(eff_sample_size(smc)) == 10\n+ )\n> smc |> eff_sample_size(format=\"d\") |> names()\n[1] \"time\"            \"eff.sample.size\"\n> smc |> eff_sample_size(format=\"d\") |> sapply(class)\n           time eff.sample.size \n      \"numeric\"       \"numeric\" \n> smc |> cond_logLik(format=\"d\") |> names()\n[1] \"time\"              \"cond_log.evidence\"\n> smc |> cond_logLik(format=\"d\") |> sapply(class)\n             time cond_log.evidence \n        \"numeric\"         \"numeric\" \n> \n> try(bsmc2())\nError : in 'bsmc2': 'data' is a required argument.\n> try(bsmc2(3L))\nError : 'bsmc2' is undefined for 'data' of class 'integer'.\n> \n> po <- smc\n> coef(po) <- NULL\n> try(bsmc2(smc))\nError : in 'bsmc2': 'Np' must be specified.\n> try(bsmc2(po))\nError : in 'bsmc2': 'Np' must be specified.\n> try(bsmc2(po,params=NULL))\nError : in 'bsmc2': 'Np' must be specified.\n> try(bsmc2(po,params=\"yes\"))\nError : in 'bsmc2': 'params' must be a named numeric vector.\nIn addition: Warning message:\nNAs introduced by coercion \n> try(bsmc2(po,params=list()))\nError : in 'bsmc2': 'Np' must be specified.\n> try(bsmc2(po,params=c(1,2,3)))\nError : in 'bsmc2': 'params' must be a named numeric vector.\n> theta <- coef(smc)\n> try(bsmc2(po,params=as.list(theta)))\nError : in 'bsmc2': 'Np' must be specified.\n> try(bsmc2(po,params=as.list(theta),Np=1))\nError : in 'bsmc2': no parameters to estimate\n> try(bsmc2(smc,Np=-10))\nError : in 'bsmc2': number of particles, 'Np', must be a positive integer.\n> try(bsmc2(smc,params=theta,Np=100,\n+   dmeasure=Csnippet(\"error(\\\"whoa nelly!\\\");\")))\nError : in 'bsmc2': in 'dmeasure': whoa nelly!\n> try(bsmc2(smc,Np=100,smooth=5))\nError : in 'bsmc2': 'smooth' must be a scalar in (0,1]\n> try(bsmc2(smc,Np=100,smooth=NA))\nError : in 'bsmc2': 'smooth' must be a scalar in (0,1]\n> try(bsmc2(smc,Np=100,smooth=-2))\nError : in 'bsmc2': 'smooth' must be a scalar in (0,1]\n> try(bsmc2(smc,Np=100,smooth=NULL))\nError : in 'bsmc2': 'smooth' must be a scalar in (0,1]\n> try(bsmc2(smc,Np=100,smooth=Inf))\nError : in 'bsmc2': 'smooth' must be a scalar in (0,1]\n> try(bsmc2(smc,Np=100,smooth=\"yes\"))\nError : in 'bsmc2': 'smooth' must be a scalar in (0,1]\n> try(bsmc2(smc,Np=100,smooth=c(1,2)))\nError : in 'bsmc2': 'smooth' must be a scalar in (0,1]\n> try(bsmc2(smc,Np=100,smooth=list(1,2)))\nError : in 'bsmc2': 'smooth' must be a scalar in (0,1]\n> try(bsmc2(smc,Np=100,rprocess=NULL))\nError : in 'bsmc2': 'rprior', 'rprocess', 'dmeasure' are needed basic components.\n> try(bsmc2(smc,Np=100,params=NULL))\nError : in 'bsmc2': in 'rprior': variable 'r' not found among the parameters.\n> try(bsmc2(smc,Np=100,dmeasure=NULL))\nError : in 'bsmc2': 'rprior', 'rprocess', 'dmeasure' are needed basic components.\n> try(bsmc2(smc,Np=100,rprior=NULL))\nError : in 'bsmc2': 'rprior', 'rprocess', 'dmeasure' are needed basic components.\n> \n> theta <- coef(gompertz)\n> theta[\"K\"] <- 1\n> try(capture.output(bsmc2(po,Np=2,params=theta,verbose=TRUE)) -> out)\n> \n> smc |> as.data.frame() |>\n+   filter(.id==\"posterior\") |>\n+   select(-.id) -> pp\n> \n> gompertz |>\n+   as.data.frame() |>\n+   subset(select=-X) |>\n+   bsmc2(\n+     times=\"time\",t0=-5,\n+     params=coef(gompertz),\n+     Np=1000,smooth=0.1,\n+     rprior=Csnippet(\"\n+       K = runif(0.1,1);\n+       r = rlnorm(log(0.2),1);\n+       sigma = rlnorm(log(0.1),0.5);\"),\n+     rprocess=gompertz@rprocess,\n+     dmeasure=gompertz@dmeasure,\n+     statenames=c(\"X\"),\n+     paramnames=c(\"r\",\"K\",\"sigma\")) -> smc4\n> smc4 |> plot()\n> \n> try(gompertz |>\n+     as.data.frame() |>\n+     subset(select=-X) |>\n+     bsmc2(\n+       times=\"time\",t0=-5,\n+       params=coef(gompertz),\n+       Np=1000,smooth=0.1,\n+       rprior=3,\n+       rprocess=gompertz@rprocess,\n+       dmeasure=gompertz@dmeasure,\n+       statenames=c(\"X\"),\n+       paramnames=c(\"r\",\"K\",\"sigma\")))\nError : in 'bsmc2': bad option for 'rprior' argument.\n> \n> smc |>\n+   bsmc2(Np=seq(10,length=12,by=10)) |>\n+   eff_sample_size()\n [1]  5.3 14.3 21.1 17.4 11.3 18.6 32.9 61.0 61.1 34.3\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/bsplines1.R",
    "content": "options(digits=3)\npng(filename=\"bsplines1-%02d.png\",res=100)\nlibrary(pomp)\n\nx <- seq(0,2,by=0.01)\ntry(y <- bspline_basis(x,degree=3,nbasis=9,names=c(\"basis1\",\"basis2\")))\ny <- bspline_basis(x,degree=3,nbasis=9)\ntry(y <- bspline_basis(x,degree=3,nbasis=3,names=letters[1:3]))\ny <- bspline_basis(x,degree=3,nbasis=12,names=letters[1:12])\ny <- bspline_basis(x,degree=3,nbasis=9,names=\"basis\")\ny <- bspline_basis(x,degree=3,nbasis=9,names=\"basis%02d\")\nmatplot(x,y,type=\"l\",ylim=c(0,1.1))\nlines(x,apply(y,1,sum),lwd=2)\n\nx <- seq(-1,2,by=0.01)\ntry(y <- periodic_bspline_basis(x,nbasis=6,names=letters[1:2]))\ny <- periodic_bspline_basis(x,nbasis=6,names=tail(letters,6))\ny <- periodic_bspline_basis(x,nbasis=5,names=\"spline\")\ny <- periodic_bspline_basis(x,nbasis=5,names=\"spline%d\")\nmatplot(x,y,type=\"l\")\n\nx <- seq(0,1,length=5)\ntry(bspline_basis(x,degree=-1,nbasis=9))\ntry(bspline_basis(x,degree=5,nbasis=3))\ntry(bspline_basis(x,degree=4,nbasis=30,deriv=-5))\ntry(periodic_bspline_basis(x,degree=-1,nbasis=9))\ntry(periodic_bspline_basis(x,degree=5,nbasis=4))\ntry(periodic_bspline_basis(x,degree=4,nbasis=5,deriv=-1))\n\n## now test derivatives\ndeg <- 5\nnb <- 10\ndx <- 0.001\n\nx <- seq(0,1,by=dx)\nB <- bspline_basis(x,nbasis=nb,degree=deg)\nd <- bspline_basis(x,nbasis=nb,degree=deg,deriv=1)\nd2 <- bspline_basis(x,nbasis=nb,degree=deg,deriv=2)\n\nB <- apply(B,2,function(x)x-x[1])\ndd <- apply(d,2,function(x){y <- diffinv(x); (head(y,-1)+tail(y,-1))/2*dx})\nmatplot(B,dd,type=\"l\")\nabline(a=0,b=1)\nstopifnot(all(signif(diag(cor(B,dd)),6)==1))\n\nd <- apply(d,2,function(x) x-x[1])\ndd <- apply(d2,2,function(x){y <- diffinv(x); (head(y,-1)+tail(y,-1))/2*dx})\nmatplot(d,dd,type=\"l\")\nabline(a=0,b=1)\nstopifnot(all(signif(diag(cor(d,dd)),6)==1))\n\nx <- seq(0,2,by=dx)\nB <- periodic_bspline_basis(x,nbasis=nb,degree=deg)\nd <- periodic_bspline_basis(x,nbasis=nb,degree=deg,deriv=1)\nd2<- periodic_bspline_basis(x,nbasis=nb,degree=deg,deriv=2)\n\nB <- apply(B,2,function(x)x-x[1])\ndd <- apply(d,2,function(x){y <- diffinv(x); (head(y,-1)+tail(y,-1))/2*dx})\nmatplot(B,dd,type=\"l\")\nabline(a=0,b=1)\nstopifnot(all(signif(diag(cor(B,dd)),6)==1))\n\nd <- apply(d,2,function(x) x-x[1])\ndd <- apply(d2,2,function(x){y <- diffinv(x); (head(y,-1)+tail(y,-1))/2*dx})\nmatplot(d,dd,type=\"l\")\nabline(a=0,b=1)\nstopifnot(all(signif(diag(cor(d,dd)),6)==1))\n\nB <- bspline_basis(x,degree=0,nbasis=4)\nB <- bspline_basis(x,degree=0,nbasis=4,deriv=1)\nstopifnot(isTRUE(all(B==0)))\nB <- periodic_bspline_basis(x,degree=8,nbasis=30,deriv=11)\nstopifnot(isTRUE(all(B==0)))\n\ntry(bspline_basis(x,degree=1,nbasis=6,rg=c(4,3)))\ntry(bspline_basis(x,degree=1,nbasis=6,rg=c(4,4)))\nB <- bspline_basis(x,degree=1,nbasis=6,rg=c(-1,3))\nmatplot(x,B,type=\"l\")\n\ndev.off()\n"
  },
  {
    "path": "tests/bsplines1.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"bsplines1-%02d.png\",res=100)\n> library(pomp)\n> \n> x <- seq(0,2,by=0.01)\n> try(y <- bspline_basis(x,degree=3,nbasis=9,names=c(\"basis1\",\"basis2\")))\nError : in 'bspline_basis': 'names' must be of length 1 or 9\n> y <- bspline_basis(x,degree=3,nbasis=9)\n> try(y <- bspline_basis(x,degree=3,nbasis=3,names=letters[1:3]))\nError : in 'bspline_basis': must have nbasis > degree\n> y <- bspline_basis(x,degree=3,nbasis=12,names=letters[1:12])\n> y <- bspline_basis(x,degree=3,nbasis=9,names=\"basis\")\n> y <- bspline_basis(x,degree=3,nbasis=9,names=\"basis%02d\")\n> matplot(x,y,type=\"l\",ylim=c(0,1.1))\n> lines(x,apply(y,1,sum),lwd=2)\n> \n> x <- seq(-1,2,by=0.01)\n> try(y <- periodic_bspline_basis(x,nbasis=6,names=letters[1:2]))\nError : in 'periodic_bspline_basis': 'names' must be of length 1 or 6\n> y <- periodic_bspline_basis(x,nbasis=6,names=tail(letters,6))\n> y <- periodic_bspline_basis(x,nbasis=5,names=\"spline\")\n> y <- periodic_bspline_basis(x,nbasis=5,names=\"spline%d\")\n> matplot(x,y,type=\"l\")\n> \n> x <- seq(0,1,length=5)\n> try(bspline_basis(x,degree=-1,nbasis=9))\nError : in 'bspline_basis': must have degree > 0\n> try(bspline_basis(x,degree=5,nbasis=3))\nError : in 'bspline_basis': must have nbasis > degree\n> try(bspline_basis(x,degree=4,nbasis=30,deriv=-5))\nError : in 'bspline_basis': must have deriv >= 0\n> try(periodic_bspline_basis(x,degree=-1,nbasis=9))\nError : in 'periodic_bspline_basis': must have degree >= 0\n> try(periodic_bspline_basis(x,degree=5,nbasis=4))\nError : in 'periodic_bspline_basis': must have nbasis >= degree\n> try(periodic_bspline_basis(x,degree=4,nbasis=5,deriv=-1))\nError : in 'periodic_bspline_basis': must have deriv >= 0\n> \n> ## now test derivatives\n> deg <- 5\n> nb <- 10\n> dx <- 0.001\n> \n> x <- seq(0,1,by=dx)\n> B <- bspline_basis(x,nbasis=nb,degree=deg)\n> d <- bspline_basis(x,nbasis=nb,degree=deg,deriv=1)\n> d2 <- bspline_basis(x,nbasis=nb,degree=deg,deriv=2)\n> \n> B <- apply(B,2,function(x)x-x[1])\n> dd <- apply(d,2,function(x){y <- diffinv(x); (head(y,-1)+tail(y,-1))/2*dx})\n> matplot(B,dd,type=\"l\")\n> abline(a=0,b=1)\n> stopifnot(all(signif(diag(cor(B,dd)),6)==1))\n> \n> d <- apply(d,2,function(x) x-x[1])\n> dd <- apply(d2,2,function(x){y <- diffinv(x); (head(y,-1)+tail(y,-1))/2*dx})\n> matplot(d,dd,type=\"l\")\n> abline(a=0,b=1)\n> stopifnot(all(signif(diag(cor(d,dd)),6)==1))\n> \n> x <- seq(0,2,by=dx)\n> B <- periodic_bspline_basis(x,nbasis=nb,degree=deg)\n> d <- periodic_bspline_basis(x,nbasis=nb,degree=deg,deriv=1)\n> d2<- periodic_bspline_basis(x,nbasis=nb,degree=deg,deriv=2)\n> \n> B <- apply(B,2,function(x)x-x[1])\n> dd <- apply(d,2,function(x){y <- diffinv(x); (head(y,-1)+tail(y,-1))/2*dx})\n> matplot(B,dd,type=\"l\")\n> abline(a=0,b=1)\n> stopifnot(all(signif(diag(cor(B,dd)),6)==1))\n> \n> d <- apply(d,2,function(x) x-x[1])\n> dd <- apply(d2,2,function(x){y <- diffinv(x); (head(y,-1)+tail(y,-1))/2*dx})\n> matplot(d,dd,type=\"l\")\n> abline(a=0,b=1)\n> stopifnot(all(signif(diag(cor(d,dd)),6)==1))\n> \n> B <- bspline_basis(x,degree=0,nbasis=4)\n> B <- bspline_basis(x,degree=0,nbasis=4,deriv=1)\nWarning message:\nin 'bspline_basis': returning 0 since 'deriv' > 'degree' \n> stopifnot(isTRUE(all(B==0)))\n> B <- periodic_bspline_basis(x,degree=8,nbasis=30,deriv=11)\nWarning message:\nin 'periodic_bspline_basis': returning 0 since 'deriv' > 'degree' \n> stopifnot(isTRUE(all(B==0)))\n> \n> try(bspline_basis(x,degree=1,nbasis=6,rg=c(4,3)))\nError : in 'bspline_basis': improper range 'rg'\n> try(bspline_basis(x,degree=1,nbasis=6,rg=c(4,4)))\nError : in 'bspline_basis': improper range 'rg'\n> B <- bspline_basis(x,degree=1,nbasis=6,rg=c(-1,3))\n> matplot(x,B,type=\"l\")\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/bsplines2.R",
    "content": "options(digits=3)\npng(filename=\"bsplines2-%02d.png\",res=100)\nlibrary(tidyr)\nlibrary(dplyr)\nlibrary(ggplot2)\nlibrary(pomp)\n\ntrajectory(\n  t0=0, times=seq(0,2,by=0.02),\n  skeleton=vectorfield(Csnippet(r\"{\n    const double *a = &a1;\n    double knots[] = {-3, -2, -1, 0, 1, 2, 3, 4, 5};\n    double s[5], p[5];\n    bspline_basis_eval(t,knots,3,5,s);\n    periodic_bspline_basis_eval(t,1,3,5,p);\n    Dx = dot_product(5,a,s);\n    Dy = dot_product(5,a,&trend_1);\n    Dz = dot_product(5,a,p);\n    Dw = dot_product(5,a,&seas_1);\n  }\")),\n  params = c(\n    a1=-1,a2=1,a3=0,a4=-3,a5=18,\n    x_0=0,y_0=0,z_0=0,w_0=0\n  ),\n  paramnames=c(\"a1\",\"a2\",\"a3\"),\n  statenames=c(\"x\",\"y\",\"w\",\"z\"),\n  covar=covariate_table(\n    times=seq(0,2.1,by=0.001),\n    trend=bspline_basis(x=times,nbasis=5,degree=3,rg=c(0,2)),\n    seas=periodic_bspline_basis(x=times,period=1,nbasis=5,degree=3)\n  )\n) |>\n  plot()\n\ntrajectory(\n  t0=0, times=seq(0,2,by=0.02),\n  skeleton=vectorfield(Csnippet(r\"{\n    const double *a = &a1;\n    double knots[] = {-3, -2, -1, 0, 1, 2, 3, 4, 5};\n    double s[5], p[5];\n    bspline_basis_eval_deriv(t,knots,3,5,1,s);\n    periodic_bspline_basis_eval_deriv(t,1,3,5,1,p);\n    Dx = dot_product(5,a,s);\n    Dy = dot_product(5,a,&trend_1);\n    Dz = dot_product(5,a,p);\n    Dw = dot_product(5,a,&seas_1);\n  }\")),\n  params = c(\n    a1=-1,a2=1,a3=0,a4=-3,a5=18,\n    x_0=0,y_0=0,z_0=0,w_0=0\n  ),\n  paramnames=c(\"a1\",\"a2\",\"a3\"),\n  statenames=c(\"x\",\"y\",\"w\",\"z\"),\n  covar=covariate_table(\n    times=seq(0,2.1,by=0.001),\n    trend=bspline_basis(x=times,nbasis=5,degree=3,deriv=1,rg=c(0,2)),\n    seas=periodic_bspline_basis(x=times,period=1,deriv=1,nbasis=5,degree=3)\n  )\n) |>\n  as.data.frame() |>\n  select(time,x,y,z,w) |>\n  pivot_longer(-time) -> dat\n\ncovariate_table(\n  times=seq(0,2.1,by=0.001),\n  trend=bspline_basis(x=times,nbasis=5,degree=3,deriv=0,rg=c(0,2)),\n  seas=periodic_bspline_basis(x=times,period=1,deriv=0,nbasis=5,degree=3)\n) -> x\n\nx@table |>\n  melt() |>\n  select(name=Var1,value,id=Var2) |>\n  left_join(\n    x@times |> melt() |> rename(time=value),\n    by=c(\"id\"=\"name\")\n  ) |>\n  select(-id) |>\n  separate(col=name,into=c(\"name\",\"fn\")) |>\n  mutate(\n    fn=as.integer(fn),\n    value=c(a1=-1,a2=1,a3=0,a4=-3,a5=18)[fn]*value\n  ) |>\n  group_by(name,time) |>\n  summarize(value=sum(value)) |>\n  ungroup() |>\n  arrange(name,time) |>\n  group_by(name) |>\n  mutate(value=value-value[1]) |>\n  ungroup() -> x\n\ndat |>\n  bind_rows(x) |>\n  filter(time<=2) |>\n  mutate(name=factor(name,levels=c(\"trend\",\"seas\",\"x\",\"w\",\"y\",\"z\"))) |>\n  ggplot(aes(x=time,y=value))+\n  geom_line()+\n  facet_wrap(~name,ncol=2,scales=\"free_y\")+\n  theme_bw()\n\ndev.off()\n"
  },
  {
    "path": "tests/bsplines2.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"bsplines2-%02d.png\",res=100)\n> library(tidyr)\n> library(dplyr)\n\nAttaching package: 'dplyr'\n\nThe following objects are masked from 'package:stats':\n\n    filter, lag\n\nThe following objects are masked from 'package:base':\n\n    intersect, setdiff, setequal, union\n\n> library(ggplot2)\n> library(pomp)\n> \n> trajectory(\n+   t0=0, times=seq(0,2,by=0.02),\n+   skeleton=vectorfield(Csnippet(r\"{\n+     const double *a = &a1;\n+     double knots[] = {-3, -2, -1, 0, 1, 2, 3, 4, 5};\n+     double s[5], p[5];\n+     bspline_basis_eval(t,knots,3,5,s);\n+     periodic_bspline_basis_eval(t,1,3,5,p);\n+     Dx = dot_product(5,a,s);\n+     Dy = dot_product(5,a,&trend_1);\n+     Dz = dot_product(5,a,p);\n+     Dw = dot_product(5,a,&seas_1);\n+   }\")),\n+   params = c(\n+     a1=-1,a2=1,a3=0,a4=-3,a5=18,\n+     x_0=0,y_0=0,z_0=0,w_0=0\n+   ),\n+   paramnames=c(\"a1\",\"a2\",\"a3\"),\n+   statenames=c(\"x\",\"y\",\"w\",\"z\"),\n+   covar=covariate_table(\n+     times=seq(0,2.1,by=0.001),\n+     trend=bspline_basis(x=times,nbasis=5,degree=3,rg=c(0,2)),\n+     seas=periodic_bspline_basis(x=times,period=1,nbasis=5,degree=3)\n+   )\n+ ) |>\n+   plot()\n> \n> trajectory(\n+   t0=0, times=seq(0,2,by=0.02),\n+   skeleton=vectorfield(Csnippet(r\"{\n+     const double *a = &a1;\n+     double knots[] = {-3, -2, -1, 0, 1, 2, 3, 4, 5};\n+     double s[5], p[5];\n+     bspline_basis_eval_deriv(t,knots,3,5,1,s);\n+     periodic_bspline_basis_eval_deriv(t,1,3,5,1,p);\n+     Dx = dot_product(5,a,s);\n+     Dy = dot_product(5,a,&trend_1);\n+     Dz = dot_product(5,a,p);\n+     Dw = dot_product(5,a,&seas_1);\n+   }\")),\n+   params = c(\n+     a1=-1,a2=1,a3=0,a4=-3,a5=18,\n+     x_0=0,y_0=0,z_0=0,w_0=0\n+   ),\n+   paramnames=c(\"a1\",\"a2\",\"a3\"),\n+   statenames=c(\"x\",\"y\",\"w\",\"z\"),\n+   covar=covariate_table(\n+     times=seq(0,2.1,by=0.001),\n+     trend=bspline_basis(x=times,nbasis=5,degree=3,deriv=1,rg=c(0,2)),\n+     seas=periodic_bspline_basis(x=times,period=1,deriv=1,nbasis=5,degree=3)\n+   )\n+ ) |>\n+   as.data.frame() |>\n+   select(time,x,y,z,w) |>\n+   pivot_longer(-time) -> dat\n> \n> covariate_table(\n+   times=seq(0,2.1,by=0.001),\n+   trend=bspline_basis(x=times,nbasis=5,degree=3,deriv=0,rg=c(0,2)),\n+   seas=periodic_bspline_basis(x=times,period=1,deriv=0,nbasis=5,degree=3)\n+ ) -> x\n> \n> x@table |>\n+   melt() |>\n+   select(name=Var1,value,id=Var2) |>\n+   left_join(\n+     x@times |> melt() |> rename(time=value),\n+     by=c(\"id\"=\"name\")\n+   ) |>\n+   select(-id) |>\n+   separate(col=name,into=c(\"name\",\"fn\")) |>\n+   mutate(\n+     fn=as.integer(fn),\n+     value=c(a1=-1,a2=1,a3=0,a4=-3,a5=18)[fn]*value\n+   ) |>\n+   group_by(name,time) |>\n+   summarize(value=sum(value)) |>\n+   ungroup() |>\n+   arrange(name,time) |>\n+   group_by(name) |>\n+   mutate(value=value-value[1]) |>\n+   ungroup() -> x\n`summarise()` has grouped output by 'name'. You can override using the\n`.groups` argument.\n> \n> dat |>\n+   bind_rows(x) |>\n+   filter(time<=2) |>\n+   mutate(name=factor(name,levels=c(\"trend\",\"seas\",\"x\",\"w\",\"y\",\"z\"))) |>\n+   ggplot(aes(x=time,y=value))+\n+   geom_line()+\n+   facet_wrap(~name,ncol=2,scales=\"free_y\")+\n+   theme_bw()\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/concat.R",
    "content": "options(digits=3)\n\nlibrary(pomp)\n\ntry(pomp:::conc())\ntry(pomp:::conc(\"a\",\"b\"))\n\ngompertz() -> gompertz\nou2() -> ou2\npomp:::conc(a=ou2,c(b=gompertz,c=ou2))\nc(a=ou2,c(b=gompertz,c=ou2)) |> class()\nc(a=ou2,b=ou2(alpha_1=-11)) -> pomps\npomps |> coef()\npomps |> obs(vars=\"y1\") |> melt() |> head()\npomps |> states(vars=\"x2\") |> melt() |> head()\n\nreplicate(2,pfilter(gompertz,Np=10)) |> class()\ndo.call(c,replicate(2,pfilter(gompertz,Np=10))) -> pfs\npfs |> class()\nc(a=pfs[[1]],b=pfs) -> pfs\npfs\ntime(pfs) -> tt\nstates(pfs) -> ss\nobs(pfs) -> oo\ncoef(pfs) -> cc\nstopifnot(\n  is.list(tt),\n  names(tt)==names(pfs),\n  sapply(tt,length)==100,\n  is.list(ss),\n  names(ss)==names(pfs),\n  sapply(ss,dim)==c(1,100),\n  is.list(oo),\n  names(oo)==names(pfs),\n  sapply(oo,dim)==c(1,100),\n  is.matrix(cc),\n  dim(cc)==c(5,3),\n  rownames(cc)==names(coef(pfs[[1]])),\n  colnames(cc)==names(pfs)\n)\n"
  },
  {
    "path": "tests/concat.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> \n> library(pomp)\n> \n> try(pomp:::conc())\nError : 'c' is not defined for objects of class 'missing'.\n> try(pomp:::conc(\"a\",\"b\"))\nError : 'c' is not defined for objects of class 'character'.\n> \n> gompertz() -> gompertz\n> ou2() -> ou2\n> pomp:::conc(a=ou2,c(b=gompertz,c=ou2))\n$a\n<object of class 'pomp'>\n\n$b\n<object of class 'pomp'>\n\n$c\n<object of class 'pomp'>\n\n> c(a=ou2,c(b=gompertz,c=ou2)) |> class()\n[1] \"pompList\"\nattr(,\"package\")\n[1] \"pomp\"\n> c(a=ou2,b=ou2(alpha_1=-11)) -> pomps\n> pomps |> coef()\n         .id\nname         a     b\n  alpha_1  0.8 -11.0\n  alpha_2 -0.5  -0.5\n  alpha_3  0.3   0.3\n  alpha_4  0.9   0.9\n  sigma_1  3.0   3.0\n  sigma_2 -0.5  -0.5\n  sigma_3  2.0   2.0\n  tau      1.0   1.0\n  x1_0    -3.0  -3.0\n  x2_0     4.0   4.0\n> pomps |> obs(vars=\"y1\") |> melt() |> head()\n  .L1 name time value\n1   a   y1    1 -4.05\n2   a   y1    2  1.83\n3   a   y1    3 -1.32\n4   a   y1    4  6.64\n5   a   y1    5  6.58\n6   a   y1    6  7.54\n> pomps |> states(vars=\"x2\") |> melt() |> head()\n  .L1 name time value\n1   a   x2    1  4.25\n2   a   x2    2  6.84\n3   a   x2    3  7.59\n4   a   x2    4  6.49\n5   a   x2    5  1.84\n6   a   x2    6 -1.57\n> \n> replicate(2,pfilter(gompertz,Np=10)) |> class()\n[1] \"list\"\n> do.call(c,replicate(2,pfilter(gompertz,Np=10))) -> pfs\n> pfs |> class()\n[1] \"pfilterList\"\nattr(,\"package\")\n[1] \"pomp\"\n> c(a=pfs[[1]],b=pfs) -> pfs\n> pfs\n$a\n<object of class 'pfilterd_pomp'>\n\n$b1\n<object of class 'pfilterd_pomp'>\n\n$b2\n<object of class 'pfilterd_pomp'>\n\n> time(pfs) -> tt\n> states(pfs) -> ss\n> obs(pfs) -> oo\n> coef(pfs) -> cc\n> stopifnot(\n+   is.list(tt),\n+   names(tt)==names(pfs),\n+   sapply(tt,length)==100,\n+   is.list(ss),\n+   names(ss)==names(pfs),\n+   sapply(ss,dim)==c(1,100),\n+   is.list(oo),\n+   names(oo)==names(pfs),\n+   sapply(oo,dim)==c(1,100),\n+   is.matrix(cc),\n+   dim(cc)==c(5,3),\n+   rownames(cc)==names(coef(pfs[[1]])),\n+   colnames(cc)==names(pfs)\n+ )\n> \n"
  },
  {
    "path": "tests/covmat.R",
    "content": "options(digits=3)\n\nlibrary(pomp)\nlibrary(tidyr)\nlibrary(dplyr)\n\ngompertz() -> gompertz\n\nset.seed(1546383977L)\n\nplist <- list(\n  y1.mean=probe_mean(var=\"Y\"),\n  probe_acf(var=\"Y\",lags=c(0,4,8))\n)\n\ngompertz |>\n  probe(probes=plist,nsim=100) |>\n  as.data.frame() |>\n  filter(.id==\"sim\") |>\n  select(-.id) |>\n  pivot_longer(everything()) |>\n  group_by(name) |>\n  summarize(value=(sd(value))) |>\n  ungroup() |>\n  pivot_wider(names_from=name) |>\n  unlist() -> scale.dat\n\nabc(\n  gompertz,\n  dprior=Csnippet(\"\n    lik = dunif(K,0,2,1)+dunif(r,0,1,1)+\n      dunif(tau,0,1,1)+dunif(sigma,0,1,1);\n    lik = (give_log) ? lik : exp(lik);\"),\n  paramnames=c(\"K\",\"sigma\",\"tau\",\"r\"),\n  Nabc=100,probes=plist,\n  scale=scale.dat,epsilon=10,\n  proposal=mvn_diag_rw(c(K=0.01,r=0.01,sigma=0.01,tau=0.01))\n) -> a1\n\nreplicate(3,\n  abc(\n    a1,\n    Nabc=500,probes=plist,\n    scale=scale.dat,epsilon=10,\n    proposal=mvn_diag_rw(c(K=0.01,r=0.01,sigma=0.01,tau=0.01))\n  )) -> a1\ndo.call(c,a1) -> a1\n\ncovmat(a1[[1]]) -> v1\ncovmat(a1) -> v2\ncovmat(a1,thin=20) -> v3\nstopifnot(\n  dim(v1)==dim(v2),\n  dim(v1)==dim(v3),\n  identical(dimnames(v1),dimnames(v2)),\n  identical(dimnames(v1),dimnames(v3))\n)\n\npo <- window(gompertz,end=10)\n\nprop1 <- mvn_diag_rw(c(r=0.01,sigma=0.01))\n\nmcmc1 <- pmcmc(po,Nmcmc=100,Np=100,dprior=Csnippet(\"\n    lik = dunif(r,0,1,1)+dnorm(sigma,0,1,1);\n    lik = (give_log) ? lik : exp(lik);\"),\n  paramnames=c(\"r\",\"sigma\"),\n  proposal=prop1)\n\ncovmat(mcmc1) -> v1\ncovmat(c(mcmc1,mcmc1)) -> v2\nstopifnot(\n  dim(v1)==dim(v2),\n  identical(dimnames(v1),dimnames(v2))\n)\n"
  },
  {
    "path": "tests/covmat.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> \n> library(pomp)\n> library(tidyr)\n> library(dplyr)\n\nAttaching package: 'dplyr'\n\nThe following objects are masked from 'package:stats':\n\n    filter, lag\n\nThe following objects are masked from 'package:base':\n\n    intersect, setdiff, setequal, union\n\n> \n> gompertz() -> gompertz\n> \n> set.seed(1546383977L)\n> \n> plist <- list(\n+   y1.mean=probe_mean(var=\"Y\"),\n+   probe_acf(var=\"Y\",lags=c(0,4,8))\n+ )\n> \n> gompertz |>\n+   probe(probes=plist,nsim=100) |>\n+   as.data.frame() |>\n+   filter(.id==\"sim\") |>\n+   select(-.id) |>\n+   pivot_longer(everything()) |>\n+   group_by(name) |>\n+   summarize(value=(sd(value))) |>\n+   ungroup() |>\n+   pivot_wider(names_from=name) |>\n+   unlist() -> scale.dat\n> \n> abc(\n+   gompertz,\n+   dprior=Csnippet(\"\n+     lik = dunif(K,0,2,1)+dunif(r,0,1,1)+\n+       dunif(tau,0,1,1)+dunif(sigma,0,1,1);\n+     lik = (give_log) ? lik : exp(lik);\"),\n+   paramnames=c(\"K\",\"sigma\",\"tau\",\"r\"),\n+   Nabc=100,probes=plist,\n+   scale=scale.dat,epsilon=10,\n+   proposal=mvn_diag_rw(c(K=0.01,r=0.01,sigma=0.01,tau=0.01))\n+ ) -> a1\n> \n> replicate(3,\n+   abc(\n+     a1,\n+     Nabc=500,probes=plist,\n+     scale=scale.dat,epsilon=10,\n+     proposal=mvn_diag_rw(c(K=0.01,r=0.01,sigma=0.01,tau=0.01))\n+   )) -> a1\n> do.call(c,a1) -> a1\n> \n> covmat(a1[[1]]) -> v1\n> covmat(a1) -> v2\n> covmat(a1,thin=20) -> v3\nWarning message:\nin 'covmat': only 26 points are being used to estimate covariance matrix. \n> stopifnot(\n+   dim(v1)==dim(v2),\n+   dim(v1)==dim(v3),\n+   identical(dimnames(v1),dimnames(v2)),\n+   identical(dimnames(v1),dimnames(v3))\n+ )\n> \n> po <- window(gompertz,end=10)\n> \n> prop1 <- mvn_diag_rw(c(r=0.01,sigma=0.01))\n> \n> mcmc1 <- pmcmc(po,Nmcmc=100,Np=100,dprior=Csnippet(\"\n+     lik = dunif(r,0,1,1)+dnorm(sigma,0,1,1);\n+     lik = (give_log) ? lik : exp(lik);\"),\n+   paramnames=c(\"r\",\"sigma\"),\n+   proposal=prop1)\n> \n> covmat(mcmc1) -> v1\n> covmat(c(mcmc1,mcmc1)) -> v2\n> stopifnot(\n+   dim(v1)==dim(v2),\n+   identical(dimnames(v1),dimnames(v2))\n+ )\n> \n"
  },
  {
    "path": "tests/csnippet.R",
    "content": "library(pomp)\n\nCsnippet(\"x = x;\") -> cs\nas(cs,\"character\")\nas.character(cs)\nprint(cs)\nshow(cs)\n"
  },
  {
    "path": "tests/csnippet.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> \n> Csnippet(\"x = x;\") -> cs\n> as(cs,\"character\")\n[1] \"x = x;\"\n> as.character(cs)\n[1] \"x = x;\"\n> print(cs)\nAn object of class \"Csnippet\"\nSlot \"text\":\n[1] \"x = x;\"\n\n> show(cs)\nAn object of class \"Csnippet\"\nSlot \"text\":\n[1] \"x = x;\"\n\n> \n"
  },
  {
    "path": "tests/dacca.R",
    "content": "library(pomp)\n\nset.seed(1420306530L)\n\npng(filename=\"dacca-%02d.png\",res=100)\n\ndacca() -> po\nplot(po,yax.flip=TRUE)\ncoef(po)\n\ntheta1 <- coef(po)\ntheta2 <- partrans(po,coef(po,transform=TRUE),dir=\"from\")\n\nstopifnot(\n  all.equal(\n    theta1[1:22],\n    theta2[1:22]\n  ),\n  all.equal(\n    theta1[23:28]/sum(theta1[23:28]),\n    theta2[23:28]/sum(theta2[23:28])\n  ),\n  all.equal(\n    coef(po,transform=TRUE),\n    partrans(po,coef(po),dir=\"to\")\n  )\n)\n\npfilter(\n  window(po,end=1893),\n  Np=1000,\n  filter.mean=TRUE,\n  pred.mean=TRUE,\n  pred.var=TRUE,\n  filter.traj=TRUE,\n  save.states=\"filter\"\n) -> pf\n\nstopifnot(\n  abs(logLik(pf)+150.3)<0.05\n)\n\nplot(pf,yax.flip=TRUE)\n\npf |> window(end=1893) |> simulate() -> sm\nplot(sm,yax.flip=TRUE)\n\ntry(dacca(logbeta=c(1,2,3),logomega=c(10,20)))\n\ndev.off()\n"
  },
  {
    "path": "tests/dacca.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> \n> set.seed(1420306530L)\n> \n> png(filename=\"dacca-%02d.png\",res=100)\n> \n> dacca() -> po\n> plot(po,yax.flip=TRUE)\n> coef(po)\n       gamma          eps          rho        delta       deltaI         clin \n20.800000000 19.100000000  0.000000000  0.020000000  0.060000000  1.000000000 \n       alpha   beta_trend     logbeta1     logbeta2     logbeta3     logbeta4 \n 1.000000000 -0.004980000  0.747000000  6.380000000 -3.440000000  4.230000000 \n    logbeta5     logbeta6    logomega1    logomega2    logomega3    logomega4 \n 3.330000000  4.550000000 -1.692819521 -2.543383580 -2.840439389 -4.691817993 \n   logomega5    logomega6      sd_beta          tau          S_0          I_0 \n-8.477972478 -4.390058806  3.130000000  0.230000000  0.621000000  0.378000000 \n         Y_0         R1_0         R2_0         R3_0 \n 0.000000000  0.000843000  0.000972000  0.000000116 \n> \n> theta1 <- coef(po)\n> theta2 <- partrans(po,coef(po,transform=TRUE),dir=\"from\")\n> \n> stopifnot(\n+   all.equal(\n+     theta1[1:22],\n+     theta2[1:22]\n+   ),\n+   all.equal(\n+     theta1[23:28]/sum(theta1[23:28]),\n+     theta2[23:28]/sum(theta2[23:28])\n+   ),\n+   all.equal(\n+     coef(po,transform=TRUE),\n+     partrans(po,coef(po),dir=\"to\")\n+   )\n+ )\n> \n> pfilter(\n+   window(po,end=1893),\n+   Np=1000,\n+   filter.mean=TRUE,\n+   pred.mean=TRUE,\n+   pred.var=TRUE,\n+   filter.traj=TRUE,\n+   save.states=\"filter\"\n+ ) -> pf\n> \n> stopifnot(\n+   abs(logLik(pf)+150.3)<0.05\n+ )\n> \n> plot(pf,yax.flip=TRUE)\n> \n> pf |> window(end=1893) |> simulate() -> sm\n> plot(sm,yax.flip=TRUE)\n> \n> try(dacca(logbeta=c(1,2,3),logomega=c(10,20)))\nError : in 'dacca': 'logbeta' and 'logomega' should be of equal length.\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/dinit.R",
    "content": "library(pomp)\nset.seed(807969746L)\n\ngompertz() -> gompertz\ntheta <- coef(gompertz)\ntheta[\"X_0\"] <- 2\ngompertz |>\n  simulate(\n    dinit=function(X, X_0, t0, ...) {\n      if (X==X_0) 0 else -Inf\n    }\n  ) -> sm\n\nsm |> dinit(x=rinit(sm,nsim=5))\nsm |> dinit(params=theta,x=rinit(sm),t0=3)\nsm |> dinit(params=cbind(parmat(theta,3),coef(sm)),x=rinit(sm))\nsm |> dinit(params=theta,x=rinit(sm,nsim=5))\ntry(sm |> dinit(params=cbind(parmat(theta,2),coef(sm)),x=rinit(sm,nsim=2)))\ntry(sm |> dinit(params=cbind(parmat(theta,3),coef(sm)),x=rinit(sm,nsim=5)))\nsm |> dinit(params=cbind(parmat(theta,3),coef(sm)),x=rinit(sm,nsim=8))\n\ngompertz |>\n  simulate(\n    rinit=Csnippet(\"X = rexp(1/X_0);\"),\n    dinit=Csnippet(\"loglik = dexp(X,1/X_0,1);\"),\n    statenames=\"X\",\n    paramnames=\"X_0\"\n  ) -> sm\nsm |> dinit(x=rinit(sm,nsim=5))\nsm |> dinit(params=theta,x=rinit(sm),t0=3)\nsm |> dinit(params=cbind(parmat(theta,3),coef(sm)),x=rinit(sm))\nsm |> dinit(params=theta,x=rinit(sm,nsim=5))\ntry(sm |> dinit(params=cbind(parmat(theta,2),coef(sm)),x=rinit(sm,nsim=2)))\ntry(sm |> dinit(params=cbind(parmat(theta,3),coef(sm)),x=rinit(sm,nsim=5)))\nsm |> dinit(params=cbind(parmat(theta,3),coef(sm)),x=rinit(sm,nsim=8))\n\ntry(dinit(x=rinit(sm)))\ntry(dinit(\"bob\",x=rinit(sm)))\n\nsir() -> sir\ntheta <- coef(sir)\nsir |>\n  simulate(\n    dinit=function (S, I, R, S_0, I_0, R_0, t0,\n      seas_1, seas_2, seas_3, pop, ...) {\n      print(c(t0,seas_1+seas_2+seas_3))\n      frac <- c(S,I,R)/(S+I+R)\n      if (all(frac==c(S_0,I_0,R_0))) {\n        0\n      } else {\n        -Inf\n      }\n    }\n  ) |>\n  dinit(x=rinit(sir),params=parmat(theta,2),log=FALSE)\n\nsir |>\n  dinit(x=rinit(sir),params=parmat(theta,2),log=FALSE)\n\nricker() |>\n  dinit(\n    x=cbind(c(N=7,e=0),c(N=7,e=1),c(N=4,e=0))\n  )\n"
  },
  {
    "path": "tests/dinit.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> set.seed(807969746L)\n> \n> gompertz() -> gompertz\n> theta <- coef(gompertz)\n> theta[\"X_0\"] <- 2\n> gompertz |>\n+   simulate(\n+     dinit=function(X, X_0, t0, ...) {\n+       if (X==X_0) 0 else -Inf\n+     }\n+   ) -> sm\n> \n> sm |> dinit(x=rinit(sm,nsim=5))\n[1] 1 1 1 1 1\n> sm |> dinit(params=theta,x=rinit(sm),t0=3)\n[1] 0\n> sm |> dinit(params=cbind(parmat(theta,3),coef(sm)),x=rinit(sm))\n[1] 0 0 0 1\n> sm |> dinit(params=theta,x=rinit(sm,nsim=5))\n[1] 0 0 0 0 0\n> try(sm |> dinit(params=cbind(parmat(theta,2),coef(sm)),x=rinit(sm,nsim=2)))\nError : in 'dinit': the larger number of replicates is not a multiple of smaller.\n> try(sm |> dinit(params=cbind(parmat(theta,3),coef(sm)),x=rinit(sm,nsim=5)))\nError : in 'dinit': the larger number of replicates is not a multiple of smaller.\n> sm |> dinit(params=cbind(parmat(theta,3),coef(sm)),x=rinit(sm,nsim=8))\n[1] 0 0 0 1 0 0 0 1\n> \n> gompertz |>\n+   simulate(\n+     rinit=Csnippet(\"X = rexp(1/X_0);\"),\n+     dinit=Csnippet(\"loglik = dexp(X,1/X_0,1);\"),\n+     statenames=\"X\",\n+     paramnames=\"X_0\"\n+   ) -> sm\n> sm |> dinit(x=rinit(sm,nsim=5))\n[1] 0.94448838 0.80500760 0.31791549 0.43259382 0.05245853\n> sm |> dinit(params=theta,x=rinit(sm),t0=3)\n[1] 0.7630703\n> sm |> dinit(params=cbind(parmat(theta,3),coef(sm)),x=rinit(sm))\n[1] 0.08727601 0.08727601 0.08727601 0.20889711\n> sm |> dinit(params=theta,x=rinit(sm,nsim=5))\n[1] 0.252742110 0.729608760 0.001120369 1.054681124 1.510551471\n> try(sm |> dinit(params=cbind(parmat(theta,2),coef(sm)),x=rinit(sm,nsim=2)))\nError : in 'dinit': the larger number of replicates is not a multiple of smaller.\n> try(sm |> dinit(params=cbind(parmat(theta,3),coef(sm)),x=rinit(sm,nsim=5)))\nError : in 'dinit': the larger number of replicates is not a multiple of smaller.\n> sm |> dinit(params=cbind(parmat(theta,3),coef(sm)),x=rinit(sm,nsim=8))\n[1] 1.381070221 0.340442425 0.001317691 0.993160154 1.530700436 0.424874199\n[7] 0.010634378 0.889641078\n> \n> try(dinit(x=rinit(sm)))\nError : in 'dinit': 'object' is a required argument.\n> try(dinit(\"bob\",x=rinit(sm)))\nError : 'dinit' is undefined for 'object' of class 'character'.\n> \n> sir() -> sir\n> theta <- coef(sir)\n> sir |>\n+   simulate(\n+     dinit=function (S, I, R, S_0, I_0, R_0, t0,\n+       seas_1, seas_2, seas_3, pop, ...) {\n+       print(c(t0,seas_1+seas_2+seas_3))\n+       frac <- c(S,I,R)/(S+I+R)\n+       if (all(frac==c(S_0,I_0,R_0))) {\n+         0\n+       } else {\n+         -Inf\n+       }\n+     }\n+   ) |>\n+   dinit(x=rinit(sir),params=parmat(theta,2),log=FALSE)\n[1] 0 1\n[1] 0 1\n[1] 1 1\n> \n> sir |>\n+   dinit(x=rinit(sir),params=parmat(theta,2),log=FALSE)\n[1] NA NA\nWarning message:\n'dinit' unspecified: likelihood undefined. \n> \n> ricker() |>\n+   dinit(\n+     x=cbind(c(N=7,e=0),c(N=7,e=1),c(N=4,e=0))\n+   )\n[1] 1 1 0\n> \n"
  },
  {
    "path": "tests/dp.R",
    "content": "options(digits=3)\npng(filename=\"dp-%02d.png\",res=100)\n\nlibrary(pomp)\nsuppressPackageStartupMessages({\n  library(dplyr)\n  library(tidyr)\n  library(ggplot2)\n})\n\nset.seed(49596868L)\n\ncreate_example <- function(times = 1, t0 = 0, mu = 0.001, N_0 = 1,\n  simulator = c(\"gillespie\",\"euler\",\"onestep\")) {\n\n  v <- cbind(death = c(-1,1))\n  simulator <- match.arg(simulator)\n  switch(\n    simulator,\n    gillespie=gillespie(Csnippet(\"rate = mu * N;\"), v = v),\n    euler=euler(\n      Csnippet(\"double x = rbinom(N,1-exp(-mu*dt)); N -= x; ct += x;\"),\n      delta.t=0.1\n    ),\n    onestep=onestep(\n      Csnippet(\"double x = rbinom(N,1-exp(-mu*dt)); N -= x; ct += x;\")\n    )\n  ) -> rprocess\n\n  rinit <- Csnippet(\"N = N_0; ct = 12;\")\n\n  pomp(data=NULL, times=times, t0=t0,\n    params=c(mu=mu,N_0=N_0),\n    rprocess=rprocess, rinit=rinit, accumvars=\"ct\",\n    paramnames=c(\"mu\",\"N_0\"), statenames=c(\"N\",\"ct\"))\n}\n\ncreate_example(simulator=\"gillespie\",times=c(0,1,10,100,1000)) |>\n  simulate(format=\"data.frame\", nsim=1000) |>\n  count(time,N) |>\n  group_by(time) |>\n  mutate(freq=n/sum(n)) |>\n  ungroup() |>\n  select(-n) |>\n  pivot_wider(names_from=N,values_from=freq) |>\n  as.data.frame()\ncreate_example(times=seq(0,5,by=0.2),mu=0.01,N_0=100) |>\n  simulate(nsim=100,format=\"data.frame\") -> sims\nsims |>\n  filter(.id<=4) |>\n  pivot_longer(cols=-c(time,.id)) |>\n  ggplot(aes(x=time,y=value,group=interaction(.id,name)))+\n  geom_step()+\n  facet_grid(name~.id,scales=\"free_y\")+\n  labs(title=\"death process, Gillespie\",subtitle=expression(mu==0.01))\nstopifnot(\n(sims |>\n   group_by(.id) |>\n   mutate(s=cumsum(ct),Nn=(N+s)==100) |>\n   filter(!Nn) |>\n   nrow()) == 0\n)\n\ncreate_example(simulator=\"onestep\",times=c(0,1,10,100,1000)) |>\n  simulate(format=\"data.frame\", nsim=1000) |>\n  count(time,N) |>\n  group_by(time) |>\n  mutate(freq=n/sum(n)) |>\n  ungroup() |>\n  select(-n) |>\n  pivot_wider(names_from=N,values_from=freq) |>\n  as.data.frame()\ncreate_example(simulator=\"onestep\",\n  times=seq(0,5,by=0.2),mu=0.01,N_0=100) |>\n  simulate(nsim=100,format=\"data.frame\") -> sims\nsims |>\n  filter(.id<=4) |>\n  pivot_longer(cols=-c(time,.id)) |>\n  ggplot(aes(x=time,y=value,group=interaction(.id,name)))+\n  geom_step()+\n  facet_grid(name~.id,scales=\"free_y\")+\n  labs(title=\"death process, onestep\",subtitle=expression(mu==0.01))\nstopifnot(\n(sims |>\n   group_by(.id) |>\n   mutate(s=cumsum(ct),Nn=(N+s)==100) |>\n   filter(!Nn) |>\n   nrow()) == 0\n)\n\ncreate_example(simulator=\"euler\",times=c(0,1,10,100,1000)) |>\n  simulate(format=\"data.frame\", nsim=1000) |>\n  count(time,N) |>\n  group_by(time) |>\n  mutate(freq=n/sum(n)) |>\n  ungroup() |>\n  select(-n) |>\n  pivot_wider(names_from=N,values_from=freq) |>\n  as.data.frame()\ncreate_example(simulator=\"euler\",\n  times=seq(0,5,by=0.2),mu=0.01,N_0=100) |>\n  simulate(nsim=100,format=\"data.frame\") -> sims\nsims |>\n  filter(.id<=4) |>\n  pivot_longer(cols=-c(time,.id)) |>\n  ggplot(aes(x=time,y=value,group=interaction(.id,name)))+\n  geom_step()+\n  facet_grid(name~.id,scales=\"free_y\")+\n  labs(title=\"death process, Euler\",subtitle=expression(mu==0.01))\nstopifnot(\n(sims |>\n   group_by(.id) |>\n   mutate(s=cumsum(ct),Nn=(N+s)==100) |>\n   filter(!Nn) |>\n   nrow()) == 0\n)\n\ncreate_example(mu=1) |>\n  simulate(format=\"data.frame\", times=c(1), nsim=1000, seed=1066) |>\n  count(N) |>\n  as.data.frame()\ncreate_example(mu=1) |>\n  simulate(format=\"data.frame\", times=c(0,1), nsim=1000, seed=1066) |>\n  filter(time>0) |>\n  count(N) |>\n  as.data.frame()\ncreate_example() |>\n  simulate(format=\"data.frame\", times=c(1e4), nsim=10000, seed=1066) |>\n  count(N) |>\n  as.data.frame()\n\ncreate_example(N_0=1000,mu=0.02,simulator=\"gillespie\",\n  times=-1/0.02*log(c(1,0.8,0.6,0.4,0.2,0.01))) |>\n  simulate(format=\"data.frame\", nsim=1000, seed=374244) |>\n  ggplot(aes(x=N,group=time))+\n  geom_histogram(aes(y=after_stat(density)),binwidth=10)+\n  labs(title=\"death process, Gillespie\",subtitle=expression(mu==0.02))+\n  facet_grid(time~.,labeller=label_bquote(t==.(time)))+\n  theme(strip.text=element_text(size=6))\n\ncreate_example(N_0=1000,mu=0.02,simulator=\"onestep\",\n  times=-1/0.02*log(c(1,0.8,0.6,0.4,0.2,0.01))) |>\n  simulate(format=\"data.frame\", nsim=1000, seed=374244) |>\n  ggplot(aes(x=N,group=time))+\n  geom_histogram(aes(y=after_stat(density)),binwidth=10)+\n  labs(title=\"death process, onestep\",subtitle=expression(mu==0.02))+\n  facet_grid(time~.,labeller=label_bquote(t==.(time)))+\n  theme(strip.text=element_text(size=6))\n\ncreate_example(N_0=1000,mu=0.02,simulator=\"euler\",\n  times=-1/0.02*log(c(1,0.8,0.6,0.4,0.2,0.01))) |>\n  simulate(format=\"data.frame\", nsim=1000, seed=374244) |>\n  ggplot(aes(x=N,group=time))+\n  geom_histogram(aes(y=after_stat(density)),binwidth=10)+\n  labs(title=\"death process, Euler\",subtitle=expression(mu==0.02))+\n  facet_grid(time~.,labeller=label_bquote(t==.(time)))+\n  theme(strip.text=element_text(size=6))\n\ndev.off()\n"
  },
  {
    "path": "tests/dp.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"dp-%02d.png\",res=100)\n> \n> library(pomp)\n> suppressPackageStartupMessages({\n+   library(dplyr)\n+   library(tidyr)\n+   library(ggplot2)\n+ })\n> \n> set.seed(49596868L)\n> \n> create_example <- function(times = 1, t0 = 0, mu = 0.001, N_0 = 1,\n+   simulator = c(\"gillespie\",\"euler\",\"onestep\")) {\n+ \n+   v <- cbind(death = c(-1,1))\n+   simulator <- match.arg(simulator)\n+   switch(\n+     simulator,\n+     gillespie=gillespie(Csnippet(\"rate = mu * N;\"), v = v),\n+     euler=euler(\n+       Csnippet(\"double x = rbinom(N,1-exp(-mu*dt)); N -= x; ct += x;\"),\n+       delta.t=0.1\n+     ),\n+     onestep=onestep(\n+       Csnippet(\"double x = rbinom(N,1-exp(-mu*dt)); N -= x; ct += x;\")\n+     )\n+   ) -> rprocess\n+ \n+   rinit <- Csnippet(\"N = N_0; ct = 12;\")\n+ \n+   pomp(data=NULL, times=times, t0=t0,\n+     params=c(mu=mu,N_0=N_0),\n+     rprocess=rprocess, rinit=rinit, accumvars=\"ct\",\n+     paramnames=c(\"mu\",\"N_0\"), statenames=c(\"N\",\"ct\"))\n+ }\n> \n> create_example(simulator=\"gillespie\",times=c(0,1,10,100,1000)) |>\n+   simulate(format=\"data.frame\", nsim=1000) |>\n+   count(time,N) |>\n+   group_by(time) |>\n+   mutate(freq=n/sum(n)) |>\n+   ungroup() |>\n+   select(-n) |>\n+   pivot_wider(names_from=N,values_from=freq) |>\n+   as.data.frame()\n  time     1     0\n1    0 1.000    NA\n2    1 1.000    NA\n3   10 0.995 0.005\n4  100 0.909 0.091\n5 1000 0.345 0.655\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> create_example(times=seq(0,5,by=0.2),mu=0.01,N_0=100) |>\n+   simulate(nsim=100,format=\"data.frame\") -> sims\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> sims |>\n+   filter(.id<=4) |>\n+   pivot_longer(cols=-c(time,.id)) |>\n+   ggplot(aes(x=time,y=value,group=interaction(.id,name)))+\n+   geom_step()+\n+   facet_grid(name~.id,scales=\"free_y\")+\n+   labs(title=\"death process, Gillespie\",subtitle=expression(mu==0.01))\n> stopifnot(\n+ (sims |>\n+    group_by(.id) |>\n+    mutate(s=cumsum(ct),Nn=(N+s)==100) |>\n+    filter(!Nn) |>\n+    nrow()) == 0\n+ )\n> \n> create_example(simulator=\"onestep\",times=c(0,1,10,100,1000)) |>\n+   simulate(format=\"data.frame\", nsim=1000) |>\n+   count(time,N) |>\n+   group_by(time) |>\n+   mutate(freq=n/sum(n)) |>\n+   ungroup() |>\n+   select(-n) |>\n+   pivot_wider(names_from=N,values_from=freq) |>\n+   as.data.frame()\n  time     1     0\n1    0 1.000    NA\n2    1 0.999 0.001\n3   10 0.989 0.011\n4  100 0.899 0.101\n5 1000 0.344 0.656\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> create_example(simulator=\"onestep\",\n+   times=seq(0,5,by=0.2),mu=0.01,N_0=100) |>\n+   simulate(nsim=100,format=\"data.frame\") -> sims\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> sims |>\n+   filter(.id<=4) |>\n+   pivot_longer(cols=-c(time,.id)) |>\n+   ggplot(aes(x=time,y=value,group=interaction(.id,name)))+\n+   geom_step()+\n+   facet_grid(name~.id,scales=\"free_y\")+\n+   labs(title=\"death process, onestep\",subtitle=expression(mu==0.01))\n> stopifnot(\n+ (sims |>\n+    group_by(.id) |>\n+    mutate(s=cumsum(ct),Nn=(N+s)==100) |>\n+    filter(!Nn) |>\n+    nrow()) == 0\n+ )\n> \n> create_example(simulator=\"euler\",times=c(0,1,10,100,1000)) |>\n+   simulate(format=\"data.frame\", nsim=1000) |>\n+   count(time,N) |>\n+   group_by(time) |>\n+   mutate(freq=n/sum(n)) |>\n+   ungroup() |>\n+   select(-n) |>\n+   pivot_wider(names_from=N,values_from=freq) |>\n+   as.data.frame()\n  time     1     0\n1    0 1.000    NA\n2    1 0.995 0.005\n3   10 0.982 0.018\n4  100 0.882 0.118\n5 1000 0.355 0.645\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> create_example(simulator=\"euler\",\n+   times=seq(0,5,by=0.2),mu=0.01,N_0=100) |>\n+   simulate(nsim=100,format=\"data.frame\") -> sims\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> sims |>\n+   filter(.id<=4) |>\n+   pivot_longer(cols=-c(time,.id)) |>\n+   ggplot(aes(x=time,y=value,group=interaction(.id,name)))+\n+   geom_step()+\n+   facet_grid(name~.id,scales=\"free_y\")+\n+   labs(title=\"death process, Euler\",subtitle=expression(mu==0.01))\n> stopifnot(\n+ (sims |>\n+    group_by(.id) |>\n+    mutate(s=cumsum(ct),Nn=(N+s)==100) |>\n+    filter(!Nn) |>\n+    nrow()) == 0\n+ )\n> \n> create_example(mu=1) |>\n+   simulate(format=\"data.frame\", times=c(1), nsim=1000, seed=1066) |>\n+   count(N) |>\n+   as.data.frame()\n  N   n\n1 0 631\n2 1 369\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> create_example(mu=1) |>\n+   simulate(format=\"data.frame\", times=c(0,1), nsim=1000, seed=1066) |>\n+   filter(time>0) |>\n+   count(N) |>\n+   as.data.frame()\n  N   n\n1 0 640\n2 1 360\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> create_example() |>\n+   simulate(format=\"data.frame\", times=c(1e4), nsim=10000, seed=1066) |>\n+   count(N) |>\n+   as.data.frame()\n  N    n\n1 0 9999\n2 1    1\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> \n> create_example(N_0=1000,mu=0.02,simulator=\"gillespie\",\n+   times=-1/0.02*log(c(1,0.8,0.6,0.4,0.2,0.01))) |>\n+   simulate(format=\"data.frame\", nsim=1000, seed=374244) |>\n+   ggplot(aes(x=N,group=time))+\n+   geom_histogram(aes(y=after_stat(density)),binwidth=10)+\n+   labs(title=\"death process, Gillespie\",subtitle=expression(mu==0.02))+\n+   facet_grid(time~.,labeller=label_bquote(t==.(time)))+\n+   theme(strip.text=element_text(size=6))\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> \n> create_example(N_0=1000,mu=0.02,simulator=\"onestep\",\n+   times=-1/0.02*log(c(1,0.8,0.6,0.4,0.2,0.01))) |>\n+   simulate(format=\"data.frame\", nsim=1000, seed=374244) |>\n+   ggplot(aes(x=N,group=time))+\n+   geom_histogram(aes(y=after_stat(density)),binwidth=10)+\n+   labs(title=\"death process, onestep\",subtitle=expression(mu==0.02))+\n+   facet_grid(time~.,labeller=label_bquote(t==.(time)))+\n+   theme(strip.text=element_text(size=6))\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> \n> create_example(N_0=1000,mu=0.02,simulator=\"euler\",\n+   times=-1/0.02*log(c(1,0.8,0.6,0.4,0.2,0.01))) |>\n+   simulate(format=\"data.frame\", nsim=1000, seed=374244) |>\n+   ggplot(aes(x=N,group=time))+\n+   geom_histogram(aes(y=after_stat(density)),binwidth=10)+\n+   labs(title=\"death process, Euler\",subtitle=expression(mu==0.02))+\n+   facet_grid(time~.,labeller=label_bquote(t==.(time)))+\n+   theme(strip.text=element_text(size=6))\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/dprocess.R",
    "content": "library(pomp)\n\nou2() -> po\n\nstopifnot(\n  round(sum(dprocess(po)),3)==1.400\n)\n\ntry(\n  dprocess(po,x=states(po)[,c(1:9,15)],times=time(po)[c(1:9,15)])\n)\n"
  },
  {
    "path": "tests/dprocess.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> \n> ou2() -> po\n> \n> stopifnot(\n+   round(sum(dprocess(po)),3)==1.400\n+ )\n> \n> try(\n+   dprocess(po,x=states(po)[,c(1:9,15)],times=time(po)[c(1:9,15)])\n+ )\nError : in 'dprocess': ou2_pdf error: transitions must be consecutive\n> \n"
  },
  {
    "path": "tests/ebola.R",
    "content": "library(pomp)\nsuppressPackageStartupMessages({\n  library(dplyr)\n})\n\npng(filename=\"ebola-%02d.png\",res=100)\n\nset.seed(48832734L)\n\nebolaModel() -> po\nplot(po)\ncoef(po)\n\nebolaWA2014 |>\n  filter(\n    country==\"SLE\",\n    date<=\"2014-10-31\"\n  ) |>\n  mutate(day=as.numeric(date-as.Date(\"2014-04-30\"))) |>\n  select(-date,-country) |>\n  ebolaModel(country=\"SLE\",k=10) -> po\nplot(po)\ncoef(po)\n\nstopifnot(\n  all.equal(\n    coef(po),\n    partrans(po,coef(po,transform=TRUE),dir=\"from\")\n  ),\n  all.equal(\n    coef(po,transform=TRUE),\n    partrans(po,coef(po),dir=\"to\")\n  )\n)\n\npfilter(\n  po,\n  Np=1000,\n  filter.mean=TRUE,\n  pred.mean=TRUE,\n  pred.var=TRUE,\n  filter.traj=TRUE,\n  save.states=\"filter\"\n) -> pf\n\nlogLik(pf)\nstopifnot(\n  abs(logLik(pf)+100)<0.5\n)\n\nplot(pf,yax.flip=TRUE)\n\nsimulate(pf) -> sm\n\nplot(cases~day,data=as.data.frame(sm),type=\"l\")\nlines(deaths~day,data=as.data.frame(sm),type=\"l\",col=\"red\")\n\ntrajectory(po) -> tj\nplot(tj,var=c(\"cases\",\"deaths\",\"I\"))\n\ndev.off()\n"
  },
  {
    "path": "tests/ebola.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> suppressPackageStartupMessages({\n+   library(dplyr)\n+ })\n> \n> png(filename=\"ebola-%02d.png\",res=100)\n> \n> set.seed(48832734L)\n> \n> ebolaModel() -> po\n> plot(po)\n> coef(po)\n           N           R0          rho          cfr            k        alpha \n1.062897e+07 1.400000e+00 2.000000e-01 7.000000e-01 0.000000e+00 8.919449e-02 \n       gamma          S_0          E_0          I_0          R_0 \n1.441480e-01 9.999991e-01 4.654124e-07 4.654124e-07 1.000000e-08 \n> \n> ebolaWA2014 |>\n+   filter(\n+     country==\"SLE\",\n+     date<=\"2014-10-31\"\n+   ) |>\n+   mutate(day=as.numeric(date-as.Date(\"2014-04-30\"))) |>\n+   select(-date,-country) |>\n+   ebolaModel(country=\"SLE\",k=10) -> po\n> plot(po)\n> coef(po)\n           N           R0          rho          cfr            k        alpha \n6.190280e+06 1.400000e+00 2.000000e-01 7.000000e-01 1.000000e+01 8.919449e-02 \n       gamma          S_0          E_0          I_0          R_0 \n1.441480e-01 9.999984e-01 8.027179e-07 8.027179e-07 1.000000e-08 \n> \n> stopifnot(\n+   all.equal(\n+     coef(po),\n+     partrans(po,coef(po,transform=TRUE),dir=\"from\")\n+   ),\n+   all.equal(\n+     coef(po,transform=TRUE),\n+     partrans(po,coef(po),dir=\"to\")\n+   )\n+ )\n> \n> pfilter(\n+   po,\n+   Np=1000,\n+   filter.mean=TRUE,\n+   pred.mean=TRUE,\n+   pred.var=TRUE,\n+   filter.traj=TRUE,\n+   save.states=\"filter\"\n+ ) -> pf\n> \n> logLik(pf)\n[1] -99.72378\n> stopifnot(\n+   abs(logLik(pf)+100)<0.5\n+ )\n> \n> plot(pf,yax.flip=TRUE)\n> \n> simulate(pf) -> sm\n> \n> plot(cases~day,data=as.data.frame(sm),type=\"l\")\n> lines(deaths~day,data=as.data.frame(sm),type=\"l\",col=\"red\")\n> \n> trajectory(po) -> tj\n> plot(tj,var=c(\"cases\",\"deaths\",\"I\"))\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/emeasure.R",
    "content": "library(pomp)\n\ntry(emeasure())\ntry(emeasure(\"does this work?\"))\ntry(simulate(t0=0,times=1:10,emeasure=Csnippet(\"E_B=rho*inc;\")))\n\nou2() -> po\nemeasure(po) -> x1\nemeasure(po,x=states(po)) -> x2\nemeasure(po,x=states(po),params=coef(po)) -> x3\nstopifnot(\n  dim(x1)==c(2,1,100),\n  identical(x1,x2),\n  identical(x1,x3)\n)\ntry(emeasure(po,x=states(po),params=coef(po),times=numeric(0)))\ntry(emeasure(po,x=states(po),params=coef(po),times=c(1,2,3)))\nsimulate(po,nsim=3,format=\"arrays\") |> getElement(\"states\") -> X\ntry(emeasure(po,x=X,params=parmat(coef(po),2),times=time(po)))\npo |> simulate(emeasure=function(x1, x2, ...) x1+x2) -> po1\ntry(emeasure(po1,x=states(po1),params=coef(po1),times=time(po1)))\npo |> simulate(emeasure=function(x1, x2, t, ...)\n  setNames(rep(x1+x2,ceiling(t)),head(letters,ceiling(t)))) -> po1\ntry(emeasure(po1,x=states(po1),params=coef(po1),times=time(po1)))\npo |> simulate(emeasure=NULL) -> po1\ne <- emeasure(po1,x=states(po1),params=coef(po1),times=time(po1))\nstopifnot(\n  dim(e)==c(2,1,100),\n  sum(is.na(e))==200\n)\n\nsir() |>\n  simulate(\n    times=(1:10)/52,\n    emeasure=function(cases, rho, seas_1, seas_2, seas_3, ...)\n      c(reports=cases*rho)\n  ) -> po\ne <- emeasure(po,x=states(po)[,10],\n  params=coef(po),times=time(po)[10])\n"
  },
  {
    "path": "tests/emeasure.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> \n> try(emeasure())\nError : in 'emeasure': 'object' is a required argument.\n> try(emeasure(\"does this work?\"))\nError : 'emeasure' is undefined for 'object' of class 'character'.\n> try(simulate(t0=0,times=1:10,emeasure=Csnippet(\"E_B=rho*inc;\")))\nError : in 'simulate': when 'emeasure' is provided as a C snippet, you must also provide 'obsnames'.\n> \n> ou2() -> po\n> emeasure(po) -> x1\n> emeasure(po,x=states(po)) -> x2\n> emeasure(po,x=states(po),params=coef(po)) -> x3\n> stopifnot(\n+   dim(x1)==c(2,1,100),\n+   identical(x1,x2),\n+   identical(x1,x3)\n+ )\n> try(emeasure(po,x=states(po),params=coef(po),times=numeric(0)))\nError : in 'emeasure': length('times') = 0, no work to do.\n> try(emeasure(po,x=states(po),params=coef(po),times=c(1,2,3)))\nError : in 'emeasure': length of 'times' and 3rd dimension of 'x' do not agree.\n> simulate(po,nsim=3,format=\"arrays\") |> getElement(\"states\") -> X\n> try(emeasure(po,x=X,params=parmat(coef(po),2),times=time(po)))\nError : in 'emeasure': larger number of replicates is not a multiple of smaller.\n> po |> simulate(emeasure=function(x1, x2, ...) x1+x2) -> po1\n> try(emeasure(po1,x=states(po1),params=coef(po1),times=time(po1)))\nError : in 'emeasure': 'emeasure' must return a named numeric vector.\n> po |> simulate(emeasure=function(x1, x2, t, ...)\n+   setNames(rep(x1+x2,ceiling(t)),head(letters,ceiling(t)))) -> po1\n> try(emeasure(po1,x=states(po1),params=coef(po1),times=time(po1)))\nError : in 'emeasure': 'emeasure' returns variable-length results.\n> po |> simulate(emeasure=NULL) -> po1\n> e <- emeasure(po1,x=states(po1),params=coef(po1),times=time(po1))\nWarning message:\n'emeasure' unspecified: NAs generated. \n> stopifnot(\n+   dim(e)==c(2,1,100),\n+   sum(is.na(e))==200\n+ )\n> \n> sir() |>\n+   simulate(\n+     times=(1:10)/52,\n+     emeasure=function(cases, rho, seas_1, seas_2, seas_3, ...)\n+       c(reports=cases*rho)\n+   ) -> po\n> e <- emeasure(po,x=states(po)[,10],\n+   params=coef(po),times=time(po)[10])\n> \n"
  },
  {
    "path": "tests/eulermultinom.R",
    "content": "library(pomp)\n\nset.seed(2130639172L)\n\nreulermultinom(n=5,size=100,rate=c(1,2,3),dt=0.1)\nreulermultinom(n=5,size=-3,rate=c(1,2,3),dt=0.1)\nreulermultinom(n=5,size=100,rate=c(1,-2,3),dt=0.1)\nreulermultinom(n=5,size=100,rate=c(1,NA,3),dt=0.1)\nreulermultinom(n=5,size=100.3,rate=c(1,2,3),dt=0.1)\nreulermultinom(n=0,size=100,rate=c(1,2,3),dt=0.1)\nreulermultinom(n=5,size=100,rate=c(1,2,3),dt=Inf)\ntry(reulermultinom(n=-2,size=100,rate=c(1,2,3),dt=0.1))\nreulermultinom(n=1,size=100,rate=c(1,2e400,3),dt=0.1)\nreulermultinom(n=1,size=100,rate=c(1,2,3),dt=c(0.1,0.2,0.3,Inf))\nreulermultinom(n=1,size=c(100,200,300),rate=c(1,2,3),dt=0.2)\nreulermultinom(n=1,size=0,rate=c(1,2,3),dt=0.2)\nreulermultinom(n=1,size=10,rate=c(1,Inf,1),0.1)\nreulermultinom(n=1,size=Inf,rate=c(1,100,1),0.1)\ntry(reulermultinom(n=NA,size=100,rate=c(1,2,3),dt=1))\nreulermultinom(n=5,size=NA,rate=c(1,2,3),dt=1)\nreulermultinom(n=5,size=100,rate=c(1,NA,3),dt=1)\nreulermultinom(n=5,size=100,rate=c(1,2,3),dt=NA)\nreulermultinom(n=5,size=100,rate=c(0,0,0,0),dt=1)\n\nx <- reulermultinom(n=3,size=100,rate=c(3,2,1),dt=0.1)\ntry(deulermultinom(rbind(x,c(0,1,0)),size=100,rate=c(3,2,1),dt=0.1))\ndeulermultinom(x,size=c(100,NA),rate=c(3,2,1),dt=0.1)\ndeulermultinom(x,size=100,rate=c(3,2,1),dt=c(0.1,0.2,0.3,Inf))\ndeulermultinom(x,size=100,rate=c(3,2,1),dt=Inf)\ndeulermultinom(x=c(3,4,0),size=10,rate=c(1,1,1),dt=0-.1)\ndeulermultinom(x=c(3,4,0),size=10,rate=c(1,1,-1),dt=0.1)\ndeulermultinom(x=c(3,-4,0),size=10,rate=c(1,1,1),dt=0.1)\ndeulermultinom(x=c(3,6,3),size=10,rate=c(1,1,0),dt=0.1,log=TRUE)\n\neeulermultinom(size=100,rate=c(1,2,3),dt=0.1)\neeulermultinom(size=-3,rate=c(1,2,3),dt=0.1)\neeulermultinom(size=100,rate=c(1,-2,3),dt=0.1)\neeulermultinom(size=100,rate=c(1,NA,3),dt=0.1)\neeulermultinom(size=100.3,rate=c(1,2,3),dt=0.1)\neeulermultinom(size=100,rate=c(1,2,3),dt=0.1)\neeulermultinom(size=100,rate=c(1,2,3),dt=Inf)\neeulermultinom(size=100,rate=c(1,2e400,3),dt=0.1)\neeulermultinom(size=100,rate=c(1,2,3),dt=c(0.1,0.2,0.3,Inf))\neeulermultinom(size=100,rate=c(1,2,3),dt=c(0.1,0.2,0.3,0.5))\neeulermultinom(size=c(100,200,300),rate=c(1,2,3),dt=0.2)\neeulermultinom(size=0,rate=c(1,2,3),dt=0.2)\neeulermultinom(size=10,rate=c(1,Inf,1),0.1)\neeulermultinom(size=Inf,rate=c(1,100,1),0.1)\neeulermultinom(size=NA,rate=c(1,2,3),dt=1)\neeulermultinom(size=100,rate=c(1,NA,3),dt=1)\neeulermultinom(size=100,rate=c(1,2,3),dt=NA)\neeulermultinom(size=100,rate=c(0,0,0,0),dt=1)\n\nrgammawn(n=5,sigma=2,dt=0.1)\nrgammawn(n=5,sigma=1:5,dt=0.1)\nrgammawn(n=5,sigma=1,dt=rep(1,5))\nrgammawn(n=3,sigma=1:5,dt=rep(1,5))\nrgammawn(n=2,sigma=-5,dt=1)\nrgammawn(n=2,sigma=10,dt=-1)\nrgammawn(n=2,sigma=0,dt=1)\ntry(rgammawn(n=-5,sigma=-5,dt=-1))\n"
  },
  {
    "path": "tests/eulermultinom.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> \n> set.seed(2130639172L)\n> \n> reulermultinom(n=5,size=100,rate=c(1,2,3),dt=0.1)\n     [,1] [,2] [,3] [,4] [,5]\n[1,]    5    6    7   11    5\n[2,]   18   17   16   16   20\n[3,]   20   22   21   23   20\n> reulermultinom(n=5,size=-3,rate=c(1,2,3),dt=0.1)\n     [,1] [,2] [,3] [,4] [,5]\n[1,]   NA   NA   NA   NA   NA\n[2,]   NA   NA   NA   NA   NA\n[3,]   NA   NA   NA   NA   NA\nWarning messages:\n1: in 'reulermultinom': NAs produced. \n2: in 'reulermultinom': NAs produced. \n3: in 'reulermultinom': NAs produced. \n4: in 'reulermultinom': NAs produced. \n5: in 'reulermultinom': NAs produced. \n> reulermultinom(n=5,size=100,rate=c(1,-2,3),dt=0.1)\n     [,1] [,2] [,3] [,4] [,5]\n[1,]   NA   NA   NA   NA   NA\n[2,]   NA   NA   NA   NA   NA\n[3,]   NA   NA   NA   NA   NA\nWarning messages:\n1: in 'reulermultinom': NAs produced. \n2: in 'reulermultinom': NAs produced. \n3: in 'reulermultinom': NAs produced. \n4: in 'reulermultinom': NAs produced. \n5: in 'reulermultinom': NAs produced. \n> reulermultinom(n=5,size=100,rate=c(1,NA,3),dt=0.1)\n     [,1] [,2] [,3] [,4] [,5]\n[1,]   NA   NA   NA   NA   NA\n[2,]   NA   NA   NA   NA   NA\n[3,]   NA   NA   NA   NA   NA\nWarning messages:\n1: in 'reulermultinom': NAs produced. \n2: in 'reulermultinom': NAs produced. \n3: in 'reulermultinom': NAs produced. \n4: in 'reulermultinom': NAs produced. \n5: in 'reulermultinom': NAs produced. \n> reulermultinom(n=5,size=100.3,rate=c(1,2,3),dt=0.1)\n     [,1] [,2] [,3] [,4] [,5]\n[1,]   NA   NA   NA   NA   NA\n[2,]   NA   NA   NA   NA   NA\n[3,]   NA   NA   NA   NA   NA\nWarning messages:\n1: in 'reulermultinom': NAs produced. \n2: in 'reulermultinom': NAs produced. \n3: in 'reulermultinom': NAs produced. \n4: in 'reulermultinom': NAs produced. \n5: in 'reulermultinom': NAs produced. \n> reulermultinom(n=0,size=100,rate=c(1,2,3),dt=0.1)\n    \n[1,]\n[2,]\n[3,]\n> reulermultinom(n=5,size=100,rate=c(1,2,3),dt=Inf)\n     [,1] [,2] [,3] [,4] [,5]\n[1,]   NA   NA   NA   NA   NA\n[2,]   NA   NA   NA   NA   NA\n[3,]   NA   NA   NA   NA   NA\nWarning messages:\n1: in 'reulermultinom': NAs produced. \n2: in 'reulermultinom': NAs produced. \n3: in 'reulermultinom': NAs produced. \n4: in 'reulermultinom': NAs produced. \n5: in 'reulermultinom': NAs produced. \n> try(reulermultinom(n=-2,size=100,rate=c(1,2,3),dt=0.1))\nError : in 'reulermultinom': in 'reulermultinom': 'n' must be a non-negative integer.\n> reulermultinom(n=1,size=100,rate=c(1,2e400,3),dt=0.1)\n     [,1]\n[1,]   NA\n[2,]   NA\n[3,]   NA\nWarning message:\nin 'reulermultinom': NAs produced. \n> reulermultinom(n=1,size=100,rate=c(1,2,3),dt=c(0.1,0.2,0.3,Inf))\n     [,1]\n[1,]   11\n[2,]   16\n[3,]   25\nWarning message:\nin 'reulermultinom': only the first element of 'dt' is meaningful \n> reulermultinom(n=1,size=c(100,200,300),rate=c(1,2,3),dt=0.2)\n     [,1]\n[1,]    9\n[2,]   22\n[3,]   39\nWarning message:\nin 'reulermultinom': only the first element of 'size' is meaningful \n> reulermultinom(n=1,size=0,rate=c(1,2,3),dt=0.2)\n     [,1]\n[1,]    0\n[2,]    0\n[3,]    0\n> reulermultinom(n=1,size=10,rate=c(1,Inf,1),0.1)\n     [,1]\n[1,]   NA\n[2,]   NA\n[3,]   NA\nWarning message:\nin 'reulermultinom': NAs produced. \n> reulermultinom(n=1,size=Inf,rate=c(1,100,1),0.1)\n     [,1]\n[1,]   NA\n[2,]   NA\n[3,]   NA\nWarning message:\nin 'reulermultinom': NAs produced. \n> try(reulermultinom(n=NA,size=100,rate=c(1,2,3),dt=1))\nError : in 'reulermultinom': in 'reulermultinom': 'n' must be a non-negative integer.\n> reulermultinom(n=5,size=NA,rate=c(1,2,3),dt=1)\n     [,1] [,2] [,3] [,4] [,5]\n[1,]   NA   NA   NA   NA   NA\n[2,]   NA   NA   NA   NA   NA\n[3,]   NA   NA   NA   NA   NA\nWarning messages:\n1: in 'reulermultinom': NAs produced. \n2: in 'reulermultinom': NAs produced. \n3: in 'reulermultinom': NAs produced. \n4: in 'reulermultinom': NAs produced. \n5: in 'reulermultinom': NAs produced. \n> reulermultinom(n=5,size=100,rate=c(1,NA,3),dt=1)\n     [,1] [,2] [,3] [,4] [,5]\n[1,]   NA   NA   NA   NA   NA\n[2,]   NA   NA   NA   NA   NA\n[3,]   NA   NA   NA   NA   NA\nWarning messages:\n1: in 'reulermultinom': NAs produced. \n2: in 'reulermultinom': NAs produced. \n3: in 'reulermultinom': NAs produced. \n4: in 'reulermultinom': NAs produced. \n5: in 'reulermultinom': NAs produced. \n> reulermultinom(n=5,size=100,rate=c(1,2,3),dt=NA)\n     [,1] [,2] [,3] [,4] [,5]\n[1,]   NA   NA   NA   NA   NA\n[2,]   NA   NA   NA   NA   NA\n[3,]   NA   NA   NA   NA   NA\nWarning messages:\n1: in 'reulermultinom': NAs produced. \n2: in 'reulermultinom': NAs produced. \n3: in 'reulermultinom': NAs produced. \n4: in 'reulermultinom': NAs produced. \n5: in 'reulermultinom': NAs produced. \n> reulermultinom(n=5,size=100,rate=c(0,0,0,0),dt=1)\n     [,1] [,2] [,3] [,4] [,5]\n[1,]    0    0    0    0    0\n[2,]    0    0    0    0    0\n[3,]    0    0    0    0    0\n[4,]    0    0    0    0    0\n> \n> x <- reulermultinom(n=3,size=100,rate=c(3,2,1),dt=0.1)\n> try(deulermultinom(rbind(x,c(0,1,0)),size=100,rate=c(3,2,1),dt=0.1))\nError : in 'deulermultinom': NROW('x') should match length of 'rate'\n> deulermultinom(x,size=c(100,NA),rate=c(3,2,1),dt=0.1)\n[1] 0.0002229822 0.0008576482 0.0009731019\nWarning message:\nin 'deulermultinom': only the first element of 'size' is meaningful \n> deulermultinom(x,size=100,rate=c(3,2,1),dt=c(0.1,0.2,0.3,Inf))\n[1] 0.0002229822 0.0008576482 0.0009731019\nWarning message:\nin 'deulermultinom': only the first element of 'dt' is meaningful \n> deulermultinom(x,size=100,rate=c(3,2,1),dt=Inf)\n[1] 0 0 0\n> deulermultinom(x=c(3,4,0),size=10,rate=c(1,1,1),dt=0-.1)\n[1] NaN\nWarning message:\nin 'deulermultinom': NaNs produced. \n> deulermultinom(x=c(3,4,0),size=10,rate=c(1,1,-1),dt=0.1)\n[1] NaN\nWarning message:\nin 'deulermultinom': NaNs produced. \n> deulermultinom(x=c(3,-4,0),size=10,rate=c(1,1,1),dt=0.1)\n[1] 0\n> deulermultinom(x=c(3,6,3),size=10,rate=c(1,1,0),dt=0.1,log=TRUE)\n[1] -Inf\n> \n> eeulermultinom(size=100,rate=c(1,2,3),dt=0.1)\n[1]  7.519806 15.039612 22.559418\n> eeulermultinom(size=-3,rate=c(1,2,3),dt=0.1)\n[1] NA NA NA\nWarning message:\nin 'eeulermultinom': NAs produced. \n> eeulermultinom(size=100,rate=c(1,-2,3),dt=0.1)\n[1] NA NA NA\nWarning message:\nin 'eeulermultinom': NAs produced. \n> eeulermultinom(size=100,rate=c(1,NA,3),dt=0.1)\n[1] NA NA NA\nWarning message:\nin 'eeulermultinom': NAs produced. \n> eeulermultinom(size=100.3,rate=c(1,2,3),dt=0.1)\n[1]  7.542365 15.084731 22.627096\n> eeulermultinom(size=100,rate=c(1,2,3),dt=0.1)\n[1]  7.519806 15.039612 22.559418\n> eeulermultinom(size=100,rate=c(1,2,3),dt=Inf)\n[1] NA NA NA\nWarning message:\nin 'eeulermultinom': NAs produced. \n> eeulermultinom(size=100,rate=c(1,2e400,3),dt=0.1)\n[1] NA NA NA\nWarning message:\nin 'eeulermultinom': NAs produced. \n> eeulermultinom(size=100,rate=c(1,2,3),dt=c(0.1,0.2,0.3,Inf))\n[1]  7.519806 15.039612 22.559418\nWarning message:\nin 'eeulermultinom': only the first element of 'dt' is meaningful \n> eeulermultinom(size=100,rate=c(1,2,3),dt=c(0.1,0.2,0.3,0.5))\n[1]  7.519806 15.039612 22.559418\nWarning message:\nin 'eeulermultinom': only the first element of 'dt' is meaningful \n> eeulermultinom(size=c(100,200,300),rate=c(1,2,3),dt=0.2)\n[1] 11.64676 23.29353 34.94029\nWarning message:\nin 'eeulermultinom': only the first element of 'size' is meaningful \n> eeulermultinom(size=0,rate=c(1,2,3),dt=0.2)\n[1] 0 0 0\n> eeulermultinom(size=10,rate=c(1,Inf,1),0.1)\n[1] NA NA NA\nWarning message:\nin 'eeulermultinom': NAs produced. \n> eeulermultinom(size=Inf,rate=c(1,100,1),0.1)\n[1] NA NA NA\nWarning message:\nin 'eeulermultinom': NAs produced. \n> eeulermultinom(size=NA,rate=c(1,2,3),dt=1)\n[1] NA NA NA\nWarning message:\nin 'eeulermultinom': NAs produced. \n> eeulermultinom(size=100,rate=c(1,NA,3),dt=1)\n[1] NA NA NA\nWarning message:\nin 'eeulermultinom': NAs produced. \n> eeulermultinom(size=100,rate=c(1,2,3),dt=NA)\n[1] NA NA NA\nWarning message:\nin 'eeulermultinom': NAs produced. \n> eeulermultinom(size=100,rate=c(0,0,0,0),dt=1)\n[1] 0 0 0 0\n> \n> rgammawn(n=5,sigma=2,dt=0.1)\n[1] 2.593438e-18 2.417425e-05 5.489565e-25 1.344180e-18 3.775061e-03\n> rgammawn(n=5,sigma=1:5,dt=0.1)\n[1] 2.427178e-01 1.267494e-01 1.392075e-52 4.280372e-20 1.691824e-28\n> rgammawn(n=5,sigma=1,dt=rep(1,5))\n[1] 0.1460176 1.0105114 1.3691768 0.2244641 0.6028195\n> rgammawn(n=3,sigma=1:5,dt=rep(1,5))\n[1] 0.54660148 0.98459737 0.08619328\n> rgammawn(n=2,sigma=-5,dt=1)\n[1] 0.006126306 0.006738350\n> rgammawn(n=2,sigma=10,dt=-1)\n[1] NaN NaN\n> rgammawn(n=2,sigma=0,dt=1)\n[1] 1 1\n> try(rgammawn(n=-5,sigma=-5,dt=-1))\nError : in 'rgammwn': negative length vectors are not allowed\n> \n"
  },
  {
    "path": "tests/flow.R",
    "content": "library(pomp)\n\ntry(flow())\ntry(flow(\"bob\"))\n\nsir() -> po\n\ntry(flow(po))\ntry(flow(po,t0=0))\ntry(flow(po,t0=10))\ntry(flow(po,t0=10,times=1:10))\ntry(flow(po,t0=10,times=numeric(0)))\ntry(flow(po,t0=10,times=NULL))\ntry(flow(po,t0=10,times=30:11))\ntry(flow(po,t0=10,times=21:30))\ntry(flow(po,t0=10,times=21:30,params=coef(po)))\nflow(po,t0=0,times=1,x0=rinit(po)) -> x\n"
  },
  {
    "path": "tests/flow.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> \n> try(flow())\nError : in 'flow': 'object' is a required argument.\n> try(flow(\"bob\"))\nError : 'flow' is undefined for 'object' of class 'character'.\n> \n> sir() -> po\n> \n> try(flow(po))\nError : in 'flow': argument \"x0\" is missing, with no default\n> try(flow(po,t0=0))\nError : in 'flow': argument \"x0\" is missing, with no default\n> try(flow(po,t0=10))\nError : in 'flow': 'times[1]' must be no later than 't0'.\n> try(flow(po,t0=10,times=1:10))\nError : in 'flow': 'times[1]' must be no later than 't0'.\n> try(flow(po,t0=10,times=numeric(0)))\nError : in 'flow': 'times' is empty, there is no work to do.\n> try(flow(po,t0=10,times=NULL))\nError : in 'flow': 'times' is empty, there is no work to do.\n> try(flow(po,t0=10,times=30:11))\nError : in 'flow': 'times' must be a non-decreasing numeric sequence.\n> try(flow(po,t0=10,times=21:30))\nError : in 'flow': argument \"x0\" is missing, with no default\n> try(flow(po,t0=10,times=21:30,params=coef(po)))\nError : in 'flow': argument \"x0\" is missing, with no default\n> flow(po,t0=0,times=1,x0=rinit(po)) -> x\n> \n"
  },
  {
    "path": "tests/gillespie.R",
    "content": "options(digits=3)\npng(filename=\"gillespie-%02d.png\",res=100)\n\nlibrary(pomp)\nsuppressPackageStartupMessages({\n  library(dplyr)\n  library(tidyr)\n  library(ggplot2)\n})\n\nset.seed(754646834L)\n\nc(gamma=24,mu=1/70,iota=0.1,\n  beta1=330,beta2=410,beta3=490,\n  rho=0.1,\n  S_0=0.07,I_0=1e-4,R_0=0.93,\n  pop=1000000\n) -> params\n\ncbind(\n  birth=c(S=1,I=0,R=0,N=1,cases=0),\n  sdeath=c(-1,0,0,-1,0),\n  infection=c(-1,1,0,0,0),\n  ideath=c(0,-1,0,-1,0),\n  recovery=c(0,-1,1,0,1),\n  rdeath=c(0,0,-1,-1,0)\n) -> Vmatrix\n\nrate.fun <- function(j, N, S, I, R,\n  iota, mu, gamma, beta1, beta2, beta3,\n  seas_1, seas_2, seas_3, ...) {\n  switch(\n    j,\n    mu*N,            # birth\n    mu*S,            # susceptible death\n    {                # infection\n      beta <- beta1*seas_1+beta2*seas_2+beta3*seas_3\n      (beta*I+iota)*S/N\n    },\n    mu*I,            # infected death\n    gamma*I,         # recovery\n    mu*R,            # recovered death\n    stop(\"unrecognized event \",j)\n  ) -> r\n  r\n}\n\nsimulate(\n  params=params,\n  seed=806867104L,\n  times=seq(from=0,to=2,by=1/52),\n  t0=0,\n  rprocess=gillespie(\n    rate.fun=rate.fun,\n    v=Vmatrix,\n    hmax=1/52/10\n  ),\n  accumvars=c(\"cases\"),\n  covar=covariate_table(\n    t=seq(0,2,by=1/52/10),\n    seas=periodic_bspline_basis(\n      t,degree=3,period=1,nbasis=3),\n    times=\"t\"\n  ),\n  rmeasure=function(cases,rho,...)\n    c(reports=rbinom(n=1,size=round(cases),prob=rho)),\n  dmeasure=function(reports,cases,rho,...,log)\n    dbinom(x=reports,size=round(cases),prob=rho,log=log),\n  rinit=function (S_0, I_0, R_0, pop, ...) {\n    s <- S_0+I_0+R_0\n    c(N=pop,cases=0,round(pop/s*c(S=S_0,I=I_0,R=R_0)))\n  }\n) -> gsir\n\ngsir |>\n  simulate(accumvars=NULL) |>\n  plot(main=\"Gillespie SIR, no zeroing\")\n\ngsir |>\n  simulate(\n    rprocess=gillespie(\n      rate.fun=Csnippet(\"\n        double beta;\n        int nbasis = *get_userdata_int(\\\"nbasis\\\");\n\n        switch (j) {\n        case 1:                       // birth\n        rate = mu*pop;\n        break;\n        case 2:                       // susceptible death\n        rate = mu*S;\n        break;\n        case 3:                       // infection\n        beta = dot_product(nbasis,&seas_1,&beta1);\n        rate = (beta*I+iota)*S/pop;\n        break;\n        case 4:                       // infected death\n        rate = mu*I;\n        break;\n        case 5:                       // recovery\n        rate = gamma*I;\n        break;\n        case 6:                       // recovered death\n        rate = mu*R;\n        break;\n        }\"\n      ),\n      v=Vmatrix,\n      hmax=1/52/10\n    ),\n    userdata=list(nbasis=3L),\n    seed=806867104L,\n    paramnames=c(\"gamma\",\"mu\",\"iota\",\"beta1\",\"beta2\",\"beta3\",\"pop\",\"rho\"),\n    statenames=c(\"S\",\"I\",\"R\",\"N\",\"cases\")\n  ) -> gsir1\n\ngsir1 |>\n  plot(main=\"Gillespie SIR, with zeroing\")\n\nsir2() -> sir2\ngsir2 <- simulate(sir2,params=c(coef(gsir),k=0.01),\n  times=time(gsir),t0=timezero(gsir),seed=806867104L)\n\nbind_rows(\n  R=as.data.frame(gsir),\n  Csnippet=as.data.frame(gsir1),\n  sir2=as.data.frame(gsir2),\n  .id=\"model\"\n) |>\n  pivot_longer(-c(time,model)) |>\n  filter(name==\"reports\") |>\n  ggplot(aes(x=time,y=value,color=model))+\n  labs(color=\"\",y=\"reports\",title=\"comparison of implementations\")+\n  geom_line()+\n  theme_bw()+\n  theme(\n    legend.position=\"inside\",\n    legend.position.inside=c(0.2,0.8)\n  )\n\ntry(gillespie(rate.fun=rate.fun,v=as.numeric(Vmatrix)))\nw <- Vmatrix\ncolnames(w) <- c(letters[1:5],\"a\")\ntry(gillespie(rate.fun=rate.fun,v=w))\nw <- Vmatrix\nrownames(w) <- c(letters[1:4],\"a\")\ntry(gillespie(rate.fun=rate.fun,v=w))\ntry(gillespie_hl(a=\"bob\"))\ntry(gillespie_hl(a=list(c(\"bob\",\"mary\"),2)))\ntry(gillespie_hl(a=list(1,2)))\ntry(gillespie_hl(.pre=3,a=list(\"bob\",c(a=2,b=1))))\ntry(gillespie_hl(a=list(\"bob\",c(a=\"h\",b=\"k\"))))\ntry(gillespie_hl(a=list(\"bob\",c(2,1))))\ntry(gillespie_hl(a=list(\"bob\",list(a=2,b=1))))\ntry(gillespie_hl(a=list(\"bob\",c(a=2,1))))\ntry(gillespie_hl(a=list(\"bob\",c(a=2,b=1)),a=list(\"mary\",c(a=1,a=2))))\ntry(gillespie_hl(a=list(\"bob\",c(a=2,b=1)),a=list(\"mary\",c(a=1,c=2))))\ngillespie_hl(A=list(\"bob\",c(a=2,b=1)),B=list(\"mary\",c(a=1,c=2))) -> f\nf@v\n\nstopifnot(\n  gsir |>\n    simulate(params=c(gamma=0,mu=0,iota=0,beta1=0,beta2=0,beta3=0,\n      rho=0.1,S_0=0.07,I_0=1e-4,R_0=0.93,pop=1e6)) |>\n    states() |> apply(1,diff) == 0\n)\n\ntry(gsir |> simulate(rprocess=gillespie(rate.fun=function(j,...)1,v=Vmatrix[1:4,])))\n\nrate.fun.bad <- function(j, x, t, params, covars, ...) {\n  if (t>1) {\n    as.numeric(0)\n  } else {\n    rate.fun(j,x,t,params,covars,...)\n  }\n}\nsimulate(gsir,rprocess=gillespie(rate.fun=rate.fun.bad,v=Vmatrix)) |>\n  plot(main=\"freeze at time 1\")\n\nrate.fun.bad <- function(j, x, t, params, covars, ...) {\n  if (t>0.1) {\n    -rate.fun(j,x,t,params,covars,...)\n  } else {\n    rate.fun(j,x,t,params,covars,...)\n  }\n}\ntry(simulate(gsir,rprocess=gillespie(rate.fun=rate.fun.bad,v=Vmatrix)))\n\nrate.fun.bad <- function(j, x, t, params, covars, ...) -1\ntry(pomp(gsir,rprocess=gillespie(rate.fun=rate.fun.bad,v=Vmatrix)) |> simulate())\n\nrate.fun.bad <- function(j, x, t, params, covars, ...) c(1,1)\ntry(pomp(gsir,rprocess=gillespie(rate.fun=rate.fun.bad,v=Vmatrix)) |> simulate())\n\ntry(pomp(gsir,rprocess=gillespie(rate.fun=3,v=Vmatrix)))\n\ncreate_example <- function(times = c(1,2), t0 = 0, mu = 0.001, N_0 = 1) {\n  rate.fun <- function(j, mu, N, ...) {\n    switch(j, mu*N, stop(\"unrecognized event \",j))\n  }\n  rprocess <- gillespie(rate.fun = rate.fun, v=rbind(N=-1, ct=1))\n  initializer <- function(t0, ...) {\n    c(N=N_0,ct=12)\n  }\n  simulate(times = times, t0 = t0, params = c(mu=mu),\n    rprocess = rprocess, rinit = initializer,\n    accumvars=\"ct\", format=\"data.frame\")\n}\n\ncreate_example(times = 1)\ncreate_example(times = c(1,2))\n\ndev.off()\n"
  },
  {
    "path": "tests/gillespie.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"gillespie-%02d.png\",res=100)\n> \n> library(pomp)\n> suppressPackageStartupMessages({\n+   library(dplyr)\n+   library(tidyr)\n+   library(ggplot2)\n+ })\n> \n> set.seed(754646834L)\n> \n> c(gamma=24,mu=1/70,iota=0.1,\n+   beta1=330,beta2=410,beta3=490,\n+   rho=0.1,\n+   S_0=0.07,I_0=1e-4,R_0=0.93,\n+   pop=1000000\n+ ) -> params\n> \n> cbind(\n+   birth=c(S=1,I=0,R=0,N=1,cases=0),\n+   sdeath=c(-1,0,0,-1,0),\n+   infection=c(-1,1,0,0,0),\n+   ideath=c(0,-1,0,-1,0),\n+   recovery=c(0,-1,1,0,1),\n+   rdeath=c(0,0,-1,-1,0)\n+ ) -> Vmatrix\n> \n> rate.fun <- function(j, N, S, I, R,\n+   iota, mu, gamma, beta1, beta2, beta3,\n+   seas_1, seas_2, seas_3, ...) {\n+   switch(\n+     j,\n+     mu*N,            # birth\n+     mu*S,            # susceptible death\n+     {                # infection\n+       beta <- beta1*seas_1+beta2*seas_2+beta3*seas_3\n+       (beta*I+iota)*S/N\n+     },\n+     mu*I,            # infected death\n+     gamma*I,         # recovery\n+     mu*R,            # recovered death\n+     stop(\"unrecognized event \",j)\n+   ) -> r\n+   r\n+ }\n> \n> simulate(\n+   params=params,\n+   seed=806867104L,\n+   times=seq(from=0,to=2,by=1/52),\n+   t0=0,\n+   rprocess=gillespie(\n+     rate.fun=rate.fun,\n+     v=Vmatrix,\n+     hmax=1/52/10\n+   ),\n+   accumvars=c(\"cases\"),\n+   covar=covariate_table(\n+     t=seq(0,2,by=1/52/10),\n+     seas=periodic_bspline_basis(\n+       t,degree=3,period=1,nbasis=3),\n+     times=\"t\"\n+   ),\n+   rmeasure=function(cases,rho,...)\n+     c(reports=rbinom(n=1,size=round(cases),prob=rho)),\n+   dmeasure=function(reports,cases,rho,...,log)\n+     dbinom(x=reports,size=round(cases),prob=rho,log=log),\n+   rinit=function (S_0, I_0, R_0, pop, ...) {\n+     s <- S_0+I_0+R_0\n+     c(N=pop,cases=0,round(pop/s*c(S=S_0,I=I_0,R=R_0)))\n+   }\n+ ) -> gsir\n> \n> gsir |>\n+   simulate(accumvars=NULL) |>\n+   plot(main=\"Gillespie SIR, no zeroing\")\n> \n> gsir |>\n+   simulate(\n+     rprocess=gillespie(\n+       rate.fun=Csnippet(\"\n+         double beta;\n+         int nbasis = *get_userdata_int(\\\"nbasis\\\");\n+ \n+         switch (j) {\n+         case 1:                       // birth\n+         rate = mu*pop;\n+         break;\n+         case 2:                       // susceptible death\n+         rate = mu*S;\n+         break;\n+         case 3:                       // infection\n+         beta = dot_product(nbasis,&seas_1,&beta1);\n+         rate = (beta*I+iota)*S/pop;\n+         break;\n+         case 4:                       // infected death\n+         rate = mu*I;\n+         break;\n+         case 5:                       // recovery\n+         rate = gamma*I;\n+         break;\n+         case 6:                       // recovered death\n+         rate = mu*R;\n+         break;\n+         }\"\n+       ),\n+       v=Vmatrix,\n+       hmax=1/52/10\n+     ),\n+     userdata=list(nbasis=3L),\n+     seed=806867104L,\n+     paramnames=c(\"gamma\",\"mu\",\"iota\",\"beta1\",\"beta2\",\"beta3\",\"pop\",\"rho\"),\n+     statenames=c(\"S\",\"I\",\"R\",\"N\",\"cases\")\n+   ) -> gsir1\n> \n> gsir1 |>\n+   plot(main=\"Gillespie SIR, with zeroing\")\n> \n> sir2() -> sir2\n> gsir2 <- simulate(sir2,params=c(coef(gsir),k=0.01),\n+   times=time(gsir),t0=timezero(gsir),seed=806867104L)\n> \n> bind_rows(\n+   R=as.data.frame(gsir),\n+   Csnippet=as.data.frame(gsir1),\n+   sir2=as.data.frame(gsir2),\n+   .id=\"model\"\n+ ) |>\n+   pivot_longer(-c(time,model)) |>\n+   filter(name==\"reports\") |>\n+   ggplot(aes(x=time,y=value,color=model))+\n+   labs(color=\"\",y=\"reports\",title=\"comparison of implementations\")+\n+   geom_line()+\n+   theme_bw()+\n+   theme(\n+     legend.position=\"inside\",\n+     legend.position.inside=c(0.2,0.8)\n+   )\n> \n> try(gillespie(rate.fun=rate.fun,v=as.numeric(Vmatrix)))\nError : in 'gillespie': 'v' must be a matrix.\n> w <- Vmatrix\n> colnames(w) <- c(letters[1:5],\"a\")\n> try(gillespie(rate.fun=rate.fun,v=w))\nError : in 'gillespie': duplicates in column names of 'v'.\n> w <- Vmatrix\n> rownames(w) <- c(letters[1:4],\"a\")\n> try(gillespie(rate.fun=rate.fun,v=w))\nError : in 'gillespie': duplicates in row names of 'v'.\n> try(gillespie_hl(a=\"bob\"))\nError : in 'gillespie_hl': each event should be specified using a length-2 list.\n> try(gillespie_hl(a=list(c(\"bob\",\"mary\"),2)))\nError : in 'gillespie_hl': for each event, the first list-element should be a C snippet or string.\n> try(gillespie_hl(a=list(1,2)))\nError : in 'gillespie_hl': for each event, the first list-element should be a C snippet or string.\n> try(gillespie_hl(.pre=3,a=list(\"bob\",c(a=2,b=1))))\nError : in 'gillespie_hl': '.pre' and '.post' must be C snippets or strings.\n> try(gillespie_hl(a=list(\"bob\",c(a=\"h\",b=\"k\"))))\nError : in 'gillespie_hl': for each event, the second list-element should be a named numeric vector (without duplicate names).\n> try(gillespie_hl(a=list(\"bob\",c(2,1))))\nError : in 'gillespie_hl': for each event, the second list-element should be a named numeric vector (without duplicate names).\n> try(gillespie_hl(a=list(\"bob\",list(a=2,b=1))))\nError : in 'gillespie_hl': for each event, the second list-element should be a named numeric vector (without duplicate names).\n> try(gillespie_hl(a=list(\"bob\",c(a=2,1))))\nError : in 'gillespie_hl': for each event, the second list-element should be a named numeric vector (without duplicate names).\n> try(gillespie_hl(a=list(\"bob\",c(a=2,b=1)),a=list(\"mary\",c(a=1,a=2))))\nError : in 'gillespie_hl': for each event, the second list-element should be a named numeric vector (without duplicate names).\n> try(gillespie_hl(a=list(\"bob\",c(a=2,b=1)),a=list(\"mary\",c(a=1,c=2))))\nError : in 'gillespie_hl': duplicated elementary event names.\n> gillespie_hl(A=list(\"bob\",c(a=2,b=1)),B=list(\"mary\",c(a=1,c=2))) -> f\n> f@v\n    event\nname A B\n   a 2 1\n   b 1 0\n   c 0 2\n> \n> stopifnot(\n+   gsir |>\n+     simulate(params=c(gamma=0,mu=0,iota=0,beta1=0,beta2=0,beta3=0,\n+       rho=0.1,S_0=0.07,I_0=1e-4,R_0=0.93,pop=1e6)) |>\n+     states() |> apply(1,diff) == 0\n+ )\n> \n> try(gsir |> simulate(rprocess=gillespie(rate.fun=function(j,...)1,v=Vmatrix[1:4,])))\nError : in 'simulate': number of state variables must equal the number of rows in 'v'.\n> \n> rate.fun.bad <- function(j, x, t, params, covars, ...) {\n+   if (t>1) {\n+     as.numeric(0)\n+   } else {\n+     rate.fun(j,x,t,params,covars,...)\n+   }\n+ }\n> simulate(gsir,rprocess=gillespie(rate.fun=rate.fun.bad,v=Vmatrix)) |>\n+   plot(main=\"freeze at time 1\")\n> \n> rate.fun.bad <- function(j, x, t, params, covars, ...) {\n+   if (t>0.1) {\n+     -rate.fun(j,x,t,params,covars,...)\n+   } else {\n+     rate.fun(j,x,t,params,covars,...)\n+   }\n+ }\n> try(simulate(gsir,rprocess=gillespie(rate.fun=rate.fun.bad,v=Vmatrix)))\nError : in 'simulate': 'rate.fun' returns a negative rate\n> \n> rate.fun.bad <- function(j, x, t, params, covars, ...) -1\n> try(pomp(gsir,rprocess=gillespie(rate.fun=rate.fun.bad,v=Vmatrix)) |> simulate())\nError : in 'simulate': 'rate.fun' returns a negative rate\n> \n> rate.fun.bad <- function(j, x, t, params, covars, ...) c(1,1)\n> try(pomp(gsir,rprocess=gillespie(rate.fun=rate.fun.bad,v=Vmatrix)) |> simulate())\nError : in 'simulate': 'rate.fun' must return a single numeric rate.\n> \n> try(pomp(gsir,rprocess=gillespie(rate.fun=3,v=Vmatrix)))\nError : bad option for 'rate.fun' argument.\n> \n> create_example <- function(times = c(1,2), t0 = 0, mu = 0.001, N_0 = 1) {\n+   rate.fun <- function(j, mu, N, ...) {\n+     switch(j, mu*N, stop(\"unrecognized event \",j))\n+   }\n+   rprocess <- gillespie(rate.fun = rate.fun, v=rbind(N=-1, ct=1))\n+   initializer <- function(t0, ...) {\n+     c(N=N_0,ct=12)\n+   }\n+   simulate(times = times, t0 = t0, params = c(mu=mu),\n+     rprocess = rprocess, rinit = initializer,\n+     accumvars=\"ct\", format=\"data.frame\")\n+ }\n> \n> create_example(times = 1)\n  time .id N ct\n1    1   1 1  0\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> create_example(times = c(1,2))\n  time .id N ct\n1    1   1 1  0\n2    2   1 1  0\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/gompertz.R",
    "content": "library(pomp)\n\nset.seed(1438408329L)\n\npng(filename=\"gompertz-%02d.png\",res=100)\n\ngompertz(X_0=1.5) -> po\nplot(po)\n\nstopifnot(\n  all.equal(\n    coef(po),\n    partrans(po,coef(po,transform=TRUE),dir=\"from\")\n  ),\n  all.equal(\n    coef(po,transform=TRUE),\n    partrans(po,coef(po),dir=\"to\")\n  )\n)\n\npfilter(\n  po,\n  Np=1000,\n  filter.mean=TRUE,\n  pred.mean=TRUE,\n  pred.var=TRUE,\n  filter.traj=TRUE,\n  save.states=\"filter\"\n) -> pf\n\nstopifnot(\n  abs(logLik(pf)-30.1)<0.05\n)\n\nplot(pf,yax.flip=TRUE)\n\nforecast(pf,format=\"d\") -> fc\nsimulate(pf) -> sm\n\nemeasure(sm) -> ef\nvmeasure(sm) -> vf\nplot(ef,vf)\n\nplot(time(sm),obs(sm),xlab=\"time\",ylab=\"Y\")\nlines(time(sm),ef)\n\nenkf(po,Np=1000) -> kf\nplot(kf,yax.flip=TRUE)\n\ntrajectory(po) -> tj\nplot(tj)\n\ndev.off()\n\n"
  },
  {
    "path": "tests/gompertz.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> \n> set.seed(1438408329L)\n> \n> png(filename=\"gompertz-%02d.png\",res=100)\n> \n> gompertz(X_0=1.5) -> po\n> plot(po)\n> \n> stopifnot(\n+   all.equal(\n+     coef(po),\n+     partrans(po,coef(po,transform=TRUE),dir=\"from\")\n+   ),\n+   all.equal(\n+     coef(po,transform=TRUE),\n+     partrans(po,coef(po),dir=\"to\")\n+   )\n+ )\n> \n> pfilter(\n+   po,\n+   Np=1000,\n+   filter.mean=TRUE,\n+   pred.mean=TRUE,\n+   pred.var=TRUE,\n+   filter.traj=TRUE,\n+   save.states=\"filter\"\n+ ) -> pf\n> \n> stopifnot(\n+   abs(logLik(pf)-30.1)<0.05\n+ )\n> \n> plot(pf,yax.flip=TRUE)\n> \n> forecast(pf,format=\"d\") -> fc\n> simulate(pf) -> sm\n> \n> emeasure(sm) -> ef\n> vmeasure(sm) -> vf\n> plot(ef,vf)\n> \n> plot(time(sm),obs(sm),xlab=\"time\",ylab=\"Y\")\n> lines(time(sm),ef)\n> \n> enkf(po,Np=1000) -> kf\n> plot(kf,yax.flip=TRUE)\n> \n> trajectory(po) -> tj\n> plot(tj)\n> \n> dev.off()\nnull device \n          1 \n> \n> \n"
  },
  {
    "path": "tests/helpers.R",
    "content": "set.seed(901772384)\n\nsuppressPackageStartupMessages({\n  library(pomp)\n  library(tidyr)\n})\n\ntry(eff_sample_size())\ntry(eff_sample_size(\"bob\"))\n\ntry(filter_mean())\ntry(filter_mean(\"bob\"))\n\ntry(forecast())\ntry(forecast(\"bob\"))\n\ntry(pred_mean())\ntry(pred_mean(\"bob\"))\n\ntry(pred_var())\ntry(pred_var(\"bob\"))\n\ntry(filter_traj())\ntry(filter_traj(\"bob\"))\n\ntry(traces())\ntry(traces(\"bob\"))\n\ntry(continue())\ntry(continue(\"bob\"))\n\ntry(cond_logLik())\ntry(cond_logLik(\"bob\"))\n\ntry(coef())\ntry(coef(\"bob\"))\n\ntry(coef() <- 3)\ntry(coef(\"bob\") <- 3)\n\nc(\n  A=ou2(alpha_1=1),\n  B=ou2(tau=2,sigma_1=0)\n) |>\n  coef(\n    pars=c(\"alpha_1\",\"sigma_3\",\"sigma_1\",\"tau\")\n  )\n\nc(\n  A=ou2(alpha_1=1),\n  B=ou2(tau=2,sigma_1=0)\n) |>\n  coef(\n    bob=c(\"alpha_1\",\"sigma_3\",\"sigma_1\",\"tau\")\n  )\n\ntry(logLik())\nlogLik(\"bob\")\n\ntry(states())\ntry(states(\"bob\"))\nou2() |>\n  states(format=\"d\") |>\n  head()\nc(A=ou2(),B=gompertz()) |>\n  states(format=\"d\") |>\n  head()\n\ntry(obs())\ntry(obs(\"bob\"))\nou2() |>\n  obs(format=\"d\") |>\n  head()\nc(A=ou2(),B=gompertz()) |>\n  obs(format=\"d\") |>\n  head()\n\ntry(melt())\nmelt(\"bob\")\nx <- data.frame(\n  a=letters[1:5],\n  b=rnorm(5),\n  c=as.integer(1:5),\n  d=rexp(5)>0.1\n)\ntry(melt(x))\ntry(melt(x[1:3]))\ntry(melt(x[2:4]))\nmelt(x[2:3])\n\nnames(x) <- NULL\nmelt(x[2:3])\n\ntry(\n  list(\n    a=data.frame(x=1:3,y=rnorm(3)),\n    b=1:2,\n    c=c(\"A\",\"B\")\n  ) |> melt()\n)\ntry(\n  list(\n    a=data.frame(x=1:3,y=rnorm(3)),\n    b=1:2,\n    c=c(TRUE,FALSE)\n  ) |> melt()\n)\n\nx <- array(\n  1:15,\n  dim=c(5,3),\n  dimnames=list(X=LETTERS[12:16],letters[1:3])\n)\ny <- melt(x); y\nmelt(list(x))\nmelt(list(list(x)))\nmelt(list(t(x),x))\nnames(dimnames(x)) <- c(\"X\",\"Y\")\nz1 <- melt(list(a=x,b=x[3:5,]))\nz1 <- z1[order(z1$.L1,z1$X,z1$Y),]; z1\nz2 <- melt(list(a=x,b=x[3:5,c(2,3,1)]))\nz2 <- z2[order(z2$.L1,z2$X,z2$Y),];\nz3 <- melt(list(a=t(x),b=x[3:5,c(2,3,1)]))\nz3 <- z3[order(z3$.L1,z3$X,z3$Y),names(z2)];\nstopifnot(\n  all.equal(z1,z2,check.attributes=FALSE),\n  all.equal(z1,z3,check.attributes=FALSE)\n)\n\nlist(\n  b=c(a=5,b=2),\n  c=array(rnorm(3),dim=3,dimnames=list(name=as.character(1:3))),\n  d=array(rnorm(3),dim=3),\n  e=array(rnorm(2),dim=2,dimnames=list(name=LETTERS[14:15]))\n) |> melt()\n"
  },
  {
    "path": "tests/helpers.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> set.seed(901772384)\n> \n> suppressPackageStartupMessages({\n+   library(pomp)\n+   library(tidyr)\n+ })\n> \n> try(eff_sample_size())\nError : in 'eff_sample_size': 'object' is a required argument.\n> try(eff_sample_size(\"bob\"))\nError : 'eff_sample_size' is undefined for 'object' of class 'character'.\n> \n> try(filter_mean())\nError : in 'filter_mean': 'object' is a required argument.\n> try(filter_mean(\"bob\"))\nError : 'filter_mean' is undefined for 'object' of class 'character'.\n> \n> try(forecast())\nError : in 'forecast': 'object' is a required argument.\n> try(forecast(\"bob\"))\nError : 'forecast' is undefined for 'object' of class 'character'.\n> \n> try(pred_mean())\nError : in 'pred_mean': 'object' is a required argument.\n> try(pred_mean(\"bob\"))\nError : 'pred_mean' is undefined for 'object' of class 'character'.\n> \n> try(pred_var())\nError : in 'pred_var': 'object' is a required argument.\n> try(pred_var(\"bob\"))\nError : 'pred_var' is undefined for 'object' of class 'character'.\n> \n> try(filter_traj())\nError : in 'filter_traj': 'object' is a required argument.\n> try(filter_traj(\"bob\"))\nError : 'filter_traj' is undefined for 'object' of class 'character'.\n> \n> try(traces())\nError : in 'traces': 'object' is a required argument.\n> try(traces(\"bob\"))\nError : 'traces' is undefined for 'object' of class 'character'.\n> \n> try(continue())\nError : in 'continue': 'object' is a required argument.\n> try(continue(\"bob\"))\nError : 'continue' is undefined for 'object' of class 'character'.\n> \n> try(cond_logLik())\nError : in 'cond_logLik': 'object' is a required argument.\n> try(cond_logLik(\"bob\"))\nError : 'cond_logLik' is undefined for 'object' of class 'character'.\n> \n> try(coef())\nError in coef.default() : argument \"object\" is missing, with no default\n> try(coef(\"bob\"))\nError in object$coefficients : $ operator is invalid for atomic vectors\n> \n> try(coef() <- 3)\nError in coef() <- 3 : invalid (NULL) left side of assignment\n> try(coef(\"bob\") <- 3)\nError in coef(\"bob\") <- 3 : \n  target of assignment expands to non-language object\n> \n> c(\n+   A=ou2(alpha_1=1),\n+   B=ou2(tau=2,sigma_1=0)\n+ ) |>\n+   coef(\n+     pars=c(\"alpha_1\",\"sigma_3\",\"sigma_1\",\"tau\")\n+   )\n         .id\nname      A   B\n  alpha_1 1 0.8\n  sigma_3 2 2.0\n  sigma_1 3 0.0\n  tau     1 2.0\n> \n> c(\n+   A=ou2(alpha_1=1),\n+   B=ou2(tau=2,sigma_1=0)\n+ ) |>\n+   coef(\n+     bob=c(\"alpha_1\",\"sigma_3\",\"sigma_1\",\"tau\")\n+   )\n         .id\nname         A    B\n  alpha_1  1.0  0.8\n  alpha_2 -0.5 -0.5\n  alpha_3  0.3  0.3\n  alpha_4  0.9  0.9\n  sigma_1  3.0  0.0\n  sigma_2 -0.5 -0.5\n  sigma_3  2.0  2.0\n  tau      1.0  2.0\n  x1_0    -3.0 -3.0\n  x2_0     4.0  4.0\n> \n> try(logLik())\nError : in 'logLik': 'object' is a required argument.\n> logLik(\"bob\")\n[1] NA\n> \n> try(states())\nError : in 'states': 'object' is a required argument.\n> try(states(\"bob\"))\nError : 'states' is undefined for '\"object\"' of class 'character'.\n> ou2() |>\n+   states(format=\"d\") |>\n+   head()\n  time         x1        x2\n1    1 -3.7184616  4.249533\n2    2  0.9403927  6.843546\n3    3 -0.3725648  7.592267\n4    4  5.8085324  6.490249\n5    5  5.6054356  1.835443\n6    6  7.3546052 -1.566206\n> c(A=ou2(),B=gompertz()) |>\n+   states(format=\"d\") |>\n+   head()\n  .id time         x1        x2  X\n1   A    1 -3.7184616  4.249533 NA\n2   A    2  0.9403927  6.843546 NA\n3   A    3 -0.3725648  7.592267 NA\n4   A    4  5.8085324  6.490249 NA\n5   A    5  5.6054356  1.835443 NA\n6   A    6  7.3546052 -1.566206 NA\n> \n> try(obs())\nError : in 'obs': 'object' is a required argument.\n> try(obs(\"bob\"))\nError : 'obs' is undefined for '\"object\"' of class 'character'.\n> ou2() |>\n+   obs(format=\"d\") |>\n+   head()\n  time        y1        y2\n1    1 -4.051293 4.7806442\n2    2  1.834630 6.2733019\n3    3 -1.317003 7.5558688\n4    4  6.640487 5.7299615\n5    5  6.575312 1.5614843\n6    6  7.540323 0.1756402\n> c(A=ou2(),B=gompertz()) |>\n+   obs(format=\"d\") |>\n+   head()\n  .id time        y1        y2  Y\n1   A    1 -4.051293 4.7806442 NA\n2   A    2  1.834630 6.2733019 NA\n3   A    3 -1.317003 7.5558688 NA\n4   A    4  6.640487 5.7299615 NA\n5   A    5  6.575312 1.5614843 NA\n6   A    6  7.540323 0.1756402 NA\n> \n> try(melt())\nError : in 'melt': 'data' is a required argument.\n> melt(\"bob\")\n  name value\n1    1   bob\n> x <- data.frame(\n+   a=letters[1:5],\n+   b=rnorm(5),\n+   c=as.integer(1:5),\n+   d=rexp(5)>0.1\n+ )\n> try(melt(x))\nError : in 'melt': refusing to melt data of incompatible types.\n> try(melt(x[1:3]))\nError : in 'melt': refusing to melt data of incompatible types.\n> try(melt(x[2:4]))\nError : in 'melt': refusing to melt data of incompatible types.\n> melt(x[2:3])\n   .L1 name      value\n1    b    1 -1.5199346\n2    b    2 -0.6149350\n3    b    3 -1.2227341\n4    b    4  0.6934577\n5    b    5 -0.5857796\n6    c    1  1.0000000\n7    c    2  2.0000000\n8    c    3  3.0000000\n9    c    4  4.0000000\n10   c    5  5.0000000\n> \n> names(x) <- NULL\n> melt(x[2:3])\n   .L1 name      value\n1    1    1 -1.5199346\n2    1    2 -0.6149350\n3    1    3 -1.2227341\n4    1    4  0.6934577\n5    1    5 -0.5857796\n6    2    1  1.0000000\n7    2    2  2.0000000\n8    2    3  3.0000000\n9    2    4  4.0000000\n10   2    5  5.0000000\n> \n> try(\n+   list(\n+     a=data.frame(x=1:3,y=rnorm(3)),\n+     b=1:2,\n+     c=c(\"A\",\"B\")\n+   ) |> melt()\n+ )\nError : in 'melt': refusing to melt data of incompatible types.\n> try(\n+   list(\n+     a=data.frame(x=1:3,y=rnorm(3)),\n+     b=1:2,\n+     c=c(TRUE,FALSE)\n+   ) |> melt()\n+ )\nError : in 'melt': refusing to melt data of incompatible types.\n> \n> x <- array(\n+   1:15,\n+   dim=c(5,3),\n+   dimnames=list(X=LETTERS[12:16],letters[1:3])\n+ )\n> y <- melt(x); y\n   X Var2 value\n1  L    a     1\n2  M    a     2\n3  N    a     3\n4  O    a     4\n5  P    a     5\n6  L    b     6\n7  M    b     7\n8  N    b     8\n9  O    b     9\n10 P    b    10\n11 L    c    11\n12 M    c    12\n13 N    c    13\n14 O    c    14\n15 P    c    15\n> melt(list(x))\n   .L1 X Var2 value\n1    1 L    a     1\n2    1 M    a     2\n3    1 N    a     3\n4    1 O    a     4\n5    1 P    a     5\n6    1 L    b     6\n7    1 M    b     7\n8    1 N    b     8\n9    1 O    b     9\n10   1 P    b    10\n11   1 L    c    11\n12   1 M    c    12\n13   1 N    c    13\n14   1 O    c    14\n15   1 P    c    15\n> melt(list(list(x)))\n   .L1 .L2 X Var2 value\n1    1   1 L    a     1\n2    1   1 M    a     2\n3    1   1 N    a     3\n4    1   1 O    a     4\n5    1   1 P    a     5\n6    1   1 L    b     6\n7    1   1 M    b     7\n8    1   1 N    b     8\n9    1   1 O    b     9\n10   1   1 P    b    10\n11   1   1 L    c    11\n12   1   1 M    c    12\n13   1   1 N    c    13\n14   1   1 O    c    14\n15   1   1 P    c    15\n> melt(list(t(x),x))\n   .L1 Var1 X value Var2\n1    1    a L     1 <NA>\n2    1    b L     6 <NA>\n3    1    c L    11 <NA>\n4    1    a M     2 <NA>\n5    1    b M     7 <NA>\n6    1    c M    12 <NA>\n7    1    a N     3 <NA>\n8    1    b N     8 <NA>\n9    1    c N    13 <NA>\n10   1    a O     4 <NA>\n11   1    b O     9 <NA>\n12   1    c O    14 <NA>\n13   1    a P     5 <NA>\n14   1    b P    10 <NA>\n15   1    c P    15 <NA>\n16   2 <NA> L     1    a\n17   2 <NA> M     2    a\n18   2 <NA> N     3    a\n19   2 <NA> O     4    a\n20   2 <NA> P     5    a\n21   2 <NA> L     6    b\n22   2 <NA> M     7    b\n23   2 <NA> N     8    b\n24   2 <NA> O     9    b\n25   2 <NA> P    10    b\n26   2 <NA> L    11    c\n27   2 <NA> M    12    c\n28   2 <NA> N    13    c\n29   2 <NA> O    14    c\n30   2 <NA> P    15    c\n> names(dimnames(x)) <- c(\"X\",\"Y\")\n> z1 <- melt(list(a=x,b=x[3:5,]))\n> z1 <- z1[order(z1$.L1,z1$X,z1$Y),]; z1\n   .L1 X Y value\n1    a L a     1\n6    a L b     6\n11   a L c    11\n2    a M a     2\n7    a M b     7\n12   a M c    12\n3    a N a     3\n8    a N b     8\n13   a N c    13\n4    a O a     4\n9    a O b     9\n14   a O c    14\n5    a P a     5\n10   a P b    10\n15   a P c    15\n16   b N a     3\n19   b N b     8\n22   b N c    13\n17   b O a     4\n20   b O b     9\n23   b O c    14\n18   b P a     5\n21   b P b    10\n24   b P c    15\n> z2 <- melt(list(a=x,b=x[3:5,c(2,3,1)]))\n> z2 <- z2[order(z2$.L1,z2$X,z2$Y),];\n> z3 <- melt(list(a=t(x),b=x[3:5,c(2,3,1)]))\n> z3 <- z3[order(z3$.L1,z3$X,z3$Y),names(z2)];\n> stopifnot(\n+   all.equal(z1,z2,check.attributes=FALSE),\n+   all.equal(z1,z3,check.attributes=FALSE)\n+ )\n> \n> list(\n+   b=c(a=5,b=2),\n+   c=array(rnorm(3),dim=3,dimnames=list(name=as.character(1:3))),\n+   d=array(rnorm(3),dim=3),\n+   e=array(rnorm(2),dim=2,dimnames=list(name=LETTERS[14:15]))\n+ ) |> melt()\n   .L1 name      value Var1\n1    b    a  5.0000000   NA\n2    b    b  2.0000000   NA\n3    c    1  1.1692565   NA\n4    c    2 -1.3578778   NA\n5    c    3 -1.0923684   NA\n6    d <NA>  0.1172689    1\n7    d <NA>  0.3549312    2\n8    d <NA>  1.6241228    3\n9    e    N  1.3449047   NA\n10   e    O  0.3683851   NA\n> \n"
  },
  {
    "path": "tests/hitch.R",
    "content": "options(digits=3)\n\nlibrary(pomp)\n\ntry(hitch())\n\nhitch(templates=pomp:::workhorse_templates)\n\ntry(hitch(templates=pomp:::workhorse_templates,\n  statenames=c(\"a\",\"b\"),paramnames=c(\"b\",\"c\")))\n\nhitch(step.fn=Csnippet(\"int bob; bob = 3\"),\n  templates=pomp:::workhorse_templates,\n  compile=FALSE,cfile=\"bob\") |> names()\n\n"
  },
  {
    "path": "tests/hitch.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> \n> library(pomp)\n> \n> try(hitch())\nError : in 'hitch': 'templates' must be supplied.\n> \n> hitch(templates=pomp:::workhorse_templates)\n$funs\nlist()\n\n$lib\nNULL\n\n> \n> try(hitch(templates=pomp:::workhorse_templates,\n+   statenames=c(\"a\",\"b\"),paramnames=c(\"b\",\"c\")))\nError : in 'hitch': the variable names in 'statenames', 'paramnames', 'covarnames', and 'obsnames' must be unique and disjoint.\n> \n> hitch(step.fn=Csnippet(\"int bob; bob = 3\"),\n+   templates=pomp:::workhorse_templates,\n+   compile=FALSE,cfile=\"bob\") |> names()\n[1] \"funs\" \"lib\" \n> \n> \n"
  },
  {
    "path": "tests/issue109.R",
    "content": "library(pomp)\nset.seed(964484044)\nsir_step <- Csnippet(\"\n  double dN_SI = rbinom(S,1-exp(-exp(Beta)*(I/10000)*dt));\n  double dN_IR = rbinom(I,1-exp(-exp(mu_IR)*dt));\n  S -= dN_SI;\n  I += dN_SI - dN_IR;\n  R += dN_IR;\n  H += dN_SI;\")\nsir_init <- Csnippet(\"\n  S = 10000-1;\n  I = 1;\n  R = 0;\n  H = 0;\")\ndmeas <- Csnippet(\"\n  lik = dbinom(reports,H,1 - exp(-exp(rho)),give_log);\")\nrmeas <- Csnippet(\"\n  reports = rbinom(H,1-exp(-exp(rho)));\")\nsimulate(\n  times=1:10,\n  t0=1,\n  rmeasure = rmeas,\n  dmeasure = dmeas,\n  rprocess = discrete_time(step.fun = Csnippet(sir_step), delta.t = 1),\n  obsnames=\"reports\",\n  statenames = c(\"S\", \"I\", \"R\", \"H\"),\n  paramnames = c(\"Beta\", \"mu_IR\", \"rho\"),\n  rinit = sir_init,\n  params = c(Beta = log(1), mu_IR = log(0.1), rho = log(0.1))\n) |>\n  pmcmc(\n    Np = 1000,\n    Nmcmc = 100,\n    proposal = mvn_diag_rw(c(Beta = 5, mu_IR = 5, rho = 5))\n#    proposal = mvn_diag_rw(c(Beta = 0.2, mu_IR = 0.2, rho = 0.2))\n  ) -> pmcmcSIR\n"
  },
  {
    "path": "tests/issue109.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> set.seed(964484044)\n> sir_step <- Csnippet(\"\n+   double dN_SI = rbinom(S,1-exp(-exp(Beta)*(I/10000)*dt));\n+   double dN_IR = rbinom(I,1-exp(-exp(mu_IR)*dt));\n+   S -= dN_SI;\n+   I += dN_SI - dN_IR;\n+   R += dN_IR;\n+   H += dN_SI;\")\n> sir_init <- Csnippet(\"\n+   S = 10000-1;\n+   I = 1;\n+   R = 0;\n+   H = 0;\")\n> dmeas <- Csnippet(\"\n+   lik = dbinom(reports,H,1 - exp(-exp(rho)),give_log);\")\n> rmeas <- Csnippet(\"\n+   reports = rbinom(H,1-exp(-exp(rho)));\")\n> simulate(\n+   times=1:10,\n+   t0=1,\n+   rmeasure = rmeas,\n+   dmeasure = dmeas,\n+   rprocess = discrete_time(step.fun = Csnippet(sir_step), delta.t = 1),\n+   obsnames=\"reports\",\n+   statenames = c(\"S\", \"I\", \"R\", \"H\"),\n+   paramnames = c(\"Beta\", \"mu_IR\", \"rho\"),\n+   rinit = sir_init,\n+   params = c(Beta = log(1), mu_IR = log(0.1), rho = log(0.1))\n+ ) |>\n+   pmcmc(\n+     Np = 1000,\n+     Nmcmc = 100,\n+     proposal = mvn_diag_rw(c(Beta = 5, mu_IR = 5, rho = 5))\n+ #    proposal = mvn_diag_rw(c(Beta = 0.2, mu_IR = 0.2, rho = 0.2))\n+   ) -> pmcmcSIR\n> \n"
  },
  {
    "path": "tests/issue222.R",
    "content": "library(pomp)\n\npng(filename=\"issue222-%02d.png\",res=100)\n\nset.seed(974650257)\n\nsimulate(\n  t0=-1/52,\n  times=seq(0,10,by=1/52),\n  params=c(\n    gamma = 26, mu = 0.02, iota = 0.1,\n    Beta = 400, Beta_sd = 0.01,\n    rho = 0.6, k = 10,\n    pop = 1e6,\n    S_0 = 25/400, I_0 = 0.001, R_0 = 375/400\n  ),\n  rprocess = euler(\n    step.fun=Csnippet(r\"{\n      double dW = rgammawn(Beta_sd,dt);\n      double rate[6];\n      double trans[6];\n      rate[0] = mu*pop;\n      rate[1] = Beta*(I+iota)/pop*dW/dt;\n      rate[2] = mu;\n      rate[3] = gamma;\n      rate[4] = mu;\n      rate[5] = mu;\n      trans[0] = rate[0]*dt;\n      eeulermultinom(2,S,&rate[1],dt,&trans[1]);\n      eeulermultinom(2,I,&rate[3],dt,&trans[3]);\n      eeulermultinom(1,R,&rate[5],dt,&trans[5]);\n      // balance equations\n      S += trans[0] - trans[1] - trans[2];\n      I += trans[1] - trans[3] - trans[4];\n      R += trans[3] - trans[5];\n      C += trans[3];\n      W += (dW-dt)/Beta_sd;}\"\n    ),\n    delta.t=1/365\n  ),\n  rmeasure = Csnippet(r\"{\n      reports = rnbinom_mu(k,rho*C);}\"\n  ),\n  rinit=initlz_pf <- Csnippet(r\"{\n      double m = pop/(S_0+I_0+R_0);\n      S = m*S_0;\n      I = m*I_0;\n      R = m*R_0;\n      C = 0;\n      W = 0;}\"\n  ),\n  partrans=parameter_trans(\n    logit=c(\"rho\"),\n    log=c(\"gamma\",\"mu\",\"k\",\"Beta\",\"Beta_sd\",\"iota\"),\n    barycentric=c(\"S_0\",\"I_0\",\"R_0\")\n  ),\n  obsnames = \"reports\",\n  accumvars = c(\"W\",\"C\"),\n  statenames = c(\"S\",\"I\",\"R\",\"C\",\"W\"),\n  paramnames = c(\n    \"pop\",\"rho\",\"k\",\"gamma\",\"mu\",\"Beta\",\"Beta_sd\",\"iota\",\n    \"S_0\",\"I_0\",\"R_0\"\n  )\n) -> po\n\npo |>\n  plot()\n\ntry(\n  po |>\n    simulate(nsim=1,seed=49986,)\n)\n\ntry(\n  po |>\n    simulate(\n      nsim=1,\n      seed=49986,\n      parameter_trans(\n        logit=c(\"rho\"),\n        log=c(\"gamma\",\"mu\",\"k\",\"Beta\",\"Beta_sd\",\"iota\"),\n        barycentric=c(\"S_0\",\"I_0\",\"R_0\")\n      )\n    )\n)\n\ndev.off()\n"
  },
  {
    "path": "tests/issue222.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> \n> png(filename=\"issue222-%02d.png\",res=100)\n> \n> set.seed(974650257)\n> \n> simulate(\n+   t0=-1/52,\n+   times=seq(0,10,by=1/52),\n+   params=c(\n+     gamma = 26, mu = 0.02, iota = 0.1,\n+     Beta = 400, Beta_sd = 0.01,\n+     rho = 0.6, k = 10,\n+     pop = 1e6,\n+     S_0 = 25/400, I_0 = 0.001, R_0 = 375/400\n+   ),\n+   rprocess = euler(\n+     step.fun=Csnippet(r\"{\n+       double dW = rgammawn(Beta_sd,dt);\n+       double rate[6];\n+       double trans[6];\n+       rate[0] = mu*pop;\n+       rate[1] = Beta*(I+iota)/pop*dW/dt;\n+       rate[2] = mu;\n+       rate[3] = gamma;\n+       rate[4] = mu;\n+       rate[5] = mu;\n+       trans[0] = rate[0]*dt;\n+       eeulermultinom(2,S,&rate[1],dt,&trans[1]);\n+       eeulermultinom(2,I,&rate[3],dt,&trans[3]);\n+       eeulermultinom(1,R,&rate[5],dt,&trans[5]);\n+       // balance equations\n+       S += trans[0] - trans[1] - trans[2];\n+       I += trans[1] - trans[3] - trans[4];\n+       R += trans[3] - trans[5];\n+       C += trans[3];\n+       W += (dW-dt)/Beta_sd;}\"\n+     ),\n+     delta.t=1/365\n+   ),\n+   rmeasure = Csnippet(r\"{\n+       reports = rnbinom_mu(k,rho*C);}\"\n+   ),\n+   rinit=initlz_pf <- Csnippet(r\"{\n+       double m = pop/(S_0+I_0+R_0);\n+       S = m*S_0;\n+       I = m*I_0;\n+       R = m*R_0;\n+       C = 0;\n+       W = 0;}\"\n+   ),\n+   partrans=parameter_trans(\n+     logit=c(\"rho\"),\n+     log=c(\"gamma\",\"mu\",\"k\",\"Beta\",\"Beta_sd\",\"iota\"),\n+     barycentric=c(\"S_0\",\"I_0\",\"R_0\")\n+   ),\n+   obsnames = \"reports\",\n+   accumvars = c(\"W\",\"C\"),\n+   statenames = c(\"S\",\"I\",\"R\",\"C\",\"W\"),\n+   paramnames = c(\n+     \"pop\",\"rho\",\"k\",\"gamma\",\"mu\",\"Beta\",\"Beta_sd\",\"iota\",\n+     \"S_0\",\"I_0\",\"R_0\"\n+   )\n+ ) -> po\n> \n> po |>\n+   plot()\n> \n> try(\n+   po |>\n+     simulate(nsim=1,seed=49986,)\n+ )\nError : in 'simulate': argument is missing, with no default\n> \n> try(\n+   po |>\n+     simulate(\n+       nsim=1,\n+       seed=49986,\n+       parameter_trans(\n+         logit=c(\"rho\"),\n+         log=c(\"gamma\",\"mu\",\"k\",\"Beta\",\"Beta_sd\",\"iota\"),\n+         barycentric=c(\"S_0\",\"I_0\",\"R_0\")\n+       )\n+     )\n+ )\nError : in 'simulate': Unnamed arguments are not permitted.\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/issue56.R",
    "content": "library(pomp)\n\ncreate_example <- function(times, t0 = 0, mu = 0.001, N_0 = 1) {\n\n  rmeasure <- function (ct, ...) {\n    c(y=rpois(n=1,ct))\n  }\n\n  rate.fun <- function(j, mu, N, ...) {\n    switch(j, mu*N, stop(\"unrecognized event \",j))\n  }\n\n  rprocess <- gillespie(rate.fun = rate.fun, v=rbind(N=-1, ct=1))\n\n  rinit <- function(params, t0, ...) c(N=N_0,ct=12)\n\n  simulate(times = times, t0 = t0, params = c(mu=mu),\n    rprocess = rprocess, rinit = rinit, rmeasure = rmeasure, accumvars = \"ct\",\n    paramnames = \"mu\", statenames = c(\"N\",\"ct\"), obsnames = \"y\",\n    covar = covariate_table(x=c(0,1),times=c(0,52)), format = \"data.frame\")\n}\n\ncreate_example(times = 1) -> x1\ncreate_example(times = c(1,2)) -> x2\ncreate_example(times = 0)-> x3\ncreate_example(times = c(0,1)) -> x4\nstopifnot(names(x1)==names(x2),x3[1,]==x4[1,])\n"
  },
  {
    "path": "tests/issue56.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> \n> create_example <- function(times, t0 = 0, mu = 0.001, N_0 = 1) {\n+ \n+   rmeasure <- function (ct, ...) {\n+     c(y=rpois(n=1,ct))\n+   }\n+ \n+   rate.fun <- function(j, mu, N, ...) {\n+     switch(j, mu*N, stop(\"unrecognized event \",j))\n+   }\n+ \n+   rprocess <- gillespie(rate.fun = rate.fun, v=rbind(N=-1, ct=1))\n+ \n+   rinit <- function(params, t0, ...) c(N=N_0,ct=12)\n+ \n+   simulate(times = times, t0 = t0, params = c(mu=mu),\n+     rprocess = rprocess, rinit = rinit, rmeasure = rmeasure, accumvars = \"ct\",\n+     paramnames = \"mu\", statenames = c(\"N\",\"ct\"), obsnames = \"y\",\n+     covar = covariate_table(x=c(0,1),times=c(0,52)), format = \"data.frame\")\n+ }\n> \n> create_example(times = 1) -> x1\n> create_example(times = c(1,2)) -> x2\n> create_example(times = 0)-> x3\n> create_example(times = c(0,1)) -> x4\n> stopifnot(names(x1)==names(x2),x3[1,]==x4[1,])\n> \n"
  },
  {
    "path": "tests/kalman.R",
    "content": "options(digits=3)\npng(filename=\"kalman-%02d.png\",res=100)\n\nlibrary(pomp)\nsuppressPackageStartupMessages({\n  library(dplyr)\n  library(tidyr)\n  library(ggplot2)\n  library(mvtnorm)\n})\nset.seed(1638125322)\n\nt <- seq(1,20)\n\nC <- matrix(c(\n  1, 0,  0, 0,\n  0, 1, -1, 0),\n  2,4,byrow=TRUE)\n\ndimX <- ncol(C)\ndimY <- nrow(C)\n\ndimnames(C) <- list(\n  paste0(\"y\",seq_len(dimY)),\n  paste0(\"x\",seq_len(dimX)))\n\nR <- matrix(c(1,0.3,0.3,1),nrow=dimY,dimnames=list(rownames(C),rownames(C)))\n\nA <- matrix(c(\n  -0.677822, -0.169411,  0.420662,  0.523571,\n  2.87451,  -0.323604, -0.489533, -0.806087,\n  -1.36617,  -0.592326,  0.567114,  0.345142,\n  -0.807978, -0.163305,  0.668037,  0.468286),\n  nrow=dimX,ncol=dimX,byrow=TRUE,\n  dimnames=list(colnames(C),colnames(C)))\n\nQ <- crossprod(matrix(rnorm(n=dimX*dimX,sd=1/4),4,4))\ndimnames(Q) <- dimnames(A)\n\nX0 <- setNames(rnorm(dimX),colnames(C))\n\nN <- length(t)\nx <- array(dim=c(dimX,N),dimnames=list(variable=colnames(C),time=t))\ny <- array(dim=c(dimY,N),dimnames=list(variable=rownames(C),time=t))\n\nxx <- X0\nsqrtQ <- t(chol(Q))\nsqrtR <- t(chol(R))\nfor (k in seq_along(t)) {\n  x[,k] <- xx <- A %*% xx + sqrtQ %*% rnorm(n=dimX)\n  y[,k] <- C %*% xx + sqrtR %*% rnorm(n=dimY)\n}\n\ny |>\n  t() |>\n  as.data.frame() |>\n  pfilter(\n    times=t,t0=0,\n    userdata=list(A=A,C=C,R=R,sqrtQ=sqrtQ,sqrtR=sqrtR,X0=X0),\n    rprocess=discrete_time(\n      step.fun=function(x1,x2,x3,x4,delta.t,...){\n        x <- c(x1,x2,x3,x4)\n        x <- A%*%x+sqrtQ%*%rnorm(n=ncol(A))\n        setNames(x,c(\"x1\",\"x2\",\"x3\",\"x4\"))\n      },\n      delta.t=1),\n    emeasure=function(x1,x2,x3,x4,C,...){\n      ex <- C%*%c(x1,x2,x3,x4)\n      dim(ex) <- NULL\n      setNames(ex,rownames(C))\n    },\n    vmeasure=function(R, ...){\n      R\n    },\n    rmeasure=function(x1,x2,x3,x4,C,sqrtR,...){\n      x <- c(x1,x2,x3,x4)\n      C%*%x+sqrtR%*%rnorm(n=nrow(C))\n    },\n    dmeasure=function(x1,x2,x3,x4,y1,y2,log,C,R,...){\n      x <- c(x1,x2,x3,x4)\n      y <- c(y1,y2)\n      dmvnorm(x=t(y-C%*%x),sigma=R,log=log)\n    },\n    rinit=function(params,t0,X0,...){\n      X0\n    },\n    params=c(),\n    Np=1000,\n    filter.mean=TRUE\n  ) -> pf\n\nfreeze(\n  seed=1286628545,\n  {\n    enkf <- enkf(pf,Np=1000)\n    eakf <- eakf(pf,Np=1000)\n    kf <- kalmanFilter(pf,A=A,Q=Q,C=C,R=R,tol=1e-9)\n    stopifnot(\n      all.equal(\n        c(kf$logLik,logLik(pf),logLik(enkf),logLik(eakf)),\n        c(-67.0,-67.1,-66.7,-67.1),\n        tolerance=1e-3\n      )\n    )\n  }\n)\n\ntry(enkf(pf))\ntry(enkf(pf,Np=c(100,200)))\ntry(enkf(pf,Np=-10))\ntry(enkf(pf,Np=\"10b\"))\ntry(enkf(pf,Np=100,emeasure=NULL))\ntry(enkf(enkf,Np=100,vmeasure=NULL))\ntry(enkf(enkf,userdata=list(C=matrix(1,2,4,dimnames=list(c(\"y2\",\"y1\"),NULL))),Np=100))\ntry(enkf(enkf,userdata=list(C=matrix(1,3,4,dimnames=list(c(\"a\",\"b\",\"c\"),NULL))),Np=100))\ntry(enkf(enkf,userdata=list(R=matrix(1,1,1,dimnames=list(c(\"y1\"),NULL))),Np=100))\ntry(enkf(enkf,userdata=list(R=matrix(1,2,2,dimnames=list(c(\"y2\",\"y1\"),NULL))),Np=100))\ntry(enkf(enkf,userdata=list(R=matrix(1,2,2,dimnames=list(c(\"a\",\"b\"),NULL))),Np=100))\ntry(enkf(enkf,userdata=list(R=matrix(1,3,3,dimnames=list(c(\"a\",\"b\",\"c\"),NULL))),Np=100))\nenkf(enkf)\nenkf(enkf,Np=100)\n\ntry(eakf(enkf,Np=c(100,200)))\ntry(eakf(enkf,Np=-10))\ntry(eakf(enkf,Np=\"10b\"))\ntry(eakf(enkf,Np=100,emeasure=NULL))\ntry(eakf(enkf,Np=100,vmeasure=NULL))\ntry(eakf(enkf,userdata=list(C=matrix(1,2,4,dimnames=list(c(\"y2\",\"y1\"),NULL))),Np=100))\ntry(eakf(enkf,userdata=list(C=matrix(1,3,4,dimnames=list(c(\"a\",\"b\",\"c\"),NULL))),Np=100))\ntry(eakf(enkf,userdata=list(R=matrix(1,1,1,dimnames=list(c(\"y1\"),NULL))),Np=100))\ntry(eakf(enkf,userdata=list(R=matrix(1,2,2,dimnames=list(c(\"y2\",\"y1\"),NULL))),Np=100))\ntry(eakf(enkf,userdata=list(R=matrix(1,2,2,dimnames=list(c(\"a\",\"b\"),NULL)),Np=100)))\ntry(eakf(enkf,userdata=list(R=matrix(1,3,3,dimnames=list(c(\"a\",\"b\",\"c\"),NULL))),Np=100))\n\ninvisible(enkf(pf,Np=1000,params=as.list(coef(pf))))\ninvisible(eakf(pf,Np=1000,params=as.list(coef(pf))))\n\nenkf |>\n  as.data.frame() |>\n  pivot_longer(cols=-time) |>\n  group_by(name) |>\n  summarize(n=length(value))\neakf |>\n  as.data.frame() |>\n  pivot_longer(cols=-time) |>\n  group_by(name) |>\n  summarize(n=length(value))\n\nenkf |>\n  forecast(format=\"d\") |>\n  ggplot(aes(x=time,y=value,group=name,color=name))+\n  geom_line()+theme_bw()+\n  labs(title=\"EnKF forecasts\")\n\neakf |>\n  forecast(vars=c(\"y1\",\"y2\"),format=\"d\") |>\n  ggplot(aes(x=time,y=value,group=name,color=name))+\n  geom_line()+theme_bw()+\n  labs(title=\"EAKF forecasts\")\n\ntry({\n  R <- matrix(c(1,0,1,0),2,2)\n  rownames(R) <- rownames(C)\n  enkf(pf,Np=1000,userdata=list(R=R))\n})\n\ntry({\n  eakf(pf,Np=1000,userdata=list(R=R))\n})\n\ntry(enkf())\ntry(enkf(\"bob\"))\ntry(eakf())\ntry(eakf(\"bob\"))\n\ndev.off()\n"
  },
  {
    "path": "tests/kalman.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"kalman-%02d.png\",res=100)\n> \n> library(pomp)\n> suppressPackageStartupMessages({\n+   library(dplyr)\n+   library(tidyr)\n+   library(ggplot2)\n+   library(mvtnorm)\n+ })\n> set.seed(1638125322)\n> \n> t <- seq(1,20)\n> \n> C <- matrix(c(\n+   1, 0,  0, 0,\n+   0, 1, -1, 0),\n+   2,4,byrow=TRUE)\n> \n> dimX <- ncol(C)\n> dimY <- nrow(C)\n> \n> dimnames(C) <- list(\n+   paste0(\"y\",seq_len(dimY)),\n+   paste0(\"x\",seq_len(dimX)))\n> \n> R <- matrix(c(1,0.3,0.3,1),nrow=dimY,dimnames=list(rownames(C),rownames(C)))\n> \n> A <- matrix(c(\n+   -0.677822, -0.169411,  0.420662,  0.523571,\n+   2.87451,  -0.323604, -0.489533, -0.806087,\n+   -1.36617,  -0.592326,  0.567114,  0.345142,\n+   -0.807978, -0.163305,  0.668037,  0.468286),\n+   nrow=dimX,ncol=dimX,byrow=TRUE,\n+   dimnames=list(colnames(C),colnames(C)))\n> \n> Q <- crossprod(matrix(rnorm(n=dimX*dimX,sd=1/4),4,4))\n> dimnames(Q) <- dimnames(A)\n> \n> X0 <- setNames(rnorm(dimX),colnames(C))\n> \n> N <- length(t)\n> x <- array(dim=c(dimX,N),dimnames=list(variable=colnames(C),time=t))\n> y <- array(dim=c(dimY,N),dimnames=list(variable=rownames(C),time=t))\n> \n> xx <- X0\n> sqrtQ <- t(chol(Q))\n> sqrtR <- t(chol(R))\n> for (k in seq_along(t)) {\n+   x[,k] <- xx <- A %*% xx + sqrtQ %*% rnorm(n=dimX)\n+   y[,k] <- C %*% xx + sqrtR %*% rnorm(n=dimY)\n+ }\n> \n> y |>\n+   t() |>\n+   as.data.frame() |>\n+   pfilter(\n+     times=t,t0=0,\n+     userdata=list(A=A,C=C,R=R,sqrtQ=sqrtQ,sqrtR=sqrtR,X0=X0),\n+     rprocess=discrete_time(\n+       step.fun=function(x1,x2,x3,x4,delta.t,...){\n+         x <- c(x1,x2,x3,x4)\n+         x <- A%*%x+sqrtQ%*%rnorm(n=ncol(A))\n+         setNames(x,c(\"x1\",\"x2\",\"x3\",\"x4\"))\n+       },\n+       delta.t=1),\n+     emeasure=function(x1,x2,x3,x4,C,...){\n+       ex <- C%*%c(x1,x2,x3,x4)\n+       dim(ex) <- NULL\n+       setNames(ex,rownames(C))\n+     },\n+     vmeasure=function(R, ...){\n+       R\n+     },\n+     rmeasure=function(x1,x2,x3,x4,C,sqrtR,...){\n+       x <- c(x1,x2,x3,x4)\n+       C%*%x+sqrtR%*%rnorm(n=nrow(C))\n+     },\n+     dmeasure=function(x1,x2,x3,x4,y1,y2,log,C,R,...){\n+       x <- c(x1,x2,x3,x4)\n+       y <- c(y1,y2)\n+       dmvnorm(x=t(y-C%*%x),sigma=R,log=log)\n+     },\n+     rinit=function(params,t0,X0,...){\n+       X0\n+     },\n+     params=c(),\n+     Np=1000,\n+     filter.mean=TRUE\n+   ) -> pf\n> \n> freeze(\n+   seed=1286628545,\n+   {\n+     enkf <- enkf(pf,Np=1000)\n+     eakf <- eakf(pf,Np=1000)\n+     kf <- kalmanFilter(pf,A=A,Q=Q,C=C,R=R,tol=1e-9)\n+     stopifnot(\n+       all.equal(\n+         c(kf$logLik,logLik(pf),logLik(enkf),logLik(eakf)),\n+         c(-67.0,-67.1,-66.7,-67.1),\n+         tolerance=1e-3\n+       )\n+     )\n+   }\n+ )\nNULL\n> \n> try(enkf(pf))\nError : in 'enkf': argument \"Np\" is missing, with no default\n> try(enkf(pf,Np=c(100,200)))\nError : in 'enkf': 'Np' should be a single positive integer.\n> try(enkf(pf,Np=-10))\nError : in 'enkf': 'Np' should be a single positive integer.\n> try(enkf(pf,Np=\"10b\"))\nError : in 'enkf': 'Np' should be a single positive integer.\nIn addition: Warning message:\nIn enkf_internal(data, ..., Np = Np, verbose = verbose) :\n  NAs introduced by coercion\n> try(enkf(pf,Np=100,emeasure=NULL))\nError : in 'enkf': 'emeasure' is a needed basic component.\n> try(enkf(enkf,Np=100,vmeasure=NULL))\nError : in 'enkf': 'vmeasure' is a needed basic component.\n> try(enkf(enkf,userdata=list(C=matrix(1,2,4,dimnames=list(c(\"y2\",\"y1\"),NULL))),Np=100))\nError : in 'enkf': rownames of matrix returned by 'vmeasure' do not match those returned by 'emeasure'.\n> try(enkf(enkf,userdata=list(C=matrix(1,3,4,dimnames=list(c(\"a\",\"b\",\"c\"),NULL))),Np=100))\nError : in 'enkf': number of observables returned by 'emeasure' does not match data.\n> try(enkf(enkf,userdata=list(R=matrix(1,1,1,dimnames=list(c(\"y1\"),NULL))),Np=100))\nError : in 'enkf': rownames of matrix returned by 'vmeasure' do not match those returned by 'emeasure'.\n> try(enkf(enkf,userdata=list(R=matrix(1,2,2,dimnames=list(c(\"y2\",\"y1\"),NULL))),Np=100))\nError : in 'enkf': rownames of matrix returned by 'vmeasure' do not match those returned by 'emeasure'.\n> try(enkf(enkf,userdata=list(R=matrix(1,2,2,dimnames=list(c(\"a\",\"b\"),NULL))),Np=100))\nError : in 'enkf': rownames of matrix returned by 'vmeasure' do not match those returned by 'emeasure'.\n> try(enkf(enkf,userdata=list(R=matrix(1,3,3,dimnames=list(c(\"a\",\"b\",\"c\"),NULL))),Np=100))\nError : in 'enkf': rownames of matrix returned by 'vmeasure' do not match those returned by 'emeasure'.\n> enkf(enkf)\n<object of class 'kalmand_pomp'>\n> enkf(enkf,Np=100)\n<object of class 'kalmand_pomp'>\n> \n> try(eakf(enkf,Np=c(100,200)))\nError : in 'eakf': 'Np' should be a single positive integer.\n> try(eakf(enkf,Np=-10))\nError : in 'eakf': 'Np' should be a single positive integer.\n> try(eakf(enkf,Np=\"10b\"))\nError : in 'eakf': 'Np' should be a single positive integer.\nIn addition: Warning message:\nIn eakf_internal(data, ..., Np = Np, verbose = verbose) :\n  NAs introduced by coercion\n> try(eakf(enkf,Np=100,emeasure=NULL))\nError : in 'eakf': 'emeasure' is a needed basic component.\n> try(eakf(enkf,Np=100,vmeasure=NULL))\nError : in 'eakf': 'vmeasure' is a needed basic component.\n> try(eakf(enkf,userdata=list(C=matrix(1,2,4,dimnames=list(c(\"y2\",\"y1\"),NULL))),Np=100))\nError : in 'eakf': rownames of matrix returned by 'vmeasure' do not match those returned by 'emeasure'.\n> try(eakf(enkf,userdata=list(C=matrix(1,3,4,dimnames=list(c(\"a\",\"b\",\"c\"),NULL))),Np=100))\nError : in 'eakf': number of observables returned by 'emeasure' does not match data.\n> try(eakf(enkf,userdata=list(R=matrix(1,1,1,dimnames=list(c(\"y1\"),NULL))),Np=100))\nError : in 'eakf': rownames of matrix returned by 'vmeasure' do not match those returned by 'emeasure'.\n> try(eakf(enkf,userdata=list(R=matrix(1,2,2,dimnames=list(c(\"y2\",\"y1\"),NULL))),Np=100))\nError : in 'eakf': rownames of matrix returned by 'vmeasure' do not match those returned by 'emeasure'.\n> try(eakf(enkf,userdata=list(R=matrix(1,2,2,dimnames=list(c(\"a\",\"b\"),NULL)),Np=100)))\nError : in 'eakf': argument \"Np\" is missing, with no default\n> try(eakf(enkf,userdata=list(R=matrix(1,3,3,dimnames=list(c(\"a\",\"b\",\"c\"),NULL))),Np=100))\nError : in 'eakf': rownames of matrix returned by 'vmeasure' do not match those returned by 'emeasure'.\n> \n> invisible(enkf(pf,Np=1000,params=as.list(coef(pf))))\n> invisible(eakf(pf,Np=1000,params=as.list(coef(pf))))\n> \n> enkf |>\n+   as.data.frame() |>\n+   pivot_longer(cols=-time) |>\n+   group_by(name) |>\n+   summarize(n=length(value))\n# A tibble: 13 × 2\n   name               n\n   <chr>          <int>\n 1 cond.logLik       20\n 2 filter.mean.x1    20\n 3 filter.mean.x2    20\n 4 filter.mean.x3    20\n 5 filter.mean.x4    20\n 6 forecast.y1       20\n 7 forecast.y2       20\n 8 pred.mean.x1      20\n 9 pred.mean.x2      20\n10 pred.mean.x3      20\n11 pred.mean.x4      20\n12 y1                20\n13 y2                20\n> eakf |>\n+   as.data.frame() |>\n+   pivot_longer(cols=-time) |>\n+   group_by(name) |>\n+   summarize(n=length(value))\n# A tibble: 13 × 2\n   name               n\n   <chr>          <int>\n 1 cond.logLik       20\n 2 filter.mean.x1    20\n 3 filter.mean.x2    20\n 4 filter.mean.x3    20\n 5 filter.mean.x4    20\n 6 forecast.y1       20\n 7 forecast.y2       20\n 8 pred.mean.x1      20\n 9 pred.mean.x2      20\n10 pred.mean.x3      20\n11 pred.mean.x4      20\n12 y1                20\n13 y2                20\n> \n> enkf |>\n+   forecast(format=\"d\") |>\n+   ggplot(aes(x=time,y=value,group=name,color=name))+\n+   geom_line()+theme_bw()+\n+   labs(title=\"EnKF forecasts\")\n> \n> eakf |>\n+   forecast(vars=c(\"y1\",\"y2\"),format=\"d\") |>\n+   ggplot(aes(x=time,y=value,group=name,color=name))+\n+   geom_line()+theme_bw()+\n+   labs(title=\"EAKF forecasts\")\n> \n> try({\n+   R <- matrix(c(1,0,1,0),2,2)\n+   rownames(R) <- rownames(C)\n+   enkf(pf,Np=1000,userdata=list(R=R))\n+ })\nError : in 'enkf': degenerate 'vmeasure': the leading minor of order 2 is not positive\n> \n> try({\n+   eakf(pf,Np=1000,userdata=list(R=R))\n+ })\nError : in 'eakf': degenerate 'vmeasure': Lapack routine dgesv: system is exactly singular: U[2,2] = 0\n> \n> try(enkf())\nError : in 'enkf': 'data' is a required argument.\n> try(enkf(\"bob\"))\nError : 'enkf' is undefined for 'data' of class 'character'.\n> try(eakf())\nError : in 'eakf': 'data' is a required argument.\n> try(eakf(\"bob\"))\nError : 'eakf' is undefined for 'data' of class 'character'.\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/kalman2.R",
    "content": "options(digits=3)\npng(filename=\"kalman2-%02d.png\",res=100)\n\nlibrary(pomp)\nsuppressPackageStartupMessages({\n  library(tidyr)\n})\n\nset.seed(1968726372)\n\ngompertz() -> po\n\npo |>\n  window(start=1,end=30) |>\n  as.data.frame() |>\n  subset(select=-X) -> dat\n\ntry(dat |> enkf())\n\ndat |>\n  enkf(\n    times=\"time\",t0=0,Np=100,\n    params=c(r=0.1,K=150),\n    rinit=function(K, ...) {\n      c(x=K)\n    },\n    rprocess=discrete_time(\n      function (x, r, K, ...) {\n        e <- rnorm(n=1,mean=0,sd=0.1)\n        c(x=x*exp(r*(1-x/K))+e)\n      }\n    ),\n    emeasure=function(x,...) c(Y=0.01*x),\n    vmeasure=function(...) matrix(2,1,1,dimnames=list(\"Y\",\"Y\"))\n  ) |> plot()\n\ntry(dat |> eakf())\n\ndat |>\n  eakf(\n    times=\"time\",t0=0,Np=100,\n    params=c(r=0.1,K=100),\n    rinit=function(K, ...) {\n      c(x=rlnorm(n=1,meanlog=log(K),sdlog=0.01))\n    },\n    rprocess=discrete_time(\n      function (x, r, K, ...) {\n        c(x=x*exp(r*(1-x/K)))\n      }\n    ),\n    vmeasure=function(R, ...) R,\n    emeasure=function(x,...) c(Y=0.01*x),\n    userdata=list(R=matrix(0.01,1,1,dimnames=list(\"Y\",\"Y\")))\n  ) -> kf\n\nkf |> plot()\n\nkf |> as.data.frame() |> names()\nkf |> as.data.frame() |> pivot_longer(-time) |> names()\nkf |> forecast() |> melt() |> sapply(class)\nkf |> forecast(format=\"d\") |> sapply(class)\nkf |> filter_mean() |> melt() |> sapply(class)\nkf |> filter_mean(format=\"d\") |> sapply(class)\nkf |> filter_mean(vars=\"x\") |> dim()\nkf |> filter_mean(vars=\"x\") |> dimnames()\nkf |> filter_mean(vars=\"x\",format=\"d\") |> dim()\nkf |> filter_mean(vars=\"x\",format=\"d\") |> getElement(\"name\") |> unique()\nkf |> pred_mean() |> melt() |> sapply(class)\nkf |> pred_mean(format=\"d\") |> sapply(class)\nkf |> pred_mean(vars=\"x\") |> dim()\nkf |> pred_mean(vars=\"x\") |> dimnames()\nkf |> pred_mean(vars=\"x\",format=\"d\") |> dim()\nkf |> pred_mean(vars=\"x\",format=\"d\") |> getElement(\"name\") |> unique()\ntry(kf |> pred_var() |> melt() |> sapply(class))\ntry(kf |> pred_var(format=\"d\") |> sapply(class))\ntry(kf |> filter_traj() |> melt() |> sapply(class))\ntry(kf |> filter_traj(format=\"d\") |> sapply(class))\ntry(kf |> saved_states() |> melt() |> sapply(class))\ntry(kf |> saved_states(format=\"d\") |> sapply(class))\ntry(kf |> forecast(format=\"l\"))\n\nkf |> forecast(format=\"a\") |> melt() -> kdat1a\nkf |> filter_mean(format=\"a\") |> melt() -> kdat2a\nkf |> pred_mean(format=\"a\") |> melt() -> kdat3a\ntry(kf |> filter_traj(format=\"a\") |> melt() -> kdat4a)\ntry(kf |> eff_sample_size(format=\"n\") |> melt() -> kdat5a)\nkf |> cond_logLik(format=\"n\") |> melt() -> kdat6a\ntry(kf |> saved_states(format=\"l\") |> melt() -> kdat7a)\nkf |> as.data.frame() -> kdat0\nkf |> forecast(format=\"d\") -> kdat1\nkf |> filter_mean(format=\"d\") -> kdat2\nkf |> pred_mean(format=\"d\") -> kdat3\ntry(kf |> filter_traj(format=\"d\") -> kdat4)\ntry(kf |> eff_sample_size(format=\"d\") -> kdat5)\nkf |> cond_logLik(format=\"d\") -> kdat6\ntry(kf |> saved_states(format=\"d\") -> kdat7)\nstopifnot(\n  all(kdat0$forecast.Y==kdat1$value),\n  all(kdat0$filter.mean.x==kdat2$value),\n  all(kdat0$pred.mean.x==kdat3$value),\n  all(kdat0$cond.logLik==kdat6$value),\n  all.equal(kdat1$time,as.numeric(kdat1a$time)),\n  all.equal(kdat2$time,as.numeric(kdat2a$time)),\n  all.equal(kdat3$time,as.numeric(kdat3a$time)),\n  all.equal(kdat1$value,kdat1a$value),\n  all.equal(kdat2$value,kdat2a$value),\n  all.equal(kdat3$value,kdat3a$value),\n  all.equal(kdat6$cond.logLik,kdat6a$value)\n)\n\ntry(po |> enkf(rprocess=NULL))\ntry(po |> eakf(rprocess=NULL))\n\ndev.off()\n"
  },
  {
    "path": "tests/kalman2.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"kalman2-%02d.png\",res=100)\n> \n> library(pomp)\n> suppressPackageStartupMessages({\n+   library(tidyr)\n+ })\n> \n> set.seed(1968726372)\n> \n> gompertz() -> po\n> \n> po |>\n+   window(start=1,end=30) |>\n+   as.data.frame() |>\n+   subset(select=-X) -> dat\n> \n> try(dat |> enkf())\nError : in 'enkf': 'times' should either be a numeric vector of observation times or a single name identifying the column of data that represents the observation times.\n> \n> dat |>\n+   enkf(\n+     times=\"time\",t0=0,Np=100,\n+     params=c(r=0.1,K=150),\n+     rinit=function(K, ...) {\n+       c(x=K)\n+     },\n+     rprocess=discrete_time(\n+       function (x, r, K, ...) {\n+         e <- rnorm(n=1,mean=0,sd=0.1)\n+         c(x=x*exp(r*(1-x/K))+e)\n+       }\n+     ),\n+     emeasure=function(x,...) c(Y=0.01*x),\n+     vmeasure=function(...) matrix(2,1,1,dimnames=list(\"Y\",\"Y\"))\n+   ) |> plot()\n> \n> try(dat |> eakf())\nError : in 'eakf': 'times' should either be a numeric vector of observation times or a single name identifying the column of data that represents the observation times.\n> \n> dat |>\n+   eakf(\n+     times=\"time\",t0=0,Np=100,\n+     params=c(r=0.1,K=100),\n+     rinit=function(K, ...) {\n+       c(x=rlnorm(n=1,meanlog=log(K),sdlog=0.01))\n+     },\n+     rprocess=discrete_time(\n+       function (x, r, K, ...) {\n+         c(x=x*exp(r*(1-x/K)))\n+       }\n+     ),\n+     vmeasure=function(R, ...) R,\n+     emeasure=function(x,...) c(Y=0.01*x),\n+     userdata=list(R=matrix(0.01,1,1,dimnames=list(\"Y\",\"Y\")))\n+   ) -> kf\n> \n> kf |> plot()\n> \n> kf |> as.data.frame() |> names()\n[1] \"time\"          \"Y\"             \"cond.logLik\"   \"pred.mean.x\"  \n[5] \"filter.mean.x\" \"forecast.Y\"   \n> kf |> as.data.frame() |> pivot_longer(-time) |> names()\n[1] \"time\"  \"name\"  \"value\"\n> kf |> forecast() |> melt() |> sapply(class)\n       name        time       value \n\"character\"   \"integer\"   \"numeric\" \n> kf |> forecast(format=\"d\") |> sapply(class)\n       name        time       value \n\"character\"   \"numeric\"   \"numeric\" \n> kf |> filter_mean() |> melt() |> sapply(class)\n       name        time       value \n\"character\" \"character\"   \"numeric\" \n> kf |> filter_mean(format=\"d\") |> sapply(class)\n       name        time       value \n\"character\"   \"numeric\"   \"numeric\" \n> kf |> filter_mean(vars=\"x\") |> dim()\n[1]  1 30\n> kf |> filter_mean(vars=\"x\") |> dimnames()\n$name\n[1] \"x\"\n\n$time\n [1] \"1\"  \"2\"  \"3\"  \"4\"  \"5\"  \"6\"  \"7\"  \"8\"  \"9\"  \"10\" \"11\" \"12\" \"13\" \"14\" \"15\"\n[16] \"16\" \"17\" \"18\" \"19\" \"20\" \"21\" \"22\" \"23\" \"24\" \"25\" \"26\" \"27\" \"28\" \"29\" \"30\"\n\n> kf |> filter_mean(vars=\"x\",format=\"d\") |> dim()\n[1] 30  3\n> kf |> filter_mean(vars=\"x\",format=\"d\") |> getElement(\"name\") |> unique()\n[1] \"x\"\n> kf |> pred_mean() |> melt() |> sapply(class)\n       name        time       value \n\"character\" \"character\"   \"numeric\" \n> kf |> pred_mean(format=\"d\") |> sapply(class)\n       name        time       value \n\"character\"   \"numeric\"   \"numeric\" \n> kf |> pred_mean(vars=\"x\") |> dim()\n[1]  1 30\n> kf |> pred_mean(vars=\"x\") |> dimnames()\n$name\n[1] \"x\"\n\n$time\n [1] \"1\"  \"2\"  \"3\"  \"4\"  \"5\"  \"6\"  \"7\"  \"8\"  \"9\"  \"10\" \"11\" \"12\" \"13\" \"14\" \"15\"\n[16] \"16\" \"17\" \"18\" \"19\" \"20\" \"21\" \"22\" \"23\" \"24\" \"25\" \"26\" \"27\" \"28\" \"29\" \"30\"\n\n> kf |> pred_mean(vars=\"x\",format=\"d\") |> dim()\n[1] 30  3\n> kf |> pred_mean(vars=\"x\",format=\"d\") |> getElement(\"name\") |> unique()\n[1] \"x\"\n> try(kf |> pred_var() |> melt() |> sapply(class))\nError in h(simpleError(msg, call)) : \n  error in evaluating the argument 'data' in selecting a method for function 'melt': 'pred_var' is undefined for 'object' of class 'kalmand_pomp'.\n> try(kf |> pred_var(format=\"d\") |> sapply(class))\nError : 'pred_var' is undefined for 'object' of class 'kalmand_pomp'.\n> try(kf |> filter_traj() |> melt() |> sapply(class))\nError in h(simpleError(msg, call)) : \n  error in evaluating the argument 'data' in selecting a method for function 'melt': 'filter_traj' is undefined for 'object' of class 'kalmand_pomp'.\n> try(kf |> filter_traj(format=\"d\") |> sapply(class))\nError : 'filter_traj' is undefined for 'object' of class 'kalmand_pomp'.\n> try(kf |> saved_states() |> melt() |> sapply(class))\nError in h(simpleError(msg, call)) : \n  error in evaluating the argument 'data' in selecting a method for function 'melt': 'saved_states' is undefined for 'object' of class 'kalmand_pomp'.\n> try(kf |> saved_states(format=\"d\") |> sapply(class))\nError : 'saved_states' is undefined for 'object' of class 'kalmand_pomp'.\n> try(kf |> forecast(format=\"l\"))\nError in match.arg(format) : 'arg' should be one of \"array\", \"data.frame\"\n> \n> kf |> forecast(format=\"a\") |> melt() -> kdat1a\n> kf |> filter_mean(format=\"a\") |> melt() -> kdat2a\n> kf |> pred_mean(format=\"a\") |> melt() -> kdat3a\n> try(kf |> filter_traj(format=\"a\") |> melt() -> kdat4a)\nError in h(simpleError(msg, call)) : \n  error in evaluating the argument 'data' in selecting a method for function 'melt': 'filter_traj' is undefined for 'object' of class 'kalmand_pomp'.\n> try(kf |> eff_sample_size(format=\"n\") |> melt() -> kdat5a)\nError in h(simpleError(msg, call)) : \n  error in evaluating the argument 'data' in selecting a method for function 'melt': 'eff_sample_size' is undefined for 'object' of class 'kalmand_pomp'.\n> kf |> cond_logLik(format=\"n\") |> melt() -> kdat6a\n> try(kf |> saved_states(format=\"l\") |> melt() -> kdat7a)\nError in h(simpleError(msg, call)) : \n  error in evaluating the argument 'data' in selecting a method for function 'melt': 'saved_states' is undefined for 'object' of class 'kalmand_pomp'.\n> kf |> as.data.frame() -> kdat0\n> kf |> forecast(format=\"d\") -> kdat1\n> kf |> filter_mean(format=\"d\") -> kdat2\n> kf |> pred_mean(format=\"d\") -> kdat3\n> try(kf |> filter_traj(format=\"d\") -> kdat4)\nError : 'filter_traj' is undefined for 'object' of class 'kalmand_pomp'.\n> try(kf |> eff_sample_size(format=\"d\") -> kdat5)\nError : 'eff_sample_size' is undefined for 'object' of class 'kalmand_pomp'.\n> kf |> cond_logLik(format=\"d\") -> kdat6\n> try(kf |> saved_states(format=\"d\") -> kdat7)\nError : 'saved_states' is undefined for 'object' of class 'kalmand_pomp'.\n> stopifnot(\n+   all(kdat0$forecast.Y==kdat1$value),\n+   all(kdat0$filter.mean.x==kdat2$value),\n+   all(kdat0$pred.mean.x==kdat3$value),\n+   all(kdat0$cond.logLik==kdat6$value),\n+   all.equal(kdat1$time,as.numeric(kdat1a$time)),\n+   all.equal(kdat2$time,as.numeric(kdat2a$time)),\n+   all.equal(kdat3$time,as.numeric(kdat3a$time)),\n+   all.equal(kdat1$value,kdat1a$value),\n+   all.equal(kdat2$value,kdat2a$value),\n+   all.equal(kdat3$value,kdat3a$value),\n+   all.equal(kdat6$cond.logLik,kdat6a$value)\n+ )\n> \n> try(po |> enkf(rprocess=NULL))\nError : in 'enkf': 'rprocess' is a needed basic component.\n> try(po |> eakf(rprocess=NULL))\nError : in 'eakf': 'rprocess' is a needed basic component.\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/link.R",
    "content": "library(pomp)\n\ncat(\"double simplefun (double x) { return(x+3); }\",file=\"simplefun.c\")\nsystem2(R.home(\"bin/R\"),args=c(\"CMD\",\"COMPILE\",\"simplefun.c\"),\n  stdout=NULL,stderr=NULL)\n\ngompertz() -> gompertz\n\npomp(gompertz,rmeasure=Csnippet(\"\n  double simplefun (double);\n  double m = simplefun(X);\n  Y = rlnorm(log(m),tau);\"),\n  statenames=\"X\",paramnames=\"tau\",\n  shlib.args=\"simplefun.o\") -> po\n\nx <- simulate(po)\n\npomp(gompertz,rmeasure=Csnippet(\"\n  double m = simplefun(X);\n  Y = rlnorm(log(m),tau);\"),\n  statenames=\"X\",paramnames=\"tau\",\n  shlib.args=\"simplefun.o\",\n  globals=\"double simplefun (double);\"\n  ) -> po\n\npomp(gompertz,rmeasure=Csnippet(\"\n  double m = simplefun(X);\n  Y = rlnorm(log(m),tau);\"),\n  statenames=\"X\",paramnames=\"tau\",\n  shlib.args=\"simplefun.o\",\n  globals=Csnippet(\"double simplefun (double);\")\n) -> po\n\nx <- simulate(po)\n"
  },
  {
    "path": "tests/link.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> \n> cat(\"double simplefun (double x) { return(x+3); }\",file=\"simplefun.c\")\n> system2(R.home(\"bin/R\"),args=c(\"CMD\",\"COMPILE\",\"simplefun.c\"),\n+   stdout=NULL,stderr=NULL)\n> \n> gompertz() -> gompertz\n> \n> pomp(gompertz,rmeasure=Csnippet(\"\n+   double simplefun (double);\n+   double m = simplefun(X);\n+   Y = rlnorm(log(m),tau);\"),\n+   statenames=\"X\",paramnames=\"tau\",\n+   shlib.args=\"simplefun.o\") -> po\n> \n> x <- simulate(po)\n> \n> pomp(gompertz,rmeasure=Csnippet(\"\n+   double m = simplefun(X);\n+   Y = rlnorm(log(m),tau);\"),\n+   statenames=\"X\",paramnames=\"tau\",\n+   shlib.args=\"simplefun.o\",\n+   globals=\"double simplefun (double);\"\n+   ) -> po\n> \n> pomp(gompertz,rmeasure=Csnippet(\"\n+   double m = simplefun(X);\n+   Y = rlnorm(log(m),tau);\"),\n+   statenames=\"X\",paramnames=\"tau\",\n+   shlib.args=\"simplefun.o\",\n+   globals=Csnippet(\"double simplefun (double);\")\n+ ) -> po\n> \n> x <- simulate(po)\n> \n"
  },
  {
    "path": "tests/load.R",
    "content": "library(pomp)\n\ngompertz() |>\n  pomp(\n    rmeasure=Csnippet(r\"{\n  Y = rlnorm(log(X),Tau);\n  }\"),\n  statenames=\"X\",paramnames=\"tau\",\n  globals=Csnippet(\"static double Tau = 0;\"),\n  on_load=Csnippet(\"Tau = 4.3;\"),\n  cdir=getwd(),cfile=\"sf\"\n) -> po\n\nfile.remove(paste0(\"sf\",.Platform$dynlib.ext))\n\ncapture.output(x <- simulate(po,verbose=TRUE)) -> out\nstopifnot(sum(grepl(\"loading\",out))==2)\n\nsir() -> sir\n\nsolibs(sir) <- NULL\nsolibs(sir) <- sir@solibs[[1]]\nstopifnot(length(sir@solibs)==2,\n  length(unique(sapply(sir@solibs,getElement,\"src\")))==1)\n"
  },
  {
    "path": "tests/load.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> \n> gompertz() |>\n+   pomp(\n+     rmeasure=Csnippet(r\"{\n+   Y = rlnorm(log(X),Tau);\n+   }\"),\n+   statenames=\"X\",paramnames=\"tau\",\n+   globals=Csnippet(\"static double Tau = 0;\"),\n+   on_load=Csnippet(\"Tau = 4.3;\"),\n+   cdir=getwd(),cfile=\"sf\"\n+ ) -> po\n> \n> file.remove(paste0(\"sf\",.Platform$dynlib.ext))\n[1] TRUE\n> \n> capture.output(x <- simulate(po,verbose=TRUE)) -> out\n> stopifnot(sum(grepl(\"loading\",out))==2)\n> \n> sir() -> sir\n> \n> solibs(sir) <- NULL\n> solibs(sir) <- sir@solibs[[1]]\n> stopifnot(length(sir@solibs)==2,\n+   length(unique(sapply(sir@solibs,getElement,\"src\")))==1)\n> \n"
  },
  {
    "path": "tests/logmeanexp.R",
    "content": "library(pomp)\n\nlogmeanexp(rep(10,10),se=TRUE)\nlogmeanexp(10^seq(8,10),se=TRUE)\nlogmeanexp(c(1.2e-100,1.4e-100,1.8e-100),se=TRUE)\nlogmeanexp(c(1e-200,1.5e-200,1.6e-200))\nlogmeanexp(10^seq(8,10),se=NA)\nlogmeanexp(10^seq(8,10),se=NULL)\nlogmeanexp(rep(10,10),ess=TRUE)\nlogmeanexp(10^seq(8,10),ess=TRUE)\nlogmeanexp(c(1.2e-100,1.4e-100,1.8e-100),se=TRUE,ess=TRUE)\n\nx1 <- freeze(-rexp(10,rate=0.1),seed=1951379414)\nx1 <- x1-max(x1)\nstopifnot(\n  all.equal(logmeanexp(x1),log(mean(exp(x1))))\n)\nlogmeanexp(x1,se=TRUE)\nlogmeanexp(x1,ess=TRUE)\nlogmeanexp(x1,ess=TRUE,se=TRUE)\n\nx2 <- freeze(-rexp(10,rate=10),seed=1951379414)\nx2 <- x2-max(x2)\nstopifnot(\n  all.equal(logmeanexp(x2),log(mean(exp(x2))))\n)\nlogmeanexp(x2,se=TRUE)\nlogmeanexp(x2,ess=TRUE)\nlogmeanexp(x2,ess=TRUE,se=TRUE)\n"
  },
  {
    "path": "tests/logmeanexp.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> \n> logmeanexp(rep(10,10),se=TRUE)\nest  se \n 10   0 \n> logmeanexp(10^seq(8,10),se=TRUE)\n  est    se \n1e+10 6e+09 \n> logmeanexp(c(1.2e-100,1.4e-100,1.8e-100),se=TRUE)\n          est            se \n1.800000e-100 2.666667e-101 \n> logmeanexp(c(1e-200,1.5e-200,1.6e-200))\n[1] 1.6e-200\n> logmeanexp(10^seq(8,10),se=NA)\n[1] 1e+10\n> logmeanexp(10^seq(8,10),se=NULL)\n[1] 1e+10\n> logmeanexp(rep(10,10),ess=TRUE)\nest ess \n 10  10 \n> logmeanexp(10^seq(8,10),ess=TRUE)\n  est   ess \n1e+10 1e+00 \n> logmeanexp(c(1.2e-100,1.4e-100,1.8e-100),se=TRUE,ess=TRUE)\n          est            se           ess \n1.800000e-100 2.666667e-101  3.000000e+00 \n> \n> x1 <- freeze(-rexp(10,rate=0.1),seed=1951379414)\n> x1 <- x1-max(x1)\n> stopifnot(\n+   all.equal(logmeanexp(x1),log(mean(exp(x1))))\n+ )\n> logmeanexp(x1,se=TRUE)\n      est        se \n-2.149512  1.744263 \n> logmeanexp(x1,ess=TRUE)\n      est       ess \n-2.149512  1.342667 \n> logmeanexp(x1,ess=TRUE,se=TRUE)\n      est        se       ess \n-2.149512  1.744263  1.342667 \n> \n> x2 <- freeze(-rexp(10,rate=10),seed=1951379414)\n> x2 <- x2-max(x2)\n> stopifnot(\n+   all.equal(logmeanexp(x2),log(mean(exp(x2))))\n+ )\n> logmeanexp(x2,se=TRUE)\n        est          se \n-0.10234692  0.03252946 \n> logmeanexp(x2,ess=TRUE)\n       est        ess \n-0.1023469  9.9047782 \n> logmeanexp(x2,ess=TRUE,se=TRUE)\n        est          se         ess \n-0.10234692  0.03252946  9.90477816 \n> \n"
  },
  {
    "path": "tests/lookup.R",
    "content": "options(digits=3)\nsuppressPackageStartupMessages({\n  library(tidyr)\n  library(ggplot2)\n})\n\npng(filename=\"lookup-%02d.png\",res=100)\n\nlibrary(pomp)\n\nct <- covariate_table(x=20:30,y=10:0,times=seq(0,10))\nlookup(ct,t=c(1,2.3,4,7,20))\nct <- covariate_table(x=20:30,y=10:0,times=seq(0,10),order=\"constant\")\nlookup(ct,t=c(1,2.3,4,7))\nlookup(ct,t=6.1)\nplot(y~t,data=lookup(ct,t=seq(0,10.5,by=0.01)),type=\"l\")\nlines(seq(0,10),10:0,col=\"blue\",type=\"s\")\nplot(x~t,data=lookup(ct,t=seq(0,10.5,by=0.01)),type=\"l\")\nlines(seq(0,10),20:30,col=\"blue\",type=\"s\")\n\nct <- covariate_table(x=20:31,y=12:1,times=c(0:5,5:10),order=\"constant\")\nlookup(ct,t=seq(4.9,5.1,by=0.05))\n\ntry(covariate_table(x=20:30,y=10:0,times=seq(10,0)))\ntry(covariate_table(x=20:23,y=10:0,times=seq(0,10)))\ntry(covariate_table(x=20:30,y=10:0,times=seq(0,3)))\ncovariate_table()\ntry(covariate_table(times=1:10))\ntry(covariate_table(a=1:10,times=1))\ntry(covariate_table(a=1:10,times=\"a\"))\ntry(covariate_table(a=1:10))\ncovariate_table(a=1:10,a=10:1,times=1:10)\ntry(covariate_table(a=1:10,a=10:1,times=\"a\"))\ntry(covariate_table(data.frame(a=1:10,a=10:1,check.names=FALSE),b=1:10,times=\"b\"))\ntry(covariate_table(data.frame(a=1:10,a=10:1),b=1:10,times=\"b\"))\ntry(covariate_table(a=1:10,b=10:1,times=\"b\"))\ntry(covariate_table(a=1:10,b=10:1,times=\"c\"))\ntry(covariate_table(a=1:10,b=10:1,times=NA))\n\ncovariate_table(\n  bspline_basis(times,nbasis=8,degree=3,deriv=0,names=\"f0\"),\n  bspline_basis(times,nbasis=8,degree=3,deriv=1,names=\"f1\"),\n  times=seq(0,10,by=0.1)\n) |>\n  lookup(t=seq(0,10,by=0.01)) |>\n  pivot_longer(-t) |>\n  separate(name,into=c(\"variable\",\"n\")) |>\n  ggplot(aes(x=t,y=value,color=factor(n)))+\n  labs(color=\"element\",y=\"\",x=\"\")+\n  geom_line()+\n  facet_grid(variable~.,\n    labeller=labeller(variable=c(f1=\"derivative\",f0=\"function\")))+\n  theme_bw()\n\ncovariate_table(\n  x=seq(1,10,by=1),\n  y=seq(2,20,by=2),\n  times=\"x\"\n) -> tab\nlookup(tab,c(0,2.5,3.6,10,20))\n\nrepair_lookup_table(tab,t=c(seq(0,10),20)) -> tab2\nlookup(tab2,c(0,2.5,3.6,10,20))\n\ncovariate_table(\n  x=seq(1,10,by=1),\n  y=seq(1,10,by=1),\n  order=\"const\",\n  times=\"x\"\n) -> tab\nlookup(tab,c(0,2.5,3.6,10,20))\n\nrepair_lookup_table(tab,t=c(seq(0,10,by=1),20)) -> tab2\nlookup(tab2,c(0,2.5,3.6,10,20))\n\ncovariate_table(\n  x=seq(1,10,by=1),\n  y=seq(1,10,by=1),\n  order=\"const\",\n  times=\"x\"\n) -> tab\n\nrepair_lookup_table(tab,t=c(seq(0,10,by=1),20),order=\"lin\") -> tab2\nlookup(tab2,c(0,2.5,3.6,10,20))\n\nrepair_lookup_table(tab,t=c(seq(0,10,by=1),20),order=\"const\") -> tab2\nlookup(tab2,c(0,2.5,3.6,10,20))\n\ndev.off()\n"
  },
  {
    "path": "tests/lookup.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> suppressPackageStartupMessages({\n+   library(tidyr)\n+   library(ggplot2)\n+ })\n> \n> png(filename=\"lookup-%02d.png\",res=100)\n> \n> library(pomp)\n> \n> ct <- covariate_table(x=20:30,y=10:0,times=seq(0,10))\n> lookup(ct,t=c(1,2.3,4,7,20))\n     t    x     y\n1  1.0 21.0   9.0\n2  2.3 22.3   7.7\n3  4.0 24.0   6.0\n4  7.0 27.0   3.0\n5 20.0 40.0 -10.0\nWarning message:\nin 'table_lookup': extrapolating at 2.000000e+01. \n> ct <- covariate_table(x=20:30,y=10:0,times=seq(0,10),order=\"constant\")\n> lookup(ct,t=c(1,2.3,4,7))\n    t  x y\n1 1.0 21 9\n2 2.3 22 8\n3 4.0 24 6\n4 7.0 27 3\n> lookup(ct,t=6.1)\n    t  x y\n1 6.1 26 4\n> plot(y~t,data=lookup(ct,t=seq(0,10.5,by=0.01)),type=\"l\")\nThere were 50 or more warnings (use warnings() to see the first 50)\n> lines(seq(0,10),10:0,col=\"blue\",type=\"s\")\n> plot(x~t,data=lookup(ct,t=seq(0,10.5,by=0.01)),type=\"l\")\nThere were 50 or more warnings (use warnings() to see the first 50)\n> lines(seq(0,10),20:30,col=\"blue\",type=\"s\")\n> \n> ct <- covariate_table(x=20:31,y=12:1,times=c(0:5,5:10),order=\"constant\")\n> lookup(ct,t=seq(4.9,5.1,by=0.05))\n     t  x y\n1 4.90 24 8\n2 4.95 24 8\n3 5.00 26 6\n4 5.05 26 6\n5 5.10 26 6\n> \n> try(covariate_table(x=20:30,y=10:0,times=seq(10,0)))\nError : in 'covariate_table': 'times' must be a non-decreasing numeric sequence (without missing values).\n> try(covariate_table(x=20:23,y=10:0,times=seq(0,10)))\nError : in 'covariate_table': binding columns: arguments imply differing number of rows: 4, 11\n> try(covariate_table(x=20:30,y=10:0,times=seq(0,3)))\nError : in 'covariate_table': 'times' must agree in length with the covariates.\n> covariate_table()\n<none>\n> try(covariate_table(times=1:10))\nError : in 'covariate_table': no covariates specified.\n> try(covariate_table(a=1:10,times=1))\nError : in 'covariate_table': 'times' must agree in length with the covariates.\n> try(covariate_table(a=1:10,times=\"a\"))\nError : in 'covariate_table': no covariates specified.\n> try(covariate_table(a=1:10))\nError : in 'covariate_table': 'times' is a required argument.\n> covariate_table(a=1:10,a=10:1,times=1:10)\n\n  - 10 records of 1 covariates, recorded from t = 1 to 10 \n  - summary of covariates:\n       a        \n Min.   : 1.00  \n 1st Qu.: 3.25  \n Median : 5.50  \n Mean   : 5.50  \n 3rd Qu.: 7.75  \n Max.   :10.00  \n> try(covariate_table(a=1:10,a=10:1,times=\"a\"))\nError : in 'covariate_table': no covariates specified.\n> try(covariate_table(data.frame(a=1:10,a=10:1,check.names=FALSE),b=1:10,times=\"b\"))\nError : in 'covariate_table': names of covariates must be unique.\n> try(covariate_table(data.frame(a=1:10,a=10:1),b=1:10,times=\"b\"))\n\n  - 10 records of 2 covariates, recorded from t = 1 to 10 \n  - summary of covariates:\n       a              a_1       \n Min.   : 1.00   Min.   : 1.00  \n 1st Qu.: 3.25   1st Qu.: 3.25  \n Median : 5.50   Median : 5.50  \n Mean   : 5.50   Mean   : 5.50  \n 3rd Qu.: 7.75   3rd Qu.: 7.75  \n Max.   :10.00   Max.   :10.00  \n> try(covariate_table(a=1:10,b=10:1,times=\"b\"))\nError : in 'covariate_table': 'times' must be a non-decreasing numeric sequence (without missing values).\n> try(covariate_table(a=1:10,b=10:1,times=\"c\"))\nError : in 'covariate_table': 'times' does not identify a unique time variable.\n> try(covariate_table(a=1:10,b=10:1,times=NA))\nError : 'covariate_table' is undefined for 'times' of class 'logical'.\n> \n> covariate_table(\n+   bspline_basis(times,nbasis=8,degree=3,deriv=0,names=\"f0\"),\n+   bspline_basis(times,nbasis=8,degree=3,deriv=1,names=\"f1\"),\n+   times=seq(0,10,by=0.1)\n+ ) |>\n+   lookup(t=seq(0,10,by=0.01)) |>\n+   pivot_longer(-t) |>\n+   separate(name,into=c(\"variable\",\"n\")) |>\n+   ggplot(aes(x=t,y=value,color=factor(n)))+\n+   labs(color=\"element\",y=\"\",x=\"\")+\n+   geom_line()+\n+   facet_grid(variable~.,\n+     labeller=labeller(variable=c(f1=\"derivative\",f0=\"function\")))+\n+   theme_bw()\n> \n> covariate_table(\n+   x=seq(1,10,by=1),\n+   y=seq(2,20,by=2),\n+   times=\"x\"\n+ ) -> tab\n> lookup(tab,c(0,2.5,3.6,10,20))\n     t    y\n1  0.0  0.0\n2  2.5  5.0\n3  3.6  7.2\n4 10.0 20.0\n5 20.0 40.0\nWarning messages:\n1: in 'table_lookup': extrapolating at 0.000000e+00. \n2: in 'table_lookup': extrapolating at 2.000000e+01. \n> \n> repair_lookup_table(tab,t=c(seq(0,10),20)) -> tab2\nWarning messages:\n1: in 'table_lookup': extrapolating at 0.000000e+00. \n2: in 'table_lookup': extrapolating at 2.000000e+01. \n> lookup(tab2,c(0,2.5,3.6,10,20))\n     t    y\n1  0.0  0.0\n2  2.5  5.0\n3  3.6  7.2\n4 10.0 20.0\n5 20.0 40.0\n> \n> covariate_table(\n+   x=seq(1,10,by=1),\n+   y=seq(1,10,by=1),\n+   order=\"const\",\n+   times=\"x\"\n+ ) -> tab\n> lookup(tab,c(0,2.5,3.6,10,20))\n     t  y\n1  0.0  1\n2  2.5  2\n3  3.6  3\n4 10.0 10\n5 20.0 10\nWarning messages:\n1: in 'table_lookup': extrapolating at 0.000000e+00. \n2: in 'table_lookup': extrapolating at 2.000000e+01. \n> \n> repair_lookup_table(tab,t=c(seq(0,10,by=1),20)) -> tab2\nWarning messages:\n1: in 'table_lookup': extrapolating at 0.000000e+00. \n2: in 'table_lookup': extrapolating at 2.000000e+01. \n> lookup(tab2,c(0,2.5,3.6,10,20))\n     t  y\n1  0.0  1\n2  2.5  2\n3  3.6  3\n4 10.0 10\n5 20.0 10\n> \n> covariate_table(\n+   x=seq(1,10,by=1),\n+   y=seq(1,10,by=1),\n+   order=\"const\",\n+   times=\"x\"\n+ ) -> tab\n> \n> repair_lookup_table(tab,t=c(seq(0,10,by=1),20),order=\"lin\") -> tab2\nWarning messages:\n1: in 'table_lookup': extrapolating at 0.000000e+00. \n2: in 'table_lookup': extrapolating at 2.000000e+01. \n> lookup(tab2,c(0,2.5,3.6,10,20))\n     t    y\n1  0.0  1.0\n2  2.5  2.5\n3  3.6  3.6\n4 10.0 10.0\n5 20.0 10.0\n> \n> repair_lookup_table(tab,t=c(seq(0,10,by=1),20),order=\"const\") -> tab2\nWarning messages:\n1: in 'table_lookup': extrapolating at 0.000000e+00. \n2: in 'table_lookup': extrapolating at 2.000000e+01. \n> lookup(tab2,c(0,2.5,3.6,10,20))\n     t  y\n1  0.0  1\n2  2.5  2\n3  3.6  3\n4 10.0 10\n5 20.0 10\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/map.R",
    "content": "library(pomp)\nlibrary(dplyr)\nlibrary(tidyr)\noptions(digits=3)\nset.seed(441155164)\n\n## Iterate a map using pomp\n\ntrajectory(\n  t0=0,\n  times=seq(0,1,by=1/52),\n  rinit = Csnippet(r\"{S = N; I = 0;}\"),\n  skeleton = map(\n    Csnippet(r\"{\n      double dt = 1.0/(52*200);\n      double rateS, transS;\n      double rateI, transI;\n      rateS = repno*gamma*(I+iota)/N;\n      rateI = gamma;\n      transS = (1.0 - exp(-rateS*dt))*S; \n      transI = (1.0 - exp(-rateI*dt))*I; \n      DS = S - transS;\n      DI = I + transS - transI;}\"\n    ),\n    delta.t = 1/52/200\n  ),\n  rprocess=euler(\n    Csnippet(r\"{\n      double rateS, transS;\n      double rateI, transI;\n      rateS = repno*gamma*(I+iota)/N;\n      rateI = gamma;\n      transS = (1.0 - exp(-rateS*dt))*S; \n      transI = (1.0 - exp(-rateI*dt))*I; \n      S -= transS;\n      I += transS - transI;}\"),\n    delta.t=1/52/200\n  ),\n  paramnames = c(\"gamma\",\"repno\",\"iota\",\"N\"),\n  statenames = c(\"S\",\"I\"),\n  params=c(gamma=365/8,repno=2,iota=1,N=1e5)\n) -> po\n\n## Iterate a map by hand\n\nstep <- function (x, repno, gamma, iota, N, dt) {\n  S <- x[1]\n  I <- x[2]\n  rateS <- repno*gamma*(I+iota)/N\n  rateI <- gamma\n  transS <- (1.0-exp(-rateS*dt))*S\n  transI <- (1.0-exp(-rateI*dt))*I\n  c(S=S-transS,I=I+transS-transI)\n}\n\ndt <- 1/(52*200) # Stepsize (should be consistent with dt in det_step)\ntimes <- seq(0,1,dt)\nstates <- matrix(nrow=length(times),ncol=2,dimnames=list(NULL,c(\"S\",\"I\")))\nstates[1,] <- rinit(po)\nfor (n in seq.int(2,length(times))) {\n  states[n,] <- step(\n    states[n-1,],\n    coef(po,\"repno\"),\n    coef(po,\"gamma\"),\n    coef(po,\"iota\"),\n    coef(po,\"N\"),\n    dt=dt\n  )\n}\n\n## checks that all three methods give the same result\nstopifnot(\n  bind_rows(\n    traj=as.data.frame(po),\n    sim=simulate(po,format=\"d\"),\n    direct=as.data.frame(cbind(time=times,states)),\n    .id=\"method\"\n  ) |>\n    select(method,time,I) |>\n    mutate(time=round(time,6)) |>\n    pivot_wider(names_from=method,values_from=I) |>\n    filter(!is.na(sim)) |>\n    arrange(time) |>\n    filter(!all.equal(traj,sim),!all.equal(sim,direct)) |>\n    nrow()==0\n)\n"
  },
  {
    "path": "tests/map.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> library(dplyr)\n\nAttaching package: 'dplyr'\n\nThe following objects are masked from 'package:stats':\n\n    filter, lag\n\nThe following objects are masked from 'package:base':\n\n    intersect, setdiff, setequal, union\n\n> library(tidyr)\n> options(digits=3)\n> set.seed(441155164)\n> \n> ## Iterate a map using pomp\n> \n> trajectory(\n+   t0=0,\n+   times=seq(0,1,by=1/52),\n+   rinit = Csnippet(r\"{S = N; I = 0;}\"),\n+   skeleton = map(\n+     Csnippet(r\"{\n+       double dt = 1.0/(52*200);\n+       double rateS, transS;\n+       double rateI, transI;\n+       rateS = repno*gamma*(I+iota)/N;\n+       rateI = gamma;\n+       transS = (1.0 - exp(-rateS*dt))*S; \n+       transI = (1.0 - exp(-rateI*dt))*I; \n+       DS = S - transS;\n+       DI = I + transS - transI;}\"\n+     ),\n+     delta.t = 1/52/200\n+   ),\n+   rprocess=euler(\n+     Csnippet(r\"{\n+       double rateS, transS;\n+       double rateI, transI;\n+       rateS = repno*gamma*(I+iota)/N;\n+       rateI = gamma;\n+       transS = (1.0 - exp(-rateS*dt))*S; \n+       transI = (1.0 - exp(-rateI*dt))*I; \n+       S -= transS;\n+       I += transS - transI;}\"),\n+     delta.t=1/52/200\n+   ),\n+   paramnames = c(\"gamma\",\"repno\",\"iota\",\"N\"),\n+   statenames = c(\"S\",\"I\"),\n+   params=c(gamma=365/8,repno=2,iota=1,N=1e5)\n+ ) -> po\n> \n> ## Iterate a map by hand\n> \n> step <- function (x, repno, gamma, iota, N, dt) {\n+   S <- x[1]\n+   I <- x[2]\n+   rateS <- repno*gamma*(I+iota)/N\n+   rateI <- gamma\n+   transS <- (1.0-exp(-rateS*dt))*S\n+   transI <- (1.0-exp(-rateI*dt))*I\n+   c(S=S-transS,I=I+transS-transI)\n+ }\n> \n> dt <- 1/(52*200) # Stepsize (should be consistent with dt in det_step)\n> times <- seq(0,1,dt)\n> states <- matrix(nrow=length(times),ncol=2,dimnames=list(NULL,c(\"S\",\"I\")))\n> states[1,] <- rinit(po)\n> for (n in seq.int(2,length(times))) {\n+   states[n,] <- step(\n+     states[n-1,],\n+     coef(po,\"repno\"),\n+     coef(po,\"gamma\"),\n+     coef(po,\"iota\"),\n+     coef(po,\"N\"),\n+     dt=dt\n+   )\n+ }\n> \n> ## checks that all three methods give the same result\n> stopifnot(\n+   bind_rows(\n+     traj=as.data.frame(po),\n+     sim=simulate(po,format=\"d\"),\n+     direct=as.data.frame(cbind(time=times,states)),\n+     .id=\"method\"\n+   ) |>\n+     select(method,time,I) |>\n+     mutate(time=round(time,6)) |>\n+     pivot_wider(names_from=method,values_from=I) |>\n+     filter(!is.na(sim)) |>\n+     arrange(time) |>\n+     filter(!all.equal(traj,sim),!all.equal(sim,direct)) |>\n+     nrow()==0\n+ )\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> \n"
  },
  {
    "path": "tests/mcap.R",
    "content": "png(filename=\"mcap-%02d.png\",width=7,height=7,units=\"in\",res=100)\n\nlibrary(pomp)\nlibrary(dplyr)\nset.seed(722855899)\n\nprofile_design(\n  theta=seq(-2,2,length=100),\n  lower=c(a=0,b=0),\n  upper=c(a=1,b=2),\n  nprof=10\n) |>\n  mutate(\n    logLik=rnorm(\n      n=length(theta),\n      mean=-theta^2-0.1*(theta+0.5)^4-300,\n      sd=0.3*(a+b)\n    )\n  ) -> x\n\nmcp <- mcap(x$logLik,x$theta)\n\nplot(logLik~theta,data=x,pch=16)\nlines(smoothed~parameter,data=mcp$fit,col=4,lwd=3)\nlines(quadratic~parameter,data=mcp$fit,col=7,lwd=3)\nabline(v=mcp$ci,lwd=3,lty=2,col=1)\nabline(v=mcp$mle,lwd=3,lty=3,col=1)\ntext(x=-0.7,y=-305,labels=bquote(MLE==.(signif(mcp$mle,2))))\ntext(x=-0.7,y=-306,labels=bquote(se[stat]==.(signif(mcp$se_stat,3))))\ntext(x=-0.7,y=-306.5,labels=bquote(se[mc]==.(signif(mcp$se_mc,3))))\ntext(x=-0.7,y=-307,labels=bquote(se[total]==.(signif(mcp$se,3))))\n\ndev.off()\n"
  },
  {
    "path": "tests/mcap.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> png(filename=\"mcap-%02d.png\",width=7,height=7,units=\"in\",res=100)\n> \n> library(pomp)\n> library(dplyr)\n\nAttaching package: 'dplyr'\n\nThe following objects are masked from 'package:stats':\n\n    filter, lag\n\nThe following objects are masked from 'package:base':\n\n    intersect, setdiff, setequal, union\n\n> set.seed(722855899)\n> \n> profile_design(\n+   theta=seq(-2,2,length=100),\n+   lower=c(a=0,b=0),\n+   upper=c(a=1,b=2),\n+   nprof=10\n+ ) |>\n+   mutate(\n+     logLik=rnorm(\n+       n=length(theta),\n+       mean=-theta^2-0.1*(theta+0.5)^4-300,\n+       sd=0.3*(a+b)\n+     )\n+   ) -> x\n> \n> mcp <- mcap(x$logLik,x$theta)\n> \n> plot(logLik~theta,data=x,pch=16)\n> lines(smoothed~parameter,data=mcp$fit,col=4,lwd=3)\n> lines(quadratic~parameter,data=mcp$fit,col=7,lwd=3)\n> abline(v=mcp$ci,lwd=3,lty=2,col=1)\n> abline(v=mcp$mle,lwd=3,lty=3,col=1)\n> text(x=-0.7,y=-305,labels=bquote(MLE==.(signif(mcp$mle,2))))\n> text(x=-0.7,y=-306,labels=bquote(se[stat]==.(signif(mcp$se_stat,3))))\n> text(x=-0.7,y=-306.5,labels=bquote(se[mc]==.(signif(mcp$se_mc,3))))\n> text(x=-0.7,y=-307,labels=bquote(se[total]==.(signif(mcp$se,3))))\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/measure.R",
    "content": "options(digits=3)\n\nlibrary(pomp)\n\npo <- window(ou2(),end=10)\n\nset.seed(3434388L)\nsimulate(po,nsim=5,format=\"arrays\") -> sm\nx <- sm$states\ny <- sm$obs[,1,]\nt <- time(po)\np <- coef(po)\n\ndmeasure(po) -> L1\ndmeasure(po,x=x,y=y,times=t,params=p) -> L\ndmeasure(po,x=x,y=y,times=t,params=p,log=TRUE) -> ll\ndmeasure(po,x=x,y=y,times=t,log=TRUE,\n  params=array(data=p,dim=length(p),dimnames=list(names(p)))) -> ll2\ndmeasure(\n  po,\n  x=array(data=x,dim=c(dim(x),1,1),\n    dimnames=list(rownames(x),NULL,NULL,NULL,NULL)),\n  y=y,\n  times=t,log=TRUE,\n  params=array(data=p,dim=length(p),dimnames=list(names(p)))\n) -> ll3\ndmeasure(\n  po,\n  x=array(data=x[,1,1],dim=nrow(x),dimnames=list(rownames(x))),\n  y=y[,1],\n  times=t[1],\n  params=p,\n  log=TRUE\n) -> ll4\nstopifnot(\n  dim(L1)==c(1,length(time(po))),\n  all.equal(ll[,1:3],log(L[,1:3])),\n  identical(dim(ll),c(5L,10L)),\n  all.equal(ll,ll2),\n  all.equal(ll,ll3),\n  all.equal(ll[1,1],ll4[1,1])\n)\n\ntry(dmeasure(\"ou2\",x=x,y=y,times=t,params=p))\ntry(dmeasure(x=x,y=y,times=t,params=p))\ntry(dmeasure(x,y=y,times=t,params=p))\ndmeasure(po,x=x,y=y,times=t) -> L1\ndmeasure(po,x=x,y=y,params=p) -> L2\ndmeasure(po,x=x,times=t,params=p) -> L3\ndmeasure(po,y=y,times=t,params=p) -> L4\nstopifnot(\n  identical(L1,L2),\n  dim(L3)==c(5,10),\n  dim(L4)==c(1,10)\n)\ntry(dmeasure(po,x=as.numeric(x),y=y,times=t,params=p))\ntry(dmeasure(po,x=x,y=as.numeric(y),times=t,params=p))\ntry(dmeasure(po,x=x,y=y,times=NULL,params=p))\ntry(dmeasure(po,x=x[,,1],y=y[,1,drop=FALSE],times=t[1],params=p))\ninvisible(dmeasure(po,x=x[,,1,drop=FALSE],y=y[,1],times=t[1],params=p))\nstopifnot(\n  all.equal(dmeasure(po,x=x[,1,,drop=FALSE],y=y,times=t,params=p),\n    dmeasure(po,x=x[,1,],y=y,times=t,params=p))\n)\ntry(dmeasure(po,x=x,y=y[1,,drop=FALSE],times=t,params=p))\ntry(dmeasure(po,x=x[1,,,drop=FALSE],y=y,times=t,params=p))\nk <- which(names(p)==\"tau\")\ntry(dmeasure(po,x=x,y=y,times=t,params=p[-k]))\n\npp <- parmat(p,5)\ntry(dmeasure(po,x=x,y=y,times=t,params=pp[,1:3]))\ndmeasure(po,x=x,y=y,times=t,params=pp) -> d\nstopifnot(\n  dim(d)==c(5,10),\n  names(dimnames(d))==c(\".id\",\"time\")\n)\n\nrmeasure(po) -> y1\nrmeasure(po,x=x,times=t,params=p) -> y\nstopifnot(\n  dim(y1)==c(2,1,10),\n  names(dimnames(y1))==c(\"name\",\".id\",\"time\"),\n  dim(y)==c(2,5,10),\n  names(dimnames(y))==c(\"name\",\".id\",\"time\")\n)\n\ntry(rmeasure(\"ou2\",x=x,times=t,params=p))\ntry(rmeasure(x=x,times=t,params=p))\ntry(rmeasure(x,times=t,params=p))\nfreeze(rmeasure(po,x=x,times=t),seed=30998684) -> xx1\nfreeze(rmeasure(po,x=x,params=p),seed=30998684) -> xx2\nstopifnot(identical(xx1,xx2))\ntry(rmeasure(po,x=as.numeric(x),times=t,params=p))\ntry(rmeasure(po,x=x,times=NULL,params=p))\ntry(rmeasure(po,x=x[,,1],times=t[1],params=p))\ninvisible(rmeasure(po,x=x[,,1,drop=FALSE],times=t[1],params=p))\ntry(rmeasure(po,x=x[1,,,drop=FALSE],times=t,params=p))\nk <- which(names(p)==\"tau\")\ntry(rmeasure(po,x=x,times=t,params=p[-k]))\n\npp <- parmat(p,5)\ntry(rmeasure(po,x=x,times=t,params=pp[,1:3]))\nrmeasure(po,x=x,times=t,params=pp) -> y\nstopifnot(\n  dim(y)==c(2,5,10),\n  names(dimnames(y))==c(\"name\",\".id\",\"time\")\n)\n\npo |> pomp(\n  rmeasure=function(...)c(1,2,3),\n  dmeasure=function(...,log)c(3,2)\n) -> po1\ntry(po1 |> rmeasure(x=x,times=t,params=p))\ntry(po1 |> dmeasure(x=x,y=y[,1,],times=t,params=p))\n\npo |> pomp(\n  rmeasure=NULL,\n  dmeasure=NULL\n) -> po1\npo1 |> rmeasure(x=x,times=t,params=p) |> is.na() |> stopifnot()\npo1 |> dmeasure(x=x,y=y[,1,],times=t,params=p) |> is.na() |> stopifnot()\n\nsir() -> sir\npo <- window(sir,end=0.5)\n\nset.seed(3434388L)\nsimulate(po,nsim=5,format=\"arrays\") -> sm\nx <- sm$states\ny <- sm$obs[,1,,drop=FALSE]\nt <- time(po)\np <- coef(po)\n\npo |> dmeasure(x=x,y=y,params=p,times=t,log=TRUE) -> d\npo |> rmeasure(x=x,params=p,times=t) -> yy\n\npo |>\n  pomp(dmeasure=function(...,log)1) |>\n  dmeasure(x=x,y=y,params=p,times=t) -> d\n\ntry({\n  pp <- p\n  names(pp)[3] <- NA\n  po |> rmeasure(x=x,params=pp,times=t)\n})\n\ntry({\n  pp <- p\n  names(pp)[3] <- \"\"\n  po |> rmeasure(x=x,params=pp,times=t)\n})\n\ntry({\n  pp <- p\n  names(pp) <- NULL\n  po |> rmeasure(x=x,params=pp,times=t)\n})\n"
  },
  {
    "path": "tests/measure.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> \n> library(pomp)\n> \n> po <- window(ou2(),end=10)\n> \n> set.seed(3434388L)\n> simulate(po,nsim=5,format=\"arrays\") -> sm\n> x <- sm$states\n> y <- sm$obs[,1,]\n> t <- time(po)\n> p <- coef(po)\n> \n> dmeasure(po) -> L1\n> dmeasure(po,x=x,y=y,times=t,params=p) -> L\n> dmeasure(po,x=x,y=y,times=t,params=p,log=TRUE) -> ll\n> dmeasure(po,x=x,y=y,times=t,log=TRUE,\n+   params=array(data=p,dim=length(p),dimnames=list(names(p)))) -> ll2\n> dmeasure(\n+   po,\n+   x=array(data=x,dim=c(dim(x),1,1),\n+     dimnames=list(rownames(x),NULL,NULL,NULL,NULL)),\n+   y=y,\n+   times=t,log=TRUE,\n+   params=array(data=p,dim=length(p),dimnames=list(names(p)))\n+ ) -> ll3\n> dmeasure(\n+   po,\n+   x=array(data=x[,1,1],dim=nrow(x),dimnames=list(rownames(x))),\n+   y=y[,1],\n+   times=t[1],\n+   params=p,\n+   log=TRUE\n+ ) -> ll4\n> stopifnot(\n+   dim(L1)==c(1,length(time(po))),\n+   all.equal(ll[,1:3],log(L[,1:3])),\n+   identical(dim(ll),c(5L,10L)),\n+   all.equal(ll,ll2),\n+   all.equal(ll,ll3),\n+   all.equal(ll[1,1],ll4[1,1])\n+ )\n> \n> try(dmeasure(\"ou2\",x=x,y=y,times=t,params=p))\nError : 'dmeasure' is undefined for 'object' of class 'character'.\n> try(dmeasure(x=x,y=y,times=t,params=p))\nError : in 'dmeasure': 'object' is a required argument.\n> try(dmeasure(x,y=y,times=t,params=p))\nError : 'dmeasure' is undefined for 'object' of class 'array'.\n> dmeasure(po,x=x,y=y,times=t) -> L1\n> dmeasure(po,x=x,y=y,params=p) -> L2\n> dmeasure(po,x=x,times=t,params=p) -> L3\n> dmeasure(po,y=y,times=t,params=p) -> L4\n> stopifnot(\n+   identical(L1,L2),\n+   dim(L3)==c(5,10),\n+   dim(L4)==c(1,10)\n+ )\n> try(dmeasure(po,x=as.numeric(x),y=y,times=t,params=p))\nError : in 'dmeasure': length of 'times' and 3rd dimension of 'x' do not agree.\n> try(dmeasure(po,x=x,y=as.numeric(y),times=t,params=p))\nError : in 'dmeasure': length of 'times' and 2nd dimension of 'y' do not agree.\n> try(dmeasure(po,x=x,y=y,times=NULL,params=p))\nError : in 'dmeasure': length('times') = 0, no work to do.\n> try(dmeasure(po,x=x[,,1],y=y[,1,drop=FALSE],times=t[1],params=p))\nError : in 'dmeasure': length of 'times' and 3rd dimension of 'x' do not agree.\n> invisible(dmeasure(po,x=x[,,1,drop=FALSE],y=y[,1],times=t[1],params=p))\n> stopifnot(\n+   all.equal(dmeasure(po,x=x[,1,,drop=FALSE],y=y,times=t,params=p),\n+     dmeasure(po,x=x[,1,],y=y,times=t,params=p))\n+ )\n> try(dmeasure(po,x=x,y=y[1,,drop=FALSE],times=t,params=p))\nError : in 'dmeasure': variable 'y2' not found among the observables.\n> try(dmeasure(po,x=x[1,,,drop=FALSE],y=y,times=t,params=p))\nError : in 'dmeasure': variable 'x2' not found among the state variables.\n> k <- which(names(p)==\"tau\")\n> try(dmeasure(po,x=x,y=y,times=t,params=p[-k]))\nError : in 'dmeasure': variable 'tau' not found among the parameters.\n> \n> pp <- parmat(p,5)\n> try(dmeasure(po,x=x,y=y,times=t,params=pp[,1:3]))\nError : in 'dmeasure': larger number of replicates is not a multiple of smaller.\n> dmeasure(po,x=x,y=y,times=t,params=pp) -> d\n> stopifnot(\n+   dim(d)==c(5,10),\n+   names(dimnames(d))==c(\".id\",\"time\")\n+ )\n> \n> rmeasure(po) -> y1\n> rmeasure(po,x=x,times=t,params=p) -> y\n> stopifnot(\n+   dim(y1)==c(2,1,10),\n+   names(dimnames(y1))==c(\"name\",\".id\",\"time\"),\n+   dim(y)==c(2,5,10),\n+   names(dimnames(y))==c(\"name\",\".id\",\"time\")\n+ )\n> \n> try(rmeasure(\"ou2\",x=x,times=t,params=p))\nError : 'rmeasure' is undefined for 'object' of class 'character'.\n> try(rmeasure(x=x,times=t,params=p))\nError : in 'rmeasure': 'object' is a required argument.\n> try(rmeasure(x,times=t,params=p))\nError : 'rmeasure' is undefined for 'object' of class 'array'.\n> freeze(rmeasure(po,x=x,times=t),seed=30998684) -> xx1\n> freeze(rmeasure(po,x=x,params=p),seed=30998684) -> xx2\n> stopifnot(identical(xx1,xx2))\n> try(rmeasure(po,x=as.numeric(x),times=t,params=p))\nError : in 'rmeasure': length of 'times' and 3rd dimension of 'x' do not agree.\n> try(rmeasure(po,x=x,times=NULL,params=p))\nError : in 'rmeasure': length('times') = 0, no work to do.\n> try(rmeasure(po,x=x[,,1],times=t[1],params=p))\nError : in 'rmeasure': length of 'times' and 3rd dimension of 'x' do not agree.\n> invisible(rmeasure(po,x=x[,,1,drop=FALSE],times=t[1],params=p))\n> try(rmeasure(po,x=x[1,,,drop=FALSE],times=t,params=p))\nError : in 'rmeasure': variable 'x2' not found among the state variables.\n> k <- which(names(p)==\"tau\")\n> try(rmeasure(po,x=x,times=t,params=p[-k]))\nError : in 'rmeasure': variable 'tau' not found among the parameters.\n> \n> pp <- parmat(p,5)\n> try(rmeasure(po,x=x,times=t,params=pp[,1:3]))\nError : in 'rmeasure': larger number of replicates is not a multiple of smaller.\n> rmeasure(po,x=x,times=t,params=pp) -> y\n> stopifnot(\n+   dim(y)==c(2,5,10),\n+   names(dimnames(y))==c(\"name\",\".id\",\"time\")\n+ )\n> \n> po |> pomp(\n+   rmeasure=function(...)c(1,2,3),\n+   dmeasure=function(...,log)c(3,2)\n+ ) -> po1\n> try(po1 |> rmeasure(x=x,times=t,params=p))\nError : in 'rmeasure': 'rmeasure' must return a named numeric vector.\n> try(po1 |> dmeasure(x=x,y=y[,1,],times=t,params=p))\nError : in 'dmeasure': user 'dmeasure' returns a vector of length 2 when it should return a scalar.\n> \n> po |> pomp(\n+   rmeasure=NULL,\n+   dmeasure=NULL\n+ ) -> po1\n> po1 |> rmeasure(x=x,times=t,params=p) |> is.na() |> stopifnot()\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> po1 |> dmeasure(x=x,y=y[,1,],times=t,params=p) |> is.na() |> stopifnot()\nWarning message:\n'dmeasure' unspecified: likelihood undefined. \n> \n> sir() -> sir\n> po <- window(sir,end=0.5)\n> \n> set.seed(3434388L)\n> simulate(po,nsim=5,format=\"arrays\") -> sm\n> x <- sm$states\n> y <- sm$obs[,1,,drop=FALSE]\n> t <- time(po)\n> p <- coef(po)\n> \n> po |> dmeasure(x=x,y=y,params=p,times=t,log=TRUE) -> d\n> po |> rmeasure(x=x,params=p,times=t) -> yy\n> \n> po |>\n+   pomp(dmeasure=function(...,log)1) |>\n+   dmeasure(x=x,y=y,params=p,times=t) -> d\n> \n> try({\n+   pp <- p\n+   names(pp)[3] <- NA\n+   po |> rmeasure(x=x,params=pp,times=t)\n+ })\nError : in 'rmeasure': variable 'iota' not found among the parameters.\n> \n> try({\n+   pp <- p\n+   names(pp)[3] <- \"\"\n+   po |> rmeasure(x=x,params=pp,times=t)\n+ })\nError : in 'rmeasure': variable 'iota' not found among the parameters.\n> \n> try({\n+   pp <- p\n+   names(pp) <- NULL\n+   po |> rmeasure(x=x,params=pp,times=t)\n+ })\nError : in 'rmeasure': variable 'gamma' not found among the parameters.\n> \n"
  },
  {
    "path": "tests/mif2.R",
    "content": "options(digits=3)\npng(filename=\"mif2-%02d.png\",res=100)\n\nset.seed(857075216L)\n\nlibrary(pomp)\nlibrary(dplyr)\n\ngompertz() |> window(end=10) -> po\n\nmif2(po,Nmif=50,Np=100,cooling.fraction.50=0.5,\n  rw.sd=rw_sd(sigma=0.02,K=0.02,r=0.02)) -> mf1\nmif2(po,Nmif=50,Np=100,cooling.fraction.50=0.5,\n  rw.sd=rw_sd(sigma=0.02,K=0.02,r=0.02)) -> mf2\nplot(mf1)\nplot(c(a=mf1,b=mf2) -> mfl,y=NA)\nc(a=mf1,b=c(mf1,mf2))\ndim(as.data.frame(c(a=mf1,b=c(mf1,mf2))))\nmfl[1]\nmfl[\"b\"]\nmfl[5]\ntraces(mfl) -> tr\nstopifnot(\n  length(tr)==2,\n  names(tr)==c(\"a\",\"b\"),\n  dim(tr$a)==dim(tr$b),\n  identical(dimnames(tr$a),dimnames(tr$b)),\n  colnames(tr$a)==c(\"loglik\",\"K\",\"r\",\"sigma\",\"tau\",\"X_0\")\n)\ncoef(mfl) -> m\nstopifnot(\n  dim(m)==c(5,2),\n  colnames(m)==c(\"a\",\"b\"),\n  rownames(m)==names(coef(po))\n)\n\nmfl |>\n  traces(transform=TRUE,pars=c(\"r\",\"sigma\")) -> tr\nstopifnot(\n  length(tr)==2,\n  names(tr)==c(\"a\",\"b\"),\n  dim(tr$a)==dim(tr$b),\n  identical(dimnames(tr$a),dimnames(tr$b)),\n  colnames(tr$a)==c(\"r\",\"sigma\")\n)\n\ntry(mfl |> traces(pars=\"bob\"))\n\ntry(mif2())\ntry(mif2(\"po\"))\ntry(mif2(po,Nmif=NA,Np=100))\ntry(mif2(po,Nmif=NULL,Np=100))\ntry(mif2(po,Nmif=-10,Np=100))\ntry(mif2(po,Nmif=c(10,20),Np=100))\ntry(mif2(po,Nmif=1,Np=function(k)c(10,20)))\ntry(mif2(po,Nmif=1,Np=\"bob\"))\ntry(mif2(po,Nmif=list(),Np=100))\ntry(mif2(po,Nmif=1,Np=Inf))\ntry(mif2(po,Nmif=1,Np=100))\ntry(mif2(po,Nmif=1,Np=NULL))\ntry(mif2(po,Nmif=1,Np=c(3,4)))\ntry(mif2(po,Nmif=1,Np=c(rep(100,10),40),rw.sd=rw_sd(sigma=0.1),cooling.fraction.50=0.5))\nmif2(po,Nmif=1,Np=c(rep(100,9),40,100),rw.sd=rw_sd(sigma=0.1),cooling.fraction.50=0.5)\ntry(mif2(po,Nmif=1,Np=100,rw.sd=3))\ntry(mif2(po,Nmif=1,Np=100,rw.sd=rw_sd()))\ntry(mif2(po,Nmif=1,Np=100,rw.sd=rw_sd(a=9)))\ntry(mif2(po,Nmif=1,Np=100,rw.sd=rw_sd(sigma=1:1000)))\ntry(mif2(po,Nmif=1,Np=100,rw.sd=rw_sd(sigma=0.1)))\ntry(mif2(po,Nmif=1,Np=100,rw.sd=rw_sd(NULL)))\ntry(mif2(po,Nmif=1,Np=100,rw.sd=rw_sd(sigma=0.1),cooling.fraction.50=12))\ntry(mif2(po,Nmif=1,Np=100,rw.sd=rw_sd(sigma=0.1),cooling.fraction.50=NA))\ntry(mif2(po,Nmif=1,Np=100,rw.sd=rw_sd(sigma=0.1),cooling.fraction.50=c(0.1,1)))\ntry(mif2(po,Nmif=1,Np=100,rw.sd=rw_sd(sigma=0.1),cooling.fraction.50=NULL))\ntry(mif2(po,params=NULL,Nmif=1,Np=100,rw.sd=rw_sd(sigma=0.1)))\ntry(mif2(po,params=list(),Nmif=1,Np=100,rw.sd=rw_sd(sigma=0.1)))\ntry(mif2(po,params=list(NULL),Nmif=1,Np=100,rw.sd=rw_sd(sigma=0.1)))\ntry(mif2(po,params=c(3,2,1),Nmif=1,Np=100,rw.sd=rw_sd(sigma=0.1)))\ntry(mif2(po,Nmif=1,Np=100:1000,rw.sd=rw_sd(sigma=0.1)))\nmif2(po,Nmif=2,Np=50,rw.sd=rw_sd(sigma=0.01,X_0=ivp(0.01)),\n  cooling.fraction.50=0.1,cooling.type=\"geometric\",\n  params=as.list(coef(po)))\ntry(mif2(po,Nmif=2,Np=100,rw.sd=rw_sd(sigma=0.01,X_0=ivp(0.01)),\n  cooling.fraction.50=0.1,rprocess=onestep(function(x,t,params,covars,delta.t,...)stop(\"boink\"))))\ntry(mif2(po,Nmif=2,Np=100,rw.sd=rw_sd(sigma=0.01,X_0=ivp(0.01)),\n  cooling.fraction.50=0.1,dmeasure=function(log,...)stop(\"blop\")))\ntry(mif2(po,Nmif=2,Np=100,rw.sd=rw_sd(sigma=0.01,X_0=ivp(0.01)),\n  cooling.fraction.50=0.1,dmeasure=function(log,...)NA))\ntry(\n  mif2(po,Nmif=2,Np=50,rw.sd=rw_sd(sigma=0.01),\n    cooling.type=\"hyper\",cooling.fraction.50=0.1,\n    drpocess=\"oops\",\n    dmeasure=function(log,...)0) -> mf3\n)\nmif2(po,Nmif=2,Np=50,rw.sd=rw_sd(sigma=0.01),\n  cooling.type=\"hyper\",cooling.fraction.50=0.1,\n  dmeasure=function(log,...)0) -> mf3\ntry(mif2(po,Nmif=2,Np=50,rw.sd=rw_sd(sigma=0.01),cooling.fraction.50=0.1,dmeasure=NULL))\ntry(mif2(po,Nmif=2,Np=50,rw.sd=rw_sd(sigma=0.01),cooling.fraction.50=0.1,rprocess=NULL))\ntry(mif2(po,Nmif=2,Np=50,rw.sd=rw_sd(sigma=0.01),cooling.fraction.50=0.1,params=NULL))\n\ntheta <- coef(po)\ntheta[\"sigma\"] <- 0.2\npo |>\n  pfilter(Np=100,params=theta) |>\n  mif2(Nmif=3,rw.sd=rw_sd(sigma=0.01,X_0=ivp(0.01)),cooling.fraction.50=0.5) |>\n  mif2() |> continue(Nmif=3,cooling.fraction.50=0.1) -> mf\nmf |>\n  plot(pars=c(\"X_0\",\"sigma\"),transform=TRUE)\n\ncapture.output(\n  mif2(po,Nmif=2,Np=100,rw.sd=rw_sd(sigma=0.01,X_0=ivp(0.01)),\n    cooling.fraction.50=1,cooling.type=\"hyperbolic\",\n    params=as.list(coef(po)),verbose=TRUE),\n  type=\"output\"\n) -> out\nstopifnot(sum(grepl(\"mif2 pfilter timestep\",out))==4,\n  sum(grepl(\"mif2 iteration\",out))==2)\n\npo |>\n  as.data.frame() |>\n  subset(select=-X) |>\n  mif2(Nmif=3,Np=100,\n    times=\"time\",t0=0,\n    params=c(sigma=5),\n    rw.sd=rw_sd(sigma=0.01),\n    cooling.fraction.50=1,cooling.type=\"hyperbolic\",\n    rprocess=onestep(function(X,...)c(X=X)),\n    dmeasure=function(Y,X,sigma,log,...)dnorm(x=Y,mean=X,sd=sigma,log=log),\n    rinit=function(...)c(X=0)\n  )\n\nmf3 |>\n  continue(dmeasure=Csnippet(\"lik = (give_log) ? R_NegInf : 0;\"))\n\ndev.off()\n"
  },
  {
    "path": "tests/mif2.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"mif2-%02d.png\",res=100)\n> \n> set.seed(857075216L)\n> \n> library(pomp)\n> library(dplyr)\n\nAttaching package: 'dplyr'\n\nThe following objects are masked from 'package:stats':\n\n    filter, lag\n\nThe following objects are masked from 'package:base':\n\n    intersect, setdiff, setequal, union\n\n> \n> gompertz() |> window(end=10) -> po\n> \n> mif2(po,Nmif=50,Np=100,cooling.fraction.50=0.5,\n+   rw.sd=rw_sd(sigma=0.02,K=0.02,r=0.02)) -> mf1\n> mif2(po,Nmif=50,Np=100,cooling.fraction.50=0.5,\n+   rw.sd=rw_sd(sigma=0.02,K=0.02,r=0.02)) -> mf2\n> plot(mf1)\n> plot(c(a=mf1,b=mf2) -> mfl,y=NA)\n> c(a=mf1,b=c(mf1,mf2))\n$a\n<object of class 'mif2d_pomp'>\n\n$b1\n<object of class 'mif2d_pomp'>\n\n$b2\n<object of class 'mif2d_pomp'>\n\n> dim(as.data.frame(c(a=mf1,b=c(mf1,mf2))))\n[1] 30  6\n> mfl[1]\n$a\n<object of class 'mif2d_pomp'>\n\n> mfl[\"b\"]\n$b\n<object of class 'mif2d_pomp'>\n\n> mfl[5]\n[[1]]\nNULL\n\n> traces(mfl) -> tr\n> stopifnot(\n+   length(tr)==2,\n+   names(tr)==c(\"a\",\"b\"),\n+   dim(tr$a)==dim(tr$b),\n+   identical(dimnames(tr$a),dimnames(tr$b)),\n+   colnames(tr$a)==c(\"loglik\",\"K\",\"r\",\"sigma\",\"tau\",\"X_0\")\n+ )\n> coef(mfl) -> m\n> stopifnot(\n+   dim(m)==c(5,2),\n+   colnames(m)==c(\"a\",\"b\"),\n+   rownames(m)==names(coef(po))\n+ )\n> \n> mfl |>\n+   traces(transform=TRUE,pars=c(\"r\",\"sigma\")) -> tr\n> stopifnot(\n+   length(tr)==2,\n+   names(tr)==c(\"a\",\"b\"),\n+   dim(tr$a)==dim(tr$b),\n+   identical(dimnames(tr$a),dimnames(tr$b)),\n+   colnames(tr$a)==c(\"r\",\"sigma\")\n+ )\n> \n> try(mfl |> traces(pars=\"bob\"))\nError : in 'traces': parameter 'bob' not found.\n> \n> try(mif2())\nError : in 'mif2': 'data' is a required argument.\n> try(mif2(\"po\"))\nError : 'mif2' is undefined for 'data' of class 'character'.\n> try(mif2(po,Nmif=NA,Np=100))\nError : in 'mif2': 'Nmif' must be a positive integer.\n> try(mif2(po,Nmif=NULL,Np=100))\nError : in 'mif2': 'Nmif' must be a positive integer.\n> try(mif2(po,Nmif=-10,Np=100))\nError : in 'mif2': 'Nmif' must be a positive integer.\n> try(mif2(po,Nmif=c(10,20),Np=100))\nError : in 'mif2': 'Nmif' must be a positive integer.\n> try(mif2(po,Nmif=1,Np=function(k)c(10,20)))\nError : in 'mif2': if 'Np' is a function, it must return a single positive integer.\n> try(mif2(po,Nmif=1,Np=\"bob\"))\nError : in 'mif2': 'Np' must be a number, a vector of numbers, or a function.\n> try(mif2(po,Nmif=list(),Np=100))\nError : in 'mif2': 'Nmif' must be a positive integer.\n> try(mif2(po,Nmif=1,Np=Inf))\nError : in 'mif2': number of particles, 'Np', must be a positive integer.\n> try(mif2(po,Nmif=1,Np=100))\nError : in 'mif2': 'rw.sd' must be specified!\n> try(mif2(po,Nmif=1,Np=NULL))\nError : in 'mif2': 'Np' must be specified.\n> try(mif2(po,Nmif=1,Np=c(3,4)))\nError : in 'mif2': 'Np' must have length 1 or length 11.\n> try(mif2(po,Nmif=1,Np=c(rep(100,10),40),rw.sd=rw_sd(sigma=0.1),cooling.fraction.50=0.5))\nError : in 'mif2': Np[1] must equal Np[11].\n> mif2(po,Nmif=1,Np=c(rep(100,9),40,100),rw.sd=rw_sd(sigma=0.1),cooling.fraction.50=0.5)\n<object of class 'mif2d_pomp'>\n> try(mif2(po,Nmif=1,Np=100,rw.sd=3))\nError : in 'mif2': 'rw.sd' should be specified using the 'rw_sd' function. See '?mif2'.\n> try(mif2(po,Nmif=1,Np=100,rw.sd=rw_sd()))\nError : in 'mif2': in 'rw.sd': parameters must be referenced by name.\n> try(mif2(po,Nmif=1,Np=100,rw.sd=rw_sd(a=9)))\nError : in 'mif2': the following parameter(s), given random walks in 'rw.sd', are not present in 'params': 'a'.\n> try(mif2(po,Nmif=1,Np=100,rw.sd=rw_sd(sigma=1:1000)))\nError : in 'mif2': 'rw.sd' spec for parameter 'sigma' does not evaluate to a vector of the correct length ('length(time(object))'=10).\n> try(mif2(po,Nmif=1,Np=100,rw.sd=rw_sd(sigma=0.1)))\nError : in 'mif2': 'cooling.fraction.50' is a required argument.\n> try(mif2(po,Nmif=1,Np=100,rw.sd=rw_sd(NULL)))\nError : in 'mif2': in 'rw.sd': parameters must be referenced by name.\n> try(mif2(po,Nmif=1,Np=100,rw.sd=rw_sd(sigma=0.1),cooling.fraction.50=12))\nError : in 'mif2': 'cooling.fraction.50' must be in (0,1].\n> try(mif2(po,Nmif=1,Np=100,rw.sd=rw_sd(sigma=0.1),cooling.fraction.50=NA))\nError : in 'mif2': 'cooling.fraction.50' must be in (0,1].\n> try(mif2(po,Nmif=1,Np=100,rw.sd=rw_sd(sigma=0.1),cooling.fraction.50=c(0.1,1)))\nError : in 'mif2': 'cooling.fraction.50' must be in (0,1].\n> try(mif2(po,Nmif=1,Np=100,rw.sd=rw_sd(sigma=0.1),cooling.fraction.50=NULL))\nError : in 'mif2': 'cooling.fraction.50' must be in (0,1].\n> try(mif2(po,params=NULL,Nmif=1,Np=100,rw.sd=rw_sd(sigma=0.1)))\nError : in 'mif2': the following parameter(s), given random walks in 'rw.sd', are not present in 'params': 'sigma'.\n> try(mif2(po,params=list(),Nmif=1,Np=100,rw.sd=rw_sd(sigma=0.1)))\nError : in 'mif2': the following parameter(s), given random walks in 'rw.sd', are not present in 'params': 'sigma'.\n> try(mif2(po,params=list(NULL),Nmif=1,Np=100,rw.sd=rw_sd(sigma=0.1)))\nError : in 'mif2': 'list' object cannot be coerced to type 'double'\n> try(mif2(po,params=c(3,2,1),Nmif=1,Np=100,rw.sd=rw_sd(sigma=0.1)))\nError : in 'mif2': 'params' must be a named numeric vector.\n> try(mif2(po,Nmif=1,Np=100:1000,rw.sd=rw_sd(sigma=0.1)))\nError : in 'mif2': 'Np' must have length 1 or length 11.\n> mif2(po,Nmif=2,Np=50,rw.sd=rw_sd(sigma=0.01,X_0=ivp(0.01)),\n+   cooling.fraction.50=0.1,cooling.type=\"geometric\",\n+   params=as.list(coef(po)))\n<object of class 'mif2d_pomp'>\n> try(mif2(po,Nmif=2,Np=100,rw.sd=rw_sd(sigma=0.01,X_0=ivp(0.01)),\n+   cooling.fraction.50=0.1,rprocess=onestep(function(x,t,params,covars,delta.t,...)stop(\"boink\"))))\nError : in 'mif2': in 'rprocess': boink\n> try(mif2(po,Nmif=2,Np=100,rw.sd=rw_sd(sigma=0.01,X_0=ivp(0.01)),\n+   cooling.fraction.50=0.1,dmeasure=function(log,...)stop(\"blop\")))\nError : in 'mif2': in 'dmeasure': blop\n> try(mif2(po,Nmif=2,Np=100,rw.sd=rw_sd(sigma=0.01,X_0=ivp(0.01)),\n+   cooling.fraction.50=0.1,dmeasure=function(log,...)NA))\nError : in 'mif2': 'dmeasure' with log=TRUE returns illegal value.\nLog likelihood, data, states, and parameters are:\n  time:            1\nloglik:           NA\n     Y:      1.02624\n     X:      1.10739\n     K:            1\n     r:          0.1\n sigma:    0.0996772\n   tau:          0.1\n   X_0:     0.990808\n> try(\n+   mif2(po,Nmif=2,Np=50,rw.sd=rw_sd(sigma=0.01),\n+     cooling.type=\"hyper\",cooling.fraction.50=0.1,\n+     drpocess=\"oops\",\n+     dmeasure=function(log,...)0) -> mf3\n+ )\nError : in 'mif2': The argument 'drpocess' is not recognized.\nUse the 'userdata' argument to supply extra objects to basic model components.\nSee '?userdata'.\n> mif2(po,Nmif=2,Np=50,rw.sd=rw_sd(sigma=0.01),\n+   cooling.type=\"hyper\",cooling.fraction.50=0.1,\n+   dmeasure=function(log,...)0) -> mf3\n> try(mif2(po,Nmif=2,Np=50,rw.sd=rw_sd(sigma=0.01),cooling.fraction.50=0.1,dmeasure=NULL))\nError : in 'mif2': 'rprocess', 'dmeasure' are needed basic components.\n> try(mif2(po,Nmif=2,Np=50,rw.sd=rw_sd(sigma=0.01),cooling.fraction.50=0.1,rprocess=NULL))\nError : in 'mif2': 'rprocess', 'dmeasure' are needed basic components.\n> try(mif2(po,Nmif=2,Np=50,rw.sd=rw_sd(sigma=0.01),cooling.fraction.50=0.1,params=NULL))\nError : in 'mif2': the following parameter(s), given random walks in 'rw.sd', are not present in 'params': 'sigma'.\n> \n> theta <- coef(po)\n> theta[\"sigma\"] <- 0.2\n> po |>\n+   pfilter(Np=100,params=theta) |>\n+   mif2(Nmif=3,rw.sd=rw_sd(sigma=0.01,X_0=ivp(0.01)),cooling.fraction.50=0.5) |>\n+   mif2() |> continue(Nmif=3,cooling.fraction.50=0.1) -> mf\n> mf |>\n+   plot(pars=c(\"X_0\",\"sigma\"),transform=TRUE)\n> \n> capture.output(\n+   mif2(po,Nmif=2,Np=100,rw.sd=rw_sd(sigma=0.01,X_0=ivp(0.01)),\n+     cooling.fraction.50=1,cooling.type=\"hyperbolic\",\n+     params=as.list(coef(po)),verbose=TRUE),\n+   type=\"output\"\n+ ) -> out\n> stopifnot(sum(grepl(\"mif2 pfilter timestep\",out))==4,\n+   sum(grepl(\"mif2 iteration\",out))==2)\n> \n> po |>\n+   as.data.frame() |>\n+   subset(select=-X) |>\n+   mif2(Nmif=3,Np=100,\n+     times=\"time\",t0=0,\n+     params=c(sigma=5),\n+     rw.sd=rw_sd(sigma=0.01),\n+     cooling.fraction.50=1,cooling.type=\"hyperbolic\",\n+     rprocess=onestep(function(X,...)c(X=X)),\n+     dmeasure=function(Y,X,sigma,log,...)dnorm(x=Y,mean=X,sd=sigma,log=log),\n+     rinit=function(...)c(X=0)\n+   )\n<object of class 'mif2d_pomp'>\n> \n> mf3 |>\n+   continue(dmeasure=Csnippet(\"lik = (give_log) ? R_NegInf : 0;\"))\n<object of class 'mif2d_pomp'>\nWarning message:\nfiltering failure at last filter iteration: using unweighted mean for point estimate. \n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/mif2_index.R",
    "content": "options(digits=3)\n\nlibrary(pomp)\n\ngompertz() -> gompertz\n\nset.seed(1481104436)\n\ngompertz |>\n  mif2(\n    Nmif=4,Np=1000,\n    .indices=seq.int(1000),\n    rw.sd=rw_sd(r=0.02,K=0.02,sigma=0.02),\n    cooling.fraction.50=0.5\n  ) |>\n  slot(\"indices\") -> idx\nstopifnot(\n  length(idx)==1000,\n  class(idx)==\"integer\"\n)\n\nset.seed(962724905)\n\ngompertz |>\n  mif2(\n    Nmif=4,Np=100,\n    .indices=as.list(seq.int(100)),\n    rw.sd=rw_sd(r=0.02,K=0.02,sigma=0.02),\n    cooling.fraction.50=0.5\n  ) |>\n  slot(\"indices\") -> idx\nstopifnot(\n  length(idx)==100,\n  class(idx)==\"list\"\n)\n\ntry(\n  mif2(\n    gompertz,\n    Nmif=1,Np=100,\n    .indices=1:5,\n    rw.sd=rw_sd(r=0.02,K=0.02,sigma=0.02),\n    cooling.fraction.50=0.5\n  )\n)\n"
  },
  {
    "path": "tests/mif2_index.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> \n> library(pomp)\n> \n> gompertz() -> gompertz\n> \n> set.seed(1481104436)\n> \n> gompertz |>\n+   mif2(\n+     Nmif=4,Np=1000,\n+     .indices=seq.int(1000),\n+     rw.sd=rw_sd(r=0.02,K=0.02,sigma=0.02),\n+     cooling.fraction.50=0.5\n+   ) |>\n+   slot(\"indices\") -> idx\n> stopifnot(\n+   length(idx)==1000,\n+   class(idx)==\"integer\"\n+ )\n> \n> set.seed(962724905)\n> \n> gompertz |>\n+   mif2(\n+     Nmif=4,Np=100,\n+     .indices=as.list(seq.int(100)),\n+     rw.sd=rw_sd(r=0.02,K=0.02,sigma=0.02),\n+     cooling.fraction.50=0.5\n+   ) |>\n+   slot(\"indices\") -> idx\n> stopifnot(\n+   length(idx)==100,\n+   class(idx)==\"list\"\n+ )\n> \n> try(\n+   mif2(\n+     gompertz,\n+     Nmif=1,Np=100,\n+     .indices=1:5,\n+     rw.sd=rw_sd(r=0.02,K=0.02,sigma=0.02),\n+     cooling.fraction.50=0.5\n+   )\n+ )\nError : in 'mif2': '.indices' has improper length.\n> \n"
  },
  {
    "path": "tests/mif2_kf.R",
    "content": "options(digits=3)\n\nlibrary(pomp)\nsuppressPackageStartupMessages({\n  library(dplyr)\n})\n\nset.seed(376098756)\n\ngompertz() |> window(end=10) |> simulate(seed=1176423047) -> po\n\npo |>\n  mif2(Nmif=100,Np=1000,cooling.fraction.50=0.4,cooling.type=\"geometric\",\n    rw.sd=rw_sd(sigma=0.02,r=0.02,X_0=ivp(0.05),tau=0.02)) |>\n  continue(Nmif=100) -> mf\nreplicate(n=10,mf |> pfilter(Np=3000)) -> pfs\npfs |> sapply(logLik) |> logmeanexp(se=TRUE) -> pf.ll.mle\n\nreplicate(n=10,po |> pfilter(Np=3000)) |>\n  sapply(logLik) |>\n  logmeanexp(se=TRUE) -> pf.ll.truth\n\npo |>\n  as.data.frame() |>\n  mutate(logY=log(Y)) |>\n  select(time,logY) |>\n  pomp(t0=0,times=\"time\") -> logpo\n  \npo |> coef() |> as.list() -> theta\npo |> rinit(params=coef(po)) |> as.numeric() -> x0\nwith(theta,c(x=log(x0/K))) -> X0\npo |> obs() |> log() -> y\nwith(theta,matrix(c(exp(-r)),1,1)) -> A\nwith(theta,matrix(c(sigma*sigma),1,1)) -> Q\nwith(theta,matrix(1,1,1)) -> C\nwith(theta,tau*tau) -> R\nkalmanFilter(logpo,X0=X0,A=A,Q=Q,C=C,R=R) -> kf.truth\n\nmf |> coef() |> as.list() -> theta\nmf |> rinit(params=coef(mf)) |> as.numeric() -> x0\nmf |> obs() |> log() -> y\nwith(theta,c(x=log(x0/K))) -> X0\nwith(theta,matrix(c(exp(-r)),1,1)) -> A\nwith(theta,matrix(c(sigma*sigma),1,1)) -> Q\nwith(theta,matrix(1,1,1)) -> C\nwith(theta,tau*tau) -> R\nkalmanFilter(logpo,X0=X0,A=A,Q=Q,C=C,R=R) -> kf.mle\n\ncat(\"likelihood at truth:\",kf.truth$logLik-sum(y),\"\\n\")\ncat(\"pfilter likelihood at truth:\",pf.ll.truth,\"\\n\")\ncat(\"likelihood at IF2 mle:\",kf.mle$logLik-sum(y),\"\\n\")\ncat(\"pfilter likelihood at IF2 mle:\",pf.ll.mle,\"\\n\")\n"
  },
  {
    "path": "tests/mif2_kf.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> \n> library(pomp)\n> suppressPackageStartupMessages({\n+   library(dplyr)\n+ })\n> \n> set.seed(376098756)\n> \n> gompertz() |> window(end=10) |> simulate(seed=1176423047) -> po\n> \n> po |>\n+   mif2(Nmif=100,Np=1000,cooling.fraction.50=0.4,cooling.type=\"geometric\",\n+     rw.sd=rw_sd(sigma=0.02,r=0.02,X_0=ivp(0.05),tau=0.02)) |>\n+   continue(Nmif=100) -> mf\n> replicate(n=10,mf |> pfilter(Np=3000)) -> pfs\n> pfs |> sapply(logLik) |> logmeanexp(se=TRUE) -> pf.ll.mle\n> \n> replicate(n=10,po |> pfilter(Np=3000)) |>\n+   sapply(logLik) |>\n+   logmeanexp(se=TRUE) -> pf.ll.truth\n> \n> po |>\n+   as.data.frame() |>\n+   mutate(logY=log(Y)) |>\n+   select(time,logY) |>\n+   pomp(t0=0,times=\"time\") -> logpo\n>   \n> po |> coef() |> as.list() -> theta\n> po |> rinit(params=coef(po)) |> as.numeric() -> x0\n> with(theta,c(x=log(x0/K))) -> X0\n> po |> obs() |> log() -> y\n> with(theta,matrix(c(exp(-r)),1,1)) -> A\n> with(theta,matrix(c(sigma*sigma),1,1)) -> Q\n> with(theta,matrix(1,1,1)) -> C\n> with(theta,tau*tau) -> R\n> kalmanFilter(logpo,X0=X0,A=A,Q=Q,C=C,R=R) -> kf.truth\n> \n> mf |> coef() |> as.list() -> theta\n> mf |> rinit(params=coef(mf)) |> as.numeric() -> x0\n> mf |> obs() |> log() -> y\n> with(theta,c(x=log(x0/K))) -> X0\n> with(theta,matrix(c(exp(-r)),1,1)) -> A\n> with(theta,matrix(c(sigma*sigma),1,1)) -> Q\n> with(theta,matrix(1,1,1)) -> C\n> with(theta,tau*tau) -> R\n> kalmanFilter(logpo,X0=X0,A=A,Q=Q,C=C,R=R) -> kf.mle\n> \n> cat(\"likelihood at truth:\",kf.truth$logLik-sum(y),\"\\n\")\nlikelihood at truth: 6.74 \n> cat(\"pfilter likelihood at truth:\",pf.ll.truth,\"\\n\")\npfilter likelihood at truth: 6.74 0.0158 \n> cat(\"likelihood at IF2 mle:\",kf.mle$logLik-sum(y),\"\\n\")\nlikelihood at IF2 mle: 8.03 \n> cat(\"pfilter likelihood at IF2 mle:\",pf.ll.mle,\"\\n\")\npfilter likelihood at IF2 mle: 8.02 0.0172 \n> \n"
  },
  {
    "path": "tests/nlf.R",
    "content": "options(digits=3)\npng(filename=\"nlf-%02d.png\",res=100)\n\nlibrary(pomp)\n\nset.seed(583615606L)\n\nou2() -> ou2\nestnames=c(\"alpha_2\",\"alpha_3\")\nou2 |> window(end=40) |> as.data.frame() |>\n  subset(select=c(time,y1,y2)) -> dat\nguess <- coef(ou2,estnames,transform=TRUE)\n\ntry(nlf_objfun())\ntry(nlf_objfun(\"bob\"))\n\ndat |>\n  nlf_objfun(times=\"time\",t0=0,params=coef(ou2),\n    lags=c(4,6),ti=100,tf=2000,seed=426094906L,\n    rprocess=ou2@rprocess,rmeasure=ou2@rmeasure,rinit=ou2@rinit) -> m0\n\nm0()\nstopifnot(m0(0)==m0(1))\nstopifnot(logLik(m0)==-m0(0))\n\nm2 <- nlf_objfun(m0,est=estnames,seed=426094906L)\nplot(sapply(seq(-1,1,by=0.1),function(x)m2(c(x,0))))\n\nlibrary(subplex)\nm2(guess) -> ll\nstopifnot(logLik(m2)==-ll)\nsubplex(par=guess,fn=m2,control=list(reltol=1e-3)) -> out\nstopifnot(out$convergence == 0)\nm2(out$par)\nplot(simulate(m2))\nstopifnot(logLik(m2)==-out$value)\n\nm2s <- nlf_objfun(m2,tensor=TRUE,period=10,seed=426094906L)\nplot(sapply(seq(-1,1,by=0.1),function(x)m2s(c(x,0))))\nsubplex(par=guess,fn=m2s,control=list(reltol=1e-3)) -> out\nstopifnot(out$convergence == 0)\nm2s(out$par)\nplot(simulate(m2s))\n\nm2t <- nlf_objfun(m2s,tensor=FALSE,seed=426094906L,fail.value=1e9)\nplot(sapply(seq(-1,1,by=0.1),function(x)m2t(c(x,0))))\nsubplex(par=guess,fn=m2t,control=list(reltol=1e-3)) -> out\nstopifnot(out$convergence == 0)\nm2t(out$par)\nplot(simulate(m2t))\nplot(pfilter(m2t,dmeasure=ou2@dmeasure,Np=100))\nm2t(NA)\n\nnlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500)\nnlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=500)\nnlf_objfun(ou2,lags=c(1,2,3),est=NULL,ti=100,tf=500)\ntry(nlf_objfun(ou2,lags=c(1,2,3),est=\"bob\",ti=100,tf=500))\ntry(nlf_objfun(ou2,lags=list(1,2,3),est=NULL,ti=100,tf=500))\ntry(nlf_objfun(ou2,lags=c(-1,2,3),est=estnames,ti=100,tf=500))\ntry(nlf_objfun(ou2,lags=c(),est=estnames,ti=100,tf=500))\ntry(nlf_objfun(ou2,lags=\"of course\",est=estnames,ti=100,tf=500))\ntry(nlf_objfun(ou2,lags=NULL,est=estnames,ti=100,tf=500))\ntry(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=-10,tf=500))\ntry(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=NULL,tf=500))\ntry(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=NA,tf=500))\ntry(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=c(12,16),tf=500))\ntry(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=NULL))\ntry(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=NA))\ntry(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=c(1,2,3)))\ntry(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=list(5)))\ntry(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=Inf))\ntry(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=\"yes\"))\ntry(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=50))\ntry(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=150))\nnlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=300)\ntry(nlf_objfun(ou2,lags=c(1,2,3),nrbf=2,ti=100,tf=500))\ntry(nlf_objfun(ou2,lags=c(1,2,3),nrbf=NA,ti=100,tf=500))\ntry(nlf_objfun(ou2,lags=c(1,2,3),nrbf=NULL,ti=100,tf=500))\ntry(nlf_objfun(ou2,lags=c(1,2,3),nrbf=\"4\",ti=100,tf=500))\ntry(nlf_objfun(ou2,lags=c(1,2,3),period=Inf,ti=100,tf=500))\nnlf_objfun(ou2,lags=c(1,2,3),period=-5,ti=100,tf=500)\ntry(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,transform.data=3))\ntry(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,transform.data=list()))\ntry(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,transform.data=\"bob\"))\ntry(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,transform.data=NULL))\ntry(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,transform.data=NA))\ntry(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,transform.data=function(x,y)x+y))\ntry(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,fail.value=c(10,20)))\ntry(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,fail.value=NULL))\ntry(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,fail.value=\"no\"))\ncapture.output(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,fail.value=10,verbose=TRUE)) -> out\nstopifnot(sum(grepl(\"logql = \",out))==1)\n\npo <- ou2\ntime(po) <- c(1:5,8:10)\ntry(po |> nlf_objfun(lags=c(1,2,3),period=5,ti=100,tf=500))\n\npo <- ou2\npo@data[2,15] <- NA\nstopifnot(po |> nlf_objfun(lags=c(1,2,3),ti=100,tf=500) |> logLik() |> is.na())\n\npo <- ou2\nstopifnot(po |> nlf_objfun(rmeasure=NULL,lags=c(1,2,3),ti=100,tf=500) |> logLik() |> is.na())\n\ntry(po |> nlf_objfun(covar=covariate_table(t=0:100,Z=100,times=\"t\"),ti=100,tf=500))\n\ndev.off()\n"
  },
  {
    "path": "tests/nlf.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"nlf-%02d.png\",res=100)\n> \n> library(pomp)\n> \n> set.seed(583615606L)\n> \n> ou2() -> ou2\n> estnames=c(\"alpha_2\",\"alpha_3\")\n> ou2 |> window(end=40) |> as.data.frame() |>\n+   subset(select=c(time,y1,y2)) -> dat\n> guess <- coef(ou2,estnames,transform=TRUE)\n> \n> try(nlf_objfun())\nError : in 'nlf_objfun': 'data' is a required argument.\n> try(nlf_objfun(\"bob\"))\nError : 'nlf_objfun' is undefined for 'data' of class 'character'.\n> \n> dat |>\n+   nlf_objfun(times=\"time\",t0=0,params=coef(ou2),\n+     lags=c(4,6),ti=100,tf=2000,seed=426094906L,\n+     rprocess=ou2@rprocess,rmeasure=ou2@rmeasure,rinit=ou2@rinit) -> m0\n> \n> m0()\n[1] 199\n> stopifnot(m0(0)==m0(1))\n> stopifnot(logLik(m0)==-m0(0))\n> \n> m2 <- nlf_objfun(m0,est=estnames,seed=426094906L)\n> plot(sapply(seq(-1,1,by=0.1),function(x)m2(c(x,0))))\n> \n> library(subplex)\n> m2(guess) -> ll\n> stopifnot(logLik(m2)==-ll)\n> subplex(par=guess,fn=m2,control=list(reltol=1e-3)) -> out\n> stopifnot(out$convergence == 0)\n> m2(out$par)\n[1] 198\n> plot(simulate(m2))\n> stopifnot(logLik(m2)==-out$value)\n> \n> m2s <- nlf_objfun(m2,tensor=TRUE,period=10,seed=426094906L)\n> plot(sapply(seq(-1,1,by=0.1),function(x)m2s(c(x,0))))\n> subplex(par=guess,fn=m2s,control=list(reltol=1e-3)) -> out\n> stopifnot(out$convergence == 0)\n> m2s(out$par)\n[1] 197\n> plot(simulate(m2s))\n> \n> m2t <- nlf_objfun(m2s,tensor=FALSE,seed=426094906L,fail.value=1e9)\n> plot(sapply(seq(-1,1,by=0.1),function(x)m2t(c(x,0))))\n> subplex(par=guess,fn=m2t,control=list(reltol=1e-3)) -> out\n> stopifnot(out$convergence == 0)\n> m2t(out$par)\n[1] 199\n> plot(simulate(m2t))\n> plot(pfilter(m2t,dmeasure=ou2@dmeasure,Np=100))\n> m2t(NA)\n[1] 1e+09\n> \n> nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500)\n<object of class 'nlf_objfun'>\n> nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=500)\n<object of class 'nlf_objfun'>\n> nlf_objfun(ou2,lags=c(1,2,3),est=NULL,ti=100,tf=500)\n<object of class 'nlf_objfun'>\n> try(nlf_objfun(ou2,lags=c(1,2,3),est=\"bob\",ti=100,tf=500))\nError : in 'nlf_objfun': parameter 'bob' not found in 'params'.\n> try(nlf_objfun(ou2,lags=list(1,2,3),est=NULL,ti=100,tf=500))\nError : in 'nlf_objfun': 'lags' must be positive integers.\n> try(nlf_objfun(ou2,lags=c(-1,2,3),est=estnames,ti=100,tf=500))\nError : in 'nlf_objfun': 'lags' must be positive integers.\n> try(nlf_objfun(ou2,lags=c(),est=estnames,ti=100,tf=500))\nError : in 'nlf_objfun': 'lags' must be positive integers.\n> try(nlf_objfun(ou2,lags=\"of course\",est=estnames,ti=100,tf=500))\nError : in 'nlf_objfun': 'lags' must be positive integers.\n> try(nlf_objfun(ou2,lags=NULL,est=estnames,ti=100,tf=500))\nError : in 'nlf_objfun': 'lags' must be positive integers.\n> try(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=-10,tf=500))\nError : in 'nlf_objfun': 'ti' must be a single numeric value larger than 't0'.\n> try(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=NULL,tf=500))\nError : in 'nlf_objfun': 'ti' must be a single numeric value larger than 't0'.\n> try(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=NA,tf=500))\nError : in 'nlf_objfun': 'ti' must be a single numeric value larger than 't0'.\n> try(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=c(12,16),tf=500))\nError : in 'nlf_objfun': 'ti' must be a single numeric value larger than 't0'.\n> try(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=NULL))\nError : in 'nlf_objfun': 'tf' must be a single numeric value larger than 'ti'.\n> try(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=NA))\nError : in 'nlf_objfun': 'tf' must be a single numeric value larger than 'ti'.\n> try(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=c(1,2,3)))\nError : in 'nlf_objfun': 'tf' must be a single numeric value larger than 'ti'.\n> try(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=list(5)))\nError : in 'nlf_objfun': 'tf' must be a single numeric value larger than 'ti'.\n> try(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=Inf))\nError : in 'nlf_objfun': 'tf' must be a single numeric value larger than 'ti'.\n> try(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=\"yes\"))\nError : in 'nlf_objfun': 'tf' must be a single numeric value larger than 'ti'.\n> try(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=50))\nError : in 'nlf_objfun': 'tf' must be a single numeric value larger than 'ti'.\n> try(nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=150))\nError : in 'nlf_objfun': insufficiently long simulated time series: increase 'tf' to at least 220.\n> nlf_objfun(ou2,lags=c(1,2,3),est=estnames,ti=100,tf=300)\n<object of class 'nlf_objfun'>\nWarning message:\nin 'nlf_objfun': insufficiently long simulated time series: consider increasing 'tf' to 460 or larger. \n> try(nlf_objfun(ou2,lags=c(1,2,3),nrbf=2,ti=100,tf=500))\nError : in 'nlf_objfun': 'nrbf' must be at least 4.\n> try(nlf_objfun(ou2,lags=c(1,2,3),nrbf=NA,ti=100,tf=500))\nError : in 'nlf_objfun': 'nrbf' must be at least 4.\n> try(nlf_objfun(ou2,lags=c(1,2,3),nrbf=NULL,ti=100,tf=500))\nError : in 'nlf_objfun': 'nrbf' must be at least 4.\n> try(nlf_objfun(ou2,lags=c(1,2,3),nrbf=\"4\",ti=100,tf=500))\nError : in 'nlf_objfun': 'nrbf' must be at least 4.\n> try(nlf_objfun(ou2,lags=c(1,2,3),period=Inf,ti=100,tf=500))\nError : in 'nlf_objfun': 'period' must be single finite number or NA.\n> nlf_objfun(ou2,lags=c(1,2,3),period=-5,ti=100,tf=500)\n<object of class 'nlf_objfun'>\n> try(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,transform.data=3))\nError : in 'nlf_objfun': object 'transform.data' of mode 'function' was not found\n> try(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,transform.data=list()))\nError : in 'nlf_objfun': object 'transform.data' of mode 'function' was not found\n> try(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,transform.data=\"bob\"))\nError : in 'nlf_objfun': object 'bob' of mode 'function' was not found\n> try(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,transform.data=NULL))\nError : in 'nlf_objfun': object 'transform.data' of mode 'function' was not found\n> try(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,transform.data=NA))\nError : in 'nlf_objfun': object 'transform.data' of mode 'function' was not found\n> try(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,transform.data=function(x,y)x+y))\nError : in 'nlf_objfun': in 'transform.data': argument \"y\" is missing, with no default\n> try(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,fail.value=c(10,20)))\nError : in 'nlf_objfun': 'fail.value' should be a single (large) number or 'NA'.\n> try(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,fail.value=NULL))\nError : in 'nlf_objfun': 'fail.value' should be a single (large) number or 'NA'.\n> try(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,fail.value=\"no\"))\nError : in 'nlf_objfun': 'fail.value' should be a single (large) number or 'NA'.\n> capture.output(nlf_objfun(ou2,lags=c(1,2,3),ti=100,tf=500,fail.value=10,verbose=TRUE)) -> out\nWarning message:\nin 'nlf_objfun': 'fail.value' should be a large number or 'NA'. \n> stopifnot(sum(grepl(\"logql = \",out))==1)\n> \n> po <- ou2\n> time(po) <- c(1:5,8:10)\n> try(po |> nlf_objfun(lags=c(1,2,3),period=5,ti=100,tf=500))\nError : in 'nlf_objfun': NLF requires uniform sampling frequency.\n> \n> po <- ou2\n> po@data[2,15] <- NA\n> stopifnot(po |> nlf_objfun(lags=c(1,2,3),ti=100,tf=500) |> logLik() |> is.na())\n> \n> po <- ou2\n> stopifnot(po |> nlf_objfun(rmeasure=NULL,lags=c(1,2,3),ti=100,tf=500) |> logLik() |> is.na())\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> \n> try(po |> nlf_objfun(covar=covariate_table(t=0:100,Z=100,times=\"t\"),ti=100,tf=500))\nError : in 'nlf_objfun': NLF is incompatible with time-varying covariates.\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/nullcases.R",
    "content": "library(pomp)\n\nsimulate(times=1:10,t0=0,\n         statenames=\"x\",\n         obsnames=\"y\",\n         params=c(x_0=0),\n         rprocess=onestep(function(...)c(x=1)),\n         rmeasure=Csnippet(\"\")\n) -> s1\nstates(s1)\nobs(s1)\n\nsimulate(times=1:10,t0=0,\n         statenames=\"x\",\n         params=c(x_0=0),\n         rprocess=onestep(function(...)c(x=1))\n) -> s2\nstates(s2)\nobs(s2)\n"
  },
  {
    "path": "tests/nullcases.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> \n> simulate(times=1:10,t0=0,\n+          statenames=\"x\",\n+          obsnames=\"y\",\n+          params=c(x_0=0),\n+          rprocess=onestep(function(...)c(x=1)),\n+          rmeasure=Csnippet(\"\")\n+ ) -> s1\n> states(s1)\n    time\nname [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n   x    1    1    1    1    1    1    1    1    1     1\n> obs(s1)\n    time\nname [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n   y   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA\n> \n> simulate(times=1:10,t0=0,\n+          statenames=\"x\",\n+          params=c(x_0=0),\n+          rprocess=onestep(function(...)c(x=1))\n+ ) -> s2\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> states(s2)\n    time\nname [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n   x    1    1    1    1    1    1    1    1    1     1\n> obs(s2)\n      time\nname   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n> \n"
  },
  {
    "path": "tests/ou2.R",
    "content": "library(pomp)\nsuppressPackageStartupMessages({\n  library(tidyr)\n  library(dplyr)\n  library(ggplot2)\n})\n\nset.seed(1438408329L)\n\npng(filename=\"ou2-%02d.png\",res=100)\n\nou2() -> po\nplot(po)\n\nstopifnot(\n  all.equal(\n    coef(po),\n    partrans(po,coef(po,transform=TRUE),dir=\"from\")\n  ),\n  all.equal(\n    coef(po,transform=TRUE),\n    partrans(po,coef(po),dir=\"to\")\n  )\n)\n\npfilter(\n  po,\n  Np=1000,\n  filter.mean=TRUE,\n  pred.mean=TRUE,\n  pred.var=TRUE,\n  filter.traj=TRUE,\n  save.states=\"filter\"\n) -> pf\n\nplot(pf,yax.flip=TRUE)\n\nforecast(pf,format=\"d\") -> fc\nsimulate(pf) -> sm\n\nemeasure(pf) |> melt() -> ef\nvmeasure(pf) |> melt() -> vf\nvf |> select(-time,-.id) |> distinct()\n\nbind_rows(\n  sim=sm |>\n    as.data.frame() |>\n    pivot_longer(c(x1,x2,y1,y2)),\n  forecast=fc,\n  filter=ef |> select(-.id),\n  prediction=pred_mean(pf,format=\"d\"),\n  filter=filter_mean(pf,format=\"d\"),\n  .id=\"type\"\n) |>\n  ggplot(aes(x=time,y=value,color=factor(type)))+\n  geom_line()+\n  labs(color=\"\")+\n  facet_wrap(~name,scales=\"free_y\")+\n  theme_bw()+theme(legend.position=\"top\")\n\nenkf(po,Np=1000) -> kf\nplot(kf,yax.flip=TRUE)\n\neakf(po,Np=1000) -> kf2\nplot(kf2,yax.flip=TRUE)\n\nKf <- kalmanFilter(\n  po,\n  A=matrix(coef(po,c(\"alpha_1\",\"alpha_2\",\"alpha_3\",\"alpha_4\")),2,2),\n  Q={\n    q <- matrix(c(coef(po,c(\"sigma_1\",\"sigma_2\")),0,coef(po,\"sigma_3\")),2,2)\n    tcrossprod(q)\n  },\n  C=diag(2),\n  R=diag(coef(po,\"tau\")^2,2)\n)\n\nstopifnot(\n  abs(logLik(pf)+478.7)<0.5,\n  abs(logLik(kf)+477.1)<0.5,\n  abs(logLik(kf2)+476.3)<0.5,\n  abs(Kf$logLik+476.6)<0.5\n)\n\ntrajectory(po) -> tj\nplot(tj)\n\nd <- dprocess(sm,log=TRUE)\nsum(d)\n#stopifnot(\n#  abs(sum(d)+452.5)<0.05\n#)\n\ndev.off()\n"
  },
  {
    "path": "tests/ou2.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> suppressPackageStartupMessages({\n+   library(tidyr)\n+   library(dplyr)\n+   library(ggplot2)\n+ })\n> \n> set.seed(1438408329L)\n> \n> png(filename=\"ou2-%02d.png\",res=100)\n> \n> ou2() -> po\n> plot(po)\n> \n> stopifnot(\n+   all.equal(\n+     coef(po),\n+     partrans(po,coef(po,transform=TRUE),dir=\"from\")\n+   ),\n+   all.equal(\n+     coef(po,transform=TRUE),\n+     partrans(po,coef(po),dir=\"to\")\n+   )\n+ )\n> \n> pfilter(\n+   po,\n+   Np=1000,\n+   filter.mean=TRUE,\n+   pred.mean=TRUE,\n+   pred.var=TRUE,\n+   filter.traj=TRUE,\n+   save.states=\"filter\"\n+ ) -> pf\n> \n> plot(pf,yax.flip=TRUE)\n> \n> forecast(pf,format=\"d\") -> fc\n> simulate(pf) -> sm\n> \n> emeasure(pf) |> melt() -> ef\n> vmeasure(pf) |> melt() -> vf\n> vf |> select(-time,-.id) |> distinct()\n  var1 var2 value\n1   y1   y1     1\n2   y2   y1     0\n3   y1   y2     0\n4   y2   y2     1\n> \n> bind_rows(\n+   sim=sm |>\n+     as.data.frame() |>\n+     pivot_longer(c(x1,x2,y1,y2)),\n+   forecast=fc,\n+   filter=ef |> select(-.id),\n+   prediction=pred_mean(pf,format=\"d\"),\n+   filter=filter_mean(pf,format=\"d\"),\n+   .id=\"type\"\n+ ) |>\n+   ggplot(aes(x=time,y=value,color=factor(type)))+\n+   geom_line()+\n+   labs(color=\"\")+\n+   facet_wrap(~name,scales=\"free_y\")+\n+   theme_bw()+theme(legend.position=\"top\")\n> \n> enkf(po,Np=1000) -> kf\n> plot(kf,yax.flip=TRUE)\n> \n> eakf(po,Np=1000) -> kf2\n> plot(kf2,yax.flip=TRUE)\n> \n> Kf <- kalmanFilter(\n+   po,\n+   A=matrix(coef(po,c(\"alpha_1\",\"alpha_2\",\"alpha_3\",\"alpha_4\")),2,2),\n+   Q={\n+     q <- matrix(c(coef(po,c(\"sigma_1\",\"sigma_2\")),0,coef(po,\"sigma_3\")),2,2)\n+     tcrossprod(q)\n+   },\n+   C=diag(2),\n+   R=diag(coef(po,\"tau\")^2,2)\n+ )\n> \n> stopifnot(\n+   abs(logLik(pf)+478.7)<0.5,\n+   abs(logLik(kf)+477.1)<0.5,\n+   abs(logLik(kf2)+476.3)<0.5,\n+   abs(Kf$logLik+476.6)<0.5\n+ )\n> \n> trajectory(po) -> tj\n> plot(tj)\n> \n> d <- dprocess(sm,log=TRUE)\n> sum(d)\n[1] -452.5375\n> #stopifnot(\n> #  abs(sum(d)+452.5)<0.05\n> #)\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/parmat.R",
    "content": "options(digits=7)\nlibrary(pomp)\n\ntheta <- c(a=1,b=3,c=4,d=5)\np <- parmat(theta,3)\np\np[\"b\",] <- 1:3\np <- parmat(p,2)\np\ntheta <- array(\n  1:30,dim=c(5,3,2),\n  dimnames=list(head(letters,5),head(LETTERS,3),NULL)\n)\np <- parmat(theta,2)\np\ntheta <- array(\n  1:30,\n  dim=c(5,3,2,1,1,1),\n  dimnames=list(head(letters,5),head(LETTERS,3),NULL)\n)\nq <- parmat(theta,2,names=head(LETTERS,12))\nstopifnot(\n  all.equal(p,parmat(theta,2)),\n  p==q\n)\n\ntry(parmat())\ntry(parmat(\"bob\"))\n\ntheta <- c(a=1,b=3,c=4,d=5)\nTheta <- array(theta,dim=length(theta),dimnames=list(names(theta)))\np1 <- parmat(Theta,nrep=2,names=c(\"A\",\"B\"))\nTheta <- array(theta,dim=c(length(theta),1),\n  dimnames=list(names(theta),NULL))\np2 <- parmat(Theta,nrep=2,names=c(\"A\",\"B\"))\nTheta <- array(theta,dim=c(length(theta),1,1,1),\n  dimnames=list(names(theta),NULL,NULL,NULL))\np3 <- parmat(Theta,nrep=2,names=c(\"A\",\"B\"))\nstopifnot(\n  identical(p1,p2),\n  identical(p1,p3)\n)\n\ntry({\n  theta <- c(a=\"tom\",b=3,c=4,d=5)\n  Theta <- array(theta,dim=length(theta),dimnames=list(names(theta)))\n  parmat(Theta,nrep=2,names=c(\"A\",\"B\"))\n})\n\ntry(\n  expand.grid(a=1:3,c=\"hello\",stringsAsFactors=FALSE) |> parmat()\n)\ntry(\n  expand.grid(a=1:3,c=\"hello\",stringsAsFactors=TRUE) |> parmat()\n)\nexpand.grid(a=1:3,b=1:2) |> parmat()\nexpand.grid(a=1:3,b=1:2) |> parmat(nrep=2)\n"
  },
  {
    "path": "tests/parmat.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=7)\n> library(pomp)\n> \n> theta <- c(a=1,b=3,c=4,d=5)\n> p <- parmat(theta,3)\n> p\n    .id\nname [,1] [,2] [,3]\n   a    1    1    1\n   b    3    3    3\n   c    4    4    4\n   d    5    5    5\n> p[\"b\",] <- 1:3\n> p <- parmat(p,2)\n> p\n    .id\nname [,1] [,2] [,3] [,4] [,5] [,6]\n   a    1    1    1    1    1    1\n   b    1    2    3    1    2    3\n   c    4    4    4    4    4    4\n   d    5    5    5    5    5    5\n> theta <- array(\n+   1:30,dim=c(5,3,2),\n+   dimnames=list(head(letters,5),head(LETTERS,3),NULL)\n+ )\n> p <- parmat(theta,2)\n> p\n    .id\nname [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]\n   a    1    6   11   16   21   26    1    6   11    16    21    26\n   b    2    7   12   17   22   27    2    7   12    17    22    27\n   c    3    8   13   18   23   28    3    8   13    18    23    28\n   d    4    9   14   19   24   29    4    9   14    19    24    29\n   e    5   10   15   20   25   30    5   10   15    20    25    30\n> theta <- array(\n+   1:30,\n+   dim=c(5,3,2,1,1,1),\n+   dimnames=list(head(letters,5),head(LETTERS,3),NULL)\n+ )\n> q <- parmat(theta,2,names=head(LETTERS,12))\n> stopifnot(\n+   all.equal(p,parmat(theta,2)),\n+   p==q\n+ )\n> \n> try(parmat())\nError : in 'parmat': 'params' is a required argument.\n> try(parmat(\"bob\"))\nError : 'parmat' is undefined for 'params' of class 'character'.\n> \n> theta <- c(a=1,b=3,c=4,d=5)\n> Theta <- array(theta,dim=length(theta),dimnames=list(names(theta)))\n> p1 <- parmat(Theta,nrep=2,names=c(\"A\",\"B\"))\n> Theta <- array(theta,dim=c(length(theta),1),\n+   dimnames=list(names(theta),NULL))\n> p2 <- parmat(Theta,nrep=2,names=c(\"A\",\"B\"))\n> Theta <- array(theta,dim=c(length(theta),1,1,1),\n+   dimnames=list(names(theta),NULL,NULL,NULL))\n> p3 <- parmat(Theta,nrep=2,names=c(\"A\",\"B\"))\n> stopifnot(\n+   identical(p1,p2),\n+   identical(p1,p3)\n+ )\n> \n> try({\n+   theta <- c(a=\"tom\",b=3,c=4,d=5)\n+   Theta <- array(theta,dim=length(theta),dimnames=list(names(theta)))\n+   parmat(Theta,nrep=2,names=c(\"A\",\"B\"))\n+ })\nError : in 'parmat': NAs introduced by coercion\n> \n> try(\n+   expand.grid(a=1:3,c=\"hello\",stringsAsFactors=FALSE) |> parmat()\n+ )\nError : in 'parmat': 'params' must contain numeric variables only.\n> try(\n+   expand.grid(a=1:3,c=\"hello\",stringsAsFactors=TRUE) |> parmat()\n+ )\nError : in 'parmat': 'params' must contain numeric variables only.\n> expand.grid(a=1:3,b=1:2) |> parmat()\n    .id\nname 1 2 3 4 5 6\n   a 1 2 3 1 2 3\n   b 1 1 1 2 2 2\n> expand.grid(a=1:3,b=1:2) |> parmat(nrep=2)\n    .id\nname 1_1 2_1 3_1 4_1 5_1 6_1 1_2 2_2 3_2 4_2 5_2 6_2\n   a   1   2   3   1   2   3   1   2   3   1   2   3\n   b   1   1   1   2   2   2   1   1   1   2   2   2\n> \n"
  },
  {
    "path": "tests/partrans.R",
    "content": "library(pomp)\n\ngompertz() -> gompertz\nset.seed(995868671L)\n\ntheta1 <- coef(gompertz)\ntheta2 <- coef(gompertz,transform=TRUE)\nstopifnot(all.equal(partrans(gompertz,theta1,dir=\"toEst\"),theta2))\nstopifnot(all.equal(partrans(gompertz,theta2,dir=\"fromEst\"),theta1))\ntheta3 <- theta2[order(runif(5))]\nstopifnot(any(names(theta1)!=names(theta3)))\nstopifnot(all.equal(partrans(gompertz,theta3)[names(theta1)],theta1))\n\ntheta3 <- theta2[-1]\ntry(partrans(params=theta1))\ntry(partrans(\"gompertz\",params=theta1))\ntry(partrans(gompertz,theta3))\ntry(partrans(pomp(gompertz,partrans=parameter_trans(from=Csnippet(\"K = exp(T_K);\")),\n  paramnames=\"K\"),theta3))\ntry(partrans(pomp(gompertz,partrans=parameter_trans(from=Csnippet(\"K = exp(T_K);\"),\n  to=Csnippet(\"T_K = log(K);\")),paramnames=\"K\"),theta3))\ntry(partrans(pomp(gompertz,partrans=parameter_trans(log=\"K\"),paramnames=\"K\"),\n  theta3))\ntry(partrans(pomp(gompertz,partrans=parameter_trans(from=function(params,...)unname(params),\n  to=function(params,...)unname(params))),theta3))\n\npp <- parmat(coef(gompertz),100)\npp[\"r\",] <- runif(100,0,100)\nstopifnot(all.equal(partrans(gompertz,partrans(gompertz,pp,dir=\"to\")),pp))\ntry(partrans(pomp(gompertz,partrans=parameter_trans(\n  from=function(...)unname(list(...)),to=function(...)unname(list(...)))),pp))\ntry(partrans(pomp(gompertz,partrans=parameter_trans(\n  from=function(...)unname(list(...)),to=NULL)),pp))\n\nparameter_trans(toEst=NULL,fromEst=NULL)\ntry(parameter_trans(toEst=NULL))\ntry(parameter_trans(fromEst=NULL))\n\nparameter_trans(logit=c(\"a\",\"b\",\"c\"))\npomp:::has_partrans(gompertz)\n\nstopifnot(\n  {\n    partrans(\n      pomp(gompertz,\n        partrans=parameter_trans(\n          from=function(r,...) c(r=exp(r)),\n          to=function(r,...) c(r=log(r))\n        )\n      ),\n      params=parmat(coef(gompertz),2),\n      dir=\"to\"\n    ) -> p1\n    partrans(\n      pomp(gompertz,\n        partrans=parameter_trans(\n          from=function(r,...) c(r=exp(r)),\n          to=function(r,...) c(r=log(r))\n        )\n      ),\n      params=p1,\n      dir=\"from\"\n    ) -> p2\n    all.equal(p2,parmat(coef(gompertz),2))\n  }\n)\n\nou2() -> ou2\npp <- parmat(coef(ou2),10)\nstopifnot(all.equal(partrans(ou2,partrans(ou2,pp,dir=\"to\"),dir=\"from\"),pp))\n"
  },
  {
    "path": "tests/partrans.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> \n> gompertz() -> gompertz\n> set.seed(995868671L)\n> \n> theta1 <- coef(gompertz)\n> theta2 <- coef(gompertz,transform=TRUE)\n> stopifnot(all.equal(partrans(gompertz,theta1,dir=\"toEst\"),theta2))\n> stopifnot(all.equal(partrans(gompertz,theta2,dir=\"fromEst\"),theta1))\n> theta3 <- theta2[order(runif(5))]\n> stopifnot(any(names(theta1)!=names(theta3)))\n> stopifnot(all.equal(partrans(gompertz,theta3)[names(theta1)],theta1))\n> \n> theta3 <- theta2[-1]\n> try(partrans(params=theta1))\nError : in 'partrans': 'object' is a required argument.\n> try(partrans(\"gompertz\",params=theta1))\nError : 'partrans' is undefined for 'object' of class 'character'.\n> try(partrans(gompertz,theta3))\nError : in 'partrans': variable 'K' not found among the parameters.\n> try(partrans(pomp(gompertz,partrans=parameter_trans(from=Csnippet(\"K = exp(T_K);\")),\n+   paramnames=\"K\"),theta3))\nError in h(simpleError(msg, call)) : \n  error in evaluating the argument 'object' in selecting a method for function 'partrans': in 'parameter_trans': if one of 'toEst', 'fromEst' is supplied, then so must the other be.\n> try(partrans(pomp(gompertz,partrans=parameter_trans(from=Csnippet(\"K = exp(T_K);\"),\n+   to=Csnippet(\"T_K = log(K);\")),paramnames=\"K\"),theta3))\nError : in 'partrans': variable 'K' not found among the parameters.\n> try(partrans(pomp(gompertz,partrans=parameter_trans(log=\"K\"),paramnames=\"K\"),\n+   theta3))\nError : in 'partrans': variable 'K' not found among the parameters.\n> try(partrans(pomp(gompertz,partrans=parameter_trans(from=function(params,...)unname(params),\n+   to=function(params,...)unname(params))),theta3))\nError : in 'partrans': argument \"params\" is missing, with no default\n> \n> pp <- parmat(coef(gompertz),100)\n> pp[\"r\",] <- runif(100,0,100)\n> stopifnot(all.equal(partrans(gompertz,partrans(gompertz,pp,dir=\"to\")),pp))\n> try(partrans(pomp(gompertz,partrans=parameter_trans(\n+   from=function(...)unname(list(...)),to=function(...)unname(list(...)))),pp))\nError : in 'partrans': user transformation functions must return named numeric vectors.\n> try(partrans(pomp(gompertz,partrans=parameter_trans(\n+   from=function(...)unname(list(...)),to=NULL)),pp))\nError in h(simpleError(msg, call)) : \n  error in evaluating the argument 'object' in selecting a method for function 'partrans': 'parameter_trans' not defined for arguments of class 'NULL', 'function'.\n> \n> parameter_trans(toEst=NULL,fromEst=NULL)\n  - to estimation scale: <identity>\n  - from estimation scale: <identity>\n> try(parameter_trans(toEst=NULL))\nError : in 'parameter_trans': if one of 'toEst', 'fromEst' is supplied, then so must the other be.\n> try(parameter_trans(fromEst=NULL))\nError : in 'parameter_trans': if one of 'toEst', 'fromEst' is supplied, then so must the other be.\n> \n> parameter_trans(logit=c(\"a\",\"b\",\"c\"))\n  - to estimation scale: An object of class \"Csnippet\"\nSlot \"text\":\n[1] \"\\n  T_a = logit(a);\\n  T_b = logit(b);\\n  T_c = logit(c);\"\n\n  - from estimation scale: An object of class \"Csnippet\"\nSlot \"text\":\n[1] \"\\n  a = expit(T_a);\\n  b = expit(T_b);\\n  c = expit(T_c);\"\n\n> pomp:::has_partrans(gompertz)\n[1] TRUE\n> \n> stopifnot(\n+   {\n+     partrans(\n+       pomp(gompertz,\n+         partrans=parameter_trans(\n+           from=function(r,...) c(r=exp(r)),\n+           to=function(r,...) c(r=log(r))\n+         )\n+       ),\n+       params=parmat(coef(gompertz),2),\n+       dir=\"to\"\n+     ) -> p1\n+     partrans(\n+       pomp(gompertz,\n+         partrans=parameter_trans(\n+           from=function(r,...) c(r=exp(r)),\n+           to=function(r,...) c(r=log(r))\n+         )\n+       ),\n+       params=p1,\n+       dir=\"from\"\n+     ) -> p2\n+     all.equal(p2,parmat(coef(gompertz),2))\n+   }\n+ )\n> \n> ou2() -> ou2\n> pp <- parmat(coef(ou2),10)\n> stopifnot(all.equal(partrans(ou2,partrans(ou2,pp,dir=\"to\"),dir=\"from\"),pp))\n> \n"
  },
  {
    "path": "tests/pfilter.R",
    "content": "options(digits=3)\n\nlibrary(pomp)\n\nou2() -> ou2\n\nset.seed(9994847L)\n\npf <- pfilter(ou2,Np=1000)\nlogLik(pf)\nstopifnot(logLik(pf)==sum(cond_logLik(pf)))\nrange(eff_sample_size(pf))\nrange(cond_logLik(pf))\nnames(as(pf,\"data.frame\"))\nidentical(as(pf,\"data.frame\"),as.data.frame(pf))\n\ntry(pfilter())\ntry(pfilter(\"bob\"))\n\ntry(pfilter(ou2))\ntry(pfilter(ou2,Np=NULL))\ntry(pfilter(ou2,Np=-10))\ntry(pfilter(ou2,Np=c(10,20,30)))\npfilter(ou2,Np=ceiling(runif(101,min=10,max=100)))\n\npo <- ou2\ncoef(po) <- NULL\ntry(pfilter(po,Np=100))\ntry(pfilter(po,Np=100,params=c()))\ntry(pfilter(po,Np=100,params=NULL))\ntry(pfilter(po,Np=100,params=c(1,2,3)))\ntry(pfilter(po,Np=100,params=c(a=1,b=2,c=3)))\ntry(pfilter(po,Np=100,params=list()))\npf <- pfilter(po,Np=100,params=as.list(coef(ou2)))\n\npf <- pfilter(pf)\ntry(pfilter(pf,Np=-1000))\nstopifnot(all.equal(coef(pf),coef(ou2)))\ntheta <- coef(ou2)\ntheta[\"alpha_2\"] <- 0.1\npf1 <- pfilter(pf,params=theta,Np=100)\nstopifnot(identical(coef(pf1),theta))\n\ntry(pfilter(ou2,params=parmat(coef(ou2),100)))\ntry(pfilter(ou2,Np=100,params=parmat(coef(ou2),100)))\n\npf2 <- pfilter(ou2,Np=function(k)c(100,150)[(k-1)%%2+1])\ntable(pf2@Np)\ntry(pfilter(pf2,Np=function(k)c(100,-150)[(k-1)%%2+1]))\ntry(pfilter(pf2,Np=function(k)c(100,-150)))\ntry(pfilter(pf2,Np=\"many\"))\n\ntheta <- coef(ou2)\ntheta[\"tau\"] <- 0\ntry(pfilter(pf,params=theta))\ntheta <- coef(ou2)\ntheta[\"sigma_2\"] <- Inf\ntry(pfilter(pf,params=theta))\ntheta <- coef(ou2)\ntheta[\"alpha_1\"] <- 1e60\ntry(pfilter(pf,params=theta,pred.var=TRUE))\n\ntry(pfilter(pf,rprocess=onestep(\n                 function(x, t, params, delta.t, ...)stop(\"yikes!\"))))\ntry(pfilter(pf,dmeasure=Csnippet(\"error(\\\"ouch!\\\");\")))\npfilter(pf,dmeasure=function(log,...) -Inf)\npfilter(pf,dmeasure=function(log,...) -Inf,filter.mean=TRUE)\n\npf1 <- pfilter(pf,save.states=\"filter\",filter.traj=TRUE)\npf2 <- pfilter(pf,pred.mean=TRUE,pred.var=TRUE,filter.mean=TRUE,save.states=\"prediction\")\npf3 <- pfilter(pf,t0=1,filter.traj=TRUE)\npf4 <- pfilter(pf,dmeasure=Csnippet(\"lik = (give_log) ? R_NegInf : 0;\"),\n  filter.traj=TRUE)\n\nstopifnot(\n  pf2 |> filter_mean() |> dim()==c(2,100),\n  pf2 |> filter_mean(vars=\"x1\") |> dim()==c(1,100),\n  pf2 |> filter_mean(vars=c(\"x2\",\"x1\")) |> dimnames() |> getElement(\"name\")==c(\"x2\",\"x1\"),\n  pf2 |> filter_mean(format=\"d\") |> dim()==c(200,3),\n  pf2 |> filter_mean(vars=\"x2\",format=\"d\") |> dim()==c(100,3),\n  pf2 |> filter_mean(vars=\"x2\",format=\"d\") |> names()==c(\"name\",\"time\",\"value\"),\n  pf2 |> pred_mean() |> dim()==c(2,100),\n  pf2 |> pred_mean(vars=\"x1\") |> dim()==c(1,100),\n  pf2 |> pred_mean(vars=c(\"x2\",\"x1\")) |> dimnames() |> getElement(\"name\")==c(\"x2\",\"x1\"),\n  pf2 |> pred_mean(format=\"d\") |> dim()==c(200,3),\n  pf2 |> pred_mean(vars=\"x2\",format=\"d\") |> dim()==c(100,3),\n  pf2 |> pred_mean(vars=\"x2\",format=\"d\") |> names()==c(\"name\",\"time\",\"value\"),\n  pf2 |> pred_var() |> dim()==c(2,100),\n  pf2 |> pred_var(vars=\"x1\") |> dim()==c(1,100),\n  pf2 |> pred_var(vars=c(\"x2\",\"x1\")) |> dimnames() |> getElement(\"name\")==c(\"x2\",\"x1\"),\n  pf2 |> pred_var(format=\"d\") |> dim()==c(200,3),\n  pf2 |> pred_var(vars=\"x2\",format=\"d\") |> dim()==c(100,3),\n  pf2 |> pred_var(vars=\"x2\",format=\"d\") |> names()==c(\"name\",\"time\",\"value\")\n)\n\npf1 |> saved_states(format=\"data\") |> names()\npf1 |> saved_states(format=\"data\") |> dim()\npf1 |> saved_states() |> melt() |> sapply(class)\npf1 |> saved_states() |> melt() |> sapply(length)\npf2 |> saved_states(format=\"data\") |> names()\npf2 |> saved_states(format=\"data\") |> dim()\n\nc(A=pf1,B=pf2) |> class()\nc(A=pf1,B=pf2) |> saved_states(format=\"d\") |> class()\nc(A=pf1,B=pf2) |> saved_states(format=\"d\") |> names()\nc(pf1,pf2) |> saved_states(format=\"d\") |> names()\nc(A=pf1,B=pf2) |> saved_states(format=\"d\") |> sapply(class)\nc(A=pf1,B=pf2) |> as.data.frame() |> sapply(class)\n\nnames(as(pf2,\"data.frame\"))\ndim(filter_traj(pf3))\ndimnames(filter_traj(pf3))\ntry(filter_traj(c(pf1,pf3)))\ndim(filter_traj(c(pf1,pf4)))\ndim(as.data.frame(c(pf1,pf4)))\nnames(dimnames(filter_traj(c(pf1,pf4))))\nnames(as(c(pf1,pf4),\"data.frame\"))\npf2 |> as.data.frame() |> names()\ntry(saved_states())\ntry(saved_states(NULL))\ntry(saved_states(\"bob\"))\nstopifnot(\n  filter_traj(pf1,vars=\"x2\") |> dim()==c(1,1,101),\n  filter_traj(pf1,vars=\"x2\",format=\"d\") |> dim()==c(101,4)\n)\n\ntry(ou2 |> as.data.frame() |> pfilter(Np=1000))\n\nou2 |>\n  as.data.frame() |>\n  subset(select=c(time,y1,y2)) |>\n  pfilter(\n    times=\"time\",t0=0,Np=500,\n    params=list(x1_0=-3,x2_0=4),\n    rprocess=onestep(\n      step.fun=function(x1,x2,delta.t,...) {\n        setNames(rnorm(n=2,mean=c(x1,x2),sd=5*delta.t),c(\"x1\",\"x2\"))\n      }\n    ),\n    dmeasure=function(x1,x2,y1,y2,...,log) {\n      ll <- sum(dnorm(x=c(y1,y2),mean=c(x1,x2),sd=5,log=TRUE))\n      if (log) ll else exp(ll)\n    }\n  )\n\ntry(ou2 |> pfilter(Np=1000) |> forecast())\ntry(ou2 |> pfilter(Np=1000,emeasure=NULL) |> forecast())\nou2 |> pfilter(Np=1000,pred.mean=TRUE) |> forecast() -> y\nou2 |> pfilter(Np=1000,pred.mean=TRUE) |> forecast(vars=\"y1\") -> y1\nstopifnot(\n  dim(y)==c(2,100),\n  dim(y1)==c(1,100)\n)\n\nset.seed(1); pf_no <- pfilter(ou2, Np = 100, save.states = \"no\")\nset.seed(1); pf_false <- pfilter(ou2, Np = 100, save.states = FALSE)\nset.seed(1); pf_true <- pfilter(ou2, Np = 100, save.states = TRUE)\nset.seed(1); pf_unweighted <- pfilter(ou2, Np = 100, save.states = \"unweighted\")\nset.seed(1); pf_filter <- pfilter(ou2, Np = 100, save.states = \"filter\")\nset.seed(1); pf_weighted <- pfilter(ou2, Np = 100, save.states = \"weighted\")\nset.seed(1); pf_predict <- pfilter(ou2, Np = 100, save.states = \"prediction\")\nstopifnot(\n  all.equal(unlist(saved_states(pf_unweighted)), unlist(saved_states(pf_filter))),\n  all.equal(unlist(saved_states(pf_true)), unlist(saved_states(pf_filter))),\n  all.equal(unlist(saved_states(pf_weighted)[2]), unlist(saved_states(pf_predict)[2])),\n  length(saved_states(pf_no)) == 0,\n  length(saved_states(pf_false)) == 0\n)\n"
  },
  {
    "path": "tests/pfilter.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> \n> library(pomp)\n> \n> ou2() -> ou2\n> \n> set.seed(9994847L)\n> \n> pf <- pfilter(ou2,Np=1000)\n> logLik(pf)\n[1] -478\n> stopifnot(logLik(pf)==sum(cond_logLik(pf)))\n> range(eff_sample_size(pf))\n[1]   2.88 243.72\n> range(cond_logLik(pf))\n[1] -9.32 -3.84\n> names(as(pf,\"data.frame\"))\n[1] \"time\"        \"y1\"          \"y2\"          \"x1\"          \"x2\"         \n[6] \"ess\"         \"cond.logLik\"\n> identical(as(pf,\"data.frame\"),as.data.frame(pf))\n[1] TRUE\n> \n> try(pfilter())\nError : in 'pfilter': 'data' is a required argument.\n> try(pfilter(\"bob\"))\nError : 'pfilter' is undefined for 'data' of class 'character'.\n> \n> try(pfilter(ou2))\nError : in 'pfilter': 'Np' must be specified.\n> try(pfilter(ou2,Np=NULL))\nError : in 'pfilter': 'Np' must be specified.\n> try(pfilter(ou2,Np=-10))\nError : in 'pfilter': number of particles, 'Np', must be a positive integer.\n> try(pfilter(ou2,Np=c(10,20,30)))\nError : in 'pfilter': 'Np' must have length 1 or length 101.\n> pfilter(ou2,Np=ceiling(runif(101,min=10,max=100)))\n<object of class 'pfilterd_pomp'>\n> \n> po <- ou2\n> coef(po) <- NULL\n> try(pfilter(po,Np=100))\nError : in 'pfilter': in 'rprocess': variable 'x1' not found among the state variables.\nIn addition: Warning message:\nin default 'rinit': there are no parameters with suffix '.0' or '_0'. See '?rinit_spec'. \n> try(pfilter(po,Np=100,params=c()))\nError : in 'pfilter': in 'rprocess': variable 'x1' not found among the state variables.\nIn addition: Warning message:\nin default 'rinit': there are no parameters with suffix '.0' or '_0'. See '?rinit_spec'. \n> try(pfilter(po,Np=100,params=NULL))\nError : in 'pfilter': in 'rprocess': variable 'x1' not found among the state variables.\nIn addition: Warning message:\nin default 'rinit': there are no parameters with suffix '.0' or '_0'. See '?rinit_spec'. \n> try(pfilter(po,Np=100,params=c(1,2,3)))\nError : in 'pfilter': 'params' must be a named numeric vector.\n> try(pfilter(po,Np=100,params=c(a=1,b=2,c=3)))\nError : in 'pfilter': in 'rprocess': variable 'x1' not found among the state variables.\nIn addition: Warning message:\nin default 'rinit': there are no parameters with suffix '.0' or '_0'. See '?rinit_spec'. \n> try(pfilter(po,Np=100,params=list()))\nError : in 'pfilter': in 'rprocess': variable 'x1' not found among the state variables.\nIn addition: Warning message:\nin default 'rinit': there are no parameters with suffix '.0' or '_0'. See '?rinit_spec'. \n> pf <- pfilter(po,Np=100,params=as.list(coef(ou2)))\n> \n> pf <- pfilter(pf)\n> try(pfilter(pf,Np=-1000))\nError : in 'pfilter': number of particles, 'Np', must be a positive integer.\n> stopifnot(all.equal(coef(pf),coef(ou2)))\n> theta <- coef(ou2)\n> theta[\"alpha_2\"] <- 0.1\n> pf1 <- pfilter(pf,params=theta,Np=100)\n> stopifnot(identical(coef(pf1),theta))\n> \n> try(pfilter(ou2,params=parmat(coef(ou2),100)))\nError : in 'pfilter': 'params' must be a named numeric vector.\n> try(pfilter(ou2,Np=100,params=parmat(coef(ou2),100)))\nError : in 'pfilter': 'params' must be a named numeric vector.\n> \n> pf2 <- pfilter(ou2,Np=function(k)c(100,150)[(k-1)%%2+1])\n> table(pf2@Np)\n\n100 150 \n 50  51 \n> try(pfilter(pf2,Np=function(k)c(100,-150)[(k-1)%%2+1]))\nError : in 'pfilter': number of particles, 'Np', must be a positive integer.\n> try(pfilter(pf2,Np=function(k)c(100,-150)))\nError : in 'pfilter': if 'Np' is a function, it must return a single positive integer.\n> try(pfilter(pf2,Np=\"many\"))\nError : in 'pfilter': 'Np' must be a number, a vector of numbers, or a function.\n> \n> theta <- coef(ou2)\n> theta[\"tau\"] <- 0\n> try(pfilter(pf,params=theta))\n<object of class 'pfilterd_pomp'>\n> theta <- coef(ou2)\n> theta[\"sigma_2\"] <- Inf\n> try(pfilter(pf,params=theta))\nError : in 'pfilter': 'dmeasure' with log=TRUE returns illegal value.\nLog likelihood, data, states, and parameters are:\n   time:            2\n loglik:          NaN\n     y1:      1.83463\n     y2:       6.2733\n     x1:          Inf\n     x2:          NaN\nalpha_1:          0.8\nalpha_2:         -0.5\nalpha_3:          0.3\nalpha_4:          0.9\nsigma_1:            3\nsigma_2:          Inf\nsigma_3:            2\n    tau:            1\n   x1_0:           -3\n   x2_0:            4\n> theta <- coef(ou2)\n> theta[\"alpha_1\"] <- 1e60\n> try(pfilter(pf,params=theta,pred.var=TRUE))\nError : in 'pfilter': non-finite state variable: x1\n> \n> try(pfilter(pf,rprocess=onestep(\n+                  function(x, t, params, delta.t, ...)stop(\"yikes!\"))))\nError : in 'pfilter': in 'rprocess': yikes!\n> try(pfilter(pf,dmeasure=Csnippet(\"error(\\\"ouch!\\\");\")))\nError : in 'pfilter': in 'dmeasure': ouch!\n> pfilter(pf,dmeasure=function(log,...) -Inf)\n<object of class 'pfilterd_pomp'>\n> pfilter(pf,dmeasure=function(log,...) -Inf,filter.mean=TRUE)\n<object of class 'pfilterd_pomp'>\n> \n> pf1 <- pfilter(pf,save.states=\"filter\",filter.traj=TRUE)\n> pf2 <- pfilter(pf,pred.mean=TRUE,pred.var=TRUE,filter.mean=TRUE,save.states=\"prediction\")\n> pf3 <- pfilter(pf,t0=1,filter.traj=TRUE)\n> pf4 <- pfilter(pf,dmeasure=Csnippet(\"lik = (give_log) ? R_NegInf : 0;\"),\n+   filter.traj=TRUE)\n> \n> stopifnot(\n+   pf2 |> filter_mean() |> dim()==c(2,100),\n+   pf2 |> filter_mean(vars=\"x1\") |> dim()==c(1,100),\n+   pf2 |> filter_mean(vars=c(\"x2\",\"x1\")) |> dimnames() |> getElement(\"name\")==c(\"x2\",\"x1\"),\n+   pf2 |> filter_mean(format=\"d\") |> dim()==c(200,3),\n+   pf2 |> filter_mean(vars=\"x2\",format=\"d\") |> dim()==c(100,3),\n+   pf2 |> filter_mean(vars=\"x2\",format=\"d\") |> names()==c(\"name\",\"time\",\"value\"),\n+   pf2 |> pred_mean() |> dim()==c(2,100),\n+   pf2 |> pred_mean(vars=\"x1\") |> dim()==c(1,100),\n+   pf2 |> pred_mean(vars=c(\"x2\",\"x1\")) |> dimnames() |> getElement(\"name\")==c(\"x2\",\"x1\"),\n+   pf2 |> pred_mean(format=\"d\") |> dim()==c(200,3),\n+   pf2 |> pred_mean(vars=\"x2\",format=\"d\") |> dim()==c(100,3),\n+   pf2 |> pred_mean(vars=\"x2\",format=\"d\") |> names()==c(\"name\",\"time\",\"value\"),\n+   pf2 |> pred_var() |> dim()==c(2,100),\n+   pf2 |> pred_var(vars=\"x1\") |> dim()==c(1,100),\n+   pf2 |> pred_var(vars=c(\"x2\",\"x1\")) |> dimnames() |> getElement(\"name\")==c(\"x2\",\"x1\"),\n+   pf2 |> pred_var(format=\"d\") |> dim()==c(200,3),\n+   pf2 |> pred_var(vars=\"x2\",format=\"d\") |> dim()==c(100,3),\n+   pf2 |> pred_var(vars=\"x2\",format=\"d\") |> names()==c(\"name\",\"time\",\"value\")\n+ )\n> \n> pf1 |> saved_states(format=\"data\") |> names()\n[1] \"time\"  \".id\"   \"name\"  \"value\"\n> pf1 |> saved_states(format=\"data\") |> dim()\n[1] 20000     4\n> pf1 |> saved_states() |> melt() |> sapply(class)\n        .L1        name         .id       value \n  \"integer\" \"character\"   \"integer\"   \"numeric\" \n> pf1 |> saved_states() |> melt() |> sapply(length)\n  .L1  name   .id value \n20000 20000 20000 20000 \n> pf2 |> saved_states(format=\"data\") |> names()\n[1] \"time\"  \".id\"   \"name\"  \"value\"\n> pf2 |> saved_states(format=\"data\") |> dim()\n[1] 30000     4\n> \n> c(A=pf1,B=pf2) |> class()\n[1] \"pfilterList\"\nattr(,\"package\")\n[1] \"pomp\"\n> c(A=pf1,B=pf2) |> saved_states(format=\"d\") |> class()\n[1] \"data.frame\"\n> c(A=pf1,B=pf2) |> saved_states(format=\"d\") |> names()\n[1] \".L1\"   \"time\"  \".id\"   \"name\"  \"value\"\n> c(pf1,pf2) |> saved_states(format=\"d\") |> names()\n[1] \".L1\"   \"time\"  \".id\"   \"name\"  \"value\"\n> c(A=pf1,B=pf2) |> saved_states(format=\"d\") |> sapply(class)\n        .L1        time         .id        name       value \n\"character\"   \"numeric\"   \"integer\" \"character\"   \"numeric\" \n> c(A=pf1,B=pf2) |> as.data.frame() |> sapply(class)\n           .L1           time             y1             y2            ess \n   \"character\"      \"numeric\"      \"numeric\"      \"numeric\"      \"numeric\" \n   cond.logLik   pred.mean.x1   pred.mean.x2    pred.var.x1    pred.var.x2 \n     \"numeric\"      \"numeric\"      \"numeric\"      \"numeric\"      \"numeric\" \nfilter.mean.x1 filter.mean.x2 \n     \"numeric\"      \"numeric\" \n> \n> names(as(pf2,\"data.frame\"))\n [1] \"time\"           \"y1\"             \"y2\"             \"ess\"           \n [5] \"cond.logLik\"    \"pred.mean.x1\"   \"pred.mean.x2\"   \"pred.var.x1\"   \n [9] \"pred.var.x2\"    \"filter.mean.x1\" \"filter.mean.x2\"\n> dim(filter_traj(pf3))\n[1]   2   1 100\n> dimnames(filter_traj(pf3))\n$name\n[1] \"x1\" \"x2\"\n\n$rep\n[1] \"1\"\n\n$time\nNULL\n\n> try(filter_traj(c(pf1,pf3)))\nError : in 'filter_traj': incommensurate dimensions.\n> dim(filter_traj(c(pf1,pf4)))\n[1]   2   1 101   2\n> dim(as.data.frame(c(pf1,pf4)))\n[1] 200   6\n> names(dimnames(filter_traj(c(pf1,pf4))))\n[1] \"name\"  \"rep\"   \"time\"  \"chain\"\n> names(as(c(pf1,pf4),\"data.frame\"))\n[1] \".L1\"         \"time\"        \"y1\"          \"y2\"          \"ess\"        \n[6] \"cond.logLik\"\n> pf2 |> as.data.frame() |> names()\n [1] \"time\"           \"y1\"             \"y2\"             \"ess\"           \n [5] \"cond.logLik\"    \"pred.mean.x1\"   \"pred.mean.x2\"   \"pred.var.x1\"   \n [9] \"pred.var.x2\"    \"filter.mean.x1\" \"filter.mean.x2\"\n> try(saved_states())\nError : in 'saved_states': 'object' is a required argument.\n> try(saved_states(NULL))\nError : 'saved_states' is undefined for 'object' of class 'NULL'.\n> try(saved_states(\"bob\"))\nError : 'saved_states' is undefined for 'object' of class 'character'.\n> stopifnot(\n+   filter_traj(pf1,vars=\"x2\") |> dim()==c(1,1,101),\n+   filter_traj(pf1,vars=\"x2\",format=\"d\") |> dim()==c(101,4)\n+ )\n> \n> try(ou2 |> as.data.frame() |> pfilter(Np=1000))\nError : in 'pfilter': 'times' should either be a numeric vector of observation times or a single name identifying the column of data that represents the observation times.\n> \n> ou2 |>\n+   as.data.frame() |>\n+   subset(select=c(time,y1,y2)) |>\n+   pfilter(\n+     times=\"time\",t0=0,Np=500,\n+     params=list(x1_0=-3,x2_0=4),\n+     rprocess=onestep(\n+       step.fun=function(x1,x2,delta.t,...) {\n+         setNames(rnorm(n=2,mean=c(x1,x2),sd=5*delta.t),c(\"x1\",\"x2\"))\n+       }\n+     ),\n+     dmeasure=function(x1,x2,y1,y2,...,log) {\n+       ll <- sum(dnorm(x=c(y1,y2),mean=c(x1,x2),sd=5,log=TRUE))\n+       if (log) ll else exp(ll)\n+     }\n+   )\n<object of class 'pfilterd_pomp'>\n> \n> try(ou2 |> pfilter(Np=1000) |> forecast())\nError : in 'forecast': no prediction mean. Rerun 'pfilter' with 'pred.mean=TRUE'.\n> try(ou2 |> pfilter(Np=1000,emeasure=NULL) |> forecast())\nError : in 'forecast': 'emeasure' is a needed basic component.\n> ou2 |> pfilter(Np=1000,pred.mean=TRUE) |> forecast() -> y\n> ou2 |> pfilter(Np=1000,pred.mean=TRUE) |> forecast(vars=\"y1\") -> y1\n> stopifnot(\n+   dim(y)==c(2,100),\n+   dim(y1)==c(1,100)\n+ )\n> \n> set.seed(1); pf_no <- pfilter(ou2, Np = 100, save.states = \"no\")\n> set.seed(1); pf_false <- pfilter(ou2, Np = 100, save.states = FALSE)\nWarning message:\nThe 'save.states' option 'FALSE' is deprecated and will be removed in a future version.\nUse 'no' instead. \n> set.seed(1); pf_true <- pfilter(ou2, Np = 100, save.states = TRUE)\nWarning message:\nThe 'save.states' option 'TRUE' is deprecated and will be removed in a future version.\nUse 'filter' instead. \n> set.seed(1); pf_unweighted <- pfilter(ou2, Np = 100, save.states = \"unweighted\")\nWarning message:\nThe 'save.states' option 'unweighted' is deprecated and will be removed in a future version.\nUse 'filter' instead. \n> set.seed(1); pf_filter <- pfilter(ou2, Np = 100, save.states = \"filter\")\n> set.seed(1); pf_weighted <- pfilter(ou2, Np = 100, save.states = \"weighted\")\nWarning message:\nThe 'save.states' option 'weighted' is deprecated and will be removed in a future version.\nUse 'prediction' instead. \n> set.seed(1); pf_predict <- pfilter(ou2, Np = 100, save.states = \"prediction\")\n> stopifnot(\n+   all.equal(unlist(saved_states(pf_unweighted)), unlist(saved_states(pf_filter))),\n+   all.equal(unlist(saved_states(pf_true)), unlist(saved_states(pf_filter))),\n+   all.equal(unlist(saved_states(pf_weighted)[2]), unlist(saved_states(pf_predict)[2])),\n+   length(saved_states(pf_no)) == 0,\n+   length(saved_states(pf_false)) == 0\n+ )\n> \n"
  },
  {
    "path": "tests/pfilter2.R",
    "content": "options(digits=3,dplyr.summarise.inform=FALSE)\npng(filename=\"pfilter2-%02d.png\",res=100)\n\nlibrary(pomp)\nsuppressPackageStartupMessages({\n  library(tidyr)\n  library(dplyr)\n  library(ggplot2)\n})\n\nset.seed(9994847L)\n\nou2(tau=5) |>\n  window(end=10) |>\n  pfilter(\n    Np=5000,\n    save.states=\"weighted\",\n    filter.mean=TRUE,\n    pred.mean=TRUE,\n    pred.var=TRUE,\n    filter.traj=TRUE\n  ) -> pf\n\npf |> as.data.frame() |> names()\npf |> as.data.frame() |> pivot_longer(-time) |> names()\npf |> forecast() |> melt() |> sapply(class)\npf |> forecast(format=\"d\") |> sapply(class)\npf |> filter_mean() |> melt() |> sapply(class)\npf |> filter_mean(format=\"d\") |> sapply(class)\npf |> pred_mean() |> melt() |> sapply(class)\npf |> pred_mean(format=\"d\") |> sapply(class)\npf |> pred_var() |> melt() |> sapply(class)\npf |> pred_var(format=\"d\") |> sapply(class)\npf |> filter_traj() |> melt() |> sapply(class)\npf |> filter_traj(format=\"d\") |> sapply(class)\npf |> saved_states() |> melt() |> sapply(class)\npf |> saved_states(format=\"d\") |> sapply(class)\n\nc(A=pf,B=pf) -> pfs\npfs |> filter_traj(format=\"d\") |> head()\npfs |> filter_traj(format=\"d\") |> dim()\npfs |> filter_traj(format=\"a\") |> dim()\npfs |> eff_sample_size(format=\"n\") |> melt() |> dim()\npfs |> eff_sample_size(format=\"d\") |> dim()\npfs |> cond_logLik(format=\"n\") |> melt() |> dim()\npfs |> cond_logLik(format=\"d\") |> dim()\nlist(A=pf,B=pf) |> concat() -> pfs2\nstopifnot(\n  all.equal(\n    pfs |> as.data.frame(),\n    pfs2 |> as.data.frame()\n  )\n)\n  \n\ntry(pf |> forecast(format=\"l\"))\n\npf |> as.data.frame() -> dat0\n\nbind_rows(\n  eff.sample.size=data.frame(\n    time=seq_along(time(pf)),\n    value=eff_sample_size(pf)\n  ),\n  cond.logLik=data.frame(\n    time=seq_along(time(pf)),\n    value=cond_logLik(pf)\n  ),\n  .id=\"name\"\n) |>\n  pivot_wider() |>\n  mutate(\n    time=time(pf)[as.integer(time)]\n  ) -> dat1\nfull_join(\n  eff_sample_size(pf,format=\"d\"),\n  cond_logLik(pf,format=\"d\"),\n  by=\"time\"\n) -> dat2\nstopifnot(\n  dat0$eff.sample.size==dat2$eff.sample.size,\n  dat0$cond.logLik==dat2$cond.logLik,\n  all.equal(dat1,dat2,check.attributes=FALSE)\n)\n\nbind_rows(\n  forecast=melt(forecast(pf)),\n  filter.mean=melt(filter_mean(pf)),\n  pred.mean=melt(pred_mean(pf)),\n  pred.var=melt(pred_var(pf)),\n  .id=\"type\"\n) |>\n  mutate(\n    time=time(pf)[as.integer(time)]\n  ) |>\n  unite(col=name,type,name,sep=\".\") |>\n  pivot_wider() -> dat1\nbind_rows(\n  forecast=forecast(pf,format=\"d\"),\n  filter.mean=filter_mean(pf,format=\"d\"),\n  pred.mean=pred_mean(pf,format=\"d\"),\n  pred.var=pred_var(pf,format=\"d\"),\n  .id=\"type\"\n) |>\n  unite(col=name,type,name,sep=\".\") |>\n  pivot_wider() -> dat2\nstopifnot(\n  all.equal(dat1,dat2,check.attributes=FALSE),\n  all.equal(dat0$filter.mean.x1,dat2$filter.mean.x1),\n  all.equal(dat0$filter.mean.x2,dat2$filter.mean.x2),\n  all.equal(dat0$pred.mean.x1,dat2$pred.mean.x1),\n  all.equal(dat0$pred.mean.x2,dat2$pred.mean.x2),\n  all.equal(dat0$pred.var.x1,dat2$pred.var.x1),\n  all.equal(dat0$pred.var.x2,dat2$pred.var.x2)\n)\n\npf |>\n  filter_traj() |>\n  melt() |>\n  mutate(\n    time=time(pf,t0=TRUE)[as.integer(time)]\n  ) -> dat1\npf |>\n  filter_traj(format=\"d\") -> dat2\nstopifnot(\n  all.equal(dat1,dat2,check.attributes=FALSE)\n)\n\npf |>\n  saved_states(format=\"l\") -> dat1\nbind_rows(\n  melt(dat1$states),\n  melt(dat1$weights)\n) |>\n  mutate(\n    name=coalesce(name,\".log.weight\"),\n    time=time(pf)[as.integer(.L1)]\n  ) |>\n  select(-.L1) |>\n  arrange(time,.id) |>\n  select(time,.id,name,value) -> dat1\npf |>\n  saved_states(format=\"d\") -> dat2\nstopifnot(\n  all.equal(dat1,dat2,check.attributes=FALSE)\n)\n\npf |>\n  saved_states(format=\"d\") |>\n  pivot_wider() |>\n  group_by(time) |>\n  reframe(\n    p=c(0.05,0.5,0.95),\n    x1=wquant(x1,weights=exp(.log.weight),probs=p),\n    x2=wquant(x2,weights=exp(.log.weight),probs=p)\n  ) |>\n  ungroup() |>\n  pivot_longer(c(x1,x2)) |>\n  pivot_wider(names_from=p) |>\n  ggplot(aes(x=time,y=`0.5`,ymin=`0.05`,ymax=`0.95`,group=name))+\n  geom_ribbon(alpha=0.5)+\n  geom_line(color=\"red\")+\n  facet_grid(name~.)+\n  labs(y=\"\")\n\ndev.off()\n"
  },
  {
    "path": "tests/pfilter2.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3,dplyr.summarise.inform=FALSE)\n> png(filename=\"pfilter2-%02d.png\",res=100)\n> \n> library(pomp)\n> suppressPackageStartupMessages({\n+   library(tidyr)\n+   library(dplyr)\n+   library(ggplot2)\n+ })\n> \n> set.seed(9994847L)\n> \n> ou2(tau=5) |>\n+   window(end=10) |>\n+   pfilter(\n+     Np=5000,\n+     save.states=\"weighted\",\n+     filter.mean=TRUE,\n+     pred.mean=TRUE,\n+     pred.var=TRUE,\n+     filter.traj=TRUE\n+   ) -> pf\nWarning message:\nThe 'save.states' option 'weighted' is deprecated and will be removed in a future version.\nUse 'prediction' instead. \n> \n> pf |> as.data.frame() |> names()\n [1] \"time\"           \"y1\"             \"y2\"             \"x1\"            \n [5] \"x2\"             \"ess\"            \"cond.logLik\"    \"pred.mean.x1\"  \n [9] \"pred.mean.x2\"   \"pred.var.x1\"    \"pred.var.x2\"    \"filter.mean.x1\"\n[13] \"filter.mean.x2\"\n> pf |> as.data.frame() |> pivot_longer(-time) |> names()\n[1] \"time\"  \"name\"  \"value\"\n> pf |> forecast() |> melt() |> sapply(class)\n       name        time       value \n\"character\"   \"integer\"   \"numeric\" \n> pf |> forecast(format=\"d\") |> sapply(class)\n       name        time       value \n\"character\"   \"numeric\"   \"numeric\" \n> pf |> filter_mean() |> melt() |> sapply(class)\n       name        time       value \n\"character\"   \"integer\"   \"numeric\" \n> pf |> filter_mean(format=\"d\") |> sapply(class)\n       name        time       value \n\"character\"   \"numeric\"   \"numeric\" \n> pf |> pred_mean() |> melt() |> sapply(class)\n       name        time       value \n\"character\"   \"integer\"   \"numeric\" \n> pf |> pred_mean(format=\"d\") |> sapply(class)\n       name        time       value \n\"character\"   \"numeric\"   \"numeric\" \n> pf |> pred_var() |> melt() |> sapply(class)\n       name        time       value \n\"character\"   \"integer\"   \"numeric\" \n> pf |> pred_var(format=\"d\") |> sapply(class)\n       name        time       value \n\"character\"   \"numeric\"   \"numeric\" \n> pf |> filter_traj() |> melt() |> sapply(class)\n       name         rep        time       value \n\"character\" \"character\"   \"integer\"   \"numeric\" \n> pf |> filter_traj(format=\"d\") |> sapply(class)\n       name         rep        time       value \n\"character\" \"character\"   \"numeric\"   \"numeric\" \n> pf |> saved_states() |> melt() |> sapply(class)\n        .L1         .L2        name         .id       value \n\"character\"   \"integer\" \"character\"   \"integer\"   \"numeric\" \n> pf |> saved_states(format=\"d\") |> sapply(class)\n       time         .id        name       value \n  \"numeric\"   \"integer\" \"character\"   \"numeric\" \n> \n> c(A=pf,B=pf) -> pfs\n> pfs |> filter_traj(format=\"d\") |> head()\n  name rep time chain value\n1   x1   1    1     A -3.00\n2   x2   1    1     A  4.00\n3   x1   1    2     A -3.58\n4   x2   1    2     A  5.85\n5   x1   1    3     A -1.13\n6   x2   1    3     A  8.31\n> pfs |> filter_traj(format=\"d\") |> dim()\n[1] 44  5\n> pfs |> filter_traj(format=\"a\") |> dim()\n[1]  2  1 11  2\n> pfs |> eff_sample_size(format=\"n\") |> melt() |> dim()\n[1] 20  3\n> pfs |> eff_sample_size(format=\"d\") |> dim()\n[1] 20  3\n> pfs |> cond_logLik(format=\"n\") |> melt() |> dim()\n[1] 20  3\n> pfs |> cond_logLik(format=\"d\") |> dim()\n[1] 20  3\n> list(A=pf,B=pf) |> concat() -> pfs2\n> stopifnot(\n+   all.equal(\n+     pfs |> as.data.frame(),\n+     pfs2 |> as.data.frame()\n+   )\n+ )\n>   \n> \n> try(pf |> forecast(format=\"l\"))\nError in match.arg(format) : 'arg' should be one of \"array\", \"data.frame\"\n> \n> pf |> as.data.frame() -> dat0\n> \n> bind_rows(\n+   eff.sample.size=data.frame(\n+     time=seq_along(time(pf)),\n+     value=eff_sample_size(pf)\n+   ),\n+   cond.logLik=data.frame(\n+     time=seq_along(time(pf)),\n+     value=cond_logLik(pf)\n+   ),\n+   .id=\"name\"\n+ ) |>\n+   pivot_wider() |>\n+   mutate(\n+     time=time(pf)[as.integer(time)]\n+   ) -> dat1\n> full_join(\n+   eff_sample_size(pf,format=\"d\"),\n+   cond_logLik(pf,format=\"d\"),\n+   by=\"time\"\n+ ) -> dat2\n> stopifnot(\n+   dat0$eff.sample.size==dat2$eff.sample.size,\n+   dat0$cond.logLik==dat2$cond.logLik,\n+   all.equal(dat1,dat2,check.attributes=FALSE)\n+ )\n> \n> bind_rows(\n+   forecast=melt(forecast(pf)),\n+   filter.mean=melt(filter_mean(pf)),\n+   pred.mean=melt(pred_mean(pf)),\n+   pred.var=melt(pred_var(pf)),\n+   .id=\"type\"\n+ ) |>\n+   mutate(\n+     time=time(pf)[as.integer(time)]\n+   ) |>\n+   unite(col=name,type,name,sep=\".\") |>\n+   pivot_wider() -> dat1\n> bind_rows(\n+   forecast=forecast(pf,format=\"d\"),\n+   filter.mean=filter_mean(pf,format=\"d\"),\n+   pred.mean=pred_mean(pf,format=\"d\"),\n+   pred.var=pred_var(pf,format=\"d\"),\n+   .id=\"type\"\n+ ) |>\n+   unite(col=name,type,name,sep=\".\") |>\n+   pivot_wider() -> dat2\n> stopifnot(\n+   all.equal(dat1,dat2,check.attributes=FALSE),\n+   all.equal(dat0$filter.mean.x1,dat2$filter.mean.x1),\n+   all.equal(dat0$filter.mean.x2,dat2$filter.mean.x2),\n+   all.equal(dat0$pred.mean.x1,dat2$pred.mean.x1),\n+   all.equal(dat0$pred.mean.x2,dat2$pred.mean.x2),\n+   all.equal(dat0$pred.var.x1,dat2$pred.var.x1),\n+   all.equal(dat0$pred.var.x2,dat2$pred.var.x2)\n+ )\n> \n> pf |>\n+   filter_traj() |>\n+   melt() |>\n+   mutate(\n+     time=time(pf,t0=TRUE)[as.integer(time)]\n+   ) -> dat1\n> pf |>\n+   filter_traj(format=\"d\") -> dat2\n> stopifnot(\n+   all.equal(dat1,dat2,check.attributes=FALSE)\n+ )\n> \n> pf |>\n+   saved_states(format=\"l\") -> dat1\n> bind_rows(\n+   melt(dat1$states),\n+   melt(dat1$weights)\n+ ) |>\n+   mutate(\n+     name=coalesce(name,\".log.weight\"),\n+     time=time(pf)[as.integer(.L1)]\n+   ) |>\n+   select(-.L1) |>\n+   arrange(time,.id) |>\n+   select(time,.id,name,value) -> dat1\n> pf |>\n+   saved_states(format=\"d\") -> dat2\n> stopifnot(\n+   all.equal(dat1,dat2,check.attributes=FALSE)\n+ )\n> \n> pf |>\n+   saved_states(format=\"d\") |>\n+   pivot_wider() |>\n+   group_by(time) |>\n+   reframe(\n+     p=c(0.05,0.5,0.95),\n+     x1=wquant(x1,weights=exp(.log.weight),probs=p),\n+     x2=wquant(x2,weights=exp(.log.weight),probs=p)\n+   ) |>\n+   ungroup() |>\n+   pivot_longer(c(x1,x2)) |>\n+   pivot_wider(names_from=p) |>\n+   ggplot(aes(x=time,y=`0.5`,ymin=`0.05`,ymax=`0.95`,group=name))+\n+   geom_ribbon(alpha=0.5)+\n+   geom_line(color=\"red\")+\n+   facet_grid(name~.)+\n+   labs(y=\"\")\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/pmcmc.R",
    "content": "options(digits=3)\npng(filename=\"pmcmc-%02d.png\",res=100)\n\nlibrary(pomp)\n\nset.seed(857075216L)\n\ngompertz() |> window(end=10) -> po\n\nprop1 <- mvn_diag_rw(c(r=0.01,sigma=0.01))\n\nmcmc1 <- pmcmc(\n  po,Nmcmc=100,Np=100,dprior=Csnippet(\"\n    lik = dunif(r,0,1,1)+dnorm(sigma,0,1,1);\n    lik = (give_log) ? lik : exp(lik);\"),\n  paramnames=c(\"r\",\"sigma\"),\n  proposal=prop1\n)\n\ntry(pmcmc())\ntry(pmcmc(\"bob\"))\ntry(pmcmc(po))\ntry(pmcmc(po,proposal=\"yes\"))\ntry(pmcmc(po,proposal=NULL))\ntry(pmcmc(po,proposal=3))\ntry(pmcmc(po,proposal=\"prop1\"))\ntry(pmcmc(po,proposal=prop1))\ntry(pmcmc(po,proposal=prop1,Np=\"bob\"))\ntry(pmcmc(po,proposal=prop1,Np=NULL))\ntry(pmcmc(po,proposal=prop1,Np=NA))\ntry(pmcmc(po,proposal=prop1,Np=c(1,2,3)))\ntry(pmcmc(po,proposal=prop1,Np=-5))\npmcmc(po,proposal=prop1,Np=1)\npmcmc(po,proposal=prop1,Np=rep(1,11))\ntry(pmcmc(po,proposal=prop1,Np=function(k)10*k))\npmcmc(po,proposal=prop1,Np=function(k)10*k+10)\n\ntry(pmcmc(mcmc1,params=c(r=3,K=1,sigma=0.1,tau=0.1,X_0=1),Np=100))\n\npf <- pfilter(po,Np=100)\nmcmc2 <- pmcmc(pf,Nmcmc=100,proposal=prop1)\nmcmc3 <- pmcmc(mcmc1,Nmcmc=50)\nmcmc3 <- continue(mcmc3,Nmcmc=50)\n\nplot(c(mcmc1,mcmc2,mcmc3),pars=c(\"r\",\"sigma\"),density=FALSE)\nplot(c(mcmc1,c(mcmc2,mcmc3)),pars=c(\"r\",\"sigma\"),trace=FALSE)\ninvisible(window(traces(c(c(mcmc1,c(mcmc2,mcmc3)))),thin=10))\nplot(traces(c(c(mcmc1,mcmc2),mcmc3),c(\"r\",\"sigma\")))\ntry(traces(c(c(mcmc1,mcmc2),mcmc3),c(\"r\",\"bob\")))\ndim(as.data.frame(c(mcmc1,mcmc2)))\n\nfilter_traj(c(mcmc1,mcmc2,mcmc3)) -> ft\nstopifnot(\n  dim(ft)==c(1,100,11,3),\n  names(dimnames(ft))==c(\"name\",\"rep\",\"time\",\"chain\")\n)\n\nprint(mcmc1)\nc(mcmc1,mcmc2) -> mcl\nmcl[1]\nmcl[3]\n\nstopifnot(dim(filter_traj(mcmc1))==c(1,100,11),\n  dim(filter_traj(c(mcmc1,mcmc2,mcmc3)))==c(1,100,11,3))\nlogLik(mcmc1)\nlogLik(c(mcmc1,mcmc2,mcmc3))\n\npmcmc(mcmc1,params=as.list(coef(mcmc3)))\ntry(pmcmc(mcmc1,params=NULL))\ntry(pmcmc(mcmc1,params=-7))\ntry(pmcmc(mcmc1,params=\"yes\"))\ntry(pmcmc(mcmc1,params=list()))\ntry({tmp <- mcmc1; coef(tmp) <- NULL; pmcmc(tmp)})\ntry(pmcmc(mcmc1,proposal=function(...)c(3,2)))\ntry(pmcmc(mcmc1,Nmcmc=3,proposal=function(...)c(a=3,b=2,X.0=1)))\ntry(pmcmc(mcmc1,proposal=function(...)stop(\"oh no!\")))\ntry({\n  count <- 0\n  delayed.failure <- function (theta, ...) {\n    count <<- count+1\n    if (count>5) stop(\"no sir!\") else theta\n  }\n  pmcmc(mcmc1,proposal=delayed.failure)})\n\ntry(pmcmc(mcmc1,Nmcmc=-20))\ntry(pmcmc(mcmc1,Nmcmc=NA))\ntry(pmcmc(mcmc1,Nmcmc=c(5,10,15)))\n\ntry(pmcmc(mcmc1,dprior=function(log,...)stop(\"not again!\")))\ntry({\n  count <- 0\n  delayed.failure <- function (log, ...) {\n    count <<- count+1\n    if (count>5) stop(\"uh huh\") else 1\n  }\n  pmcmc(mcmc1,dprior=delayed.failure)})\n\ntry(pmcmc(mcmc1,dmeasure=function(log,...)if (log) -Inf else 0))\n\ncapture.output(invisible(pmcmc(mcmc1,Nmcmc=10,verbose=TRUE))) -> out\nstopifnot(sum(grepl(\"acceptance ratio\",out))==10)\nstopifnot(sum(grepl(\"PMCMC iteration\",out))==11)\n\ngompertz() -> gompertz\n\nset.seed(857075216L)\n\ntry(gompertz |> as.data.frame() |> pmcmc())\ntry(gompertz |> as.data.frame() |> pmcmc(times=\"time\",t0=0))\ntry(gompertz |> as.data.frame() |> pmcmc(times=\"time\",t0=0,\n  proposal=mvn_diag_rw(c(a=1,b=2))))\n\ngompertz |>\n  as.data.frame() |>\n  pmcmc(\n    Nmcmc=10,Np=100,\n    times=\"time\",t0=0,\n    rprocess=discrete_time(\n      function (x, r, K, ...) {\n        c(x=x*exp(r*(1-x/K)))\n      }\n    ),\n    dmeasure=function (Y, x, ..., log) {\n      dlnorm(Y,meanlog=log(0.01*x),sdlog=2,log=log)\n    },\n    dprior=function(r,K,...,log) {\n      ll <- sum(dlnorm(x=c(r,K),meanlog=log(0.1,150),sdlog=3,log=TRUE))\n      if (log) ll else exp(ll)\n    },\n    proposal=mvn_diag_rw(c(r=0.01,K=10)),\n    params=c(r=0.1,K=150,x_0=150)\n  ) -> mcmc5\nplot(mcmc5,pars=c(\"r\",\"K\"))\n\ndev.off()\n"
  },
  {
    "path": "tests/pmcmc.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"pmcmc-%02d.png\",res=100)\n> \n> library(pomp)\n> \n> set.seed(857075216L)\n> \n> gompertz() |> window(end=10) -> po\n> \n> prop1 <- mvn_diag_rw(c(r=0.01,sigma=0.01))\n> \n> mcmc1 <- pmcmc(\n+   po,Nmcmc=100,Np=100,dprior=Csnippet(\"\n+     lik = dunif(r,0,1,1)+dnorm(sigma,0,1,1);\n+     lik = (give_log) ? lik : exp(lik);\"),\n+   paramnames=c(\"r\",\"sigma\"),\n+   proposal=prop1\n+ )\n> \n> try(pmcmc())\nError : in 'pmcmc': 'data' is a required argument.\n> try(pmcmc(\"bob\"))\nError : 'pmcmc' is undefined for 'data' of class 'character'.\n> try(pmcmc(po))\nError : in 'pmcmc': 'proposal' must be specified\n> try(pmcmc(po,proposal=\"yes\"))\nError : in 'pmcmc': 'proposal' must be a function: object 'yes' of mode 'function' was not found\n> try(pmcmc(po,proposal=NULL))\nError : in 'pmcmc': 'proposal' must be specified\n> try(pmcmc(po,proposal=3))\nError : in 'pmcmc': 'proposal' must be a function: object 'proposal' of mode 'function' was not found\n> try(pmcmc(po,proposal=\"prop1\"))\nError : in 'pmcmc': in 'pfilter': 'Np' must be specified.\n> try(pmcmc(po,proposal=prop1))\nError : in 'pmcmc': in 'pfilter': 'Np' must be specified.\n> try(pmcmc(po,proposal=prop1,Np=\"bob\"))\nError : in 'pmcmc': in 'pfilter': 'Np' must be a number, a vector of numbers, or a function.\n> try(pmcmc(po,proposal=prop1,Np=NULL))\nError : in 'pmcmc': in 'pfilter': 'Np' must be specified.\n> try(pmcmc(po,proposal=prop1,Np=NA))\nError : in 'pmcmc': in 'pfilter': 'Np' must be a number, a vector of numbers, or a function.\n> try(pmcmc(po,proposal=prop1,Np=c(1,2,3)))\nError : in 'pmcmc': in 'pfilter': 'Np' must have length 1 or length 11.\n> try(pmcmc(po,proposal=prop1,Np=-5))\nError : in 'pmcmc': in 'pfilter': number of particles, 'Np', must be a positive integer.\n> pmcmc(po,proposal=prop1,Np=1)\n<object of class 'pmcmcd_pomp'>\n> pmcmc(po,proposal=prop1,Np=rep(1,11))\n<object of class 'pmcmcd_pomp'>\n> try(pmcmc(po,proposal=prop1,Np=function(k)10*k))\nError : in 'pmcmc': in 'pfilter': number of particles, 'Np', must be a positive integer.\n> pmcmc(po,proposal=prop1,Np=function(k)10*k+10)\n<object of class 'pmcmcd_pomp'>\n> \n> try(pmcmc(mcmc1,params=c(r=3,K=1,sigma=0.1,tau=0.1,X_0=1),Np=100))\nError : in 'pmcmc': non-finite log prior at starting parameters.\n> \n> pf <- pfilter(po,Np=100)\n> mcmc2 <- pmcmc(pf,Nmcmc=100,proposal=prop1)\n> mcmc3 <- pmcmc(mcmc1,Nmcmc=50)\n> mcmc3 <- continue(mcmc3,Nmcmc=50)\n> \n> plot(c(mcmc1,mcmc2,mcmc3),pars=c(\"r\",\"sigma\"),density=FALSE)\n> plot(c(mcmc1,c(mcmc2,mcmc3)),pars=c(\"r\",\"sigma\"),trace=FALSE)\n> invisible(window(traces(c(c(mcmc1,c(mcmc2,mcmc3)))),thin=10))\n> plot(traces(c(c(mcmc1,mcmc2),mcmc3),c(\"r\",\"sigma\")))\n> try(traces(c(c(mcmc1,mcmc2),mcmc3),c(\"r\",\"bob\")))\nError : in 'traces': parameter 'bob' not found.\n> dim(as.data.frame(c(mcmc1,mcmc2)))\n[1] 20  5\n> \n> filter_traj(c(mcmc1,mcmc2,mcmc3)) -> ft\n> stopifnot(\n+   dim(ft)==c(1,100,11,3),\n+   names(dimnames(ft))==c(\"name\",\"rep\",\"time\",\"chain\")\n+ )\n> \n> print(mcmc1)\n<object of class 'pmcmcd_pomp'>\n> c(mcmc1,mcmc2) -> mcl\n> mcl[1]\n[[1]]\n<object of class 'pmcmcd_pomp'>\n\n> mcl[3]\n[[1]]\nNULL\n\n> \n> stopifnot(dim(filter_traj(mcmc1))==c(1,100,11),\n+   dim(filter_traj(c(mcmc1,mcmc2,mcmc3)))==c(1,100,11,3))\n> logLik(mcmc1)\n[1] 3.43\n> logLik(c(mcmc1,mcmc2,mcmc3))\n[1] 3.43 3.43 3.43\n> \n> pmcmc(mcmc1,params=as.list(coef(mcmc3)))\n<object of class 'pmcmcd_pomp'>\n> try(pmcmc(mcmc1,params=NULL))\nError : in 'pmcmc': in 'dprior': variable 'r' not found among the parameters.\nIn addition: Warning message:\nIn rnorm(n = n, mean = theta[parnm], sd = rw.sd) : NAs produced\n> try(pmcmc(mcmc1,params=-7))\nError : in 'pmcmc': 'params' must be a named numeric vector.\n> try(pmcmc(mcmc1,params=\"yes\"))\nError : in 'pmcmc': 'params' must be a named numeric vector.\nIn addition: Warning message:\nNAs introduced by coercion \n> try(pmcmc(mcmc1,params=list()))\nError : in 'pmcmc': in 'dprior': variable 'r' not found among the parameters.\nIn addition: Warning message:\nIn rnorm(n = n, mean = theta[parnm], sd = rw.sd) : NAs produced\n> try({tmp <- mcmc1; coef(tmp) <- NULL; pmcmc(tmp)})\nError : in 'pmcmc': in 'dprior': variable 'r' not found among the parameters.\nIn addition: Warning message:\nIn rnorm(n = n, mean = theta[parnm], sd = rw.sd) : NAs produced\n> try(pmcmc(mcmc1,proposal=function(...)c(3,2)))\nError : in 'pmcmc': 'proposal' must return a named numeric vector.\n> try(pmcmc(mcmc1,Nmcmc=3,proposal=function(...)c(a=3,b=2,X.0=1)))\nError : in 'pmcmc': in 'dprior': variable 'r' not found among the parameters.\n> try(pmcmc(mcmc1,proposal=function(...)stop(\"oh no!\")))\nError : in 'pmcmc': error in proposal function: oh no!\n> try({\n+   count <- 0\n+   delayed.failure <- function (theta, ...) {\n+     count <<- count+1\n+     if (count>5) stop(\"no sir!\") else theta\n+   }\n+   pmcmc(mcmc1,proposal=delayed.failure)})\nError : in 'pmcmc': error in proposal function: no sir!\n> \n> try(pmcmc(mcmc1,Nmcmc=-20))\nError : in 'pmcmc': 'Nmcmc' must be a positive integer\n> try(pmcmc(mcmc1,Nmcmc=NA))\nError : in 'pmcmc': 'Nmcmc' must be a positive integer\n> try(pmcmc(mcmc1,Nmcmc=c(5,10,15)))\nError : in 'pmcmc': 'Nmcmc' must be a positive integer\n> \n> try(pmcmc(mcmc1,dprior=function(log,...)stop(\"not again!\")))\nError : in 'pmcmc': in 'dprior': not again!\n> try({\n+   count <- 0\n+   delayed.failure <- function (log, ...) {\n+     count <<- count+1\n+     if (count>5) stop(\"uh huh\") else 1\n+   }\n+   pmcmc(mcmc1,dprior=delayed.failure)})\nError : in 'pmcmc': in 'dprior': uh huh\n> \n> try(pmcmc(mcmc1,dmeasure=function(log,...)if (log) -Inf else 0))\nError : in 'pmcmc': non-finite log likelihood at starting parameters.\n> \n> capture.output(invisible(pmcmc(mcmc1,Nmcmc=10,verbose=TRUE))) -> out\n> stopifnot(sum(grepl(\"acceptance ratio\",out))==10)\n> stopifnot(sum(grepl(\"PMCMC iteration\",out))==11)\n> \n> gompertz() -> gompertz\n> \n> set.seed(857075216L)\n> \n> try(gompertz |> as.data.frame() |> pmcmc())\nError : in 'pmcmc': 'times' should either be a numeric vector of observation times or a single name identifying the column of data that represents the observation times.\n> try(gompertz |> as.data.frame() |> pmcmc(times=\"time\",t0=0))\nError : in 'pmcmc': 'proposal' must be specified\n> try(gompertz |> as.data.frame() |> pmcmc(times=\"time\",t0=0,\n+   proposal=mvn_diag_rw(c(a=1,b=2))))\nError : in 'pmcmc': in 'pfilter': 'rprocess', 'dmeasure' are needed basic components.\nIn addition: Warning message:\nIn rnorm(n = n, mean = theta[parnm], sd = rw.sd) : NAs produced\n> \n> gompertz |>\n+   as.data.frame() |>\n+   pmcmc(\n+     Nmcmc=10,Np=100,\n+     times=\"time\",t0=0,\n+     rprocess=discrete_time(\n+       function (x, r, K, ...) {\n+         c(x=x*exp(r*(1-x/K)))\n+       }\n+     ),\n+     dmeasure=function (Y, x, ..., log) {\n+       dlnorm(Y,meanlog=log(0.01*x),sdlog=2,log=log)\n+     },\n+     dprior=function(r,K,...,log) {\n+       ll <- sum(dlnorm(x=c(r,K),meanlog=log(0.1,150),sdlog=3,log=TRUE))\n+       if (log) ll else exp(ll)\n+     },\n+     proposal=mvn_diag_rw(c(r=0.01,K=10)),\n+     params=c(r=0.1,K=150,x_0=150)\n+   ) -> mcmc5\n> plot(mcmc5,pars=c(\"r\",\"K\"))\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/pomp.R",
    "content": "options(digits=3)\n\nset.seed(758723694)\n\nlibrary(pomp)\n\ntry(pomp())\ntry(pomp(\"bob\"))\ntry(pomp(times=3))\ntry(pomp(NULL))\ntry(data.frame(a=1:10,a=1:10,check.names=FALSE) |> pomp(t0=4))\ntry(data.frame(a=1:10,a=1:10,check.names=FALSE) |> pomp(times=1:10,t0=4))\ntry(data.frame(a=1:10,a=1:10,check.names=FALSE) |> pomp(times=\"a\",t0=4))\ntry(data.frame(a=1:10,b=1:10) |> pomp(times=1:10,t0=4))\ntry(data.frame(a=1:10,b=1:10) |> pomp(times=\"b\"))\ntry(data.frame(a=10:1,b=1:10) |> pomp(times=\"a\",t0=0))\ndata.frame(a=1:10,b=1:10) |> pomp(times=1:10,t0=0)\ntry(data.frame(a=1:10,b=1:10) |> pomp(times=1))\ntry(data.frame(a=1:10,b=1:10) |> pomp(times=\"a\"))\ntry(data.frame(a=1:10,b=1:10) |> pomp(times=\"c\",t0=0))\ntry(data.frame(a=1:10,b=1:10) |> pomp(times=NA,t0=0))\ntry(data.frame(a=1:10,b=1:10) |> pomp(times=NULL,t0=0))\ntry(data.frame(a=1:10,b=1:10) |> pomp(times=1,t0=11))\ntry(data.frame(a=1:10,b=1:10) |> pomp(times=\"a\",t0=11))\ntry(data.frame(a=1:10,b=1:10) |> pomp(times=\"b\",t0=NULL))\ntry(data.frame(a=1:10,b=1:10) |> pomp(times=\"a\",t0=NA))\nstopifnot(data.frame(a=1:10,b=1:10) |>\n    pomp(covar=covariate_table(c=0:10,d=0:10,times=\"c\"),\n      covarnames=\"d\",times=\"a\",t0=0,userdata=list(bob=3)) |> class() == \"pomp\")\ntry(data.frame(a=1:10,b=1:10) |>\n    pomp(covar=covariate_table(c=1:10,d=1:10,d=1:10,times=\"c\"),\n      times=\"a\",t0=0))\nstopifnot(data.frame(a=1:10,b=1:10) |>\n    pomp(times=\"a\",t0=0) |> class() == \"pomp\")\ntry(NULL |> pomp(t0=4))\ntry(NULL |> pomp(times=\"a\",t0=0))\ntry(NULL |> pomp(times=1:10,t0=3))\ntry(NULL |> pomp(times=1:10,t0=1,rinit=3))\nstopifnot(NULL |> pomp(times=1:10,t0=1) |> class() == \"pomp\")\n\ngompertz() -> po\nstopifnot({\n  po |> pomp(rprocess=NULL) -> po1\n  rprocess(po1,x0=rinit(po1),t0=timezero(po1),\n    times=time(po1),params=coef(po1)) -> x\n  sum(is.na(x))==100\n})\n\npo |> pomp(rprocess=NULL) |> slot(\"rprocess\")\npo |> pomp(skeleton=NULL) |> slot(\"skeleton\")\npo |> pomp(partrans=NULL) |> slot(\"partrans\")\n\nstopifnot({\n  po |> pomp(partrans=NULL) |> coef(transform=TRUE) -> theta1\n  coef(po) -> theta2\n  theta1==theta2\n},\n  po |> pomp(times=1:5) |> class() == \"pomp\")\n\nstopifnot(po |>\n    pomp(rprocess=onestep(function(x,t,params,delta.t,...)x),\n      skeleton=map(function(x,t,params,...)x),\n      rmeasure=function(...)3,\n      dmeasure=function(log,...)1,\n      covar=covariate_table(a=1:20,b=1:20,times=\"a\")) |> class() == \"pomp\")\n\ntry(po |> pomp(times=3:1))\n\ntry(po |> pomp(rinit=Csnippet(\"X=3;\")))\nstopifnot(\n  po |> pomp(rinit=Csnippet(\"X=3;\"),statenames=c(\"X\",\"Z\")) |> class() == \"pomp\",\n  po |> pomp(\n          globals=r\"{#define X (__x[0])}\",\n          rinit=Csnippet(\"X=3;\"),\n          statenames=character(0),\n          nstatevars=c(3,NA)\n        ) |>\n    rinit() |>\n    dim()==c(3,1),\n  po |> pomp(nstatevars=-3) |> class() == \"pomp\",\n  po |> pomp(nstatevars=NA) |> class() == \"pomp\"\n)\n\ntry(po |> pomp(rprocess=\"bob\"))\ntry(po |> pomp(skeleton=\"bob\"))\ntry(po |> pomp(partrans=\"bob\"))\ntry(po |> pomp(params=c(1,2,3)))\ntry(po |> pomp(params=c(a=1,b=2,3)))\n\nsir() |> window(end=0.12) -> po2\npo2 |> simulate(seed=4358686) |> as.data.frame()\npomp(po2,covar=NULL)@covar\ntry(po2 |> pomp(covar=\"bob\"))\ntry(po2 |> pomp(rmeasure=function(x)x))\ntry(pomp(data=NULL,times=1:10,t0=0,rmeasure=Csnippet(\"\")))\n\ntry(po2 |> pomp(rmeasure=Csnippet(\"reports=3;\"),cfile=\"sir_source\"))\n"
  },
  {
    "path": "tests/pomp.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> \n> set.seed(758723694)\n> \n> library(pomp)\n> \n> try(pomp())\nError : in 'pomp': 'data' is a required argument.\n> try(pomp(\"bob\"))\nError : in 'pomp': 'data' must be a data frame or an object of class 'pomp'.\n> try(pomp(times=3))\nError : in 'pomp': 'data' is a required argument.\n> try(pomp(NULL))\nError : 'times' should either be a numeric vector of observation times or a single name identifying the column of data that represents the observation times.\n> try(data.frame(a=1:10,a=1:10,check.names=FALSE) |> pomp(t0=4))\nError : 'times' should either be a numeric vector of observation times or a single name identifying the column of data that represents the observation times.\n> try(data.frame(a=1:10,a=1:10,check.names=FALSE) |> pomp(times=1:10,t0=4))\nError : names of data variables must be unique.\n> try(data.frame(a=1:10,a=1:10,check.names=FALSE) |> pomp(times=\"a\",t0=4))\nError : names of data variables must be unique.\n> try(data.frame(a=1:10,b=1:10) |> pomp(times=1:10,t0=4))\nError : 't0' must be a single number not greater than 'times[1]'.\n> try(data.frame(a=1:10,b=1:10) |> pomp(times=\"b\"))\nError : 't0' is a required argument.\n> try(data.frame(a=10:1,b=1:10) |> pomp(times=\"a\",t0=0))\nError : 'times' must be a non-decreasing sequence of numbers.\n> data.frame(a=1:10,b=1:10) |> pomp(times=1:10,t0=0)\n<object of class 'pomp'>\n> try(data.frame(a=1:10,b=1:10) |> pomp(times=1))\nError : 't0' is a required argument.\n> try(data.frame(a=1:10,b=1:10) |> pomp(times=\"a\"))\nError : 't0' is a required argument.\n> try(data.frame(a=1:10,b=1:10) |> pomp(times=\"c\",t0=0))\nError : 'times' does not identify a single column of 'data' by name.\n> try(data.frame(a=1:10,b=1:10) |> pomp(times=NA,t0=0))\nError : 'times' should either be a numeric vector of observation times or a single name identifying the column of data that represents the observation times.\n> try(data.frame(a=1:10,b=1:10) |> pomp(times=NULL,t0=0))\nError : 'times' should either be a numeric vector of observation times or a single name identifying the column of data that represents the observation times.\n> try(data.frame(a=1:10,b=1:10) |> pomp(times=1,t0=11))\nError : the length of 'times' does not match that of the data.\n> try(data.frame(a=1:10,b=1:10) |> pomp(times=\"a\",t0=11))\nError : 't0' must be a single number not greater than 'times[1]'.\n> try(data.frame(a=1:10,b=1:10) |> pomp(times=\"b\",t0=NULL))\nError : 't0' must be a single number not greater than 'times[1]'.\n> try(data.frame(a=1:10,b=1:10) |> pomp(times=\"a\",t0=NA))\nError : 't0' must be a single number not greater than 'times[1]'.\n> stopifnot(data.frame(a=1:10,b=1:10) |>\n+     pomp(covar=covariate_table(c=0:10,d=0:10,times=\"c\"),\n+       covarnames=\"d\",times=\"a\",t0=0,userdata=list(bob=3)) |> class() == \"pomp\")\n> try(data.frame(a=1:10,b=1:10) |>\n+     pomp(covar=covariate_table(c=1:10,d=1:10,d=1:10,times=\"c\"),\n+       times=\"a\",t0=0))\n<object of class 'pomp'>\nWarning message:\nin 'pomp': the supplied covariate times do not embrace the data times: covariates may be extrapolated. \n> stopifnot(data.frame(a=1:10,b=1:10) |>\n+     pomp(times=\"a\",t0=0) |> class() == \"pomp\")\n> try(NULL |> pomp(t0=4))\nError : 'times' should either be a numeric vector of observation times or a single name identifying the column of data that represents the observation times.\n> try(NULL |> pomp(times=\"a\",t0=0))\nError : 'times' should either be a numeric vector of observation times or a single name identifying the column of data that represents the observation times.\n> try(NULL |> pomp(times=1:10,t0=3))\nError : 't0' must be a single number not greater than 'times[1]'.\n> try(NULL |> pomp(times=1:10,t0=1,rinit=3))\nError : bad option for 'rinit' argument.\n> stopifnot(NULL |> pomp(times=1:10,t0=1) |> class() == \"pomp\")\n> \n> gompertz() -> po\n> stopifnot({\n+   po |> pomp(rprocess=NULL) -> po1\n+   rprocess(po1,x0=rinit(po1),t0=timezero(po1),\n+     times=time(po1),params=coef(po1)) -> x\n+   sum(is.na(x))==100\n+ })\nWarning message:\n'rprocess' unspecified: NAs generated. \n> \n> po |> pomp(rprocess=NULL) |> slot(\"rprocess\")\n<undefined>\n> po |> pomp(skeleton=NULL) |> slot(\"skeleton\")\n<default>\n\n> po |> pomp(partrans=NULL) |> slot(\"partrans\")\n  - to estimation scale: <identity>\n  - from estimation scale: <identity>\n> \n> stopifnot({\n+   po |> pomp(partrans=NULL) |> coef(transform=TRUE) -> theta1\n+   coef(po) -> theta2\n+   theta1==theta2\n+ },\n+   po |> pomp(times=1:5) |> class() == \"pomp\")\n> \n> stopifnot(po |>\n+     pomp(rprocess=onestep(function(x,t,params,delta.t,...)x),\n+       skeleton=map(function(x,t,params,...)x),\n+       rmeasure=function(...)3,\n+       dmeasure=function(log,...)1,\n+       covar=covariate_table(a=1:20,b=1:20,times=\"a\")) |> class() == \"pomp\")\nWarning message:\nin 'pomp': the supplied covariate times do not embrace the data times: covariates may be extrapolated. \n> \n> try(po |> pomp(times=3:1))\nError : in 'time<-': times must be a non-decreasing numeric sequence.\n> \n> try(po |> pomp(rinit=Csnippet(\"X=3;\")))\nError : when 'rinit' is provided as a C snippet, you must also provide 'statenames'.\n> stopifnot(\n+   po |> pomp(rinit=Csnippet(\"X=3;\"),statenames=c(\"X\",\"Z\")) |> class() == \"pomp\",\n+   po |> pomp(\n+           globals=r\"{#define X (__x[0])}\",\n+           rinit=Csnippet(\"X=3;\"),\n+           statenames=character(0),\n+           nstatevars=c(3,NA)\n+         ) |>\n+     rinit() |>\n+     dim()==c(3,1),\n+   po |> pomp(nstatevars=-3) |> class() == \"pomp\",\n+   po |> pomp(nstatevars=NA) |> class() == \"pomp\"\n+ )\n> \n> try(po |> pomp(rprocess=\"bob\"))\nError : 'rprocess' must be specified using one of the plugins:\n'onestep', 'discrete_time', 'euler', 'gillespie', or 'gillespie_hl'.\n> try(po |> pomp(skeleton=\"bob\"))\nError : 'skeleton' must be specified using either 'map' or 'vectorfield'.\n> try(po |> pomp(partrans=\"bob\"))\nError : 'partrans' must be specified using 'parameter_trans'.\n> try(po |> pomp(params=c(1,2,3)))\nError : 'params' must be a named numeric vector.\n> try(po |> pomp(params=c(a=1,b=2,3)))\nError : 'params' must be a named numeric vector.\n> \n> sir() |> window(end=0.12) -> po2\n> po2 |> simulate(seed=4358686) |> as.data.frame()\n    time reports      S    I       R cases       W seas_1 seas_2 seas_3\n1 0.0192     798 136185 2085 1961717  1051  0.0281  0.663  0.197 0.1395\n2 0.0385     575 135920 2106 1961963  1006 -0.2345  0.654  0.230 0.1157\n3 0.0577     552 135555 2183 1962268  1083  0.0194  0.639  0.266 0.0952\n4 0.0769     754 135180 2246 1962523  1044 -0.0823  0.619  0.303 0.0780\n5 0.0962     604 134729 2332 1962895  1139 -0.0201  0.595  0.341 0.0641\n6 0.1154     803 134298 2353 1963336  1184 -0.0699  0.567  0.379 0.0536\n> pomp(po2,covar=NULL)@covar\n<none>\n> try(po2 |> pomp(covar=\"bob\"))\nError : bad option for 'covar'.\n> try(po2 |> pomp(rmeasure=function(x)x))\nError : in 'rmeasure': 'rmeasure' must be a function of the form 'rmeasure(...)'\n> try(pomp(data=NULL,times=1:10,t0=0,rmeasure=Csnippet(\"\")))\nError : when 'rmeasure' is provided as a C snippet, you must also provide 'obsnames'.\n> \n> try(po2 |> pomp(rmeasure=Csnippet(\"reports=3;\"),cfile=\"sir_source\"))\nError : C file name \"sir_source\" cannot be re-used.\n> \n"
  },
  {
    "path": "tests/pomp_fun.R",
    "content": "options(digits=3,keep.source=TRUE)\n\nlibrary(pomp)\n\npomp:::pomp_fun()\npomp:::pomp_fun(NULL)\ntry(pomp:::pomp_fun(36,slotname=\"silly\"))\npomp:::pomp_fun(function(x,y)x+y,proto=quote(bob(x,y)),slotname=\"blarp\")\ntry(pomp:::pomp_fun(function(x)x+y,proto=quote(bob(x,y)),slotname=\"blarp\"))\npomp:::pomp_fun(function(x)x+y,slotname=\"blarp\") -> f\nprint(f)\npomp:::pomp_fun(\"jehosaphat\",PACKAGE=\"harglebarge\",slotname=\"blurp\")\npomp:::pomp_fun(Csnippet(\"x = x;\"),paramnames=\"x\",slotname=\"blork\")\npomp:::pomp_fun(Csnippet(\"x = x;\"),paramnames=\"x\",slotname=\"blork\",Cname=\"yurp\")\npomp:::pomp_fun(Csnippet(\"x = x;\"),paramnames=\"x\",slotname=\"blork\",Cname=\"yurp\",\n  libname=\"splarm\")\npomp:::pomp_fun(f)\n"
  },
  {
    "path": "tests/pomp_fun.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3,keep.source=TRUE)\n> \n> library(pomp)\n> \n> pomp:::pomp_fun()\n<default>\n> pomp:::pomp_fun(NULL)\n<default>\n> try(pomp:::pomp_fun(36,slotname=\"silly\"))\nError : bad option for 'silly' argument.\n> pomp:::pomp_fun(function(x,y)x+y,proto=quote(bob(x,y)),slotname=\"blarp\")\nR function\n  - definition: function(x,y)x+y\n\n> try(pomp:::pomp_fun(function(x)x+y,proto=quote(bob(x,y)),slotname=\"blarp\"))\nError : in 'blarp': 'bob' must be a function of the form 'bob(x, y)'\n> pomp:::pomp_fun(function(x)x+y,slotname=\"blarp\") -> f\n> print(f)\nR function\n  - definition: function(x)x+y\n\n> pomp:::pomp_fun(\"jehosaphat\",PACKAGE=\"harglebarge\",slotname=\"blurp\")\nnative function\n  - name: 'jehosaphat'\n  - dynamically loaded from: 'harglebarge'\n> pomp:::pomp_fun(Csnippet(\"x = x;\"),paramnames=\"x\",slotname=\"blork\")\nnative function\n  - name: \n\n> pomp:::pomp_fun(Csnippet(\"x = x;\"),paramnames=\"x\",slotname=\"blork\",Cname=\"yurp\")\nnative function\n  - name: \n\n> pomp:::pomp_fun(Csnippet(\"x = x;\"),paramnames=\"x\",slotname=\"blork\",Cname=\"yurp\",\n+   libname=\"splarm\")\nnative function\n  - name: 'yurp'\n  - defined by a C snippet in library 'splarm'\n> pomp:::pomp_fun(f)\nR function\n  - definition: function(x)x+y\n\n> \n"
  },
  {
    "path": "tests/pomp_methods.R",
    "content": "library(pomp)\n\ngompertz() -> po\n\nset.seed(530370883)\n\ncoef(po)\ncoef(po,transform=TRUE)\ncoef(po,c(\"r\",\"tau\"))\ntry(coef(po,c(\"bob\",\"tau\")))\ntry(coef(po) <- c(1,2,3))\ntry(coef(po,transform=TRUE) <- c(1,2,3))\ncoef(po) <- list(as.list(coef(po)))\ncoef(po,\"r\") <- 0.2\ncoef(po,\"r\") <- list(r=0.2)\ncoef(po,c(\"r\",\"theta\")) <- list(r=0.2)\ncoef(po,\"sigma\",transform=TRUE) <- 0\ncoef(po)\ncoef(po) <- NULL\nstopifnot(identical(coef(po),numeric(0)))\ncoef(po,c(\"r\",\"sigma\")) <- 1\nstopifnot(all.equal(coef(po),c(r=1,sigma=1)))\ncoef(po) <- NULL\ntry(coef(po,c(\"r\",\"sigma\"),transform=TRUE) <- 0)\ncoef(po) <- NULL\ncoef(po) <- c(r=1,sigma=1)\nstopifnot(all.equal(coef(po),c(r=1,sigma=1)))\ncoef(po) <- NULL\ncoef(po,transform=TRUE) <- c(r=0,sigma=0,K=0,tau=0,X_0=0)\nstopifnot(all.equal(coef(po),c(r=1,sigma=1,K=1,tau=1,X_0=1)))\n\nou2() -> po\npo1 <- simulate(po)\n\nas(po,\"data.frame\") |> head()\nas.data.frame(po1) |> head()\n\nobs(po)[,1:3]\nobs(po,\"y2\")[,1:3]\ntry(obs(po,c(\"y2\",\"z\")))\n\nstates(po)\nstates(po1,\"x1\")[,1:3]\ntry(states(po1,\"z\"))\nstates(po1)[,1:3]\nstates(ricker())[,1:3]\n\ntime(po)[1:3]\ntime(po,t0=TRUE)[1:3]\n\ntime(po) <- 1:10\ntry(time(po) <- c(\"bob\",\"nancy\"))\ntime(po1,t0=TRUE) <- 0:10\ntry(time(po) <- 10:0)\ntry(time(po,t0=TRUE) <- c(4,1:10))\ntime(po1) <- c(1:5,5,5:10)\nstopifnot(obs(po1)[,6:7]==obs(po1)[,5],\n  states(po1)[,6:7]==states(po1)[,5])\n\nwindow(po,end=5)\nwindow(po,start=5)\nwindow(po,start=5,end=10)\ntry(window(po,start=5,end=3))\ntry(window(po,start=NA,end=3))\ntry(window(po,start=1,end=NULL))\n\ntimezero(po)\ntimezero(po) <- -3\ntry(timezero(po) <- NA)\ntry(timezero(po) <- c(1,2,3))\ntry(timezero(po) <- 20)\n\ncoef(po)\ncoef(po,c(\"alpha_3\",\"tau\"))\ntry(coef(po,c(\"alpha_3\",\"z\")))\n\ncoef(po,\"alpha_3\") <- 4\ncoef(po,\"z\") <- 9\ncoef(po)\ncoef(po) <- NULL\ncoef(po)\ncoef(po) <- list(a=3,b=12)\n\ngompertz() -> gompertz\ngompertz -> po\n\npos <- c(po,po,po)\nstopifnot(\n  dim(coef(pos))==c(5,3),\n  length(obs(pos))==3,\n  all(sapply(obs(pos),length)==100),\n  length(states(pos))==3,\n  all(sapply(states(pos),length)==100)\n)\n\ncoef(po)\ncoef(po,transform=TRUE,pars=c(\"r\",\"K\"))\ncoef(po,\"sigma\",transform=TRUE) <- 0\ncoef(po)\ncoef(po,c(\"r\",\"K\",\"sigma\",\"tau\",\"X_0\")) <- c(a=1,b=2,c=3,d=4,e=5)\ncoef(po) <- c(r=1,K=1)\ncoef(po) <- NULL\ntry(coef(po,transform=FALSE) <- c(5,3))\ntry(coef(po,transform=TRUE) <- c(5,3))\ncoef(po)\npo |>\n  window(start=5,end=20) |>\n  pomp(covar=covariate_table(times=0:20,q=0:20),\n    userdata=list(larry=3L)) -> po1\nas(po1,\"data.frame\") |> head()\n\ndim(as.data.frame(c(a=po1,b=po1)))\n"
  },
  {
    "path": "tests/pomp_methods.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> \n> gompertz() -> po\n> \n> set.seed(530370883)\n> \n> coef(po)\n    K     r sigma   tau   X_0 \n  1.0   0.1   0.1   0.1   1.0 \n> coef(po,transform=TRUE)\n        K         r     sigma       tau       X_0 \n 0.000000 -2.302585 -2.302585 -2.302585  0.000000 \n> coef(po,c(\"r\",\"tau\"))\n  r tau \n0.1 0.1 \n> try(coef(po,c(\"bob\",\"tau\")))\nError : in 'coef': name 'bob' corresponds to no parameter.\n> try(coef(po) <- c(1,2,3))\nError : in 'coef<-': 'value' must be a named vector.\n> try(coef(po,transform=TRUE) <- c(1,2,3))\nError : in 'partrans': variable 'r' not found among the parameters.\n> coef(po) <- list(as.list(coef(po)))\n> coef(po,\"r\") <- 0.2\n> coef(po,\"r\") <- list(r=0.2)\nWarning message:\nin 'coef<-': names of 'value' are being discarded. \n> coef(po,c(\"r\",\"theta\")) <- list(r=0.2)\nWarning messages:\n1: in 'coef<-': names of 'value' are being discarded. \n2: in 'coef<-': name 'theta' refers to no existing parameter; it is being concatenated. \n> coef(po,\"sigma\",transform=TRUE) <- 0\n> coef(po)\n    K     r sigma   tau   X_0 theta \n  1.0   0.2   1.0   0.1   1.0   0.2 \n> coef(po) <- NULL\n> stopifnot(identical(coef(po),numeric(0)))\n> coef(po,c(\"r\",\"sigma\")) <- 1\n> stopifnot(all.equal(coef(po),c(r=1,sigma=1)))\n> coef(po) <- NULL\n> try(coef(po,c(\"r\",\"sigma\"),transform=TRUE) <- 0)\nError : in 'partrans': variable 'K' not found among the parameters.\n> coef(po) <- NULL\n> coef(po) <- c(r=1,sigma=1)\n> stopifnot(all.equal(coef(po),c(r=1,sigma=1)))\n> coef(po) <- NULL\n> coef(po,transform=TRUE) <- c(r=0,sigma=0,K=0,tau=0,X_0=0)\n> stopifnot(all.equal(coef(po),c(r=1,sigma=1,K=1,tau=1,X_0=1)))\n> \n> ou2() -> po\n> po1 <- simulate(po)\n> \n> as(po,\"data.frame\") |> head()\n  time        y1        y2         x1        x2\n1    1 -4.051293 4.7806442 -3.7184616  4.249533\n2    2  1.834630 6.2733019  0.9403927  6.843546\n3    3 -1.317003 7.5558688 -0.3725648  7.592267\n4    4  6.640487 5.7299615  5.8085324  6.490249\n5    5  6.575312 1.5614843  5.6054356  1.835443\n6    6  7.540323 0.1756402  7.3546052 -1.566206\n> as.data.frame(po1) |> head()\n  time          y1       y2         x1       x2\n1    1  1.83110320 3.210702  3.0483049 3.974364\n2    2 -0.04753752 5.523446  0.4419551 4.171528\n3    3 -4.98247221 1.617596 -2.5276922 1.783185\n4    4 -3.58397785 4.565235 -2.4003663 3.022412\n5    5  2.39608380 5.300931  1.6061913 5.384364\n6    6 -1.60007417 3.159562 -0.2400938 3.300455\n> \n> obs(po)[,1:3]\n    time\nname      [,1]     [,2]      [,3]\n  y1 -4.051293 1.834630 -1.317003\n  y2  4.780644 6.273302  7.555869\n> obs(po,\"y2\")[,1:3]\n[1] 4.780644 6.273302 7.555869\n> try(obs(po,c(\"y2\",\"z\")))\nError : in 'obs': some elements of 'vars' correspond to no observed variable.\n> \n> states(po)\n    time\nname      [,1]      [,2]       [,3]     [,4]     [,5]      [,6]      [,7]\n  x1 -3.718462 0.9403927 -0.3725648 5.808532 5.605436  7.354605  6.027326\n  x2  4.249533 6.8435458  7.5922673 6.490249 1.835443 -1.566206 -5.769165\n    time\nname      [,8]      [,9]       [,10]     [,11]     [,12]     [,13]     [,14]\n  x1  2.591861  1.564051   0.9793928 -3.769735 -4.465833 -2.609638 -1.571468\n  x2 -8.204354 -8.129966 -10.4613626 -8.241354 -8.319737 -8.341361 -7.866703\n    time\nname     [,15]     [,16]     [,17]       [,18]     [,19]     [,20]     [,21]\n  x1 -1.676192 -6.459881 -9.677313 -12.1463456 -7.161080 -6.548949 -2.168746\n  x2 -8.955705 -6.614633 -2.263629   0.7498668  7.646225 14.144493 17.074303\n    time\nname     [,22]    [,23]     [,24]     [,25]     [,26]     [,27]      [,28]\n  x1  5.819274  9.54269 11.771201 11.118814 10.557558  2.672949  0.1864453\n  x2 19.905790 18.22261  9.578661  4.180379 -3.285832 -5.987268 -7.8591845\n    time\nname     [,29]     [,30]     [,31]     [,32]     [,33]      [,34]      [,35]\n  x1 -2.824932 -4.556638 -6.423103 -7.833862 -3.650647 -2.7021807 -4.1179304\n  x2 -8.408981 -7.208283 -8.994633 -4.552298 -1.658030  0.5031595 -0.3472324\n    time\nname     [,36]     [,37]     [,38]     [,39]    [,40]     [,41]       [,42]\n  x1 -3.548005 -2.252424 0.7992541 0.2633074 2.014700 0.2839356 -0.24930759\n  x2  1.613964  1.965179 2.2202156 5.0421617 0.823271 0.7792341 -0.05037456\n    time\nname     [,43]     [,44]    [,45]    [,46]    [,47]    [,48]    [,49]     [,50]\n  x1 -3.047634 -2.295912 2.175010 4.161905 4.338019 2.102369 1.878480 0.9165691\n  x2  4.293642  7.854921 9.350568 8.817059 7.507315 5.879635 2.446674 4.1226197\n    time\nname      [,51]     [,52]     [,53]      [,54]      [,55]      [,56]      [,57]\n  x1 3.95790848  2.815407  1.146323  0.8955099 -0.6876014  0.7267551 -0.1082068\n  x2 0.02479867 -3.399517 -7.570888 -5.0939677 -3.0098935 -4.0507391 -6.0031982\n    time\nname      [,58]     [,59]     [,60]     [,61]     [,62]      [,63]    [,64]\n  x1  0.2069616 -8.333998 -9.503259 -6.708169 -5.185757 -0.4473262 6.091655\n  x2 -6.3700829 -6.325354 -1.396653  1.226086  4.604219  7.0241444 1.939488\n    time\nname       [,65]     [,66]     [,67]     [,68]      [,69]     [,70]     [,71]\n  x1  7.38875983  7.033866  4.613739  2.480244 -0.1542312 -1.505933 -5.338838\n  x2 -0.01318833 -1.428150 -5.515425 -6.767179 -4.3387467 -5.995982 -5.549160\n    time\nname      [,72]     [,73]     [,74]     [,75]     [,76]    [,77]     [,78]\n  x1 -10.109899 -5.693187 -5.309844 -10.28625  2.228661 9.618410 9.3340634\n  x2  -1.713551  1.398188  5.629586  10.19314 11.181627 8.083588 0.2761495\n    time\nname     [,79]     [,80]     [,81]     [,82]      [,83]      [,84]     [,85]\n  x1  3.318304  5.927537  4.686989  1.824861 -0.4577823 -3.3841796 -4.883498\n  x2 -3.158758 -2.998267 -3.616432 -2.695511 -1.9417755  0.4407706  4.278637\n    time\nname     [,86]     [,87]     [,88]     [,89]     [,90]     [,91]    [,92]\n  x1 -4.324573 -8.957549 -5.523806 -2.901289  5.836531  9.610322 12.89082\n  x2  5.643270 10.894346 14.748086 16.443004 20.429526 18.607595 12.76983\n    time\nname     [,93]     [,94]      [,95]       [,96]      [,97]     [,98]     [,99]\n  x1 13.789569  9.124335   9.574495  -0.7486587  -2.105521 -7.631643 -3.725199\n  x2  3.645828 -4.273479 -11.626880 -11.5756615 -13.330174 -8.523203 -2.712183\n    time\nname     [,100]\n  x1 -3.8740390\n  x2 -0.1375925\n> states(po1,\"x1\")[,1:3]\n[1]  3.0483049  0.4419551 -2.5276922\n> try(states(po1,\"z\"))\nError : in 'states': some elements of 'vars' correspond to no state variable\n> states(po1)[,1:3]\n    time\nname     [,1]      [,2]      [,3]\n  x1 3.048305 0.4419551 -2.527692\n  x2 3.974364 4.1715284  1.783185\n> states(ricker())[,1:3]\n      time\nname   [,1] [,2] [,3]\n> \n> time(po)[1:3]\n[1] 1 2 3\n> time(po,t0=TRUE)[1:3]\n[1] 0 1 2\n> \n> time(po) <- 1:10\n> try(time(po) <- c(\"bob\",\"nancy\"))\nError : in 'time<-':  times must be numeric and finite.\n> time(po1,t0=TRUE) <- 0:10\n> try(time(po) <- 10:0)\nError : in 'time<-': times must be a non-decreasing numeric sequence.\n> try(time(po,t0=TRUE) <- c(4,1:10))\nError : in 'time<-': the zero-time 't0' must occur no later than the first observation.\n> time(po1) <- c(1:5,5,5:10)\n> stopifnot(obs(po1)[,6:7]==obs(po1)[,5],\n+   states(po1)[,6:7]==states(po1)[,5])\n> \n> window(po,end=5)\n<object of class 'pomp'>\n> window(po,start=5)\n<object of class 'pomp'>\n> window(po,start=5,end=10)\n<object of class 'pomp'>\n> try(window(po,start=5,end=3))\nError : in 'window': 'start' must not be later than 'end'.\n> try(window(po,start=NA,end=3))\nError : in 'window': 'start' and 'end' must be finite times.\n> try(window(po,start=1,end=NULL))\nError : in 'window': 'start' and 'end' must be finite times.\n> \n> timezero(po)\n[1] 0\n> timezero(po) <- -3\n> try(timezero(po) <- NA)\nError : in 'timezero<-': the zero-time 't0' must be a single finite number.\n> try(timezero(po) <- c(1,2,3))\nError : in 'timezero<-': the zero-time 't0' must be a single finite number.\n> try(timezero(po) <- 20)\nError : in 'timezero<-': the zero-time 't0' must occur no later than the first observation.\n> \n> coef(po)\nalpha_1 alpha_2 alpha_3 alpha_4 sigma_1 sigma_2 sigma_3     tau    x1_0    x2_0 \n    0.8    -0.5     0.3     0.9     3.0    -0.5     2.0     1.0    -3.0     4.0 \n> coef(po,c(\"alpha_3\",\"tau\"))\nalpha_3     tau \n    0.3     1.0 \n> try(coef(po,c(\"alpha_3\",\"z\")))\nError : in 'coef': name 'z' corresponds to no parameter.\n> \n> coef(po,\"alpha_3\") <- 4\n> coef(po,\"z\") <- 9\nWarning message:\nin 'coef<-': name 'z' refers to no existing parameter; it is being concatenated. \n> coef(po)\nalpha_1 alpha_2 alpha_3 alpha_4 sigma_1 sigma_2 sigma_3     tau    x1_0    x2_0 \n    0.8    -0.5     4.0     0.9     3.0    -0.5     2.0     1.0    -3.0     4.0 \n      z \n    9.0 \n> coef(po) <- NULL\n> coef(po)\nnumeric(0)\n> coef(po) <- list(a=3,b=12)\n> \n> gompertz() -> gompertz\n> gompertz -> po\n> \n> pos <- c(po,po,po)\n> stopifnot(\n+   dim(coef(pos))==c(5,3),\n+   length(obs(pos))==3,\n+   all(sapply(obs(pos),length)==100),\n+   length(states(pos))==3,\n+   all(sapply(states(pos),length)==100)\n+ )\n> \n> coef(po)\n    K     r sigma   tau   X_0 \n  1.0   0.1   0.1   0.1   1.0 \n> coef(po,transform=TRUE,pars=c(\"r\",\"K\"))\n        r         K \n-2.302585  0.000000 \n> coef(po,\"sigma\",transform=TRUE) <- 0\n> coef(po)\n    K     r sigma   tau   X_0 \n  1.0   0.1   1.0   0.1   1.0 \n> coef(po,c(\"r\",\"K\",\"sigma\",\"tau\",\"X_0\")) <- c(a=1,b=2,c=3,d=4,e=5)\nWarning message:\nin 'coef<-': names of 'value' are being discarded. \n> coef(po) <- c(r=1,K=1)\n> coef(po) <- NULL\n> try(coef(po,transform=FALSE) <- c(5,3))\nError : in 'coef<-': 'value' must be a named vector.\n> try(coef(po,transform=TRUE) <- c(5,3))\nError : in 'partrans': variable 'r' not found among the parameters.\n> coef(po)\nnumeric(0)\n> po |>\n+   window(start=5,end=20) |>\n+   pomp(covar=covariate_table(times=0:20,q=0:20),\n+     userdata=list(larry=3L)) -> po1\n> as(po1,\"data.frame\") |> head()\n  time         Y  q\n1    5 0.7408867  5\n2    6 1.0457807  6\n3    7 1.1067887  7\n4    8 1.0408258  8\n5    9 1.1051387  9\n6   10 1.3038009 10\n> \n> dim(as.data.frame(c(a=po1,b=po1)))\n[1] 32  4\n> \n"
  },
  {
    "path": "tests/prior.R",
    "content": "options(digits=3)\n\nlibrary(pomp)\nsuppressPackageStartupMessages({\n  library(dplyr)\n})\n\nou2() -> po\n\nstopifnot(\n  po |> rprior() == coef(po)\n)\n\ncoef(po,\"alpha_sd\") <- 5\n\nset.seed(1835425749L)\n\npo |>\n  pomp(\n    dprior=function(alpha_1,alpha_2,alpha_3,alpha_4,alpha_sd,...,log) {\n      ll <- sum(\n        dnorm(\n          x=c(alpha_1,alpha_2,alpha_3,alpha_4),\n          mean=c(0.8,-0.5,0.3,0.9),\n          sd=alpha_sd,\n          log=TRUE\n        )\n      )\n      if (log) ll else exp(ll)\n    },\n    rprior=function(alpha_1,alpha_2,alpha_3,alpha_4,alpha_sd,...) {\n      c(\n        alpha_1=rnorm(n=1,mean=0.8,sd=alpha_sd),\n        alpha_2=rnorm(n=1,mean=-0.5,sd=alpha_sd),\n        alpha_3=rnorm(n=1,mean=0.3,sd=alpha_sd),\n        alpha_4=rnorm(n=1,mean=0.9,sd=alpha_sd)\n      )\n    }\n  ) -> po\n\nstopifnot(\n  po |> dprior(params=coef(po),log=TRUE) == 4*dnorm(x=0,mean=0,sd=5,log=TRUE),\n  all.equal(po |> dprior(params=coef(po)),dnorm(x=0,mean=0,sd=5)^4)\n)\n\nreplicate(5,rprior(po,params=coef(po))) |> parmat() -> theta\nstopifnot(round(dprior(po,params=theta,log=TRUE),3) ==\n            c(-12.237, -10.848, -15.806, -10.847, -11.526))\n\ntry(dprior(\"ou2\",params=theta))\ntry(dprior(params=theta))\n\ntry(rprior(\"ou2\",params=theta))\ntry(rprior(params=theta))\n\ntry(po |> pomp(rprior=function(...)c(1,3,3)) |> rprior(params=theta))\npo |> rprior(params=parmat(theta,3)) -> p\nstopifnot(\n  dim(p)==c(11,15),\n  names(dimnames(p))==c(\"name\",\".id\"),\n  rownames(p)==names(coef(po))\n)\n\nfreeze(\n  mean(dprior(po,params=replicate(n=10000,rprior(po)),log=TRUE)),\n  seed=1865498175\n) -> L\nstopifnot(round(L,1)==-12.1)\n"
  },
  {
    "path": "tests/prior.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> \n> library(pomp)\n> suppressPackageStartupMessages({\n+   library(dplyr)\n+ })\n> \n> ou2() -> po\n> \n> stopifnot(\n+   po |> rprior() == coef(po)\n+ )\nWarning message:\n'rprior' unspecified: duplicating parameters. \n> \n> coef(po,\"alpha_sd\") <- 5\nWarning message:\nin 'coef<-': name 'alpha_sd' refers to no existing parameter; it is being concatenated. \n> \n> set.seed(1835425749L)\n> \n> po |>\n+   pomp(\n+     dprior=function(alpha_1,alpha_2,alpha_3,alpha_4,alpha_sd,...,log) {\n+       ll <- sum(\n+         dnorm(\n+           x=c(alpha_1,alpha_2,alpha_3,alpha_4),\n+           mean=c(0.8,-0.5,0.3,0.9),\n+           sd=alpha_sd,\n+           log=TRUE\n+         )\n+       )\n+       if (log) ll else exp(ll)\n+     },\n+     rprior=function(alpha_1,alpha_2,alpha_3,alpha_4,alpha_sd,...) {\n+       c(\n+         alpha_1=rnorm(n=1,mean=0.8,sd=alpha_sd),\n+         alpha_2=rnorm(n=1,mean=-0.5,sd=alpha_sd),\n+         alpha_3=rnorm(n=1,mean=0.3,sd=alpha_sd),\n+         alpha_4=rnorm(n=1,mean=0.9,sd=alpha_sd)\n+       )\n+     }\n+   ) -> po\n> \n> stopifnot(\n+   po |> dprior(params=coef(po),log=TRUE) == 4*dnorm(x=0,mean=0,sd=5,log=TRUE),\n+   all.equal(po |> dprior(params=coef(po)),dnorm(x=0,mean=0,sd=5)^4)\n+ )\n> \n> replicate(5,rprior(po,params=coef(po))) |> parmat() -> theta\n> stopifnot(round(dprior(po,params=theta,log=TRUE),3) ==\n+             c(-12.237, -10.848, -15.806, -10.847, -11.526))\n> \n> try(dprior(\"ou2\",params=theta))\nError : 'dprior' is undefined for 'object' of class 'character'.\n> try(dprior(params=theta))\nError : in 'dprior': 'object' is a required argument.\n> \n> try(rprior(\"ou2\",params=theta))\nError : 'rprior' is undefined for 'object' of class 'character'.\n> try(rprior(params=theta))\nError : in 'rprior': 'object' is a required argument.\n> \n> try(po |> pomp(rprior=function(...)c(1,3,3)) |> rprior(params=theta))\nError : in 'rprior': 'rprior' must return a named numeric vector.\n> po |> rprior(params=parmat(theta,3)) -> p\n> stopifnot(\n+   dim(p)==c(11,15),\n+   names(dimnames(p))==c(\"name\",\".id\"),\n+   rownames(p)==names(coef(po))\n+ )\n> \n> freeze(\n+   mean(dprior(po,params=replicate(n=10000,rprior(po)),log=TRUE)),\n+   seed=1865498175\n+ ) -> L\n> stopifnot(round(L,1)==-12.1)\n> \n"
  },
  {
    "path": "tests/probe.R",
    "content": "options(digits=3)\npng(filename=\"probe-%02d.png\",res=100)\n\nlibrary(pomp)\n\ngompertz() -> gompertz\n\nset.seed(234501470L)\n\npo <- gompertz\n\nplist <- list(\n  mean=probe_mean(\"Y\",trim=0.1,transform=sqrt),\n  sd=probe_sd(\"Y\",transform=sqrt),\n  probe_marginal(\"Y\",ref=obs(po)),\n  probe_acf(\"Y\",lags=c(1,3,5),type=\"correlation\",transform=sqrt),\n  probe_quantile(\"Y\",prob=c(0.25,0.75))\n)\n\nprobe(po,probes=plist,nsim=500,seed=595969) -> pb\nplot(pb,y=NULL)\npb |> as.data.frame() |> head(3) |> knitr::kable()\nsummary(pb)\n\ntry(probe())\ntry(probe(\"po\"))\ntry(probe(NULL))\ntry(probe(po,nsim=10))\ntry(probe(po,probes=plist[1:3]))\ntry(probe(po,probes=plist[1:3],nsim=-100))\ntry(probe(po,probes=plist[1:3],nsim=c(10,20)))\ntry(probe(po,probes=plist[1:3],nsim=NA))\ntry(probe(po,nsim=100,probes=function(x)rep(1,times=ceiling(runif(1,max=10)))))\n\ntry(probe(33L))\nprobe(pb)\nplot(probe(pb,probes=plist[[1]]))\ntry(probe(pb,probes=\"okay\"))\ntry(probe(pb,probes=function(x,y)x+y))\ntry(probe(pb,probes=function(x)stop(\"hold on now!\")))\ntry(probe(pb,probes=function(x)\"bob\"))\ntry({\n  count <- 0\n  delayed.error <- function (y) {\n    count <<- count+1\n    if (count>5) stop(\"whoa nelly!\")\n    y[1]\n  }\n  probe(pb,probes=delayed.error)\n})\ntry({\n  count <- 0\n  delayed.badval <- function (y) {\n    count <<- count+1\n    if (count>10) \"bob\" else 10\n  }\n  probe(pb,probes=delayed.badval)\n})\ntry({\n  count <- 0\n  delayed.badval <- function (y) {\n    count <<- count+1\n    if (count>10) rep(3.5,count) else 3.5\n  }\n  probe(pb,probes=delayed.badval)\n})\n\ntry(probe(pb,nsim=10))\n\nprobe(pb,params=as.list(coef(pb)))\ntry(probe(pb,params=NULL))\ntry(probe(pb,params=\"I think so\"))\ntry({pb1 <- pb; coef(pb1) <- NULL; probe(pb1)})\n\npo |> probe(nsim=100,probes=function(x)1) |> logLik()\n\ntry(data.frame(t=1:10,a=1:10) |> probe())\n\ndata.frame(t=1:10,a=1:10) |>\n  probe(\n    times=\"t\",t0=0,\n    rprocess=euler(\n      function(t,x,delta.t,...){\n        c(x=rlnorm(n=1,meanlog=log(x),sd=sqrt(delta.t)))\n      },delta.t=0.1),\n    rmeasure=function(t,x,...){\n      c(a=rpois(n=1,lambda=x))\n    },\n    nsim=1000,\n    params=c(x_0=1),\n    probes=list(\n      f=probe_mean(\"a\",transform=sqrt),\n      g=probe_median(\"a\"),\n      h=function(y)range(y)\n    )\n  )\n\nou2() -> ou2\nou2 |> probe(nsim=100,probes=probe_ccf(c(\"y1\",\"y2\"),lags=c(-10,0,1))) |> plot()\n\ndev.off()\n"
  },
  {
    "path": "tests/probe.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"probe-%02d.png\",res=100)\n> \n> library(pomp)\n> \n> gompertz() -> gompertz\n> \n> set.seed(234501470L)\n> \n> po <- gompertz\n> \n> plist <- list(\n+   mean=probe_mean(\"Y\",trim=0.1,transform=sqrt),\n+   sd=probe_sd(\"Y\",transform=sqrt),\n+   probe_marginal(\"Y\",ref=obs(po)),\n+   probe_acf(\"Y\",lags=c(1,3,5),type=\"correlation\",transform=sqrt),\n+   probe_quantile(\"Y\",prob=c(0.25,0.75))\n+ )\n> \n> probe(po,probes=plist,nsim=500,seed=595969) -> pb\n> plot(pb,y=NULL)\n> pb |> as.data.frame() |> head(3) |> knitr::kable()\n\n\n|   |  mean|    sd| marg.1| marg.2| marg.3| acf[1]| acf[3]| acf[5]|   25%|  75%|.id  |\n|:--|-----:|-----:|------:|------:|------:|------:|------:|------:|-----:|----:|:----|\n|0  | 1.056| 0.126|  1.000|  0.000|  0.000|  0.742|  0.586|  0.515| 0.943| 1.32|data |\n|1  | 0.978| 0.127|  0.757|  0.126|  0.537|  0.814|  0.633|  0.496| 0.800| 1.12|sim  |\n|2  | 1.014| 0.105|  0.668|  0.074|  3.124|  0.640|  0.455|  0.279| 0.885| 1.21|sim  |\n> summary(pb)\n$coef\n    K     r sigma   tau   X_0 \n  1.0   0.1   0.1   0.1   1.0 \n\n$nsim\n[1] 500\n\n$quantiles\n  mean     sd marg.1 marg.2 marg.3 acf[1] acf[3] acf[5]    25%    75% \n 0.840  0.718  0.946  0.446  0.038  0.664  0.670  0.814  0.826  0.874 \n\n$pvals\n  mean     sd marg.1 marg.2 marg.3 acf[1] acf[3] acf[5]    25%    75% \n0.3234 0.5669 0.1118 0.8942 0.0798 0.6747 0.6627 0.3752 0.3513 0.2555 \n\n$synth.loglik\n[1] 15.4\n\n> \n> try(probe())\nError : in 'probe': 'data' is a required argument.\n> try(probe(\"po\"))\nError : 'probe' is undefined for 'data' of class 'character'.\n> try(probe(NULL))\nError : 'probe' is undefined for 'data' of class 'NULL'.\n> try(probe(po,nsim=10))\nError : in 'probe': 'probes' must be furnished.\n> try(probe(po,probes=plist[1:3]))\nError : in 'probe': 'nsim' must be specified.\n> try(probe(po,probes=plist[1:3],nsim=-100))\nError : in 'probe': number of simulations, 'nsim', must be a single positive integer.\n> try(probe(po,probes=plist[1:3],nsim=c(10,20)))\nError : in 'probe': number of simulations, 'nsim', must be a single positive integer.\n> try(probe(po,probes=plist[1:3],nsim=NA))\nError : in 'probe': number of simulations, 'nsim', must be a single positive integer.\n> try(probe(po,nsim=100,probes=function(x)rep(1,times=ceiling(runif(1,max=10)))))\nError : in 'probe': applying probes to simulated data: probes return different number of values on different datasets.\n> \n> try(probe(33L))\nError : 'probe' is undefined for 'data' of class 'integer'.\n> probe(pb)\n<object of class 'probed_pomp'>\n> plot(probe(pb,probes=plist[[1]]))\n> try(probe(pb,probes=\"okay\"))\nError : in 'probe': 'probes' must be a function or a list of functions.\n> try(probe(pb,probes=function(x,y)x+y))\nError : in 'probe': each probe must be a function of a single argument.\n> try(probe(pb,probes=function(x)stop(\"hold on now!\")))\nError : in 'probe': applying probes to actual data: hold on now!\n> try(probe(pb,probes=function(x)\"bob\"))\nError : in 'probe': applying probes to actual data: probe 1 returns a non-numeric result\n> try({\n+   count <- 0\n+   delayed.error <- function (y) {\n+     count <<- count+1\n+     if (count>5) stop(\"whoa nelly!\")\n+     y[1]\n+   }\n+   probe(pb,probes=delayed.error)\n+ })\nError : in 'probe': applying probes to simulated data: whoa nelly!\n> try({\n+   count <- 0\n+   delayed.badval <- function (y) {\n+     count <<- count+1\n+     if (count>10) \"bob\" else 10\n+   }\n+   probe(pb,probes=delayed.badval)\n+ })\nError : in 'probe': applying probes to simulated data: probe 1 returns a non-numeric result.\n> try({\n+   count <- 0\n+   delayed.badval <- function (y) {\n+     count <<- count+1\n+     if (count>10) rep(3.5,count) else 3.5\n+   }\n+   probe(pb,probes=delayed.badval)\n+ })\nError : in 'probe': applying probes to simulated data: variable-sized results returned by probe 1.\n> \n> try(probe(pb,nsim=10))\nError : in 'probe': 'nsim' (=10), should be (much) larger than the number of probes (=10).\n> \n> probe(pb,params=as.list(coef(pb)))\n<object of class 'probed_pomp'>\n> try(probe(pb,params=NULL))\nError : in 'probe': applying probes to simulated data: variable 'X' not found among the state variables.\nIn addition: Warning message:\nin default 'rinit': there are no parameters with suffix '.0' or '_0'. See '?rinit_spec'. \n> try(probe(pb,params=\"I think so\"))\nError : in 'probe': 'params' must be a named numeric vector.\nIn addition: Warning message:\nNAs introduced by coercion \n> try({pb1 <- pb; coef(pb1) <- NULL; probe(pb1)})\nError : in 'probe': applying probes to simulated data: variable 'X' not found among the state variables.\nIn addition: Warning message:\nin default 'rinit': there are no parameters with suffix '.0' or '_0'. See '?rinit_spec'. \n> \n> po |> probe(nsim=100,probes=function(x)1) |> logLik()\n[1] NaN\n> \n> try(data.frame(t=1:10,a=1:10) |> probe())\nError : in 'probe': 'times' should either be a numeric vector of observation times or a single name identifying the column of data that represents the observation times.\n> \n> data.frame(t=1:10,a=1:10) |>\n+   probe(\n+     times=\"t\",t0=0,\n+     rprocess=euler(\n+       function(t,x,delta.t,...){\n+         c(x=rlnorm(n=1,meanlog=log(x),sd=sqrt(delta.t)))\n+       },delta.t=0.1),\n+     rmeasure=function(t,x,...){\n+       c(a=rpois(n=1,lambda=x))\n+     },\n+     nsim=1000,\n+     params=c(x_0=1),\n+     probes=list(\n+       f=probe_mean(\"a\",transform=sqrt),\n+       g=probe_median(\"a\"),\n+       h=function(y)range(y)\n+     )\n+   )\n<object of class 'probed_pomp'>\n> \n> ou2() -> ou2\n> ou2 |> probe(nsim=100,probes=probe_ccf(c(\"y1\",\"y2\"),lags=c(-10,0,1))) |> plot()\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/probe_match.R",
    "content": "options(digits=3)\npng(filename=\"probe_match-%02d.png\",res=100)\n\nlibrary(pomp)\n\ngompertz() -> po\npo |> as.data.frame() |> subset(select=-X) -> dat\n\nplist <- list(\n  mean=probe_mean(\"Y\",trim=0.1,transform=sqrt),\n  sd=probe_sd(\"Y\",transform=sqrt),\n  probe_marginal(\"Y\",ref=obs(po)),\n  probe_acf(\"Y\",lags=c(1,3,5),type=\"correlation\",transform=sqrt),\n  probe_quantile(\"Y\",prob=c(0.25,0.75),na.rm=TRUE)\n)\n\ntry(dat |> probe_objfun())\ntry(dat |> probe_objfun(times=\"time\",t0=0))\n\ndat |>\n  probe_objfun(\n    times=\"time\",t0=0,\n    rinit=po@rinit,\n    rprocess=po@rprocess,\n    rmeasure=po@rmeasure,\n    probes=plist,\n    params=coef(po),\n    nsim=100,\n    seed=5069977\n  ) -> f\n\nplot(f)\n\ntry(as(f,\"pomp\") <- po)\n\nf()\nstopifnot(f(0)==f(1))\nstopifnot(logLik(f)==-f(0))\n\nf |> probe_objfun(est=c(\"K\"),seed=580656309) -> f1\nplot(sapply(seq(0.8,1.6,by=0.1),f1))\n\nf1(1.1)\nlibrary(subplex)\nsubplex(fn=f1,par=0.4,control=list(reltol=1e-3)) -> out\nf1(out$par)\n\ntry(probe_objfun())\ntry(probe_objfun(\"bob\"))\n\ntry(probe_objfun(f,est=\"harry\"))\n\nf1 |> as(\"probed_pomp\") |> plot()\n\nf1 |> summary() |> names()\n\nf1 |> plot()\n\npompLoad(f1)\nf1 |> probe() |> plot()\npompUnload(f1)\n\nf1 |> as_pomp() |> as.data.frame() |> names()\n\nf1 |> probe_objfun(fail.value=1e10) -> f2\n\nf1 |> spect(kernel.width=3,nsim=100,seed=748682047) |> plot()\n\nf1 |> as(\"pomp\")\nf1 |> as(\"data.frame\") |> names()\n\npo |> probe_objfun(nsim=100,probes=function(x)1,fail.value=1e9) -> f2\nlogLik(f2)\nf2(1)\n\nricker() |>\n  probe_objfun(\n    nsim=1000,\n    probes=list(\n      mean=probe_mean(\"y\",trim=0.1,transform=sqrt),\n      sd=probe_sd(\"y\",transform=sqrt),\n      probe_quantile(\"y\",prob=c(0.25,0.75),na.rm=TRUE)\n    ),\n    seed=501991903\n  ) -> f\n\npompUnload(f)\n## f() # would result in segfault\npompLoad(f)\n## stopifnot(all.equal(round(f(),3),2.724))\nprint(f())\n\ndev.off()\n"
  },
  {
    "path": "tests/probe_match.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"probe_match-%02d.png\",res=100)\n> \n> library(pomp)\n> \n> gompertz() -> po\n> po |> as.data.frame() |> subset(select=-X) -> dat\n> \n> plist <- list(\n+   mean=probe_mean(\"Y\",trim=0.1,transform=sqrt),\n+   sd=probe_sd(\"Y\",transform=sqrt),\n+   probe_marginal(\"Y\",ref=obs(po)),\n+   probe_acf(\"Y\",lags=c(1,3,5),type=\"correlation\",transform=sqrt),\n+   probe_quantile(\"Y\",prob=c(0.25,0.75),na.rm=TRUE)\n+ )\n> \n> try(dat |> probe_objfun())\nError : in 'probe_objfun': in 'probe': 'times' should either be a numeric vector of observation times or a single name identifying the column of data that represents the observation times.\n> try(dat |> probe_objfun(times=\"time\",t0=0))\nError : in 'probe_objfun': in 'probe': 'rprocess', 'rmeasure' are needed basic components.\n> \n> dat |>\n+   probe_objfun(\n+     times=\"time\",t0=0,\n+     rinit=po@rinit,\n+     rprocess=po@rprocess,\n+     rmeasure=po@rmeasure,\n+     probes=plist,\n+     params=coef(po),\n+     nsim=100,\n+     seed=5069977\n+   ) -> f\n> \n> plot(f)\n> \n> try(as(f,\"pomp\") <- po)\nError : in 'as<-': cannot replace the pomp object in a stateful objective function.\n> \n> f()\n[1] -15.1\n> stopifnot(f(0)==f(1))\n> stopifnot(logLik(f)==-f(0))\n> \n> f |> probe_objfun(est=c(\"K\"),seed=580656309) -> f1\n> plot(sapply(seq(0.8,1.6,by=0.1),f1))\n> \n> f1(1.1)\n[1] -16.4\n> library(subplex)\n> subplex(fn=f1,par=0.4,control=list(reltol=1e-3)) -> out\n> f1(out$par)\n[1] -16.5\n> \n> try(probe_objfun())\nError : in 'probe_objfun': 'data' is a required argument.\n> try(probe_objfun(\"bob\"))\nError : 'probe_objfun' is undefined for 'data' of class 'character'.\n> \n> try(probe_objfun(f,est=\"harry\"))\nError : in 'probe_objfun': parameter 'harry' not found in 'params'.\n> \n> f1 |> as(\"probed_pomp\") |> plot()\n> \n> f1 |> summary() |> names()\n[1] \"coef\"         \"nsim\"         \"quantiles\"    \"pvals\"        \"synth.loglik\"\n> \n> f1 |> plot()\n> \n> pompLoad(f1)\n> f1 |> probe() |> plot()\n> pompUnload(f1)\n> \n> f1 |> as_pomp() |> as.data.frame() |> names()\n[1] \"time\" \"Y\"   \n> \n> f1 |> probe_objfun(fail.value=1e10) -> f2\n> \n> f1 |> spect(kernel.width=3,nsim=100,seed=748682047) |> plot()\n> \n> f1 |> as(\"pomp\")\n<object of class 'pomp'>\n> f1 |> as(\"data.frame\") |> names()\n[1] \"time\" \"Y\"   \n> \n> po |> probe_objfun(nsim=100,probes=function(x)1,fail.value=1e9) -> f2\n> logLik(f2)\n[1] NaN\n> f2(1)\n[1] 1e+09\n> \n> ricker() |>\n+   probe_objfun(\n+     nsim=1000,\n+     probes=list(\n+       mean=probe_mean(\"y\",trim=0.1,transform=sqrt),\n+       sd=probe_sd(\"y\",transform=sqrt),\n+       probe_quantile(\"y\",prob=c(0.25,0.75),na.rm=TRUE)\n+     ),\n+     seed=501991903\n+   ) -> f\n> \n> pompUnload(f)\n> ## f() # would result in segfault\n> pompLoad(f)\n> ## stopifnot(all.equal(round(f(),3),2.724))\n> print(f())\n[1] 2.72\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/process.R",
    "content": "options(digits=3)\n\nlibrary(pomp)\n\nou2() |> window(end=10) -> po\n\nset.seed(293982095)\n\npo |>\n  simulate(format=\"arrays\",nsim=3,seed=3434388L) |>\n  getElement(\"states\") -> x\npo |> time() -> t\ncoef(po) |> parmat(7) -> p\np[\"sigma_1\",] <- seq(from=1,to=7,by=1)\n\ntry(dprocess(\"ou2\",x=x,times=t,params=p))\ntry(dprocess(x=x,times=t,params=p))\ntry(po |> dprocess(x=x,times=t,params=p,log=TRUE))\ntry(po |> dprocess(x=x,times=t,params=p[,1:2],log=TRUE))\ntry(po |> dprocess(x=x,times=t[1:5],params=p,log=TRUE))\npo |> dprocess(x=x,times=t,params=p[,1:3],log=TRUE) -> d1\npo |> dprocess(x=x,times=t,params=p[,2],log=TRUE) -> d2\nstopifnot(d1[2,]==d2[2,])\ntry(po |> dprocess(x=x[,,2],times=t[2],params=p[,1:3],log=FALSE))\ntry(po |> dprocess(x=x[,,2:5],times=t[2:5],params=p[,1:2],log=FALSE))\npo |> dprocess(x=x[,,2:5],times=t[2:5],params=p[,1:3],log=TRUE) |>\n  apply(1,sum)\ntry(po |> dprocess(x=x[,1:2,2:5],times=t[2:5],params=p[,1:3],log=TRUE) |>\n      apply(1,sum))\npo |> dprocess(x=x[,1,2:5],times=t[2:5],params=p[,1:3],log=TRUE) |>\n  apply(1,sum)\npo |> pomp(dprocess=NULL) |>\n  dprocess(x=x[,1,2:5],times=t[2:5],params=p[,1:3],log=TRUE) |> is.na() |>\n  stopifnot()\n\npo |> rinit(params=coef(po)) -> x0\nfreeze(\n  po |>\n    rprocess(\n      params=coef(po),\n      x0=parmat(x0,3),\n      t0=timezero(po),\n      times=time(po)\n    ),\n  seed=3434388L\n) -> x1\n\nstopifnot(max(abs(x-x1))==0)\n\npo |> rinit(nsim=6) -> x0\ntry(rprocess(\"ou2\",x0=x0,t0=t[1],times=t,params=p))\ntry(rprocess(x0=x0,t0=t[1],times=t,params=p))\nfreeze(po |> rprocess(times=t,params=p),seed=995484) -> x1\ntry(po |> rprocess(x0=x0,params=p))\ntry(po |> rprocess(x0=x0,t0=t[1],params=p))\nfreeze(po |> rprocess(x0=x0,times=t),seed=995484) -> x2\ntry(po |> rprocess(x0=x0,times=t,params=p))\ntry(po |> rprocess(x0=x0,t0=t[1],times=t,params=p))\npo |> rprocess(x0=x0,t0=t[1],times=t,params=p[,1:3]) -> x\nstopifnot(\n  dim(x)==c(2,6,10),\n  names(dimnames(x))==c(\"name\",\".id\",\"time\")\n)\npo |> rprocess(x0=x0[,2],t0=t[1],times=t,params=p[,1:3]) -> x\nstopifnot(\n  dim(x)==c(2,3,10),\n  names(dimnames(x))==c(\"name\",\".id\",\"time\")\n)\n\ntry(po |> rprocess(x0=x0,t0=t[1],times=numeric(0),params=p))\ntry(po |> rprocess(x0=x0[,2],t0=t[2],times=t[1],params=p[,1:3]))\ntry(po |> rprocess(x0=x0[,2:4],t0=t[2],times=t[2:5],params=p[,1:2]))\npo |> rprocess(x0=x0[,2:4],t0=t[2],times=t[2:5],params=p[,1:3]) |>\n  apply(1,sum)\n\nsimulate(\n  times=seq(0,10), t0=0,\n  params=c(s=3,x_0=0,tau=1),\n  covar=covariate_table(z=c(1,1),times=c(0,10)),\n  rprocess = onestep(\n    function (t, x, s, delta.t, ...) {\n      c(x=rnorm(n=1,mean=x,sd=s*sqrt(delta.t)))\n    }\n  ),\n  dprocess = function (x_1, x_2, s, t_1, t_2, ...) {\n    delta.t <- t_2-t_1\n    dnorm(x=x_2,mean=x_1,sd=s*sqrt(delta.t),log=TRUE)\n  },\n  seed=3434388L\n) -> rw\n\ndprocess(rw,x=states(rw),params=coef(rw),times=time(rw),log=TRUE) -> d\nstopifnot(\n  round(sum(d),1)==-23.2,\n  dim(d)==c(1,10),\n  names(dimnames(d))==c(\".id\",\"time\")\n)\n"
  },
  {
    "path": "tests/process.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> \n> library(pomp)\n> \n> ou2() |> window(end=10) -> po\n> \n> set.seed(293982095)\n> \n> po |>\n+   simulate(format=\"arrays\",nsim=3,seed=3434388L) |>\n+   getElement(\"states\") -> x\n> po |> time() -> t\n> coef(po) |> parmat(7) -> p\n> p[\"sigma_1\",] <- seq(from=1,to=7,by=1)\n> \n> try(dprocess(\"ou2\",x=x,times=t,params=p))\nError : 'dprocess' is undefined for 'object' of class 'character'.\n> try(dprocess(x=x,times=t,params=p))\nError : in 'dprocess': 'object' is a required argument.\n> try(po |> dprocess(x=x,times=t,params=p,log=TRUE))\nError : in 'dprocess': the larger number of replicates is not a multiple of smaller.\n> try(po |> dprocess(x=x,times=t,params=p[,1:2],log=TRUE))\nError : in 'dprocess': the larger number of replicates is not a multiple of smaller.\n> try(po |> dprocess(x=x,times=t[1:5],params=p,log=TRUE))\nError : in 'dprocess': the length of 'times' and 3rd dimension of 'x' do not agree.\n> po |> dprocess(x=x,times=t,params=p[,1:3],log=TRUE) -> d1\n> po |> dprocess(x=x,times=t,params=p[,2],log=TRUE) -> d2\n> stopifnot(d1[2,]==d2[2,])\n> try(po |> dprocess(x=x[,,2],times=t[2],params=p[,1:3],log=FALSE))\nError : in 'dprocess': length(times) < 2: with no transitions, there is no work to do.\n> try(po |> dprocess(x=x[,,2:5],times=t[2:5],params=p[,1:2],log=FALSE))\nError : in 'dprocess': the larger number of replicates is not a multiple of smaller.\n> po |> dprocess(x=x[,,2:5],times=t[2:5],params=p[,1:3],log=TRUE) |>\n+   apply(1,sum)\n[1] -30.7 -12.2 -14.3\n> try(po |> dprocess(x=x[,1:2,2:5],times=t[2:5],params=p[,1:3],log=TRUE) |>\n+       apply(1,sum))\nError : in 'dprocess': the larger number of replicates is not a multiple of smaller.\n> po |> dprocess(x=x[,1,2:5],times=t[2:5],params=p[,1:3],log=TRUE) |>\n+   apply(1,sum)\n[1] -30.7 -20.1 -19.1\n> po |> pomp(dprocess=NULL) |>\n+   dprocess(x=x[,1,2:5],times=t[2:5],params=p[,1:3],log=TRUE) |> is.na() |>\n+   stopifnot()\nWarning message:\n'dprocess' unspecified: likelihood undefined. \n> \n> po |> rinit(params=coef(po)) -> x0\n> freeze(\n+   po |>\n+     rprocess(\n+       params=coef(po),\n+       x0=parmat(x0,3),\n+       t0=timezero(po),\n+       times=time(po)\n+     ),\n+   seed=3434388L\n+ ) -> x1\n> \n> stopifnot(max(abs(x-x1))==0)\n> \n> po |> rinit(nsim=6) -> x0\n> try(rprocess(\"ou2\",x0=x0,t0=t[1],times=t,params=p))\nError : 'rprocess' is undefined for 'object' of class 'character'.\n> try(rprocess(x0=x0,t0=t[1],times=t,params=p))\nError : in 'rprocess': 'object' is a required argument.\n> freeze(po |> rprocess(times=t,params=p),seed=995484) -> x1\n> try(po |> rprocess(x0=x0,params=p))\nError : in 'rprocess': the larger number of replicates is not a multiple of smaller.\n> try(po |> rprocess(x0=x0,t0=t[1],params=p))\nError : in 'rprocess': the larger number of replicates is not a multiple of smaller.\n> freeze(po |> rprocess(x0=x0,times=t),seed=995484) -> x2\n> try(po |> rprocess(x0=x0,times=t,params=p))\nError : in 'rprocess': the larger number of replicates is not a multiple of smaller.\n> try(po |> rprocess(x0=x0,t0=t[1],times=t,params=p))\nError : in 'rprocess': the larger number of replicates is not a multiple of smaller.\n> po |> rprocess(x0=x0,t0=t[1],times=t,params=p[,1:3]) -> x\n> stopifnot(\n+   dim(x)==c(2,6,10),\n+   names(dimnames(x))==c(\"name\",\".id\",\"time\")\n+ )\n> po |> rprocess(x0=x0[,2],t0=t[1],times=t,params=p[,1:3]) -> x\n> stopifnot(\n+   dim(x)==c(2,3,10),\n+   names(dimnames(x))==c(\"name\",\".id\",\"time\")\n+ )\n> \n> try(po |> rprocess(x0=x0,t0=t[1],times=numeric(0),params=p))\nError : in 'rprocess': length(times) < 1: no work to do.\n> try(po |> rprocess(x0=x0[,2],t0=t[2],times=t[1],params=p[,1:3]))\nError : in 'rprocess': 't0' must be no later than 'times[1]'.\n> try(po |> rprocess(x0=x0[,2:4],t0=t[2],times=t[2:5],params=p[,1:2]))\nError : in 'rprocess': the larger number of replicates is not a multiple of smaller.\n> po |> rprocess(x0=x0[,2:4],t0=t[2],times=t[2:5],params=p[,1:3]) |>\n+   apply(1,sum)\n   x1    x2 \n-27.5  36.2 \n> \n> simulate(\n+   times=seq(0,10), t0=0,\n+   params=c(s=3,x_0=0,tau=1),\n+   covar=covariate_table(z=c(1,1),times=c(0,10)),\n+   rprocess = onestep(\n+     function (t, x, s, delta.t, ...) {\n+       c(x=rnorm(n=1,mean=x,sd=s*sqrt(delta.t)))\n+     }\n+   ),\n+   dprocess = function (x_1, x_2, s, t_1, t_2, ...) {\n+     delta.t <- t_2-t_1\n+     dnorm(x=x_2,mean=x_1,sd=s*sqrt(delta.t),log=TRUE)\n+   },\n+   seed=3434388L\n+ ) -> rw\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> \n> dprocess(rw,x=states(rw),params=coef(rw),times=time(rw),log=TRUE) -> d\n> stopifnot(\n+   round(sum(d),1)==-23.2,\n+   dim(d)==c(1,10),\n+   names(dimnames(d))==c(\".id\",\"time\")\n+ )\n> \n"
  },
  {
    "path": "tests/profile_design.R",
    "content": "png(filename=\"profile_design-%02d.png\",res=100)\nlibrary(pomp)\nsuppressPackageStartupMessages({\n  library(dplyr)\n})\nset.seed(722855899)\n\n## A one-parameter profile design:\nx <- profile_design(p=1:10,lower=c(q=3,a=0,b=0),upper=c(q=5,a=1,b=5),nprof=20)\nstopifnot(x |> count(p) |> pull(n) |> unique() == 20)\nplot(x)\n\n## A two-parameter profile design:\nx <- profile_design(p=1:10,q=3:5,lower=c(a=0,b=0),upper=c(b=5,a=1),nprof=30)\nstopifnot(x |> count(p,q) |> pull(n) |> unique() == 30)\nplot(x)\n\ntry(profile_design(1:10,q=3:5,nprof=10))\ntry(profile_design(p=1:10,q=3:5,lower=c(a=0,c=0),upper=c(b=5,a=1),nprof=20))\n\ndev.off()\n"
  },
  {
    "path": "tests/profile_design.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> png(filename=\"profile_design-%02d.png\",res=100)\n> library(pomp)\n> suppressPackageStartupMessages({\n+   library(dplyr)\n+ })\n> set.seed(722855899)\n> \n> ## A one-parameter profile design:\n> x <- profile_design(p=1:10,lower=c(q=3,a=0,b=0),upper=c(q=5,a=1,b=5),nprof=20)\n> stopifnot(x |> count(p) |> pull(n) |> unique() == 20)\n> plot(x)\n> \n> ## A two-parameter profile design:\n> x <- profile_design(p=1:10,q=3:5,lower=c(a=0,b=0),upper=c(b=5,a=1),nprof=30)\n> stopifnot(x |> count(p,q) |> pull(n) |> unique() == 30)\n> plot(x)\n> \n> try(profile_design(1:10,q=3:5,nprof=10))\nError : in 'profile_design': you cannot profile over an unnamed variable!\n> try(profile_design(p=1:10,q=3:5,lower=c(a=0,c=0),upper=c(b=5,a=1),nprof=20))\nError : in 'profile_design': names of 'lower' and 'upper' must match!\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/proposals.R",
    "content": "options(digits=3)\n\nlibrary(pomp)\n\nou2() -> po\n\nset.seed(1178744046L)\n\ntry(mvn_diag_rw(\"bob\"))\ntry(mvn_diag_rw(NULL))\ntry(mvn_diag_rw())\ntry(mvn_diag_rw(c(3,2)))\nf <- mvn_diag_rw(c(a=3,b=2))\nf(c(a=0,b=0))\n\ntry(mvn_rw(matrix(0,2,2)))\ntry(mvn_rw(array(dim=c(2,3),dimnames=list(letters[1:2],LETTERS[1:3]))))\ntry({m <- diag(3); m[3,3] <- 0; rownames(m) <- colnames(m) <- letters[1:3];\n    mvn_rw(m) -> f})\ncmat <- matrix(c(1,1,0,1),2,2,dimnames=list(letters[1:2],letters[1:2]))\nf <- mvn_rw(cmat)\nf(c(a=0,b=0))\n\ntry(mvn_rw_adaptive(c(a=1,b=1),scale.start=-2))\ntry(mvn_rw_adaptive(c(a=1,b=1),scale.cooling=2))\ntry(mvn_rw_adaptive(c(a=1,b=1),shape.start=-3))\ntry(mvn_rw_adaptive())\ntry(mvn_rw_adaptive(rw.sd=\"bob\"))\ncmat1 <- matrix(c(1,1,0,1),2,2)\ntry(mvn_rw_adaptive(rw.var=cmat1))\ncmat1 <- matrix(c(1,1,0,1,1,0),2,3,dimnames=list(letters[1:2],letters[1:3]))\ntry(mvn_rw_adaptive(rw.var=cmat1))\ncmat1 <- matrix(c(1,1,0,1),2,2,dimnames=list(letters[1:2],letters[3:4]))\ntry(mvn_rw_adaptive(rw.var=cmat1))\ntry(mvn_rw_adaptive(rw.var=cmat,scale.start=-300))\ntry(mvn_rw_adaptive(rw.var=cmat,scale.start=NA))\ntry(mvn_rw_adaptive(rw.var=cmat,scale.start=NULL))\ntry(mvn_rw_adaptive(rw.var=cmat,scale.start=1000))\ntry(mvn_rw_adaptive(rw.var=cmat,scale.start=1000,scale.cooling=3))\ntry(mvn_rw_adaptive(rw.var=cmat,scale.start=1000,scale.cooling=NA))\ntry(mvn_rw_adaptive(rw.var=cmat,scale.start=1000,scale.cooling=3.2))\ntry(mvn_rw_adaptive(rw.var=cmat,scale.start=1000,scale.cooling=0.2,\n  shape.start=-10))\ntry(mvn_rw_adaptive(rw.var=cmat,scale.start=1000,scale.cooling=0.2,\n  shape.start=10,target=3))\ntry(mvn_rw_adaptive(rw.var=cmat,scale.start=1000,scale.cooling=0.2,\n  shape.start=10,target=NA))\ntry(mvn_rw_adaptive(rw.var=cmat,scale.start=1000,scale.cooling=0.2,\n  shape.start=10,target=Inf))\ntry(mvn_rw_adaptive(rw.var=cmat,scale.start=1000,scale.cooling=0.2,\n  shape.start=10,target=\"bob\"))\nmvn_rw_adaptive(rw.sd=c(alpha_1=0.1,alpha_3=0.0),\n  scale.start=5,scale.cooling=0.1,shape.start=10) -> f1\nf1(c(alpha_1=1,alpha_3=1),.n=100,.accepts=1000,verbose=FALSE)\n\nmvn_rw_adaptive(rw.sd=c(alpha_1=0.1,alpha_3=0.1),\n  scale.start=5,scale.cooling=0.1,shape.start=10) -> f\noptions(verbose=TRUE) -> op\ncapture.output(po |> pmcmc(Nmcmc=200,Np=100,proposal=f) -> mcmc1) -> out\nstopifnot(sum(grepl(\"proposal covariance matrix:\",out))==200)\nevalq(covmat.emp,envir=environment(f))\noptions(op)\n"
  },
  {
    "path": "tests/proposals.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> \n> library(pomp)\n> \n> ou2() -> po\n> \n> set.seed(1178744046L)\n> \n> try(mvn_diag_rw(\"bob\"))\nError : in 'mvn_diag_rw': 'rw.sd' must be a named numeric vector.\n> try(mvn_diag_rw(NULL))\nError : in 'mvn_diag_rw': 'rw.sd' must be a named numeric vector.\n> try(mvn_diag_rw())\nError : in 'mvn_diag_rw': 'rw.sd' must be a named numeric vector.\n> try(mvn_diag_rw(c(3,2)))\nError : in 'mvn_diag_rw': 'rw.sd' must have names.\n> f <- mvn_diag_rw(c(a=3,b=2))\n> f(c(a=0,b=0))\n    a     b \n-3.53 -1.45 \n> \n> try(mvn_rw(matrix(0,2,2)))\nError : in 'mvn_rw': 'rw.var' must have row- and column-names.\n> try(mvn_rw(array(dim=c(2,3),dimnames=list(letters[1:2],LETTERS[1:3]))))\nError : in 'mvn_rw': 'rw.var' must be a square matrix.\n> try({m <- diag(3); m[3,3] <- 0; rownames(m) <- colnames(m) <- letters[1:3];\n+     mvn_rw(m) -> f})\nWarning messages:\n1: In chol.default(rw.var, pivot = TRUE) :\n  the matrix is either rank-deficient or not positive definite\n2: in 'mvn_rw': rank-deficient covariance matrix \n> cmat <- matrix(c(1,1,0,1),2,2,dimnames=list(letters[1:2],letters[1:2]))\n> f <- mvn_rw(cmat)\n> f(c(a=0,b=0))\n      a       b \n 0.9458 -0.0943 \n> \n> try(mvn_rw_adaptive(c(a=1,b=1),scale.start=-2))\nError : in 'mvn_rw_adaptive': 'scale.start' must be a positive integer.\n> try(mvn_rw_adaptive(c(a=1,b=1),scale.cooling=2))\nError : in 'mvn_rw_adaptive': 'scale.start' must be a positive integer.\n> try(mvn_rw_adaptive(c(a=1,b=1),shape.start=-3))\nError : in 'mvn_rw_adaptive': 'scale.start' must be a positive integer.\n> try(mvn_rw_adaptive())\nError : in 'mvn_rw_adaptive': exactly one of 'rw.sd' and 'rw.var' must be supplied.\n> try(mvn_rw_adaptive(rw.sd=\"bob\"))\nError : in 'mvn_rw_adaptive': 'rw.sd' must be a named numeric vector.\n> cmat1 <- matrix(c(1,1,0,1),2,2)\n> try(mvn_rw_adaptive(rw.var=cmat1))\nError : in 'mvn_rw_adaptive': 'rw.var' must have row- and column-names.\n> cmat1 <- matrix(c(1,1,0,1,1,0),2,3,dimnames=list(letters[1:2],letters[1:3]))\n> try(mvn_rw_adaptive(rw.var=cmat1))\nError : in 'mvn_rw_adaptive': 'rw.var' must be a square matrix.\n> cmat1 <- matrix(c(1,1,0,1),2,2,dimnames=list(letters[1:2],letters[3:4]))\n> try(mvn_rw_adaptive(rw.var=cmat1))\nError : in 'mvn_rw_adaptive': row- and column-names of 'rw.var' must agree.\n> try(mvn_rw_adaptive(rw.var=cmat,scale.start=-300))\nError : in 'mvn_rw_adaptive': 'scale.start' must be a positive integer.\n> try(mvn_rw_adaptive(rw.var=cmat,scale.start=NA))\nError : in 'mvn_rw_adaptive': 'scale.start' must be a positive integer.\n> try(mvn_rw_adaptive(rw.var=cmat,scale.start=NULL))\nError : in 'mvn_rw_adaptive': 'scale.start' must be a positive integer.\n> try(mvn_rw_adaptive(rw.var=cmat,scale.start=1000))\nError : in 'mvn_rw_adaptive': 'shape.start' must be a positive integer.\n> try(mvn_rw_adaptive(rw.var=cmat,scale.start=1000,scale.cooling=3))\nError : in 'mvn_rw_adaptive': 'scale.cooling' must be in (0,1].\n> try(mvn_rw_adaptive(rw.var=cmat,scale.start=1000,scale.cooling=NA))\nError : in 'mvn_rw_adaptive': 'scale.cooling' must be in (0,1].\n> try(mvn_rw_adaptive(rw.var=cmat,scale.start=1000,scale.cooling=3.2))\nError : in 'mvn_rw_adaptive': 'scale.cooling' must be in (0,1].\n> try(mvn_rw_adaptive(rw.var=cmat,scale.start=1000,scale.cooling=0.2,\n+   shape.start=-10))\nError : in 'mvn_rw_adaptive': 'shape.start' must be a positive integer.\n> try(mvn_rw_adaptive(rw.var=cmat,scale.start=1000,scale.cooling=0.2,\n+   shape.start=10,target=3))\nError : in 'mvn_rw_adaptive': 'target' must be a number in (0,1).\n> try(mvn_rw_adaptive(rw.var=cmat,scale.start=1000,scale.cooling=0.2,\n+   shape.start=10,target=NA))\nError : in 'mvn_rw_adaptive': 'target' must be a number in (0,1).\n> try(mvn_rw_adaptive(rw.var=cmat,scale.start=1000,scale.cooling=0.2,\n+   shape.start=10,target=Inf))\nError : in 'mvn_rw_adaptive': 'target' must be a number in (0,1).\n> try(mvn_rw_adaptive(rw.var=cmat,scale.start=1000,scale.cooling=0.2,\n+   shape.start=10,target=\"bob\"))\nError : in 'mvn_rw_adaptive': 'target' must be a number in (0,1).\nIn addition: Warning message:\nIn mvn_rw_adaptive(rw.var = cmat, scale.start = 1000, scale.cooling = 0.2,  :\n  NAs introduced by coercion\n> mvn_rw_adaptive(rw.sd=c(alpha_1=0.1,alpha_3=0.0),\n+   scale.start=5,scale.cooling=0.1,shape.start=10) -> f1\n> f1(c(alpha_1=1,alpha_3=1),.n=100,.accepts=1000,verbose=FALSE)\nalpha_1 alpha_3 \n      1       1 \nWarning messages:\n1: In chol.default(covmat, pivot = TRUE) :\n  the matrix is either rank-deficient or not positive definite\n2: in 'mvn_rw_adaptive': degenerate proposal. \n> \n> mvn_rw_adaptive(rw.sd=c(alpha_1=0.1,alpha_3=0.1),\n+   scale.start=5,scale.cooling=0.1,shape.start=10) -> f\n> options(verbose=TRUE) -> op\n> capture.output(po |> pmcmc(Nmcmc=200,Np=100,proposal=f) -> mcmc1) -> out\n> stopifnot(sum(grepl(\"proposal covariance matrix:\",out))==200)\n> evalq(covmat.emp,envir=environment(f))\n         alpha_1  alpha_3\nalpha_1 0.005957 0.000615\nalpha_3 0.000615 0.000906\n> options(op)\n> \n"
  },
  {
    "path": "tests/resample.R",
    "content": "library(pomp)\nset.seed(807969746L)\n\nw <- runif(100)\nk <- systematic_resample(w,100)\ntry(k <-systematic_resample(-w))\nk <- systematic_resample(w,10)\nk <- systematic_resample(w,110)\n"
  },
  {
    "path": "tests/resample.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> set.seed(807969746L)\n> \n> w <- runif(100)\n> k <- systematic_resample(w,100)\n> try(k <-systematic_resample(-w))\nError : in 'systematic_resampling': non-positive sum of weights\n> k <- systematic_resample(w,10)\n> k <- systematic_resample(w,110)\n> \n"
  },
  {
    "path": "tests/rgammawn.R",
    "content": "library(pomp)\nset.seed(39596886L)\n\nstopifnot(\n  `m1 fail`=rgammawn(n=10000,sigma=1,dt=0.1) |>\n    mean() |>\n    all.equal(0.1,tolerance=0.05),\n  `m2 fail`=rgammawn(n=10000,sigma=0.1,dt=0.1) |>\n    mean() |>\n    all.equal(0.1,tolerance=0.05),\n  `v1 fail`=rgammawn(n=10000,sigma=1,dt=0.1) |>\n    var() |>\n    all.equal(0.1,tolerance=0.05)\n)\n\n"
  },
  {
    "path": "tests/rgammawn.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> set.seed(39596886L)\n> \n> stopifnot(\n+   `m1 fail`=rgammawn(n=10000,sigma=1,dt=0.1) |>\n+     mean() |>\n+     all.equal(0.1,tolerance=0.05),\n+   `m2 fail`=rgammawn(n=10000,sigma=0.1,dt=0.1) |>\n+     mean() |>\n+     all.equal(0.1,tolerance=0.05),\n+   `v1 fail`=rgammawn(n=10000,sigma=1,dt=0.1) |>\n+     var() |>\n+     all.equal(0.1,tolerance=0.05)\n+ )\n> \n> \n"
  },
  {
    "path": "tests/ricker.R",
    "content": "library(pomp)\n\nset.seed(1800076828)\n\npng(filename=\"ricker-%02d.png\",res=100)\n\nricker() -> po\nplot(po)\n\nstopifnot(\n  all.equal(\n    coef(po),\n    partrans(po,coef(po,transform=TRUE),dir=\"from\")\n  ),\n  all.equal(\n    coef(po,transform=TRUE),\n    partrans(po,coef(po),dir=\"to\")\n  )\n)\n\npfilter(\n  po,\n  Np=1000,\n  filter.mean=TRUE,\n  pred.mean=TRUE,\n  pred.var=TRUE,\n  filter.traj=TRUE,\n  save.states=\"filter\"\n) -> pf\n\nstopifnot(\n  abs(logLik(pf)+138.5)<0.05\n)\n\nplot(pf,yax.flip=TRUE)\n\nforecast(pf,format=\"d\") -> fc\nsimulate(pf) -> sm\n\nemeasure(sm) -> ef\nvmeasure(sm) -> vf\nplot(ef,vf)\n\nplot(time(sm),obs(sm),xlab=\"time\",ylab=\"Y\")\nlines(time(sm),ef)\n\ntrajectory(po) -> tj\nplot(tj)\n\ndev.off()\n"
  },
  {
    "path": "tests/ricker.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> \n> set.seed(1800076828)\n> \n> png(filename=\"ricker-%02d.png\",res=100)\n> \n> ricker() -> po\n> plot(po)\n> \n> stopifnot(\n+   all.equal(\n+     coef(po),\n+     partrans(po,coef(po,transform=TRUE),dir=\"from\")\n+   ),\n+   all.equal(\n+     coef(po,transform=TRUE),\n+     partrans(po,coef(po),dir=\"to\")\n+   )\n+ )\n> \n> pfilter(\n+   po,\n+   Np=1000,\n+   filter.mean=TRUE,\n+   pred.mean=TRUE,\n+   pred.var=TRUE,\n+   filter.traj=TRUE,\n+   save.states=\"filter\"\n+ ) -> pf\n> \n> stopifnot(\n+   abs(logLik(pf)+138.5)<0.05\n+ )\n> \n> plot(pf,yax.flip=TRUE)\n> \n> forecast(pf,format=\"d\") -> fc\n> simulate(pf) -> sm\n> \n> emeasure(sm) -> ef\n> vmeasure(sm) -> vf\n> plot(ef,vf)\n> \n> plot(time(sm),obs(sm),xlab=\"time\",ylab=\"Y\")\n> lines(time(sm),ef)\n> \n> trajectory(po) -> tj\n> plot(tj)\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/rinit.R",
    "content": "library(pomp)\nset.seed(807969746L)\n\ngompertz() -> gompertz\nrinit(gompertz)\nrinit(gompertz,params=coef(gompertz))\n\np <- coef(gompertz)[-5]\ntry(rinit(gompertz,params=p))\n\ngompertz |> simulate(rinit=NULL)\n\ngompertz |>\n  pomp(rinit=function (...) 5) -> po\ntry(rinit(po))\ntry(rinit(\"gompertz\"))\ntry(rinit())\n\nstopifnot(dim(rinit(gompertz))==c(1,1))\n\npp <- parmat(coef(gompertz),10)\nstopifnot(gompertz |> rinit(params=pp) |> as.numeric()==1)\nrinit(gompertz,params=pp[,1:3],nsim=2) -> x0\nstopifnot(dim(x0)==c(1,6))\ndimnames(x0)\ncolnames(pp) <- head(LETTERS,10)\nrinit(gompertz,params=pp[,1:5],nsim=2) -> x0\nstopifnot(dim(x0)==c(1,10))\ndimnames(x0)\nrinit(gompertz,params=pp[,1:5],nsim=1) -> x0\nstopifnot(dim(x0)==c(1,5),colnames(x0)==head(LETTERS,5))\n\ntry(gompertz |>\n  pomp(rinit=function(...)\n    c(r=32)) |>\n  rinit())\ntry({\n  pp <- matrix(c(1:5),1,5)\n  rownames(pp) <- \"a\"\n  gompertz |>\n    pomp(rinit=function(a,...)\n      c(X=rep(1,a))) |>\n    rinit(params=pp)\n})\n\nsir() -> sir\ntry(sir |> simulate(rinit=NULL))\nsir |>\n  pomp(rinit=function(seas_1,...)\n    c(S=seas_1)) |>\n  rinit()\n\ngompertz |> rinit(nsim=3) -> x\ngompertz |> pomp(rinit=function(K,...)c(X=K)) |> rinit(nsim=3) -> y\nstopifnot(identical(x,y))\n\ngompertz |>\n  pomp(rinit=Csnippet(\"X=0.1;\"),statenames=c(\"X\",\"Z\"),nstatevars=4) |>\n  rinit() -> x\nstopifnot(rownames(x)==c(\"X\",\"Z\",\"\",\"\"))\n"
  },
  {
    "path": "tests/rinit.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> set.seed(807969746L)\n> \n> gompertz() -> gompertz\n> rinit(gompertz)\n    .id\nname [,1]\n   X    1\n> rinit(gompertz,params=coef(gompertz))\n    .id\nname [,1]\n   X    1\n> \n> p <- coef(gompertz)[-5]\n> try(rinit(gompertz,params=p))\n      .id\nname   [,1]\nWarning message:\nin default 'rinit': there are no parameters with suffix '.0' or '_0'. See '?rinit_spec'. \n> \n> gompertz |> simulate(rinit=NULL)\n<object of class 'pomp'>\n> \n> gompertz |>\n+   pomp(rinit=function (...) 5) -> po\n> try(rinit(po))\nError : in 'rinit': user 'rinit' must return a named numeric vector.\n> try(rinit(\"gompertz\"))\nError : 'rinit' is undefined for 'object' of class 'character'.\n> try(rinit())\nError : in 'rinit': 'object' is a required argument.\n> \n> stopifnot(dim(rinit(gompertz))==c(1,1))\n> \n> pp <- parmat(coef(gompertz),10)\n> stopifnot(gompertz |> rinit(params=pp) |> as.numeric()==1)\n> rinit(gompertz,params=pp[,1:3],nsim=2) -> x0\n> stopifnot(dim(x0)==c(1,6))\n> dimnames(x0)\n$name\n[1] \"X\"\n\n$.id\n[1] \"1_1\" \"2_1\" \"3_1\" \"1_2\" \"2_2\" \"3_2\"\n\n> colnames(pp) <- head(LETTERS,10)\n> rinit(gompertz,params=pp[,1:5],nsim=2) -> x0\n> stopifnot(dim(x0)==c(1,10))\n> dimnames(x0)\n$name\n[1] \"X\"\n\n$.id\n [1] \"A_1\" \"B_1\" \"C_1\" \"D_1\" \"E_1\" \"A_2\" \"B_2\" \"C_2\" \"D_2\" \"E_2\"\n\n> rinit(gompertz,params=pp[,1:5],nsim=1) -> x0\n> stopifnot(dim(x0)==c(1,5),colnames(x0)==head(LETTERS,5))\n> \n> try(gompertz |>\n+   pomp(rinit=function(...)\n+     c(r=32)) |>\n+   rinit())\nError : in 'rinit': a state variable and a parameter share the name: 'r'.\n> try({\n+   pp <- matrix(c(1:5),1,5)\n+   rownames(pp) <- \"a\"\n+   gompertz |>\n+     pomp(rinit=function(a,...)\n+       c(X=rep(1,a))) |>\n+     rinit(params=pp)\n+ })\nError : in 'rinit': user 'rinit' returns vectors of variable length.\n> \n> sir() -> sir\n> try(sir |> simulate(rinit=NULL))\nError : in 'simulate': variable 'cases' not found among the state variables.\n> sir |>\n+   pomp(rinit=function(seas_1,...)\n+     c(S=seas_1)) |>\n+   rinit()\n    .id\nname      [,1]\n   S 0.6666667\n> \n> gompertz |> rinit(nsim=3) -> x\n> gompertz |> pomp(rinit=function(K,...)c(X=K)) |> rinit(nsim=3) -> y\n> stopifnot(identical(x,y))\n> \n> gompertz |>\n+   pomp(rinit=Csnippet(\"X=0.1;\"),statenames=c(\"X\",\"Z\"),nstatevars=4) |>\n+   rinit() -> x\n> stopifnot(rownames(x)==c(\"X\",\"Z\",\"\",\"\"))\n> \n"
  },
  {
    "path": "tests/runif_design.R",
    "content": "png(filename=\"runif_design-%02d.png\",res=100)\nlibrary(pomp)\nsuppressPackageStartupMessages({\n  library(dplyr)\n})\n\nset.seed(818859525)\n\n## A 3D random design:\nx <- runif_design(lower=c(q=3,a=0,b=0),upper=c(q=5,a=1,b=5),nseq=20)\nstopifnot(x |> count(q) |> pull(n) |> unique() == 1)\nplot(x)\n\n## A 1D random design:\nx <- runif_design(lower=c(a=1,b=0),upper=c(b=5,a=1),nseq=30)\nstopifnot(x |> count(a) |> pull(n) |> unique() == 30)\nplot(x)\n\ntry(runif_design(lower=c(),upper=c(),nseq=10))\ntry(runif_design(lower=c(a=3),upper=c(),nseq=10))\ntry(runif_design(lower=c(a=3),upper=c(a=1),nseq=10))\ntry(runif_design(lower=c(a=3),upper=c(b=10),nseq=10))\ntry(runif_design(lower=c(a=3),upper=c(a=10),nseq=-1))\n\ndev.off()\n"
  },
  {
    "path": "tests/runif_design.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> png(filename=\"runif_design-%02d.png\",res=100)\n> library(pomp)\n> suppressPackageStartupMessages({\n+   library(dplyr)\n+ })\n> \n> set.seed(818859525)\n> \n> ## A 3D random design:\n> x <- runif_design(lower=c(q=3,a=0,b=0),upper=c(q=5,a=1,b=5),nseq=20)\n> stopifnot(x |> count(q) |> pull(n) |> unique() == 1)\n> plot(x)\n> \n> ## A 1D random design:\n> x <- runif_design(lower=c(a=1,b=0),upper=c(b=5,a=1),nseq=30)\n> stopifnot(x |> count(a) |> pull(n) |> unique() == 30)\n> plot(x)\n> \n> try(runif_design(lower=c(),upper=c(),nseq=10))\nError : in 'runif_design': 'lower' and 'upper' must be named vectors.\n> try(runif_design(lower=c(a=3),upper=c(),nseq=10))\nError : in 'runif_design': 'lower' and 'upper' must have same length.\n> try(runif_design(lower=c(a=3),upper=c(a=1),nseq=10))\nError : in 'runif_design': upper values should be at least as large as lower ones.\n> try(runif_design(lower=c(a=3),upper=c(b=10),nseq=10))\nError : in 'runif_design': names of 'lower' and 'upper' must match.\n> try(runif_design(lower=c(a=3),upper=c(a=10),nseq=-1))\nError : in 'runif_design': 'nseq'< 0.\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/rw2.R",
    "content": "library(pomp)\nsuppressPackageStartupMessages({\n  library(tidyr)\n  library(dplyr)\n  library(ggplot2)\n})\n\nset.seed(1438408329L)\n\npng(filename=\"rw2-%02d.png\",res=100)\n\nrw2(x1_0=1,x2_0=-1) -> po\nplot(po)\n\nstopifnot(\n  all.equal(\n    coef(po),\n    partrans(po,coef(po,transform=TRUE),dir=\"from\")\n  ),\n  all.equal(\n    coef(po,transform=TRUE),\n    partrans(po,coef(po),dir=\"to\")\n  )\n)\n\npfilter(\n  po,\n  Np=1000,\n  filter.mean=TRUE,\n  pred.mean=TRUE,\n  pred.var=TRUE,\n  filter.traj=TRUE,\n  save.states=\"filter\"\n) -> pf\n\nplot(pf,yax.flip=TRUE)\n\nforecast(pf,format=\"d\") -> fc\nsimulate(pf) -> sm\n\nemeasure(pf) |> melt() -> ef\nvmeasure(pf) |> melt() -> vf\nvf |> select(-time,-.id) |> distinct()\n\nbind_rows(\n  sim=sm |>\n    as.data.frame() |>\n    pivot_longer(c(x1,x2,y1,y2)),\n  forecast=fc,\n  filter=ef |> select(-.id),\n  prediction=pred_mean(pf,format=\"d\"),\n  filter=filter_mean(pf,format=\"d\"),\n  .id=\"type\"\n) |>\n  ggplot(aes(x=time,y=value,color=factor(type)))+\n  geom_line()+\n  labs(color=\"\")+\n  facet_wrap(~name,scales=\"free_y\")+\n  theme_bw()+theme(legend.position=\"top\")\n\nenkf(po,Np=1000) -> kf\nplot(kf,yax.flip=TRUE)\n\neakf(po,Np=1000) -> kf2\nplot(kf2,yax.flip=TRUE)\n\nKf <- kalmanFilter(\n  po,\n  A=diag(2),\n  Q=diag(coef(po,c(\"s1\",\"s2\"))^2),\n  C=diag(2),\n  R=coef(po,\"tau\")^2*diag(2)\n)\n\nprint(c(logLik(pf),logLik(kf),logLik(kf2),Kf$logLik))\n\nstopifnot(\n  abs(logLik(pf)+451.6)<0.05,\n  abs(logLik(kf)+450.4)<0.05,\n  abs(logLik(kf2)+449.1)<0.05,\n  abs(Kf$logLik+449.6)<0.05\n)\n\nd <- dprocess(sm,log=TRUE)\nprint(sum(d))\nstopifnot(\n  abs(sum(d)+381.4) < 0.5\n)\n\ndev.off()\n"
  },
  {
    "path": "tests/rw2.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> suppressPackageStartupMessages({\n+   library(tidyr)\n+   library(dplyr)\n+   library(ggplot2)\n+ })\n> \n> set.seed(1438408329L)\n> \n> png(filename=\"rw2-%02d.png\",res=100)\n> \n> rw2(x1_0=1,x2_0=-1) -> po\n> plot(po)\n> \n> stopifnot(\n+   all.equal(\n+     coef(po),\n+     partrans(po,coef(po,transform=TRUE),dir=\"from\")\n+   ),\n+   all.equal(\n+     coef(po,transform=TRUE),\n+     partrans(po,coef(po),dir=\"to\")\n+   )\n+ )\n> \n> pfilter(\n+   po,\n+   Np=1000,\n+   filter.mean=TRUE,\n+   pred.mean=TRUE,\n+   pred.var=TRUE,\n+   filter.traj=TRUE,\n+   save.states=\"filter\"\n+ ) -> pf\n> \n> plot(pf,yax.flip=TRUE)\n> \n> forecast(pf,format=\"d\") -> fc\n> simulate(pf) -> sm\n> \n> emeasure(pf) |> melt() -> ef\n> vmeasure(pf) |> melt() -> vf\n> vf |> select(-time,-.id) |> distinct()\n  var1 var2 value\n1   y1   y1     1\n2   y2   y1     0\n3   y1   y2     0\n4   y2   y2     1\n> \n> bind_rows(\n+   sim=sm |>\n+     as.data.frame() |>\n+     pivot_longer(c(x1,x2,y1,y2)),\n+   forecast=fc,\n+   filter=ef |> select(-.id),\n+   prediction=pred_mean(pf,format=\"d\"),\n+   filter=filter_mean(pf,format=\"d\"),\n+   .id=\"type\"\n+ ) |>\n+   ggplot(aes(x=time,y=value,color=factor(type)))+\n+   geom_line()+\n+   labs(color=\"\")+\n+   facet_wrap(~name,scales=\"free_y\")+\n+   theme_bw()+theme(legend.position=\"top\")\n> \n> enkf(po,Np=1000) -> kf\n> plot(kf,yax.flip=TRUE)\n> \n> eakf(po,Np=1000) -> kf2\n> plot(kf2,yax.flip=TRUE)\n> \n> Kf <- kalmanFilter(\n+   po,\n+   A=diag(2),\n+   Q=diag(coef(po,c(\"s1\",\"s2\"))^2),\n+   C=diag(2),\n+   R=coef(po,\"tau\")^2*diag(2)\n+ )\n> \n> print(c(logLik(pf),logLik(kf),logLik(kf2),Kf$logLik))\n[1] -451.5674 -450.3839 -449.0972 -449.5744\n> \n> stopifnot(\n+   abs(logLik(pf)+451.6)<0.05,\n+   abs(logLik(kf)+450.4)<0.05,\n+   abs(logLik(kf2)+449.1)<0.05,\n+   abs(Kf$logLik+449.6)<0.05\n+ )\n> \n> d <- dprocess(sm,log=TRUE)\n> print(sum(d))\n[1] -381.4356\n> stopifnot(\n+   abs(sum(d)+381.4) < 0.5\n+ )\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/sannbox.R",
    "content": "options(digits=3)\n\nlibrary(pomp)\n\nset.seed(240311270)\n\nripple <- function (x) {\n  r <- sqrt(sum(x^2))\n  1-exp(-r^2)*cos(10*r)^2\n}\n\nsannbox(par=c(1),fn=ripple,control=list(lower=1,upper=5)) -> out1\nsannbox(par=c(1),fn=ripple,control=list(lower=NULL,upper=NULL)) -> out2\nstopifnot(out1$convergence==0, out2$convergence==0)\ntry(sannbox(par=c(1),fn=ripple,control=list(\n  lower=NULL,upper=NULL,\n  sched=seq(10,1,length=10))))\nsannbox(par=c(1),fn=ripple,control=list(\n  lower=1,upper=5,maxit=100,sched=seq(10,1,length=100))) -> out3\nstopifnot(out3$convergence == 0)\ncapture.output(\n  sannbox(par=c(1),fn=ripple,control=list(lower=1,upper=5,maxit=10,trace=4)) -> out5\n) -> tout\nstopifnot(\n  sum(grepl(\"current params\",tout))==10,\n  sum(grepl(\"proposed params\",tout))==10,\n  sum(grepl(\"accept\",tout))==10,\n  sum(grepl(\"best\",tout))==1\n)\n\nf <- function (x) {\n  if (sqrt(sum(x^2))<1) ripple(x)\n  else Inf\n}\ninvisible(sannbox(par=c(2,2),fn=f))\n\ntry(sannbox(par=c(2,2),fn=f,control=list(candidate.dist=\"bob\")))\ntry(sannbox(par=c(2,2),fn=f,control=list(\n  candidate.dist=function(x)x)))\n"
  },
  {
    "path": "tests/sannbox.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> \n> library(pomp)\n> \n> set.seed(240311270)\n> \n> ripple <- function (x) {\n+   r <- sqrt(sum(x^2))\n+   1-exp(-r^2)*cos(10*r)^2\n+ }\n> \n> sannbox(par=c(1),fn=ripple,control=list(lower=1,upper=5)) -> out1\n> sannbox(par=c(1),fn=ripple,control=list(lower=NULL,upper=NULL)) -> out2\n> stopifnot(out1$convergence==0, out2$convergence==0)\n> try(sannbox(par=c(1),fn=ripple,control=list(\n+   lower=NULL,upper=NULL,\n+   sched=seq(10,1,length=10))))\nError : in 'sannbox': insufficiently many temperatures supplied in 'control$sched'\n> sannbox(par=c(1),fn=ripple,control=list(\n+   lower=1,upper=5,maxit=100,sched=seq(10,1,length=100))) -> out3\n> stopifnot(out3$convergence == 0)\n> capture.output(\n+   sannbox(par=c(1),fn=ripple,control=list(lower=1,upper=5,maxit=10,trace=4)) -> out5\n+ ) -> tout\n> stopifnot(\n+   sum(grepl(\"current params\",tout))==10,\n+   sum(grepl(\"proposed params\",tout))==10,\n+   sum(grepl(\"accept\",tout))==10,\n+   sum(grepl(\"best\",tout))==1\n+ )\n> \n> f <- function (x) {\n+   if (sqrt(sum(x^2))<1) ripple(x)\n+   else Inf\n+ }\n> invisible(sannbox(par=c(2,2),fn=f))\n> \n> try(sannbox(par=c(2,2),fn=f,control=list(candidate.dist=\"bob\")))\nError : in 'sannbox': 'control$candidate.dist' must be a function.\n> try(sannbox(par=c(2,2),fn=f,control=list(\n+   candidate.dist=function(x)x)))\nError : in 'sannbox': 'candidate.dist' must be a function of the form 'candidate.dist(par, temp, scale, ...)'.\n> \n"
  },
  {
    "path": "tests/save.R",
    "content": "library(dplyr)\nlibrary(tidyr)\nlibrary(pomp)\nset.seed(1800076828)\nricker() -> po\noptions(pomp_archive_dir=tempdir())\n\nsimulate(po,nsim=20) |>\n  coef() |>\n  melt() |>\n  pivot_wider() |>\n  append_data(\"tmp.csv\",overwrite=TRUE)\n\nsimulate(po,nsim=20,times=1:3) |>\n  as.data.frame() |>\n  rename(.id=.L1) |>\n  append_data(\"tmp.csv\") -> dat\n\ndata.table::fread(file.path(tempdir(),\"tmp.csv\")) -> dat1\n\nstopifnot(all.equal(dat,dat1))\n\ntry(append_data(\"bob\",file=\"tmp.csv\"))\ntry(append_data(\"bob\",file=\"tmp.csv\",overwrite=TRUE))\n"
  },
  {
    "path": "tests/save.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(dplyr)\n\nAttaching package: 'dplyr'\n\nThe following objects are masked from 'package:stats':\n\n    filter, lag\n\nThe following objects are masked from 'package:base':\n\n    intersect, setdiff, setequal, union\n\n> library(tidyr)\n> library(pomp)\n> set.seed(1800076828)\n> ricker() -> po\n> options(pomp_archive_dir=tempdir())\n> \n> simulate(po,nsim=20) |>\n+   coef() |>\n+   melt() |>\n+   pivot_wider() |>\n+   append_data(\"tmp.csv\",overwrite=TRUE)\n> \n> simulate(po,nsim=20,times=1:3) |>\n+   as.data.frame() |>\n+   rename(.id=.L1) |>\n+   append_data(\"tmp.csv\") -> dat\n> \n> data.table::fread(file.path(tempdir(),\"tmp.csv\")) -> dat1\n> \n> stopifnot(all.equal(dat,dat1))\n> \n> try(append_data(\"bob\",file=\"tmp.csv\"))\nError : in 'append_data': Item 2 of input is not a data.frame, data.table or list\n> try(append_data(\"bob\",file=\"tmp.csv\",overwrite=TRUE))\nError : in 'append_data': is.list(x) is not TRUE\n> \n"
  },
  {
    "path": "tests/simulate.R",
    "content": "options(digits=3)\npng(filename=\"simulate-%02d.png\",res=100)\n\nlibrary(pomp)\nlibrary(dplyr)\n\nset.seed(1041414791L)\n\nou2() -> ou2\nou2 |> simulate(times=0:20,t0=-4,seed=298831503) |> plot()\n\ntry(simulate(rprocess=onestep(Csnippet(\"z = runif(0,1);\")),\n  rmeasure=Csnippet(\"w = rnorm(z,1);\"),\n  rinit=Csnippet(\"z = 0;\"),\n  statenames=\"z\",obsnames=\"w\"))\ntry(simulate(times=1:10,\n  rprocess=onestep(Csnippet(\"z = runif(0,1);\")),\n  rmeasure=Csnippet(\"w = rnorm(z,1);\"),\n  rinit=Csnippet(\"z = 0;\"),\n  statenames=\"z\",obsnames=\"w\"))\ntry(simulate(times=c(1:5,NA,7:10),t0=0,\n  rprocess=onestep(Csnippet(\"z = runif(0,1);\")),\n  rmeasure=Csnippet(\"w = rnorm(z,1);\"),\n  rinit=Csnippet(\"z = 0;\"),\n  statenames=\"z\",obsnames=\"w\"))\ntry(simulate(times=NULL,t0=0,\n  rprocess=onestep(Csnippet(\"z = runif(0,1);\")),\n  rmeasure=Csnippet(\"w = rnorm(z,1);\"),\n  rinit=Csnippet(\"z = 0;\"),\n  statenames=\"z\",obsnames=\"w\"))\ntry(simulate(times=1:10,t0=NA,\n  rprocess=onestep(Csnippet(\"z = runif(0,1);\")),\n  rmeasure=Csnippet(\"w = rnorm(z,1);\"),\n  rinit=Csnippet(\"z = 0;\"),\n  statenames=\"z\",obsnames=\"w\"))\ntry(simulate(times=1:10,t0=NULL,\n  rprocess=onestep(Csnippet(\"z = runif(0,1);\")),\n  rmeasure=Csnippet(\"w = rnorm(z,1);\"),\n  rinit=Csnippet(\"z = 0;\"),\n  statenames=\"z\",obsnames=\"w\"))\n\nsimulate(times=1:100,t0=0,seed=450738202,\n  rprocess=onestep(Csnippet(\"z = runif(z-0.5,z+0.5);\")),\n  rmeasure=Csnippet(\"w = rnorm(z,1);\"),\n  rinit=Csnippet(\"z = 0;\"),\n  statenames=\"z\",obsnames=\"w\") |> plot()\n\ntry(simulate(times=1:100,t0=0,\n  rmeasure=Csnippet(\"w = rnorm(z,1);\"),\n  rinit=Csnippet(\"z = 0;\"),\n  statenames=\"z\",obsnames=\"w\"))\n\nsimulate(times=1:100,t0=0,\n  rprocess=onestep(function(z,...) {\n    c(z=runif(1,z-0.5,z+0.5))\n  }),\n  rmeasure=function(z,...) {\n    c(w = rnorm(1,z,1))\n  },params=c(z.0=0))\n\nstopifnot(\n  {\n    simulate(times=1:100,t0=0,\n      rprocess=onestep(function(z,...) {\n        c(z=runif(1,z-0.5,z+0.5))\n      }),params=c(z.0=0)) |> obs() -> y\n    dim(y)==c(0,100)\n  }\n)\n\nstopifnot(\n  {\n    simulate(times=1:100,t0=0,\n      rprocess=onestep(function(z,...) {\n        c(z=runif(1,z-0.5,z+0.5))\n      }),params=c(z.0=0),format=\"arrays\") -> s\n    dim(s$states)==c(1,1,100)\n    dim(s$obs)==c(0,1,100)\n  }\n)\n\ntry(simulate(times=1:100,t0=0,\n  rprocess=euler(function(w,z,...,delta.t) c(w,z),delta.t=0.1),\n  params=c(w_0=1,z_0=3)))\n\ntry(simulate(times=1:100,t0=0,\n  rprocess=euler(function(w,z,...,delta.t) c(w=w,z),delta.t=0.1),\n  params=c(w_0=1,z_0=3)))\n\ntry(simulate(times=1:100,t0=0,\n  rprocess=onestep(Csnippet(\"z = runif(z-0.5,z+0.5);\")),\n  rmeasure=function(t,z,...) c(w=rnorm(n=t,z,1)),\n  rinit=Csnippet(\"z = 2;\"),\n  statenames=\"z\"))\n\nsimulate(times=1:100,t0=0,seed=993523767,\n  rprocess=onestep(Csnippet(\"z = runif(z-0.5,z+0.5);\")),\n  rmeasure=function(z,...) c(w=rnorm(1,z,1)),\n  rinit=Csnippet(\"z = 0;\"),\n  statenames=\"z\") -> po\npo |> plot()\n\nsimulate(times=1:100,t0=0,seed=378047885,\n  rprocess=onestep(function(z,...)\n    c(z=runif(n=1,z-0.5,z+0.5))),\n  rmeasure=function(z,...) c(w=rnorm(1,z,1)),\n  rinit=function(params,t0,...)c(z=0)) |> plot()\n\nrm(.Random.seed)\npo |>\n  simulate(params=as.list(coef(po)),seed=406214171) |>\n  plot(variables=rep(c(\"z\",\"w\"),10),main=\"test\",yax.flip=TRUE)\n\nset.seed(1041414791L)\n\ndata.frame(u=1:10,v=runif(10)) |>\n  pomp(times=\"u\",t0=0) |>\n  simulate(rprocess=onestep(Csnippet(\"w = runif(0,1);\")),\n    rmeasure=function(w,...){\n      p <- w+c(-0.5,0.5)\n      c(y=runif(n=1,p[1],p[2]))\n    },\n    rinit=Csnippet(\"w=0;\"),\n    statenames=\"w\") |>\n  obs() |>\n  rownames()\n\ndata.frame(u=1:10,v=runif(10)) |>\n  pomp(times=\"u\",t0=0) |>\n  simulate(rprocess=onestep(Csnippet(\"w = runif(0,1);\")),\n    rmeasure=Csnippet(\"y=runif(w-0.5,w+0.5);\"),\n    rinit=Csnippet(\"w=0;\"),\n    statenames=\"w\",obsnames=\"y\") |>\n  obs() |>\n  rownames()\n\ntry(simulate(ou2,nsim=-3))\ntry(simulate(ou2,nsim=NA))\ntry(simulate(ou2,nsim=NULL))\ntry(simulate(ou2,nsim=\"bob\"))\n\nou2 |> window(end=3) -> po\nsimulate(po,format=\"data.frame\",seed=49569969,nsim=3) |>\n  count(.id) |> as.data.frame()\nsimulate(po,format=\"data.frame\",seed=49569969,nsim=3,include.data=TRUE) |>\n  count(.id) |> as.data.frame()\nsimulate(po,format=\"data.frame\",seed=49569969)\nsimulate(po,format=\"data.frame\",include.data=TRUE,seed=49569969)\nsimulate(po,format=\"arrays\") -> s\ns$states |> rownames()\ns$obs |> rownames()\nsimulate(po,nsim=3) |> show()\n\ndata.frame(u=1:10,v=runif(10)) |>\n  pomp(times=\"u\",t0=0) |>\n  simulate(rprocess=onestep(Csnippet(\"w = runif(0,1);\")),\n    rmeasure=Csnippet(\"y=runif(w-0.5,w+0.5);\"),\n    rinit=Csnippet(\"w=0;\"),\n    statenames=\"w\",obsnames=\"y\",format=\"data.frame\",include.data=TRUE) -> dat\ndat |> names()\ndat |> dim()\n\nrw2() -> rw2\nsimulate(rw2,accumvars=\"x2\") |> plot()\ntry(simulate(rw2,params=c(a=\"bob\",b=\"nancy\")))\n\nsimulate(rw2,times=c(1:5,5,5),format=\"d\",seed=49569969) -> x\nstopifnot(with(x,c(x1[6:7]==x1[5],x2[6:7]==x2[5],time[6:7]==time[5],\n  y1[6:7]!=y1[5],y2[6:7]!=y2[5])))\n\nsimulate(rw2,rinit=function(...) c(x1=0,x2=0)) -> x\n\nlibrary(tidyr)\ndacca() |>\n  simulate(nsim=2,include.data=TRUE,format=\"data.frame\") -> dat\ndat |>\n  select(time,.id,seas_1,seas_2) |>\n  arrange(time,.id) |>\n  head(6)\ndat |>\n  pivot_longer(-.id) |>\n  group_by(.id,name) |>\n  summarize(n=sum(is.na(value)),.groups=\"drop\") |>\n  filter(n>0) -> d1\nstopifnot(\n  `na in sim`=all(d1$.id==\"data\"),\n  full=all(d1$n==600)\n)\n\ndev.off()\n"
  },
  {
    "path": "tests/simulate.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"simulate-%02d.png\",res=100)\n> \n> library(pomp)\n> library(dplyr)\n\nAttaching package: 'dplyr'\n\nThe following objects are masked from 'package:stats':\n\n    filter, lag\n\nThe following objects are masked from 'package:base':\n\n    intersect, setdiff, setequal, union\n\n> \n> set.seed(1041414791L)\n> \n> ou2() -> ou2\n> ou2 |> simulate(times=0:20,t0=-4,seed=298831503) |> plot()\n> \n> try(simulate(rprocess=onestep(Csnippet(\"z = runif(0,1);\")),\n+   rmeasure=Csnippet(\"w = rnorm(z,1);\"),\n+   rinit=Csnippet(\"z = 0;\"),\n+   statenames=\"z\",obsnames=\"w\"))\nError : in 'simulate': 'times' should either be a numeric vector of observation times or a single name identifying the column of data that represents the observation times.\n> try(simulate(times=1:10,\n+   rprocess=onestep(Csnippet(\"z = runif(0,1);\")),\n+   rmeasure=Csnippet(\"w = rnorm(z,1);\"),\n+   rinit=Csnippet(\"z = 0;\"),\n+   statenames=\"z\",obsnames=\"w\"))\nError : in 'simulate': 't0' is a required argument.\n> try(simulate(times=c(1:5,NA,7:10),t0=0,\n+   rprocess=onestep(Csnippet(\"z = runif(0,1);\")),\n+   rmeasure=Csnippet(\"w = rnorm(z,1);\"),\n+   rinit=Csnippet(\"z = 0;\"),\n+   statenames=\"z\",obsnames=\"w\"))\nError : in 'simulate': 'times' must be a non-decreasing sequence of numbers.\n> try(simulate(times=NULL,t0=0,\n+   rprocess=onestep(Csnippet(\"z = runif(0,1);\")),\n+   rmeasure=Csnippet(\"w = rnorm(z,1);\"),\n+   rinit=Csnippet(\"z = 0;\"),\n+   statenames=\"z\",obsnames=\"w\"))\nError : in 'simulate': 'times' should either be a numeric vector of observation times or a single name identifying the column of data that represents the observation times.\n> try(simulate(times=1:10,t0=NA,\n+   rprocess=onestep(Csnippet(\"z = runif(0,1);\")),\n+   rmeasure=Csnippet(\"w = rnorm(z,1);\"),\n+   rinit=Csnippet(\"z = 0;\"),\n+   statenames=\"z\",obsnames=\"w\"))\nError : in 'simulate': 't0' must be a single number not greater than 'times[1]'.\n> try(simulate(times=1:10,t0=NULL,\n+   rprocess=onestep(Csnippet(\"z = runif(0,1);\")),\n+   rmeasure=Csnippet(\"w = rnorm(z,1);\"),\n+   rinit=Csnippet(\"z = 0;\"),\n+   statenames=\"z\",obsnames=\"w\"))\nError : in 'simulate': 't0' must be a single number not greater than 'times[1]'.\n> \n> simulate(times=1:100,t0=0,seed=450738202,\n+   rprocess=onestep(Csnippet(\"z = runif(z-0.5,z+0.5);\")),\n+   rmeasure=Csnippet(\"w = rnorm(z,1);\"),\n+   rinit=Csnippet(\"z = 0;\"),\n+   statenames=\"z\",obsnames=\"w\") |> plot()\n> \n> try(simulate(times=1:100,t0=0,\n+   rmeasure=Csnippet(\"w = rnorm(z,1);\"),\n+   rinit=Csnippet(\"z = 0;\"),\n+   statenames=\"z\",obsnames=\"w\"))\nError : in 'simulate': 'rprocess' is undefined.\n> \n> simulate(times=1:100,t0=0,\n+   rprocess=onestep(function(z,...) {\n+     c(z=runif(1,z-0.5,z+0.5))\n+   }),\n+   rmeasure=function(z,...) {\n+     c(w = rnorm(1,z,1))\n+   },params=c(z.0=0))\n<object of class 'pomp'>\n> \n> stopifnot(\n+   {\n+     simulate(times=1:100,t0=0,\n+       rprocess=onestep(function(z,...) {\n+         c(z=runif(1,z-0.5,z+0.5))\n+       }),params=c(z.0=0)) |> obs() -> y\n+     dim(y)==c(0,100)\n+   }\n+ )\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> \n> stopifnot(\n+   {\n+     simulate(times=1:100,t0=0,\n+       rprocess=onestep(function(z,...) {\n+         c(z=runif(1,z-0.5,z+0.5))\n+       }),params=c(z.0=0),format=\"arrays\") -> s\n+     dim(s$states)==c(1,1,100)\n+     dim(s$obs)==c(0,1,100)\n+   }\n+ )\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> \n> try(simulate(times=1:100,t0=0,\n+   rprocess=euler(function(w,z,...,delta.t) c(w,z),delta.t=0.1),\n+   params=c(w_0=1,z_0=3)))\nError : in 'simulate': 'rprocess' must return a named numeric vector.\n> \n> try(simulate(times=1:100,t0=0,\n+   rprocess=euler(function(w,z,...,delta.t) c(w=w,z),delta.t=0.1),\n+   params=c(w_0=1,z_0=3)))\nError : in 'simulate': variable 'z' not found among the state variables.\n> \n> try(simulate(times=1:100,t0=0,\n+   rprocess=onestep(Csnippet(\"z = runif(z-0.5,z+0.5);\")),\n+   rmeasure=function(t,z,...) c(w=rnorm(n=t,z,1)),\n+   rinit=Csnippet(\"z = 2;\"),\n+   statenames=\"z\"))\nError : in 'simulate': 'rmeasure' returns variable-length results.\n> \n> simulate(times=1:100,t0=0,seed=993523767,\n+   rprocess=onestep(Csnippet(\"z = runif(z-0.5,z+0.5);\")),\n+   rmeasure=function(z,...) c(w=rnorm(1,z,1)),\n+   rinit=Csnippet(\"z = 0;\"),\n+   statenames=\"z\") -> po\n> po |> plot()\n> \n> simulate(times=1:100,t0=0,seed=378047885,\n+   rprocess=onestep(function(z,...)\n+     c(z=runif(n=1,z-0.5,z+0.5))),\n+   rmeasure=function(z,...) c(w=rnorm(1,z,1)),\n+   rinit=function(params,t0,...)c(z=0)) |> plot()\n> \n> rm(.Random.seed)\n> po |>\n+   simulate(params=as.list(coef(po)),seed=406214171) |>\n+   plot(variables=rep(c(\"z\",\"w\"),10),main=\"test\",yax.flip=TRUE)\n> \n> set.seed(1041414791L)\n> \n> data.frame(u=1:10,v=runif(10)) |>\n+   pomp(times=\"u\",t0=0) |>\n+   simulate(rprocess=onestep(Csnippet(\"w = runif(0,1);\")),\n+     rmeasure=function(w,...){\n+       p <- w+c(-0.5,0.5)\n+       c(y=runif(n=1,p[1],p[2]))\n+     },\n+     rinit=Csnippet(\"w=0;\"),\n+     statenames=\"w\") |>\n+   obs() |>\n+   rownames()\n[1] \"y\"\n> \n> data.frame(u=1:10,v=runif(10)) |>\n+   pomp(times=\"u\",t0=0) |>\n+   simulate(rprocess=onestep(Csnippet(\"w = runif(0,1);\")),\n+     rmeasure=Csnippet(\"y=runif(w-0.5,w+0.5);\"),\n+     rinit=Csnippet(\"w=0;\"),\n+     statenames=\"w\",obsnames=\"y\") |>\n+   obs() |>\n+   rownames()\n[1] \"y\"\n> \n> try(simulate(ou2,nsim=-3))\nError : in 'simulate': 'nsim' must be a positive integer.\n> try(simulate(ou2,nsim=NA))\nError : in 'simulate': 'nsim' must be a positive integer.\n> try(simulate(ou2,nsim=NULL))\nError : in 'simulate': 'nsim' must be a positive integer.\n> try(simulate(ou2,nsim=\"bob\"))\nError : in 'simulate': 'nsim' must be a positive integer.\n> \n> ou2 |> window(end=3) -> po\n> simulate(po,format=\"data.frame\",seed=49569969,nsim=3) |>\n+   count(.id) |> as.data.frame()\n  .id n\n1   1 3\n2   2 3\n3   3 3\n> simulate(po,format=\"data.frame\",seed=49569969,nsim=3,include.data=TRUE) |>\n+   count(.id) |> as.data.frame()\n   .id n\n1 data 3\n2    1 3\n3    2 3\n4    3 3\n> simulate(po,format=\"data.frame\",seed=49569969)\n  time .id      x1   x2     y1   y2\n1    1   1 -1.5048 6.11 -1.033 6.49\n2    2   1 -0.6614 4.80 -0.486 3.18\n3    3   1  0.0843 5.75  2.609 3.41\n> simulate(po,format=\"data.frame\",include.data=TRUE,seed=49569969)\n  time  .id     y1   y2      x1   x2\n1    1 data -4.051 4.78 -3.7185 4.25\n2    2 data  1.835 6.27  0.9404 6.84\n3    3 data -1.317 7.56 -0.3726 7.59\n4    1    1 -1.033 6.49 -1.5048 6.11\n5    2    1 -0.486 3.18 -0.6614 4.80\n6    3    1  2.609 3.41  0.0843 5.75\n> simulate(po,format=\"arrays\") -> s\n> s$states |> rownames()\n[1] \"x1\" \"x2\"\n> s$obs |> rownames()\n[1] \"y1\" \"y2\"\n> simulate(po,nsim=3) |> show()\n[[1]]\n<object of class 'pomp'>\n\n[[2]]\n<object of class 'pomp'>\n\n[[3]]\n<object of class 'pomp'>\n\n> \n> data.frame(u=1:10,v=runif(10)) |>\n+   pomp(times=\"u\",t0=0) |>\n+   simulate(rprocess=onestep(Csnippet(\"w = runif(0,1);\")),\n+     rmeasure=Csnippet(\"y=runif(w-0.5,w+0.5);\"),\n+     rinit=Csnippet(\"w=0;\"),\n+     statenames=\"w\",obsnames=\"y\",format=\"data.frame\",include.data=TRUE) -> dat\n> dat |> names()\n[1] \"u\"   \".id\" \"v\"   \"w\"   \"y\"  \n> dat |> dim()\n[1] 20  5\n> \n> rw2() -> rw2\n> simulate(rw2,accumvars=\"x2\") |> plot()\n> try(simulate(rw2,params=c(a=\"bob\",b=\"nancy\")))\nError : in 'simulate': 'params' must be named and numeric.\n> \n> simulate(rw2,times=c(1:5,5,5),format=\"d\",seed=49569969) -> x\n> stopifnot(with(x,c(x1[6:7]==x1[5],x2[6:7]==x2[5],time[6:7]==time[5],\n+   y1[6:7]!=y1[5],y2[6:7]!=y2[5])))\n> \n> simulate(rw2,rinit=function(...) c(x1=0,x2=0)) -> x\n> \n> library(tidyr)\n> dacca() |>\n+   simulate(nsim=2,include.data=TRUE,format=\"data.frame\") -> dat\n> dat |>\n+   select(time,.id,seas_1,seas_2) |>\n+   arrange(time,.id) |>\n+   head(6)\n  time  .id seas_1 seas_2\n1 1891 data  0.666  0.167\n2 1891    1  0.666  0.167\n3 1891    2  0.666  0.167\n4 1891 data  0.479  0.479\n5 1891    1  0.479  0.479\n6 1891    2  0.479  0.479\n> dat |>\n+   pivot_longer(-.id) |>\n+   group_by(.id,name) |>\n+   summarize(n=sum(is.na(value)),.groups=\"drop\") |>\n+   filter(n>0) -> d1\n> stopifnot(\n+   `na in sim`=all(d1$.id==\"data\"),\n+   full=all(d1$n==600)\n+ )\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/simulate_data_frame.R",
    "content": "options(digits=3)\n\nlibrary(pomp)\nlibrary(dplyr)\n\nset.seed(1041414791L)\n\ndata.frame(t=0:10,y=runif(11)) |>\n  simulate(times=\"t\",t0=0,\n    rprocess=discrete_time(\n      step.fun=function(r,x,...) {\n        c(x=r*x*exp(-x))\n      }),\n    rmeasure=function(x,...) {\n      c(y=rpois(n=1,100*x))\n    },\n    params=list(r=15,x.0=0.1)\n  )\n\ntry(data.frame(t=0:10,y=runif(11)) |>\n    simulate(times=\"t\",t0=0,\n      rprocess=discrete_time(\n        step.fun=function(r,x,...) {\n          c(x=r*x*exp(-x))\n        }),\n      rmeasure=function(x,...) {\n        c(y=rpois(n=1,100*x))\n      },\n      params=list(r=15,x.0=0.1),\n      format=\"bob\"\n    )\n)\n\ntry(data.frame(t=0:10,y=runif(11)) |>\n  simulate(times=1:50))\ntry(data.frame(t=0:10,y=runif(11)) |>\n    simulate(times=\"t\"))\ntry(data.frame(t=0:10,y=runif(11)) |>\n    simulate(times=\"t\",t0=0))\ntry(data.frame(t=0:10,y=runif(11)) |>\n    simulate(times=\"t\",t0=0))\ntry(data.frame(t=0:10,y=runif(11)) |>\n    simulate(times=\"t\",t0=0,params=c(x.0=1)))\n"
  },
  {
    "path": "tests/simulate_data_frame.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> \n> library(pomp)\n> library(dplyr)\n\nAttaching package: 'dplyr'\n\nThe following objects are masked from 'package:stats':\n\n    filter, lag\n\nThe following objects are masked from 'package:base':\n\n    intersect, setdiff, setequal, union\n\n> \n> set.seed(1041414791L)\n> \n> data.frame(t=0:10,y=runif(11)) |>\n+   simulate(times=\"t\",t0=0,\n+     rprocess=discrete_time(\n+       step.fun=function(r,x,...) {\n+         c(x=r*x*exp(-x))\n+       }),\n+     rmeasure=function(x,...) {\n+       c(y=rpois(n=1,100*x))\n+     },\n+     params=list(r=15,x.0=0.1)\n+   )\n<object of class 'pomp'>\n> \n> try(data.frame(t=0:10,y=runif(11)) |>\n+     simulate(times=\"t\",t0=0,\n+       rprocess=discrete_time(\n+         step.fun=function(r,x,...) {\n+           c(x=r*x*exp(-x))\n+         }),\n+       rmeasure=function(x,...) {\n+         c(y=rpois(n=1,100*x))\n+       },\n+       params=list(r=15,x.0=0.1),\n+       format=\"bob\"\n+     )\n+ )\nError : in 'simulate': 'arg' should be one of \"pomps\", \"arrays\", \"data.frame\"\n> \n> try(data.frame(t=0:10,y=runif(11)) |>\n+   simulate(times=1:50))\nError : in 'simulate': 't0' is a required argument.\n> try(data.frame(t=0:10,y=runif(11)) |>\n+     simulate(times=\"t\"))\nError : in 'simulate': 't0' is a required argument.\n> try(data.frame(t=0:10,y=runif(11)) |>\n+     simulate(times=\"t\",t0=0))\nError : in 'simulate': 'rprocess' is undefined.\n> try(data.frame(t=0:10,y=runif(11)) |>\n+     simulate(times=\"t\",t0=0))\nError : in 'simulate': 'rprocess' is undefined.\n> try(data.frame(t=0:10,y=runif(11)) |>\n+     simulate(times=\"t\",t0=0,params=c(x.0=1)))\nError : in 'simulate': 'rprocess' is undefined.\n> \n"
  },
  {
    "path": "tests/sir.R",
    "content": "library(pomp)\nsuppressPackageStartupMessages({\n  library(dplyr)\n})\n\nset.seed(48832734L)\n\npng(filename=\"sir-%02d.png\",res=100)\n\nsir() -> po\nplot(po)\n\nstopifnot(\n  all.equal(\n    coef(po),\n    partrans(po,coef(po,transform=TRUE),dir=\"from\")\n  ),\n  all.equal(\n    coef(po,transform=TRUE),\n    partrans(po,coef(po),dir=\"to\")\n  )\n)\n\npfilter(\n  po,\n  Np=1000,\n  filter.mean=TRUE,\n  pred.mean=TRUE,\n  pred.var=TRUE,\n  filter.traj=TRUE,\n  save.states=\"filter\"\n) -> pf\n\nstopifnot(\n  abs(logLik(pf)+1250.1)<0.05\n)\n\nplot(pf,yax.flip=TRUE)\n\nforecast(pf,format=\"d\") -> fc\nsimulate(pf) -> sm\n\nemeasure(sm) -> ef\nvmeasure(sm) -> vf\nplot(ef,vf)\n\nplot(time(sm),obs(sm),xlab=\"time\",ylab=\"Y\")\nlines(time(sm),ef)\n\ntrajectory(po) -> tj\nplot(tj)\n\ndev.off()\n"
  },
  {
    "path": "tests/sir.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> suppressPackageStartupMessages({\n+   library(dplyr)\n+ })\n> \n> set.seed(48832734L)\n> \n> png(filename=\"sir-%02d.png\",res=100)\n> \n> sir() -> po\n> plot(po)\n> \n> stopifnot(\n+   all.equal(\n+     coef(po),\n+     partrans(po,coef(po,transform=TRUE),dir=\"from\")\n+   ),\n+   all.equal(\n+     coef(po,transform=TRUE),\n+     partrans(po,coef(po),dir=\"to\")\n+   )\n+ )\n> \n> pfilter(\n+   po,\n+   Np=1000,\n+   filter.mean=TRUE,\n+   pred.mean=TRUE,\n+   pred.var=TRUE,\n+   filter.traj=TRUE,\n+   save.states=\"filter\"\n+ ) -> pf\n> \n> stopifnot(\n+   abs(logLik(pf)+1250.1)<0.05\n+ )\n> \n> plot(pf,yax.flip=TRUE)\n> \n> forecast(pf,format=\"d\") -> fc\n> simulate(pf) -> sm\n> \n> emeasure(sm) -> ef\n> vmeasure(sm) -> vf\n> plot(ef,vf)\n> \n> plot(time(sm),obs(sm),xlab=\"time\",ylab=\"Y\")\n> lines(time(sm),ef)\n> \n> trajectory(po) -> tj\n> plot(tj)\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/sir2.R",
    "content": "library(pomp)\nsuppressPackageStartupMessages({\n  library(dplyr)\n})\n\nset.seed(48832734L)\n\npng(filename=\"sir2-%02d.png\",res=100)\n\nsir2() |> window(end=2) -> po\nplot(po)\n\nstopifnot(\n  all.equal(\n    coef(po),\n    partrans(po,coef(po,transform=TRUE),dir=\"from\")\n  ),\n  all.equal(\n    coef(po,transform=TRUE),\n    partrans(po,coef(po),dir=\"to\")\n  )\n)\n\npfilter(\n  window(po,end=1),\n  Np=1000,\n  filter.mean=TRUE,\n  pred.mean=TRUE,\n  pred.var=TRUE,\n  filter.traj=TRUE,\n  save.states=\"filter\"\n) -> pf\n\nstopifnot(\n  abs(logLik(pf)+43.2)<0.05\n)\n\nplot(pf,yax.flip=TRUE)\n\nforecast(pf,format=\"d\") -> fc\nsimulate(pf) -> sm\n\nemeasure(sm) -> ef\nvmeasure(sm) -> vf\nplot(ef,vf)\n\nplot(time(sm),obs(sm),xlab=\"time\",ylab=\"Y\")\nlines(time(sm),ef)\n\ntrajectory(po) -> tj\nplot(tj)\n\ndev.off()\n"
  },
  {
    "path": "tests/sir2.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> suppressPackageStartupMessages({\n+   library(dplyr)\n+ })\n> \n> set.seed(48832734L)\n> \n> png(filename=\"sir2-%02d.png\",res=100)\n> \n> sir2() |> window(end=2) -> po\n> plot(po)\n> \n> stopifnot(\n+   all.equal(\n+     coef(po),\n+     partrans(po,coef(po,transform=TRUE),dir=\"from\")\n+   ),\n+   all.equal(\n+     coef(po,transform=TRUE),\n+     partrans(po,coef(po),dir=\"to\")\n+   )\n+ )\n> \n> pfilter(\n+   window(po,end=1),\n+   Np=1000,\n+   filter.mean=TRUE,\n+   pred.mean=TRUE,\n+   pred.var=TRUE,\n+   filter.traj=TRUE,\n+   save.states=\"filter\"\n+ ) -> pf\n> \n> stopifnot(\n+   abs(logLik(pf)+43.2)<0.05\n+ )\n> \n> plot(pf,yax.flip=TRUE)\n> \n> forecast(pf,format=\"d\") -> fc\n> simulate(pf) -> sm\n> \n> emeasure(sm) -> ef\n> vmeasure(sm) -> vf\n> plot(ef,vf)\n> \n> plot(time(sm),obs(sm),xlab=\"time\",ylab=\"Y\")\n> lines(time(sm),ef)\n> \n> trajectory(po) -> tj\n> plot(tj)\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/skeleton.R",
    "content": "options(digits=3)\npng(filename=\"skeleton-%02d.png\",res=100)\n\nlibrary(pomp)\nsuppressPackageStartupMessages({\n  library(ggplot2)\n  library(dplyr)\n  library(tidyr)\n})\n\nricker() -> ricker\n\nricker <- simulate(ricker,times=1:500,seed=366829807L)\nx <- states(ricker)\np <- parmat(coef(ricker),3)\np[\"r\",] <- exp(c(1,2,4))\nf <- skeleton(ricker,x=x,params=p,times=time(ricker))\nf |>\n  melt() |>\n  filter(name==\"N\") |>\n  select(-name) |>\n  pivot_wider(names_from=.id) |>\n  left_join(\n    x |> melt() |> filter(name==\"N\") |>\n      select(-name) |> rename(x=value),\n    by=\"time\"\n  ) |>\n  pivot_longer(cols=-c(time,x)) |>\n  mutate(\n    name=as.integer(name),\n    log.r=log(p[\"r\",name])\n  ) |> \n  ggplot(aes(x=x,y=value,color=factor(signif(log.r,3))))+\n  geom_line()+\n  labs(y=expression(N[t+1]),x=expression(N[t]),color=expression(log(r)))+\n  theme_classic()\n\nskeleton(ricker,params=parmat(coef(ricker),3)) -> dx\nstopifnot(dim(dx)==c(2,3,500))\n\ntry(skeleton(x=x,times=time(ricker),params=p))\ntry(skeleton(\"ricker\",x=x,times=time(ricker),params=p))\n\nsir() -> sir\np <- parmat(coef(sir),nrep=3)\np[\"beta2\",2:3] <- exp(c(3,5))\ntrajectory(sir,params=p,times=seq(0,1,length=1000),format=\"a\") -> tj\nskeleton(sir,x=tj,params=p,times=seq(0,1,length=1000)) -> f\ntj |> apply(c(1,2),diff) |> melt() |> rename(diff=value) |>\n  mutate(.id=as.integer(.id)) -> dtj\nf |>\n  melt() |>\n  rename(deriv=value) |>\n  right_join(\n    dtj,\n    by=c(\"time\",\"name\",\".id\")\n  ) |>\n  filter(name %in% c(\"S\",\"I\",\"R\")) |>\n  mutate(name=factor(name,levels=c(\"S\",\"I\",\"R\"))) |>\n  ggplot(aes(x=deriv,y=diff/0.001,color=factor(.id)))+\n  geom_point()+\n  geom_abline(intercept=0,slope=1,color=\"black\")+\n  facet_grid(.id~name,labeller=labeller(.id=label_both))+\n  guides(color=\"none\")+\n  labs(x=\"derivative\",y=\"finite difference\")+\n  theme_bw()\n\ntry(ricker |> pomp(skeleton=map(function(...)c(5))) |>\n    skeleton(x=x,times=time(ricker),params=coef(ricker)))\ntry(ricker |> pomp(skeleton=map(function(...)c(5,3))) |>\n    skeleton(x=x,times=time(ricker),params=coef(ricker)))\nricker |> skeleton(x=x,times=time(ricker),params=parmat(coef(ricker),2)) -> xx\ntry(ricker |> skeleton(x=xx,times=time(ricker),params=parmat(coef(ricker),3)))\ntry(ricker |> skeleton(x=xx,times=time(ricker)[1:5],params=parmat(coef(ricker),2)))\n\nstopifnot(\n  ricker |> pomp(skeleton=NULL) |>\n    skeleton(x=x,times=time(ricker),params=coef(ricker)) |>\n    is.na()\n)\n\ntry(ricker |> pomp(skeleton=map(function(...)1,delta.t=-5)))\ntry(ricker |> pomp(skeleton=map(function(...)1,delta.t=NA)))\ntry(ricker |> pomp(skeleton=map(function(...)1,delta.t=c(1,2,3))))\ntry(ricker |> pomp(skeleton=map(function(...)1,delta.t=NULL)))\ntry(ricker |> pomp(skeleton=map(function(...)1,delta.t=Inf)))\n\ndev.off()\n"
  },
  {
    "path": "tests/skeleton.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"skeleton-%02d.png\",res=100)\n> \n> library(pomp)\n> suppressPackageStartupMessages({\n+   library(ggplot2)\n+   library(dplyr)\n+   library(tidyr)\n+ })\n> \n> ricker() -> ricker\n> \n> ricker <- simulate(ricker,times=1:500,seed=366829807L)\n> x <- states(ricker)\n> p <- parmat(coef(ricker),3)\n> p[\"r\",] <- exp(c(1,2,4))\n> f <- skeleton(ricker,x=x,params=p,times=time(ricker))\n> f |>\n+   melt() |>\n+   filter(name==\"N\") |>\n+   select(-name) |>\n+   pivot_wider(names_from=.id) |>\n+   left_join(\n+     x |> melt() |> filter(name==\"N\") |>\n+       select(-name) |> rename(x=value),\n+     by=\"time\"\n+   ) |>\n+   pivot_longer(cols=-c(time,x)) |>\n+   mutate(\n+     name=as.integer(name),\n+     log.r=log(p[\"r\",name])\n+   ) |> \n+   ggplot(aes(x=x,y=value,color=factor(signif(log.r,3))))+\n+   geom_line()+\n+   labs(y=expression(N[t+1]),x=expression(N[t]),color=expression(log(r)))+\n+   theme_classic()\n> \n> skeleton(ricker,params=parmat(coef(ricker),3)) -> dx\n> stopifnot(dim(dx)==c(2,3,500))\n> \n> try(skeleton(x=x,times=time(ricker),params=p))\nError : in 'skeleton': 'object' is a required argument.\n> try(skeleton(\"ricker\",x=x,times=time(ricker),params=p))\nError : 'skeleton' is undefined for 'object' of class 'character'.\n> \n> sir() -> sir\n> p <- parmat(coef(sir),nrep=3)\n> p[\"beta2\",2:3] <- exp(c(3,5))\n> trajectory(sir,params=p,times=seq(0,1,length=1000),format=\"a\") -> tj\n> skeleton(sir,x=tj,params=p,times=seq(0,1,length=1000)) -> f\n> tj |> apply(c(1,2),diff) |> melt() |> rename(diff=value) |>\n+   mutate(.id=as.integer(.id)) -> dtj\n> f |>\n+   melt() |>\n+   rename(deriv=value) |>\n+   right_join(\n+     dtj,\n+     by=c(\"time\",\"name\",\".id\")\n+   ) |>\n+   filter(name %in% c(\"S\",\"I\",\"R\")) |>\n+   mutate(name=factor(name,levels=c(\"S\",\"I\",\"R\"))) |>\n+   ggplot(aes(x=deriv,y=diff/0.001,color=factor(.id)))+\n+   geom_point()+\n+   geom_abline(intercept=0,slope=1,color=\"black\")+\n+   facet_grid(.id~name,labeller=labeller(.id=label_both))+\n+   guides(color=\"none\")+\n+   labs(x=\"derivative\",y=\"finite difference\")+\n+   theme_bw()\n> \n> try(ricker |> pomp(skeleton=map(function(...)c(5))) |>\n+     skeleton(x=x,times=time(ricker),params=coef(ricker)))\nError : in 'skeleton': 'skeleton' returns a vector of 1 state variables but 2 are expected.\n> try(ricker |> pomp(skeleton=map(function(...)c(5,3))) |>\n+     skeleton(x=x,times=time(ricker),params=coef(ricker)))\nError : in 'skeleton': 'skeleton' must return a named numeric vector.\n> ricker |> skeleton(x=x,times=time(ricker),params=parmat(coef(ricker),2)) -> xx\n> try(ricker |> skeleton(x=xx,times=time(ricker),params=parmat(coef(ricker),3)))\nError : in 'skeleton': 2nd dimensions of 'x' and 'params' are incompatible\n> try(ricker |> skeleton(x=xx,times=time(ricker)[1:5],params=parmat(coef(ricker),2)))\nError : in 'skeleton': length of 'times' and 3rd dimension of 'x' do not agree.\n> \n> stopifnot(\n+   ricker |> pomp(skeleton=NULL) |>\n+     skeleton(x=x,times=time(ricker),params=coef(ricker)) |>\n+     is.na()\n+ )\nWarning message:\n'skeleton' unspecified: NAs generated. \n> \n> try(ricker |> pomp(skeleton=map(function(...)1,delta.t=-5)))\nError : in 'map': 'delta.t' must be a positive number.\n> try(ricker |> pomp(skeleton=map(function(...)1,delta.t=NA)))\nError : in 'map': 'delta.t' must be a positive number.\n> try(ricker |> pomp(skeleton=map(function(...)1,delta.t=c(1,2,3))))\nError : in 'map': 'delta.t' must be a positive number.\n> try(ricker |> pomp(skeleton=map(function(...)1,delta.t=NULL)))\nError : in 'map': 'delta.t' must be a positive number.\n> try(ricker |> pomp(skeleton=map(function(...)1,delta.t=Inf)))\nError : in 'map': 'delta.t' must be a positive number.\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/slice_design.R",
    "content": "png(filename=\"slice_design-%02d.png\",res=100)\n\nlibrary(pomp)\nlibrary(dplyr)\n\n## A single 11-point slice through the point c(A=3,B=8,C=0) along the B direction.\nx <- slice_design(center=c(A=3,B=8,C=0),B=seq(0,10,by=1))\nx |> count(slice) |> as.data.frame()\nplot(x)\n\n## Two slices through the same point along the A and C directions.\nx <- slice_design(c(A=3,B=8,C=0),A=seq(0,5,by=1),C=seq(0,5,length=11))\nx |> count(slice) |> as.data.frame()\nplot(x)\n\ntry(x <- slice_design(center=c(A=3,C=0),B=seq(0,10,by=1)))\ntry(x <- slice_design(center=c(A=3),B=seq(0,10,by=1),C=c(1,2,3)))\ntry(x <- slice_design(center=c(3),B=seq(0,10,by=1),C=c(1,2,3)))\ntry(x <- slice_design(center=c(A=\"3\"),B=seq(0,10,by=1),C=c(1,2,3)))\ntry(x <- slice_design(center=c(A=3,B=2),seq(1,3),A=seq(0,5)))\n\ndev.off()\n"
  },
  {
    "path": "tests/slice_design.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> png(filename=\"slice_design-%02d.png\",res=100)\n> \n> library(pomp)\n> library(dplyr)\n\nAttaching package: 'dplyr'\n\nThe following objects are masked from 'package:stats':\n\n    filter, lag\n\nThe following objects are masked from 'package:base':\n\n    intersect, setdiff, setequal, union\n\n> \n> ## A single 11-point slice through the point c(A=3,B=8,C=0) along the B direction.\n> x <- slice_design(center=c(A=3,B=8,C=0),B=seq(0,10,by=1))\n> x |> count(slice) |> as.data.frame()\n  slice  n\n1     B 11\n> plot(x)\n> \n> ## Two slices through the same point along the A and C directions.\n> x <- slice_design(c(A=3,B=8,C=0),A=seq(0,5,by=1),C=seq(0,5,length=11))\n> x |> count(slice) |> as.data.frame()\n  slice  n\n1     A  6\n2     C 11\n> plot(x)\n> \n> try(x <- slice_design(center=c(A=3,C=0),B=seq(0,10,by=1)))\nError : in 'slice_design': variable 'B' does not appear in 'center'\n> try(x <- slice_design(center=c(A=3),B=seq(0,10,by=1),C=c(1,2,3)))\nError : in 'slice_design': variables 'B','C' do not appear in 'center'\n> try(x <- slice_design(center=c(3),B=seq(0,10,by=1),C=c(1,2,3)))\nError : in 'slice_design': 'center' must be a named numeric vector\n> try(x <- slice_design(center=c(A=\"3\"),B=seq(0,10,by=1),C=c(1,2,3)))\nError : in 'slice_design': 'center' must be a named numeric vector\n> try(x <- slice_design(center=c(A=3,B=2),seq(1,3),A=seq(0,5)))\nError : in 'slice_design': cannot slice along an unnamed parameter.\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/sobol.R",
    "content": "png(filename=\"sobol-%02d.png\",res=100)\nlibrary(pomp)\n\n## Sobol' low-discrepancy design\nplot(sobol_design(lower=c(a=0,b=100),upper=c(b=200,a=1),100))\n\ntry(sobol_design(lower=c(a=0,b=100),upper=c(b=200,a=1,q=99),10))\ntry(sobol_design(lower=c(0,100),upper=c(b=200,a=1),10))\ntry(sobol_design(lower=c(a=0,b=100),upper=c(b=200,c=1),10))\n\ntry(sobol_design(lower=c(a=0,b=100),upper=c(b=200,a=1),2^30+1))\n\nrnames <- sprintf(\"n%04d\",1:5000)\ntry(sobol_design(lower=setNames(runif(5000),rnames),\n                upper=setNames(runif(5000,min=-1,max=0),rnames),\n                100))\nx <- sobol_design(lower=setNames(runif(15),head(rnames,15)),\n  upper=setNames(runif(15,min=1,max=2),head(rnames,15)),\n  100)\n\ndev.off()\n"
  },
  {
    "path": "tests/sobol.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> png(filename=\"sobol-%02d.png\",res=100)\n> library(pomp)\n> \n> ## Sobol' low-discrepancy design\n> plot(sobol_design(lower=c(a=0,b=100),upper=c(b=200,a=1),100))\n> \n> try(sobol_design(lower=c(a=0,b=100),upper=c(b=200,a=1,q=99),10))\nError : in 'sobol_design': 'lower' and 'upper' must have same length.\n> try(sobol_design(lower=c(0,100),upper=c(b=200,a=1),10))\nError : in 'sobol_design': 'lower' and 'upper' must be named vectors.\n> try(sobol_design(lower=c(a=0,b=100),upper=c(b=200,c=1),10))\nError : in 'sobol_design': names of 'lower' and 'upper' must match.\n> \n> try(sobol_design(lower=c(a=0,b=100),upper=c(b=200,a=1),2^30+1))\nError : in 'sobol_design': too many points requested.\n> \n> rnames <- sprintf(\"n%04d\",1:5000)\n> try(sobol_design(lower=setNames(runif(5000),rnames),\n+                 upper=setNames(runif(5000,min=-1,max=0),rnames),\n+                 100))\nError : in 'sobol_design': dimension is too high\n> x <- sobol_design(lower=setNames(runif(15),head(rnames,15)),\n+   upper=setNames(runif(15,min=1,max=2),head(rnames,15)),\n+   100)\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/spect.R",
    "content": "options(digits=3)\npng(filename=\"spect-%02d.png\",res=100)\n\nlibrary(pomp)\n\ngompertz() -> gompertz\nset.seed(362083261L)\n\nsp <- spect(gompertz,kernel.width=3,nsim=100,seed=838775L)\nsummary(sp)\nplot(sp)\n\nspect(sp,kernel.width=5,seed=838775L) -> sp2\nplot(sp2)\n\nspect(sp,detrend=\"mean\") -> sp3\nspect(sp,detrend=\"linear\") -> sp4\nspect(sp,detrend=\"quadratic\") -> sp5\n\ntheta <- as.list(coef(sp))\ntheta$r <- 25\nspect(sp,params=theta) -> sp4\nplot(sp4,quantiles=c(0.5,0.95))\nplot(sp4,plot.data=FALSE,quantile.styles=list(col=1:5))\nplot(sp4,plot.data=FALSE,quantile.styles=list(col=\"grey10\",lty=1:5))\nplot(sp4,plot.data=FALSE,quantile.styles=list(col=\"grey10\",lty=1:3))\ntry(plot(sp4,plot.data=FALSE,quantile.styles=c(col=\"grey10\",lty=1:3)))\nplot(sp4,plot.data=TRUE,data.styles=list(col=\"red\",lty=1))\ntry(plot(sp4,plot.data=TRUE,data.styles=c(col=\"red\",lty=1)))\n\ntry(spect())\ntry(spect(\"bob\"))\n\ntry(spect(sp,kernel.width=-3))\ntry(spect(sp,kernel.width=NA))\ntry(spect(sp,kernel.width=NULL))\n\ntry(spect(sp,nsim=-100))\ntry(spect(sp,nsim=Inf))\ntry(spect(sp,nsim=NULL))\n\nsp4@data[17] <- NA\ntry(spect(sp4))\n\ntry(spect(sp3,rmeasure=function(t,X,...){\n  if (t==13) c(Y=NA) else c(Y=X)\n}))\n\ntime(sp3) <- c(0:7,10:40)\ntry(spect(sp3))\n\ntry(spect(sp2,rmeasure=function(...) stop(\"yikes!\")))\n\nsimulate(times=1:100,t0=0,\n  rprocess=euler(Csnippet(\"\n       x = rnorm(0,1);\n       y = rnorm(0,1);\n       z = rnorm(0,1);\"),\n    delta.t=1),\n  rmeasure=Csnippet(\"\n       a = rnorm(x,1);\n       b = rnorm(y,1);\n       c = rnorm(z,1);\"),\n  rinit=Csnippet(\"x = y = z = 0;\"),\n  obsnames=c(\"a\",\"b\",\"c\"),\n  statenames=c(\"x\",\"y\",\"z\"),\n  params=c()) -> bob\n\nplot(spect(bob,kernel.width=3,nsim=500),\n  data.styles=list(lwd=c(2,3),lty=2,col=\"red\"))\n\ntry({bob |> simulate(times=c(1:5,8:10)) |>\n    spect(kernel.width=3,nsim=10)})\n\ncount <- 0\nbad.transform <- function (y) {\n  count <<- count+1\n  if (count>3) rep(NA_real_,length(y)) else y\n}\ntry(bob |> spect(transform.data=bad.transform,kernel.width=3,nsim=100))\n\ndev.off()\n"
  },
  {
    "path": "tests/spect.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"spect-%02d.png\",res=100)\n> \n> library(pomp)\n> \n> gompertz() -> gompertz\n> set.seed(362083261L)\n> \n> sp <- spect(gompertz,kernel.width=3,nsim=100,seed=838775L)\n> summary(sp)\n$coef\n    K     r sigma   tau   X_0 \n  1.0   0.1   0.1   0.1   1.0 \n\n$nsim\n[1] 100\n\n$pvals\n    Y   all \n0.554 0.554 \n\n> plot(sp)\n> \n> spect(sp,kernel.width=5,seed=838775L) -> sp2\n> plot(sp2)\n> \n> spect(sp,detrend=\"mean\") -> sp3\n> spect(sp,detrend=\"linear\") -> sp4\n> spect(sp,detrend=\"quadratic\") -> sp5\n> \n> theta <- as.list(coef(sp))\n> theta$r <- 25\n> spect(sp,params=theta) -> sp4\n> plot(sp4,quantiles=c(0.5,0.95))\n> plot(sp4,plot.data=FALSE,quantile.styles=list(col=1:5))\n> plot(sp4,plot.data=FALSE,quantile.styles=list(col=\"grey10\",lty=1:5))\n> plot(sp4,plot.data=FALSE,quantile.styles=list(col=\"grey10\",lty=1:3))\nWarning message:\nin 'plot': 'quantile.styles' contains an element with more than 1 entry but fewer entries than quantiles. \n> try(plot(sp4,plot.data=FALSE,quantile.styles=c(col=\"grey10\",lty=1:3)))\nError : in 'plot': 'quantile.styles' must be a list.\n> plot(sp4,plot.data=TRUE,data.styles=list(col=\"red\",lty=1))\n> try(plot(sp4,plot.data=TRUE,data.styles=c(col=\"red\",lty=1)))\nError : in 'plot': 'data.styles' must be a list\n> \n> try(spect())\nError : in 'spect': 'data' is a required argument.\n> try(spect(\"bob\"))\nError : 'spect' is undefined for 'data' of class 'character'.\n> \n> try(spect(sp,kernel.width=-3))\nError : in 'spect': 'kernel.width' must be a positive integer.\n> try(spect(sp,kernel.width=NA))\nError : in 'spect': 'kernel.width' must be a positive integer.\n> try(spect(sp,kernel.width=NULL))\nError : in 'spect': 'kernel.width' must be a positive integer.\n> \n> try(spect(sp,nsim=-100))\nError : in 'spect': 'nsim' must be a positive integer.\n> try(spect(sp,nsim=Inf))\nError : in 'spect': 'nsim' must be a positive integer.\n> try(spect(sp,nsim=NULL))\nError : in 'spect': 'nsim' must be a positive integer.\n> \n> sp4@data[17] <- NA\n> try(spect(sp4))\nError : in 'spect': missing or infinite values in the data.\n> \n> try(spect(sp3,rmeasure=function(t,X,...){\n+   if (t==13) c(Y=NA) else c(Y=X)\n+ }))\nError : in 'spect': missing or infinite values in simulated data.\n> \n> time(sp3) <- c(0:7,10:40)\n> try(spect(sp3))\nError : in 'spect': missing or infinite values in the data.\n> \n> try(spect(sp2,rmeasure=function(...) stop(\"yikes!\")))\nError : in 'spect': in simulation: yikes!\n> \n> simulate(times=1:100,t0=0,\n+   rprocess=euler(Csnippet(\"\n+        x = rnorm(0,1);\n+        y = rnorm(0,1);\n+        z = rnorm(0,1);\"),\n+     delta.t=1),\n+   rmeasure=Csnippet(\"\n+        a = rnorm(x,1);\n+        b = rnorm(y,1);\n+        c = rnorm(z,1);\"),\n+   rinit=Csnippet(\"x = y = z = 0;\"),\n+   obsnames=c(\"a\",\"b\",\"c\"),\n+   statenames=c(\"x\",\"y\",\"z\"),\n+   params=c()) -> bob\n> \n> plot(spect(bob,kernel.width=3,nsim=500),\n+   data.styles=list(lwd=c(2,3),lty=2,col=\"red\"))\nWarning message:\nin 'plot': 'data.styles' contains an element with more than 1 entry but fewer entries than observed variables. \n> \n> try({bob |> simulate(times=c(1:5,8:10)) |>\n+     spect(kernel.width=3,nsim=10)})\nError : in 'spect': 'spect' assumes evenly spaced times.\n> \n> count <- 0\n> bad.transform <- function (y) {\n+   count <<- count+1\n+   if (count>3) rep(NA_real_,length(y)) else y\n+ }\n> try(bob |> spect(transform.data=bad.transform,kernel.width=3,nsim=100))\nError : in 'spect': in 'spec.pgram': missing values in object\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/spect_match.R",
    "content": "options(digits=3)\npng(filename=\"spect_match-%02d.png\",res=100)\n\nlibrary(pomp)\n\nou2() -> ou2\nou2 |> as.data.frame() |> subset(select=c(time,y1,y2)) -> dat\n\ntry(dat |> spect_objfun())\ntry(dat |> spect_objfun(times=\"time\",t0=0))\n\ndat |>\n  spect_objfun(\n    times=\"time\",t0=0,\n    rinit=ou2@rinit,\n    rprocess=ou2@rprocess,\n    rmeasure=ou2@rmeasure,\n    kernel.width=3,\n    params=coef(ou2),\n    nsim=100,\n    seed=5069977\n    ) -> f\n\nplot(f)\n\nf()\nstopifnot(f(0)==f(1))\nstopifnot(logLik(f)==-f(0))\n\nf |> spect_objfun(est=c(\"alpha_1\"),seed=580656309) -> f1\nplot(sapply(seq(0.3,1.2,by=0.1),f1),log=\"y\")\n\nf1(1.1)\nplot(spect(f1))\nlibrary(subplex)\nsubplex(fn=f1,par=0.4,control=list(reltol=1e-3)) -> out\nf1(out$par)\n\ntry(spect_objfun())\ntry(spect_objfun(\"bob\"))\ntry(spect_objfun(f1,est=\"harry\"))\n\nf1 |> as(\"spectd_pomp\") |> plot()\n\nf1 |> summary() |> names()\n\nf1 |> plot()\n\nf1 |> spect() |> plot()\n\nf1 |> as(\"pomp\")\nf1 |> as(\"data.frame\") |> names()\n\nf1 |> spect_objfun(fail.value=1e10) -> f2\n\ntry(spect_objfun(f2,weights=\"heavy\"))\ntry(spect_objfun(f2,weights=c(3,4,5)))\nspect_objfun(f2,weights=exp(-seq(0,1,length=50)))\ntry(spect_objfun(f2,weights=function(f)1-4*f))\ntry(spect_objfun(f2,weights=function(f)stop(\"oh no!\")))\nspect_objfun(f2,seed=5069977,weights=function(f)exp(-f/0.1)) -> f2\nsubplex(fn=f2,par=out$par,control=list(reltol=1e-3)) -> out\nf2(out$par)\nsummary(f2) |> names()\nplot(spect(f2))\n\nf2 |> probe(nsim=100,seed=639095851,\n  probes=list(probe_mean(\"y1\"),probe_mean(\"y2\"))) |>\n  plot()\n\ndev.off()\n"
  },
  {
    "path": "tests/spect_match.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"spect_match-%02d.png\",res=100)\n> \n> library(pomp)\n> \n> ou2() -> ou2\n> ou2 |> as.data.frame() |> subset(select=c(time,y1,y2)) -> dat\n> \n> try(dat |> spect_objfun())\nError : in 'spect_objfun': in 'spect': 'times' should either be a numeric vector of observation times or a single name identifying the column of data that represents the observation times.\n> try(dat |> spect_objfun(times=\"time\",t0=0))\nError : in 'spect_objfun': in 'spect': 'rprocess', 'rmeasure' are needed basic components.\n> \n> dat |>\n+   spect_objfun(\n+     times=\"time\",t0=0,\n+     rinit=ou2@rinit,\n+     rprocess=ou2@rprocess,\n+     rmeasure=ou2@rmeasure,\n+     kernel.width=3,\n+     params=coef(ou2),\n+     nsim=100,\n+     seed=5069977\n+     ) -> f\n> \n> plot(f)\n> \n> f()\n[1] 222\n> stopifnot(f(0)==f(1))\n> stopifnot(logLik(f)==-f(0))\n> \n> f |> spect_objfun(est=c(\"alpha_1\"),seed=580656309) -> f1\n> plot(sapply(seq(0.3,1.2,by=0.1),f1),log=\"y\")\n> \n> f1(1.1)\n[1] 4796\n> plot(spect(f1))\n> library(subplex)\n> subplex(fn=f1,par=0.4,control=list(reltol=1e-3)) -> out\n> f1(out$par)\n[1] 217\n> \n> try(spect_objfun())\nError : in 'spect_objfun': 'data' is a required argument.\n> try(spect_objfun(\"bob\"))\nError : 'spect_objfun' is undefined for 'data' of class 'character'.\n> try(spect_objfun(f1,est=\"harry\"))\nError : in 'spect_objfun': parameter 'harry' not found in 'params'\n> \n> f1 |> as(\"spectd_pomp\") |> plot()\n> \n> f1 |> summary() |> names()\n[1] \"coef\"  \"nsim\"  \"pvals\"\n> \n> f1 |> plot()\n> \n> f1 |> spect() |> plot()\n> \n> f1 |> as(\"pomp\")\n<object of class 'pomp'>\n> f1 |> as(\"data.frame\") |> names()\n[1] \"time\" \"y1\"   \"y2\"  \n> \n> f1 |> spect_objfun(fail.value=1e10) -> f2\n> \n> try(spect_objfun(f2,weights=\"heavy\"))\nError : in 'spect_objfun': 'weights' must be specified as a vector or as a function\n> try(spect_objfun(f2,weights=c(3,4,5)))\nError : in 'spect_objfun': if 'weights' is provided as a vector, it must have length 50\n> spect_objfun(f2,weights=exp(-seq(0,1,length=50)))\n<object of class 'spect_match_objfun'>\n> try(spect_objfun(f2,weights=function(f)1-4*f))\nError : in 'spect_objfun': 'weights' should be nonnegative and finite\n> try(spect_objfun(f2,weights=function(f)stop(\"oh no!\")))\nError : in 'spect_objfun': 'weights' function: oh no!\n> spect_objfun(f2,seed=5069977,weights=function(f)exp(-f/0.1)) -> f2\n> subplex(fn=f2,par=out$par,control=list(reltol=1e-3)) -> out\n> f2(out$par)\n[1] 83.6\n> summary(f2) |> names()\n[1] \"coef\"  \"nsim\"  \"pvals\"\n> plot(spect(f2))\n> \n> f2 |> probe(nsim=100,seed=639095851,\n+   probes=list(probe_mean(\"y1\"),probe_mean(\"y2\"))) |>\n+   plot()\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/spy.R",
    "content": "options(digits=3)\n\nlibrary(pomp)\n\ngompertz() -> po\n\npomp(po,partrans=NULL,userdata=list(bob=3),\n  covar=covariate_table(a=0:20,b=0:20,times=\"a\")) -> po1\nspy(po1)\n\npo1 |>\n  pomp(partrans=parameter_trans(log=\"r\"),params=NULL,\n    rinit=function(params,t0,...)params,\n    paramnames=\"r\",compile=FALSE,cfile=\"nancy\") -> po2\nspy(po2)\n\nsir() -> sir\nspy(sir)\n\nrw2() -> rw2\nspy(rw2)\n\nsir2() -> sir2\nspy(sir2)\n\ntry(spy())\ntry(spy(list()))\n\npomp(\n  data=NULL,\n  t0=0,times=1:10,\n  userdata=list(x0=as.double(1)),\n  params=c(x_0=1,a=22),\n  rinit=Csnippet(r\"{x = *get_userdata_double(\"x0\");}\"),\n  statenames=\"x\",\n  compile=FALSE\n) |>\n  spy()\n\npomp(\n  data=NULL,\n  t0=0,times=1:10,\n  userdata=list(x0=as.double(1)),\n  params=c(x_0=1,a=22),\n  globals=Csnippet(\"static double X0;\"),\n  rinit=Csnippet(r\"{x = X0;}\"),\n  rprocess=euler(Csnippet(r\"(x += rgammawn(0.1,dt);)\"),delta.t=0.1),\n  on_load=Csnippet(r\"{X0 = *get_userdata_double(\"x0\");}\"),\n  statenames=\"x\",\n  compile=FALSE\n) |>\n  spy()\n"
  },
  {
    "path": "tests/spy.Rout",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> \n> library(pomp)\n> \n> gompertz() -> po\n> \n> pomp(po,partrans=NULL,userdata=list(bob=3),\n+   covar=covariate_table(a=0:20,b=0:20,times=\"a\")) -> po1\nWarning message:\nin 'pomp': the supplied covariate times do not embrace the data times: covariates may be extrapolated. \n> spy(po1)\n==================\npomp object 'po1':\n\n- data:\n  - 100 records of 1 observable, recorded from t = 1 to 100 \n  - summary of data:\n       Y        \n Min.   :0.620  \n 1st Qu.:0.943  \n Median :1.106  \n Mean   :1.134  \n 3rd Qu.:1.325  \n Max.   :2.012  \n- zero time, t0 = 0\n- covariates: \n  - 21 records of 1 covariates, recorded from t = 0 to 20 \n  - summary of covariates:\n       b     \n Min.   : 0  \n 1st Qu.: 5  \n Median :10  \n Mean   :10  \n 3rd Qu.:15  \n Max.   :20  \n- initial state simulator, rinit: <default>\n- initial state density, dinit: <default>\n- process-model simulator, rprocess: discrete-time process-model simulator\n  - timestep = 1 \n  - step.fun: native function\n  - name: '_gompertz_step'\n  - dynamically loaded from: 'pomp'\n- process model density, dprocess: <default>\n- measurement model simulator, rmeasure: native function\n  - name: '_gompertz_normal_rmeasure'\n  - dynamically loaded from: 'pomp'\n- measurement model density, dmeasure: native function\n  - name: '_gompertz_normal_dmeasure'\n  - dynamically loaded from: 'pomp'\n- measurement model expectation, emeasure: native function\n  - name: '_gompertz_normal_emeasure'\n  - dynamically loaded from: 'pomp'\n- measurement model covariance, vmeasure: native function\n  - name: '_gompertz_normal_vmeasure'\n  - dynamically loaded from: 'pomp'\n- prior simulator, rprior: <default>\n- prior density, dprior: <default>\n- deterministic skeleton: map:\n  - timestep = 1 \n  - native function\n  - name: '_gompertz_skeleton'\n  - dynamically loaded from: 'pomp'\n- parameter vector:\n    K     r sigma   tau   X_0 \n  1.0   0.1   0.1   0.1   1.0 \n- extra user-defined variables:\n  - 'bob' (type 'double')\n\n\n> \n> po1 |>\n+   pomp(partrans=parameter_trans(log=\"r\"),params=NULL,\n+     rinit=function(params,t0,...)params,\n+     paramnames=\"r\",compile=FALSE,cfile=\"nancy\") -> po2\nWarning message:\nin 'pomp': the supplied covariate times do not embrace the data times: covariates may be extrapolated. \n> spy(po2)\n==================\npomp object 'po2':\n\n- data:\n  - 100 records of 1 observable, recorded from t = 1 to 100 \n  - summary of data:\n       Y        \n Min.   :0.620  \n 1st Qu.:0.943  \n Median :1.106  \n Mean   :1.134  \n 3rd Qu.:1.325  \n Max.   :2.012  \n- zero time, t0 = 0\n- covariates: \n  - 21 records of 1 covariates, recorded from t = 0 to 20 \n  - summary of covariates:\n       b     \n Min.   : 0  \n 1st Qu.: 5  \n Median :10  \n Mean   :10  \n 3rd Qu.:15  \n Max.   :20  \n- initial state simulator, rinit: R function\n  - definition: function (params, t0, ...) \nparams\n\n- initial state density, dinit: <default>\n- process-model simulator, rprocess: discrete-time process-model simulator\n  - timestep = 1 \n  - step.fun: native function\n  - name: '_gompertz_step'\n  - dynamically loaded from: 'pomp'\n- process model density, dprocess: <default>\n- measurement model simulator, rmeasure: native function\n  - name: '_gompertz_normal_rmeasure'\n  - dynamically loaded from: 'pomp'\n- measurement model density, dmeasure: native function\n  - name: '_gompertz_normal_dmeasure'\n  - dynamically loaded from: 'pomp'\n- measurement model expectation, emeasure: native function\n  - name: '_gompertz_normal_emeasure'\n  - dynamically loaded from: 'pomp'\n- measurement model covariance, vmeasure: native function\n  - name: '_gompertz_normal_vmeasure'\n  - dynamically loaded from: 'pomp'\n- prior simulator, rprior: <default>\n- prior density, dprior: <default>\n- deterministic skeleton: map:\n  - timestep = 1 \n  - native function\n  - name: '_gompertz_skeleton'\n  - dynamically loaded from: 'pomp'\n- parameter transformations:\n  - to estimation scale: native function\n  - name: '__pomp_to_trans'\n  - defined by a C snippet in library 'nancy'\n  - from estimation scale: native function\n  - name: '__pomp_from_trans'\n  - defined by a C snippet in library 'nancy'\n- parameter vector unspecified\n- extra user-defined variables:\n  - 'bob' (type 'double')\n\n- C snippet file  1 :\n\n\n/* pomp C snippet file: nancy */\n/* Time: 2025-11-23 10:49:50.882 -0500 */\n/* Salt: 0741617CE0040B36C024FF9F */\n\n#include <pomp.h>\n#include <R_ext/Rdynload.h> \n \n\n\n\n/* C snippet: 'toEst' */\n\n#define b (__covars[__covindex[0]])\n#define r (__p[__parindex[0]])\n#define T_r (__pt[__parindex[0]])\n \nvoid __pomp_to_trans (double *__pt, const double *__p, const int *__parindex) { \n  T_r = log(r); \n}\n \n\n#undef b\n#undef r\n#undef T_r\n\n/* C snippet: 'fromEst' */\n\n#define b (__covars[__covindex[0]])\n#define r (__p[__parindex[0]])\n#define T_r (__pt[__parindex[0]])\n \nvoid __pomp_from_trans (double *__p, const double *__pt, const int *__parindex) { \n  r = exp(T_r); \n}\n \n\n#undef b\n#undef r\n#undef T_r\nstatic int __pomp_load_stack = 0;\nvoid __pomp_load_stack_incr (void) {++__pomp_load_stack;}\nvoid __pomp_load_stack_decr (int *val) {*val = --__pomp_load_stack;} \n\n \nvoid R_init_nancy (DllInfo *info) {\n  R_RegisterCCallable(\"nancy\", \"__pomp_load_stack_incr\", (DL_FUNC) __pomp_load_stack_incr);\n  R_RegisterCCallable(\"nancy\", \"__pomp_load_stack_decr\", (DL_FUNC) __pomp_load_stack_decr);\n  R_RegisterCCallable(\"nancy\", \"__pomp_to_trans\", (DL_FUNC) __pomp_to_trans);\n  R_RegisterCCallable(\"nancy\", \"__pomp_from_trans\", (DL_FUNC) __pomp_from_trans);\n  \n\n}\n \n> \n> sir() -> sir\n> spy(sir)\n==================\npomp object 'sir':\n\n- data:\n  - 208 records of 1 observable, recorded from t = 0.0192 to 4 \n  - summary of data:\n    reports    \n Min.   :  44  \n 1st Qu.: 151  \n Median : 246  \n Mean   : 448  \n 3rd Qu.: 645  \n Max.   :2183  \n- zero time, t0 = 0\n- covariates: \n  - 421 records of 3 covariates, recorded from t = 0 to 4.2 \n  - summary of covariates:\n     seas_1           seas_2           seas_3      \n Min.   :0.0417   Min.   :0.0417   Min.   :0.0417  \n 1st Qu.:0.1177   1st Qu.:0.1217   1st Qu.:0.0995  \n Median :0.3349   Median :0.3217   Median :0.2891  \n Mean   :0.3452   Mean   :0.3342   Mean   :0.3206  \n 3rd Qu.:0.5604   3rd Qu.:0.5387   3rd Qu.:0.5387  \n Max.   :0.6667   Max.   :0.6666   Max.   :0.6666  \n- initial state simulator, rinit: native function\n  - name: '__pomp_rinit'\n  - defined by a C snippet in library 'sir_source'\n- initial state density, dinit: <default>\n- process-model simulator, rprocess: Euler-method process-model simulator\n  - timestep = 0.000962 \n  - step.fun: native function\n  - name: '__pomp_stepfn'\n  - defined by a C snippet in library 'sir_source'\n- process model density, dprocess: <default>\n- measurement model simulator, rmeasure: native function\n  - name: '__pomp_rmeasure'\n  - defined by a C snippet in library 'sir_source'\n- measurement model density, dmeasure: native function\n  - name: '__pomp_dmeasure'\n  - defined by a C snippet in library 'sir_source'\n- measurement model expectation, emeasure: native function\n  - name: '__pomp_emeasure'\n  - defined by a C snippet in library 'sir_source'\n- measurement model covariance, vmeasure: native function\n  - name: '__pomp_vmeasure'\n  - defined by a C snippet in library 'sir_source'\n- prior simulator, rprior: <default>\n- prior density, dprior: <default>\n- deterministic skeleton: vectorfield:\n  - native function\n  - name: '__pomp_skelfn'\n  - defined by a C snippet in library 'sir_source'\n- parameter transformations:\n  - to estimation scale: native function\n  - name: '__pomp_to_trans'\n  - defined by a C snippet in library 'sir_source'\n  - from estimation scale: native function\n  - name: '__pomp_from_trans'\n  - defined by a C snippet in library 'sir_source'\n- parameter vector:\n   gamma       mu     iota    beta1    beta2    beta3  beta_sd      rho \n2.60e+01 2.00e-02 1.00e-02 4.00e+02 4.80e+02 3.20e+02 1.00e-03 6.00e-01 \n       k      pop      S_0      I_0      R_0 \n1.00e-01 2.10e+06 6.50e-02 1.00e-03 9.34e-01 \n\n- C snippet file  1 :\n\n\n/* pomp C snippet file: sir_source */\n/* Time: 2025-11-23 10:49:50.968 -0500 */\n/* Salt: 452BC0D2ACE64D635ECA6F1D */\n\n#include <pomp.h>\n#include <R_ext/Rdynload.h> \n\n      static int nbasis = 3; \n\n\n\n/* C snippet: 'rinit' */\n\n#define gamma (__p[__parindex[0]])\n#define mu (__p[__parindex[1]])\n#define iota (__p[__parindex[2]])\n#define beta1 (__p[__parindex[3]])\n#define beta_sd (__p[__parindex[4]])\n#define pop (__p[__parindex[5]])\n#define rho (__p[__parindex[6]])\n#define k (__p[__parindex[7]])\n#define S_0 (__p[__parindex[8]])\n#define I_0 (__p[__parindex[9]])\n#define R_0 (__p[__parindex[10]])\n#define seas_1 (__covars[__covindex[0]])\n#define seas_2 (__covars[__covindex[1]])\n#define seas_3 (__covars[__covindex[2]])\n#define S (__x[__stateindex[0]])\n#define I (__x[__stateindex[1]])\n#define R (__x[__stateindex[2]])\n#define cases (__x[__stateindex[3]])\n#define W (__x[__stateindex[4]])\n \nvoid __pomp_rinit (double *__x, const double *__p, double t,\n   const int *__stateindex, const int *__parindex, const int *__covindex,\n   const double *__covars) { \n      double m = pop/(S_0+I_0+R_0);\n      S = nearbyint(m*S_0);\n      I = nearbyint(m*I_0);\n      R = nearbyint(m*R_0);\n      cases = 0;\n      W = 0; \n}\n \n\n#undef gamma\n#undef mu\n#undef iota\n#undef beta1\n#undef beta_sd\n#undef pop\n#undef rho\n#undef k\n#undef S_0\n#undef I_0\n#undef R_0\n#undef seas_1\n#undef seas_2\n#undef seas_3\n#undef S\n#undef I\n#undef R\n#undef cases\n#undef W\n\n/* C snippet: 'step.fn' */\n\n#define gamma (__p[__parindex[0]])\n#define mu (__p[__parindex[1]])\n#define iota (__p[__parindex[2]])\n#define beta1 (__p[__parindex[3]])\n#define beta_sd (__p[__parindex[4]])\n#define pop (__p[__parindex[5]])\n#define rho (__p[__parindex[6]])\n#define k (__p[__parindex[7]])\n#define S_0 (__p[__parindex[8]])\n#define I_0 (__p[__parindex[9]])\n#define R_0 (__p[__parindex[10]])\n#define seas_1 (__covars[__covindex[0]])\n#define seas_2 (__covars[__covindex[1]])\n#define seas_3 (__covars[__covindex[2]])\n#define S (__x[__stateindex[0]])\n#define I (__x[__stateindex[1]])\n#define R (__x[__stateindex[2]])\n#define cases (__x[__stateindex[3]])\n#define W (__x[__stateindex[4]])\n \nvoid __pomp_stepfn (double *__x, const double *__p, const int *__stateindex,\n  const int *__parindex, const int *__covindex, const double *__covars,\n  double t, double dt) { \n        int nrate = 6;\n        double rate[nrate];               // transition rates\n        double trans[nrate];            // transition numbers\n        double beta;\n        double dW;\n\n        beta = dot_product(nbasis,&beta1,&seas_1);\n\n        // gamma noise, mean=dt, variance=(beta_sd^2 dt)\n        dW = rgammawn(beta_sd,dt);\n\n        // compute the transition rates\n        rate[0] = mu*pop;               // birth into susceptible class\n        rate[1] = (iota+beta*I*dW/dt)/pop; // force of infection\n        rate[2] = mu;                   // death from susceptible class\n        rate[3] = gamma;        // recovery\n        rate[4] = mu;                   // death from infectious class\n        rate[5] = mu;           // death from recovered class\n\n        // compute the transition numbers\n        trans[0] = rpois(rate[0]*dt);   // births are Poisson\n        reulermultinom(2,S,&rate[1],dt,&trans[1]);\n        reulermultinom(2,I,&rate[3],dt,&trans[3]);\n        reulermultinom(1,R,&rate[5],dt,&trans[5]);\n\n        // balance the equations\n        S += trans[0]-trans[1]-trans[2];\n        I += trans[1]-trans[3]-trans[4];\n        R += trans[3]-trans[5];\n        cases += trans[3];              // cases are cumulative recoveries\n        if (beta_sd > 0.0)  W += (dW-dt)/beta_sd; \n}\n \n\n#undef gamma\n#undef mu\n#undef iota\n#undef beta1\n#undef beta_sd\n#undef pop\n#undef rho\n#undef k\n#undef S_0\n#undef I_0\n#undef R_0\n#undef seas_1\n#undef seas_2\n#undef seas_3\n#undef S\n#undef I\n#undef R\n#undef cases\n#undef W\n\n/* C snippet: 'rmeasure' */\n\n#define gamma (__p[__parindex[0]])\n#define mu (__p[__parindex[1]])\n#define iota (__p[__parindex[2]])\n#define beta1 (__p[__parindex[3]])\n#define beta_sd (__p[__parindex[4]])\n#define pop (__p[__parindex[5]])\n#define rho (__p[__parindex[6]])\n#define k (__p[__parindex[7]])\n#define S_0 (__p[__parindex[8]])\n#define I_0 (__p[__parindex[9]])\n#define R_0 (__p[__parindex[10]])\n#define seas_1 (__covars[__covindex[0]])\n#define seas_2 (__covars[__covindex[1]])\n#define seas_3 (__covars[__covindex[2]])\n#define S (__x[__stateindex[0]])\n#define I (__x[__stateindex[1]])\n#define R (__x[__stateindex[2]])\n#define cases (__x[__stateindex[3]])\n#define W (__x[__stateindex[4]])\n#define reports (__y[__obsindex[0]])\n \nvoid __pomp_rmeasure (double *__y, const double *__x, const double *__p,\n  const int *__obsindex, const int *__stateindex, const int *__parindex,\n  const int *__covindex, const double *__covars, double t) { \n      reports = rnbinom_mu(1.0/k,cases*rho); \n}\n \n\n#undef gamma\n#undef mu\n#undef iota\n#undef beta1\n#undef beta_sd\n#undef pop\n#undef rho\n#undef k\n#undef S_0\n#undef I_0\n#undef R_0\n#undef seas_1\n#undef seas_2\n#undef seas_3\n#undef S\n#undef I\n#undef R\n#undef cases\n#undef W\n#undef reports\n\n/* C snippet: 'dmeasure' */\n\n#define gamma (__p[__parindex[0]])\n#define mu (__p[__parindex[1]])\n#define iota (__p[__parindex[2]])\n#define beta1 (__p[__parindex[3]])\n#define beta_sd (__p[__parindex[4]])\n#define pop (__p[__parindex[5]])\n#define rho (__p[__parindex[6]])\n#define k (__p[__parindex[7]])\n#define S_0 (__p[__parindex[8]])\n#define I_0 (__p[__parindex[9]])\n#define R_0 (__p[__parindex[10]])\n#define seas_1 (__covars[__covindex[0]])\n#define seas_2 (__covars[__covindex[1]])\n#define seas_3 (__covars[__covindex[2]])\n#define S (__x[__stateindex[0]])\n#define I (__x[__stateindex[1]])\n#define R (__x[__stateindex[2]])\n#define cases (__x[__stateindex[3]])\n#define W (__x[__stateindex[4]])\n#define reports (__y[__obsindex[0]])\n#define lik (__lik[0])\n \nvoid __pomp_dmeasure (double *__lik, const double *__y, const double *__x,\n  const double *__p, int give_log, const int *__obsindex,\n  const int *__stateindex, const int *__parindex, const int *__covindex,\n  const double *__covars, double t) { \n      lik = dnbinom_mu(nearbyint(reports),1.0/k,cases*rho,give_log); \n}\n \n\n#undef gamma\n#undef mu\n#undef iota\n#undef beta1\n#undef beta_sd\n#undef pop\n#undef rho\n#undef k\n#undef S_0\n#undef I_0\n#undef R_0\n#undef seas_1\n#undef seas_2\n#undef seas_3\n#undef S\n#undef I\n#undef R\n#undef cases\n#undef W\n#undef reports\n#undef lik\n\n/* C snippet: 'emeasure' */\n\n#define gamma (__p[__parindex[0]])\n#define mu (__p[__parindex[1]])\n#define iota (__p[__parindex[2]])\n#define beta1 (__p[__parindex[3]])\n#define beta_sd (__p[__parindex[4]])\n#define pop (__p[__parindex[5]])\n#define rho (__p[__parindex[6]])\n#define k (__p[__parindex[7]])\n#define S_0 (__p[__parindex[8]])\n#define I_0 (__p[__parindex[9]])\n#define R_0 (__p[__parindex[10]])\n#define seas_1 (__covars[__covindex[0]])\n#define seas_2 (__covars[__covindex[1]])\n#define seas_3 (__covars[__covindex[2]])\n#define S (__x[__stateindex[0]])\n#define I (__x[__stateindex[1]])\n#define R (__x[__stateindex[2]])\n#define cases (__x[__stateindex[3]])\n#define W (__x[__stateindex[4]])\n#define E_reports (__f[__obsindex[0]])\n \nvoid __pomp_emeasure (double *__f, const double *__x, const double *__p,\n  const int *__obsindex, const int *__stateindex, const int *__parindex,\n  const int *__covindex, const double *__covars, double t) { \n      E_reports = cases*rho; \n}\n \n\n#undef gamma\n#undef mu\n#undef iota\n#undef beta1\n#undef beta_sd\n#undef pop\n#undef rho\n#undef k\n#undef S_0\n#undef I_0\n#undef R_0\n#undef seas_1\n#undef seas_2\n#undef seas_3\n#undef S\n#undef I\n#undef R\n#undef cases\n#undef W\n#undef E_reports\n\n/* C snippet: 'vmeasure' */\n\n#define gamma (__p[__parindex[0]])\n#define mu (__p[__parindex[1]])\n#define iota (__p[__parindex[2]])\n#define beta1 (__p[__parindex[3]])\n#define beta_sd (__p[__parindex[4]])\n#define pop (__p[__parindex[5]])\n#define rho (__p[__parindex[6]])\n#define k (__p[__parindex[7]])\n#define S_0 (__p[__parindex[8]])\n#define I_0 (__p[__parindex[9]])\n#define R_0 (__p[__parindex[10]])\n#define seas_1 (__covars[__covindex[0]])\n#define seas_2 (__covars[__covindex[1]])\n#define seas_3 (__covars[__covindex[2]])\n#define S (__x[__stateindex[0]])\n#define I (__x[__stateindex[1]])\n#define R (__x[__stateindex[2]])\n#define cases (__x[__stateindex[3]])\n#define W (__x[__stateindex[4]])\n#define V_reports_reports (__f[__vmatindex[0]])\n \nvoid __pomp_vmeasure (double *__f, const double *__x, const double *__p,\n  const int *__vmatindex, const int *__stateindex, const int *__parindex,\n  const int *__covindex, const double *__covars, int nobs, double t) { \n      double mean = cases*rho;\n      V_reports_reports = mean*(1+k*mean); \n}\n \n\n#undef gamma\n#undef mu\n#undef iota\n#undef beta1\n#undef beta_sd\n#undef pop\n#undef rho\n#undef k\n#undef S_0\n#undef I_0\n#undef R_0\n#undef seas_1\n#undef seas_2\n#undef seas_3\n#undef S\n#undef I\n#undef R\n#undef cases\n#undef W\n#undef V_reports_reports\n\n/* C snippet: 'toEst' */\n\n#define seas_1 (__covars[__covindex[0]])\n#define seas_2 (__covars[__covindex[1]])\n#define seas_3 (__covars[__covindex[2]])\n#define gamma (__p[__parindex[0]])\n#define mu (__p[__parindex[1]])\n#define iota (__p[__parindex[2]])\n#define beta1 (__p[__parindex[3]])\n#define beta_sd (__p[__parindex[4]])\n#define pop (__p[__parindex[5]])\n#define rho (__p[__parindex[6]])\n#define k (__p[__parindex[7]])\n#define S_0 (__p[__parindex[8]])\n#define I_0 (__p[__parindex[9]])\n#define R_0 (__p[__parindex[10]])\n#define T_gamma (__pt[__parindex[0]])\n#define T_mu (__pt[__parindex[1]])\n#define T_iota (__pt[__parindex[2]])\n#define T_beta1 (__pt[__parindex[3]])\n#define T_beta_sd (__pt[__parindex[4]])\n#define T_pop (__pt[__parindex[5]])\n#define T_rho (__pt[__parindex[6]])\n#define T_k (__pt[__parindex[7]])\n#define T_S_0 (__pt[__parindex[8]])\n#define T_I_0 (__pt[__parindex[9]])\n#define T_R_0 (__pt[__parindex[10]])\n \nvoid __pomp_to_trans (double *__pt, const double *__p, const int *__parindex) { \n        int j;\n        const double *BETA = &beta1;\n        double *TBETA = &T_beta1;\n        for (j = 0; j < nbasis; j++) TBETA[j] = log(BETA[j]);\n\n  T_gamma = log(gamma);\n  T_mu = log(mu);\n  T_iota = log(iota);\n  T_beta_sd = log(beta_sd);\n  T_k = log(k);\n  T_rho = logit(rho);\n  to_log_barycentric(&T_S_0,&S_0,3); \n}\n \n\n#undef seas_1\n#undef seas_2\n#undef seas_3\n#undef gamma\n#undef mu\n#undef iota\n#undef beta1\n#undef beta_sd\n#undef pop\n#undef rho\n#undef k\n#undef S_0\n#undef I_0\n#undef R_0\n#undef T_gamma\n#undef T_mu\n#undef T_iota\n#undef T_beta1\n#undef T_beta_sd\n#undef T_pop\n#undef T_rho\n#undef T_k\n#undef T_S_0\n#undef T_I_0\n#undef T_R_0\n\n/* C snippet: 'fromEst' */\n\n#define seas_1 (__covars[__covindex[0]])\n#define seas_2 (__covars[__covindex[1]])\n#define seas_3 (__covars[__covindex[2]])\n#define gamma (__p[__parindex[0]])\n#define mu (__p[__parindex[1]])\n#define iota (__p[__parindex[2]])\n#define beta1 (__p[__parindex[3]])\n#define beta_sd (__p[__parindex[4]])\n#define pop (__p[__parindex[5]])\n#define rho (__p[__parindex[6]])\n#define k (__p[__parindex[7]])\n#define S_0 (__p[__parindex[8]])\n#define I_0 (__p[__parindex[9]])\n#define R_0 (__p[__parindex[10]])\n#define T_gamma (__pt[__parindex[0]])\n#define T_mu (__pt[__parindex[1]])\n#define T_iota (__pt[__parindex[2]])\n#define T_beta1 (__pt[__parindex[3]])\n#define T_beta_sd (__pt[__parindex[4]])\n#define T_pop (__pt[__parindex[5]])\n#define T_rho (__pt[__parindex[6]])\n#define T_k (__pt[__parindex[7]])\n#define T_S_0 (__pt[__parindex[8]])\n#define T_I_0 (__pt[__parindex[9]])\n#define T_R_0 (__pt[__parindex[10]])\n \nvoid __pomp_from_trans (double *__p, const double *__pt, const int *__parindex) { \n        int j;\n        const double *TBETA = &T_beta1;\n        double *BETA = &beta1;\n        for (j = 0; j < nbasis; j++) BETA[j] = exp(TBETA[j]);\n\n  gamma = exp(T_gamma);\n  mu = exp(T_mu);\n  iota = exp(T_iota);\n  beta_sd = exp(T_beta_sd);\n  k = exp(T_k);\n  rho = expit(T_rho);\n  from_log_barycentric(&S_0,&T_S_0,3); \n}\n \n\n#undef seas_1\n#undef seas_2\n#undef seas_3\n#undef gamma\n#undef mu\n#undef iota\n#undef beta1\n#undef beta_sd\n#undef pop\n#undef rho\n#undef k\n#undef S_0\n#undef I_0\n#undef R_0\n#undef T_gamma\n#undef T_mu\n#undef T_iota\n#undef T_beta1\n#undef T_beta_sd\n#undef T_pop\n#undef T_rho\n#undef T_k\n#undef T_S_0\n#undef T_I_0\n#undef T_R_0\n\n/* C snippet: 'skeleton' */\n\n#define gamma (__p[__parindex[0]])\n#define mu (__p[__parindex[1]])\n#define iota (__p[__parindex[2]])\n#define beta1 (__p[__parindex[3]])\n#define beta_sd (__p[__parindex[4]])\n#define pop (__p[__parindex[5]])\n#define rho (__p[__parindex[6]])\n#define k (__p[__parindex[7]])\n#define S_0 (__p[__parindex[8]])\n#define I_0 (__p[__parindex[9]])\n#define R_0 (__p[__parindex[10]])\n#define seas_1 (__covars[__covindex[0]])\n#define seas_2 (__covars[__covindex[1]])\n#define seas_3 (__covars[__covindex[2]])\n#define S (__x[__stateindex[0]])\n#define I (__x[__stateindex[1]])\n#define R (__x[__stateindex[2]])\n#define cases (__x[__stateindex[3]])\n#define W (__x[__stateindex[4]])\n#define DS (__f[__stateindex[0]])\n#define DI (__f[__stateindex[1]])\n#define DR (__f[__stateindex[2]])\n#define Dcases (__f[__stateindex[3]])\n#define DW (__f[__stateindex[4]])\n \nvoid __pomp_skelfn (double *__f, const double *__x, const double *__p,\n  const int *__stateindex, const int *__parindex, const int *__covindex,\n  const double *__covars, double t) { \n      int nrate = 6;\n      double rate[nrate];                 // transition rates\n      double term[nrate];               // terms in the equations\n      double beta;\n      double dW;\n\n      beta = dot_product(nbasis,&beta1,&seas_1);\n\n      // compute the transition rates\n      rate[0] = mu*pop;         // birth into susceptible class\n      rate[1] = (iota+beta*I)/pop; // force of infection\n      rate[2] = mu;                     // death from susceptible class\n      rate[3] = gamma;  // recovery\n      rate[4] = mu;                     // death from infectious class\n      rate[5] = mu;             // death from recovered class\n\n      // compute the several terms\n      term[0] = rate[0];\n      term[1] = rate[1]*S;\n      term[2] = rate[2]*S;\n      term[3] = rate[3]*I;\n      term[4] = rate[4]*I;\n      term[5] = rate[5]*R;\n\n      // balance the equations\n      DS = term[0]-term[1]-term[2];\n      DI = term[1]-term[3]-term[4];\n      DR = term[3]-term[5];\n      Dcases = term[3];         // accumulate the new I->R transitions\n      DW = 0;                   // no noise, so no noise accumulation \n}\n \n\n#undef gamma\n#undef mu\n#undef iota\n#undef beta1\n#undef beta_sd\n#undef pop\n#undef rho\n#undef k\n#undef S_0\n#undef I_0\n#undef R_0\n#undef seas_1\n#undef seas_2\n#undef seas_3\n#undef S\n#undef I\n#undef R\n#undef cases\n#undef W\n#undef DS\n#undef DI\n#undef DR\n#undef Dcases\n#undef DW\nstatic int __pomp_load_stack = 0;\nvoid __pomp_load_stack_incr (void) {++__pomp_load_stack;}\nvoid __pomp_load_stack_decr (int *val) {*val = --__pomp_load_stack;} \n\n \nvoid R_init_sir_source (DllInfo *info) {\n  R_RegisterCCallable(\"sir_source\", \"__pomp_load_stack_incr\", (DL_FUNC) __pomp_load_stack_incr);\n  R_RegisterCCallable(\"sir_source\", \"__pomp_load_stack_decr\", (DL_FUNC) __pomp_load_stack_decr);\n  R_RegisterCCallable(\"sir_source\", \"__pomp_rinit\", (DL_FUNC) __pomp_rinit);\n  R_RegisterCCallable(\"sir_source\", \"__pomp_stepfn\", (DL_FUNC) __pomp_stepfn);\n  R_RegisterCCallable(\"sir_source\", \"__pomp_rmeasure\", (DL_FUNC) __pomp_rmeasure);\n  R_RegisterCCallable(\"sir_source\", \"__pomp_dmeasure\", (DL_FUNC) __pomp_dmeasure);\n  R_RegisterCCallable(\"sir_source\", \"__pomp_emeasure\", (DL_FUNC) __pomp_emeasure);\n  R_RegisterCCallable(\"sir_source\", \"__pomp_vmeasure\", (DL_FUNC) __pomp_vmeasure);\n  R_RegisterCCallable(\"sir_source\", \"__pomp_to_trans\", (DL_FUNC) __pomp_to_trans);\n  R_RegisterCCallable(\"sir_source\", \"__pomp_from_trans\", (DL_FUNC) __pomp_from_trans);\n  R_RegisterCCallable(\"sir_source\", \"__pomp_skelfn\", (DL_FUNC) __pomp_skelfn);\n  \n\n}\n \n> \n> rw2() -> rw2\n> spy(rw2)\n==================\npomp object 'rw2':\n\n- data:\n  - 100 records of 2 observables, recorded from t = 1 to 100 \n  - summary of data:\n       y1               y2         \n Min.   :-16.93   Min.   :-13.859  \n 1st Qu.:-11.45   1st Qu.: -4.569  \n Median : -4.15   Median : -1.744  \n Mean   : -5.81   Mean   : -0.925  \n 3rd Qu.: -1.30   3rd Qu.:  3.066  \n Max.   :  3.50   Max.   : 10.257  \n- zero time, t0 = 0\n- covariates: <none>\n- initial state simulator, rinit: <default>\n- initial state density, dinit: <default>\n- process-model simulator, rprocess: one-step process-model simulator\n  - step.fun: native function\n  - name: '__pomp_stepfn'\n  - defined by a C snippet in library 'rw2_source'\n- process model density, dprocess: native function\n  - name: '__pomp_dproc'\n  - defined by a C snippet in library 'rw2_source'\n- measurement model simulator, rmeasure: native function\n  - name: '__pomp_rmeasure'\n  - defined by a C snippet in library 'rw2_source'\n- measurement model density, dmeasure: native function\n  - name: '__pomp_dmeasure'\n  - defined by a C snippet in library 'rw2_source'\n- measurement model expectation, emeasure: native function\n  - name: '__pomp_emeasure'\n  - defined by a C snippet in library 'rw2_source'\n- measurement model covariance, vmeasure: native function\n  - name: '__pomp_vmeasure'\n  - defined by a C snippet in library 'rw2_source'\n- prior simulator, rprior: <default>\n- prior density, dprior: <default>\n- deterministic skeleton: <default>\n\n- parameter vector:\nx1_0 x2_0   s1   s2  tau \n   0    0    1    3    1 \n\n- C snippet file  1 :\n\n\n/* pomp C snippet file: rw2_source */\n/* Time: 2025-11-23 10:49:51.638 -0500 */\n/* Salt: E30E8AB737C0FB37014418C8 */\n\n#include <pomp.h>\n#include <R_ext/Rdynload.h> \n \n\n\n\n/* C snippet: 'step.fn' */\n\n#define s1 (__p[__parindex[0]])\n#define s2 (__p[__parindex[1]])\n#define tau (__p[__parindex[2]])\n#define x1 (__x[__stateindex[0]])\n#define x2 (__x[__stateindex[1]])\n \nvoid __pomp_stepfn (double *__x, const double *__p, const int *__stateindex,\n  const int *__parindex, const int *__covindex, const double *__covars,\n  double t, double dt) { \n        x1 = rnorm(x1,s1*sqrt(dt));\n        x2 = rnorm(x2,s2*sqrt(dt)); \n}\n \n\n#undef s1\n#undef s2\n#undef tau\n#undef x1\n#undef x2\n\n/* C snippet: 'dprocess' */\n\n#define s1 (__p[__parindex[0]])\n#define s2 (__p[__parindex[1]])\n#define tau (__p[__parindex[2]])\n#define x1_1 (__x1[__stateindex[0]])\n#define x2_1 (__x1[__stateindex[1]])\n#define x1_2 (__x2[__stateindex[0]])\n#define x2_2 (__x2[__stateindex[1]])\n#define loglik (__loglik[0])\n \nvoid __pomp_dproc (double *__loglik, const double *__x1, const double *__x2,\n  double t_1, double t_2, const double *__p, const int *__stateindex,\n  const int *__parindex, const int *__covindex, const double *__covars) { \n        double sdt = sqrt(t_2 - t_1);\n        loglik = dnorm(x1_2,x1_1,s1*sdt,1)+\n        dnorm(x2_2,x2_1,s2*sdt,1); \n}\n \n\n#undef s1\n#undef s2\n#undef tau\n#undef x1_1\n#undef x2_1\n#undef x1_2\n#undef x2_2\n#undef loglik\n\n/* C snippet: 'rmeasure' */\n\n#define s1 (__p[__parindex[0]])\n#define s2 (__p[__parindex[1]])\n#define tau (__p[__parindex[2]])\n#define x1 (__x[__stateindex[0]])\n#define x2 (__x[__stateindex[1]])\n#define y1 (__y[__obsindex[0]])\n#define y2 (__y[__obsindex[1]])\n \nvoid __pomp_rmeasure (double *__y, const double *__x, const double *__p,\n  const int *__obsindex, const int *__stateindex, const int *__parindex,\n  const int *__covindex, const double *__covars, double t) { \n        y1 = rnorm(x1,tau);\n        y2 = rnorm(x2,tau); \n}\n \n\n#undef s1\n#undef s2\n#undef tau\n#undef x1\n#undef x2\n#undef y1\n#undef y2\n\n/* C snippet: 'dmeasure' */\n\n#define s1 (__p[__parindex[0]])\n#define s2 (__p[__parindex[1]])\n#define tau (__p[__parindex[2]])\n#define x1 (__x[__stateindex[0]])\n#define x2 (__x[__stateindex[1]])\n#define y1 (__y[__obsindex[0]])\n#define y2 (__y[__obsindex[1]])\n#define lik (__lik[0])\n \nvoid __pomp_dmeasure (double *__lik, const double *__y, const double *__x,\n  const double *__p, int give_log, const int *__obsindex,\n  const int *__stateindex, const int *__parindex, const int *__covindex,\n  const double *__covars, double t) { \n        lik = dnorm(y1,x1,tau,1)+dnorm(y2,x2,tau,1);\n        lik = (give_log) ? lik : exp(lik); \n}\n \n\n#undef s1\n#undef s2\n#undef tau\n#undef x1\n#undef x2\n#undef y1\n#undef y2\n#undef lik\n\n/* C snippet: 'emeasure' */\n\n#define s1 (__p[__parindex[0]])\n#define s2 (__p[__parindex[1]])\n#define tau (__p[__parindex[2]])\n#define x1 (__x[__stateindex[0]])\n#define x2 (__x[__stateindex[1]])\n#define E_y1 (__f[__obsindex[0]])\n#define E_y2 (__f[__obsindex[1]])\n \nvoid __pomp_emeasure (double *__f, const double *__x, const double *__p,\n  const int *__obsindex, const int *__stateindex, const int *__parindex,\n  const int *__covindex, const double *__covars, double t) { \n        E_y1 = x1;\n        E_y2 = x2; \n}\n \n\n#undef s1\n#undef s2\n#undef tau\n#undef x1\n#undef x2\n#undef E_y1\n#undef E_y2\n\n/* C snippet: 'vmeasure' */\n\n#define s1 (__p[__parindex[0]])\n#define s2 (__p[__parindex[1]])\n#define tau (__p[__parindex[2]])\n#define x1 (__x[__stateindex[0]])\n#define x2 (__x[__stateindex[1]])\n#define V_y1_y1 (__f[__vmatindex[0]])\n#define V_y2_y1 (__f[__vmatindex[1]])\n#define V_y1_y2 (__f[__vmatindex[2]])\n#define V_y2_y2 (__f[__vmatindex[3]])\n \nvoid __pomp_vmeasure (double *__f, const double *__x, const double *__p,\n  const int *__vmatindex, const int *__stateindex, const int *__parindex,\n  const int *__covindex, const double *__covars, int nobs, double t) { \n        V_y1_y1 = V_y2_y2 = tau*tau;\n        V_y1_y2 = V_y2_y1 = 0; \n}\n \n\n#undef s1\n#undef s2\n#undef tau\n#undef x1\n#undef x2\n#undef V_y1_y1\n#undef V_y2_y1\n#undef V_y1_y2\n#undef V_y2_y2\nstatic int __pomp_load_stack = 0;\nvoid __pomp_load_stack_incr (void) {++__pomp_load_stack;}\nvoid __pomp_load_stack_decr (int *val) {*val = --__pomp_load_stack;} \n\n \nvoid R_init_rw2_source (DllInfo *info) {\n  R_RegisterCCallable(\"rw2_source\", \"__pomp_load_stack_incr\", (DL_FUNC) __pomp_load_stack_incr);\n  R_RegisterCCallable(\"rw2_source\", \"__pomp_load_stack_decr\", (DL_FUNC) __pomp_load_stack_decr);\n  R_RegisterCCallable(\"rw2_source\", \"__pomp_stepfn\", (DL_FUNC) __pomp_stepfn);\n  R_RegisterCCallable(\"rw2_source\", \"__pomp_dproc\", (DL_FUNC) __pomp_dproc);\n  R_RegisterCCallable(\"rw2_source\", \"__pomp_rmeasure\", (DL_FUNC) __pomp_rmeasure);\n  R_RegisterCCallable(\"rw2_source\", \"__pomp_dmeasure\", (DL_FUNC) __pomp_dmeasure);\n  R_RegisterCCallable(\"rw2_source\", \"__pomp_emeasure\", (DL_FUNC) __pomp_emeasure);\n  R_RegisterCCallable(\"rw2_source\", \"__pomp_vmeasure\", (DL_FUNC) __pomp_vmeasure);\n  \n\n}\n \n> \n> sir2() -> sir2\n> spy(sir2)\n==================\npomp object 'sir2':\n\n- data:\n  - 120 records of 1 observable, recorded from t = 0.0833 to 10 \n  - summary of data:\n    reports   \n Min.   :  0  \n 1st Qu.:  5  \n Median : 18  \n Mean   :110  \n 3rd Qu.:151  \n Max.   :876  \n- zero time, t0 = 0\n- covariates: \n  - 1021 records of 3 covariates, recorded from t = 0 to 10.2 \n  - summary of covariates:\n     seas_1           seas_2           seas_3      \n Min.   :0.0417   Min.   :0.0417   Min.   :0.0417  \n 1st Qu.:0.1177   1st Qu.:0.1139   1st Qu.:0.1029  \n Median :0.3349   Median :0.3217   Median :0.3020  \n Mean   :0.3382   Mean   :0.3337   Mean   :0.3281  \n 3rd Qu.:0.5604   3rd Qu.:0.5497   3rd Qu.:0.5497  \n Max.   :0.6667   Max.   :0.6666   Max.   :0.6666  \n- initial state simulator, rinit: native function\n  - name: '__pomp_rinit'\n  - defined by a C snippet in library 'sir2_source'\n- initial state density, dinit: <default>\n- process-model simulator, rprocess: Gillespie-method process-model simulator\n  - stoichiometry matrix:\n       event\nname    birth susc.death infection inf.death recovery recov.death\n  S         1         -1        -1         0        0           0\n  I         0          0         1        -1       -1           0\n  R         0          0         0         0        1          -1\n  N         1         -1         0        -1        0          -1\n  cases     0          0         0         0        1           0\n  - rate.fun: native function\n  - name: '__pomp_ratefn'\n  - defined by a C snippet in library 'sir2_source'\n- process model density, dprocess: <default>\n- measurement model simulator, rmeasure: native function\n  - name: '__pomp_rmeasure'\n  - defined by a C snippet in library 'sir2_source'\n- measurement model density, dmeasure: native function\n  - name: '__pomp_dmeasure'\n  - defined by a C snippet in library 'sir2_source'\n- measurement model expectation, emeasure: native function\n  - name: '__pomp_emeasure'\n  - defined by a C snippet in library 'sir2_source'\n- measurement model covariance, vmeasure: native function\n  - name: '__pomp_vmeasure'\n  - defined by a C snippet in library 'sir2_source'\n- prior simulator, rprior: <default>\n- prior density, dprior: <default>\n- deterministic skeleton: vectorfield:\n  - native function\n  - name: '__pomp_skelfn'\n  - defined by a C snippet in library 'sir2_source'\n- parameter transformations:\n  - to estimation scale: native function\n  - name: '__pomp_to_trans'\n  - defined by a C snippet in library 'sir2_source'\n  - from estimation scale: native function\n  - name: '__pomp_from_trans'\n  - defined by a C snippet in library 'sir2_source'\n- parameter vector:\n   gamma       mu     iota      rho        k    beta1    beta2    beta3 \n2.40e+01 1.43e-02 1.00e-01 1.00e-01 1.00e-01 3.30e+02 4.10e+02 4.90e+02 \n     S_0      I_0      R_0      pop \n5.00e-02 1.00e-04 9.50e-01 1.00e+06 \n\n- C snippet file  1 :\n\n\n/* pomp C snippet file: sir2_source */\n/* Time: 2025-11-23 10:49:52.162 -0500 */\n/* Salt: 77EBA13C4E4F8F8A7B2EAF7F */\n\n#include <pomp.h>\n#include <R_ext/Rdynload.h> \nstatic int nbasis = 3; \n\n\n\n/* C snippet: 'rinit' */\n\n#define gamma (__p[__parindex[0]])\n#define mu (__p[__parindex[1]])\n#define iota (__p[__parindex[2]])\n#define pop (__p[__parindex[3]])\n#define rho (__p[__parindex[4]])\n#define k (__p[__parindex[5]])\n#define beta1 (__p[__parindex[6]])\n#define beta2 (__p[__parindex[7]])\n#define beta3 (__p[__parindex[8]])\n#define S_0 (__p[__parindex[9]])\n#define I_0 (__p[__parindex[10]])\n#define R_0 (__p[__parindex[11]])\n#define seas_1 (__covars[__covindex[0]])\n#define seas_2 (__covars[__covindex[1]])\n#define seas_3 (__covars[__covindex[2]])\n#define S (__x[__stateindex[0]])\n#define I (__x[__stateindex[1]])\n#define R (__x[__stateindex[2]])\n#define N (__x[__stateindex[3]])\n#define cases (__x[__stateindex[4]])\n \nvoid __pomp_rinit (double *__x, const double *__p, double t,\n   const int *__stateindex, const int *__parindex, const int *__covindex,\n   const double *__covars) { \n      double m;\n      m = pop/(S_0+I_0+R_0);\n      S = nearbyint(m*S_0);\n      I = nearbyint(m*I_0);\n      N = nearbyint(pop);\n      R = nearbyint(m*R_0);\n      cases = 0; \n}\n \n\n#undef gamma\n#undef mu\n#undef iota\n#undef pop\n#undef rho\n#undef k\n#undef beta1\n#undef beta2\n#undef beta3\n#undef S_0\n#undef I_0\n#undef R_0\n#undef seas_1\n#undef seas_2\n#undef seas_3\n#undef S\n#undef I\n#undef R\n#undef N\n#undef cases\n\n/* C snippet: 'rate.fn' */\n\n#define gamma (__p[__parindex[0]])\n#define mu (__p[__parindex[1]])\n#define iota (__p[__parindex[2]])\n#define pop (__p[__parindex[3]])\n#define rho (__p[__parindex[4]])\n#define k (__p[__parindex[5]])\n#define beta1 (__p[__parindex[6]])\n#define beta2 (__p[__parindex[7]])\n#define beta3 (__p[__parindex[8]])\n#define S_0 (__p[__parindex[9]])\n#define I_0 (__p[__parindex[10]])\n#define R_0 (__p[__parindex[11]])\n#define seas_1 (__covars[__covindex[0]])\n#define seas_2 (__covars[__covindex[1]])\n#define seas_3 (__covars[__covindex[2]])\n#define S (__x[__stateindex[0]])\n#define I (__x[__stateindex[1]])\n#define R (__x[__stateindex[2]])\n#define N (__x[__stateindex[3]])\n#define cases (__x[__stateindex[4]])\n \ndouble __pomp_ratefn (int j, double t, double *__x, const double *__p,\n  const int *__stateindex, const int *__parindex, const int *__covindex,\n  const double *__covars) {\n  double rate = 0.0; double beta;\nswitch (j) {\ncase 1:\n{\nrate = mu*pop;\n}\nbreak;\n\ncase 2:\n{\nrate = mu*S;\n}\nbreak;\n\ncase 3:\n{\n\n      beta = dot_product(nbasis,&beta1,&seas_1);\n      rate = (beta*I+iota)*S/pop;\n}\nbreak;\n\ncase 4:\n{\nrate = mu*I;\n}\nbreak;\n\ncase 5:\n{\nrate = gamma*I;\n}\nbreak;\n\ncase 6:\n{\nrate = mu*R;\n}\nbreak;\n\ndefault:\nerror(\"unrecognized event %d\",j);\nbreak;\n}\n \n  return rate;\n} \n\n#undef gamma\n#undef mu\n#undef iota\n#undef pop\n#undef rho\n#undef k\n#undef beta1\n#undef beta2\n#undef beta3\n#undef S_0\n#undef I_0\n#undef R_0\n#undef seas_1\n#undef seas_2\n#undef seas_3\n#undef S\n#undef I\n#undef R\n#undef N\n#undef cases\n\n/* C snippet: 'rmeasure' */\n\n#define gamma (__p[__parindex[0]])\n#define mu (__p[__parindex[1]])\n#define iota (__p[__parindex[2]])\n#define pop (__p[__parindex[3]])\n#define rho (__p[__parindex[4]])\n#define k (__p[__parindex[5]])\n#define beta1 (__p[__parindex[6]])\n#define beta2 (__p[__parindex[7]])\n#define beta3 (__p[__parindex[8]])\n#define S_0 (__p[__parindex[9]])\n#define I_0 (__p[__parindex[10]])\n#define R_0 (__p[__parindex[11]])\n#define seas_1 (__covars[__covindex[0]])\n#define seas_2 (__covars[__covindex[1]])\n#define seas_3 (__covars[__covindex[2]])\n#define S (__x[__stateindex[0]])\n#define I (__x[__stateindex[1]])\n#define R (__x[__stateindex[2]])\n#define N (__x[__stateindex[3]])\n#define cases (__x[__stateindex[4]])\n#define reports (__y[__obsindex[0]])\n \nvoid __pomp_rmeasure (double *__y, const double *__x, const double *__p,\n  const int *__obsindex, const int *__stateindex, const int *__parindex,\n  const int *__covindex, const double *__covars, double t) { \n      reports = rnbinom_mu(1.0/k,cases*rho); \n}\n \n\n#undef gamma\n#undef mu\n#undef iota\n#undef pop\n#undef rho\n#undef k\n#undef beta1\n#undef beta2\n#undef beta3\n#undef S_0\n#undef I_0\n#undef R_0\n#undef seas_1\n#undef seas_2\n#undef seas_3\n#undef S\n#undef I\n#undef R\n#undef N\n#undef cases\n#undef reports\n\n/* C snippet: 'dmeasure' */\n\n#define gamma (__p[__parindex[0]])\n#define mu (__p[__parindex[1]])\n#define iota (__p[__parindex[2]])\n#define pop (__p[__parindex[3]])\n#define rho (__p[__parindex[4]])\n#define k (__p[__parindex[5]])\n#define beta1 (__p[__parindex[6]])\n#define beta2 (__p[__parindex[7]])\n#define beta3 (__p[__parindex[8]])\n#define S_0 (__p[__parindex[9]])\n#define I_0 (__p[__parindex[10]])\n#define R_0 (__p[__parindex[11]])\n#define seas_1 (__covars[__covindex[0]])\n#define seas_2 (__covars[__covindex[1]])\n#define seas_3 (__covars[__covindex[2]])\n#define S (__x[__stateindex[0]])\n#define I (__x[__stateindex[1]])\n#define R (__x[__stateindex[2]])\n#define N (__x[__stateindex[3]])\n#define cases (__x[__stateindex[4]])\n#define reports (__y[__obsindex[0]])\n#define lik (__lik[0])\n \nvoid __pomp_dmeasure (double *__lik, const double *__y, const double *__x,\n  const double *__p, int give_log, const int *__obsindex,\n  const int *__stateindex, const int *__parindex, const int *__covindex,\n  const double *__covars, double t) { \n      lik = dnbinom_mu(nearbyint(reports),1.0/k,cases*rho,give_log); \n}\n \n\n#undef gamma\n#undef mu\n#undef iota\n#undef pop\n#undef rho\n#undef k\n#undef beta1\n#undef beta2\n#undef beta3\n#undef S_0\n#undef I_0\n#undef R_0\n#undef seas_1\n#undef seas_2\n#undef seas_3\n#undef S\n#undef I\n#undef R\n#undef N\n#undef cases\n#undef reports\n#undef lik\n\n/* C snippet: 'emeasure' */\n\n#define gamma (__p[__parindex[0]])\n#define mu (__p[__parindex[1]])\n#define iota (__p[__parindex[2]])\n#define pop (__p[__parindex[3]])\n#define rho (__p[__parindex[4]])\n#define k (__p[__parindex[5]])\n#define beta1 (__p[__parindex[6]])\n#define beta2 (__p[__parindex[7]])\n#define beta3 (__p[__parindex[8]])\n#define S_0 (__p[__parindex[9]])\n#define I_0 (__p[__parindex[10]])\n#define R_0 (__p[__parindex[11]])\n#define seas_1 (__covars[__covindex[0]])\n#define seas_2 (__covars[__covindex[1]])\n#define seas_3 (__covars[__covindex[2]])\n#define S (__x[__stateindex[0]])\n#define I (__x[__stateindex[1]])\n#define R (__x[__stateindex[2]])\n#define N (__x[__stateindex[3]])\n#define cases (__x[__stateindex[4]])\n#define E_reports (__f[__obsindex[0]])\n \nvoid __pomp_emeasure (double *__f, const double *__x, const double *__p,\n  const int *__obsindex, const int *__stateindex, const int *__parindex,\n  const int *__covindex, const double *__covars, double t) { \n      E_reports = cases*rho; \n}\n \n\n#undef gamma\n#undef mu\n#undef iota\n#undef pop\n#undef rho\n#undef k\n#undef beta1\n#undef beta2\n#undef beta3\n#undef S_0\n#undef I_0\n#undef R_0\n#undef seas_1\n#undef seas_2\n#undef seas_3\n#undef S\n#undef I\n#undef R\n#undef N\n#undef cases\n#undef E_reports\n\n/* C snippet: 'vmeasure' */\n\n#define gamma (__p[__parindex[0]])\n#define mu (__p[__parindex[1]])\n#define iota (__p[__parindex[2]])\n#define pop (__p[__parindex[3]])\n#define rho (__p[__parindex[4]])\n#define k (__p[__parindex[5]])\n#define beta1 (__p[__parindex[6]])\n#define beta2 (__p[__parindex[7]])\n#define beta3 (__p[__parindex[8]])\n#define S_0 (__p[__parindex[9]])\n#define I_0 (__p[__parindex[10]])\n#define R_0 (__p[__parindex[11]])\n#define seas_1 (__covars[__covindex[0]])\n#define seas_2 (__covars[__covindex[1]])\n#define seas_3 (__covars[__covindex[2]])\n#define S (__x[__stateindex[0]])\n#define I (__x[__stateindex[1]])\n#define R (__x[__stateindex[2]])\n#define N (__x[__stateindex[3]])\n#define cases (__x[__stateindex[4]])\n#define V_reports_reports (__f[__vmatindex[0]])\n \nvoid __pomp_vmeasure (double *__f, const double *__x, const double *__p,\n  const int *__vmatindex, const int *__stateindex, const int *__parindex,\n  const int *__covindex, const double *__covars, int nobs, double t) { \n      double mean = cases*rho;\n      V_reports_reports = mean*(1+k*mean); \n}\n \n\n#undef gamma\n#undef mu\n#undef iota\n#undef pop\n#undef rho\n#undef k\n#undef beta1\n#undef beta2\n#undef beta3\n#undef S_0\n#undef I_0\n#undef R_0\n#undef seas_1\n#undef seas_2\n#undef seas_3\n#undef S\n#undef I\n#undef R\n#undef N\n#undef cases\n#undef V_reports_reports\n\n/* C snippet: 'toEst' */\n\n#define seas_1 (__covars[__covindex[0]])\n#define seas_2 (__covars[__covindex[1]])\n#define seas_3 (__covars[__covindex[2]])\n#define gamma (__p[__parindex[0]])\n#define mu (__p[__parindex[1]])\n#define iota (__p[__parindex[2]])\n#define pop (__p[__parindex[3]])\n#define rho (__p[__parindex[4]])\n#define k (__p[__parindex[5]])\n#define beta1 (__p[__parindex[6]])\n#define beta2 (__p[__parindex[7]])\n#define beta3 (__p[__parindex[8]])\n#define S_0 (__p[__parindex[9]])\n#define I_0 (__p[__parindex[10]])\n#define R_0 (__p[__parindex[11]])\n#define T_gamma (__pt[__parindex[0]])\n#define T_mu (__pt[__parindex[1]])\n#define T_iota (__pt[__parindex[2]])\n#define T_pop (__pt[__parindex[3]])\n#define T_rho (__pt[__parindex[4]])\n#define T_k (__pt[__parindex[5]])\n#define T_beta1 (__pt[__parindex[6]])\n#define T_beta2 (__pt[__parindex[7]])\n#define T_beta3 (__pt[__parindex[8]])\n#define T_S_0 (__pt[__parindex[9]])\n#define T_I_0 (__pt[__parindex[10]])\n#define T_R_0 (__pt[__parindex[11]])\n \nvoid __pomp_to_trans (double *__pt, const double *__p, const int *__parindex) { \n  T_gamma = log(gamma);\n  T_mu = log(mu);\n  T_iota = log(iota);\n  T_k = log(k);\n  T_beta1 = log(beta1);\n  T_beta2 = log(beta2);\n  T_beta3 = log(beta3);\n  T_rho = logit(rho);\n  to_log_barycentric(&T_S_0,&S_0,3); \n}\n \n\n#undef seas_1\n#undef seas_2\n#undef seas_3\n#undef gamma\n#undef mu\n#undef iota\n#undef pop\n#undef rho\n#undef k\n#undef beta1\n#undef beta2\n#undef beta3\n#undef S_0\n#undef I_0\n#undef R_0\n#undef T_gamma\n#undef T_mu\n#undef T_iota\n#undef T_pop\n#undef T_rho\n#undef T_k\n#undef T_beta1\n#undef T_beta2\n#undef T_beta3\n#undef T_S_0\n#undef T_I_0\n#undef T_R_0\n\n/* C snippet: 'fromEst' */\n\n#define seas_1 (__covars[__covindex[0]])\n#define seas_2 (__covars[__covindex[1]])\n#define seas_3 (__covars[__covindex[2]])\n#define gamma (__p[__parindex[0]])\n#define mu (__p[__parindex[1]])\n#define iota (__p[__parindex[2]])\n#define pop (__p[__parindex[3]])\n#define rho (__p[__parindex[4]])\n#define k (__p[__parindex[5]])\n#define beta1 (__p[__parindex[6]])\n#define beta2 (__p[__parindex[7]])\n#define beta3 (__p[__parindex[8]])\n#define S_0 (__p[__parindex[9]])\n#define I_0 (__p[__parindex[10]])\n#define R_0 (__p[__parindex[11]])\n#define T_gamma (__pt[__parindex[0]])\n#define T_mu (__pt[__parindex[1]])\n#define T_iota (__pt[__parindex[2]])\n#define T_pop (__pt[__parindex[3]])\n#define T_rho (__pt[__parindex[4]])\n#define T_k (__pt[__parindex[5]])\n#define T_beta1 (__pt[__parindex[6]])\n#define T_beta2 (__pt[__parindex[7]])\n#define T_beta3 (__pt[__parindex[8]])\n#define T_S_0 (__pt[__parindex[9]])\n#define T_I_0 (__pt[__parindex[10]])\n#define T_R_0 (__pt[__parindex[11]])\n \nvoid __pomp_from_trans (double *__p, const double *__pt, const int *__parindex) { \n  gamma = exp(T_gamma);\n  mu = exp(T_mu);\n  iota = exp(T_iota);\n  k = exp(T_k);\n  beta1 = exp(T_beta1);\n  beta2 = exp(T_beta2);\n  beta3 = exp(T_beta3);\n  rho = expit(T_rho);\n  from_log_barycentric(&S_0,&T_S_0,3); \n}\n \n\n#undef seas_1\n#undef seas_2\n#undef seas_3\n#undef gamma\n#undef mu\n#undef iota\n#undef pop\n#undef rho\n#undef k\n#undef beta1\n#undef beta2\n#undef beta3\n#undef S_0\n#undef I_0\n#undef R_0\n#undef T_gamma\n#undef T_mu\n#undef T_iota\n#undef T_pop\n#undef T_rho\n#undef T_k\n#undef T_beta1\n#undef T_beta2\n#undef T_beta3\n#undef T_S_0\n#undef T_I_0\n#undef T_R_0\n\n/* C snippet: 'skeleton' */\n\n#define gamma (__p[__parindex[0]])\n#define mu (__p[__parindex[1]])\n#define iota (__p[__parindex[2]])\n#define pop (__p[__parindex[3]])\n#define rho (__p[__parindex[4]])\n#define k (__p[__parindex[5]])\n#define beta1 (__p[__parindex[6]])\n#define beta2 (__p[__parindex[7]])\n#define beta3 (__p[__parindex[8]])\n#define S_0 (__p[__parindex[9]])\n#define I_0 (__p[__parindex[10]])\n#define R_0 (__p[__parindex[11]])\n#define seas_1 (__covars[__covindex[0]])\n#define seas_2 (__covars[__covindex[1]])\n#define seas_3 (__covars[__covindex[2]])\n#define S (__x[__stateindex[0]])\n#define I (__x[__stateindex[1]])\n#define R (__x[__stateindex[2]])\n#define N (__x[__stateindex[3]])\n#define cases (__x[__stateindex[4]])\n#define DS (__f[__stateindex[0]])\n#define DI (__f[__stateindex[1]])\n#define DR (__f[__stateindex[2]])\n#define DN (__f[__stateindex[3]])\n#define Dcases (__f[__stateindex[4]])\n \nvoid __pomp_skelfn (double *__f, const double *__x, const double *__p,\n  const int *__stateindex, const int *__parindex, const int *__covindex,\n  const double *__covars, double t) { \n        int nrate = 6;\n        double rate[nrate];\n        double term[nrate];\n        double beta;\n\n        beta = dot_product(nbasis,&beta1,&seas_1);\n\n        rate[0] = mu*pop;\n        rate[1] = (iota+beta*I)/pop;\n        rate[2] = mu;\n        rate[3] = gamma;\n        rate[4] = mu;\n        rate[5] = mu;\n\n        term[0] = rate[0];\n        term[1] = rate[1]*S;\n        term[2] = rate[2]*S;\n        term[3] = rate[3]*I;\n        term[4] = rate[4]*I;\n        term[5] = rate[5]*R;\n\n        DS = term[0]-term[1]-term[2];\n        DI = term[1]-term[3]-term[4];\n        DR = term[3]-term[5];\n        DN = term[0]-term[2]-term[4]-term[5];\n        Dcases = term[3]; \n}\n \n\n#undef gamma\n#undef mu\n#undef iota\n#undef pop\n#undef rho\n#undef k\n#undef beta1\n#undef beta2\n#undef beta3\n#undef S_0\n#undef I_0\n#undef R_0\n#undef seas_1\n#undef seas_2\n#undef seas_3\n#undef S\n#undef I\n#undef R\n#undef N\n#undef cases\n#undef DS\n#undef DI\n#undef DR\n#undef DN\n#undef Dcases\nstatic int __pomp_load_stack = 0;\nvoid __pomp_load_stack_incr (void) {++__pomp_load_stack;}\nvoid __pomp_load_stack_decr (int *val) {*val = --__pomp_load_stack;} \n\n \nvoid R_init_sir2_source (DllInfo *info) {\n  R_RegisterCCallable(\"sir2_source\", \"__pomp_load_stack_incr\", (DL_FUNC) __pomp_load_stack_incr);\n  R_RegisterCCallable(\"sir2_source\", \"__pomp_load_stack_decr\", (DL_FUNC) __pomp_load_stack_decr);\n  R_RegisterCCallable(\"sir2_source\", \"__pomp_rinit\", (DL_FUNC) __pomp_rinit);\n  R_RegisterCCallable(\"sir2_source\", \"__pomp_ratefn\", (DL_FUNC) __pomp_ratefn);\n  R_RegisterCCallable(\"sir2_source\", \"__pomp_rmeasure\", (DL_FUNC) __pomp_rmeasure);\n  R_RegisterCCallable(\"sir2_source\", \"__pomp_dmeasure\", (DL_FUNC) __pomp_dmeasure);\n  R_RegisterCCallable(\"sir2_source\", \"__pomp_emeasure\", (DL_FUNC) __pomp_emeasure);\n  R_RegisterCCallable(\"sir2_source\", \"__pomp_vmeasure\", (DL_FUNC) __pomp_vmeasure);\n  R_RegisterCCallable(\"sir2_source\", \"__pomp_to_trans\", (DL_FUNC) __pomp_to_trans);\n  R_RegisterCCallable(\"sir2_source\", \"__pomp_from_trans\", (DL_FUNC) __pomp_from_trans);\n  R_RegisterCCallable(\"sir2_source\", \"__pomp_skelfn\", (DL_FUNC) __pomp_skelfn);\n  \n\n}\n \n> \n> try(spy())\nError : in 'spy': 'object' is a required argument.\n> try(spy(list()))\nError : 'spy' is undefined for 'object' of class 'list'.\n> \n> pomp(\n+   data=NULL,\n+   t0=0,times=1:10,\n+   userdata=list(x0=as.double(1)),\n+   params=c(x_0=1,a=22),\n+   rinit=Csnippet(r\"{x = *get_userdata_double(\"x0\");}\"),\n+   statenames=\"x\",\n+   compile=FALSE\n+ ) |>\n+   spy()\n==================\npomp object 'pomp(data = NULL, t0 = 0, times = 1:10, userdata = list(x0 = as.double(1)), ''    params = c(x_0 = 1, a = 22), rinit = Csnippet(\"x = *get_userdata_double(\\\"x0\\\");\"), ''    statenames = \"x\", compile = FALSE)':\n\n- data: <none>\n- zero time, t0 = 0\n- covariates: <none>\n- initial state simulator, rinit: native function\n  - name: '__pomp_rinit'\n  - defined by a C snippet in library 'pomp_79d7fb28dea7e6b8c8162d6e182f4009'\n- initial state density, dinit: <default>\n- process-model simulator, rprocess: <undefined>\n- process model density, dprocess: <default>\n- measurement model simulator, rmeasure: <default>\n- measurement model density, dmeasure: <default>\n- measurement model expectation, emeasure: <default>\n- measurement model covariance, vmeasure: <default>\n- prior simulator, rprior: <default>\n- prior density, dprior: <default>\n- deterministic skeleton: <default>\n\n- parameter vector:\nx_0   a \n  1  22 \n- extra user-defined variables:\n  - 'x0' (type 'double')\n\n- C snippet file  1 :\n\n\n/* pomp C snippet file: pomp_79d7fb28dea7e6b8c8162d6e182f4009 */\n/* Time: 2025-11-23 10:49:52.744 -0500 */\n/* Salt: 9159B3E23C4CD32979C073B6 */\n\n#include <pomp.h>\n#include <R_ext/Rdynload.h> \n \n\n\nstatic get_userdata_double_t *__pomp_get_userdata_double;\n#define get_userdata_double(X)  (__pomp_get_userdata_double(X))\n\n/* C snippet: 'rinit' */\n\n#define x (__x[__stateindex[0]])\n \nvoid __pomp_rinit (double *__x, const double *__p, double t,\n   const int *__stateindex, const int *__parindex, const int *__covindex,\n   const double *__covars) { x = *get_userdata_double(\"x0\"); \n}\n \n\n#undef x\nstatic int __pomp_load_stack = 0;\nvoid __pomp_load_stack_incr (void) {++__pomp_load_stack;}\nvoid __pomp_load_stack_decr (int *val) {*val = --__pomp_load_stack;} \n\n \nvoid R_init_pomp_79d7fb28dea7e6b8c8162d6e182f4009 (DllInfo *info) {\n  __pomp_get_userdata_double = (get_userdata_double_t *) R_GetCCallable(\"pomp\",\"get_userdata_double\");\n  R_RegisterCCallable(\"pomp_79d7fb28dea7e6b8c8162d6e182f4009\", \"__pomp_load_stack_incr\", (DL_FUNC) __pomp_load_stack_incr);\n  R_RegisterCCallable(\"pomp_79d7fb28dea7e6b8c8162d6e182f4009\", \"__pomp_load_stack_decr\", (DL_FUNC) __pomp_load_stack_decr);\n  R_RegisterCCallable(\"pomp_79d7fb28dea7e6b8c8162d6e182f4009\", \"__pomp_rinit\", (DL_FUNC) __pomp_rinit);\n  \n\n}\n \n> \n> pomp(\n+   data=NULL,\n+   t0=0,times=1:10,\n+   userdata=list(x0=as.double(1)),\n+   params=c(x_0=1,a=22),\n+   globals=Csnippet(\"static double X0;\"),\n+   rinit=Csnippet(r\"{x = X0;}\"),\n+   rprocess=euler(Csnippet(r\"(x += rgammawn(0.1,dt);)\"),delta.t=0.1),\n+   on_load=Csnippet(r\"{X0 = *get_userdata_double(\"x0\");}\"),\n+   statenames=\"x\",\n+   compile=FALSE\n+ ) |>\n+   spy()\n==================\npomp object 'pomp(data = NULL, t0 = 0, times = 1:10, userdata = list(x0 = as.double(1)), ''    params = c(x_0 = 1, a = 22), globals = Csnippet(\"static double X0;\"), ''    rinit = Csnippet(\"x = X0;\"), rprocess = euler(Csnippet(\"x += rgammawn(0.1,dt);\"), ''        delta.t = 0.1), on_load = Csnippet(\"X0 = *get_userdata_double(\\\"x0\\\");\"), ''    statenames = \"x\", compile = FALSE)':\n\n- data: <none>\n- zero time, t0 = 0\n- covariates: <none>\n- initial state simulator, rinit: native function\n  - name: '__pomp_rinit'\n  - defined by a C snippet in library 'pomp_2e6999d8816ed46fa84f8610dad10974'\n- initial state density, dinit: <default>\n- process-model simulator, rprocess: Euler-method process-model simulator\n  - timestep = 0.1 \n  - step.fun: native function\n  - name: '__pomp_stepfn'\n  - defined by a C snippet in library 'pomp_2e6999d8816ed46fa84f8610dad10974'\n- process model density, dprocess: <default>\n- measurement model simulator, rmeasure: <default>\n- measurement model density, dmeasure: <default>\n- measurement model expectation, emeasure: <default>\n- measurement model covariance, vmeasure: <default>\n- prior simulator, rprior: <default>\n- prior density, dprior: <default>\n- deterministic skeleton: <default>\n\n- parameter vector:\nx_0   a \n  1  22 \n- extra user-defined variables:\n  - 'x0' (type 'double')\n\n- C snippet file  1 :\n\n\n/* pomp C snippet file: pomp_2e6999d8816ed46fa84f8610dad10974 */\n/* Time: 2025-11-23 10:49:52.791 -0500 */\n/* Salt: 252A1E845536254CDA6D98E6 */\n\n#include <pomp.h>\n#include <R_ext/Rdynload.h> \nstatic double X0; \n\n\nstatic get_userdata_double_t *__pomp_get_userdata_double;\n#define get_userdata_double(X)  (__pomp_get_userdata_double(X))\n\n/* C snippet: 'rinit' */\n\n#define x (__x[__stateindex[0]])\n \nvoid __pomp_rinit (double *__x, const double *__p, double t,\n   const int *__stateindex, const int *__parindex, const int *__covindex,\n   const double *__covars) { x = X0; \n}\n \n\n#undef x\n\n/* C snippet: 'step.fn' */\n\n#define x (__x[__stateindex[0]])\n \nvoid __pomp_stepfn (double *__x, const double *__p, const int *__stateindex,\n  const int *__parindex, const int *__covindex, const double *__covars,\n  double t, double dt) { x += rgammawn(0.1,dt); \n}\n \n\n#undef x\nstatic int __pomp_load_stack = 0;\nvoid __pomp_load_stack_incr (void) {++__pomp_load_stack;}\nvoid __pomp_load_stack_decr (int *val) {*val = --__pomp_load_stack;} \n\n \nvoid R_init_pomp_2e6999d8816ed46fa84f8610dad10974 (DllInfo *info) {\n  __pomp_get_userdata_double = (get_userdata_double_t *) R_GetCCallable(\"pomp\",\"get_userdata_double\");\n  R_RegisterCCallable(\"pomp_2e6999d8816ed46fa84f8610dad10974\", \"__pomp_load_stack_incr\", (DL_FUNC) __pomp_load_stack_incr);\n  R_RegisterCCallable(\"pomp_2e6999d8816ed46fa84f8610dad10974\", \"__pomp_load_stack_decr\", (DL_FUNC) __pomp_load_stack_decr);\n  R_RegisterCCallable(\"pomp_2e6999d8816ed46fa84f8610dad10974\", \"__pomp_rinit\", (DL_FUNC) __pomp_rinit);\n  R_RegisterCCallable(\"pomp_2e6999d8816ed46fa84f8610dad10974\", \"__pomp_stepfn\", (DL_FUNC) __pomp_stepfn);\n X0 = *get_userdata_double(\"x0\"); \n\n}\n \n> \n"
  },
  {
    "path": "tests/steps.R",
    "content": "options(digits=3)\n\nsuppressPackageStartupMessages({\n  library(tidyr)\n  library(dplyr)\n})\nlibrary(pomp)\n\ntm <- freeze(sort(runif(n=20,max=50)),seed=1930502785L)\nsimulate(\n  times=tm,\n  t0=0,\n  rprocess=discrete_time(\n    Csnippet(\"\n      double dW = rnorm(0,sqrt(dt));\n      N += r*N*(1-N)*dt+sigma*dW;\n      e += dW;\n      step += 1;\n    \"),\n    delta.t=0.1\n  ),\n  skeleton=map(\n    Csnippet(\"\n      double dt = 0.1;\n      DN = N+r*N*(1-N)*dt;\n      De = 0;\n      Dstep = step+1;\n    \"),\n    delta.t=0.1\n  ),\n  rinit=Csnippet(\"e=0; N = N_0; step = 0;\"),\n  accumvars=\"step\",\n  params=c(r=0.5,N_0=0.5,sigma=0.1,phi=10,c=1),\n  paramnames=c(\"sigma\",\"r\",\"N_0\"),\n  statenames=c(\"N\",\"e\",\"step\")\n) -> sm\nsm |> trajectory() -> tj\nstopifnot(\n  all.equal(\n    diff(floor(time(sm,t0=TRUE)/0.1)),\n    as.numeric(states(sm,\"step\"))\n  ),\n  all.equal(\n    floor(diff(time(tj,t0=TRUE))/0.1),\n    as.numeric(states(tj,\"step\"))\n  )\n)\n\ntm <- freeze(sort(runif(n=100,max=2)),seed=342643819)\nsir() |>\n  simulate(\n    times=tm,\n    rprocess=euler(Csnippet(\"\n      double rate[6];\t\t  // transition rates\n      double trans[6];\t\t// transition numbers\n      double beta;\n      double dW;\n      beta = dot_product(3,&beta1,&seas_1);\n      dW = rgammawn(beta_sd,dt);\n      rate[0] = mu*pop;\n      rate[1] = (iota+beta*I*dW/dt)/pop;\n      rate[2] = mu;\n      rate[3] = gamma;\n      rate[4] = mu;\n      rate[5] = mu;\n      trans[0] = rpois(rate[0]*dt);\t// births are Poisson\n      reulermultinom(2,S,&rate[1],dt,&trans[1]);\n      reulermultinom(2,I,&rate[3],dt,&trans[3]);\n      reulermultinom(1,R,&rate[5],dt,&trans[5]);\n      S += trans[0]-trans[1]-trans[2];\n      I += trans[1]-trans[3]-trans[4];\n      R += trans[3]-trans[5];\n      cases += trans[3];\n      steps += 1;\n      \"),\n      delta.t=0.01\n    ),\n    rinit=Csnippet(\"\n      double m = pop/(S_0+I_0+R_0);\n      S = nearbyint(m*S_0);\n      I = nearbyint(m*I_0);\n      R = nearbyint(m*R_0);\n      cases = 0;\n      W = 0;\n      steps = 0;\n      \"),\n    statenames=c(\"S\",\"I\",\"R\",\"cases\",\"steps\",\"W\"),\n    accumvars=c(\"cases\",\"steps\"),\n    paramnames=c(\n      \"mu\",\"gamma\",\"iota\",\"beta1\",\"beta_sd\",\"pop\",\n      \"S_0\",\"I_0\",\"R_0\"\n    ),\n    seed=1232934371\n  ) -> sm\n\nstopifnot(\n  all.equal(\n    ceiling(diff(time(sm,t0=TRUE))/0.01),\n    as.numeric(states(sm,\"steps\"))\n  )\n)\n\nsimulate(\n  t0=0,\n  times=c(0,0,0,1,3,3,7),\n  rinit=\\(t0,...)c(x=t0,n=0),\n  rprocess=onestep(\\(t,x,n,delta.t,...) c(x=t+delta.t,n=n+1)),\n  rmeasure=\\(x,n,...) c(y1=x,y2=n),\n  dmeasure=\\(...,log) if (log) 0 else 1\n) -> s1\n\nsimulate(\n  t0=0,\n  times=c(0,0,0,1,3,3,7),\n  rinit=Csnippet(\"x=t; n=0;\"),\n  rprocess=onestep(Csnippet(\"x=t+dt; n=n+1;\")),\n  rmeasure=Csnippet(\"y1 = x; y2 = n;\"),\n  dmeasure=Csnippet(\"lik = (give_log) ? 0 : 1;\"),\n  statenames=c(\"x\",\"n\"),\n  obsnames=c(\"y1\",\"y2\")\n) -> s2\n\ns1 |>\n  as.data.frame() |>\n  with(\n    stopifnot(\n      time==x,\n      n==seq_along(time)\n    )\n  )\n\ns2 |>\n  pfilter(Np=1,save.states=\"filter\") |>\n  saved_states(format=\"list\") |>\n  melt() |>\n  pivot_wider() |>\n  mutate(time=time(s2)[.L1]) |>\n  with(\n    stopifnot(\n      time==x,\n      n==seq_along(time)\n    )\n  )\n"
  },
  {
    "path": "tests/steps.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> \n> suppressPackageStartupMessages({\n+   library(tidyr)\n+   library(dplyr)\n+ })\n> library(pomp)\n> \n> tm <- freeze(sort(runif(n=20,max=50)),seed=1930502785L)\n> simulate(\n+   times=tm,\n+   t0=0,\n+   rprocess=discrete_time(\n+     Csnippet(\"\n+       double dW = rnorm(0,sqrt(dt));\n+       N += r*N*(1-N)*dt+sigma*dW;\n+       e += dW;\n+       step += 1;\n+     \"),\n+     delta.t=0.1\n+   ),\n+   skeleton=map(\n+     Csnippet(\"\n+       double dt = 0.1;\n+       DN = N+r*N*(1-N)*dt;\n+       De = 0;\n+       Dstep = step+1;\n+     \"),\n+     delta.t=0.1\n+   ),\n+   rinit=Csnippet(\"e=0; N = N_0; step = 0;\"),\n+   accumvars=\"step\",\n+   params=c(r=0.5,N_0=0.5,sigma=0.1,phi=10,c=1),\n+   paramnames=c(\"sigma\",\"r\",\"N_0\"),\n+   statenames=c(\"N\",\"e\",\"step\")\n+ ) -> sm\nWarning message:\n'rmeasure' unspecified: NAs generated. \n> sm |> trajectory() -> tj\n> stopifnot(\n+   all.equal(\n+     diff(floor(time(sm,t0=TRUE)/0.1)),\n+     as.numeric(states(sm,\"step\"))\n+   ),\n+   all.equal(\n+     floor(diff(time(tj,t0=TRUE))/0.1),\n+     as.numeric(states(tj,\"step\"))\n+   )\n+ )\n> \n> tm <- freeze(sort(runif(n=100,max=2)),seed=342643819)\n> sir() |>\n+   simulate(\n+     times=tm,\n+     rprocess=euler(Csnippet(\"\n+       double rate[6];\t\t  // transition rates\n+       double trans[6];\t\t// transition numbers\n+       double beta;\n+       double dW;\n+       beta = dot_product(3,&beta1,&seas_1);\n+       dW = rgammawn(beta_sd,dt);\n+       rate[0] = mu*pop;\n+       rate[1] = (iota+beta*I*dW/dt)/pop;\n+       rate[2] = mu;\n+       rate[3] = gamma;\n+       rate[4] = mu;\n+       rate[5] = mu;\n+       trans[0] = rpois(rate[0]*dt);\t// births are Poisson\n+       reulermultinom(2,S,&rate[1],dt,&trans[1]);\n+       reulermultinom(2,I,&rate[3],dt,&trans[3]);\n+       reulermultinom(1,R,&rate[5],dt,&trans[5]);\n+       S += trans[0]-trans[1]-trans[2];\n+       I += trans[1]-trans[3]-trans[4];\n+       R += trans[3]-trans[5];\n+       cases += trans[3];\n+       steps += 1;\n+       \"),\n+       delta.t=0.01\n+     ),\n+     rinit=Csnippet(\"\n+       double m = pop/(S_0+I_0+R_0);\n+       S = nearbyint(m*S_0);\n+       I = nearbyint(m*I_0);\n+       R = nearbyint(m*R_0);\n+       cases = 0;\n+       W = 0;\n+       steps = 0;\n+       \"),\n+     statenames=c(\"S\",\"I\",\"R\",\"cases\",\"steps\",\"W\"),\n+     accumvars=c(\"cases\",\"steps\"),\n+     paramnames=c(\n+       \"mu\",\"gamma\",\"iota\",\"beta1\",\"beta_sd\",\"pop\",\n+       \"S_0\",\"I_0\",\"R_0\"\n+     ),\n+     seed=1232934371\n+   ) -> sm\n> \n> stopifnot(\n+   all.equal(\n+     ceiling(diff(time(sm,t0=TRUE))/0.01),\n+     as.numeric(states(sm,\"steps\"))\n+   )\n+ )\n> \n> simulate(\n+   t0=0,\n+   times=c(0,0,0,1,3,3,7),\n+   rinit=\\(t0,...)c(x=t0,n=0),\n+   rprocess=onestep(\\(t,x,n,delta.t,...) c(x=t+delta.t,n=n+1)),\n+   rmeasure=\\(x,n,...) c(y1=x,y2=n),\n+   dmeasure=\\(...,log) if (log) 0 else 1\n+ ) -> s1\n> \n> simulate(\n+   t0=0,\n+   times=c(0,0,0,1,3,3,7),\n+   rinit=Csnippet(\"x=t; n=0;\"),\n+   rprocess=onestep(Csnippet(\"x=t+dt; n=n+1;\")),\n+   rmeasure=Csnippet(\"y1 = x; y2 = n;\"),\n+   dmeasure=Csnippet(\"lik = (give_log) ? 0 : 1;\"),\n+   statenames=c(\"x\",\"n\"),\n+   obsnames=c(\"y1\",\"y2\")\n+ ) -> s2\n> \n> s1 |>\n+   as.data.frame() |>\n+   with(\n+     stopifnot(\n+       time==x,\n+       n==seq_along(time)\n+     )\n+   )\n> \n> s2 |>\n+   pfilter(Np=1,save.states=\"filter\") |>\n+   saved_states(format=\"list\") |>\n+   melt() |>\n+   pivot_wider() |>\n+   mutate(time=time(s2)[.L1]) |>\n+   with(\n+     stopifnot(\n+       time==x,\n+       n==seq_along(time)\n+     )\n+   )\n> \n"
  },
  {
    "path": "tests/synlik.R",
    "content": "options(digits=3)\npng(filename=\"synlik-%02d.png\",res=100)\n\nlibrary(pomp)\n\nou2() -> ou2\n\nset.seed(6457673L)\n\npo <- window(ou2,end=5)\n\nou2.kalman <- function (x, object, params) {\n  y <- obs(object)\n  p <- params\n  p[names(x)] <- x\n  x0 <- rinit(object,params=p)\n  A <- matrix(p[c(\"alpha_1\",\"alpha_2\",\"alpha_3\",\"alpha_4\")],2,2)\n  C <- diag(1,2)\n  Q <- matrix(p[c(\"sigma_1\",\"sigma_2\",NA,\"sigma_3\")],2,2)\n  Q[1,2] <- 0\n  Q <- tcrossprod(Q)\n  R <- diag(p[\"tau\"]^2,2,2)\n  kalmanFilter(object,X0=x0,A=A,C=C,Q=Q,R=R)$logLik\n}\n\n# exact likelihood\np.truth <- coef(po)\nloglik.truth <- ou2.kalman(p.truth,po,p.truth)\n\n## likelihood from probes (works since ou2 is Gaussian)\nloglik.probe <- replicate(n=500,logLik(probe(po,nsim=200,probes=function(x)x)))\n## likelihood from particle filters\nloglik.pfilter <- replicate(n=500,logLik(pfilter(po,Np=200)))\n\nkruskal.test(list(loglik.probe,loglik.pfilter))\nwilcox.test(loglik.probe,loglik.pfilter)\nks.test(loglik.pfilter,loglik.probe)\nplot(density(loglik.probe))\nabline(v=loglik.truth)\nplot(density(loglik.pfilter))\nabline(v=loglik.truth)\n\ndev.off()\n"
  },
  {
    "path": "tests/synlik.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"synlik-%02d.png\",res=100)\n> \n> library(pomp)\n> \n> ou2() -> ou2\n> \n> set.seed(6457673L)\n> \n> po <- window(ou2,end=5)\n> \n> ou2.kalman <- function (x, object, params) {\n+   y <- obs(object)\n+   p <- params\n+   p[names(x)] <- x\n+   x0 <- rinit(object,params=p)\n+   A <- matrix(p[c(\"alpha_1\",\"alpha_2\",\"alpha_3\",\"alpha_4\")],2,2)\n+   C <- diag(1,2)\n+   Q <- matrix(p[c(\"sigma_1\",\"sigma_2\",NA,\"sigma_3\")],2,2)\n+   Q[1,2] <- 0\n+   Q <- tcrossprod(Q)\n+   R <- diag(p[\"tau\"]^2,2,2)\n+   kalmanFilter(object,X0=x0,A=A,C=C,Q=Q,R=R)$logLik\n+ }\n> \n> # exact likelihood\n> p.truth <- coef(po)\n> loglik.truth <- ou2.kalman(p.truth,po,p.truth)\n> \n> ## likelihood from probes (works since ou2 is Gaussian)\n> loglik.probe <- replicate(n=500,logLik(probe(po,nsim=200,probes=function(x)x)))\n> ## likelihood from particle filters\n> loglik.pfilter <- replicate(n=500,logLik(pfilter(po,Np=200)))\n> \n> kruskal.test(list(loglik.probe,loglik.pfilter))\n\n\tKruskal-Wallis rank sum test\n\ndata:  list(loglik.probe, loglik.pfilter)\nKruskal-Wallis chi-squared = 5, df = 1, p-value = 0.03\n\n> wilcox.test(loglik.probe,loglik.pfilter)\n\n\tWilcoxon rank sum test with continuity correction\n\ndata:  loglik.probe and loglik.pfilter\nW = 1e+05, p-value = 0.03\nalternative hypothesis: true location shift is not equal to 0\n\n> ks.test(loglik.pfilter,loglik.probe)\n\n\tAsymptotic two-sample Kolmogorov-Smirnov test\n\ndata:  loglik.pfilter and loglik.probe\nD = 0.09, p-value = 0.03\nalternative hypothesis: two-sided\n\n> plot(density(loglik.probe))\n> abline(v=loglik.truth)\n> plot(density(loglik.pfilter))\n> abline(v=loglik.truth)\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/traj_match.R",
    "content": "options(digits=3)\npng(filename=\"traj_match-%02d.png\",res=100)\n\nlibrary(pomp)\n\nou2() -> ou2\n\ntry(traj_objfun())\ntry(traj_objfun(\"bob\"))\ntry(ou2 |> as.data.frame() |> traj_objfun())\ntry(ou2 |> as.data.frame() |> traj_objfun(times=\"time\",t0=0))\n\nou2 |>\n  as.data.frame() |>\n  traj_objfun(\n    times=\"time\",t0=0,\n    rinit=ou2@rinit,\n    skeleton=ou2@skeleton,\n    dmeasure=ou2@dmeasure,\n    params=coef(ou2)\n  ) -> f\n\nf()\nstopifnot(\n  f(0)==f(1),\n  logLik(f)!=f(0)\n)\n\nf |> traj_objfun(est=c(\"alpha_1\")) -> f1\nplot(sapply(seq(0.1,0.9,by=0.1),f1),xlab=\"\",ylab=\"\")\n\nf1(1.1)\nmatplot(t(trajectory(f1,format=\"a\")[,1,]),type=\"l\",ylab=\"y\")\nlibrary(subplex)\nsubplex(fn=f1,par=0.4,control=list(reltol=1e-3)) -> out\nf1(out$par)\n\ntry(traj_objfun(f1,est=\"harry\"))\n\nf1 |> as(\"pomp\")\nf1 |> as(\"data.frame\") |> names()\n\nf1 |> traj_objfun(fail.value=1e10) -> f2\nf2(NA)\n\n## ------------------\n## cf issue #149\n## ------------------\n\nenames <- c(\"gamma\",\"iota\",\"rho\",\"k\")\n\nsir() |>\n  traj_objfun(\n    dmeasure=Csnippet(\"\n      lik = dnbinom_mu(nearbyint(reports),1/k,rho*cases,give_log);\n    \"),\n    rmeasure=NULL,\n    params=c(coef(sir()),k=1),\n    partrans=parameter_trans(\n      log=c(\"gamma\",\"iota\",\"k\"),\n      logit=\"rho\"\n    ),\n    est=enames,\n    paramnames=enames,\n    statenames=\"cases\"\n  ) -> ofun\n\ntheta <- c(gamma=10,iota=1,rho=0.2,k=1)\ncoef(ofun,c(\"gamma\",\"iota\",\"rho\",\"k\")) <- theta\ncoef(ofun)\nstopifnot(\n  coef(ofun,names(theta))==theta,\n  ofun@env$params==coef(ofun,transform=TRUE)\n)\n\nsubplex(\n  fn=ofun,\n  par=partrans(ofun,theta,dir=\"toEst\")\n) -> fit\n\ninvisible(ofun(fit$par))\n\nlibrary(ggplot2)\n\nofun |>\n  trajectory(format=\"d\") |>\n  ggplot(aes(x=time,y=coef(ofun,\"rho\")*cases))+\n  geom_line()+\n  geom_point(\n    data=as(ofun,\"data.frame\"),\n    mapping=aes(x=time,y=reports)\n  )+\n  theme_bw()\n## ------------------\n\ndev.off()\n"
  },
  {
    "path": "tests/traj_match.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"traj_match-%02d.png\",res=100)\n> \n> library(pomp)\n> \n> ou2() -> ou2\n> \n> try(traj_objfun())\nError : in 'traj_objfun': 'data' is a required argument.\n> try(traj_objfun(\"bob\"))\nError : 'traj_objfun' is undefined for 'data' of class 'character'.\n> try(ou2 |> as.data.frame() |> traj_objfun())\nError : in 'traj_objfun': 'times' should either be a numeric vector of observation times or a single name identifying the column of data that represents the observation times.\n> try(ou2 |> as.data.frame() |> traj_objfun(times=\"time\",t0=0))\nError : in 'traj_objfun': 'skeleton', 'dmeasure' are needed basic components.\n> \n> ou2 |>\n+   as.data.frame() |>\n+   traj_objfun(\n+     times=\"time\",t0=0,\n+     rinit=ou2@rinit,\n+     skeleton=ou2@skeleton,\n+     dmeasure=ou2@dmeasure,\n+     params=coef(ou2)\n+   ) -> f\n> \n> f()\n[1] 4854\n> stopifnot(\n+   f(0)==f(1),\n+   logLik(f)!=f(0)\n+ )\n> \n> f |> traj_objfun(est=c(\"alpha_1\")) -> f1\n> plot(sapply(seq(0.1,0.9,by=0.1),f1),xlab=\"\",ylab=\"\")\n> \n> f1(1.1)\n[1] 40889714\n> matplot(t(trajectory(f1,format=\"a\")[,1,]),type=\"l\",ylab=\"y\")\n> library(subplex)\n> subplex(fn=f1,par=0.4,control=list(reltol=1e-3)) -> out\n> f1(out$par)\n[1] 4826\n> \n> try(traj_objfun(f1,est=\"harry\"))\nError : in 'traj_objfun': parameter 'harry' not found in 'params'\n> \n> f1 |> as(\"pomp\")\n<object of class 'pomp'>\n> f1 |> as(\"data.frame\") |> names()\n[1] \"time\" \"y1\"   \"y2\"   \"x1\"   \"x2\"  \n> \n> f1 |> traj_objfun(fail.value=1e10) -> f2\n> f2(NA)\n[1] 1e+10\n> \n> ## ------------------\n> ## cf issue #149\n> ## ------------------\n> \n> enames <- c(\"gamma\",\"iota\",\"rho\",\"k\")\n> \n> sir() |>\n+   traj_objfun(\n+     dmeasure=Csnippet(\"\n+       lik = dnbinom_mu(nearbyint(reports),1/k,rho*cases,give_log);\n+     \"),\n+     rmeasure=NULL,\n+     params=c(coef(sir()),k=1),\n+     partrans=parameter_trans(\n+       log=c(\"gamma\",\"iota\",\"k\"),\n+       logit=\"rho\"\n+     ),\n+     est=enames,\n+     paramnames=enames,\n+     statenames=\"cases\"\n+   ) -> ofun\n> \n> theta <- c(gamma=10,iota=1,rho=0.2,k=1)\n> coef(ofun,c(\"gamma\",\"iota\",\"rho\",\"k\")) <- theta\nWarning message:\nin 'coef<-': names of 'value' are being discarded. \n> coef(ofun)\n   gamma       mu     iota    beta1    beta2    beta3  beta_sd      rho \n1.00e+01 2.00e-02 1.00e+00 4.00e+02 4.80e+02 3.20e+02 1.00e-03 2.00e-01 \n       k      pop      S_0      I_0      R_0        k \n1.00e+00 2.10e+06 6.50e-02 1.00e-03 9.34e-01 1.00e+00 \n> stopifnot(\n+   coef(ofun,names(theta))==theta,\n+   ofun@env$params==coef(ofun,transform=TRUE)\n+ )\n> \n> subplex(\n+   fn=ofun,\n+   par=partrans(ofun,theta,dir=\"toEst\")\n+ ) -> fit\n> \n> invisible(ofun(fit$par))\n> \n> library(ggplot2)\n> \n> ofun |>\n+   trajectory(format=\"d\") |>\n+   ggplot(aes(x=time,y=coef(ofun,\"rho\")*cases))+\n+   geom_line()+\n+   geom_point(\n+     data=as(ofun,\"data.frame\"),\n+     mapping=aes(x=time,y=reports)\n+   )+\n+   theme_bw()\n> ## ------------------\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/trajectory.R",
    "content": "options(digits=3)\npng(filename=\"trajectory-%02d.png\",res=100)\n\nlibrary(pomp)\nlibrary(ggplot2)\n\npomp(\n  data=NULL,\n  times=seq(0,60,by=0.1),t0=0,\n  skeleton=vectorfield(Csnippet(\"\n    DV = c*(V-pow(V,3)/3 - R + i);\n    DR = (V + a - b*R)/c;\"\n  )),\n  rinit=Csnippet(\"\n    V = 1; R = 0;\"\n  ),\n  statenames=c(\"V\",\"R\"),\n  paramnames=c(\"c\",\"i\",\"a\",\"b\"),\n  params=c(a=0.7,b=0.8,c=2,i=0.8)\n) -> fhn\n\nx <- array(c(0,1,1,2,1,1,0,-1),\n  dim=c(2,2,2),\n  dimnames=list(c(\"V\",\"R\"),NULL,NULL))\nparams <- rbind(a=c(0.7,0.5),b=c(0.8,0.5),c=c(2,5),i=c(0.8,0))\nskeleton(fhn,x=x,times=c(0,3),params=params)\ny <- trajectory(fhn,params=params,ode_control=list(hmax=0.1),format=\"a\")\ninvisible(y[,,599:601])\nmatplot(time(fhn),t(y[\"V\",,]),type=\"l\",lty=1)\nplot(y[1,,],y[2,,],type=\"n\")\npoints(y[1,1,],y[2,1,],pch=\".\",cex=3,col=\"black\")\npoints(y[1,2,],y[2,2,],pch=\".\",cex=3,col=\"red\")\n\n## nonautonomous case\npomp(\n  data=fhn,\n  times=seq(0,100,by=0.01),t0=0,\n  covar=covariate_table(\n    i=sin(2*pi*times),\n    times=seq(0,101,by=0.1)\n  ),\n  rinit=function(...) {\n    c(V=1,R=0)\n  },\n  skeleton=vectorfield(\n    function(V,R,a,b,c,i,...) {\n      c(\n        V=c*(V-(V^3)/3-R+i),\n        R=(V+a-b*R)/c\n      )\n    }\n  )\n) -> fhn1\n\nparams <- params[c(\"a\",\"b\",\"c\"),]\ninvisible(skeleton(fhn1,x=x,times=c(0,3),params=params))\ny <- trajectory(fhn1,params=params,ode_control=list(hmax=0.01),format=\"a\")\ny[,,199:201]\nmatplot(time(fhn1),t(y[\"V\",,]),type=\"l\",lty=1)\nplot(y[1,,],y[2,,],type=\"n\")\npoints(y[1,1,],y[2,1,],pch=\".\",cex=3,col=\"black\")\npoints(y[1,2,],y[2,2,],pch=\".\",cex=3,col=\"red\")\n\ninvisible(trajectory(fhn,times=c(1,5),format=\"a\"))\ntry(trajectory(fhn,times=numeric(0)))\ntry(trajectory(fhn,times=c(1,1,1)))\ntry(trajectory(fhn,t0=10))\ntry(trajectory(fhn,params=c(3,2,1)))\ntry(trajectory(fhn,params=matrix(c(3,2,1,5),2,2)))\ntry(trajectory(fhn,params=NULL))\ntry(trajectory(fhn,params=list(a=3,b=2)))\ntry(trajectory(fhn,ode_control=list(maxsteps=-1)))\ntry(trajectory(fhn,ode_control=list(maxsteps=1),verbose=TRUE) -> x)\ntry(trajectory(pomp(fhn,accumvars=\"q\")) -> x)\nfhn@skeleton@type <- 3L\nstopifnot(\n  {\n    trajectory(fhn,format=\"array\") -> x\n    sum(is.na(x))==1202\n  }\n)\ntry(trajectory(\"fhn\"))\ntry(trajectory())\n\nsir() -> sir\ntrajectory(sir,format=\"data.frame\") -> x\nplot(cases~time,data=x,type=\"l\")\n\ngompertz() -> gompertz\ngompertz |> trajectory(format=\"a\") -> x\ngompertz |>\n  pomp(\n    skeleton=map(function(r,X,Y,K,...){\n      c(X=r*X*exp(-X/K),Y=Y+X)\n    }),\n    accumvars=c(\"Y\"),\n    params=c(r=17,X_0=1,Y.0=0,K=100)\n  ) -> po3\npo3 |>\n  trajectory(times=seq(1,1000),format=\"data.frame\") -> dat\nplot(X~time,data=dat,subset=(time<100),type=\"l\")\nplot(X~Y,data=dat)\ngompertz |>\n  pomp(accumvars=c(\"X\")) |>\n  trajectory(times=seq(1,1000,by=10),format=\"a\") -> x\nstopifnot(all(x==0))\n\ntry(\n  po3 |>\n    pomp(skeleton=map(function(...)c(X=1,Y=2,Z=3))) |>\n    trajectory(params=c(X_0=1,Y_0=0),format=\"a\")\n)\n\nstopifnot(\n  po3 |> trajectory(times=seq(0,100,by=5),format=\"a\") |> dim()==c(2,1,21),\n  po3 |> pomp(skeleton=NULL) |> trajectory(format=\"a\") |> is.na()\n)\n\ntrajectory(\n  t0=0,times=seq(0,10,by=0.1),\n  rinit=function(...)c(x=1,y=0),\n  skeleton=vectorfield(function(x,y,t,...)c(x=x,y=200*t)),\n  format=\"d\"\n) -> dat\nplot(x~time,data=dat,col=2,type=\"l\",ylab=\"\")\nlines(y~time,data=dat,col=3)\n\ndat1 <- dat[c(\"time\",\"x\",\"y\")]\nnames(dat1) <- c(\"time\",\"X\",\"Y\")\ndat1 |>\n  trajectory(\n    t0=0,times=\"time\",\n    rinit=function(...)c(x=1,y=0),\n    skeleton=vectorfield(function(x,y,t,...)c(x=x,y=200*t)),\n    format=\"d\"\n  ) -> dat2\nstopifnot(all.equal(dat,dat2))\n\nricker() -> po\ntry(trajectory(po,params=c(\"A\",\"B\")))\np <- parmat(coef(po),3)\ncolnames(p) <- LETTERS[1:3]\np[\"r\",] <- c(5,10,45)\npo |>\n  trajectory(params=p,times=1:5,format=\"array\") |>\n  dimnames() -> dn\nstopifnot(\n  names(dn)==c(\"name\",\".id\",\"time\"),\n  dn$.id==LETTERS[1:3],\n  is.null(dn$time)\n)\npo |>\n  trajectory(params=p,times=1:5,format=\"data.frame\") -> x\nunique(x$.id)\npo |>\n  trajectory(format=\"pomps\") |>\n  trajectory(params=p,times=1:50,format=\"pomps\") -> pos\nstates(pos) -> x\nobs(pos) -> y\nstopifnot(\n  names(pos)==LETTERS[1:3],\n  length(x)==3,\n  length(y)==3\n)\npos |>\n  as.data.frame() |>\n  ggplot(aes(x=time,y=N,group=.L1,color=.L1))+\n  geom_line()+\n  facet_wrap(~.L1,ncol=1)+\n  theme_bw()\n\ndev.off()\n"
  },
  {
    "path": "tests/trajectory.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"trajectory-%02d.png\",res=100)\n> \n> library(pomp)\n> library(ggplot2)\n> \n> pomp(\n+   data=NULL,\n+   times=seq(0,60,by=0.1),t0=0,\n+   skeleton=vectorfield(Csnippet(\"\n+     DV = c*(V-pow(V,3)/3 - R + i);\n+     DR = (V + a - b*R)/c;\"\n+   )),\n+   rinit=Csnippet(\"\n+     V = 1; R = 0;\"\n+   ),\n+   statenames=c(\"V\",\"R\"),\n+   paramnames=c(\"c\",\"i\",\"a\",\"b\"),\n+   params=c(a=0.7,b=0.8,c=2,i=0.8)\n+ ) -> fhn\n> \n> x <- array(c(0,1,1,2,1,1,0,-1),\n+   dim=c(2,2,2),\n+   dimnames=list(c(\"V\",\"R\"),NULL,NULL))\n> params <- rbind(a=c(0.7,0.5),b=c(0.8,0.5),c=c(2,5),i=c(0.8,0))\n> skeleton(fhn,x=x,times=c(0,3),params=params)\n, , 1\n\n    .id\nname  [,1]  [,2]\n   V -0.40 -6.67\n   R -0.05  0.10\n\n, , 2\n\n    .id\nname  [,1] [,2]\n   V 0.933  5.0\n   R 0.450  0.2\n\n> y <- trajectory(fhn,params=params,ode_control=list(hmax=0.1),format=\"a\")\n> invisible(y[,,599:601])\n> matplot(time(fhn),t(y[\"V\",,]),type=\"l\",lty=1)\n> plot(y[1,,],y[2,,],type=\"n\")\n> points(y[1,1,],y[2,1,],pch=\".\",cex=3,col=\"black\")\n> points(y[1,2,],y[2,2,],pch=\".\",cex=3,col=\"red\")\n> \n> ## nonautonomous case\n> pomp(\n+   data=fhn,\n+   times=seq(0,100,by=0.01),t0=0,\n+   covar=covariate_table(\n+     i=sin(2*pi*times),\n+     times=seq(0,101,by=0.1)\n+   ),\n+   rinit=function(...) {\n+     c(V=1,R=0)\n+   },\n+   skeleton=vectorfield(\n+     function(V,R,a,b,c,i,...) {\n+       c(\n+         V=c*(V-(V^3)/3-R+i),\n+         R=(V+a-b*R)/c\n+       )\n+     }\n+   )\n+ ) -> fhn1\n> \n> params <- params[c(\"a\",\"b\",\"c\"),]\n> invisible(skeleton(fhn1,x=x,times=c(0,3),params=params))\n> y <- trajectory(fhn1,params=params,ode_control=list(hmax=0.01),format=\"a\")\n> y[,,199:201]\n, , 1\n\n    .id\nname      1      2\n   V -0.133 -0.538\n   R  1.184  0.632\n\n, , 2\n\n    .id\nname      1      2\n   V -0.161 -0.600\n   R  1.182  0.632\n\n, , 3\n\n    .id\nname      1      2\n   V -0.189 -0.660\n   R  1.180  0.631\n\n> matplot(time(fhn1),t(y[\"V\",,]),type=\"l\",lty=1)\n> plot(y[1,,],y[2,,],type=\"n\")\n> points(y[1,1,],y[2,1,],pch=\".\",cex=3,col=\"black\")\n> points(y[1,2,],y[2,2,],pch=\".\",cex=3,col=\"red\")\n> \n> invisible(trajectory(fhn,times=c(1,5),format=\"a\"))\n> try(trajectory(fhn,times=numeric(0)))\nError : in 'trajectory': in 'time<-':  times must be numeric and finite.\n> try(trajectory(fhn,times=c(1,1,1)))\n<object of class 'pomp'>\n> try(trajectory(fhn,t0=10))\nError : in 'trajectory': 't0' must be a single number not greater than 'times[1]'.\n> try(trajectory(fhn,params=c(3,2,1)))\nError : in 'trajectory': in 'rinit': variable 'c' not found among the parameters.\n> try(trajectory(fhn,params=matrix(c(3,2,1,5),2,2)))\nError : in 'trajectory': in 'rinit': variable 'c' not found among the parameters.\n> try(trajectory(fhn,params=NULL))\nError : in 'trajectory': in 'rinit': variable 'c' not found among the parameters.\n> try(trajectory(fhn,params=list(a=3,b=2)))\nError : in 'trajectory': in 'rinit': variable 'c' not found among the parameters.\n> try(trajectory(fhn,ode_control=list(maxsteps=-1)))\nDLSODA-  MXSTEP (=I1) .lt. 0  \nIn above message, I1 = -1\n \nError : in 'trajectory': in 'flow': error in ODE integrator: illegal input detected before taking any integration steps - see written message\n> try(trajectory(fhn,ode_control=list(maxsteps=1),verbose=TRUE) -> x)\nDLSODA-  At current T (=R1), MXSTEP (=I1) steps   \n      taken on this call before reaching TOUT     \nIn above message, I1 = 1\n \nIn above message, R1 = 9.89415e-05\n \n\n--------------------\nlsoda return code\n--------------------\n\n  return code (idid) =  -1 \n  Excess work done on this call. (Perhaps wrong Jacobian type MF.)\n\n--------------------\nINTEGER values\n--------------------\n\n  1 The return code : -1 \n  2 The number of steps taken for the problem so far: 1 \n  3 The number of function evaluations for the problem so far: 3 \n  5 The method order last used (successfully): 1 \n  6 The order of the method to be attempted on the next step: 1 \n  7 If return flag =-4,-5: the largest component in error vector 0 \n  8 The length of the real work array actually required: 52 \n  9 The length of the integer work array actually required: 22 \n 14 The number of Jacobian evaluations and LU decompositions so far: 0 \n 15 The method indicator for the last succesful step,\n           1=adams (nonstiff), 2= bdf (stiff): 1 \n 16 The current method indicator to be attempted on the next step,\n           1=adams (nonstiff), 2= bdf (stiff): 1 \n \n--------------------\nRSTATE values\n--------------------\n\n  1 The step size in t last used (successfully): 9.89e-05 \n  2 The step size to be attempted on the next step: 9.89e-05 \n  3 The current value of the independent variable which the solver has reached: 9.89e-05 \n  4 Tolerance scale factor > 1.0 computed when requesting too much accuracy: 0 \n  5 The value of t at the time of the last method switch, if any: 0 \n \nWarning messages:\n1: In lsoda(y, times, func, parms, ...) :\n  an excessive amount of work (> maxsteps ) was done, but integration was not successful - increase maxsteps\n2: In lsoda(y, times, func, parms, ...) :\n  Returning early. Results are accurate, as far as they go\n3: in 'flow': abnormal exit from ODE integrator, istate = -1 \n> try(trajectory(pomp(fhn,accumvars=\"q\")) -> x)\nError : in 'trajectory': in 'flow': accumulator variable 'q' not found among the state variables.\n> fhn@skeleton@type <- 3L\n> stopifnot(\n+   {\n+     trajectory(fhn,format=\"array\") -> x\n+     sum(is.na(x))==1202\n+   }\n+ )\n> try(trajectory(\"fhn\"))\nError : 'trajectory' is undefined for 'object' of class 'character'.\n> try(trajectory())\nError : in 'trajectory': 'times' should either be a numeric vector of observation times or a single name identifying the column of data that represents the observation times.\n> \n> sir() -> sir\n> trajectory(sir,format=\"data.frame\") -> x\n> plot(cases~time,data=x,type=\"l\")\n> \n> gompertz() -> gompertz\n> gompertz |> trajectory(format=\"a\") -> x\n> gompertz |>\n+   pomp(\n+     skeleton=map(function(r,X,Y,K,...){\n+       c(X=r*X*exp(-X/K),Y=Y+X)\n+     }),\n+     accumvars=c(\"Y\"),\n+     params=c(r=17,X_0=1,Y.0=0,K=100)\n+   ) -> po3\n> po3 |>\n+   trajectory(times=seq(1,1000),format=\"data.frame\") -> dat\n> plot(X~time,data=dat,subset=(time<100),type=\"l\")\n> plot(X~Y,data=dat)\n> gompertz |>\n+   pomp(accumvars=c(\"X\")) |>\n+   trajectory(times=seq(1,1000,by=10),format=\"a\") -> x\n> stopifnot(all(x==0))\n> \n> try(\n+   po3 |>\n+     pomp(skeleton=map(function(...)c(X=1,Y=2,Z=3))) |>\n+     trajectory(params=c(X_0=1,Y_0=0),format=\"a\")\n+ )\nError : in 'trajectory': in 'flow': 'skeleton' returns a vector of 3 state variables but 2 are expected.\n> \n> stopifnot(\n+   po3 |> trajectory(times=seq(0,100,by=5),format=\"a\") |> dim()==c(2,1,21),\n+   po3 |> pomp(skeleton=NULL) |> trajectory(format=\"a\") |> is.na()\n+ )\n> \n> trajectory(\n+   t0=0,times=seq(0,10,by=0.1),\n+   rinit=function(...)c(x=1,y=0),\n+   skeleton=vectorfield(function(x,y,t,...)c(x=x,y=200*t)),\n+   format=\"d\"\n+ ) -> dat\n> plot(x~time,data=dat,col=2,type=\"l\",ylab=\"\")\n> lines(y~time,data=dat,col=3)\n> \n> dat1 <- dat[c(\"time\",\"x\",\"y\")]\n> names(dat1) <- c(\"time\",\"X\",\"Y\")\n> dat1 |>\n+   trajectory(\n+     t0=0,times=\"time\",\n+     rinit=function(...)c(x=1,y=0),\n+     skeleton=vectorfield(function(x,y,t,...)c(x=x,y=200*t)),\n+     format=\"d\"\n+   ) -> dat2\n> stopifnot(all.equal(dat,dat2))\n> \n> ricker() -> po\n> try(trajectory(po,params=c(\"A\",\"B\")))\nError : in 'trajectory': 'params' must be named and numeric.\n> p <- parmat(coef(po),3)\n> colnames(p) <- LETTERS[1:3]\n> p[\"r\",] <- c(5,10,45)\n> po |>\n+   trajectory(params=p,times=1:5,format=\"array\") |>\n+   dimnames() -> dn\n> stopifnot(\n+   names(dn)==c(\"name\",\".id\",\"time\"),\n+   dn$.id==LETTERS[1:3],\n+   is.null(dn$time)\n+ )\n> po |>\n+   trajectory(params=p,times=1:5,format=\"data.frame\") -> x\n> unique(x$.id)\n[1] A B C\nLevels: A < B < C\n> po |>\n+   trajectory(format=\"pomps\") |>\n+   trajectory(params=p,times=1:50,format=\"pomps\") -> pos\n> states(pos) -> x\n> obs(pos) -> y\n> stopifnot(\n+   names(pos)==LETTERS[1:3],\n+   length(x)==3,\n+   length(y)==3\n+ )\n> pos |>\n+   as.data.frame() |>\n+   ggplot(aes(x=time,y=N,group=.L1,color=.L1))+\n+   geom_line()+\n+   facet_wrap(~.L1,ncol=1)+\n+   theme_bw()\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/transformations.R",
    "content": "options(digits=3)\n\nlibrary(pomp)\n\nset.seed(770238753)\n\np <- runif(50)\nx <- rcauchy(50,scale=0.1)\nstopifnot(\n  all.equal(expit(logit(p)),p),\n  all.equal(logit(expit(x)),x)\n)\n\nY <- matrix(rcauchy(50,scale=0.1),5,10)\nX <- matrix(rexp(50),5,10)\nX <- apply(X,2,function(x)x/sum(x))\n\nstopifnot(\n  all.equal(apply(apply(X,2,log_barycentric),2,inv_log_barycentric),X),\n  all.equal(apply(apply(Y,2,inv_log_barycentric),2,sum),rep(1,ncol(Y))),\n  all.equal(apply(apply(apply(apply(Y,2,inv_log_barycentric),2,log_barycentric)-Y,2,range),2,diff),rep(0,ncol(Y)))\n)\n"
  },
  {
    "path": "tests/transformations.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> \n> library(pomp)\n> \n> set.seed(770238753)\n> \n> p <- runif(50)\n> x <- rcauchy(50,scale=0.1)\n> stopifnot(\n+   all.equal(expit(logit(p)),p),\n+   all.equal(logit(expit(x)),x)\n+ )\n> \n> Y <- matrix(rcauchy(50,scale=0.1),5,10)\n> X <- matrix(rexp(50),5,10)\n> X <- apply(X,2,function(x)x/sum(x))\n> \n> stopifnot(\n+   all.equal(apply(apply(X,2,log_barycentric),2,inv_log_barycentric),X),\n+   all.equal(apply(apply(Y,2,inv_log_barycentric),2,sum),rep(1,ncol(Y))),\n+   all.equal(apply(apply(apply(apply(Y,2,inv_log_barycentric),2,log_barycentric)-Y,2,range),2,diff),rep(0,ncol(Y)))\n+ )\n> \n"
  },
  {
    "path": "tests/undefined.R",
    "content": "options(digits=3)\n\nlibrary(pomp)\n\npomp:::undefined()\npomp:::undefined(\"harry\")\npomp:::undefined(function(x)x)\npomp:::undefined(pomp:::pomp_fun(function(x)x))\npomp:::undefined(pomp:::pomp_fun())\npomp:::undefined(parameter_trans())\npomp:::undefined(pomp:::rproc_plugin())\npomp:::undefined(pomp:::skel_plugin())\n"
  },
  {
    "path": "tests/undefined.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> \n> library(pomp)\n> \n> pomp:::undefined()\n[1] NA\n> pomp:::undefined(\"harry\")\n[1] NA\n> pomp:::undefined(function(x)x)\n[1] NA\n> pomp:::undefined(pomp:::pomp_fun(function(x)x))\n[1] FALSE\n> pomp:::undefined(pomp:::pomp_fun())\n[1] TRUE\n> pomp:::undefined(parameter_trans())\n[1] TRUE\n> pomp:::undefined(pomp:::rproc_plugin())\n[1] TRUE\n> pomp:::undefined(pomp:::skel_plugin())\n[1] TRUE\n> \n"
  },
  {
    "path": "tests/userdata.R",
    "content": "options(digits=3)\nset.seed(58668844L)\n\nlibrary(pomp)\n\nsimulate(\n  times=seq(1,100),t0=0,\n  userdata=list(\n    nbasis=9L,\n    period=50.0,\n    msg=\"hello!\"\n  ),\n  params=setNames(runif(n=9,min=-5,max=5),sprintf(\"beta%d\",1:9)),\n  rprocess=euler(\n    Csnippet(r\"{\n      static int first = 1;\n      if (first) {\n        SEXP Msg = get_userdata(\"msg\");\n        char *msg = CHAR(STRING_ELT(Msg,0));\n        Rprintf(\"%s\\n\",msg);\n        first = 0;\n      }\n      int nbasis = *(get_userdata_int(\"nbasis\"));\n      int degree = 3;\n      double period = *(get_userdata_double(\"period\"));\n      double dxdt[nbasis];\n      periodic_bspline_basis_eval(t,period,degree,nbasis,dxdt);\n      x += dt*dot_product(nbasis,dxdt,&beta1);}\"\n    ),delta.t=0.01\n  ),\n  rmeasure=Csnippet(\"y = x;\"),\n  rinit=Csnippet(\"x = 0;\"),\n  statenames=\"x\",obsnames=\"y\",paramnames=c(\"beta1\",\"beta2\",\"beta3\")\n) -> po\n\ntry(po |>\n    simulate(rprocess=onestep(\n      Csnippet(r\"{\n      SEXP Msg = get_userdata(\"bob\");\n      char *msg = CHAR(STRING_ELT(Msg,0));\n      Rprintf(\"%s\\n\",msg);}\"))))\ntry(po |> simulate(time=1:3))\ntry(po |> simulate(time=1:3,bob=77))\ntry(po |> simulate(times=1:3,seed=NULL,nsim=5,77))\ntry(po |> pomp(77))\ntry(po |>\n    simulate(rprocess=onestep(\n      Csnippet(r\"{double nbasis = *(get_userdata_double(\"nbasis\"));}\"))))\ntry(po |>\n    simulate(rprocess=onestep(\n      Csnippet(r\"{double nbasis = *(get_userdata_double(\"bob\"));}\"))))\ntry(po |>\n    simulate(rprocess=onestep(\n      Csnippet(r\"{int nbasis = *(get_userdata_int(\"period\"));}\"))))\ntry(po |>\n    simulate(rprocess=onestep(\n      Csnippet(r\"{int nbasis = *(get_userdata_int(\"bob\"));}\"))))\ntry(po |>\n    simulate(rprocess=onestep(\n      Csnippet(r\"{int nbasis = *(get_userdata_int(\"bob\"));}\")),\n      userdata=list(bob=3)))\nstopifnot(po |>\n    simulate(rprocess=onestep(\n      Csnippet(r\"{int nbasis = *(get_userdata_int(\"bob\"));}\")),\n      userdata=list(bob=3L)) |> class() == \"pomp\")\n"
  },
  {
    "path": "tests/userdata.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> set.seed(58668844L)\n> \n> library(pomp)\n> \n> simulate(\n+   times=seq(1,100),t0=0,\n+   userdata=list(\n+     nbasis=9L,\n+     period=50.0,\n+     msg=\"hello!\"\n+   ),\n+   params=setNames(runif(n=9,min=-5,max=5),sprintf(\"beta%d\",1:9)),\n+   rprocess=euler(\n+     Csnippet(r\"{\n+       static int first = 1;\n+       if (first) {\n+         SEXP Msg = get_userdata(\"msg\");\n+         char *msg = CHAR(STRING_ELT(Msg,0));\n+         Rprintf(\"%s\\n\",msg);\n+         first = 0;\n+       }\n+       int nbasis = *(get_userdata_int(\"nbasis\"));\n+       int degree = 3;\n+       double period = *(get_userdata_double(\"period\"));\n+       double dxdt[nbasis];\n+       periodic_bspline_basis_eval(t,period,degree,nbasis,dxdt);\n+       x += dt*dot_product(nbasis,dxdt,&beta1);}\"\n+     ),delta.t=0.01\n+   ),\n+   rmeasure=Csnippet(\"y = x;\"),\n+   rinit=Csnippet(\"x = 0;\"),\n+   statenames=\"x\",obsnames=\"y\",paramnames=c(\"beta1\",\"beta2\",\"beta3\")\n+ ) -> po\nhello!\n> \n> try(po |>\n+     simulate(rprocess=onestep(\n+       Csnippet(r\"{\n+       SEXP Msg = get_userdata(\"bob\");\n+       char *msg = CHAR(STRING_ELT(Msg,0));\n+       Rprintf(\"%s\\n\",msg);}\"))))\nError : in 'simulate': no user-data element 'bob' is found.\n> try(po |> simulate(time=1:3))\nError : in 'simulate': The argument 'time' is not recognized.\nUse the 'userdata' argument to supply extra objects to basic model components.\nSee '?userdata'.\n> try(po |> simulate(time=1:3,bob=77))\nError : in 'simulate': The arguments 'time','bob' are not recognized.\nUse the 'userdata' argument to supply extra objects to basic model components.\nSee '?userdata'.\n> try(po |> simulate(times=1:3,seed=NULL,nsim=5,77))\nError : in 'simulate': Unnamed arguments are not permitted.\n> try(po |> pomp(77))\nError : Unnamed arguments are not permitted.\n> try(po |>\n+     simulate(rprocess=onestep(\n+       Csnippet(r\"{double nbasis = *(get_userdata_double(\"nbasis\"));}\"))))\nError : in 'simulate': user-data element 'nbasis' is not a numeric vector.\n> try(po |>\n+     simulate(rprocess=onestep(\n+       Csnippet(r\"{double nbasis = *(get_userdata_double(\"bob\"));}\"))))\nError : in 'simulate': no user-data element 'bob' is found.\n> try(po |>\n+     simulate(rprocess=onestep(\n+       Csnippet(r\"{int nbasis = *(get_userdata_int(\"period\"));}\"))))\nError : in 'simulate': user-data element 'period' is not an integer.\n> try(po |>\n+     simulate(rprocess=onestep(\n+       Csnippet(r\"{int nbasis = *(get_userdata_int(\"bob\"));}\"))))\nError : in 'simulate': no user-data element 'bob' is found.\n> try(po |>\n+     simulate(rprocess=onestep(\n+       Csnippet(r\"{int nbasis = *(get_userdata_int(\"bob\"));}\")),\n+       userdata=list(bob=3)))\nError : in 'simulate': user-data element 'bob' is not an integer.\n> stopifnot(po |>\n+     simulate(rprocess=onestep(\n+       Csnippet(r\"{int nbasis = *(get_userdata_int(\"bob\"));}\")),\n+       userdata=list(bob=3L)) |> class() == \"pomp\")\n> \n"
  },
  {
    "path": "tests/verhulst.R",
    "content": "library(pomp)\n\nset.seed(1438408329L)\n\npng(filename=\"verhulst-%02d.png\",res=100)\n\nverhulst(n_0=100) -> po\nplot(po)\n\nstopifnot(\n  all.equal(\n    coef(po),\n    partrans(po,coef(po,transform=TRUE),dir=\"from\")\n  ),\n  all.equal(\n    coef(po,transform=TRUE),\n    partrans(po,coef(po),dir=\"to\")\n  )\n)\n\npfilter(\n  po,\n  Np=1000,\n  filter.mean=TRUE,\n  pred.mean=TRUE,\n  pred.var=TRUE,\n  filter.traj=TRUE,\n  save.states=\"filter\"\n) -> pf\n\nprint(logLik(pf))\nstopifnot(\n  abs(logLik(pf)+8687.3)<0.05\n)\n\nplot(pf,yax.flip=TRUE)\n\nforecast(pf,format=\"d\") -> fc\nsimulate(pf) -> sm\n\nemeasure(sm) -> ef\nvmeasure(sm) -> vf\nplot(ef,vf)\n\nplot(time(sm),obs(sm),xlab=\"time\",ylab=\"Y\")\nlines(time(sm),ef)\n\nenkf(po,Np=1000) -> kf\nplot(kf,yax.flip=TRUE)\n\ntrajectory(po) -> tj\nplot(tj)\n\ndev.off()\n"
  },
  {
    "path": "tests/verhulst.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> \n> set.seed(1438408329L)\n> \n> png(filename=\"verhulst-%02d.png\",res=100)\n> \n> verhulst(n_0=100) -> po\n> plot(po)\n> \n> stopifnot(\n+   all.equal(\n+     coef(po),\n+     partrans(po,coef(po,transform=TRUE),dir=\"from\")\n+   ),\n+   all.equal(\n+     coef(po,transform=TRUE),\n+     partrans(po,coef(po),dir=\"to\")\n+   )\n+ )\n> \n> pfilter(\n+   po,\n+   Np=1000,\n+   filter.mean=TRUE,\n+   pred.mean=TRUE,\n+   pred.var=TRUE,\n+   filter.traj=TRUE,\n+   save.states=\"filter\"\n+ ) -> pf\n> \n> print(logLik(pf))\n[1] -8687.331\n> stopifnot(\n+   abs(logLik(pf)+8687.3)<0.05\n+ )\n> \n> plot(pf,yax.flip=TRUE)\n> \n> forecast(pf,format=\"d\") -> fc\n> simulate(pf) -> sm\n> \n> emeasure(sm) -> ef\n> vmeasure(sm) -> vf\n> plot(ef,vf)\n> \n> plot(time(sm),obs(sm),xlab=\"time\",ylab=\"Y\")\n> lines(time(sm),ef)\n> \n> enkf(po,Np=1000) -> kf\n> plot(kf,yax.flip=TRUE)\n> \n> trajectory(po) -> tj\n> plot(tj)\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/vmeasure.R",
    "content": "library(pomp)\n\ntry(vmeasure())\ntry(vmeasure(\"does this work?\"))\ntry(simulate(t0=0,times=1:10,vmeasure=Csnippet(\"V_B_B=rho*(1-rho)*inc;\")))\n\nou2() -> po\nvmeasure(po) -> v1\nvmeasure(po,x=states(po)) -> v2\nvmeasure(po,x=states(po),params=coef(po)) -> v3\nstopifnot(\n  dim(v1)==c(2,2,1,100),\n  identical(v1,v2),\n  identical(v1,v3)\n)\ntry(vmeasure(po,x=states(po),params=coef(po),times=numeric(0)))\ntry(vmeasure(po,x=states(po),params=coef(po),times=c(1,2,3)))\nsimulate(po,nsim=3,format=\"arrays\") |> getElement(\"states\") -> X\ntry(vmeasure(po,x=X,params=parmat(coef(po),2),times=time(po)))\npo |>\n  simulate(\n    vmeasure=function(x1, x2, ...) {\n      matrix(c(x1+x2,1,1,x1+x2,1,1),nrow=2)\n    }\n  ) -> po1\ntry(vmeasure(po1,x=states(po1),params=coef(po1),times=time(po1)))\npo |>\n  simulate(\n    vmeasure=function(x1, x2, ...) {\n      matrix(c(x1+x2,1,1,x1+x2),nrow=2)\n    }\n  ) -> po1\ntry(vmeasure(po1,x=states(po1),params=coef(po1),times=time(po1)))\npo |>\n  simulate(\n    vmeasure=function(x1, x2, t, ...) {\n      v <- matrix(rep(x1+x2,ceiling(t)^2),nrow=ceiling(t))\n      nm <- head(letters,ceiling(t))\n      dimnames(v) <- list(nm,nm)\n      v\n    }\n  ) -> po1\ntry(vmeasure(po1,x=states(po1),params=coef(po1),times=time(po1)))\npo |>\n  simulate(\n    vmeasure=function(x1, x2, t, ...) {\n      v <- matrix(c(x1+x2,1,1,x1+x2),nrow=2)\n      nm <- c(\"a\",\"b\")\n      dimnames(v) <- list(nm,NULL)\n      v\n    }\n  ) -> po1\nv <- vmeasure(po1,x=states(po1),params=coef(po1),times=time(po1))\nstopifnot(\n  dim(v)==c(2,2,1,100),\n  v[1,1,,]==v[2,2,,],\n  v[1,2,,]==v[2,1,,],\n  rownames(v)==c(\"a\",\"b\"),\n  colnames(v)==c(\"a\",\"b\"),\n  sum(is.na(v))==0\n)\npo |> simulate(vmeasure=NULL) -> po1\nv <- vmeasure(po1,x=states(po1),params=coef(po1),times=time(po1))\nstopifnot(\n  dim(v)==c(2,2,1,100),\n  rownames(v)==c(\"y1\",\"y2\"),\n  colnames(v)==c(\"y1\",\"y2\"),\n  sum(is.na(v))==400\n)\n\nsir() |>\n  simulate(\n    times=(1:10)/52,\n    vmeasure=function(cases, rho, seas_1, seas_2, seas_3, ...) {\n      v <- array(dim=c(1,1),dimnames=list(\"reports\",\"reports\"))\n      v[,] <- cases*rho*(1-rho)\n      v\n    }\n  ) -> po\nv <- vmeasure(po,x=states(po)[,10],params=coef(po),times=time(po)[10])\n"
  },
  {
    "path": "tests/vmeasure.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(pomp)\n> \n> try(vmeasure())\nError : in 'vmeasure': 'object' is a required argument.\n> try(vmeasure(\"does this work?\"))\nError : 'vmeasure' is undefined for 'object' of class 'character'.\n> try(simulate(t0=0,times=1:10,vmeasure=Csnippet(\"V_B_B=rho*(1-rho)*inc;\")))\nError : in 'simulate': when 'vmeasure' is provided as a C snippet, you must also provide 'obsnames'.\n> \n> ou2() -> po\n> vmeasure(po) -> v1\n> vmeasure(po,x=states(po)) -> v2\n> vmeasure(po,x=states(po),params=coef(po)) -> v3\n> stopifnot(\n+   dim(v1)==c(2,2,1,100),\n+   identical(v1,v2),\n+   identical(v1,v3)\n+ )\n> try(vmeasure(po,x=states(po),params=coef(po),times=numeric(0)))\nError : in 'vmeasure': length('times') = 0, no work to do.\n> try(vmeasure(po,x=states(po),params=coef(po),times=c(1,2,3)))\nError : in 'vmeasure': length of 'times' and 3rd dimension of 'x' do not agree.\n> simulate(po,nsim=3,format=\"arrays\") |> getElement(\"states\") -> X\n> try(vmeasure(po,x=X,params=parmat(coef(po),2),times=time(po)))\nError : in 'vmeasure': larger number of replicates is not a multiple of smaller.\n> po |>\n+   simulate(\n+     vmeasure=function(x1, x2, ...) {\n+       matrix(c(x1+x2,1,1,x1+x2,1,1),nrow=2)\n+     }\n+   ) -> po1\n> try(vmeasure(po1,x=states(po1),params=coef(po1),times=time(po1)))\nError : in 'vmeasure': 'vmeasure' must return a symmetric square matrix.\n> po |>\n+   simulate(\n+     vmeasure=function(x1, x2, ...) {\n+       matrix(c(x1+x2,1,1,x1+x2),nrow=2)\n+     }\n+   ) -> po1\n> try(vmeasure(po1,x=states(po1),params=coef(po1),times=time(po1)))\nError : in 'vmeasure': 'vmeasure' must return a matrix with row-names.\n> po |>\n+   simulate(\n+     vmeasure=function(x1, x2, t, ...) {\n+       v <- matrix(rep(x1+x2,ceiling(t)^2),nrow=ceiling(t))\n+       nm <- head(letters,ceiling(t))\n+       dimnames(v) <- list(nm,nm)\n+       v\n+     }\n+   ) -> po1\n> try(vmeasure(po1,x=states(po1),params=coef(po1),times=time(po1)))\nError : in 'vmeasure': 'vmeasure' returns variable-length results.\n> po |>\n+   simulate(\n+     vmeasure=function(x1, x2, t, ...) {\n+       v <- matrix(c(x1+x2,1,1,x1+x2),nrow=2)\n+       nm <- c(\"a\",\"b\")\n+       dimnames(v) <- list(nm,NULL)\n+       v\n+     }\n+   ) -> po1\n> v <- vmeasure(po1,x=states(po1),params=coef(po1),times=time(po1))\n> stopifnot(\n+   dim(v)==c(2,2,1,100),\n+   v[1,1,,]==v[2,2,,],\n+   v[1,2,,]==v[2,1,,],\n+   rownames(v)==c(\"a\",\"b\"),\n+   colnames(v)==c(\"a\",\"b\"),\n+   sum(is.na(v))==0\n+ )\n> po |> simulate(vmeasure=NULL) -> po1\n> v <- vmeasure(po1,x=states(po1),params=coef(po1),times=time(po1))\nWarning message:\n'vmeasure' unspecified: NAs generated. \n> stopifnot(\n+   dim(v)==c(2,2,1,100),\n+   rownames(v)==c(\"y1\",\"y2\"),\n+   colnames(v)==c(\"y1\",\"y2\"),\n+   sum(is.na(v))==400\n+ )\n> \n> sir() |>\n+   simulate(\n+     times=(1:10)/52,\n+     vmeasure=function(cases, rho, seas_1, seas_2, seas_3, ...) {\n+       v <- array(dim=c(1,1),dimnames=list(\"reports\",\"reports\"))\n+       v[,] <- cases*rho*(1-rho)\n+       v\n+     }\n+   ) -> po\n> v <- vmeasure(po,x=states(po)[,10],params=coef(po),times=time(po)[10])\n> \n"
  },
  {
    "path": "tests/wpfilter.R",
    "content": "options(digits=3)\npng(filename=\"wpfilter-%02d.png\",res=100)\n\nlibrary(pomp)\n\nset.seed(9994847L)\n\nricker() -> po\ntry(wpfilter(po))\ntry(wpfilter(po,Np=NULL))\ntry(wpfilter(po,Np=-10))\ntry(wpfilter(po,Np=c(10,20,30)))\n\nwpfilter(po,Np=200,trigger=1,target=1) |> plot()\nwpfilter(po,Np=200,trigger=1,target=0.5) |> plot()\nwpfilter(po,Np=200,trigger=1,target=0) |> plot()\nwpfilter(po,Np=200,trigger=0.8) |> plot()\n\nwpfilter(po,Np=1000,trigger=0.5,target=0.5) |> logLik()\nwpfilter(po,Np=1000,trigger=0.5,target=0.2) |> logLik()\nwpfilter(po,Np=1000,trigger=0.5,target=0) |> logLik()\nwpfilter(po,Np=1000,trigger=1,target=0) |> logLik()\npfilter(po,Np=1000) |> logLik()\n\ndo.call(c,replicate(n=10,pfilter(window(po,end=4),Np=1000))) |> logLik() |> logmeanexp(se=TRUE)\ndo.call(c,replicate(n=10,wpfilter(window(po,end=4),Np=1000))) |> logLik() |> logmeanexp(se=TRUE)\n\ndo.call(c,replicate(n=10,pfilter(window(po,end=20),Np=1000))) |> logLik() |> logmeanexp(se=TRUE)\ndo.call(c,replicate(n=10,wpfilter(window(po,end=20),Np=1000,trigger=0.8))) |> logLik() |> logmeanexp(se=TRUE)\n\nset.seed(9994847L)\ntry(wpfilter())\ntry(wpfilter(\"bob\"))\ntry(wpfilter(list(3,2,1)))\nwpfilter(po,Np=100,dmeasure=function(...,log)-Inf)\n\nwpfilter(po,Np=100) |> wpfilter() -> pf\nwpfilter(po,Np=100) |> wpfilter(target=0,trigger=0.1,Np=200) -> pf\npf |> as.data.frame() |> nrow()\npf |> as(\"data.frame\") |> names()\npf |> eff_sample_size(format=\"d\") |> names()\npf |> eff_sample_size(format=\"d\") |> sapply(class)\npf |> cond_logLik(format=\"d\") |> names()\npf |> cond_logLik(format=\"d\") |> sapply(class)\n\ntry(wpfilter(po,dmeasure=NULL))\ntry(wpfilter(po,rprocess=NULL))\ntry(wpfilter(po,Np=100,trigger=-1))\ntry(wpfilter(po,Np=100,trigger=NULL))\ntry(wpfilter(po,Np=100,trigger=c(0,1)))\ntry(wpfilter(po,Np=100,trigger=NA))\ntry(wpfilter(po,Np=100,target=-1))\ntry(wpfilter(po,Np=100,target=2))\ntry(wpfilter(po,Np=100,target=NULL))\ntry(wpfilter(po,Np=100,target=c(0,1)))\ntry(wpfilter(po,Np=100,target=NaN))\n\ntry(wpfilter(po,Np=100,dmeasure=function(...,log)sample(c(0,Inf),1)))\n\npo |>\n  as.data.frame() |>\n  wpfilter(\n    times=\"time\",t0=0,Np=100,\n    params=c(N0=7,phi=10,r=40),\n    rinit=function(N0,...)c(N=N0),\n    dmeasure=function(y,N,phi,...,log) dnorm(x=y,mean=phi*N,sd=sqrt(phi*N),log=log),\n    rprocess=discrete_time(function(r,N,...) c(N=r*N*exp(-N+rnorm(1))),delta.t=1)\n  ) |> plot()\n\ndev.off()\n"
  },
  {
    "path": "tests/wpfilter.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> png(filename=\"wpfilter-%02d.png\",res=100)\n> \n> library(pomp)\n> \n> set.seed(9994847L)\n> \n> ricker() -> po\n> try(wpfilter(po))\nError : in 'wpfilter': 'Np' must be specified.\n> try(wpfilter(po,Np=NULL))\nError : in 'wpfilter': 'Np' must be specified.\n> try(wpfilter(po,Np=-10))\nError : in 'wpfilter': number of particles, 'Np', must be a positive integer.\n> try(wpfilter(po,Np=c(10,20,30)))\nError : in 'wpfilter': 'Np' must have length 1 or length 52.\n> \n> wpfilter(po,Np=200,trigger=1,target=1) |> plot()\n> wpfilter(po,Np=200,trigger=1,target=0.5) |> plot()\n> wpfilter(po,Np=200,trigger=1,target=0) |> plot()\n> wpfilter(po,Np=200,trigger=0.8) |> plot()\n> \n> wpfilter(po,Np=1000,trigger=0.5,target=0.5) |> logLik()\n[1] -139\n> wpfilter(po,Np=1000,trigger=0.5,target=0.2) |> logLik()\n[1] -139\n> wpfilter(po,Np=1000,trigger=0.5,target=0) |> logLik()\n[1] -140\n> wpfilter(po,Np=1000,trigger=1,target=0) |> logLik()\n[1] -140\n> pfilter(po,Np=1000) |> logLik()\n[1] -140\n> \n> do.call(c,replicate(n=10,pfilter(window(po,end=4),Np=1000))) |> logLik() |> logmeanexp(se=TRUE)\n     est       se \n-13.0978   0.0165 \n> do.call(c,replicate(n=10,wpfilter(window(po,end=4),Np=1000))) |> logLik() |> logmeanexp(se=TRUE)\n     est       se \n-13.0941   0.0198 \n> \n> do.call(c,replicate(n=10,pfilter(window(po,end=20),Np=1000))) |> logLik() |> logmeanexp(se=TRUE)\n     est       se \n-56.9719   0.0509 \n> do.call(c,replicate(n=10,wpfilter(window(po,end=20),Np=1000,trigger=0.8))) |> logLik() |> logmeanexp(se=TRUE)\n     est       se \n-57.0958   0.0742 \n> \n> set.seed(9994847L)\n> try(wpfilter())\nError : in 'wpfilter': 'data' is a required argument.\n> try(wpfilter(\"bob\"))\nError : 'wpfilter' is undefined for 'data' of class 'character'.\n> try(wpfilter(list(3,2,1)))\nError : 'wpfilter' is undefined for 'data' of class 'list'.\n> wpfilter(po,Np=100,dmeasure=function(...,log)-Inf)\n<object of class 'wpfilterd_pomp'>\n> \n> wpfilter(po,Np=100) |> wpfilter() -> pf\n> wpfilter(po,Np=100) |> wpfilter(target=0,trigger=0.1,Np=200) -> pf\n> pf |> as.data.frame() |> nrow()\n[1] 51\n> pf |> as(\"data.frame\") |> names()\n[1] \"time\"            \"y\"               \"eff.sample.size\" \"cond.logLik\"    \n> pf |> eff_sample_size(format=\"d\") |> names()\n[1] \"time\"            \"eff.sample.size\"\n> pf |> eff_sample_size(format=\"d\") |> sapply(class)\n           time eff.sample.size \n      \"numeric\"       \"numeric\" \n> pf |> cond_logLik(format=\"d\") |> names()\n[1] \"time\"        \"cond.logLik\"\n> pf |> cond_logLik(format=\"d\") |> sapply(class)\n       time cond.logLik \n  \"numeric\"   \"numeric\" \n> \n> try(wpfilter(po,dmeasure=NULL))\nError : in 'wpfilter': 'rprocess', 'dmeasure' are needed basic components.\n> try(wpfilter(po,rprocess=NULL))\nError : in 'wpfilter': 'rprocess', 'dmeasure' are needed basic components.\n> try(wpfilter(po,Np=100,trigger=-1))\nError : in 'wpfilter': 'trigger' should be a non-negative scalar.\n> try(wpfilter(po,Np=100,trigger=NULL))\nError : in 'wpfilter': 'trigger' should be a non-negative scalar.\n> try(wpfilter(po,Np=100,trigger=c(0,1)))\nError : in 'wpfilter': 'trigger' should be a non-negative scalar.\n> try(wpfilter(po,Np=100,trigger=NA))\nError : in 'wpfilter': 'trigger' should be a non-negative scalar.\n> try(wpfilter(po,Np=100,target=-1))\nError : in 'wpfilter': 'target' should be a scalar in [0,1].\n> try(wpfilter(po,Np=100,target=2))\nError : in 'wpfilter': 'target' should be a scalar in [0,1].\n> try(wpfilter(po,Np=100,target=NULL))\nError : in 'wpfilter': 'target' should be a scalar in [0,1].\n> try(wpfilter(po,Np=100,target=c(0,1)))\nError : in 'wpfilter': 'target' should be a scalar in [0,1].\n> try(wpfilter(po,Np=100,target=NaN))\nError : in 'wpfilter': missing value where TRUE/FALSE needed\n> \n> try(wpfilter(po,Np=100,dmeasure=function(...,log)sample(c(0,Inf),1)))\nError : in 'wpfilter': 'dmeasure' with log=TRUE returns illegal value.\nLog likelihood, data, states, and parameters are:\n  time:            0\nloglik:          Inf\n     y:           68\n     N:            7\n     e:            0\n     r:      44.7012\n sigma:          0.3\n   phi:           10\n     c:            1\n   N_0:            7\n   e_0:            0\n> \n> po |>\n+   as.data.frame() |>\n+   wpfilter(\n+     times=\"time\",t0=0,Np=100,\n+     params=c(N0=7,phi=10,r=40),\n+     rinit=function(N0,...)c(N=N0),\n+     dmeasure=function(y,N,phi,...,log) dnorm(x=y,mean=phi*N,sd=sqrt(phi*N),log=log),\n+     rprocess=discrete_time(function(r,N,...) c(N=r*N*exp(-N+rnorm(1))),delta.t=1)\n+   ) |> plot()\n> \n> dev.off()\nnull device \n          1 \n> \n"
  },
  {
    "path": "tests/wquant.R",
    "content": "options(digits=3)\nlibrary(pomp)\nset.seed(1147838039)\n\nx <- c(1,1,1,2,2,3,3,3,3,4,5,5,6,6,6)\nquantile(x)\nwquant(x,weights=rep(1,length(x)))\nwquant(c(1,2,3,4,5,6),weights=c(3,2,4,1,2,3))\nwquant(c(1,2,3,4,5),c(1,0,0,1,1))\nwquant(c(1,2,3,4,5),c(0,1,0,1,1))\nwquant(c(1,2,3,4,5),c(0,1,0,1,0))\nwquant(c(1,2,3,4,5),c(0,1,0,0,1))\nwquant(c(1,1,2,2),c(1,1,1,1))\nwquant(c(1,2),c(2,2))\n\ntry(wquant(c(1,NA),c(1,2)))\ntry(wquant(c(1,2),c(NA,1)))\ntry(wquant(c(1,2,3),c(1,2)))\ntry(wquant(c(1,2,3),c(1,2,-1)))\ntry(wquant(c(1,2,3),c(1,1,1),probs=c(0.1,NA)))\ntry(wquant(c(1,2,3),c(1,2,3),probs=c(0.1,2)))\n\nx <- rnorm(n=10000)\nstopifnot(\n  all.equal(\n    wquant(x,probs=seq(0.1,0.9,by=0.1)),\n    quantile(x,probs=seq(0.1,0.9,by=0.1),names=FALSE),\n    tolerance=0.01\n  )\n)\ny <- seq(-4,4,by=0.01)\np <- diff(pnorm(y))\ny <- 0.5*(head(y,-1)+tail(y,-1))\nstopifnot(\n  all.equal(\n    wquant(y,weights=p,probs=c(0.1,0.5,0.9)),\n    qnorm(p=c(0.1,0.5,0.9)),\n    tolerance=0.01\n  )\n)\n"
  },
  {
    "path": "tests/wquant.Rout.save",
    "content": "\nR version 4.5.2 (2025-10-31) -- \"[Not] Part in a Rumble\"\nCopyright (C) 2025 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n  Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> options(digits=3)\n> library(pomp)\n> set.seed(1147838039)\n> \n> x <- c(1,1,1,2,2,3,3,3,3,4,5,5,6,6,6)\n> quantile(x)\n  0%  25%  50%  75% 100% \n   1    2    3    5    6 \n> wquant(x,weights=rep(1,length(x)))\n  0%  25%  50%  75% 100% \n1.00 1.86 3.21 5.05 6.00 \n> wquant(c(1,2,3,4,5,6),weights=c(3,2,4,1,2,3))\n  0%  25%  50%  75% 100% \n1.00 1.88 3.31 4.97 6.00 \n> wquant(c(1,2,3,4,5),c(1,0,0,1,1))\n  0%  25%  50%  75% 100% \n1.00 1.93 3.48 4.59 5.00 \n> wquant(c(1,2,3,4,5),c(0,1,0,1,1))\n  0%  25%  50%  75% 100% \n2.00 2.63 3.74 4.63 5.00 \n> wquant(c(1,2,3,4,5),c(0,1,0,1,0))\n  0%  25%  50%  75% 100% \n 2.0  2.3  3.0  3.7  4.0 \n> wquant(c(1,2,3,4,5),c(0,1,0,0,1))\n  0%  25%  50%  75% 100% \n2.00 2.45 3.50 4.55 5.00 \n> wquant(c(1,1,2,2),c(1,1,1,1))\n  0%  25%  50%  75% 100% \n 1.0  1.1  1.5  1.9  2.0 \n> wquant(c(1,2),c(2,2))\n  0%  25%  50%  75% 100% \n1.00 1.15 1.50 1.85 2.00 \n> \n> try(wquant(c(1,NA),c(1,2)))\nError : in 'wquant': NA and non-finite values are disallowed.\n> try(wquant(c(1,2),c(NA,1)))\nError : in 'wquant': NA and non-finite values are disallowed.\n> try(wquant(c(1,2,3),c(1,2)))\nError : in 'wquant': 'x' and 'weights' must be of equal length.\n> try(wquant(c(1,2,3),c(1,2,-1)))\nError : in 'wquant': weights must be non-negative.\n> try(wquant(c(1,2,3),c(1,1,1),probs=c(0.1,NA)))\nError : in 'wquant': 'probs' must be a numeric vector with values in [0,1].\n> try(wquant(c(1,2,3),c(1,2,3),probs=c(0.1,2)))\nError : in 'wquant': 'probs' must be a numeric vector with values in [0,1].\n> \n> x <- rnorm(n=10000)\n> stopifnot(\n+   all.equal(\n+     wquant(x,probs=seq(0.1,0.9,by=0.1)),\n+     quantile(x,probs=seq(0.1,0.9,by=0.1),names=FALSE),\n+     tolerance=0.01\n+   )\n+ )\n> y <- seq(-4,4,by=0.01)\n> p <- diff(pnorm(y))\n> y <- 0.5*(head(y,-1)+tail(y,-1))\n> stopifnot(\n+   all.equal(\n+     wquant(y,weights=p,probs=c(0.1,0.5,0.9)),\n+     qnorm(p=c(0.1,0.5,0.9)),\n+     tolerance=0.01\n+   )\n+ )\n> \n"
  },
  {
    "path": "tools/check.env",
    "content": "_R_CHECK_AS_DATA_FRAME_EXPLICIT_METHOD_=true\n_R_CHECK_ALL_NON_ISO_C_=false\n_R_CHECK_ALWAYS_LOG_VIGNETTE_OUTPUT_=false\n_R_CHECK_ASCII_CODE_=true\n_R_CHECK_ASCII_DATA_=true\n_R_CHECK_AUTOCONF_=true\n_R_CHECK_BASHISMS_=true\n_R_CHECK_BOGUS_RETURN_=true\n_R_CHECK_BUILD_VIGNETTES_SEPARATELY_=true\n_R_CHECK_CLEAN_VIGN_TEST_=true\n_R_CHECK_CODE_ASSIGN_TO_GLOBALENV_=true\n_R_CHECK_CODE_ATTACH_=true\n_R_CHECK_CODE_CLASS_IS_STRING_=true\n_R_CHECK_CODE_DATA_INTO_GLOBALENV_=true\n_R_CHECK_CODE_USAGE_VIA_NAMESPACES_=true\n_R_CHECK_CODE_USAGE_WITH_ONLY_BASE_ATTACHED_=true\n_R_CHECK_CODOC_S4_METHODS_=true\n_R_CHECK_COMPACT_DATA_=true\n_R_CHECK_COMPILATION_FLAGS_=true\n_R_CHECK_CONNECTIONS_LEFT_OPEN_=true\n_R_CHECK_CRAN_INCOMING_=false\n_R_CHECK_DATALIST_=true\n_R_CHECK_DEPENDS_ONLY_=false\n_R_CHECK_DEPRECATED_DEFUNCT_=true\n_R_CHECK_DONTTEST_EXAMPLES_=false\n_R_CHECK_DOT_FIRSTLIB_=true\n_R_CHECK_DOT_INTERNAL_=true\n_R_CHECK_EXAMPLE_TIMING_THRESHOLD_=5\n_R_CHECK_EXCESSIVE_IMPORTS_=20\n_R_CHECK_EXECUTABLES_=true\n_R_CHECK_EXECUTABLES_EXCLUSIONS_=false\n_R_CHECK_EXIT_ON_FIRST_ERROR_=false\n_R_CHECK_FF_CALLS_=true\n_R_CHECK_FF_DUP_=true\n_R_CHECK_FORCE_SUGGESTS_=false\n_R_CHECK_FUTURE_FILE_TIMESTAMPS_=true\n_R_CHECK_GCT_N_=0\n_R_CHECK_INSTALL_DEPENDS_=true\n_R_CHECK_LENGTH_1_CONDITION_ =package:_R_CHECK_PACKAGE_NAME_\n_R_CHECK_LENGTH_1_LOGIC2_=package:_R_CHECK_PACKAGE_NAME_,abort,verbose\n_R_CHECK_LICENSE_=true\n_R_CHECK_LIMIT_CORES_=true\n_R_CHECK_RD_MATH_RENDERING_=true\n_R_CHECK_MATRIX_DATA_=true\n_R_CHECK_NATIVE_ROUTINE_REGISTRATION_=true\n_R_CHECK_NO_RECOMMENDED_=true\n_R_CHECK_NO_STOP_ON_TEST_ERROR_=true\n_R_CHECK_ORPHANED_=true\n_R_CHECK_OVERWRITE_REGISTERED_S3_METHODS_=true\n_R_CHECK_PACKAGES_USED_IN_TESTS_USE_SUBDIRS_=true\n_R_CHECK_PKG_SIZES_=true\n_R_CHECK_PKG_SIZES_THRESHOLD_=5\n_R_CHECK_PRAGMAS_=true\n_R_CHECK_RD_CHECKRD_MINLEVEL_=-1\n_R_CHECK_RD_CONTENTS_=true\n_R_CHECK_RD_EXAMPLES_T_AND_F_=false\n_R_CHECK_RD_LINE_WIDTHS_=true\n_R_CHECK_RD_STYLE_=true\n_R_CHECK_RD_VALIDATE_RD2HTML_=true\n_R_CHECK_RD_XREFS_=true\n_R_CHECK_REPLACING_IMPORTS_=true\n_R_CHECK_R_DEPENDS_=\"warn\"\n_R_CHECK_R_ON_PATH_=true\n_R_CHECK_S3_METHODS_NOT_REGISTERED_=true\n_R_CHECK_SERIALIZATION_=true\n_R_CHECK_SHLIB_OPENMP_FLAGS_=true\n_R_CHECK_SKIP_ARCH_=none\n_R_CHECK_SRC_MINUS_W_IMPLICIT_=true\n_R_CHECK_SRC_MINUS_W_UNUSED_=true\n_R_CHECK_SUBDIRS_NOCASE_=true\n_R_CHECK_SUBDIRS_STRICT_=default\n_R_CHECK_SUGGESTS_ONLY_=true\n_R_CHECK_SYSTEM_CLOCK_=false\n_R_CHECK_TESTS_NLINES_=13\n_R_CHECK_THINGS_IN_CHECK_DIR_=true\n_R_CHECK_THINGS_IN_OTHER_DIRS_=false\n_R_CHECK_THINGS_IN_TEMP_DIR_=true\n_R_CHECK_TIMINGS_=10\n_R_CHECK_TOPLEVEL_FILES_=true\n_R_CHECK_UNSAFE_CALLS_=true\n_R_CHECK_USE_CODETOOLS_=true\n_R_CHECK_USE_INSTALL_LOG_=true\n_R_CHECK_VC_DIRS_=true\n_R_CHECK_VIGNETTES_NLINES_=10\n_R_CHECK_VIGNETTES_SKIP_RUN_MAYBE_=true\n_R_CHECK_WALL_FORTRAN_=true\n_R_CHECK_XREFS_MIND_SUSPECT_ANCHORS_=false\n_R_CHECK_XREFS_PKGS_ARE_DECLARED_=false\n_R_CHECK_XREFS_USE_ALIASES_FROM_CRAN_=false\n_R_CHECK_CODETOOLS_PROFILE_=\"suppressLocalUnused=FALSE,suppressPartialMatchArgs=FALSE,suppressParamUnused=TRUE,suppressUndefined=FALSE\"\n"
  }
]